Skip to content

Commit 01d5704

Browse files
committed
Merge branch 'master' into 55-mapped-reference-fields
2 parents 8878d57 + 0bef2dc commit 01d5704

110 files changed

Lines changed: 1300 additions & 269 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: 40 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2510,6 +2510,18 @@ bool Converter::VisitSourceLocExpr(clang::SourceLocExpr *expr) {
25102510
}
25112511
}
25122512

2513+
std::string Converter::GetCharArrayLiteral(const clang::StringLiteral *expr) {
2514+
std::string out = "(&[";
2515+
for (char c : expr->getString()) {
2516+
auto value = CharRustTypeIsSigned()
2517+
? std::to_string(static_cast<signed char>(c))
2518+
: std::to_string(static_cast<unsigned char>(c));
2519+
out += getTypedLiteral(value.c_str(), CharRustType()) + ", ";
2520+
}
2521+
out += getTypedLiteral("0", CharRustType()) + "])";
2522+
return out;
2523+
}
2524+
25132525
bool Converter::VisitStringLiteral(clang::StringLiteral *expr) {
25142526
if (IsCodeUnitStringLiteral(expr)) {
25152527
EmitFresh(GetCodeUnitArrayLiteral(expr));
@@ -2538,19 +2550,18 @@ bool Converter::VisitStringLiteral(clang::StringLiteral *expr) {
25382550
GetEscapedStringLiteral(expr, 1)));
25392551
return false;
25402552
}
2553+
std::string literal;
25412554
if (expr->getString().contains('\0')) {
2542-
std::string out = "(&[";
2543-
for (char c : expr->getString()) {
2544-
auto value = CharRustTypeIsSigned()
2545-
? std::to_string(static_cast<signed char>(c))
2546-
: std::to_string(static_cast<unsigned char>(c));
2547-
out += getTypedLiteral(value.c_str(), CharRustType()) + ", ";
2548-
}
2549-
out += getTypedLiteral("0", CharRustType()) + "])";
2550-
EmitFresh(out);
2551-
return false;
2555+
literal = GetCharArrayLiteral(expr);
2556+
} else {
2557+
literal = std::format("c{}", GetEscapedStringLiteral(expr, 0));
2558+
}
2559+
// A pointer to the array.
2560+
if (isAddrOf()) {
2561+
literal = std::format("{}.as_ptr().cast::<{}>()", literal,
2562+
ToString(expr->getType()));
25522563
}
2553-
EmitFresh(std::format("c{}", GetEscapedStringLiteral(expr, 0)));
2564+
EmitFresh(literal);
25542565
return false;
25552566
}
25562567

