RecursiveAstVisitor&Rewriter: How to add an include file?

Hi everyone,

I am trying to add an user defined include file at the top level of q
compilation unit with a RecursiveAstVisitor and a Rewriter. Is there
something like VisitModule?

Any hints are welcome!

Thanks

Marcel

After digging around I came to the following solution:

class MyFrontendAction : public ASTFrontendAction {
public:
MyFrontendAction() {}
void EndSourceFileAction() override {
SourceManager &SM = TheRewriter.getSourceMgr();
TheRewriter.getEditBuffer(SM.getMainFileID()).write(llvm::errs());

clang::SourceLocation loc = SM.getLocForStartOfFile(SM.getMainFileID());
std::stringstream SSBefore;
SSBefore << “#include "myinclude.h"\n”;
TheRewriter.InsertTextBefore(loc, SSBefore.str());

}

Thanks
Marcel

After digging around I came to the following solution:

class MyFrontendAction : public ASTFrontendAction {
public:
    MyFrontendAction() {}
    void EndSourceFileAction() override {
        SourceManager &SM = TheRewriter.getSourceMgr();
        TheRewriter.getEditBuffer(SM.getMainFileID()).write(llvm::errs());

        clang::SourceLocation loc =
SM.getLocForStartOfFile(SM.getMainFileID());
        std::stringstream SSBefore;
        SSBefore << "#include \"myinclude.h\"\n";

Why do you use a stream? InsertTextBefore takes a StringRef.

const char * before = R"(#include "myinclude.h")" "\n" ;
TheRewriter.InsertTextBefore(loc, before); // StringRef temporary constructed

        TheRewriter.InsertTextBefore(loc, SSBefore.str());
        ...
    }

Csaba