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

2

6

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.

Ladon answered 22/9, 2014 at 1:27 Comment(1)
I did get a bit further along in my adventures ---- basically the standard approach here is to use Replacements.Ladon
L
1

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.

Ladon answered 29/5, 2015 at 15:53 Comment(0)
S
0

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.

Sarong answered 29/5, 2015 at 13:52 Comment(1)
Yep hasName in a Matcher is a good thing to use when you are hunting down something specific. Similarly with the ast-dump-filter, though I would imagine that once you start to examine larger codebases with many classes it could become very unwieldy very quickly. Hopefully if it happens to all encapsulate into a single namespace, and ast-dump-filter works on namespaces, then you would still be in luck.Ladon

© 2022 - 2024 — McMap. All rights reserved.