Reputation: 79
I have the following recursive AST visitor implementation.
class ExampleVisitor : public clang::RecursiveASTVisitor<ExampleVisitor>{
private:
clang::ASTContext* ast_context_; // used for getting additional AST info
public:
explicit ExampleVisitor(clang::CompilerInstance* ci)
: ast_context_(&(ci->getASTContext())) // initialize private members
virtual bool VisitFunctionDecl(clang::FunctionDecl* func)
{
numFunctions++;
foo(func);
return true;
}};
The function foo prints the names of the declared functions for a given input file.
In this implementation foo prints the functions that are declared in the input file as well as dumps all function declarations from the included header files. How can I modify this code to print only the functions declared in the given input file?
Upvotes: 1
Views: 1675
Reputation: 1111
Try using the SourceManager to determine whether the FunctionDecl is in the main file of the translation unit:
virtual bool VisitFunctionDecl(clang::FunctionDecl* func)
{
clang::SourceManager &sm(ast_context_->getSourceManager());
bool const inMainFile(
sm.isInMainFile(sm.getExpansionLoc(func->getLocStart())));
if(inMainFile){
numFunctions++;
foo(func);
}
else{
std::cout << "Skipping '" << func->getNameAsString()
<< "' not in main file\n";
}
return true;
}};
I happened to know that there is an AST Matcher called isExpansionInMainFile
. I got the code above from the source for that matcher in cfe-3.9.0.src/include/clang/ASTMatchers/ASTMatchers.h lines 209-14.
Upvotes: 4