Skip to content

Commit 611547d

Browse files
committed
Add From trait for enums
1 parent eddc30e commit 611547d

2 files changed

Lines changed: 29 additions & 0 deletions

File tree

cpp2rust/converter/converter.cpp

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1890,6 +1890,13 @@ bool Converter::VisitExplicitCastExpr(clang::ExplicitCastExpr *expr) {
18901890
StrCat(')');
18911891
return false;
18921892
}
1893+
if (type->isEnumeralType() && !sub_expr->getType()->isEnumeralType()) {
1894+
StrCat(std::format("{}::from", GetUnsafeTypeAsString(type)));
1895+
PushParen paren(*this);
1896+
Convert(sub_expr);
1897+
StrCat(keyword::kAs, "i32");
1898+
return false;
1899+
}
18931900
{
18941901
PushParen paren(*this);
18951902
Convert(sub_expr);
@@ -2704,9 +2711,29 @@ bool Converter::VisitEnumDecl(clang::EnumDecl *decl) {
27042711
std::string_view(init.data(), init.size())));
27052712
}
27062713
StrCat("}");
2714+
2715+
AddFromImpl(decl);
27072716
return false;
27082717
}
27092718

2719+
void Converter::AddFromImpl(clang::EnumDecl *decl) {
2720+
auto name = GetRecordName(decl);
2721+
StrCat(std::format("impl From<i32> for {}", name));
2722+
PushBrace impl(*this);
2723+
StrCat(std::format("fn from(n: i32) -> {}", name));
2724+
PushBrace fn(*this);
2725+
StrCat("match n");
2726+
PushBrace match(*this);
2727+
for (auto e : decl->enumerators()) {
2728+
llvm::SmallVector<char, 32> init;
2729+
e->getInitVal().toString(init, 10);
2730+
StrCat(std::format("{} => {}::{},",
2731+
std::string_view(init.data(), init.size()), name,
2732+
std::string_view(e->getName())));
2733+
}
2734+
StrCat(std::format("_ => panic!(\"invalid {} value: {{}}\", n),", name));
2735+
}
2736+
27102737
bool Converter::VisitCXXDefaultArgExpr(clang::CXXDefaultArgExpr *expr) {
27112738
if (expr->getType()->isPointerType()) {
27122739
StrCat(keyword_default_);

cpp2rust/converter/converter.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -293,6 +293,8 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
293293

294294
virtual bool VisitEnumDecl(clang::EnumDecl *decl);
295295

296+
virtual void AddFromImpl(clang::EnumDecl *decl);
297+
296298
virtual bool VisitCXXDefaultArgExpr(clang::CXXDefaultArgExpr *expr);
297299

298300
virtual bool VisitLambdaExpr(clang::LambdaExpr *expr);

0 commit comments

Comments
 (0)