我正在使用Clang工具进行源到源的转换。目前,我能够生成修改后的源代码并保存修改后的文件。这是我用来发出修改后的文件的功能。
rewriter.getEditBuffer(sm.getMainFileID()).write(llvm::outs());
// I can also save all modified files at once
rewriter.overwriteChangedFiles();
但是,我不想保存修改后的文件,而是发出预处理器输出。我想实现类似下面的代码。
rewriter.emitPreprocessorOutput(rewriter.getBuffers());
关于如何执行此操作的任何提示?
这里是我正在使用的参考代码的一小部分。
#include <sstream>
#include <iostream>
#include "clang/Driver/Options.h"
#include "clang/AST/AST.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Frontend/ASTConsumers.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "clang/Rewrite/Core/Rewriter.h"
#include "clang/AST/DeclCXX.h"
#include "llvm/ADT/Sequence.h"
#include <iostream>
#include <iterator>
#include <string>
using namespace std;
using namespace clang;
using namespace clang::driver;
using namespace clang::tooling;
using namespace llvm;
Rewriter rewriter;
class ExampleVisitor : public RecursiveASTVisitor<ExampleVisitor> {
private:
ASTContext *astContext;
public:
explicit ExampleVisitor(CompilerInstance *CI) : astContext(&(CI->getASTContext())) {}
// Custom modifier visitors
// ...
};
class ExampleASTConsumer : public ASTConsumer {
private:
ExampleVisitor *visitor;
public:
explicit ExampleASTConsumer(CompilerInstance *CI) : visitor(new ExampleVisitor(CI)) { }
virtual void HandleTranslationUnit(ASTContext &Context) {
visitor->TraverseDecl(Context.getTranslationUnitDecl());
}
};
class ExampleFrontendAction : public ASTFrontendAction {
public:
virtual std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI, StringRef file) {
rewriter.setSourceMgr(CI.getSourceManager(), CI.getLangOpts());
return std::unique_ptr<clang::ASTConsumer>(new ExampleASTConsumer(&CI)); // pass CI pointer to ASTConsumer
}
void EndSourceFileAction() override {
SourceManager &sm = rewriter.getSourceMgr();
rewriter.InsertTextBefore(sm.getLocForStartOfFile(sm.getMainFileID()), "// This file has been modified");
rewriter.getEditBuffer(sm.getMainFileID()).write(llvm::outs());
}
};
static llvm::cl::OptionCategory ReplaceTypeCategory("Source-to-source options");
int main(int argc, const char **argv) {
CommonOptionsParser op(argc, argv, ReplaceTypeCategory);
ClangTool Tool(op.getCompilations(), op.getSourcePathList());
int result = Tool.run(newFrontendActionFactory<ExampleFrontendAction>().get());
return result;
}
快速参考