Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
b3ac62c
Update tests
lucic71 Dec 3, 2026
32b3d57
Add value category and cv markers
lucic71 Dec 3, 2026
ccc03b6
Update tests
lucic71 Dec 3, 2026
9cb3c09
Add value category and cv markers
lucic71 Dec 3, 2026
3ae93bb
Update rules
lucic71 Dec 3, 2026
d7a3cec
Use explicit as_pointer for refrences
lucic71 Dec 3, 2026
2db5e33
Add refrence support in converter
lucic71 Dec 3, 2026
96d3e28
Add tests for reference collapsing and reference binding
lucic71 Dec 3, 2026
7f42416
Update tests
lucic71 Dec 3, 2026
76ef34b
Update tests
lucic71 Dec 3, 2026
92e8268
Update tests
lucic71 Dec 3, 2026
7c0d2c2
Merge branch 'master' into constructible-from
lucic71 Dec 3, 2026
6073dd9
Update tests
lucic71 Dec 3, 2026
dd9d152
Update rules
lucic71 Dec 3, 2026
2073c69
Write unsafe by default zero-initialization
lucic71 Dec 3, 2026
d01affa
Add equality comparable for references
lucic71 Dec 3, 2026
3c593b3
Add ConstructibleFrom and ConvertibleTo
lucic71 Dec 3, 2026
213423e
Update rules
lucic71 Dec 3, 2026
44e3656
Update rules
lucic71 Dec 4, 2026
bd86de1
Add runtime overload resolution
lucic71 Dec 4, 2026
4d48edb
Update tests
lucic71 Dec 4, 2026
7585db9
Update rules
lucic71 Dec 4, 2026
4e5f8c0
Add ConvertibleTo and ConstructibleFrom as marker traits
lucic71 Dec 4, 2026
6867d2f
MoveConstructible and CopyConstructible are markers over Converter
lucic71 Dec 4, 2026
99716f6
Merge remote-tracking branch 'upstream/master' into constructible-from
lucic71 Dec 4, 2026
b7f54bc
Add converter support for ConvertibleTo and ConstructibleFrom
lucic71 Dec 4, 2026
856d397
Remove leftover impl
lucic71 Dec 4, 2026
46c532d
Update expected output
lucic71 Dec 4, 2026
6043785
Update tests
lucic71 Dec 4, 2026
fa8ef82
Fix
lucic71 Dec 4, 2026
57d5d83
Add Pointer marker
lucic71 Dec 4, 2026
7982a85
format
lucic71 Dec 4, 2026
8fa523d
Fix inference of input
lucic71 Dec 4, 2026
d53a23f
Remove comments
lucic71 Dec 4, 2026
4f583d9
Fix macos
lucic71 Dec 4, 2026
b985af1
Fix formatting
lucic71 Dec 4, 2026
9865e61
Fix macos
lucic71 Dec 4, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
3 changes: 3 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ find_program(RUFF NAMES ruff)
file(GLOB_RECURSE ALL_CXX_SOURCES
cpp2rust/*.cpp cpp2rust/*.h rules/*.cpp rules/*.c rules/*.h tests/*.cpp tests/*.c)

file(GLOB_RECURSE RULE_RUST_SOURCES rules/*/*.rs)

set(PYTHON_SOURCES ${PROJECT_SOURCE_DIR}/tests/lit/lit/formats/Cpp2RustTest.py)

