Search code examples
c++clangabstract-syntax-treellvm-clangclang-static-analyzer

Storing Decl nodes in Clang AST


I'm trying to store all FunctionDecl nodes in a vector so that I can visit them in the future. The use case would for stepping into functions (e.g. function a calls function b, I want to be able to call VisitDecl on the function b node)

Storing of all these nodes are done in the HandleTopLevelDecl within ASTConsumer:

std::vector<Decl> vec;

virtual bool HandleTopLevelDecl (DeclGroupRef DG) {
  for (DeclGroupRef::iterator i = DG.begin(), e = DG.end(); i != e; ++i) {
    Decl *D = *i;
    vec.push_back(*D);
  }
} 

However, during compilation there is an error '~Decl' is a protected member of 'clang::Decl'

Anyone can shed some light on this?


Solution

  • The problem is that you are putting a copy of Decl instance into your array. Creation and deletion of these objects is responsibility of other class, hence you can only have a reference to an instance.

    Here is proper solution for your problem:

    std::vector<Decl *> vec;
    
    virtual bool HandleTopLevelDecl (DeclGroupRef DG) {
      for (DeclGroupRef::iterator i = DG.begin(), e = DG.end(); i != e; ++i) {
        Decl *D = *i;
        vec.push_back(D);
      }
    }