摘要:要获取源文本,请使用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
and decl_end_end
?使用 SourceRange 有一个问题:结束位置不是代码结束的位置;它是范围中最后一个标记的开始。所以如果我们去 SourceManagerdecl_range.getEnd()
对于函数定义,我们不会得到右大括号。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);
}
Back in 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 有函数的源代码;您可以写入新文件等。
为了消除原始文件中的函数源,我们可以生成一个替换,并让 RefactoringTool 为我们应用它。要创建替换,我们需要再添加两行代码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);
我在 apps/FunctionMover.cc 中添加了一个工作示例应用程序CoARCT,Clang 重构示例集合 https://github.com/lanl/CoARCT.