Skip to content

Commit c5b86e9

Browse files
committed
Short circuit Enum::from(X as i32) to X
1 parent f59ca0e commit c5b86e9

1 file changed

Lines changed: 13 additions & 0 deletions

File tree

cpp2rust/converter/converter.cpp

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1733,6 +1733,19 @@ bool Converter::VisitCXXBoolLiteralExpr(clang::CXXBoolLiteralExpr *expr) {
17331733

17341734
void Converter::ConvertIntegerToEnumeralCast(clang::Expr *to,
17351735
clang::Expr *from) {
1736+
// Short circuit `Enum::from(X as i32)` to `X`
1737+
if (auto ref =
1738+
clang::dyn_cast<clang::DeclRefExpr>(from->IgnoreParenImpCasts())) {
1739+
if (auto ec = clang::dyn_cast<clang::EnumConstantDecl>(ref->getDecl())) {
1740+
auto src_enum = clang::dyn_cast<clang::EnumDecl>(ec->getDeclContext());
1741+
auto dst_enum = to->getType()->getAs<clang::EnumType>();
1742+
if (src_enum && dst_enum && dst_enum->getDecl() == src_enum) {
1743+
StrCat(std::format("{}::{}", GetRecordName(src_enum),
1744+
std::string_view(ec->getName())));
1745+
return;
1746+
}
1747+
}
1748+
}
17361749
StrCat(GetUnsafeTypeAsString(to->getType()), "::from");
17371750
PushParen paren(*this);
17381751
Convert(from);

0 commit comments

Comments
 (0)