Steven Lu
Steven Lu

Reputation: 43437

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.

Upvotes: 6

Views: 1996

Answers (2)

Steven Lu
Steven Lu

Reputation: 43437

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.

Upvotes: 1

Thomas
Thomas

Reputation: 457

One route I'm looking at is to narrow matches with things like hasName() (as found here. For example:

recordDecl(hasName("MyBaseClass")) // etc.

However your comment above using -ast-dump is something I tried as well to get a lay of the land on my own CLang tool. I found this post to be extremely helpful. Armed with their suggestion, I used clang-check to filter to a specific class name and fed it my top-level CPP file. The output was a much more manageable few hundred lines representing the class declarations and definitions of interest.

Upvotes: 0

Related Questions