Skip to content

Commit 174df42

Browse files
Keep directly moved strings null-terminated
Use the string initializer when taking a string whose source can be used again. Keep take for implicit returns of locals and by-value parameters. Signed-off-by: Perfloop Agent <agent@perfloop.ai> Signed-off-by: Tomás Senart <ts@perfloop.ai>
1 parent 22d33d4 commit 174df42

7 files changed

Lines changed: 375 additions & 2 deletions

File tree

‎cpp2rust/converter/converter.cpp‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1424,6 +1424,7 @@ bool Converter::VisitDeclStmt(clang::DeclStmt *stmt) {
14241424
}
14251425

14261426
bool Converter::VisitReturnStmt(clang::ReturnStmt *stmt) {
1427+
ScopedValue return_value(return_value_, stmt->getRetValue());
14271428
auto return_type = curr_function_->getReturnType();
14281429
if (!return_type->isVoidType()) {
14291430
HoistMaterializedTempBindings hoist_temps(*this);
@@ -5109,11 +5110,40 @@ std::string Converter::ConvertBorrowMut(clang::Expr *arg) {
51095110
}
51105111

51115112
std::string Converter::ConvertTake(clang::Expr *arg) {
5113+
auto moved_from = GetMovedFromValue(arg);
51125114
auto lvalue = ConvertLValue(arg);
51135115
MarkFresh();
5116+
if (!moved_from.empty()) {
5117+
return std::format("std::mem::replace(&mut {}, {})", std::move(lvalue),
5118+
std::move(moved_from));
5119+
}
51145120
return std::format("std::mem::take(&mut {})", std::move(lvalue));
51155121
}
51165122

5123+
std::string Converter::GetMovedFromValue(clang::Expr *arg) {
5124+
auto type = arg->getType();
5125+
if (!IsStdDecl(type->getAsCXXRecordDecl(), "basic_string")) {
5126+
return {};
5127+
}
5128+
// An implicit return move consumes a local or by-value parameter. There is
5129+
// no need to allocate a terminator for the object about to be destroyed.
5130+
auto *returned = return_value_ ? return_value_->IgnoreImplicit() : nullptr;
5131+
if (auto *ctor = clang::dyn_cast_or_null<clang::CXXConstructExpr>(returned);
5132+
ctor && ctor->getConstructor()->isMoveConstructor() &&
5133+
ctor->getArg(0)->IgnoreParenImpCasts() == arg->IgnoreParenImpCasts()) {
5134+
if (auto *ref =
5135+
clang::dyn_cast<clang::DeclRefExpr>(arg->IgnoreParenImpCasts())) {
5136+
if (auto *var = clang::dyn_cast<clang::VarDecl>(ref->getDecl());
5137+
var && var->hasLocalStorage() && !var->getType()->isReferenceType()) {
5138+
return {};
5139+
}
5140+
}
5141+
}
5142+
// A string is translated as a vector that ends with a null terminator, so an
5143+
// empty vector is not a valid empty string.
5144+
return Mapper::MapInitializer(*this, type);
5145+
}
5146+
51175147
std::string Converter::ConvertMappedMethodCall(
51185148
clang::Expr *expr, const TranslationRule::MethodCallFragment &mc,
51195149
llvm::ArrayRef<clang::TemplateArgument> bindings,

‎cpp2rust/converter/converter.h‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -878,6 +878,11 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
878878
// Moves the value out of `arg`, leaving a default value behind.
879879
virtual std::string ConvertTake(clang::Expr *arg);
880880

881+
// The value to leave behind when moving from `arg`. Empty if std::mem::take
882+
// suffices, including implicit return moves of locals and by-value
883+
// parameters.
884+
std::string GetMovedFromValue(clang::Expr *arg);
885+
881886
// The place of `arg`, which is borrowed mutably by a rule.
882887
virtual std::string ConvertBorrowMut(clang::Expr *arg);
883888

@@ -945,6 +950,7 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
945950
clang::ASTContext &ctx_;
946951
std::unique_ptr<clang::MangleContext> mangle_context_;
947952
clang::FunctionDecl *curr_function_ = nullptr;
953+
clang::Expr *return_value_ = nullptr;
948954
bool InConstructor() const {
949955
return clang::isa_and_present<clang::CXXConstructorDecl>(curr_function_);
950956
}

‎cpp2rust/converter/models/converter_refcount.cpp‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3009,12 +3009,21 @@ std::string ConverterRefCount::ConvertBorrowMut(clang::Expr *arg) {
30093009
}
30103010

30113011
std::string ConverterRefCount::ConvertTake(clang::Expr *arg) {
3012+
auto moved_from = GetMovedFromValue(arg);
30123013
auto lvalue = ConvertLValue(arg);
30133014
MarkFresh();
30143015
// An object reached through a pointer is taken through it.
30153016
if (!pending_deref_.empty()) {
3017+
if (!moved_from.empty()) {
3018+
return std::format("{}.with_mut(|__v| std::mem::replace(__v, {}))",
3019+
pending_deref_.take(), std::move(moved_from));
3020+
}
30163021
return std::format("{}.with_mut(std::mem::take)", pending_deref_.take());
30173022
}
3023+
if (!moved_from.empty()) {
3024+
return std::format("std::mem::replace(&mut {}, {})", std::move(lvalue),
3025+
std::move(moved_from));
3026+
}
30183027
return std::format("std::mem::take(&mut {})", std::move(lvalue));
30193028
}
30203029

Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
extern crate libcc2rs;
2+
use libcc2rs::*;
3+
use std::cell::RefCell;
4+
use std::collections::BTreeMap;
5+
use std::io::prelude::*;
6+
use std::io::{Read, Seek, Write};
7+
use std::os::fd::AsFd;
8+
use std::rc::{Rc, Weak};
9+
pub fn print_moved_from_0(mut label: Ptr<i8>, from: Ptr<Vec<i8>>, to: Ptr<Vec<i8>>) {
10+
let sub: Value<Vec<i8>> = Rc::new(RefCell::new(from.with(|__s: &Vec<i8>| {
11+
let mut __tmp1 =
12+
__s[0_usize..::std::cmp::min(0_usize + 0_usize, __s.len().saturating_sub(1))].to_vec();
13+
__tmp1.push(0);
14+
__tmp1
15+
})));
16+
println!(
17+
"{}: {} {} {} {} {} [{}]",
18+
label,
19+
((*from.upgrade().deref()).len() - 1),
20+
((*sub.borrow()).len() - 1),
21+
((elem!(from.decay(), 0).read()) as i32),
22+
((*to.upgrade().deref()).len() - 1),
23+
((elem!(sub.decay(), 0).read()) as i32),
24+
to.decay()
25+
);
26+
}
27+
pub fn return_local_1() -> Vec<i8> {
28+
let mut word: Vec<i8> = {
29+
let mut __bytes = Ptr::<i8>::from_string_literal(b"returned local").to_c_bytes();
30+
__bytes.push(0);
31+
__bytes
32+
};
33+
return std::mem::take(&mut (word));
34+
}
35+
pub fn return_parameter_2(mut word: Vec<i8>) -> Vec<i8> {
36+
return std::mem::take(&mut word);
37+
}
38+
pub fn return_reference_3(word: Ptr<Vec<i8>>) -> Vec<i8> {
39+
return word.with_mut(|__v| std::mem::replace(__v, vec![0]));
40+
}
41+
pub fn return_rvalue_reference_4(word: Ptr<Vec<i8>>) -> Vec<i8> {
42+
return word.with_mut(|__v| std::mem::replace(__v, vec![0]));
43+
}
44+
pub fn main() {
45+
__cpp2rust_init_globals();
46+
std::process::exit(main_0());
47+
}
48+
fn main_0() -> i32 {
49+
let empty: Value<Vec<i8>> = Rc::new(RefCell::new(vec![0]));
50+
let from_empty: Value<Vec<i8>> = Rc::new(RefCell::new(
51+
({ std::mem::replace(&mut (*empty.borrow_mut()), vec![0]) }),
52+
));
53+
({
54+
print_moved_from_0(
55+
Ptr::<i8>::from_string_literal(b"construct empty"),
56+
empty.as_pointer(),
57+
from_empty.as_pointer(),
58+
)
59+
});
60+
let word: Value<Vec<i8>> = Rc::new(RefCell::new({
61+
let mut __bytes = Ptr::<i8>::from_string_literal(b"hello").to_c_bytes();
62+
__bytes.push(0);
63+
__bytes
64+
}));
65+
let from_word: Value<Vec<i8>> = Rc::new(RefCell::new(
66+
({ std::mem::replace(&mut (*word.borrow_mut()), vec![0]) }),
67+
));
68+
({
69+
print_moved_from_0(
70+
Ptr::<i8>::from_string_literal(b"construct word"),
71+
word.as_pointer(),
72+
from_word.as_pointer(),
73+
)
74+
});
75+
let long_word: Value<Vec<i8>> = Rc::new(RefCell::new({
76+
let mut __bytes =
77+
Ptr::<i8>::from_string_literal(b"a string that does not fit in place").to_c_bytes();
78+
__bytes.push(0);
79+
__bytes
80+
}));
81+
let assigned: Value<Vec<i8>> = Rc::new(RefCell::new({
82+
let mut __bytes = Ptr::<i8>::from_string_literal(b"x").to_c_bytes();
83+
__bytes.push(0);
84+
__bytes
85+
}));
86+
assigned
87+
.as_pointer()
88+
.write(({ std::mem::replace(&mut (*long_word.borrow_mut()), vec![0]) }));
89+
({
90+
print_moved_from_0(
91+
Ptr::<i8>::from_string_literal(b"assign long"),
92+
long_word.as_pointer(),
93+
assigned.as_pointer(),
94+
)
95+
});
96+
let short_word: Value<Vec<i8>> = Rc::new(RefCell::new({
97+
let mut __bytes = Ptr::<i8>::from_string_literal(b"ab").to_c_bytes();
98+
__bytes.push(0);
99+
__bytes
100+
}));
101+
let assigned_short: Value<Vec<i8>> = Rc::new(RefCell::new(vec![0]));
102+
assigned_short
103+
.as_pointer()
104+
.write(({ std::mem::replace(&mut (*short_word.borrow_mut()), vec![0]) }));
105+
({
106+
print_moved_from_0(
107+
Ptr::<i8>::from_string_literal(b"assign short"),
108+
short_word.as_pointer(),
109+
assigned_short.as_pointer(),
110+
)
111+
});
112+
{
113+
word.as_pointer().with_mut(|__v: &mut Vec<i8>| {
114+
__v.pop();
115+
Ptr::<i8>::from_string_literal(b"again")
116+
.with_slice(5_usize as usize, |__s| __v.extend_from_slice(__s));
117+
__v.push(0);
118+
});
119+
word.as_pointer()
120+
};
121+
println!("reuse: {} {}", ((*word.borrow()).len() - 1), word.decay());
122+
let local: Value<Vec<i8>> = Rc::new(RefCell::new(({ return_local_1() })));
123+
let parameter: Value<Vec<i8>> = Rc::new(RefCell::new(
124+
({
125+
return_parameter_2({
126+
let mut __bytes =
127+
Ptr::<i8>::from_string_literal(b"returned parameter").to_c_bytes();
128+
__bytes.push(0);
129+
__bytes
130+
})
131+
}),
132+
));
133+
println!("returns: {} {}", local.decay(), parameter.decay());
134+
let source: Value<Vec<i8>> = Rc::new(RefCell::new({
135+
let mut __bytes = Ptr::<i8>::from_string_literal(b"returned reference").to_c_bytes();
136+
__bytes.push(0);
137+
__bytes
138+
}));
139+
let reference: Value<Vec<i8>> =
140+
Rc::new(RefCell::new(({ return_reference_3(source.as_pointer()) })));
141+
({
142+
print_moved_from_0(
143+
Ptr::<i8>::from_string_literal(b"return reference"),
144+
source.as_pointer(),
145+
reference.as_pointer(),
146+
)
147+
});
148+
{
149+
source.as_pointer().with_mut(|__v: &mut Vec<i8>| {
150+
__v.pop();
151+
Ptr::<i8>::from_string_literal(b"rvalue reference")
152+
.with_slice(16_usize as usize, |__s| __v.extend_from_slice(__s));
153+
__v.push(0);
154+
});
155+
source.as_pointer()
156+
};
157+
let rvalue_reference: Value<Vec<i8>> = Rc::new(RefCell::new(
158+
({ return_rvalue_reference_4(source.as_pointer()) }),
159+
));
160+
({
161+
print_moved_from_0(
162+
Ptr::<i8>::from_string_literal(b"return rvalue reference"),
163+
source.as_pointer(),
164+
rvalue_reference.as_pointer(),
165+
)
166+
});
167+
return 0;
168+
}
169+
pub fn __cpp2rust_init_globals() {}

‎tests/unit/out/refcount/vector_deque_vector_string.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ fn main_0() -> i32 {
119119
.decay()
120120
.decay()
121121
.offset(0_usize)
122-
.write(__tmp_3.with_mut(std::mem::take)),
122+
.write(__tmp_3.with_mut(|__v| std::mem::replace(__v, vec![0]))),
123123
};
124124
match (v.decay().offset(0_usize).decay().decay().offset(1_usize),) {
125125
(__tmp_4,) => {

0 commit comments

Comments
 (0)