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
255 changes: 225 additions & 30 deletions cpp2rust/converter/converter.cpp

Large diffs are not rendered by default.

37 changes: 30 additions & 7 deletions cpp2rust/converter/converter.h
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,8 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
std::string GetTemplateArgumentAsString(const clang::TemplateArgument &arg);

bool VisitRecoveryExpr(clang::RecoveryExpr *expr);
bool VisitExprWithCleanups(clang::ExprWithCleanups *expr);
bool VisitMaterializeTemporaryExpr(clang::MaterializeTemporaryExpr *expr);

virtual void EmitFilePreamble();

Expand Down Expand Up @@ -518,19 +520,22 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
virtual bool VisitBinaryOperator(clang::BinaryOperator *expr);
bool VisitCXXRewrittenBinaryOperator(clang::CXXRewrittenBinaryOperator *expr);

void ConvertAssignmentRef(clang::BinaryOperator *expr);
virtual void ConvertBinaryOperator(clang::BinaryOperator *expr);

// The value that the compound assignment expr assigns to its left operand,
// whose type differs from the computation type.
std::string ConvertCompoundAssignValue(clang::CompoundAssignOperator *expr);
// The value that the compound assignment expr assigns to its left operand.
// Optional operand strings refer to values that have already been evaluated.
std::string ConvertCompoundAssignValue(clang::CompoundAssignOperator *expr,
std::string_view lhs_value = {},
std::string_view rhs_value = {});

virtual bool ConvertIncAndDec(clang::UnaryOperator *expr);

virtual bool VisitUnaryOperator(clang::UnaryOperator *expr);

virtual bool VisitStmtExpr(clang::StmtExpr *expr);

bool ConvertLValueConditional(clang::ConditionalOperator *expr);
virtual bool ConvertLValueConditional(clang::ConditionalOperator *expr);

virtual bool VisitConditionalOperator(clang::ConditionalOperator *expr);

Expand Down Expand Up @@ -853,7 +858,8 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {

virtual void
ConvertUnsignedArithBinaryOperator(clang::BinaryOperator *binary_operator,
clang::Expr *expr);
clang::Expr *expr,
std::string_view value = {});

virtual void ConvertAddrOf(clang::Expr *expr, clang::QualType pointer_type);

Expand Down Expand Up @@ -899,6 +905,15 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
// address is not taken.
std::unordered_set<const clang::VarDecl *> bound_values_;

// Bound initializer arguments may need a mapped move constructor when
// forwarding the original rvalue from its pointer binding.
std::unordered_set<const clang::VarDecl *> bound_init_args_;

// Updates the pointee using its previous value, borrowing it once.
virtual std::string
AssignPtrExpr(std::string_view ptr, clang::QualType type,
llvm::function_ref<std::string(std::string_view)> value);

std::string ConvertVariadicTail(clang::Expr *expr,
llvm::ArrayRef<clang::Expr *> all_args);

Expand Down Expand Up @@ -1012,6 +1027,9 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
return std::format("__tmp_{}", materialized_temp_id_++);
}
std::string *materialized_temp_bindings_ = nullptr;
// Owning temporaries needed by references bound before a rule expansion.
std::string *full_expression_temporaries_ = nullptr;
bool retain_bound_temporaries_ = false;
class HoistMaterializedTempBindings {
Converter &c;
std::string *prev;
Expand Down Expand Up @@ -1089,6 +1107,7 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
Callee,
LValue,
RValue,
FreshRValue,
XValue,
AddrOf,
Object,
Expand All @@ -1103,6 +1122,8 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
return "LValue";
case ExprKind::RValue:
return "RValue";
case ExprKind::FreshRValue:
return "FreshRValue";
case ExprKind::XValue:
return "XValue";
case ExprKind::AddrOf:
Expand All @@ -1118,6 +1139,7 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {

bool isLValue() const;
bool isRValue() const;
bool isFreshRValue() const;
bool isXValue() const;
bool isAddrOf() const;
bool isObject() const;
Expand Down Expand Up @@ -1210,10 +1232,11 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
int line = __builtin_LINE());

/// Materialize a temporary for a prvalue bound to a reference parameter.
/// Returns (binding_code, ref_expression).
/// Returns (binding_code, ref_expression). With declarations, emit the local
/// declaration there and return its initialization at the evaluation site.
virtual std::pair<std::string, std::string>
MaterializeTemp(const std::string &binding_name, clang::QualType param_type,
clang::Expr *expr);
clang::Expr *expr, std::string *declarations = nullptr);

