在Clang AST中查找声明的父级 [英] Find parent of a declaration in Clang AST
问题描述
我正在使用clang进行一些分析,我需要在AST中找到声明的父级。例如,在下面的代码中,我有 int x
,我想获取其父级,该父级应该是函数声明:
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}
我知道此链接中所述 http://comments.gmane.org/gmane.comp.compilers.clang.devel / 2152 中有一个ParentMap类来跟踪父节点。但是,这仅代表了Stmt *-> Stmt *的映射,我需要找到声明的父级。有人知道我该怎么做吗?
I know as mentioned in this link http://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?
推荐答案
您可以使用AstContext :: getParents()查找ast节点的父节点
示例代码如下:
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;
}
AstContext :: getParents()可以接收stmt参数或decl参数
the AstContext::getParents() can receive a stmt parameter or a decl parameter。
这篇关于在Clang AST中查找声明的父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!