blob: 2795cabdd0aeb0cce1d953b5f7926e4b2a9862fd [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"
Alexander Kornienko21503902016-06-17 09:25:24 +000013#include "clang/Frontend/CompilerInstance.h"
14#include "clang/Lex/PPCallbacks.h"
15#include "clang/Lex/Preprocessor.h"
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000016#include "llvm/ADT/DenseMapInfo.h"
17#include "llvm/Support/Debug.h"
18#include "llvm/Support/Format.h"
Alexander Kornienko76c28802015-08-19 11:15:36 +000019
20#define DEBUG_TYPE "clang-tidy"
21
22using namespace clang::ast_matchers;
23
Alexander Kornienko21503902016-06-17 09:25:24 +000024namespace llvm {
25/// Specialisation of DenseMapInfo to allow NamingCheckId objects in DenseMaps
26template <>
27struct DenseMapInfo<
28 clang::tidy::readability::IdentifierNamingCheck::NamingCheckId> {
29 using NamingCheckId =
30 clang::tidy::readability::IdentifierNamingCheck::NamingCheckId;
31
32 static inline NamingCheckId getEmptyKey() {
33 return NamingCheckId(
34 clang::SourceLocation::getFromRawEncoding(static_cast<unsigned>(-1)),
35 "EMPTY");
36 }
37
38 static inline NamingCheckId getTombstoneKey() {
39 return NamingCheckId(
40 clang::SourceLocation::getFromRawEncoding(static_cast<unsigned>(-2)),
41 "TOMBSTONE");
42 }
43
44 static unsigned getHashValue(NamingCheckId Val) {
45 assert(Val != getEmptyKey() && "Cannot hash the empty key!");
46 assert(Val != getTombstoneKey() && "Cannot hash the tombstone key!");
47
48 std::hash<NamingCheckId::second_type> SecondHash;
49 return Val.first.getRawEncoding() + SecondHash(Val.second);
50 }
51
Benjamin Kramera079cdb2017-03-21 21:34:58 +000052 static bool isEqual(const NamingCheckId &LHS, const NamingCheckId &RHS) {
Alexander Kornienko21503902016-06-17 09:25:24 +000053 if (RHS == getEmptyKey())
54 return LHS == getEmptyKey();
55 if (RHS == getTombstoneKey())
56 return LHS == getTombstoneKey();
57 return LHS == RHS;
58 }
59};
60} // namespace llvm
61
Alexander Kornienko76c28802015-08-19 11:15:36 +000062namespace clang {
63namespace tidy {
64namespace readability {
65
Alexander Kornienko3d777682015-09-28 08:59:12 +000066// clang-format off
Alexander Kornienko76c28802015-08-19 11:15:36 +000067#define NAMING_KEYS(m) \
68 m(Namespace) \
69 m(InlineNamespace) \
70 m(EnumConstant) \
71 m(ConstexprVariable) \
72 m(ConstantMember) \
73 m(PrivateMember) \
74 m(ProtectedMember) \
75 m(PublicMember) \
76 m(Member) \
77 m(ClassConstant) \
78 m(ClassMember) \
79 m(GlobalConstant) \
Jonas Tothc97671e2018-10-04 15:47:57 +000080 m(GlobalConstantPointer) \
81 m(GlobalPointer) \
Alexander Kornienko76c28802015-08-19 11:15:36 +000082 m(GlobalVariable) \
83 m(LocalConstant) \
Jonas Tothc97671e2018-10-04 15:47:57 +000084 m(LocalConstantPointer) \
85 m(LocalPointer) \
Alexander Kornienko76c28802015-08-19 11:15:36 +000086 m(LocalVariable) \
87 m(StaticConstant) \
88 m(StaticVariable) \
89 m(Constant) \
90 m(Variable) \
91 m(ConstantParameter) \
92 m(ParameterPack) \
93 m(Parameter) \
Jonas Tothc97671e2018-10-04 15:47:57 +000094 m(PointerParameter) \
95 m(ConstantPointerParameter) \
Alexander Kornienko76c28802015-08-19 11:15:36 +000096 m(AbstractClass) \
97 m(Struct) \
98 m(Class) \
99 m(Union) \
100 m(Enum) \
101 m(GlobalFunction) \
102 m(ConstexprFunction) \
103 m(Function) \
104 m(ConstexprMethod) \
105 m(VirtualMethod) \
106 m(ClassMethod) \
107 m(PrivateMethod) \
108 m(ProtectedMethod) \
109 m(PublicMethod) \
110 m(Method) \
111 m(Typedef) \
112 m(TypeTemplateParameter) \
113 m(ValueTemplateParameter) \
114 m(TemplateTemplateParameter) \
115 m(TemplateParameter) \
Alexander Kornienko5ae76e02016-06-07 09:11:19 +0000116 m(TypeAlias) \
Alexander Kornienko21503902016-06-17 09:25:24 +0000117 m(MacroDefinition) \
Yan Zhang004b6c62018-04-23 00:15:15 +0000118 m(ObjcIvar) \
Alexander Kornienko76c28802015-08-19 11:15:36 +0000119
120enum StyleKind {
121#define ENUMERATE(v) SK_ ## v,
122 NAMING_KEYS(ENUMERATE)
123#undef ENUMERATE
124 SK_Count,
125 SK_Invalid
126};
127
128static StringRef const StyleNames[] = {
129#define STRINGIZE(v) #v,
130 NAMING_KEYS(STRINGIZE)
131#undef STRINGIZE
132};
133
134#undef NAMING_KEYS
Alexander Kornienko3d777682015-09-28 08:59:12 +0000135// clang-format on
Alexander Kornienko76c28802015-08-19 11:15:36 +0000136
Alexander Kornienko21503902016-06-17 09:25:24 +0000137namespace {
138/// Callback supplies macros to IdentifierNamingCheck::checkMacro
139class IdentifierNamingCheckPPCallbacks : public PPCallbacks {
140public:
141 IdentifierNamingCheckPPCallbacks(Preprocessor *PP,
142 IdentifierNamingCheck *Check)
143 : PP(PP), Check(Check) {}
144
145 /// MacroDefined calls checkMacro for macros in the main file
146 void MacroDefined(const Token &MacroNameTok,
147 const MacroDirective *MD) override {
148 Check->checkMacro(PP->getSourceManager(), MacroNameTok, MD->getMacroInfo());
149 }
150
151 /// MacroExpands calls expandMacro for macros in the main file
152 void MacroExpands(const Token &MacroNameTok, const MacroDefinition &MD,
153 SourceRange /*Range*/,
154 const MacroArgs * /*Args*/) override {
155 Check->expandMacro(MacroNameTok, MD.getMacroInfo());
156 }
157
158private:
159 Preprocessor *PP;
160 IdentifierNamingCheck *Check;
161};
162} // namespace
163
Alexander Kornienko76c28802015-08-19 11:15:36 +0000164IdentifierNamingCheck::IdentifierNamingCheck(StringRef Name,
165 ClangTidyContext *Context)
166 : ClangTidyCheck(Name, Context) {
167 auto const fromString = [](StringRef Str) {
Alexander Kornienko1c657f72017-03-22 12:50:05 +0000168 return llvm::StringSwitch<llvm::Optional<CaseType>>(Str)
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000169 .Case("aNy_CasE", CT_AnyCase)
Alexander Kornienko76c28802015-08-19 11:15:36 +0000170 .Case("lower_case", CT_LowerCase)
171 .Case("UPPER_CASE", CT_UpperCase)
172 .Case("camelBack", CT_CamelBack)
173 .Case("CamelCase", CT_CamelCase)
Kirill Bobyrev5d8f0712016-07-20 12:28:38 +0000174 .Case("Camel_Snake_Case", CT_CamelSnakeCase)
175 .Case("camel_Snake_Back", CT_CamelSnakeBack)
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000176 .Default(llvm::None);
Alexander Kornienko76c28802015-08-19 11:15:36 +0000177 };
178
179 for (auto const &Name : StyleNames) {
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000180 auto const caseOptional =
181 fromString(Options.get((Name + "Case").str(), ""));
182 auto prefix = Options.get((Name + "Prefix").str(), "");
183 auto postfix = Options.get((Name + "Suffix").str(), "");
184
185 if (caseOptional || !prefix.empty() || !postfix.empty()) {
186 NamingStyles.push_back(NamingStyle(caseOptional, prefix, postfix));
187 } else {
188 NamingStyles.push_back(llvm::None);
189 }
Alexander Kornienko76c28802015-08-19 11:15:36 +0000190 }
191
192 IgnoreFailedSplit = Options.get("IgnoreFailedSplit", 0);
193}
194
195void IdentifierNamingCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
196 auto const toString = [](CaseType Type) {
197 switch (Type) {
198 case CT_AnyCase:
199 return "aNy_CasE";
200 case CT_LowerCase:
201 return "lower_case";
202 case CT_CamelBack:
203 return "camelBack";
204 case CT_UpperCase:
205 return "UPPER_CASE";
206 case CT_CamelCase:
207 return "CamelCase";
Kirill Bobyrev5d8f0712016-07-20 12:28:38 +0000208 case CT_CamelSnakeCase:
209 return "Camel_Snake_Case";
210 case CT_CamelSnakeBack:
211 return "camel_Snake_Back";
Alexander Kornienko76c28802015-08-19 11:15:36 +0000212 }
213
214 llvm_unreachable("Unknown Case Type");
215 };
216
217 for (size_t i = 0; i < SK_Count; ++i) {
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000218 if (NamingStyles[i]) {
219 if (NamingStyles[i]->Case) {
220 Options.store(Opts, (StyleNames[i] + "Case").str(),
221 toString(*NamingStyles[i]->Case));
222 }
223 Options.store(Opts, (StyleNames[i] + "Prefix").str(),
224 NamingStyles[i]->Prefix);
225 Options.store(Opts, (StyleNames[i] + "Suffix").str(),
226 NamingStyles[i]->Suffix);
227 }
Alexander Kornienko76c28802015-08-19 11:15:36 +0000228 }
229
230 Options.store(Opts, "IgnoreFailedSplit", IgnoreFailedSplit);
231}
232
233void IdentifierNamingCheck::registerMatchers(MatchFinder *Finder) {
Alexander Kornienko76c28802015-08-19 11:15:36 +0000234 Finder->addMatcher(namedDecl().bind("decl"), this);
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000235 Finder->addMatcher(usingDecl().bind("using"), this);
236 Finder->addMatcher(declRefExpr().bind("declRef"), this);
237 Finder->addMatcher(cxxConstructorDecl().bind("classRef"), this);
238 Finder->addMatcher(cxxDestructorDecl().bind("classRef"), this);
239 Finder->addMatcher(typeLoc().bind("typeLoc"), this);
240 Finder->addMatcher(nestedNameSpecifierLoc().bind("nestedNameLoc"), this);
Alexander Kornienko76c28802015-08-19 11:15:36 +0000241}
242
Alexander Kornienkobbc89dc2019-03-22 13:42:48 +0000243void IdentifierNamingCheck::registerPPCallbacks(
244 const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) {
245 ModuleExpanderPP->addPPCallbacks(
Jonas Devlieghere1c705d92019-08-14 23:52:23 +0000246 std::make_unique<IdentifierNamingCheckPPCallbacks>(ModuleExpanderPP,
Alexander Kornienkobbc89dc2019-03-22 13:42:48 +0000247 this));
Alexander Kornienko21503902016-06-17 09:25:24 +0000248}
249
Alexander Kornienko76c28802015-08-19 11:15:36 +0000250static bool matchesStyle(StringRef Name,
251 IdentifierNamingCheck::NamingStyle Style) {
252 static llvm::Regex Matchers[] = {
253 llvm::Regex("^.*$"),
254 llvm::Regex("^[a-z][a-z0-9_]*$"),
255 llvm::Regex("^[a-z][a-zA-Z0-9]*$"),
256 llvm::Regex("^[A-Z][A-Z0-9_]*$"),
257 llvm::Regex("^[A-Z][a-zA-Z0-9]*$"),
Kirill Bobyrev5d8f0712016-07-20 12:28:38 +0000258 llvm::Regex("^[A-Z]([a-z0-9]*(_[A-Z])?)*"),
259 llvm::Regex("^[a-z]([a-z0-9]*(_[A-Z])?)*"),
Alexander Kornienko76c28802015-08-19 11:15:36 +0000260 };
261
262 bool Matches = true;
263 if (Name.startswith(Style.Prefix))
264 Name = Name.drop_front(Style.Prefix.size());
265 else
266 Matches = false;
267
268 if (Name.endswith(Style.Suffix))
269 Name = Name.drop_back(Style.Suffix.size());
270 else
271 Matches = false;
272
Alexander Kornienkoeec01ad2017-04-26 16:39:11 +0000273 // Ensure the name doesn't have any extra underscores beyond those specified
274 // in the prefix and suffix.
275 if (Name.startswith("_") || Name.endswith("_"))
276 Matches = false;
277
Alexander Kornienko1c657f72017-03-22 12:50:05 +0000278 if (Style.Case && !Matchers[static_cast<size_t>(*Style.Case)].match(Name))
Alexander Kornienko76c28802015-08-19 11:15:36 +0000279 Matches = false;
280
281 return Matches;
282}
283
284static std::string fixupWithCase(StringRef Name,
285 IdentifierNamingCheck::CaseType Case) {
286 static llvm::Regex Splitter(
287 "([a-z0-9A-Z]*)(_+)|([A-Z]?[a-z0-9]+)([A-Z]|$)|([A-Z]+)([A-Z]|$)");
288
289 SmallVector<StringRef, 8> Substrs;
290 Name.split(Substrs, "_", -1, false);
291
292 SmallVector<StringRef, 8> Words;
293 for (auto Substr : Substrs) {
294 while (!Substr.empty()) {
295 SmallVector<StringRef, 8> Groups;
296 if (!Splitter.match(Substr, &Groups))
297 break;
298
299 if (Groups[2].size() > 0) {
300 Words.push_back(Groups[1]);
301 Substr = Substr.substr(Groups[0].size());
302 } else if (Groups[3].size() > 0) {
303 Words.push_back(Groups[3]);
304 Substr = Substr.substr(Groups[0].size() - Groups[4].size());
305 } else if (Groups[5].size() > 0) {
306 Words.push_back(Groups[5]);
307 Substr = Substr.substr(Groups[0].size() - Groups[6].size());
308 }
309 }
310 }
311
312 if (Words.empty())
313 return Name;
314
315 std::string Fixup;
316 switch (Case) {
317 case IdentifierNamingCheck::CT_AnyCase:
318 Fixup += Name;
319 break;
320
321 case IdentifierNamingCheck::CT_LowerCase:
322 for (auto const &Word : Words) {
323 if (&Word != &Words.front())
324 Fixup += "_";
325 Fixup += Word.lower();
326 }
327 break;
328
329 case IdentifierNamingCheck::CT_UpperCase:
330 for (auto const &Word : Words) {
331 if (&Word != &Words.front())
332 Fixup += "_";
333 Fixup += Word.upper();
334 }
335 break;
336
337 case IdentifierNamingCheck::CT_CamelCase:
338 for (auto const &Word : Words) {
339 Fixup += Word.substr(0, 1).upper();
340 Fixup += Word.substr(1).lower();
341 }
342 break;
343
344 case IdentifierNamingCheck::CT_CamelBack:
345 for (auto const &Word : Words) {
346 if (&Word == &Words.front()) {
347 Fixup += Word.lower();
348 } else {
349 Fixup += Word.substr(0, 1).upper();
350 Fixup += Word.substr(1).lower();
351 }
352 }
353 break;
Kirill Bobyrev5d8f0712016-07-20 12:28:38 +0000354
355 case IdentifierNamingCheck::CT_CamelSnakeCase:
356 for (auto const &Word : Words) {
357 if (&Word != &Words.front())
358 Fixup += "_";
359 Fixup += Word.substr(0, 1).upper();
360 Fixup += Word.substr(1).lower();
361 }
362 break;
363
364 case IdentifierNamingCheck::CT_CamelSnakeBack:
365 for (auto const &Word : Words) {
366 if (&Word != &Words.front()) {
367 Fixup += "_";
368 Fixup += Word.substr(0, 1).upper();
369 } else {
370 Fixup += Word.substr(0, 1).lower();
371 }
372 Fixup += Word.substr(1).lower();
373 }
374 break;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000375 }
376
377 return Fixup;
378}
379
Alexander Kornienko1c657f72017-03-22 12:50:05 +0000380static std::string
381fixupWithStyle(StringRef Name,
382 const IdentifierNamingCheck::NamingStyle &Style) {
Alexander Kornienkoeec01ad2017-04-26 16:39:11 +0000383 const std::string Fixed = fixupWithCase(
384 Name, Style.Case.getValueOr(IdentifierNamingCheck::CaseType::CT_AnyCase));
385 StringRef Mid = StringRef(Fixed).trim("_");
386 if (Mid.empty())
387 Mid = "_";
388 return (Style.Prefix + Mid + Style.Suffix).str();
Alexander Kornienko76c28802015-08-19 11:15:36 +0000389}
390
391static StyleKind findStyleKind(
392 const NamedDecl *D,
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000393 const std::vector<llvm::Optional<IdentifierNamingCheck::NamingStyle>>
394 &NamingStyles) {
Artem Belevichfcfcd502018-09-18 21:51:02 +0000395 assert(D && D->getIdentifier() && !D->getName().empty() && !D->isImplicit() &&
396 "Decl must be an explicit identifier with a name.");
397
Yan Zhang004b6c62018-04-23 00:15:15 +0000398 if (isa<ObjCIvarDecl>(D) && NamingStyles[SK_ObjcIvar])
399 return SK_ObjcIvar;
400
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000401 if (isa<TypedefDecl>(D) && NamingStyles[SK_Typedef])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000402 return SK_Typedef;
403
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000404 if (isa<TypeAliasDecl>(D) && NamingStyles[SK_TypeAlias])
Alexander Kornienko5ae76e02016-06-07 09:11:19 +0000405 return SK_TypeAlias;
406
Alexander Kornienko76c28802015-08-19 11:15:36 +0000407 if (const auto *Decl = dyn_cast<NamespaceDecl>(D)) {
408 if (Decl->isAnonymousNamespace())
409 return SK_Invalid;
410
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000411 if (Decl->isInline() && NamingStyles[SK_InlineNamespace])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000412 return SK_InlineNamespace;
413
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000414 if (NamingStyles[SK_Namespace])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000415 return SK_Namespace;
416 }
417
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000418 if (isa<EnumDecl>(D) && NamingStyles[SK_Enum])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000419 return SK_Enum;
420
421 if (isa<EnumConstantDecl>(D)) {
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000422 if (NamingStyles[SK_EnumConstant])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000423 return SK_EnumConstant;
424
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000425 if (NamingStyles[SK_Constant])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000426 return SK_Constant;
427
428 return SK_Invalid;
429 }
430
431 if (const auto *Decl = dyn_cast<CXXRecordDecl>(D)) {
432 if (Decl->isAnonymousStructOrUnion())
433 return SK_Invalid;
434
Jonathan Coe89f12c02016-11-03 13:52:09 +0000435 if (!Decl->getCanonicalDecl()->isThisDeclarationADefinition())
436 return SK_Invalid;
437
Alexander Kornienko76c28802015-08-19 11:15:36 +0000438 if (Decl->hasDefinition() && Decl->isAbstract() &&
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000439 NamingStyles[SK_AbstractClass])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000440 return SK_AbstractClass;
441
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000442 if (Decl->isStruct() && NamingStyles[SK_Struct])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000443 return SK_Struct;
444
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000445 if (Decl->isStruct() && NamingStyles[SK_Class])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000446 return SK_Class;
447
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000448 if (Decl->isClass() && 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_Struct])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000452 return SK_Struct;
453
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000454 if (Decl->isUnion() && NamingStyles[SK_Union])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000455 return SK_Union;
456
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000457 if (Decl->isEnum() && NamingStyles[SK_Enum])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000458 return SK_Enum;
459
460 return SK_Invalid;
461 }
462
463 if (const auto *Decl = dyn_cast<FieldDecl>(D)) {
464 QualType Type = Decl->getType();
465
Alexander Kornienkoba874922017-12-11 19:02:26 +0000466 if (!Type.isNull() && Type.isConstQualified()) {
467 if (NamingStyles[SK_ConstantMember])
468 return SK_ConstantMember;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000469
Alexander Kornienkoba874922017-12-11 19:02:26 +0000470 if (NamingStyles[SK_Constant])
471 return SK_Constant;
472 }
Alexander Kornienko76c28802015-08-19 11:15:36 +0000473
Alexander Kornienko1c657f72017-03-22 12:50:05 +0000474 if (Decl->getAccess() == AS_private && NamingStyles[SK_PrivateMember])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000475 return SK_PrivateMember;
476
Alexander Kornienko1c657f72017-03-22 12:50:05 +0000477 if (Decl->getAccess() == AS_protected && NamingStyles[SK_ProtectedMember])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000478 return SK_ProtectedMember;
479
Alexander Kornienko1c657f72017-03-22 12:50:05 +0000480 if (Decl->getAccess() == AS_public && NamingStyles[SK_PublicMember])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000481 return SK_PublicMember;
482
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000483 if (NamingStyles[SK_Member])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000484 return SK_Member;
485
486 return SK_Invalid;
487 }
488
489 if (const auto *Decl = dyn_cast<ParmVarDecl>(D)) {
490 QualType Type = Decl->getType();
491
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000492 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprVariable])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000493 return SK_ConstexprVariable;
494
Alexander Kornienkoba874922017-12-11 19:02:26 +0000495 if (!Type.isNull() && Type.isConstQualified()) {
Jonas Tothc97671e2018-10-04 15:47:57 +0000496 if (Type.getTypePtr()->isAnyPointerType() && NamingStyles[SK_ConstantPointerParameter])
497 return SK_ConstantPointerParameter;
498
Alexander Kornienkoba874922017-12-11 19:02:26 +0000499 if (NamingStyles[SK_ConstantParameter])
500 return SK_ConstantParameter;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000501
Alexander Kornienkoba874922017-12-11 19:02:26 +0000502 if (NamingStyles[SK_Constant])
503 return SK_Constant;
504 }
Alexander Kornienko76c28802015-08-19 11:15:36 +0000505
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000506 if (Decl->isParameterPack() && NamingStyles[SK_ParameterPack])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000507 return SK_ParameterPack;
508
Jonas Tothc97671e2018-10-04 15:47:57 +0000509 if (!Type.isNull() && Type.getTypePtr()->isAnyPointerType() && NamingStyles[SK_PointerParameter])
510 return SK_PointerParameter;
511
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000512 if (NamingStyles[SK_Parameter])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000513 return SK_Parameter;
514
515 return SK_Invalid;
516 }
517
518 if (const auto *Decl = dyn_cast<VarDecl>(D)) {
519 QualType Type = Decl->getType();
520
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000521 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprVariable])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000522 return SK_ConstexprVariable;
523
Alexander Kornienkoba874922017-12-11 19:02:26 +0000524 if (!Type.isNull() && Type.isConstQualified()) {
525 if (Decl->isStaticDataMember() && NamingStyles[SK_ClassConstant])
526 return SK_ClassConstant;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000527
Jonas Tothc97671e2018-10-04 15:47:57 +0000528 if (Decl->isFileVarDecl() && Type.getTypePtr()->isAnyPointerType() && NamingStyles[SK_GlobalConstantPointer])
529 return SK_GlobalConstantPointer;
530
Alexander Kornienkoba874922017-12-11 19:02:26 +0000531 if (Decl->isFileVarDecl() && NamingStyles[SK_GlobalConstant])
532 return SK_GlobalConstant;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000533
Alexander Kornienkoba874922017-12-11 19:02:26 +0000534 if (Decl->isStaticLocal() && NamingStyles[SK_StaticConstant])
535 return SK_StaticConstant;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000536
Jonas Tothc97671e2018-10-04 15:47:57 +0000537 if (Decl->isLocalVarDecl() && Type.getTypePtr()->isAnyPointerType() && NamingStyles[SK_LocalConstantPointer])
538 return SK_LocalConstantPointer;
539
Alexander Kornienkoba874922017-12-11 19:02:26 +0000540 if (Decl->isLocalVarDecl() && NamingStyles[SK_LocalConstant])
541 return SK_LocalConstant;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000542
Alexander Kornienkoba874922017-12-11 19:02:26 +0000543 if (Decl->isFunctionOrMethodVarDecl() && NamingStyles[SK_LocalConstant])
544 return SK_LocalConstant;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000545
Alexander Kornienkoba874922017-12-11 19:02:26 +0000546 if (NamingStyles[SK_Constant])
547 return SK_Constant;
548 }
Alexander Kornienko76c28802015-08-19 11:15:36 +0000549
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000550 if (Decl->isStaticDataMember() && NamingStyles[SK_ClassMember])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000551 return SK_ClassMember;
552
Jonas Tothc97671e2018-10-04 15:47:57 +0000553 if (Decl->isFileVarDecl() && Type.getTypePtr()->isAnyPointerType() && NamingStyles[SK_GlobalPointer])
554 return SK_GlobalPointer;
555
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000556 if (Decl->isFileVarDecl() && NamingStyles[SK_GlobalVariable])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000557 return SK_GlobalVariable;
558
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000559 if (Decl->isStaticLocal() && NamingStyles[SK_StaticVariable])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000560 return SK_StaticVariable;
Jonas Tothc97671e2018-10-04 15:47:57 +0000561
562 if (Decl->isLocalVarDecl() && Type.getTypePtr()->isAnyPointerType() && NamingStyles[SK_LocalPointer])
563 return SK_LocalPointer;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000564
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000565 if (Decl->isLocalVarDecl() && NamingStyles[SK_LocalVariable])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000566 return SK_LocalVariable;
567
Alexander Kornienko1c657f72017-03-22 12:50:05 +0000568 if (Decl->isFunctionOrMethodVarDecl() && NamingStyles[SK_LocalVariable])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000569 return SK_LocalVariable;
570
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000571 if (NamingStyles[SK_Variable])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000572 return SK_Variable;
573
574 return SK_Invalid;
575 }
576
577 if (const auto *Decl = dyn_cast<CXXMethodDecl>(D)) {
578 if (Decl->isMain() || !Decl->isUserProvided() ||
Alexander Kornienko76c28802015-08-19 11:15:36 +0000579 Decl->size_overridden_methods() > 0)
580 return SK_Invalid;
581
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000582 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprMethod])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000583 return SK_ConstexprMethod;
584
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000585 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprFunction])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000586 return SK_ConstexprFunction;
587
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000588 if (Decl->isStatic() && NamingStyles[SK_ClassMethod])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000589 return SK_ClassMethod;
590
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000591 if (Decl->isVirtual() && NamingStyles[SK_VirtualMethod])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000592 return SK_VirtualMethod;
593
Alexander Kornienko1c657f72017-03-22 12:50:05 +0000594 if (Decl->getAccess() == AS_private && NamingStyles[SK_PrivateMethod])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000595 return SK_PrivateMethod;
596
Alexander Kornienko1c657f72017-03-22 12:50:05 +0000597 if (Decl->getAccess() == AS_protected && NamingStyles[SK_ProtectedMethod])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000598 return SK_ProtectedMethod;
599
Alexander Kornienko1c657f72017-03-22 12:50:05 +0000600 if (Decl->getAccess() == AS_public && NamingStyles[SK_PublicMethod])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000601 return SK_PublicMethod;
602
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000603 if (NamingStyles[SK_Method])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000604 return SK_Method;
605
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000606 if (NamingStyles[SK_Function])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000607 return SK_Function;
608
609 return SK_Invalid;
610 }
611
612 if (const auto *Decl = dyn_cast<FunctionDecl>(D)) {
613 if (Decl->isMain())
614 return SK_Invalid;
615
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000616 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprFunction])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000617 return SK_ConstexprFunction;
618
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000619 if (Decl->isGlobal() && NamingStyles[SK_GlobalFunction])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000620 return SK_GlobalFunction;
621
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000622 if (NamingStyles[SK_Function])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000623 return SK_Function;
624 }
625
626 if (isa<TemplateTypeParmDecl>(D)) {
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000627 if (NamingStyles[SK_TypeTemplateParameter])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000628 return SK_TypeTemplateParameter;
629
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000630 if (NamingStyles[SK_TemplateParameter])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000631 return SK_TemplateParameter;
632
633 return SK_Invalid;
634 }
635
636 if (isa<NonTypeTemplateParmDecl>(D)) {
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000637 if (NamingStyles[SK_ValueTemplateParameter])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000638 return SK_ValueTemplateParameter;
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<TemplateTemplateParmDecl>(D)) {
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000647 if (NamingStyles[SK_TemplateTemplateParameter])
Alexander Kornienko76c28802015-08-19 11:15:36 +0000648 return SK_TemplateTemplateParameter;
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 return SK_Invalid;
657}
658
Alexander Kornienko3d777682015-09-28 08:59:12 +0000659static void addUsage(IdentifierNamingCheck::NamingCheckFailureMap &Failures,
Alexander Kornienko21503902016-06-17 09:25:24 +0000660 const IdentifierNamingCheck::NamingCheckId &Decl,
Jason Henline481e6aa2016-10-24 17:20:32 +0000661 SourceRange Range, SourceManager *SourceMgr = nullptr) {
Jonathan Coe2c8592a2016-01-26 18:55:55 +0000662 // Do nothing if the provided range is invalid.
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000663 if (Range.getBegin().isInvalid() || Range.getEnd().isInvalid())
664 return;
665
Jason Henline481e6aa2016-10-24 17:20:32 +0000666 // If we have a source manager, use it to convert to the spelling location for
667 // performing the fix. This is necessary because macros can map the same
668 // spelling location to different source locations, and we only want to fix
669 // the token once, before it is expanded by the macro.
670 SourceLocation FixLocation = Range.getBegin();
671 if (SourceMgr)
672 FixLocation = SourceMgr->getSpellingLoc(FixLocation);
673 if (FixLocation.isInvalid())
674 return;
675
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000676 // Try to insert the identifier location in the Usages map, and bail out if it
677 // is already in there
Alexander Kornienko3d777682015-09-28 08:59:12 +0000678 auto &Failure = Failures[Decl];
Jason Henline481e6aa2016-10-24 17:20:32 +0000679 if (!Failure.RawUsageLocs.insert(FixLocation.getRawEncoding()).second)
Alexander Kornienko3d777682015-09-28 08:59:12 +0000680 return;
681
Jason Henline481e6aa2016-10-24 17:20:32 +0000682 if (!Failure.ShouldFix)
683 return;
684
Roman Lebedev08701ec2018-10-26 13:09:27 +0000685 Failure.ShouldFix = utils::rangeCanBeFixed(Range, SourceMgr);
Alexander Kornienko3d777682015-09-28 08:59:12 +0000686}
687
Alexander Kornienko21503902016-06-17 09:25:24 +0000688/// Convenience method when the usage to be added is a NamedDecl
689static void addUsage(IdentifierNamingCheck::NamingCheckFailureMap &Failures,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000690 const NamedDecl *Decl, SourceRange Range,
691 SourceManager *SourceMgr = nullptr) {
Alexander Kornienkoba874922017-12-11 19:02:26 +0000692 return addUsage(Failures,
693 IdentifierNamingCheck::NamingCheckId(Decl->getLocation(),
694 Decl->getNameAsString()),
Jason Henline481e6aa2016-10-24 17:20:32 +0000695 Range, SourceMgr);
Alexander Kornienko21503902016-06-17 09:25:24 +0000696}
697
Alexander Kornienko76c28802015-08-19 11:15:36 +0000698void IdentifierNamingCheck::check(const MatchFinder::MatchResult &Result) {
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000699 if (const auto *Decl =
700 Result.Nodes.getNodeAs<CXXConstructorDecl>("classRef")) {
701 if (Decl->isImplicit())
702 return;
703
704 addUsage(NamingCheckFailures, Decl->getParent(),
Alexander Kornienko21503902016-06-17 09:25:24 +0000705 Decl->getNameInfo().getSourceRange());
Eric Fiselier732a3e02016-11-16 21:15:58 +0000706
707 for (const auto *Init : Decl->inits()) {
708 if (!Init->isWritten() || Init->isInClassMemberInitializer())
709 continue;
710 if (const auto *FD = Init->getAnyMember())
Alexander Kornienkoba874922017-12-11 19:02:26 +0000711 addUsage(NamingCheckFailures, FD,
712 SourceRange(Init->getMemberLocation()));
Eric Fiselier732a3e02016-11-16 21:15:58 +0000713 // Note: delegating constructors and base class initializers are handled
714 // via the "typeLoc" matcher.
715 }
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000716 return;
717 }
718
719 if (const auto *Decl =
720 Result.Nodes.getNodeAs<CXXDestructorDecl>("classRef")) {
721 if (Decl->isImplicit())
722 return;
723
724 SourceRange Range = Decl->getNameInfo().getSourceRange();
725 if (Range.getBegin().isInvalid())
726 return;
727 // The first token that will be found is the ~ (or the equivalent trigraph),
728 // we want instead to replace the next token, that will be the identifier.
729 Range.setBegin(CharSourceRange::getTokenRange(Range).getEnd());
730
Alexander Kornienko21503902016-06-17 09:25:24 +0000731 addUsage(NamingCheckFailures, Decl->getParent(), Range);
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000732 return;
733 }
734
735 if (const auto *Loc = Result.Nodes.getNodeAs<TypeLoc>("typeLoc")) {
736 NamedDecl *Decl = nullptr;
737 if (const auto &Ref = Loc->getAs<TagTypeLoc>()) {
738 Decl = Ref.getDecl();
739 } else if (const auto &Ref = Loc->getAs<InjectedClassNameTypeLoc>()) {
740 Decl = Ref.getDecl();
741 } else if (const auto &Ref = Loc->getAs<UnresolvedUsingTypeLoc>()) {
742 Decl = Ref.getDecl();
743 } else if (const auto &Ref = Loc->getAs<TemplateTypeParmTypeLoc>()) {
744 Decl = Ref.getDecl();
745 }
746
747 if (Decl) {
Alexander Kornienko21503902016-06-17 09:25:24 +0000748 addUsage(NamingCheckFailures, Decl, Loc->getSourceRange());
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000749 return;
750 }
751
752 if (const auto &Ref = Loc->getAs<TemplateSpecializationTypeLoc>()) {
753 const auto *Decl =
754 Ref.getTypePtr()->getTemplateName().getAsTemplateDecl();
755
756 SourceRange Range(Ref.getTemplateNameLoc(), Ref.getTemplateNameLoc());
757 if (const auto *ClassDecl = dyn_cast<TemplateDecl>(Decl)) {
Matthias Gehrea9e812b2016-07-09 20:09:28 +0000758 if (const auto *TemplDecl = ClassDecl->getTemplatedDecl())
759 addUsage(NamingCheckFailures, TemplDecl, Range);
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000760 return;
761 }
762 }
763
764 if (const auto &Ref =
765 Loc->getAs<DependentTemplateSpecializationTypeLoc>()) {
Matthias Gehrea9e812b2016-07-09 20:09:28 +0000766 if (const auto *Decl = Ref.getTypePtr()->getAsTagDecl())
767 addUsage(NamingCheckFailures, Decl, Loc->getSourceRange());
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000768 return;
769 }
770 }
771
772 if (const auto *Loc =
773 Result.Nodes.getNodeAs<NestedNameSpecifierLoc>("nestedNameLoc")) {
774 if (NestedNameSpecifier *Spec = Loc->getNestedNameSpecifier()) {
775 if (NamespaceDecl *Decl = Spec->getAsNamespace()) {
Alexander Kornienko21503902016-06-17 09:25:24 +0000776 addUsage(NamingCheckFailures, Decl, Loc->getLocalSourceRange());
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000777 return;
778 }
779 }
780 }
781
782 if (const auto *Decl = Result.Nodes.getNodeAs<UsingDecl>("using")) {
783 for (const auto &Shadow : Decl->shadows()) {
784 addUsage(NamingCheckFailures, Shadow->getTargetDecl(),
Alexander Kornienko21503902016-06-17 09:25:24 +0000785 Decl->getNameInfo().getSourceRange());
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000786 }
787 return;
788 }
789
790 if (const auto *DeclRef = Result.Nodes.getNodeAs<DeclRefExpr>("declRef")) {
Alexander Kornienko76c28802015-08-19 11:15:36 +0000791 SourceRange Range = DeclRef->getNameInfo().getSourceRange();
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000792 addUsage(NamingCheckFailures, DeclRef->getDecl(), Range,
793 Result.SourceManager);
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000794 return;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000795 }
796
797 if (const auto *Decl = Result.Nodes.getNodeAs<NamedDecl>("decl")) {
798 if (!Decl->getIdentifier() || Decl->getName().empty() || Decl->isImplicit())
799 return;
800
Alexander Kornienko21503902016-06-17 09:25:24 +0000801 // Fix type aliases in value declarations
802 if (const auto *Value = Result.Nodes.getNodeAs<ValueDecl>("decl")) {
Haojian Wu2255b312019-05-28 11:54:01 +0000803 if (const auto *TypePtr = Value->getType().getTypePtrOrNull()) {
804 if (const auto *Typedef = TypePtr->getAs<TypedefType>()) {
805 addUsage(NamingCheckFailures, Typedef->getDecl(),
806 Value->getSourceRange());
807 }
Alexander Kornienko21503902016-06-17 09:25:24 +0000808 }
809 }
810
811 // Fix type aliases in function declarations
812 if (const auto *Value = Result.Nodes.getNodeAs<FunctionDecl>("decl")) {
813 if (const auto *Typedef =
814 Value->getReturnType().getTypePtr()->getAs<TypedefType>()) {
815 addUsage(NamingCheckFailures, Typedef->getDecl(),
816 Value->getSourceRange());
817 }
818 for (unsigned i = 0; i < Value->getNumParams(); ++i) {
819 if (const auto *Typedef = Value->parameters()[i]
820 ->getType()
821 .getTypePtr()
822 ->getAs<TypedefType>()) {
823 addUsage(NamingCheckFailures, Typedef->getDecl(),
824 Value->getSourceRange());
825 }
826 }
827 }
828
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000829 // Ignore ClassTemplateSpecializationDecl which are creating duplicate
830 // replacements with CXXRecordDecl
831 if (isa<ClassTemplateSpecializationDecl>(Decl))
832 return;
833
Alexander Kornienko76c28802015-08-19 11:15:36 +0000834 StyleKind SK = findStyleKind(Decl, NamingStyles);
835 if (SK == SK_Invalid)
836 return;
837
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000838 if (!NamingStyles[SK])
839 return;
840
841 const NamingStyle &Style = *NamingStyles[SK];
Alexander Kornienko76c28802015-08-19 11:15:36 +0000842 StringRef Name = Decl->getName();
843 if (matchesStyle(Name, Style))
844 return;
845
846 std::string KindName = fixupWithCase(StyleNames[SK], CT_LowerCase);
847 std::replace(KindName.begin(), KindName.end(), '_', ' ');
848
849 std::string Fixup = fixupWithStyle(Name, Style);
850 if (StringRef(Fixup).equals(Name)) {
851 if (!IgnoreFailedSplit) {
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000852 LLVM_DEBUG(llvm::dbgs()
Stephen Kelly43465bf2018-08-09 22:42:26 +0000853 << Decl->getBeginLoc().printToString(*Result.SourceManager)
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000854 << llvm::format(": unable to split words for %s '%s'\n",
855 KindName.c_str(), Name.str().c_str()));
Alexander Kornienko76c28802015-08-19 11:15:36 +0000856 }
857 } else {
Alexander Kornienko21503902016-06-17 09:25:24 +0000858 NamingCheckFailure &Failure = NamingCheckFailures[NamingCheckId(
859 Decl->getLocation(), Decl->getNameAsString())];
Alexander Kornienko76c28802015-08-19 11:15:36 +0000860 SourceRange Range =
861 DeclarationNameInfo(Decl->getDeclName(), Decl->getLocation())
862 .getSourceRange();
863
864 Failure.Fixup = std::move(Fixup);
865 Failure.KindName = std::move(KindName);
Alexander Kornienko21503902016-06-17 09:25:24 +0000866 addUsage(NamingCheckFailures, Decl, Range);
Alexander Kornienko76c28802015-08-19 11:15:36 +0000867 }
868 }
869}
870
Alexander Kornienko21503902016-06-17 09:25:24 +0000871void IdentifierNamingCheck::checkMacro(SourceManager &SourceMgr,
872 const Token &MacroNameTok,
873 const MacroInfo *MI) {
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000874 if (!NamingStyles[SK_MacroDefinition])
875 return;
876
Alexander Kornienko21503902016-06-17 09:25:24 +0000877 StringRef Name = MacroNameTok.getIdentifierInfo()->getName();
Alexander Kornienkoee9247e2017-03-22 12:49:58 +0000878 const NamingStyle &Style = *NamingStyles[SK_MacroDefinition];
Alexander Kornienko21503902016-06-17 09:25:24 +0000879 if (matchesStyle(Name, Style))
880 return;
881
882 std::string KindName =
883 fixupWithCase(StyleNames[SK_MacroDefinition], CT_LowerCase);
884 std::replace(KindName.begin(), KindName.end(), '_', ' ');
885
886 std::string Fixup = fixupWithStyle(Name, Style);
887 if (StringRef(Fixup).equals(Name)) {
888 if (!IgnoreFailedSplit) {
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000889 LLVM_DEBUG(llvm::dbgs()
890 << MacroNameTok.getLocation().printToString(SourceMgr)
891 << llvm::format(": unable to split words for %s '%s'\n",
892 KindName.c_str(), Name.str().c_str()));
Alexander Kornienko21503902016-06-17 09:25:24 +0000893 }
894 } else {
895 NamingCheckId ID(MI->getDefinitionLoc(), Name);
896 NamingCheckFailure &Failure = NamingCheckFailures[ID];
897 SourceRange Range(MacroNameTok.getLocation(), MacroNameTok.getEndLoc());
898
899 Failure.Fixup = std::move(Fixup);
900 Failure.KindName = std::move(KindName);
901 addUsage(NamingCheckFailures, ID, Range);
902 }
903}
904
905void IdentifierNamingCheck::expandMacro(const Token &MacroNameTok,
906 const MacroInfo *MI) {
907 StringRef Name = MacroNameTok.getIdentifierInfo()->getName();
908 NamingCheckId ID(MI->getDefinitionLoc(), Name);
909
910 auto Failure = NamingCheckFailures.find(ID);
911 if (Failure == NamingCheckFailures.end())
912 return;
913
914 SourceRange Range(MacroNameTok.getLocation(), MacroNameTok.getEndLoc());
915 addUsage(NamingCheckFailures, ID, Range);
916}
917
Alexander Kornienko76c28802015-08-19 11:15:36 +0000918void IdentifierNamingCheck::onEndOfTranslationUnit() {
919 for (const auto &Pair : NamingCheckFailures) {
Alexander Kornienko21503902016-06-17 09:25:24 +0000920 const NamingCheckId &Decl = Pair.first;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000921 const NamingCheckFailure &Failure = Pair.second;
922
Alexander Kornienko3d777682015-09-28 08:59:12 +0000923 if (Failure.KindName.empty())
924 continue;
925
Alexander Kornienko76c28802015-08-19 11:15:36 +0000926 if (Failure.ShouldFix) {
Alexander Kornienko21503902016-06-17 09:25:24 +0000927 auto Diag = diag(Decl.first, "invalid case style for %0 '%1'")
928 << Failure.KindName << Decl.second;
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000929
Alexander Kornienko3d777682015-09-28 08:59:12 +0000930 for (const auto &Loc : Failure.RawUsageLocs) {
931 // We assume that the identifier name is made of one token only. This is
932 // always the case as we ignore usages in macros that could build
933 // identifier names by combining multiple tokens.
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000934 //
935 // For destructors, we alread take care of it by remembering the
936 // location of the start of the identifier and not the start of the
937 // tilde.
938 //
939 // Other multi-token identifiers, such as operators are not checked at
940 // all.
Alexander Kornienko76c28802015-08-19 11:15:36 +0000941 Diag << FixItHint::CreateReplacement(
Alexander Kornienko3d777682015-09-28 08:59:12 +0000942 SourceRange(SourceLocation::getFromRawEncoding(Loc)),
943 Failure.Fixup);
Alexander Kornienko76c28802015-08-19 11:15:36 +0000944 }
945 }
946 }
947}
948
949} // namespace readability
950} // namespace tidy
951} // namespace clang