clang-tools  9.0.0svn
ClangTidy.h
Go to the documentation of this file.
1 //===--- ClangTidy.h - clang-tidy -------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDY_H
10 #define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDY_H
11 
13 #include "ClangTidyOptions.h"
14 #include "clang/ASTMatchers/ASTMatchFinder.h"
15 #include "clang/Basic/Diagnostic.h"
16 #include "clang/Basic/SourceManager.h"
17 #include "clang/Tooling/Refactoring.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/Support/raw_ostream.h"
20 #include <memory>
21 #include <type_traits>
22 #include <vector>
23 
24 namespace clang {
25 
26 class CompilerInstance;
27 namespace tooling {
28 class CompilationDatabase;
29 }
30 
31 namespace tidy {
32 
33 /// \brief Provides access to the ``ClangTidyCheck`` options via check-local
34 /// names.
35 ///
36 /// Methods of this class prepend ``CheckName + "."`` to translate check-local
37 /// option names to global option names.
38 class OptionsView {
39 public:
40  /// \brief Initializes the instance using \p CheckName + "." as a prefix.
41  OptionsView(StringRef CheckName,
42  const ClangTidyOptions::OptionMap &CheckOptions);
43 
44  /// \brief Read a named option from the ``Context``.
45  ///
46  /// Reads the option with the check-local name \p LocalName from the
47  /// ``CheckOptions``. If the corresponding key is not present, returns
48  /// \p Default.
49  std::string get(StringRef LocalName, StringRef Default) const;
50 
51  /// \brief Read a named option from the ``Context``.
52  ///
53  /// Reads the option with the check-local name \p LocalName from local or
54  /// global ``CheckOptions``. Gets local option first. If local is not present,
55  /// falls back to get global option. If global option is not present either,
56  /// returns Default.
57  std::string getLocalOrGlobal(StringRef LocalName, StringRef Default) const;
58 
59  /// \brief Read a named option from the ``Context`` and parse it as an
60  /// integral type ``T``.
61  ///
62  /// Reads the option with the check-local name \p LocalName from the
63  /// ``CheckOptions``. If the corresponding key is not present, returns
64  /// \p Default.
65  template <typename T>
66  typename std::enable_if<std::is_integral<T>::value, T>::type
67  get(StringRef LocalName, T Default) const {
68  std::string Value = get(LocalName, "");
69  T Result = Default;
70  if (!Value.empty())
71  StringRef(Value).getAsInteger(10, Result);
72  return Result;
73  }
74 
75  /// \brief Read a named option from the ``Context`` and parse it as an
76  /// integral type ``T``.
77  ///
78  /// Reads the option with the check-local name \p LocalName from local or
79  /// global ``CheckOptions``. Gets local option first. If local is not present,
80  /// falls back to get global option. If global option is not present either,
81  /// returns Default.
82  template <typename T>
83  typename std::enable_if<std::is_integral<T>::value, T>::type
84  getLocalOrGlobal(StringRef LocalName, T Default) const {
85  std::string Value = getLocalOrGlobal(LocalName, "");
86  T Result = Default;
87  if (!Value.empty())
88  StringRef(Value).getAsInteger(10, Result);
89  return Result;
90  }
91 
92  /// \brief Stores an option with the check-local name \p LocalName with string
93  /// value \p Value to \p Options.
94  void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName,
95  StringRef Value) const;
96 
97  /// \brief Stores an option with the check-local name \p LocalName with
98  /// ``int64_t`` value \p Value to \p Options.
99  void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName,
100  int64_t Value) const;
101 
102 private:
103  std::string NamePrefix;
104  const ClangTidyOptions::OptionMap &CheckOptions;
105 };
106 
107 /// \brief Base class for all clang-tidy checks.
108 ///
109 /// To implement a ``ClangTidyCheck``, write a subclass and override some of the
110 /// base class's methods. E.g. to implement a check that validates namespace
111 /// declarations, override ``registerMatchers``:
112 ///
113 /// ~~~{.cpp}
114 /// void registerMatchers(ast_matchers::MatchFinder *Finder) override {
115 /// Finder->addMatcher(namespaceDecl().bind("namespace"), this);
116 /// }
117 /// ~~~
118 ///
119 /// and then override ``check(const MatchResult &Result)`` to do the actual
120 /// check for each match.
121 ///
122 /// A new ``ClangTidyCheck`` instance is created per translation unit.
123 ///
124 /// FIXME: Figure out whether carrying information from one TU to another is
125 /// useful/necessary.
126 class ClangTidyCheck : public ast_matchers::MatchFinder::MatchCallback {
127 public:
128  /// \brief Initializes the check with \p CheckName and \p Context.
129  ///
130  /// Derived classes must implement the constructor with this signature or
131  /// delegate it. If a check needs to read options, it can do this in the
132  /// constructor using the Options.get() methods below.
133  ClangTidyCheck(StringRef CheckName, ClangTidyContext *Context)
134  : CheckName(CheckName), Context(Context),
135  Options(CheckName, Context->getOptions().CheckOptions) {
136  assert(Context != nullptr);
137  assert(!CheckName.empty());
138  }
139 
140  /// \brief Override this to register ``PPCallbacks`` with ``Compiler``.
141  ///
142  /// This should be used for clang-tidy checks that analyze preprocessor-
143  /// dependent properties, e.g. the order of include directives.
144  virtual void registerPPCallbacks(CompilerInstance &Compiler) {}
145 
146  /// \brief Override this to register AST matchers with \p Finder.
147  ///
148  /// This should be used by clang-tidy checks that analyze code properties that
149  /// dependent on AST knowledge.
150  ///
151  /// You can register as many matchers as necessary with \p Finder. Usually,
152  /// "this" will be used as callback, but you can also specify other callback
153  /// classes. Thereby, different matchers can trigger different callbacks.
154  ///
155  /// If you need to merge information between the different matchers, you can
156  /// store these as members of the derived class. However, note that all
157  /// matches occur in the order of the AST traversal.
158  virtual void registerMatchers(ast_matchers::MatchFinder *Finder) {}
159 
160  /// \brief ``ClangTidyChecks`` that register ASTMatchers should do the actual
161  /// work in here.
162  virtual void check(const ast_matchers::MatchFinder::MatchResult &Result) {}
163 
164  /// \brief Add a diagnostic with the check's name.
165  DiagnosticBuilder diag(SourceLocation Loc, StringRef Description,
166  DiagnosticIDs::Level Level = DiagnosticIDs::Warning);
167 
168  /// \brief Should store all options supported by this check with their
169  /// current values or default values for options that haven't been overridden.
170  ///
171  /// The check should use ``Options.store()`` to store each option it supports
172  /// whether it has the default value or it has been overridden.
173  virtual void storeOptions(ClangTidyOptions::OptionMap &Options) {}
174 
175 private:
176  void run(const ast_matchers::MatchFinder::MatchResult &Result) override;
177  StringRef getID() const override { return CheckName; }
178  std::string CheckName;
179  ClangTidyContext *Context;
180 
181 protected:
183  /// \brief Returns the main file name of the current translation unit.
184  StringRef getCurrentMainFile() const { return Context->getCurrentFile(); }
185  /// \brief Returns the language options from the context.
186  LangOptions getLangOpts() const { return Context->getLangOpts(); }
187 };
188 
190 
192 public:
194 
195  /// \brief Returns an ASTConsumer that runs the specified clang-tidy checks.
196  std::unique_ptr<clang::ASTConsumer>
197  CreateASTConsumer(clang::CompilerInstance &Compiler, StringRef File);
198 
199  /// \brief Get the list of enabled checks.
200  std::vector<std::string> getCheckNames();
201 
202  /// \brief Get the union of options from all checks.
204 
205 private:
206  ClangTidyContext &Context;
207  std::unique_ptr<ClangTidyCheckFactories> CheckFactories;
208 };
209 
210 /// \brief Fills the list of check names that are enabled when the provided
211 /// filters are applied.
212 std::vector<std::string> getCheckNames(const ClangTidyOptions &Options,
214 
215 /// \brief Returns the effective check-specific options.
216 ///
217 /// The method configures ClangTidy with the specified \p Options and collects
218 /// effective options from all created checks. The returned set of options
219 /// includes default check-specific options for all keys not overridden by \p
220 /// Options.
222 getCheckOptions(const ClangTidyOptions &Options,
223  bool AllowEnablingAnalyzerAlphaCheckers);
224 
225 /// \brief Run a set of clang-tidy checks on a set of files.
226 ///
227 /// \param EnableCheckProfile If provided, it enables check profile collection
228 /// in MatchFinder, and will contain the result of the profile.
229 /// \param StoreCheckProfile If provided, and EnableCheckProfile is true,
230 /// the profile will not be output to stderr, but will instead be stored
231 /// as a JSON file in the specified directory.
232 std::vector<ClangTidyError>
234  const tooling::CompilationDatabase &Compilations,
235  ArrayRef<std::string> InputFiles,
236  llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS,
237  bool EnableCheckProfile = false,
238  llvm::StringRef StoreCheckProfile = StringRef());
239 
240 // FIXME: This interface will need to be significantly extended to be useful.
241 // FIXME: Implement confidence levels for displaying/fixing errors.
242 //
243 /// \brief Displays the found \p Errors to the users. If \p Fix is true, \p
244 /// Errors containing fixes are automatically applied and reformatted. If no
245 /// clang-format configuration file is found, the given \P FormatStyle is used.
246 void handleErrors(llvm::ArrayRef<ClangTidyError> Errors,
247  ClangTidyContext &Context, bool Fix,
248  unsigned &WarningsAsErrorsCount,
249  llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS);
250 
251 /// \brief Serializes replacements into YAML and writes them to the specified
252 /// output stream.
253 void exportReplacements(StringRef MainFilePath,
254  const std::vector<ClangTidyError> &Errors,
255  raw_ostream &OS);
256 
257 } // end namespace tidy
258 } // end namespace clang
259 
260 #endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDY_H
SourceLocation Loc
&#39;#&#39; location in the include directive
virtual void registerMatchers(ast_matchers::MatchFinder *Finder)
Override this to register AST matchers with Finder.
Definition: ClangTidy.h:158
std::vector< ClangTidyError > runClangTidy(clang::tidy::ClangTidyContext &Context, const tooling::CompilationDatabase &Compilations, ArrayRef< std::string > InputFiles, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > BaseFS, bool EnableCheckProfile=false, llvm::StringRef StoreCheckProfile=StringRef())
Run a set of clang-tidy checks on a set of files.
LangOptions getLangOpts() const
Returns the language options from the context.
Definition: ClangTidy.h:186
std::enable_if< std::is_integral< T >::value, T >::type getLocalOrGlobal(StringRef LocalName, T Default) const
Read a named option from the Context and parse it as an integral type T.
Definition: ClangTidy.h:84
static cl::opt< std::string > StoreCheckProfile("store-check-profile", cl::desc(R"( By default reports are printed in tabulated format to stderr. When this option is passed, these per-TU profiles are instead stored as JSON. )"), cl::value_desc("prefix"), cl::cat(ClangTidyCategory))
Contains options for clang-tidy.
StringRef getCurrentMainFile() const
Returns the main file name of the current translation unit.
Definition: ClangTidy.h:184
Base class for all clang-tidy checks.
Definition: ClangTidy.h:126
ClangTidyOptions::OptionMap getCheckOptions(const ClangTidyOptions &Options, bool AllowEnablingAnalyzerAlphaCheckers)
Returns the effective check-specific options.
Definition: ClangTidy.cpp:494
A collection of ClangTidyCheckFactory instances.
void handleErrors(llvm::ArrayRef< ClangTidyError > Errors, ClangTidyContext &Context, bool Fix, unsigned &WarningsAsErrorsCount, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > BaseFS)
Displays the found Errors to the users.
Definition: ClangTidy.cpp:580
void exportReplacements(StringRef MainFilePath, const std::vector< ClangTidyError > &Errors, raw_ostream &OS)
Serializes replacements into YAML and writes them to the specified output stream. ...
static cl::opt< bool > AllowEnablingAnalyzerAlphaCheckers("allow-enabling-analyzer-alpha-checkers", cl::init(false), cl::Hidden, cl::cat(ClangTidyCategory))
This option allows enabling the experimental alpha checkers from the static analyzer.
virtual void registerPPCallbacks(CompilerInstance &Compiler)
Override this to register PPCallbacks with Compiler.
Definition: ClangTidy.h:144
const LangOptions & getLangOpts() const
Gets the language options from the AST context.
StringRef getCurrentFile() const
Returns the main file name of the current translation unit.
std::map< std::string, std::string > OptionMap
llvm::Optional< llvm::Expected< tooling::AtomicChanges > > Result
static cl::opt< bool > EnableCheckProfile("enable-check-profile", cl::desc(R"( Enable per-check timing profiles, and print a report to stderr. )"), cl::init(false), cl::cat(ClangTidyCategory))
ClangTidyCheck(StringRef CheckName, ClangTidyContext *Context)
Initializes the check with CheckName and Context.
Definition: ClangTidy.h:133
Provides access to the ClangTidyCheck options via check-local names.
Definition: ClangTidy.h:38
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
std::vector< std::string > getCheckNames(const ClangTidyOptions &Options, bool AllowEnablingAnalyzerAlphaCheckers)
Fills the list of check names that are enabled when the provided filters are applied.
Definition: ClangTidy.cpp:483
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
const char * Description
Definition: Dexp.cpp:257
static cl::opt< bool > Fix("fix", cl::desc(R"( Apply suggested fixes. Without -fix-errors clang-tidy will bail out if any compilation errors were found. )"), cl::init(false), cl::cat(ClangTidyCategory))
virtual void check(const ast_matchers::MatchFinder::MatchResult &Result)
ClangTidyChecks that register ASTMatchers should do the actual work in here.
Definition: ClangTidy.h:162
virtual void storeOptions(ClangTidyOptions::OptionMap &Options)
Should store all options supported by this check with their current values or default values for opti...
Definition: ClangTidy.h:173