clang-tools  3.8.0
ClangTidy.h
Go to the documentation of this file.
1 //===--- ClangTidy.h - clang-tidy -------------------------------*- C++ -*-===//
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 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDY_H
11 #define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDY_H
12 
14 #include "ClangTidyOptions.h"
15 #include "clang/ASTMatchers/ASTMatchFinder.h"
16 #include "clang/Basic/Diagnostic.h"
17 #include "clang/Basic/SourceManager.h"
18 #include "clang/Tooling/Refactoring.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include <memory>
22 #include <type_traits>
23 #include <vector>
24 
25 namespace clang {
26 
27 class CompilerInstance;
28 namespace tooling {
29 class CompilationDatabase;
30 }
31 
32 namespace tidy {
33 
34 /// \brief Provides access to the \c ClangTidyCheck options via check-local
35 /// names.
36 ///
37 /// Methods of this class prepend <tt>CheckName + "."</tt> to translate
38 /// check-local option names to global option names.
39 class OptionsView {
40 public:
41  /// \brief Initializes the instance using \p CheckName + "." as a prefix.
42  OptionsView(StringRef CheckName,
43  const ClangTidyOptions::OptionMap &CheckOptions);
44 
45  /// \brief Read a named option from the \c Context.
46  ///
47  /// Reads the option with the check-local name \p LocalName from the
48  /// \c CheckOptions. If the corresponding key is not present, returns
49  /// \p Default.
50  std::string get(StringRef LocalName, std::string Default) const;
51 
52  /// \brief Read a named option from the \c Context and parse it as an integral
53  /// type \c T.
54  ///
55  /// Reads the option with the check-local name \p LocalName from the
56  /// \c CheckOptions. If the corresponding key is not present, returns
57  /// \p Default.
58  template <typename T>
59  typename std::enable_if<std::is_integral<T>::value, T>::type
60  get(StringRef LocalName, T Default) const {
61  std::string Value = get(LocalName, "");
62  T Result = Default;
63  if (!Value.empty())
64  StringRef(Value).getAsInteger(10, Result);
65  return Result;
66  }
67 
68  /// \brief Stores an option with the check-local name \p LocalName with string
69  /// value \p Value to \p Options.
70  void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName,
71  StringRef Value) const;
72 
73  /// \brief Stores an option with the check-local name \p LocalName with
74  /// \c int64_t value \p Value to \p Options.
75  void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName,
76  int64_t Value) const;
77 
78 private:
79  std::string NamePrefix;
80  const ClangTidyOptions::OptionMap &CheckOptions;
81 };
82 
83 /// \brief Base class for all clang-tidy checks.
84 ///
85 /// To implement a \c ClangTidyCheck, write a subclass and override some of the
86 /// base class's methods. E.g. to implement a check that validates namespace
87 /// declarations, override \c registerMatchers:
88 ///
89 /// \code
90 /// registerMatchers(ast_matchers::MatchFinder *Finder) {
91 /// Finder->addMatcher(namespaceDecl().bind("namespace"), this);
92 /// }
93 /// \endcode
94 ///
95 /// and then override \c check(const MatchResult &Result) to do the actual
96 /// check for each match.
97 ///
98 /// A new \c ClangTidyCheck instance is created per translation unit.
99 ///
100 /// FIXME: Figure out whether carrying information from one TU to another is
101 /// useful/necessary.
102 class ClangTidyCheck : public ast_matchers::MatchFinder::MatchCallback {
103 public:
104  /// \brief Initializes the check with \p CheckName and \p Context.
105  ///
106  /// Derived classes must implement the constructor with this signature or
107  /// delegate it. If a check needs to read options, it can do this in the
108  /// constructor using the Options.get() methods below.
109  ClangTidyCheck(StringRef CheckName, ClangTidyContext *Context)
110  : CheckName(CheckName), Context(Context),
111  Options(CheckName, Context->getOptions().CheckOptions) {
112  assert(Context != nullptr);
113  assert(!CheckName.empty());
114  }
115 
116  /// \brief Override this to register \c PPCallbacks with \c Compiler.
117  ///
118  /// This should be used for clang-tidy checks that analyze preprocessor-
119  /// dependent properties, e.g. the order of include directives.
120  virtual void registerPPCallbacks(CompilerInstance &Compiler) {}
121 
122  /// \brief Override this to register ASTMatchers with \p Finder.
123  ///
124  /// This should be used by clang-tidy checks that analyze code properties that
125  /// dependent on AST knowledge.
126  ///
127  /// You can register as many matchers as necessary with \p Finder. Usually,
128  /// "this" will be used as callback, but you can also specify other callback
129  /// classes. Thereby, different matchers can trigger different callbacks.
130  ///
131  /// If you need to merge information between the different matchers, you can
132  /// store these as members of the derived class. However, note that all
133  /// matches occur in the order of the AST traversal.
134  virtual void registerMatchers(ast_matchers::MatchFinder *Finder) {}
135 
136  /// \brief \c ClangTidyChecks that register ASTMatchers should do the actual
137  /// work in here.
138  virtual void check(const ast_matchers::MatchFinder::MatchResult &Result) {}
139 
140  /// \brief Add a diagnostic with the check's name.
141  DiagnosticBuilder diag(SourceLocation Loc, StringRef Description,
142  DiagnosticIDs::Level Level = DiagnosticIDs::Warning);
143 
144  /// \brief Should store all options supported by this check with their
145  /// current values or default values for options that haven't been overridden.
146  ///
147  /// The check should use \c Options.store() to store each option it supports
148  /// whether it has the default value or it has been overridden.
150 
151 private:
152  void run(const ast_matchers::MatchFinder::MatchResult &Result) override;
153  StringRef getID() const override { return CheckName; }
154  std::string CheckName;
155  ClangTidyContext *Context;
156 
157 protected:
159  /// \brief Returns the main file name of the current translation unit.
160  StringRef getCurrentMainFile() const { return Context->getCurrentFile(); }
161  /// \brief Returns the language options from the context.
162  LangOptions getLangOpts() const { return Context->getLangOpts(); }
163 };
164 
165 class ClangTidyCheckFactories;
166 
168 public:
170 
171  /// \brief Returns an ASTConsumer that runs the specified clang-tidy checks.
172  std::unique_ptr<clang::ASTConsumer>
173  CreateASTConsumer(clang::CompilerInstance &Compiler, StringRef File);
174 
175  /// \brief Get the list of enabled checks.
176  std::vector<std::string> getCheckNames();
177 
178  /// \brief Get the union of options from all checks.
180 
181 private:
182  typedef std::vector<std::pair<std::string, bool>> CheckersList;
183  CheckersList getCheckersControlList(GlobList &Filter);
184 
185  ClangTidyContext &Context;
186  std::unique_ptr<ClangTidyCheckFactories> CheckFactories;
187 };
188 
189 /// \brief Fills the list of check names that are enabled when the provided
190 /// filters are applied.
191 std::vector<std::string> getCheckNames(const ClangTidyOptions &Options);
192 
193 /// \brief Returns the effective check-specific options.
194 ///
195 /// The method configures ClangTidy with the specified \p Options and collects
196 /// effective options from all created checks. The returned set of options
197 /// includes default check-specific options for all keys not overridden by \p
198 /// Options.
200 
201 /// \brief Run a set of clang-tidy checks on a set of files.
202 ///
203 /// \param Profile if provided, it enables check profile collection in
204 /// MatchFinder, and will contain the result of the profile.
206 runClangTidy(std::unique_ptr<ClangTidyOptionsProvider> OptionsProvider,
207  const tooling::CompilationDatabase &Compilations,
208  ArrayRef<std::string> InputFiles,
209  std::vector<ClangTidyError> *Errors,
210  ProfileData *Profile = nullptr);
211 
212 // FIXME: This interface will need to be significantly extended to be useful.
213 // FIXME: Implement confidence levels for displaying/fixing errors.
214 //
215 /// \brief Displays the found \p Errors to the users. If \p Fix is true, \p
216 /// Errors containing fixes are automatically applied.
217 void handleErrors(const std::vector<ClangTidyError> &Errors, bool Fix);
218 
219 /// \brief Serializes replacements into YAML and writes them to the specified
220 /// output stream.
221 void exportReplacements(const std::vector<ClangTidyError> &Errors,
222  raw_ostream &OS);
223 
224 } // end namespace tidy
225 } // end namespace clang
226 
227 #endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDY_H
SourceLocation Loc
'#' location in the include directive
virtual void registerMatchers(ast_matchers::MatchFinder *Finder)
Override this to register ASTMatchers with Finder.
Definition: ClangTidy.h:134
std::vector< std::string > getCheckNames()
Get the list of enabled checks.
Definition: ClangTidy.cpp:268
ClangTidyASTConsumerFactory(ClangTidyContext &Context)
Definition: ClangTidy.cpp:194
LangOptions getLangOpts() const
Returns the language options from the context.
Definition: ClangTidy.h:162
Read-only set of strings represented as a list of positive and negative globs.
StringRef getCurrentMainFile() const
Returns the main file name of the current translation unit.
Definition: ClangTidy.h:160
std::unique_ptr< ast_matchers::MatchFinder > Finder
Definition: ClangTidy.cpp:188
ClangTidyOptions::OptionMap getCheckOptions()
Get the union of options from all checks.
Definition: ClangTidy.cpp:283
HeaderHandle File
ClangTidyOptions::OptionMap getCheckOptions(const ClangTidyOptions &Options)
Returns the effective check-specific options.
Definition: ClangTidy.cpp:362
Contains options for clang-tidy.
Base class for all clang-tidy checks.
Definition: ClangTidy.h:102
StringRef getCurrentFile() const
Returns the main file name of the current translation unit.
void exportReplacements(const std::vector< ClangTidyError > &Errors, raw_ostream &OS)
Serializes replacements into YAML and writes them to the specified output stream. ...
Definition: ClangTidy.cpp:431
LangOptions getLangOpts() const
Gets the language options from the AST context.
void handleErrors(const std::vector< ClangTidyError > &Errors, bool Fix)
Displays the found Errors to the users.
Definition: ClangTidy.cpp:424
virtual void registerPPCallbacks(CompilerInstance &Compiler)
Override this to register PPCallbacks with Compiler.
Definition: ClangTidy.h:120
void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const
Stores an option with the check-local name LocalName with string value Value to Options.
Definition: ClangTidy.cpp:344
std::map< std::string, std::string > OptionMap
std::vector< std::string > getCheckNames(const ClangTidyOptions &Options)
Fills the list of check names that are enabled when the provided filters are applied.
Definition: ClangTidy.cpp:354
ClangTidyStats runClangTidy(std::unique_ptr< ClangTidyOptionsProvider > OptionsProvider, const tooling::CompilationDatabase &Compilations, ArrayRef< std::string > InputFiles, std::vector< ClangTidyError > *Errors, ProfileData *Profile)
Run a set of clang-tidy checks on a set of files.
Definition: ClangTidy.cpp:371
ClangTidyCheck(StringRef CheckName, ClangTidyContext *Context)
Initializes the check with CheckName and Context.
Definition: ClangTidy.h:109
Provides access to the ClangTidyCheck options via check-local names.
Definition: ClangTidy.h:39
OptionsView(StringRef CheckName, const ClangTidyOptions::OptionMap &CheckOptions)
Initializes the instance using CheckName + "." as a prefix.
Definition: ClangTidy.cpp:333
Contains displayed and ignored diagnostic counters for a ClangTidy run.
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
std::unique_ptr< clang::ASTConsumer > CreateASTConsumer(clang::CompilerInstance &Compiler, StringRef File)
Returns an ASTConsumer that runs the specified clang-tidy checks.
Definition: ClangTidy.cpp:217
static cl::opt< bool > Fix("fix", cl::desc("Apply suggested fixes. Without -fix-errors\n""clang-tidy will bail out if any compilation\n""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:138
Container for clang-tidy profiling data.
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
Definition: ClangTidy.cpp:323
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:149
const NamedDecl * Result
Definition: USRFinder.cpp:121