From 1e9c805b10cf1b7b13016fa64b5f9601fb2e4c07 Mon Sep 17 00:00:00 2001 From: Lucian Popescu Date: Tue, 17 Nov 2026 21:48:37 +0000 Subject: [PATCH 1/3] Read the pointer of mapped reference fields in refcount --- cpp2rust/converter/models/converter_refcount.cpp | 3 +++ tests/std/utilities/pairs/pairs.pair.cpp | 7 +++++++ 2 files changed, 10 insertions(+) diff --git a/cpp2rust/converter/models/converter_refcount.cpp b/cpp2rust/converter/models/converter_refcount.cpp index c98074028d..b9afd0ce12 100644 --- a/cpp2rust/converter/models/converter_refcount.cpp +++ b/cpp2rust/converter/models/converter_refcount.cpp @@ -1836,6 +1836,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(member)) { // The pointer that the reference field holds, which is used in place in // an unboxed struct. diff --git a/tests/std/utilities/pairs/pairs.pair.cpp b/tests/std/utilities/pairs/pairs.pair.cpp index 3098126f5d..9213beb6ce 100644 --- a/tests/std/utilities/pairs/pairs.pair.cpp +++ b/tests/std/utilities/pairs/pairs.pair.cpp @@ -37,6 +37,13 @@ void test() { std::pair, int> copied(std::move(values), 3); assert(values.size() == 2); assert(copied.first.size() == 2 && copied.first[1] == 7); + + int referent = 5; + std::pair bound(referent, 'c'); + referent = 6; + assert(bound.first == 6); + assert(&bound.first == &referent); + assert(bound.second == 'c'); } } // namespace p12_forwarding_constructor From 6f8a10b06ec696a85fe7640e7eff86cae89ca5fb Mon Sep 17 00:00:00 2001 From: Lucian Popescu Date: Tue, 17 Nov 2026 22:44:02 +0000 Subject: [PATCH 2/3] Add generic in the type instead of parsing it as string --- cpp2rust/converter/converter.cpp | 3 +- cpp2rust/converter/models/boxed_vars.cpp | 2 +- cpp2rust/converter/rules/registry.cpp | 33 +++++++++++++++---- cpp2rust/converter/translation_rule.cpp | 11 ++++--- cpp2rust/converter/translation_rule.h | 3 +- rule-preprocessor/src/ir.rs | 2 ++ rule-preprocessor/src/syntactic.rs | 10 ++++-- .../pairs/out/refcount/pairs.pair.rs | 11 +++++++ .../utilities/pairs/out/unsafe/pairs.pair.rs | 6 ++++ 9 files changed, 65 insertions(+), 16 deletions(-) diff --git a/cpp2rust/converter/converter.cpp b/cpp2rust/converter/converter.cpp index fd4a3b5c30..20d3719f0a 100644 --- a/cpp2rust/converter/converter.cpp +++ b/cpp2rust/converter/converter.cpp @@ -5592,7 +5592,8 @@ std::string Converter::GetMappedAsString(clang::Expr *expr, clang::Expr **args, // The rule takes the value of a transparent union. auto *arg = IgnoreTransparentUnion(all_args[i]); auto type = arg->getType(); - bool by_value = arg->isPRValue() && !tgt_ir->takesAddress(ctx_, i, arg); + bool by_value = + arg->isPRValue() && !tgt_ir->takesAddress(ctx_, expr, i, arg); if (!by_value && arg->isPRValue()) { arg = new (ctx_) clang::MaterializeTemporaryExpr(type, arg, false); } diff --git a/cpp2rust/converter/models/boxed_vars.cpp b/cpp2rust/converter/models/boxed_vars.cpp index 4e78ce6b00..ba2965d50e 100644 --- a/cpp2rust/converter/models/boxed_vars.cpp +++ b/cpp2rust/converter/models/boxed_vars.cpp @@ -381,7 +381,7 @@ class AddressTakenVisitor })) { continue; } - if (!rule->takesAddress(ctx_, i, arg) || + if (!rule->takesAddress(ctx_, expr, i, arg) || rule->takesTemporaryAddress(ctx_, expr, i, arg)) { AddValueUse(arg); } diff --git a/cpp2rust/converter/rules/registry.cpp b/cpp2rust/converter/rules/registry.cpp index ef867d4b97..5373bb731f 100644 --- a/cpp2rust/converter/rules/registry.cpp +++ b/cpp2rust/converter/rules/registry.cpp @@ -555,11 +555,33 @@ bool ReturnsReference(const clang::Expr *expr) { ->isReferenceType(); } +static bool BindsGenericToReference(const TranslationRule::TypeInfo ¶m, + const Matcher::Bindings &bindings, + const clang::Expr *expr, unsigned index) { + auto n = param.generic; + if (!n || n > bindings.size() || + bindings[n - 1].getKind() != clang::TemplateArgument::Type || + !bindings[n - 1].getAsType()->isReferenceType()) { + return false; + } + auto *function = findExpr(expr).rule_decl->decl->getAsFunction(); + if (!function) { + return true; + } + auto *type = function->getParamDecl(index) + ->getType() + .getNonReferenceType() + ->getAs(); + return !type || type->getIndex() != n - 1; +} + 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 ¶m = rule->params.at(index); + return param.is_pointer() || + BindsGenericToReference(param, bindings, expr, index); } clang::Expr *BuildParamConversion(clang::ASTContext &ctx, @@ -567,9 +589,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); @@ -578,7 +599,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()); diff --git a/cpp2rust/converter/translation_rule.cpp b/cpp2rust/converter/translation_rule.cpp index bc82a38bd3..a450f95d65 100644 --- a/cpp2rust/converter/translation_rule.cpp +++ b/cpp2rust/converter/translation_rule.cpp @@ -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) { @@ -332,13 +334,14 @@ ExprRule::argsToBind(clang::ASTContext &ctx, const clang::Expr *expr, return bind; } -bool ExprRule::takesAddress(clang::ASTContext &ctx, unsigned i, - const clang::Expr *arg) const { +bool ExprRule::takesAddress(clang::ASTContext &ctx, const clang::Expr *expr, + unsigned i, const clang::Expr *arg) const { // An init pack forwards references to its arguments, not their values. if (i >= params.size()) { return usesInit(); } - return params[i].is_pointer() && !arg->getType()->isPointerType() && + return RuleRegistry::ParamIsPointer(ctx, expr, i) && + !arg->getType()->isPointerType() && !RuleRegistry::MapsToPointer(ctx, arg->getType()); } @@ -347,7 +350,7 @@ bool ExprRule::takesTemporaryAddress(clang::ASTContext &ctx, const clang::Expr *arg) const { auto *call = clang::dyn_cast(expr); unsigned first_arg = clang::isa(expr); - return call && i >= first_arg && takesAddress(ctx, i, arg) && + return call && i >= first_arg && takesAddress(ctx, expr, i, arg) && GetRefBindingTempType(ctx, call, i - first_arg).has_value(); } diff --git a/cpp2rust/converter/translation_rule.h b/cpp2rust/converter/translation_rule.h index d5be83aa90..43d104a3f3 100644 --- a/cpp2rust/converter/translation_rule.h +++ b/cpp2rust/converter/translation_rule.h @@ -110,6 +110,7 @@ struct TypeInfo { bool is_refcount_pointer = false; bool is_unsafe_pointer = false; std::optional elems; + unsigned generic = 0; bool is_pointer() const { return is_refcount_pointer || is_unsafe_pointer; } @@ -140,7 +141,7 @@ struct ExprRule { // Whether the body takes a pointer to arg, its argument i, which is not a // pointer. - bool takesAddress(clang::ASTContext &ctx, unsigned i, + bool takesAddress(clang::ASTContext &ctx, const clang::Expr *expr, unsigned i, const clang::Expr *arg) const; // Whether the body takes a pointer to a temporary copy of arg, argument i diff --git a/rule-preprocessor/src/ir.rs b/rule-preprocessor/src/ir.rs index 116a6edd30..9d40f2fe3d 100644 --- a/rule-preprocessor/src/ir.rs +++ b/rule-preprocessor/src/ir.rs @@ -74,6 +74,8 @@ pub struct TypeInfo { pub cpp_type: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub elems: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub generic: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/rule-preprocessor/src/syntactic.rs b/rule-preprocessor/src/syntactic.rs index 435144ba34..3f481d625b 100644 --- a/rule-preprocessor/src/syntactic.rs +++ b/rule-preprocessor/src/syntactic.rs @@ -503,6 +503,7 @@ impl<'a> FnIrBuilder<'a> { derives: Vec::new(), cpp_type: None, elems: None, + generic: None, }) } } @@ -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 = generics.keys().cloned().collect(); let params_map: BTreeMap = params .iter() @@ -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 = 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(); @@ -840,6 +843,7 @@ impl<'a> TypeIrBuilder<'a> { derives: Vec::new(), cpp_type: None, elems: elems(&ty), + generic: None, }, } } diff --git a/tests/std/utilities/pairs/out/refcount/pairs.pair.rs b/tests/std/utilities/pairs/out/refcount/pairs.pair.rs index 7282793e7e..38cda8c96e 100644 --- a/tests/std/utilities/pairs/out/refcount/pairs.pair.rs +++ b/tests/std/utilities/pairs/out/refcount/pairs.pair.rs @@ -66,6 +66,17 @@ pub fn test_1() { && ((elem!((*copied.borrow()).0.decay(), 1_usize).read()) == 7) }) ); + let referent: Value = Rc::new(RefCell::new(5)); + let bound: Value<(Value>, Value)> = 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, Value>>)> = Rc::new(RefCell::new(( diff --git a/tests/std/utilities/pairs/out/unsafe/pairs.pair.rs b/tests/std/utilities/pairs/out/unsafe/pairs.pair.rs index 401669adc7..a2fe964c8d 100644 --- a/tests/std/utilities/pairs/out/unsafe/pairs.pair.rs +++ b/tests/std/utilities/pairs/out/unsafe/pairs.pair.rs @@ -60,6 +60,12 @@ pub unsafe fn test_1() { let mut copied: (Vec, 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>) = ( From 8878d57bccfd65a499c9fd651d2fba836e3561c0 Mon Sep 17 00:00:00 2001 From: Lucian Popescu Date: Tue, 17 Nov 2026 22:51:17 +0000 Subject: [PATCH 3/3] Check that generic bidns to any kind of reference --- cpp2rust/converter/rules/registry.cpp | 23 +++++------------------ 1 file changed, 5 insertions(+), 18 deletions(-) diff --git a/cpp2rust/converter/rules/registry.cpp b/cpp2rust/converter/rules/registry.cpp index 5373bb731f..217b591e4b 100644 --- a/cpp2rust/converter/rules/registry.cpp +++ b/cpp2rust/converter/rules/registry.cpp @@ -556,23 +556,11 @@ bool ReturnsReference(const clang::Expr *expr) { } static bool BindsGenericToReference(const TranslationRule::TypeInfo ¶m, - const Matcher::Bindings &bindings, - const clang::Expr *expr, unsigned index) { + const Matcher::Bindings &bindings) { auto n = param.generic; - if (!n || n > bindings.size() || - bindings[n - 1].getKind() != clang::TemplateArgument::Type || - !bindings[n - 1].getAsType()->isReferenceType()) { - return false; - } - auto *function = findExpr(expr).rule_decl->decl->getAsFunction(); - if (!function) { - return true; - } - auto *type = function->getParamDecl(index) - ->getType() - .getNonReferenceType() - ->getAs(); - return !type || type->getIndex() != n - 1; + 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, @@ -580,8 +568,7 @@ bool ParamIsPointer(clang::ASTContext &ctx, const clang::Expr *expr, auto [rule, bindings] = Search(ctx, expr); assert(rule && "expression must have a translation rule"); auto ¶m = rule->params.at(index); - return param.is_pointer() || - BindsGenericToReference(param, bindings, expr, index); + return param.is_pointer() || BindsGenericToReference(param, bindings); } clang::Expr *BuildParamConversion(clang::ASTContext &ctx,