blob: 32289404132579dd32f7a5a38c94b09137e9c240 [file] [log] [blame]
Alexander Kornienko76c28802015-08-19 11:15:36 +00001//===--- IdentifierNamingCheck.cpp - clang-tidy ---------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Alexander Kornienko76c28802015-08-19 11:15:36 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "IdentifierNamingCheck.h"
10
Roman Lebedev08701ec2018-10-26 13:09:27 +000011#include "../utils/ASTUtils.h"
Alexander Kornienko76c28802015-08-19 11:15:36 +000012#include "clang/ASTMatchers/ASTMatchFinder.h"
Sam McCall9004c072019-08-28 12:08:57 +000013#include "clang/AST/CXXInheritance.h"
Alexander Kornienko21503902016-06-17 09:25:24 +000014#include "clang/Frontend/CompilerInstance.h"
15#include "clang/Lex/PPCallbacks.h"
16#include "clang/Lex/Preprocessor.h"
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000017#include "llvm/ADT/DenseMapInfo.h"
18#include "llvm/Support/Debug.h"
19#include "llvm/Support/Format.h"
Alexander Kornienko76c28802015-08-19 11:15:36 +000020
21#define DEBUG_TYPE "clang-tidy"
22
23using namespace clang::ast_matchers;
24
Alexander Kornienko21503902016-06-17 09:25:24 +000025namespace llvm {
26/// Specialisation of DenseMapInfo to allow NamingCheckId objects in DenseMaps
27template <>
28struct DenseMapInfo<
29 clang::tidy::readability::IdentifierNamingCheck::NamingCheckId> {
30 using NamingCheckId =
31 clang::tidy::readability::IdentifierNamingCheck::NamingCheckId;
32
33 static inline NamingCheckId getEmptyKey() {
34 return NamingCheckId(
35 clang::SourceLocation::getFromRawEncoding(static_cast<unsigned>(-1)),
36 "EMPTY");
37 }
38
39 static inline NamingCheckId getTombstoneKey() {
40 return NamingCheckId(
41 clang::SourceLocation::getFromRawEncoding(static_cast<unsigned>(-2)),
42 "TOMBSTONE");
43 }
44
45 static unsigned getHashValue(NamingCheckId Val) {
46 assert(Val != getEmptyKey() && "Cannot hash the empty key!");
47 assert(Val != getTombstoneKey() && "Cannot hash the tombstone key!");
48
49 std::hash<NamingCheckId::second_type> SecondHash;
50 return Val.first.getRawEncoding() + SecondHash(Val.second);
51 }
52
Benjamin Kramera079cdb2017-03-21 21:34:58 +000053 static bool isEqual(const NamingCheckId &LHS, const NamingCheckId &RHS) {
Alexander Kornienko21503902016-06-17 09:25:24 +000054 if (RHS == getEmptyKey())
55 return LHS == getEmptyKey();
56 if (RHS == getTombstoneKey())
57 return LHS == getTombstoneKey();
58 return LHS == RHS;
59 }
60};
61} // namespace llvm
62
Alexander Kornienko76c28802015-08-19 11:15:36 +000063namespace clang {
64namespace tidy {
65namespace readability {
66
Alexander Kornienko3d777682015-09-28 08:59:12 +000067// clang-format off
Alexander Kornienko76c28802015-08-19 11:15:36 +000068#define NAMING_KEYS(m) \
69 m(Namespace) \
70 m(InlineNamespace) \
71 m(EnumConstant) \
72 m(ConstexprVariable) \
73 m(ConstantMember) \
74 m(PrivateMember) \
75 m(ProtectedMember) \
76 m(PublicMember) \
77 m(Member) \
78 m(ClassConstant) \
79 m(ClassMember) \
80 m(GlobalConstant) \
Jonas Tothc97671e2018-10-04 15:47:57 +000081 m(GlobalConstantPointer) \
82 m(GlobalPointer) \
Alexander Kornienko76c28802015-08-19 11:15:36 +000083 m(GlobalVariable) \
84 m(LocalConstant) \
Jonas Tothc97671e2018-10-04 15:47:57 +000085 m(LocalConstantPointer) \
86 m(LocalPointer) \
Alexander Kornienko76c28802015-08-19 11:15:36 +000087 m(LocalVariable) \
88 m(StaticConstant) \
89 m(StaticVariable) \
90 m(Constant) \
91 m(Variable) \
92 m(ConstantParameter) \
93 m(ParameterPack) \
94 m(Parameter) \
Jonas Tothc97671e2018-10-04 15:47:57 +000095 m(PointerParameter) \
96 m(ConstantPointerParameter) \
Alexander Kornienko76c28802015-08-19 11:15:36 +000097 m(AbstractClass) \
98 m(Struct) \
99 m(Class) \
100 m(Union) \
101 m(Enum) \
102 m(GlobalFunction) \
103 m(ConstexprFunction) \
104 m(Function) \
105 m(ConstexprMethod) \
106 m(VirtualMethod) \
107 m(ClassMethod) \
108 m(PrivateMethod) \
109 m(ProtectedMethod) \
110 m(PublicMethod) \
111 m(Method) \
112 m(Typedef) \
113 m(TypeTemplateParameter) \
114 m(ValueTemplateParameter) \
115 m(TemplateTemplateParameter) \
116 m(TemplateParameter) \
Alexander Kornienko5ae76e02016-06-07 09:11:19 +0000117 m(TypeAlias) \
Alexander Kornienko21503902016-06-17 09:25:24 +0000118 m(MacroDefinition) \
Yan Zhang004b6c62018-04-23 00:15:15 +0000119 m(ObjcIvar) \
Alexander Kornienko76c28802015-08-19 11:15:36 +0000120
121enum StyleKind {
122#define ENUMERATE(v) SK_ ## v,
123 NAMING_KEYS(ENUMERATE)
124#undef ENUMERATE
125 SK_Count,
126 SK_Invalid
127};
128
129static StringRef const StyleNames[] = {
130#define STRINGIZE(v) #v,
131 NAMING_KEYS(STRINGIZE)
132#undef STRINGIZE
133};
134
135#undef NAMING_KEYS
Alexander Kornienko3d777682015-09-28 08:59:12 +0000136// clang-format on
Alexander Kornienko76c28802015-08-19 11:15:36 +0000137
Alexander Kornienko21503902016-06-17 09:25:24 +0000138namespace {
139/// Callback supplies macros to IdentifierNamingCheck::checkMacro
140class IdentifierNamingCheckPPCallbacks : public PPCallbacks {
141public:
142 IdentifierNamingCheckPPCallbacks(Preprocessor *PP,
143 IdentifierNamingCheck *Check)
144 : PP(PP), Check(Check) {}
145
146 /// MacroDefined calls checkMacro for macros in the main file
147 void MacroDefined(const Token &MacroNameTok,
148 const MacroDirective *MD) override {
149 Check->checkMacro(PP->getSourceManager(), MacroNameTok, MD->getMacroInfo());
150 }
151
152 /// MacroExpands calls expandMacro for macros in the main file
153 void MacroExpands(const Token &MacroNameTok, const MacroDefinition &MD,
154 SourceRange /*Range*/,
155 const MacroArgs * /*Args*/) override {
156 Check->expandMacro(MacroNameTok, MD.getMacroInfo());
157 }
158
159private:
160 Preprocessor *PP;
161 IdentifierNamingCheck *Check;
162};
163} // namespace
164
Alexander Kornienko76c28802015-08-19 11:15:36 +0000165IdentifierNamingCheck::IdentifierNamingCheck(StringRef Name,
166 ClangTidyContext *Context)
167 : ClangTidyCheck(Name, Context) {
168 auto const fromString = [](StringRef Str) {
Alexander Kornienko1c657f72017-03-22 12:50:05 +0000169 return llvm::StringSwitch<llvm::Optional<CaseType>>(Str)
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000170 .Case("aNy_CasE", CT_AnyCase)
Alexander Kornienko76c28802015-08-19 11:15:36 +0000171 .Case("lower_case", CT_LowerCase)
172 .Case("UPPER_CASE", CT_UpperCase)
173 .Case("camelBack", CT_CamelBack)
174 .Case("CamelCase", CT_CamelCase)
Kirill Bobyrev5d8f0712016-07-20 12:28:38 +0000175 .Case("Camel_Snake_Case", CT_CamelSnakeCase)
176 .Case("camel_Snake_Back", CT_CamelSnakeBack)
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000177 .Default(llvm::None);
Alexander Kornienko76c28802015-08-19 11:15:36 +0000178 };
179
180 for (auto const &Name : StyleNames) {
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000181 auto const caseOptional =
182 fromString(Options.get((Name + "Case").str(), ""));
183 auto prefix = Options.get((Name + "Prefix").str(), "");
184 auto postfix = Options.get((Name + "Suffix").str(), "");
185
186 if (caseOptional || !prefix.empty() || !postfix.empty()) {
187 NamingStyles.push_back(NamingStyle(caseOptional, prefix, postfix));
188 } else {
189 NamingStyles.push_back(llvm::None);
190 }
Alexander Kornienko76c28802015-08-19 11:15:36 +0000191 }
192
193 IgnoreFailedSplit = Options.get("IgnoreFailedSplit", 0);
194}
195
Dmitri Gribenko5338ffc2019-09-26 13:47:29 +0000196IdentifierNamingCheck::~IdentifierNamingCheck() = default;
197
Alexander Kornienko76c28802015-08-19 11:15:36 +0000198void IdentifierNamingCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
199 auto const toString = [](CaseType Type) {
200 switch (Type) {
201 case CT_AnyCase:
202 return "aNy_CasE";
203 case CT_LowerCase:
204 return "lower_case";
205 case CT_CamelBack:
206 return "camelBack";
207 case CT_UpperCase:
208 return "UPPER_CASE";
209 case CT_CamelCase:
210 return "CamelCase";
Kirill Bobyrev5d8f0712016-07-20 12:28:38 +0000211 case CT_CamelSnakeCase:
212 return "Camel_Snake_Case";
213 case CT_CamelSnakeBack:
214 return "camel_Snake_Back";
Alexander Kornienko76c28802015-08-19 11:15:36 +0000215 }
216
217 llvm_unreachable("Unknown Case Type");
218 };
219
220 for (size_t i = 0; i < SK_Count; ++i) {
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000221 if (NamingStyles[i]) {
222 if (NamingStyles[i]->Case) {
223 Options.store(Opts, (StyleNames[i] + "Case").str(),
224 toString(*NamingStyles[i]->Case));
225 }
226 Options.store(Opts, (StyleNames[i] + "Prefix").str(),
227 NamingStyles[i]->Prefix);
228 Options.store(Opts, (StyleNames[i] + "Suffix").str(),
229 NamingStyles[i]->Suffix);
230 }
Alexander Kornienko76c28802015-08-19 11:15:36 +0000231 }
232
233 Options.store(Opts, "IgnoreFailedSplit", IgnoreFailedSplit);
234}
235
236void IdentifierNamingCheck::registerMatchers(MatchFinder *Finder) {
Alexander Kornienko76c28802015-08-19 11:15:36 +0000237 Finder->addMatcher(namedDecl().bind("decl"), this);
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000238 Finder->addMatcher(usingDecl().bind("using"), this);
239 Finder->addMatcher(declRefExpr().bind("declRef"), this);
240 Finder->addMatcher(cxxConstructorDecl().bind("classRef"), this);
241 Finder->addMatcher(cxxDestructorDecl().bind("classRef"), this);
242 Finder->addMatcher(typeLoc().bind("typeLoc"), this);
243 Finder->addMatcher(nestedNameSpecifierLoc().bind("nestedNameLoc"), this);
Alexander Kornienko76c28802015-08-19 11:15:36 +0000244}
245
Alexander Kornienkobbc89dc2019-03-22 13:42:48 +0000246void IdentifierNamingCheck::registerPPCallbacks(
247 const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) {
248 ModuleExpanderPP->addPPCallbacks(
Jonas Devlieghere1c705d92019-08-14 23:52:23 +0000249 std::make_unique<IdentifierNamingCheckPPCallbacks>(ModuleExpanderPP,
Alexander Kornienkobbc89dc2019-03-22 13:42:48 +0000250 this));
Alexander Kornienko21503902016-06-17 09:25:24 +0000251}
252
Alexander Kornienko76c28802015-08-19 11:15:36 +0000253static bool matchesStyle(StringRef Name,
254 IdentifierNamingCheck::NamingStyle Style) {
255 static llvm::Regex Matchers[] = {
256 llvm::Regex("^.*$"),
257 llvm::Regex("^[a-z][a-z0-9_]*$"),
258 llvm::Regex("^[a-z][a-zA-Z0-9]*$"),
259 llvm::Regex("^[A-Z][A-Z0-9_]*$"),
260 llvm::Regex("^[A-Z][a-zA-Z0-9]*$"),
Kirill Bobyrev5d8f0712016-07-20 12:28:38 +0000261 llvm::Regex("^[A-Z]([a-z0-9]*(_[A-Z])?)*"),
262 llvm::Regex("^[a-z]([a-z0-9]*(_[A-Z])?)*"),
Alexander Kornienko76c28802015-08-19 11:15:36 +0000263 };
264
265 bool Matches = true;
266 if (Name.startswith(Style.Prefix))
267 Name = Name.drop_front(Style.Prefix.size());
268 else
269 Matches = false;
270
271 if (Name.endswith(Style.Suffix))
272 Name = Name.drop_back(Style.Suffix.size());
273 else
274 Matches = false;
275
Alexander Kornienkoeec01ad2017-04-26 16:39:11 +0000276 // Ensure the name doesn't have any extra underscores beyond those specified
277 // in the prefix and suffix.
278 if (Name.startswith("_") || Name.endswith("_"))
279 Matches = false;
280
Alexander Kornienko1c657f72017-03-22 12:50:05 +0000281 if (Style.Case && !Matchers[static_cast<size_t>(*Style.Case)].match(Name))
Alexander Kornienko76c28802015-08-19 11:15:36 +0000282 Matches = false;
283
284 return Matches;
285}
286
287static std::string fixupWithCase(StringRef Name,
288 IdentifierNamingCheck::CaseType Case) {
289 static llvm::Regex Splitter(
290 "([a-z0-9A-Z]*)(_+)|([A-Z]?[a-z0-9]+)([A-Z]|$)|([A-Z]+)([A-Z]|$)");
291
292 SmallVector<StringRef, 8> Substrs;
293 Name.split(Substrs, "_", -1, false);
294
295 SmallVector<StringRef, 8> Words;
296 for (auto Substr : Substrs) {
297 while (!Substr.empty()) {
298 SmallVector<StringRef, 8> Groups;
299 if (!Splitter.match(Substr, &Groups))
300 break;
301
302 if (Groups[2].size() > 0) {
303 Words.push_back(Groups[1]);
304 Substr = Substr.substr(Groups[0].size());
305 } else if (Groups[3].size() > 0) {
306 Words.push_back(Groups[3]);
307 Substr = Substr.substr(Groups[0].size() - Groups[4].size());
308 } else if (Groups[5].size() > 0) {
309 Words.push_back(Groups[5]);
310 Substr = Substr.substr(Groups[0].size() - Groups[6].size());
311 }
312 }
313 }
314
315 if (Words.empty())
316 return Name;
317
318 std::string Fixup;
319 switch (Case) {
320 case IdentifierNamingCheck::CT_AnyCase:
321 Fixup += Name;
322 break;
323
324 case IdentifierNamingCheck::CT_LowerCase:
325 for (auto const &Word : Words) {
326 if (&Word != &Words.front())
327 Fixup += "_";
328 Fixup += Word.lower();
329 }
330 break;
331
332 case IdentifierNamingCheck::CT_UpperCase:
333 for (auto const &Word : Words) {
334 if (&Word != &Words.front())
335 Fixup += "_";
336 Fixup += Word.upper();
337 }
338 break;
339
340 case IdentifierNamingCheck::CT_CamelCase:
341 for (auto const &Word : Words) {
342 Fixup += Word.substr(0, 1).upper();
343 Fixup += Word.substr(1).lower();
344 }
345 break;
346
347 case IdentifierNamingCheck::CT_CamelBack:
348 for (auto const &Word : Words) {
349 if (&Word == &Words.front()) {
350 Fixup += Word.lower();
351 } else {
352 Fixup += Word.substr(0, 1).upper();
353 Fixup += Word.substr(1).lower();
354 }
355 }
356 break;
Kirill Bobyrev5d8f0712016-07-20 12:28:38 +0000357
358 case IdentifierNamingCheck::CT_CamelSnakeCase:
359 for (auto const &Word : Words) {
360 if (&Word != &Words.front())
361 Fixup += "_";
362 Fixup += Word.substr(0, 1).upper();
363 Fixup += Word.substr(1).lower();
364 }
365 break;
366
367 case IdentifierNamingCheck::CT_CamelSnakeBack:
368 for (auto const &Word : Words) {
369 if (&Word != &Words.front()) {
370 Fixup += "_";
371 Fixup += Word.substr(0, 1).upper();
372 } else {
373 Fixup += Word.substr(0, 1).lower();
374 }
375 Fixup += Word.substr(1).lower();
376 }
377 break;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000378 }
379
380 return Fixup;
381}
382
Alexander Kornienko1c657f72017-03-22 12:50:05 +0000383static std::string
384fixupWithStyle(StringRef Name,
385 const IdentifierNamingCheck::NamingStyle &Style) {
Alexander Kornienkoeec01ad2017-04-26 16:39:11 +0000386 const std::string Fixed = fixupWithCase(
387 Name, Style.Case.getValueOr(IdentifierNamingCheck::CaseType::CT_AnyCase));
388 StringRef Mid = StringRef(Fixed).trim("_");
389 if (Mid.empty())
390 Mid = "_";
391 return (Style.Prefix + Mid + Style.Suffix).str();
Alexander Kornienko76c28802015-08-19 11:15:36 +0000392}
393
394static StyleKind findStyleKind(
395 const NamedDecl *D,
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000396 const std::vector<llvm::Optional<IdentifierNamingCheck::NamingStyle>>
397 &NamingStyles) {
Artem Belevichfcfcd502018-09-18 21:51:02 +0000398 assert(D && D->getIdentifier() && !D->getName().empty() && !D->isImplicit() &&
399 "Decl must be an explicit identifier with a name.");
400
Yan Zhang004b6c62018-04-23 00:15:15 +0000401 if (isa<ObjCIvarDecl>(D) && NamingStyles[SK_ObjcIvar])
402 return SK_ObjcIvar;
403
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000404 if (isa<TypedefDecl>(D) && NamingStyles[SK_Typedef])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000405 return SK_Typedef;
406
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000407 if (isa<TypeAliasDecl>(D) && NamingStyles[SK_TypeAlias])
Alexander Kornienko5ae76e02016-06-07 09:11:19 +0000408 return SK_TypeAlias;
409
Alexander Kornienko76c28802015-08-19 11:15:36 +0000410 if (const auto *Decl = dyn_cast<NamespaceDecl>(D)) {
411 if (Decl->isAnonymousNamespace())
412 return SK_Invalid;
413
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000414 if (Decl->isInline() && NamingStyles[SK_InlineNamespace])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000415 return SK_InlineNamespace;
416
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000417 if (NamingStyles[SK_Namespace])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000418 return SK_Namespace;
419 }
420
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000421 if (isa<EnumDecl>(D) && NamingStyles[SK_Enum])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000422 return SK_Enum;
423
424 if (isa<EnumConstantDecl>(D)) {
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000425 if (NamingStyles[SK_EnumConstant])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000426 return SK_EnumConstant;
427
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000428 if (NamingStyles[SK_Constant])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000429 return SK_Constant;
430
431 return SK_Invalid;
432 }
433
434 if (const auto *Decl = dyn_cast<CXXRecordDecl>(D)) {
435 if (Decl->isAnonymousStructOrUnion())
436 return SK_Invalid;
437
Jonathan Coe89f12c02016-11-03 13:52:09 +0000438 if (!Decl->getCanonicalDecl()->isThisDeclarationADefinition())
439 return SK_Invalid;
440
Alexander Kornienko76c28802015-08-19 11:15:36 +0000441 if (Decl->hasDefinition() && Decl->isAbstract() &&
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000442 NamingStyles[SK_AbstractClass])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000443 return SK_AbstractClass;
444
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000445 if (Decl->isStruct() && NamingStyles[SK_Struct])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000446 return SK_Struct;
447
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000448 if (Decl->isStruct() && NamingStyles[SK_Class])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000449 return SK_Class;
450
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000451 if (Decl->isClass() && NamingStyles[SK_Class])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000452 return SK_Class;
453
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000454 if (Decl->isClass() && NamingStyles[SK_Struct])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000455 return SK_Struct;
456
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000457 if (Decl->isUnion() && NamingStyles[SK_Union])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000458 return SK_Union;
459
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000460 if (Decl->isEnum() && NamingStyles[SK_Enum])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000461 return SK_Enum;
462
463 return SK_Invalid;
464 }
465
466 if (const auto *Decl = dyn_cast<FieldDecl>(D)) {
467 QualType Type = Decl->getType();
468
Alexander Kornienkoba874922017-12-11 19:02:26 +0000469 if (!Type.isNull() && Type.isConstQualified()) {
470 if (NamingStyles[SK_ConstantMember])
471 return SK_ConstantMember;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000472
Alexander Kornienkoba874922017-12-11 19:02:26 +0000473 if (NamingStyles[SK_Constant])
474 return SK_Constant;
475 }
Alexander Kornienko76c28802015-08-19 11:15:36 +0000476
Alexander Kornienko1c657f72017-03-22 12:50:05 +0000477 if (Decl->getAccess() == AS_private && NamingStyles[SK_PrivateMember])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000478 return SK_PrivateMember;
479
Alexander Kornienko1c657f72017-03-22 12:50:05 +0000480 if (Decl->getAccess() == AS_protected && NamingStyles[SK_ProtectedMember])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000481 return SK_ProtectedMember;
482
Alexander Kornienko1c657f72017-03-22 12:50:05 +0000483 if (Decl->getAccess() == AS_public && NamingStyles[SK_PublicMember])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000484 return SK_PublicMember;
485
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000486 if (NamingStyles[SK_Member])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000487 return SK_Member;
488
489 return SK_Invalid;
490 }
491
492 if (const auto *Decl = dyn_cast<ParmVarDecl>(D)) {
493 QualType Type = Decl->getType();
494
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000495 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprVariable])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000496 return SK_ConstexprVariable;
497
Alexander Kornienkoba874922017-12-11 19:02:26 +0000498 if (!Type.isNull() && Type.isConstQualified()) {
Jonas Tothc97671e2018-10-04 15:47:57 +0000499 if (Type.getTypePtr()->isAnyPointerType() && NamingStyles[SK_ConstantPointerParameter])
500 return SK_ConstantPointerParameter;
501
Alexander Kornienkoba874922017-12-11 19:02:26 +0000502 if (NamingStyles[SK_ConstantParameter])
503 return SK_ConstantParameter;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000504
Alexander Kornienkoba874922017-12-11 19:02:26 +0000505 if (NamingStyles[SK_Constant])
506 return SK_Constant;
507 }
Alexander Kornienko76c28802015-08-19 11:15:36 +0000508
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000509 if (Decl->isParameterPack() && NamingStyles[SK_ParameterPack])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000510 return SK_ParameterPack;
511
Jonas Tothc97671e2018-10-04 15:47:57 +0000512 if (!Type.isNull() && Type.getTypePtr()->isAnyPointerType() && NamingStyles[SK_PointerParameter])
513 return SK_PointerParameter;
514
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000515 if (NamingStyles[SK_Parameter])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000516 return SK_Parameter;
517
518 return SK_Invalid;
519 }
520
521 if (const auto *Decl = dyn_cast<VarDecl>(D)) {
522 QualType Type = Decl->getType();
523
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000524 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprVariable])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000525 return SK_ConstexprVariable;
526
Alexander Kornienkoba874922017-12-11 19:02:26 +0000527 if (!Type.isNull() && Type.isConstQualified()) {
528 if (Decl->isStaticDataMember() && NamingStyles[SK_ClassConstant])
529 return SK_ClassConstant;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000530
Jonas Tothc97671e2018-10-04 15:47:57 +0000531 if (Decl->isFileVarDecl() && Type.getTypePtr()->isAnyPointerType() && NamingStyles[SK_GlobalConstantPointer])
532 return SK_GlobalConstantPointer;
533
Alexander Kornienkoba874922017-12-11 19:02:26 +0000534 if (Decl->isFileVarDecl() && NamingStyles[SK_GlobalConstant])
535 return SK_GlobalConstant;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000536
Alexander Kornienkoba874922017-12-11 19:02:26 +0000537 if (Decl->isStaticLocal() && NamingStyles[SK_StaticConstant])
538 return SK_StaticConstant;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000539
Jonas Tothc97671e2018-10-04 15:47:57 +0000540 if (Decl->isLocalVarDecl() && Type.getTypePtr()->isAnyPointerType() && NamingStyles[SK_LocalConstantPointer])
541 return SK_LocalConstantPointer;
542
Alexander Kornienkoba874922017-12-11 19:02:26 +0000543 if (Decl->isLocalVarDecl() && NamingStyles[SK_LocalConstant])
544 return SK_LocalConstant;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000545
Alexander Kornienkoba874922017-12-11 19:02:26 +0000546 if (Decl->isFunctionOrMethodVarDecl() && NamingStyles[SK_LocalConstant])
547 return SK_LocalConstant;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000548
Alexander Kornienkoba874922017-12-11 19:02:26 +0000549 if (NamingStyles[SK_Constant])
550 return SK_Constant;
551 }
Alexander Kornienko76c28802015-08-19 11:15:36 +0000552
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000553 if (Decl->isStaticDataMember() && NamingStyles[SK_ClassMember])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000554 return SK_ClassMember;
555
Jonas Tothc97671e2018-10-04 15:47:57 +0000556 if (Decl->isFileVarDecl() && Type.getTypePtr()->isAnyPointerType() && NamingStyles[SK_GlobalPointer])
557 return SK_GlobalPointer;
558
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000559 if (Decl->isFileVarDecl() && NamingStyles[SK_GlobalVariable])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000560 return SK_GlobalVariable;
561
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000562 if (Decl->isStaticLocal() && NamingStyles[SK_StaticVariable])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000563 return SK_StaticVariable;
Jonas Tothc97671e2018-10-04 15:47:57 +0000564
565 if (Decl->isLocalVarDecl() && Type.getTypePtr()->isAnyPointerType() && NamingStyles[SK_LocalPointer])
566 return SK_LocalPointer;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000567
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000568 if (Decl->isLocalVarDecl() && NamingStyles[SK_LocalVariable])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000569 return SK_LocalVariable;
570
Alexander Kornienko1c657f72017-03-22 12:50:05 +0000571 if (Decl->isFunctionOrMethodVarDecl() && NamingStyles[SK_LocalVariable])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000572 return SK_LocalVariable;
573
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000574 if (NamingStyles[SK_Variable])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000575 return SK_Variable;
576
577 return SK_Invalid;
578 }
579
580 if (const auto *Decl = dyn_cast<CXXMethodDecl>(D)) {
581 if (Decl->isMain() || !Decl->isUserProvided() ||
Alexander Kornienko76c28802015-08-19 11:15:36 +0000582 Decl->size_overridden_methods() > 0)
583 return SK_Invalid;
584
Sam McCall9004c072019-08-28 12:08:57 +0000585 // If this method has the same name as any base method, this is likely
586 // necessary even if it's not an override. e.g. CRTP.
587 auto FindHidden = [&](const CXXBaseSpecifier *S, clang::CXXBasePath &P) {
588 return CXXRecordDecl::FindOrdinaryMember(S, P, Decl->getDeclName());
589 };
590 CXXBasePaths UnusedPaths;
591 if (Decl->getParent()->lookupInBases(FindHidden, UnusedPaths))
592 return SK_Invalid;
593
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000594 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprMethod])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000595 return SK_ConstexprMethod;
596
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000597 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprFunction])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000598 return SK_ConstexprFunction;
599
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000600 if (Decl->isStatic() && NamingStyles[SK_ClassMethod])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000601 return SK_ClassMethod;
602
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000603 if (Decl->isVirtual() && NamingStyles[SK_VirtualMethod])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000604 return SK_VirtualMethod;
605
Alexander Kornienko1c657f72017-03-22 12:50:05 +0000606 if (Decl->getAccess() == AS_private && NamingStyles[SK_PrivateMethod])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000607 return SK_PrivateMethod;
608
Alexander Kornienko1c657f72017-03-22 12:50:05 +0000609 if (Decl->getAccess() == AS_protected && NamingStyles[SK_ProtectedMethod])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000610 return SK_ProtectedMethod;
611
Alexander Kornienko1c657f72017-03-22 12:50:05 +0000612 if (Decl->getAccess() == AS_public && NamingStyles[SK_PublicMethod])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000613 return SK_PublicMethod;
614
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000615 if (NamingStyles[SK_Method])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000616 return SK_Method;
617
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000618 if (NamingStyles[SK_Function])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000619 return SK_Function;
620
621 return SK_Invalid;
622 }
623
624 if (const auto *Decl = dyn_cast<FunctionDecl>(D)) {
625 if (Decl->isMain())
626 return SK_Invalid;
627
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000628 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprFunction])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000629 return SK_ConstexprFunction;
630
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000631 if (Decl->isGlobal() && NamingStyles[SK_GlobalFunction])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000632 return SK_GlobalFunction;
633
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000634 if (NamingStyles[SK_Function])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000635 return SK_Function;
636 }
637
638 if (isa<TemplateTypeParmDecl>(D)) {
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000639 if (NamingStyles[SK_TypeTemplateParameter])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000640 return SK_TypeTemplateParameter;
641
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000642 if (NamingStyles[SK_TemplateParameter])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000643 return SK_TemplateParameter;
644
645 return SK_Invalid;
646 }
647
648 if (isa<NonTypeTemplateParmDecl>(D)) {
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000649 if (NamingStyles[SK_ValueTemplateParameter])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000650 return SK_ValueTemplateParameter;
651
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000652 if (NamingStyles[SK_TemplateParameter])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000653 return SK_TemplateParameter;
654
655 return SK_Invalid;
656 }
657
658 if (isa<TemplateTemplateParmDecl>(D)) {
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000659 if (NamingStyles[SK_TemplateTemplateParameter])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000660 return SK_TemplateTemplateParameter;
661
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000662 if (NamingStyles[SK_TemplateParameter])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000663 return SK_TemplateParameter;
664
665 return SK_Invalid;
666 }
667
668 return SK_Invalid;
669}
670
Alexander Kornienko3d777682015-09-28 08:59:12 +0000671static void addUsage(IdentifierNamingCheck::NamingCheckFailureMap &Failures,
Alexander Kornienko21503902016-06-17 09:25:24 +0000672 const IdentifierNamingCheck::NamingCheckId &Decl,
Jason Henline481e6aa2016-10-24 17:20:32 +0000673 SourceRange Range, SourceManager *SourceMgr = nullptr) {
Jonathan Coe2c8592a2016-01-26 18:55:55 +0000674 // Do nothing if the provided range is invalid.
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000675 if (Range.getBegin().isInvalid() || Range.getEnd().isInvalid())
676 return;
677
Jason Henline481e6aa2016-10-24 17:20:32 +0000678 // If we have a source manager, use it to convert to the spelling location for
679 // performing the fix. This is necessary because macros can map the same
680 // spelling location to different source locations, and we only want to fix
681 // the token once, before it is expanded by the macro.
682 SourceLocation FixLocation = Range.getBegin();
683 if (SourceMgr)
684 FixLocation = SourceMgr->getSpellingLoc(FixLocation);
685 if (FixLocation.isInvalid())
686 return;
687
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000688 // Try to insert the identifier location in the Usages map, and bail out if it
689 // is already in there
Alexander Kornienko3d777682015-09-28 08:59:12 +0000690 auto &Failure = Failures[Decl];
Jason Henline481e6aa2016-10-24 17:20:32 +0000691 if (!Failure.RawUsageLocs.insert(FixLocation.getRawEncoding()).second)
Alexander Kornienko3d777682015-09-28 08:59:12 +0000692 return;
693
Jason Henline481e6aa2016-10-24 17:20:32 +0000694 if (!Failure.ShouldFix)
695 return;
696
Roman Lebedev08701ec2018-10-26 13:09:27 +0000697 Failure.ShouldFix = utils::rangeCanBeFixed(Range, SourceMgr);
Alexander Kornienko3d777682015-09-28 08:59:12 +0000698}
699
Alexander Kornienko21503902016-06-17 09:25:24 +0000700/// Convenience method when the usage to be added is a NamedDecl
701static void addUsage(IdentifierNamingCheck::NamingCheckFailureMap &Failures,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000702 const NamedDecl *Decl, SourceRange Range,
703 SourceManager *SourceMgr = nullptr) {
Alexander Kornienkoba874922017-12-11 19:02:26 +0000704 return addUsage(Failures,
705 IdentifierNamingCheck::NamingCheckId(Decl->getLocation(),
706 Decl->getNameAsString()),
Jason Henline481e6aa2016-10-24 17:20:32 +0000707 Range, SourceMgr);
Alexander Kornienko21503902016-06-17 09:25:24 +0000708}
709
Alexander Kornienko76c28802015-08-19 11:15:36 +0000710void IdentifierNamingCheck::check(const MatchFinder::MatchResult &Result) {
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000711 if (const auto *Decl =
712 Result.Nodes.getNodeAs<CXXConstructorDecl>("classRef")) {
713 if (Decl->isImplicit())
714 return;
715
716 addUsage(NamingCheckFailures, Decl->getParent(),
Alexander Kornienko21503902016-06-17 09:25:24 +0000717 Decl->getNameInfo().getSourceRange());
Eric Fiselier732a3e02016-11-16 21:15:58 +0000718
719 for (const auto *Init : Decl->inits()) {
720 if (!Init->isWritten() || Init->isInClassMemberInitializer())
721 continue;
722 if (const auto *FD = Init->getAnyMember())
Alexander Kornienkoba874922017-12-11 19:02:26 +0000723 addUsage(NamingCheckFailures, FD,
724 SourceRange(Init->getMemberLocation()));
Eric Fiselier732a3e02016-11-16 21:15:58 +0000725 // Note: delegating constructors and base class initializers are handled
726 // via the "typeLoc" matcher.
727 }
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000728 return;
729 }
730
731 if (const auto *Decl =
732 Result.Nodes.getNodeAs<CXXDestructorDecl>("classRef")) {
733 if (Decl->isImplicit())
734 return;
735
736 SourceRange Range = Decl->getNameInfo().getSourceRange();
737 if (Range.getBegin().isInvalid())
738 return;
739 // The first token that will be found is the ~ (or the equivalent trigraph),
740 // we want instead to replace the next token, that will be the identifier.
741 Range.setBegin(CharSourceRange::getTokenRange(Range).getEnd());
742
Alexander Kornienko21503902016-06-17 09:25:24 +0000743 addUsage(NamingCheckFailures, Decl->getParent(), Range);
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000744 return;
745 }
746
747 if (const auto *Loc = Result.Nodes.getNodeAs<TypeLoc>("typeLoc")) {
748 NamedDecl *Decl = nullptr;
749 if (const auto &Ref = Loc->getAs<TagTypeLoc>()) {
750 Decl = Ref.getDecl();
751 } else if (const auto &Ref = Loc->getAs<InjectedClassNameTypeLoc>()) {
752 Decl = Ref.getDecl();
753 } else if (const auto &Ref = Loc->getAs<UnresolvedUsingTypeLoc>()) {
754 Decl = Ref.getDecl();
755 } else if (const auto &Ref = Loc->getAs<TemplateTypeParmTypeLoc>()) {
756 Decl = Ref.getDecl();
757 }
758
759 if (Decl) {
Alexander Kornienko21503902016-06-17 09:25:24 +0000760 addUsage(NamingCheckFailures, Decl, Loc->getSourceRange());
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000761 return;
762 }
763
764 if (const auto &Ref = Loc->getAs<TemplateSpecializationTypeLoc>()) {
765 const auto *Decl =
766 Ref.getTypePtr()->getTemplateName().getAsTemplateDecl();
767
768 SourceRange Range(Ref.getTemplateNameLoc(), Ref.getTemplateNameLoc());
769 if (const auto *ClassDecl = dyn_cast<TemplateDecl>(Decl)) {
Matthias Gehrea9e812b2016-07-09 20:09:28 +0000770 if (const auto *TemplDecl = ClassDecl->getTemplatedDecl())
771 addUsage(NamingCheckFailures, TemplDecl, Range);
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000772 return;
773 }
774 }
775
776 if (const auto &Ref =
777 Loc->getAs<DependentTemplateSpecializationTypeLoc>()) {
Matthias Gehrea9e812b2016-07-09 20:09:28 +0000778 if (const auto *Decl = Ref.getTypePtr()->getAsTagDecl())
779 addUsage(NamingCheckFailures, Decl, Loc->getSourceRange());
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000780 return;
781 }
782 }
783
784 if (const auto *Loc =
785 Result.Nodes.getNodeAs<NestedNameSpecifierLoc>("nestedNameLoc")) {
786 if (NestedNameSpecifier *Spec = Loc->getNestedNameSpecifier()) {
787 if (NamespaceDecl *Decl = Spec->getAsNamespace()) {
Alexander Kornienko21503902016-06-17 09:25:24 +0000788 addUsage(NamingCheckFailures, Decl, Loc->getLocalSourceRange());
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000789 return;
790 }
791 }
792 }
793
794 if (const auto *Decl = Result.Nodes.getNodeAs<UsingDecl>("using")) {
795 for (const auto &Shadow : Decl->shadows()) {
796 addUsage(NamingCheckFailures, Shadow->getTargetDecl(),
Alexander Kornienko21503902016-06-17 09:25:24 +0000797 Decl->getNameInfo().getSourceRange());
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000798 }
799 return;
800 }
801
802 if (const auto *DeclRef = Result.Nodes.getNodeAs<DeclRefExpr>("declRef")) {
Alexander Kornienko76c28802015-08-19 11:15:36 +0000803 SourceRange Range = DeclRef->getNameInfo().getSourceRange();
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000804 addUsage(NamingCheckFailures, DeclRef->getDecl(), Range,
805 Result.SourceManager);
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000806 return;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000807 }
808
809 if (const auto *Decl = Result.Nodes.getNodeAs<NamedDecl>("decl")) {
810 if (!Decl->getIdentifier() || Decl->getName().empty() || Decl->isImplicit())
811 return;
812
Alexander Kornienko21503902016-06-17 09:25:24 +0000813 // Fix type aliases in value declarations
814 if (const auto *Value = Result.Nodes.getNodeAs<ValueDecl>("decl")) {
Haojian Wu2255b312019-05-28 11:54:01 +0000815 if (const auto *TypePtr = Value->getType().getTypePtrOrNull()) {
816 if (const auto *Typedef = TypePtr->getAs<TypedefType>()) {
817 addUsage(NamingCheckFailures, Typedef->getDecl(),
818 Value->getSourceRange());
819 }
Alexander Kornienko21503902016-06-17 09:25:24 +0000820 }
821 }
822
823 // Fix type aliases in function declarations
824 if (const auto *Value = Result.Nodes.getNodeAs<FunctionDecl>("decl")) {
825 if (const auto *Typedef =
826 Value->getReturnType().getTypePtr()->getAs<TypedefType>()) {
827 addUsage(NamingCheckFailures, Typedef->getDecl(),
828 Value->getSourceRange());
829 }
830 for (unsigned i = 0; i < Value->getNumParams(); ++i) {
831 if (const auto *Typedef = Value->parameters()[i]
832 ->getType()
833 .getTypePtr()
834 ->getAs<TypedefType>()) {
835 addUsage(NamingCheckFailures, Typedef->getDecl(),
836 Value->getSourceRange());
837 }
838 }
839 }
840
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000841 // Ignore ClassTemplateSpecializationDecl which are creating duplicate
842 // replacements with CXXRecordDecl
843 if (isa<ClassTemplateSpecializationDecl>(Decl))
844 return;
845
Alexander Kornienko76c28802015-08-19 11:15:36 +0000846 StyleKind SK = findStyleKind(Decl, NamingStyles);
847 if (SK == SK_Invalid)
848 return;
849
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000850 if (!NamingStyles[SK])
851 return;
852
853 const NamingStyle &Style = *NamingStyles[SK];
Alexander Kornienko76c28802015-08-19 11:15:36 +0000854 StringRef Name = Decl->getName();
855 if (matchesStyle(Name, Style))
856 return;
857
858 std::string KindName = fixupWithCase(StyleNames[SK], CT_LowerCase);
859 std::replace(KindName.begin(), KindName.end(), '_', ' ');
860
861 std::string Fixup = fixupWithStyle(Name, Style);
862 if (StringRef(Fixup).equals(Name)) {
863 if (!IgnoreFailedSplit) {
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000864 LLVM_DEBUG(llvm::dbgs()
Stephen Kelly43465bf2018-08-09 22:42:26 +0000865 << Decl->getBeginLoc().printToString(*Result.SourceManager)
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000866 << llvm::format(": unable to split words for %s '%s'\n",
867 KindName.c_str(), Name.str().c_str()));
Alexander Kornienko76c28802015-08-19 11:15:36 +0000868 }
869 } else {
Alexander Kornienko21503902016-06-17 09:25:24 +0000870 NamingCheckFailure &Failure = NamingCheckFailures[NamingCheckId(
871 Decl->getLocation(), Decl->getNameAsString())];
Alexander Kornienko76c28802015-08-19 11:15:36 +0000872 SourceRange Range =
873 DeclarationNameInfo(Decl->getDeclName(), Decl->getLocation())
874 .getSourceRange();
875
876 Failure.Fixup = std::move(Fixup);
877 Failure.KindName = std::move(KindName);
Alexander Kornienko21503902016-06-17 09:25:24 +0000878 addUsage(NamingCheckFailures, Decl, Range);
Alexander Kornienko76c28802015-08-19 11:15:36 +0000879 }
880 }
881}
882
Alexander Kornienko21503902016-06-17 09:25:24 +0000883void IdentifierNamingCheck::checkMacro(SourceManager &SourceMgr,
884 const Token &MacroNameTok,
885 const MacroInfo *MI) {
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000886 if (!NamingStyles[SK_MacroDefinition])
887 return;
888
Alexander Kornienko21503902016-06-17 09:25:24 +0000889 StringRef Name = MacroNameTok.getIdentifierInfo()->getName();
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000890 const NamingStyle &Style = *NamingStyles[SK_MacroDefinition];
Alexander Kornienko21503902016-06-17 09:25:24 +0000891 if (matchesStyle(Name, Style))
892 return;
893
894 std::string KindName =
895 fixupWithCase(StyleNames[SK_MacroDefinition], CT_LowerCase);
896 std::replace(KindName.begin(), KindName.end(), '_', ' ');
897
898 std::string Fixup = fixupWithStyle(Name, Style);
899 if (StringRef(Fixup).equals(Name)) {
900 if (!IgnoreFailedSplit) {
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000901 LLVM_DEBUG(llvm::dbgs()
902 << MacroNameTok.getLocation().printToString(SourceMgr)
903 << llvm::format(": unable to split words for %s '%s'\n",
904 KindName.c_str(), Name.str().c_str()));
Alexander Kornienko21503902016-06-17 09:25:24 +0000905 }
906 } else {
907 NamingCheckId ID(MI->getDefinitionLoc(), Name);
908 NamingCheckFailure &Failure = NamingCheckFailures[ID];
909 SourceRange Range(MacroNameTok.getLocation(), MacroNameTok.getEndLoc());
910
911 Failure.Fixup = std::move(Fixup);
912 Failure.KindName = std::move(KindName);
913 addUsage(NamingCheckFailures, ID, Range);
914 }
915}
916
917void IdentifierNamingCheck::expandMacro(const Token &MacroNameTok,
918 const MacroInfo *MI) {
919 StringRef Name = MacroNameTok.getIdentifierInfo()->getName();
920 NamingCheckId ID(MI->getDefinitionLoc(), Name);
921
922 auto Failure = NamingCheckFailures.find(ID);
923 if (Failure == NamingCheckFailures.end())
924 return;
925
926 SourceRange Range(MacroNameTok.getLocation(), MacroNameTok.getEndLoc());
927 addUsage(NamingCheckFailures, ID, Range);
928}
929
Alexander Kornienko76c28802015-08-19 11:15:36 +0000930void IdentifierNamingCheck::onEndOfTranslationUnit() {
931 for (const auto &Pair : NamingCheckFailures) {
Alexander Kornienko21503902016-06-17 09:25:24 +0000932 const NamingCheckId &Decl = Pair.first;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000933 const NamingCheckFailure &Failure = Pair.second;
934
Alexander Kornienko3d777682015-09-28 08:59:12 +0000935 if (Failure.KindName.empty())
936 continue;
937
Alexander Kornienko76c28802015-08-19 11:15:36 +0000938 if (Failure.ShouldFix) {
Alexander Kornienko21503902016-06-17 09:25:24 +0000939 auto Diag = diag(Decl.first, "invalid case style for %0 '%1'")
940 << Failure.KindName << Decl.second;
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000941
Alexander Kornienko3d777682015-09-28 08:59:12 +0000942 for (const auto &Loc : Failure.RawUsageLocs) {
943 // We assume that the identifier name is made of one token only. This is
944 // always the case as we ignore usages in macros that could build
945 // identifier names by combining multiple tokens.
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000946 //
947 // For destructors, we alread take care of it by remembering the
948 // location of the start of the identifier and not the start of the
949 // tilde.
950 //
951 // Other multi-token identifiers, such as operators are not checked at
952 // all.
Alexander Kornienko76c28802015-08-19 11:15:36 +0000953 Diag << FixItHint::CreateReplacement(
Alexander Kornienko3d777682015-09-28 08:59:12 +0000954 SourceRange(SourceLocation::getFromRawEncoding(Loc)),
955 Failure.Fixup);
Alexander Kornienko76c28802015-08-19 11:15:36 +0000956 }
957 }
958 }
959}
960
961} // namespace readability
962} // namespace tidy
963} // namespace clang