在 Clang AST 中查找声明的父级 [英] Find parent of a declaration in Clang AST

查看:36
本文介绍了在 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
";
            return false;
        }
        llvm::errs() << "find parent size=" << parents.size() << "
";
        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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