Transform Enum constants in the source to their integral values


I want to transform a source file so that Enum constants are replaced by their respective integral values.

More specifically, this should work on variable initializations and function or template default argument values.

I can obtain a VarDecl for functions and variables and a
NonTypeTemplateParmDecl for the templates.

(By using DeclVisitor)

How can I detect if these represent Enum Constants ?

And then get their value, possibly.

I tried implementing VisitEnumConstantDecl, but that doesn’t seem to get called for these cases.


Manasij Mukherjee

enum Enum { One, Two };
Enum e = One;

‘One’ and ‘Two’ are EnumConstantDecls but ‘e’ is a VarDecl whose type is Enum (EnumType).

That makes sense.

How do I get the value of ‘One’ from the VarDecl.

I ultimately want to do:

Enum e = 0; // if the enum constant One is defaulted to 0

My guess is get the initializer for the variable declaration, cast it to appropriate expression class, get the value from that.

// Enum e = One;

VarDecl *Var = // declaration for ‘e’
DeclRefExpr *Expr = dyn_cast(Var->getInit());

EnumConstantDecl *ED = dyn_cast(Expr->getFoundDecl());
int N = ED->getInitVal();