Skip to content

Commit 682ad3e

Browse files
authored
Wrap struct literals in parens before applying rules on them (#654)
Rust consideres the following while ill-formed without parens around B: `while a != (B {}) { body }`
1 parent 6a30625 commit 682ad3e

17 files changed

Lines changed: 131 additions & 29 deletions

‎cpp2rust/converter/converter.cpp‎

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5760,6 +5760,8 @@ std::string Converter::ConvertIRFragment(
57605760
if (borrows_ && isFresh() && !CreatesTemporary(arg)) {
57615761
value = std::format("({{ {} }})", value);
57625762
borrows_ = false;
5763+
} else if (IsStructLiteral(arg)) {
5764+
value = std::format("({})", value);
57635765
}
57645766
borrows_ |= outer_borrows;
57655767
result += value;
@@ -5937,22 +5939,25 @@ Converter::ConvertInitFragment(clang::Expr *expr,
59375939

59385940
Buffer buf(*this);
59395941
PushExprKind push(*this, ExprKind::RValue);
5940-
ConvertConstructFromArgs(type, all_args.drop_front(tgt_ir->params.size()),
5941-
expr->getExprLoc());
5942-
return std::move(buf).str();
5942+
auto *init = ConvertConstructFromArgs(
5943+
type, all_args.drop_front(tgt_ir->params.size()), expr->getExprLoc());
5944+
auto value = std::move(buf).str();
5945+
return IsStructLiteral(init) ? std::format("({})", value) : value;
59435946
}
59445947

5945-
void Converter::ConvertConstructFromArgs(clang::QualType type,
5946-
llvm::ArrayRef<clang::Expr *> args,
5947-
clang::SourceLocation loc) {
5948+
clang::Expr *
5949+
Converter::ConvertConstructFromArgs(clang::QualType type,
5950+
llvm::ArrayRef<clang::Expr *> args,
5951+
clang::SourceLocation loc) {
59485952
auto *init = BuildInitExpr(GetSema(), type, args, loc);
59495953
assert(init && "type cannot be initialized from the arguments");
59505954
if (args.empty() &&
59515955
!clang::isa<clang::CXXConstructExpr>(init->IgnoreImplicit())) {
59525956
StrCat(GetDefaultAsString(type));
5953-
return;
5957+
return init;
59545958
}
59555959
ConvertInit(type, init);
5960+
return init;
59565961
}
59575962

59585963
void Converter::ConvertInit(clang::QualType type, clang::Expr *init) {

‎cpp2rust/converter/converter.h‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -944,9 +944,9 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
944944
std::string ConvertInitFragment(clang::Expr *expr,
945945
llvm::ArrayRef<clang::Expr *> all_args);
946946

947-
void ConvertConstructFromArgs(clang::QualType type,
948-
llvm::ArrayRef<clang::Expr *> args,
949-
clang::SourceLocation loc);
947+
clang::Expr *ConvertConstructFromArgs(clang::QualType type,
948+
llvm::ArrayRef<clang::Expr *> args,
949+
clang::SourceLocation loc);
950950

951951
void ConvertInit(clang::QualType type, clang::Expr *init);
952952

‎cpp2rust/converter/converter_lib.cpp‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -359,6 +359,24 @@ bool IsLibraryOnlySpecialization(const clang::FunctionDecl *decl) {
359359
HasLibraryInternalArgument(ctx, args->asArray());
360360
}
361361

362+
bool IsStructLiteral(const clang::Expr *expr) {
363+
expr = expr->IgnoreImplicit();
364+
if (auto *cast = clang::dyn_cast<clang::CXXFunctionalCastExpr>(expr)) {
365+
expr = cast->getSubExpr()->IgnoreImplicit();
366+
}
367+
auto *list = clang::dyn_cast<clang::InitListExpr>(expr);
368+
if (!list) {
369+
return false;
370+
}
371+
auto *syntactic = list->isSyntacticForm() ? list : list->getSyntacticForm();
372+
if (auto *form = list->getSemanticForm()) {
373+
list = form;
374+
}
375+
auto *record = list->getType()->getAsRecordDecl();
376+
return record && IsUserDefinedDecl(record) && !list->isTransparent() &&
377+
syntactic->getNumInits() != 0;
378+
}
379+
362380
bool IsAbstractUserClass(const clang::RecordDecl *decl) {
363381
auto cxx = llvm::dyn_cast<clang::CXXRecordDecl>(decl);
364382
auto definition = cxx ? cxx->getDefinition() : nullptr;

‎cpp2rust/converter/converter_lib.h‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,8 @@ bool IsCodeUnitStringLiteral(const clang::StringLiteral *expr);
5656

5757
bool IsUserDefinedDecl(const clang::Decl *decl);
5858

59+
bool IsStructLiteral(const clang::Expr *expr);
60+
5961
bool IsAbstractUserClass(const clang::RecordDecl *decl);
6062

6163
bool IsLibraryOnlySpecialization(

‎tests/unit/find.cpp‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,11 @@
33
#include <map>
44
#include <vector>
55

6+
struct P {
7+
int x;
8+
bool operator==(const P &o) const { return x == o.x; }
9+
};
10+
611
int main() {
712
std::vector<int> v;
813
v.push_back(1);
@@ -25,5 +30,7 @@ int main() {
2530
assert(std::find(w.begin() + 2, w.end(), 4) == w.begin() + 3);
2631
assert(std::find(w.begin() + 2, w.end(), 1) == w.end());
2732
assert(std::find(w.begin() + 2, w.begin() + 4, 5) == w.begin() + 4);
33+
std::vector<P> p = {P{0}, P{1}, P{2}};
34+
assert(std::find(p.begin(), p.end(), P{1}) == p.begin() + 1);
2835
return 0;
2936
}

‎tests/unit/out/refcount/class_templates.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ pub fn main() {
130130
fn main_0() -> i32 {
131131
let mut ev: Vec<Elem> = Vec::new();
132132
{
133-
let __a1 = Elem { i: 2 };
133+
let __a1 = (Elem { i: 2 });
134134
ev.push(__a1)
135135
};
136136
assert!((ev[0_usize].i == 2));

‎tests/unit/out/refcount/find.rs‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,17 @@ use std::io::prelude::*;
66
use std::io::{Read, Seek, Write};
77
use std::os::fd::AsFd;
88
use std::rc::{Rc, Weak};
9+
#[derive(Copy, Clone, Record, ByteRepr, VaArg, FnPtrArg, Default)]
10+
#[byte_size(4)]
11+
pub struct P {
12+
#[offset(0)]
13+
pub x: i32,
14+
}
15+
impl CppEq for P {
16+
fn equal(__lhs: &Ptr<Self>, __rhs: &Ptr<Self>) -> bool {
17+
PImpl::operator_eq(__lhs, __rhs.clone())
18+
}
19+
}
920
pub fn main() {
1021
__cpp2rust_init_globals();
1122
std::process::exit(main_0());
@@ -139,6 +150,35 @@ fn main_0() -> i32 {
139150
}
140151
}) == w.decay().begin().iter_add(4_isize)
141152
);
153+
let p: Value<Vec<P>> = Rc::new(RefCell::new(Vec::from([
154+
P { x: 0 },
155+
P { x: 1 },
156+
P { x: 2 },
157+
])));
158+
assert!(
159+
({
160+
let __tmp_16: Value<P> = Rc::new(RefCell::new(P { x: 1 }));
161+
match ({ p.decay().begin() }, { p.decay().end() }) {
162+
(mut __tmp_14, mut __tmp_15) => {
163+
let mut __it = (__tmp_14).clone();
164+
while __it != __tmp_15
165+
&& !CppEq::equal(&__it.iter_deref(), &(__tmp_16.as_pointer()))
166+
{
167+
__it.iter_inc();
168+
}
169+
__it
170+
}
171+
}
172+
}) == p.decay().begin().iter_add(1_isize)
173+
);
142174
return 0;
143175
}
176+
pub trait PImpl {
177+
fn operator_eq(&self, o: Ptr<P>) -> bool;
178+
}
179+
impl PImpl for Ptr<P> {
180+
fn operator_eq(&self, o: Ptr<P>) -> bool {
181+
return ({ (*self).with(|__s| __s.x) } == { o.with(|__s| __s.x) });
182+
}
183+
}
144184
pub fn __cpp2rust_init_globals() {}

‎tests/unit/out/refcount/fn_ptr_stable_sort.rs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,15 +24,15 @@ pub fn main() {
2424
fn main_0() -> i32 {
2525
let v: Value<Vec<Item>> = Rc::new(RefCell::new(Vec::new()));
2626
{
27-
let __a1 = Item { key: 3, value: 30 };
27+
let __a1 = (Item { key: 3, value: 30 });
2828
(*v.borrow_mut()).push(__a1)
2929
};
3030
{
31-
let __a1 = Item { key: 1, value: 10 };
31+
let __a1 = (Item { key: 1, value: 10 });
3232
(*v.borrow_mut()).push(__a1)
3333
};
3434
{
35-
let __a1 = Item { key: 2, value: 20 };
35+
let __a1 = (Item { key: 2, value: 20 });
3636
(*v.borrow_mut()).push(__a1)
3737
};
3838
match ({ v.decay().begin() },) {

‎tests/unit/out/refcount/operator_traits.rs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -206,13 +206,13 @@ fn main_0() -> i32 {
206206
let m: Value<Map<Lt, (Value<Lt>, Value<i32>)>> = Rc::new(RefCell::new(Map::new()));
207207
Map::subscript_move(
208208
m.as_pointer(),
209-
Rc::new(RefCell::new(Lt { v: 2 })).as_pointer(),
209+
(Rc::new(RefCell::new(Lt { v: 2 })).as_pointer()),
210210
|__k| cpp_move!(__k),
211211
)
212212
.write(20);
213213
Map::subscript_move(
214214
m.as_pointer(),
215-
Rc::new(RefCell::new(Lt { v: 1 })).as_pointer(),
215+
(Rc::new(RefCell::new(Lt { v: 1 })).as_pointer()),
216216
|__k| cpp_move!(__k),
217217
)
218218
.write(10);
@@ -230,7 +230,7 @@ fn main_0() -> i32 {
230230
assert!(
231231
((Map::subscript_move(
232232
m.as_pointer(),
233-
Rc::new(RefCell::new(Lt { v: 2 })).as_pointer(),
233+
(Rc::new(RefCell::new(Lt { v: 2 })).as_pointer()),
234234
|__k| cpp_move!(__k)
235235
)
236236
.read())

‎tests/unit/out/refcount/pair_converting_construction.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -207,8 +207,8 @@ fn main_0() -> i32 {
207207
assert!(({ ({ (*(*from_copied_pair.borrow()).0.borrow()).degrees } == 5) }));
208208
assert!(({ ((*(*from_copied_pair.borrow()).1.borrow()) == 6_i64) }));
209209
let meters: Value<(Value<Meters>, Value<Meters>)> = Rc::new(RefCell::new((
210-
Rc::new(RefCell::new(Meters { value: 8 })),
211-
Rc::new(RefCell::new(Meters { value: 9 })),
210+
Rc::new(RefCell::new((Meters { value: 8 }))),
211+
Rc::new(RefCell::new((Meters { value: 9 }))),
212212
)));
213213
let from_operator_pair: Value<(Value<i32>, Value<i32>)> = Rc::new(RefCell::new((
214214
Rc::new(RefCell::new(<i32 as CppFrom<Meters>>::cpp_from(

0 commit comments

Comments
 (0)