Skip to content

Instantly share code, notes, and snippets.

@vaioco
Created October 26, 2017 09:17
Show Gist options
  • Save vaioco/3ba0fbf2b0389eac47bb8c9012e83abf to your computer and use it in GitHub Desktop.
Save vaioco/3ba0fbf2b0389eac47bb8c9012e83abf to your computer and use it in GitHub Desktop.

Revisions

  1. vaioco created this gist Oct 26, 2017.
    43 changes: 43 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@


    class ReplacementsTest : public MatchFinder::MatchCallback {
    using reps_t = std::map<std::string, Replacements>;
    public:
    ReplacementsTest(reps_t *reps) : Replace(reps) {}
    virtual void run(const MatchFinder::MatchResult &Result) {
    clang::ASTContext *Context = Result.Context;
    const clang::FunctionDecl *FS = Result.Nodes.getNodeAs<clang::FunctionDecl>("funcdecl");
    if (!FS || !Context->getSourceManager().isWrittenInMainFile(FS->getLocStart()))
    return;
    else{
    clang::SourceRange sr = FS->getSourceRange();
    std::string s = std::string("//test123\n");
    auto *sm = &Context->getSourceManager();
    auto fpath = sm->getFilename(FS->getLocation()).str();
    Replacement Rep(*(Result.SourceManager), sr.getBegin(), 0, s);
    auto res = Replace->insert(std::pair<std::string, Replacements>(fpath, Replacements(Rep)));
    if (res.second == false) {
    llvm::errs() << "map error\n";
    }
    }
    }
    private:
    reps_t *Replace;
    };

    int main(int argc, const char **argv) {
    CommonOptionsParser OptionsParser(argc, argv, MyToolCategory);
    ClangTool Tool(OptionsParser.getCompilations(),
    OptionsParser.getSourcePathList());
    // how the following line should look like?
    // as RefactoringTool was in place, i was doing:
    ReplacementsTest rtest(&Tool.getReplacements());
    MatchFinder Finder;

    StatementMatcher LoopMatcher = forStmt().bind("forLoop");
    DeclarationMatcher FuncMatcher = functionDecl(isDefinition()).bind("funcdecl");
    Finder.addMatcher(FuncMatcher, &rtest);
    if(int result = Tool.run(newFrontendActionFactory(&Finder).get())){
    return result;
    }
    }