Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clang libTooling: How to find which header an AST item came out of?

Examples found on the web for clang tools are always run on toy examples, which are usually all really trivial C programs.

I am building a tool which performs source-to-source transformations on C++ code, which is obviously a very, very challenging task, but clang is up to this task.

The issue I am facing now is that the AST that clang generates for any C++ code that utilizes the STL is enormous. For example I have some C++ code for which clang++ -ast-dump ... | wc -l is 67,018 lines of horrifying AST gobbledygook!

99% of this is standard library stuff, which I aim to ignore in my source-to-source metaprogramming task. So, to achieve this I want to simply filter out files. Suppose I want to look at only the class definitions in the headers of the project that I'm analyzing (and ignore all standard library headers's stuff), I will need to just figure out which header each of my CXXRecordDecl's came from!

Can this be done?

Edit: Hopefully this is a way to go about it. Trying this out now... The important bit is that it has to tell me the header that the decls came out of, not the cpp file corresponding to the translation unit.

like image 252
Steven Lu Avatar asked Nov 11 '22 01:11

Steven Lu


1 Answers

In my experience so far, the "source" of some given AST node is best retrieved by using Locations. For example every node at least has a start location, and when you print this out it will contain the header file path.

Then it's possible to use this path to decide whether it is a system library or part of your application code that you still are interested in examining.

like image 145
Steven Lu Avatar answered Nov 14 '22 21:11

Steven Lu