Find parent of a declaration in Clang AST

时光毁灭记忆、已成空白 提交于 2020-02-27 07:36:09

问题


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 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?


回答1:


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。




回答2:


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].



来源:https://stackoverflow.com/questions/27308691/find-parent-of-a-declaration-in-clang-ast

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!