# `clippy --fix` downgrades -Dwarnings errors back to warnings, and manifest
Expand All @@ -109,6 +111,7 @@ set(CLIPPY_ENV CARGO_BUILD_WARNINGS=deny)
add_custom_target("format"
COMMAND ${CLANG_FORMAT} -i ${ALL_CXX_SOURCES}
COMMAND cargo +${RUST_STABLE_VERSION} fmt --manifest-path ${PROJECT_SOURCE_DIR}/rules/Cargo.toml
COMMAND rustfmt +${RUST_STABLE_VERSION} --edition 2024 ${RULE_RUST_SOURCES}
COMMAND cargo +${RUST_NIGHTLY_VERSION} fmt --manifest-path ${PROJECT_SOURCE_DIR}/rule-preprocessor/Cargo.toml
COMMAND cargo +${RUST_STABLE_VERSION} fmt --manifest-path ${PROJECT_SOURCE_DIR}/libcc2rs/Cargo.toml
COMMAND cargo +${RUST_STABLE_VERSION} fmt --manifest-path ${PROJECT_SOURCE_DIR}/libcc2rs-macros/Cargo.toml
Expand Down
441 changes: 269 additions & 172 deletions cpp2rust/converter/converter.cpp

Large diffs are not rendered by default.

36 changes: 22 additions & 14 deletions cpp2rust/converter/converter.h
Original file line number Diff line number Diff line change
Expand Up @@ -101,12 +101,28 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {

std::string GetTemplateArgumentAsString(const clang::TemplateArgument &arg);

bool IsReferenceToObject(clang::QualType type) const;

std::string GetReferenceMarkerAsString(clang::QualType type);

virtual const char *GetReferenceMarker(bool is_rvalue) const;

virtual const char *GetParameterObjectMarker() const;

virtual const char *GetPointerMarker() const;

std::string GetPointerMarkerAsString(clang::QualType type);

std::string GetCvObjectAsString(clang::QualType object);

std::string GetParameterObjectType(clang::QualType type);

void EmitConversionsAttrs(const clang::CXXRecordDecl *decl);

virtual const char *GetConversionsTrait() const;

std::string GetConstructorArgType(const clang::ParmVarDecl *param);

virtual std::string GetParamTypeAsString(const clang::ParmVarDecl *param);

virtual std::string CollapseReference(std::string_view result,
clang::QualType referred,
bool is_place);
Expand Down Expand Up @@ -197,8 +213,6 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
void EmitReprC(clang::RecordDecl *decl);
void EmitDerives(const clang::RecordDecl *decl);

void EmitConversionAttrs(clang::CXXRecordDecl *decl);

virtual void EmitRustUnion(clang::RecordDecl *decl);

virtual bool EmitsReprCForRecords() const { return true; }
Expand Down Expand Up @@ -273,9 +287,6 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {

virtual const char *GetConstructorWrite() const;

virtual std::string
GetConstructorPath(const clang::CXXConstructorDecl *ctor) const;

// A variable named name that holds zero-initialized storage for a record,
// in which a constructor constructs the record.
virtual std::string
Expand All @@ -298,7 +309,7 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {

virtual const char *TakePlacementValue() const;

virtual const char *GetReturnSlotReceiver() const;
virtual std::string GetReturnSlotReceiver(std::string_view slot) const;

virtual std::string GetReturnSlotArg(std::string_view receiver) const;

Expand Down Expand Up @@ -396,11 +407,6 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
clang::Expr *expr, llvm::ArrayRef<clang::Expr *> args,
TempMaterializationCtx *ctx);

std::string ConvertConversion(clang::QualType to, clang::QualType from,
bool is_move, const std::string &ptr);

virtual const char *GetConversionTraitName() const;

virtual const RecordTraitSpelling &
GetRecordTraitSpelling(const RecordTrait &trait) const;

Expand Down Expand Up @@ -1024,7 +1030,8 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
virtual std::string
GetAssignmentTraitSignature(const RecordTrait &trait) const;

std::string GetCopyOrMoveSourceType(const RecordTrait &trait) const;
std::string GetCopyOrMoveSourceType(const RecordTrait &trait,
std::string_view self = "Self") const;

virtual void AddDefaultTraitForUnion(const clang::RecordDecl *decl);

Expand Down Expand Up @@ -1236,6 +1243,7 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
bool in_function_formals_ = false;

std::string ufcs_receiver_;

bool in_const_initializer_ = false;
bool constant_evaluated_ = false;
std::optional<bool> autoref_mut_;
Expand Down
139 changes: 132 additions & 7 deletions cpp2rust/converter/converter_lib.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -871,12 +871,12 @@ const RecordTrait *GetRecordTrait(const clang::CXXMethodDecl *method) {
: nullptr;
}
const char *name = GetCopyOrMoveName(method);
auto *ctor = clang::dyn_cast<clang::CXXConstructorDecl>(method);
if (!name || method->isDeleted() || method->isVirtual() ||
!CanUseCopyOrMoveName(method, name) ||
(!ctor && !CanUseCopyOrMoveName(method, name)) ||
(!IsUserWrittenMember(method) && !IsTranslatedSpecialMember(method))) {
return nullptr;
}
auto *ctor = clang::dyn_cast<clang::CXXConstructorDecl>(method);
if (!ctor && !method->getReturnType()->isLValueReferenceType()) {
return nullptr;
}
Expand All @@ -896,6 +896,18 @@ const RecordTrait *GetRecordTrait(const clang::CXXMethodDecl *method) {
return is_copy ? &kCopyAssignable : &kMoveAssignable;
}

bool IsConstructibleFromConstructor(const clang::FunctionDecl *decl) {
auto *ctor = clang::dyn_cast_or_null<clang::CXXConstructorDecl>(decl);
if (!ctor || ctor->isDeleted() || ctor->isVariadic() ||
ctor->getNumParams() == 0 || GetRecordTrait(ctor)) {
return false;
}
auto *record = ctor->getParent();
return IsUserDefinedDecl(record) && !record->isLambda() &&
!record->isAbstract() && !record->isDependentContext() &&
!record->isUnion();
}

const clang::ParmVarDecl *GetCopyOrMoveSource(const clang::FunctionDecl *decl) {
auto *method = clang::dyn_cast<clang::CXXMethodDecl>(decl);
auto *trait = method ? GetRecordTrait(method) : nullptr;
Expand Down Expand Up @@ -1029,23 +1041,22 @@ bool MovesRuleArg(clang::Expr *expr, unsigned arg_idx, clang::Expr *arg,
return moved && !clang::isa<clang::MaterializeTemporaryExpr>(arg);
}

static bool
IsImplicitConvertingConstructor(const clang::CXXConstructorDecl *ctor) {
static bool IsOneArgumentConstructor(const clang::CXXConstructorDecl *ctor) {
return !ctor->isCopyOrMoveConstructor() && !ctor->isImplicit() &&
!ctor->isDeleted() && ctor->hasBody() && ctor->getNumParams() == 1 &&
ctor->isConvertingConstructor(/*AllowExplicit=*/false);
ctor->isConvertingConstructor(/*AllowExplicit=*/true);
}

void ForEachConvertingConstructor(
clang::CXXRecordDecl *decl,
llvm::function_ref<void(clang::CXXConstructorDecl *)> fn) {
for (auto *ctor : decl->ctors()) {
if (IsImplicitConvertingConstructor(ctor)) {
if (IsOneArgumentConstructor(ctor)) {
fn(ctor);
}
}
for (auto *ctor : GetTemplateInstantiatedCtors(decl)) {
if (IsImplicitConvertingConstructor(ctor)) {
if (IsOneArgumentConstructor(ctor)) {
fn(ctor);
}
}
Expand Down Expand Up @@ -1487,6 +1498,103 @@ unsigned GetCtorIndex(clang::CXXConstructorDecl *ctor) {
return static_cast<unsigned>(std::distance(vec.begin(), it) + 1);
}

const RecordTrait *GetMethodTrait(const clang::FunctionDecl *decl) {
auto *method = clang::dyn_cast_or_null<clang::CXXMethodDecl>(decl);
return method && !clang::isa<clang::CXXConstructorDecl>(method)
? GetRecordTrait(method)
: nullptr;
}

bool IsReferenceToObject(clang::QualType type) {
if (!type->isReferenceType()) {
return false;
}
auto pointee = type->getPointeeType();
auto *record = pointee->getAsCXXRecordDecl();
return !pointee->isFunctionType() && !pointee->isArrayType() &&
!IsVaListType(pointee) && !(record && IsAbstractUserClass(record));
}

bool HasConversionsTable(clang::QualType type) {
if (IsVaListType(type.getNonReferenceType())) {
return false;
}
type = type.getNonReferenceType().getCanonicalType();
if (type->isArithmeticType() && !type->isEnumeralType()) {
return true;
}
if (type->isPointerType()) {
return HasConversionsTable(type->getPointeeType());
}
auto *record = type->getAsCXXRecordDecl();
return record && record->isCompleteDefinition() &&
IsUserDefinedDecl(record) && !record->isLambda() &&
!record->isAbstract() && !record->isUnion() &&
!record->isDependentContext();
}

bool UsesPointerMarker(clang::QualType type) {
return type->isPointerType() && HasConversionsTable(type) &&
!type->getPointeeType().isVolatileQualified();
}

bool IsTableConversionFunction(const clang::CXXConversionDecl *conversion) {
auto *record = conversion->getParent();
auto type = conversion->getConversionType();
return IsUserDefinedDecl(record) && !record->isLambda() &&
!record->isDependentContext() && !IsAbstractUserClass(record) &&
!conversion->isDeleted() && !conversion->isVirtual() &&
!type->isReferenceType() && HasConversionsTable(type) &&
!conversion->getMethodQualifiers().hasVolatile();
}

std::optional<std::string> GetInitMethod(const clang::FunctionDecl *decl) {
auto *ctor = clang::dyn_cast_or_null<clang::CXXConstructorDecl>(decl);
if (!ctor || IsDerivedCopyOrMove(ctor) ||
(!GetRecordTrait(ctor) && !IsConstructibleFromConstructor(ctor))) {
return std::nullopt;
}
if (ctor->getPrimaryTemplate()) {
return std::format(
"constructor_{}_{}", GetDeclaredCtorIndex(ctor),
GetCtorIndex(const_cast<clang::CXXConstructorDecl *>(ctor)));
}
return std::format("constructor_{}", GetDeclaredCtorIndex(ctor));
}

bool IsEmittedConstructor(clang::CXXConstructorDecl *ctor) {
return IsEmittableMethod(ctor) && IsConvertedConstructor(ctor) &&
!IsDerivedCopyOrMove(ctor) && ctor->isDefined();
}

unsigned GetDeclaredCtorIndex(const clang::CXXConstructorDecl *ctor) {
const clang::Decl *target = ctor->getCanonicalDecl();
if (auto *tmpl = ctor->getPrimaryTemplate()) {
target = tmpl->getCanonicalDecl();
}
unsigned declared = 0;
for (auto *decl : ctor->getParent()->decls()) {
if (decl->isImplicit()) {
continue;
}
auto *templated = decl;
if (auto *tmpl = clang::dyn_cast<clang::FunctionTemplateDecl>(decl)) {
templated = tmpl->getTemplatedDecl();
}
if (!clang::isa<clang::CXXConstructorDecl>(templated)) {
continue;
}
++declared;
if (decl->getCanonicalDecl() == target) {
return declared;
}
}
if (ctor->isDefaultConstructor()) {
return declared + 1;
}
return declared + (ctor->isCopyConstructor() ? 2 : 3);
}

clang::CXXConstructorDecl *
GetUserDefinedDefaultConstructor(const clang::CXXRecordDecl *decl) {
for (auto c : decl->ctors()) {
Expand Down Expand Up @@ -3222,4 +3330,21 @@ const char *GetConstCastSuffix(clang::QualType to, clang::QualType from) {
return to.isConstQualified() ? ".cast_const()" : ".cast_mut()";
}

bool HasConstructor(const clang::CXXRecordDecl *decl, bool is_move) {
if (is_move ? decl->needsImplicitMoveConstructor()
: decl->needsImplicitCopyConstructor()) {
return is_move ? !decl->defaultedMoveConstructorIsDeleted()
: !decl->defaultedCopyConstructorIsDeleted();
}
return llvm::any_of(decl->ctors(), [&](auto *ctor) {
if (ctor->isDeleted()) {
return false;
}
unsigned quals = 0;
return is_move ? ctor->isMoveConstructor()
: ctor->isCopyConstructor(quals) &&
(quals & clang::Qualifiers::Const);
});
}

} // namespace cpp2rust
46 changes: 34 additions & 12 deletions cpp2rust/converter/converter_lib.h
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ struct RecordTraitSpelling {
const char *name;
const char *signature = nullptr;
const char *receiver = nullptr;
const char *constructor = nullptr;
};

struct RecordTrait {
Expand All @@ -119,27 +120,28 @@ struct RecordTrait {

inline constexpr RecordTrait kDefaultConstructible{
"default_constructor",
{"DefaultConstructible", "fn default_constructor(this: Ptr<Self>)",
"this.clone()"},
{"DefaultConstructible", "fn constructor(this: Ptr<Self>, _: ())",
"this.clone()", "Constructor<()>"},
{"DefaultConstructibleUnsafe",
"unsafe fn default_constructor(this: *mut Self)", "this"}};
"unsafe fn constructor(this: *mut Self, _: ())", "this",
"ConstructorUnsafe<()>"}};
inline constexpr RecordTrait kCopyConstructible{
"copy_constructor",
{"CopyConstructible",
"fn copy_constructor(this: Ptr<Self>, _: LvalueRef<Const<Self>>)",
"this.clone()"},
"fn constructor(this: Ptr<Self>, _: (LvalueRef<Const<Self>>,))",
"this.clone()", "Constructor<(LvalueRef<Const<Self>>,)>"},
{"CopyConstructibleUnsafe",
"unsafe fn copy_constructor(this: *mut Self, _: "
"LvalueRefUnsafe<Const<Self>>)",
"this"}};
"unsafe fn constructor(this: *mut Self, _: "
"(LvalueRefUnsafe<Const<Self>>,))",
"this", "ConstructorUnsafe<(LvalueRefUnsafe<Const<Self>>,)>"}};
inline constexpr RecordTrait kMoveConstructible{
"move_constructor",
{"MoveConstructible",
"fn move_constructor(this: Ptr<Self>, _: RvalueRef<Self>)",
"this.clone()"},
"fn constructor(this: Ptr<Self>, _: (RvalueRef<Self>,))", "this.clone()",
"Constructor<(RvalueRef<Self>,)>"},
{"MoveConstructibleUnsafe",
"unsafe fn move_constructor(this: *mut Self, _: RvalueRefUnsafe<Self>)",
"this"}};
"unsafe fn constructor(this: *mut Self, _: (RvalueRefUnsafe<Self>,))",
"this", "ConstructorUnsafe<(RvalueRefUnsafe<Self>,)>"}};
inline constexpr RecordTrait kCopyAssignable{
"copy_assign",
{"CopyAssignable",
Expand Down Expand Up @@ -236,6 +238,10 @@ inline constexpr RecordTrait kMemberwise{

const RecordTrait *GetRecordTrait(const clang::CXXMethodDecl *method);

const RecordTrait *GetMethodTrait(const clang::FunctionDecl *decl);

bool IsConstructibleFromConstructor(const clang::FunctionDecl *decl);

const clang::ParmVarDecl *GetCopyOrMoveSource(const clang::FunctionDecl *decl);

const RecordTrait *GetComparisonTrait(const clang::FunctionDecl *fn);
Expand Down Expand Up @@ -396,6 +402,20 @@ unsigned GetNumberOfConvertingCtors(clang::CXXRecordDecl *decl);

unsigned GetCtorIndex(clang::CXXConstructorDecl *ctor);

unsigned GetDeclaredCtorIndex(const clang::CXXConstructorDecl *ctor);

bool IsReferenceToObject(clang::QualType type);

bool HasConversionsTable(clang::QualType type);

bool UsesPointerMarker(clang::QualType type);

std::optional<std::string> GetInitMethod(const clang::FunctionDecl *decl);

bool IsTableConversionFunction(const clang::CXXConversionDecl *conversion);

bool IsEmittedConstructor(clang::CXXConstructorDecl *ctor);

clang::CXXConstructorDecl *
GetUserDefinedDefaultConstructor(const clang::CXXRecordDecl *decl);

Expand Down Expand Up @@ -664,4 +684,6 @@ void ReplaceAll(std::string &str, std::string_view from, std::string_view to);
// their constness differs, or nullptr if it doesn't.
const char *GetConstCastSuffix(clang::QualType to, clang::QualType from);

bool HasConstructor(const clang::CXXRecordDecl *decl, bool is_move);

} // namespace cpp2rust
Loading
Loading