diff --git a/cpp2rust/converter/converter.cpp b/cpp2rust/converter/converter.cpp index eb0231c9f0..c2b30a763b 100644 --- a/cpp2rust/converter/converter.cpp +++ b/cpp2rust/converter/converter.cpp @@ -23,6 +23,7 @@ #include "converter/converter_lib.h" #include "converter/lex.h" #include "converter/mapper.h" +#include "converter/models/boxed_vars.h" #include "converter/printer.h" #include "converter/rules/registry.h" @@ -3007,7 +3008,8 @@ bool Converter::VisitBinaryOperator(clang::BinaryOperator *expr) { ConvertAssignmentRef(expr); return false; } - if (expr->isAssignmentOp() && isLValue()) { + if (isLValue() && + (expr->isAssignmentOp() || (expr->isCommaOp() && expr->isLValue()))) { EmitPointee(std::format("({})", ConvertFreshPointer(expr)), expr->getType(), /*fresh=*/true); return false; @@ -3036,6 +3038,7 @@ void Converter::ConvertAssignmentRef(clang::BinaryOperator *expr) { auto *lhs = expr->getLHS(); auto *rhs = expr->getRHS(); auto value = ConvertFreshRValue(rhs); + ScopedValue retain(retain_bound_temporaries_, true); std::string ptr; { PushExprKind push(*this, ExprKind::RValue); @@ -3048,11 +3051,6 @@ void Converter::ConvertAssignmentRef(clang::BinaryOperator *expr) { if (auto *compound = clang::dyn_cast(expr)) { assignment = AssignPtrExpr(left, lhs->getType(), [&](std::string_view read) { - if (lhs->getType()->isPointerType()) { - return std::format( - "({}).offset({}({} as isize))", read, - expr->getOpcode() == clang::BO_SubAssign ? "-" : "", right); - } return ConvertCompoundAssignValue(compound, read, right); }); } @@ -3072,13 +3070,22 @@ void Converter::ConvertBinaryOperator(clang::BinaryOperator *expr) { auto rhs_type = rhs->getType(); std::string_view opcode_as_string = expr->getOpcodeStr(); - if (auto *cmpd_assign_op = - llvm::dyn_cast(expr); - expr->isCompoundAssignmentOp() && - GetUnsafeTypeAsString(lhs_type) != - GetUnsafeTypeAsString(cmpd_assign_op->getComputationResultType())) { + auto *compound = clang::dyn_cast(expr); + if (compound && + (isRValue() || IsUnsignedArithOp(expr) || + GetUnsafeTypeAsString(lhs_type) != + GetUnsafeTypeAsString(compound->getComputationResultType())) && + NeedsAssignmentBinding(lhs, rhs, compound)) { + ConvertAssignment(lhs, rhs, opcode_as_string, compound); + } else if (compound && + GetUnsafeTypeAsString(lhs_type) != + GetUnsafeTypeAsString(compound->getComputationResultType())) { + PushBrace brace(*this, isRValue()); StrCat(ConvertLValue(lhs), token::kAssign, - ConvertCompoundAssignValue(cmpd_assign_op)); + ConvertCompoundAssignValue(compound)); + if (isRValue()) { + StrCat(token::kSemiColon, ConvertFreshRValue(lhs)); + } } else if (expr->isCommaOp()) { PushBrace brace(*this); { @@ -3089,11 +3096,14 @@ void Converter::ConvertBinaryOperator(clang::BinaryOperator *expr) { StrCat(token::kSemiColon); if (isRValue()) { StrCat(ConvertFreshRValue(rhs)); + } else if (isAddrOf()) { + StrCat(MakeFresh(ToString(rhs))); } else { Convert(rhs); } } else if (IsUnsignedArithOp(expr)) { - if (expr->isCompoundAssignmentOp()) { + PushBrace brace(*this, compound && isRValue()); + if (compound) { Convert(lhs); StrCat(token::kAssign); } @@ -3102,8 +3112,10 @@ void Converter::ConvertBinaryOperator(clang::BinaryOperator *expr) { ConvertUnsignedArithOperand(lhs, type); } ConvertUnsignedArithBinaryOperator(expr, rhs); - if (!expr->isCompoundAssignmentOp()) { + if (!compound) { MarkFresh(); + } else if (isRValue()) { + StrCat(token::kSemiColon, ConvertFreshRValue(lhs)); } } else if (expr->isAssignmentOp()) { if (expr->isCompoundAssignmentOp() && lhs_type->isPointerType() && @@ -3185,12 +3197,21 @@ Converter::ConvertCompoundAssignValue(clang::CompoundAssignOperator *expr, std::string_view rhs_value) { auto *lhs = expr->getLHS(); auto computation_result_type = expr->getComputationResultType(); + if (lhs->getType()->isPointerType()) { + return std::format("({}).offset({}({} as isize))", lhs_value, + expr->getOpcode() == clang::BO_SubAssign ? "-" : "", + rhs_value); + } Buffer buf(*this); { PushParen outer(*this); { PushParen inner(*this); StrCat(lhs_value.empty() ? ConvertRValue(lhs) : lhs_value); + if (lhs->getType()->isBooleanType() && + computation_result_type->isFloatingType()) { + StrCat(keyword::kAs, "u8"); + } ConvertCast(computation_result_type); } if (IsUnsignedArithOp(expr)) { @@ -3208,7 +3229,8 @@ Converter::ConvertCompoundAssignValue(clang::CompoundAssignOperator *expr, } } if (lhs->getType()->isBooleanType()) { - StrCat(token::kDiff, token::kZero); + StrCat(token::kDiff, + computation_result_type->isFloatingType() ? "0.0" : "0"); } else { ConvertCast(lhs->getType()); } @@ -3237,6 +3259,11 @@ void Converter::ConvertGenericBinaryOperator(clang::BinaryOperator *expr) { bool Converter::IsReferenceType(const clang::Expr *expr) const { const auto *e = IgnoreTransparentStdCall(ctx_, expr->IgnoreCasts())->IgnoreCasts(); + if (const auto *comma = + clang::dyn_cast(e->IgnoreParens()); + comma && comma->isCommaOp()) { + return IsReferenceType(comma->getRHS()); + } if (const auto *call = clang::dyn_cast(e)) { return !clang::isa(call) && GetReturnTypeOfFunction(call)->isReferenceType(); @@ -4944,8 +4971,474 @@ void Converter::ConvertArraySubscript(clang::Expr *base, clang::Expr *idx, } } +namespace { +// A local can be reread across an effectful RHS only if none of its uses can +// escape its storage. Unknown lvalue uses are conservatively address-taking. +void FindAssignmentAliases(const clang::Stmt *stmt, + std::unordered_set &vars, + bool value_use = false, bool discarded_use = false) { + if (!stmt) { + return; + } + if (const auto *ref = clang::dyn_cast(stmt)) { + if (!value_use) { + if (auto *var = clang::dyn_cast(ref->getDecl())) { + vars.insert(var); + } + } + return; + } + if (const auto *paren = clang::dyn_cast(stmt)) { + FindAssignmentAliases(paren->getSubExpr(), vars, value_use, discarded_use); + return; + } + if (const auto *cleanups = clang::dyn_cast(stmt)) { + FindAssignmentAliases(cleanups->getSubExpr(), vars, value_use, + discarded_use); + return; + } + if (const auto *cast = clang::dyn_cast(stmt)) { + FindAssignmentAliases(cast->getSubExpr(), vars, + cast->getCastKind() == clang::CK_LValueToRValue || + cast->getCastKind() == clang::CK_ToVoid); + return; + } + if (const auto *expr = clang::dyn_cast(stmt); + expr && clang::isa(expr)) { + if (const auto *object = GetEnclosingObject(expr)) { + if (const auto *element = + clang::dyn_cast(expr)) { + FindAssignmentAliases(element->getIdx(), vars); + } + FindAssignmentAliases(object, vars, value_use, discarded_use); + return; + } + } + if (const auto *binary = clang::dyn_cast(stmt)) { + FindAssignmentAliases( + binary->getLHS(), vars, + binary->isAssignmentOp() && + (value_use || discarded_use || binary->isPRValue()), + binary->isCommaOp()); + FindAssignmentAliases(binary->getRHS(), vars, + binary->isCommaOp() && value_use, + binary->isCommaOp() && discarded_use); + return; + } + if (const auto *unary = clang::dyn_cast(stmt)) { + FindAssignmentAliases(unary->getSubExpr(), vars, + unary->isIncrementDecrementOp() && + (value_use || discarded_use || + unary->isPostfix() || unary->isPRValue())); + return; + } + if (const auto *lambda = clang::dyn_cast(stmt)) { + for (const auto &capture : lambda->captures()) { + if (capture.capturesVariable()) { + vars.insert(clang::dyn_cast(capture.getCapturedVar())); + } + } + } + if (const auto *opaque = clang::dyn_cast(stmt)) { + if (opaque->getSourceExpr()) { + FindAssignmentAliases(opaque->getSourceExpr(), vars); + } else { + vars.insert(nullptr); + } + return; + } + // These extensions may keep captures or yield an lvalue from a body. Bind + // all targets rather than assuming their statement children cannot alias. + if (clang::isa(stmt)) { + vars.insert(nullptr); + } + for (const auto *child : stmt->children()) { + bool discarded = clang::isa(stmt); + if (const auto *branch = clang::dyn_cast(stmt)) { + discarded = child == branch->getThen() || child == branch->getElse(); + } else if (const auto *loop = clang::dyn_cast(stmt)) { + discarded = child == loop->getInit() || child == loop->getInc() || + child == loop->getBody(); + } else if (const auto *loop = clang::dyn_cast(stmt)) { + discarded = child == loop->getBody(); + } else if (const auto *loop = clang::dyn_cast(stmt)) { + discarded = child == loop->getBody(); + } else if (const auto *loop = + clang::dyn_cast(stmt)) { + discarded = child == loop->getBody(); + } else if (const auto *label = clang::dyn_cast(stmt)) { + discarded = child == label->getSubStmt(); + } else if (const auto *label = clang::dyn_cast(stmt)) { + discarded = child == label->getSubStmt(); + } + FindAssignmentAliases(child, vars, /*value_use=*/false, discarded); + } +} +} // namespace + +bool Converter::NeedsAssignmentBinding( + const clang::Expr *lhs, const clang::Expr *rhs, + const clang::CompoundAssignOperator *compound) { + const auto *target = lhs->IgnoreParenImpCasts(); + for (const auto *part = target; part;) { + if (const auto *member = clang::dyn_cast(part); + member && member->getMemberDecl()->getType()->isReferenceType()) { + // Referenced storage can also hold a value used to select the target. + return true; + } + const auto *object = GetEnclosingObject(part); + part = object ? object->IgnoreParenImpCasts() : nullptr; + } + const auto *ref = clang::dyn_cast(target); + const auto *var = + ref ? clang::dyn_cast(ref->getDecl()) : nullptr; + auto may_alias = [&](const clang::VarDecl *decl, bool aggregate = false) { + if (boxed_vars_) { + return boxed_vars_->contains(decl); + } + if ((!aggregate && !decl->getType()->isScalarType()) || + decl->isInitCapture()) { + return true; + } + auto [entry, inserted] = assignment_vars_.try_emplace(curr_function_); + if (inserted) { + FindAssignmentAliases(curr_function_->getBody(), entry->second); + } + return entry->second.contains(nullptr) || entry->second.contains(decl); + }; + bool rhs_effects = rhs->HasSideEffects(ctx_); + if (var && !var->isImplicit()) { + // A variable's storage never changes. Only compound assignments can read + // its old value too early, before an effectful right operand changes it. + if (!compound || + (!IsUnsignedArithOp(compound) && !lhs->getType()->isPointerType() && + ctx_.hasSameUnqualifiedType(lhs->getType(), + compound->getComputationResultType()))) { + return false; + } + if (!rhs_effects) { + return false; + } + if (!(var->isLocalVarDecl() || clang::isa(var)) || + IsGlobalVar(var) || !curr_function_ || + var->getDeclContext() != curr_function_) { + return true; + } + auto refers_to_var = [&](auto &&self, const clang::Stmt *stmt) -> bool { + if (!stmt) { + return false; + } + if (const auto *ref = clang::dyn_cast(stmt); + ref && ref->getDecl() == var) { + return true; + } + return std::ranges::any_of(stmt->children(), [&](const auto *child) { + return self(self, child); + }); + }; + if (!refers_to_var(refers_to_var, rhs)) { + return may_alias(var); + } + return true; + } + if (!rhs_effects) { + auto stable_index = [&](auto &&self, const clang::Expr *expr, + const clang::VarDecl *decl) -> bool { + if (expr->HasSideEffects(ctx_)) { + return false; + } + if (expr->isIntegerConstantExpr(ctx_)) { + return true; + } + expr = expr->IgnoreParenImpCasts(); + if (const auto *ref = clang::dyn_cast(expr)) { + const auto *index = clang::dyn_cast(ref->getDecl()); + return index && index != decl && !index->isImplicit() && + !IsGlobalVar(index) && curr_function_ && + index->getDeclContext() == curr_function_ && + !index->getType()->isReferenceType(); + } + if (const auto *member = clang::dyn_cast(expr)) { + return !member->isArrow() && + !member->getMemberDecl()->getType()->isReferenceType() && + self(self, member->getBase(), decl); + } + if (const auto *element = + clang::dyn_cast(expr)) { + return element->getBase() + ->IgnoreParenImpCasts() + ->getType() + ->isArrayType() && + self(self, element->getBase(), decl) && + self(self, element->getIdx(), decl); + } + if (const auto *binary = clang::dyn_cast(expr); + binary && binary->isPtrMemOp()) { + return false; + } + if (clang::isa(expr) || + (clang::isa(expr) && + clang::cast(expr)->getOpcode() != + clang::UO_Deref)) { + return std::ranges::all_of(expr->children(), [&](const auto *child) { + const auto *value = clang::dyn_cast_or_null(child); + return value && self(self, value, decl); + }); + } + return false; + }; + // Fixed array elements, including their fields, still select the same + // storage after the write. Keep their compact lowering too. + const auto *base = target; + while (const auto *member = clang::dyn_cast(base)) { + if (member->isArrow()) { + break; + } + base = member->getBase()->IgnoreParenImpCasts(); + } + if (const auto *subscript = + clang::dyn_cast(base); + subscript && !lhs->HasSideEffects(ctx_)) { + const auto *root = subscript->getBase()->IgnoreParenImpCasts(); + while (const auto *row = + clang::dyn_cast(root)) { + root = row->getBase()->IgnoreParenImpCasts(); + } + const auto *array = clang::dyn_cast(root); + const auto *decl = + array ? clang::dyn_cast(array->getDecl()) : nullptr; + if (decl && !decl->isImplicit() && decl->getType()->isArrayType()) { + // An index made from independent by-value variables cannot change when + // this array element is stored. References and indirect reads can. + bool stable = true; + for (const auto *element = subscript; element;) { + stable &= stable_index(stable_index, element->getIdx(), decl); + const auto *base = element->getBase()->IgnoreParenImpCasts(); + stable &= base->getType()->isArrayType(); + element = clang::dyn_cast(base); + } + if (stable) { + return false; + } + } + } + if (const auto *member = clang::dyn_cast(target)) { + const auto *base = clang::dyn_cast( + member->getBase()->IgnoreParenImpCasts()); + const auto *object = + base ? clang::dyn_cast(base->getDecl()) : nullptr; + if (object && !object->isImplicit() && + (!member->isArrow() || !object->getType()->isReferenceType()) && + !lhs->HasSideEffects(ctx_)) { + return false; + } + } + // Standard flat-container subscripts are calls in the AST, but independent + // indices and effect-free receivers keep selecting the same element. + auto enclosing_target = [](const clang::Expr *expr) -> const clang::Expr * { + if (const auto *object = GetEnclosingObject(expr)) { + return object; + } + if (const auto *call = clang::dyn_cast(expr); + call && call->getOperator() == clang::OO_Subscript) { + const auto *object = call->getArg(0)->IgnoreParenImpCasts(); + const auto *record = object->getType()->getAsCXXRecordDecl(); + if (record && record->isInStdNamespace() && + (record->getName() == "array" || record->getName() == "vector" || + record->getName() == "basic_string")) { + return object; + } + } + return nullptr; + }; + const auto *container = target; + while (const auto *object = enclosing_target(container)) { + container = object->IgnoreParenImpCasts(); + } + const auto *container_ref = clang::dyn_cast(container); + const auto *container_decl = + container_ref + ? clang::dyn_cast(container_ref->getDecl()) + : nullptr; + bool stable_container = container_decl && !container_decl->isImplicit(); + bool has_subscript = false; + for (auto *part = target; stable_container && part != container;) { + if (const auto *call = clang::dyn_cast(part); + call && call->getOperator() == clang::OO_Subscript) { + has_subscript = true; + stable_container &= + stable_index(stable_index, call->getArg(1), container_decl); + } else if (const auto *element = + clang::dyn_cast(part)) { + stable_container &= + stable_index(stable_index, element->getIdx(), container_decl); + } + part = enclosing_target(part)->IgnoreParenImpCasts(); + } + if (stable_container && has_subscript) { + return false; + } + auto storage_root = [](const clang::Expr *expr) { + expr = expr->IgnoreParenImpCasts(); + while (const auto *object = GetEnclosingObject(expr)) { + if (const auto *member = clang::dyn_cast(expr); + member && member->getMemberDecl()->getType()->isReferenceType()) { + break; + } + expr = object->IgnoreParenImpCasts(); + } + return expr; + }; + const auto *written_root = + clang::dyn_cast(storage_root(target)); + auto disjoint_members = [&](const clang::Expr *read) { + for (auto *left = target; left;) { + if (const auto *member = clang::dyn_cast(left)) { + for (auto *right = read; right;) { + if (const auto *other = clang::dyn_cast(right); + other && member->getMemberDecl() != other->getMemberDecl() && + member->getMemberDecl()->getDeclContext() == + other->getMemberDecl()->getDeclContext()) { + return true; + } + right = GetEnclosingObject(right); + if (right) { + right = right->IgnoreParenImpCasts(); + } + } + } + left = GetEnclosingObject(left); + if (left) { + left = left->IgnoreParenImpCasts(); + } + } + return false; + }; + // Indirect places can also be reread when all values used to select them + // belong to local storage that no pointer can modify. Reference bindings do + // not rebind, but reading through a reference is not an isolated scalar + // read. + auto stable_reads = [&](auto &&self, const clang::Stmt *stmt) -> bool { + if (const auto *expr = clang::dyn_cast(stmt); + expr && expr->isIntegerConstantExpr(ctx_)) { + return true; + } + if (clang::isa(stmt)) { + return false; + } + if (const auto *ref = clang::dyn_cast(stmt)) { + const auto *decl = clang::dyn_cast(ref->getDecl()); + if (!decl || decl->isImplicit() || !curr_function_ || + decl->getDeclContext() != curr_function_ || IsGlobalVar(decl)) { + return false; + } + } + if (const auto *cast = clang::dyn_cast(stmt); + cast && cast->getCastKind() == clang::CK_LValueToRValue) { + const auto *place = cast->getSubExpr()->IgnoreParenImpCasts(); + if (const auto *root = + clang::dyn_cast(storage_root(place)); + root && written_root && + root->getDecl() == written_root->getDecl() && + !disjoint_members(place)) { + return false; + } + // A pointer-valued selector cannot overlap a non-character arithmetic + // target in a well-defined program. Still check its base and indices. + if (place->getType()->isPointerType() && + lhs->getType()->isArithmeticType() && + !lhs->getType()->isAnyCharacterType()) { + for (const auto *part = place;;) { + if (const auto *element = + clang::dyn_cast(part); + element && !self(self, element->getIdx())) { + return false; + } + const auto *object = GetEnclosingObject(part); + if (!object) { + return clang::isa(part) || self(self, part); + } + part = object->IgnoreParenImpCasts(); + } + } + while ( + clang::isa(place)) { + if (const auto *member = clang::dyn_cast(place); + member && member->getMemberDecl()->getType()->isReferenceType()) { + return false; + } + if (const auto *element = + clang::dyn_cast(place); + element && !self(self, element->getIdx())) { + return false; + } + const auto *object = GetEnclosingObject(place); + if (!object) { + return false; + } + place = object->IgnoreParenImpCasts(); + } + const auto *ref = clang::dyn_cast(place); + const auto *read = + ref ? clang::dyn_cast(ref->getDecl()) : nullptr; + return read && !read->isImplicit() && curr_function_ && + read->getDeclContext() == curr_function_ && + (read->isLocalVarDecl() || + clang::isa(read)) && + !IsGlobalVar(read) && !read->isInitCapture() && + !read->getType()->isReferenceType() && + (read->getType()->isScalarType() || + read->getType().isTrivialType(ctx_)) && + !may_alias(read, /*aggregate=*/true); + } + return std::ranges::all_of(stmt->children(), [&](const auto *child) { + return !child || self(self, child); + }); + }; + if (!lhs->HasSideEffects(ctx_) && stable_reads(stable_reads, lhs)) { + return false; + } + } + if (lhs->HasSideEffects(ctx_) || rhs_effects) { + return true; + } + // A store can change which element a composite target selects. Implicit + // variables and structured bindings can expand to such targets too. + return isRValue(); +} + void Converter::ConvertAssignment(clang::Expr *lhs, clang::Expr *rhs, - std::string_view assign_operator) { + std::string_view assign_operator, + clang::CompoundAssignOperator *compound) { + if (compound || (isRValue() && NeedsAssignmentBinding(lhs, rhs))) { + auto right = NewTempName(); + auto left = NewTempName(); + auto rhs_value = ConvertFreshRValue( + rhs, compound ? std::nullopt : std::optional(lhs->getType())); + // A returned reference or pointer can still depend on a temporary owner. + ScopedValue retain(retain_bound_temporaries_, true); + auto lhs_value = ConvertLValue(lhs); + auto read = std::format("(*{})", left); + auto value = + compound ? ConvertCompoundAssignValue(compound, read, right) : right; + // Rust evaluates tuple operands left to right. Resolve the target only + // after the right operand, keeping its temporaries alive through the write. + StrCat("match ({ ", rhs_value, " }, &mut "); + { + PushParen paren(*this); + StrCat(lhs_value); + } + StrCat(") { (", right, ", ", left, ") => {", read, token::kAssign, value, + token::kSemiColon); + if (isRValue()) { + StrCat(read, ".clone()"); + } + StrCat("} }"); + MarkFresh(); + return; + } + std::string lhs_as_string; { ScopedPush init_type(curr_init_type_, lhs->getType()); diff --git a/cpp2rust/converter/converter.h b/cpp2rust/converter/converter.h index df548824c5..c34e08dca8 100644 --- a/cpp2rust/converter/converter.h +++ b/cpp2rust/converter/converter.h @@ -27,6 +27,7 @@ #include "logging.h" namespace cpp2rust { +class BoxedVars; inline constexpr const char kDestructorName[] = "destructor"; // Sets var to value while in scope. @@ -794,8 +795,13 @@ class Converter : public clang::RecursiveASTVisitor { void EmitFlexibleArrayElementPtr(clang::Expr *array, clang::Expr *idx, bool is_mut); - virtual void ConvertAssignment(clang::Expr *lhs, clang::Expr *rhs, - std::string_view assign_operator); + bool NeedsAssignmentBinding( + const clang::Expr *lhs, const clang::Expr *rhs, + const clang::CompoundAssignOperator *compound = nullptr); + virtual void + ConvertAssignment(clang::Expr *lhs, clang::Expr *rhs, + std::string_view assign_operator, + clang::CompoundAssignOperator *compound = nullptr); virtual void ConvertFunctionParameters(clang::FunctionDecl *decl); @@ -1046,6 +1052,10 @@ class Converter : public clang::RecursiveASTVisitor { std::string *rs_code_; clang::ASTContext &ctx_; + std::shared_ptr boxed_vars_; + std::unordered_map> + assignment_vars_; std::unique_ptr mangle_context_; clang::FunctionDecl *curr_function_ = nullptr; clang::Expr *return_value_ = nullptr; diff --git a/cpp2rust/converter/models/converter_refcount.cpp b/cpp2rust/converter/models/converter_refcount.cpp index bcb26c3f41..a719f88698 100644 --- a/cpp2rust/converter/models/converter_refcount.cpp +++ b/cpp2rust/converter/models/converter_refcount.cpp @@ -37,8 +37,10 @@ ConverterRefCount::ConverterRefCount(std::string &rs_code, ConverterRefCount::ConverterRefCount( std::string &rs_code, clang::ASTContext &ctx, std::shared_ptr boxed_vars) - : Converter(rs_code, ctx, "", ""), boxed_vars_(std::move(boxed_vars)), - conversion_kind_({ConversionKind::Unboxed}) {} + : Converter(rs_code, ctx, "", ""), + conversion_kind_({ConversionKind::Unboxed}) { + boxed_vars_ = std::move(boxed_vars); +} void ConverterRefCount::EmitFilePreamble() { StrCat(R"( @@ -1591,28 +1593,38 @@ void ConverterRefCount::ConvertBinaryOperator(clang::BinaryOperator *expr) { auto rhs_type = rhs->getType(); std::string_view opcode_as_string = expr->getOpcodeStr(); - if (auto *assign = llvm::dyn_cast(expr); - assign && GetSafeTypeAsString(lhs_type) != - GetSafeTypeAsString(assign->getComputationResultType())) { - EmitCompoundSetOrAssign(lhs, rhs, ConvertCompoundAssignValue(assign)); + auto *compound = clang::dyn_cast(expr); + if (compound && + (isRValue() || IsUnsignedArithOp(expr) || + GetSafeTypeAsString(lhs_type) != + GetSafeTypeAsString(compound->getComputationResultType())) && + NeedsAssignmentBinding(lhs, rhs, compound)) { + ConvertAssignment(lhs, rhs, opcode_as_string, compound); + return; + } + + if (compound && + GetSafeTypeAsString(lhs_type) != + GetSafeTypeAsString(compound->getComputationResultType())) { + EmitCompoundSetOrAssign(lhs, rhs, ConvertCompoundAssignValue(compound)); return; } if (IsUnsignedArithOp(expr)) { std::optional buf; - if (expr->isCompoundAssignmentOp()) { + if (compound) { buf.emplace(*this); } { PushParen paren(*this); - if (expr->isCompoundAssignmentOp() && lhs->isLValue()) { + if (compound && lhs->isLValue()) { StrCat(ConvertRValue(lhs)); } else { ConvertUnsignedArithOperand(lhs, expr->getType()); } } ConvertUnsignedArithBinaryOperator(expr, rhs); - if (expr->isCompoundAssignmentOp()) { + if (compound) { auto value = std::move(*buf).str(); buf.reset(); EmitCompoundSetOrAssign(lhs, rhs, value); @@ -2388,15 +2400,19 @@ void ConverterRefCount::ConvertVarInit(clang::QualType qual_type, StrCat(BoxValue(ConvertVarInitValue(qual_type, expr))); } +static const clang::VarDecl *GetGlobalValueDecl(const clang::Expr *expr) { + auto *ref = clang::dyn_cast(expr->IgnoreImplicit()); + auto *var = ref ? clang::dyn_cast(ref->getDecl()) : nullptr; + return var && IsGlobalVar(var) && !var->getType()->isReferenceType() + ? var + : nullptr; +} + bool ConverterRefCount::EmitGlobalValueAssign(clang::Expr *lhs, std::string_view assign_operator, std::string_view rhs) { - auto *decl_ref = clang::dyn_cast(lhs->IgnoreImplicit()); - if (!decl_ref) { - return false; - } - auto *var = clang::dyn_cast(decl_ref->getDecl()); - if (!var || !IsGlobalVar(var) || var->getType()->isReferenceType()) { + auto *var = GetGlobalValueDecl(lhs); + if (!var) { return false; } PushBrace brace(*this, in_const_initializer_); @@ -2435,18 +2451,132 @@ bool ConverterRefCount::CanBraceAssignedValue( void ConverterRefCount::EmitCompoundSetOrAssign(clang::Expr *lhs, clang::Expr *rhs, std::string_view value) { - if (CanBraceAssignedValue(lhs, rhs, "=")) { - PushBrace brace(*this, isRValue()); + bool can_brace = CanBraceAssignedValue(lhs, rhs, "="); + PushBrace brace(*this, isRValue() || !can_brace); + if (can_brace) { EmitSetOrAssign(lhs, std::format("{{ {} }}", value)); - return; + } else { + StrCat(keyword::kLet, "rhs_0", token::kAssign, value, token::kSemiColon); + EmitSetOrAssign(lhs, "rhs_0"); + } + if (isRValue()) { + StrCat(token::kSemiColon, ConvertFreshRValue(lhs)); } - PushBrace brace(*this); - StrCat(keyword::kLet, "rhs_0", token::kAssign, value, token::kSemiColon); - EmitSetOrAssign(lhs, "rhs_0"); } -void ConverterRefCount::ConvertAssignment(clang::Expr *lhs, clang::Expr *rhs, - std::string_view assign_operator) { +void ConverterRefCount::ConvertAssignment( + clang::Expr *lhs, clang::Expr *rhs, std::string_view assign_operator, + clang::CompoundAssignOperator *compound) { + auto *global = GetGlobalValueDecl(lhs); + if (global && compound && + (lhs->getType()->isPointerType() || IsUnsignedArithOp(compound) || + GetSafeTypeAsString(lhs->getType()) != + GetSafeTypeAsString(compound->getComputationResultType()))) { + // The target is fixed, but the right operand can change its value. + PushBrace brace(*this); + auto right = NewTempName(); + StrCat(keyword::kLet, right, token::kAssign, ConvertFreshRValue(rhs), + token::kSemiColon); + if (lhs->getType()->isPointerType()) { + EmitGlobalValueAssign(lhs, assign_operator, + std::format("({} as isize)", right)); + if (isRValue()) { + StrCat(token::kSemiColon, ConvertFreshRValue(lhs)); + } + MarkFresh(); + } else { + EmitCompoundSetOrAssign( + lhs, rhs, + ConvertCompoundAssignValue(compound, ConvertRValue(lhs), right)); + } + return; + } + if (!global && + (compound || (isRValue() && NeedsAssignmentBinding(lhs, rhs)))) { + // End target borrows before an enclosing expression consumes the result. + PushBrace brace(*this); + auto right = NewTempName(); + auto left = NewTempName(); + auto rhs_value = ConvertFreshRValue( + rhs, compound ? std::nullopt : std::optional(lhs->getType())); + // A returned reference or pointer can still depend on a temporary owner. + ScopedValue retain(retain_bound_temporaries_, true); + std::string lhs_value; + auto *base = lhs->IgnoreParenImpCasts(); + while (auto *member = clang::dyn_cast(base)) { + if (member->isArrow()) { + break; + } + base = member->getBase()->IgnoreParenImpCasts(); + } + auto *subscript = clang::dyn_cast(base); + const auto *array = subscript + ? clang::dyn_cast( + subscript->getBase()->IgnoreParenImpCasts()) + : nullptr; + const auto *decl = + array ? clang::dyn_cast(array->getDecl()) : nullptr; + bool fixed_index = subscript && decl && !decl->isImplicit() && + decl->getType()->isArrayType() && + subscript->getIdx()->isIntegerConstantExpr(ctx_); + bool staged_subscript = + subscript && !fixed_index && + ((!IsPointerSubscript(subscript) && !IsUnboxedPlace(base)) || + (IsPointerSubscript(subscript) && ReadsMemory(subscript->getIdx()))); + if (staged_subscript) { + // Resolve the index before borrowing the array, as it may read the same + // storage. The pointer keeps the selected element, not an active borrow. + auto ptr = ConvertFreshPointer(lhs); + pending_deref_.set(std::move(ptr), /*fresh=*/true); + } else { + lhs_value = ConvertLValue(lhs); + } + auto read = std::format("(*{})", left); + auto value = + compound ? ConvertCompoundAssignValue(compound, read, right) : right; + // Rust evaluates tuple operands left to right. Resolve the target only + // after the right operand, keeping its temporaries alive through the write. + StrCat("match ({ ", rhs_value, " }, "); + bool through_pointer = !pending_deref_.empty(); + bool through_reference_member = false; + for (const auto *part = lhs->IgnoreParenImpCasts(); part;) { + if (const auto *member = clang::dyn_cast(part)) { + through_reference_member |= + member->getMemberDecl()->getType()->isReferenceType(); + } + const auto *object = GetEnclosingObject(part); + part = object ? object->IgnoreParenImpCasts() : nullptr; + } + if (through_pointer && through_reference_member) { + // Keep the referenced place, but end borrows used to select its owner. + StrCat("{ let ", left, token::kAssign); + { + PushParen paren(*this); + StrCat(pending_deref_.take()); + } + StrCat(".clone()", token::kSemiColon, left, "}"); + } else if (staged_subscript) { + // End incidental index borrows before with_mut takes the write borrow. + StrCat("{ let ", left, token::kAssign, pending_deref_.take(), + token::kSemiColon, left, "}"); + } else { + StrCat(through_pointer ? "&" : "&mut "); + PushParen paren(*this); + StrCat(through_pointer ? pending_deref_.take() : lhs_value); + } + StrCat(") { (", right, ", ", left, ") => "); + if (through_pointer) { + StrCat(left, ".with_mut(|", left, "| "); + } + StrCat('{', read, token::kAssign, value, token::kSemiColon); + if (isRValue()) { + StrCat(read, ".clone()"); + } + StrCat(through_pointer ? "}) }" : "} }"); + MarkFresh(); + return; + } + auto rhs_as_string = ConvertFreshRValue(rhs, lhs->getType()); PushBrace brace(*this, isRValue()); diff --git a/cpp2rust/converter/models/converter_refcount.h b/cpp2rust/converter/models/converter_refcount.h index ac55da89b7..f3f691ca8b 100644 --- a/cpp2rust/converter/models/converter_refcount.h +++ b/cpp2rust/converter/models/converter_refcount.h @@ -299,8 +299,10 @@ class ConverterRefCount final : public Converter { std::string ConvertVarInitValue(clang::QualType qual_type, clang::Expr *expr); - void ConvertAssignment(clang::Expr *lhs, clang::Expr *rhs, - std::string_view assign_operator) override; + void + ConvertAssignment(clang::Expr *lhs, clang::Expr *rhs, + std::string_view assign_operator, + clang::CompoundAssignOperator *compound = nullptr) override; bool ConvertCXXOperatorCallExpr(clang::CXXOperatorCallExpr *expr) override; @@ -581,7 +583,6 @@ class ConverterRefCount final : public Converter { // Whether expr is a field of an unboxed variable, or of a field of one, // which is stored in place, even if it is a reference. bool IsFieldOfUnboxedPlace(const clang::MemberExpr *expr) const; - std::shared_ptr boxed_vars_; // Set when a constructor's translation refers to `this`, which then needs // the object being built to be in a Value. diff --git a/tests/unit/assignment_single_eval.cpp b/tests/unit/assignment_single_eval.cpp new file mode 100644 index 0000000000..8c89e5e15f --- /dev/null +++ b/tests/unit/assignment_single_eval.cpp @@ -0,0 +1,112 @@ +#include +#include + +unsigned rows[2][2] = {{0, 10}, {20, 30}}; +unsigned global = 10; +unsigned mutate_global() { + global = 20; + return 5; +} +struct Holder { + unsigned value; +} holder{10}; +unsigned inspect(unsigned value) { return value + holder.value; } + +unsigned selections; +struct Temp { + std::unique_ptr value = std::make_unique(10); + unsigned &get() { + ++selections; + return *value; + } + unsigned *data() { + ++selections; + return value.get(); + } +}; +int read(unsigned &value) { return value; } + +template void test() { + T a[] = {10, 20, 30, 40}; + int i = 0; + a[i++] += 5; + T compound = (a[i++] += 5); + T assigned = (a[i++] = 99); + T local = 10; + T scalar = (local += 5); + T element = (a[0] += 5); + std::printf("%d %d %d %d\n", (int)local, (int)scalar, (int)element, + (int)a[0]); + std::printf("%d %d %d: %d %d %d %d\n", i, (int)compound, (int)assigned, + (int)a[0], (int)a[1], (int)a[2], (int)a[3]); +} + +int main() { + test(); + test(); + Temp{}.get() += 5; + unsigned temporary = (Temp{}.data()[0] += 5); + int read_result = read(Temp{}.get() = 99); + std::printf("%d %u %u\n", read_result, temporary, selections); + int row = 0; + unsigned nested = (rows[rows[row++][0]][0] += 1); + unsigned global_result = (global += mutate_global()); + std::printf("%u %u\n", global_result, global); + std::printf("%u\n", inspect(holder.value += mutate_global())); + std::printf("%d %u %u\n", row, nested, rows[0][0]); + struct Slot { + unsigned &value; + }; + unsigned index = 0, other = 77; + Slot slots[] = {{index}, {other}}; + unsigned member = (slots[index].value += 1); + std::printf("%u %u %u\n", index, other, member); + index = 0; + member = (slots[index].value = 1); + std::printf("%u %u %u\n", index, other, member); + struct Index { + unsigned value; + } first{0}, second{77}; + struct Group { + Index &ref; + } groups[] = {{first}, {second}}; + member = (groups[first.value].ref.value += 1); + std::printf("%u %u %u\n", first.value, second.value, member); + int values[2] = {1, 2}; + int *p = values + 1; + int j = 0; + int *q = (*(&p + j++) -= 1); + std::printf("%d %d %d\n", j, p == values, q == values); + unsigned x = 10; + unsigned *alias = &x; + auto mutate = [alias]() { + *alias = 20; + return 5u; + }; + x += mutate(); + std::printf("%u\n", x); + unsigned captured = 10; + auto change = [&captured]() { + captured = 20; + return 5u; + }; + captured += change(); + std::printf("%u\n", captured); + short outer = 10; + short *ptr = &outer; + auto update = [&]() { return (outer += (*ptr = -1, 0.5)); }; + int updated = update(); + std::printf("%d %d\n", updated, (int)outer); + bool flags[] = {false}; + int i = 0; + bool result = (flags[i++] += 0.5); + std::printf("%d %d %d\n", i, (int)result, (int)flags[0]); + unsigned a[2] = {10, 20}; + unsigned (&ref)[2] = a; + i = 0; + unsigned v = ((++i, ref)[0] += 5); + std::printf("%d %u %u %u\n", i, v, a[0], a[1]); + unsigned *target = &v; + unsigned comma = ((++i, *target) += 1); + std::printf("%d %u %u\n", i, comma, *target); +} diff --git a/tests/unit/out/refcount/assignment_single_eval.rs b/tests/unit/out/refcount/assignment_single_eval.rs new file mode 100644 index 0000000000..1fc093407d --- /dev/null +++ b/tests/unit/out/refcount/assignment_single_eval.rs @@ -0,0 +1,565 @@ +extern crate libcc2rs; +use libcc2rs::*; +use std::cell::RefCell; +use std::collections::BTreeMap; +use std::io::prelude::*; +use std::io::{Read, Seek, Write}; +use std::os::fd::AsFd; +use std::rc::{Rc, Weak}; +thread_local!( + pub static rows_0: Value]>> = Rc::new(RefCell::new(Box::new([ + Box::new([0_u32, 10_u32]), + Box::new([20_u32, 30_u32]), + ]))); +); +thread_local!( + pub static global_1: Value = Rc::new(RefCell::new(10_u32)); +); +pub fn mutate_global_2() -> u32 { + global_1.with(|rc| *rc.borrow_mut() = 20_u32); + return 5_u32; +} +#[derive(Copy, Clone, Record, ByteRepr, VaArg, FnPtrArg, Default)] +#[byte_size(4)] +pub struct Holder { + #[offset(0)] + pub value: u32, +} +thread_local!( + pub static holder_3: Value = Rc::new(RefCell::new(Holder { value: 10_u32 })); +); +pub fn inspect_4(mut value: u32) -> u32 { + return (value).wrapping_add({ holder_3.with(|rc| *rc.borrow()).value }); +} +thread_local!( + pub static selections_5: Value = Rc::new(RefCell::new(0_u32)); +); +#[derive(Record, ByteRepr, FnPtrArg, MoveCtor, MoveAssign)] +#[byte_size(8)] +pub struct Temp { + #[offset(0)] + #[byte_size(8)] + pub value: Option>, +} +impl Temp { + pub fn move_from(_a0: Ptr) -> Self { + Self { + value: field!(_a0, value).with_mut(|__v: &mut Option>| __v.take()), + } + } +} +impl Default for Temp { + fn default() -> Self { + { + Temp { + value: Some(Rc::new(RefCell::new((10 as u32)))), + } + } + } +} +pub fn read_6(value: Ptr) -> i32 { + return ((value.read()) as i32); +} +pub fn test_7() { + let mut a: [u32; 4] = [10_u32, 20_u32, 30_u32, 40_u32]; + let mut i: i32 = 0; + { + match ({ 5_u32 }, &mut (a[(i.postfix_inc()) as usize])) { + (__tmp_0, __tmp_1) => { + (*__tmp_1) = (((*__tmp_1) as u32).wrapping_add((__tmp_0 as u32))) as u32; + } + } + }; + let mut compound: u32 = ({ + match ({ 5_u32 }, &mut (a[(i.postfix_inc()) as usize])) { + (__tmp_2, __tmp_3) => { + (*__tmp_3) = (((*__tmp_3) as u32).wrapping_add((__tmp_2 as u32))) as u32; + (*__tmp_3).clone() + } + } + }); + let mut assigned: u32 = ({ + match ({ 99_u32 }, &mut (a[(i.postfix_inc()) as usize])) { + (__tmp_4, __tmp_5) => { + (*__tmp_5) = __tmp_4; + (*__tmp_5).clone() + } + } + }); + let mut local: u32 = 10_u32; + let mut scalar: u32 = ({ + local = { (local).wrapping_add(5_u32) }; + local + }); + let mut element: u32 = ({ + a[(0) as usize] = { (a[(0) as usize]).wrapping_add(5_u32) }; + a[(0) as usize] + }); + printf!( + b"%d %d %d %d\n", + (local as i32), + (scalar as i32), + (element as i32), + (a[(0) as usize] as i32) + ); + printf!( + b"%d %d %d: %d %d %d %d\n", + i, + (compound as i32), + (assigned as i32), + (a[(0) as usize] as i32), + (a[(1) as usize] as i32), + (a[(2) as usize] as i32), + (a[(3) as usize] as i32) + ); +} +pub fn test_8() { + let mut a: [i16; 4] = [10_i16, 20_i16, 30_i16, 40_i16]; + let mut i: i32 = 0; + { + match ({ 5 }, &mut (a[(i.postfix_inc()) as usize])) { + (__tmp_6, __tmp_7) => { + (*__tmp_7) = (((*__tmp_7) as i32) + (__tmp_6 as i32)) as i16; + } + } + }; + let mut compound: i16 = ({ + match ({ 5 }, &mut (a[(i.postfix_inc()) as usize])) { + (__tmp_8, __tmp_9) => { + (*__tmp_9) = (((*__tmp_9) as i32) + (__tmp_8 as i32)) as i16; + (*__tmp_9).clone() + } + } + }); + let mut assigned: i16 = ({ + match ({ 99_i16 }, &mut (a[(i.postfix_inc()) as usize])) { + (__tmp_10, __tmp_11) => { + (*__tmp_11) = __tmp_10; + (*__tmp_11).clone() + } + } + }); + let mut local: i16 = 10_i16; + let mut scalar: i16 = ({ + local = { ((local as i32) + 5) as i16 }; + local + }); + let mut element: i16 = ({ + a[(0) as usize] = { ((a[(0) as usize] as i32) + 5) as i16 }; + a[(0) as usize] + }); + printf!( + b"%d %d %d %d\n", + (local as i32), + (scalar as i32), + (element as i32), + (a[(0) as usize] as i32) + ); + printf!( + b"%d %d %d: %d %d %d %d\n", + i, + (compound as i32), + (assigned as i32), + (a[(0) as usize] as i32), + (a[(1) as usize] as i32), + (a[(2) as usize] as i32), + (a[(3) as usize] as i32) + ); +} +pub fn main() { + __cpp2rust_init_globals(); + libcc2rs::cpp2rust_exit(main_0()); +} +fn main_0() -> i32 { + ({ test_7() }); + ({ test_8() }); + { + let __tmp_14: Value; + { + match ( + { 5_u32 }, + &({ + TempImpl::get(&{ + __tmp_14 = Rc::new(RefCell::new(::default())); + __tmp_14.as_pointer() + }) + }), + ) { + (__tmp_12, __tmp_13) => __tmp_13.with_mut(|__tmp_13| { + (*__tmp_13) = (((*__tmp_13) as u32).wrapping_add((__tmp_12 as u32))) as u32; + }), + } + } + }; + let mut temporary: u32 = { + let __tmp_17: Value; + ({ + match ( + { 5_u32 }, + &(elem!( + ({ + TempImpl::data(&{ + __tmp_17 = Rc::new(RefCell::new(::default())); + __tmp_17.as_pointer() + }) + }), + 0 + )), + ) { + (__tmp_15, __tmp_16) => __tmp_16.with_mut(|__tmp_16| { + (*__tmp_16) = (((*__tmp_16) as u32).wrapping_add((__tmp_15 as u32))) as u32; + (*__tmp_16).clone() + }), + } + }) + }; + let mut read_result: i32 = { + let __tmp_18: Value; + ({ + read_6( + match ( + { 99_u32 }, + ({ + TempImpl::get(&{ + __tmp_18 = Rc::new(RefCell::new(::default())); + __tmp_18.as_pointer() + }) + }), + ) { + (__tmp_20, __tmp_19) => { + __tmp_19.write(__tmp_20); + __tmp_19 + } + }, + ) + }) + }; + printf!( + b"%d %u %u\n", + read_result, + temporary, + selections_5.with(|rc| *rc.borrow()) + ); + let mut row: i32 = 0; + let mut nested: u32 = ({ + match ({ 1_u32 }, { + let __tmp_22 = rows_0 + .with(|v| v.decay()) + .offset( + ({ + let __idx0 = (row.postfix_inc()) as usize; + let __idx1 = (0) as usize; + rows_0.with(|rc| rc.borrow()[__idx0][__idx1]) + }), + ) + .decay() + .offset(0); + __tmp_22 + }) { + (__tmp_21, __tmp_22) => __tmp_22.with_mut(|__tmp_22| { + (*__tmp_22) = (((*__tmp_22) as u32).wrapping_add((__tmp_21 as u32))) as u32; + (*__tmp_22).clone() + }), + } + }); + let mut global_result: u32 = ({ + let __tmp_23 = ({ mutate_global_2() }); + { + let rhs_0 = + ((global_1.with(|rc| *rc.borrow()) as u32).wrapping_add((__tmp_23 as u32))) as u32; + global_1.with(|rc| *rc.borrow_mut() = rhs_0); + global_1.with(|rc| *rc.borrow()) + } + }); + printf!(b"%u %u\n", global_result, global_1.with(|rc| *rc.borrow())); + printf!( + b"%u\n", + ({ + inspect_4({ + match ( + { ({ mutate_global_2() }) }, + &mut ((*holder_3.with(Value::clone).borrow_mut()).value), + ) { + (__tmp_24, __tmp_25) => { + (*__tmp_25) = (((*__tmp_25) as u32).wrapping_add((__tmp_24 as u32))) as u32; + (*__tmp_25).clone() + } + } + }) + }) + ); + printf!( + b"%d %u %u\n", + row, + nested, + ({ + let __idx0 = (0) as usize; + let __idx1 = (0) as usize; + rows_0.with(|rc| rc.borrow()[__idx0][__idx1]) + }) + ); + let index: Value = Rc::new(RefCell::new(0_u32)); + let other: Value = Rc::new(RefCell::new(77_u32)); + let mut slots: [Slot_9; 2] = [ + Slot_9 { + value: index.as_pointer(), + }, + Slot_9 { + value: other.as_pointer(), + }, + ]; + let mut member: u32 = ({ + match ({ 1_u32 }, { + let __tmp_27 = (slots[(*index.borrow()) as usize].value).clone(); + __tmp_27 + }) { + (__tmp_26, __tmp_27) => __tmp_27.with_mut(|__tmp_27| { + (*__tmp_27) = (((*__tmp_27) as u32).wrapping_add((__tmp_26 as u32))) as u32; + (*__tmp_27).clone() + }), + } + }); + printf!(b"%u %u %u\n", (*index.borrow()), (*other.borrow()), member); + (*index.borrow_mut()) = 0_u32; + let __rhs = ({ + match ({ 1_u32 }, { + let __tmp_29 = (slots[(*index.borrow()) as usize].value).clone(); + __tmp_29 + }) { + (__tmp_28, __tmp_29) => __tmp_29.with_mut(|__tmp_29| { + (*__tmp_29) = __tmp_28; + (*__tmp_29).clone() + }), + } + }); + member = __rhs; + printf!(b"%u %u %u\n", (*index.borrow()), (*other.borrow()), member); + let first: Value = Rc::new(RefCell::new(Index_10 { value: 0_u32 })); + let second: Value = Rc::new(RefCell::new(Index_10 { value: 77_u32 })); + let mut groups: [Group_11; 2] = [ + Group_11 { + ref_: first.as_pointer(), + }, + Group_11 { + ref_: second.as_pointer(), + }, + ]; + member = ({ + match ({ 1_u32 }, { + let __tmp_31 = + (field!(groups[({ (*first.borrow()).value }) as usize].ref_, value)).clone(); + __tmp_31 + }) { + (__tmp_30, __tmp_31) => __tmp_31.with_mut(|__tmp_31| { + (*__tmp_31) = (((*__tmp_31) as u32).wrapping_add((__tmp_30 as u32))) as u32; + (*__tmp_31).clone() + }), + } + }); + printf!( + b"%u %u %u\n", + { (*first.borrow()).value }, + { (*second.borrow()).value }, + member + ); + let values: Value> = Rc::new(RefCell::new(Box::new([1, 2]))); + let p: Value> = Rc::new(RefCell::new(values.decay().offset((1) as isize))); + let mut j: i32 = 0; + let mut q: Ptr = ({ + match ( + { 1 }, + &((p.as_pointer()).offset((j.postfix_inc()) as isize)), + ) { + (__tmp_32, __tmp_33) => __tmp_33.with_mut(|__tmp_33| { + (*__tmp_33) = (*__tmp_33).offset(-(__tmp_32 as isize)); + (*__tmp_33).clone() + }), + } + }); + printf!( + b"%d %d %d\n", + j, + (({ (*p.borrow()).clone() } == { values.decay() }) as i32), + (({ (q).clone() } == { values.decay() }) as i32) + ); + let x: Value = Rc::new(RefCell::new(10_u32)); + let alias: Value> = Rc::new(RefCell::new((x.as_pointer()))); + let mutate: Value u32>> = Rc::new(RefCell::new(lambda!( + { + let alias: Value> = Rc::new(RefCell::new((*alias.borrow()).clone())); + }, + || -> u32 { + (*alias.borrow()).write(20_u32); + return 5_u32; + } + ))); + { + match ( + { ({ (*mutate.borrow()).call() }).clone() }, + &mut (*x.borrow_mut()), + ) { + (__tmp_34, __tmp_35) => { + (*__tmp_35) = (((*__tmp_35) as u32).wrapping_add((__tmp_34 as u32))) as u32; + } + } + }; + printf!(b"%u\n", (*x.borrow())); + let captured: Value = Rc::new(RefCell::new(10_u32)); + let change: Value u32>> = Rc::new(RefCell::new(lambda!( + { + let captured: Ptr = captured.as_pointer(); + }, + || -> u32 { + captured.write(20_u32); + return 5_u32; + } + ))); + { + match ( + { ({ (*change.borrow()).call() }).clone() }, + &mut (*captured.borrow_mut()), + ) { + (__tmp_36, __tmp_37) => { + (*__tmp_37) = (((*__tmp_37) as u32).wrapping_add((__tmp_36 as u32))) as u32; + } + } + }; + printf!(b"%u\n", (*captured.borrow())); + let outer: Value = Rc::new(RefCell::new(10_i16)); + let ptr: Value> = Rc::new(RefCell::new((outer.as_pointer()))); + let update: Value i16>> = Rc::new(RefCell::new(lambda!( + { + let outer: Ptr = outer.as_pointer(); + let ptr: Ptr> = ptr.as_pointer(); + }, + || -> i16 { + return ({ + match ( + { + { + (ptr.read()).write((-1_i32 as i16)); + 0.5_f64 + } + }, + &(outer), + ) { + (__tmp_38, __tmp_39) => __tmp_39.with_mut(|__tmp_39| { + (*__tmp_39) = (((*__tmp_39) as f64) + (__tmp_38 as f64)) as i16; + (*__tmp_39).clone() + }), + } + }); + } + ))); + let mut updated: i32 = (({ (*update.borrow()).call() }) as i32); + printf!(b"%d %d\n", updated, ((*outer.borrow()) as i32)); + let mut flags: [bool; 1] = [false]; + let mut i: i32 = 0; + let mut result: bool = ({ + match ({ 0.5_f64 }, &mut (flags[(i.postfix_inc()) as usize])) { + (__tmp_40, __tmp_41) => { + (*__tmp_41) = (((*__tmp_41) as u8 as f64) + (__tmp_40 as f64)) != 0.0; + (*__tmp_41).clone() + } + } + }); + printf!( + b"%d %d %d\n", + i, + (result as i32), + (flags[(0) as usize] as i32) + ); + let a: Value> = Rc::new(RefCell::new(Box::new([10_u32, 20_u32]))); + let ref_: Ptr = a.decay(); + i = 0; + let v: Value = Rc::new(RefCell::new( + ({ + match ( + { 5_u32 }, + &(elem!( + { + i.prefix_inc(); + (ref_).clone() + }, + 0 + )), + ) { + (__tmp_42, __tmp_43) => __tmp_43.with_mut(|__tmp_43| { + (*__tmp_43) = (((*__tmp_43) as u32).wrapping_add((__tmp_42 as u32))) as u32; + (*__tmp_43).clone() + }), + } + }), + )); + printf!( + b"%d %u %u %u\n", + i, + (*v.borrow()), + (*a.borrow())[(0) as usize], + (*a.borrow())[(1) as usize] + ); + let mut target: Ptr = (v.as_pointer()); + let mut comma: u32 = ({ + match ( + { 1_u32 }, + &({ + i.prefix_inc(); + (target).clone() + }), + ) { + (__tmp_44, __tmp_45) => __tmp_45.with_mut(|__tmp_45| { + (*__tmp_45) = (((*__tmp_45) as u32).wrapping_add((__tmp_44 as u32))) as u32; + (*__tmp_45).clone() + }), + } + }); + printf!(b"%d %u %u\n", i, comma, (target.read())); + 0 +} +#[derive(Clone, Record, ByteRepr, VaArg, FnPtrArg, Default)] +#[byte_size(8)] +pub struct Slot_9 { + #[offset(0)] + #[byte_size(8)] + pub value: Ptr, +} +#[derive(Copy, Clone, Record, ByteRepr, VaArg, FnPtrArg, Default)] +#[byte_size(4)] +pub struct Index_10 { + #[offset(0)] + pub value: u32, +} +#[derive(Clone, Record, ByteRepr, VaArg, FnPtrArg, Default)] +#[byte_size(8)] +pub struct Group_11 { + #[offset(0)] + #[byte_size(8)] + pub ref_: Ptr, +} +pub trait TempImpl { + fn get(&self) -> Ptr; + fn data(&self) -> Ptr; + fn move_assign(&self, _a0: Ptr) -> Ptr; +} +impl TempImpl for Ptr { + fn get(&self) -> Ptr { + (*selections_5.with(Value::clone).borrow_mut()).prefix_inc(); + return (*self).with(|__s| __s.value.clone()).as_pointer(); + } + fn data(&self) -> Ptr { + (*selections_5.with(Value::clone).borrow_mut()).prefix_inc(); + return (*self).with(|__s| __s.value.clone()).as_pointer(); + } + fn move_assign(&self, _a0: Ptr) -> Ptr { + field!((*self), value).with_mut(|__b0| { + (*__b0) = field!(_a0, value).with_mut(|__v: &mut Option>| __v.take()); + }); + return (*self).clone(); + } +} +pub fn __cpp2rust_init_globals() { + let _ = rows_0.with(|_| ()); + let _ = global_1.with(|_| ()); + let _ = holder_3.with(|_| ()); + let _ = selections_5.with(|_| ()); +} diff --git a/tests/unit/out/unsafe/assignment_single_eval.rs b/tests/unit/out/unsafe/assignment_single_eval.rs new file mode 100644 index 0000000000..7abbff52c6 --- /dev/null +++ b/tests/unit/out/unsafe/assignment_single_eval.rs @@ -0,0 +1,531 @@ +extern crate libc; +use libc::*; +extern crate libcc2rs; +use libcc2rs::*; +use std::collections::BTreeMap; +use std::io::{Read, Seek, Write}; +use std::os::fd::{AsFd, FromRawFd, IntoRawFd}; +use std::rc::Rc; +pub static mut rows_0: std::cell::LazyCell<[[u32; 2]; 2]> = + std::cell::LazyCell::new(|| unsafe { [[0_u32, 10_u32], [20_u32, 30_u32]] }); +pub static mut global_1: std::cell::LazyCell = std::cell::LazyCell::new(|| unsafe { 10_u32 }); +pub unsafe fn mutate_global_2() -> u32 { + (*std::cell::LazyCell::force_mut(&mut *&raw mut global_1)) = 20_u32; + return 5_u32; +} +#[repr(C)] +#[derive(Copy, Clone, VaArg, FnPtrArg, Default)] +pub struct Holder { + pub value: u32, +} +pub static mut holder_3: std::cell::LazyCell = + std::cell::LazyCell::new(|| unsafe { Holder { value: 10_u32 } }); +pub unsafe fn inspect_4(mut value: u32) -> u32 { + return (value).wrapping_add((*std::cell::LazyCell::force_mut(&mut *&raw mut holder_3)).value); +} +pub static mut selections_5: std::cell::LazyCell = + std::cell::LazyCell::new(|| unsafe { 0_u32 }); +#[repr(C)] +#[derive(FnPtrArg, MoveCtorUnsafe, MoveAssignUnsafe)] +pub struct Temp { + pub value: Option>, +} +impl Temp { + pub unsafe fn get(&mut self) -> *mut u32 { + (*std::cell::LazyCell::force_mut(&mut *&raw mut selections_5)).prefix_inc(); + return &mut (*self + .value + .as_deref() + .map_or(::std::ptr::null_mut(), |v| v as *const u32 as *mut u32)); + } + pub unsafe fn data(&mut self) -> *mut u32 { + (*std::cell::LazyCell::force_mut(&mut *&raw mut selections_5)).prefix_inc(); + return self + .value + .as_deref_mut() + .map_or(::std::ptr::null_mut(), |v| v as *mut u32); + } + pub unsafe fn move_from(_a0: *mut Temp) -> Self { + let mut this = Self { + value: (*_a0).value.take(), + }; + this + } + pub unsafe fn move_assign(&mut self, _a0: *mut Temp) -> *mut Temp { + { + self.value = (*_a0).value.take(); + }; + return &mut (*(self as *mut Temp)); + } +} +impl Default for Temp { + fn default() -> Self { + unsafe { + Temp { + value: Some(Box::new((10 as u32))), + } + } + } +} +pub unsafe fn read_6(value: *mut u32) -> i32 { + return ((*value) as i32); +} +pub unsafe fn test_7() { + let mut a: [u32; 4] = [10_u32, 20_u32, 30_u32, 40_u32]; + let mut i: i32 = 0; + match ({ 5_u32 }, &mut (a[(i.postfix_inc()) as usize])) { + (__tmp_0, __tmp_1) => { + (*__tmp_1) = (((*__tmp_1) as u32).wrapping_add((__tmp_0 as u32))) as u32; + } + }; + let mut compound: u32 = (match ({ 5_u32 }, &mut (a[(i.postfix_inc()) as usize])) { + (__tmp_2, __tmp_3) => { + (*__tmp_3) = (((*__tmp_3) as u32).wrapping_add((__tmp_2 as u32))) as u32; + (*__tmp_3).clone() + } + }); + let mut assigned: u32 = (match ({ 99_u32 }, &mut (a[(i.postfix_inc()) as usize])) { + (__tmp_4, __tmp_5) => { + (*__tmp_5) = __tmp_4; + (*__tmp_5).clone() + } + }); + let mut local: u32 = 10_u32; + let mut scalar: u32 = ({ + local = (local).wrapping_add(5_u32); + local + }); + let mut element: u32 = ({ + a[(0) as usize] = (a[(0) as usize]).wrapping_add(5_u32); + a[(0) as usize] + }); + (unsafe { + libc::printf( + c"%d %d %d %d\n".as_ptr() as *const libc::c_char, + (local as i32), + (scalar as i32), + (element as i32), + (a[(0) as usize] as i32), + ) + }); + (unsafe { + libc::printf( + c"%d %d %d: %d %d %d %d\n".as_ptr() as *const libc::c_char, + (i), + (compound as i32), + (assigned as i32), + (a[(0) as usize] as i32), + (a[(1) as usize] as i32), + (a[(2) as usize] as i32), + (a[(3) as usize] as i32), + ) + }); +} +pub unsafe fn test_8() { + let mut a: [i16; 4] = [10_i16, 20_i16, 30_i16, 40_i16]; + let mut i: i32 = 0; + match ({ 5 }, &mut (a[(i.postfix_inc()) as usize])) { + (__tmp_6, __tmp_7) => { + (*__tmp_7) = (((*__tmp_7) as i32) + (__tmp_6 as i32)) as i16; + } + }; + let mut compound: i16 = (match ({ 5 }, &mut (a[(i.postfix_inc()) as usize])) { + (__tmp_8, __tmp_9) => { + (*__tmp_9) = (((*__tmp_9) as i32) + (__tmp_8 as i32)) as i16; + (*__tmp_9).clone() + } + }); + let mut assigned: i16 = (match ({ 99_i16 }, &mut (a[(i.postfix_inc()) as usize])) { + (__tmp_10, __tmp_11) => { + (*__tmp_11) = __tmp_10; + (*__tmp_11).clone() + } + }); + let mut local: i16 = 10_i16; + let mut scalar: i16 = ({ + local = ((local as i32) + 5) as i16; + local + }); + let mut element: i16 = ({ + a[(0) as usize] = ((a[(0) as usize] as i32) + 5) as i16; + a[(0) as usize] + }); + (unsafe { + libc::printf( + c"%d %d %d %d\n".as_ptr() as *const libc::c_char, + (local as i32), + (scalar as i32), + (element as i32), + (a[(0) as usize] as i32), + ) + }); + (unsafe { + libc::printf( + c"%d %d %d: %d %d %d %d\n".as_ptr() as *const libc::c_char, + (i), + (compound as i32), + (assigned as i32), + (a[(0) as usize] as i32), + (a[(1) as usize] as i32), + (a[(2) as usize] as i32), + (a[(3) as usize] as i32), + ) + }); +} +pub fn main() { + unsafe { + __cpp2rust_init_globals(); + libcc2rs::cpp2rust_exit(main_0() as i32); + } +} +unsafe fn main_0() -> i32 { + (unsafe { test_7() }); + (unsafe { test_8() }); + { + let mut __tmp_14: Temp; + match ( + { 5_u32 }, + &mut (*(unsafe { + Temp::get( + &mut (*{ + __tmp_14 = ::default(); + &mut __tmp_14 + }), + ) + })), + ) { + (__tmp_12, __tmp_13) => { + (*__tmp_13) = (((*__tmp_13) as u32).wrapping_add((__tmp_12 as u32))) as u32; + } + } + }; + let mut temporary: u32 = { + let mut __tmp_17: Temp; + (match ( + { 5_u32 }, + &mut (*(unsafe { + Temp::data( + &mut (*{ + __tmp_17 = ::default(); + &mut __tmp_17 + }), + ) + }) + .offset((0) as isize)), + ) { + (__tmp_15, __tmp_16) => { + (*__tmp_16) = (((*__tmp_16) as u32).wrapping_add((__tmp_15 as u32))) as u32; + (*__tmp_16).clone() + } + }) + }; + let mut read_result: i32 = { + let mut __tmp_18: Temp; + (unsafe { + read_6( + match ( + { 99_u32 }, + ((unsafe { + Temp::get( + &mut (*{ + __tmp_18 = ::default(); + &mut __tmp_18 + }), + ) + }) as *mut u32), + ) { + (__tmp_20, __tmp_19) => { + __tmp_19.write(__tmp_20); + __tmp_19 + } + }, + ) + }) + }; + (unsafe { + libc::printf( + c"%d %u %u\n".as_ptr() as *const libc::c_char, + (read_result), + (temporary), + (*std::cell::LazyCell::force_mut(&mut *&raw mut selections_5)), + ) + }); + let mut row: i32 = 0; + let mut nested: u32 = (match ( + { 1_u32 }, + &mut ((*std::cell::LazyCell::force_mut(&mut *&raw mut rows_0)) + [((*std::cell::LazyCell::force_mut(&mut *&raw mut rows_0)) + [(row.postfix_inc()) as usize][(0) as usize]) as usize][(0) as usize]), + ) { + (__tmp_21, __tmp_22) => { + (*__tmp_22) = (((*__tmp_22) as u32).wrapping_add((__tmp_21 as u32))) as u32; + (*__tmp_22).clone() + } + }); + let mut global_result: u32 = (match ( + { (unsafe { mutate_global_2() }) }, + &mut (*std::cell::LazyCell::force_mut(&mut *&raw mut global_1)), + ) { + (__tmp_23, __tmp_24) => { + (*__tmp_24) = (((*__tmp_24) as u32).wrapping_add((__tmp_23 as u32))) as u32; + (*__tmp_24).clone() + } + }); + (unsafe { + libc::printf( + c"%u %u\n".as_ptr() as *const libc::c_char, + (global_result), + (*std::cell::LazyCell::force_mut(&mut *&raw mut global_1)), + ) + }); + (unsafe { + libc::printf( + c"%u\n".as_ptr() as *const libc::c_char, + (unsafe { + inspect_4( + match ( + { (unsafe { mutate_global_2() }) }, + &mut ((*std::cell::LazyCell::force_mut(&mut *&raw mut holder_3)).value), + ) { + (__tmp_25, __tmp_26) => { + (*__tmp_26) = + (((*__tmp_26) as u32).wrapping_add((__tmp_25 as u32))) as u32; + (*__tmp_26).clone() + } + }, + ) + }), + ) + }); + (unsafe { + libc::printf( + c"%d %u %u\n".as_ptr() as *const libc::c_char, + (row), + (nested), + ((*std::cell::LazyCell::force_mut(&mut *&raw mut rows_0))[(0) as usize][(0) as usize]), + ) + }); + let mut index: u32 = 0_u32; + let mut other: u32 = 77_u32; + let mut slots: [Slot_9; 2] = [Slot_9 { value: &mut index }, Slot_9 { value: &mut other }]; + let mut member: u32 = (match ({ 1_u32 }, &mut (*slots[(index) as usize].value)) { + (__tmp_27, __tmp_28) => { + (*__tmp_28) = (((*__tmp_28) as u32).wrapping_add((__tmp_27 as u32))) as u32; + (*__tmp_28).clone() + } + }); + (unsafe { + libc::printf( + c"%u %u %u\n".as_ptr() as *const libc::c_char, + (index), + (other), + (member), + ) + }); + index = 0_u32; + member = (match ({ 1_u32 }, &mut (*slots[(index) as usize].value)) { + (__tmp_29, __tmp_30) => { + (*__tmp_30) = __tmp_29; + (*__tmp_30).clone() + } + }); + (unsafe { + libc::printf( + c"%u %u %u\n".as_ptr() as *const libc::c_char, + (index), + (other), + (member), + ) + }); + let mut first: Index_10 = Index_10 { value: 0_u32 }; + let mut second: Index_10 = Index_10 { value: 77_u32 }; + let mut groups: [Group_11; 2] = [ + Group_11 { ref_: &mut first }, + Group_11 { ref_: &mut second }, + ]; + member = (match ( + { 1_u32 }, + &mut ((*groups[(first.value) as usize].ref_).value), + ) { + (__tmp_31, __tmp_32) => { + (*__tmp_32) = (((*__tmp_32) as u32).wrapping_add((__tmp_31 as u32))) as u32; + (*__tmp_32).clone() + } + }); + (unsafe { + libc::printf( + c"%u %u %u\n".as_ptr() as *const libc::c_char, + (first.value), + (second.value), + (member), + ) + }); + let mut values: [i32; 2] = [1, 2]; + let mut p: *mut i32 = values.as_mut_ptr().offset((1) as isize); + let mut j: i32 = 0; + let mut q: *mut i32 = (match ( + { 1 }, + &mut (*((&mut p as *mut *mut i32).offset((j.postfix_inc()) as isize))), + ) { + (__tmp_33, __tmp_34) => { + (*__tmp_34) = (*__tmp_34).offset(-(__tmp_33 as isize)); + (*__tmp_34).clone() + } + }); + (unsafe { + libc::printf( + c"%d %d %d\n".as_ptr() as *const libc::c_char, + (j), + (((p) == (values.as_mut_ptr())) as i32), + (((q) == (values.as_mut_ptr())) as i32), + ) + }); + let mut x: u32 = 10_u32; + let mut alias: *mut u32 = (&mut x as *mut u32); + let mut mutate: FnPtr u32> = lambda_unsafe!( + { + let alias: *mut u32 = alias; + }, + || -> u32 { + (*alias) = 20_u32; + return 5_u32; + } + ); + match ({ (unsafe { mutate.call() }).clone() }, &mut (x)) { + (__tmp_35, __tmp_36) => { + (*__tmp_36) = (((*__tmp_36) as u32).wrapping_add((__tmp_35 as u32))) as u32; + } + }; + (unsafe { libc::printf(c"%u\n".as_ptr() as *const libc::c_char, (x)) }); + let mut captured: u32 = 10_u32; + let mut change: FnPtr u32> = lambda_unsafe!( + { + let captured: *mut u32 = &mut captured; + }, + || -> u32 { + (*captured) = 20_u32; + return 5_u32; + } + ); + match ({ (unsafe { change.call() }).clone() }, &mut (captured)) { + (__tmp_37, __tmp_38) => { + (*__tmp_38) = (((*__tmp_38) as u32).wrapping_add((__tmp_37 as u32))) as u32; + } + }; + (unsafe { libc::printf(c"%u\n".as_ptr() as *const libc::c_char, (captured)) }); + let mut outer: i16 = 10_i16; + let mut ptr: *mut i16 = (&mut outer as *mut i16); + let mut update: FnPtr i16> = lambda_unsafe!( + { + let outer: *mut i16 = &mut outer; + let ptr: *mut *mut i16 = &mut ptr; + }, + || -> i16 { + return (match ( + { + { + (*(*ptr)) = (-1_i32 as i16); + 0.5_f64 + } + }, + &mut (*outer), + ) { + (__tmp_39, __tmp_40) => { + (*__tmp_40) = (((*__tmp_40) as f64) + (__tmp_39 as f64)) as i16; + (*__tmp_40).clone() + } + }); + } + ); + let mut updated: i32 = ((unsafe { update.call() }) as i32); + (unsafe { + libc::printf( + c"%d %d\n".as_ptr() as *const libc::c_char, + (updated), + (outer as i32), + ) + }); + let mut flags: [bool; 1] = [false]; + let mut i: i32 = 0; + let mut result: bool = (match ({ 0.5_f64 }, &mut (flags[(i.postfix_inc()) as usize])) { + (__tmp_41, __tmp_42) => { + (*__tmp_42) = (((*__tmp_42) as u8 as f64) + (__tmp_41 as f64)) != 0.0; + (*__tmp_42).clone() + } + }); + (unsafe { + libc::printf( + c"%d %d %d\n".as_ptr() as *const libc::c_char, + (i), + (result as i32), + (flags[(0) as usize] as i32), + ) + }); + let mut a: [u32; 2] = [10_u32, 20_u32]; + let ref_: *mut [u32; 2] = &mut a; + i = 0; + let mut v: u32 = (match ( + { 5_u32 }, + &mut ((*({ + i.prefix_inc(); + (ref_).clone() + }))[(0) as usize]), + ) { + (__tmp_43, __tmp_44) => { + (*__tmp_44) = (((*__tmp_44) as u32).wrapping_add((__tmp_43 as u32))) as u32; + (*__tmp_44).clone() + } + }); + (unsafe { + libc::printf( + c"%d %u %u %u\n".as_ptr() as *const libc::c_char, + (i), + (v), + (a[(0) as usize]), + (a[(1) as usize]), + ) + }); + let mut target: *mut u32 = (&mut v as *mut u32); + let mut comma: u32 = (match ( + { 1_u32 }, + &mut (*({ + i.prefix_inc(); + (target).clone() + })), + ) { + (__tmp_45, __tmp_46) => { + (*__tmp_46) = (((*__tmp_46) as u32).wrapping_add((__tmp_45 as u32))) as u32; + (*__tmp_46).clone() + } + }); + (unsafe { + libc::printf( + c"%d %u %u\n".as_ptr() as *const libc::c_char, + (i), + (comma), + (*target), + ) + }); + 0 +} +#[repr(C)] +#[derive(Copy, Clone, VaArg, FnPtrArg, Default)] +pub struct Slot_9 { + pub value: *mut u32, +} +#[repr(C)] +#[derive(Copy, Clone, VaArg, FnPtrArg, Default)] +pub struct Index_10 { + pub value: u32, +} +#[repr(C)] +#[derive(Copy, Clone, VaArg, FnPtrArg, Default)] +pub struct Group_11 { + pub ref_: *mut Index_10, +} +pub unsafe fn __cpp2rust_init_globals() { + std::cell::LazyCell::force(&*&raw const rows_0); + std::cell::LazyCell::force(&*&raw const global_1); + std::cell::LazyCell::force(&*&raw const holder_3); + std::cell::LazyCell::force(&*&raw const selections_5); +}