clang-tools 8.0.0

IdentifierNamingCheck.cpp
Go to the documentation of this file.
1 //===--- 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
12 #include "../utils/ASTUtils.h"
13 #include "clang/ASTMatchers/ASTMatchFinder.h"
14 #include "clang/Frontend/CompilerInstance.h"
15 #include "clang/Lex/PPCallbacks.h"
16 #include "clang/Lex/Preprocessor.h"
17 #include "llvm/ADT/DenseMapInfo.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/Support/Format.h"
20
21 #define DEBUG_TYPE "clang-tidy"
22
23 using namespace clang::ast_matchers;
24
25 namespace llvm {
26 /// Specialisation of DenseMapInfo to allow NamingCheckId objects in DenseMaps
27 template <>
28 struct 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
53 static bool isEqual(const NamingCheckId &LHS, const NamingCheckId &RHS) {
54 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
63 namespace clang {
64 namespace tidy {
65 namespace readability {
66
67 // clang-format off
68 #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) \
81 m(GlobalConstantPointer) \
82 m(GlobalPointer) \
83 m(GlobalVariable) \
84 m(LocalConstant) \
85 m(LocalConstantPointer) \
86 m(LocalPointer) \
87 m(LocalVariable) \
88 m(StaticConstant) \
89 m(StaticVariable) \
90 m(Constant) \
91 m(Variable) \
92 m(ConstantParameter) \
93 m(ParameterPack) \
94 m(Parameter) \
95 m(PointerParameter) \
96 m(ConstantPointerParameter) \
97 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) \
117 m(TypeAlias) \
118 m(MacroDefinition) \
119 m(ObjcIvar) \
120
121 enum StyleKind {
122 #define ENUMERATE(v) SK_ ## v,
123 NAMING_KEYS(ENUMERATE)
124 #undef ENUMERATE
125 SK_Count,
126 SK_Invalid
127 };
128
129 static StringRef const StyleNames[] = {
130 #define STRINGIZE(v) #v,
131 NAMING_KEYS(STRINGIZE)
132 #undef STRINGIZE
133 };
134
135 #undef NAMING_KEYS
136 // clang-format on
137
138 namespace {
139 /// Callback supplies macros to IdentifierNamingCheck::checkMacro
140 class IdentifierNamingCheckPPCallbacks : public PPCallbacks {
141 public:
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
159 private:
160 Preprocessor *PP;
161 IdentifierNamingCheck *Check;
162 };
163 } // namespace
164
165 IdentifierNamingCheck::IdentifierNamingCheck(StringRef Name,
166 ClangTidyContext *Context)
167 : ClangTidyCheck(Name, Context) {
168 auto const fromString = [](StringRef Str) {
169 return llvm::StringSwitch<llvm::Optional<CaseType>>(Str)
170 .Case("aNy_CasE", CT_AnyCase)
171 .Case("lower_case", CT_LowerCase)
172 .Case("UPPER_CASE", CT_UpperCase)
173 .Case("camelBack", CT_CamelBack)
174 .Case("CamelCase", CT_CamelCase)
175 .Case("Camel_Snake_Case", CT_CamelSnakeCase)
176 .Case("camel_Snake_Back", CT_CamelSnakeBack)
177 .Default(llvm::None);
178 };
179
180 for (auto const &Name : StyleNames) {
181 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 }
191 }
192
193 IgnoreFailedSplit = Options.get("IgnoreFailedSplit", 0);
194 }
195
196 void 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";
209 case CT_CamelSnakeCase:
210 return "Camel_Snake_Case";
211 case CT_CamelSnakeBack:
212 return "camel_Snake_Back";
213 }
214
215 llvm_unreachable("Unknown Case Type");
216 };
217
218 for (size_t i = 0; i < SK_Count; ++i) {
219 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 }
229 }
230
231 Options.store(Opts, "IgnoreFailedSplit", IgnoreFailedSplit);
232 }
233
234 void IdentifierNamingCheck::registerMatchers(MatchFinder *Finder) {
235 Finder->addMatcher(namedDecl().bind("decl"), this);
236 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);
242 }
243
244 void IdentifierNamingCheck::registerPPCallbacks(CompilerInstance &Compiler) {
245 Compiler.getPreprocessor().addPPCallbacks(
246 llvm::make_unique<IdentifierNamingCheckPPCallbacks>(
247 &Compiler.getPreprocessor(), this));
248 }
249
250 static 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]*$"),
258 llvm::Regex("^[A-Z]([a-z0-9]*(_[A-Z])?)*"),
259 llvm::Regex("^[a-z]([a-z0-9]*(_[A-Z])?)*"),
260 };
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
273 // 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
278 if (Style.Case && !Matchers[static_cast<size_t>(*Style.Case)].match(Name))
279 Matches = false;
280
281 return Matches;
282 }
283
284 static 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;
354
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;
375 }
376
377 return Fixup;
378 }
379
380 static std::string
381 fixupWithStyle(StringRef Name,
382 const IdentifierNamingCheck::NamingStyle &Style) {
383 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();
389 }
390
391 static StyleKind findStyleKind(
392 const NamedDecl *D,
393 const std::vector<llvm::Optional<IdentifierNamingCheck::NamingStyle>>
394 &NamingStyles) {
395 assert(D && D->getIdentifier() && !D->getName().empty() && !D->isImplicit() &&
396 "Decl must be an explicit identifier with a name.");
397
398 if (isa<ObjCIvarDecl>(D) && NamingStyles[SK_ObjcIvar])
399 return SK_ObjcIvar;
400
401 if (isa<TypedefDecl>(D) && NamingStyles[SK_Typedef])
402 return SK_Typedef;
403
404 if (isa<TypeAliasDecl>(D) && NamingStyles[SK_TypeAlias])
405 return SK_TypeAlias;
406
407 if (const auto *Decl = dyn_cast<NamespaceDecl>(D)) {
408 if (Decl->isAnonymousNamespace())
409 return SK_Invalid;
410
411 if (Decl->isInline() && NamingStyles[SK_InlineNamespace])
412 return SK_InlineNamespace;
413
414 if (NamingStyles[SK_Namespace])
415 return SK_Namespace;
416 }
417
418 if (isa<EnumDecl>(D) && NamingStyles[SK_Enum])
419 return SK_Enum;
420
421 if (isa<EnumConstantDecl>(D)) {
422 if (NamingStyles[SK_EnumConstant])
423 return SK_EnumConstant;
424
425 if (NamingStyles[SK_Constant])
426 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
435 if (!Decl->getCanonicalDecl()->isThisDeclarationADefinition())
436 return SK_Invalid;
437
438 if (Decl->hasDefinition() && Decl->isAbstract() &&
439 NamingStyles[SK_AbstractClass])
440 return SK_AbstractClass;
441
442 if (Decl->isStruct() && NamingStyles[SK_Struct])
443 return SK_Struct;
444
445 if (Decl->isStruct() && NamingStyles[SK_Class])
446 return SK_Class;
447
448 if (Decl->isClass() && NamingStyles[SK_Class])
449 return SK_Class;
450
451 if (Decl->isClass() && NamingStyles[SK_Struct])
452 return SK_Struct;
453
454 if (Decl->isUnion() && NamingStyles[SK_Union])
455 return SK_Union;
456
457 if (Decl->isEnum() && NamingStyles[SK_Enum])
458 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
466 if (!Type.isNull() && Type.isConstQualified()) {
467 if (NamingStyles[SK_ConstantMember])
468 return SK_ConstantMember;
469
470 if (NamingStyles[SK_Constant])
471 return SK_Constant;
472 }
473
474 if (Decl->getAccess() == AS_private && NamingStyles[SK_PrivateMember])
475 return SK_PrivateMember;
476
477 if (Decl->getAccess() == AS_protected && NamingStyles[SK_ProtectedMember])
478 return SK_ProtectedMember;
479
480 if (Decl->getAccess() == AS_public && NamingStyles[SK_PublicMember])
481 return SK_PublicMember;
482
483 if (NamingStyles[SK_Member])
484 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
492 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprVariable])
493 return SK_ConstexprVariable;
494
495 if (!Type.isNull() && Type.isConstQualified()) {
496 if (Type.getTypePtr()->isAnyPointerType() && NamingStyles[SK_ConstantPointerParameter])
497 return SK_ConstantPointerParameter;
498
499 if (NamingStyles[SK_ConstantParameter])
500 return SK_ConstantParameter;
501
502 if (NamingStyles[SK_Constant])
503 return SK_Constant;
504 }
505
506 if (Decl->isParameterPack() && NamingStyles[SK_ParameterPack])
507 return SK_ParameterPack;
508
509 if (!Type.isNull() && Type.getTypePtr()->isAnyPointerType() && NamingStyles[SK_PointerParameter])
510 return SK_PointerParameter;
511
512 if (NamingStyles[SK_Parameter])
513 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
521 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprVariable])
522 return SK_ConstexprVariable;
523
524 if (!Type.isNull() && Type.isConstQualified()) {
525 if (Decl->isStaticDataMember() && NamingStyles[SK_ClassConstant])
526 return SK_ClassConstant;
527
528 if (Decl->isFileVarDecl() && Type.getTypePtr()->isAnyPointerType() && NamingStyles[SK_GlobalConstantPointer])
529 return SK_GlobalConstantPointer;
530
531 if (Decl->isFileVarDecl() && NamingStyles[SK_GlobalConstant])
532 return SK_GlobalConstant;
533
534 if (Decl->isStaticLocal() && NamingStyles[SK_StaticConstant])
535 return SK_StaticConstant;
536
537 if (Decl->isLocalVarDecl() && Type.getTypePtr()->isAnyPointerType() && NamingStyles[SK_LocalConstantPointer])
538 return SK_LocalConstantPointer;
539
540 if (Decl->isLocalVarDecl() && NamingStyles[SK_LocalConstant])
541 return SK_LocalConstant;
542
543 if (Decl->isFunctionOrMethodVarDecl() && NamingStyles[SK_LocalConstant])
544 return SK_LocalConstant;
545
546 if (NamingStyles[SK_Constant])
547 return SK_Constant;
548 }
549
550 if (Decl->isStaticDataMember() && NamingStyles[SK_ClassMember])
551 return SK_ClassMember;
552
553 if (Decl->isFileVarDecl() && Type.getTypePtr()->isAnyPointerType() && NamingStyles[SK_GlobalPointer])
554 return SK_GlobalPointer;
555
556 if (Decl->isFileVarDecl() && NamingStyles[SK_GlobalVariable])
557 return SK_GlobalVariable;
558
559 if (Decl->isStaticLocal() && NamingStyles[SK_StaticVariable])
560 return SK_StaticVariable;
561
562 if (Decl->isLocalVarDecl() && Type.getTypePtr()->isAnyPointerType() && NamingStyles[SK_LocalPointer])
563 return SK_LocalPointer;
564
565 if (Decl->isLocalVarDecl() && NamingStyles[SK_LocalVariable])
566 return SK_LocalVariable;
567
568 if (Decl->isFunctionOrMethodVarDecl() && NamingStyles[SK_LocalVariable])
569 return SK_LocalVariable;
570
571 if (NamingStyles[SK_Variable])
572 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() ||
579 Decl->size_overridden_methods() > 0)
580 return SK_Invalid;
581
582 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprMethod])
583 return SK_ConstexprMethod;
584
585 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprFunction])
586 return SK_ConstexprFunction;
587
588 if (Decl->isStatic() && NamingStyles[SK_ClassMethod])
589 return SK_ClassMethod;
590
591 if (Decl->isVirtual() && NamingStyles[SK_VirtualMethod])
592 return SK_VirtualMethod;
593
594 if (Decl->getAccess() == AS_private && NamingStyles[SK_PrivateMethod])
595 return SK_PrivateMethod;
596
597 if (Decl->getAccess() == AS_protected && NamingStyles[SK_ProtectedMethod])
598 return SK_ProtectedMethod;
599
600 if (Decl->getAccess() == AS_public && NamingStyles[SK_PublicMethod])
601 return SK_PublicMethod;
602
603 if (NamingStyles[SK_Method])
604 return SK_Method;
605
606 if (NamingStyles[SK_Function])
607 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
616 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprFunction])
617 return SK_ConstexprFunction;
618
619 if (Decl->isGlobal() && NamingStyles[SK_GlobalFunction])
620 return SK_GlobalFunction;
621
622 if (NamingStyles[SK_Function])
623 return SK_Function;
624 }
625
626 if (isa<TemplateTypeParmDecl>(D)) {
627 if (NamingStyles[SK_TypeTemplateParameter])
628 return SK_TypeTemplateParameter;
629
630 if (NamingStyles[SK_TemplateParameter])
631 return SK_TemplateParameter;
632
633 return SK_Invalid;
634 }
635
636 if (isa<NonTypeTemplateParmDecl>(D)) {
637 if (NamingStyles[SK_ValueTemplateParameter])
638 return SK_ValueTemplateParameter;
639
640 if (NamingStyles[SK_TemplateParameter])
641 return SK_TemplateParameter;
642
643 return SK_Invalid;
644 }
645
646 if (isa<TemplateTemplateParmDecl>(D)) {
647 if (NamingStyles[SK_TemplateTemplateParameter])
648 return SK_TemplateTemplateParameter;
649
650 if (NamingStyles[SK_TemplateParameter])
651 return SK_TemplateParameter;
652
653 return SK_Invalid;
654 }
655
656 return SK_Invalid;
657 }
658
659 static void addUsage(IdentifierNamingCheck::NamingCheckFailureMap &Failures,
660 const IdentifierNamingCheck::NamingCheckId &Decl,
661 SourceRange Range, SourceManager *SourceMgr = nullptr) {
662 // Do nothing if the provided range is invalid.
663 if (Range.getBegin().isInvalid() || Range.getEnd().isInvalid())
664 return;
665
666 // 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
676 // Try to insert the identifier location in the Usages map, and bail out if it
677 // is already in there
678 auto &Failure = Failures[Decl];
679 if (!Failure.RawUsageLocs.insert(FixLocation.getRawEncoding()).second)
680 return;
681
682 if (!Failure.ShouldFix)
683 return;
684
685 Failure.ShouldFix = utils::rangeCanBeFixed(Range, SourceMgr);
686 }
687
688 /// Convenience method when the usage to be added is a NamedDecl
689 static void addUsage(IdentifierNamingCheck::NamingCheckFailureMap &Failures,
690 const NamedDecl *Decl, SourceRange Range,
691 SourceManager *SourceMgr = nullptr) {
692 return addUsage(Failures,
693 IdentifierNamingCheck::NamingCheckId(Decl->getLocation(),
694 Decl->getNameAsString()),
695 Range, SourceMgr);
696 }
697
698 void IdentifierNamingCheck::check(const MatchFinder::MatchResult &Result) {
699 if (const auto *Decl =
700 Result.Nodes.getNodeAs<CXXConstructorDecl>("classRef")) {
701 if (Decl->isImplicit())
702 return;
703
704 addUsage(NamingCheckFailures, Decl->getParent(),
705 Decl->getNameInfo().getSourceRange());
706
707 for (const auto *Init : Decl->inits()) {
708 if (!Init->isWritten() || Init->isInClassMemberInitializer())
709 continue;
710 if (const auto *FD = Init->getAnyMember())
711 addUsage(NamingCheckFailures, FD,
712 SourceRange(Init->getMemberLocation()));
713 // Note: delegating constructors and base class initializers are handled
714 // via the "typeLoc" matcher.
715 }
716 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
731 addUsage(NamingCheckFailures, Decl->getParent(), Range);
732 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) {
748 addUsage(NamingCheckFailures, Decl, Loc->getSourceRange());
749 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)) {
758 if (const auto *TemplDecl = ClassDecl->getTemplatedDecl())
759 addUsage(NamingCheckFailures, TemplDecl, Range);
760 return;
761 }
762 }
763
764 if (const auto &Ref =
765 Loc->getAs<DependentTemplateSpecializationTypeLoc>()) {
766 if (const auto *Decl = Ref.getTypePtr()->getAsTagDecl())
767 addUsage(NamingCheckFailures, Decl, Loc->getSourceRange());
768 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()) {
776 addUsage(NamingCheckFailures, Decl, Loc->getLocalSourceRange());
777 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(),
785 Decl->getNameInfo().getSourceRange());
786 }
787 return;
788 }
789
790 if (const auto *DeclRef = Result.Nodes.getNodeAs<DeclRefExpr>("declRef")) {
791 SourceRange Range = DeclRef->getNameInfo().getSourceRange();
792 addUsage(NamingCheckFailures, DeclRef->getDecl(), Range,
793 Result.SourceManager);
794 return;
795 }
796
797 if (const auto *Decl = Result.Nodes.getNodeAs<NamedDecl>("decl")) {
798 if (!Decl->getIdentifier() || Decl->getName().empty() || Decl->isImplicit())
799 return;
800
801 // Fix type aliases in value declarations
802 if (const auto *Value = Result.Nodes.getNodeAs<ValueDecl>("decl")) {
803 if (const auto *Typedef =
804 Value->getType().getTypePtr()->getAs<TypedefType>()) {
805 addUsage(NamingCheckFailures, Typedef->getDecl(),
806 Value->getSourceRange());
807 }
808 }
809
810 // Fix type aliases in function declarations
811 if (const auto *Value = Result.Nodes.getNodeAs<FunctionDecl>("decl")) {
812 if (const auto *Typedef =
813 Value->getReturnType().getTypePtr()->getAs<TypedefType>()) {
814 addUsage(NamingCheckFailures, Typedef->getDecl(),
815 Value->getSourceRange());
816 }
817 for (unsigned i = 0; i < Value->getNumParams(); ++i) {
818 if (const auto *Typedef = Value->parameters()[i]
819 ->getType()
820 .getTypePtr()
821 ->getAs<TypedefType>()) {
822 addUsage(NamingCheckFailures, Typedef->getDecl(),
823 Value->getSourceRange());
824 }
825 }
826 }
827
828 // Ignore ClassTemplateSpecializationDecl which are creating duplicate
829 // replacements with CXXRecordDecl
830 if (isa<ClassTemplateSpecializationDecl>(Decl))
831 return;
832
833 StyleKind SK = findStyleKind(Decl, NamingStyles);
834 if (SK == SK_Invalid)
835 return;
836
837 if (!NamingStyles[SK])
838 return;
839
840 const NamingStyle &Style = *NamingStyles[SK];
841 StringRef Name = Decl->getName();
842 if (matchesStyle(Name, Style))
843 return;
844
845 std::string KindName = fixupWithCase(StyleNames[SK], CT_LowerCase);
846 std::replace(KindName.begin(), KindName.end(), '_', ' ');
847
848 std::string Fixup = fixupWithStyle(Name, Style);
849 if (StringRef(Fixup).equals(Name)) {
850 if (!IgnoreFailedSplit) {
851 LLVM_DEBUG(llvm::dbgs()
852 << Decl->getBeginLoc().printToString(*Result.SourceManager)
853 << llvm::format(": unable to split words for %s '%s'\n",
854 KindName.c_str(), Name.str().c_str()));
855 }
856 } else {
857 NamingCheckFailure &Failure = NamingCheckFailures[NamingCheckId(
858 Decl->getLocation(), Decl->getNameAsString())];
859 SourceRange Range =
860 DeclarationNameInfo(Decl->getDeclName(), Decl->getLocation())
861 .getSourceRange();
862
863 Failure.Fixup = std::move(Fixup);
864 Failure.KindName = std::move(KindName);
865 addUsage(NamingCheckFailures, Decl, Range);
866 }
867 }
868 }
869
870 void IdentifierNamingCheck::checkMacro(SourceManager &SourceMgr,
871 const Token &MacroNameTok,
872 const MacroInfo *MI) {
873 if (!NamingStyles[SK_MacroDefinition])
874 return;
875
876 StringRef Name = MacroNameTok.getIdentifierInfo()->getName();
877 const NamingStyle &Style = *NamingStyles[SK_MacroDefinition];
878 if (matchesStyle(Name, Style))
879 return;
880
881 std::string KindName =
882 fixupWithCase(StyleNames[SK_MacroDefinition], CT_LowerCase);
883 std::replace(KindName.begin(), KindName.end(), '_', ' ');
884
885 std::string Fixup = fixupWithStyle(Name, Style);
886 if (StringRef(Fixup).equals(Name)) {
887 if (!IgnoreFailedSplit) {
888 LLVM_DEBUG(llvm::dbgs()
889 << MacroNameTok.getLocation().printToString(SourceMgr)
890 << llvm::format(": unable to split words for %s '%s'\n",
891 KindName.c_str(), Name.str().c_str()));
892 }
893 } else {
894 NamingCheckId ID(MI->getDefinitionLoc(), Name);
895 NamingCheckFailure &Failure = NamingCheckFailures[ID];
896 SourceRange Range(MacroNameTok.getLocation(), MacroNameTok.getEndLoc());
897
898 Failure.Fixup = std::move(Fixup);
899 Failure.KindName = std::move(KindName);
900 addUsage(NamingCheckFailures, ID, Range);
901 }
902 }
903
904 void IdentifierNamingCheck::expandMacro(const Token &MacroNameTok,
905 const MacroInfo *MI) {
906 StringRef Name = MacroNameTok.getIdentifierInfo()->getName();
907 NamingCheckId ID(MI->getDefinitionLoc(), Name);
908
909 auto Failure = NamingCheckFailures.find(ID);
910 if (Failure == NamingCheckFailures.end())
911 return;
912
913 SourceRange Range(MacroNameTok.getLocation(), MacroNameTok.getEndLoc());
914 addUsage(NamingCheckFailures, ID, Range);
915 }
916
917 void IdentifierNamingCheck::onEndOfTranslationUnit() {
918 for (const auto &Pair : NamingCheckFailures) {
919 const NamingCheckId &Decl = Pair.first;
920 const NamingCheckFailure &Failure = Pair.second;
921
922 if (Failure.KindName.empty())
923 continue;
924
925 if (Failure.ShouldFix) {
926 auto Diag = diag(Decl.first, "invalid case style for %0 '%1'")
927 << Failure.KindName << Decl.second;
928
929 for (const auto &Loc : Failure.RawUsageLocs) {
930 // We assume that the identifier name is made of one token only. This is
931 // always the case as we ignore usages in macros that could build
932 // identifier names by combining multiple tokens.
933 //
934 // For destructors, we alread take care of it by remembering the
935 // location of the start of the identifier and not the start of the
936 // tilde.
937 //
938 // Other multi-token identifiers, such as operators are not checked at
939 // all.
940 Diag << FixItHint::CreateReplacement(
941 SourceRange(SourceLocation::getFromRawEncoding(Loc)),
942 Failure.Fixup);
943 }
944 }
945 }
946 }
947
948 } // namespace readability
949 } // namespace tidy
950 } // namespace clang
llvm::DenseMapInfo< clang::tidy::readability::IdentifierNamingCheck::NamingCheckId >::getHashValue
static unsigned getHashValue(NamingCheckId Val)
Definition: IdentifierNamingCheck.cpp:45
Loc
SourceLocation Loc
&#39;#&#39; location in the include directive
Definition: IncludeOrderCheck.cpp:37
clang::ast_matchers
Definition: AbseilMatcher.h:15
clang::tidy::OptionsView::store
void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const
Stores an option with the check-local name LocalName with string value Value to Options.
Definition: ClangTidy.cpp:473
ENUMERATE
#define ENUMERATE(v)
Definition: IdentifierNamingCheck.cpp:122
clang::tidy::readability::IdentifierNamingCheck::registerPPCallbacks
void registerPPCallbacks(CompilerInstance &Compiler) override
Override this to register PPCallbacks with Compiler.
Definition: IdentifierNamingCheck.cpp:244
llvm
Some operations such as code completion produce a set of candidates.
Definition: YAMLGenerator.cpp:28
clang::tidy::readability::IdentifierNamingCheck::CT_CamelSnakeBack
Definition: IdentifierNamingCheck.h:52
clang::tidy::readability::addUsage
static void addUsage(IdentifierNamingCheck::NamingCheckFailureMap &Failures, const IdentifierNamingCheck::NamingCheckId &Decl, SourceRange Range, SourceManager *SourceMgr=nullptr)
Definition: IdentifierNamingCheck.cpp:659
clang::tidy::OptionsView::get
std::string get(StringRef LocalName, StringRef Default) const
Read a named option from the Context.
Definition: ClangTidy.cpp:454
clang::tidy::readability::SK_Invalid
Definition: IdentifierNamingCheck.cpp:126
clang::tidy::readability::IdentifierNamingCheck::NamingCheckFailure
Holds an identifier name check failure, tracking the kind of the identifer, its possible fixup and th...
Definition: IdentifierNamingCheck.h:70
clang::tidy::readability::IdentifierNamingCheck::CT_CamelSnakeCase
Definition: IdentifierNamingCheck.h:51
clang::tidy::readability::IdentifierNamingCheck::CT_LowerCase
Definition: IdentifierNamingCheck.h:47
clang::tidy::readability::matchesStyle
static bool matchesStyle(StringRef Name, IdentifierNamingCheck::NamingStyle Style)
Definition: IdentifierNamingCheck.cpp:250
clang::tidy::readability::IdentifierNamingCheck::CaseType
CaseType
Definition: IdentifierNamingCheck.h:45
clang::tidy::readability::IdentifierNamingCheck::check
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
Definition: IdentifierNamingCheck.cpp:698
clang::tidy::readability::IdentifierNamingCheck::NamingStyle::Case
llvm::Optional< CaseType > Case
Definition: IdentifierNamingCheck.h:62
clang::tidy::cppcoreguidelines::toString
static llvm::StringRef toString(SpecialMemberFunctionsCheck::SpecialMemberFunctionKind K)
Definition: SpecialMemberFunctionsCheck.cpp:59
llvm::DenseMapInfo< clang::tidy::readability::IdentifierNamingCheck::NamingCheckId >::getEmptyKey
static NamingCheckId getEmptyKey()
Definition: IdentifierNamingCheck.cpp:33
clang::tidy::ClangTidyCheck
Base class for all clang-tidy checks.
Definition: ClangTidy.h:127
clang::tidy::readability::StyleKind
StyleKind
Definition: IdentifierNamingCheck.cpp:121
clang::tidy::readability::IdentifierNamingCheck::CT_AnyCase
Definition: IdentifierNamingCheck.h:46
llvm::DenseMapInfo< clang::tidy::readability::IdentifierNamingCheck::NamingCheckId >::isEqual
static bool isEqual(const NamingCheckId &LHS, const NamingCheckId &RHS)
Definition: IdentifierNamingCheck.cpp:53
clang::tidy::readability::IdentifierNamingCheck::NamingStyle::Suffix
std::string Suffix
Definition: IdentifierNamingCheck.h:64
llvm::DenseMapInfo< clang::tidy::readability::IdentifierNamingCheck::NamingCheckId >::NamingCheckId
clang::tidy::readability::IdentifierNamingCheck::NamingCheckId NamingCheckId
Definition: IdentifierNamingCheck.cpp:31
clang::tidy::ClangTidyCheck::Options
OptionsView Options
Definition: ClangTidy.h:183
clang::tidy::readability::IdentifierNamingCheck::NamingCheckFailure::KindName
std::string KindName
Definition: IdentifierNamingCheck.h:71
clang::tidy::readability::IdentifierNamingCheck::CT_CamelCase
Definition: IdentifierNamingCheck.h:50
clang::tidy::readability::IdentifierNamingCheck::expandMacro
void expandMacro(const Token &MacroNameTok, const MacroInfo *MI)
Add a usage of a macro if it already has a violation.
Definition: IdentifierNamingCheck.cpp:904
clang::tidy::readability::IdentifierNamingCheck::NamingCheckId
std::pair< SourceLocation, std::string > NamingCheckId
Definition: IdentifierNamingCheck.h:87
llvm::DenseMapInfo< clang::tidy::readability::IdentifierNamingCheck::NamingCheckId >::getTombstoneKey
static NamingCheckId getTombstoneKey()
Definition: IdentifierNamingCheck.cpp:39
clang::tidy::readability::IdentifierNamingCheck::registerMatchers
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
Definition: IdentifierNamingCheck.cpp:234
Name
static constexpr llvm::StringLiteral Name
Definition: UppercaseLiteralSuffixCheck.cpp:28
clang::tidy::ClangTidyOptions::OptionMap
std::map< std::string, std::string > OptionMap
Definition: ClangTidyOptions.h:98
D
const Decl * D
Definition: XRefs.cpp:79
Result
llvm::Optional< llvm::Expected< tooling::AtomicChanges > > Result
Definition: ClangdServer.cpp:60
clang::tidy::readability::IdentifierNamingCheck::NamingCheckFailure::Fixup
std::string Fixup
Definition: IdentifierNamingCheck.h:72
clang::tidy::readability::IdentifierNamingCheck::onEndOfTranslationUnit
void onEndOfTranslationUnit() override
Definition: IdentifierNamingCheck.cpp:917
clang::tidy::readability::SK_Count
Definition: IdentifierNamingCheck.cpp:125
clang::tidy::readability::IdentifierNamingCheck::storeOptions
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
Definition: IdentifierNamingCheck.cpp:196
clang::tidy::readability::fixupWithCase
static std::string fixupWithCase(StringRef Name, IdentifierNamingCheck::CaseType Case)
Definition: IdentifierNamingCheck.cpp:284
clang::tidy::readability::IdentifierNamingCheck::CT_UpperCase
Definition: IdentifierNamingCheck.h:49
clang::tidy::readability::IdentifierNamingCheck::checkMacro
void checkMacro(SourceManager &sourceMgr, const Token &MacroNameTok, const MacroInfo *MI)
Check Macros for style violations.
Definition: IdentifierNamingCheck.cpp:870
clang
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Definition: ChangeNamespace.cpp:18
clang::tidy::readability::IdentifierNamingCheck::NamingStyle
Definition: IdentifierNamingCheck.h:55
IdentifierNamingCheck.h
clang::tidy::readability::fixupWithStyle
static std::string fixupWithStyle(StringRef Name, const IdentifierNamingCheck::NamingStyle &Style)
Definition: IdentifierNamingCheck.cpp:381
clang::tidy::readability::IdentifierNamingCheck::NamingCheckFailureMap
llvm::DenseMap< NamingCheckId, NamingCheckFailure > NamingCheckFailureMap
Definition: IdentifierNamingCheck.h:90
clang::tidy::readability::IdentifierNamingCheck::NamingStyle::Prefix
std::string Prefix
Definition: IdentifierNamingCheck.h:63
clang::doc::MD
static GeneratorRegistry::Add< MDGenerator > MD(MDGenerator::Format, "Generator for MD output.")
clang::tidy::readability::findStyleKind
static StyleKind findStyleKind(const NamedDecl *D, const std::vector< llvm::Optional< IdentifierNamingCheck::NamingStyle >> &NamingStyles)
Definition: IdentifierNamingCheck.cpp:391
Range
CharSourceRange Range
SourceRange for the file name.
Definition: IncludeOrderCheck.cpp:38
clang::tidy::utils::rangeCanBeFixed
bool rangeCanBeFixed(SourceRange Range, const SourceManager *SM)
Definition: ASTUtils.cpp:91
clang::tidy::ClangTidyContext
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
Definition: ClangTidyDiagnosticConsumer.h:100
STRINGIZE
#define STRINGIZE(v)
clang::tidy::readability::StyleNames
static StringRef const StyleNames[]
Definition: IdentifierNamingCheck.cpp:129
clang::tidy::readability::IdentifierNamingCheck::CT_CamelBack
Definition: IdentifierNamingCheck.h:48
NAMING_KEYS
#define NAMING_KEYS(m)
Definition: IdentifierNamingCheck.cpp:68
clang::tidy::readability::IdentifierNamingCheck::NamingCheckFailure::RawUsageLocs
llvm::DenseSet< unsigned > RawUsageLocs
A set of all the identifier usages starting SourceLocation, in their encoded form.
Definition: IdentifierNamingCheck.h:82
DeclRef
const DeclRefExpr * DeclRef
Definition: UseAfterMoveCheck.cpp:30
clang::tidy::ClangTidyCheck::diag
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check&#39;s name.
Definition: ClangTidy.cpp:438
clang::tidy::readability::IdentifierNamingCheck
Checks for identifiers naming style mismatch.
Definition: IdentifierNamingCheck.h:35
clang::tidy::readability::IdentifierNamingCheck::NamingCheckFailure::ShouldFix
bool ShouldFix
Whether the failure should be fixed or not.
Definition: IdentifierNamingCheck.h:78