blob: c1c2eb70466a9f2ca0db09281eb0e34b02de118d [file] [log] [blame]
Alexander Kornienko76c28802015-08-19 11:15:36 +00001//===--- IdentifierNamingCheck.cpp - clang-tidy ---------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "IdentifierNamingCheck.h"
11
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
52 static bool isEqual(NamingCheckId LHS, NamingCheckId RHS) {
53 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) \
80 m(GlobalVariable) \
81 m(LocalConstant) \
82 m(LocalVariable) \
83 m(StaticConstant) \
84 m(StaticVariable) \
85 m(Constant) \
86 m(Variable) \
87 m(ConstantParameter) \
88 m(ParameterPack) \
89 m(Parameter) \
90 m(AbstractClass) \
91 m(Struct) \
92 m(Class) \
93 m(Union) \
94 m(Enum) \
95 m(GlobalFunction) \
96 m(ConstexprFunction) \
97 m(Function) \
98 m(ConstexprMethod) \
99 m(VirtualMethod) \
100 m(ClassMethod) \
101 m(PrivateMethod) \
102 m(ProtectedMethod) \
103 m(PublicMethod) \
104 m(Method) \
105 m(Typedef) \
106 m(TypeTemplateParameter) \
107 m(ValueTemplateParameter) \
108 m(TemplateTemplateParameter) \
109 m(TemplateParameter) \
Alexander Kornienko5ae76e02016-06-07 09:11:19 +0000110 m(TypeAlias) \
Alexander Kornienko21503902016-06-17 09:25:24 +0000111 m(MacroDefinition) \
Alexander Kornienko76c28802015-08-19 11:15:36 +0000112
113enum StyleKind {
114#define ENUMERATE(v) SK_ ## v,
115 NAMING_KEYS(ENUMERATE)
116#undef ENUMERATE
117 SK_Count,
118 SK_Invalid
119};
120
121static StringRef const StyleNames[] = {
122#define STRINGIZE(v) #v,
123 NAMING_KEYS(STRINGIZE)
124#undef STRINGIZE
125};
126
127#undef NAMING_KEYS
Alexander Kornienko3d777682015-09-28 08:59:12 +0000128// clang-format on
Alexander Kornienko76c28802015-08-19 11:15:36 +0000129
Alexander Kornienko21503902016-06-17 09:25:24 +0000130namespace {
131/// Callback supplies macros to IdentifierNamingCheck::checkMacro
132class IdentifierNamingCheckPPCallbacks : public PPCallbacks {
133public:
134 IdentifierNamingCheckPPCallbacks(Preprocessor *PP,
135 IdentifierNamingCheck *Check)
136 : PP(PP), Check(Check) {}
137
138 /// MacroDefined calls checkMacro for macros in the main file
139 void MacroDefined(const Token &MacroNameTok,
140 const MacroDirective *MD) override {
141 Check->checkMacro(PP->getSourceManager(), MacroNameTok, MD->getMacroInfo());
142 }
143
144 /// MacroExpands calls expandMacro for macros in the main file
145 void MacroExpands(const Token &MacroNameTok, const MacroDefinition &MD,
146 SourceRange /*Range*/,
147 const MacroArgs * /*Args*/) override {
148 Check->expandMacro(MacroNameTok, MD.getMacroInfo());
149 }
150
151private:
152 Preprocessor *PP;
153 IdentifierNamingCheck *Check;
154};
155} // namespace
156
Alexander Kornienko76c28802015-08-19 11:15:36 +0000157IdentifierNamingCheck::IdentifierNamingCheck(StringRef Name,
158 ClangTidyContext *Context)
159 : ClangTidyCheck(Name, Context) {
160 auto const fromString = [](StringRef Str) {
161 return llvm::StringSwitch<CaseType>(Str)
162 .Case("lower_case", CT_LowerCase)
163 .Case("UPPER_CASE", CT_UpperCase)
164 .Case("camelBack", CT_CamelBack)
165 .Case("CamelCase", CT_CamelCase)
Kirill Bobyrev5d8f0712016-07-20 12:28:38 +0000166 .Case("Camel_Snake_Case", CT_CamelSnakeCase)
167 .Case("camel_Snake_Back", CT_CamelSnakeBack)
Alexander Kornienko76c28802015-08-19 11:15:36 +0000168 .Default(CT_AnyCase);
169 };
170
171 for (auto const &Name : StyleNames) {
172 NamingStyles.push_back(
173 NamingStyle(fromString(Options.get((Name + "Case").str(), "")),
174 Options.get((Name + "Prefix").str(), ""),
175 Options.get((Name + "Suffix").str(), "")));
176 }
177
178 IgnoreFailedSplit = Options.get("IgnoreFailedSplit", 0);
179}
180
181void IdentifierNamingCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
182 auto const toString = [](CaseType Type) {
183 switch (Type) {
184 case CT_AnyCase:
185 return "aNy_CasE";
186 case CT_LowerCase:
187 return "lower_case";
188 case CT_CamelBack:
189 return "camelBack";
190 case CT_UpperCase:
191 return "UPPER_CASE";
192 case CT_CamelCase:
193 return "CamelCase";
Kirill Bobyrev5d8f0712016-07-20 12:28:38 +0000194 case CT_CamelSnakeCase:
195 return "Camel_Snake_Case";
196 case CT_CamelSnakeBack:
197 return "camel_Snake_Back";
Alexander Kornienko76c28802015-08-19 11:15:36 +0000198 }
199
200 llvm_unreachable("Unknown Case Type");
201 };
202
203 for (size_t i = 0; i < SK_Count; ++i) {
204 Options.store(Opts, (StyleNames[i] + "Case").str(),
205 toString(NamingStyles[i].Case));
206 Options.store(Opts, (StyleNames[i] + "Prefix").str(),
207 NamingStyles[i].Prefix);
208 Options.store(Opts, (StyleNames[i] + "Suffix").str(),
209 NamingStyles[i].Suffix);
210 }
211
212 Options.store(Opts, "IgnoreFailedSplit", IgnoreFailedSplit);
213}
214
215void IdentifierNamingCheck::registerMatchers(MatchFinder *Finder) {
Alexander Kornienko76c28802015-08-19 11:15:36 +0000216 Finder->addMatcher(namedDecl().bind("decl"), this);
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000217 Finder->addMatcher(usingDecl().bind("using"), this);
218 Finder->addMatcher(declRefExpr().bind("declRef"), this);
219 Finder->addMatcher(cxxConstructorDecl().bind("classRef"), this);
220 Finder->addMatcher(cxxDestructorDecl().bind("classRef"), this);
221 Finder->addMatcher(typeLoc().bind("typeLoc"), this);
222 Finder->addMatcher(nestedNameSpecifierLoc().bind("nestedNameLoc"), this);
Alexander Kornienko76c28802015-08-19 11:15:36 +0000223}
224
Alexander Kornienko21503902016-06-17 09:25:24 +0000225void IdentifierNamingCheck::registerPPCallbacks(CompilerInstance &Compiler) {
226 Compiler.getPreprocessor().addPPCallbacks(
227 llvm::make_unique<IdentifierNamingCheckPPCallbacks>(
228 &Compiler.getPreprocessor(), this));
229}
230
Alexander Kornienko76c28802015-08-19 11:15:36 +0000231static bool matchesStyle(StringRef Name,
232 IdentifierNamingCheck::NamingStyle Style) {
233 static llvm::Regex Matchers[] = {
234 llvm::Regex("^.*$"),
235 llvm::Regex("^[a-z][a-z0-9_]*$"),
236 llvm::Regex("^[a-z][a-zA-Z0-9]*$"),
237 llvm::Regex("^[A-Z][A-Z0-9_]*$"),
238 llvm::Regex("^[A-Z][a-zA-Z0-9]*$"),
Kirill Bobyrev5d8f0712016-07-20 12:28:38 +0000239 llvm::Regex("^[A-Z]([a-z0-9]*(_[A-Z])?)*"),
240 llvm::Regex("^[a-z]([a-z0-9]*(_[A-Z])?)*"),
Alexander Kornienko76c28802015-08-19 11:15:36 +0000241 };
242
243 bool Matches = true;
244 if (Name.startswith(Style.Prefix))
245 Name = Name.drop_front(Style.Prefix.size());
246 else
247 Matches = false;
248
249 if (Name.endswith(Style.Suffix))
250 Name = Name.drop_back(Style.Suffix.size());
251 else
252 Matches = false;
253
254 if (!Matchers[static_cast<size_t>(Style.Case)].match(Name))
255 Matches = false;
256
257 return Matches;
258}
259
260static std::string fixupWithCase(StringRef Name,
261 IdentifierNamingCheck::CaseType Case) {
262 static llvm::Regex Splitter(
263 "([a-z0-9A-Z]*)(_+)|([A-Z]?[a-z0-9]+)([A-Z]|$)|([A-Z]+)([A-Z]|$)");
264
265 SmallVector<StringRef, 8> Substrs;
266 Name.split(Substrs, "_", -1, false);
267
268 SmallVector<StringRef, 8> Words;
269 for (auto Substr : Substrs) {
270 while (!Substr.empty()) {
271 SmallVector<StringRef, 8> Groups;
272 if (!Splitter.match(Substr, &Groups))
273 break;
274
275 if (Groups[2].size() > 0) {
276 Words.push_back(Groups[1]);
277 Substr = Substr.substr(Groups[0].size());
278 } else if (Groups[3].size() > 0) {
279 Words.push_back(Groups[3]);
280 Substr = Substr.substr(Groups[0].size() - Groups[4].size());
281 } else if (Groups[5].size() > 0) {
282 Words.push_back(Groups[5]);
283 Substr = Substr.substr(Groups[0].size() - Groups[6].size());
284 }
285 }
286 }
287
288 if (Words.empty())
289 return Name;
290
291 std::string Fixup;
292 switch (Case) {
293 case IdentifierNamingCheck::CT_AnyCase:
294 Fixup += Name;
295 break;
296
297 case IdentifierNamingCheck::CT_LowerCase:
298 for (auto const &Word : Words) {
299 if (&Word != &Words.front())
300 Fixup += "_";
301 Fixup += Word.lower();
302 }
303 break;
304
305 case IdentifierNamingCheck::CT_UpperCase:
306 for (auto const &Word : Words) {
307 if (&Word != &Words.front())
308 Fixup += "_";
309 Fixup += Word.upper();
310 }
311 break;
312
313 case IdentifierNamingCheck::CT_CamelCase:
314 for (auto const &Word : Words) {
315 Fixup += Word.substr(0, 1).upper();
316 Fixup += Word.substr(1).lower();
317 }
318 break;
319
320 case IdentifierNamingCheck::CT_CamelBack:
321 for (auto const &Word : Words) {
322 if (&Word == &Words.front()) {
323 Fixup += Word.lower();
324 } else {
325 Fixup += Word.substr(0, 1).upper();
326 Fixup += Word.substr(1).lower();
327 }
328 }
329 break;
Kirill Bobyrev5d8f0712016-07-20 12:28:38 +0000330
331 case IdentifierNamingCheck::CT_CamelSnakeCase:
332 for (auto const &Word : Words) {
333 if (&Word != &Words.front())
334 Fixup += "_";
335 Fixup += Word.substr(0, 1).upper();
336 Fixup += Word.substr(1).lower();
337 }
338 break;
339
340 case IdentifierNamingCheck::CT_CamelSnakeBack:
341 for (auto const &Word : Words) {
342 if (&Word != &Words.front()) {
343 Fixup += "_";
344 Fixup += Word.substr(0, 1).upper();
345 } else {
346 Fixup += Word.substr(0, 1).lower();
347 }
348 Fixup += Word.substr(1).lower();
349 }
350 break;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000351 }
352
353 return Fixup;
354}
355
356static std::string fixupWithStyle(StringRef Name,
357 IdentifierNamingCheck::NamingStyle Style) {
358 return Style.Prefix + fixupWithCase(Name, Style.Case) + Style.Suffix;
359}
360
361static StyleKind findStyleKind(
362 const NamedDecl *D,
363 const std::vector<IdentifierNamingCheck::NamingStyle> &NamingStyles) {
364 if (isa<TypedefDecl>(D) && NamingStyles[SK_Typedef].isSet())
365 return SK_Typedef;
366
Alexander Kornienko5ae76e02016-06-07 09:11:19 +0000367 if (isa<TypeAliasDecl>(D) && NamingStyles[SK_TypeAlias].isSet())
368 return SK_TypeAlias;
369
Alexander Kornienko76c28802015-08-19 11:15:36 +0000370 if (const auto *Decl = dyn_cast<NamespaceDecl>(D)) {
371 if (Decl->isAnonymousNamespace())
372 return SK_Invalid;
373
374 if (Decl->isInline() && NamingStyles[SK_InlineNamespace].isSet())
375 return SK_InlineNamespace;
376
377 if (NamingStyles[SK_Namespace].isSet())
378 return SK_Namespace;
379 }
380
381 if (isa<EnumDecl>(D) && NamingStyles[SK_Enum].isSet())
382 return SK_Enum;
383
384 if (isa<EnumConstantDecl>(D)) {
385 if (NamingStyles[SK_EnumConstant].isSet())
386 return SK_EnumConstant;
387
388 if (NamingStyles[SK_Constant].isSet())
389 return SK_Constant;
390
391 return SK_Invalid;
392 }
393
394 if (const auto *Decl = dyn_cast<CXXRecordDecl>(D)) {
395 if (Decl->isAnonymousStructOrUnion())
396 return SK_Invalid;
397
Jonathan Coe89f12c02016-11-03 13:52:09 +0000398 if (!Decl->getCanonicalDecl()->isThisDeclarationADefinition())
399 return SK_Invalid;
400
Alexander Kornienko76c28802015-08-19 11:15:36 +0000401 if (Decl->hasDefinition() && Decl->isAbstract() &&
402 NamingStyles[SK_AbstractClass].isSet())
403 return SK_AbstractClass;
404
405 if (Decl->isStruct() && NamingStyles[SK_Struct].isSet())
406 return SK_Struct;
407
408 if (Decl->isStruct() && NamingStyles[SK_Class].isSet())
409 return SK_Class;
410
411 if (Decl->isClass() && NamingStyles[SK_Class].isSet())
412 return SK_Class;
413
414 if (Decl->isClass() && NamingStyles[SK_Struct].isSet())
415 return SK_Struct;
416
417 if (Decl->isUnion() && NamingStyles[SK_Union].isSet())
418 return SK_Union;
419
420 if (Decl->isEnum() && NamingStyles[SK_Enum].isSet())
421 return SK_Enum;
422
423 return SK_Invalid;
424 }
425
426 if (const auto *Decl = dyn_cast<FieldDecl>(D)) {
427 QualType Type = Decl->getType();
428
429 if (!Type.isNull() && Type.isLocalConstQualified() &&
430 NamingStyles[SK_ConstantMember].isSet())
431 return SK_ConstantMember;
432
433 if (!Type.isNull() && Type.isLocalConstQualified() &&
434 NamingStyles[SK_Constant].isSet())
435 return SK_Constant;
436
437 if (Decl->getAccess() == AS_private &&
438 NamingStyles[SK_PrivateMember].isSet())
439 return SK_PrivateMember;
440
441 if (Decl->getAccess() == AS_protected &&
442 NamingStyles[SK_ProtectedMember].isSet())
443 return SK_ProtectedMember;
444
445 if (Decl->getAccess() == AS_public && NamingStyles[SK_PublicMember].isSet())
446 return SK_PublicMember;
447
448 if (NamingStyles[SK_Member].isSet())
449 return SK_Member;
450
451 return SK_Invalid;
452 }
453
454 if (const auto *Decl = dyn_cast<ParmVarDecl>(D)) {
455 QualType Type = Decl->getType();
456
457 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprVariable].isSet())
458 return SK_ConstexprVariable;
459
460 if (!Type.isNull() && Type.isLocalConstQualified() &&
461 NamingStyles[SK_ConstantParameter].isSet())
462 return SK_ConstantParameter;
463
464 if (!Type.isNull() && Type.isLocalConstQualified() &&
465 NamingStyles[SK_Constant].isSet())
466 return SK_Constant;
467
468 if (Decl->isParameterPack() && NamingStyles[SK_ParameterPack].isSet())
469 return SK_ParameterPack;
470
471 if (NamingStyles[SK_Parameter].isSet())
472 return SK_Parameter;
473
474 return SK_Invalid;
475 }
476
477 if (const auto *Decl = dyn_cast<VarDecl>(D)) {
478 QualType Type = Decl->getType();
479
480 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprVariable].isSet())
481 return SK_ConstexprVariable;
482
483 if (!Type.isNull() && Type.isLocalConstQualified() &&
484 Decl->isStaticDataMember() && NamingStyles[SK_ClassConstant].isSet())
485 return SK_ClassConstant;
486
487 if (!Type.isNull() && Type.isLocalConstQualified() &&
488 Decl->isFileVarDecl() && NamingStyles[SK_GlobalConstant].isSet())
489 return SK_GlobalConstant;
490
491 if (!Type.isNull() && Type.isLocalConstQualified() &&
492 Decl->isStaticLocal() && NamingStyles[SK_StaticConstant].isSet())
493 return SK_StaticConstant;
494
495 if (!Type.isNull() && Type.isLocalConstQualified() &&
496 Decl->isLocalVarDecl() && NamingStyles[SK_LocalConstant].isSet())
497 return SK_LocalConstant;
498
499 if (!Type.isNull() && Type.isLocalConstQualified() &&
500 Decl->isFunctionOrMethodVarDecl() &&
501 NamingStyles[SK_LocalConstant].isSet())
502 return SK_LocalConstant;
503
504 if (!Type.isNull() && Type.isLocalConstQualified() &&
505 NamingStyles[SK_Constant].isSet())
506 return SK_Constant;
507
508 if (Decl->isStaticDataMember() && NamingStyles[SK_ClassMember].isSet())
509 return SK_ClassMember;
510
511 if (Decl->isFileVarDecl() && NamingStyles[SK_GlobalVariable].isSet())
512 return SK_GlobalVariable;
513
514 if (Decl->isStaticLocal() && NamingStyles[SK_StaticVariable].isSet())
515 return SK_StaticVariable;
516
517 if (Decl->isLocalVarDecl() && NamingStyles[SK_LocalVariable].isSet())
518 return SK_LocalVariable;
519
520 if (Decl->isFunctionOrMethodVarDecl() &&
521 NamingStyles[SK_LocalVariable].isSet())
522 return SK_LocalVariable;
523
524 if (NamingStyles[SK_Variable].isSet())
525 return SK_Variable;
526
527 return SK_Invalid;
528 }
529
530 if (const auto *Decl = dyn_cast<CXXMethodDecl>(D)) {
531 if (Decl->isMain() || !Decl->isUserProvided() ||
532 Decl->isUsualDeallocationFunction() ||
533 Decl->isCopyAssignmentOperator() || Decl->isMoveAssignmentOperator() ||
534 Decl->size_overridden_methods() > 0)
535 return SK_Invalid;
536
537 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprMethod].isSet())
538 return SK_ConstexprMethod;
539
540 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprFunction].isSet())
541 return SK_ConstexprFunction;
542
543 if (Decl->isStatic() && NamingStyles[SK_ClassMethod].isSet())
544 return SK_ClassMethod;
545
546 if (Decl->isVirtual() && NamingStyles[SK_VirtualMethod].isSet())
547 return SK_VirtualMethod;
548
549 if (Decl->getAccess() == AS_private &&
550 NamingStyles[SK_PrivateMethod].isSet())
551 return SK_PrivateMethod;
552
553 if (Decl->getAccess() == AS_protected &&
554 NamingStyles[SK_ProtectedMethod].isSet())
555 return SK_ProtectedMethod;
556
557 if (Decl->getAccess() == AS_public && NamingStyles[SK_PublicMethod].isSet())
558 return SK_PublicMethod;
559
560 if (NamingStyles[SK_Method].isSet())
561 return SK_Method;
562
563 if (NamingStyles[SK_Function].isSet())
564 return SK_Function;
565
566 return SK_Invalid;
567 }
568
569 if (const auto *Decl = dyn_cast<FunctionDecl>(D)) {
570 if (Decl->isMain())
571 return SK_Invalid;
572
573 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprFunction].isSet())
574 return SK_ConstexprFunction;
575
576 if (Decl->isGlobal() && NamingStyles[SK_GlobalFunction].isSet())
577 return SK_GlobalFunction;
578
579 if (NamingStyles[SK_Function].isSet())
580 return SK_Function;
581 }
582
583 if (isa<TemplateTypeParmDecl>(D)) {
584 if (NamingStyles[SK_TypeTemplateParameter].isSet())
585 return SK_TypeTemplateParameter;
586
587 if (NamingStyles[SK_TemplateParameter].isSet())
588 return SK_TemplateParameter;
589
590 return SK_Invalid;
591 }
592
593 if (isa<NonTypeTemplateParmDecl>(D)) {
594 if (NamingStyles[SK_ValueTemplateParameter].isSet())
595 return SK_ValueTemplateParameter;
596
597 if (NamingStyles[SK_TemplateParameter].isSet())
598 return SK_TemplateParameter;
599
600 return SK_Invalid;
601 }
602
603 if (isa<TemplateTemplateParmDecl>(D)) {
604 if (NamingStyles[SK_TemplateTemplateParameter].isSet())
605 return SK_TemplateTemplateParameter;
606
607 if (NamingStyles[SK_TemplateParameter].isSet())
608 return SK_TemplateParameter;
609
610 return SK_Invalid;
611 }
612
613 return SK_Invalid;
614}
615
Alexander Kornienko3d777682015-09-28 08:59:12 +0000616static void addUsage(IdentifierNamingCheck::NamingCheckFailureMap &Failures,
Alexander Kornienko21503902016-06-17 09:25:24 +0000617 const IdentifierNamingCheck::NamingCheckId &Decl,
Jason Henline481e6aa2016-10-24 17:20:32 +0000618 SourceRange Range, SourceManager *SourceMgr = nullptr) {
Jonathan Coe2c8592a2016-01-26 18:55:55 +0000619 // Do nothing if the provided range is invalid.
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000620 if (Range.getBegin().isInvalid() || Range.getEnd().isInvalid())
621 return;
622
Jason Henline481e6aa2016-10-24 17:20:32 +0000623 // If we have a source manager, use it to convert to the spelling location for
624 // performing the fix. This is necessary because macros can map the same
625 // spelling location to different source locations, and we only want to fix
626 // the token once, before it is expanded by the macro.
627 SourceLocation FixLocation = Range.getBegin();
628 if (SourceMgr)
629 FixLocation = SourceMgr->getSpellingLoc(FixLocation);
630 if (FixLocation.isInvalid())
631 return;
632
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000633 // Try to insert the identifier location in the Usages map, and bail out if it
634 // is already in there
Alexander Kornienko3d777682015-09-28 08:59:12 +0000635 auto &Failure = Failures[Decl];
Jason Henline481e6aa2016-10-24 17:20:32 +0000636 if (!Failure.RawUsageLocs.insert(FixLocation.getRawEncoding()).second)
Alexander Kornienko3d777682015-09-28 08:59:12 +0000637 return;
638
Jason Henline481e6aa2016-10-24 17:20:32 +0000639 if (!Failure.ShouldFix)
640 return;
641
642 // Check if the range is entirely contained within a macro argument.
643 SourceLocation MacroArgExpansionStartForRangeBegin;
644 SourceLocation MacroArgExpansionStartForRangeEnd;
645 bool RangeIsEntirelyWithinMacroArgument =
646 SourceMgr &&
647 SourceMgr->isMacroArgExpansion(Range.getBegin(),
648 &MacroArgExpansionStartForRangeBegin) &&
649 SourceMgr->isMacroArgExpansion(Range.getEnd(),
650 &MacroArgExpansionStartForRangeEnd) &&
651 MacroArgExpansionStartForRangeBegin == MacroArgExpansionStartForRangeEnd;
652
653 // Check if the range contains any locations from a macro expansion.
654 bool RangeContainsMacroExpansion = RangeIsEntirelyWithinMacroArgument ||
655 Range.getBegin().isMacroID() ||
656 Range.getEnd().isMacroID();
657
658 bool RangeCanBeFixed =
659 RangeIsEntirelyWithinMacroArgument || !RangeContainsMacroExpansion;
660 Failure.ShouldFix = RangeCanBeFixed;
Alexander Kornienko3d777682015-09-28 08:59:12 +0000661}
662
Alexander Kornienko21503902016-06-17 09:25:24 +0000663/// Convenience method when the usage to be added is a NamedDecl
664static void addUsage(IdentifierNamingCheck::NamingCheckFailureMap &Failures,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000665 const NamedDecl *Decl, SourceRange Range,
666 SourceManager *SourceMgr = nullptr) {
Alexander Kornienko21503902016-06-17 09:25:24 +0000667 return addUsage(Failures, IdentifierNamingCheck::NamingCheckId(
668 Decl->getLocation(), Decl->getNameAsString()),
Jason Henline481e6aa2016-10-24 17:20:32 +0000669 Range, SourceMgr);
Alexander Kornienko21503902016-06-17 09:25:24 +0000670}
671
Alexander Kornienko76c28802015-08-19 11:15:36 +0000672void IdentifierNamingCheck::check(const MatchFinder::MatchResult &Result) {
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000673 if (const auto *Decl =
674 Result.Nodes.getNodeAs<CXXConstructorDecl>("classRef")) {
675 if (Decl->isImplicit())
676 return;
677
678 addUsage(NamingCheckFailures, Decl->getParent(),
Alexander Kornienko21503902016-06-17 09:25:24 +0000679 Decl->getNameInfo().getSourceRange());
Eric Fiselier732a3e02016-11-16 21:15:58 +0000680
681 for (const auto *Init : Decl->inits()) {
682 if (!Init->isWritten() || Init->isInClassMemberInitializer())
683 continue;
684 if (const auto *FD = Init->getAnyMember())
685 addUsage(NamingCheckFailures, FD, SourceRange(Init->getMemberLocation()));
686 // Note: delegating constructors and base class initializers are handled
687 // via the "typeLoc" matcher.
688 }
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000689 return;
690 }
691
692 if (const auto *Decl =
693 Result.Nodes.getNodeAs<CXXDestructorDecl>("classRef")) {
694 if (Decl->isImplicit())
695 return;
696
697 SourceRange Range = Decl->getNameInfo().getSourceRange();
698 if (Range.getBegin().isInvalid())
699 return;
700 // The first token that will be found is the ~ (or the equivalent trigraph),
701 // we want instead to replace the next token, that will be the identifier.
702 Range.setBegin(CharSourceRange::getTokenRange(Range).getEnd());
703
Alexander Kornienko21503902016-06-17 09:25:24 +0000704 addUsage(NamingCheckFailures, Decl->getParent(), Range);
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000705 return;
706 }
707
708 if (const auto *Loc = Result.Nodes.getNodeAs<TypeLoc>("typeLoc")) {
709 NamedDecl *Decl = nullptr;
710 if (const auto &Ref = Loc->getAs<TagTypeLoc>()) {
711 Decl = Ref.getDecl();
712 } else if (const auto &Ref = Loc->getAs<InjectedClassNameTypeLoc>()) {
713 Decl = Ref.getDecl();
714 } else if (const auto &Ref = Loc->getAs<UnresolvedUsingTypeLoc>()) {
715 Decl = Ref.getDecl();
716 } else if (const auto &Ref = Loc->getAs<TemplateTypeParmTypeLoc>()) {
717 Decl = Ref.getDecl();
718 }
719
720 if (Decl) {
Alexander Kornienko21503902016-06-17 09:25:24 +0000721 addUsage(NamingCheckFailures, Decl, Loc->getSourceRange());
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000722 return;
723 }
724
725 if (const auto &Ref = Loc->getAs<TemplateSpecializationTypeLoc>()) {
726 const auto *Decl =
727 Ref.getTypePtr()->getTemplateName().getAsTemplateDecl();
728
729 SourceRange Range(Ref.getTemplateNameLoc(), Ref.getTemplateNameLoc());
730 if (const auto *ClassDecl = dyn_cast<TemplateDecl>(Decl)) {
Matthias Gehrea9e812b2016-07-09 20:09:28 +0000731 if (const auto *TemplDecl = ClassDecl->getTemplatedDecl())
732 addUsage(NamingCheckFailures, TemplDecl, Range);
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000733 return;
734 }
735 }
736
737 if (const auto &Ref =
738 Loc->getAs<DependentTemplateSpecializationTypeLoc>()) {
Matthias Gehrea9e812b2016-07-09 20:09:28 +0000739 if (const auto *Decl = Ref.getTypePtr()->getAsTagDecl())
740 addUsage(NamingCheckFailures, Decl, Loc->getSourceRange());
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000741 return;
742 }
743 }
744
745 if (const auto *Loc =
746 Result.Nodes.getNodeAs<NestedNameSpecifierLoc>("nestedNameLoc")) {
747 if (NestedNameSpecifier *Spec = Loc->getNestedNameSpecifier()) {
748 if (NamespaceDecl *Decl = Spec->getAsNamespace()) {
Alexander Kornienko21503902016-06-17 09:25:24 +0000749 addUsage(NamingCheckFailures, Decl, Loc->getLocalSourceRange());
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000750 return;
751 }
752 }
753 }
754
755 if (const auto *Decl = Result.Nodes.getNodeAs<UsingDecl>("using")) {
756 for (const auto &Shadow : Decl->shadows()) {
757 addUsage(NamingCheckFailures, Shadow->getTargetDecl(),
Alexander Kornienko21503902016-06-17 09:25:24 +0000758 Decl->getNameInfo().getSourceRange());
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000759 }
760 return;
761 }
762
763 if (const auto *DeclRef = Result.Nodes.getNodeAs<DeclRefExpr>("declRef")) {
Alexander Kornienko76c28802015-08-19 11:15:36 +0000764 SourceRange Range = DeclRef->getNameInfo().getSourceRange();
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000765 addUsage(NamingCheckFailures, DeclRef->getDecl(), Range,
766 Result.SourceManager);
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000767 return;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000768 }
769
770 if (const auto *Decl = Result.Nodes.getNodeAs<NamedDecl>("decl")) {
771 if (!Decl->getIdentifier() || Decl->getName().empty() || Decl->isImplicit())
772 return;
773
Alexander Kornienko21503902016-06-17 09:25:24 +0000774 // Fix type aliases in value declarations
775 if (const auto *Value = Result.Nodes.getNodeAs<ValueDecl>("decl")) {
776 if (const auto *Typedef =
777 Value->getType().getTypePtr()->getAs<TypedefType>()) {
778 addUsage(NamingCheckFailures, Typedef->getDecl(),
779 Value->getSourceRange());
780 }
781 }
782
783 // Fix type aliases in function declarations
784 if (const auto *Value = Result.Nodes.getNodeAs<FunctionDecl>("decl")) {
785 if (const auto *Typedef =
786 Value->getReturnType().getTypePtr()->getAs<TypedefType>()) {
787 addUsage(NamingCheckFailures, Typedef->getDecl(),
788 Value->getSourceRange());
789 }
790 for (unsigned i = 0; i < Value->getNumParams(); ++i) {
791 if (const auto *Typedef = Value->parameters()[i]
792 ->getType()
793 .getTypePtr()
794 ->getAs<TypedefType>()) {
795 addUsage(NamingCheckFailures, Typedef->getDecl(),
796 Value->getSourceRange());
797 }
798 }
799 }
800
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000801 // Ignore ClassTemplateSpecializationDecl which are creating duplicate
802 // replacements with CXXRecordDecl
803 if (isa<ClassTemplateSpecializationDecl>(Decl))
804 return;
805
Alexander Kornienko76c28802015-08-19 11:15:36 +0000806 StyleKind SK = findStyleKind(Decl, NamingStyles);
807 if (SK == SK_Invalid)
808 return;
809
810 NamingStyle Style = NamingStyles[SK];
811 StringRef Name = Decl->getName();
812 if (matchesStyle(Name, Style))
813 return;
814
815 std::string KindName = fixupWithCase(StyleNames[SK], CT_LowerCase);
816 std::replace(KindName.begin(), KindName.end(), '_', ' ');
817
818 std::string Fixup = fixupWithStyle(Name, Style);
819 if (StringRef(Fixup).equals(Name)) {
820 if (!IgnoreFailedSplit) {
Hans Wennborg53bd9f32016-02-29 21:17:39 +0000821 DEBUG(llvm::dbgs()
822 << Decl->getLocStart().printToString(*Result.SourceManager)
823 << llvm::format(": unable to split words for %s '%s'\n",
Mehdi Amini9ff8e872016-10-07 08:25:42 +0000824 KindName.c_str(), Name.str().c_str()));
Alexander Kornienko76c28802015-08-19 11:15:36 +0000825 }
826 } else {
Alexander Kornienko21503902016-06-17 09:25:24 +0000827 NamingCheckFailure &Failure = NamingCheckFailures[NamingCheckId(
828 Decl->getLocation(), Decl->getNameAsString())];
Alexander Kornienko76c28802015-08-19 11:15:36 +0000829 SourceRange Range =
830 DeclarationNameInfo(Decl->getDeclName(), Decl->getLocation())
831 .getSourceRange();
832
833 Failure.Fixup = std::move(Fixup);
834 Failure.KindName = std::move(KindName);
Alexander Kornienko21503902016-06-17 09:25:24 +0000835 addUsage(NamingCheckFailures, Decl, Range);
Alexander Kornienko76c28802015-08-19 11:15:36 +0000836 }
837 }
838}
839
Alexander Kornienko21503902016-06-17 09:25:24 +0000840void IdentifierNamingCheck::checkMacro(SourceManager &SourceMgr,
841 const Token &MacroNameTok,
842 const MacroInfo *MI) {
843 StringRef Name = MacroNameTok.getIdentifierInfo()->getName();
844 NamingStyle Style = NamingStyles[SK_MacroDefinition];
845 if (matchesStyle(Name, Style))
846 return;
847
848 std::string KindName =
849 fixupWithCase(StyleNames[SK_MacroDefinition], CT_LowerCase);
850 std::replace(KindName.begin(), KindName.end(), '_', ' ');
851
852 std::string Fixup = fixupWithStyle(Name, Style);
853 if (StringRef(Fixup).equals(Name)) {
854 if (!IgnoreFailedSplit) {
855 DEBUG(
856 llvm::dbgs() << MacroNameTok.getLocation().printToString(SourceMgr)
857 << llvm::format(": unable to split words for %s '%s'\n",
Mehdi Amini9ff8e872016-10-07 08:25:42 +0000858 KindName.c_str(), Name.str().c_str()));
Alexander Kornienko21503902016-06-17 09:25:24 +0000859 }
860 } else {
861 NamingCheckId ID(MI->getDefinitionLoc(), Name);
862 NamingCheckFailure &Failure = NamingCheckFailures[ID];
863 SourceRange Range(MacroNameTok.getLocation(), MacroNameTok.getEndLoc());
864
865 Failure.Fixup = std::move(Fixup);
866 Failure.KindName = std::move(KindName);
867 addUsage(NamingCheckFailures, ID, Range);
868 }
869}
870
871void IdentifierNamingCheck::expandMacro(const Token &MacroNameTok,
872 const MacroInfo *MI) {
873 StringRef Name = MacroNameTok.getIdentifierInfo()->getName();
874 NamingCheckId ID(MI->getDefinitionLoc(), Name);
875
876 auto Failure = NamingCheckFailures.find(ID);
877 if (Failure == NamingCheckFailures.end())
878 return;
879
880 SourceRange Range(MacroNameTok.getLocation(), MacroNameTok.getEndLoc());
881 addUsage(NamingCheckFailures, ID, Range);
882}
883
Alexander Kornienko76c28802015-08-19 11:15:36 +0000884void IdentifierNamingCheck::onEndOfTranslationUnit() {
885 for (const auto &Pair : NamingCheckFailures) {
Alexander Kornienko21503902016-06-17 09:25:24 +0000886 const NamingCheckId &Decl = Pair.first;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000887 const NamingCheckFailure &Failure = Pair.second;
888
Alexander Kornienko3d777682015-09-28 08:59:12 +0000889 if (Failure.KindName.empty())
890 continue;
891
Alexander Kornienko76c28802015-08-19 11:15:36 +0000892 if (Failure.ShouldFix) {
Alexander Kornienko21503902016-06-17 09:25:24 +0000893 auto Diag = diag(Decl.first, "invalid case style for %0 '%1'")
894 << Failure.KindName << Decl.second;
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000895
Alexander Kornienko3d777682015-09-28 08:59:12 +0000896 for (const auto &Loc : Failure.RawUsageLocs) {
897 // We assume that the identifier name is made of one token only. This is
898 // always the case as we ignore usages in macros that could build
899 // identifier names by combining multiple tokens.
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000900 //
901 // For destructors, we alread take care of it by remembering the
902 // location of the start of the identifier and not the start of the
903 // tilde.
904 //
905 // Other multi-token identifiers, such as operators are not checked at
906 // all.
Alexander Kornienko76c28802015-08-19 11:15:36 +0000907 Diag << FixItHint::CreateReplacement(
Alexander Kornienko3d777682015-09-28 08:59:12 +0000908 SourceRange(SourceLocation::getFromRawEncoding(Loc)),
909 Failure.Fixup);
Alexander Kornienko76c28802015-08-19 11:15:36 +0000910 }
911 }
912 }
913}
914
915} // namespace readability
916} // namespace tidy
917} // namespace clang