/// Emits binding_code to materialized_temp_bindings_.
/// Returns ref_expression.
Expand Down
68 changes: 66 additions & 2 deletions cpp2rust/converter/models/boxed_vars.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#include "converter/models/boxed_vars.h"

#include <clang/AST/RecursiveASTVisitor.h>
#include <clang/AST/StmtVisitor.h>
#include <clang/Basic/SourceManager.h>

#include <algorithm>
Expand Down Expand Up @@ -231,6 +232,63 @@ class AddressTakenVisitor
}

private:
// Follow only the object whose address a bound lvalue needs, not the
// operands that merely compute that address.
class AddressUseVisitor : public clang::ConstStmtVisitor<AddressUseVisitor> {
public:
explicit AddressUseVisitor(AddressTakenVisitor &owner) : owner_(owner) {}

void Traverse(const clang::Expr *expr) {
Visit(expr->IgnoreParenImpCasts());
}

void VisitDeclRefExpr(const clang::DeclRefExpr *expr) {
owner_.AddressTaken(expr->getDecl());
}

void VisitExpr(const clang::Expr *expr) {
if (auto *object = GetEnclosingObject(expr)) {
Traverse(object);
}
}

void VisitCallExpr(const clang::CallExpr *expr) {
if (IsTransparentStdCall(expr)) {
Traverse(expr->getArg(0));
} else {
VisitExpr(expr);
}
}

void VisitCastExpr(const clang::CastExpr *expr) {
if (expr->isGLValue()) {
Traverse(expr->getSubExpr());
}
}

void VisitUnaryOperator(const clang::UnaryOperator *expr) {
if (expr->isIncrementDecrementOp()) {
Traverse(expr->getSubExpr());
}
}

void VisitBinaryOperator(const clang::BinaryOperator *expr) {
if (expr->isAssignmentOp()) {
Traverse(expr->getLHS());
} else if (expr->isCommaOp()) {
Traverse(expr->getRHS());
}
}

void VisitConditionalOperator(const clang::ConditionalOperator *expr) {
Traverse(expr->getTrueExpr());
Traverse(expr->getFalseExpr());
}

private:
AddressTakenVisitor &owner_;
};

