clang-tools 3.8.0

- Main Page
- Namespaces
- Classes
- Files

- File List
- File Members

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
13 #include "ClangTidyDiagnosticConsumer.h"
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.
149 virtual void storeOptions(ClangTidyOptions::OptionMap &Options) {}
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:
158 OptionsView Options;
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
167 class ClangTidyASTConsumerFactory {
168 public:
169 ClangTidyASTConsumerFactory(ClangTidyContext &Context);
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.
179 ClangTidyOptions::OptionMap getCheckOptions();
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.
199 ClangTidyOptions::OptionMap getCheckOptions(const ClangTidyOptions &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.
205 ClangTidyStats
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
Loc
SourceLocation Loc
'#' location in the include directive
Definition: IncludeOrderCheck.cpp:34
clang::tidy::ClangTidyCheck::registerMatchers
virtual void registerMatchers(ast_matchers::MatchFinder *Finder)
Override this to register ASTMatchers with Finder.
Definition: ClangTidy.h:134
clang::tidy::ClangTidyASTConsumerFactory::getCheckNames
std::vector< std::string > getCheckNames()
Get the list of enabled checks.
Definition: ClangTidy.cpp:268
clang::tidy::ClangTidyASTConsumerFactory::ClangTidyASTConsumerFactory
ClangTidyASTConsumerFactory(ClangTidyContext &Context)
Definition: ClangTidy.cpp:194
clang::tidy::ClangTidyCheck::getLangOpts
LangOptions getLangOpts() const
Returns the language options from the context.
Definition: ClangTidy.h:162
clang::tidy::GlobList
Read-only set of strings represented as a list of positive and negative globs.
Definition: ClangTidyDiagnosticConsumer.h:73
clang::tidy::ClangTidyCheck::getCurrentMainFile
StringRef getCurrentMainFile() const
Returns the main file name of the current translation unit.
Definition: ClangTidy.h:160
Finder
std::unique_ptr< ast_matchers::MatchFinder > Finder
Definition: ClangTidy.cpp:188
clang::tidy::ClangTidyASTConsumerFactory::getCheckOptions
ClangTidyOptions::OptionMap getCheckOptions()
Get the union of options from all checks.
Definition: ClangTidy.cpp:283
clang::tidy::ClangTidyASTConsumerFactory
Definition: ClangTidy.h:167
File
HeaderHandle File
Definition: PreprocessorTracker.cpp:526
clang::tidy::getCheckOptions
ClangTidyOptions::OptionMap getCheckOptions(const ClangTidyOptions &Options)
Returns the effective check-specific options.
Definition: ClangTidy.cpp:362
clang::tidy::ClangTidyOptions
Contains options for clang-tidy.
Definition: ClangTidyOptions.h:49
clang::tidy::ClangTidyCheck
Base class for all clang-tidy checks.
Definition: ClangTidy.h:102
clang::tidy::ClangTidyContext::getCurrentFile
StringRef getCurrentFile() const
Returns the main file name of the current translation unit.
Definition: ClangTidyDiagnosticConsumer.h:147
ClangTidyOptions.h
clang::tidy::ClangTidyCheck::Options
OptionsView Options
Definition: ClangTidy.h:158
clang::tidy::exportReplacements
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
clang::tidy::ClangTidyContext::getLangOpts
LangOptions getLangOpts() const
Gets the language options from the AST context.
Definition: ClangTidyDiagnosticConsumer.h:153
clang::tidy::handleErrors
void handleErrors(const std::vector< ClangTidyError > &Errors, bool Fix)
Displays the found Errors to the users.
Definition: ClangTidy.cpp:424
ClangTidyDiagnosticConsumer.h
clang::tidy::ClangTidyCheck::registerPPCallbacks
virtual void registerPPCallbacks(CompilerInstance &Compiler)
Override this to register PPCallbacks with Compiler.
Definition: ClangTidy.h:120
clang::tidy::OptionsView::store
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
clang::tidy::ClangTidyOptions::OptionMap
std::map< std::string, std::string > OptionMap
Definition: ClangTidyOptions.h:82
clang::tidy::getCheckNames
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
clang::tidy::runClangTidy
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
clang::tidy::ClangTidyCheck::ClangTidyCheck
ClangTidyCheck(StringRef CheckName, ClangTidyContext *Context)
Initializes the check with CheckName and Context.
Definition: ClangTidy.h:109
clang::tidy::OptionsView
Provides access to the ClangTidyCheck options via check-local names.
Definition: ClangTidy.h:39
clang::tidy::OptionsView::OptionsView
OptionsView(StringRef CheckName, const ClangTidyOptions::OptionMap &CheckOptions)
Initializes the instance using CheckName + "." as a prefix.
Definition: ClangTidy.cpp:333
clang::tidy::ClangTidyStats
Contains displayed and ignored diagnostic counters for a ClangTidy run.
Definition: ClangTidyDiagnosticConsumer.h:93
clang::tidy::ClangTidyContext
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
Definition: ClangTidyDiagnosticConsumer.h:124
clang::tidy::ClangTidyASTConsumerFactory::CreateASTConsumer
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
Fix
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))
clang::tidy::ClangTidyCheck::check
virtual void check(const ast_matchers::MatchFinder::MatchResult &Result)
ClangTidyChecks that register ASTMatchers should do the actual work in here.
Definition: ClangTidy.h:138
clang::tidy::ProfileData
Container for clang-tidy profiling data.
Definition: ClangTidyDiagnosticConsumer.h:111
clang::tidy::ClangTidyCheck::diag
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
Definition: ClangTidy.cpp:323
clang::tidy::ClangTidyCheck::storeOptions
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
Result
const NamedDecl * Result
Definition: USRFinder.cpp:121