我正在使用LibTooling做一些分析。我知道如何遍历AST并在某个地方插入一些文本。例如,
Rewriter mywriter;
mywriter.InsertTextAfter(func->getLocEnd(),"Hello");现在我想知道有什么方法可以保存代码吗?(天气将其保存到原始文件或生成新文件)
因为经过分析,我只能在终端上读到结果,这对我来说是不够的。
发布于 2017-07-01 15:43:05
应该在ASTFrontEndAction对象中在EndSourceFileAction()函数中完成
// For each source file provided to the tool, a new FrontendAction is created.
class MyFrontendAction : public ASTFrontendAction {
public:
MyFrontendAction() {}
void EndSourceFileAction() override {
SourceManager &SM = TheRewriter.getSourceMgr();
llvm::errs() << "** EndSourceFileAction for: "
<< SM.getFileEntryForID(SM.getMainFileID())->getName() << "\n";
// Now emit the rewritten buffer.
// TheRewriter.getEditBuffer(SM.getMainFileID()).write(llvm::outs()); --> this will output to screen as what you got.
std::error_code error_code;
llvm::raw_fd_ostream outFile("output.txt", error_code, llvm::sys::fs::F_None);
TheRewriter.getEditBuffer(SM.getMainFileID()).write(outFile); // --> this will write the result to outFile
outFile.close();
}
//as normal, make sure it matches your ASTConsumer constructor
std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
StringRef file) override {
llvm::errs() << "** Creating AST consumer for: " << file << "\n";
TheRewriter.setSourceMgr(CI.getSourceManager(), CI.getLangOpts());
return llvm::make_unique<MyASTConsumer>(TheRewriter,&CI.getASTContext());
}在这种情况下,output.txt是您想要的输出文件。
发布于 2017-04-19 14:41:08
mywriter.overwriteChangedFiles();
https://stackoverflow.com/questions/43157172
复制相似问题