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
Jump to file
Failed to load files.
Loading
Diff view
Diff view
210 changes: 139 additions & 71 deletions cpp2rust/converter/converter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -835,8 +835,8 @@ bool Converter::ConvertVarDecl(clang::VarDecl *decl) {
return false;
}

if (auto *construct = GetInPlaceVarConstruct(decl)) {
EmitLocalObject(decl, construct);
if (ConstructsVarInPlace(decl)) {
EmitLocalObject(decl);
return true;
}

Expand Down Expand Up @@ -1554,8 +1554,8 @@ void Converter::ConvertCXXConstructorBody(clang::CXXConstructorDecl *decl) {
void Converter::EmitConstructorInit(clang::CXXConstructorDecl *decl) {
if (decl->isDelegatingConstructor()) {
auto *init = (*decl->init_begin())->getInit();
if (auto *construct = GetInPlaceConstruct(init)) {
ConstructInPlace(init, construct, GetDelegatingReceiver());
if (BuildsInStorage(init)) {
ConstructInPlace(init, GetDelegatingReceiver());
return;
}
StrCat(GetConstructorWrite());
Expand Down Expand Up @@ -1587,8 +1587,8 @@ void Converter::EmitConstructorFieldInits(clang::CXXConstructorDecl *decl) {

auto *init = ctor_initializer ? ctor_initializer->getInit()
: field->getInClassInitializer();
if (auto *construct = init ? GetPlacementInitializer(init) : nullptr) {
ConstructInPlace(init, construct, GetFieldPlacementReceiver(field_name));
if (init && BuildsInStorage(init)) {
ConstructInPlace(init, GetFieldPlacementReceiver(field_name));
continue;
}
std::string value;
Expand Down Expand Up @@ -1764,8 +1764,8 @@ bool Converter::VisitReturnStmt(clang::ReturnStmt *stmt) {
auto return_type = curr_function_->getReturnType();
if (auto *value = stmt->getRetValue(); value && UsesReturnSlot(return_type)) {
std::string_view slot = "__return";
if (auto *construct = GetPlacementInitializer(value)) {
ConstructInPlace(value, construct, GetReturnSlotReceiver(slot));
if (BuildsInStorage(value)) {
ConstructInPlace(value, GetReturnSlotReceiver(slot));
} else {
HoistMaterializedTempBindings hoist_temps(*this);
StrCat(slot, ".write");
Expand Down Expand Up @@ -2037,6 +2037,10 @@ bool Converter::Convert(clang::Expr *expr,
}

bool Converter::VisitExprWithCleanups(clang::ExprWithCleanups *expr) {
if (ForwardsStorage(expr, expr->getSubExpr())) {
Convert(expr->getSubExpr());
return false;
}
ConvertFullExpression([&] { Convert(expr->getSubExpr()); });
return false;
}
Expand Down Expand Up @@ -2065,9 +2069,13 @@ std::string Converter::ConstructTemporaryInPlace(const std::string &name,
std::string *declarations) {
auto storage = CreatePlacementStorage(
GetRecordName(init->getType()->getAsCXXRecordDecl()), name);
PushExprKind push(*this, ExprKind::Void);
ScopedValue in_place(in_place_, {init, GetPlacementReceiver(name)});
auto construct = std::format("{};", ToString(temporary->IgnoreImplicit()));
std::string construct;
{
Buffer buf(*this);
ConvertIntoStorage(const_cast<clang::Expr *>(init),
GetPlacementReceiver(name));
construct = std::format("{};", std::move(buf).str());
}
if (!declarations) {
return storage + construct;
}
Expand Down Expand Up @@ -2346,19 +2354,7 @@ void Converter::ConvertVAArgCall(clang::CallExpr *expr) {
}

bool Converter::VisitCallExpr(clang::CallExpr *expr) {
if (IsReturnSlotCall(expr) && in_place_.expr != expr) {
PushBrace block(*this);
StrCat(CreatePlacementStorage(
GetRecordName(expr->getType()->getAsCXXRecordDecl())));
{
ScopedValue in_place(in_place_, {expr, GetPlacementReceiver()});
Convert(expr);
}
StrCat(token::kSemiColon);
if (!isVoid()) {
StrCat(TakePlacementValue());
}
MarkFresh();
if (IsReturnSlotCall(expr) && ConvertInBlockStorage(expr)) {
return false;
}
if (ConvertSpecialCall(expr)) {
Expand Down Expand Up @@ -3237,6 +3233,23 @@ bool Converter::IsCastRedundantInRust(clang::Expr *expr,
return GetUnsafeTypeAsString(expr->getType()) == target;
}

bool Converter::VisitCXXBindTemporaryExpr(clang::CXXBindTemporaryExpr *expr) {
ForwardsStorage(expr, expr->getSubExpr());
return true;
}

bool Converter::VisitCastExpr(clang::CastExpr *expr) {
bool forwards = expr->getCastKind() == clang::CK_ConstructorConversion ||
expr->getCastKind() == clang::CK_UserDefinedConversion ||
(clang::isa<clang::ImplicitCastExpr>(expr) &&
expr->getCastKind() == clang::CK_NoOp && expr->isPRValue());
if (forwards && ForwardsStorage(expr, expr->getSubExpr())) {
Convert(expr->getSubExpr());
return false;
}
return true;
}

bool Converter::VisitImplicitCastExpr(clang::ImplicitCastExpr *expr) {
auto *sub_expr = expr->getSubExpr();
auto type = expr->getType();
Expand Down Expand Up @@ -3728,6 +3741,9 @@ void Converter::ConvertBinaryOperator(clang::BinaryOperator *expr) {
return;
}

if (ForwardsStorage(expr, rhs)) {
in_place_.object_tail = nullptr;
}
PushBrace brace(*this);
StrCat(effect, token::kSemiColon);
if (isRValue()) {
Expand Down Expand Up @@ -4083,6 +4099,10 @@ bool Converter::ConvertLValueConditional(clang::ConditionalOperator *expr) {
}

bool Converter::VisitConditionalOperator(clang::ConditionalOperator *expr) {
if (in_place_.expr == expr) {
ConvertConditionalIntoStorage(expr);
return false;
}
if (ConvertLValueConditional(expr)) {
return false;
}
Expand Down Expand Up @@ -4221,6 +4241,10 @@ void Converter::ConvertDeclRefValue(clang::Expr *expr, clang::ValueDecl *decl) {
}

bool Converter::VisitParenExpr(clang::ParenExpr *expr) {
if (ForwardsStorage(expr, expr->getSubExpr())) {
Convert(expr->getSubExpr());
return false;
}
if (auto *bin = clang::dyn_cast<clang::BinaryOperator>(expr->getSubExpr());
bin && (bin->isCommaOp() || (bin->isAssignmentOp() && isVoid()))) {
Convert(expr->getSubExpr());
Expand Down Expand Up @@ -4819,16 +4843,14 @@ bool Converter::VisitCXXNewExpr(clang::CXXNewExpr *expr) {
if (!curr_init_type_.empty() && curr_init_type_.back()->isPointerType()) {
StrCat(".as_mut_ptr()");
}
} else if (auto *construct =
expr->getInitializer()
? GetPlacementInitializer(expr->getInitializer())
: nullptr) {
} else if (expr->getInitializer() &&
BuildsInStorage(expr->getInitializer())) {
PushBrace block(*this);
StrCat(
std::format("let __p: *mut {0} = Box::leak(Box::new(<{0}>::"
"zero_init()));",
GetRecordName(construct->getType()->getAsCXXRecordDecl())));
ConstructInPlace(expr->getInitializer(), construct, "__p");
StrCat(std::format(
"let __p: *mut {0} = Box::leak(Box::new(<{0}>::"
"zero_init()));",
GetRecordName(expr->getAllocatedType()->getAsCXXRecordDecl())));
ConstructInPlace(expr->getInitializer(), "__p");
StrCat("__p");
} else if (pointee) {
StrCat(
Expand Down Expand Up @@ -4903,18 +4925,22 @@ void Converter::ConvertArrayCXXConstructExpr(clang::CXXConstructExpr *expr) {
GetArraySize(expr->getType())));
PushParen paren(*this);
StrCat("|_|");
ConvertCXXConstructExprArgs(expr);
Convert(GetElementConstruct(expr));
}

clang::CXXConstructExpr *
Converter::GetElementConstruct(clang::CXXConstructExpr *expr) {
return MakeConstructExpr(ctx_, ctx_.getBaseElementType(expr->getType()),
expr->getConstructor(),
llvm::ArrayRef(expr->getArgs(), expr->getNumArgs()));
}

void Converter::ConvertCXXConstructExprArgs(clang::CXXConstructExpr *expr) {
if (ConvertInBlockStorage(expr)) {
return;
}
HoistMaterializedTempBindings hoist_temps(*this, /*as_block=*/true);
auto ctor = expr->getConstructor();
bool in_place = in_place_.expr == expr;
std::optional<PushBrace> block;
if (!in_place) {
block.emplace(*this);
StrCat(CreatePlacementStorage(GetRecordName(ctor->getParent())));
}
bool is_derived = IsDerivedCopyOrMove(ctor);
bool is_init = is_derived || GetInitMethod(ctor).has_value();
std::string args;
Expand Down Expand Up @@ -4943,7 +4969,7 @@ void Converter::ConvertCXXConstructExprArgs(clang::CXXConstructExpr *expr) {
}
args += std::format("{}{}", i ? ", " : "", converted);
}
if (in_place && in_place_.object_tail && hoist_temps.empty() &&
if (in_place_.object_tail && hoist_temps.empty() &&
full_expression_temporaries_->empty() && !is_derived) {
auto record_name = GetRecordName(ctor->getParent());
if (auto name = GetCtorName(ctor); name == kConstructName) {
Expand All @@ -4961,55 +4987,95 @@ void Converter::ConvertCXXConstructExprArgs(clang::CXXConstructExpr *expr) {
GetRecordTrait(ctor)->method)
: std::format("{}::{}", GetRecordName(ctor->getParent()),
GetCtorName(ctor));
StrCat(std::format("{}({}{}{})", path,
in_place ? in_place_.receiver : GetPlacementReceiver(),
StrCat(std::format("{}({}{}{})", path, in_place_.receiver,
args.empty() ? "" : ", ", args));
if (!in_place) {
StrCat(token::kSemiColon, TakePlacementValue());
}
}

void Converter::ConstructInPlace(clang::Expr *init,
const clang::Expr *construct,
std::string receiver) {
ScopedValue in_place(in_place_, {construct, std::move(receiver)});
ConvertFullExpression([&] { Convert(init); });
void Converter::ConstructInPlace(clang::Expr *init, std::string receiver) {
ConvertFullExpression([&] { ConvertIntoStorage(init, std::move(receiver)); });
StrCat(token::kSemiColon);
}

const clang::Expr *Converter::GetInPlaceVarConstruct(clang::VarDecl *decl) {
if (!decl->isLocalVarDecl() || decl->isStaticLocal() || IsGlobalVar(decl) ||
!decl->hasInit() || clang::isa<clang::DecompositionDecl>(decl) ||
!CanConstructVarInPlace(decl)) {
return nullptr;
void Converter::ConvertIntoStorage(clang::Expr *expr, std::string receiver,
std::optional<std::string> *object_tail) {
PushExprKind push(*this, ExprKind::Void);
ScopedValue in_place(in_place_, {expr, std::move(receiver), object_tail});
Convert(expr);
}

bool Converter::ForwardsStorage(const clang::Expr *expr,
const clang::Expr *operand) {
if (in_place_.expr != expr) {
return false;
}
in_place_.expr = operand;
return true;
}

void Converter::ConvertConditionalIntoStorage(
clang::ConditionalOperator *expr) {
auto receiver = in_place_.receiver;
auto branch = [&](clang::Expr *branch_expr) {
PushBrace brace(*this);
if (BuildsInStorage(branch_expr)) {
ConvertIntoStorage(branch_expr, receiver);
} else {
std::string value;
{
Buffer buf(*this);
PushExprKind push(*this, ExprKind::RValue);
ConvertVarInit(branch_expr->getType(), branch_expr);
value = std::move(buf).str();
}
StrCat(std::format("({}).write({})", receiver, value));
}
StrCat(token::kSemiColon);
};
StrCat(keyword::kIf);
ConvertIfCondition(expr->getCond());
branch(expr->getTrueExpr());
StrCat(keyword::kElse);
branch(expr->getFalseExpr());
}

bool Converter::ConvertInBlockStorage(clang::Expr *producer) {
assert(BuildsInStorage(producer));
if (in_place_.expr == producer) {
return false;
}
return GetPlacementInitializer(decl->getInit());
PushBrace block(*this);
StrCat(CreatePlacementStorage(
GetRecordName(producer->getType()->getAsCXXRecordDecl())));
ConvertIntoStorage(producer, GetPlacementReceiver());
StrCat(token::kSemiColon);
if (!isVoid()) {
StrCat(TakePlacementValue());
}
MarkFresh();
return true;
}

bool Converter::ConstructsVarInPlace(clang::VarDecl *decl) {
return decl->isLocalVarDecl() && !decl->isStaticLocal() &&
!IsGlobalVar(decl) && decl->hasInit() &&
CanConstructVarInPlace(decl) && BuildsInStorage(decl->getInit());
}

void Converter::EmitLocalObject(clang::VarDecl *decl,
const clang::Expr *construct) {
void Converter::EmitLocalObject(clang::VarDecl *decl) {
auto name = GetNamedDeclAsString(decl);
std::optional<std::string> tail;
std::string declarations;
std::string init;
{
Buffer buf(*this);
// The full expression of the initializer, whose wrappers of a constructor
// 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, GetStorageReceiver(name), &tail});
auto *init_expr = clang::isa<clang::CXXConstructExpr>(construct)
? const_cast<clang::Expr *>(construct)
: decl->getInit();
Convert(init_expr);
ConvertIntoStorage(decl->getInit(), GetStorageReceiver(name), &tail);
init = std::move(buf).str();
}
if (!tail) {
tail = std::format(
"{}, |{}| {}",
GetRecordName(construct->getType()->getAsCXXRecordDecl()), name,
GetRecordName(decl->getInit()->getType()->getAsCXXRecordDecl()), name,
declarations.empty() ? init
: std::format("{{ {}{} }}", declarations, init));
}
Expand Down Expand Up @@ -5442,6 +5508,7 @@ bool Converter::VisitSwitchStmt(clang::SwitchStmt *stmt) {
// TODO: right now defaults go into the constructor, but they should also be
// placed in the Default trait impl.
bool Converter::VisitCXXDefaultInitExpr(clang::CXXDefaultInitExpr *expr) {
ForwardsStorage(expr, expr->getExpr());
Convert(expr->getExpr());
return false;
}
Expand Down Expand Up @@ -6348,6 +6415,7 @@ void Converter::AddDefaultTrait(const clang::RecordDecl *decl) {
}
if (auto *default_ctor =
cxx ? GetUserDefinedDefaultConstructor(cxx) : nullptr) {
PushExprKind push(*this, ExprKind::RValue);
Convert(MakeDefaultConstructExpr(cxx, default_ctor));
} else {
EmitDefaultStructLiteral(decl);
Expand Down Expand Up @@ -6377,8 +6445,7 @@ void Converter::AddDefaultConstructibleTrait(const clang::CXXRecordDecl *decl,
PushBrace fn_brace(*this);
StrCat(keyword_unsafe_);
PushBrace unsafe_brace(*this);
auto *construct = MakeDefaultConstructExpr(decl, ctor);
ConstructInPlace(construct, construct, spelling.receiver);
ConstructInPlace(MakeDefaultConstructExpr(decl, ctor), spelling.receiver);
}
}

Expand Down Expand Up @@ -6842,6 +6909,7 @@ Converter::ConvertMoveConstruction(clang::Expr *arg) {
return std::nullopt;
}
Buffer buf(*this);
PushExprKind push(*this, ExprKind::FreshRValue);
Convert(init);
return std::move(buf).str();
}
Expand Down
Loading
Loading