From a855ccc80e5474206cc470fd5c958c8eb69f85e4 Mon Sep 17 00:00:00 2001 From: Perfloop Agent Date: Sat, 14 Nov 2026 22:58:17 +0000 Subject: [PATCH 1/2] Test moved-from strings and string returns MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Tomás Senart --- tests/unit/string_moved_from.cpp | 58 ++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 tests/unit/string_moved_from.cpp diff --git a/tests/unit/string_moved_from.cpp b/tests/unit/string_moved_from.cpp new file mode 100644 index 0000000000..37419a5309 --- /dev/null +++ b/tests/unit/string_moved_from.cpp @@ -0,0 +1,58 @@ +#include +#include +#include + +static void print_moved_from(const char *label, const std::string &from, + const std::string &to) { + std::string sub = from.substr(0, 0); + printf("%s: %zu %zu %d %zu %d [%s]\n", label, from.size(), sub.size(), + from.c_str()[0], to.size(), sub.c_str()[0], to.c_str()); +} + +static std::string return_local() { + std::string word = "returned local"; + return (word); +} + +static std::string return_parameter(std::string word) { return word; } + +static std::string return_reference(std::string &word) { + return std::move(word); +} + +static std::string return_rvalue_reference(std::string &&word) { return word; } + +int main() { + std::string empty; + std::string from_empty(std::move(empty)); + print_moved_from("construct empty", empty, from_empty); + + std::string word = "hello"; + std::string from_word(std::move(word)); + print_moved_from("construct word", word, from_word); + + std::string long_word = "a string that does not fit in place"; + std::string assigned = "x"; + assigned = std::move(long_word); + print_moved_from("assign long", long_word, assigned); + + std::string short_word = "ab"; + std::string assigned_short; + assigned_short = std::move(short_word); + print_moved_from("assign short", short_word, assigned_short); + + word.append("again", 5); + printf("reuse: %zu %s\n", word.size(), word.c_str()); + std::string local = return_local(); + std::string parameter = return_parameter("returned parameter"); + printf("returns: %s %s\n", local.c_str(), parameter.c_str()); + + std::string source = "returned reference"; + std::string reference = return_reference(source); + print_moved_from("return reference", source, reference); + + source.append("rvalue reference", 16); + std::string rvalue_reference = return_rvalue_reference(std::move(source)); + print_moved_from("return rvalue reference", source, rvalue_reference); + return 0; +} From 3b0154853deea2676bd8ec3ea3de7d0ac4e5282c Mon Sep 17 00:00:00 2001 From: Perfloop Agent Date: Sat, 14 Nov 2026 22:58:17 +0000 Subject: [PATCH 2/2] Keep directly moved strings null-terminated MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Tomás Senart --- cpp2rust/converter/converter.cpp | 30 ++++ cpp2rust/converter/converter.h | 6 + .../converter/models/converter_refcount.cpp | 9 + tests/unit/out/refcount/string_moved_from.rs | 169 ++++++++++++++++++ .../refcount/vector_deque_vector_string.rs | 2 +- tests/unit/out/unsafe/string_moved_from.rs | 158 ++++++++++++++++ .../out/unsafe/vector_deque_vector_string.rs | 2 +- 7 files changed, 374 insertions(+), 2 deletions(-) create mode 100644 tests/unit/out/refcount/string_moved_from.rs create mode 100644 tests/unit/out/unsafe/string_moved_from.rs diff --git a/cpp2rust/converter/converter.cpp b/cpp2rust/converter/converter.cpp index 0ed5bda34c..ed3c5db8fb 100644 --- a/cpp2rust/converter/converter.cpp +++ b/cpp2rust/converter/converter.cpp @@ -1419,6 +1419,7 @@ bool Converter::VisitDeclStmt(clang::DeclStmt *stmt) { } bool Converter::VisitReturnStmt(clang::ReturnStmt *stmt) { + ScopedValue return_value(return_value_, stmt->getRetValue()); auto return_type = curr_function_->getReturnType(); if (!return_type->isVoidType()) { HoistMaterializedTempBindings hoist_temps(*this); @@ -5119,11 +5120,40 @@ std::string Converter::ConvertBorrowMut(clang::Expr *arg) { } std::string Converter::ConvertTake(clang::Expr *arg) { + auto moved_from = GetMovedFromValue(arg); auto lvalue = ConvertLValue(arg); MarkFresh(); + if (!moved_from.empty()) { + return std::format("std::mem::replace(&mut {}, {})", std::move(lvalue), + std::move(moved_from)); + } return std::format("std::mem::take(&mut {})", std::move(lvalue)); } +std::string Converter::GetMovedFromValue(clang::Expr *arg) { + auto type = arg->getType(); + if (!IsStdDecl(type->getAsCXXRecordDecl(), "basic_string")) { + return {}; + } + // An implicit return move consumes a local or by-value parameter. There is + // no need to allocate a terminator for the object about to be destroyed. + auto *returned = return_value_ ? return_value_->IgnoreImplicit() : nullptr; + if (auto *ctor = clang::dyn_cast_or_null(returned); + ctor && ctor->getConstructor()->isMoveConstructor() && + ctor->getArg(0)->IgnoreParenImpCasts() == arg->IgnoreParenImpCasts()) { + if (auto *ref = + clang::dyn_cast(arg->IgnoreParenImpCasts())) { + if (auto *var = clang::dyn_cast(ref->getDecl()); + var && var->hasLocalStorage() && !var->getType()->isReferenceType()) { + return {}; + } + } + } + // A string is translated as a vector that ends with a null terminator, so an + // empty vector is not a valid empty string. + return Mapper::MapInitializer(*this, type); +} + std::string Converter::ConvertMappedMethodCall( clang::Expr *expr, const TranslationRule::MethodCallFragment &mc, llvm::ArrayRef bindings, diff --git a/cpp2rust/converter/converter.h b/cpp2rust/converter/converter.h index ebc92cd42b..ec49e3712e 100644 --- a/cpp2rust/converter/converter.h +++ b/cpp2rust/converter/converter.h @@ -878,6 +878,11 @@ class Converter : public clang::RecursiveASTVisitor { // Moves the value out of `arg`, leaving a default value behind. virtual std::string ConvertTake(clang::Expr *arg); + // The value to leave behind when moving from `arg`. Empty if std::mem::take + // suffices, including implicit return moves of locals and by-value + // parameters. + std::string GetMovedFromValue(clang::Expr *arg); + // The place of `arg`, which is borrowed mutably by a rule. virtual std::string ConvertBorrowMut(clang::Expr *arg); @@ -945,6 +950,7 @@ class Converter : public clang::RecursiveASTVisitor { clang::ASTContext &ctx_; std::unique_ptr mangle_context_; clang::FunctionDecl *curr_function_ = nullptr; + clang::Expr *return_value_ = nullptr; bool InConstructor() const { return clang::isa_and_present(curr_function_); } diff --git a/cpp2rust/converter/models/converter_refcount.cpp b/cpp2rust/converter/models/converter_refcount.cpp index 46604c74f7..b44508cf06 100644 --- a/cpp2rust/converter/models/converter_refcount.cpp +++ b/cpp2rust/converter/models/converter_refcount.cpp @@ -2987,12 +2987,21 @@ std::string ConverterRefCount::ConvertBorrowMut(clang::Expr *arg) { } std::string ConverterRefCount::ConvertTake(clang::Expr *arg) { + auto moved_from = GetMovedFromValue(arg); auto lvalue = ConvertLValue(arg); MarkFresh(); // An object reached through a pointer is taken through it. if (!pending_deref_.empty()) { + if (!moved_from.empty()) { + return std::format("{}.with_mut(|__v| std::mem::replace(__v, {}))", + pending_deref_.take(), std::move(moved_from)); + } return std::format("{}.with_mut(std::mem::take)", pending_deref_.take()); } + if (!moved_from.empty()) { + return std::format("std::mem::replace(&mut {}, {})", std::move(lvalue), + std::move(moved_from)); + } return std::format("std::mem::take(&mut {})", std::move(lvalue)); } diff --git a/tests/unit/out/refcount/string_moved_from.rs b/tests/unit/out/refcount/string_moved_from.rs new file mode 100644 index 0000000000..acb0594a9c --- /dev/null +++ b/tests/unit/out/refcount/string_moved_from.rs @@ -0,0 +1,169 @@ +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 print_moved_from_0(mut label: Ptr, from: Ptr>, to: Ptr>) { + let sub: Value> = Rc::new(RefCell::new(from.with(|__s: &Vec| { + let mut __tmp1 = + __s[0_usize..::std::cmp::min(0_usize + 0_usize, __s.len().saturating_sub(1))].to_vec(); + __tmp1.push(0); + __tmp1 + }))); + println!( + "{}: {} {} {} {} {} [{}]", + label, + ((*from.upgrade().deref()).len() - 1), + ((*sub.borrow()).len() - 1), + ((elem!(from.decay(), 0).read()) as i32), + ((*to.upgrade().deref()).len() - 1), + ((elem!(sub.decay(), 0).read()) as i32), + to.decay() + ); +} +pub fn return_local_1() -> Vec { + let mut word: Vec = { + let mut __bytes = Ptr::::from_string_literal(b"returned local").to_c_bytes(); + __bytes.push(0); + __bytes + }; + return std::mem::take(&mut (word)); +} +pub fn return_parameter_2(mut word: Vec) -> Vec { + return std::mem::take(&mut word); +} +pub fn return_reference_3(word: Ptr>) -> Vec { + return word.with_mut(|__v| std::mem::replace(__v, vec![0])); +} +pub fn return_rvalue_reference_4(word: Ptr>) -> Vec { + return word.with_mut(|__v| std::mem::replace(__v, vec![0])); +} +pub fn main() { + __cpp2rust_init_globals(); + std::process::exit(main_0()); +} +fn main_0() -> i32 { + let empty: Value> = Rc::new(RefCell::new(vec![0])); + let from_empty: Value> = Rc::new(RefCell::new( + ({ std::mem::replace(&mut (*empty.borrow_mut()), vec![0]) }), + )); + ({ + print_moved_from_0( + Ptr::::from_string_literal(b"construct empty"), + empty.as_pointer(), + from_empty.as_pointer(), + ) + }); + let word: Value> = Rc::new(RefCell::new({ + let mut __bytes = Ptr::::from_string_literal(b"hello").to_c_bytes(); + __bytes.push(0); + __bytes + })); + let from_word: Value> = Rc::new(RefCell::new( + ({ std::mem::replace(&mut (*word.borrow_mut()), vec![0]) }), + )); + ({ + print_moved_from_0( + Ptr::::from_string_literal(b"construct word"), + word.as_pointer(), + from_word.as_pointer(), + ) + }); + let long_word: Value> = Rc::new(RefCell::new({ + let mut __bytes = + Ptr::::from_string_literal(b"a string that does not fit in place").to_c_bytes(); + __bytes.push(0); + __bytes + })); + let assigned: Value> = Rc::new(RefCell::new({ + let mut __bytes = Ptr::::from_string_literal(b"x").to_c_bytes(); + __bytes.push(0); + __bytes + })); + assigned + .as_pointer() + .write(({ std::mem::replace(&mut (*long_word.borrow_mut()), vec![0]) })); + ({ + print_moved_from_0( + Ptr::::from_string_literal(b"assign long"), + long_word.as_pointer(), + assigned.as_pointer(), + ) + }); + let short_word: Value> = Rc::new(RefCell::new({ + let mut __bytes = Ptr::::from_string_literal(b"ab").to_c_bytes(); + __bytes.push(0); + __bytes + })); + let assigned_short: Value> = Rc::new(RefCell::new(vec![0])); + assigned_short + .as_pointer() + .write(({ std::mem::replace(&mut (*short_word.borrow_mut()), vec![0]) })); + ({ + print_moved_from_0( + Ptr::::from_string_literal(b"assign short"), + short_word.as_pointer(), + assigned_short.as_pointer(), + ) + }); + { + word.as_pointer().with_mut(|__v: &mut Vec| { + __v.pop(); + Ptr::::from_string_literal(b"again") + .with_slice(5_usize, |__s| __v.extend_from_slice(__s)); + __v.push(0); + }); + word.as_pointer() + }; + println!("reuse: {} {}", ((*word.borrow()).len() - 1), word.decay()); + let local: Value> = Rc::new(RefCell::new(({ return_local_1() }))); + let parameter: Value> = Rc::new(RefCell::new( + ({ + return_parameter_2({ + let mut __bytes = + Ptr::::from_string_literal(b"returned parameter").to_c_bytes(); + __bytes.push(0); + __bytes + }) + }), + )); + println!("returns: {} {}", local.decay(), parameter.decay()); + let source: Value> = Rc::new(RefCell::new({ + let mut __bytes = Ptr::::from_string_literal(b"returned reference").to_c_bytes(); + __bytes.push(0); + __bytes + })); + let reference: Value> = + Rc::new(RefCell::new(({ return_reference_3(source.as_pointer()) }))); + ({ + print_moved_from_0( + Ptr::::from_string_literal(b"return reference"), + source.as_pointer(), + reference.as_pointer(), + ) + }); + { + source.as_pointer().with_mut(|__v: &mut Vec| { + __v.pop(); + Ptr::::from_string_literal(b"rvalue reference") + .with_slice(16_usize, |__s| __v.extend_from_slice(__s)); + __v.push(0); + }); + source.as_pointer() + }; + let rvalue_reference: Value> = Rc::new(RefCell::new( + ({ return_rvalue_reference_4(source.as_pointer()) }), + )); + ({ + print_moved_from_0( + Ptr::::from_string_literal(b"return rvalue reference"), + source.as_pointer(), + rvalue_reference.as_pointer(), + ) + }); + return 0; +} +pub fn __cpp2rust_init_globals() {} diff --git a/tests/unit/out/refcount/vector_deque_vector_string.rs b/tests/unit/out/refcount/vector_deque_vector_string.rs index 86b3515cc6..a5ececa9a7 100644 --- a/tests/unit/out/refcount/vector_deque_vector_string.rs +++ b/tests/unit/out/refcount/vector_deque_vector_string.rs @@ -119,7 +119,7 @@ fn main_0() -> i32 { .decay() .decay() .offset(0_usize) - .write(__tmp_3.with_mut(std::mem::take)), + .write(__tmp_3.with_mut(|__v| std::mem::replace(__v, vec![0]))), }; match (v.decay().offset(0_usize).decay().decay().offset(1_usize),) { (__tmp_4,) => { diff --git a/tests/unit/out/unsafe/string_moved_from.rs b/tests/unit/out/unsafe/string_moved_from.rs new file mode 100644 index 0000000000..053dc1d9e9 --- /dev/null +++ b/tests/unit/out/unsafe/string_moved_from.rs @@ -0,0 +1,158 @@ +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 print_moved_from_0( + mut label: *const libc::c_char, + from: *const Vec, + to: *const Vec, +) { + let mut sub: Vec = { + let __range = 0_usize + ..::std::cmp::min( + 0_usize + 0_usize, + (*(from as *const Vec)).len() - 1, + ); + let mut __tmp1 = (&*(from as *const Vec))[__range].to_vec(); + __tmp1.push(0); + __tmp1 + }; + (unsafe { + libc::printf( + c"%s: %zu %zu %d %zu %d [%s]\n".as_ptr() as *const libc::c_char, + (label), + ((*from).len() - 1), + (sub.len() - 1), + ((*(*from).as_ptr().offset((0) as isize)) as i32), + ((*to).len() - 1), + ((*sub.as_ptr().offset((0) as isize)) as i32), + ((*to).as_ptr()), + ) + }); +} +pub unsafe fn return_local_1() -> Vec { + let mut word: Vec = std::slice::from_raw_parts( + c"returned local".as_ptr(), + (0..) + .take_while(|&i| *c"returned local".as_ptr().add(i) != 0) + .count() + + 1, + ) + .to_vec(); + return std::mem::take(&mut (word)); +} +pub unsafe fn return_parameter_2(mut word: Vec) -> Vec { + return std::mem::take(&mut word); +} +pub unsafe fn return_reference_3(word: *mut Vec) -> Vec { + return std::mem::replace(&mut (*word), vec![0]); +} +pub unsafe fn return_rvalue_reference_4(word: *mut Vec) -> Vec { + return std::mem::replace(&mut (*word), vec![0]); +} +pub fn main() { + unsafe { + __cpp2rust_init_globals(); + std::process::exit(main_0() as i32); + } +} +unsafe fn main_0() -> i32 { + let mut empty: Vec = vec![0]; + let mut from_empty: Vec = std::mem::replace(&mut empty, vec![0]); + (unsafe { print_moved_from_0(c"construct empty".as_ptr(), &empty, &from_empty) }); + let mut word: Vec = std::slice::from_raw_parts( + c"hello".as_ptr(), + (0..) + .take_while(|&i| *c"hello".as_ptr().add(i) != 0) + .count() + + 1, + ) + .to_vec(); + let mut from_word: Vec = std::mem::replace(&mut word, vec![0]); + (unsafe { print_moved_from_0(c"construct word".as_ptr(), &word, &from_word) }); + let mut long_word: Vec = std::slice::from_raw_parts( + c"a string that does not fit in place".as_ptr(), + (0..) + .take_while(|&i| *c"a string that does not fit in place".as_ptr().add(i) != 0) + .count() + + 1, + ) + .to_vec(); + let mut assigned: Vec = std::slice::from_raw_parts( + c"x".as_ptr(), + (0..).take_while(|&i| *c"x".as_ptr().add(i) != 0).count() + 1, + ) + .to_vec(); + assigned = std::mem::replace(&mut long_word, vec![0]); + (unsafe { print_moved_from_0(c"assign long".as_ptr(), &long_word, &assigned) }); + let mut short_word: Vec = std::slice::from_raw_parts( + c"ab".as_ptr(), + (0..).take_while(|&i| *c"ab".as_ptr().add(i) != 0).count() + 1, + ) + .to_vec(); + let mut assigned_short: Vec = vec![0]; + assigned_short = std::mem::replace(&mut short_word, vec![0]); + (unsafe { print_moved_from_0(c"assign short".as_ptr(), &short_word, &assigned_short) }); + word.splice(word.len().saturating_sub(1)..word.len(), { + let mut v = ::std::slice::from_raw_parts(c"again".as_ptr(), 5_usize).to_vec(); + v.push(0); + v + }); + (unsafe { + libc::printf( + c"reuse: %zu %s\n".as_ptr() as *const libc::c_char, + (word.len() - 1), + (word.as_ptr()), + ) + }); + let mut local: Vec = (unsafe { return_local_1() }); + let mut parameter: Vec = (unsafe { + return_parameter_2( + std::slice::from_raw_parts( + c"returned parameter".as_ptr(), + (0..) + .take_while(|&i| *c"returned parameter".as_ptr().add(i) != 0) + .count() + + 1, + ) + .to_vec(), + ) + }); + (unsafe { + libc::printf( + c"returns: %s %s\n".as_ptr() as *const libc::c_char, + (local.as_ptr()), + (parameter.as_ptr()), + ) + }); + let mut source: Vec = std::slice::from_raw_parts( + c"returned reference".as_ptr(), + (0..) + .take_while(|&i| *c"returned reference".as_ptr().add(i) != 0) + .count() + + 1, + ) + .to_vec(); + let mut reference: Vec = (unsafe { return_reference_3(&mut source) }); + (unsafe { print_moved_from_0(c"return reference".as_ptr(), &source, &reference) }); + source.splice(source.len().saturating_sub(1)..source.len(), { + let mut v = ::std::slice::from_raw_parts(c"rvalue reference".as_ptr(), 16_usize).to_vec(); + v.push(0); + v + }); + let mut rvalue_reference: Vec = + (unsafe { return_rvalue_reference_4(&mut source) }); + (unsafe { + print_moved_from_0( + c"return rvalue reference".as_ptr(), + &source, + &rvalue_reference, + ) + }); + return 0; +} +pub unsafe fn __cpp2rust_init_globals() {} diff --git a/tests/unit/out/unsafe/vector_deque_vector_string.rs b/tests/unit/out/unsafe/vector_deque_vector_string.rs index 06209af98c..49f7edc824 100644 --- a/tests/unit/out/unsafe/vector_deque_vector_string.rs +++ b/tests/unit/out/unsafe/vector_deque_vector_string.rs @@ -97,7 +97,7 @@ unsafe fn main_0() -> i32 { { (__tmp_1,) => { (&mut (*((copy[(0_usize)]).first_mut().unwrap())))[(0_usize)] = - std::mem::take(&mut (*__tmp_1)) + std::mem::replace(&mut (*__tmp_1), vec![0]) } }; (*match (