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
48 changes: 31 additions & 17 deletions cpp2rust/converter/converter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5479,6 +5479,11 @@ std::string Converter::ConvertPlaceholder(clang::Expr *expr, clang::Expr *arg,
}

if (ph_ctx.access == TranslationRule::Access::kMove) {
if (MovesFromArg(expr, ph_ctx.arg_idx, arg)) {
auto ptr = ConvertPointer(arg);
MarkFresh();
return ConvertMoveThroughPointer(arg->getType(), ptr);
}
return ConvertFreshRValue(arg, ph_ctx.implicit_convert_to);
}

Expand All @@ -5490,7 +5495,8 @@ std::string Converter::ConvertBorrowMut(clang::Expr *arg) {
}

std::string Converter::ConvertTake(clang::Expr *arg) {
auto moved_from = GetMovedFromValue(arg);
auto moved_from =
IsImplicitReturnMove(arg) ? "" : GetMovedFromValue(arg->getType());
auto lvalue = ConvertLValue(arg);
MarkFresh();
if (!moved_from.empty()) {
Expand All @@ -5500,30 +5506,35 @@ std::string Converter::ConvertTake(clang::Expr *arg) {
return std::format("std::mem::take(&mut {})", std::move(lvalue));
}

std::string Converter::GetMovedFromValue(clang::Expr *arg) {
auto type = arg->getType();
bool Converter::IsImplicitReturnMove(clang::Expr *arg) const {
auto *returned = return_value_ ? return_value_->IgnoreImplicit() : nullptr;
auto *ctor = clang::dyn_cast_or_null<clang::CXXConstructExpr>(returned);
if (!ctor || !ctor->getConstructor()->isMoveConstructor() ||
ctor->getArg(0)->IgnoreParenImpCasts() != arg->IgnoreParenImpCasts()) {
return false;
}
auto *ref = clang::dyn_cast<clang::DeclRefExpr>(arg->IgnoreParenImpCasts());
auto *var = ref ? clang::dyn_cast<clang::VarDecl>(ref->getDecl()) : nullptr;
return var && var->hasLocalStorage() && !var->getType()->isReferenceType();
}

std::string Converter::GetMovedFromValue(clang::QualType type) {
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::ConvertMoveThroughPointer(clang::QualType type,
const std::string &ptr) {
if (auto moved_from = GetMovedFromValue(type); !moved_from.empty()) {
return std::format("std::mem::replace(&mut *{}, {})", ptr, moved_from);
}
return std::format("cpp_move_unsafe!({})", ptr);
}

std::string Converter::ConvertMappedMethodCall(
clang::Expr *expr, const TranslationRule::MethodCallFragment &mc,
llvm::ArrayRef<clang::TemplateArgument> bindings,
Expand Down Expand Up @@ -5791,6 +5802,9 @@ std::string Converter::ConvertConversion(clang::QualType to,
}
return std::format("({} as {})", value, GetUnsafeTypeAsString(to));
}
if (is_move && ctx_.hasSameUnqualifiedType(to, from)) {
return ConvertMoveThroughPointer(to, ptr);
}
return std::format("<{} as {}<{}>>::{}({})", GetUnboxedTypeAsString(to),
GetConversionTraitName(), GetUnboxedTypeAsString(from),
is_move ? "cpp_from_move" : "cpp_from", ptr);
Expand Down
10 changes: 6 additions & 4 deletions cpp2rust/converter/converter.h
Original file line number Diff line number Diff line change
Expand Up @@ -908,10 +908,12 @@ 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);
bool IsImplicitReturnMove(clang::Expr *arg) const;

std::string GetMovedFromValue(clang::QualType type);

virtual std::string ConvertMoveThroughPointer(clang::QualType type,
const std::string &ptr);

// The place of `arg`, which is borrowed mutably by a rule.
virtual std::string ConvertBorrowMut(clang::Expr *arg);
Expand Down
7 changes: 7 additions & 0 deletions cpp2rust/converter/converter_lib.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -619,6 +619,13 @@ bool HasMoveFromConstructor(const clang::RecordDecl *decl) {
});
}

bool MovesFromArg(clang::Expr *expr, unsigned arg_idx, clang::Expr *arg) {
auto param_type = GetParamType(expr, arg_idx);
return param_type && (*param_type)->isRValueReferenceType() &&
!(*param_type)->getPointeeType().isConstQualified() &&
!clang::isa<clang::MaterializeTemporaryExpr>(arg);
}

// Whether move assigning a field of decl isn't a copy: the field is a record
// with a move_assign method, or a library type that moves its contents.
static bool HasFieldWithMoveAssign(const clang::RecordDecl *decl) {
Expand Down
2 changes: 2 additions & 0 deletions cpp2rust/converter/converter_lib.h
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,8 @@ bool IsConvertibleMoveConstructor(const clang::CXXConstructorDecl *ctor);
// Whether decl has a move constructor converted to a move_from method.
bool HasMoveFromConstructor(const clang::RecordDecl *decl);

bool MovesFromArg(clang::Expr *expr, unsigned arg_idx, clang::Expr *arg);

void ForEachConvertingConstructor(
clang::CXXRecordDecl *decl,
llvm::function_ref<void(clang::CXXConstructorDecl *)> fn);
Expand Down
13 changes: 12 additions & 1 deletion cpp2rust/converter/models/converter_refcount.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3092,8 +3092,19 @@ std::string ConverterRefCount::ConvertBorrowMut(clang::Expr *arg) {
return lvalue;
}

std::string
ConverterRefCount::ConvertMoveThroughPointer(clang::QualType type,
const std::string &ptr) {
if (auto moved_from = GetMovedFromValue(type); !moved_from.empty()) {
return std::format("{}.with_mut(|__v| std::mem::replace(__v, {}))", ptr,
moved_from);
}
return std::format("cpp_move!({})", ptr);
}

std::string ConverterRefCount::ConvertTake(clang::Expr *arg) {
auto moved_from = GetMovedFromValue(arg);
auto moved_from =
IsImplicitReturnMove(arg) ? "" : GetMovedFromValue(arg->getType());
auto lvalue = ConvertLValue(arg);
MarkFresh();
// An object reached through a pointer is taken through it.
Expand Down
3 changes: 3 additions & 0 deletions cpp2rust/converter/models/converter_refcount.h
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,9 @@ class ConverterRefCount final : public Converter {

std::string ConvertTake(clang::Expr *arg) override;

std::string ConvertMoveThroughPointer(clang::QualType type,
const std::string &ptr) override;

std::string ConvertBorrowMut(clang::Expr *arg) override;

// Whether the receiver of a method call translated by a rule is being
Expand Down
4 changes: 2 additions & 2 deletions rules/pair/tgt_unsafe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ unsafe fn f10<T1, T2>(a0: T1, a1: T2) -> (T1, T2) {
(a0, a1)
}

unsafe fn f12<T1: Default, T2: Default>(a0: &mut (T1, T2)) -> (T1, T2) {
std::mem::take(&mut *a0)
unsafe fn f12<T1, T2>(a0: &mut (T1, T2)) -> (T1, T2) {
(cpp_move_unsafe!(&mut a0.0), cpp_move_unsafe!(&mut a0.1))
}

unsafe fn f13<T1: Clone, T2: Clone>(a0: &mut (T1, T2), a1: (T1, T2)) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
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 source: Value<(Value<Option<Value<i32>>>, Value<i32>)> = Rc::new(RefCell::new((
Rc::new(RefCell::new(Ptr::alloc(1).to_owned_opt())),
Rc::new(RefCell::new(2)),
)));
let pairs: Value<Vec<(Value<Option<Value<i32>>>, Value<i32>)>> =
Rc::new(RefCell::new(Vec::new()));
match ({
<RandomAccessIterator<(Value<Option<Value<i32>>>, Value<i32>)>>::from(pairs.decay().end())
},)
{
(mut __tmp_0,) => {
let __off = __tmp_0.index();
(*pairs.borrow_mut()).insert(__off, cpp_move!(source.as_pointer()));
(__tmp_0).clone()
}
};
assert!(({ (((*(*pairs.borrow())[0_usize].0.borrow()).as_pointer().read()) == 1) }));
assert!(({ (*(*source.borrow()).0.borrow()).is_none() }));
assert!(({ ((*(*source.borrow()).1.borrow()) == 2) }));
}
pub fn test_1() {
let source: Value<(Value<Option<Value<i32>>>, Value<i32>)> = Rc::new(RefCell::new((
Rc::new(RefCell::new(Ptr::alloc(1).to_owned_opt())),
Rc::new(RefCell::new(2)),
)));
let pairs: Value<Vec<(Value<Option<Value<i32>>>, Value<i32>)>> =
Rc::new(RefCell::new(Vec::new()));
{
let __a1 = ({ std::mem::take(&mut (*source.borrow_mut())) });
(*pairs.borrow_mut()).push(__a1)
};
assert!(({ (((*(*pairs.borrow())[0_usize].0.borrow()).as_pointer().read()) == 1) }));
assert!(({ (*(*source.borrow()).0.borrow()).is_none() }));
assert!(({ ((*(*source.borrow()).1.borrow()) == 2) }));
}
pub fn main() {
__cpp2rust_init_globals();
std::process::exit(main_0());
}
fn main_0() -> i32 {
({ test_0() });
({ test_1() });
return 0;
}
pub fn __cpp2rust_init_globals() {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
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: (Option<Box<i32>>, i32) =
(Some(Box::from_raw((Box::leak(Box::new(1)) as *mut i32))), 2);
let mut pairs: Vec<(Option<Box<i32>>, i32)> = Vec::new();
match ({ <UnsafeRandomAccessIterator<(Option<Box<i32>>, i32)>>::from(pairs.end()) },) {
(mut __tmp_0,) => {
let pos = __tmp_0.iter_distance(&UnsafeRandomAccessIterator::Vec(pairs.as_mut_ptr()))
as usize;
pairs.insert(pos, cpp_move_unsafe!(&mut source));
(__tmp_0).clone()
}
};
assert!(
((*pairs[(0_usize)]
.0
.as_deref()
.map_or(::std::ptr::null_mut(), |v| v as *const i32 as *mut i32))
== (1))
);
assert!(source.0.is_none());
assert!(((source.1) == (2)));
}
pub unsafe fn test_1() {
let mut source: (Option<Box<i32>>, i32) =
(Some(Box::from_raw((Box::leak(Box::new(1)) as *mut i32))), 2);
let mut pairs: Vec<(Option<Box<i32>>, i32)> = Vec::new();
{
let __a1 = std::mem::take(&mut source);
pairs.push(__a1)
};
assert!(
((*pairs[(0_usize)]
.0
.as_deref()
.map_or(::std::ptr::null_mut(), |v| v as *const i32 as *mut i32))
== (1))
);
assert!(source.0.is_none());
assert!(((source.1) == (2)));
}
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() });
return 0;
}
pub unsafe fn __cpp2rust_init_globals() {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// panic: refcount, unsafe
// ADDITIONAL_COMPILE_FLAGS: -std=c++23
#include <cassert>
#include <memory>
#include <utility>
#include <vector>

// N4950 [sequence.reqmts]/30: a.insert(p, rv) inserts a copy of rv (copy
// according to [container.alloc.reqmts]/2.3, where T is Cpp17MoveInsertable)
// before p.
namespace p30_insert_moves_pair {
void test() {
std::pair<std::unique_ptr<int>, int> source(std::unique_ptr<int>(new int(1)),
2);
std::vector<std::pair<std::unique_ptr<int>, int>> pairs;
pairs.insert(pairs.end(), std::move(source));
assert(*pairs[0].first == 1);
assert(source.first == nullptr);
assert(source.second == 2);
}
} // namespace p30_insert_moves_pair

// N4950 [sequence.reqmts]/104: a.push_back(rv) appends a copy of rv (copy
// according to [container.alloc.reqmts]/2.3, where T is Cpp17MoveInsertable).
namespace p104_push_back_moves_pair {
void test() {
std::pair<std::unique_ptr<int>, int> source(std::unique_ptr<int>(new int(1)),
2);
std::vector<std::pair<std::unique_ptr<int>, int>> pairs;
pairs.push_back(std::move(source));
assert(*pairs[0].first == 1);
assert(source.first == nullptr);
assert(source.second == 2);
}
} // namespace p104_push_back_moves_pair

int main() {
p30_insert_moves_pair::test();
p104_push_back_moves_pair::test();
return 0;
}
Loading
Loading