0
我想使用Clang來獲取它的AST以獲取有關特定源文件中變量和方法的一些信息。但是,我不想使用LibTooling工具。我想親手寫代碼來調用解析.cpp的方法,然後獲取樹。我找不到任何資源告訴我如何執行此操作。任何人都可以幫忙嗎?使用Clang獲取AST
我想使用Clang來獲取它的AST以獲取有關特定源文件中變量和方法的一些信息。但是,我不想使用LibTooling工具。我想親手寫代碼來調用解析.cpp的方法,然後獲取樹。我找不到任何資源告訴我如何執行此操作。任何人都可以幫忙嗎?使用Clang獲取AST
如果您的目標是學習如何驅動Clang組件以使用編譯數據庫,配置編譯器實例等,那麼Clang源代碼是一種資源。也許ClangTool::buildASTs()
方法的來源可能是一個很好的開始:請參閱源代碼樹的lib/Tooling /目錄中的Tooling.cpp。
如果您的目標是做一個LibTooling不支持的分析,並且您只想以最小的麻煩得到AST,那麼ClangTool::buildASTs
或clang::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();
...