Skip to content
  •  
  •  
  •  
170 changes: 108 additions & 62 deletions cpp2rust/converter/converter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -997,6 +997,16 @@ void Converter::EmitRustStructOrUnion(clang::RecordDecl *decl) {
AddDefaultTrait(decl);
}

void Converter::ConvertTemplateInstantiatedCtors(clang::CXXRecordDecl *decl) {
for (auto c : GetTemplateInstantiatedCtors(decl)) {
if (!decl_ids_.contains(GetID(c))) {
StrCat(keyword::kImpl, GetRecordName(decl));
PushBrace brace(*this);
VisitCXXMethodDecl(c);
}
}
}

void Converter::ConvertLateInstantiatedMethods(clang::CXXRecordDecl *decl) {
ConvertCXXMethodDecls(
decl, std::format("{} {}", keyword::kImpl, GetRecordName(decl)),
Expand Down Expand Up @@ -1132,13 +1142,7 @@ bool Converter::VisitCXXRecordDecl(clang::CXXRecordDecl *decl) {
}

if (!decl->isUnion()) {
for (auto c : GetTemplateInstantiatedCtors(decl)) {
if (!decl_ids_.contains(GetID(c))) {
StrCat(keyword::kImpl, GetRecordName(decl));
PushBrace brace(*this);
VisitCXXMethodDecl(c);
}
}
ConvertTemplateInstantiatedCtors(decl);
}

if (!record_decls_.MarkDefined(GetRecordName(decl))) {
Expand Down Expand Up @@ -1280,47 +1284,56 @@ std::string Converter::GetCtorName(clang::CXXConstructorDecl *decl) {
}

bool Converter::VisitCXXConstructorDecl(clang::CXXConstructorDecl *decl) {
if (decl->isOutOfLine() ||
(decl->isImplicit() && !IsConvertibleImplicitMember(decl))) {
if (!IsConvertedConstructor(decl)) {
return false;
}
ScopedValue push_fn(curr_function_, decl);

if (decl->isCopyOrMoveConstructor() && !decl->hasBody()) {
return false;
if (method_target_ == MethodTarget::ValueImpl) {
StrCat(AccessSpecifierAsString(decl->getAccess()));
}

StrCat(AccessSpecifierAsString(decl->getAccess()), keyword_unsafe_,
keyword::kFn, GetCtorName(decl));
StrCat(keyword_unsafe_, keyword::kFn, GetCtorName(decl));
{
PushParen paren(*this);
StrCat(GetConstructorSelf(), token::kComma);
ConvertFunctionParameters(decl);
}
StrCat(token::kArrow, "Self");
if (method_target_ == MethodTarget::TraitDecl) {
StrCat(token::kSemiColon);
return false;
}
{
PushBrace brace(*this);
ConvertCXXConstructorBody(decl);
if (method_target_ == MethodTarget::TraitDefault) {
StrCat("unimplemented!()");
} else {
ConvertCXXConstructorBody(decl);
}
}

return false;
}

void Converter::ConvertCXXConstructorBody(clang::CXXConstructorDecl *decl) {
EmitFunctionPreamble(decl);
StrCat(keyword::kLet, "mut", "this", token::kAssign);
EmitConstructorInit(decl);
StrCat(token::kSemiColon);
ConvertBodyStmts(decl->getBody());
StrCat("this");
}

void Converter::EmitConstructorInit(clang::CXXConstructorDecl *decl) {
if (decl->isDelegatingConstructor()) {
Convert((*decl->init_begin())->getInit());
StrCat(GetConstructorWrite());
{
PushParen paren(*this);
Convert((*decl->init_begin())->getInit());
}
StrCat(token::kSemiColon);
return;
}
StrCat("Self");
PushBrace this_init(*this);
EmitConstructorFieldInits(decl);
}

void Converter::EmitConstructorFieldInits(clang::CXXConstructorDecl *decl) {
const auto *record_decl = decl->getParent();
auto *definition_or_null = decl->getDefinition();
assert(definition_or_null);
Expand All @@ -1336,13 +1349,24 @@ void Converter::EmitConstructorInit(clang::CXXConstructorDecl *decl) {
}
}

StrCat(field_name, token::kColon);
ConvertFieldInit(field, ctor_initializer ? ctor_initializer->getInit()
: field->getInClassInitializer());
StrCat(token::kComma);
std::string value;
{
Buffer buf(*this);
ConvertFieldInit(field, ctor_initializer
? ctor_initializer->getInit()
: field->getInClassInitializer());
value = std::move(buf).str();
}
StrCat(ConvertConstructorFieldWrite(field_name, value));
}
}

std::string
Converter::ConvertConstructorFieldWrite(const std::string &field_name,
const std::string &value) {
return std::format("(&raw mut self.{}).write({});", field_name, value);
}

bool Converter::VisitFieldDecl(clang::FieldDecl *decl) {
auto access_spec = AccessSpecifierAsString(decl->getAccess());
auto field_name = GetNamedDeclAsString(decl);
Expand Down Expand Up @@ -3766,7 +3790,7 @@ void Converter::SetUFCSReceiver(clang::Expr *base, bool is_arrow,
const clang::CXXMethodDecl *method) {
if (clang::isa<clang::CXXThisExpr>(base->IgnoreParenImpCasts()) &&
!AsLambdaOperatorCall(curr_function_)) {
ufcs_receiver_ = InConstructor() ? "&mut this" : keyword::kSelfValue;
ufcs_receiver_ = keyword::kSelfValue;
return;
}
Buffer buf(*this);
Expand Down Expand Up @@ -3819,7 +3843,7 @@ void Converter::ConvertMemberExpr(clang::MemberExpr *expr) {
bool bound_object = retain_bound_temporaries_ && isAddrOf();
PushExprKind push(*this, isLValue() ? ExprKind::LValue : ExprKind::RValue);
if (base_is_this) {
StrCat(InConstructor() ? "this" : keyword::kSelfValue);
StrCat(keyword::kSelfValue);
} else if (expr->isArrow()) {
ConvertArrow(base);
} else if (bound_object) {
Expand Down Expand Up @@ -3867,9 +3891,7 @@ bool Converter::VisitCXXThisExpr(clang::CXXThisExpr *expr) {
: std::format("(&raw mut {})", name));
return false;
}
if (InConstructor()) {
StrCat("&raw mut this");
} else {
{
PushParen paren(*this);
StrCat(keyword::kSelfValue, keyword::kAs, ToString(expr->getType()));
}
Expand Down Expand Up @@ -4206,24 +4228,48 @@ void Converter::ConvertArrayCXXConstructExpr(clang::CXXConstructExpr *expr) {
void Converter::ConvertCXXConstructExprArgs(clang::CXXConstructExpr *expr) {
HoistMaterializedTempBindings hoist_temps(*this, /*as_block=*/true);
auto ctor = expr->getConstructor();
StrCat(GetRecordName(ctor->getParent()), token::kDoubleColon,
GetCtorName(ctor));
PushParen paren(*this);

for (unsigned i = 0; i < ctor->getNumParams(); ++i) {
assert(i < expr->getNumArgs());
clang::Expr *arg = expr->getArg(i);
if (auto *default_arg = clang::dyn_cast<clang::CXXDefaultArgExpr>(arg)) {
arg = default_arg->getExpr();
}
{
PushBrace brace(*this);
ConvertVarInit(ctor->getParamDecl(i)->getType(), arg);
PushBrace block(*this);
StrCat(CreatePlacementStorage(GetRecordName(ctor->getParent())));
StrCat(GetConstructorPath(ctor), token::kDoubleColon, GetCtorName(ctor));
{
PushParen paren(*this);
StrCat(GetPlacementReceiver(), token::kComma);
for (unsigned i = 0; i < ctor->getNumParams(); ++i) {
assert(i < expr->getNumArgs());
clang::Expr *arg = expr->getArg(i);
if (auto *default_arg = clang::dyn_cast<clang::CXXDefaultArgExpr>(arg)) {
arg = default_arg->getExpr();
}
{
PushBrace brace(*this);
ConvertVarInit(ctor->getParamDecl(i)->getType(), arg);
}
StrCat(token::kComma);
}
StrCat(token::kComma);
}
StrCat(token::kSemiColon, TakePlacementValue());
}

std::string Converter::GetConstructorSelf() const { return "&mut self"; }

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

std::string
Converter::GetConstructorPath(const clang::CXXConstructorDecl *ctor) const {
return GetRecordName(ctor->getParent());
}

std::string
Converter::CreatePlacementStorage(const std::string &record_name) const {
return std::format("let mut __v: {0} = <{0}>::zero_init();", record_name);
}

std::string Converter::GetPlacementReceiver() const { return "&mut __v"; }

std::string Converter::TakePlacementValue() const { return "__v"; }

bool Converter::VisitCXXConstructExpr(clang::CXXConstructExpr *expr) {
if (expr->isElidable()) {
Convert(expr->getArg(0));
Expand Down Expand Up @@ -4674,11 +4720,8 @@ std::string Converter::GetDefaultAsStringFallback(clang::QualType qual_type) {
}

if (qual_type->isEnumeralType()) {
auto enum_decl = qual_type->castAs<clang::EnumType>()->getDecl();
if (enum_decl->enumerators().empty()) {
return GetDefaultAsString(enum_decl->getIntegerType());
}
return EnumeratorName(*enum_decl->enumerator_begin());
return GetDefaultAsString(
qual_type->castAs<clang::EnumType>()->getDecl()->getIntegerType());
}

return std::format("<{}>::default()", ToString(qual_type));
Expand Down Expand Up @@ -4739,7 +4782,7 @@ std::string Converter::GetRecordName(const clang::NamedDecl *decl) const {
std::vector<const char *>
Converter::GetStructAttributes(const clang::RecordDecl *decl) {
if (decl->isUnion()) {
return {"Copy", "Clone", "FnPtrArg", "VaArg"};
return {"Copy", "Clone", "FnPtrArg", "VaArg", "ZeroInitializationUnsafe"};
}

std::vector<const char *> struct_attrs;
Expand All @@ -4756,6 +4799,7 @@ Converter::GetStructAttributes(const clang::RecordDecl *decl) {
struct_attrs.emplace_back("VaArg");
}
struct_attrs.emplace_back("FnPtrArg");
struct_attrs.emplace_back("ZeroInitializationUnsafe");

if (HasMoveFromConstructor(decl)) {
struct_attrs.emplace_back("MoveCtorUnsafe");
Expand Down Expand Up @@ -5278,11 +5322,12 @@ void Converter::AddCloneTrait(const clang::RecordDecl *decl) {
StrCat("fn clone(&self) -> Self");
PushBrace fn_brace(*this);
auto source = ctor->getParamDecl(0)->getType().getNonReferenceType();
StrCat(std::format("unsafe {{ {}::{}(self as *const {}{}) }}", record_name,
GetCtorName(ctor), record_name,
source.isConstQualified()
? ""
: std::format(" as *mut {}", record_name)));
StrCat(std::format(
"unsafe {{ {}{}::{}({}, self as *const {}{}); {} }}",
CreatePlacementStorage(record_name), GetConstructorPath(ctor),
GetCtorName(ctor), GetPlacementReceiver(), record_name,
source.isConstQualified() ? "" : std::format(" as *mut {}", record_name),
TakePlacementValue()));
}

bool Converter::RecordImplementsClone(const clang::RecordDecl *decl) {
Expand All @@ -5306,6 +5351,10 @@ void Converter::AddDefaultTrait(const clang::RecordDecl *decl) {
StrCat(keyword_unsafe_);
PushBrace unsafe_brace(*this);
auto *cxx = clang::dyn_cast<clang::CXXRecordDecl>(decl);
if (cxx && !cxx->hasDefaultConstructor()) {
StrCat(std::format("<{}>::zero_init()", GetRecordName(decl)));
return;
}
if (auto *default_ctor =
cxx ? GetUserDefinedDefaultConstructor(cxx) : nullptr) {
std::vector<clang::Expr *> args;
Expand Down Expand Up @@ -6225,12 +6274,9 @@ std::string Converter::ConvertGenericCall(
if (call.method == "move_ctor") {
assert(call_args.size() == 1 && "move_ctor takes one argument");
auto *record = type->getAsCXXRecordDecl();
if (record && HasMoveFromConstructor(record)) {
return std::format("{}::move_from({})", GetUnboxedTypeAsString(type),
call_args[0]);
}
if (record && !IsUserDefinedDecl(record) &&
!record->hasTrivialMoveConstructor()) {
if (record && (HasMoveFromConstructor(record) ||
(!IsUserDefinedDecl(record) &&
!record->hasTrivialMoveConstructor()))) {
return std::format("<{} as {}>::move_ctor({})",
GetUnboxedTypeAsString(type), GetMoveCtorTraitName(),
call_args[0]);
Expand Down
28 changes: 24 additions & 4 deletions cpp2rust/converter/converter.h
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,8 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {

virtual void ConvertLateInstantiatedMethods(clang::CXXRecordDecl *decl);

virtual void ConvertTemplateInstantiatedCtors(clang::CXXRecordDecl *decl);

virtual std::string DestroyMembers(const clang::CXXRecordDecl *decl);

bool NeedsScopedDestructor(const clang::VarDecl *decl) const;
Expand All @@ -233,10 +235,30 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {

virtual bool ThisIsRustPtr() const { return false; }

virtual void ConvertCXXConstructorBody(clang::CXXConstructorDecl *decl);
void ConvertCXXConstructorBody(clang::CXXConstructorDecl *decl);
// The object that decl constructs, before its body runs.
void EmitConstructorInit(clang::CXXConstructorDecl *decl);

void EmitConstructorFieldInits(clang::CXXConstructorDecl *decl);

virtual std::string
ConvertConstructorFieldWrite(const std::string &field_name,
const std::string &value);

virtual std::string GetConstructorSelf() const;

virtual std::string GetConstructorWrite() const;

virtual std::string
GetConstructorPath(const clang::CXXConstructorDecl *ctor) const;

virtual std::string
CreatePlacementStorage(const std::string &record_name) const;

virtual std::string GetPlacementReceiver() const;

virtual std::string TakePlacementValue() const;

virtual bool VisitCXXConstructorDecl(clang::CXXConstructorDecl *decl);

virtual bool VisitFieldDecl(clang::FieldDecl *decl);
Expand Down Expand Up @@ -1049,9 +1071,6 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
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_);
}
bool in_function_formals_ = false;
enum class MethodTarget : uint8_t {
ValueImpl,
Expand Down Expand Up @@ -1108,6 +1127,7 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
return std::format("__tmp_{}", materialized_temp_id_++);
}
std::string *materialized_temp_bindings_ = nullptr;

// The variable whose initializer is converted, which extends the lifetime
// of the temporaries bound to its reference to its own.
const clang::VarDecl *extending_decl_ = nullptr;
Expand Down
8 changes: 8 additions & 0 deletions cpp2rust/converter/converter_lib.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -806,6 +806,14 @@ bool IsConvertibleImplicitMember(const clang::CXXMethodDecl *method) {
IsConvertibleCopyAssignment(method);
}

bool IsConvertedConstructor(const clang::CXXConstructorDecl *decl) {
if (decl->isOutOfLine() ||
(decl->isImplicit() && !IsConvertibleImplicitMember(decl))) {
return false;
}
return !decl->isCopyOrMoveConstructor() || decl->hasBody();
}

bool IsDefaultedMoveConstructor(const clang::CXXConstructorDecl *ctor) {
return ctor->isMoveConstructor() && !ctor->isUserProvided() &&
IsUserDefinedDecl(ctor->getParent());
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 @@ -143,6 +143,8 @@ bool HasMoveAssignOperator(const clang::RecordDecl *decl);

bool IsConvertibleImplicitMember(const clang::CXXMethodDecl *method);

bool IsConvertedConstructor(const clang::CXXConstructorDecl *decl);

clang::CXXConstructorDecl *
GetUserDefinedCopyConstructor(const clang::RecordDecl *decl);

Expand Down
Loading
Loading