使用 RecursiveASTVisitor 访问 Clang AST 时确定 Stmt 的父函数节点

Trú*_*Lâm 5 c++ clang llvm-clang c++11

我正在学习如何建立解析用C工具libtooling叮当声

我正在使用一个RecursiveASTVisitor-inherited 类,所以它的所有 traverse 和visitor 方法都可用。我想知道在覆盖 method 时是否可以确定语句的父函数节点VisitStmt(Stmt *s)。例如在这里,我可以FunctionDecl*s?

谢谢。

Kri*_*izz 2

我没有 clang 方面的专业知识,但是你不能只存储上次VisitDecl调用中收到的值吗?

喜欢:

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_;
};
Run Code Online (Sandbox Code Playgroud)

我还没有编译它,所以可能需要一些修复,但它应该说明这个概念。