Skip to content

Commit 5da4e3b

Browse files
committed
Write all rules over Rust references
Cpp2Rust will now adapt the input and output to have the relevant type. THis allows rules over e.g. strings to not force their arguments to be boxed since the system can now keep arguments as references.
1 parent a14d133 commit 5da4e3b

180 files changed

Lines changed: 3531 additions & 2785 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎cpp2rust/converter/converter.cpp‎

Lines changed: 141 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -796,7 +796,13 @@ bool Converter::IsPassThroughRule(clang::Expr *expr) {
796796
if (!rule || rule->body.size() != 1) {
797797
return false;
798798
}
799-
auto *ph = std::get_if<TranslationRule::PlaceholderFragment>(&rule->body[0]);
799+
// The rule returns its argument, or a reference to it.
800+
auto *operand = rule->refExprOperand();
801+
auto &body = operand ? *operand : rule->body;
802+
if (body.size() != 1) {
803+
return false;
804+
}
805+
auto *ph = std::get_if<TranslationRule::PlaceholderFragment>(&body[0]);
800806
if (!ph) {
801807
return false;
802808
}
@@ -2956,8 +2962,8 @@ void Converter::ConvertBinaryOperator(clang::BinaryOperator *expr) {
29562962
expr->isCompoundAssignmentOp() &&
29572963
GetUnsafeTypeAsString(lhs_type) !=
29582964
GetUnsafeTypeAsString(cmpd_assign_op->getComputationResultType())) {
2959-
Convert(lhs);
2960-
StrCat(token::kAssign, ConvertCompoundAssignValue(cmpd_assign_op));
2965+
StrCat(ConvertLValue(lhs), token::kAssign,
2966+
ConvertCompoundAssignValue(cmpd_assign_op));
29612967
} else if (expr->isCommaOp()) {
29622968
PushBrace brace(*this);
29632969
{
@@ -5647,7 +5653,37 @@ std::string Converter::GetMappedAsString(clang::Expr *expr, clang::Expr **args,
56475653
// objects are bound to live until the end of the statement, like those of
56485654
// the C++ arguments.
56495655
auto all_args = BuildUnifiedArgs(expr, args, num_args);
5656+
// An argument that is the reference that another rule returns to its own
5657+
// argument is that argument, after the rest of the other rule, unless the
5658+
// rule may return a place, which can't be computed after something else.
5659+
std::string effects;
5660+
bool may_be_place = expr->isGLValue() && !isAddrOf() && !isVoid();
5661+
for (size_t i = 0; !may_be_place && i < all_args.size(); ++i) {
5662+
auto *returned = RuleRegistry::GetReturnedArg(ctx_, all_args[i]);
5663+
if (!returned || returned->HasSideEffects(ctx_) ||
5664+
llvm::any_of(all_args, [&](clang::Expr *arg) {
5665+
return arg != all_args[i] && arg->HasSideEffects(ctx_);
5666+
})) {
5667+
continue;
5668+
}
5669+
PushExprKind push(*this, ExprKind::Void);
5670+
effects += ToString(all_args[i]) + token::kSemiColon;
5671+
all_args[i] = returned;
5672+
}
56505673
auto bind = tgt_ir->argsToBind(ctx_, expr, all_args);
5674+
auto *operand = tgt_ir->refExprOperand();
5675+
auto effect = tgt_ir->refExprEffect();
5676+
// The C++ expression is a reference to the argument, or an element of it.
5677+
auto *base = expr->isGLValue() ? tgt_ir->refExprBase() : nullptr;
5678+
bool discards_ref =
5679+
base && operand->size() == 1 && !effect.empty() && isVoid();
5680+
// The temporaries of an argument that a pointer is returned to live as long
5681+
// as the binding.
5682+
if (base && !discards_ref && all_args[base->n]->HasSideEffects(ctx_) &&
5683+
ReturnsPointerToArg(all_args[base->n])) {
5684+
bind[base->n] = true;
5685+
}
5686+
auto first = ArgsToEvaluateFirst(expr, *tgt_ir, all_args, bind);
56515687
std::vector<std::string> values, names;
56525688
// Bindings in a global initializer are local to the expansion too.
56535689
clang::DeclContext *binding_context = curr_function_;
@@ -5656,14 +5692,14 @@ std::string Converter::GetMappedAsString(clang::Expr *expr, clang::Expr **args,
56565692
ctx_, ctx_.getTranslationUnitDecl(), expr->getExprLoc());
56575693
}
56585694
for (size_t i = 0; binding_context && i < all_args.size(); ++i) {
5659-
if (!bind[i]) {
5695+
if (!bind[i] && !first[i]) {
56605696
continue;
56615697
}
56625698
// The rule takes the value of a transparent union.
56635699
auto *arg = IgnoreTransparentUnion(all_args[i]);
56645700
auto type = arg->getType();
5665-
bool by_value =
5666-
arg->isPRValue() && !tgt_ir->takesAddress(ctx_, expr, i, arg);
5701+
bool by_value = (arg->isPRValue() || first[i]) &&
5702+
!tgt_ir->takesAddress(ctx_, expr, i, arg);
56675703
if (!by_value && arg->isPRValue()) {
56685704
arg = new (ctx_) clang::MaterializeTemporaryExpr(type, arg, false);
56695705
}
@@ -5681,6 +5717,10 @@ std::string Converter::GetMappedAsString(clang::Expr *expr, clang::Expr **args,
56815717
if (tgt_ir->usesInit() && i >= tgt_ir->params.size()) {
56825718
bound_init_args_.insert(var);
56835719
}
5720+
// The value, or the pointer, is moved into the body, which uses it once.
5721+
if (first[i] && UsedOnce(*tgt_ir, i)) {
5722+
moved_values_.insert(var);
5723+
}
56845724
// The temporaries of a value, e.g., borrows, end with its block.
56855725
if (by_value) {
56865726
bound_values_.insert(var);
@@ -5714,34 +5754,110 @@ std::string Converter::GetMappedAsString(clang::Expr *expr, clang::Expr **args,
57145754
}
57155755

57165756
auto saved_borrows = std::exchange(mut_borrows_, {});
5717-
auto *operand = tgt_ir->refExprOperand();
5718-
bool lvalue = operand && !isAddrOf();
5719-
auto result =
5720-
ConvertIRFragment(lvalue && values.empty() ? *operand : tgt_ir->body,
5721-
bindings, expr, all_args, ctx);
5722-
if (tgt_ir->multi_statement) {
5723-
result = '{' + result + '}';
5757+
auto saved_borrowed_args = std::exchange(borrowed_args_, {});
5758+
auto outer_borrows = std::exchange(borrows_, false);
5759+
BorrowArgsForCall(expr, *tgt_ir, all_args);
5760+
bool place = false;
5761+
std::string result;
5762+
if (discards_ref) {
5763+
// The reference to the argument is not used.
5764+
result =
5765+
'{' + ConvertIRFragment(effect, bindings, expr, all_args, ctx) + '}';
5766+
} else if (base && ReturnsPointerToArg(all_args[base->n])) {
5767+
auto str = ConvertIRFragment(effect, bindings, expr, all_args, ctx);
5768+
std::string index;
5769+
if (operand->size() > 1) {
5770+
index = ConvertIRFragment(llvm::ArrayRef(*operand).drop_front(), bindings,
5771+
expr, all_args, ctx);
5772+
index = index.substr(1, index.size() - 2);
5773+
}
5774+
result = ConvertPointerToArg(all_args[base->n], index);
5775+
if (!str.empty()) {
5776+
result = std::format("{{ {} {} }}", str, result);
5777+
}
5778+
} else if (base && isAddrOf()) {
5779+
// A pointer to the place is a raw one.
5780+
auto &prefix = std::get<std::unique_ptr<TranslationRule::RefExprFragment>>(
5781+
tgt_ir->body.back())
5782+
->prefix;
5783+
result = std::format(
5784+
"{}{} {}", ConvertIRFragment(effect, bindings, expr, all_args, ctx),
5785+
prefix == "&mut" ? "&raw mut"
5786+
: prefix == "&" ? "&raw const"
5787+
: prefix,
5788+
ConvertIRFragment(*operand, bindings, expr, all_args, ctx));
5789+
if (!effect.empty()) {
5790+
result = '{' + result + '}';
5791+
}
5792+
} else {
5793+
place = operand && !isAddrOf() && !isVoid();
5794+
result = ConvertIRFragment(
5795+
place && values.empty() && effect.empty() ? *operand : tgt_ir->body,
5796+
bindings, expr, all_args, ctx);
5797+
if (tgt_ir->multi_statement) {
5798+
result = '{' + result + '}';
5799+
}
57245800
}
57255801
// The arguments borrowed through pointers are borrowed for the whole call.
57265802
for (auto &[place, name] : std::ranges::reverse_view(mut_borrows_)) {
57275803
result = std::format("{}.with_mut(|{}| {})", place, name, result);
57285804
}
57295805
mut_borrows_ = std::move(saved_borrows);
5730-
// A place is reached through a reference to it, out of the match, so that it
5731-
// can be assigned.
5806+
borrowed_args_ = std::move(saved_borrowed_args);
5807+
// A pointer that the rule returns doesn't need the borrows of its arguments,
5808+
// e.g., of the map that std::map::operator[] inserts into, which end with
5809+
// the block, unless it may point to a temporary, which would end too.
5810+
if (borrows_ && tgt_ir->return_type.is_pointer() &&
5811+
llvm::none_of(all_args,
5812+
[&](clang::Expr *arg) { return CreatesTemporary(arg); })) {
5813+
result = std::format("({{ {} }})", result);
5814+
borrows_ = false;
5815+
}
5816+
borrows_ |= outer_borrows;
57325817
if (!values.empty()) {
57335818
result =
57345819
std::format("match ({},) {{ ({},) => {{ {} }} }}",
57355820
llvm::join(values, ", "), llvm::join(names, ", "), result);
5736-
if (lvalue) {
5737-
result = std::format("(*{})", result);
5738-
}
5821+
}
5822+
// A place is reached through a reference to it, out of the match or the
5823+
// block that computes it, so that it can be assigned.
5824+
if (place && (!values.empty() || !effect.empty())) {
5825+
result = std::format("(*{})", result);
5826+
}
5827+
returned_place_ = place && base;
5828+
if (!effects.empty()) {
5829+
result = std::format("{{ {} {} }}", effects, result);
57395830
}
57405831
return result;
57415832
}
57425833

5834+
bool Converter::UsedOnce(const TranslationRule::ExprRule &rule, unsigned n) {
5835+
unsigned uses = 0;
5836+
TranslationRule::AnyFragment(rule.body, [&](const auto &frag) {
5837+
auto *ph = std::get_if<TranslationRule::PlaceholderFragment>(&frag);
5838+
if (ph && ph->n == n) {
5839+
uses += ph->conditional ? 2 : 1;
5840+
}
5841+
return false;
5842+
});
5843+
return uses == 1;
5844+
}
5845+
5846+
std::vector<bool>
5847+
Converter::ArgsToEvaluateFirst(clang::Expr *, const TranslationRule::ExprRule &,
5848+
llvm::ArrayRef<clang::Expr *> args,
5849+
const std::vector<bool> &) {
5850+
return std::vector<bool>(args.size());
5851+
}
5852+
5853+
bool Converter::ReturnsPointerToArg(clang::Expr *) { return false; }
5854+
5855+
std::string Converter::ConvertPointerToArg(clang::Expr *, std::string_view) {
5856+
llvm_unreachable("the reference to the argument is a place");
5857+
}
5858+
57435859
std::string Converter::ConvertIRFragment(
5744-
const std::vector<TranslationRule::BodyFragment> &fragments,
5860+
llvm::ArrayRef<TranslationRule::BodyFragment> fragments,
57455861
llvm::ArrayRef<clang::TemplateArgument> bindings, clang::Expr *expr,
57465862
llvm::ArrayRef<clang::Expr *> all_args, TempMaterializationCtx *ctx) {
57475863
using namespace TranslationRule;
@@ -5757,6 +5873,12 @@ std::string Converter::ConvertIRFragment(
57575873
auto arg_idx = ph->n;
57585874
assert(arg_idx < all_args.size());
57595875
auto *arg = all_args[arg_idx];
5876+
// The argument is borrowed for the whole call.
5877+
if (auto it = borrowed_args_.find(arg); it != borrowed_args_.end()) {
5878+
result += std::format("(*{})", it->second);
5879+
MarkNotFresh();
5880+
continue;
5881+
}
57605882
bool is_receiver = HasReceiver(expr) && arg_idx == 0;
57615883
bool cpp_ptr = arg->getType()->isPointerType();
57625884
bool is_cpp_ptr =

‎cpp2rust/converter/converter.h‎

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -312,7 +312,7 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
312312

313313
// args are the arguments of expr, including its receiver.
314314
std::string
315-
ConvertIRFragment(const std::vector<TranslationRule::BodyFragment> &fragments,
315+
ConvertIRFragment(llvm::ArrayRef<TranslationRule::BodyFragment> fragments,
316316
llvm::ArrayRef<clang::TemplateArgument> bindings,
317317
clang::Expr *expr, llvm::ArrayRef<clang::Expr *> args,
318318
TempMaterializationCtx *ctx);
@@ -926,6 +926,12 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
926926
// through, with the names they are borrowed as, e.g., a pointer and the
927927
// closure parameter of its with_mut.
928928
std::vector<std::pair<std::string, std::string>> mut_borrows_;
929+
// Whether the last rule converted returned a place, rather than a pointer,
930+
// for a reference.
931+
bool returned_place_ = false;
932+
// The arguments of the rule being converted that are borrowed for the whole
933+
// call, with the names they are borrowed as.
934+
std::unordered_map<const clang::Expr *, std::string> borrowed_args_;
929935

930936
// Whether the expression being converted borrows a value in a temporary,
931937
// e.g., a guard of a RefCell, which lives until the end of the statement.
@@ -934,6 +940,12 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
934940
// The variables that arguments of rules are bound to by value, whose
935941
// address is not taken.
936942
std::unordered_set<const clang::VarDecl *> bound_values_;
943+
// The variables bound to values, or pointers, that are moved into the body
944+
// of a rule.
945+
std::unordered_set<const clang::VarDecl *> moved_values_;
946+
947+
// Whether the body of rule evaluates argument n once.
948+
static bool UsedOnce(const TranslationRule::ExprRule &rule, unsigned n);
937949

938950
// Bound initializer arguments may need a mapped move constructor when
939951
// forwarding the original rvalue from its pointer binding.
@@ -959,6 +971,28 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
959971
virtual void ConvertConstructedValue(clang::QualType type,
960972
clang::CXXConstructExpr *ctor);
961973

974+
// The arguments of a rule to evaluate before its body, besides those bound
975+
// by argsToBind, e.g., so that they are not evaluated while the body
976+
// borrows another argument.
977+
virtual std::vector<bool>
978+
ArgsToEvaluateFirst(clang::Expr *expr, const TranslationRule::ExprRule &rule,
979+
llvm::ArrayRef<clang::Expr *> args,
980+
const std::vector<bool> &bind);
981+
982+
// Borrows the arguments that the body of a rule borrows mutably and uses
983+
// more than once for the whole call, rather than once for each use.
984+
virtual void BorrowArgsForCall(clang::Expr *expr,
985+
const TranslationRule::ExprRule &rule,
986+
llvm::ArrayRef<clang::Expr *> args) {}
987+
988+
// Whether the reference that a rule returns to arg, or to an element of it,
989+
// is made a pointer to it, rather than a place.
990+
virtual bool ReturnsPointerToArg(clang::Expr *arg);
991+
992+
// A pointer to arg, or to its element at index, unless that is empty.
993+
virtual std::string ConvertPointerToArg(clang::Expr *arg,
994+
std::string_view index);
995+
962996
virtual std::string ConvertMappedMethodCall(
963997
clang::Expr *expr, const TranslationRule::MethodCallFragment &mc,
964998
llvm::ArrayRef<clang::TemplateArgument> bindings,

‎cpp2rust/converter/converter_lib.cpp‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2484,7 +2484,12 @@ bool IsTransparentStdCall(clang::ASTContext &ctx, const clang::CallExpr *expr) {
24842484
clang::isa<clang::CXXMemberCallExpr>(expr) || expr->getNumArgs() == 0) {
24852485
return false;
24862486
}
2487-
auto *ph = std::get_if<TranslationRule::PlaceholderFragment>(&rule->body[0]);
2487+
// The rule returns its argument, or a reference to it.
2488+
auto *operand = rule->refExprOperand();
2489+
auto &body = operand ? *operand : rule->body;
2490+
auto *ph = body.size() == 1
2491+
? std::get_if<TranslationRule::PlaceholderFragment>(&body[0])
2492+
: nullptr;
24882493
return ph && ph->n == 0 &&
24892494
ctx.hasSameUnqualifiedType(expr->getArg(0)->getType(),
24902495
expr->getType());

‎cpp2rust/converter/models/boxed_vars.cpp‎

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -310,6 +310,9 @@ class AddressTakenVisitor
310310
void VisitCallExpr(const clang::CallExpr *expr) {
311311
if (IsTransparentStdCall(owner_.ctx_, expr)) {
312312
Traverse(expr->getArg(0));
313+
} else if (auto *arg =
314+
RuleRegistry::GetReferencedArg(owner_.ctx_, expr)) {
315+
Traverse(arg);
313316
} else {
314317
VisitExpr(expr);
315318
}
@@ -356,6 +359,9 @@ class AddressTakenVisitor
356359
}
357360
auto all_args = BuildUnifiedArgs(expr, args, num_args);
358361
auto bound = rule->argsToBind(ctx_, expr, all_args);
362+
// The use of the argument that the rule returns a reference to is that of
363+
// the reference.
364+
auto *referenced = RuleRegistry::GetReferencedArg(ctx_, expr);
359365
for (unsigned i = 0; i < all_args.size(); ++i) {
360366
if (bound[i]) {
361367
if (all_args[i]->isGLValue()) {
@@ -385,8 +391,9 @@ class AddressTakenVisitor
385391
})) {
386392
continue;
387393
}
388-
if (!rule->takesAddress(ctx_, expr, i, arg) ||
389-
rule->takesTemporaryAddress(ctx_, expr, i, arg)) {
394+
if (all_args[i] != referenced &&
395+
(!rule->takesAddress(ctx_, expr, i, arg) ||
396+
rule->takesTemporaryAddress(ctx_, expr, i, arg))) {
390397
AddValueUse(arg);
391398
}
392399
}
@@ -414,6 +421,17 @@ class AddressTakenVisitor
414421
} else if (auto *assign = clang::dyn_cast<clang::BinaryOperator>(expr);
415422
assign && assign->isAssignmentOp() && !write) {
416423
AddValueUse(assign->getLHS(), /*write=*/true);
424+
} else if (bool element; auto *arg = RuleRegistry::GetReferencedArg(
425+
ctx_, expr, &element)) {
426+
// The reference that a rule returns to its argument, or to an element
427+
// of it, is the argument, or the element of it, in place.
428+
auto *call = clang::cast<clang::CallExpr>(expr);
429+
if (!write || !element ||
430+
llvm::none_of(call->arguments(), [&](const clang::Expr *other) {
431+
return other != arg && ReferToCommonVar(arg, other);
432+
})) {
433+
AddValueUse(arg, write);
434+
}
417435
} else if (auto *object = GetEnclosingObject(expr)) {
418436
// Rust doesn't let the index of an element that is written to read the
419437
// vector, as the vector is borrowed mutably first.
@@ -436,6 +454,8 @@ class AddressTakenVisitor
436454
if (auto *op = clang::dyn_cast<clang::UnaryOperator>(expr);
437455
op && op->isIncrementDecrementOp()) {
438456
AddValueUse(op->getSubExpr(), /*write=*/true);
457+
} else if (RuleRegistry::GetReferencedArg(ctx_, expr)) {
458+
AddValueUse(expr);
439459
} else if (auto *comma = clang::dyn_cast<clang::BinaryOperator>(expr);
440460
comma && comma->getOpcode() == clang::BO_Comma) {
441461
AddDiscardedUse(comma->getRHS());

0 commit comments

Comments
 (0)