From 761ba77aee7d0a896ea2aa1268ef2b74e74d556f Mon Sep 17 00:00:00 2001 From: Lucian Popescu Date: Tue, 17 Nov 2026 15:02:04 +0000 Subject: [PATCH 1/8] Look through std::move when finding value uses of boxed variables --- cpp2rust/converter/converter.cpp | 31 +++++----- cpp2rust/converter/converter_lib.cpp | 29 ++++++++++ cpp2rust/converter/converter_lib.h | 15 +++++ cpp2rust/converter/models/boxed_vars.cpp | 19 ++++++- tests/std/utilities/utility/forward.cpp | 72 ++++++++++++++++++++++++ 5 files changed, 150 insertions(+), 16 deletions(-) create mode 100644 tests/std/utilities/utility/forward.cpp diff --git a/cpp2rust/converter/converter.cpp b/cpp2rust/converter/converter.cpp index d1a32a9e08..129a2e68b6 100644 --- a/cpp2rust/converter/converter.cpp +++ b/cpp2rust/converter/converter.cpp @@ -5436,17 +5436,24 @@ std::string Converter::ConvertPlaceholder(clang::Expr *expr, clang::Expr *arg, // The rule takes the argument by value from an rvalue reference parameter, // e.g., push_back(T &&), and so C++ moves it. - auto param_type = GetParamType(expr, ph_ctx.arg_idx); - bool moved = ph_ctx.access == TranslationRule::Access::kTake || - (ph_ctx.access == TranslationRule::Access::kMove && param_type && - (*param_type)->isRValueReferenceType()); - if (moved && !clang::isa(arg)) { + if (auto *init = BuildMoveConstruction(ctx_, expr, ph_ctx.arg_idx, arg, + ph_ctx.access)) { + Buffer buf(*this); + Convert(init); + return std::move(buf).str(); + } + if (MovesRuleArg(expr, ph_ctx.arg_idx, arg, ph_ctx.access)) { auto *ref = clang::dyn_cast(arg->IgnoreParenImpCasts()); auto *var = ref ? clang::dyn_cast(ref->getDecl()) : nullptr; - if (auto *record = arg->getType()->getAsCXXRecordDecl(); - record && (IsUserDefinedDecl(record) || - (ph_ctx.access == TranslationRule::Access::kMove && - bound_init_args_.contains(var)))) { + auto *record = arg->getType()->getAsCXXRecordDecl(); + if (record && IsUserDefinedDecl(record)) { + if (TypeIsCopyable(arg->getType())) { + return ConvertRValue(arg); + } + return ConvertFreshRValue(arg); + } + if (record && ph_ctx.access == TranslationRule::Access::kMove && + bound_init_args_.contains(var)) { for (auto *ctor : record->ctors()) { if (!ctor->isMoveConstructor() || ctor->isDeleted()) { continue; @@ -5462,12 +5469,6 @@ std::string Converter::ConvertPlaceholder(clang::Expr *expr, clang::Expr *arg, Convert(init); return std::move(buf).str(); } - if (IsUserDefinedDecl(record)) { - if (TypeIsCopyable(arg->getType())) { - return ConvertRValue(arg); - } - return ConvertFreshRValue(arg); - } } } diff --git a/cpp2rust/converter/converter_lib.cpp b/cpp2rust/converter/converter_lib.cpp index 8499531211..fee8952373 100644 --- a/cpp2rust/converter/converter_lib.cpp +++ b/cpp2rust/converter/converter_lib.cpp @@ -567,6 +567,35 @@ bool IsConvertibleMoveConstructor(const clang::CXXConstructorDecl *ctor) { return ctor->isUserProvided() || NeedsDefaultedMoveConstructor(parent); } +bool MovesRuleArg(clang::Expr *expr, unsigned arg_idx, clang::Expr *arg, + TranslationRule::Access access) { + auto param_type = GetParamType(expr, arg_idx); + bool moved = access == TranslationRule::Access::kTake || + (access == TranslationRule::Access::kMove && param_type && + (*param_type)->isRValueReferenceType()); + return moved && !clang::isa(arg); +} + +clang::CXXConstructExpr *BuildMoveConstruction(clang::ASTContext &ctx, + clang::Expr *expr, + unsigned arg_idx, + clang::Expr *arg, + TranslationRule::Access access) { + if (!MovesRuleArg(expr, arg_idx, arg, access)) { + return nullptr; + } + auto *record = arg->getType()->getAsCXXRecordDecl(); + if (!record || !IsUserDefinedDecl(record)) { + return nullptr; + } + for (auto *ctor : record->ctors()) { + if (IsConvertibleMoveConstructor(ctor)) { + return MakeConstructExpr(ctx, arg->getType(), ctor, arg); + } + } + return nullptr; +} + static bool IsImplicitConvertingConstructor(const clang::CXXConstructorDecl *ctor) { return !ctor->isCopyOrMoveConstructor() && !ctor->isImplicit() && diff --git a/cpp2rust/converter/converter_lib.h b/cpp2rust/converter/converter_lib.h index acdb97eccb..224973621b 100644 --- a/cpp2rust/converter/converter_lib.h +++ b/cpp2rust/converter/converter_lib.h @@ -20,6 +20,7 @@ #include #include +#include "converter/translation_rule.h" #include "logging.h" namespace clang { @@ -105,6 +106,20 @@ bool IsDefaultedMoveConstructor(const clang::CXXConstructorDecl *ctor); bool IsConvertibleMoveConstructor(const clang::CXXConstructorDecl *ctor); +// Whether a rule moves arg, its argument arg_idx of expr, out of an object +// rather than a temporary: it takes it by value, or by value from an rvalue +// reference parameter, e.g., push_back(T &&). +bool MovesRuleArg(clang::Expr *expr, unsigned arg_idx, clang::Expr *arg, + TranslationRule::Access access); + +// The call to the move constructor of a user-defined record that moves arg, +// its argument arg_idx of expr, into a rule, which takes a pointer to arg. +clang::CXXConstructExpr *BuildMoveConstruction(clang::ASTContext &ctx, + clang::Expr *expr, + unsigned arg_idx, + clang::Expr *arg, + TranslationRule::Access access); + // Whether decl has a move constructor converted to a move_from method. bool HasMoveFromConstructor(const clang::RecordDecl *decl); diff --git a/cpp2rust/converter/models/boxed_vars.cpp b/cpp2rust/converter/models/boxed_vars.cpp index 3934c5a434..afb0e54dd6 100644 --- a/cpp2rust/converter/models/boxed_vars.cpp +++ b/cpp2rust/converter/models/boxed_vars.cpp @@ -317,6 +317,23 @@ class AddressTakenVisitor TraverseStmt(init); continue; } + bool moved_by_ctor = false; + TranslationRule::AnyFragment( + rule->body, [&](const TranslationRule::BodyFragment &fragment) { + auto *ph = + std::get_if(&fragment); + if (ph && ph->n == i) { + if (auto *init = BuildMoveConstruction(ctx_, expr, i, all_args[i], + ph->access)) { + TraverseStmt(init); + moved_by_ctor = true; + } + } + return false; + }); + if (moved_by_ctor) { + continue; + } if (!rule->takesAddress(ctx_, i, arg) || rule->takesTemporaryAddress(ctx_, expr, i, arg)) { AddValueUse(arg); @@ -327,7 +344,7 @@ class AddressTakenVisitor // An element of an array or vector, or a field of a struct, is accessed // without making a pointer to it. void AddValueUse(const clang::Expr *expr, bool write = false) { - expr = IgnoreNoOpCasts(expr->IgnoreParens()); + expr = IgnoreNoOpCasts(IgnoreTransparentStdCall(expr)->IgnoreParens()); // The value of a conditional lvalue is the value of either operand; it is // written through a pointer to the operand. if (auto *cond = clang::dyn_cast(expr)) { diff --git a/tests/std/utilities/utility/forward.cpp b/tests/std/utilities/utility/forward.cpp new file mode 100644 index 0000000000..b7db5a6a96 --- /dev/null +++ b/tests/std/utilities/utility/forward.cpp @@ -0,0 +1,72 @@ +// ADDITIONAL_COMPILE_FLAGS: -std=c++23 +#include +#include +#include + +// N4950 [forward]/9: std::move(t) returns +// static_cast&&>(t), so moving a scalar reads its value. +namespace p9_move_scalar { +void test() { + int source = 1; + int target = std::move(source); + assert(target == 1); + assert(source == 1); +} +} // namespace p9_move_scalar + +// N4950 [forward]/9: moving a trivially copyable object copies its value. +namespace p9_move_trivially_copyable { +struct Point { + int x; + int y; +}; + +void test() { + Point source{1, 2}; + Point target = std::move(source); + assert(target.x == 1 && target.y == 2); + assert(source.x == 1 && source.y == 2); + + Point assigned{0, 0}; + Point other{3, 4}; + assigned = std::move(other); + assert(assigned.x == 3 && assigned.y == 4); + assert(other.x == 3 && other.y == 4); + + std::vector points; + Point element{5, 6}; + points.push_back(std::move(element)); + assert(points[0].x == 5 && points[0].y == 6); + assert(element.x == 5 && element.y == 6); +} +} // namespace p9_move_trivially_copyable + +// N4950 [forward]/10: std::move(a) binds to the constructor A(A&&), which +// moves the value from a. +namespace p10_move_constructor { +struct A { + int value; + A(int value) : value(value) {} + A(A &&other) : value(other.value) { other.value = 0; } +}; + +void test() { + A source(1); + A target = std::move(source); + assert(target.value == 1); + assert(source.value == 0); + + std::vector values; + A element(2); + values.push_back(std::move(element)); + assert(values[0].value == 2); + assert(element.value == 0); +} +} // namespace p10_move_constructor + +int main() { + p9_move_scalar::test(); + p9_move_trivially_copyable::test(); + p10_move_constructor::test(); + return 0; +} From 54e2983f24a9804af31a6dfde8de3db2d21d0e90 Mon Sep 17 00:00:00 2001 From: Lucian Popescu Date: Tue, 17 Nov 2026 19:41:19 +0000 Subject: [PATCH 2/8] Drop comments --- cpp2rust/converter/converter_lib.h | 5 ----- 1 file changed, 5 deletions(-) diff --git a/cpp2rust/converter/converter_lib.h b/cpp2rust/converter/converter_lib.h index 829fa43541..73b2d6e9ac 100644 --- a/cpp2rust/converter/converter_lib.h +++ b/cpp2rust/converter/converter_lib.h @@ -111,14 +111,9 @@ bool IsDefaultedMoveConstructor(const clang::CXXConstructorDecl *ctor); bool IsConvertibleMoveConstructor(const clang::CXXConstructorDecl *ctor); -// Whether a rule moves arg, its argument arg_idx of expr, out of an object -// rather than a temporary: it takes it by value, or by value from an rvalue -// reference parameter, e.g., push_back(T &&). bool MovesRuleArg(clang::Expr *expr, unsigned arg_idx, clang::Expr *arg, TranslationRule::Access access); -// The call to the move constructor of a user-defined record that moves arg, -// its argument arg_idx of expr, into a rule, which takes a pointer to arg. clang::CXXConstructExpr *BuildMoveConstruction(clang::ASTContext &ctx, clang::Expr *expr, unsigned arg_idx, From 99a2637edd41437e0bb99e06a9730ad3e49f89aa Mon Sep 17 00:00:00 2001 From: Lucian Popescu Date: Tue, 17 Nov 2026 19:45:48 +0000 Subject: [PATCH 3/8] Update tests --- .../utilities/utility/out/refcount/forward.rs | 92 +++++++++++++++++++ .../utilities/utility/out/unsafe/forward.rs | 89 ++++++++++++++++++ tests/unit/out/refcount/11_move.rs | 6 +- tests/unit/out/refcount/alloc_array.rs | 8 +- .../unit/out/refcount/copy_move_defaulted.rs | 10 +- tests/unit/out/refcount/foreach_double.rs | 12 +-- tests/unit/out/refcount/matmul.rs | 10 +- tests/unit/out/refcount/references2.rs | 4 +- tests/unit/out/refcount/unique_ptr.rs | 23 +++-- tests/unit/out/refcount/unique_ptr_small.rs | 4 +- 10 files changed, 218 insertions(+), 40 deletions(-) create mode 100644 tests/std/utilities/utility/out/refcount/forward.rs create mode 100644 tests/std/utilities/utility/out/unsafe/forward.rs diff --git a/tests/std/utilities/utility/out/refcount/forward.rs b/tests/std/utilities/utility/out/refcount/forward.rs new file mode 100644 index 0000000000..70fd80ede9 --- /dev/null +++ b/tests/std/utilities/utility/out/refcount/forward.rs @@ -0,0 +1,92 @@ +extern crate libcc2rs; +use libcc2rs::*; +use std::cell::RefCell; +use std::collections::BTreeMap; +use std::io::prelude::*; +use std::io::{Read, Seek, Write}; +use std::os::fd::AsFd; +use std::rc::{Rc, Weak}; +pub fn test_0() { + let mut source: i32 = 1; + let mut target: i32 = source; + assert!((target == 1)); + assert!((source == 1)); +} +#[derive(Clone, Record, ByteRepr, VaArg, FnPtrArg, Default)] +#[byte_size(8)] +pub struct p9_move_trivially_copyable_Point { + #[offset(0)] + pub x: i32, + #[offset(4)] + pub y: i32, +} +pub fn test_1() { + let mut source: p9_move_trivially_copyable_Point = + p9_move_trivially_copyable_Point { x: 1, y: 2 }; + let mut target: p9_move_trivially_copyable_Point = (source).clone(); + assert!((target.x == 1) && (target.y == 2)); + assert!((source.x == 1) && (source.y == 2)); + let mut assigned: p9_move_trivially_copyable_Point = + p9_move_trivially_copyable_Point { x: 0, y: 0 }; + let mut other: p9_move_trivially_copyable_Point = + p9_move_trivially_copyable_Point { x: 3, y: 4 }; + assigned = (other).clone(); + assert!((assigned.x == 3) && (assigned.y == 4)); + assert!((other.x == 3) && (other.y == 4)); + let mut points: Vec = Vec::new(); + let mut element: p9_move_trivially_copyable_Point = + p9_move_trivially_copyable_Point { x: 5, y: 6 }; + { + let __a1 = (element).clone(); + points.push(__a1) + }; + assert!((points[0_usize].x == 5) && (points[0_usize].y == 6)); + assert!((element.x == 5) && (element.y == 6)); +} +#[derive(Record, ByteRepr, FnPtrArg, MoveCtor, CppFrom, Default)] +#[cpp_from(i32, new, value)] +#[byte_size(4)] +pub struct p10_move_constructor_A { + #[offset(0)] + pub value: i32, +} +impl p10_move_constructor_A { + pub fn new(mut value: i32) -> Self { + Self { value: value } + } + pub fn move_from(other: Ptr) -> Self { + let __this: p10_move_constructor_A = Self { + value: other.with(|__s| __s.value), + }; + field!(other, value).write(0); + __this + } +} +pub fn test_2() { + let source: Value = + Rc::new(RefCell::new(p10_move_constructor_A::new({ 1 }))); + let mut target: p10_move_constructor_A = + p10_move_constructor_A::move_from({ source.as_pointer() }); + assert!((target.value == 1)); + assert!(({ ({ (*source.borrow()).value } == 0) })); + let mut values: Vec = Vec::new(); + let element: Value = + Rc::new(RefCell::new(p10_move_constructor_A::new({ 2 }))); + { + let __a1 = p10_move_constructor_A::move_from({ element.as_pointer() }); + values.push(__a1) + }; + assert!((values[0_usize].value == 2)); + assert!(({ ({ (*element.borrow()).value } == 0) })); +} +pub fn main() { + __cpp2rust_init_globals(); + std::process::exit(main_0()); +} +fn main_0() -> i32 { + ({ test_0() }); + ({ test_1() }); + ({ test_2() }); + return 0; +} +pub fn __cpp2rust_init_globals() {} diff --git a/tests/std/utilities/utility/out/unsafe/forward.rs b/tests/std/utilities/utility/out/unsafe/forward.rs new file mode 100644 index 0000000000..4ea1041c97 --- /dev/null +++ b/tests/std/utilities/utility/out/unsafe/forward.rs @@ -0,0 +1,89 @@ +extern crate libc; +use libc::*; +extern crate libcc2rs; +use libcc2rs::*; +use std::collections::BTreeMap; +use std::io::{Read, Seek, Write}; +use std::os::fd::{AsFd, FromRawFd, IntoRawFd}; +use std::rc::Rc; +pub unsafe fn test_0() { + let mut source: i32 = 1; + let mut target: i32 = source; + assert!(((target) == (1))); + assert!(((source) == (1))); +} +#[repr(C)] +#[derive(Copy, Clone, VaArg, FnPtrArg, Default)] +pub struct p9_move_trivially_copyable_Point { + pub x: i32, + pub y: i32, +} +pub unsafe fn test_1() { + let mut source: p9_move_trivially_copyable_Point = + p9_move_trivially_copyable_Point { x: 1, y: 2 }; + let mut target: p9_move_trivially_copyable_Point = source; + assert!(((target.x) == (1)) && ((target.y) == (2))); + assert!(((source.x) == (1)) && ((source.y) == (2))); + let mut assigned: p9_move_trivially_copyable_Point = + p9_move_trivially_copyable_Point { x: 0, y: 0 }; + let mut other: p9_move_trivially_copyable_Point = + p9_move_trivially_copyable_Point { x: 3, y: 4 }; + assigned = other; + assert!(((assigned.x) == (3)) && ((assigned.y) == (4))); + assert!(((other.x) == (3)) && ((other.y) == (4))); + let mut points: Vec = Vec::new(); + let mut element: p9_move_trivially_copyable_Point = + p9_move_trivially_copyable_Point { x: 5, y: 6 }; + { + let __a1 = element; + points.push(__a1) + }; + assert!(((points[(0_usize)].x) == (5)) && ((points[(0_usize)].y) == (6))); + assert!(((element.x) == (5)) && ((element.y) == (6))); +} +#[repr(C)] +#[derive(FnPtrArg, MoveCtorUnsafe, CppFromUnsafe, Default)] +#[cpp_from(i32, new, value)] +pub struct p10_move_constructor_A { + pub value: i32, +} +impl p10_move_constructor_A { + pub unsafe fn new(mut value: i32) -> Self { + let mut this = Self { value: value }; + this + } + pub unsafe fn move_from(other: *mut p10_move_constructor_A) -> Self { + let mut this = Self { + value: (*other).value, + }; + (*other).value = 0; + this + } +} +pub unsafe fn test_2() { + let mut source: p10_move_constructor_A = p10_move_constructor_A::new({ 1 }); + let mut target: p10_move_constructor_A = p10_move_constructor_A::move_from({ &mut source }); + assert!(((target.value) == (1))); + assert!(((source.value) == (0))); + let mut values: Vec = Vec::new(); + let mut element: p10_move_constructor_A = p10_move_constructor_A::new({ 2 }); + { + let __a1 = p10_move_constructor_A::move_from({ &mut element }); + values.push(__a1) + }; + assert!(((values[(0_usize)].value) == (2))); + assert!(((element.value) == (0))); +} +pub fn main() { + unsafe { + __cpp2rust_init_globals(); + std::process::exit(main_0() as i32); + } +} +unsafe fn main_0() -> i32 { + (unsafe { test_0() }); + (unsafe { test_1() }); + (unsafe { test_2() }); + return 0; +} +pub unsafe fn __cpp2rust_init_globals() {} diff --git a/tests/unit/out/refcount/11_move.rs b/tests/unit/out/refcount/11_move.rs index 5fd52dccaf..498f036548 100644 --- a/tests/unit/out/refcount/11_move.rs +++ b/tests/unit/out/refcount/11_move.rs @@ -7,9 +7,9 @@ use std::io::{Read, Seek, Write}; use std::os::fd::AsFd; use std::rc::{Rc, Weak}; pub fn change_0(n: Ptr>>) { - let m: Value>> = Rc::new(RefCell::new(Some(Rc::new(RefCell::new(20))))); - n.write((*m.borrow_mut()).take()); - assert!(({ ((*m.borrow()).as_pointer()).is_null() })); + let mut m: Option> = Some(Rc::new(RefCell::new(20))); + n.write(m.take()); + assert!((m.as_pointer()).is_null()); } pub fn main() { __cpp2rust_init_globals(); diff --git a/tests/unit/out/refcount/alloc_array.rs b/tests/unit/out/refcount/alloc_array.rs index 3a95c576f8..3d995d3501 100644 --- a/tests/unit/out/refcount/alloc_array.rs +++ b/tests/unit/out/refcount/alloc_array.rs @@ -7,17 +7,17 @@ use std::io::{Read, Seek, Write}; use std::os::fd::AsFd; use std::rc::{Rc, Weak}; pub fn All_0(arr: Ptr>>>, mut N: i32, mut element: i32) { - let all: Value>>> = Rc::new(RefCell::new(Some(Rc::new(RefCell::new( + let mut all: Option>> = Some(Rc::new(RefCell::new( (0..(N as usize)).map(|_| 0_i32).collect::>(), - ))))); + ))); { let mut i: i32 = 0; 'loop_: while (i < N) { - (*all.borrow()).decay().offset((i as usize)).write(element); + all.decay().offset((i as usize)).write(element); i.prefix_inc(); } } - arr.write((*all.borrow_mut()).take()); + arr.write(all.take()); } pub fn Consume_1(mut arr: Option>>, mut N: i32) -> i32 { let mut sum: i32 = 0; diff --git a/tests/unit/out/refcount/copy_move_defaulted.rs b/tests/unit/out/refcount/copy_move_defaulted.rs index 418bf61131..f98b250d14 100644 --- a/tests/unit/out/refcount/copy_move_defaulted.rs +++ b/tests/unit/out/refcount/copy_move_defaulted.rs @@ -297,15 +297,15 @@ fn main_0() -> i32 { ({ same_0(g.as_pointer(), f.as_pointer(),) }) && ({ same_0(e.as_pointer(), f.as_pointer(),) }) ); - let i: Value = Rc::new(RefCell::new(Implicit { + let mut i: Implicit = Implicit { v: 5, inner: Inner { x: 50 }, arr: Box::new([5, 6]), - })); - let mut j: Implicit = (*i.borrow()).clone(); - let mut k: Implicit = (*i.borrow()).clone(); + }; + let mut j: Implicit = (i).clone(); + let mut k: Implicit = (i).clone(); assert!(((j.v == 5) && (j.inner.x == 50)) && (j.arr[(1) as usize] == 6)); - assert!(({ ({ (*i.borrow()).v } == 5) && (k.v == 5) })); + assert!((i.v == 5) && (k.v == 5)); let mut l: Implicit = Implicit { v: 0, inner: Inner { x: 0 }, diff --git a/tests/unit/out/refcount/foreach_double.rs b/tests/unit/out/refcount/foreach_double.rs index 8fc4bd4e97..156b2968f9 100644 --- a/tests/unit/out/refcount/foreach_double.rs +++ b/tests/unit/out/refcount/foreach_double.rs @@ -54,19 +54,19 @@ fn main_0() -> i32 { } } let m: Value>> = Rc::new(RefCell::new(Vec::new())); - let v1: Value> = Rc::new(RefCell::new(Vec::new())); + let mut v1: Vec = Vec::new(); { - let __a1 = ({ std::mem::take(&mut (*v1.borrow_mut())) }); + let __a1 = std::mem::take(&mut v1); (*m.borrow_mut()).push(__a1) }; - let v2: Value> = Rc::new(RefCell::new(Vec::new())); + let mut v2: Vec = Vec::new(); { - let __a1 = ({ std::mem::take(&mut (*v2.borrow_mut())) }); + let __a1 = std::mem::take(&mut v2); (*m.borrow_mut()).push(__a1) }; - let v3: Value> = Rc::new(RefCell::new(Vec::new())); + let mut v3: Vec = Vec::new(); { - let __a1 = ({ std::mem::take(&mut (*v3.borrow_mut())) }); + let __a1 = std::mem::take(&mut v3); (*m.borrow_mut()).push(__a1) }; 'loop_: for row in IterRange::new(m.decay().begin(), m.decay().end()) { diff --git a/tests/unit/out/refcount/matmul.rs b/tests/unit/out/refcount/matmul.rs index 98dee9e0b1..6d518cbc5a 100644 --- a/tests/unit/out/refcount/matmul.rs +++ b/tests/unit/out/refcount/matmul.rs @@ -91,15 +91,13 @@ pub fn main() { fn main_0() -> i32 { let mut n: i32 = 1; let mut p: i32 = 10; - let m1: Value>>]>>>> = - Rc::new(RefCell::new(({ matalloc_0(n, p, 1) }))); - let m2: Value>>]>>>> = - Rc::new(RefCell::new(({ matalloc_0(p, n, 2) }))); + let mut m1: Option>>]>>> = ({ matalloc_0(n, p, 1) }); + let mut m2: Option>>]>>> = ({ matalloc_0(p, n, 2) }); let mut m3: Option>>]>>> = ({ - let _m1: Option>>]>>> = (*m1.borrow_mut()).take(); + let _m1: Option>>]>>> = m1.take(); let _n1: i32 = n; let _p1: i32 = p; - let _m2: Option>>]>>> = (*m2.borrow_mut()).take(); + let _m2: Option>>]>>> = m2.take(); let _n2: i32 = p; let _p2: i32 = n; matmul_1(_m1, _n1, _p1, _m2, _n2, _p2) diff --git a/tests/unit/out/refcount/references2.rs b/tests/unit/out/refcount/references2.rs index 199227f616..a97c447154 100644 --- a/tests/unit/out/refcount/references2.rs +++ b/tests/unit/out/refcount/references2.rs @@ -7,8 +7,8 @@ use std::io::{Read, Seek, Write}; use std::os::fd::AsFd; use std::rc::{Rc, Weak}; pub fn change_0(p: Ptr>>) { - let q: Value>> = Rc::new(RefCell::new(Some(Rc::new(RefCell::new(7))))); - p.write((*q.borrow_mut()).take()); + let mut q: Option> = Some(Rc::new(RefCell::new(7))); + p.write(q.take()); } pub fn main() { __cpp2rust_init_globals(); diff --git a/tests/unit/out/refcount/unique_ptr.rs b/tests/unit/out/refcount/unique_ptr.rs index 1d2576a5fb..c6408209fd 100644 --- a/tests/unit/out/refcount/unique_ptr.rs +++ b/tests/unit/out/refcount/unique_ptr.rs @@ -30,20 +30,20 @@ pub struct Pair { } pub fn DoStuffWithSafePointer_0(safe_ptr: Ptr>>) { let x1: Value>> = Rc::new(RefCell::new(Some(Rc::new(RefCell::new(0))))); - let x2: Value>> = Rc::new(RefCell::new(Some(Rc::new(RefCell::new(0))))); - (*x2.borrow()).as_pointer().write(1); - x1.as_pointer().write((*x2.borrow_mut()).take()); + let mut x2: Option> = Some(Rc::new(RefCell::new(0))); + x2.as_pointer().write(1); + x1.as_pointer().write(x2.take()); let mut raw_ptr1: Ptr = ((*x1.borrow()).as_pointer()); raw_ptr1.with_mut(|__v| __v.prefix_inc()); ({ field_ptr!(((*safe_ptr.upgrade().deref()).as_pointer()), ptr) }) .write((*x1.borrow_mut()).take()); ({ SafePointerImpl::inc(&((*safe_ptr.upgrade().deref()).as_pointer())) }); ({ SafePointerImpl::inc(&((*safe_ptr.upgrade().deref()).as_pointer())) }); - let x3: Value>> = Rc::new(RefCell::new(Some(Rc::new(RefCell::new(10))))); + let mut x3: Option> = Some(Rc::new(RefCell::new(10))); let x4: Value>> = Rc::new(RefCell::new(Some(Rc::new(RefCell::new(20))))); - let __rhs = (((*x3.borrow()).as_pointer().read()) + ((*x4.borrow()).as_pointer().read())); - (*x3.borrow()).as_pointer().write(__rhs); - x4.as_pointer().write((*x3.borrow_mut()).take()); + let __rhs = ((x3.as_pointer().read()) + ((*x4.borrow()).as_pointer().read())); + x3.as_pointer().write(__rhs); + x4.as_pointer().write(x3.take()); let mut raw_ptr2: Ptr = ((*x4.borrow()).as_pointer()); { raw_ptr2.with_mut(|__v| *__v = *__v + 1) @@ -72,9 +72,8 @@ pub fn DoStuffWithSafePointer_0(safe_ptr: Ptr>>) { .as_pointer() .write(__rhs); } -pub fn Consume_1(safe_ptr: Option>) -> i32 { - let safe_ptr: Value>> = Rc::new(RefCell::new(safe_ptr)); - let mut x: Option> = (*safe_ptr.borrow_mut()).take(); +pub fn Consume_1(mut safe_ptr: Option>) -> i32 { + let mut x: Option> = safe_ptr.take(); let mut p: Option> = Ptr::alloc(::default()).to_owned_opt(); return ((x .as_pointer() @@ -184,10 +183,10 @@ pub fn main() { std::process::exit(main_0()); } fn main_0() -> i32 { - let x: Value>> = Rc::new(RefCell::new(Some(Rc::new(RefCell::new(0))))); + let mut x: Option> = Some(Rc::new(RefCell::new(0))); let safe_ptr: Value>> = Rc::new(RefCell::new(Some(Rc::new(RefCell::new(SafePointer { - ptr: (*x.borrow_mut()).take(), + ptr: x.take(), }))))); ({ DoStuffWithSafePointer_0(safe_ptr.as_pointer()) }); assert!(({ (({ Consume_1((*safe_ptr.borrow_mut()).take(),) }) == 60) })); diff --git a/tests/unit/out/refcount/unique_ptr_small.rs b/tests/unit/out/refcount/unique_ptr_small.rs index ccf2d86e79..00295e2444 100644 --- a/tests/unit/out/refcount/unique_ptr_small.rs +++ b/tests/unit/out/refcount/unique_ptr_small.rs @@ -7,8 +7,8 @@ use std::io::{Read, Seek, Write}; use std::os::fd::AsFd; use std::rc::{Rc, Weak}; pub fn change_0(n: Ptr>>) { - let m: Value>> = Rc::new(RefCell::new(Some(Rc::new(RefCell::new(20))))); - n.write((*m.borrow_mut()).take()); + let mut m: Option> = Some(Rc::new(RefCell::new(20))); + n.write(m.take()); } pub fn main() { __cpp2rust_init_globals(); From e5ffa1ae5045cea0f358917ed4c51ed1c87b74d0 Mon Sep 17 00:00:00 2001 From: Lucian Popescu Date: Tue, 17 Nov 2026 19:47:29 +0000 Subject: [PATCH 4/8] Keep ConvertPlaceholder as on master --- cpp2rust/converter/converter.cpp | 25 +++++++----------- cpp2rust/converter/converter_lib.cpp | 20 -------------- cpp2rust/converter/converter_lib.h | 6 ----- cpp2rust/converter/models/boxed_vars.cpp | 33 +++++++++++++----------- 4 files changed, 28 insertions(+), 56 deletions(-) diff --git a/cpp2rust/converter/converter.cpp b/cpp2rust/converter/converter.cpp index fb9f30637e..ede8f8dbb7 100644 --- a/cpp2rust/converter/converter.cpp +++ b/cpp2rust/converter/converter.cpp @@ -5443,24 +5443,13 @@ std::string Converter::ConvertPlaceholder(clang::Expr *expr, clang::Expr *arg, // The rule takes the argument by value from an rvalue reference parameter, // e.g., push_back(T &&), and so C++ moves it. - if (auto *init = BuildMoveConstruction(ctx_, expr, ph_ctx.arg_idx, arg, - ph_ctx.access)) { - Buffer buf(*this); - Convert(init); - return std::move(buf).str(); - } if (MovesRuleArg(expr, ph_ctx.arg_idx, arg, ph_ctx.access)) { auto *ref = clang::dyn_cast(arg->IgnoreParenImpCasts()); auto *var = ref ? clang::dyn_cast(ref->getDecl()) : nullptr; - auto *record = arg->getType()->getAsCXXRecordDecl(); - if (record && IsUserDefinedDecl(record)) { - if (TypeIsCopyable(arg->getType())) { - return ConvertRValue(arg); - } - return ConvertFreshRValue(arg); - } - if (record && ph_ctx.access == TranslationRule::Access::kMove && - bound_init_args_.contains(var)) { + if (auto *record = arg->getType()->getAsCXXRecordDecl(); + record && (IsUserDefinedDecl(record) || + (ph_ctx.access == TranslationRule::Access::kMove && + bound_init_args_.contains(var)))) { for (auto *ctor : record->ctors()) { if (!ctor->isMoveConstructor() || ctor->isDeleted()) { continue; @@ -5476,6 +5465,12 @@ std::string Converter::ConvertPlaceholder(clang::Expr *expr, clang::Expr *arg, Convert(init); return std::move(buf).str(); } + if (IsUserDefinedDecl(record)) { + if (TypeIsCopyable(arg->getType())) { + return ConvertRValue(arg); + } + return ConvertFreshRValue(arg); + } } } diff --git a/cpp2rust/converter/converter_lib.cpp b/cpp2rust/converter/converter_lib.cpp index f33c2da55d..591e036b02 100644 --- a/cpp2rust/converter/converter_lib.cpp +++ b/cpp2rust/converter/converter_lib.cpp @@ -621,26 +621,6 @@ bool MovesRuleArg(clang::Expr *expr, unsigned arg_idx, clang::Expr *arg, return moved && !clang::isa(arg); } -clang::CXXConstructExpr *BuildMoveConstruction(clang::ASTContext &ctx, - clang::Expr *expr, - unsigned arg_idx, - clang::Expr *arg, - TranslationRule::Access access) { - if (!MovesRuleArg(expr, arg_idx, arg, access)) { - return nullptr; - } - auto *record = arg->getType()->getAsCXXRecordDecl(); - if (!record || !IsUserDefinedDecl(record)) { - return nullptr; - } - for (auto *ctor : record->ctors()) { - if (IsConvertibleMoveConstructor(ctor)) { - return MakeConstructExpr(ctx, arg->getType(), ctor, arg); - } - } - return nullptr; -} - static bool IsImplicitConvertingConstructor(const clang::CXXConstructorDecl *ctor) { return !ctor->isCopyOrMoveConstructor() && !ctor->isImplicit() && diff --git a/cpp2rust/converter/converter_lib.h b/cpp2rust/converter/converter_lib.h index 73b2d6e9ac..91c4ca620c 100644 --- a/cpp2rust/converter/converter_lib.h +++ b/cpp2rust/converter/converter_lib.h @@ -114,12 +114,6 @@ bool IsConvertibleMoveConstructor(const clang::CXXConstructorDecl *ctor); bool MovesRuleArg(clang::Expr *expr, unsigned arg_idx, clang::Expr *arg, TranslationRule::Access access); -clang::CXXConstructExpr *BuildMoveConstruction(clang::ASTContext &ctx, - clang::Expr *expr, - unsigned arg_idx, - clang::Expr *arg, - TranslationRule::Access access); - // Whether decl has a move constructor converted to a move_from method. bool HasMoveFromConstructor(const clang::RecordDecl *decl); diff --git a/cpp2rust/converter/models/boxed_vars.cpp b/cpp2rust/converter/models/boxed_vars.cpp index afb0e54dd6..26613729cf 100644 --- a/cpp2rust/converter/models/boxed_vars.cpp +++ b/cpp2rust/converter/models/boxed_vars.cpp @@ -317,21 +317,7 @@ class AddressTakenVisitor TraverseStmt(init); continue; } - bool moved_by_ctor = false; - TranslationRule::AnyFragment( - rule->body, [&](const TranslationRule::BodyFragment &fragment) { - auto *ph = - std::get_if(&fragment); - if (ph && ph->n == i) { - if (auto *init = BuildMoveConstruction(ctx_, expr, i, all_args[i], - ph->access)) { - TraverseStmt(init); - moved_by_ctor = true; - } - } - return false; - }); - if (moved_by_ctor) { + if (MovesIntoMoveConstructor(rule, expr, i, all_args[i])) { continue; } if (!rule->takesAddress(ctx_, i, arg) || @@ -341,6 +327,23 @@ class AddressTakenVisitor } } + bool MovesIntoMoveConstructor(const TranslationRule::ExprRule *rule, + clang::Expr *expr, unsigned arg_idx, + clang::Expr *arg) { + auto *record = arg->getType()->getAsCXXRecordDecl(); + if (!record || !IsUserDefinedDecl(record) || + !llvm::any_of(record->ctors(), IsConvertibleMoveConstructor)) { + return false; + } + return TranslationRule::AnyFragment( + rule->body, [&](const TranslationRule::BodyFragment &fragment) { + auto *ph = + std::get_if(&fragment); + return ph && ph->n == arg_idx && + MovesRuleArg(expr, arg_idx, arg, ph->access); + }); + } + // An element of an array or vector, or a field of a struct, is accessed // without making a pointer to it. void AddValueUse(const clang::Expr *expr, bool write = false) { From a1fe61b2bf35f1e00fea2462f4447778d4b089c2 Mon Sep 17 00:00:00 2001 From: Lucian Popescu Date: Tue, 17 Nov 2026 19:52:35 +0000 Subject: [PATCH 5/8] Use HasMoveFromConstructor --- cpp2rust/converter/models/boxed_vars.cpp | 27 ++++++++---------------- 1 file changed, 9 insertions(+), 18 deletions(-) diff --git a/cpp2rust/converter/models/boxed_vars.cpp b/cpp2rust/converter/models/boxed_vars.cpp index 26613729cf..60b5217d9a 100644 --- a/cpp2rust/converter/models/boxed_vars.cpp +++ b/cpp2rust/converter/models/boxed_vars.cpp @@ -317,7 +317,15 @@ class AddressTakenVisitor TraverseStmt(init); continue; } - if (MovesIntoMoveConstructor(rule, expr, i, all_args[i])) { + auto *record = arg->getType()->getAsRecordDecl(); + if (record && HasMoveFromConstructor(record) && + TranslationRule::AnyFragment( + rule->body, [&](const TranslationRule::BodyFragment &fragment) { + auto *ph = std::get_if( + &fragment); + return ph && ph->n == i && + MovesRuleArg(expr, i, all_args[i], ph->access); + })) { continue; } if (!rule->takesAddress(ctx_, i, arg) || @@ -327,23 +335,6 @@ class AddressTakenVisitor } } - bool MovesIntoMoveConstructor(const TranslationRule::ExprRule *rule, - clang::Expr *expr, unsigned arg_idx, - clang::Expr *arg) { - auto *record = arg->getType()->getAsCXXRecordDecl(); - if (!record || !IsUserDefinedDecl(record) || - !llvm::any_of(record->ctors(), IsConvertibleMoveConstructor)) { - return false; - } - return TranslationRule::AnyFragment( - rule->body, [&](const TranslationRule::BodyFragment &fragment) { - auto *ph = - std::get_if(&fragment); - return ph && ph->n == arg_idx && - MovesRuleArg(expr, arg_idx, arg, ph->access); - }); - } - // An element of an array or vector, or a field of a struct, is accessed // without making a pointer to it. void AddValueUse(const clang::Expr *expr, bool write = false) { From 225a1e9bda8327531ae6f16446821a4a2277d96d Mon Sep 17 00:00:00 2001 From: Lucian Popescu Date: Tue, 17 Nov 2026 20:32:01 +0000 Subject: [PATCH 6/8] Update expectation for copy_ctor --- tests/unit/copy_ctor.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/unit/copy_ctor.cpp b/tests/unit/copy_ctor.cpp index d0f59679f9..766d55a22a 100644 --- a/tests/unit/copy_ctor.cpp +++ b/tests/unit/copy_ctor.cpp @@ -1,3 +1,4 @@ +// translation-fail: refcount #include #include #include From cf530e50cd50dd898181e63822975ea09bbce61e Mon Sep 17 00:00:00 2001 From: Lucian Popescu Date: Tue, 17 Nov 2026 20:43:01 +0000 Subject: [PATCH 7/8] Keep variables moved through a pointer into rules boxed --- cpp2rust/converter/models/boxed_vars.cpp | 8 +++++--- tests/unit/copy_ctor.cpp | 1 - 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/cpp2rust/converter/models/boxed_vars.cpp b/cpp2rust/converter/models/boxed_vars.cpp index 7d569a71f4..494ddacc37 100644 --- a/cpp2rust/converter/models/boxed_vars.cpp +++ b/cpp2rust/converter/models/boxed_vars.cpp @@ -320,13 +320,15 @@ class AddressTakenVisitor continue; } auto *record = arg->getType()->getAsRecordDecl(); - if (record && HasMoveFromConstructor(record) && - TranslationRule::AnyFragment( + if (TranslationRule::AnyFragment( rule->body, [&](const TranslationRule::BodyFragment &fragment) { auto *ph = std::get_if( &fragment); return ph && ph->n == i && - MovesRuleArg(expr, i, all_args[i], ph->access); + ((ph->access == TranslationRule::Access::kMove && + MovesFromArg(expr, i, all_args[i])) || + (record && HasMoveFromConstructor(record) && + MovesRuleArg(expr, i, all_args[i], ph->access))); })) { continue; } diff --git a/tests/unit/copy_ctor.cpp b/tests/unit/copy_ctor.cpp index 766d55a22a..d0f59679f9 100644 --- a/tests/unit/copy_ctor.cpp +++ b/tests/unit/copy_ctor.cpp @@ -1,4 +1,3 @@ -// translation-fail: refcount #include #include #include From 8456a6121b2752e34694db9b4a479f60bfd802a2 Mon Sep 17 00:00:00 2001 From: Lucian Popescu Date: Tue, 17 Nov 2026 20:48:25 +0000 Subject: [PATCH 8/8] Update tests --- tests/std/utilities/pairs/out/refcount/pairs.pair.rs | 6 +++--- tests/unit/out/refcount/copy_ctor.rs | 5 ++--- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/tests/std/utilities/pairs/out/refcount/pairs.pair.rs b/tests/std/utilities/pairs/out/refcount/pairs.pair.rs index ac23017e3b..7282793e7e 100644 --- a/tests/std/utilities/pairs/out/refcount/pairs.pair.rs +++ b/tests/std/utilities/pairs/out/refcount/pairs.pair.rs @@ -54,12 +54,12 @@ pub fn test_1() { }) }) ); - let values: Value> = Rc::new(RefCell::new(vec![7; 2_usize])); + let mut values: Vec = vec![7; 2_usize]; let copied: Value<(Value>, Value)> = Rc::new(RefCell::new(( - Rc::new(RefCell::new(({ (*values.borrow()).clone() }))), + Rc::new(RefCell::new((values).clone())), Rc::new(RefCell::new(3)), ))); - assert!(({ ((*values.borrow()).len() == 2_usize) })); + assert!((values.len() == 2_usize)); assert!( ({ ((*(*copied.borrow()).0.borrow()).len() == 2_usize) diff --git a/tests/unit/out/refcount/copy_ctor.rs b/tests/unit/out/refcount/copy_ctor.rs index cc49568175..be13b9132a 100644 --- a/tests/unit/out/refcount/copy_ctor.rs +++ b/tests/unit/out/refcount/copy_ctor.rs @@ -121,9 +121,8 @@ pub struct Box_int_ { pub val: i32, } impl Box_int_ { - pub fn new(v: i32) -> Self { - let v: Value = Rc::new(RefCell::new(v)); - Self { val: (*v.borrow()) } + pub fn new(mut v: i32) -> Self { + Self { val: v } } pub fn copy_from(o: Ptr) -> Self { Self {