Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
097a707
Update tests
lucic71 Dec 3, 2026
9288bf3
Stop implementing methods on SImpl
lucic71 Dec 3, 2026
864a633
Update tests
lucic71 Dec 3, 2026
c71898d
Add EqualityComparable
lucic71 Dec 3, 2026
8d68645
Update tests
lucic71 Dec 3, 2026
f25479c
Receive raw pointer in unsafe instead of reference
lucic71 Dec 3, 2026
46d1836
Merge branch 'ptr-receiver-ref' into partia-eq-as-cpp-trait
lucic71 Dec 3, 2026
a6dfbbc
format
lucic71 Dec 3, 2026
9b9e0dd
Update tests
lucic71 Dec 3, 2026
8bab5d5
Fix signature of trait derived from free function operator
lucic71 Dec 3, 2026
9d010c0
Update tests
lucic71 Dec 3, 2026
4f7c7f7
Use the equality traits inside rules
lucic71 Dec 3, 2026
fd5ea20
Synthesize not_equal
lucic71 Dec 3, 2026
8fbc98b
Make WeaklyEqualityComparableWith symmetric
lucic71 Dec 3, 2026
449ebef
Remove PartialEq where possible
lucic71 Dec 3, 2026
030786f
Update tests
lucic71 Dec 3, 2026
548778a
Add WeaklyEqualityComparableWith for refcount pointers
lucic71 Dec 3, 2026
6d1f1a3
Stop emitting PartialEq, PartialOrd, Ord
lucic71 Dec 3, 2026
0481659
Update tests
lucic71 Dec 3, 2026
9ba4036
Add LessThanComparable, PartiallyOrderedWith, TotallyOrdered
lucic71 Dec 3, 2026
f676994
Add TotallyOrdered
lucic71 Dec 3, 2026
4fd69cc
Use macro to genrate TotallyOrdered
lucic71 Dec 3, 2026
5289a6a
Translate weak, partial and strong ordering
lucic71 Dec 3, 2026
8b69302
Add ThreeWayComparable trait
lucic71 Dec 3, 2026
04617d3
Merge branch 'master' into ord-as-cpp-trait
lucic71 Dec 3, 2026
673cf43
Merge branch 'master' into ord-as-cpp-trait
lucic71 Dec 3, 2026
9f99bee
Update tests
lucic71 Dec 3, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
201 changes: 117 additions & 84 deletions cpp2rust/converter/converter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -74,36 +74,36 @@ Converter::DeferredBlock &Converter::DeferredImpl(std::string header) {
return it->second;
}

