1

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?

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.