@@ -3136,6 +3147,11 @@ bool Converter::ConvertIncAndDec(clang::UnaryOperator *expr) {
31363147
MarkFresh();
31373148
return true;
31383149
}
3150+
bool deref_prefix = expr->isPrefix() && !isVoid();
3151+
PushParen paren(*this, deref_prefix);
3152+
if (deref_prefix) {
3153+
StrCat(token::kStar);
3154+
}
31393155
{
31403156
PushExprKind push(*this, ExprKind::LValue);
31413157
Convert(expr->getSubExpr());
@@ -5404,6 +5420,14 @@ std::string Converter::ConvertPlaceholder(clang::Expr *expr, clang::Expr *arg,
54045420
return std::move(buf).str();
54055421
}
54065422

5423+
if (auto *literal = clang::dyn_cast<clang::StringLiteral>(
5424+
arg->IgnoreParens()->IgnoreImplicit());
5425+
literal && arg->getType()->isArrayType() &&
5426+
!IsCodeUnitStringLiteral(literal)) {
5427+
MarkFresh();
5428+
return GetCharArrayLiteral(literal);
5429+
}
5430+
54075431
if (ph_ctx.needs_materialization()) {
54085432
auto materialized = ph_ctx.materialize_ctx->GetOrMaterialize(
54095433
static_cast<unsigned>(ph_ctx.materialize_idx),
@@ -5688,7 +5712,9 @@ std::string Converter::ConvertIRFragment(
56885712
assert(arg_idx < all_args.size());
56895713
auto *arg = all_args[arg_idx];
56905714
bool is_receiver = HasReceiver(expr) && arg_idx == 0;
5691-
bool is_cpp_ptr = arg->getType()->isPointerType();
5715+
bool cpp_ptr = arg->getType()->isPointerType();
5716+
bool is_cpp_ptr =
5717+
cpp_ptr && RuleRegistry::ParamTakesPointerValue(expr, arg_idx);
56925718

56935719
PlaceholderCtx ph_ctx{
56945720
.arg_idx = arg_idx,
@@ -5701,9 +5727,8 @@ std::string Converter::ConvertIRFragment(
57015727
.is_cpp_ptr = is_cpp_ptr,
57025728
// Whatever its spelling, a pointer in C++ is converted as one.
57035729
.maps_to_rust_ptr =
5704-
!is_cpp_ptr &&
5705-
RuleRegistry::MapsToPointer(
5706-
ctx_, arg->IgnoreParenNoopCasts(ctx_)->getType()),
5730+
!cpp_ptr && RuleRegistry::MapsToPointer(
5731+
ctx_, arg->IgnoreParenNoopCasts(ctx_)->getType()),
57075732
.declared_in_rule_as_rust_ptr =
57085733
RuleRegistry::ParamIsPointer(ctx_, expr, arg_idx),
57095734
.is_index_base = ph->is_index_base,

‎cpp2rust/converter/converter.h‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -494,6 +494,9 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
494494
virtual bool VisitCharacterLiteral(clang::CharacterLiteral *expr);
495495

496496
std::string GetCodeUnitArrayLiteral(const clang::StringLiteral *expr);
497+
498+
std::string GetCharArrayLiteral(const clang::StringLiteral *expr);
499+
497500
bool IsArrayInitContext() const;
498501

499502
std::string GetEscapedUTF8CharLiteral(clang::Expr *expr) const;

‎cpp2rust/converter/converter_lib.cpp‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2623,7 +2623,9 @@ void ReplaceAll(std::string &str, std::string_view from, std::string_view to) {
26232623
}
26242624

26252625
const char *GetConstCastSuffix(clang::QualType to, clang::QualType from) {
2626-
if (to.isConstQualified() == from.isConstQualified()) {
2626+
if (to.isConstQualified() == from.isConstQualified() ||
2627+
to.getCanonicalType().getUnqualifiedType() !=
2628+
from.getCanonicalType().getUnqualifiedType()) {
26272629
return nullptr;
26282630
}
26292631
return to.isConstQualified() ? ".cast_const()" : ".cast_mut()";

‎cpp2rust/converter/models/boxed_vars.cpp‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,8 @@ class AddressTakenVisitor
255255
}
256256

257257
bool VisitUnaryOperator(clang::UnaryOperator *expr) {
258-
if (expr->isIncrementDecrementOp()) {
258+
if (expr->isIncrementDecrementOp() &&
259+
(expr->isPostfix() || expr->isPRValue())) {
259260
AddValueUse(expr->getSubExpr(), /*write=*/true);
260261
}
261262
return true;
@@ -344,7 +345,7 @@ class AddressTakenVisitor
344345
// borrowed, unless the rule takes a pointer to them, other than to a
345346
// temporary copy of them, or they are bound to references. A pointer
346347
// parameter receives the value of an argument that is itself translated to a
347-
// pointer.
348+
// pointer, unless the rule binds a reference to that argument.
348349
void AddRuleArgs(clang::Expr *expr, clang::Expr **args, unsigned num_args) {
349350
auto *rule = RuleRegistry::GetExprRule(ctx_, expr);
350351
if (!rule) {
@@ -392,6 +393,11 @@ class AddressTakenVisitor
392393
// without making a pointer to it.
393394
void AddValueUse(const clang::Expr *expr, bool write = false) {
394395
expr = IgnoreNoOpCasts(IgnoreTransparentStdCall(expr)->IgnoreParens());
396+
if (auto *op = clang::dyn_cast<clang::UnaryOperator>(expr);
397+
op && op->isPrefix() && op->isIncrementDecrementOp()) {
398+
AddValueUse(op->getSubExpr(), /*write=*/true);
399+
return;
400+
}
395401
// The value of a conditional lvalue is the value of either operand; it is
396402
// written through a pointer to the operand.
397403
if (auto *cond = clang::dyn_cast<clang::ConditionalOperator>(expr)) {
@@ -423,6 +429,14 @@ class AddressTakenVisitor
423429
if (auto *cleanups = clang::dyn_cast<clang::ExprWithCleanups>(expr)) {
424430
expr = cleanups->getSubExpr()->IgnoreParens();
425431
}
432+
if (auto *op = clang::dyn_cast<clang::UnaryOperator>(expr);
433+
op && op->isIncrementDecrementOp()) {
434+
AddValueUse(op->getSubExpr(), /*write=*/true);
435+
} else if (auto *comma = clang::dyn_cast<clang::BinaryOperator>(expr);
436+
comma && comma->getOpcode() == clang::BO_Comma) {
437+
AddDiscardedUse(comma->getRHS());
438+
}
439+
426440
auto *binary = clang::dyn_cast<clang::BinaryOperator>(expr);
427441
if (!binary) {
428442
return;

‎cpp2rust/converter/models/converter_refcount.cpp‎

Lines changed: 40 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -433,6 +433,9 @@ bool ConverterRefCount::ParamIsElementPtr(clang::Expr *expr, clang::Expr *arg,
433433
}
434434

435435
std::string ConverterRefCount::ConvertElementPtr(clang::Expr *arg) {
436+
if (IsStringLiteralExpr(arg)) {
437+
return ConvertStringLiteralPtr(arg);
438+
}
436439
return ConvertObject(arg, ObjectShape::Element);
437440
}
438441

@@ -925,22 +928,51 @@ bool ConverterRefCount::ConvertIncAndDec(clang::UnaryOperator *expr) {
925928
if (expr->isPrefix() && isAddrOf()) {
926929
auto ptr = ConvertFreshObject(sub_expr);
927930
auto name = NewTempName();
928-
StrCat(
929-
std::format("{{ let {0} = {1}; {0}.with_mut(|__v| __v.{2}()); {0} }}",
930-
name, ptr, method));
931+
StrCat(std::format(
932+
"{{ let {0} = {1}; {0}.with_mut(|__v| {{ __v.{2}(); }}); {0} }}", name,
933+
ptr, method));
931934
MarkFresh();
932935
return true;
933936
}
934937

938+
bool is_prefix = expr->isPrefix();
935939
auto str = ConvertLValue(sub_expr);
936940
if (!pending_deref_.empty()) {
937-
StrCat(pending_deref_.take(), ".with_mut(|__v| __v.", method, "())");
941+
bool fresh = pending_deref_.is_fresh();
942+
auto ptr = pending_deref_.take();
943+
if (!is_prefix) {
944+
StrCat(ptr, ".with_mut(|__v| __v.", method, "())");
945+
} else if (isVoid()) {
946+
StrCat(ptr, ".with_mut(|__v| { __v.", method, "(); })");
947+
} else if (isLValue()) {
948+
auto name = NewTempName();
949+
pending_deref_.set(std::format("{{ let {0} = {1}{2}; {0}.with_mut(|__v| "
950+
"{{ __v.{3}(); }}); {0} }}",
951+
name, ptr, fresh ? "" : ".clone()",
952+
method),
953+
/*fresh=*/true);
954+
return true;
955+
} else {
956+
StrCat(ptr, ".with_mut(|__v| __v.", method, "().clone())");
957+
}
938958
} else if (!isVoid() &&
939959
clang::isa<clang::MemberExpr>(sub_expr->IgnoreParens()) &&
940960
!IsUnboxedPlace(sub_expr)) {
941961
// The struct is borrowed in a block, which ends the borrow before the
942962
// result is used, e.g., to write through a pointer into the struct.
943-
StrCat(std::format("{{ {}.{}() }}", str, method));
963+
if (!is_prefix) {
964+
StrCat(std::format("{{ {}.{}() }}", str, method));
965+
} else if (isLValue()) {
966+
StrCat(std::format("(*{}.{}())", str, method));
967+
} else {
968+
StrCat(std::format("{{ {}.{}().clone() }}", str, method));
969+
}
970+
} else if (is_prefix && !isVoid()) {
971+
StrCat(std::format("(*{}.{}())", str, method));
972+
if (!isLValue()) {
973+
SetValueFreshness(expr->getType());
974+
return true;
975+
}
944976
} else {
945977
StrCat(str, '.', method, "()");
946978
}
@@ -1547,9 +1579,9 @@ bool ConverterRefCount::VisitExplicitCastExpr(clang::ExplicitCastExpr *expr) {
15471579
case clang::Stmt::CXXReinterpretCastExprClass:
15481580
assert(expr->getType()->isPointerType() &&
15491581
"Only pointer casts are supported in reinterpret_cast");
1550-
EmitFresh(
1551-
std::format("{}.reinterpret_cast::<{}>()", ToString(expr->getSubExpr()),
1552-
GetUnsafeTypeAsString(expr->getType()->getPointeeType())));
1582+
EmitFresh(std::format("{}.reinterpret_cast::<{}>()",
1583+
ToString(expr->getSubExpr()),
1584+
ConvertPointeeType(expr->getType())));
15531585
return false;
15541586
case clang::Stmt::CStyleCastExprClass:
15551587
case clang::Stmt::CXXStaticCastExprClass:

‎cpp2rust/converter/rules/registry.cpp‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -571,6 +571,24 @@ bool ParamIsPointer(clang::ASTContext &ctx, const clang::Expr *expr,
571571
return param.is_pointer() || BindsGenericToReference(param, bindings);
572572
}
573573

574+
bool ParamTakesPointerValue(const clang::Expr *expr, unsigned index) {
575+
if (HasReceiver(const_cast<clang::Expr *>(expr)) && index == 0) {
576+
return true;
577+
}
578+
auto match = findExpr(expr);
579+
assert(match.rule_decl && "expression must have a translation rule");
580+
auto decl = match.rule_decl->decl;
581+
auto function = decl->getAsFunction();
582+
auto type =
583+
function ? function->getType()
584+
: llvm::cast<clang::VarDecl>(decl)->getType()->getPointeeType();
585+
auto proto = type->getAs<clang::FunctionProtoType>();
586+
assert(proto && "expression rule is neither a function nor a function "
587+
"pointer");
588+
return index >= proto->getNumParams() ||
589+
!proto->getParamType(index)->isReferenceType();
590+
}
591+
574592
clang::Expr *BuildParamConversion(clang::ASTContext &ctx,
575593
const clang::Expr *expr, unsigned index,
576594
clang::Expr *arg) {

‎cpp2rust/converter/rules/registry.h‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,8 @@ bool ReturnsReference(const clang::Expr *expr);
5757
bool ParamIsPointer(clang::ASTContext &ctx, const clang::Expr *expr,
5858
unsigned index);
5959

60+
bool ParamTakesPointerValue(const clang::Expr *expr, unsigned index);
61+
6062
clang::Expr *BuildParamConversion(clang::ASTContext &ctx,
6163
const clang::Expr *expr, unsigned index,
6264
clang::Expr *arg);

‎cpp2rust/converter/translation_rule.cpp‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -270,14 +270,16 @@ std::vector<bool>
270270
ExprRule::argsToBind(clang::ASTContext &ctx, const clang::Expr *expr,
271271
llvm::ArrayRef<clang::Expr *> args) const {
272272
// The number of evaluations of each argument, two standing for any other
273-
// than one, and the position of the first.
274-
std::vector<unsigned> uses(args.size()), first(args.size());
273+
// than one, the position of the first, and the number of placeholders.
274+
std::vector<unsigned> uses(args.size()), first(args.size()),
275+
copies(args.size());
275276
unsigned position = 0;
276277
AnyFragment(body, [&](const BodyFragment &frag) {
277278
if (auto *ph = std::get_if<PlaceholderFragment>(&frag)) {
278279
if (uses[ph->n]++ == 0) {
279280
first[ph->n] = position;
280281
}
282+
++copies[ph->n];
281283
if (ph->conditional) {
282284
++uses[ph->n];
283285
}
@@ -329,6 +331,11 @@ ExprRule::argsToBind(clang::ASTContext &ctx, const clang::Expr *expr,
329331
// A value computed from others is not computed again, nor before the
330332
// side effects of the previous arguments.
331333
bind[i] = bind_rest = true;
334+
} else if (copies[i] > 1 &&
335+
clang::isa<clang::StringLiteral>(arg->IgnoreParens())) {
336+
// A string literal is one object, but each of its translations is a
337+
// new array.
338+
bind[i] = true;
332339
}
333340
}
334341
return bind;
@@ -340,6 +347,12 @@ bool ExprRule::takesAddress(clang::ASTContext &ctx, const clang::Expr *expr,
340347
if (i >= params.size()) {
341348
return usesInit();
342349
}
350+
if (!params[i].is_pointer()) {
351+
return false;
352+
}
353+
if (arg->getType()->isPointerType()) {
354+
return !RuleRegistry::ParamTakesPointerValue(expr, i);
355+
}
343356
return RuleRegistry::ParamIsPointer(ctx, expr, i) &&
344357
!arg->getType()->isPointerType() &&
345358
!RuleRegistry::MapsToPointer(ctx, arg->getType());

‎cpp2rust/converter/translation_rule.h‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -139,8 +139,8 @@ struct ExprRule {
139139
std::vector<bool> argsToBind(clang::ASTContext &ctx, const clang::Expr *expr,
140140
llvm::ArrayRef<clang::Expr *> args) const;
141141

142-
// Whether the body takes a pointer to arg, its argument i, which is not a
143-
// pointer.
142+
// Whether the body takes a pointer to arg, argument i of expr, rather than
143+
// its value.
144144
bool takesAddress(clang::ASTContext &ctx, const clang::Expr *expr, unsigned i,
145145
const clang::Expr *arg) const;
146146

‎docs/src/runtime/inc-dec.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,14 @@ statement, so the `inc` and `dec` modules define one trait per operator form:
66

77
```rust
88
pub trait PostfixInc { fn postfix_inc(&mut self) -> Self; }
9-
pub trait PrefixInc { fn prefix_inc(&mut self) -> Self; }
9+
pub trait PrefixInc { fn prefix_inc(&mut self) -> &mut Self; }
1010
pub trait PostfixDec { fn postfix_dec(&mut self) -> Self; }
11-
pub trait PrefixDec { fn prefix_dec(&mut self) -> Self; }
11+
pub trait PrefixDec { fn prefix_dec(&mut self) -> &mut Self; }
1212
```
1313

1414
Each method updates the value in place and returns what the C expression
1515
evaluates to: the postfix forms return a copy of the old value, the prefix forms
16-
the new one.
16+
a mutable reference to the updated operand, which is an lvalue in C++.
1717

1818
```c
1919
int x = 0;

0 commit comments

Comments
 (0)