Find parent of a declaration in Clang AST
Asked Answered
W

3

10

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?

Worktable answered 5/12, 2014 at 4:17 Comment(0)
H
8

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。

Helios answered 22/10, 2016 at 5:19 Comment(2)
Have you check this solution? The author need to find parent of a DECLARATION.Looker
If I am reading the documentation correctly, it is now possible to get the parents of other AST nodes besides Decls and Stmts: 'NodeT' can be one of Decl, Stmt, Type, TypeLoc, NestedNameSpecifier or NestedNameSpecifierLoc.Hackler
S
4

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

Schaper answered 14/2, 2015 at 23:36 Comment(0)
L
1

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.

Looker answered 2/11, 2020 at 8:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.