Clang using LibTooling Rewriter to generate new file?
Asked Answered
L

2

5

I'm using LibTooling to do some analysis. I know how to traverse the AST and insert some text into somewhere. For example,

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

Now I'm wondering if there are any way to save the code? (Weather save it to original file or generate a new file)

Because after the analysis, I can only read the result on terminal and it's not enough for me.

Lochner answered 1/4, 2017 at 12:57 Comment(0)
D
10

it should be done in your ASTFrontEndAction object, within the EndSourceFileAction() function

// 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());
  }

In that case output.txt is the output file you wanted.

Dusk answered 1/7, 2017 at 15:43 Comment(0)
B
0

mywriter.overwriteChangedFiles();

Befuddle answered 19/4, 2017 at 14:41 Comment(1)
The OP specifically asked if there was a way to save the edits to a new file.Verrazano

© 2022 - 2024 — McMap. All rights reserved.