clang ast visitor for single line multiple variable declaration

1.4k views Asked by At

I am new to Clang libTooling development.

consider the following variable declaration

int i, j, k = 10;
^              ^  

For my project requirement, I want to capture the whole declaration expression including "i", "j" and "k".

How to capture the complete declaration expression including all variables with clang libTooling?

What I am experiencing is that I do not get the visitor for complete expression instead I get the visitor for individual variable declaration.

Is this the expected behavior in clang libTooling OR am I missing something?

Please suggest me the correct way to capture single line multiple declarations or any workaround? Any kind of help will be really appreciated.

Thanks, Hemant

1

There are 1 answers

2
Stefan Moosbrugger On

To solve the described problem you could for instance write a recursive AST visitor that visits DeclStmt nodes (not only VarDecl). Check this site to see how to write such a visitor: http://clang.llvm.org/docs/RAVFrontendAction.html

The reason why you should visit DeclStmt nodes and not only VarDecl nodes can be explained by having a look at the AST representation of your declaration statement:

    |-DeclStmt 0x35dbfc8 <line:3:1, col:17>
    | |-VarDecl 0x35dbe48 <col:1, col:5> col:5 i 'int'
    | |-VarDecl 0x35dbeb8 <col:1, col:8> col:8 j 'int'
    | `-VarDecl 0x35dbf28 <col:1, col:15> col:11 k 'int' cinit
    |   `-IntegerLiteral 0x35dbf88 <col:15> 'int' 10

As you can see the DeclStmt "captures" all the VarDecl nodes (and the initialization, if given). Once your visitor visits the DeclStmt you can check with the isSingleDecl() member function if your declaration refers to a single declaration or not. If not (as in your case) you can retrieve an iterator to the different VarDecl nodes with decl_begin(), decl_end(), etc.