Find the parent of an ad in Clang AST
I am using clang to do some analysis and I need to find the parent of the declaration in the AST. For example, in the following code I have int x
, and I want to get its parent, which should be a function declaration:
int main(int x) { return 0 }
I know as mentioned in this link http://comments.gmane.org/gmane.comp.compilers.clang.devel/2152 there is a ParentMap class for keeping track of parent nodes. However, this is just a map from Stmt * -> Stmt * and I need to find the parent of the ad. Does anyone know how I can do this?
source to share
This is exactly ParentMap
as described in the related topic you are looking for. In clang special declarations, everything inherits from clang::Decl
which provides
virtual Stmt* getBody() const;
Alternatively, you can also be happy with pre-made AST layouts that make it easy to create queries in AST. Face-to-face checks use them heavily and are fairly easy to understand, see the sources [git] .
source to share
you can use AstContext :: getParents () to find the parent of the ast node. example code:
const Stmt* ST = str;
while (true) {
//get parents
const auto& parents = pContext->getParents(*ST);
if ( parents.empty() ) {
llvm::errs() << "Can not find parent\n";
return false;
}
llvm::errs() << "find parent size=" << parents.size() << "\n";
ST = parents[0].get<Stmt>();
if (!ST)
return false;
ST->dump();
if (isa<CompoundStmt>(ST))
break;
}
AstContext :: getParents () can take stmt parameter or decl parameter.
source to share