#include "clang/Tooling/CompilationDatabase.h" #include "clang/Tooling/Core/Replacement.h" #include "clang/Tooling/Tooling.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Regex.h" #include "llvm/Support/raw_ostream.h" #include "clang/Tooling/Refactoring/RefactoringTool.h" #includeusing namespace llvm; using namespace clang; using namespace clang::tooling; using namespace clang::ast_matchers; void insertMainMethod(SourceManager &SM, ASTContext &Context) { const FunctionDecl *Main = nullptr; for (const auto &D : Context.getTranslationUnitDecl()->decls()) { if (const auto *FD = llvm::dyn_cast (&D)) { if (FD->isMain()) { Main = FD; break; } } } if (!Main) return;
#include "clang/Basic/SourceManager.h" #include "clang/AST/ASTContext.h" #include "clang/AST/ASTNodeTraverser.h" #include "clang/ASTMatchers/ASTMatchers.h" #include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/Frontend/CompilerInstance.h" #include "llvm/Support/raw_ostream.h" using namespace clang; using namespace clang::ast_matchers; class MyASTConsumer : public ASTConsumer { public: MyASTConsumer(SourceManager &SM) : SM(SM) {} virtual void HandleTranslationUnit(ASTContext &Context) { MatchFinder Finder; Finder.addMatcher( varDecl(hasName("x")).bind("x"), [this, &Context](const MatchFinder::MatchResult &Result) { const VarDecl *X = Result.Nodes.getNodeAsBoth of these examples use the SourceManager class from the Clang tooling library. Example 1 uses it to retrieve the context's translation unit declarations, check whether there is a main function, and locate it. Example 2 uses it to traverse the AST, retrieve location information about a variable declaration node, and print the line number of that location. These examples use various other libraries and classes from Clang, such as ASTContext, MatchFinder, and FrontendAction, and they are part of the Clang Tooling package library.("x"); const SourceLocation Loc = X->getLocation(); const unsigned Line = SM.getExpansionLineNumber(Loc); llvm::outs() << "Variable X is declared on line " << Line << "\n"; }); Finder.matchAST(Context); } private: SourceManager &SM; }; class MyFrontendAction : public ASTFrontendAction { public: virtual std::unique_ptr CreateASTConsumer( CompilerInstance &Compiler, llvm::StringRef InFile) { SM = &Compiler.getSourceManager(); return std::unique_ptr (new MyASTConsumer(*SM)); } private: SourceManager *SM; };