Skip to content
  •  
  •  
  •  
86 changes: 76 additions & 10 deletions cpp2rust/converter/converter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -394,7 +394,7 @@ bool Converter::VisitTranslationUnitDecl(clang::TranslationUnitDecl *decl) {
for (auto *child : decl->decls()) {
if (IsUserDefinedDecl(child) &&
(IsInMainFile(child) || !decl_ids_.contains(GetID(child)))) {
Convert(child);
ConvertNamespaceMember(child);
if (!hoisted_records_.empty()) {
StrCat(hoisted_records_);
hoisted_records_.clear();
Expand Down Expand Up @@ -512,6 +512,10 @@ void Converter::ConvertFunctionBody(clang::FunctionDecl *decl) {
}

bool Converter::VisitFunctionTemplateDecl(clang::FunctionTemplateDecl *decl) {
if (!clang::isa<clang::CXXMethodDecl>(decl->getTemplatedDecl()) &&
!decl->isCanonicalDecl()) {
return false;
}
for (auto *function_decl : decl->specializations()) {
if (function_decl->getTemplateSpecializationKind() ==
clang::TSK_ExplicitSpecialization) {
Expand Down Expand Up @@ -1175,7 +1179,7 @@ bool Converter::ConvertCXXMethodDecl(clang::CXXMethodDecl *decl) {

{
PushParen paren(*this);
if (!decl->isStatic()) {
if (decl->isImplicitObjectMemberFunction()) {
StrCat(GetSelfMaybeWithMut(decl), token::kComma);
}
ConvertFunctionParameters(decl);
Expand Down Expand Up @@ -1322,11 +1326,20 @@ void Converter::EmitFunctionPreamble(clang::FunctionDecl *decl) {
void Converter::ConvertDeclContext(clang::DeclContext *decl) {
for (auto *child : decl->decls()) {
if (IsInMainFile(child) || !decl_ids_.contains(GetID(child))) {
Convert(child);
ConvertNamespaceMember(child);
}
}
}

void Converter::ConvertNamespaceMember(clang::Decl *decl) {
if (auto *var = clang::dyn_cast<clang::VarDecl>(decl);
var && var->isImplicit()) {
VisitVarDecl(var);
} else {
Convert(decl);
}
}

bool Converter::VisitNamespaceDecl(clang::NamespaceDecl *decl) {
ConvertDeclContext(decl);
return false;
Expand Down Expand Up @@ -1431,6 +1444,9 @@ bool Converter::VisitDeclStmt(clang::DeclStmt *stmt) {
if (var && IsAliasOfInit(ctx_, var)) {
continue;
}
if (var && var->isLocalExternDecl()) {
continue;
}
if (var && var->isImplicit()) {
VisitVarDecl(var);
} else {
Expand Down Expand Up @@ -1466,11 +1482,16 @@ void Converter::ConvertCondition(clang::Expr *cond) {
}

bool Converter::VisitIfStmt(clang::IfStmt *stmt) {
// The variables of the init statement are only visible in the if.
PushBrace scope(*this, stmt->getInit());
// The variables of the init statement and of the condition are only
// visible in the if.
auto *cond_var = stmt->getConditionVariableDeclStmt();
PushBrace scope(*this, stmt->getInit() || cond_var);
if (auto *init = stmt->getInit()) {
Convert(init);
}
if (cond_var) {
Convert(cond_var);
}
if (bool taken = false;
!stmt->getConditionVariable() && !stmt->isConsteval() &&
!stmt->getCond()->isValueDependent() &&
Expand All @@ -1495,13 +1516,32 @@ bool Converter::VisitIfStmt(clang::IfStmt *stmt) {
bool Converter::VisitWhileStmt(clang::WhileStmt *stmt) {
ScopedPush push(break_target_, BreakTarget::Loop);
StrCat("'loop_:");
ScopedPush no_inc(curr_for_inc_, nullptr);
if (auto *cond_var = stmt->getConditionVariableDeclStmt()) {
StrCat(keyword::kLoop);
PushBrace loop_brace(*this);
ConvertConditionVariableTest(cond_var, stmt->getCond());
ConvertBodyStmts(stmt->getBody());
return false;
}
StrCat(keyword::kWhile);
ConvertCondition(stmt->getCond());
ScopedPush no_inc(curr_for_inc_, nullptr);
ConvertBody(stmt->getBody());
return false;
}

// The condition variable is created and destroyed on each iteration.
void Converter::ConvertConditionVariableTest(clang::DeclStmt *cond_var,
clang::Expr *cond) {
Convert(cond_var);
StrCat(keyword::kIf, token::kNot);
{
PushParen paren(*this);
ConvertCondition(cond);
}
StrCat("{ break; }");
}

bool Converter::VisitDoStmt(clang::DoStmt *stmt) {
ScopedPush push(break_target_, BreakTarget::Loop);
const char *control_var = "__do_while";
Expand All @@ -1523,16 +1563,27 @@ bool Converter::VisitDoStmt(clang::DoStmt *stmt) {

bool Converter::VisitForStmt(clang::ForStmt *stmt) {
ScopedPush push(break_target_, BreakTarget::Loop);
// The variables of the init statement are only visible in the for.
PushBrace scope(*this, stmt->getInit() &&
clang::isa<clang::DeclStmt>(stmt->getInit()));
Convert(stmt->getInit());
StrCat("'loop_:");
StrCat(keyword::kWhile);
if (stmt->getCond() == nullptr) {
StrCat("true");
auto *cond_var = stmt->getConditionVariableDeclStmt();
if (cond_var) {
StrCat(keyword::kLoop);
} else {
ConvertCondition(stmt->getCond());
StrCat(keyword::kWhile);
if (stmt->getCond() == nullptr) {
StrCat("true");
} else {
ConvertCondition(stmt->getCond());
}
}
{
PushBrace brace(*this);
if (cond_var) {
ConvertConditionVariableTest(cond_var, stmt->getCond());
}
{
ScopedPush inc(curr_for_inc_, stmt->getInc());
ConvertBodyStmts(stmt->getBody());
Expand Down Expand Up @@ -3212,6 +3263,10 @@ std::string Converter::ConvertDeclRef(clang::Expr *expr,
if (method->isStatic()) {
return GetFunctionRefName(method);
}
if (method->isExplicitObjectMemberFunction()) {
return std::format("{}::{}", GetUFCSName(method),
GetMethodName(method));
}
}
return GetNamedDeclAsString(function->getCanonicalDecl());
}
Expand Down Expand Up @@ -4211,6 +4266,17 @@ bool Converter::VisitSwitchStmt(clang::SwitchStmt *stmt) {
? BreakTarget::FallthroughSwitch
: BreakTarget::Switch);

// The variables of the init statement and of the condition are only
// visible in the switch.
auto *cond_var = stmt->getConditionVariableDeclStmt();
PushBrace scope(*this, stmt->getInit() || cond_var);
if (auto *init = stmt->getInit()) {
Convert(init);
}
if (cond_var) {
Convert(cond_var);
}

if (needs_switch_macro) {
StrCat("switch!");
} else {
Expand Down
5 changes: 5 additions & 0 deletions cpp2rust/converter/converter.h
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,8 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {

void ConvertDeclContext(clang::DeclContext *decl);

void ConvertNamespaceMember(clang::Decl *decl);

virtual bool VisitTypedefDecl(clang::TypedefDecl *decl);
virtual bool VisitTypeAliasDecl(clang::TypeAliasDecl *decl);
virtual bool VisitTypeAliasTemplateDecl(clang::TypeAliasTemplateDecl *decl);
Expand All @@ -266,6 +268,9 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {

virtual bool VisitWhileStmt(clang::WhileStmt *stmt);

void ConvertConditionVariableTest(clang::DeclStmt *cond_var,
clang::Expr *cond);

virtual bool VisitDoStmt(clang::DoStmt *stmt);

virtual bool VisitForStmt(clang::ForStmt *stmt);
Expand Down
17 changes: 14 additions & 3 deletions cpp2rust/converter/converter_lib.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,8 @@ static const char rust_keywords[][12] = {
namespace cpp2rust {

bool IsGlobalVar(const clang::VarDecl *decl) {
return decl->isFileVarDecl() || decl->isStaticLocal();
return decl->isFileVarDecl() || decl->isStaticLocal() ||
decl->isLocalExternDecl();
}

bool IsGlobalVar(const clang::Expr *expr) {
Expand Down Expand Up @@ -249,6 +250,15 @@ std::string GetNumAsString(llvm::APFloat value) {
}
}

static bool IsAnonymousUnionObject(const clang::Decl *decl) {
auto *var = clang::dyn_cast<clang::VarDecl>(decl);
if (!var) {
return false;
}
auto *record = var->getType()->getAsRecordDecl();
return record && record->isAnonymousStructOrUnion();
}

bool IsUserDefinedDecl(const clang::Decl *decl) {
const auto &ctx = decl->getASTContext();
const auto &src_mgr = ctx.getSourceManager();
Expand Down Expand Up @@ -287,7 +297,8 @@ bool IsUserDefinedDecl(const clang::Decl *decl) {
clang::TSK_ExplicitInstantiationDefinition)) {
src_loc = spec->getSpecializedTemplate()->getLocation();
}
return !decl->getBeginLoc().isInvalid() && !decl->isImplicit() &&
return !decl->getBeginLoc().isInvalid() &&
(!decl->isImplicit() || IsAnonymousUnionObject(decl)) &&
!src_mgr.isInSystemHeader(src_loc) &&
!src_mgr.isInSystemMacro(src_loc);
}
Expand Down Expand Up @@ -1186,7 +1197,7 @@ std::string GetNamedDeclAsString(const clang::NamedDecl *decl) {
id = GetDeclId(decl, fn->getFormalLinkage() == clang::Linkage::Internal);
}
} else if (auto *var = clang::dyn_cast<clang::VarDecl>(decl);
var && (var->isFileVarDecl() || var->isStaticLocal())) {
var && IsGlobalVar(var)) {
id = GetDeclId(var->getCanonicalDecl(),
var->getFormalLinkage() != clang::Linkage::External);
} else if (auto *tag = clang::dyn_cast<clang::TagDecl>(decl);
Expand Down
10 changes: 8 additions & 2 deletions cpp2rust/converter/models/converter_refcount.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3186,8 +3186,14 @@ void ConverterRefCount::SetUFCSReceiver(clang::Expr *base, bool is_arrow,

std::string
ConverterRefCount::GetUFCSName(const clang::CXXMethodDecl *method) const {
return IsMethodOnPtr(method) ? TraitName(method->getParent())
: GetRecordName(method->getParent());
if (!IsMethodOnPtr(method)) {
return GetRecordName(method->getParent());
}
if (method->isExplicitObjectMemberFunction()) {
return std::format("<Ptr<{}> as {}>", GetRecordName(method->getParent()),
TraitName(method->getParent()));
}
return TraitName(method->getParent());
}

std::string
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
// [=] does not capture t.
#include <cassert>

#include "../../support/lifetime-tracked.h"
#include "../support/lifetime-tracked.h"

int main() {
LifetimeTracked t;
Expand Down
110 changes: 110 additions & 0 deletions tests/std/basic/basic.def.odr-unsupported.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
// XFAIL: refcount, unsafe
// no-compile: refcount, unsafe
// ADDITIONAL_COMPILE_FLAGS: -std=c++23
#include <cassert>

#include "../support/has-constexpr-ctor.h"
#include "../support/lifetime-tracked.h"

// N4950 [basic.def.odr]/3.5: the potential results of E1.*E2 are those of E1.
// Reading k.*pm does not odr-use k, so [=] does not capture it.
namespace p3_5_pointer_to_member {
void test() {
HasConstexprCtor::reset();
constexpr HasConstexprCtor k{5};
constexpr int HasConstexprCtor::*pm = &HasConstexprCtor::m;
auto f = [=] { return k.*pm; };
assert(HasConstexprCtor::copyCount == 0);
assert(f() == 5);
assert(HasConstexprCtor::copyCount == 0);
}
} // namespace p3_5_pointer_to_member

// N4950 [basic.def.odr]/4.1: forming a pointer to member does not name a pure
// virtual function. HasPureVirtual::f is never defined; the call through the
// pointer to member runs the override.
namespace p4_1_pure_virtual_member_pointer {
static int derived_calls;

struct HasPureVirtual {
virtual void f() = 0;
};

struct OverridesPureVirtual : HasPureVirtual {
void f() override { ++derived_calls; }
};

void test() {
void (HasPureVirtual::*pm)() = &HasPureVirtual::f;
OverridesPureVirtual d;
HasPureVirtual *p = &d;
(p->*pm)();
assert(derived_calls == 1);
}
} // namespace p4_1_pure_virtual_member_pointer

// The converter drops the body of a pure virtual function and the
// qualification of calls to it.
// N4950 [basic.def.odr]/4.1: a pure virtual function is named by an
// id-expression with an explicitly qualified name. HasPureVirtual::f is pure
// but defined; the qualified call runs the base body, not the override.
namespace p4_1_pure_virtual_qualified_call {
static int base_calls, derived_calls;

struct HasPureVirtual {
virtual void f() = 0;
};

void HasPureVirtual::f() { ++base_calls; }

struct OverridesPureVirtual : HasPureVirtual {
void f() override {
++derived_calls;
HasPureVirtual::f();
}
};

void test() {
OverridesPureVirtual d;
HasPureVirtual *p = &d;
p->f();
assert(derived_calls == 1);
assert(base_calls == 1);
d.HasPureVirtual::f();
assert(derived_calls == 1);
assert(base_calls == 2);
}
} // namespace p4_1_pure_virtual_qualified_call

// Inside the lambda the converter refers to the original structured binding,
// not to the captured copy.
// N4950 [basic.def.odr]/6: a structured binding is odr-used if it appears as a
// potentially-evaluated expression, so [=] captures a by copy.
namespace p6_evaluated_binding_is_captured {
struct HasTwoMembers {
LifetimeTracked a;
LifetimeTracked b;
};

void test() {
LifetimeTracked::reset();
HasTwoMembers p{LifetimeTracked(), LifetimeTracked()};
assert(LifetimeTracked::ctorCount == 2);
auto &[a, b] = p;
assert(LifetimeTracked::copyCount == 0);
auto f = [=] { a.use(); };
assert(LifetimeTracked::copyCount == 1);
f();
assert(LifetimeTracked::copyCount == 1);
assert(LifetimeTracked::useCount == 1);
assert(p.a.uses == 0);
}
} // namespace p6_evaluated_binding_is_captured

int main() {
p3_5_pointer_to_member::test();
p4_1_pure_virtual_member_pointer::test();
p4_1_pure_virtual_qualified_call::test();
p6_evaluated_binding_is_captured::test();
return 0;
}
Loading
Loading