5

I am learning how to build a tool for parsing C using libtooling of clang.

I'm using a RecursiveASTVisitor-inherited class, so all its traverse and visitor methods are available. I wonder if I can determine the parent function node of a statement when overriding method VisitStmt(Stmt *s). For example here, can I get a FunctionDecl* from s?

Thanks.

Krizz
  • 11,362
  • 1
  • 30
  • 43

4 Answers4

2

I don't have an expertise in clang, but can't you just store the value you received in the last VisitDecl call?

Like:

class FooVisitor : public RecursiveASTVisitor<FooVisitor> {
 public:
  explicit FooVisitor(ASTContext* context)
    : context_(context), current_func_(nullptr) {}

  bool VisitDecl(Decl *decl) {
     if (decl->isFunctionOrFunctionTemplate())
        current_func_ = decl->getAsFunction();
     return true;
  }

  bool VisitStmt(Stmt* stmt) {
     do_something(current_func_, stmt);
     return true;
  }
 private:
  ASTContext* context_;
  FunctionDecl* current_func_;
};

I haven't compiled it, so may need some fixups, but it should illustrate the concept.

Krizz
  • 11,362
  • 1
  • 30
  • 43
2

Since you hold an ASTContext, I think you can visit Node's parents via ASTContext::getParent().

2

I think this code is you want:

    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;
    } 
xawi2000
  • 152
  • 1
  • 4
0

May be bit late. If you add parsing over decls as well as Stmts to @xawi2000 then i guess you would get to the top node. for example, you may have

functionDecl

compoundStmt

VarDecl

Stmt

in which case you need to parse over stmt, then decl to get to the functionDecl. Only parsing over stmts, may not give this case