void Converter::AddEqualityComparableMethod(const clang::FunctionDecl *op,
const RecordTrait &trait,
std::string_view method) {
void Converter::AddComparisonTraitMethod(const clang::FunctionDecl *op,
const RecordTrait &trait,
std::string_view method) {
auto *record = GetComparisonRecord(op);
auto name = GetRecordName(record);
clang::QualType lhs = ctx_.getCanonicalTagType(record);
auto rhs = GetComparisonRhsType(op);
if (lhs == rhs) {
EqualityComparableImpl(name, "").body += method;
ComparisonTraitImpl(trait, name, "").body += method;
if (&trait == &kWeaklyEqualityComparableWith) {
converted_record_traits_.emplace(name, trait.refcount.name);
}
return;
}
auto other = GetUnboxedTypeAsString(rhs);
EqualityComparableImpl(name, other).body += method;
ComparisonTraitImpl(trait, name, other).body += method;
if (&trait != &kWeaklyEqualityComparableWith ||
HasEqualityOperator(ctx_, rhs, lhs)) {
FindComparisonOperator(ctx_, rhs, lhs, clang::OO_EqualEqual)) {
return;
}
EqualityComparableImpl(other, name).body +=
ComparisonTraitImpl(trait, other, name).body +=
std::format("{} {{ <{} as {}<{}>>::{}(rhs, lhs) }}\n",
GetComparisonTraitSignature(trait, "lhs", "rhs", name), name,
GetRecordTraitSpelling(trait).name, other, trait.method);
}

Converter::DeferredBlock &
Converter::EqualityComparableImpl(std::string_view self,
std::string_view other) {
const char *name = GetRecordTraitSpelling(kWeaklyEqualityComparableWith).name;
Converter::ComparisonTraitImpl(const RecordTrait &trait, std::string_view self,
std::string_view other) {
const char *name = GetRecordTraitSpelling(trait).name;
if (other.empty()) {
return DeferredImpl(std::format("impl {} for {}", name, self));
}
Expand Down Expand Up @@ -136,13 +136,16 @@ void Converter::EmitUndefinedRecordTraits(Model model, std::string &out) {
void Converter::DeclareRecordTraits(const clang::CXXRecordDecl *decl) {
auto &traits = declared_record_traits_[GetRecordName(decl)];
for (auto *method : decl->methods()) {
if (GetComparisonTrait(method)) {
if (IsSameTypeComparison(method, decl)) {
if (auto *comparison = GetComparisonTrait(method);
comparison && HasDeferredComparisonImpl(*comparison)) {
if (IsEqualityComparableTrait(*comparison) &&
IsSameTypeComparison(method, decl)) {
traits.emplace(kWeaklyEqualityComparableWith.refcount.name,
&kWeaklyEqualityComparableWith);
}
} else if (auto *trait = GetRecordTrait(method);
trait && !IsDerivedCopyOrMove(method)) {
trait && trait != &kThreeWayComparable &&
!IsDerivedCopyOrMove(method)) {
traits.emplace(trait->refcount.name, trait);
}
}
Expand Down Expand Up @@ -590,7 +593,24 @@ void Converter::ConvertComparisonTraitImpl(clang::FunctionDecl *decl,
}
method = std::move(buf).str();
}
AddEqualityComparableMethod(decl, trait, method);
if (HasDeferredComparisonImpl(trait)) {
AddComparisonTraitMethod(decl, trait, method);
return;
}
auto record_name = GetRecordName(GetComparisonRecord(decl));
converted_record_traits_.emplace(record_name, trait.refcount.name);
StrCat(keyword::kImpl, GetRecordTraitSpelling(trait).name, "for",
record_name);
PushBrace impl_brace(*this);
if (&trait == &kThreeWayComparable) {
StrCat(GetComparisonCategory(decl));
}
StrCat(method);
}

std::string Converter::GetComparisonCategory(const clang::FunctionDecl *op) {
return std::format("type Category = {};",
GetUnboxedTypeAsString(op->getReturnType()));
}

void Converter::EmitHoistedDecls(clang::CompoundStmt *body) {
Expand Down Expand Up @@ -1215,15 +1235,18 @@ void Converter::ConvertCopyOrMoveTraitImpl(clang::CXXMethodDecl *method,
if (body.empty()) {
return;
}
if (GetComparisonTrait(method)) {
AddEqualityComparableMethod(method, trait, body);
if (HasDeferredComparisonImpl(trait)) {
AddComparisonTraitMethod(method, trait, body);
return;
}
converted_record_traits_.emplace(GetRecordName(method->getParent()),
trait.refcount.name);
StrCat(keyword::kImpl, GetCopyOrMoveTraitName(trait), "for",
GetRecordName(method->getParent()));
PushBrace brace(*this);
if (&trait == &kThreeWayComparable) {
StrCat(GetComparisonCategory(method));
}
StrCat(body);
}

Expand All @@ -1245,11 +1268,27 @@ std::string Converter::DestroyMembers(const clang::CXXRecordDecl *decl) {
}

void Converter::EmitDerives(const clang::RecordDecl *decl) {
auto *cxx = clang::dyn_cast<clang::CXXRecordDecl>(decl);
auto *three_way = cxx ? GetDerivingThreeWayOperator(ctx_, cxx) : nullptr;
StrCat("#[derive(");
for (auto *attr : GetStructAttributes(decl)) {
StrCat(attr, ',');
}
if (three_way) {
StrCat(GetCopyOrMoveTraitName(kPartiallyOrderedWith), ',');
}
StrCat(")]");
if (auto *method = clang::dyn_cast_or_null<clang::CXXMethodDecl>(three_way)) {
StrCat(std::format("#[three_way({}::{})]", GetUFCSName(method),
GetMethodName(method)));
} else if (auto *trait =
three_way ? GetComparisonTrait(three_way) : nullptr) {
StrCat(std::format("#[three_way({}::{})]", GetCopyOrMoveTraitName(*trait),
trait->method));
} else if (three_way) {
StrCat(std::format("#[three_way({})]",
GetNamedDeclAsString(three_way->getCanonicalDecl())));
}
if (auto methods = GetDerivedCopyOrMoves(decl); !methods.empty()) {
StrCat("#[memberwise(");
for (auto *method : methods) {
Expand Down Expand Up @@ -3484,9 +3523,13 @@ bool Converter::VisitBinaryOperator(clang::BinaryOperator *expr) {
}

if (expr->getOpcode() == clang::BO_Cmp) {
EmitFresh(std::format("std::cmp::Ord::cmp(&({}), &({}))",
ConvertRValue(expr->getLHS()),
ConvertRValue(expr->getRHS())));
auto *category = ctx_.CompCategories.lookupInfoForType(expr->getType());
assert(category && "built-in <=> gives a comparison category");
EmitFresh(std::format(
"{}::from(std::cmp::{}(&({}), &({})))",
GetUnboxedTypeAsString(expr->getType()),
category->isPartial() ? "PartialOrd::partial_cmp" : "Ord::cmp",
ConvertRValue(expr->getLHS()), ConvertRValue(expr->getRHS())));
return false;
}
bool needs_cast = (expr->isComparisonOp() || expr->isLogicalOp()) &&
Expand Down Expand Up @@ -5903,34 +5946,6 @@ bool Converter::ConvertOutOfLineVirtualMethod(clang::CXXMethodDecl *decl) {
return emitted;
}

void Converter::ConvertOrdAndPartialOrdTraitsBase(
std::string_view cmp_body, std::string_view eq_body,
std::string_view record_name) {
if (cmp_body.empty()) {
return;
}
StrCat(keyword::kImpl, "std::cmp::Ord for ", record_name, '{');
StrCat("fn cmp(&self, other: &Self) -> std::cmp::Ordering {");
StrCat(std::format("{} {{", keyword_unsafe_));
StrCat(cmp_body);
StrCat("}}}");

StrCat(keyword::kImpl, "std::cmp::PartialOrd for", record_name, '{');
StrCat(R"(
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
})");

StrCat(keyword::kImpl, "std::cmp::PartialEq for", record_name, '{');
StrCat("fn eq(&self, other: &Self) -> bool {");
StrCat(std::format("{} {{", keyword_unsafe_));
StrCat(eq_body);
StrCat("}}}");

StrCat(keyword::kImpl, "std::cmp::Eq for", record_name, "{}");
}

std::string Converter::GetComparisonCall(const clang::FunctionDecl *op,
const clang::CXXRecordDecl *decl,
std::string_view lhs,
Expand Down Expand Up @@ -6011,46 +6026,63 @@ std::string Converter::GetComparisonReceiver(const clang::CXXMethodDecl *method,
return is_mut ? std::format("{}.cast_mut()", lhs) : std::string(lhs);
}

std::string Converter::GetEqBody(const clang::CXXRecordDecl *decl,
const clang::FunctionDecl *eq,
const clang::FunctionDecl *lt,
const clang::FunctionDecl *cmp,
std::string_view lhs, std::string_view rhs) {
if (eq) {
return GetComparisonBool(eq, decl, lhs, rhs);
}
if (cmp) {
return std::format("{} == std::cmp::Ordering::Equal",
GetComparisonCall(cmp, decl, lhs, rhs));
}
return std::format("!({}) && !({})", GetComparisonBool(lt, decl, lhs, rhs),
GetComparisonBool(lt, decl, rhs, lhs));
}

void Converter::ConvertOrdAndPartialOrdTraits(const clang::CXXRecordDecl *decl,
const clang::FunctionDecl *eq,
const clang::FunctionDecl *lt,
const clang::FunctionDecl *cmp) {
const char *kSelfPtr = "(self as *const Self)";
const char *kOtherPtr = "(other as *const Self)";
std::string cmp_body;
if (cmp) {
cmp_body = GetComparisonCall(cmp, decl, kSelfPtr, kOtherPtr);
} else if (lt) {
cmp_body = std::format("if {} {{ std::cmp::Ordering::Less }} else if {} {{ "
"std::cmp::Ordering::Greater }} else {{ "
"std::cmp::Ordering::Equal }}",
GetComparisonBool(lt, decl, kSelfPtr, kOtherPtr),
GetComparisonBool(lt, decl, kOtherPtr, kSelfPtr));
}
ConvertOrdAndPartialOrdTraitsBase(
cmp_body, GetEqBody(decl, eq, lt, cmp, kSelfPtr, kOtherPtr),
GetRecordName(decl));
void Converter::ConvertComparisonTraitWrappers(const clang::CXXRecordDecl *decl,
const clang::FunctionDecl *eq,
const clang::FunctionDecl *lt,
const clang::FunctionDecl *cmp) {
if (auto *op = lt ? lt : cmp; op && !(lt && GetComparisonTrait(lt))) {
const auto &trait = kLessThanComparable;
auto [lhs, rhs] = GetComparisonOperandNames(op);
StrCat(keyword::kImpl, GetRecordTraitSpelling(trait).name, "for",
GetRecordName(decl));
PushBrace impl_brace(*this);
StrCat(GetComparisonTraitSignature(trait, lhs, rhs, "Self"));
PushBrace body(*this);
if (lt) {
StrCat(GetComparisonBool(lt, decl, lhs, rhs));
} else {
StrCat(std::format("libcc2rs::is_lt({})",
GetComparisonCall(cmp, decl, lhs, rhs)));
}
}
if (eq && !GetComparisonTrait(eq)) {
ConvertEqualityComparableImpl(decl, eq);
}
}

void Converter::ConvertPartiallyOrderedWithImpl(
const clang::CXXRecordDecl *decl) {
if (!IsPartiallyOrdered(ctx_, decl) ||
GetDerivingThreeWayOperator(ctx_, decl)) {
return;
}
clang::QualType type = ctx_.getCanonicalTagType(decl);
auto *cmp = FindComparisonOperator(ctx_, type, type, clang::OO_Spaceship);
auto add = [&](const RecordTrait &trait, const std::string &body) {
ComparisonTraitImpl(trait, GetRecordName(decl), "").body += std::format(
"{} {{ {} }}\n",
GetComparisonTraitSignature(trait, "lhs", "rhs", "Self"), body);
};
add(kPartiallyOrderedWith,
std::format("<Self as {}>::{}(lhs, rhs)",
GetRecordTraitSpelling(kLessThanComparable).name,
kLessThanComparable.method));
const std::pair<clang::OverloadedOperatorKind, const char *> relations[] = {
{clang::OO_Greater, "is_gt"},
{clang::OO_LessEqual, "is_lteq"},
{clang::OO_GreaterEqual, "is_gteq"}};
for (auto [kind, from_three_way] : relations) {
const auto &trait = GetPartiallyOrderedWithTrait(kind);
auto *op = FindComparisonOperator(ctx_, type, type, kind);
if (!op) {
add(trait, std::format("libcc2rs::{}({})", from_three_way,
GetComparisonCall(cmp, decl, "lhs", "rhs")));
} else if (!GetComparisonTrait(op)) {
add(trait, GetComparisonBool(op, decl, "lhs", "rhs"));
}
}
}

std::pair<std::string, std::string>
Converter::GetComparisonOperandNames(const clang::FunctionDecl *op) {
auto params = DefinitionParameters(op);
Expand All @@ -6066,7 +6098,7 @@ void Converter::ConvertEqualityComparableImpl(const clang::CXXRecordDecl *decl,
? kWeaklyEqualityComparableWithNotEqual
: kWeaklyEqualityComparableWith;
auto [lhs, rhs] = GetComparisonOperandNames(op);
AddEqualityComparableMethod(
AddComparisonTraitMethod(
op, trait,
std::format("{} {{ {} }}\n",
GetComparisonTraitSignature(trait, lhs, rhs, "Self"),
Expand Down Expand Up @@ -6140,12 +6172,13 @@ void Converter::AddOrdTrait(const clang::CXXRecordDecl *decl) {
if (eq && ne && !GetComparisonTrait(ne)) {
ConvertEqualityComparableImpl(decl, ne);
}
ConvertPartiallyOrderedWithImpl(decl);

if (!eq && !lt && !cmp) {
return;
}

ConvertOrdAndPartialOrdTraits(decl, eq, lt, cmp);
ConvertComparisonTraitWrappers(decl, eq, lt, cmp);
}

void Converter::AddSpecialMemberDerives(const clang::RecordDecl *decl,
Expand Down
33 changes: 14 additions & 19 deletions cpp2rust/converter/converter.h
Original file line number Diff line number Diff line change
Expand Up @@ -501,6 +501,10 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
void ConvertEqualityComparableImpl(const clang::CXXRecordDecl *decl,
const clang::FunctionDecl *op);

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

std::string GetComparisonCategory(const clang::FunctionDecl *op);

void ConvertParamTy(clang::QualType param_type, clang::Expr *expr);

virtual void ConvertParamTyConstCast(clang::QualType param_type,
Expand Down Expand Up @@ -968,20 +972,10 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {

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

virtual void ConvertOrdAndPartialOrdTraits(const clang::CXXRecordDecl *decl,
const clang::FunctionDecl *eq,
const clang::FunctionDecl *lt,
const clang::FunctionDecl *cmp);

std::string GetEqBody(const clang::CXXRecordDecl *decl,
const clang::FunctionDecl *eq,
const clang::FunctionDecl *lt,
const clang::FunctionDecl *cmp, std::string_view lhs,
std::string_view rhs);

void ConvertOrdAndPartialOrdTraitsBase(std::string_view cmp_body,
std::string_view eq_body,
std::string_view record_name);
void ConvertComparisonTraitWrappers(const clang::CXXRecordDecl *decl,
const clang::FunctionDecl *eq,
const clang::FunctionDecl *lt,
const clang::FunctionDecl *cmp);

std::string GetComparisonCall(const clang::FunctionDecl *op,
const clang::CXXRecordDecl *decl,
Expand Down Expand Up @@ -1394,12 +1388,13 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {

static DeferredBlock &DeferredImpl(std::string header);

DeferredBlock &EqualityComparableImpl(std::string_view self,
std::string_view other);
DeferredBlock &ComparisonTraitImpl(const RecordTrait &trait,
std::string_view self,
std::string_view other);

void AddEqualityComparableMethod(const clang::FunctionDecl *op,
const RecordTrait &trait,
std::string_view method);
void AddComparisonTraitMethod(const clang::FunctionDecl *op,
const RecordTrait &trait,
std::string_view method);
static std::map<std::string, std::map<std::string, const RecordTrait *>>
declared_record_traits_;
static std::set<std::pair<std::string, std::string>> converted_record_traits_;
Expand Down
Loading
Loading