Skip to content

Commit d849f8c

Browse files
authored
Translate std::array as [T; N] in unsafe and Box<[T]> in refcount (#586)
1 parent 3517587 commit d849f8c

30 files changed

Lines changed: 665 additions & 110 deletions

‎cpp2rust/converter/converter.cpp‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5301,6 +5301,42 @@ std::string Converter::ConvertGenericCall(
53015301
assert(call_args.empty() && "default takes no arguments");
53025302
return GetUnboxedDefaultAsString(type);
53035303
}
5304+
if (call.method == "move_ctor") {
5305+
assert(call_args.size() == 1 && "move_ctor takes one argument");
5306+
auto *record = type->getAsCXXRecordDecl();
5307+
if (record && HasMoveFromConstructor(record)) {
5308+
return std::format("{}::move_from({})", GetUnboxedTypeAsString(type),
5309+
call_args[0]);
5310+
}
5311+
if (record && !IsUserDefinedDecl(record) &&
5312+
!record->hasTrivialMoveConstructor()) {
5313+
return std::format("<{} as {}>::move_ctor({})",
5314+
GetUnboxedTypeAsString(type), GetMoveCtorTraitName(),
5315+
call_args[0]);
5316+
}
5317+
return ConvertPtrRead(type, call_args[0]);
5318+
}
5319+
if (call.method == "move_assign" || call.method == "copy_assign") {
5320+
assert(call_args.size() == 2 && "assignments take two arguments");
5321+
bool is_move = call.method == "move_assign";
5322+
auto *record = type->getAsCXXRecordDecl();
5323+
if (record && is_move && HasMoveAssignOperator(record)) {
5324+
return ConvertPointeeMethodCall("move_assign", call_args[0],
5325+
call_args[1]);
5326+
}
5327+
if (record && HasCopyAssignOperator(record)) {
5328+
return ConvertPointeeMethodCall("copy_assign", call_args[0],
5329+
call_args[1]);
5330+
}
5331+
if (is_move && record && !IsUserDefinedDecl(record) &&
5332+
!record->hasTrivialMoveAssignment()) {
5333+
return ConvertPtrWrite(call_args[0],
5334+
std::format("<{} as {}>::move_ctor({})",
5335+
GetUnboxedTypeAsString(type),
5336+
GetMoveCtorTraitName(), call_args[1]));
5337+
}
5338+
return ConvertPtrWrite(call_args[0], ConvertPtrRead(type, call_args[1]));
5339+
}
53045340
if (call.method == "cpp_from" || call.method == "cpp_from_move") {
53055341
assert(call_args.size() == 1 && "cpp_from takes one argument");
53065342
return ConvertConversion(
@@ -5337,6 +5373,27 @@ const char *Converter::GetConversionTraitName() const {
53375373
return "CppFromUnsafe";
53385374
}
53395375

5376+
std::string Converter::ConvertPtrRead(clang::QualType type,
5377+
const std::string &src) {
5378+
if (type->isScalarType()) {
5379+
return std::format("(*{})", src);
5380+
}
5381+
return std::format("(*{}).clone()", src);
5382+
}
5383+
5384+
std::string Converter::ConvertPtrWrite(const std::string &dst,
5385+
const std::string &value) {
5386+
return std::format("*{} = {}", dst, value);
5387+
}
5388+
5389+
std::string Converter::ConvertPointeeMethodCall(const char *method,
5390+
const std::string &dst,
5391+
const std::string &src) {
5392+
return std::format("(*{}).{}({})", dst, method, src);
5393+
}
5394+
5395+
const char *Converter::GetMoveCtorTraitName() const { return "MoveCtorUnsafe"; }
5396+
53405397
std::string Converter::DerefPtrExpr(std::string_view ptr_expr,
53415398
clang::QualType pointee_type) {
53425399
return std::format("({}{})", GetPointerDerefPrefix(pointee_type), ptr_expr);

‎cpp2rust/converter/converter.h‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -319,6 +319,18 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
319319

320320
virtual const char *GetConversionTraitName() const;
321321

322+
virtual std::string ConvertPtrRead(clang::QualType type,
323+
const std::string &src);
324+
325+
virtual std::string ConvertPtrWrite(const std::string &dst,
326+
const std::string &value);
327+
328+
virtual std::string ConvertPointeeMethodCall(const char *method,
329+
const std::string &dst,
330+
const std::string &src);
331+
332+
virtual const char *GetMoveCtorTraitName() const;
333+
322334
virtual std::string DerefPtrExpr(std::string_view ptr_expr,
323335
clang::QualType pointee_type);
324336

‎cpp2rust/converter/mapper.cpp‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,18 @@ std::string Map(Converter &converter, clang::QualType qual_type) {
5858
return {};
5959
}
6060

61+
std::optional<TranslationRule::Elems> Elems(Converter &converter,
62+
clang::QualType qual_type) {
63+
auto [rule, subs] =
64+
RuleRegistry::Search(converter.GetASTContext(), qual_type);
65+
if (!rule || !rule->type_info.elems) {
66+
return std::nullopt;
67+
}
68+
auto &elems = *rule->type_info.elems;
69+
return TranslationRule::Elems{
70+
elems.kind, Matcher::InstantiateTgt(converter, subs, elems.type)};
71+
}
72+
6173
std::string MapInitializer(Converter &converter, clang::QualType qual_type) {
6274
auto [rule, subs] =
6375
RuleRegistry::Search(converter.GetASTContext(), qual_type);

‎cpp2rust/converter/mapper.h‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
#include <clang/AST/Expr.h>
88
#include <clang/AST/Type.h>
99

10+
#include <optional>
1011
#include <string>
1112

1213
#include "converter/translation_rule.h"
@@ -22,6 +23,8 @@ bool IsRefExpr(clang::ASTContext &ctx, const clang::Expr *expr);
2223

2324
std::string Map(clang::ASTContext &ctx, clang::QualType qual_type);
2425
std::string Map(Converter &converter, clang::QualType qual_type);
26+
std::optional<TranslationRule::Elems> Elems(Converter &converter,
27+
clang::QualType qual_type);
2528
std::string MapInitializer(Converter &converter, clang::QualType qual_type);
2629
std::string MapFunctionName(clang::ASTContext &ctx,
2730
const clang::FunctionDecl *decl);

‎cpp2rust/converter/models/converter_refcount.cpp‎

Lines changed: 40 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -52,12 +52,13 @@ use std::rc::{Rc, Weak};
5252
)");
5353
}
5454

55-
static bool IsBoxedType(std::string_view type) {
56-
return type.starts_with("Vec<") || type.starts_with("Box<");
55+
bool ConverterRefCount::IsBoxedType(clang::QualType type) {
56+
return Mapper::Elems(*this, type.getUnqualifiedType()).has_value();
5757
}
5858

59-
static bool IsBoxedType(clang::ASTContext &ctx, clang::QualType type) {
60-
return IsBoxedType(Mapper::Map(ctx, type.getUnqualifiedType()));
59+
bool ConverterRefCount::IsVecType(clang::QualType type) {
60+
auto elems = Mapper::Elems(*this, type.getUnqualifiedType());
61+
return elems && elems->kind == TranslationRule::ElemsKind::kVec;
6162
}
6263

6364
// A Rust type without whitespace, and with the paths into libcc2rs, which the
@@ -73,11 +74,9 @@ static std::string NormalizeType(std::string type) {
7374

7475
// Virtual methods take &mut self, as the fields of the struct are stored in
7576
// it.
76-
static bool NeedsMutAccess(clang::ASTContext &ctx,
77-
const clang::CXXMethodDecl *method,
78-
clang::QualType base_type) {
79-
return !method->isConst() &&
80-
(IsBoxedType(ctx, base_type) || method->isVirtual());
77+
bool ConverterRefCount::NeedsMutAccess(const clang::CXXMethodDecl *method,
78+
clang::QualType base_type) {
79+
return !method->isConst() && (IsBoxedType(base_type) || method->isVirtual());
8180
}
8281

8382
// Whether `expr` is an array field whose elements are accessed through
@@ -135,19 +134,6 @@ void ConverterRefCount::PendingDeref::set_unchecked(std::string str,
135134
type = ComputedExprType::Pending;
136135
}
137136

138-
std::string ConverterRefCount::GetInnerType(clang::QualType type) {
139-
PushConversionKind push(*this, ConversionKind::Unboxed);
140-
auto str = ToString(type);
141-
auto pos = str.find('<');
142-
auto end = str.rfind('>');
143-
if (str[pos + 1] == '[' && str[end - 1] == ']') {
144-
// Unwrap inner array type
145-
pos++;
146-
end--;
147-
}
148-
return std::move(str).substr(pos + 1, end - pos - 1);
149-
}
150-
151137
std::string
152138
ConverterRefCount::GetSafeTypeAsString(clang::QualType qual_type) const {
153139
std::string type_as_string;
@@ -383,7 +369,7 @@ std::string ConverterRefCount::ConvertObject(clang::Expr *expr,
383369
if (is_ptr) {
384370
type = type->getPointeeType();
385371
}
386-
if (IsBoxedType(ctx_, type) || (is_ptr && type->isArrayType())) {
372+
if (IsBoxedType(type) || (is_ptr && type->isArrayType())) {
387373
MarkFresh();
388374
return std::move(str) + ".decay()";
389375
}
@@ -393,7 +379,7 @@ std::string ConverterRefCount::ConvertObject(clang::Expr *expr,
393379

394380
std::string ConverterRefCount::AsPointerMethod(clang::QualType type) {
395381
if (isObject() && object_shape_ == ObjectShape::Element &&
396-
type->isRecordType() && IsBoxedType(ctx_, type)) {
382+
type->isRecordType() && IsBoxedType(type)) {
397383
object_shape_ = ObjectShape::Whole;
398384
return ".decay()";
399385
}
@@ -419,7 +405,7 @@ bool ConverterRefCount::ParamIsElementPtr(clang::Expr *expr, clang::Expr *arg,
419405
type = type->getPointeeType();
420406
}
421407
type = type.getUnqualifiedType();
422-
if (!IsBoxedType(ctx_, type)) {
408+
if (!IsBoxedType(type)) {
423409
return false;
424410
}
425411
// The C++ parameter is a reference or pointer to the container, which the
@@ -531,9 +517,9 @@ ConverterRefCount::MaterializeTemp(const std::string &binding_name,
531517

532518
std::string ConverterRefCount::ConvertPtrType(clang::QualType type) {
533519
std::string str;
534-
// decays into Ptr; remove the outer type Vec<>
535-
if (IsBoxedType(ctx_, type)) {
536-
str = GetInnerType(type);
520+
if (auto elems = Mapper::Elems(*this, type.getUnqualifiedType())) {
521+
PushConversionKind push(*this, ConversionKind::Unboxed);
522+
str = std::move(elems->type);
537523
} else {
538524
PushConversionKind push(*this, ConversionKind::Ptr);
539525
str = ToString(type);
@@ -768,7 +754,7 @@ void ConverterRefCount::EmitByteSizeAttr(const clang::RecordDecl *decl) {
768754

769755
std::string
770756
ConverterRefCount::GetSelfMaybeWithMut(const clang::CXXMethodDecl *decl) {
771-
return NeedsMutAccess(ctx_, decl, decl->getThisType()->getPointeeType())
757+
return NeedsMutAccess(decl, decl->getThisType()->getPointeeType())
772758
? "&mut self"
773759
: "&self";
774760
}
@@ -1776,7 +1762,7 @@ bool ConverterRefCount::VisitMemberExpr(clang::MemberExpr *expr) {
17761762
if (base_type->isPointerType()) {
17771763
base_type = base_type->getPointeeType();
17781764
}
1779-
bool needs_mut = NeedsMutAccess(ctx_, method, base_type);
1765+
bool needs_mut = NeedsMutAccess(method, base_type);
17801766
PushExprKind push(*this, needs_mut ? ExprKind::LValue : ExprKind::RValue);
17811767
Converter::ConvertMemberExpr(expr);
17821768
MarkFresh();
@@ -1845,7 +1831,7 @@ void ConverterRefCount::ConvertInlineField(clang::MemberExpr *expr) {
18451831
if (type->isArrayType()) {
18461832
StrCat(std::format("array_field_ptr!({}, {})", ConvertRecordPtr(expr),
18471833
name));
1848-
} else if (IsBoxedType(ctx_, type)) {
1834+
} else if (IsBoxedType(type)) {
18491835
StrCat(std::format("field_ref!({}, {}){}", ConvertRecordPtr(expr), name,
18501836
AsPointerMethod(type)));
18511837
} else {
@@ -2271,6 +2257,25 @@ const char *ConverterRefCount::GetConversionTraitName() const {
22712257
return "CppFrom";
22722258
}
22732259

2260+
std::string ConverterRefCount::ConvertPtrRead(clang::QualType,
2261+
const std::string &src) {
2262+
return std::format("{}.read()", src);
2263+
}
2264+
2265+
std::string ConverterRefCount::ConvertPtrWrite(const std::string &dst,
2266+
const std::string &value) {
2267+
return std::format("{}.write({})", dst, value);
2268+
}
2269+
2270+
std::string ConverterRefCount::ConvertPointeeMethodCall(
2271+
const char *method, const std::string &dst, const std::string &src) {
2272+
return std::format("{}.{}({})", dst, method, src);
2273+
}
2274+
2275+
const char *ConverterRefCount::GetMoveCtorTraitName() const {
2276+
return "MoveCtor";
2277+
}
2278+
22742279
bool ConverterRefCount::TypeDerivesDefault(clang::QualType qual_type) {
22752280
// Arrays are translated to Value<Box<[T]>>, whose Default is empty
22762281
return !qual_type->isArrayType() && Converter::TypeDerivesDefault(qual_type);
@@ -2483,8 +2488,8 @@ bool ConverterRefCount::ConvertCXXOperatorCallExpr(
24832488

24842489
case clang::OverloadedOperatorKind::OO_Subscript: {
24852490
bool is_inner_boxed =
2486-
IsBoxedType(ctx_, expr->getType().getNonReferenceType()) &&
2487-
IsBoxedType(ctx_, expr->getArg(0)->getType().getNonReferenceType());
2491+
IsBoxedType(expr->getType().getNonReferenceType()) &&
2492+
IsBoxedType(expr->getArg(0)->getType().getNonReferenceType());
24882493

24892494
// An element of an unboxed container is accessed directly, as is one of
24902495
// a container stored in a Value that can be borrowed.
@@ -2583,9 +2588,7 @@ std::string ConverterRefCount::ConvertElemPlace(clang::Expr *container,
25832588
: nullptr;
25842589
if (field && !field->getType()->isReferenceType() &&
25852590
!field->getParent()->isUnion() && !Mapper::Contains(ctx_, member) &&
2586-
!IsUnboxedPlace(member) &&
2587-
Mapper::Map(ctx_, field->getType().getUnqualifiedType())
2588-
.starts_with("Vec<")) {
2591+
!IsUnboxedPlace(member) && IsVecType(field->getType())) {
25892592
if (IsFieldOfVectorElem(member)) {
25902593
return std::format("index!({}, {})", ConvertPlace(member),
25912594
ConvertSubscriptIndex(idx));
@@ -2600,8 +2603,7 @@ std::string ConverterRefCount::ConvertElemPlace(clang::Expr *container,
26002603
container->IgnoreParenNoopCasts(ctx_));
26012604
if ((IsReferenceType(container) ||
26022605
(deref && deref->getOpcode() == clang::UO_Deref)) &&
2603-
Mapper::Map(ctx_, container->getType().getUnqualifiedType())
2604-
.starts_with("Vec<")) {
2606+
IsVecType(container->getType())) {
26052607
ConvertLValue(container);
26062608
if (!pending_deref_.empty()) {
26072609
auto place = pending_deref_.take();

‎cpp2rust/converter/models/converter_refcount.h‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -422,7 +422,23 @@ class ConverterRefCount final : public Converter {
422422

423423
const char *GetConversionTraitName() const override;
424424

425-
std::string GetInnerType(clang::QualType type);
425+
std::string ConvertPtrRead(clang::QualType type,
426+
const std::string &src) override;
427+
428+
std::string ConvertPtrWrite(const std::string &dst,
429+
const std::string &value) override;
430+
431+
std::string ConvertPointeeMethodCall(const char *method,
432+
const std::string &dst,
433+
const std::string &src) override;
434+
435+
const char *GetMoveCtorTraitName() const override;
436+
437+
bool IsBoxedType(clang::QualType type);
438+
bool IsVecType(clang::QualType type);
439+
440+
bool NeedsMutAccess(const clang::CXXMethodDecl *method,
441+
clang::QualType base_type);
426442

427443
// What an Object-kind conversion of a boxed container/array should yield:
428444
// a pointer to the whole object (Ptr<Vec<T>>), or one to its first

‎cpp2rust/converter/translation_rule.cpp‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,14 @@ TypeInfo ParseTypeInfoJSON(const llvm::json::Object &obj) {
3535
info.derives.emplace_back(s->str());
3636
}
3737
}
38+
if (auto *elems = obj.getObject("elems")) {
39+
auto kind = elems->getString("kind");
40+
auto type = elems->getString("type");
41+
assert(kind && type);
42+
assert(*kind == "vec" || *kind == "array");
43+
info.elems = Elems{*kind == "vec" ? ElemsKind::kVec : ElemsKind::kArray,
44+
type->str()};
45+
}
3846
return info;
3947
}
4048

@@ -346,6 +354,8 @@ void TypeInfo::dump() const {
346354
log() << " [rc_ptr]";
347355
if (is_unsafe_pointer)
348356
log() << " [unsafe_ptr]";
357+
if (elems)
358+
log() << " [elems " << elems->type << ']';
349359
for (const auto &d : derives)
350360
log() << " +" << d;
351361
}

‎cpp2rust/converter/translation_rule.h‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
#include <llvm/Support/JSON.h>
1010

1111
#include <filesystem>
12+
#include <optional>
1213
#include <string>
1314
#include <variant>
1415
#include <vector>
@@ -93,12 +94,20 @@ struct Bound {
9394
bool AnyFragment(const std::vector<BodyFragment> &body,
9495
llvm::function_ref<bool(const BodyFragment &)> pred);
9596

97+
enum class ElemsKind { kVec, kArray };
98+
99+
struct Elems {
100+
ElemsKind kind;
101+
std::string type;
102+
};
103+
96104
struct TypeInfo {
97105
std::vector<std::string> derives;
98106
std::string type;
99107
std::string cpp_type;
100108
bool is_refcount_pointer = false;
101109
bool is_unsafe_pointer = false;
110+
std::optional<Elems> elems;
102111

103112
bool is_pointer() const { return is_refcount_pointer || is_unsafe_pointer; }
104113

0 commit comments

Comments
 (0)