From 15854cd511dab8e34b80369bdc9f76d94036a299 Mon Sep 17 00:00:00 2001 From: Lucian Popescu Date: Sat, 5 Dec 2026 00:30:51 +0000 Subject: [PATCH 1/4] Build record prvalues into the storage offered by their parent --- cpp2rust/converter/converter.cpp | 172 ++++++++++-------- cpp2rust/converter/converter.h | 36 ++-- cpp2rust/converter/converter_lib.cpp | 106 ++++++----- cpp2rust/converter/converter_lib.h | 19 +- cpp2rust/converter/models/boxed_vars.cpp | 6 +- .../converter/models/converter_refcount.cpp | 16 +- .../out/refcount/class.conv.ctor.rs | 21 +-- .../class.conv/out/unsafe/class.conv.ctor.rs | 16 +- .../unit/out/refcount/copy_move_defaulted.rs | 27 +-- .../out/refcount/destructor_temporaries.rs | 28 +-- .../refcount/structured_binding_copy_ctor.rs | 15 +- .../structured_binding_element_ctor.rs | 50 +++-- .../refcount/structured_binding_move_ctor.rs | 15 +- tests/unit/out/refcount/this.rs | 6 +- tests/unit/out/unsafe/copy_move_defaulted.rs | 38 ++-- .../unit/out/unsafe/destructor_temporaries.rs | 28 +-- .../unsafe/structured_binding_copy_ctor.rs | 17 +- .../unsafe/structured_binding_element_ctor.rs | 50 +++-- .../unsafe/structured_binding_move_ctor.rs | 17 +- tests/unit/out/unsafe/this.rs | 6 +- 20 files changed, 354 insertions(+), 335 deletions(-) diff --git a/cpp2rust/converter/converter.cpp b/cpp2rust/converter/converter.cpp index fa688b9c02..d1e3f34d53 100644 --- a/cpp2rust/converter/converter.cpp +++ b/cpp2rust/converter/converter.cpp @@ -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; } @@ -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()); @@ -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; @@ -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"); @@ -2065,9 +2065,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(init), + GetPlacementReceiver(name)); + construct = std::format("{};", std::move(buf).str()); + } if (!declarations) { return storage + construct; } @@ -2346,19 +2350,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)) { @@ -4819,16 +4811,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( @@ -4903,18 +4893,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 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; @@ -4943,7 +4937,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) { @@ -4961,55 +4955,90 @@ 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(decl) || - !CanConstructVarInPlace(decl)) { - return nullptr; +void Converter::ConvertIntoStorage(clang::Expr *expr, std::string receiver, + std::optional *object_tail) { + if (IsStorageProducer(expr)) { + PushExprKind push(*this, ExprKind::Void); + ScopedValue in_place(in_place_, {expr, std::move(receiver), object_tail}); + Convert(expr); + return; + } + if (auto *wrapped = GetStorageWrappedExpr(expr)) { + ConvertIntoStorage(const_cast(wrapped), std::move(receiver), + object_tail); + return; } - return GetPlacementInitializer(decl->getInit()); + if (auto *conditional = clang::dyn_cast(expr); + conditional && BuildsInStorage(conditional)) { + auto branch = [&](clang::Expr *branch_expr) { + PushBrace brace(*this); + ConvertIntoStorage(branch_expr, receiver); + StrCat(token::kSemiColon); + }; + StrCat(keyword::kIf); + ConvertIfCondition(conditional->getCond()); + branch(conditional->getTrueExpr()); + StrCat(keyword::kElse); + branch(conditional->getFalseExpr()); + return; + } + std::string value; + { + Buffer buf(*this); + PushExprKind push(*this, ExprKind::RValue); + ConvertVarInit(expr->getType(), expr); + value = std::move(buf).str(); + } + StrCat(std::format("({}).write({})", receiver, value)); } -void Converter::EmitLocalObject(clang::VarDecl *decl, - const clang::Expr *construct) { +bool Converter::ConvertInBlockStorage(clang::Expr *producer) { + assert(IsStorageProducer(producer)); + if (in_place_.expr == producer) { + return false; + } + 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) { auto name = GetNamedDeclAsString(decl); std::optional 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(construct) - ? const_cast(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)); } @@ -6348,6 +6377,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); @@ -6377,8 +6407,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); } } @@ -6842,6 +6871,7 @@ Converter::ConvertMoveConstruction(clang::Expr *arg) { return std::nullopt; } Buffer buf(*this); + PushExprKind push(*this, ExprKind::FreshRValue); Convert(init); return std::move(buf).str(); } diff --git a/cpp2rust/converter/converter.h b/cpp2rust/converter/converter.h index 44dbc79de1..ee59a99637 100644 --- a/cpp2rust/converter/converter.h +++ b/cpp2rust/converter/converter.h @@ -772,6 +772,9 @@ class Converter : public clang::RecursiveASTVisitor { virtual void ConvertArrayCXXConstructExpr(clang::CXXConstructExpr *expr); + // The construction of an element of the array that expr constructs. + clang::CXXConstructExpr *GetElementConstruct(clang::CXXConstructExpr *expr); + virtual bool VisitUnaryExprOrTypeTraitExpr(clang::UnaryExprOrTypeTraitExpr *expr); @@ -1302,10 +1305,9 @@ class Converter : public clang::RecursiveASTVisitor { // Owning temporaries needed by references bound before a rule expansion. std::string *full_expression_temporaries_ = nullptr; - // A construction that constructs its object in place, in the storage that - // receiver gives to the constructor. A local object also gets, in - // object_tail, the arguments of the object! macro after its name, if the - // constructor call is all that its construction emits. + // The storage, which receiver gives, offered to the producer expr. A local + // object also gets, in object_tail, the arguments of the object! macro after + // its name, if the constructor call is all that its construction emits. struct InPlaceConstruct { const clang::Expr *expr = nullptr; std::string receiver; @@ -1328,18 +1330,26 @@ class Converter : public clang::RecursiveASTVisitor { 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::Expr *construct, - std::string receiver); + // Converts init, which builds in storage, to a statement that builds its + // object in the storage that receiver gives. + void ConstructInPlace(clang::Expr *init, std::string receiver); + + // Converts expr, whose object is built in the storage that receiver gives, + // to the code that builds it there. + void ConvertIntoStorage(clang::Expr *expr, std::string receiver, + std::optional *object_tail = nullptr); + + // Converts producer, unless a parent offers storage to it, in a block that + // builds its object in a local storage and results in the object, unless it + // is discarded. Returns whether it converted producer. + bool ConvertInBlockStorage(clang::Expr *producer); - // The construction of decl by its initializer, if it can be done in the - // storage of decl. - const clang::Expr *GetInPlaceVarConstruct(clang::VarDecl *decl); + // Whether decl is constructed in its storage by its initializer. + bool ConstructsVarInPlace(clang::VarDecl *decl); - // Declares decl, which construct constructs in place, with the object! + // Declares decl, which its initializer builds in place, with the object! // macro, which also destroys it at the end of its scope. - void EmitLocalObject(clang::VarDecl *decl, const clang::Expr *construct); + void EmitLocalObject(clang::VarDecl *decl); bool retain_bound_temporaries_ = false; class HoistMaterializedTempBindings { Converter &c; diff --git a/cpp2rust/converter/converter_lib.cpp b/cpp2rust/converter/converter_lib.cpp index 88fc850a5f..dffa4e0717 100644 --- a/cpp2rust/converter/converter_lib.cpp +++ b/cpp2rust/converter/converter_lib.cpp @@ -1314,23 +1314,6 @@ bool IsPassThroughConstructor(const clang::CXXConstructorDecl *ctor) { IsRValueConvertingConstructor(ctor)); } -static const clang::Expr *IgnorePlacementWrappers(const clang::Expr *init) { - while (true) { - init = init->IgnoreParens(); - if (auto *cleanups = clang::dyn_cast(init)) { - init = cleanups->getSubExpr(); - } else if (auto *default_init = - clang::dyn_cast(init)) { - init = default_init->getExpr(); - } else if (auto *cast = clang::dyn_cast(init); - cast && cast->getCastKind() == clang::CK_ConstructorConversion) { - init = cast->getSubExpr(); - } else { - return init; - } - } -} - bool UsesReturnSlot(clang::QualType type) { auto *record = type->getAsCXXRecordDecl(); return record && record->hasDefinition() && IsUserDefinedDecl(record) && @@ -1346,48 +1329,79 @@ bool IsReturnSlotCall(const clang::Expr *expr) { return !callee || IsUserDefinedDecl(callee); } -const clang::Expr *GetPlacementInitializer(const clang::Expr *init) { - auto *call = IgnorePlacementWrappers(init); - if (auto *bind = clang::dyn_cast(call)) { - call = bind->getSubExpr(); +static bool IsStorageConstruct(const clang::Expr *expr) { + auto *construct = clang::dyn_cast(expr); + if (!construct || construct->isElidable() || + construct->getType()->isArrayType()) { + return false; + } + auto *ctor = construct->getConstructor(); + auto *parent = ctor->getParent(); + if (parent->isLambda() || !IsUserDefinedDecl(parent)) { + return false; + } + if (ctor->isCopyOrMoveConstructor()) { + return IsConvertibleCopyOrMoveConstructor(ctor); + } + return ctor->isUserProvided() || IsConvertibleDefaultConstructor(ctor); +} + +bool IsStorageProducer(const clang::Expr *expr) { + return IsStorageConstruct(expr) || IsReturnSlotCall(expr); +} + +const clang::Expr *GetStorageWrappedExpr(const clang::Expr *expr) { + if (auto *paren = clang::dyn_cast(expr)) { + return paren->getSubExpr(); + } + if (auto *cleanups = clang::dyn_cast(expr)) { + return cleanups->getSubExpr(); + } + if (auto *bind = clang::dyn_cast(expr)) { + return bind->getSubExpr(); + } + if (auto *default_init = clang::dyn_cast(expr)) { + return default_init->getExpr(); + } + if (auto *cast = clang::dyn_cast(expr); + cast && cast->getCastKind() == clang::CK_NoOp && cast->isPRValue()) { + return cast->getSubExpr(); + } + if (auto *cast = clang::dyn_cast(expr); + cast && cast->getCastKind() == clang::CK_ConstructorConversion) { + return cast->getSubExpr(); + } + return nullptr; +} + +bool BuildsInStorage(const clang::Expr *expr) { + if (IsStorageProducer(expr)) { + return true; + } + if (auto *wrapped = GetStorageWrappedExpr(expr)) { + return BuildsInStorage(wrapped); } - if (IsReturnSlotCall(call)) { - return call; + if (auto *conditional = clang::dyn_cast(expr); + conditional && conditional->isPRValue() && + conditional->getType()->isRecordType()) { + return BuildsInStorage(conditional->getTrueExpr()) || + BuildsInStorage(conditional->getFalseExpr()); } - return GetInPlaceConstruct(init); + return false; } const clang::Expr * GetTemporaryPlacementInitializer(const clang::ASTContext &ctx, const clang::Expr *temporary, clang::QualType type) { - auto *init = GetPlacementInitializer(temporary->IgnoreImplicit()); - if (!init || !ctx.hasSameUnqualifiedType(init->getType(), type)) { + auto *init = temporary->IgnoreImplicit(); + if (!BuildsInStorage(init) || + !ctx.hasSameUnqualifiedType(init->getType(), type)) { return nullptr; } return init; } -const clang::CXXConstructExpr *GetInPlaceConstruct(const clang::Expr *init) { - init = IgnorePlacementWrappers(init); - auto *construct = clang::dyn_cast(init); - if (!construct || construct->isElidable() || - construct->getType()->isArrayType()) { - return nullptr; - } - auto *ctor = construct->getConstructor(); - auto *parent = ctor->getParent(); - if (parent->isLambda() || !IsUserDefinedDecl(parent)) { - return nullptr; - } - if (ctor->isCopyOrMoveConstructor()) { - return IsConvertibleCopyOrMoveConstructor(ctor) ? construct : nullptr; - } - return ctor->isUserProvided() || IsConvertibleDefaultConstructor(ctor) - ? construct - : nullptr; -} - bool IsConvertibleCXXRecordDecl(const clang::CXXRecordDecl *decl) { return decl->isThisDeclarationADefinition() && !decl->isDependentContext() && !decl->isInvalidDecl(); diff --git a/cpp2rust/converter/converter_lib.h b/cpp2rust/converter/converter_lib.h index 51b08bcb1c..561a6e79fc 100644 --- a/cpp2rust/converter/converter_lib.h +++ b/cpp2rust/converter/converter_lib.h @@ -345,17 +345,24 @@ bool HasDefaultedCopyAssignment(const clang::RecordDecl *decl); bool IsRValueConvertingConstructor(const clang::CXXConstructorDecl *ctor); -// The call of a translated constructor that init, the initializer of an -// object, is. The constructor can construct the object in its storage, as it -// is translated to a function that receives the storage. -const clang::CXXConstructExpr *GetInPlaceConstruct(const clang::Expr *init); - bool UsesReturnSlot(clang::QualType type); bool IsReturnSlotCall(const clang::Expr *expr); -const clang::Expr *GetPlacementInitializer(const clang::Expr *init); +// Whether expr is a prvalue that is built only through a receiver of the +// storage of its object: the call of a translated constructor, or a call that +// returns its object through a return slot. +bool IsStorageProducer(const clang::Expr *expr); + +// The operand of expr, which only wraps it, whose object is the object of +// expr. +const clang::Expr *GetStorageWrappedExpr(const clang::Expr *expr); + +// Whether expr builds its object in the storage that its parent offers, by a +// producer that the nodes above it forward the storage to. +bool BuildsInStorage(const clang::Expr *expr); +// The initializer of temporary that builds it in its storage, if it has type. const clang::Expr * GetTemporaryPlacementInitializer(const clang::ASTContext &ctx, const clang::Expr *temporary, diff --git a/cpp2rust/converter/models/boxed_vars.cpp b/cpp2rust/converter/models/boxed_vars.cpp index a0d63e9b61..cae2f4e0f3 100644 --- a/cpp2rust/converter/models/boxed_vars.cpp +++ b/cpp2rust/converter/models/boxed_vars.cpp @@ -160,11 +160,11 @@ class AddressTakenVisitor bool TraverseDecltypeType(clang::DecltypeType *, bool) { return true; } - // A variable that a translated constructor constructs is passed to the - // constructor as `this`, which constructs it in place. + // A variable whose initializer builds it in its storage gives a pointer to + // the storage to the initializer. bool VisitVarDecl(clang::VarDecl *decl) { if (decl->isLocalVarDecl() && decl->hasInit() && - GetPlacementInitializer(decl->getInit())) { + BuildsInStorage(decl->getInit())) { AddressTaken(decl); } return true; diff --git a/cpp2rust/converter/models/converter_refcount.cpp b/cpp2rust/converter/models/converter_refcount.cpp index 3435b57a9b..614fc54c40 100644 --- a/cpp2rust/converter/models/converter_refcount.cpp +++ b/cpp2rust/converter/models/converter_refcount.cpp @@ -2038,15 +2038,13 @@ bool ConverterRefCount::VisitCXXNewExpr(clang::CXXNewExpr *expr) { array_size_as_string, default_alloc_type_as_string, alloc_type_as_string)); } - } 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 = Ptr::alloc(<{}>::zero_init());", - GetRecordName(construct->getType()->getAsCXXRecordDecl()))); - ConstructInPlace(expr->getInitializer(), construct, "__p.clone()"); + StrCat(std::format( + "let __p = Ptr::alloc(<{}>::zero_init());", + GetRecordName(expr->getAllocatedType()->getAsCXXRecordDecl()))); + ConstructInPlace(expr->getInitializer(), "__p.clone()"); StrCat("__p"); } else { StrCat("Ptr::alloc("); @@ -2104,7 +2102,7 @@ void ConverterRefCount::ConvertArrayCXXConstructExpr( PushParen inner(*this); StrCat("|_|"); PushConversionKind push(*this, ConversionKind::Unboxed); - ConvertCXXConstructExprArgs(expr); + Convert(GetElementConstruct(expr)); } std::string ConverterRefCount::ConvertStream(clang::Expr *expr) { diff --git a/tests/std/class/class.mem/class.conv/out/refcount/class.conv.ctor.rs b/tests/std/class/class.mem/class.conv/out/refcount/class.conv.ctor.rs index 7d5e62eabe..1c62fa4239 100644 --- a/tests/std/class/class.mem/class.conv/out/refcount/class.conv.ctor.rs +++ b/tests/std/class/class.mem/class.conv/out/refcount/class.conv.ctor.rs @@ -80,13 +80,11 @@ impl p1_implicit_conversion_by_constructor_Meters { } } pub fn test_1() { - let mut m: p1_implicit_conversion_by_constructor_Meters = { - let __v: Value = - Rc::new(RefCell::new(ZeroInitialization::zero_init())); - p1_implicit_conversion_by_constructor_Meters::constructor_1(__v.as_pointer(), 5); - Rc::try_unwrap(__v).ok().unwrap().into_inner() - }; - assert!((m.value == 5)); + object!( + m, + p1_implicit_conversion_by_constructor_Meters::constructor_1(5) + ); + assert!(({ (*m.borrow()).value } == 5)); let source: Value<(Value, Value)> = Rc::new(RefCell::new(( Rc::new(RefCell::new(3)), Rc::new(RefCell::new(4)), @@ -191,13 +189,8 @@ impl p2_explicit_constructor_Celsius { pub fn test_2() { object!(direct, p2_explicit_constructor_Celsius::constructor_1(3)); assert!(({ (*direct.borrow()).degrees } == 3)); - let mut cast: p2_explicit_constructor_Celsius = { - let __v: Value = - Rc::new(RefCell::new(ZeroInitialization::zero_init())); - p2_explicit_constructor_Celsius::constructor_1(__v.as_pointer(), 4); - Rc::try_unwrap(__v).ok().unwrap().into_inner() - }; - assert!((cast.degrees == 4)); + object!(cast, p2_explicit_constructor_Celsius::constructor_1(4)); + assert!(({ (*cast.borrow()).degrees } == 4)); let converted: Value<(Value, Value)> = Rc::new(RefCell::new( match (Rc::new(RefCell::new(( diff --git a/tests/std/class/class.mem/class.conv/out/unsafe/class.conv.ctor.rs b/tests/std/class/class.mem/class.conv/out/unsafe/class.conv.ctor.rs index ec44ca2f4a..5acf77c3dc 100644 --- a/tests/std/class/class.mem/class.conv/out/unsafe/class.conv.ctor.rs +++ b/tests/std/class/class.mem/class.conv/out/unsafe/class.conv.ctor.rs @@ -74,12 +74,10 @@ impl p1_implicit_conversion_by_constructor_Meters { } } pub unsafe fn test_1() { - let mut m: p1_implicit_conversion_by_constructor_Meters = { - let mut __v: p1_implicit_conversion_by_constructor_Meters = - ZeroInitializationUnsafe::zero_init(); - p1_implicit_conversion_by_constructor_Meters::constructor_1(&raw mut __v, 5); - __v - }; + object_unsafe!( + m, + p1_implicit_conversion_by_constructor_Meters::constructor_1(5) + ); assert!(((m.value) == (5))); let mut source: (i32, i32) = (3, 4); let mut copied: (p1_implicit_conversion_by_constructor_Meters, i64) = { @@ -149,11 +147,7 @@ impl p2_explicit_constructor_Celsius { pub unsafe fn test_2() { object_unsafe!(direct, p2_explicit_constructor_Celsius::constructor_1(3)); assert!(((direct.degrees) == (3))); - let mut cast: p2_explicit_constructor_Celsius = { - let mut __v: p2_explicit_constructor_Celsius = ZeroInitializationUnsafe::zero_init(); - p2_explicit_constructor_Celsius::constructor_1(&raw mut __v, 4); - __v - }; + object_unsafe!(cast, p2_explicit_constructor_Celsius::constructor_1(4)); assert!(((cast.degrees) == (4))); let mut converted: (p2_explicit_constructor_Celsius, i32) = match ((&mut (5, 6) as *mut (i32, i32)),) { diff --git a/tests/unit/out/refcount/copy_move_defaulted.rs b/tests/unit/out/refcount/copy_move_defaulted.rs index 99e7082ee2..d3aec9ca05 100644 --- a/tests/unit/out/refcount/copy_move_defaulted.rs +++ b/tests/unit/out/refcount/copy_move_defaulted.rs @@ -714,14 +714,15 @@ fn main_0() -> i32 { assert!(((l.v == 5) && (l.inner.x == 50)) && (l.arr[(0) as usize] == 5)); let vec_: Value> = Rc::new(RefCell::new(Vec::new())); CopyConstructible::push_copied(&vec_.as_pointer(), b.as_pointer()); - match (Rc::new(RefCell::new({ - let __v: Value = Rc::new(RefCell::new(ZeroInitialization::zero_init())); - Explicit::constructor_1(__v.as_pointer(), 9); - Rc::try_unwrap(__v).ok().unwrap().into_inner() - })) - .as_pointer(),) { - (__tmp_1,) => MoveConstructible::push_moved(&vec_.as_pointer(), (__tmp_1).clone()), + let __tmp_2: Value = Rc::new(RefCell::new(ZeroInitialization::zero_init())); + match ({ + Explicit::constructor_1(__tmp_2.as_pointer(), 9); + __tmp_2.as_pointer() + },) + { + (__tmp_1,) => MoveConstructible::push_moved(&vec_.as_pointer(), (__tmp_1).clone()), + } }; assert!(({ (*vec_.borrow())[0_usize].v } == 1) && ({ (*vec_.borrow())[1_usize].v } == 9)); object!(m, DefaultCopyUserMove::constructor_1(7)); @@ -796,7 +797,7 @@ fn main_0() -> i32 { let bufs: Value> = Rc::new(RefCell::new(Vec::new())); MoveConstructible::push_moved(&bufs.as_pointer(), r.as_pointer()); { - let mut __tmp_2 = { + let mut __tmp_3 = { { let __v: Value = Rc::new(RefCell::new(ZeroInitialization::zero_init())); ::move_constructor( @@ -806,7 +807,7 @@ fn main_0() -> i32 { Rc::try_unwrap(__v).ok().unwrap().into_inner() } }; - (*bufs.borrow_mut()).push(__tmp_2); + (*bufs.borrow_mut()).push(__tmp_3); }; assert!( ({ @@ -817,10 +818,10 @@ fn main_0() -> i32 { ); object!(o1, Owner::constructor_1()); ({ - let __tmp_3: Value = Rc::new(RefCell::new(5)); + let __tmp_4: Value = Rc::new(RefCell::new(5)); MoveConstructible::push_moved( &field_ref!(o1.as_pointer(), data).as_pointer(), - __tmp_3.as_pointer(), + __tmp_4.as_pointer(), ) }); (*o1.borrow_mut()).n = 5; @@ -986,10 +987,10 @@ fn main_0() -> i32 { object!(a3, OutOfLineAssign::constructor_1()); (*a1.borrow_mut()).v = 3; ({ - let __tmp_4: Value = Rc::new(RefCell::new(4)); + let __tmp_5: Value = Rc::new(RefCell::new(4)); MoveConstructible::push_moved( &field_ref!(a1.as_pointer(), w).as_pointer(), - __tmp_4.as_pointer(), + __tmp_5.as_pointer(), ) }); assign!(a2 = a1); diff --git a/tests/unit/out/refcount/destructor_temporaries.rs b/tests/unit/out/refcount/destructor_temporaries.rs index 191cf428b5..9e93451902 100644 --- a/tests/unit/out/refcount/destructor_temporaries.rs +++ b/tests/unit/out/refcount/destructor_temporaries.rs @@ -166,17 +166,17 @@ fn main_0() -> i32 { })); assert!((x == 3) && (destroyed_0.with(|rc| *rc.borrow()) == 2)); destroyed_0.with(|rc| *rc.borrow_mut() = 0); - x = { - (if (x == 3) { - { - let __v: Value = Rc::new(RefCell::new(ZeroInitialization::zero_init())); - ({ make_2(Ptr::clone(&__v.as_pointer()), 9) }); - Rc::try_unwrap(__v).ok().unwrap().into_inner() - } - } else { - S { v: 10 } - }) - .v + { + let __tmp_3: Value = Rc::new(RefCell::new(ZeroInitialization::zero_init())); + x = { + if (x == 3) { + ({ make_2(Ptr::clone(&__tmp_3.as_pointer()), 9) }); + } else { + (__tmp_3.as_pointer()).write(S { v: 10 }); + }; + __tmp_3.as_pointer() + } + .with(|__s| __s.v) }; assert!( ((x == 9) && (destroyed_0.with(|rc| *rc.borrow()) == 1)) @@ -184,9 +184,9 @@ fn main_0() -> i32 { ); destroyed_0.with(|rc| *rc.borrow_mut() = 0); { - let __tmp_3: Value = Rc::new(RefCell::new(ZeroInitialization::zero_init())); - ({ make_2(Ptr::clone(&__tmp_3.as_pointer()), 11) }); - let r: Ptr = __tmp_3.as_pointer(); + let __tmp_4: Value = Rc::new(RefCell::new(ZeroInitialization::zero_init())); + ({ make_2(Ptr::clone(&__tmp_4.as_pointer()), 11) }); + let r: Ptr = __tmp_4.as_pointer(); assert!((destroyed_0.with(|rc| *rc.borrow()) == 0) && (r.with(|__s| __s.v) == 11)); } assert!((destroyed_0.with(|rc| *rc.borrow()) == 1) && (last_1.with(|rc| *rc.borrow()) == 11)); diff --git a/tests/unit/out/refcount/structured_binding_copy_ctor.rs b/tests/unit/out/refcount/structured_binding_copy_ctor.rs index b015c29c02..1cf42c1327 100644 --- a/tests/unit/out/refcount/structured_binding_copy_ctor.rs +++ b/tests/unit/out/refcount/structured_binding_copy_ctor.rs @@ -55,11 +55,10 @@ pub fn main() { } fn main_0() -> i32 { object!(s, Counted::constructor_1(1, 2)); - let __decomp_2: Value = Rc::new(RefCell::new({ - let __v: Value = Rc::new(RefCell::new(ZeroInitialization::zero_init())); - Counted::constructor_2(__v.as_pointer(), LvalueRef::bind(s.as_pointer())); - Rc::try_unwrap(__v).ok().unwrap().into_inner() - })); + object!( + __decomp_2, + Counted::constructor_2(LvalueRef::bind(s.as_pointer())) + ); assert!((copies_0.with(|rc| *rc.borrow()) == 1)); assert!(({ (*__decomp_2.borrow()).x } == 2)); assert!(({ (*__decomp_2.borrow()).y } == 4)); @@ -70,10 +69,8 @@ fn main_0() -> i32 { let __decomp_4: Ptr = s.as_pointer(); assert!((copies_0.with(|rc| *rc.borrow()) == 1)); assert!((__decomp_4.with(|__s| __s.x) == 1)); - let __decomp_5: Value = Rc::new(RefCell::new({ - let __v: Value = Rc::new(RefCell::new(ZeroInitialization::zero_init())); - ({ make_counted_1(Ptr::clone(&__v.as_pointer())) }); - Rc::try_unwrap(__v).ok().unwrap().into_inner() + object!(__decomp_5, Counted, |__decomp_5| ({ + make_counted_1(Ptr::clone(&__decomp_5.clone())) })); assert!((copies_0.with(|rc| *rc.borrow()) == 1)); assert!(({ (*__decomp_5.borrow()).x } == 5)); diff --git a/tests/unit/out/refcount/structured_binding_element_ctor.rs b/tests/unit/out/refcount/structured_binding_element_ctor.rs index 2c555331a3..b3f731f495 100644 --- a/tests/unit/out/refcount/structured_binding_element_ctor.rs +++ b/tests/unit/out/refcount/structured_binding_element_ctor.rs @@ -90,14 +90,12 @@ fn main_0() -> i32 { })); let mut base_copies: i32 = copies_0.with(|rc| *rc.borrow()); let mut base_moves: i32 = moves_1.with(|rc| *rc.borrow()); - let __decomp_3: Value = Rc::new(RefCell::new({ - let __v: Value = Rc::new(RefCell::new(ZeroInitialization::zero_init())); + object!(__decomp_3, Two, |__decomp_3| { ::copy_constructor( - __v.as_pointer(), + __decomp_3.clone(), LvalueRef::bind(t.as_pointer()), - ); - Rc::try_unwrap(__v).ok().unwrap().into_inner() - })); + ) + }); assert!((copies_0.with(|rc| *rc.borrow()) == (base_copies + 2))); assert!((moves_1.with(|rc| *rc.borrow()) == base_moves)); assert!(({ (*__decomp_3.borrow()).a.v } == 101)); @@ -107,46 +105,42 @@ fn main_0() -> i32 { assert!(({ (*__decomp_4.upgrade().deref()).a.v } == 1)); field!(field!(__decomp_4, a), v).write(50); assert!(({ (*t.borrow()).a.v } == 50)); - let __decomp_5: Value = Rc::new(RefCell::new({ - let __v: Value = Rc::new(RefCell::new(ZeroInitialization::zero_init())); + object!(__decomp_5, Two, |__decomp_5| { ::move_constructor( - __v.as_pointer(), + __decomp_5.clone(), RvalueRef::bind(t.as_pointer()), - ); - Rc::try_unwrap(__v).ok().unwrap().into_inner() - })); + ) + }); assert!((moves_1.with(|rc| *rc.borrow()) == (base_moves + 2))); assert!(({ (*__decomp_5.borrow()).a.v } == 1050)); assert!(({ (*__decomp_5.borrow()).b.v } == 1002)); assert!(({ (*t.borrow()).a.v } == -1_i32)); let mut before_copies: i32 = copies_0.with(|rc| *rc.borrow()); let mut before_moves: i32 = moves_1.with(|rc| *rc.borrow()); - let __decomp_6: Value = Rc::new(RefCell::new({ - let __v: Value = Rc::new(RefCell::new(ZeroInitialization::zero_init())); - ({ make_two_2(Ptr::clone(&__v.as_pointer())) }); - Rc::try_unwrap(__v).ok().unwrap().into_inner() + object!(__decomp_6, Two, |__decomp_6| ({ + make_two_2(Ptr::clone(&__decomp_6.clone())) })); assert!((copies_0.with(|rc| *rc.borrow()) == before_copies)); assert!((moves_1.with(|rc| *rc.borrow()) == before_moves)); assert!(({ (*__decomp_6.borrow()).a.v } == 1)); let p: Value<(Value, Value)> = Rc::new(RefCell::new(( Rc::new(RefCell::new({ - let __tmp_0: Value = Rc::new(RefCell::new(ZeroInitialization::zero_init())); - Elem::constructor_1(__tmp_0.as_pointer(), 7); + let __v: Value = Rc::new(RefCell::new(ZeroInitialization::zero_init())); { - let __v: Value = Rc::new(RefCell::new(ZeroInitialization::zero_init())); - Elem::constructor_3(__v.as_pointer(), RvalueRef::bind(__tmp_0.as_pointer())); - Rc::try_unwrap(__v).ok().unwrap().into_inner() - } + let __tmp_0: Value = Rc::new(RefCell::new(ZeroInitialization::zero_init())); + Elem::constructor_1(__tmp_0.as_pointer(), 7); + Elem::constructor_3(__v.as_pointer(), RvalueRef::bind(__tmp_0.as_pointer())) + }; + Rc::try_unwrap(__v).ok().unwrap().into_inner() })), Rc::new(RefCell::new({ - let __tmp_1: Value = Rc::new(RefCell::new(ZeroInitialization::zero_init())); - Elem::constructor_1(__tmp_1.as_pointer(), 8); + let __v: Value = Rc::new(RefCell::new(ZeroInitialization::zero_init())); { - let __v: Value = Rc::new(RefCell::new(ZeroInitialization::zero_init())); - Elem::constructor_3(__v.as_pointer(), RvalueRef::bind(__tmp_1.as_pointer())); - Rc::try_unwrap(__v).ok().unwrap().into_inner() - } + let __tmp_1: Value = Rc::new(RefCell::new(ZeroInitialization::zero_init())); + Elem::constructor_1(__tmp_1.as_pointer(), 8); + Elem::constructor_3(__v.as_pointer(), RvalueRef::bind(__tmp_1.as_pointer())) + }; + Rc::try_unwrap(__v).ok().unwrap().into_inner() })), ))); before_copies = copies_0.with(|rc| *rc.borrow()); diff --git a/tests/unit/out/refcount/structured_binding_move_ctor.rs b/tests/unit/out/refcount/structured_binding_move_ctor.rs index f284322384..135ad91bf7 100644 --- a/tests/unit/out/refcount/structured_binding_move_ctor.rs +++ b/tests/unit/out/refcount/structured_binding_move_ctor.rs @@ -91,11 +91,10 @@ pub fn main() { } fn main_0() -> i32 { object!(m, Movable::constructor_1(3, 4)); - let __decomp_2: Value = Rc::new(RefCell::new({ - let __v: Value = Rc::new(RefCell::new(ZeroInitialization::zero_init())); - Movable::constructor_3(__v.as_pointer(), RvalueRef::bind(m.as_pointer())); - Rc::try_unwrap(__v).ok().unwrap().into_inner() - })); + object!( + __decomp_2, + Movable::constructor_3(RvalueRef::bind(m.as_pointer())) + ); assert!((moves_1.with(|rc| *rc.borrow()) == 1)); assert!((copies_0.with(|rc| *rc.borrow()) == 0)); assert!(({ (*__decomp_2.borrow()).x } == 3)); @@ -106,10 +105,8 @@ fn main_0() -> i32 { xs: Vec::from([1, 2, 3]), ys: Vec::from([4, 5]), })); - let __decomp_3: Value = Rc::new(RefCell::new({ - let __v: Value = Rc::new(RefCell::new(ZeroInitialization::zero_init())); - ({ Holder::extract(h.as_pointer(), Ptr::clone(&__v.as_pointer())) }); - Rc::try_unwrap(__v).ok().unwrap().into_inner() + object!(__decomp_3, Holder, |__decomp_3| ({ + Holder::extract(h.as_pointer(), Ptr::clone(&__decomp_3.clone())) })); assert!(({ ((*__decomp_3.borrow()).xs.len() == 3_usize) })); assert!(({ ((*__decomp_3.borrow()).ys.len() == 2_usize) })); diff --git a/tests/unit/out/refcount/this.rs b/tests/unit/out/refcount/this.rs index cf648bb3b7..d89df44815 100644 --- a/tests/unit/out/refcount/this.rs +++ b/tests/unit/out/refcount/this.rs @@ -207,11 +207,7 @@ fn main_0() -> i32 { assert!(({ { (*s.borrow()).self__.clone() } } == { { (*other.borrow()).self__.clone() } })); object!(u, S::constructor_2(1, Pointer::bind((s.as_pointer())))); assert!(({ { (*u.borrow()).self__.clone() } } == { (s.as_pointer()) })); - let s_const: Value = Rc::new(RefCell::new({ - let __v: Value = Rc::new(RefCell::new(ZeroInitialization::zero_init())); - S::constructor_1(__v.as_pointer(), 100); - Rc::try_unwrap(__v).ok().unwrap().into_inner() - })); + object!(s_const, S::constructor_1(100)); object!( u1, S::constructor_3(1, Pointer::bind((s_const.as_pointer()))) diff --git a/tests/unit/out/unsafe/copy_move_defaulted.rs b/tests/unit/out/unsafe/copy_move_defaulted.rs index c7a1b84532..f45491b01f 100644 --- a/tests/unit/out/unsafe/copy_move_defaulted.rs +++ b/tests/unit/out/unsafe/copy_move_defaulted.rs @@ -640,13 +640,15 @@ unsafe fn main_0() -> i32 { assert!((((l.v) == (5)) && ((l.inner.x) == (50))) && ((l.arr[(0) as usize]) == (5))); let mut vec_: Vec = Vec::new(); vec_.push_copied(&mut b); - match ((&mut { - let mut __v: Explicit = ZeroInitializationUnsafe::zero_init(); - Explicit::constructor_1(&raw mut __v, 9); - __v - } as *mut Explicit),) { - (__tmp_0,) => vec_.push_moved(__tmp_0), + let mut __tmp_1: Explicit = ZeroInitializationUnsafe::zero_init(); + match (({ + Explicit::constructor_1(&raw mut __tmp_1, 9); + &mut __tmp_1 + } as *mut Explicit),) + { + (__tmp_0,) => vec_.push_moved(__tmp_0), + } }; assert!(((vec_[(0_usize)].v) == (1)) && ((vec_[(1_usize)].v) == (9))); object_unsafe!(m, DefaultCopyUserMove::constructor_1(7)); @@ -699,7 +701,7 @@ unsafe fn main_0() -> i32 { let mut bufs: Vec = Vec::new(); bufs.push_moved(&mut r); { - let mut __tmp_1 = { + let mut __tmp_2 = { { let mut __v: Buffer = ZeroInitializationUnsafe::zero_init(); ::move_constructor( @@ -709,7 +711,7 @@ unsafe fn main_0() -> i32 { __v } }; - bufs.push_mut(__tmp_1) + bufs.push_mut(__tmp_2) }; assert!( (((bufs[(1_usize)].n) == (3)) && ((bufs[(1_usize)].data.len()) == (3_usize))) @@ -717,18 +719,18 @@ unsafe fn main_0() -> i32 { ); object_unsafe!(o1, Owner::constructor_1()); { - let mut __tmp_2: i32 = 5; - o1.data.push_moved(&mut __tmp_2) + let mut __tmp_3: i32 = 5; + o1.data.push_moved(&mut __tmp_3) }; o1.n = 5; o1.arr[(0) as usize] = 5; o1.arr[(1) as usize] = 6; { - let mut __tmp_3 = { (Box::leak(Box::new(7)) as *mut i32) }; - o1.p = if __tmp_3.is_null() { + let mut __tmp_4 = { (Box::leak(Box::new(7)) as *mut i32) }; + o1.p = if __tmp_4.is_null() { None } else { - Some(Box::from_raw(__tmp_3)) + Some(Box::from_raw(__tmp_4)) } }; object_unsafe!(o2, Owner, |o2| { @@ -782,11 +784,11 @@ unsafe fn main_0() -> i32 { assert!(((c4.data[(1_usize)]) == (2)) && (c3.data.is_empty())); object_unsafe!(h1, Holder::constructor_1(4)); { - let mut __tmp_4 = { (Box::leak(Box::new(9)) as *mut i32) }; - h1.p = if __tmp_4.is_null() { + let mut __tmp_5 = { (Box::leak(Box::new(9)) as *mut i32) }; + h1.p = if __tmp_5.is_null() { None } else { - Some(Box::from_raw(__tmp_4)) + Some(Box::from_raw(__tmp_5)) } }; object_unsafe!(h2, Holder, |h2| { @@ -893,8 +895,8 @@ unsafe fn main_0() -> i32 { object_unsafe!(a3, OutOfLineAssign::constructor_1()); a1.v = 3; { - let mut __tmp_5: i32 = 4; - a1.w.push_moved(&mut __tmp_5) + let mut __tmp_6: i32 = 4; + a1.w.push_moved(&mut __tmp_6) }; assign_unsafe!(a2 = a1); assert!((((a2.v) == (3)) && ((a2.w.len()) == (1_usize))) && ((a1.w.len()) == (1_usize))); diff --git a/tests/unit/out/unsafe/destructor_temporaries.rs b/tests/unit/out/unsafe/destructor_temporaries.rs index c49a623c5c..e8011983e4 100644 --- a/tests/unit/out/unsafe/destructor_temporaries.rs +++ b/tests/unit/out/unsafe/destructor_temporaries.rs @@ -165,25 +165,27 @@ unsafe fn main_0() -> i32 { })); assert!(((x) == (3)) && ((*std::cell::LazyCell::force_mut(&mut *&raw mut destroyed_0)) == (2))); (*std::cell::LazyCell::force_mut(&mut *&raw mut destroyed_0)) = 0; - x = (if ((x) == (3)) { - { - let mut __v: S = ZeroInitializationUnsafe::zero_init(); - (unsafe { make_2(&raw mut __v, 9) }); - __v - } - } else { - S { v: 10 } - }) - .v; + { + let mut __tmp_3: S = ZeroInitializationUnsafe::zero_init(); + x = (*{ + if ((x) == (3)) { + (unsafe { make_2(&raw mut __tmp_3, 9) }); + } else { + (&raw mut __tmp_3).write(S { v: 10 }); + }; + &mut __tmp_3 + }) + .v + }; assert!( (((x) == (9)) && ((*std::cell::LazyCell::force_mut(&mut *&raw mut destroyed_0)) == (1))) && ((*std::cell::LazyCell::force_mut(&mut *&raw mut last_1)) == (9)) ); (*std::cell::LazyCell::force_mut(&mut *&raw mut destroyed_0)) = 0; { - let mut __tmp_3: S = ZeroInitializationUnsafe::zero_init(); - (unsafe { make_2(&raw mut __tmp_3, 11) }); - let r: *const S = &mut __tmp_3; + let mut __tmp_4: S = ZeroInitializationUnsafe::zero_init(); + (unsafe { make_2(&raw mut __tmp_4, 11) }); + let r: *const S = &mut __tmp_4; assert!( ((*std::cell::LazyCell::force_mut(&mut *&raw mut destroyed_0)) == (0)) && (((*r).v) == (11)) diff --git a/tests/unit/out/unsafe/structured_binding_copy_ctor.rs b/tests/unit/out/unsafe/structured_binding_copy_ctor.rs index afb7188eb3..43d3ab33f3 100644 --- a/tests/unit/out/unsafe/structured_binding_copy_ctor.rs +++ b/tests/unit/out/unsafe/structured_binding_copy_ctor.rs @@ -51,11 +51,10 @@ pub fn main() { } unsafe fn main_0() -> i32 { object_unsafe!(s, Counted::constructor_1(1, 2)); - let mut __decomp_2: Counted = { - let mut __v: Counted = ZeroInitializationUnsafe::zero_init(); - Counted::constructor_2(&raw mut __v, LvalueRefUnsafe::bind(&s)); - __v - }; + object_unsafe!( + __decomp_2, + Counted::constructor_2(LvalueRefUnsafe::bind(&s)) + ); assert!(((*std::cell::LazyCell::force_mut(&mut *&raw mut copies_0)) == (1))); assert!(((__decomp_2.x) == (2))); assert!(((__decomp_2.y) == (4))); @@ -66,11 +65,9 @@ unsafe fn main_0() -> i32 { let __decomp_4: *const Counted = &s; assert!(((*std::cell::LazyCell::force_mut(&mut *&raw mut copies_0)) == (1))); assert!((((*__decomp_4).x) == (1))); - let mut __decomp_5: Counted = { - let mut __v: Counted = ZeroInitializationUnsafe::zero_init(); - (unsafe { make_counted_1(&raw mut __v) }); - __v - }; + object_unsafe!(__decomp_5, Counted, |__decomp_5| (unsafe { + make_counted_1(__decomp_5) + })); assert!(((*std::cell::LazyCell::force_mut(&mut *&raw mut copies_0)) == (1))); assert!(((__decomp_5.x) == (5))); assert!(((__decomp_5.y) == (6))); diff --git a/tests/unit/out/unsafe/structured_binding_element_ctor.rs b/tests/unit/out/unsafe/structured_binding_element_ctor.rs index 9c88a0824e..dbc029e6ae 100644 --- a/tests/unit/out/unsafe/structured_binding_element_ctor.rs +++ b/tests/unit/out/unsafe/structured_binding_element_ctor.rs @@ -83,11 +83,9 @@ unsafe fn main_0() -> i32 { }; let mut base_copies: i32 = (*std::cell::LazyCell::force_mut(&mut *&raw mut copies_0)); let mut base_moves: i32 = (*std::cell::LazyCell::force_mut(&mut *&raw mut moves_1)); - let mut __decomp_3: Two = { - let mut __v: Two = ZeroInitializationUnsafe::zero_init(); - ::copy_constructor(&raw mut __v, LvalueRefUnsafe::bind(&t)); - __v - }; + object_unsafe!(__decomp_3, Two, |__decomp_3| { + ::copy_constructor(__decomp_3, LvalueRefUnsafe::bind(&t)) + }); assert!(((*std::cell::LazyCell::force_mut(&mut *&raw mut copies_0)) == ((base_copies) + (2)))); assert!(((*std::cell::LazyCell::force_mut(&mut *&raw mut moves_1)) == (base_moves))); assert!(((__decomp_3.a.v) == (101))); @@ -97,46 +95,42 @@ unsafe fn main_0() -> i32 { assert!((((*__decomp_4).a.v) == (1))); (*__decomp_4).a.v = 50; assert!(((t.a.v) == (50))); - let mut __decomp_5: Two = { - let mut __v: Two = ZeroInitializationUnsafe::zero_init(); + object_unsafe!(__decomp_5, Two, |__decomp_5| { ::move_constructor( - &raw mut __v, + __decomp_5, RvalueRefUnsafe::bind(&mut t), - ); - __v - }; + ) + }); assert!(((*std::cell::LazyCell::force_mut(&mut *&raw mut moves_1)) == ((base_moves) + (2)))); assert!(((__decomp_5.a.v) == (1050))); assert!(((__decomp_5.b.v) == (1002))); assert!(((t.a.v) == (-1_i32))); let mut before_copies: i32 = (*std::cell::LazyCell::force_mut(&mut *&raw mut copies_0)); let mut before_moves: i32 = (*std::cell::LazyCell::force_mut(&mut *&raw mut moves_1)); - let mut __decomp_6: Two = { - let mut __v: Two = ZeroInitializationUnsafe::zero_init(); - (unsafe { make_two_2(&raw mut __v) }); - __v - }; + object_unsafe!(__decomp_6, Two, |__decomp_6| (unsafe { + make_two_2(__decomp_6) + })); assert!(((*std::cell::LazyCell::force_mut(&mut *&raw mut copies_0)) == (before_copies))); assert!(((*std::cell::LazyCell::force_mut(&mut *&raw mut moves_1)) == (before_moves))); assert!(((__decomp_6.a.v) == (1))); let mut p: (Elem, Elem) = ( { - let mut __tmp_0: Elem = ZeroInitializationUnsafe::zero_init(); - Elem::constructor_1(&raw mut __tmp_0, 7); + let mut __v: Elem = ZeroInitializationUnsafe::zero_init(); { - let mut __v: Elem = ZeroInitializationUnsafe::zero_init(); - Elem::constructor_3(&raw mut __v, RvalueRefUnsafe::bind(&mut __tmp_0)); - __v - } + let mut __tmp_0: Elem = ZeroInitializationUnsafe::zero_init(); + Elem::constructor_1(&raw mut __tmp_0, 7); + Elem::constructor_3(&raw mut __v, RvalueRefUnsafe::bind(&mut __tmp_0)) + }; + __v }, { - let mut __tmp_1: Elem = ZeroInitializationUnsafe::zero_init(); - Elem::constructor_1(&raw mut __tmp_1, 8); + let mut __v: Elem = ZeroInitializationUnsafe::zero_init(); { - let mut __v: Elem = ZeroInitializationUnsafe::zero_init(); - Elem::constructor_3(&raw mut __v, RvalueRefUnsafe::bind(&mut __tmp_1)); - __v - } + let mut __tmp_1: Elem = ZeroInitializationUnsafe::zero_init(); + Elem::constructor_1(&raw mut __tmp_1, 8); + Elem::constructor_3(&raw mut __v, RvalueRefUnsafe::bind(&mut __tmp_1)) + }; + __v }, ); before_copies = (*std::cell::LazyCell::force_mut(&mut *&raw mut copies_0)); diff --git a/tests/unit/out/unsafe/structured_binding_move_ctor.rs b/tests/unit/out/unsafe/structured_binding_move_ctor.rs index 5a2cc0cf9f..15f1c69081 100644 --- a/tests/unit/out/unsafe/structured_binding_move_ctor.rs +++ b/tests/unit/out/unsafe/structured_binding_move_ctor.rs @@ -81,11 +81,10 @@ pub fn main() { } unsafe fn main_0() -> i32 { object_unsafe!(m, Movable::constructor_1(3, 4)); - let mut __decomp_2: Movable = { - let mut __v: Movable = ZeroInitializationUnsafe::zero_init(); - Movable::constructor_3(&raw mut __v, RvalueRefUnsafe::bind(&mut m)); - __v - }; + object_unsafe!( + __decomp_2, + Movable::constructor_3(RvalueRefUnsafe::bind(&mut m)) + ); assert!(((*std::cell::LazyCell::force_mut(&mut *&raw mut moves_1)) == (1))); assert!(((*std::cell::LazyCell::force_mut(&mut *&raw mut copies_0)) == (0))); assert!(((__decomp_2.x) == (3))); @@ -96,11 +95,9 @@ unsafe fn main_0() -> i32 { xs: Vec::from([1, 2, 3]), ys: Vec::from([4, 5]), }; - let mut __decomp_3: Holder = { - let mut __v: Holder = ZeroInitializationUnsafe::zero_init(); - (unsafe { Holder::extract(&raw mut h, &raw mut __v) }); - __v - }; + object_unsafe!(__decomp_3, Holder, |__decomp_3| (unsafe { + Holder::extract(&raw mut h, __decomp_3) + })); assert!(((__decomp_3.xs.len()) == (3_usize))); assert!(((__decomp_3.ys.len()) == (2_usize))); assert!(((__decomp_3.xs[(2_usize)]) == (3))); diff --git a/tests/unit/out/unsafe/this.rs b/tests/unit/out/unsafe/this.rs index 471e7670b3..4cc02cbfb8 100644 --- a/tests/unit/out/unsafe/this.rs +++ b/tests/unit/out/unsafe/this.rs @@ -226,11 +226,7 @@ unsafe fn main_0() -> i32 { S::constructor_2(1, PointerUnsafe::bind((&mut s as *mut S))) ); assert!(((u.self__) == (&mut s as *mut S))); - let s_const: S = { - let mut __v: S = ZeroInitializationUnsafe::zero_init(); - S::constructor_1(&raw mut __v, 100); - __v - }; + object_unsafe!(s_const, S::constructor_1(100)); object_unsafe!( u1, S::constructor_3(1, PointerUnsafe::bind((&s_const as *const S))) From 8bc8d232c4dc58d493aafef0c80dc11f5aa2e65f Mon Sep 17 00:00:00 2001 From: Lucian Popescu Date: Sat, 5 Dec 2026 14:03:59 +0000 Subject: [PATCH 2/4] Refator build into storage --- cpp2rust/converter/converter.cpp | 98 ++++++++++++++++-------- cpp2rust/converter/converter.h | 22 ++---- cpp2rust/converter/converter_lib.cpp | 71 +++++++++-------- cpp2rust/converter/converter_lib.h | 12 --- cpp2rust/converter/models/boxed_vars.cpp | 2 - 5 files changed, 114 insertions(+), 91 deletions(-) diff --git a/cpp2rust/converter/converter.cpp b/cpp2rust/converter/converter.cpp index d1e3f34d53..08748f4506 100644 --- a/cpp2rust/converter/converter.cpp +++ b/cpp2rust/converter/converter.cpp @@ -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; } @@ -3229,6 +3233,22 @@ 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 || + (clang::isa(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(); @@ -4075,6 +4095,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; } @@ -4213,6 +4237,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(expr->getSubExpr()); bin && (bin->isCommaOp() || (bin->isAssignmentOp() && isVoid()))) { Convert(expr->getSubExpr()); @@ -4966,43 +4994,48 @@ void Converter::ConstructInPlace(clang::Expr *init, std::string receiver) { void Converter::ConvertIntoStorage(clang::Expr *expr, std::string receiver, std::optional *object_tail) { - if (IsStorageProducer(expr)) { - PushExprKind push(*this, ExprKind::Void); - ScopedValue in_place(in_place_, {expr, std::move(receiver), object_tail}); - Convert(expr); - return; - } - if (auto *wrapped = GetStorageWrappedExpr(expr)) { - ConvertIntoStorage(const_cast(wrapped), std::move(receiver), - object_tail); - return; + 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; } - if (auto *conditional = clang::dyn_cast(expr); - conditional && BuildsInStorage(conditional)) { - auto branch = [&](clang::Expr *branch_expr) { - PushBrace brace(*this); + 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); - StrCat(token::kSemiColon); - }; - StrCat(keyword::kIf); - ConvertIfCondition(conditional->getCond()); - branch(conditional->getTrueExpr()); - StrCat(keyword::kElse); - branch(conditional->getFalseExpr()); - return; - } - std::string value; - { - Buffer buf(*this); - PushExprKind push(*this, ExprKind::RValue); - ConvertVarInit(expr->getType(), expr); - value = std::move(buf).str(); - } - StrCat(std::format("({}).write({})", receiver, value)); + } 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(IsStorageProducer(producer)); + assert(BuildsInStorage(producer)); if (in_place_.expr == producer) { return false; } @@ -5471,6 +5504,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; } diff --git a/cpp2rust/converter/converter.h b/cpp2rust/converter/converter.h index ee59a99637..b77270af82 100644 --- a/cpp2rust/converter/converter.h +++ b/cpp2rust/converter/converter.h @@ -129,6 +129,10 @@ class Converter : public clang::RecursiveASTVisitor { bool VisitRecoveryExpr(clang::RecoveryExpr *expr); bool VisitExprWithCleanups(clang::ExprWithCleanups *expr); + + bool VisitCXXBindTemporaryExpr(clang::CXXBindTemporaryExpr *expr); + + bool VisitCastExpr(clang::CastExpr *expr); bool VisitMaterializeTemporaryExpr(clang::MaterializeTemporaryExpr *expr); virtual void EmitFilePreamble(); @@ -772,7 +776,6 @@ class Converter : public clang::RecursiveASTVisitor { virtual void ConvertArrayCXXConstructExpr(clang::CXXConstructExpr *expr); - // The construction of an element of the array that expr constructs. clang::CXXConstructExpr *GetElementConstruct(clang::CXXConstructExpr *expr); virtual bool @@ -1305,9 +1308,6 @@ class Converter : public clang::RecursiveASTVisitor { // Owning temporaries needed by references bound before a rule expansion. std::string *full_expression_temporaries_ = nullptr; - // The storage, which receiver gives, offered to the producer expr. A local - // object also gets, in object_tail, the arguments of the object! macro after - // its name, if the constructor call is all that its construction emits. struct InPlaceConstruct { const clang::Expr *expr = nullptr; std::string receiver; @@ -1330,25 +1330,19 @@ class Converter : public clang::RecursiveASTVisitor { const clang::Expr *init, std::string *declarations); - // Converts init, which builds in storage, to a statement that builds its - // object in the storage that receiver gives. void ConstructInPlace(clang::Expr *init, std::string receiver); - // Converts expr, whose object is built in the storage that receiver gives, - // to the code that builds it there. void ConvertIntoStorage(clang::Expr *expr, std::string receiver, std::optional *object_tail = nullptr); - // Converts producer, unless a parent offers storage to it, in a block that - // builds its object in a local storage and results in the object, unless it - // is discarded. Returns whether it converted producer. + bool ForwardsStorage(const clang::Expr *expr, const clang::Expr *operand); + + void ConvertConditionalIntoStorage(clang::ConditionalOperator *expr); + bool ConvertInBlockStorage(clang::Expr *producer); - // Whether decl is constructed in its storage by its initializer. bool ConstructsVarInPlace(clang::VarDecl *decl); - // Declares decl, which its initializer builds in place, with the object! - // macro, which also destroys it at the end of its scope. void EmitLocalObject(clang::VarDecl *decl); bool retain_bound_temporaries_ = false; class HoistMaterializedTempBindings { diff --git a/cpp2rust/converter/converter_lib.cpp b/cpp2rust/converter/converter_lib.cpp index dffa4e0717..cb5dffbf73 100644 --- a/cpp2rust/converter/converter_lib.cpp +++ b/cpp2rust/converter/converter_lib.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -1346,48 +1347,56 @@ static bool IsStorageConstruct(const clang::Expr *expr) { return ctor->isUserProvided() || IsConvertibleDefaultConstructor(ctor); } -bool IsStorageProducer(const clang::Expr *expr) { - return IsStorageConstruct(expr) || IsReturnSlotCall(expr); -} +namespace { +class StorageTarget : public clang::ConstStmtVisitor { +public: + bool VisitStmt(const clang::Stmt *) { return false; } -const clang::Expr *GetStorageWrappedExpr(const clang::Expr *expr) { - if (auto *paren = clang::dyn_cast(expr)) { - return paren->getSubExpr(); + bool VisitParenExpr(const clang::ParenExpr *expr) { + return Visit(expr->getSubExpr()); } - if (auto *cleanups = clang::dyn_cast(expr)) { - return cleanups->getSubExpr(); + + bool VisitExprWithCleanups(const clang::ExprWithCleanups *expr) { + return Visit(expr->getSubExpr()); } - if (auto *bind = clang::dyn_cast(expr)) { - return bind->getSubExpr(); + + bool VisitCXXBindTemporaryExpr(const clang::CXXBindTemporaryExpr *expr) { + return Visit(expr->getSubExpr()); } - if (auto *default_init = clang::dyn_cast(expr)) { - return default_init->getExpr(); + + bool VisitCXXDefaultInitExpr(const clang::CXXDefaultInitExpr *expr) { + return Visit(expr->getExpr()); } - if (auto *cast = clang::dyn_cast(expr); - cast && cast->getCastKind() == clang::CK_NoOp && cast->isPRValue()) { - return cast->getSubExpr(); + + bool VisitImplicitCastExpr(const clang::ImplicitCastExpr *expr) { + if (expr->getCastKind() == clang::CK_NoOp && expr->isPRValue()) { + return Visit(expr->getSubExpr()); + } + return VisitCastExpr(expr); } - if (auto *cast = clang::dyn_cast(expr); - cast && cast->getCastKind() == clang::CK_ConstructorConversion) { - return cast->getSubExpr(); + + bool VisitCastExpr(const clang::CastExpr *expr) { + return expr->getCastKind() == clang::CK_ConstructorConversion && + Visit(expr->getSubExpr()); } - return nullptr; -} -bool BuildsInStorage(const clang::Expr *expr) { - if (IsStorageProducer(expr)) { - return true; + bool VisitConditionalOperator(const clang::ConditionalOperator *expr) { + return expr->isPRValue() && expr->getType()->isRecordType() && + (Visit(expr->getTrueExpr()) || Visit(expr->getFalseExpr())); } - if (auto *wrapped = GetStorageWrappedExpr(expr)) { - return BuildsInStorage(wrapped); + + bool VisitCXXConstructExpr(const clang::CXXConstructExpr *expr) { + return IsStorageConstruct(expr); } - if (auto *conditional = clang::dyn_cast(expr); - conditional && conditional->isPRValue() && - conditional->getType()->isRecordType()) { - return BuildsInStorage(conditional->getTrueExpr()) || - BuildsInStorage(conditional->getFalseExpr()); + + bool VisitCallExpr(const clang::CallExpr *expr) { + return IsReturnSlotCall(expr); } - return false; +}; +} // namespace + +bool BuildsInStorage(const clang::Expr *expr) { + return StorageTarget().Visit(expr); } const clang::Expr * diff --git a/cpp2rust/converter/converter_lib.h b/cpp2rust/converter/converter_lib.h index 561a6e79fc..ca21caf352 100644 --- a/cpp2rust/converter/converter_lib.h +++ b/cpp2rust/converter/converter_lib.h @@ -349,20 +349,8 @@ bool UsesReturnSlot(clang::QualType type); bool IsReturnSlotCall(const clang::Expr *expr); -// Whether expr is a prvalue that is built only through a receiver of the -// storage of its object: the call of a translated constructor, or a call that -// returns its object through a return slot. -bool IsStorageProducer(const clang::Expr *expr); - -// The operand of expr, which only wraps it, whose object is the object of -// expr. -const clang::Expr *GetStorageWrappedExpr(const clang::Expr *expr); - -// Whether expr builds its object in the storage that its parent offers, by a -// producer that the nodes above it forward the storage to. bool BuildsInStorage(const clang::Expr *expr); -// The initializer of temporary that builds it in its storage, if it has type. const clang::Expr * GetTemporaryPlacementInitializer(const clang::ASTContext &ctx, const clang::Expr *temporary, diff --git a/cpp2rust/converter/models/boxed_vars.cpp b/cpp2rust/converter/models/boxed_vars.cpp index cae2f4e0f3..e0e7fd4985 100644 --- a/cpp2rust/converter/models/boxed_vars.cpp +++ b/cpp2rust/converter/models/boxed_vars.cpp @@ -160,8 +160,6 @@ class AddressTakenVisitor bool TraverseDecltypeType(clang::DecltypeType *, bool) { return true; } - // A variable whose initializer builds it in its storage gives a pointer to - // the storage to the initializer. bool VisitVarDecl(clang::VarDecl *decl) { if (decl->isLocalVarDecl() && decl->hasInit() && BuildsInStorage(decl->getInit())) { From 60ffd9ffa325b26c4b3780c805b8e789eb0991b9 Mon Sep 17 00:00:00 2001 From: Lucian Popescu Date: Sat, 5 Dec 2026 14:10:03 +0000 Subject: [PATCH 3/4] Handle comma operators and user conversions that build in storage --- cpp2rust/converter/converter.cpp | 4 + cpp2rust/converter/converter_lib.cpp | 7 +- .../class.mem/class.conv/class.conv.fct.cpp | 22 +++++ .../class.conv/out/refcount/class.conv.fct.rs | 86 ++++++++++++++++++- .../class.conv/out/unsafe/class.conv.fct.rs | 78 ++++++++++++++++- tests/unit/comma_operator.cpp | 10 +++ tests/unit/out/refcount/comma_operator.rs | 37 ++++++++ tests/unit/out/unsafe/comma_operator.rs | 34 ++++++++ 8 files changed, 275 insertions(+), 3 deletions(-) diff --git a/cpp2rust/converter/converter.cpp b/cpp2rust/converter/converter.cpp index 08748f4506..10919e5896 100644 --- a/cpp2rust/converter/converter.cpp +++ b/cpp2rust/converter/converter.cpp @@ -3240,6 +3240,7 @@ bool Converter::VisitCXXBindTemporaryExpr(clang::CXXBindTemporaryExpr *expr) { bool Converter::VisitCastExpr(clang::CastExpr *expr) { bool forwards = expr->getCastKind() == clang::CK_ConstructorConversion || + expr->getCastKind() == clang::CK_UserDefinedConversion || (clang::isa(expr) && expr->getCastKind() == clang::CK_NoOp && expr->isPRValue()); if (forwards && ForwardsStorage(expr, expr->getSubExpr())) { @@ -3740,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()) { diff --git a/cpp2rust/converter/converter_lib.cpp b/cpp2rust/converter/converter_lib.cpp index cb5dffbf73..d4ff3c0802 100644 --- a/cpp2rust/converter/converter_lib.cpp +++ b/cpp2rust/converter/converter_lib.cpp @@ -1376,10 +1376,15 @@ class StorageTarget : public clang::ConstStmtVisitor { } bool VisitCastExpr(const clang::CastExpr *expr) { - return expr->getCastKind() == clang::CK_ConstructorConversion && + return (expr->getCastKind() == clang::CK_ConstructorConversion || + expr->getCastKind() == clang::CK_UserDefinedConversion) && Visit(expr->getSubExpr()); } + bool VisitBinComma(const clang::BinaryOperator *expr) { + return Visit(expr->getRHS()); + } + bool VisitConditionalOperator(const clang::ConditionalOperator *expr) { return expr->isPRValue() && expr->getType()->isRecordType() && (Visit(expr->getTrueExpr()) || Visit(expr->getFalseExpr())); diff --git a/tests/std/class/class.mem/class.conv/class.conv.fct.cpp b/tests/std/class/class.mem/class.conv/class.conv.fct.cpp index 9b721ec476..9b7177772c 100644 --- a/tests/std/class/class.mem/class.conv/class.conv.fct.cpp +++ b/tests/std/class/class.mem/class.conv/class.conv.fct.cpp @@ -56,6 +56,27 @@ void test() { } } // namespace p2_explicit_conversion_function +// N4950 [class.conv.fct]/2: a conversion function to a class type specifies a +// conversion from X to that class type. +namespace p2_conversion_function_to_class { +struct Celsius { + int degrees; + Celsius(int d) : degrees(d) {} + Celsius(const Celsius &other) : degrees(other.degrees + 100) {} +}; + +struct Kelvin { + int degrees; + operator Celsius() const { return Celsius(degrees - 273); } +}; + +void test() { + Kelvin kelvin{300}; + Celsius celsius = kelvin; + assert(celsius.degrees == 27); +} +} // namespace p2_conversion_function_to_class + // N4950 [class.conv.fct]/1, [dcl.init.ref]/5.1.2: a conversion function to an // lvalue reference returns a reference that a reference binds to directly. namespace p1_conversion_function_to_reference { @@ -76,6 +97,7 @@ int main() { p2_non_const_conversion_function::test(); p2_implicit_conversion_function::test(); p2_explicit_conversion_function::test(); + p2_conversion_function_to_class::test(); p1_conversion_function_to_reference::test(); return 0; } diff --git a/tests/std/class/class.mem/class.conv/out/refcount/class.conv.fct.rs b/tests/std/class/class.mem/class.conv/out/refcount/class.conv.fct.rs index 4c4224906a..513adffa84 100644 --- a/tests/std/class/class.mem/class.conv/out/refcount/class.conv.fct.rs +++ b/tests/std/class/class.mem/class.conv/out/refcount/class.conv.fct.rs @@ -161,6 +161,89 @@ pub fn test_2() { let mut cast: bool = ({ p2_explicit_conversion_function_Flag::to_bool(on.as_pointer()) }); assert!(cast); } +#[derive( + Record, + ByteRepr, + ZeroInitialization, + FnPtrArg, + DefaultInitializable, + Memberwise, + MoveConstructible, + MoveAssignable, + Swappable, + Default, +)] +#[memberwise(copy_assign)] +#[derive(Conversions)] +#[conversions(copy)] +#[constructor(constructor_1, i32)] +#[constructor(constructor_2, LvalueRef>)] +#[byte_size(4)] +pub struct p2_conversion_function_to_class_Celsius { + #[offset(0)] + pub degrees: i32, +} +impl p2_conversion_function_to_class_Celsius { + pub fn constructor_1(this: Ptr, mut d: i32) { + field!(this, degrees).write(d); + } + pub fn constructor_2( + this: Ptr, + other: LvalueRef>, + ) { + let other = other.as_pointer(); + field!(this, degrees).write((other.with(|__s| __s.degrees) + 100)); + } +} +#[derive( + Copy, + Clone, + Record, + ByteRepr, + ZeroInitialization, + VaArg, + FnPtrArg, + TriviallyDefaultConstructible, + TriviallyCopyable, + Default, + Conversions, +)] +#[conversions(copy, move)] +#[conversion_function(to_p2_conversion_function_to_class_Celsius, LvalueRef>, p2_conversion_function_to_class_Celsius , return_slot)] +#[byte_size(4)] +pub struct p2_conversion_function_to_class_Kelvin { + #[offset(0)] + pub degrees: i32, +} +impl p2_conversion_function_to_class_Kelvin { + pub fn to_p2_conversion_function_to_class_Celsius( + this: Ptr, + __return: Ptr, + ) { + p2_conversion_function_to_class_Celsius::constructor_1( + __return.clone(), + (this.with(|__s| __s.degrees) - 273), + ); + return; + } +} +pub fn test_3() { + let kelvin: Value = + Rc::new(RefCell::new(p2_conversion_function_to_class_Kelvin { + degrees: 300, + })); + object!( + celsius, + p2_conversion_function_to_class_Celsius, + |celsius| ({ + p2_conversion_function_to_class_Kelvin::to_p2_conversion_function_to_class_Celsius( + kelvin.as_pointer(), + Ptr::clone(&celsius.clone()), + ) + }) + ); + assert!(({ (*celsius.borrow()).degrees } == 27)); +} #[derive( Copy, Clone, @@ -185,7 +268,7 @@ impl p1_conversion_function_to_reference_Holder { return field_ptr!(this, value); } } -pub fn test_3() { +pub fn test_4() { let holder: Value = Rc::new(RefCell::new(p1_conversion_function_to_reference_Holder { value: 1, @@ -204,6 +287,7 @@ fn main_0() -> i32 { ({ test_1() }); ({ test_2() }); ({ test_3() }); + ({ test_4() }); return 0; } pub fn __cpp2rust_init_globals() {} diff --git a/tests/std/class/class.mem/class.conv/out/unsafe/class.conv.fct.rs b/tests/std/class/class.mem/class.conv/out/unsafe/class.conv.fct.rs index 9aa229123c..df065ad0e1 100644 --- a/tests/std/class/class.mem/class.conv/out/unsafe/class.conv.fct.rs +++ b/tests/std/class/class.mem/class.conv/out/unsafe/class.conv.fct.rs @@ -133,6 +133,81 @@ pub unsafe fn test_2() { assert!(cast); } #[repr(C)] +#[derive( + FnPtrArg, + ZeroInitializationUnsafe, + DefaultInitializableUnsafe, + MemberwiseUnsafe, + MoveConstructibleUnsafe, + MoveAssignableUnsafe, + SwappableUnsafe, + Default, +)] +#[memberwise(copy_assign)] +#[derive(ConversionsUnsafe)] +#[conversions(copy)] +#[constructor(constructor_1, i32)] +#[constructor(constructor_2, LvalueRefUnsafe>)] +pub struct p2_conversion_function_to_class_Celsius { + pub degrees: i32, +} +impl p2_conversion_function_to_class_Celsius { + pub unsafe fn constructor_1(this: *mut Self, mut d: i32) { + (&raw mut (*this).degrees).write(d); + } + pub unsafe fn constructor_2( + this: *mut Self, + other: LvalueRefUnsafe>, + ) { + let other = (other.as_ptr() as *const p2_conversion_function_to_class_Celsius); + (&raw mut (*this).degrees).write((((*other).degrees) + (100))); + } +} +#[repr(C)] +#[derive( + Copy, + Clone, + VaArg, + FnPtrArg, + ZeroInitializationUnsafe, + TriviallyDefaultConstructibleUnsafe, + TriviallyCopyableUnsafe, + Default, + ConversionsUnsafe, +)] +#[conversions(copy, move)] +#[conversion_function(to_p2_conversion_function_to_class_Celsius, LvalueRefUnsafe>, p2_conversion_function_to_class_Celsius , return_slot)] +pub struct p2_conversion_function_to_class_Kelvin { + pub degrees: i32, +} +impl p2_conversion_function_to_class_Kelvin { + pub unsafe fn to_p2_conversion_function_to_class_Celsius( + this: *const Self, + __return: *mut p2_conversion_function_to_class_Celsius, + ) { + p2_conversion_function_to_class_Celsius::constructor_1( + __return, + (((*this).degrees) - (273)), + ); + return; + } +} +pub unsafe fn test_3() { + let mut kelvin: p2_conversion_function_to_class_Kelvin = + p2_conversion_function_to_class_Kelvin { degrees: 300 }; + object_unsafe!( + celsius, + p2_conversion_function_to_class_Celsius, + |celsius| (unsafe { + p2_conversion_function_to_class_Kelvin::to_p2_conversion_function_to_class_Celsius( + &raw const kelvin, + celsius, + ) + }) + ); + assert!(((celsius.degrees) == (27))); +} +#[repr(C)] #[derive( Copy, Clone, @@ -153,7 +228,7 @@ impl p1_conversion_function_to_reference_Holder { return &mut (*this).value; } } -pub unsafe fn test_3() { +pub unsafe fn test_4() { let mut holder: p1_conversion_function_to_reference_Holder = p1_conversion_function_to_reference_Holder { value: 1 }; let ref_: *mut i32 = @@ -172,6 +247,7 @@ unsafe fn main_0() -> i32 { (unsafe { test_1() }); (unsafe { test_2() }); (unsafe { test_3() }); + (unsafe { test_4() }); return 0; } pub unsafe fn __cpp2rust_init_globals() {} diff --git a/tests/unit/comma_operator.cpp b/tests/unit/comma_operator.cpp index 874e7019f9..a9356c2740 100644 --- a/tests/unit/comma_operator.cpp +++ b/tests/unit/comma_operator.cpp @@ -6,6 +6,12 @@ struct Pair { int second; }; +struct Counted { + int value; + Counted(int v) : value(v) {} + Counted(const Counted &other) : value(other.value + 100) {} +}; + long twice(const long &v) { return v * 2; } int sum(const Pair &p) { return p.first + p.second; } @@ -47,5 +53,9 @@ int main() { assert(sum((a = 7, p1)) == 3); assert(a == 7); + Counted c = (a = 8, Counted(4)); + assert(a == 8); + assert(c.value == 4); + return 0; } diff --git a/tests/unit/out/refcount/comma_operator.rs b/tests/unit/out/refcount/comma_operator.rs index c4bf0369ef..1015ee62ef 100644 --- a/tests/unit/out/refcount/comma_operator.rs +++ b/tests/unit/out/refcount/comma_operator.rs @@ -27,6 +27,37 @@ pub struct Pair { #[offset(4)] pub second: i32, } +#[derive( + Record, + ByteRepr, + ZeroInitialization, + FnPtrArg, + DefaultInitializable, + Memberwise, + MoveConstructible, + MoveAssignable, + Swappable, + Default, +)] +#[memberwise(copy_assign)] +#[derive(Conversions)] +#[conversions(copy)] +#[constructor(constructor_1, i32)] +#[constructor(constructor_2, LvalueRef>)] +#[byte_size(4)] +pub struct Counted { + #[offset(0)] + pub value: i32, +} +impl Counted { + pub fn constructor_1(this: Ptr, mut v: i32) { + field!(this, value).write(v); + } + pub fn constructor_2(this: Ptr, other: LvalueRef>) { + let other = other.as_pointer(); + field!(this, value).write((other.with(|__s| __s.value) + 100)); + } +} pub fn twice_0(v: Ptr) -> i64 { return ((v.read()) * 2_i64); } @@ -113,6 +144,12 @@ fn main_0() -> i32 { }) == 3) ); assert!((a == 7)); + object!(c, Counted, |c| { + a = 8; + Counted::constructor_1(c.clone(), 4) + }); + assert!((a == 8)); + assert!(({ (*c.borrow()).value } == 4)); return 0; } pub fn __cpp2rust_init_globals() {} diff --git a/tests/unit/out/unsafe/comma_operator.rs b/tests/unit/out/unsafe/comma_operator.rs index e45b678f5b..872789bd05 100644 --- a/tests/unit/out/unsafe/comma_operator.rs +++ b/tests/unit/out/unsafe/comma_operator.rs @@ -23,6 +23,34 @@ pub struct Pair { pub first: i32, pub second: i32, } +#[repr(C)] +#[derive( + FnPtrArg, + ZeroInitializationUnsafe, + DefaultInitializableUnsafe, + MemberwiseUnsafe, + MoveConstructibleUnsafe, + MoveAssignableUnsafe, + SwappableUnsafe, + Default, +)] +#[memberwise(copy_assign)] +#[derive(ConversionsUnsafe)] +#[conversions(copy)] +#[constructor(constructor_1, i32)] +#[constructor(constructor_2, LvalueRefUnsafe>)] +pub struct Counted { + pub value: i32, +} +impl Counted { + pub unsafe fn constructor_1(this: *mut Self, mut v: i32) { + (&raw mut (*this).value).write(v); + } + pub unsafe fn constructor_2(this: *mut Self, other: LvalueRefUnsafe>) { + let other = (other.as_ptr() as *const Counted); + (&raw mut (*this).value).write((((*other).value) + (100))); + } +} pub unsafe fn twice_0(v: *const i64) -> i64 { return ((*v) * (2_i64)); } @@ -111,6 +139,12 @@ unsafe fn main_0() -> i32 { }) == (3)) ); assert!(((a) == (7))); + object_unsafe!(c, Counted, |c| { + a = 8; + Counted::constructor_1(c, 4) + }); + assert!(((a) == (8))); + assert!(((c.value) == (4))); return 0; } pub unsafe fn __cpp2rust_init_globals() {} From 1ba16500d92cb5b6a82e86c927f6ed1539de670a Mon Sep 17 00:00:00 2001 From: Lucian Popescu Date: Sat, 5 Dec 2026 14:19:31 +0000 Subject: [PATCH 4/4] Add tests for conditional operator --- tests/std/expr/expr.compound/expr.cond.cpp | 60 +++++ .../expr.compound/out/refcount/expr.cond.rs | 227 +++++++++++++++++- .../expr.compound/out/unsafe/expr.cond.rs | 223 ++++++++++++++++- 3 files changed, 508 insertions(+), 2 deletions(-) diff --git a/tests/std/expr/expr.compound/expr.cond.cpp b/tests/std/expr/expr.compound/expr.cond.cpp index 3533a2cbfa..8fe89d47a0 100644 --- a/tests/std/expr/expr.compound/expr.cond.cpp +++ b/tests/std/expr/expr.compound/expr.cond.cpp @@ -21,7 +21,67 @@ void test() { } } // namespace p7_4_pointer_to_member_and_null +// N4950 [expr.cond]/7.1: if the second and third operands have the same type, +// the result is of that type and the result object is initialized using the +// selected operand. +namespace p7_1_class_prvalue_operands { +int constructed = 0; + +struct S { + int value; + S(int v) : value(v) { ++constructed; } + S(const S &other) : value(other.value + 100) { ++constructed; } +}; + +S make(int v) { return S(v); } + +S pick(bool first) { return first ? S(1) : make(2); } + +int read(const S &s) { return s.value; } + +struct Holder { + S held; + Holder(bool first) : held(first ? make(3) : S(4)) {} +}; + +void test() { + bool yes = true; + bool no = false; + + S from_constructors = yes ? S(5) : S(6); + assert(from_constructors.value == 5); + + S from_call = no ? S(7) : make(8); + assert(from_call.value == 8); + + S nested = no ? S(9) : (yes ? make(10) : S(11)); + assert(nested.value == 10); + + S parenthesized = (yes ? S(12) : make(13)); + assert(parenthesized.value == 12); + + S converted = no ? S(14) : 15; + assert(converted.value == 15); + + assert(pick(true).value == 1); + assert(pick(false).value == 2); + + assert(Holder(true).held.value == 3); + assert(Holder(false).held.value == 4); + + assert(read(no ? S(16) : make(17)) == 17); + assert((yes ? make(18) : S(19)).value == 18); + + S *allocated = new S(no ? S(20) : S(21)); + assert(allocated->value == 21); + delete allocated; + + assert(constructed == 12); +} +} // namespace p7_1_class_prvalue_operands + int main() { p7_4_pointer_to_member_and_null::test(); + p7_1_class_prvalue_operands::test(); return 0; } diff --git a/tests/std/expr/expr.compound/out/refcount/expr.cond.rs b/tests/std/expr/expr.compound/out/refcount/expr.cond.rs index 1b589f0934..b3a176da46 100644 --- a/tests/std/expr/expr.compound/out/refcount/expr.cond.rs +++ b/tests/std/expr/expr.compound/out/refcount/expr.cond.rs @@ -52,12 +52,237 @@ pub fn test_1() { == 4) ); } +thread_local!( + pub static constructed_2: Value = Rc::new(RefCell::new(0)); +); +#[derive( + Record, + ByteRepr, + ZeroInitialization, + FnPtrArg, + DefaultInitializable, + Memberwise, + MoveConstructible, + MoveAssignable, + Swappable, + Default, +)] +#[memberwise(copy_assign)] +#[derive(Conversions)] +#[conversions(copy)] +#[constructor(constructor_1, i32)] +#[constructor(constructor_2, LvalueRef>)] +#[byte_size(4)] +pub struct p7_1_class_prvalue_operands_S { + #[offset(0)] + pub value: i32, +} +impl p7_1_class_prvalue_operands_S { + pub fn constructor_1(this: Ptr, mut v: i32) { + field!(this, value).write(v); + (*constructed_2.with(Value::clone).borrow_mut()).prefix_inc(); + } + pub fn constructor_2(this: Ptr, other: LvalueRef>) { + let other = other.as_pointer(); + field!(this, value).write((other.with(|__s| __s.value) + 100)); + (*constructed_2.with(Value::clone).borrow_mut()).prefix_inc(); + } +} +pub fn make_3(__return: Ptr, mut v: i32) { + p7_1_class_prvalue_operands_S::constructor_1(__return.clone(), v); + return; +} +pub fn pick_4(__return: Ptr, mut first: bool) { + if first { + p7_1_class_prvalue_operands_S::constructor_1(__return.clone(), 1); + } else { + ({ make_3(Ptr::clone(&__return.clone()), 2) }); + }; + return; +} +pub fn read_5(s: Ptr) -> i32 { + return s.with(|__s| __s.value); +} +#[derive( + Record, + ByteRepr, + ZeroInitialization, + FnPtrArg, + DefaultInitializable, + Memberwise, + Swappable, + Default, +)] +#[memberwise(copy_constructor, move_constructor, move_assign, copy_assign)] +#[derive(Conversions)] +#[conversions(copy, move)] +#[constructor(constructor_1, bool)] +#[byte_size(4)] +pub struct p7_1_class_prvalue_operands_Holder { + #[offset(0)] + #[byte_size(4)] + pub held: p7_1_class_prvalue_operands_S, +} +impl p7_1_class_prvalue_operands_Holder { + pub fn constructor_1(this: Ptr, mut first: bool) { + if first { + ({ make_3(Ptr::clone(&field_ptr!(this, held)), 3) }); + } else { + p7_1_class_prvalue_operands_S::constructor_1(field_ptr!(this, held), 4); + }; + } +} +pub fn test_6() { + let mut yes: bool = true; + let mut no: bool = false; + object!( + from_constructors, + p7_1_class_prvalue_operands_S, + |from_constructors| if yes { + p7_1_class_prvalue_operands_S::constructor_1(from_constructors.clone(), 5); + } else { + p7_1_class_prvalue_operands_S::constructor_1(from_constructors.clone(), 6); + } + ); + assert!(({ (*from_constructors.borrow()).value } == 5)); + object!( + from_call, + p7_1_class_prvalue_operands_S, + |from_call| if no { + p7_1_class_prvalue_operands_S::constructor_1(from_call.clone(), 7); + } else { + ({ make_3(Ptr::clone(&from_call.clone()), 8) }); + } + ); + assert!(({ (*from_call.borrow()).value } == 8)); + object!(nested, p7_1_class_prvalue_operands_S, |nested| if no { + p7_1_class_prvalue_operands_S::constructor_1(nested.clone(), 9); + } else { + if yes { + ({ make_3(Ptr::clone(&nested.clone()), 10) }); + } else { + p7_1_class_prvalue_operands_S::constructor_1(nested.clone(), 11); + }; + }); + assert!(({ (*nested.borrow()).value } == 10)); + object!( + parenthesized, + p7_1_class_prvalue_operands_S, + |parenthesized| if yes { + p7_1_class_prvalue_operands_S::constructor_1(parenthesized.clone(), 12); + } else { + ({ make_3(Ptr::clone(&parenthesized.clone()), 13) }); + } + ); + assert!(({ (*parenthesized.borrow()).value } == 12)); + object!( + converted, + p7_1_class_prvalue_operands_S, + |converted| if no { + p7_1_class_prvalue_operands_S::constructor_1(converted.clone(), 14); + } else { + p7_1_class_prvalue_operands_S::constructor_1(converted.clone(), 15); + } + ); + assert!(({ (*converted.borrow()).value } == 15)); + { + let __tmp_0: Value = + Rc::new(RefCell::new(ZeroInitialization::zero_init())); + assert!( + ({ + ({ pick_4(Ptr::clone(&__tmp_0.as_pointer()), true) }); + __tmp_0.as_pointer() + } + .with(|__s| __s.value) + == 1) + ) + }; + { + let __tmp_1: Value = + Rc::new(RefCell::new(ZeroInitialization::zero_init())); + assert!( + ({ + ({ pick_4(Ptr::clone(&__tmp_1.as_pointer()), false) }); + __tmp_1.as_pointer() + } + .with(|__s| __s.value) + == 2) + ) + }; + { + let __tmp_2: Value = + Rc::new(RefCell::new(ZeroInitialization::zero_init())); + assert!( + ({ + p7_1_class_prvalue_operands_Holder::constructor_1(__tmp_2.as_pointer(), true); + __tmp_2.as_pointer() + } + .with(|__s| __s.held.value) + == 3) + ) + }; + { + let __tmp_3: Value = + Rc::new(RefCell::new(ZeroInitialization::zero_init())); + assert!( + ({ + p7_1_class_prvalue_operands_Holder::constructor_1(__tmp_3.as_pointer(), false); + __tmp_3.as_pointer() + } + .with(|__s| __s.held.value) + == 4) + ) + }; + assert!( + (({ + let _s: Value = + Rc::new(RefCell::new(ZeroInitialization::zero_init())); + if no { + p7_1_class_prvalue_operands_S::constructor_1(_s.as_pointer(), 16); + } else { + ({ make_3(Ptr::clone(&_s.as_pointer()), 17) }); + }; + read_5(_s.as_pointer()) + }) == 17) + ); + { + let __tmp_4: Value = + Rc::new(RefCell::new(ZeroInitialization::zero_init())); + assert!( + ({ + if yes { + ({ make_3(Ptr::clone(&__tmp_4.as_pointer()), 18) }); + } else { + p7_1_class_prvalue_operands_S::constructor_1(__tmp_4.as_pointer(), 19); + }; + __tmp_4.as_pointer() + } + .with(|__s| __s.value) + == 18) + ) + }; + let mut allocated: Ptr = { + let __p = Ptr::alloc(::zero_init()); + if no { + p7_1_class_prvalue_operands_S::constructor_1(__p.clone(), 20); + } else { + p7_1_class_prvalue_operands_S::constructor_1(__p.clone(), 21); + }; + __p + }; + assert!((allocated.with(|__s| __s.value) == 21)); + allocated.delete(); + assert!((constructed_2.with(|rc| *rc.borrow()) == 12)); +} pub fn main() { __cpp2rust_init_globals(); libcc2rs::cpp2rust_exit(main_0()); } fn main_0() -> i32 { ({ test_1() }); + ({ test_6() }); return 0; } -pub fn __cpp2rust_init_globals() {} +pub fn __cpp2rust_init_globals() { + let _ = constructed_2.with(|_| ()); +} diff --git a/tests/std/expr/expr.compound/out/unsafe/expr.cond.rs b/tests/std/expr/expr.compound/out/unsafe/expr.cond.rs index eb160580db..c0f49f7fa3 100644 --- a/tests/std/expr/expr.compound/out/unsafe/expr.cond.rs +++ b/tests/std/expr/expr.compound/out/unsafe/expr.cond.rs @@ -49,6 +49,224 @@ pub unsafe fn test_1() { == (4)) ); } +pub static mut constructed_2: std::cell::LazyCell = std::cell::LazyCell::new(|| unsafe { 0 }); +#[repr(C)] +#[derive( + FnPtrArg, + ZeroInitializationUnsafe, + DefaultInitializableUnsafe, + MemberwiseUnsafe, + MoveConstructibleUnsafe, + MoveAssignableUnsafe, + SwappableUnsafe, + Default, +)] +#[memberwise(copy_assign)] +#[derive(ConversionsUnsafe)] +#[conversions(copy)] +#[constructor(constructor_1, i32)] +#[constructor(constructor_2, LvalueRefUnsafe>)] +pub struct p7_1_class_prvalue_operands_S { + pub value: i32, +} +impl p7_1_class_prvalue_operands_S { + pub unsafe fn constructor_1(this: *mut Self, mut v: i32) { + (&raw mut (*this).value).write(v); + (*std::cell::LazyCell::force_mut(&mut *&raw mut constructed_2)).prefix_inc(); + } + pub unsafe fn constructor_2( + this: *mut Self, + other: LvalueRefUnsafe>, + ) { + let other = (other.as_ptr() as *const p7_1_class_prvalue_operands_S); + (&raw mut (*this).value).write((((*other).value) + (100))); + (*std::cell::LazyCell::force_mut(&mut *&raw mut constructed_2)).prefix_inc(); + } +} +pub unsafe fn make_3(__return: *mut p7_1_class_prvalue_operands_S, mut v: i32) { + p7_1_class_prvalue_operands_S::constructor_1(__return, v); + return; +} +pub unsafe fn pick_4(__return: *mut p7_1_class_prvalue_operands_S, mut first: bool) { + if first { + p7_1_class_prvalue_operands_S::constructor_1(__return, 1); + } else { + (unsafe { make_3(__return, 2) }); + }; + return; +} +pub unsafe fn read_5(s: *const p7_1_class_prvalue_operands_S) -> i32 { + return (*s).value; +} +#[repr(C)] +#[derive( + FnPtrArg, + ZeroInitializationUnsafe, + DefaultInitializableUnsafe, + MemberwiseUnsafe, + SwappableUnsafe, + Default, +)] +#[memberwise(copy_constructor, move_constructor, move_assign, copy_assign)] +#[derive(ConversionsUnsafe)] +#[conversions(copy, move)] +#[constructor(constructor_1, bool)] +pub struct p7_1_class_prvalue_operands_Holder { + pub held: p7_1_class_prvalue_operands_S, +} +impl p7_1_class_prvalue_operands_Holder { + pub unsafe fn constructor_1(this: *mut Self, mut first: bool) { + if first { + (unsafe { make_3(&raw mut (*this).held, 3) }); + } else { + p7_1_class_prvalue_operands_S::constructor_1(&raw mut (*this).held, 4); + }; + } +} +pub unsafe fn test_6() { + let mut yes: bool = true; + let mut no: bool = false; + object_unsafe!( + from_constructors, + p7_1_class_prvalue_operands_S, + |from_constructors| if yes { + p7_1_class_prvalue_operands_S::constructor_1(from_constructors, 5); + } else { + p7_1_class_prvalue_operands_S::constructor_1(from_constructors, 6); + } + ); + assert!(((from_constructors.value) == (5))); + object_unsafe!( + from_call, + p7_1_class_prvalue_operands_S, + |from_call| if no { + p7_1_class_prvalue_operands_S::constructor_1(from_call, 7); + } else { + (unsafe { make_3(from_call, 8) }); + } + ); + assert!(((from_call.value) == (8))); + object_unsafe!(nested, p7_1_class_prvalue_operands_S, |nested| if no { + p7_1_class_prvalue_operands_S::constructor_1(nested, 9); + } else { + if yes { + (unsafe { make_3(nested, 10) }); + } else { + p7_1_class_prvalue_operands_S::constructor_1(nested, 11); + }; + }); + assert!(((nested.value) == (10))); + object_unsafe!( + parenthesized, + p7_1_class_prvalue_operands_S, + |parenthesized| if yes { + p7_1_class_prvalue_operands_S::constructor_1(parenthesized, 12); + } else { + (unsafe { make_3(parenthesized, 13) }); + } + ); + assert!(((parenthesized.value) == (12))); + object_unsafe!( + converted, + p7_1_class_prvalue_operands_S, + |converted| if no { + p7_1_class_prvalue_operands_S::constructor_1(converted, 14); + } else { + p7_1_class_prvalue_operands_S::constructor_1(converted, 15); + } + ); + assert!(((converted.value) == (15))); + { + let mut __tmp_0: p7_1_class_prvalue_operands_S = ZeroInitializationUnsafe::zero_init(); + assert!( + (((*{ + (unsafe { pick_4(&raw mut __tmp_0, true) }); + &mut __tmp_0 + }) + .value) + == (1)) + ) + }; + { + let mut __tmp_1: p7_1_class_prvalue_operands_S = ZeroInitializationUnsafe::zero_init(); + assert!( + (((*{ + (unsafe { pick_4(&raw mut __tmp_1, false) }); + &mut __tmp_1 + }) + .value) + == (2)) + ) + }; + { + let mut __tmp_2: p7_1_class_prvalue_operands_Holder = ZeroInitializationUnsafe::zero_init(); + assert!( + (((*{ + p7_1_class_prvalue_operands_Holder::constructor_1(&raw mut __tmp_2, true); + &mut __tmp_2 + }) + .held + .value) + == (3)) + ) + }; + { + let mut __tmp_3: p7_1_class_prvalue_operands_Holder = ZeroInitializationUnsafe::zero_init(); + assert!( + (((*{ + p7_1_class_prvalue_operands_Holder::constructor_1(&raw mut __tmp_3, false); + &mut __tmp_3 + }) + .held + .value) + == (4)) + ) + }; + assert!( + ((unsafe { + let mut _s: p7_1_class_prvalue_operands_S = ZeroInitializationUnsafe::zero_init(); + if no { + p7_1_class_prvalue_operands_S::constructor_1(&raw mut _s, 16); + } else { + (unsafe { make_3(&raw mut _s, 17) }); + }; + read_5(&mut _s) + }) == (17)) + ); + { + let mut __tmp_4: p7_1_class_prvalue_operands_S = ZeroInitializationUnsafe::zero_init(); + assert!( + (((*{ + if yes { + (unsafe { make_3(&raw mut __tmp_4, 18) }); + } else { + p7_1_class_prvalue_operands_S::constructor_1(&raw mut __tmp_4, 19); + }; + &mut __tmp_4 + }) + .value) + == (18)) + ) + }; + let mut allocated: *mut p7_1_class_prvalue_operands_S = { + let __p: *mut p7_1_class_prvalue_operands_S = + Box::leak(Box::new(::zero_init())); + if no { + p7_1_class_prvalue_operands_S::constructor_1(__p, 20); + } else { + p7_1_class_prvalue_operands_S::constructor_1(__p, 21); + }; + __p + }; + assert!((((*allocated).value) == (21))); + { + let __p = allocated; + if !__p.is_null() { + ::std::mem::drop(Box::from_raw(__p)) + } + }; + assert!(((*std::cell::LazyCell::force_mut(&mut *&raw mut constructed_2)) == (12))); +} pub fn main() { unsafe { __cpp2rust_init_globals(); @@ -57,6 +275,9 @@ pub fn main() { } unsafe fn main_0() -> i32 { (unsafe { test_1() }); + (unsafe { test_6() }); return 0; } -pub unsafe fn __cpp2rust_init_globals() {} +pub unsafe fn __cpp2rust_init_globals() { + std::cell::LazyCell::force(&*&raw const constructed_2); +}