// The arguments of a call translated by a rule are passed by value or
// borrowed, unless the rule takes a pointer to them, other than to a
// temporary copy of them, or they are bound to references. A pointer
Expand All @@ -241,11 +299,17 @@ class AddressTakenVisitor
if (!rule) {
return;
}
// Variadic arguments are not considered.
auto all_args = BuildUnifiedArgs(expr, args, num_args);
auto bound = rule->argsToBind(ctx_, expr, all_args);
for (unsigned i = 0; i < all_args.size() && i < rule->params.size(); ++i) {
for (unsigned i = 0; i < all_args.size(); ++i) {
if (bound[i]) {
if (all_args[i]->isGLValue()) {
AddressUseVisitor(*this).Traverse(all_args[i]);
}
continue;
}
// Unbound variadic arguments are not considered.
if (i >= rule->params.size()) {
continue;
}
auto *arg = IgnoreNoOpCasts(all_args[i]);
Expand Down
94 changes: 72 additions & 22 deletions cpp2rust/converter/models/converter_refcount.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,11 @@ std::string ConverterRefCount::ConvertPointerReceiver(
if (clang::isa<clang::MaterializeTemporaryExpr>(arg->IgnoreImpCasts())) {
return ConvertTemporaryPointer(arg, implicit_convert_to);
}
if (retain_bound_temporaries_ && arg->getType()->isArrayType()) {
auto ptr = ConvertElementPtr(arg);
object_shape_ = ObjectShape::Whole;
return ptr;
}
return isObject() ? ConvertObject(arg) : ConvertFreshObject(arg);
}

Expand Down Expand Up @@ -437,6 +442,9 @@ std::string ConverterRefCount::ConvertFreshObject(clang::Expr *expr) {

std::string ConverterRefCount::ConvertTemporaryPointer(
clang::Expr *expr, std::optional<clang::QualType> implicit_convert_to) {
if (retain_bound_temporaries_ && full_expression_temporaries_) {
return Converter::ConvertTemporaryPointer(expr, implicit_convert_to);
}
return std::format("Rc::new(RefCell::new({})).as_pointer()",
ConvertFreshRValue(expr, implicit_convert_to));
}
Expand All @@ -456,7 +464,8 @@ std::string ConverterRefCount::ConvertFreshRValue(
{
ScopedValue<const clang::Expr *> copied(copied_expr_,
expr->IgnoreParenImpCasts());
str = ConvertRValue(expr, implicit_convert_to);
PushExprKind push(*this, ExprKind::FreshRValue);
str = ToString(expr, implicit_convert_to);
}
if (expr->getType()->isVoidType()) {
MarkFresh();
Expand Down Expand Up @@ -490,29 +499,39 @@ std::string ConverterRefCount::ConvertPointeeCast(std::string str,
ToString(element.getUnqualifiedType()));
}

std::pair<std::string, std::string>
ConverterRefCount::MaterializeTemp(const std::string &binding_name,
clang::QualType param_type,
clang::Expr *expr) {
std::pair<std::string, std::string> ConverterRefCount::MaterializeTemp(
const std::string &binding_name, clang::QualType param_type,
clang::Expr *expr, std::string *declarations) {
if (!declarations && retain_bound_temporaries_) {
declarations = full_expression_temporaries_;
}
auto pointee = param_type.getNonReferenceType();
const auto *decl = in_const_initializer_ ? keyword::kStatic : keyword::kLet;
std::string binding;
bool is_static = in_const_initializer_ && !declarations;
const auto *decl = is_static ? keyword::kStatic : keyword::kLet;
std::string type, value;
if (pointee->isConstantArrayType()) {
PushConversionKind push(*this, ConversionKind::FullRefCount);
binding =
std::format("{} {} : {} = {};", decl, binding_name, ToString(pointee),
BoxValue(ConvertVarInitValue(pointee, expr)));
type = ToString(pointee);
value = BoxValue(ConvertVarInitValue(pointee, expr));
} else {
auto unboxed = ConvertFreshRValue(expr, pointee);
type = std::format("Value<{}>", ToStringBase(pointee));
value = std::format("Rc::new(RefCell::new({}))", unboxed);
}
std::string binding;
if (declarations) {
*declarations += std::format("let {} : {};", binding_name, type);
binding = std::format("{} = {};", binding_name, value);
} else {
auto value = ConvertFreshRValue(expr, pointee);
auto type_str = ToStringBase(pointee);
binding = std::format("{} {} : Value<{}> = Rc::new(RefCell::new({}));",
decl, binding_name, type_str, value);
binding = std::format("{} {} : {} = {};", decl, binding_name, type, value);
}
auto ref =
in_const_initializer_ ? ".with(Value::as_pointer)" : ".as_pointer()";
auto ref = is_static ? ".with(Value::as_pointer)" : ".as_pointer()";
// A reference to an array is a pointer to its first element.
if (pointee->isConstantArrayType()) {
ref = in_const_initializer_ ? ".with(|__v| __v.decay())" : ".decay()";
ref = is_static ? ".with(|__v| __v.decay())" : ".decay()";
if (retain_bound_temporaries_ && isObject()) {
object_shape_ = ObjectShape::Whole;
}
}
return {binding, binding_name + ref};
}
Expand Down Expand Up @@ -903,6 +922,16 @@ bool ConverterRefCount::ConvertIncAndDec(clang::UnaryOperator *expr) {
return false;
}

if (expr->isPrefix() && isAddrOf()) {
auto ptr = ConvertFreshObject(sub_expr);
auto name = NewTempName();
StrCat(
std::format("{{ let {0} = {1}; {0}.with_mut(|__v| __v.{2}()); {0} }}",
name, ptr, method));
MarkFresh();
return true;
}

auto str = ConvertLValue(sub_expr);
if (!pending_deref_.empty()) {
StrCat(pending_deref_.take(), ".with_mut(|__v| __v.", method, "())");
Expand All @@ -919,6 +948,14 @@ bool ConverterRefCount::ConvertIncAndDec(clang::UnaryOperator *expr) {
return true;
}

bool ConverterRefCount::ConvertLValueConditional(
clang::ConditionalOperator *expr) {
if (isRValue()) {
return false;
}
return Converter::ConvertLValueConditional(expr);
}

void ConverterRefCount::ConvertConditionalBranch(clang::Expr *expr,
clang::QualType type) {
StrCat(ConvertFresh(expr, type));
Expand Down Expand Up @@ -2725,10 +2762,12 @@ void ConverterRefCount::ConvertArraySubscript(clang::Expr *base,
StrCat(std::format("{}.offset({})", ConvertStringLiteralPtr(base),
ConvertSubscriptIndex(idx)));
} else {
StrCat(std::format(
"{}.offset({})",
ConvertObject(base->IgnoreImplicit(), ObjectShape::Element),
ConvertSubscriptIndex(idx)));
StrCat(std::format("{}.offset({})",
ConvertObject(retain_bound_temporaries_
? base->IgnoreImpCasts()
: base->IgnoreImplicit(),
ObjectShape::Element),
ConvertSubscriptIndex(idx)));
}
MarkFresh();
} else if (auto *global = GetGlobalArrayRValue(SubscriptedArray(base))) {
Expand All @@ -2750,7 +2789,8 @@ void ConverterRefCount::ConvertArraySubscript(clang::Expr *base,
ConvertDeclRef(global, global->getDecl()), path,
TypeIsCopyable(type) ? "" : ".clone()"));
} else {
Convert(base->IgnoreImplicit());
Convert(retain_bound_temporaries_ ? base->IgnoreImpCasts()
: base->IgnoreImplicit());
// An array reached through a pointer is indexed in place.
if (!pending_deref_.empty()) {
auto place = pending_deref_.take();
Expand Down Expand Up @@ -2983,6 +3023,12 @@ std::string ConverterRefCount::DerefPtrExpr(std::string_view ptr_expr,
GetPointerDerefSuffix(pointee_type));
}

std::string ConverterRefCount::AssignPtrExpr(
std::string_view ptr, clang::QualType,
llvm::function_ref<std::string(std::string_view)> value) {
return std::format("{}.with_mut(|__v| *__v = {})", ptr, value("(*__v)"));
}

bool ConverterRefCount::IsReferenceType(const clang::Expr *expr) const {
if (Converter::IsReferenceType(expr)) {
return true;
Expand Down Expand Up @@ -3125,6 +3171,10 @@ void ConverterRefCount::SetUFCSReceiver(clang::Expr *base, bool is_arrow,
}
if (IsTemporaryObject(base) && base->getType()->isRecordType() &&
!IsReferenceType(base->IgnoreImplicit())) {
if (retain_bound_temporaries_ && full_expression_temporaries_) {
ufcs_receiver_ = token::kRef + ConvertTemporaryPointer(base, {});
return;
}
PushConversionKind push(*this, ConversionKind::FullRefCount);
ufcs_receiver_ =
token::kRef + BoxValue(ConvertRValue(base)) + ".as_pointer()";
Expand Down
Loading
Loading