Could I get the Parent AST of a Stmt?

In my clang-tool, I want to do some analysis on AST after visit some specific type of Stmt Node. So I need to go to the parent AST node of current stmt. Is there any member functions of Stmt to archieve this goal?

For example, I am visiting the AST node StringLiteral “xmloption”, how can I get to the Node InitListExpr “config_generic”?(I am using the VisitStringLiteral() function to visit the StringLiteral Node).

2016-01-01 15:12:54的屏幕截图.png

Thanks a lot!


You can get parents of current AST node via calling clang::ASTContext::getParents(). In order to reach InitListExpr you should walk up several times.

Hope that helps,
Kirill Bobyrev

As far as I understand the issue:

  1. You might want to pass *string to the ASTContext::getParents() function as it doesn’t accept pointer to the AST node of any kind.
  2. ASTContext::getParents() returns DynTypedNodeList and it can’t be implicitly converted into a ParentVector.

Hope that helps,
Kirill Bobyrev


As I understand, you should take a look at the ParentMap class and its methods.


You can use the following code to walk through the parents of a stmt/expr:

const clang::Decl* get_DeclContext_from_Stmt(const clang::Stmt& stmt)
auto it = ASTContext->getParents(stmt).begin();

if(it == ASTContext->getParents(stmt).end())
return nullptr;

const clang::Decl *aDecl = it->getclang::Decl();
return aDecl;

const clang::Stmt *aStmt = it->getclang::Stmt();
return get_DeclContext_from_Stmt(*aStmt);

return nullptr;

It tries to find a declaration, but you can change it to find any stmt/expr.

Best regards,