I'm using clang to do some analysis and I need to find parent of a declaration in AST. For instance, in the following code I have int x
and I want to get its parent which should be the function declaration :
int main(int x) { return 0 }
I know as mentioned in this linkhttp://comments.gmane.org/gmane.comp.compilers.clang.devel/2152 there is a ParentMap class to track parent nodes. However, this just represents a map from Stmt* -> Stmt* and I need to find parent of a declaration. Does anyone know how I could do this?
you can use AstContext::getParents() to find parent of a ast node。 example code like this:
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;
}
the AstContext::getParents() can receive a stmt parameter or a decl parameter。
It is exactly ParentMap
like described in the linked thread that you are looking for. In clang specific declarations all inherit from clang::Decl
which provides
virtual Stmt* getBody() const;
Alternatively you might also be happy with the ready-made AST matchers which make creating queries on the AST much easier. The clang-tidy checks make heavy use of them and are pretty easy to follow, see the sources [git] .
About parent of a FunctionDecl, there something to notice: a declaration of Function may be a member of a class or it may be an "independent" declaration.
If FunctionDecl is a member of a class then FunctionDecl is a CXXMethodDecl so you can check with:
isa<CXXMethodDecl>(FunctionDecl *FD).
Then you can get the parent of CXXMethodDecl with getParent() method. This method is absent in FunctionDecl .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.