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
143 changes: 122 additions & 21 deletions cpp2rust/converter/converter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@ std::string Converter::ConvertPointerReceiver(

std::string Converter::ConvertTemporaryPointer(
clang::Expr *expr, std::optional<clang::QualType> implicit_convert_to) {
if (retain_bound_temporaries_ && full_expression_temporaries_) {
if (KeepsTemporaryOwner(expr)) {
auto [binding, ref] =
MaterializeTemp(NewTempName(),
ctx_.getLValueReferenceType(
Expand Down Expand Up @@ -327,6 +327,11 @@ Converter::MaterializeTemp(const std::string &binding_name,
declarations = full_expression_temporaries_;
}
auto pointee = param_type.getNonReferenceType();
if (auto *init = GetTemporaryPlacementInitializer(ctx_, expr, pointee);
init && (declarations || !in_const_initializer_)) {
return {ConstructTemporaryInPlace(binding_name, expr, init, declarations),
std::format("& mut {}", binding_name)};
}
std::string value;
{
ScopedPush init_type(curr_init_type_, pointee);
Expand Down Expand Up @@ -394,6 +399,12 @@ bool Converter::VisitReferenceType(clang::ReferenceType *type) {
std::string
Converter::ConvertFunctionPointerType(const clang::FunctionProtoType *proto) {
std::string result = "fn(";
auto return_type = proto->getReturnType();
bool return_slot = UsesReturnSlot(return_type);
if (return_slot) {
result += ToString(ctx_.getPointerType(return_type.getUnqualifiedType()));
result += ',';
}
for (auto p_ty : proto->param_types()) {
result += ToString(p_ty);
result += ',';
Expand All @@ -402,8 +413,8 @@ Converter::ConvertFunctionPointerType(const clang::FunctionProtoType *proto) {
result += "Box<[VaArg]>,";
}
result += ')';
if (!proto->getReturnType()->isVoidType()) {
result += std::format(" -> {}", ToString(proto->getReturnType()));
if (!return_type->isVoidType() && !return_slot) {
result += std::format(" -> {}", ToString(return_type));
}
return result;
}
Expand Down Expand Up @@ -651,9 +662,7 @@ void Converter::ConvertVarDeclInitializer(clang::VarDecl *decl) {
// Rust-only argument conversions can need temporaries even when Clang
// supplies no ExprWithCleanups for the initializer.
std::string declarations;
ScopedValue scope(full_expression_temporaries_,
in_const_initializer_ ? &declarations
: full_expression_temporaries_);
ScopedValue scope(full_expression_temporaries_, &declarations);
auto start = rs_code_->size();
bool registers_destructor = NeedsStaticDestructor(decl);
if (registers_destructor) {
Expand Down Expand Up @@ -715,7 +724,7 @@ void Converter::ConvertVarDecl(clang::VarDecl *decl) {
if (auto *construct = GetInPlaceVarConstruct(decl)) {
auto name = GetNamedDeclAsString(decl);
StrCat(CreatePlacementStorage(
GetRecordName(construct->getConstructor()->getParent()), name));
GetRecordName(construct->getType()->getAsCXXRecordDecl()), name));
ConstructInPlace(decl->getInit(), construct, GetPlacementReceiver(name));
return;
}
Expand Down Expand Up @@ -1433,7 +1442,7 @@ void Converter::EmitConstructorFieldInits(clang::CXXConstructorDecl *decl) {

auto *init = ctor_initializer ? ctor_initializer->getInit()
: field->getInClassInitializer();
if (auto *construct = init ? GetInPlaceConstruct(init) : nullptr) {
if (auto *construct = init ? GetPlacementInitializer(init) : nullptr) {
ConstructInPlace(init, construct, GetFieldPlacementReceiver(field_name));
continue;
}
Expand Down Expand Up @@ -1542,7 +1551,13 @@ static bool IsaSemiColonStmt(const clang::Stmt *stmt) {

bool Converter::Convert(clang::Stmt *stmt) {
PushExprKind push(*this, ExprKind::Void);
auto exited_visit = TraverseStmt(stmt);
bool exited_visit = false;
if (stmt &&
(clang::isa<clang::Expr>(stmt) || clang::isa<clang::ReturnStmt>(stmt))) {
ConvertFullExpression([&] { exited_visit = TraverseStmt(stmt); });
} else {
exited_visit = TraverseStmt(stmt);
}
if (stmt && IsaSemiColonStmt(stmt)) {
StrCat(token::kSemiColon);
}
Expand Down Expand Up @@ -1602,6 +1617,21 @@ bool Converter::VisitDeclStmt(clang::DeclStmt *stmt) {
bool Converter::VisitReturnStmt(clang::ReturnStmt *stmt) {
ScopedValue return_value(return_value_, stmt->getRetValue());
auto return_type = curr_function_->getReturnType();
if (auto *value = stmt->getRetValue(); value && UsesReturnSlot(return_type)) {
if (auto *construct = GetPlacementInitializer(value)) {
ConstructInPlace(value, construct, GetReturnSlotReceiver());
} else {
HoistMaterializedTempBindings hoist_temps(*this);
StrCat("this.write");
{
PushParen paren(*this);
ConvertVarInit(return_type, value);
}
StrCat(token::kSemiColon);
}
StrCat(keyword::kReturn, token::kSemiColon);
return false;
}
if (!return_type->isVoidType()) {
HoistMaterializedTempBindings hoist_temps(*this);
StrCat(keyword::kReturn);
Expand All @@ -1620,7 +1650,7 @@ bool Converter::VisitGotoStmt(clang::GotoStmt *stmt) {

void Converter::ConvertCondition(clang::Expr *cond) {
PushExprKind push(*this, ExprKind::RValue);
Convert(NormalizeToBool(cond, ctx_));
ConvertFullExpression([&] { Convert(NormalizeToBool(cond, ctx_)); });
}

void Converter::ConvertIfCondition(clang::Expr *cond) {
Expand Down Expand Up @@ -1876,13 +1906,35 @@ void Converter::ConvertFullExpression(llvm::function_ref<void()> convert) {
}
}

bool Converter::KeepsTemporaryOwner(const clang::Expr *temporary) const {
return full_expression_temporaries_ &&
(retain_bound_temporaries_ ||
GetTemporaryPlacementInitializer(ctx_, temporary,
temporary->getType()));
}

std::string Converter::ConstructTemporaryInPlace(const std::string &name,
clang::Expr *temporary,
const clang::Expr *init,
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()));
if (!declarations) {
return storage + construct;
}
*declarations += storage;
return construct;
}

bool Converter::VisitMaterializeTemporaryExpr(
clang::MaterializeTemporaryExpr *expr) {
// A temporary bound to a reference variable lives as long as the variable.
bool extended = IsExtendedTemporary(expr);
// A consuming conversion moves the temporary into its result instead.
if (isFreshRValue() || (!extended && (!retain_bound_temporaries_ ||
!full_expression_temporaries_))) {
if (isFreshRValue() || (!extended && !KeepsTemporaryOwner(expr))) {
return true;
}
// Keep the owner through the full expression, or the scope of the variable
Expand All @@ -1898,6 +1950,12 @@ bool Converter::VisitMaterializeTemporaryExpr(
: materialized_temp_bindings_;
}
bool pointer = isAddrOf();
if (!pointer &&
GetTemporaryPlacementInitializer(ctx_, expr, expr->getType())) {
StrCat(DerefPtrExpr(ConvertFreshPointer(expr), expr->getType()));
SetValueFreshness(expr->getType());
return false;
}
auto name = NewTempName();
auto type = ctx_.getLValueReferenceType(expr->getType());
auto [binding, ref] =
Expand Down Expand Up @@ -2142,6 +2200,21 @@ 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();
return false;
}
if (ConvertSpecialCall(expr)) {
return false;
}
Expand Down Expand Up @@ -2492,6 +2565,11 @@ void Converter::EmitArgList(const CallInfo &info) {
StrCat(std::exchange(ufcs_receiver_, std::string()), token::kComma);
}

if (IsReturnSlotCall(info.expr)) {
assert(in_place_.expr == info.expr);
StrCat(GetReturnSlotArg(in_place_.receiver), token::kComma);
}

for (unsigned i = 0; i < info.args.size(); i++) {
const auto &ca = info.args[i];
switch (ca.kind) {
Expand Down Expand Up @@ -4469,14 +4547,15 @@ 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()
? GetInPlaceConstruct(expr->getInitializer())
: nullptr) {
} else if (auto *construct =
expr->getInitializer()
? GetPlacementInitializer(expr->getInitializer())
: nullptr) {
PushBrace block(*this);
StrCat(
std::format("let __p: *mut {0} = Box::leak(Box::new(<{0}>::"
"zero_init()));",
GetRecordName(construct->getConstructor()->getParent())));
GetRecordName(construct->getType()->getAsCXXRecordDecl())));
ConstructInPlace(expr->getInitializer(), construct, "&mut *__p");
StrCat("__p");
} else if (pointee) {
Expand Down Expand Up @@ -4588,21 +4667,20 @@ void Converter::ConvertCXXConstructExprArgs(clang::CXXConstructExpr *expr) {
}

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

const clang::CXXConstructExpr *
Converter::GetInPlaceVarConstruct(clang::VarDecl *decl) {
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;
}
return GetInPlaceConstruct(decl->getInit());
return GetPlacementInitializer(decl->getInit());
}

const char *Converter::GetConstructorSelf() const { return "&mut self"; }
Expand Down Expand Up @@ -4641,6 +4719,17 @@ bool Converter::CanConstructVarInPlace(const clang::VarDecl *decl) const {

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

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

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

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

bool Converter::VisitCXXConstructExpr(clang::CXXConstructExpr *expr) {
if (expr->isElidable()) {
Convert(expr->getArg(0));
Expand Down Expand Up @@ -4849,6 +4938,9 @@ void Converter::ConvertLambdaCapture(const clang::FieldDecl *field,
void Converter::ConvertLambdaClosure(const clang::CXXRecordDecl *decl,
clang::CXXMethodDecl *call_operator) {
StrCat('|');
if (UsesReturnSlot(call_operator->getReturnType())) {
StrCat(GetReturnSlotParam(call_operator->getReturnType()));
}
ConvertParamList(call_operator->parameters(), call_operator->isVariadic());
StrCat('|');
ConvertFunctionReturnType(call_operator);
Expand Down Expand Up @@ -5383,6 +5475,9 @@ void Converter::ConvertAssignment(clang::Expr *lhs, clang::Expr *rhs,
}

void Converter::ConvertFunctionParameters(clang::FunctionDecl *decl) {
if (UsesReturnSlot(decl->getReturnType())) {
StrCat(GetReturnSlotParam(decl->getReturnType()));
}
ConvertParamList(DefinitionParameters(decl), decl->isVariadic());
}

Expand All @@ -5400,7 +5495,7 @@ void Converter::ConvertParamList(llvm::ArrayRef<clang::ParmVarDecl *> params,

void Converter::ConvertFunctionReturnType(clang::FunctionDecl *decl) {
auto return_type = decl->getReturnType();
if (!return_type->isVoidType()) {
if (!return_type->isVoidType() && !UsesReturnSlot(return_type)) {
StrCat(token::kArrow);
Convert(return_type);
}
Expand Down Expand Up @@ -5748,6 +5843,12 @@ void Converter::AddCopyAndMoveDerives(const clang::RecordDecl *decl,
if (!writes_move) {
if (copies) {
derive(kMovable, {&kMoveConstructible, &kMoveAssignable, &kSwappable});
return;
}
for (size_t i = 0; i < std::size(copy); ++i) {
if (implements(copy[i])) {
derive(*move[i], {move[i]});
}
}
return;
}
Expand Down
20 changes: 16 additions & 4 deletions cpp2rust/converter/converter.h
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,12 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {

virtual const char *TakePlacementValue() const;

virtual const char *GetReturnSlotReceiver() const;

virtual std::string GetReturnSlotArg(std::string_view receiver) const;

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

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

virtual bool VisitFieldDecl(clang::FieldDecl *decl);
Expand Down Expand Up @@ -1226,7 +1232,7 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
// A construction that constructs its object in place, in the storage that
// receiver gives to the constructor.
struct InPlaceConstruct {
const clang::CXXConstructExpr *expr = nullptr;
const clang::Expr *expr = nullptr;
std::string receiver;
};
InPlaceConstruct in_place_;
Expand All @@ -1239,15 +1245,21 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
// temporaries that live through it, if there are any.
void ConvertFullExpression(llvm::function_ref<void()> convert);

bool KeepsTemporaryOwner(const clang::Expr *temporary) const;

std::string ConstructTemporaryInPlace(const std::string &name,
clang::Expr *temporary,
const clang::Expr *init,
std::string *declarations);

// Converts init, which constructs an object by construct, to a statement that
// constructs the object in the storage that receiver gives.
void ConstructInPlace(clang::Expr *init,
const clang::CXXConstructExpr *construct,
void ConstructInPlace(clang::Expr *init, const clang::Expr *construct,
std::string receiver);

// The construction of decl by its initializer, if it can be done in the
// storage of decl.
const clang::CXXConstructExpr *GetInPlaceVarConstruct(clang::VarDecl *decl);
const clang::Expr *GetInPlaceVarConstruct(clang::VarDecl *decl);
bool retain_bound_temporaries_ = false;
class HoistMaterializedTempBindings {
Converter &c;
Expand Down
Loading
Loading