Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 12 additions & 7 deletions cpp2rust/converter/converter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5760,6 +5760,8 @@ std::string Converter::ConvertIRFragment(
if (borrows_ && isFresh() && !CreatesTemporary(arg)) {
value = std::format("({{ {} }})", value);
borrows_ = false;
} else if (IsStructLiteral(arg)) {
value = std::format("({})", value);
}
borrows_ |= outer_borrows;
result += value;
Expand Down Expand Up @@ -5937,22 +5939,25 @@ Converter::ConvertInitFragment(clang::Expr *expr,

Buffer buf(*this);
PushExprKind push(*this, ExprKind::RValue);
ConvertConstructFromArgs(type, all_args.drop_front(tgt_ir->params.size()),
expr->getExprLoc());
return std::move(buf).str();
auto *init = ConvertConstructFromArgs(
type, all_args.drop_front(tgt_ir->params.size()), expr->getExprLoc());
auto value = std::move(buf).str();
return IsStructLiteral(init) ? std::format("({})", value) : value;
}

void Converter::ConvertConstructFromArgs(clang::QualType type,
llvm::ArrayRef<clang::Expr *> args,
clang::SourceLocation loc) {
clang::Expr *
Converter::ConvertConstructFromArgs(clang::QualType type,
llvm::ArrayRef<clang::Expr *> args,
clang::SourceLocation loc) {
auto *init = BuildInitExpr(GetSema(), type, args, loc);
assert(init && "type cannot be initialized from the arguments");
if (args.empty() &&
!clang::isa<clang::CXXConstructExpr>(init->IgnoreImplicit())) {
StrCat(GetDefaultAsString(type));
return;
return init;
}
ConvertInit(type, init);
return init;
}

void Converter::ConvertInit(clang::QualType type, clang::Expr *init) {
Expand Down
6 changes: 3 additions & 3 deletions cpp2rust/converter/converter.h
Original file line number Diff line number Diff line change
Expand Up @@ -944,9 +944,9 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
std::string ConvertInitFragment(clang::Expr *expr,
llvm::ArrayRef<clang::Expr *> all_args);

void ConvertConstructFromArgs(clang::QualType type,
llvm::ArrayRef<clang::Expr *> args,
clang::SourceLocation loc);
clang::Expr *ConvertConstructFromArgs(clang::QualType type,
llvm::ArrayRef<clang::Expr *> args,
clang::SourceLocation loc);

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

Expand Down
18 changes: 18 additions & 0 deletions cpp2rust/converter/converter_lib.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,24 @@ bool IsLibraryOnlySpecialization(const clang::FunctionDecl *decl) {
HasLibraryInternalArgument(ctx, args->asArray());
}

bool IsStructLiteral(const clang::Expr *expr) {
expr = expr->IgnoreImplicit();
if (auto *cast = clang::dyn_cast<clang::CXXFunctionalCastExpr>(expr)) {
expr = cast->getSubExpr()->IgnoreImplicit();
}
auto *list = clang::dyn_cast<clang::InitListExpr>(expr);
if (!list) {
return false;
}
auto *syntactic = list->isSyntacticForm() ? list : list->getSyntacticForm();
if (auto *form = list->getSemanticForm()) {
list = form;
}
auto *record = list->getType()->getAsRecordDecl();
return record && IsUserDefinedDecl(record) && !list->isTransparent() &&
syntactic->getNumInits() != 0;
}

bool IsAbstractUserClass(const clang::RecordDecl *decl) {
auto cxx = llvm::dyn_cast<clang::CXXRecordDecl>(decl);
auto definition = cxx ? cxx->getDefinition() : nullptr;
Expand Down
2 changes: 2 additions & 0 deletions cpp2rust/converter/converter_lib.h
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ bool IsCodeUnitStringLiteral(const clang::StringLiteral *expr);

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

bool IsStructLiteral(const clang::Expr *expr);

bool IsAbstractUserClass(const clang::RecordDecl *decl);

bool IsLibraryOnlySpecialization(
Expand Down
7 changes: 7 additions & 0 deletions tests/unit/find.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@
#include <map>
#include <vector>

struct P {
int x;
bool operator==(const P &o) const { return x == o.x; }
};

int main() {
std::vector<int> v;
v.push_back(1);
Expand All @@ -25,5 +30,7 @@ int main() {
assert(std::find(w.begin() + 2, w.end(), 4) == w.begin() + 3);
assert(std::find(w.begin() + 2, w.end(), 1) == w.end());
assert(std::find(w.begin() + 2, w.begin() + 4, 5) == w.begin() + 4);
std::vector<P> p = {P{0}, P{1}, P{2}};
assert(std::find(p.begin(), p.end(), P{1}) == p.begin() + 1);
return 0;
}
2 changes: 1 addition & 1 deletion tests/unit/out/refcount/class_templates.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ pub fn main() {
fn main_0() -> i32 {
let mut ev: Vec<Elem> = Vec::new();
{
let __a1 = Elem { i: 2 };
let __a1 = (Elem { i: 2 });
ev.push(__a1)
};
assert!((ev[0_usize].i == 2));
Expand Down
40 changes: 40 additions & 0 deletions tests/unit/out/refcount/find.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,17 @@ use std::io::prelude::*;
use std::io::{Read, Seek, Write};
use std::os::fd::AsFd;
use std::rc::{Rc, Weak};
#[derive(Copy, Clone, Record, ByteRepr, VaArg, FnPtrArg, Default)]
#[byte_size(4)]
pub struct P {
#[offset(0)]
pub x: i32,
}
impl CppEq for P {
fn equal(__lhs: &Ptr<Self>, __rhs: &Ptr<Self>) -> bool {
PImpl::operator_eq(__lhs, __rhs.clone())
}
}
pub fn main() {
__cpp2rust_init_globals();
std::process::exit(main_0());
Expand Down Expand Up @@ -139,6 +150,35 @@ fn main_0() -> i32 {
}
}) == w.decay().begin().iter_add(4_isize)
);
let p: Value<Vec<P>> = Rc::new(RefCell::new(Vec::from([
P { x: 0 },
P { x: 1 },
P { x: 2 },
])));
assert!(
({
let __tmp_16: Value<P> = Rc::new(RefCell::new(P { x: 1 }));
match ({ p.decay().begin() }, { p.decay().end() }) {
(mut __tmp_14, mut __tmp_15) => {
let mut __it = (__tmp_14).clone();
while __it != __tmp_15
&& !CppEq::equal(&__it.iter_deref(), &(__tmp_16.as_pointer()))
{
__it.iter_inc();
}
__it
}
}
}) == p.decay().begin().iter_add(1_isize)
);
return 0;
}
pub trait PImpl {
fn operator_eq(&self, o: Ptr<P>) -> bool;
}
impl PImpl for Ptr<P> {
fn operator_eq(&self, o: Ptr<P>) -> bool {
return ({ (*self).with(|__s| __s.x) } == { o.with(|__s| __s.x) });
}
}
pub fn __cpp2rust_init_globals() {}
6 changes: 3 additions & 3 deletions tests/unit/out/refcount/fn_ptr_stable_sort.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,15 @@ pub fn main() {
fn main_0() -> i32 {
let v: Value<Vec<Item>> = Rc::new(RefCell::new(Vec::new()));
{
let __a1 = Item { key: 3, value: 30 };
let __a1 = (Item { key: 3, value: 30 });
(*v.borrow_mut()).push(__a1)
};
{
let __a1 = Item { key: 1, value: 10 };
let __a1 = (Item { key: 1, value: 10 });
(*v.borrow_mut()).push(__a1)
};
{
let __a1 = Item { key: 2, value: 20 };
let __a1 = (Item { key: 2, value: 20 });
(*v.borrow_mut()).push(__a1)
};
match ({ v.decay().begin() },) {
Expand Down
6 changes: 3 additions & 3 deletions tests/unit/out/refcount/operator_traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -206,13 +206,13 @@ fn main_0() -> i32 {
let m: Value<Map<Lt, (Value<Lt>, Value<i32>)>> = Rc::new(RefCell::new(Map::new()));
Map::subscript_move(
m.as_pointer(),
Rc::new(RefCell::new(Lt { v: 2 })).as_pointer(),
(Rc::new(RefCell::new(Lt { v: 2 })).as_pointer()),
|__k| cpp_move!(__k),
)
.write(20);
Map::subscript_move(
m.as_pointer(),
Rc::new(RefCell::new(Lt { v: 1 })).as_pointer(),
(Rc::new(RefCell::new(Lt { v: 1 })).as_pointer()),
|__k| cpp_move!(__k),
)
.write(10);
Expand All @@ -230,7 +230,7 @@ fn main_0() -> i32 {
assert!(
((Map::subscript_move(
m.as_pointer(),
Rc::new(RefCell::new(Lt { v: 2 })).as_pointer(),
(Rc::new(RefCell::new(Lt { v: 2 })).as_pointer()),
|__k| cpp_move!(__k)
)
.read())
Expand Down
4 changes: 2 additions & 2 deletions tests/unit/out/refcount/pair_converting_construction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -207,8 +207,8 @@ fn main_0() -> i32 {
assert!(({ ({ (*(*from_copied_pair.borrow()).0.borrow()).degrees } == 5) }));
assert!(({ ((*(*from_copied_pair.borrow()).1.borrow()) == 6_i64) }));
let meters: Value<(Value<Meters>, Value<Meters>)> = Rc::new(RefCell::new((
Rc::new(RefCell::new(Meters { value: 8 })),
Rc::new(RefCell::new(Meters { value: 9 })),
Rc::new(RefCell::new((Meters { value: 8 }))),
Rc::new(RefCell::new((Meters { value: 9 }))),
)));
let from_operator_pair: Value<(Value<i32>, Value<i32>)> = Rc::new(RefCell::new((
Rc::new(RefCell::new(<i32 as CppFrom<Meters>>::cpp_from(
Expand Down
2 changes: 1 addition & 1 deletion tests/unit/out/refcount/vector_subscript_direct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ fn main_0() -> i32 {
};
vec_elem!(h.as_pointer(), values, 1_usize).write(6);
{
let __a1 = Point { x: 1, y: 2 };
let __a1 = (Point { x: 1, y: 2 });
(*h.borrow_mut()).points.push(__a1)
};
field!(vec_elem!(h.as_pointer(), points, 0_usize), y).write(5);
Expand Down
2 changes: 1 addition & 1 deletion tests/unit/out/unsafe/class_templates.rs
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ pub fn main() {
unsafe fn main_0() -> i32 {
let mut ev: Vec<Elem> = Vec::new();
{
let __a1 = Elem { i: 2 };
let __a1 = (Elem { i: 2 });
ev.push(__a1)
};
assert!(((ev[(0_usize)].i) == (2)));
Expand Down
30 changes: 30 additions & 0 deletions tests/unit/out/unsafe/find.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,22 @@ use std::collections::BTreeMap;
use std::io::{Read, Seek, Write};
use std::os::fd::{AsFd, FromRawFd, IntoRawFd};
use std::rc::Rc;
#[repr(C)]
#[derive(Copy, Clone, VaArg, FnPtrArg, Default)]
pub struct P {
pub x: i32,
}
impl P {
pub unsafe fn operator_eq(&self, o: *const P) -> bool {
return ((self.x) == ((*o).x));
}
}
impl std::cmp::PartialEq for P {
fn eq(&self, other: &Self) -> bool {
unsafe { P::operator_eq(self, other as *const P) }
}
}
impl std::cmp::Eq for P {}
pub fn main() {
unsafe {
__cpp2rust_init_globals();
Expand Down Expand Up @@ -102,6 +118,20 @@ unsafe fn main_0() -> i32 {
}
} == w.begin().iter_add(4_isize)
);
let mut p: Vec<P> = Vec::from([P { x: 0 }, P { x: 1 }, P { x: 2 }]);
assert!(
match ({ p.begin() }, { p.end() },) {
(mut __tmp_9, mut __tmp_10) => {
{
let mut __it = (__tmp_9).clone();
while __it != __tmp_10 && *__it.iter_deref() != (P { x: 1 }) {
__it.iter_inc();
}
__it
}
}
} == p.begin().iter_add(1_isize)
);
return 0;
}
pub unsafe fn __cpp2rust_init_globals() {}
6 changes: 3 additions & 3 deletions tests/unit/out/unsafe/fn_ptr_stable_sort.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,15 @@ pub fn main() {
unsafe fn main_0() -> i32 {
let mut v: Vec<Item> = Vec::new();
{
let __a1 = Item { key: 3, value: 30 };
let __a1 = (Item { key: 3, value: 30 });
v.push(__a1)
};
{
let __a1 = Item { key: 1, value: 10 };
let __a1 = (Item { key: 1, value: 10 });
v.push(__a1)
};
{
let __a1 = Item { key: 2, value: 20 };
let __a1 = (Item { key: 2, value: 20 });
v.push(__a1)
};
match ({ v.begin() },) {
Expand Down
6 changes: 3 additions & 3 deletions tests/unit/out/unsafe/operator_traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,10 +251,10 @@ unsafe fn main_0() -> i32 {
.v) == (2))
);
let mut m: UnsafeMap<Lt, (Lt, i32)> = UnsafeMap::new();
(*m.subscript_move(&mut Lt { v: 2 }, |__k| cpp_move_unsafe!(__k))) = 20;
(*m.subscript_move(&mut Lt { v: 1 }, |__k| cpp_move_unsafe!(__k))) = 10;
(*m.subscript_move((&mut Lt { v: 2 }), |__k| cpp_move_unsafe!(__k))) = 20;
(*m.subscript_move((&mut Lt { v: 1 }), |__k| cpp_move_unsafe!(__k))) = 10;
assert!((((*m.begin().iter_deref()).1) == (10)));
assert!(((*m.subscript_move(&mut Lt { v: 2 }, |__k| cpp_move_unsafe!(__k))) == (20)));
assert!(((*m.subscript_move((&mut Lt { v: 2 }), |__k| cpp_move_unsafe!(__k))) == (20)));
return 0;
}
pub unsafe fn __cpp2rust_init_globals() {}
2 changes: 1 addition & 1 deletion tests/unit/out/unsafe/pair_converting_construction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ unsafe fn main_0() -> i32 {
);
assert!(((from_copied_pair.0.degrees) == (5)));
assert!(((from_copied_pair.1) == (6_i64)));
let mut meters: (Meters, Meters) = (Meters { value: 8 }, Meters { value: 9 });
let mut meters: (Meters, Meters) = ((Meters { value: 8 }), (Meters { value: 9 }));
let mut from_operator_pair: (i32, i32) = (
<i32 as CppFromUnsafe<Meters>>::cpp_from(&meters.0),
<i32 as CppFromUnsafe<Meters>>::cpp_from(&meters.1),
Expand Down
2 changes: 1 addition & 1 deletion tests/unit/out/unsafe/vector_subscript_direct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ unsafe fn main_0() -> i32 {
};
h.values[(1_usize)] = 6;
{
let __a1 = Point { x: 1, y: 2 };
let __a1 = (Point { x: 1, y: 2 });
h.points.push(__a1)
};
h.points[(0_usize)].y = 5;
Expand Down
Loading