Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
227 changes: 187 additions & 40 deletions cpp2rust/converter/converter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ std::unordered_set<std::string> Converter::decl_ids_;
std::unordered_set<std::string> Converter::globals_;
std::vector<std::string> Converter::global_inits_;
Converter::RecordIndex Converter::record_decls_;
std::map<std::string, Converter::DeferredBlock> Converter::virtual_methods_;
std::map<std::string, Converter::DeferredBlock> Converter::deferred_impls_;
std::map<std::string, std::map<std::string, const RecordTrait *>>
Converter::declared_record_traits_;
std::set<std::pair<std::string, std::string>>
Expand All @@ -60,12 +60,56 @@ void Converter::EmitDeferredBlock(const DeferredBlock &block,
out += "}\n";
}

void Converter::EmitVirtualMethods(std::string &out) {
for (const auto &[name, impl] : virtual_methods_) {
void Converter::EmitDeferredImpls(std::string &out) {
for (const auto &[header, impl] : deferred_impls_) {
EmitDeferredBlock(impl, out);
}
}

Converter::DeferredBlock &Converter::DeferredImpl(std::string header) {
auto [it, inserted] = deferred_impls_.try_emplace(header);
if (inserted) {
it->second.header = std::move(header);
}
return it->second;
}

void Converter::AddEqualityComparableMethod(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;
if (&trait == &kWeaklyEqualityComparableWith) {
converted_record_traits_.emplace(name, trait.refcount.name);
}
return;
}
auto other = GetUnboxedTypeAsString(rhs);
EqualityComparableImpl(name, other).body += method;
if (&trait != &kWeaklyEqualityComparableWith ||
HasEqualityOperator(ctx_, rhs, lhs)) {
return;
}
EqualityComparableImpl(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;
if (other.empty()) {
return DeferredImpl(std::format("impl {} for {}", name, self));
}
return DeferredImpl(std::format("impl {}<{}> for {}", name, other, self));
}

void Converter::EmitUndefinedRecordTraits(Model model, std::string &out) {
bool is_unsafe = model == Model::kUnsafe;
for (const auto &[record, traits] : declared_record_traits_) {
Expand All @@ -74,6 +118,13 @@ void Converter::EmitUndefinedRecordTraits(Model model, std::string &out) {
continue;
}
const auto &spelling = is_unsafe ? trait->unsafe : trait->refcount;
if (trait == &kWeaklyEqualityComparableWith) {
DeferredImpl(std::format("impl {} for {}", spelling.name, record))
.body +=
std::format("{} {{ unreachable!(\"{}::{} is never defined\") }}\n",
spelling.signature, record, trait->method);
continue;
}
out += std::format(
"impl {} for {} {{ {} {{ unreachable!(\"{}::{} is never defined\") "
"}} }}\n",
Expand All @@ -85,8 +136,13 @@ 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 (auto *trait = GetRecordTrait(method);
trait && !IsDerivedCopyOrMove(method)) {
if (GetComparisonTrait(method)) {
if (IsSameTypeComparison(method, decl)) {
traits.emplace(kWeaklyEqualityComparableWith.refcount.name,
&kWeaklyEqualityComparableWith);
}
} else if (auto *trait = GetRecordTrait(method);
trait && !IsDerivedCopyOrMove(method)) {
traits.emplace(trait->refcount.name, trait);
}
}
Expand Down Expand Up @@ -489,6 +545,10 @@ bool Converter::VisitFunctionDecl(clang::FunctionDecl *decl) {
}
DumpVerbose(decl);
ScopedValue push_fn(curr_function_, decl);
if (auto *trait = GetComparisonTrait(decl)) {
ConvertComparisonTraitImpl(decl, *trait);
return false;
}
std::string function_name;
if (decl->isMain()) {
// main_0 is private.
Expand All @@ -512,6 +572,27 @@ bool Converter::VisitFunctionDecl(clang::FunctionDecl *decl) {
return false;
}

void Converter::ConvertComparisonTraitImpl(clang::FunctionDecl *decl,
const RecordTrait &trait) {
std::string method;
{
Buffer buf(*this);
StrCat(keyword_unsafe_, keyword::kFn, trait.method);
{
PushParen paren(*this);
ConvertFunctionParameters(decl);
}
ConvertFunctionReturnType(decl);
{
PushBrace body(*this);
EmitFunctionPreamble(decl);
ConvertFunctionBody(decl);
}
method = std::move(buf).str();
}
AddEqualityComparableMethod(decl, trait, method);
}

void Converter::EmitHoistedDecls(clang::CompoundStmt *body) {
for (auto *child : body->body()) {
if (auto *decl_stmt = clang::dyn_cast<clang::DeclStmt>(child)) {
Expand Down Expand Up @@ -1134,6 +1215,10 @@ void Converter::ConvertCopyOrMoveTraitImpl(clang::CXXMethodDecl *method,
if (body.empty()) {
return;
}
if (GetComparisonTrait(method)) {
AddEqualityComparableMethod(method, trait, body);
return;
}
converted_record_traits_.emplace(GetRecordName(method->getParent()),
trait.refcount.name);
StrCat(keyword::kImpl, GetCopyOrMoveTraitName(trait), "for",
Expand Down Expand Up @@ -2684,14 +2769,27 @@ void Converter::EmitCall(CallInfo &&info) {
auto *direct_callee = info.expr->getDirectCallee();
assert(direct_callee);
StrCat("libc::", direct_callee->getName());
} else {
} else if (!EmitComparisonTraitCallee(info)) {
PushExprKind push(*this, ExprKind::Callee);
Convert(GetCallee(info.expr));
}

EmitArgList(info);
}

bool Converter::EmitComparisonTraitCallee(const CallInfo &info) {
auto *callee = info.expr->getDirectCallee();
if (!callee || clang::isa<clang::CXXMethodDecl>(callee)) {
return false;
}
auto *trait = GetComparisonTrait(callee);
if (!trait) {
return false;
}
StrCat(GetCopyOrMoveTraitName(*trait), token::kDoubleColon, trait->method);
return true;
}

void Converter::ConvertGenericCallExpr(clang::CallExpr *expr) {
PushParen outer(*this);
StrCat(keyword_unsafe_);
Expand Down Expand Up @@ -2735,7 +2833,7 @@ void Converter::ConvertUserOperatorCall(clang::CXXOperatorCallExpr *expr) {
SetUFCSReceiver(expr->getArg(0), false, method);
}
StrCat(GetUFCSName(method), token::kDoubleColon, GetMethodName(method));
} else {
} else if (!EmitComparisonTraitCallee(info)) {
StrCat(GetNamedDeclAsString(callee->getCanonicalDecl()));
}
EmitArgList(info);
Expand Down Expand Up @@ -5765,14 +5863,10 @@ void Converter::ConvertCXXMethodDecls(

Converter::DeferredBlock &
Converter::VirtualMethodsFor(const clang::CXXRecordDecl *decl) {
auto name = GetRecordName(decl);
auto [it, inserted] = virtual_methods_.try_emplace(name);
if (inserted) {
it->second.header = std::format(
"{} impl {} for {}", keyword_unsafe_,
GetUnsafeTypeAsString(decl->bases_begin()->getType()), name);
}
return it->second;
return DeferredImpl(
std::format("{} impl {} for {}", keyword_unsafe_,
GetUnsafeTypeAsString(decl->bases_begin()->getType()),
GetRecordName(decl)));
}

void Converter::ConvertVirtualMethods(clang::CXXRecordDecl *decl) {
Expand Down Expand Up @@ -5809,20 +5903,21 @@ bool Converter::ConvertOutOfLineVirtualMethod(clang::CXXMethodDecl *decl) {
void Converter::ConvertOrdAndPartialOrdTraitsBase(
std::string_view cmp_body, std::string_view eq_body,
std::string_view record_name) {
if (!cmp_body.empty()) {
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"(
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 {");
Expand All @@ -5843,6 +5938,11 @@ std::string Converter::GetComparisonCall(const clang::FunctionDecl *op,
GetComparisonReceiver(method, lhs),
GetComparisonArg(op->getParamDecl(0), decl, rhs));
}
if (auto *trait = GetComparisonTrait(op)) {
return std::format("{}::{}({}, {})", GetCopyOrMoveTraitName(*trait),
trait->method, lhs,
GetComparisonArg(op->getParamDecl(1), decl, rhs));
}
return std::format("{}({}, {})", GetNamedDeclAsString(op->getCanonicalDecl()),
GetComparisonArg(op->getParamDecl(0), decl, lhs),
GetComparisonArg(op->getParamDecl(1), decl, rhs));
Expand Down Expand Up @@ -5877,31 +5977,35 @@ std::string Converter::GetComparisonBool(const clang::FunctionDecl *op,
}

std::string Converter::GetComparisonArg(const clang::ParmVarDecl *param,
const clang::CXXRecordDecl *decl,
const clang::CXXRecordDecl *,
std::string_view value) {
if (param->getType()->isReferenceType()) {
return std::format("{} as *const {}", value, GetRecordName(decl));
auto type = param->getType();
if (!type->isReferenceType()) {
return std::format("(*{}).clone()", value);
}
return std::format("{}.clone()", value);
if (type.getNonReferenceType().isConstQualified()) {
return std::string(value);
}
return std::format("{}.cast_mut()", value);
}

std::string
Converter::GetComparisonResultReceiver(const clang::CXXMethodDecl *method,
bool returns_ref,
std::string_view result) {
return GetComparisonReceiver(
method, std::format("{}{}", returns_ref ? "&*" : "&", result));
method, returns_ref ? std::format("({} as *const _)", result)
: std::format("(&raw const {})", result));
}

std::string Converter::GetComparisonReceiver(const clang::CXXMethodDecl *method,
std::string_view lhs) {
if (!MethodNeedsMutableReceiver(method)) {
return std::string(lhs);
}
bool is_mut = MethodNeedsMutableReceiver(method);
if (!IsMethodOnPtr(method)) {
return std::format("&mut *(&raw const *{}).cast_mut()", lhs);
return is_mut ? std::format("&mut *{}.cast_mut()", lhs)
: std::format("&*{}", lhs);
}
return std::format("(&raw const *{}).cast_mut()", lhs);
return is_mut ? std::format("{}.cast_mut()", lhs) : std::string(lhs);
}

std::string Converter::GetEqBody(const clang::CXXRecordDecl *decl,
Expand All @@ -5924,23 +6028,58 @@ 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, "self", "other");
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, "self", "other"),
GetComparisonBool(lt, decl, "other", "self"));
GetComparisonBool(lt, decl, kSelfPtr, kOtherPtr),
GetComparisonBool(lt, decl, kOtherPtr, kSelfPtr));
}
ConvertOrdAndPartialOrdTraitsBase(
cmp_body, GetEqBody(decl, eq, lt, cmp, "self", "other"),
cmp_body, GetEqBody(decl, eq, lt, cmp, kSelfPtr, kOtherPtr),
GetRecordName(decl));
if (eq && !GetComparisonTrait(eq)) {
ConvertEqualityComparableImpl(decl, eq);
}
}

std::pair<std::string, std::string>
Converter::GetComparisonOperandNames(const clang::FunctionDecl *op) {
auto params = DefinitionParameters(op);
return {clang::isa<clang::CXXMethodDecl>(op)
? "this"
: GetNamedDeclAsString(params.front()),
GetNamedDeclAsString(params.back())};
}

void Converter::ConvertEqualityComparableImpl(const clang::CXXRecordDecl *decl,
const clang::FunctionDecl *op) {
const auto &trait = op->getOverloadedOperator() == clang::OO_ExclaimEqual
? kWeaklyEqualityComparableWithNotEqual
: kWeaklyEqualityComparableWith;
auto [lhs, rhs] = GetComparisonOperandNames(op);
AddEqualityComparableMethod(
op, trait,
std::format("{} {{ {} }}\n",
GetComparisonTraitSignature(trait, lhs, rhs, "Self"),
GetComparisonBool(op, decl, lhs, rhs)));
}

std::string Converter::GetComparisonTraitSignature(
const RecordTrait &trait, std::string_view lhs, std::string_view rhs,
std::string_view rhs_type) const {
return std::format("unsafe fn {}({}: *const Self, {}: *const {}) -> bool",
trait.method, lhs, rhs, rhs_type);
}

void Converter::AddOrdTrait(const clang::CXXRecordDecl *decl) {
const clang::FunctionDecl *eq = nullptr;
const clang::FunctionDecl *ne = nullptr;
const clang::FunctionDecl *lt = nullptr;
const clang::FunctionDecl *cmp = nullptr;
auto consider = [&](const clang::FunctionDecl *fn) {
Expand All @@ -5956,6 +6095,9 @@ void Converter::AddOrdTrait(const clang::CXXRecordDecl *decl) {
case clang::OO_EqualEqual:
eq = fn;
break;
case clang::OO_ExclaimEqual:
ne = fn;
break;
case clang::OO_Less:
lt = fn;
break;
Expand All @@ -5979,7 +6121,8 @@ void Converter::AddOrdTrait(const clang::CXXRecordDecl *decl) {
for (const auto *method : decl->methods()) {
consider(method);
}
for (auto op : {clang::OO_EqualEqual, clang::OO_Less, clang::OO_Spaceship}) {
for (auto op : {clang::OO_EqualEqual, clang::OO_ExclaimEqual, clang::OO_Less,
clang::OO_Spaceship}) {
auto name = ctx_.DeclarationNames.getCXXOperatorName(op);
for (const auto *found : decl->getDeclContext()->lookup(name)) {
consider_decl(found);
Expand All @@ -5991,6 +6134,10 @@ void Converter::AddOrdTrait(const clang::CXXRecordDecl *decl) {
}
}

if (eq && ne && !GetComparisonTrait(ne)) {
ConvertEqualityComparableImpl(decl, ne);
}

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