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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
176 changes: 111 additions & 65 deletions cpp2rust/converter/converter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -996,6 +996,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 @@ -1121,13 +1131,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 @@ -1261,55 +1265,64 @@ std::string Converter::GetCtorName(clang::CXXConstructorDecl *decl) {
CanUseCopyOrMoveName(decl, name)) {
return name;
}
return std::format("new_{}", GetCtorIndex(decl));
return std::format("construct_{}", GetCtorIndex(decl));
}
return GetNumberOfConvertingCtors(decl->getParent()) != 1
? std::format("new_{}", GetCtorIndex(decl))
: "new";
? std::format("construct_{}", GetCtorIndex(decl))
: "construct";
}

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 @@ -1325,13 +1338,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 @@ -3949,7 +3973,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 @@ -4002,7 +4026,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 @@ -4050,9 +4074,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 @@ -4388,24 +4410,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());
}

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

const char *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);
}

const char *Converter::GetPlacementReceiver() const { return "&mut __v"; }

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

bool Converter::VisitCXXConstructExpr(clang::CXXConstructExpr *expr) {
if (expr->isElidable()) {
Convert(expr->getArg(0));
Expand Down Expand Up @@ -4856,11 +4902,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 @@ -4921,7 +4964,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 @@ -4938,6 +4981,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 @@ -5460,11 +5504,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 @@ -5488,6 +5533,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 @@ -6412,12 +6461,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 @@ -211,6 +211,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 @@ -235,10 +237,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 const char *GetConstructorSelf() const;

virtual const char *GetConstructorWrite() const;

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

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

virtual const char *GetPlacementReceiver() const;

virtual const char *TakePlacementValue() const;

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

virtual bool VisitFieldDecl(clang::FieldDecl *decl);
Expand Down Expand Up @@ -1115,9 +1137,6 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
std::shared_ptr<const BoxedVars> boxed_vars_;
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 @@ -1174,6 +1193,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