使用 Clang 获取 AST

Using Clang to get AST

我想使用 Clang 获取其 AST 以获取有关特定源文件中的变量和方法的一些信息。但是,我不想使用 LibTooling 工具。我想手动编写代码,调用方法来解析 .cpp,然后获取树。我找不到任何资源告诉我如何做到这一点。有人可以帮忙吗?

如果您的目标是学习如何驱动 Clang 组件与编译数据库一起工作、配置编译器实例等,那么 Clang 源代码就是一种资源。也许 ClangTool::buildASTs() 方法的源代码是一个很好的起点:请参阅源代码树的 lib/Tooling/ 目录中的 Tooling.cpp。

如果您的目标是进行 LibTooling 不支持的分析,并且您只想轻松获得 AST,那么 ClangTool::buildASTsclang::tooling::buildASTFromCode 都可能有用。如果您需要编译数据库来表达编译器选项、包含路径等,ClangTool 方法会更好。如果您有一段用于轻量级测试的独立代码,buildASTFromCode 就可以了。这是 ClangTool 方法的示例:

#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/Support/CommandLine.h"
#include <memory>
#include <vector>

static llvm::cl::OptionCategory MyOpts("Ignored");

int main(int argc, const char ** argv)
{
  using namespace clang;
  using namespace clang::tooling;
  CommonOptionsParser opt_prs(argc, argv, MyOpts);
  ClangTool tool(opt_prs.getCompilations(), opt_prs.getSourcePathList());
  using ast_vec_t = std::vector<std::unique_ptr<ASTUnit>>;
  ast_vec_t asts;
  tool.buildASTs(asts); 
  // now you the AST for each translation unit
  ...

这是 buildASTFromCode 的示例:

#include "clang/Frontend/ASTUnit.h"
#include "clang/Tooling/Tooling.h" 

  ...
  std::string code = "struct A{public: int i;}; void f(A & a}{}";   
  std::unique_ptr<clang::ASTUnit> ast(clang::tooling::buildASTFromCode(code));
  // now you have the AST for the code snippet
  clang::ASTContext * pctx = &(ast->getASTContext());
  clang::TranslationUnitDecl * decl = pctx->getTranslationUnitDecl();
  ...