Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find parent of a declaration in Clang AST

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?

like image 219
media Avatar asked Dec 05 '14 04:12

media


3 Answers

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。

like image 91
xawi2000 Avatar answered Nov 05 '22 05:11

xawi2000


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

like image 3
Benjamin Bannier Avatar answered Nov 05 '22 05:11

Benjamin Bannier


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.

like image 1
Thien Tran Avatar answered Nov 05 '22 05:11

Thien Tran