Search code examples
c++cabstract-syntax-treelibclang

Using libclang/libtooling


I have to retrieve all the structures and type defined in a project (as described in my previous question "https://stackoverflow.com/questions/23154414/c-project-get-all-global-variables-and-all-types" ).

I chose the clang solution because it seems to be my only way... However, the only "good" tutorial I've found is this one : http://kevinaboos.wordpress.com/2013/07/23/clang-tutorial-part-i-introduction/ and there are still some questions remaining :

1) Are the pre-processor directives handled (#include, #define etc.)

2) How to retrieve the type, and the structure member ?

actually, for this * simple * code for example:

typedef struct
{
   int i;
   char i2;
} S1; 

typedef struct S2
{
   int i;
   struct S2 s2;
} S2;

typedef S3 struct S3;
struct S3
{
   int i;
   char i2;
}
S1 m_s1;
S2 m_s2;
struct S3 m_s3;

what method from an clang::RecursiveASTVisitor-derived class (http://clang.llvm.org/doxygen/classclang_1_1RecursiveASTVisitor.html) are called and in wich order ? (and could you give me explanations on how to retrieve the data I need ?)


Solution

  • Okay, as Mat Petersson Adviced, I experimented.

    1) Yes, the AST is generated after the preprocessor. It permit to retrieve all the informations.

    2) The AST traversal is depth-first. Rather than implement VisitFoo(Foo *) methods, you can reimplement TraverseFoo(Foo *) method to get the begin and the end of each node lookup :

    class YourVisitor : public RecursiveASTVisitor<YourVisitor>
    {
       //...
       virtual bool TraverseFoo(Foo * f)
       {
          //Some stuff to do before to explore the children
          bool r = RecursiveASTVisitor<YourVisitor>::TraverseFoo(f);
          //Some stuff to do after
          return r
       }
    }
    

    Then to get the structs ( = records) and their members, just to re-implement TraverseRecordDecl to handle the struct and VisitFieldDecl to get the fields.