clang-tools 20.0.0git
ClangTidyCheck.cpp
Go to the documentation of this file.
1//===--- ClangTidyCheck.cpp - 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#include "ClangTidyCheck.h"
10#include "llvm/ADT/StringRef.h"
11#include "llvm/ADT/StringSet.h"
12#include "llvm/Support/YAMLParser.h"
13#include <optional>
14#include <string>
15
16namespace clang::tidy {
17
19 : CheckName(CheckName), Context(Context),
20 Options(CheckName, Context->getOptions().CheckOptions, Context) {
21 assert(Context != nullptr);
22 assert(!CheckName.empty());
23}
24
25DiagnosticBuilder ClangTidyCheck::diag(SourceLocation Loc,
26 StringRef Description,
27 DiagnosticIDs::Level Level) {
28 return Context->diag(CheckName, Loc, Description, Level);
29}
30
31DiagnosticBuilder ClangTidyCheck::diag(StringRef Description,
32 DiagnosticIDs::Level Level) {
33 return Context->diag(CheckName, Description, Level);
34}
35
36DiagnosticBuilder
38 DiagnosticIDs::Level Level) const {
39 return Context->configurationDiag(Description, Level);
40}
41
42void ClangTidyCheck::run(const ast_matchers::MatchFinder::MatchResult &Result) {
43 // For historical reasons, checks don't implement the MatchFinder run()
44 // callback directly. We keep the run()/check() distinction to avoid interface
45 // churn, and to allow us to add cross-cutting logic in the future.
46 check(Result);
47}
48
50 StringRef CheckName, const ClangTidyOptions::OptionMap &CheckOptions,
51 ClangTidyContext *Context)
52 : NamePrefix((CheckName + ".").str()), CheckOptions(CheckOptions),
53 Context(Context) {}
54
55std::optional<StringRef>
56ClangTidyCheck::OptionsView::get(StringRef LocalName) const {
57 if (Context->getOptionsCollector())
58 Context->getOptionsCollector()->insert((NamePrefix + LocalName).str());
59 const auto &Iter = CheckOptions.find((NamePrefix + LocalName).str());
60 if (Iter != CheckOptions.end())
61 return StringRef(Iter->getValue().Value);
62 return std::nullopt;
63}
64
65static const llvm::StringSet<> DeprecatedGlobalOptions{
66 "StrictMode",
67 "IgnoreMacros",
68};
69
70static ClangTidyOptions::OptionMap::const_iterator
72 StringRef NamePrefix, StringRef LocalName,
73 ClangTidyContext *Context) {
74 llvm::StringSet<> *Collector = Context->getOptionsCollector();
75 if (Collector) {
76 Collector->insert((NamePrefix + LocalName).str());
77 Collector->insert(LocalName);
78 }
79 auto IterLocal = Options.find((NamePrefix + LocalName).str());
80 auto IterGlobal = Options.find(LocalName);
81 // FIXME: temporary solution for deprecation warnings, should be removed
82 // after 22.x. Warn configuration deps on deprecation global options.
83 if (IterLocal == Options.end() && IterGlobal != Options.end() &&
84 DeprecatedGlobalOptions.contains(LocalName))
85 Context->configurationDiag(
86 "global option '%0' is deprecated, please use '%1%0' instead.")
87 << LocalName << NamePrefix;
88 if (IterLocal == Options.end())
89 return IterGlobal;
90 if (IterGlobal == Options.end())
91 return IterLocal;
92 if (IterLocal->getValue().Priority >= IterGlobal->getValue().Priority)
93 return IterLocal;
94 return IterGlobal;
95}
96
97std::optional<StringRef>
99 auto Iter = findPriorityOption(CheckOptions, NamePrefix, LocalName, Context);
100 if (Iter != CheckOptions.end())
101 return StringRef(Iter->getValue().Value);
102 return std::nullopt;
103}
104
105static std::optional<bool> getAsBool(StringRef Value,
106 const llvm::Twine &LookupName) {
107
108 if (std::optional<bool> Parsed = llvm::yaml::parseBool(Value))
109 return Parsed;
110 // To maintain backwards compatability, we support parsing numbers as
111 // booleans, even though its not supported in YAML.
112 long long Number = 0;
113 if (!Value.getAsInteger(10, Number))
114 return Number != 0;
115 return std::nullopt;
116}
117
118template <>
119std::optional<bool>
120ClangTidyCheck::OptionsView::get<bool>(StringRef LocalName) const {
121 if (std::optional<StringRef> ValueOr = get(LocalName)) {
122 if (auto Result = getAsBool(*ValueOr, NamePrefix + LocalName))
123 return Result;
124 diagnoseBadBooleanOption(NamePrefix + LocalName, *ValueOr);
125 }
126 return std::nullopt;
127}
128
129template <>
130std::optional<bool>
131ClangTidyCheck::OptionsView::getLocalOrGlobal<bool>(StringRef LocalName) const {
132 auto Iter = findPriorityOption(CheckOptions, NamePrefix, LocalName, Context);
133 if (Iter != CheckOptions.end()) {
134 if (auto Result = getAsBool(Iter->getValue().Value, Iter->getKey()))
135 return Result;
136 diagnoseBadBooleanOption(Iter->getKey(), Iter->getValue().Value);
137 }
138 return std::nullopt;
139}
140
142 StringRef LocalName,
143 StringRef Value) const {
144 Options[(NamePrefix + LocalName).str()] = Value;
145}
146
147void ClangTidyCheck::OptionsView::storeInt(ClangTidyOptions::OptionMap &Options,
148 StringRef LocalName,
149 int64_t Value) const {
150 store(Options, LocalName, llvm::itostr(Value));
151}
152
153void ClangTidyCheck::OptionsView::storeUnsigned(
154 ClangTidyOptions::OptionMap &Options, StringRef LocalName,
155 uint64_t Value) const {
156 store(Options, LocalName, llvm::utostr(Value));
157}
158
159template <>
160void ClangTidyCheck::OptionsView::store<bool>(
161 ClangTidyOptions::OptionMap &Options, StringRef LocalName,
162 bool Value) const {
163 store(Options, LocalName, Value ? StringRef("true") : StringRef("false"));
164}
165
166std::optional<int64_t> ClangTidyCheck::OptionsView::getEnumInt(
167 StringRef LocalName, ArrayRef<NameAndValue> Mapping, bool CheckGlobal,
168 bool IgnoreCase) const {
169 if (!CheckGlobal && Context->getOptionsCollector())
170 Context->getOptionsCollector()->insert((NamePrefix + LocalName).str());
171 auto Iter = CheckGlobal ? findPriorityOption(CheckOptions, NamePrefix,
172 LocalName, Context)
173 : CheckOptions.find((NamePrefix + LocalName).str());
174 if (Iter == CheckOptions.end())
175 return std::nullopt;
176
177 StringRef Value = Iter->getValue().Value;
178 StringRef Closest;
179 unsigned EditDistance = 3;
180 for (const auto &NameAndEnum : Mapping) {
181 if (IgnoreCase) {
182 if (Value.equals_insensitive(NameAndEnum.second))
183 return NameAndEnum.first;
184 } else if (Value == NameAndEnum.second) {
185 return NameAndEnum.first;
186 } else if (Value.equals_insensitive(NameAndEnum.second)) {
187 Closest = NameAndEnum.second;
188 EditDistance = 0;
189 continue;
190 }
191 unsigned Distance =
192 Value.edit_distance(NameAndEnum.second, true, EditDistance);
193 if (Distance < EditDistance) {
194 EditDistance = Distance;
195 Closest = NameAndEnum.second;
196 }
197 }
198 if (EditDistance < 3)
199 diagnoseBadEnumOption(Iter->getKey(), Iter->getValue().Value, Closest);
200 else
201 diagnoseBadEnumOption(Iter->getKey(), Iter->getValue().Value);
202 return std::nullopt;
203}
204
205static constexpr llvm::StringLiteral ConfigWarning(
206 "invalid configuration value '%0' for option '%1'%select{|; expected a "
207 "bool|; expected an integer|; did you mean '%3'?}2");
208
209void ClangTidyCheck::OptionsView::diagnoseBadBooleanOption(
210 const Twine &Lookup, StringRef Unparsed) const {
211 SmallString<64> Buffer;
213 << Unparsed << Lookup.toStringRef(Buffer) << 1;
214}
215
216void ClangTidyCheck::OptionsView::diagnoseBadIntegerOption(
217 const Twine &Lookup, StringRef Unparsed) const {
218 SmallString<64> Buffer;
220 << Unparsed << Lookup.toStringRef(Buffer) << 2;
221}
222
223void ClangTidyCheck::OptionsView::diagnoseBadEnumOption(
224 const Twine &Lookup, StringRef Unparsed, StringRef Suggestion) const {
225 SmallString<64> Buffer;
226 auto Diag = Context->configurationDiag(ConfigWarning)
227 << Unparsed << Lookup.toStringRef(Buffer);
228 if (Suggestion.empty())
229 Diag << 0;
230 else
231 Diag << 3 << Suggestion;
232}
233
234StringRef ClangTidyCheck::OptionsView::get(StringRef LocalName,
235 StringRef Default) const {
236 return get(LocalName).value_or(Default);
237}
238
239StringRef
241 StringRef Default) const {
242 return getLocalOrGlobal(LocalName).value_or(Default);
243}
244} // namespace clang::tidy
SourceLocation Loc
unsigned Number
std::optional< StringRef > get(StringRef LocalName) const
Read a named option from the Context.
OptionsView(StringRef CheckName, const ClangTidyOptions::OptionMap &CheckOptions, ClangTidyContext *Context)
Initializes the instance using CheckName + "." as a prefix.
std::optional< StringRef > getLocalOrGlobal(StringRef LocalName) const
Read a named option from the Context.
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.
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
DiagnosticBuilder configurationDiag(StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning) const
Adds a diagnostic to report errors in the check's configuration.
ClangTidyCheck(StringRef CheckName, ClangTidyContext *Context)
Initializes the check with CheckName and Context.
virtual void check(const ast_matchers::MatchFinder::MatchResult &Result)
ClangTidyChecks that register ASTMatchers should do the actual work in here.
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
llvm::StringSet * getOptionsCollector() const
DiagnosticBuilder configurationDiag(StringRef Message, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Report any errors to do with reading the configuration using this method.
DiagnosticBuilder diag(StringRef CheckName, SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Report any errors detected using this method.
static constexpr llvm::StringLiteral ConfigWarning("invalid configuration value '%0' for option '%1'%select{|; expected a " "bool|; expected an integer|; did you mean '%3'?}2")
static ClangTidyOptions::OptionMap::const_iterator findPriorityOption(const ClangTidyOptions::OptionMap &Options, StringRef NamePrefix, StringRef LocalName, ClangTidyContext *Context)
static const llvm::StringSet DeprecatedGlobalOptions
static std::optional< bool > getAsBool(StringRef Value, const llvm::Twine &LookupName)
llvm::StringMap< ClangTidyValue > OptionMap