总结:要获取源文本,请使用SourceManager;要从原始文件中删除该函数,请生成 Replacement 并使用 RefactoringTool 应用它。
首先,这是一种获取函数定义源代码的方法,假设 AST 匹配器看起来像这样:
auto matcher(std::string const & fname) {
return functionDecl(hasName(fname)).bind("f_decl");
}
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));
decl_start_end 和 decl_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(),有了准确的开始和结束位置,你可以得到指向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);
func_string 有函数的源代码;您可以写入新文件等。
为了消除原始文件中的函数源,我们可以生成一个替换,并让重构工具为我们应用它。要创建替换,我们需要在run() 中再添加两行代码:
uint32_t const decl_length =
sm.getFileOffset(decl_end_end) - sm.getFileOffset(decl_begin);
Replacement repl(sm,decl_begin,decl_length,"");
Replacement ctor 获取 SourceManager,从哪里开始替换,覆盖多少,以及覆盖什么。此替换将覆盖整个原始函数定义。
我们如何获得 RefactoringTool 的替换?我们可以使用对 RefactoringTool 的 Replacements 成员的引用来构造回调类。在run 中,人们会得出结论:
repls_.insert(repl);
我在 CoARCT, a collection of Clang refactoring examples 的 apps/FunctionMover.cc 中添加了一个工作示例应用程序。