c++ - Clang 使用 LibTooling Rewriter 生成新文件?

标签 c++ clang llvm libtooling

我正在使用 LibTooling 进行一些分析。我知道如何遍历 AST 并将一些文本插入某处。例如,

Rewriter mywriter;
mywriter.InsertTextAfter(func->getLocEnd(),"Hello");

现在我想知道有没有办法保存代码? (天气保存到原始文件或生成新文件)

因为在分析之后,我只能在终端上读取结果,这对我来说还不够。

最佳答案

它应该在您的 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 就是您想要的输出文件。

关于c++ - Clang 使用 LibTooling Rewriter 生成新文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43157172/

相关文章:

c++ - 从 MCInsts (x86) 获取 "actual"寄存器

c++列表迭代器的段错误

c++ - 构造函数模板

c++ - 在分配大型数组期间增加内存

c++ - clang:自定义属性在 AST 中不可见

python - 如何使用 Python 将更改应用于源文件?

c++ - 静态断言失败,返回 "Windows headers require the default packing option..."

ios - 使用 RCT_EXPORT_METHOD 语法时如何修复 Xcode 上的 'Semicolon before method body is ignored' 错误?

concurrency - LLVM:在分布式/并发系统中 move 生成的代码

c++ - clang 如何引导 C/C++ 代码优化?