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
117 changes: 102 additions & 15 deletions cpp2rust/converter/converter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,9 @@ std::string
Converter::GetTemplateArgumentAsString(const clang::TemplateArgument &arg) {
switch (arg.getKind()) {
case clang::TemplateArgument::Type:
if (IsReferenceToObject(arg.getAsType())) {
return GetReferenceMarkerAsString(arg.getAsType());
}
return GetUnboxedTypeAsString(arg.getAsType());
case clang::TemplateArgument::Integral:
if (!arg.getIntegralType()->isBooleanType()) {
Expand Down Expand Up @@ -1173,10 +1176,16 @@ void Converter::AddAssignmentTraits(const clang::CXXRecordDecl *decl) {
StrCat(GetAssignmentTraitSignature(*trait));
PushBrace fn_brace(*this);
// An argument by value is constructed from the source.
std::string arg = "src";
clang::QualType source_type = ctx_.getCanonicalTagType(decl);
if (trait == &kCopyAssignable) {
source_type.addConst();
}
auto arg = GetReferredObjectPointer(
"src", ctx_.getLValueReferenceType(source_type));
if (!param_type->isReferenceType()) {
StrCat(std::format("{}(__o, {}, {});", GetObjectMacro(), record_name,
trait == &kMoveAssignable ? "Moved(src)" : "src"));
StrCat(std::format("{}(__o, {}, {}::bind({}));", GetObjectMacro(),
record_name,
GetReferenceMarker(trait == &kMoveAssignable), arg));
arg = GetReturnSlotArg(GetPlacementReceiver("__o"));
}
StrCat(std::format("{}::{}({}, {});", GetUFCSName(method),
Expand All @@ -1187,9 +1196,15 @@ void Converter::AddAssignmentTraits(const clang::CXXRecordDecl *decl) {

std::string
Converter::GetAssignmentTraitSignature(const RecordTrait &trait) const {
return std::format("unsafe fn {}(this: *mut Self, src: {} Self) -> *mut Self",
trait.method,
&trait == &kMoveAssignable ? "*mut" : "*const");
return std::format("unsafe fn {}(this: *mut Self, src: {}) -> *mut Self",
trait.method, GetCopyOrMoveSourceType(trait));
}

std::string Converter::GetCopyOrMoveSourceType(const RecordTrait &trait) const {
if (&trait == &kMoveConstructible || &trait == &kMoveAssignable) {
return std::format("{}<Self>", GetReferenceMarker(true));
}
return std::format("{}<Const<Self>>", GetReferenceMarker(false));
}

void Converter::ConvertTemplateInstantiatedCtors(clang::CXXRecordDecl *decl) {
Expand Down Expand Up @@ -2744,14 +2759,14 @@ void Converter::EmitArgList(const CallInfo &info) {
StrCat(GetReturnSlotArg(in_place_.receiver), token::kComma);
}

// The move operator= is picked by a Moved source.
// The move operator= is picked by an rvalue reference source.
auto *method = clang::dyn_cast_or_null<clang::CXXMethodDecl>(
info.expr->getDirectCallee());
bool moved = method && GetRecordTrait(method) == &kMoveAssignable;
for (unsigned i = 0; i < info.args.size(); i++) {
const auto &ca = info.args[i];
if (moved) {
StrCat("Moved");
StrCat(GetReferenceMarker(true), "::bind");
}
PushParen moved_paren(*this, moved);
switch (ca.kind) {
Expand Down Expand Up @@ -2913,7 +2928,7 @@ void Converter::ConvertAssignCall(clang::CallExpr *expr,
}));
}
if (GetRecordTrait(method) == &kMoveAssignable) {
src = std::format("Moved({})", src);
src = std::format("{}({})", GetReferenceMarker(true), src);
}
std::string dst;
if (auto *member = clang::dyn_cast<clang::CXXMemberCallExpr>(expr)) {
Expand Down Expand Up @@ -4458,6 +4473,12 @@ void Converter::SetUFCSReceiver(clang::Expr *base, bool is_arrow,

void Converter::ConvertMemberExpr(clang::MemberExpr *expr) {
if (auto mapped = GetMappedAsString(expr); !mapped.empty()) {
if (auto type = expr->getMemberDecl()->getType();
IsReferenceToObject(type)) {
mapped =
std::format("({}.as_ptr() as {})", mapped,
ToString(ctx_.getPointerType(type->getPointeeType())));
}
if (RuleRegistry::ReturnsPointer(ctx_, expr) && !isAddrOf() &&
!Mapper::IsRefExpr(ctx_, expr)) {
PushParen paren(*this);
Expand Down Expand Up @@ -4934,8 +4955,9 @@ void Converter::ConvertCXXConstructExprArgs(clang::CXXConstructExpr *expr) {
auto *trait = GetRecordTrait(ctor);
bool from_source =
trait == &kCopyConstructible || trait == &kMoveConstructible;
if (trait == &kMoveConstructible) {
args = std::format("Moved({})", args);
if (from_source) {
args = std::format("{}::bind({})",
GetReferenceMarker(trait == &kMoveConstructible), args);
}
if (in_place && in_place_.object_tail && hoist_temps.empty() &&
full_expression_temporaries_->empty()) {
Expand All @@ -4953,10 +4975,7 @@ void Converter::ConvertCXXConstructExprArgs(clang::CXXConstructExpr *expr) {
return;
}
auto path =
from_source
? std::format("{}::{}", GetCopyOrMoveTraitName(kConstructFrom),
kConstructFrom.method)
: std::format("{}::{}", GetConstructorPath(ctor), GetCtorName(ctor));
std::format("{}::{}", GetConstructorPath(ctor), GetCtorName(ctor));
StrCat(std::format("{}({}{}{})", path,
in_place ? in_place_.receiver : GetPlacementReceiver(),
args.empty() ? "" : ", ", args));
Expand Down Expand Up @@ -5834,9 +5853,28 @@ void Converter::ConvertFunctionParameters(clang::FunctionDecl *decl) {
if (UsesReturnSlot(decl->getReturnType())) {
StrCat(GetReturnSlotParam(decl->getReturnType()));
}
if (auto *source = GetCopyOrMoveSource(decl)) {
StrCat(GetNamedDeclAsString(source), token::kColon,
GetReferenceMarkerAsString(source->getType()), token::kComma);
return;
}
ConvertParamList(DefinitionParameters(decl), decl->isVariadic());
}

void Converter::EmitFunctionPreamble(clang::FunctionDecl *decl) {
if (auto *source = GetCopyOrMoveSource(decl)) {
auto name = GetNamedDeclAsString(source);
StrCat(std::format("let {} = {};", name,
GetReferredObjectPointer(name, source->getType())));
}
}

std::string Converter::GetReferredObjectPointer(std::string_view reference,
clang::QualType type) {
return std::format("({}.as_ptr() as {})", reference,
ToString(ctx_.getPointerType(type->getPointeeType())));
}

void Converter::ConvertParamList(llvm::ArrayRef<clang::ParmVarDecl *> params,
bool is_variadic) {
ScopedValue in_formals(in_function_formals_, true);
Expand Down Expand Up @@ -7150,9 +7188,24 @@ std::string Converter::GetMappedAsString(clang::Expr *expr, clang::Expr **args,
if (!effects.empty()) {
result = std::format("{{ {} {} }}", effects, result);
}
if (auto referred = RuleRegistry::GetReferenceReturnedByReference(expr);
!referred.isNull() && IsReferenceToObject(referred) &&
tgt_ir->return_type.is_pointer()) {
result = CollapseReference(result, referred, place);
}
return result;
}

std::string Converter::CollapseReference(std::string_view result,
clang::QualType referred,
bool is_place) {
auto type = ToString(ctx_.getPointerType(referred->getPointeeType()));
if (is_place) {
return std::format("(*(({}).as_ptr() as {}))", result, type);
}
return std::format("((*({})).as_ptr() as {})", result, type);
}

bool Converter::UsedOnce(const TranslationRule::ExprRule &rule, unsigned n) {
unsigned uses = 0;
TranslationRule::AnyFragment(rule.body, [&](const auto &frag) {
Expand Down Expand Up @@ -7215,6 +7268,33 @@ std::vector<bool> Converter::ArgsToEvaluateFirst(
return first;
}

bool Converter::IsReferenceToObject(clang::QualType type) const {
if (!type->isReferenceType()) {
return false;
}
auto pointee = type->getPointeeType();
auto *record = pointee->getAsCXXRecordDecl();
return !pointee->isFunctionType() && !pointee->isArrayType() &&
!(record && IsAbstractUserClass(record));
}

std::string Converter::GetReferenceMarkerAsString(clang::QualType type) {
auto pointee = type->getPointeeType();
auto object = GetUnboxedTypeAsString(pointee.getUnqualifiedType());
if (pointee.isVolatileQualified()) {
object = std::format("Volatile<{}>", object);
}
if (pointee.isConstQualified()) {
object = std::format("Const<{}>", object);
}
return std::format("{}<{}>",
GetReferenceMarker(type->isRValueReferenceType()), object);
}

const char *Converter::GetReferenceMarker(bool is_rvalue) const {
return is_rvalue ? "RvalueRefUnsafe" : "LvalueRefUnsafe";
}

bool Converter::ReturnsPointerToArg(clang::Expr *) { return false; }

std::string Converter::ConvertPointerToArg(clang::Expr *, std::string_view) {
Expand Down Expand Up @@ -7278,6 +7358,13 @@ std::string Converter::ConvertIRFragment(
value = std::format("({})", value);
}
borrows_ |= outer_borrows;
if (auto bound =
RuleRegistry::GetReferenceBoundToParam(ctx_, expr, arg_idx);
!bound.isNull() && IsReferenceToObject(bound)) {
value = std::format("{}::bind({})",
GetReferenceMarker(bound->isRValueReferenceType()),
value);
}
result += value;
} else if (std::get_if<TranslationRule::VaArgsFragment>(&frag)) {
assert(expr && "variadic arguments outside an expression rule");
Expand Down
17 changes: 16 additions & 1 deletion cpp2rust/converter/converter.h
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,16 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {

std::string GetTemplateArgumentAsString(const clang::TemplateArgument &arg);

bool IsReferenceToObject(clang::QualType type) const;

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

virtual const char *GetReferenceMarker(bool is_rvalue) const;

virtual std::string CollapseReference(std::string_view result,
clang::QualType referred,
bool is_place);

bool VisitRecoveryExpr(clang::RecoveryExpr *expr);
bool VisitExprWithCleanups(clang::ExprWithCleanups *expr);
bool VisitMaterializeTemporaryExpr(clang::MaterializeTemporaryExpr *expr);
Expand Down Expand Up @@ -142,7 +152,10 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {

virtual bool VisitFunctionDecl(clang::FunctionDecl *decl);

virtual void EmitFunctionPreamble(clang::FunctionDecl *) {}
virtual void EmitFunctionPreamble(clang::FunctionDecl *decl);

virtual std::string GetReferredObjectPointer(std::string_view reference,
clang::QualType type);

virtual void ConvertFunctionBody(clang::FunctionDecl *decl);

Expand Down Expand Up @@ -1011,6 +1024,8 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
virtual std::string
GetAssignmentTraitSignature(const RecordTrait &trait) const;

std::string GetCopyOrMoveSourceType(const RecordTrait &trait) const;

virtual void AddDefaultTraitForUnion(const clang::RecordDecl *decl);

clang::CXXConstructExpr *
Expand Down
10 changes: 10 additions & 0 deletions cpp2rust/converter/converter_lib.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -896,6 +896,16 @@ const RecordTrait *GetRecordTrait(const clang::CXXMethodDecl *method) {
return is_copy ? &kCopyAssignable : &kMoveAssignable;
}

const clang::ParmVarDecl *GetCopyOrMoveSource(const clang::FunctionDecl *decl) {
auto *method = clang::dyn_cast<clang::CXXMethodDecl>(decl);
auto *trait = method ? GetRecordTrait(method) : nullptr;
if (trait != &kCopyConstructible && trait != &kMoveConstructible &&
trait != &kCopyAssignable && trait != &kMoveAssignable) {
return nullptr;
}
return DefinitionParameters(decl)[0];
}

bool IsDerivedCopyOrMove(const clang::CXXMethodDecl *method) {
if (auto *ctor = clang::dyn_cast<clang::CXXConstructorDecl>(method);
ctor && ctor->isDefaultConstructor()) {
Expand Down
29 changes: 17 additions & 12 deletions cpp2rust/converter/converter_lib.h
Original file line number Diff line number Diff line change
Expand Up @@ -125,36 +125,39 @@ inline constexpr RecordTrait kDefaultConstructible{
"unsafe fn default_constructor(this: *mut Self)", "this"}};
inline constexpr RecordTrait kCopyConstructible{
"copy_constructor",
{"CopyConstructible", "fn copy_constructor(this: Ptr<Self>, _: Ptr<Self>)",
{"CopyConstructible",
"fn copy_constructor(this: Ptr<Self>, _: LvalueRef<Const<Self>>)",
"this.clone()"},
{"CopyConstructibleUnsafe",
"unsafe fn copy_constructor(this: *mut Self, _: *const Self)", "this"}};
"unsafe fn copy_constructor(this: *mut Self, _: "
"LvalueRefUnsafe<Const<Self>>)",
"this"}};
inline constexpr RecordTrait kMoveConstructible{
"move_constructor",
{"MoveConstructible", "fn move_constructor(this: Ptr<Self>, _: Ptr<Self>)",
{"MoveConstructible",
"fn move_constructor(this: Ptr<Self>, _: RvalueRef<Self>)",
"this.clone()"},
{"MoveConstructibleUnsafe",
"unsafe fn move_constructor(this: *mut Self, _: *mut Self)", "this"}};
"unsafe fn move_constructor(this: *mut Self, _: RvalueRefUnsafe<Self>)",
"this"}};
inline constexpr RecordTrait kCopyAssignable{
"copy_assign",
{"CopyAssignable",
"fn copy_assign(this: Ptr<Self>, _: Ptr<Self>) -> Ptr<Self>",
"fn copy_assign(this: Ptr<Self>, _: LvalueRef<Const<Self>>) -> Ptr<Self>",
"this.clone()"},
{"CopyAssignableUnsafe",
"unsafe fn copy_assign(this: *mut Self, _: *const Self) -> *mut Self",
"unsafe fn copy_assign(this: *mut Self, _: LvalueRefUnsafe<Const<Self>>) "
"-> *mut Self",
"this"}};
inline constexpr RecordTrait kMoveAssignable{
"move_assign",
{"MoveAssignable",
"fn move_assign(this: Ptr<Self>, _: Ptr<Self>) -> Ptr<Self>",
"fn move_assign(this: Ptr<Self>, _: RvalueRef<Self>) -> Ptr<Self>",
"this.clone()"},
{"MoveAssignableUnsafe",
"unsafe fn move_assign(this: *mut Self, _: *mut Self) -> *mut Self",
"unsafe fn move_assign(this: *mut Self, _: RvalueRefUnsafe<Self>) -> "
"*mut Self",
"this"}};
// The construction from a source, which picks the copy or the move
// constructor from the type of the source.
inline constexpr RecordTrait kConstructFrom{
"construct_from", {"ConstructFrom"}, {"ConstructFromUnsafe"}};
inline constexpr RecordTrait kSwappable{
"swap",
{"Swappable", "fn swap(this: Ptr<Self>, _: Ptr<Self>)", "this.clone()"},
Expand Down Expand Up @@ -233,6 +236,8 @@ inline constexpr RecordTrait kMemberwise{

const RecordTrait *GetRecordTrait(const clang::CXXMethodDecl *method);

const clang::ParmVarDecl *GetCopyOrMoveSource(const clang::FunctionDecl *decl);

const RecordTrait *GetComparisonTrait(const clang::FunctionDecl *fn);

bool IsEqualityComparableTrait(const RecordTrait &trait);
Expand Down
26 changes: 22 additions & 4 deletions cpp2rust/converter/models/converter_refcount.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,15 @@ bool ConverterRefCount::VisitReferenceType(clang::ReferenceType *type) {
return false;
}

const char *ConverterRefCount::GetReferenceMarker(bool is_rvalue) const {
return is_rvalue ? "RvalueRef" : "LvalueRef";
}

std::string ConverterRefCount::CollapseReference(std::string_view result,
clang::QualType, bool) {
return std::format("{}.with(|__r| __r.as_pointer())", result);
}

std::string ConverterRefCount::ConvertFunctionPointerType(
const clang::FunctionProtoType *proto) {
PushConversionKind push(*this, ConversionKind::Unboxed);
Expand Down Expand Up @@ -642,7 +651,7 @@ ConverterRefCount::GetComparisonArg(const clang::ParmVarDecl *param,
if (IsTriviallyCopyable(decl)) {
return std::format("{}.read()", value);
}
return std::format("{{ {} {}::{}({}, {}.clone()); {} }}",
return std::format("{{ {} {}::{}({}, LvalueRef::bind({}.clone())); {} }}",
CreatePlacementStorage(GetRecordName(decl)),
GetCopyOrMoveTraitName(kCopyConstructible),
kCopyConstructible.method, GetPlacementReceiver(), value,
Expand Down Expand Up @@ -848,7 +857,14 @@ bool ConverterRefCount::VisitFieldDecl(clang::FieldDecl *decl) {
return Converter::VisitFieldDecl(decl);
}

std::string
ConverterRefCount::GetReferredObjectPointer(std::string_view reference,
clang::QualType) {
return std::format("{}.as_pointer()", reference);
}

void ConverterRefCount::EmitFunctionPreamble(clang::FunctionDecl *decl) {
Converter::EmitFunctionPreamble(decl);
PushConversionKind push(*this, ConversionKind::FullRefCount);
if (decl->isVariadic()) {
StrCat("let __args: Value<Box<[VaArg]>> = "
Expand Down Expand Up @@ -1792,7 +1808,9 @@ bool ConverterRefCount::VisitMemberExpr(clang::MemberExpr *expr) {
if (known) {
str = GetMappedAsString(expr);
if (member->getType()->isReferenceType()) {
str = std::format("{}.borrow().clone()", str);
str = std::format("{}.borrow().{}()", str,
IsReferenceToObject(member->getType()) ? "as_pointer"
: "clone");
borrows_ = true;
}
} else if (clang::isa<clang::FieldDecl>(member)) {
Expand Down Expand Up @@ -3623,8 +3641,8 @@ std::string ConverterRefCount::ConvertObjectOperand(clang::Expr *expr,

std::string
ConverterRefCount::GetAssignmentTraitSignature(const RecordTrait &trait) const {
return std::format("fn {}(this: Ptr<Self>, src: Ptr<Self>) -> Ptr<Self>",
trait.method);
return std::format("fn {}(this: Ptr<Self>, src: {}) -> Ptr<Self>",
trait.method, GetCopyOrMoveSourceType(trait));
}

const char *ConverterRefCount::GetConstructorSelf() const {
Expand Down
Loading
Loading