blob: dc24f663ae35391a3e74ec0488430141447117d6 [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
196void IdentifierNamingCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
197 auto const toString = [](CaseType Type) {
198 switch (Type) {
199 case CT_AnyCase:
200 return "aNy_CasE";
201 case CT_LowerCase:
202 return "lower_case";
203 case CT_CamelBack:
204 return "camelBack";
205 case CT_UpperCase:
206 return "UPPER_CASE";
207 case CT_CamelCase:
208 return "CamelCase";
Kirill Bobyrev5d8f0712016-07-20 12:28:38 +0000209 case CT_CamelSnakeCase:
210 return "Camel_Snake_Case";
211 case CT_CamelSnakeBack:
212 return "camel_Snake_Back";
Alexander Kornienko76c28802015-08-19 11:15:36 +0000213 }
214
215 llvm_unreachable("Unknown Case Type");
216 };
217
218 for (size_t i = 0; i < SK_Count; ++i) {
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000219 if (NamingStyles[i]) {
220 if (NamingStyles[i]->Case) {
221 Options.store(Opts, (StyleNames[i] + "Case").str(),
222 toString(*NamingStyles[i]->Case));
223 }
224 Options.store(Opts, (StyleNames[i] + "Prefix").str(),
225 NamingStyles[i]->Prefix);
226 Options.store(Opts, (StyleNames[i] + "Suffix").str(),
227 NamingStyles[i]->Suffix);
228 }
Alexander Kornienko76c28802015-08-19 11:15:36 +0000229 }
230
231 Options.store(Opts, "IgnoreFailedSplit", IgnoreFailedSplit);
232}
233
234void IdentifierNamingCheck::registerMatchers(MatchFinder *Finder) {
Alexander Kornienko76c28802015-08-19 11:15:36 +0000235 Finder->addMatcher(namedDecl().bind("decl"), this);
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000236 Finder->addMatcher(usingDecl().bind("using"), this);
237 Finder->addMatcher(declRefExpr().bind("declRef"), this);
238 Finder->addMatcher(cxxConstructorDecl().bind("classRef"), this);
239 Finder->addMatcher(cxxDestructorDecl().bind("classRef"), this);
240 Finder->addMatcher(typeLoc().bind("typeLoc"), this);
241 Finder->addMatcher(nestedNameSpecifierLoc().bind("nestedNameLoc"), this);
Alexander Kornienko76c28802015-08-19 11:15:36 +0000242}
243
Alexander Kornienkobbc89dc2019-03-22 13:42:48 +0000244void IdentifierNamingCheck::registerPPCallbacks(
245 const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) {
246 ModuleExpanderPP->addPPCallbacks(
Jonas Devlieghere1c705d92019-08-14 23:52:23 +0000247 std::make_unique<IdentifierNamingCheckPPCallbacks>(ModuleExpanderPP,
Alexander Kornienkobbc89dc2019-03-22 13:42:48 +0000248 this));
Alexander Kornienko21503902016-06-17 09:25:24 +0000249}
250
Alexander Kornienko76c28802015-08-19 11:15:36 +0000251static bool matchesStyle(StringRef Name,
252 IdentifierNamingCheck::NamingStyle Style) {
253 static llvm::Regex Matchers[] = {
254 llvm::Regex("^.*$"),
255 llvm::Regex("^[a-z][a-z0-9_]*$"),
256 llvm::Regex("^[a-z][a-zA-Z0-9]*$"),
257 llvm::Regex("^[A-Z][A-Z0-9_]*$"),
258 llvm::Regex("^[A-Z][a-zA-Z0-9]*$"),
Kirill Bobyrev5d8f0712016-07-20 12:28:38 +0000259 llvm::Regex("^[A-Z]([a-z0-9]*(_[A-Z])?)*"),
260 llvm::Regex("^[a-z]([a-z0-9]*(_[A-Z])?)*"),
Alexander Kornienko76c28802015-08-19 11:15:36 +0000261 };
262
263 bool Matches = true;
264 if (Name.startswith(Style.Prefix))
265 Name = Name.drop_front(Style.Prefix.size());
266 else
267 Matches = false;
268
269 if (Name.endswith(Style.Suffix))
270 Name = Name.drop_back(Style.Suffix.size());
271 else
272 Matches = false;
273
Alexander Kornienkoeec01ad2017-04-26 16:39:11 +0000274 // Ensure the name doesn't have any extra underscores beyond those specified
275 // in the prefix and suffix.
276 if (Name.startswith("_") || Name.endswith("_"))
277 Matches = false;
278
Alexander Kornienko1c657f72017-03-22 12:50:05 +0000279 if (Style.Case && !Matchers[static_cast<size_t>(*Style.Case)].match(Name))
Alexander Kornienko76c28802015-08-19 11:15:36 +0000280 Matches = false;
281
282 return Matches;
283}
284
285static std::string fixupWithCase(StringRef Name,
286 IdentifierNamingCheck::CaseType Case) {
287 static llvm::Regex Splitter(
288 "([a-z0-9A-Z]*)(_+)|([A-Z]?[a-z0-9]+)([A-Z]|$)|([A-Z]+)([A-Z]|$)");
289
290 SmallVector<StringRef, 8> Substrs;
291 Name.split(Substrs, "_", -1, false);
292
293 SmallVector<StringRef, 8> Words;
294 for (auto Substr : Substrs) {
295 while (!Substr.empty()) {
296 SmallVector<StringRef, 8> Groups;
297 if (!Splitter.match(Substr, &Groups))
298 break;
299
300 if (Groups[2].size() > 0) {
301 Words.push_back(Groups[1]);
302 Substr = Substr.substr(Groups[0].size());
303 } else if (Groups[3].size() > 0) {
304 Words.push_back(Groups[3]);
305 Substr = Substr.substr(Groups[0].size() - Groups[4].size());
306 } else if (Groups[5].size() > 0) {
307 Words.push_back(Groups[5]);
308 Substr = Substr.substr(Groups[0].size() - Groups[6].size());
309 }
310 }
311 }
312
313 if (Words.empty())
314 return Name;
315
316 std::string Fixup;
317 switch (Case) {
318 case IdentifierNamingCheck::CT_AnyCase:
319 Fixup += Name;
320 break;
321
322 case IdentifierNamingCheck::CT_LowerCase:
323 for (auto const &Word : Words) {
324 if (&Word != &Words.front())
325 Fixup += "_";
326 Fixup += Word.lower();
327 }
328 break;
329
330 case IdentifierNamingCheck::CT_UpperCase:
331 for (auto const &Word : Words) {
332 if (&Word != &Words.front())
333 Fixup += "_";
334 Fixup += Word.upper();
335 }
336 break;
337
338 case IdentifierNamingCheck::CT_CamelCase:
339 for (auto const &Word : Words) {
340 Fixup += Word.substr(0, 1).upper();
341 Fixup += Word.substr(1).lower();
342 }
343 break;
344
345 case IdentifierNamingCheck::CT_CamelBack:
346 for (auto const &Word : Words) {
347 if (&Word == &Words.front()) {
348 Fixup += Word.lower();
349 } else {
350 Fixup += Word.substr(0, 1).upper();
351 Fixup += Word.substr(1).lower();
352 }
353 }
354 break;
Kirill Bobyrev5d8f0712016-07-20 12:28:38 +0000355
356 case IdentifierNamingCheck::CT_CamelSnakeCase:
357 for (auto const &Word : Words) {
358 if (&Word != &Words.front())
359 Fixup += "_";
360 Fixup += Word.substr(0, 1).upper();
361 Fixup += Word.substr(1).lower();
362 }
363 break;
364
365 case IdentifierNamingCheck::CT_CamelSnakeBack:
366 for (auto const &Word : Words) {
367 if (&Word != &Words.front()) {
368 Fixup += "_";
369 Fixup += Word.substr(0, 1).upper();
370 } else {
371 Fixup += Word.substr(0, 1).lower();
372 }
373 Fixup += Word.substr(1).lower();
374 }
375 break;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000376 }
377
378 return Fixup;
379}
380
Alexander Kornienko1c657f72017-03-22 12:50:05 +0000381static std::string
382fixupWithStyle(StringRef Name,
383 const IdentifierNamingCheck::NamingStyle &Style) {
Alexander Kornienkoeec01ad2017-04-26 16:39:11 +0000384 const std::string Fixed = fixupWithCase(
385 Name, Style.Case.getValueOr(IdentifierNamingCheck::CaseType::CT_AnyCase));
386 StringRef Mid = StringRef(Fixed).trim("_");
387 if (Mid.empty())
388 Mid = "_";
389 return (Style.Prefix + Mid + Style.Suffix).str();
Alexander Kornienko76c28802015-08-19 11:15:36 +0000390}
391
392static StyleKind findStyleKind(
393 const NamedDecl *D,
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000394 const std::vector<llvm::Optional<IdentifierNamingCheck::NamingStyle>>
395 &NamingStyles) {
Artem Belevichfcfcd502018-09-18 21:51:02 +0000396 assert(D && D->getIdentifier() && !D->getName().empty() && !D->isImplicit() &&
397 "Decl must be an explicit identifier with a name.");
398
Yan Zhang004b6c62018-04-23 00:15:15 +0000399 if (isa<ObjCIvarDecl>(D) && NamingStyles[SK_ObjcIvar])
400 return SK_ObjcIvar;
401
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000402 if (isa<TypedefDecl>(D) && NamingStyles[SK_Typedef])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000403 return SK_Typedef;
404
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000405 if (isa<TypeAliasDecl>(D) && NamingStyles[SK_TypeAlias])
Alexander Kornienko5ae76e02016-06-07 09:11:19 +0000406 return SK_TypeAlias;
407
Alexander Kornienko76c28802015-08-19 11:15:36 +0000408 if (const auto *Decl = dyn_cast<NamespaceDecl>(D)) {
409 if (Decl->isAnonymousNamespace())
410 return SK_Invalid;
411
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000412 if (Decl->isInline() && NamingStyles[SK_InlineNamespace])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000413 return SK_InlineNamespace;
414
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000415 if (NamingStyles[SK_Namespace])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000416 return SK_Namespace;
417 }
418
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000419 if (isa<EnumDecl>(D) && NamingStyles[SK_Enum])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000420 return SK_Enum;
421
422 if (isa<EnumConstantDecl>(D)) {
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000423 if (NamingStyles[SK_EnumConstant])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000424 return SK_EnumConstant;
425
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000426 if (NamingStyles[SK_Constant])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000427 return SK_Constant;
428
429 return SK_Invalid;
430 }
431
432 if (const auto *Decl = dyn_cast<CXXRecordDecl>(D)) {
433 if (Decl->isAnonymousStructOrUnion())
434 return SK_Invalid;
435
Jonathan Coe89f12c02016-11-03 13:52:09 +0000436 if (!Decl->getCanonicalDecl()->isThisDeclarationADefinition())
437 return SK_Invalid;
438
Alexander Kornienko76c28802015-08-19 11:15:36 +0000439 if (Decl->hasDefinition() && Decl->isAbstract() &&
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000440 NamingStyles[SK_AbstractClass])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000441 return SK_AbstractClass;
442
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000443 if (Decl->isStruct() && NamingStyles[SK_Struct])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000444 return SK_Struct;
445
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000446 if (Decl->isStruct() && NamingStyles[SK_Class])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000447 return SK_Class;
448
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000449 if (Decl->isClass() && NamingStyles[SK_Class])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000450 return SK_Class;
451
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000452 if (Decl->isClass() && NamingStyles[SK_Struct])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000453 return SK_Struct;
454
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000455 if (Decl->isUnion() && NamingStyles[SK_Union])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000456 return SK_Union;
457
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000458 if (Decl->isEnum() && NamingStyles[SK_Enum])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000459 return SK_Enum;
460
461 return SK_Invalid;
462 }
463
464 if (const auto *Decl = dyn_cast<FieldDecl>(D)) {
465 QualType Type = Decl->getType();
466
Alexander Kornienkoba874922017-12-11 19:02:26 +0000467 if (!Type.isNull() && Type.isConstQualified()) {
468 if (NamingStyles[SK_ConstantMember])
469 return SK_ConstantMember;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000470
Alexander Kornienkoba874922017-12-11 19:02:26 +0000471 if (NamingStyles[SK_Constant])
472 return SK_Constant;
473 }
Alexander Kornienko76c28802015-08-19 11:15:36 +0000474
Alexander Kornienko1c657f72017-03-22 12:50:05 +0000475 if (Decl->getAccess() == AS_private && NamingStyles[SK_PrivateMember])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000476 return SK_PrivateMember;
477
Alexander Kornienko1c657f72017-03-22 12:50:05 +0000478 if (Decl->getAccess() == AS_protected && NamingStyles[SK_ProtectedMember])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000479 return SK_ProtectedMember;
480
Alexander Kornienko1c657f72017-03-22 12:50:05 +0000481 if (Decl->getAccess() == AS_public && NamingStyles[SK_PublicMember])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000482 return SK_PublicMember;
483
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000484 if (NamingStyles[SK_Member])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000485 return SK_Member;
486
487 return SK_Invalid;
488 }
489
490 if (const auto *Decl = dyn_cast<ParmVarDecl>(D)) {
491 QualType Type = Decl->getType();
492
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000493 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprVariable])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000494 return SK_ConstexprVariable;
495
Alexander Kornienkoba874922017-12-11 19:02:26 +0000496 if (!Type.isNull() && Type.isConstQualified()) {
Jonas Tothc97671e2018-10-04 15:47:57 +0000497 if (Type.getTypePtr()->isAnyPointerType() && NamingStyles[SK_ConstantPointerParameter])
498 return SK_ConstantPointerParameter;
499
Alexander Kornienkoba874922017-12-11 19:02:26 +0000500 if (NamingStyles[SK_ConstantParameter])
501 return SK_ConstantParameter;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000502
Alexander Kornienkoba874922017-12-11 19:02:26 +0000503 if (NamingStyles[SK_Constant])
504 return SK_Constant;
505 }
Alexander Kornienko76c28802015-08-19 11:15:36 +0000506
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000507 if (Decl->isParameterPack() && NamingStyles[SK_ParameterPack])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000508 return SK_ParameterPack;
509
Jonas Tothc97671e2018-10-04 15:47:57 +0000510 if (!Type.isNull() && Type.getTypePtr()->isAnyPointerType() && NamingStyles[SK_PointerParameter])
511 return SK_PointerParameter;
512
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000513 if (NamingStyles[SK_Parameter])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000514 return SK_Parameter;
515
516 return SK_Invalid;
517 }
518
519 if (const auto *Decl = dyn_cast<VarDecl>(D)) {
520 QualType Type = Decl->getType();
521
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000522 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprVariable])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000523 return SK_ConstexprVariable;
524
Alexander Kornienkoba874922017-12-11 19:02:26 +0000525 if (!Type.isNull() && Type.isConstQualified()) {
526 if (Decl->isStaticDataMember() && NamingStyles[SK_ClassConstant])
527 return SK_ClassConstant;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000528
Jonas Tothc97671e2018-10-04 15:47:57 +0000529 if (Decl->isFileVarDecl() && Type.getTypePtr()->isAnyPointerType() && NamingStyles[SK_GlobalConstantPointer])
530 return SK_GlobalConstantPointer;
531
Alexander Kornienkoba874922017-12-11 19:02:26 +0000532 if (Decl->isFileVarDecl() && NamingStyles[SK_GlobalConstant])
533 return SK_GlobalConstant;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000534
Alexander Kornienkoba874922017-12-11 19:02:26 +0000535 if (Decl->isStaticLocal() && NamingStyles[SK_StaticConstant])
536 return SK_StaticConstant;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000537
Jonas Tothc97671e2018-10-04 15:47:57 +0000538 if (Decl->isLocalVarDecl() && Type.getTypePtr()->isAnyPointerType() && NamingStyles[SK_LocalConstantPointer])
539 return SK_LocalConstantPointer;
540
Alexander Kornienkoba874922017-12-11 19:02:26 +0000541 if (Decl->isLocalVarDecl() && NamingStyles[SK_LocalConstant])
542 return SK_LocalConstant;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000543
Alexander Kornienkoba874922017-12-11 19:02:26 +0000544 if (Decl->isFunctionOrMethodVarDecl() && NamingStyles[SK_LocalConstant])
545 return SK_LocalConstant;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000546
Alexander Kornienkoba874922017-12-11 19:02:26 +0000547 if (NamingStyles[SK_Constant])
548 return SK_Constant;
549 }
Alexander Kornienko76c28802015-08-19 11:15:36 +0000550
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000551 if (Decl->isStaticDataMember() && NamingStyles[SK_ClassMember])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000552 return SK_ClassMember;
553
Jonas Tothc97671e2018-10-04 15:47:57 +0000554 if (Decl->isFileVarDecl() && Type.getTypePtr()->isAnyPointerType() && NamingStyles[SK_GlobalPointer])
555 return SK_GlobalPointer;
556
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000557 if (Decl->isFileVarDecl() && NamingStyles[SK_GlobalVariable])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000558 return SK_GlobalVariable;
559
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000560 if (Decl->isStaticLocal() && NamingStyles[SK_StaticVariable])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000561 return SK_StaticVariable;
Jonas Tothc97671e2018-10-04 15:47:57 +0000562
563 if (Decl->isLocalVarDecl() && Type.getTypePtr()->isAnyPointerType() && NamingStyles[SK_LocalPointer])
564 return SK_LocalPointer;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000565
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000566 if (Decl->isLocalVarDecl() && NamingStyles[SK_LocalVariable])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000567 return SK_LocalVariable;
568
Alexander Kornienko1c657f72017-03-22 12:50:05 +0000569 if (Decl->isFunctionOrMethodVarDecl() && NamingStyles[SK_LocalVariable])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000570 return SK_LocalVariable;
571
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000572 if (NamingStyles[SK_Variable])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000573 return SK_Variable;
574
575 return SK_Invalid;
576 }
577
578 if (const auto *Decl = dyn_cast<CXXMethodDecl>(D)) {
579 if (Decl->isMain() || !Decl->isUserProvided() ||
Alexander Kornienko76c28802015-08-19 11:15:36 +0000580 Decl->size_overridden_methods() > 0)
581 return SK_Invalid;
582
Sam McCall9004c072019-08-28 12:08:57 +0000583 // If this method has the same name as any base method, this is likely
584 // necessary even if it's not an override. e.g. CRTP.
585 auto FindHidden = [&](const CXXBaseSpecifier *S, clang::CXXBasePath &P) {
586 return CXXRecordDecl::FindOrdinaryMember(S, P, Decl->getDeclName());
587 };
588 CXXBasePaths UnusedPaths;
589 if (Decl->getParent()->lookupInBases(FindHidden, UnusedPaths))
590 return SK_Invalid;
591
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000592 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprMethod])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000593 return SK_ConstexprMethod;
594
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000595 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprFunction])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000596 return SK_ConstexprFunction;
597
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000598 if (Decl->isStatic() && NamingStyles[SK_ClassMethod])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000599 return SK_ClassMethod;
600
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000601 if (Decl->isVirtual() && NamingStyles[SK_VirtualMethod])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000602 return SK_VirtualMethod;
603
Alexander Kornienko1c657f72017-03-22 12:50:05 +0000604 if (Decl->getAccess() == AS_private && NamingStyles[SK_PrivateMethod])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000605 return SK_PrivateMethod;
606
Alexander Kornienko1c657f72017-03-22 12:50:05 +0000607 if (Decl->getAccess() == AS_protected && NamingStyles[SK_ProtectedMethod])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000608 return SK_ProtectedMethod;
609
Alexander Kornienko1c657f72017-03-22 12:50:05 +0000610 if (Decl->getAccess() == AS_public && NamingStyles[SK_PublicMethod])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000611 return SK_PublicMethod;
612
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000613 if (NamingStyles[SK_Method])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000614 return SK_Method;
615
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000616 if (NamingStyles[SK_Function])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000617 return SK_Function;
618
619 return SK_Invalid;
620 }
621
622 if (const auto *Decl = dyn_cast<FunctionDecl>(D)) {
623 if (Decl->isMain())
624 return SK_Invalid;
625
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000626 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprFunction])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000627 return SK_ConstexprFunction;
628
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000629 if (Decl->isGlobal() && NamingStyles[SK_GlobalFunction])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000630 return SK_GlobalFunction;
631
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000632 if (NamingStyles[SK_Function])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000633 return SK_Function;
634 }
635
636 if (isa<TemplateTypeParmDecl>(D)) {
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000637 if (NamingStyles[SK_TypeTemplateParameter])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000638 return SK_TypeTemplateParameter;
639
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000640 if (NamingStyles[SK_TemplateParameter])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000641 return SK_TemplateParameter;
642
643 return SK_Invalid;
644 }
645
646 if (isa<NonTypeTemplateParmDecl>(D)) {
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000647 if (NamingStyles[SK_ValueTemplateParameter])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000648 return SK_ValueTemplateParameter;
649
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000650 if (NamingStyles[SK_TemplateParameter])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000651 return SK_TemplateParameter;
652
653 return SK_Invalid;
654 }
655
656 if (isa<TemplateTemplateParmDecl>(D)) {
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000657 if (NamingStyles[SK_TemplateTemplateParameter])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000658 return SK_TemplateTemplateParameter;
659
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000660 if (NamingStyles[SK_TemplateParameter])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000661 return SK_TemplateParameter;
662
663 return SK_Invalid;
664 }
665
666 return SK_Invalid;
667}
668
Alexander Kornienko3d777682015-09-28 08:59:12 +0000669static void addUsage(IdentifierNamingCheck::NamingCheckFailureMap &Failures,
Alexander Kornienko21503902016-06-17 09:25:24 +0000670 const IdentifierNamingCheck::NamingCheckId &Decl,
Jason Henline481e6aa2016-10-24 17:20:32 +0000671 SourceRange Range, SourceManager *SourceMgr = nullptr) {
Jonathan Coe2c8592a2016-01-26 18:55:55 +0000672 // Do nothing if the provided range is invalid.
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000673 if (Range.getBegin().isInvalid() || Range.getEnd().isInvalid())
674 return;
675
Jason Henline481e6aa2016-10-24 17:20:32 +0000676 // If we have a source manager, use it to convert to the spelling location for
677 // performing the fix. This is necessary because macros can map the same
678 // spelling location to different source locations, and we only want to fix
679 // the token once, before it is expanded by the macro.
680 SourceLocation FixLocation = Range.getBegin();
681 if (SourceMgr)
682 FixLocation = SourceMgr->getSpellingLoc(FixLocation);
683 if (FixLocation.isInvalid())
684 return;
685
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000686 // Try to insert the identifier location in the Usages map, and bail out if it
687 // is already in there
Alexander Kornienko3d777682015-09-28 08:59:12 +0000688 auto &Failure = Failures[Decl];
Jason Henline481e6aa2016-10-24 17:20:32 +0000689 if (!Failure.RawUsageLocs.insert(FixLocation.getRawEncoding()).second)
Alexander Kornienko3d777682015-09-28 08:59:12 +0000690 return;
691
Jason Henline481e6aa2016-10-24 17:20:32 +0000692 if (!Failure.ShouldFix)
693 return;
694
Roman Lebedev08701ec2018-10-26 13:09:27 +0000695 Failure.ShouldFix = utils::rangeCanBeFixed(Range, SourceMgr);
Alexander Kornienko3d777682015-09-28 08:59:12 +0000696}
697
Alexander Kornienko21503902016-06-17 09:25:24 +0000698/// Convenience method when the usage to be added is a NamedDecl
699static void addUsage(IdentifierNamingCheck::NamingCheckFailureMap &Failures,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000700 const NamedDecl *Decl, SourceRange Range,
701 SourceManager *SourceMgr = nullptr) {
Alexander Kornienkoba874922017-12-11 19:02:26 +0000702 return addUsage(Failures,
703 IdentifierNamingCheck::NamingCheckId(Decl->getLocation(),
704 Decl->getNameAsString()),
Jason Henline481e6aa2016-10-24 17:20:32 +0000705 Range, SourceMgr);
Alexander Kornienko21503902016-06-17 09:25:24 +0000706}
707
Alexander Kornienko76c28802015-08-19 11:15:36 +0000708void IdentifierNamingCheck::check(const MatchFinder::MatchResult &Result) {
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000709 if (const auto *Decl =
710 Result.Nodes.getNodeAs<CXXConstructorDecl>("classRef")) {
711 if (Decl->isImplicit())
712 return;
713
714 addUsage(NamingCheckFailures, Decl->getParent(),
Alexander Kornienko21503902016-06-17 09:25:24 +0000715 Decl->getNameInfo().getSourceRange());
Eric Fiselier732a3e02016-11-16 21:15:58 +0000716
717 for (const auto *Init : Decl->inits()) {
718 if (!Init->isWritten() || Init->isInClassMemberInitializer())
719 continue;
720 if (const auto *FD = Init->getAnyMember())
Alexander Kornienkoba874922017-12-11 19:02:26 +0000721 addUsage(NamingCheckFailures, FD,
722 SourceRange(Init->getMemberLocation()));
Eric Fiselier732a3e02016-11-16 21:15:58 +0000723 // Note: delegating constructors and base class initializers are handled
724 // via the "typeLoc" matcher.
725 }
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000726 return;
727 }
728
729 if (const auto *Decl =
730 Result.Nodes.getNodeAs<CXXDestructorDecl>("classRef")) {
731 if (Decl->isImplicit())
732 return;
733
734 SourceRange Range = Decl->getNameInfo().getSourceRange();
735 if (Range.getBegin().isInvalid())
736 return;
737 // The first token that will be found is the ~ (or the equivalent trigraph),
738 // we want instead to replace the next token, that will be the identifier.
739 Range.setBegin(CharSourceRange::getTokenRange(Range).getEnd());
740
Alexander Kornienko21503902016-06-17 09:25:24 +0000741 addUsage(NamingCheckFailures, Decl->getParent(), Range);
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000742 return;
743 }
744
745 if (const auto *Loc = Result.Nodes.getNodeAs<TypeLoc>("typeLoc")) {
746 NamedDecl *Decl = nullptr;
747 if (const auto &Ref = Loc->getAs<TagTypeLoc>()) {
748 Decl = Ref.getDecl();
749 } else if (const auto &Ref = Loc->getAs<InjectedClassNameTypeLoc>()) {
750 Decl = Ref.getDecl();
751 } else if (const auto &Ref = Loc->getAs<UnresolvedUsingTypeLoc>()) {
752 Decl = Ref.getDecl();
753 } else if (const auto &Ref = Loc->getAs<TemplateTypeParmTypeLoc>()) {
754 Decl = Ref.getDecl();
755 }
756
757 if (Decl) {
Alexander Kornienko21503902016-06-17 09:25:24 +0000758 addUsage(NamingCheckFailures, Decl, Loc->getSourceRange());
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000759 return;
760 }
761
762 if (const auto &Ref = Loc->getAs<TemplateSpecializationTypeLoc>()) {
763 const auto *Decl =
764 Ref.getTypePtr()->getTemplateName().getAsTemplateDecl();
765
766 SourceRange Range(Ref.getTemplateNameLoc(), Ref.getTemplateNameLoc());
767 if (const auto *ClassDecl = dyn_cast<TemplateDecl>(Decl)) {
Matthias Gehrea9e812b2016-07-09 20:09:28 +0000768 if (const auto *TemplDecl = ClassDecl->getTemplatedDecl())
769 addUsage(NamingCheckFailures, TemplDecl, Range);
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000770 return;
771 }
772 }
773
774 if (const auto &Ref =
775 Loc->getAs<DependentTemplateSpecializationTypeLoc>()) {
Matthias Gehrea9e812b2016-07-09 20:09:28 +0000776 if (const auto *Decl = Ref.getTypePtr()->getAsTagDecl())
777 addUsage(NamingCheckFailures, Decl, Loc->getSourceRange());
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000778 return;
779 }
780 }
781
782 if (const auto *Loc =
783 Result.Nodes.getNodeAs<NestedNameSpecifierLoc>("nestedNameLoc")) {
784 if (NestedNameSpecifier *Spec = Loc->getNestedNameSpecifier()) {
785 if (NamespaceDecl *Decl = Spec->getAsNamespace()) {
Alexander Kornienko21503902016-06-17 09:25:24 +0000786 addUsage(NamingCheckFailures, Decl, Loc->getLocalSourceRange());
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000787 return;
788 }
789 }
790 }
791
792 if (const auto *Decl = Result.Nodes.getNodeAs<UsingDecl>("using")) {
793 for (const auto &Shadow : Decl->shadows()) {
794 addUsage(NamingCheckFailures, Shadow->getTargetDecl(),
Alexander Kornienko21503902016-06-17 09:25:24 +0000795 Decl->getNameInfo().getSourceRange());
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000796 }
797 return;
798 }
799
800 if (const auto *DeclRef = Result.Nodes.getNodeAs<DeclRefExpr>("declRef")) {
Alexander Kornienko76c28802015-08-19 11:15:36 +0000801 SourceRange Range = DeclRef->getNameInfo().getSourceRange();
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000802 addUsage(NamingCheckFailures, DeclRef->getDecl(), Range,
803 Result.SourceManager);
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000804 return;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000805 }
806
807 if (const auto *Decl = Result.Nodes.getNodeAs<NamedDecl>("decl")) {
808 if (!Decl->getIdentifier() || Decl->getName().empty() || Decl->isImplicit())
809 return;
810
Alexander Kornienko21503902016-06-17 09:25:24 +0000811 // Fix type aliases in value declarations
812 if (const auto *Value = Result.Nodes.getNodeAs<ValueDecl>("decl")) {
Haojian Wu2255b312019-05-28 11:54:01 +0000813 if (const auto *TypePtr = Value->getType().getTypePtrOrNull()) {
814 if (const auto *Typedef = TypePtr->getAs<TypedefType>()) {
815 addUsage(NamingCheckFailures, Typedef->getDecl(),
816 Value->getSourceRange());
817 }
Alexander Kornienko21503902016-06-17 09:25:24 +0000818 }
819 }
820
821 // Fix type aliases in function declarations
822 if (const auto *Value = Result.Nodes.getNodeAs<FunctionDecl>("decl")) {
823 if (const auto *Typedef =
824 Value->getReturnType().getTypePtr()->getAs<TypedefType>()) {
825 addUsage(NamingCheckFailures, Typedef->getDecl(),
826 Value->getSourceRange());
827 }
828 for (unsigned i = 0; i < Value->getNumParams(); ++i) {
829 if (const auto *Typedef = Value->parameters()[i]
830 ->getType()
831 .getTypePtr()
832 ->getAs<TypedefType>()) {
833 addUsage(NamingCheckFailures, Typedef->getDecl(),
834 Value->getSourceRange());
835 }
836 }
837 }
838
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000839 // Ignore ClassTemplateSpecializationDecl which are creating duplicate
840 // replacements with CXXRecordDecl
841 if (isa<ClassTemplateSpecializationDecl>(Decl))
842 return;
843
Alexander Kornienko76c28802015-08-19 11:15:36 +0000844 StyleKind SK = findStyleKind(Decl, NamingStyles);
845 if (SK == SK_Invalid)
846 return;
847
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000848 if (!NamingStyles[SK])
849 return;
850
851 const NamingStyle &Style = *NamingStyles[SK];
Alexander Kornienko76c28802015-08-19 11:15:36 +0000852 StringRef Name = Decl->getName();
853 if (matchesStyle(Name, Style))
854 return;
855
856 std::string KindName = fixupWithCase(StyleNames[SK], CT_LowerCase);
857 std::replace(KindName.begin(), KindName.end(), '_', ' ');
858
859 std::string Fixup = fixupWithStyle(Name, Style);
860 if (StringRef(Fixup).equals(Name)) {
861 if (!IgnoreFailedSplit) {
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000862 LLVM_DEBUG(llvm::dbgs()
Stephen Kelly43465bf2018-08-09 22:42:26 +0000863 << Decl->getBeginLoc().printToString(*Result.SourceManager)
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000864 << llvm::format(": unable to split words for %s '%s'\n",
865 KindName.c_str(), Name.str().c_str()));
Alexander Kornienko76c28802015-08-19 11:15:36 +0000866 }
867 } else {
Alexander Kornienko21503902016-06-17 09:25:24 +0000868 NamingCheckFailure &Failure = NamingCheckFailures[NamingCheckId(
869 Decl->getLocation(), Decl->getNameAsString())];
Alexander Kornienko76c28802015-08-19 11:15:36 +0000870 SourceRange Range =
871 DeclarationNameInfo(Decl->getDeclName(), Decl->getLocation())
872 .getSourceRange();
873
874 Failure.Fixup = std::move(Fixup);
875 Failure.KindName = std::move(KindName);
Alexander Kornienko21503902016-06-17 09:25:24 +0000876 addUsage(NamingCheckFailures, Decl, Range);
Alexander Kornienko76c28802015-08-19 11:15:36 +0000877 }
878 }
879}
880
Alexander Kornienko21503902016-06-17 09:25:24 +0000881void IdentifierNamingCheck::checkMacro(SourceManager &SourceMgr,
882 const Token &MacroNameTok,
883 const MacroInfo *MI) {
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000884 if (!NamingStyles[SK_MacroDefinition])
885 return;
886
Alexander Kornienko21503902016-06-17 09:25:24 +0000887 StringRef Name = MacroNameTok.getIdentifierInfo()->getName();
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000888 const NamingStyle &Style = *NamingStyles[SK_MacroDefinition];
Alexander Kornienko21503902016-06-17 09:25:24 +0000889 if (matchesStyle(Name, Style))
890 return;
891
892 std::string KindName =
893 fixupWithCase(StyleNames[SK_MacroDefinition], CT_LowerCase);
894 std::replace(KindName.begin(), KindName.end(), '_', ' ');
895
896 std::string Fixup = fixupWithStyle(Name, Style);
897 if (StringRef(Fixup).equals(Name)) {
898 if (!IgnoreFailedSplit) {
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000899 LLVM_DEBUG(llvm::dbgs()
900 << MacroNameTok.getLocation().printToString(SourceMgr)
901 << llvm::format(": unable to split words for %s '%s'\n",
902 KindName.c_str(), Name.str().c_str()));
Alexander Kornienko21503902016-06-17 09:25:24 +0000903 }
904 } else {
905 NamingCheckId ID(MI->getDefinitionLoc(), Name);
906 NamingCheckFailure &Failure = NamingCheckFailures[ID];
907 SourceRange Range(MacroNameTok.getLocation(), MacroNameTok.getEndLoc());
908
909 Failure.Fixup = std::move(Fixup);
910 Failure.KindName = std::move(KindName);
911 addUsage(NamingCheckFailures, ID, Range);
912 }
913}
914
915void IdentifierNamingCheck::expandMacro(const Token &MacroNameTok,
916 const MacroInfo *MI) {
917 StringRef Name = MacroNameTok.getIdentifierInfo()->getName();
918 NamingCheckId ID(MI->getDefinitionLoc(), Name);
919
920 auto Failure = NamingCheckFailures.find(ID);
921 if (Failure == NamingCheckFailures.end())
922 return;
923
924 SourceRange Range(MacroNameTok.getLocation(), MacroNameTok.getEndLoc());
925 addUsage(NamingCheckFailures, ID, Range);
926}
927
Alexander Kornienko76c28802015-08-19 11:15:36 +0000928void IdentifierNamingCheck::onEndOfTranslationUnit() {
929 for (const auto &Pair : NamingCheckFailures) {
Alexander Kornienko21503902016-06-17 09:25:24 +0000930 const NamingCheckId &Decl = Pair.first;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000931 const NamingCheckFailure &Failure = Pair.second;
932
Alexander Kornienko3d777682015-09-28 08:59:12 +0000933 if (Failure.KindName.empty())
934 continue;
935
Alexander Kornienko76c28802015-08-19 11:15:36 +0000936 if (Failure.ShouldFix) {
Alexander Kornienko21503902016-06-17 09:25:24 +0000937 auto Diag = diag(Decl.first, "invalid case style for %0 '%1'")
938 << Failure.KindName << Decl.second;
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000939
Alexander Kornienko3d777682015-09-28 08:59:12 +0000940 for (const auto &Loc : Failure.RawUsageLocs) {
941 // We assume that the identifier name is made of one token only. This is
942 // always the case as we ignore usages in macros that could build
943 // identifier names by combining multiple tokens.
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000944 //
945 // For destructors, we alread take care of it by remembering the
946 // location of the start of the identifier and not the start of the
947 // tilde.
948 //
949 // Other multi-token identifiers, such as operators are not checked at
950 // all.
Alexander Kornienko76c28802015-08-19 11:15:36 +0000951 Diag << FixItHint::CreateReplacement(
Alexander Kornienko3d777682015-09-28 08:59:12 +0000952 SourceRange(SourceLocation::getFromRawEncoding(Loc)),
953 Failure.Fixup);
Alexander Kornienko76c28802015-08-19 11:15:36 +0000954 }
955 }
956 }
957}
958
959} // namespace readability
960} // namespace tidy
961} // namespace clang