Retrieve variable name

Hi all,

please consider this code:

int main {

int a = 7;

int b = a;

}

I have a Decl object called decl that represents int b = a; If i do decl->getInit() i can have an Expr pointer that represents a I think. From there how can i retrieve the variable name ‘a’? Maybe using getNameAsString()? I tried but it didn’t work.

Thanks,
Alberto

getInit should be/contain a declrefexpr

Hi all,

please consider this code:

int main {

I assume you mean “main()”

int a = 7;

int b = a;

}

I have a Decl object called decl that represents int b = a; If i do decl->getInit() i can have an Expr pointer that represents a I think. From there how can i retrieve the variable name ‘a’? Maybe using getNameAsString()? I tried but it didn’t work.

As -ast-dump shows, getInit is a ImplicitCastExpr which has a DeclRefExpr which points to ‘a’.

$ clang_check -ast-dump /tmp/t.cc –
TranslationUnitDecl 0x21c05e0 <>

-TypedefDecl 0x21c0b20 <> implicit __int128_t ‘__int128’
-TypedefDecl 0x21c0b80 <> implicit __uint128_t ‘unsigned __int128’
-TypedefDecl 0x21c0f40 <> implicit __builtin_va_list ‘__va_list_tag [1]’
-FunctionDecl 0x21c0fe0 </tmp/t.cc:1:1, line:4:1> line:1:5 main 'int (void)' -CompoundStmt 0x21c1240 <col:12, line:4:1>
-DeclStmt 0x21c1168 <line:2:3, col:12>
-VarDecl 0x21c10f0 <col:3, col:11> col:7 used a 'int' cinit -IntegerLiteral 0x21c1148 col:11 ‘int’ 7
-DeclStmt 0x21c1228 <line:3:3, col:12> -VarDecl 0x21c1190 <col:3, col:11> col:7 b ‘int’ cinit
-ImplicitCastExpr 0x21c1210 <col:11> 'int' <LValueToRValue> -DeclRefExpr 0x21c11e8 col:11 ‘int’ lvalue Var 0x21c10f0 ‘a’ ‘int’

Hi Manuel,
thanks for your help.

Yes i meant “int main()”. Based on what you said I think I should do something like: decl->getInit()->getNameInfo()->getName();

Thanks,
Alberto

Well, you’ll need to dyn_cast and look through the implicitcast node, but apart from that, sounds about right.

Yes yes, I’ll do it.

Thanks,
Alberto

Hi,

I hope this can help someone. I solved in this way:

Expr *e = (dyn_cast(d->getInit()))->getSubExpr(); // return an object that points to b

dyn_cast(e)->getNameInfo().getAsString(); //this return b

Thanks for your help,
Alberto

Hi,
I hope this can help someone. I solved in this way:

Expr *e = (dyn_cast<ImplicitCastExpr>(d->getInit()))->getSubExpr(); //
return an object that points to b

dyn_cast<DeclRefExpr>(e)->getNameInfo().getAsString(); //this return b

If you're going to assume that 'e' is a DeclRefExpr (and likewise for the
ImplicitCastExpr case), use cast<> rather than dyn_cast. Otherwise, you
should cope with dyn_cast returning nullptr.