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
3 changes: 3 additions & 0 deletions cpp2rust/converter/models/converter_refcount.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1868,6 +1868,9 @@ bool ConverterRefCount::VisitMemberExpr(clang::MemberExpr *expr) {
std::string str;
if (known) {
str = GetMappedAsString(expr);
if (member->getType()->isReferenceType()) {
str = std::format("{}.borrow().clone()", str);
}
} else if (clang::isa<clang::FieldDecl>(member)) {
// The pointer that the reference field holds, which is used in place in
// an unboxed struct.
Expand Down
20 changes: 14 additions & 6 deletions cpp2rust/converter/rules/registry.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -555,11 +555,20 @@ bool ReturnsReference(const clang::Expr *expr) {
->isReferenceType();
}

static bool BindsGenericToReference(const TranslationRule::TypeInfo &param,
const Matcher::Bindings &bindings) {
auto n = param.generic;
return n && n <= bindings.size() &&
bindings[n - 1].getKind() == clang::TemplateArgument::Type &&
bindings[n - 1].getAsType()->isReferenceType();
}

bool ParamIsPointer(clang::ASTContext &ctx, const clang::Expr *expr,
unsigned index) {
auto rule = Search(ctx, expr).first;
auto [rule, bindings] = Search(ctx, expr);
assert(rule && "expression must have a translation rule");
return rule->params.at(index).is_pointer();
auto &param = rule->params.at(index);
return param.is_pointer() || BindsGenericToReference(param, bindings);
}

bool ParamTakesPointerValue(const clang::Expr *expr, unsigned index) {
Expand All @@ -585,9 +594,8 @@ clang::Expr *BuildParamConversion(clang::ASTContext &ctx,
clang::Expr *arg) {
auto [rule, bindings] = Search(ctx, expr);
assert(rule && "expression must have a translation rule");
llvm::StringRef type = rule->params.at(index).type;
unsigned n = 0;
if (!type.consume_front("T") || type.empty() || type.getAsInteger(10, n)) {
auto n = rule->params.at(index).generic;
if (!n) {
return nullptr;
}
auto &binding = bindings.at(n - 1);
Expand All @@ -596,7 +604,7 @@ clang::Expr *BuildParamConversion(clang::ASTContext &ctx,
auto target = binding.getAsType();
if ((arg->getType()->isArrayType() && target->isPointerType()) ||
ctx.hasSameUnqualifiedType(arg->getType().getNonReferenceType(),
target)) {
target.getNonReferenceType())) {
return nullptr;
}
auto *init = BuildInitExpr(*sema_, target, arg, arg->getExprLoc());
Expand Down
6 changes: 5 additions & 1 deletion cpp2rust/converter/translation_rule.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ TypeInfo ParseTypeInfoJSON(const llvm::json::Object &obj) {
info.is_refcount_pointer = *v;
if (auto v = obj.getBoolean("is_unsafe_pointer"))
info.is_unsafe_pointer = *v;
if (auto v = obj.getInteger("generic"))
info.generic = *v;
assert(!(info.is_refcount_pointer && info.is_unsafe_pointer));
if (auto *arr = obj.getArray("derives")) {
for (const auto &elem : *arr) {
Expand Down Expand Up @@ -351,7 +353,9 @@ bool ExprRule::takesAddress(clang::ASTContext &ctx, const clang::Expr *expr,
if (arg->getType()->isPointerType()) {
return !RuleRegistry::ParamTakesPointerValue(expr, i);
}
return !RuleRegistry::MapsToPointer(ctx, arg->getType());
return RuleRegistry::ParamIsPointer(ctx, expr, i) &&
!arg->getType()->isPointerType() &&
!RuleRegistry::MapsToPointer(ctx, arg->getType());
}

bool ExprRule::takesTemporaryAddress(clang::ASTContext &ctx,
Expand Down
1 change: 1 addition & 0 deletions cpp2rust/converter/translation_rule.h
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ struct TypeInfo {
bool is_refcount_pointer = false;
bool is_unsafe_pointer = false;
std::optional<Elems> elems;
unsigned generic = 0;

bool is_pointer() const { return is_refcount_pointer || is_unsafe_pointer; }

Expand Down
2 changes: 2 additions & 0 deletions rule-preprocessor/src/ir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ pub struct TypeInfo {
pub cpp_type: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub elems: Option<Elems>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub generic: Option<i32>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
Expand Down
10 changes: 7 additions & 3 deletions rule-preprocessor/src/syntactic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -503,6 +503,7 @@ impl<'a> FnIrBuilder<'a> {
derives: Vec::new(),
cpp_type: None,
elems: None,
generic: None,
})
}
}
Expand Down Expand Up @@ -714,6 +715,8 @@ impl<'a> FnIrBuilder<'a> {
.map(|n| n.text().to_string())
.unwrap_or_default();
let params = self.params();
let generics = self.generics();
let generic_names: Vec<String> = generics.keys().cloned().collect();

let params_map: BTreeMap<String, TypeInfo> = params
.iter()
Expand All @@ -728,14 +731,14 @@ impl<'a> FnIrBuilder<'a> {
derives: Vec::new(),
cpp_type: p.cpp_type.clone(),
elems: None,
generic: generic_names
.contains(&p.ty)
.then(|| p.ty[1..].parse().unwrap_or(0)),
},
)
})
.collect();

let generics = self.generics();
let generic_names: Vec<String> = generics.keys().cloned().collect();

let multi_statement = self.fn_item.body().and_then(|body| {
body.stmt_list().and_then(|stmt_list| {
let stmt_count = stmt_list.statements().count();
Expand Down Expand Up @@ -840,6 +843,7 @@ impl<'a> TypeIrBuilder<'a> {
derives: Vec::new(),
cpp_type: None,
elems: elems(&ty),
generic: None,
},
}
}
Expand Down
11 changes: 11 additions & 0 deletions tests/std/utilities/pairs/out/refcount/pairs.pair.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,17 @@ pub fn test_1() {
&& ((elem!((*copied.borrow()).0.decay(), 1_usize).read()) == 7)
})
);
let referent: Value<i32> = Rc::new(RefCell::new(5));
let bound: Value<(Value<Ptr<i32>>, Value<i8>)> = Rc::new(RefCell::new((
Rc::new(RefCell::new(referent.as_pointer())),
Rc::new(RefCell::new(('c' as i8))),
)));
(*referent.borrow_mut()) = 6;
assert!(({ (((*bound.borrow()).0.borrow().clone().read()) == 6) }));
assert!(
({ ({ ((*bound.borrow()).0.borrow().clone()).clone() } == { (referent.as_pointer()) }) })
);
assert!(({ (((*(*bound.borrow()).1.borrow()) as i32) == (('c' as i8) as i32)) }));
}
pub fn test_2() {
let source: Value<(Value<i32>, Value<Option<Value<i32>>>)> = Rc::new(RefCell::new((
Expand Down
6 changes: 6 additions & 0 deletions tests/std/utilities/pairs/out/unsafe/pairs.pair.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,12 @@ pub unsafe fn test_1() {
let mut copied: (Vec<i32>, i32) = ((values).clone(), 3);
assert!(((values.len()) == (2_usize)));
assert!(((copied.0.len()) == (2_usize)) && ((copied.0[(1_usize)]) == (7)));
let mut referent: i32 = 5;
let mut bound: (*const i32, libc::c_char) = (&mut referent, ('c' as libc::c_char));
referent = 6;
assert!(((*bound.0) == (6)));
assert!(((bound.0) == ((&mut referent as *mut i32).cast_const())));
assert!(((bound.1 as i32) == (('c' as libc::c_char) as i32)));
}
pub unsafe fn test_2() {
let mut source: (i32, Option<Box<i32>>) = (
Expand Down
7 changes: 7 additions & 0 deletions tests/std/utilities/pairs/pairs.pair.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,13 @@ void test() {
std::pair<std::vector<int>, int> copied(std::move(values), 3);
assert(values.size() == 2);
assert(copied.first.size() == 2 && copied.first[1] == 7);

int referent = 5;
std::pair<const int &, char> bound(referent, 'c');
referent = 6;
assert(bound.first == 6);
assert(&bound.first == &referent);
assert(bound.second == 'c');
}
} // namespace p12_forwarding_constructor

Expand Down
Loading