Clang:将函数的 AST 从原始文件写入新文件

ign*_*rer 3 clang libtooling

我是 Clang 的新手,他试图通过 libtooling 分析 AST。我想找到一个特定的函数,并将其 AST 从原始源文件移动到一个新文件。

我已经知道如何通过 MatchFinder 找到该函数。现在,我想知道如何将其 AST 写入新文件(.c 或 .cpp)

提前致谢!

Som*_*Tim 6

摘要:要获取源文本,请使用SourceManager; 要从原始文件中删除该函数,请生成 aReplacement并使用RefactoringTool.

首先,这里有一种获取函数定义源代码的方法,假设 AST 匹配器如下所示:

auto matcher(std::string const & fname) {
  return functionDecl(hasName(fname)).bind("f_decl");
}
Run Code Online (Sandbox Code Playgroud)

Callback 的 run 方法将首先访问匹配的 AST 节点,获取函数声明所涵盖的源范围,并获取对 SouceManager 的引用,后者将 SourceLocation 对象与实际源相关联:

virtual void run(MatchResult_t const & result) override {
  using namespace clang;
  FunctionDecl * f_decl = const_cast<FunctionDecl *>(
      result.Nodes.getNodeAs<FunctionDecl>("f_decl"));
  if(f_decl) {
    SourceManager &sm(result.Context->getSourceManager());
    SourceRange decl_range(f_decl->getSourceRange());
    SourceLocation decl_begin(decl_range.getBegin());
    SourceLocation decl_start_end(decl_range.getEnd());
    SourceLocation decl_end_end( end_of_the_end( decl_start_end,sm));
Run Code Online (Sandbox Code Playgroud)

有什么是decl_start_enddecl_end_end?使用 SourceRange 有一个问题:结束位置不是代码结束的地方;它是范围内最后一个标记的开始。因此,如果我们decl_range.getEnd()使用函数定义转到 SourceManager ,我们将不会得到右大括号。end_of_the_end()使用词法分析器获取代码最后一位的位置:

SourceLocation
end_of_the_end(SourceLocation const & start_of_end, SourceManager & sm){
  LangOptions lopt;
  return Lexer::getLocForEndOfToken(start_of_end, 0, sm, lopt);
}
Run Code Online (Sandbox Code Playgroud)

回到run(),使用准确的开始和结束位置,您可以获得指向 SourceManager 的字符缓冲区的指针:

    const char * buff_begin( sm.getCharacterData(decl_begin));
    const char * buff_end( sm.getCharacterData(decl_end_end));
    std::string const func_string(buff_begin,buff_end);
Run Code Online (Sandbox Code Playgroud)

func_string 有函数的源代码;您可以写入新文件等。

为了消除原始文件中的函数源,我们可以生成一个替换,并让 RefactoringTool 为我们应用它。要创建替换,我们需要再添加两行代码到run()

    uint32_t const decl_length =
      sm.getFileOffset(decl_end_end) - sm.getFileOffset(decl_begin);
    Replacement repl(sm,decl_begin,decl_length,"");
Run Code Online (Sandbox Code Playgroud)

Replacement ctor 使用 SourceManager,从哪里开始替换,覆盖多少,覆盖什么。此替换将覆盖整个原始函数定义。

我们如何获得对 RefactoringTool 的替换?我们可以使用对 RefactoringTool 的 Replacements 成员的引用来构造回调类。在 中run,人们会得出结论:

    repls_.insert(repl);
Run Code Online (Sandbox Code Playgroud)

我在CoARCT 的apps/FunctionMover.cc 中添加了一个工作示例应用程序,这是 Clang 重构示例的集合