Skip to content
Open
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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
105 changes: 62 additions & 43 deletions cpp2rust/converter/converter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -816,11 +816,10 @@ void Converter::EmitScopedDestructor(const clang::VarDecl *decl) {
if (!NeedsScopedDestructor(decl)) {
return;
}
StrCat(
token::kSemiColon,
std::format("let _dtor_{0} = std::mem::DropGuard::new(&raw mut {0}, "
"|__p| unsafe {{ DestructibleUnsafe::destroy(&mut *__p) }})",
GetNamedDeclAsString(decl)));
StrCat(token::kSemiColon,
std::format("let _dtor_{0} = std::mem::DropGuard::new(&raw mut {0}, "
"|__p| unsafe {{ DestructibleUnsafe::destroy(__p) }})",
GetNamedDeclAsString(decl)));
}

bool Converter::RecordDerivesDefault(const clang::RecordDecl *decl) {
Expand Down Expand Up @@ -1087,7 +1086,7 @@ void Converter::AddAssignmentTraits(const clang::CXXRecordDecl *decl) {

std::string
Converter::GetAssignmentTraitSignature(const RecordTrait &trait) const {
return std::format("unsafe fn {}(&mut self, src: {} Self) -> *mut Self",
return std::format("unsafe fn {}(this: *mut Self, src: {} Self) -> *mut Self",
trait.method,
&trait == &kMoveAssignable ? "*mut" : "*const");
}
Expand Down Expand Up @@ -1154,7 +1153,8 @@ std::string Converter::DestroyMembers(const clang::CXXRecordDecl *decl) {
std::string out;
for (auto *field : FieldsToDestroy(decl)) {
auto name = GetNamedDeclAsString(field);
out += std::format("DestructibleUnsafe::destroy(&mut self.{});\n", name);
out += std::format("DestructibleUnsafe::destroy(&raw mut (*this).{});\n",
name);
}
return out;
}
Expand Down Expand Up @@ -1359,7 +1359,7 @@ bool Converter::ConvertCXXMethodDecl(clang::CXXMethodDecl *decl) {
return VisitCXXConstructorDecl(ctor);
}

if (method_target_ == MethodTarget::ValueImpl && !GetRecordTrait(decl) &&
if (!GetRecordTrait(decl) &&
(decl->isStatic() ||
(!decl->isVirtual() && !decl->getParent()->isAbstract()))) {
StrCat(AccessSpecifierAsString(decl->getAccess()));
Expand All @@ -1374,11 +1374,8 @@ bool Converter::ConvertCXXMethodDecl(clang::CXXMethodDecl *decl) {
ConvertFunctionParameters(decl);
}
ConvertFunctionReturnType(decl);
if (decl->isPureVirtual() || method_target_ == MethodTarget::TraitDecl) {
if (decl->isPureVirtual()) {
StrCat(token::kSemiColon);
} else if (method_target_ == MethodTarget::TraitDefault) {
PushBrace body(*this);
StrCat("unimplemented!()");
} else {
PushBrace body(*this);
EmitFunctionPreamble(decl);
Expand All @@ -1388,7 +1385,11 @@ bool Converter::ConvertCXXMethodDecl(clang::CXXMethodDecl *decl) {
}

std::string Converter::GetSelfMaybeWithMut(const clang::CXXMethodDecl *decl) {
return MethodNeedsMutableReceiver(decl) ? "&mut self" : "&self";
bool is_mut = MethodNeedsMutableReceiver(decl);
if (GetRecordTrait(decl) || IsMethodOnPtr(decl)) {
return is_mut ? "this: *mut Self" : "this: *const Self";
}
return is_mut ? "&mut self" : "&self";
}

std::string Converter::GetCtorName(clang::CXXConstructorDecl *decl) {
Expand All @@ -1413,7 +1414,7 @@ bool Converter::VisitCXXConstructorDecl(clang::CXXConstructorDecl *decl) {
}
ScopedValue push_fn(curr_function_, decl);

if (method_target_ == MethodTarget::ValueImpl && !GetRecordTrait(decl)) {
if (!GetRecordTrait(decl)) {
StrCat(AccessSpecifierAsString(decl->getAccess()));
}
StrCat(keyword_unsafe_, keyword::kFn, GetCtorName(decl));
Expand All @@ -1422,17 +1423,9 @@ bool Converter::VisitCXXConstructorDecl(clang::CXXConstructorDecl *decl) {
StrCat(GetConstructorSelf(), token::kComma);
ConvertFunctionParameters(decl);
}
if (method_target_ == MethodTarget::TraitDecl) {
StrCat(token::kSemiColon);
return false;
}
{
PushBrace brace(*this);
if (method_target_ == MethodTarget::TraitDefault) {
StrCat("unimplemented!()");
} else {
ConvertCXXConstructorBody(decl);
}
ConvertCXXConstructorBody(decl);
}

return false;
Expand Down Expand Up @@ -1497,7 +1490,7 @@ void Converter::EmitConstructorFieldInits(clang::CXXConstructorDecl *decl) {
std::string
Converter::ConvertConstructorFieldWrite(const std::string &field_name,
const std::string &value) {
return std::format("(&raw mut self.{}).write({});", field_name, value);
return std::format("(&raw mut (*this).{}).write({});", field_name, value);
}

bool Converter::VisitFieldDecl(clang::FieldDecl *decl) {
Expand Down Expand Up @@ -1660,7 +1653,7 @@ bool Converter::VisitReturnStmt(clang::ReturnStmt *stmt) {
ConstructInPlace(value, construct, GetReturnSlotReceiver());
} else {
HoistMaterializedTempBindings hoist_temps(*this);
StrCat("this.write");
StrCat("__return.write");
{
PushParen paren(*this);
ConvertVarInit(return_type, value);
Expand Down Expand Up @@ -4293,14 +4286,26 @@ bool Converter::VisitMemberExpr(clang::MemberExpr *expr) {

void Converter::SetUFCSReceiver(clang::Expr *base, bool is_arrow,
const clang::CXXMethodDecl *method) {
bool is_mut = MethodNeedsMutableReceiver(method);
bool takes_pointer = GetRecordTrait(method) || IsMethodOnPtr(method);
if (clang::isa<clang::CXXThisExpr>(base->IgnoreParenImpCasts()) &&
!AsLambdaOperatorCall(curr_function_)) {
ufcs_receiver_ = keyword::kSelfValue;
return;
if (takes_pointer) {
ufcs_receiver_ = ConvertFreshRValue(base);
return;
}
if (!ThisIsRustPtr()) {
ufcs_receiver_ = keyword::kSelfValue;
return;
}
}
Buffer buf(*this);
PushExprKind push(*this, ExprKind::LValue);
StrCat(MethodNeedsMutableReceiver(method) ? "&mut" : "&");
if (takes_pointer && (is_arrow || !IsTemporaryObject(ctx_, base))) {
StrCat(is_mut ? "&raw mut" : "&raw const");
} else {
StrCat(is_mut ? "&mut" : "&");
}
if (is_arrow) {
ConvertArrow(base);
} else {
Expand Down Expand Up @@ -4388,6 +4393,12 @@ const clang::Expr *Converter::GetFieldReadCall(const clang::MemberExpr *expr) {
return clang::isa<clang::CallExpr>(base) ? base : nullptr;
}

bool Converter::ThisIsRustPtr() const {
auto *method = clang::dyn_cast_or_null<clang::CXXMethodDecl>(curr_function_);
return method && (GetRecordTrait(method) || IsMethodOnPtr(method) ||
clang::isa<clang::CXXConstructorDecl>(method));
}

bool Converter::VisitCXXThisExpr(clang::CXXThisExpr *expr) {
if (auto field = AsLambdaCaptureThis(curr_function_)) {
auto name = GetNamedDeclAsString(field);
Expand All @@ -4396,7 +4407,9 @@ bool Converter::VisitCXXThisExpr(clang::CXXThisExpr *expr) {
: std::format("(&raw mut {})", name));
return false;
}
{
if (ThisIsRustPtr()) {
StrCat("this");
} else {
PushParen paren(*this);
StrCat(keyword::kSelfValue, keyword::kAs, ToString(expr->getType()));
}
Expand Down Expand Up @@ -4671,7 +4684,7 @@ bool Converter::VisitCXXNewExpr(clang::CXXNewExpr *expr) {
std::format("let __p: *mut {0} = Box::leak(Box::new(<{0}>::"
"zero_init()));",
GetRecordName(construct->getType()->getAsCXXRecordDecl())));
ConstructInPlace(expr->getInitializer(), construct, "&mut *__p");
ConstructInPlace(expr->getInitializer(), construct, "__p");
StrCat("__p");
} else if (pointee) {
StrCat(
Expand Down Expand Up @@ -4711,10 +4724,10 @@ bool Converter::VisitCXXDeleteExpr(clang::CXXDeleteExpr *expr) {
StrCat(
std::format("for __i in (0..libcc2rs::malloc_usable_size(__p as *mut "
"::libc::c_void) / ::std::mem::size_of::<{0}>()).rev() {{ "
"DestructibleUnsafe::destroy(&mut *__p.add(__i)); }}",
"DestructibleUnsafe::destroy(__p.add(__i)); }}",
record_name));
} else {
StrCat("DestructibleUnsafe::destroy(&mut *__p)", token::kSemiColon);
StrCat("DestructibleUnsafe::destroy(__p)", token::kSemiColon);
}
EmitDeallocation(expr, "__p");
return false;
Expand Down Expand Up @@ -4839,7 +4852,8 @@ void Converter::EmitLocalObject(clang::VarDecl *decl,
// call (parentheses, casts to its type) emit nothing else.
ScopedValue scope(full_expression_temporaries_, &declarations);
// Any other construction gets the storage as a reference named name.
ScopedValue in_place(in_place_, {construct, name, &tail});
ScopedValue in_place(in_place_,
{construct, GetStorageReceiver(name), &tail});
auto *init_expr = clang::isa<clang::CXXConstructExpr>(construct)
? const_cast<clang::Expr *>(construct)
: decl->getInit();
Expand All @@ -4858,6 +4872,10 @@ void Converter::EmitLocalObject(clang::VarDecl *decl,

const char *Converter::GetObjectMacro() const { return "object_unsafe!"; }

std::string Converter::GetStorageReceiver(std::string_view name) const {
return std::string(name);
}

const char *Converter::GetAssignMacro() const { return "assign_unsafe!"; }

std::string Converter::ConvertObjectOperand(clang::Expr *expr, bool is_arrow) {
Expand All @@ -4871,11 +4889,9 @@ std::string Converter::ConvertObjectOperand(clang::Expr *expr, bool is_arrow) {
return std::move(buf).str();
}

const char *Converter::GetConstructorSelf() const { return "&mut self"; }
const char *Converter::GetConstructorSelf() const { return "this: *mut Self"; }

const char *Converter::GetConstructorWrite() const {
return "(self as *mut Self).write";
}
const char *Converter::GetConstructorWrite() const { return "this.write"; }

std::string
Converter::GetConstructorPath(const clang::CXXConstructorDecl *ctor) const {
Expand All @@ -4892,29 +4908,29 @@ std::string Converter::CreatePlacementStorage(const std::string &record_name,
}

std::string Converter::GetPlacementReceiver(std::string_view name) const {
return std::format("&mut {}", name);
return std::format("&raw mut {}", name);
}

std::string Converter::GetFieldPlacementReceiver(std::string_view field) const {
return std::format("&mut self.{}", field);
return std::format("&raw mut (*this).{}", field);
}

const char *Converter::GetDelegatingReceiver() const { return "&mut *self"; }
const char *Converter::GetDelegatingReceiver() const { return "this"; }

bool Converter::CanConstructVarInPlace(const clang::VarDecl *decl) const {
return true;
}

const char *Converter::TakePlacementValue() const { return "__v"; }

const char *Converter::GetReturnSlotReceiver() const { return "&mut *this"; }
const char *Converter::GetReturnSlotReceiver() const { return "__return"; }

std::string Converter::GetReturnSlotArg(std::string_view receiver) const {
return std::string(receiver);
}

std::string Converter::GetReturnSlotParam(clang::QualType type) {
return std::format("this: {},",
return std::format("__return: {},",
ToString(ctx_.getPointerType(type.getUnqualifiedType())));
}

Expand Down Expand Up @@ -5882,7 +5898,10 @@ std::string Converter::GetComparisonReceiver(const clang::CXXMethodDecl *method,
if (!MethodNeedsMutableReceiver(method)) {
return std::string(lhs);
}
return std::format("&mut *(&raw const *{}).cast_mut()", lhs);
if (!IsMethodOnPtr(method)) {
return std::format("&mut *(&raw const *{}).cast_mut()", lhs);
}
return std::format("(&raw const *{}).cast_mut()", lhs);
}

std::string Converter::GetEqBody(const clang::CXXRecordDecl *decl,
Expand Down
11 changes: 3 additions & 8 deletions cpp2rust/converter/converter.h
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {

virtual std::string GetUFCSName(const clang::CXXMethodDecl *method) const;

virtual bool ThisIsRustPtr() const { return false; }
virtual bool ThisIsRustPtr() const;

void ConvertCXXConstructorBody(clang::CXXConstructorDecl *decl);
// The object that decl constructs, before its body runs.
Expand Down Expand Up @@ -395,6 +395,8 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {

virtual const char *GetObjectMacro() const;

virtual std::string GetStorageReceiver(std::string_view name) const;

// The macro that calls the copy or the move operator= of a class.
virtual const char *GetAssignMacro() const;

Expand Down Expand Up @@ -1207,13 +1209,6 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
clang::FunctionDecl *curr_function_ = nullptr;
clang::Expr *return_value_ = nullptr;
bool in_function_formals_ = false;
enum class MethodTarget : uint8_t {
ValueImpl,
TraitDecl,
TraitDefault,
PtrImpl,
};
MethodTarget method_target_ = MethodTarget::ValueImpl;

std::string ufcs_receiver_;
bool in_const_initializer_ = false;
Expand Down
44 changes: 23 additions & 21 deletions cpp2rust/converter/converter_lib.h
Original file line number Diff line number Diff line change
Expand Up @@ -119,49 +119,51 @@ struct RecordTrait {

inline constexpr RecordTrait kDefaultConstructible{
"default_constructor",
{"DefaultConstructible", "fn default_constructor(this: &Ptr<Self>)",
"this"},
{"DefaultConstructibleUnsafe", "unsafe fn default_constructor(&mut self)",
"&mut *self"}};
{"DefaultConstructible", "fn default_constructor(this: Ptr<Self>)",
"this.clone()"},
{"DefaultConstructibleUnsafe",
"unsafe fn default_constructor(this: *mut Self)", "this"}};
inline constexpr RecordTrait kCopyConstructible{
"copy_constructor",
{"CopyConstructible", "fn copy_constructor(this: &Ptr<Self>, _: Ptr<Self>)",
"this"},
{"CopyConstructible", "fn copy_constructor(this: Ptr<Self>, _: Ptr<Self>)",
"this.clone()"},
{"CopyConstructibleUnsafe",
"unsafe fn copy_constructor(&mut self, _: *const Self)", "&mut *self"}};
"unsafe fn copy_constructor(this: *mut Self, _: *const Self)", "this"}};
inline constexpr RecordTrait kMoveConstructible{
"move_constructor",
{"MoveConstructible", "fn move_constructor(this: &Ptr<Self>, _: Ptr<Self>)",
"this"},
{"MoveConstructible", "fn move_constructor(this: Ptr<Self>, _: Ptr<Self>)",
"this.clone()"},
{"MoveConstructibleUnsafe",
"unsafe fn move_constructor(&mut self, _: *mut Self)", "&mut *self"}};
"unsafe fn move_constructor(this: *mut Self, _: *mut Self)", "this"}};
inline constexpr RecordTrait kCopyAssignable{
"copy_assign",
{"CopyAssignable",
"fn copy_assign(this: &Ptr<Self>, _: Ptr<Self>) -> Ptr<Self>", "this"},
"fn copy_assign(this: Ptr<Self>, _: Ptr<Self>) -> Ptr<Self>",
"this.clone()"},
{"CopyAssignableUnsafe",
"unsafe fn copy_assign(&mut self, _: *const Self) -> *mut Self",
"&mut *self"}};
"unsafe fn copy_assign(this: *mut Self, _: *const Self) -> *mut Self",
"this"}};
inline constexpr RecordTrait kMoveAssignable{
"move_assign",
{"MoveAssignable",
"fn move_assign(this: &Ptr<Self>, _: Ptr<Self>) -> Ptr<Self>", "this"},
"fn move_assign(this: Ptr<Self>, _: Ptr<Self>) -> Ptr<Self>",
"this.clone()"},
{"MoveAssignableUnsafe",
"unsafe fn move_assign(&mut self, _: *mut Self) -> *mut Self",
"&mut *self"}};
"unsafe fn move_assign(this: *mut Self, _: *mut 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"},
{"SwappableUnsafe", "unsafe fn swap(&mut self, _: *mut Self)",
"&mut *self"}};
{"Swappable", "fn swap(this: Ptr<Self>, _: Ptr<Self>)", "this.clone()"},
{"SwappableUnsafe", "unsafe fn swap(this: *mut Self, _: *mut Self)",
"this"}};
inline constexpr RecordTrait kDestructible{
"destroy",
{"Destructible", "fn destroy(this: &Ptr<Self>)", "this"},
{"DestructibleUnsafe", "unsafe fn destroy(&mut self)", "&mut *self"}};
{"Destructible", "fn destroy(this: Ptr<Self>)", "this.clone()"},
{"DestructibleUnsafe", "unsafe fn destroy(this: *mut Self)", "this"}};
inline constexpr RecordTrait kTriviallyDefaultConstructible{
nullptr,
{"TriviallyDefaultConstructible"},
Expand Down
Loading
Loading