Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine parent function node of a Stmt when visiting Clang AST using RecursiveASTVisitor

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.

like image 930
Trúc Nguyễn Lâm Avatar asked Aug 20 '14 17:08

Trúc Nguyễn Lâm


1 Answers

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.

like image 117
Krizz Avatar answered Sep 18 '22 22:09

Krizz