我将MatchFinder定义为:
MatchFinder Finder;
Finder.addMatcher(FunctionCallMatcher, &printer);
StatementMatcher和MatchCallback如下:
DeclarationMatcher FunctionCallMatcher = functionDecl(isDefinition()).bind("func");
class FuncPrinter : public MatchFinder::MatchCallback {
public :
FuncPrinter(){Replace = new Replacements;}
FuncPrinter(Replacements *Replace) : Replace(Replace) {}
virtual void run(const MatchFinder::MatchResult &Result) {
clang::ASTContext *Context = Result.Context;
if (const FunctionDecl *FS = Result.Nodes.getNodeAs<clang::FunctionDecl>("func")) {
FS->dump();
SourceRange sr = FS->getSourceRange();
std::string s = std::string("test");
Replacement Rep(*(Result.SourceManager), sr.getEnd(), s.length(), s);
if(llvm::Error err = Replace->add(Rep)) {
}
}
}
private:
Replacements *Replace;
};
在我的主代码中,我为finder执行前端操作,并获得替换:
RefactoringTool Tool(OptionsParser.getCompilations(),
OptionsParser.getSourcePathList());
FuncPrinter printer;
MatchFinder Finder;
Finder.addMatcher(FunctionCallMatcher, &printer);
if (int Result = Tool.run(newFrontendActionFactory(&Finder).get())) {
return Result;
}
std::map<std::string, Replacements>& reps = Tool.getReplacements();
虽然我可以观察到在执行FrontendAction时FuncPrinter中的Replace变量被填充,Tool.getReplacements()
会返回一个空的std::map<std::string, Replacements>
。如果有人能提出我出错的地方,我将不胜感激。
答案 0 :(得分:0)
管理解决它,所以发布我自己的解决方案。问题在于使用默认构造函数,而使用FuncPrinter(reps_t *reps) does the trick.
class FuncPrinter : public MatchFinder::MatchCallback {
using reps_t = std::map<std::string, Replacements>;
public :
FuncPrinter(reps_t *reps) : Replace(reps) {}
virtual void run(const MatchFinder::MatchResult &Result) {
clang::ASTContext *Context = Result.Context;
if (const FunctionDecl *FS = Result.Nodes.getNodeAs<clang::FunctionDecl>("func")) {
FS->dump();
SourceRange sr = FS->getSourceRange();
std::string s = std::string("test");
Replacement Rep(*(Result.SourceManager), sr.getEnd(), s.length(), s);
Replace->insert(std::pair<std::string,Replacements>(path, Replacements(Rep)));
}
}
private:
reps_t *Replace;
};