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
30 changes: 30 additions & 0 deletions cpp2rust/converter/converter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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<clang::CXXConstructExpr>(returned);
ctor && ctor->getConstructor()->isMoveConstructor() &&
ctor->getArg(0)->IgnoreParenImpCasts() == arg->IgnoreParenImpCasts()) {
if (auto *ref =
clang::dyn_cast<clang::DeclRefExpr>(arg->IgnoreParenImpCasts())) {
if (auto *var = clang::dyn_cast<clang::VarDecl>(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<clang::TemplateArgument> bindings,
Expand Down
6 changes: 6 additions & 0 deletions cpp2rust/converter/converter.h
Original file line number Diff line number Diff line change
Expand Up @@ -878,6 +878,11 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
// 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);

Expand Down Expand Up @@ -945,6 +950,7 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
clang::ASTContext &ctx_;
std::unique_ptr<clang::MangleContext> mangle_context_;
clang::FunctionDecl *curr_function_ = nullptr;
clang::Expr *return_value_ = nullptr;
bool InConstructor() const {
return clang::isa_and_present<clang::CXXConstructorDecl>(curr_function_);
}
Expand Down
9 changes: 9 additions & 0 deletions cpp2rust/converter/models/converter_refcount.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}

Expand Down
169 changes: 169 additions & 0 deletions tests/unit/out/refcount/string_moved_from.rs
Original file line number Diff line number Diff line change
@@ -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<i8>, from: Ptr<Vec<i8>>, to: Ptr<Vec<i8>>) {
let sub: Value<Vec<i8>> = Rc::new(RefCell::new(from.with(|__s: &Vec<i8>| {
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<i8> {
let mut word: Vec<i8> = {
let mut __bytes = Ptr::<i8>::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<i8>) -> Vec<i8> {
return std::mem::take(&mut word);
}
pub fn return_reference_3(word: Ptr<Vec<i8>>) -> Vec<i8> {
return word.with_mut(|__v| std::mem::replace(__v, vec![0]));
}
pub fn return_rvalue_reference_4(word: Ptr<Vec<i8>>) -> Vec<i8> {
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<Vec<i8>> = Rc::new(RefCell::new(vec![0]));
let from_empty: Value<Vec<i8>> = Rc::new(RefCell::new(
({ std::mem::replace(&mut (*empty.borrow_mut()), vec![0]) }),
));
({
print_moved_from_0(
Ptr::<i8>::from_string_literal(b"construct empty"),
empty.as_pointer(),
from_empty.as_pointer(),
)
});
let word: Value<Vec<i8>> = Rc::new(RefCell::new({
let mut __bytes = Ptr::<i8>::from_string_literal(b"hello").to_c_bytes();
__bytes.push(0);
__bytes
}));
let from_word: Value<Vec<i8>> = Rc::new(RefCell::new(
({ std::mem::replace(&mut (*word.borrow_mut()), vec![0]) }),
));
({
print_moved_from_0(
Ptr::<i8>::from_string_literal(b"construct word"),
word.as_pointer(),
from_word.as_pointer(),
)
});
let long_word: Value<Vec<i8>> = Rc::new(RefCell::new({
let mut __bytes =
Ptr::<i8>::from_string_literal(b"a string that does not fit in place").to_c_bytes();
__bytes.push(0);
__bytes
}));
let assigned: Value<Vec<i8>> = Rc::new(RefCell::new({
let mut __bytes = Ptr::<i8>::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::<i8>::from_string_literal(b"assign long"),
long_word.as_pointer(),
assigned.as_pointer(),
)
});
let short_word: Value<Vec<i8>> = Rc::new(RefCell::new({
let mut __bytes = Ptr::<i8>::from_string_literal(b"ab").to_c_bytes();
__bytes.push(0);
__bytes
}));
let assigned_short: Value<Vec<i8>> = 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::<i8>::from_string_literal(b"assign short"),
short_word.as_pointer(),
assigned_short.as_pointer(),
)
});
{
word.as_pointer().with_mut(|__v: &mut Vec<i8>| {
__v.pop();
Ptr::<i8>::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<Vec<i8>> = Rc::new(RefCell::new(({ return_local_1() })));
let parameter: Value<Vec<i8>> = Rc::new(RefCell::new(
({
return_parameter_2({
let mut __bytes =
Ptr::<i8>::from_string_literal(b"returned parameter").to_c_bytes();
__bytes.push(0);
__bytes
})
}),
));
println!("returns: {} {}", local.decay(), parameter.decay());
let source: Value<Vec<i8>> = Rc::new(RefCell::new({
let mut __bytes = Ptr::<i8>::from_string_literal(b"returned reference").to_c_bytes();
__bytes.push(0);
__bytes
}));
let reference: Value<Vec<i8>> =
Rc::new(RefCell::new(({ return_reference_3(source.as_pointer()) })));
({
print_moved_from_0(
Ptr::<i8>::from_string_literal(b"return reference"),
source.as_pointer(),
reference.as_pointer(),
)
});
{
source.as_pointer().with_mut(|__v: &mut Vec<i8>| {
__v.pop();
Ptr::<i8>::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<Vec<i8>> = Rc::new(RefCell::new(
({ return_rvalue_reference_4(source.as_pointer()) }),
));
({
print_moved_from_0(
Ptr::<i8>::from_string_literal(b"return rvalue reference"),
source.as_pointer(),
rvalue_reference.as_pointer(),
)
});
return 0;
}
pub fn __cpp2rust_init_globals() {}
2 changes: 1 addition & 1 deletion tests/unit/out/refcount/vector_deque_vector_string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,) => {
Expand Down
Loading
Loading