clang-tools  8.0.0
ToolTemplate.cpp
Go to the documentation of this file.
1 //===---- tools/extra/ToolTemplate.cpp - Template for refactoring tool ----===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements an empty refactoring tool using the clang tooling.
11 // The goal is to lower the "barrier to entry" for writing refactoring tools.
12 //
13 // Usage:
14 // tool-template <cmake-output-dir> <file1> <file2> ...
15 //
16 // Where <cmake-output-dir> is a CMake build directory in which a file named
17 // compile_commands.json exists (enable -DCMAKE_EXPORT_COMPILE_COMMANDS in
18 // CMake to get this output).
19 //
20 // <file1> ... specify the paths of files in the CMake source tree. This path
21 // is looked up in the compile command database. If the path of a file is
22 // absolute, it needs to point into CMake's source tree. If the path is
23 // relative, the current working directory needs to be in the CMake source
24 // tree and the file must be in a subdirectory of the current working
25 // directory. "./" prefixes in the relative files will be automatically
26 // removed, but the rest of a relative path must be a suffix of a path in
27 // the compile command line database.
28 //
29 // For example, to use tool-template on all files in a subtree of the
30 // source tree, use:
31 //
32 // /path/in/subtree $ find . -name '*.cpp'|
33 // xargs tool-template /path/to/build
34 //
35 //===----------------------------------------------------------------------===//
36 
37 #include "clang/ASTMatchers/ASTMatchFinder.h"
38 #include "clang/ASTMatchers/ASTMatchers.h"
39 #include "clang/Basic/SourceManager.h"
40 #include "clang/Frontend/FrontendActions.h"
41 #include "clang/Lex/Lexer.h"
42 #include "clang/Tooling/CommonOptionsParser.h"
43 #include "clang/Tooling/Execution.h"
44 #include "clang/Tooling/Refactoring.h"
45 #include "clang/Tooling/Refactoring/AtomicChange.h"
46 #include "clang/Tooling/Tooling.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/MemoryBuffer.h"
49 #include "llvm/Support/Signals.h"
50 
51 using namespace clang;
52 using namespace clang::ast_matchers;
53 using namespace clang::tooling;
54 using namespace llvm;
55 
56 namespace {
57 class ToolTemplateCallback : public MatchFinder::MatchCallback {
58 public:
59  ToolTemplateCallback(ExecutionContext &Context) : Context(Context) {}
60 
61  void run(const MatchFinder::MatchResult &Result) override {
62  // TODO: This routine will get called for each thing that the matchers
63  // find.
64  // At this point, you can examine the match, and do whatever you want,
65  // including replacing the matched text with other text
66  auto *D = Result.Nodes.getNodeAs<NamedDecl>("decl");
67  assert(D);
68  // Use AtomicChange to get a key.
69  if (D->getBeginLoc().isValid()) {
70  AtomicChange Change(*Result.SourceManager, D->getBeginLoc());
71  Context.reportResult(Change.getKey(), D->getQualifiedNameAsString());
72  }
73  }
74 
75  void onStartOfTranslationUnit() override {
76  Context.reportResult("START", "Start of TU.");
77  }
78  void onEndOfTranslationUnit() override {
79  Context.reportResult("END", "End of TU.");
80  }
81 
82 private:
83  ExecutionContext &Context;
84 };
85 } // end anonymous namespace
86 
87 // Set up the command line options
88 static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
89 static cl::OptionCategory ToolTemplateCategory("tool-template options");
90 
91 int main(int argc, const char **argv) {
92  llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
93 
94  auto Executor = clang::tooling::createExecutorFromCommandLineArgs(
95  argc, argv, ToolTemplateCategory);
96 
97  if (!Executor) {
98  llvm::errs() << llvm::toString(Executor.takeError()) << "\n";
99  return 1;
100  }
101 
102  ast_matchers::MatchFinder Finder;
103  ToolTemplateCallback Callback(*Executor->get()->getExecutionContext());
104 
105  // TODO: Put your matchers here.
106  // Use Finder.addMatcher(...) to define the patterns in the AST that you
107  // want to match against. You are not limited to just one matcher!
108  //
109  // This is a sample matcher:
110  Finder.addMatcher(
111  namedDecl(cxxRecordDecl(), isExpansionInMainFile()).bind("decl"),
112  &Callback);
113 
114  auto Err = Executor->get()->execute(newFrontendActionFactory(&Finder));
115  if (Err) {
116  llvm::errs() << llvm::toString(std::move(Err)) << "\n";
117  }
118  Executor->get()->getToolResults()->forEachResult(
119  [](llvm::StringRef key, llvm::StringRef value) {
120  llvm::errs() << "----" << key.str() << "\n" << value.str() << "\n";
121  });
122 }
Some operations such as code completion produce a set of candidates.
static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage)
int main(int argc, const char **argv)
static llvm::StringRef toString(SpecialMemberFunctionsCheck::SpecialMemberFunctionKind K)
llvm::unique_function< void(llvm::Expected< T >)> Callback
A Callback<T> is a void function that accepts Expected<T>.
Definition: Function.h:29
static cl::OptionCategory ToolTemplateCategory("tool-template options")
const Decl * D
Definition: XRefs.cpp:79
llvm::Optional< llvm::Expected< tooling::AtomicChanges > > Result
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//