clang-tools  3.9.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 "llvm/Support/Debug.h"
13 #include "llvm/Support/Format.h"
14 #include "clang/ASTMatchers/ASTMatchFinder.h"
15 #include "clang/Frontend/CompilerInstance.h"
16 #include "clang/Lex/PPCallbacks.h"
17 #include "clang/Lex/Preprocessor.h"
18 #include "llvm/ADT/DenseMapInfo.h"
19 
20 #define DEBUG_TYPE "clang-tidy"
21 
22 using namespace clang::ast_matchers;
23 
24 namespace llvm {
25 /// Specialisation of DenseMapInfo to allow NamingCheckId objects in DenseMaps
26 template <>
27 struct DenseMapInfo<
29  using 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 
62 namespace clang {
63 namespace tidy {
64 namespace readability {
65 
66 // clang-format off
67 #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) \
110  m(TypeAlias) \
111  m(MacroDefinition) \
112 
113 enum StyleKind {
114 #define ENUMERATE(v) SK_ ## v,
116 #undef ENUMERATE
119 };
120 
121 static StringRef const StyleNames[] = {
122 #define STRINGIZE(v) #v,
124 #undef STRINGIZE
125 };
126 
127 #undef NAMING_KEYS
128 // clang-format on
129 
130 namespace {
131 /// Callback supplies macros to IdentifierNamingCheck::checkMacro
132 class IdentifierNamingCheckPPCallbacks : public PPCallbacks {
133 public:
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 
151 private:
152  Preprocessor *PP;
153  IdentifierNamingCheck *Check;
154 };
155 } // namespace
156 
157 IdentifierNamingCheck::IdentifierNamingCheck(StringRef Name,
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)
166  .Default(CT_AnyCase);
167  };
168 
169  for (auto const &Name : StyleNames) {
170  NamingStyles.push_back(
171  NamingStyle(fromString(Options.get((Name + "Case").str(), "")),
172  Options.get((Name + "Prefix").str(), ""),
173  Options.get((Name + "Suffix").str(), "")));
174  }
175 
176  IgnoreFailedSplit = Options.get("IgnoreFailedSplit", 0);
177 }
178 
180  auto const toString = [](CaseType Type) {
181  switch (Type) {
182  case CT_AnyCase:
183  return "aNy_CasE";
184  case CT_LowerCase:
185  return "lower_case";
186  case CT_CamelBack:
187  return "camelBack";
188  case CT_UpperCase:
189  return "UPPER_CASE";
190  case CT_CamelCase:
191  return "CamelCase";
192  }
193 
194  llvm_unreachable("Unknown Case Type");
195  };
196 
197  for (size_t i = 0; i < SK_Count; ++i) {
198  Options.store(Opts, (StyleNames[i] + "Case").str(),
199  toString(NamingStyles[i].Case));
200  Options.store(Opts, (StyleNames[i] + "Prefix").str(),
201  NamingStyles[i].Prefix);
202  Options.store(Opts, (StyleNames[i] + "Suffix").str(),
203  NamingStyles[i].Suffix);
204  }
205 
206  Options.store(Opts, "IgnoreFailedSplit", IgnoreFailedSplit);
207 }
208 
210  Finder->addMatcher(namedDecl().bind("decl"), this);
211  Finder->addMatcher(usingDecl().bind("using"), this);
212  Finder->addMatcher(declRefExpr().bind("declRef"), this);
213  Finder->addMatcher(cxxConstructorDecl().bind("classRef"), this);
214  Finder->addMatcher(cxxDestructorDecl().bind("classRef"), this);
215  Finder->addMatcher(typeLoc().bind("typeLoc"), this);
216  Finder->addMatcher(nestedNameSpecifierLoc().bind("nestedNameLoc"), this);
217 }
218 
219 void IdentifierNamingCheck::registerPPCallbacks(CompilerInstance &Compiler) {
220  Compiler.getPreprocessor().addPPCallbacks(
221  llvm::make_unique<IdentifierNamingCheckPPCallbacks>(
222  &Compiler.getPreprocessor(), this));
223 }
224 
225 static bool matchesStyle(StringRef Name,
227  static llvm::Regex Matchers[] = {
228  llvm::Regex("^.*$"),
229  llvm::Regex("^[a-z][a-z0-9_]*$"),
230  llvm::Regex("^[a-z][a-zA-Z0-9]*$"),
231  llvm::Regex("^[A-Z][A-Z0-9_]*$"),
232  llvm::Regex("^[A-Z][a-zA-Z0-9]*$"),
233  };
234 
235  bool Matches = true;
236  if (Name.startswith(Style.Prefix))
237  Name = Name.drop_front(Style.Prefix.size());
238  else
239  Matches = false;
240 
241  if (Name.endswith(Style.Suffix))
242  Name = Name.drop_back(Style.Suffix.size());
243  else
244  Matches = false;
245 
246  if (!Matchers[static_cast<size_t>(Style.Case)].match(Name))
247  Matches = false;
248 
249  return Matches;
250 }
251 
252 static std::string fixupWithCase(StringRef Name,
254  static llvm::Regex Splitter(
255  "([a-z0-9A-Z]*)(_+)|([A-Z]?[a-z0-9]+)([A-Z]|$)|([A-Z]+)([A-Z]|$)");
256 
257  SmallVector<StringRef, 8> Substrs;
258  Name.split(Substrs, "_", -1, false);
259 
260  SmallVector<StringRef, 8> Words;
261  for (auto Substr : Substrs) {
262  while (!Substr.empty()) {
263  SmallVector<StringRef, 8> Groups;
264  if (!Splitter.match(Substr, &Groups))
265  break;
266 
267  if (Groups[2].size() > 0) {
268  Words.push_back(Groups[1]);
269  Substr = Substr.substr(Groups[0].size());
270  } else if (Groups[3].size() > 0) {
271  Words.push_back(Groups[3]);
272  Substr = Substr.substr(Groups[0].size() - Groups[4].size());
273  } else if (Groups[5].size() > 0) {
274  Words.push_back(Groups[5]);
275  Substr = Substr.substr(Groups[0].size() - Groups[6].size());
276  }
277  }
278  }
279 
280  if (Words.empty())
281  return Name;
282 
283  std::string Fixup;
284  switch (Case) {
286  Fixup += Name;
287  break;
288 
290  for (auto const &Word : Words) {
291  if (&Word != &Words.front())
292  Fixup += "_";
293  Fixup += Word.lower();
294  }
295  break;
296 
298  for (auto const &Word : Words) {
299  if (&Word != &Words.front())
300  Fixup += "_";
301  Fixup += Word.upper();
302  }
303  break;
304 
306  for (auto const &Word : Words) {
307  Fixup += Word.substr(0, 1).upper();
308  Fixup += Word.substr(1).lower();
309  }
310  break;
311 
313  for (auto const &Word : Words) {
314  if (&Word == &Words.front()) {
315  Fixup += Word.lower();
316  } else {
317  Fixup += Word.substr(0, 1).upper();
318  Fixup += Word.substr(1).lower();
319  }
320  }
321  break;
322  }
323 
324  return Fixup;
325 }
326 
327 static std::string fixupWithStyle(StringRef Name,
329  return Style.Prefix + fixupWithCase(Name, Style.Case) + Style.Suffix;
330 }
331 
333  const NamedDecl *D,
334  const std::vector<IdentifierNamingCheck::NamingStyle> &NamingStyles) {
335  if (isa<TypedefDecl>(D) && NamingStyles[SK_Typedef].isSet())
336  return SK_Typedef;
337 
338  if (isa<TypeAliasDecl>(D) && NamingStyles[SK_TypeAlias].isSet())
339  return SK_TypeAlias;
340 
341  if (const auto *Decl = dyn_cast<NamespaceDecl>(D)) {
342  if (Decl->isAnonymousNamespace())
343  return SK_Invalid;
344 
345  if (Decl->isInline() && NamingStyles[SK_InlineNamespace].isSet())
346  return SK_InlineNamespace;
347 
348  if (NamingStyles[SK_Namespace].isSet())
349  return SK_Namespace;
350  }
351 
352  if (isa<EnumDecl>(D) && NamingStyles[SK_Enum].isSet())
353  return SK_Enum;
354 
355  if (isa<EnumConstantDecl>(D)) {
356  if (NamingStyles[SK_EnumConstant].isSet())
357  return SK_EnumConstant;
358 
359  if (NamingStyles[SK_Constant].isSet())
360  return SK_Constant;
361 
362  return SK_Invalid;
363  }
364 
365  if (const auto *Decl = dyn_cast<CXXRecordDecl>(D)) {
366  if (Decl->isAnonymousStructOrUnion())
367  return SK_Invalid;
368 
369  if (Decl->hasDefinition() && Decl->isAbstract() &&
370  NamingStyles[SK_AbstractClass].isSet())
371  return SK_AbstractClass;
372 
373  if (Decl->isStruct() && NamingStyles[SK_Struct].isSet())
374  return SK_Struct;
375 
376  if (Decl->isStruct() && NamingStyles[SK_Class].isSet())
377  return SK_Class;
378 
379  if (Decl->isClass() && NamingStyles[SK_Class].isSet())
380  return SK_Class;
381 
382  if (Decl->isClass() && NamingStyles[SK_Struct].isSet())
383  return SK_Struct;
384 
385  if (Decl->isUnion() && NamingStyles[SK_Union].isSet())
386  return SK_Union;
387 
388  if (Decl->isEnum() && NamingStyles[SK_Enum].isSet())
389  return SK_Enum;
390 
391  return SK_Invalid;
392  }
393 
394  if (const auto *Decl = dyn_cast<FieldDecl>(D)) {
395  QualType Type = Decl->getType();
396 
397  if (!Type.isNull() && Type.isLocalConstQualified() &&
398  NamingStyles[SK_ConstantMember].isSet())
399  return SK_ConstantMember;
400 
401  if (!Type.isNull() && Type.isLocalConstQualified() &&
402  NamingStyles[SK_Constant].isSet())
403  return SK_Constant;
404 
405  if (Decl->getAccess() == AS_private &&
406  NamingStyles[SK_PrivateMember].isSet())
407  return SK_PrivateMember;
408 
409  if (Decl->getAccess() == AS_protected &&
410  NamingStyles[SK_ProtectedMember].isSet())
411  return SK_ProtectedMember;
412 
413  if (Decl->getAccess() == AS_public && NamingStyles[SK_PublicMember].isSet())
414  return SK_PublicMember;
415 
416  if (NamingStyles[SK_Member].isSet())
417  return SK_Member;
418 
419  return SK_Invalid;
420  }
421 
422  if (const auto *Decl = dyn_cast<ParmVarDecl>(D)) {
423  QualType Type = Decl->getType();
424 
425  if (Decl->isConstexpr() && NamingStyles[SK_ConstexprVariable].isSet())
426  return SK_ConstexprVariable;
427 
428  if (!Type.isNull() && Type.isLocalConstQualified() &&
429  NamingStyles[SK_ConstantParameter].isSet())
430  return SK_ConstantParameter;
431 
432  if (!Type.isNull() && Type.isLocalConstQualified() &&
433  NamingStyles[SK_Constant].isSet())
434  return SK_Constant;
435 
436  if (Decl->isParameterPack() && NamingStyles[SK_ParameterPack].isSet())
437  return SK_ParameterPack;
438 
439  if (NamingStyles[SK_Parameter].isSet())
440  return SK_Parameter;
441 
442  return SK_Invalid;
443  }
444 
445  if (const auto *Decl = dyn_cast<VarDecl>(D)) {
446  QualType Type = Decl->getType();
447 
448  if (Decl->isConstexpr() && NamingStyles[SK_ConstexprVariable].isSet())
449  return SK_ConstexprVariable;
450 
451  if (!Type.isNull() && Type.isLocalConstQualified() &&
452  Decl->isStaticDataMember() && NamingStyles[SK_ClassConstant].isSet())
453  return SK_ClassConstant;
454 
455  if (!Type.isNull() && Type.isLocalConstQualified() &&
456  Decl->isFileVarDecl() && NamingStyles[SK_GlobalConstant].isSet())
457  return SK_GlobalConstant;
458 
459  if (!Type.isNull() && Type.isLocalConstQualified() &&
460  Decl->isStaticLocal() && NamingStyles[SK_StaticConstant].isSet())
461  return SK_StaticConstant;
462 
463  if (!Type.isNull() && Type.isLocalConstQualified() &&
464  Decl->isLocalVarDecl() && NamingStyles[SK_LocalConstant].isSet())
465  return SK_LocalConstant;
466 
467  if (!Type.isNull() && Type.isLocalConstQualified() &&
468  Decl->isFunctionOrMethodVarDecl() &&
469  NamingStyles[SK_LocalConstant].isSet())
470  return SK_LocalConstant;
471 
472  if (!Type.isNull() && Type.isLocalConstQualified() &&
473  NamingStyles[SK_Constant].isSet())
474  return SK_Constant;
475 
476  if (Decl->isStaticDataMember() && NamingStyles[SK_ClassMember].isSet())
477  return SK_ClassMember;
478 
479  if (Decl->isFileVarDecl() && NamingStyles[SK_GlobalVariable].isSet())
480  return SK_GlobalVariable;
481 
482  if (Decl->isStaticLocal() && NamingStyles[SK_StaticVariable].isSet())
483  return SK_StaticVariable;
484 
485  if (Decl->isLocalVarDecl() && NamingStyles[SK_LocalVariable].isSet())
486  return SK_LocalVariable;
487 
488  if (Decl->isFunctionOrMethodVarDecl() &&
489  NamingStyles[SK_LocalVariable].isSet())
490  return SK_LocalVariable;
491 
492  if (NamingStyles[SK_Variable].isSet())
493  return SK_Variable;
494 
495  return SK_Invalid;
496  }
497 
498  if (const auto *Decl = dyn_cast<CXXMethodDecl>(D)) {
499  if (Decl->isMain() || !Decl->isUserProvided() ||
500  Decl->isUsualDeallocationFunction() ||
501  Decl->isCopyAssignmentOperator() || Decl->isMoveAssignmentOperator() ||
502  Decl->size_overridden_methods() > 0)
503  return SK_Invalid;
504 
505  if (Decl->isConstexpr() && NamingStyles[SK_ConstexprMethod].isSet())
506  return SK_ConstexprMethod;
507 
508  if (Decl->isConstexpr() && NamingStyles[SK_ConstexprFunction].isSet())
509  return SK_ConstexprFunction;
510 
511  if (Decl->isStatic() && NamingStyles[SK_ClassMethod].isSet())
512  return SK_ClassMethod;
513 
514  if (Decl->isVirtual() && NamingStyles[SK_VirtualMethod].isSet())
515  return SK_VirtualMethod;
516 
517  if (Decl->getAccess() == AS_private &&
518  NamingStyles[SK_PrivateMethod].isSet())
519  return SK_PrivateMethod;
520 
521  if (Decl->getAccess() == AS_protected &&
522  NamingStyles[SK_ProtectedMethod].isSet())
523  return SK_ProtectedMethod;
524 
525  if (Decl->getAccess() == AS_public && NamingStyles[SK_PublicMethod].isSet())
526  return SK_PublicMethod;
527 
528  if (NamingStyles[SK_Method].isSet())
529  return SK_Method;
530 
531  if (NamingStyles[SK_Function].isSet())
532  return SK_Function;
533 
534  return SK_Invalid;
535  }
536 
537  if (const auto *Decl = dyn_cast<FunctionDecl>(D)) {
538  if (Decl->isMain())
539  return SK_Invalid;
540 
541  if (Decl->isConstexpr() && NamingStyles[SK_ConstexprFunction].isSet())
542  return SK_ConstexprFunction;
543 
544  if (Decl->isGlobal() && NamingStyles[SK_GlobalFunction].isSet())
545  return SK_GlobalFunction;
546 
547  if (NamingStyles[SK_Function].isSet())
548  return SK_Function;
549  }
550 
551  if (isa<TemplateTypeParmDecl>(D)) {
552  if (NamingStyles[SK_TypeTemplateParameter].isSet())
553  return SK_TypeTemplateParameter;
554 
555  if (NamingStyles[SK_TemplateParameter].isSet())
556  return SK_TemplateParameter;
557 
558  return SK_Invalid;
559  }
560 
561  if (isa<NonTypeTemplateParmDecl>(D)) {
562  if (NamingStyles[SK_ValueTemplateParameter].isSet())
563  return SK_ValueTemplateParameter;
564 
565  if (NamingStyles[SK_TemplateParameter].isSet())
566  return SK_TemplateParameter;
567 
568  return SK_Invalid;
569  }
570 
571  if (isa<TemplateTemplateParmDecl>(D)) {
572  if (NamingStyles[SK_TemplateTemplateParameter].isSet())
573  return SK_TemplateTemplateParameter;
574 
575  if (NamingStyles[SK_TemplateParameter].isSet())
576  return SK_TemplateParameter;
577 
578  return SK_Invalid;
579  }
580 
581  return SK_Invalid;
582 }
583 
586  SourceRange Range) {
587  // Do nothing if the provided range is invalid.
588  if (Range.getBegin().isInvalid() || Range.getEnd().isInvalid())
589  return;
590 
591  // Try to insert the identifier location in the Usages map, and bail out if it
592  // is already in there
593  auto &Failure = Failures[Decl];
594  if (!Failure.RawUsageLocs.insert(Range.getBegin().getRawEncoding()).second)
595  return;
596 
597  Failure.ShouldFix = Failure.ShouldFix && !Range.getBegin().isMacroID() &&
598  !Range.getEnd().isMacroID();
599 }
600 
601 /// Convenience method when the usage to be added is a NamedDecl
603  const NamedDecl *Decl, SourceRange Range) {
605  Decl->getLocation(), Decl->getNameAsString()),
606  Range);
607 }
608 
609 void IdentifierNamingCheck::check(const MatchFinder::MatchResult &Result) {
610  if (const auto *Decl =
611  Result.Nodes.getNodeAs<CXXConstructorDecl>("classRef")) {
612  if (Decl->isImplicit())
613  return;
614 
615  addUsage(NamingCheckFailures, Decl->getParent(),
616  Decl->getNameInfo().getSourceRange());
617  return;
618  }
619 
620  if (const auto *Decl =
621  Result.Nodes.getNodeAs<CXXDestructorDecl>("classRef")) {
622  if (Decl->isImplicit())
623  return;
624 
625  SourceRange Range = Decl->getNameInfo().getSourceRange();
626  if (Range.getBegin().isInvalid())
627  return;
628  // The first token that will be found is the ~ (or the equivalent trigraph),
629  // we want instead to replace the next token, that will be the identifier.
630  Range.setBegin(CharSourceRange::getTokenRange(Range).getEnd());
631 
632  addUsage(NamingCheckFailures, Decl->getParent(), Range);
633  return;
634  }
635 
636  if (const auto *Loc = Result.Nodes.getNodeAs<TypeLoc>("typeLoc")) {
637  NamedDecl *Decl = nullptr;
638  if (const auto &Ref = Loc->getAs<TagTypeLoc>()) {
639  Decl = Ref.getDecl();
640  } else if (const auto &Ref = Loc->getAs<InjectedClassNameTypeLoc>()) {
641  Decl = Ref.getDecl();
642  } else if (const auto &Ref = Loc->getAs<UnresolvedUsingTypeLoc>()) {
643  Decl = Ref.getDecl();
644  } else if (const auto &Ref = Loc->getAs<TemplateTypeParmTypeLoc>()) {
645  Decl = Ref.getDecl();
646  }
647 
648  if (Decl) {
649  addUsage(NamingCheckFailures, Decl, Loc->getSourceRange());
650  return;
651  }
652 
653  if (const auto &Ref = Loc->getAs<TemplateSpecializationTypeLoc>()) {
654  const auto *Decl =
655  Ref.getTypePtr()->getTemplateName().getAsTemplateDecl();
656 
657  SourceRange Range(Ref.getTemplateNameLoc(), Ref.getTemplateNameLoc());
658  if (const auto *ClassDecl = dyn_cast<TemplateDecl>(Decl)) {
659  if (const auto *TemplDecl = ClassDecl->getTemplatedDecl())
660  addUsage(NamingCheckFailures, TemplDecl, Range);
661  return;
662  }
663  }
664 
665  if (const auto &Ref =
666  Loc->getAs<DependentTemplateSpecializationTypeLoc>()) {
667  if (const auto *Decl = Ref.getTypePtr()->getAsTagDecl())
668  addUsage(NamingCheckFailures, Decl, Loc->getSourceRange());
669  return;
670  }
671  }
672 
673  if (const auto *Loc =
674  Result.Nodes.getNodeAs<NestedNameSpecifierLoc>("nestedNameLoc")) {
675  if (NestedNameSpecifier *Spec = Loc->getNestedNameSpecifier()) {
676  if (NamespaceDecl *Decl = Spec->getAsNamespace()) {
677  addUsage(NamingCheckFailures, Decl, Loc->getLocalSourceRange());
678  return;
679  }
680  }
681  }
682 
683  if (const auto *Decl = Result.Nodes.getNodeAs<UsingDecl>("using")) {
684  for (const auto &Shadow : Decl->shadows()) {
685  addUsage(NamingCheckFailures, Shadow->getTargetDecl(),
686  Decl->getNameInfo().getSourceRange());
687  }
688  return;
689  }
690 
691  if (const auto *DeclRef = Result.Nodes.getNodeAs<DeclRefExpr>("declRef")) {
692  SourceRange Range = DeclRef->getNameInfo().getSourceRange();
693  addUsage(NamingCheckFailures, DeclRef->getDecl(), Range);
694  return;
695  }
696 
697  if (const auto *Decl = Result.Nodes.getNodeAs<NamedDecl>("decl")) {
698  if (!Decl->getIdentifier() || Decl->getName().empty() || Decl->isImplicit())
699  return;
700 
701  // Fix type aliases in value declarations
702  if (const auto *Value = Result.Nodes.getNodeAs<ValueDecl>("decl")) {
703  if (const auto *Typedef =
704  Value->getType().getTypePtr()->getAs<TypedefType>()) {
705  addUsage(NamingCheckFailures, Typedef->getDecl(),
706  Value->getSourceRange());
707  }
708  }
709 
710  // Fix type aliases in function declarations
711  if (const auto *Value = Result.Nodes.getNodeAs<FunctionDecl>("decl")) {
712  if (const auto *Typedef =
713  Value->getReturnType().getTypePtr()->getAs<TypedefType>()) {
714  addUsage(NamingCheckFailures, Typedef->getDecl(),
715  Value->getSourceRange());
716  }
717  for (unsigned i = 0; i < Value->getNumParams(); ++i) {
718  if (const auto *Typedef = Value->parameters()[i]
719  ->getType()
720  .getTypePtr()
721  ->getAs<TypedefType>()) {
722  addUsage(NamingCheckFailures, Typedef->getDecl(),
723  Value->getSourceRange());
724  }
725  }
726  }
727 
728  // Ignore ClassTemplateSpecializationDecl which are creating duplicate
729  // replacements with CXXRecordDecl
730  if (isa<ClassTemplateSpecializationDecl>(Decl))
731  return;
732 
733  StyleKind SK = findStyleKind(Decl, NamingStyles);
734  if (SK == SK_Invalid)
735  return;
736 
737  NamingStyle Style = NamingStyles[SK];
738  StringRef Name = Decl->getName();
739  if (matchesStyle(Name, Style))
740  return;
741 
742  std::string KindName = fixupWithCase(StyleNames[SK], CT_LowerCase);
743  std::replace(KindName.begin(), KindName.end(), '_', ' ');
744 
745  std::string Fixup = fixupWithStyle(Name, Style);
746  if (StringRef(Fixup).equals(Name)) {
747  if (!IgnoreFailedSplit) {
748  DEBUG(llvm::dbgs()
749  << Decl->getLocStart().printToString(*Result.SourceManager)
750  << llvm::format(": unable to split words for %s '%s'\n",
751  KindName.c_str(), Name));
752  }
753  } else {
754  NamingCheckFailure &Failure = NamingCheckFailures[NamingCheckId(
755  Decl->getLocation(), Decl->getNameAsString())];
756  SourceRange Range =
757  DeclarationNameInfo(Decl->getDeclName(), Decl->getLocation())
758  .getSourceRange();
759 
760  Failure.Fixup = std::move(Fixup);
761  Failure.KindName = std::move(KindName);
762  addUsage(NamingCheckFailures, Decl, Range);
763  }
764  }
765 }
766 
768  const Token &MacroNameTok,
769  const MacroInfo *MI) {
770  StringRef Name = MacroNameTok.getIdentifierInfo()->getName();
771  NamingStyle Style = NamingStyles[SK_MacroDefinition];
772  if (matchesStyle(Name, Style))
773  return;
774 
775  std::string KindName =
776  fixupWithCase(StyleNames[SK_MacroDefinition], CT_LowerCase);
777  std::replace(KindName.begin(), KindName.end(), '_', ' ');
778 
779  std::string Fixup = fixupWithStyle(Name, Style);
780  if (StringRef(Fixup).equals(Name)) {
781  if (!IgnoreFailedSplit) {
782  DEBUG(
783  llvm::dbgs() << MacroNameTok.getLocation().printToString(SourceMgr)
784  << llvm::format(": unable to split words for %s '%s'\n",
785  KindName.c_str(), Name));
786  }
787  } else {
788  NamingCheckId ID(MI->getDefinitionLoc(), Name);
789  NamingCheckFailure &Failure = NamingCheckFailures[ID];
790  SourceRange Range(MacroNameTok.getLocation(), MacroNameTok.getEndLoc());
791 
792  Failure.Fixup = std::move(Fixup);
793  Failure.KindName = std::move(KindName);
794  addUsage(NamingCheckFailures, ID, Range);
795  }
796 }
797 
798 void IdentifierNamingCheck::expandMacro(const Token &MacroNameTok,
799  const MacroInfo *MI) {
800  StringRef Name = MacroNameTok.getIdentifierInfo()->getName();
801  NamingCheckId ID(MI->getDefinitionLoc(), Name);
802 
803  auto Failure = NamingCheckFailures.find(ID);
804  if (Failure == NamingCheckFailures.end())
805  return;
806 
807  SourceRange Range(MacroNameTok.getLocation(), MacroNameTok.getEndLoc());
808  addUsage(NamingCheckFailures, ID, Range);
809 }
810 
812  for (const auto &Pair : NamingCheckFailures) {
813  const NamingCheckId &Decl = Pair.first;
814  const NamingCheckFailure &Failure = Pair.second;
815 
816  if (Failure.KindName.empty())
817  continue;
818 
819  if (Failure.ShouldFix) {
820  auto Diag = diag(Decl.first, "invalid case style for %0 '%1'")
821  << Failure.KindName << Decl.second;
822 
823  for (const auto &Loc : Failure.RawUsageLocs) {
824  // We assume that the identifier name is made of one token only. This is
825  // always the case as we ignore usages in macros that could build
826  // identifier names by combining multiple tokens.
827  //
828  // For destructors, we alread take care of it by remembering the
829  // location of the start of the identifier and not the start of the
830  // tilde.
831  //
832  // Other multi-token identifiers, such as operators are not checked at
833  // all.
834  Diag << FixItHint::CreateReplacement(
835  SourceRange(SourceLocation::getFromRawEncoding(Loc)),
836  Failure.Fixup);
837  }
838  }
839  }
840 }
841 
842 } // namespace readability
843 } // namespace tidy
844 } // namespace clang
SourceLocation Loc
'#' location in the include directive
static StyleKind findStyleKind(const NamedDecl *D, const std::vector< IdentifierNamingCheck::NamingStyle > &NamingStyles)
const std::string Name
Definition: USRFinder.cpp:140
#define ENUMERATE(v)
void registerPPCallbacks(CompilerInstance &Compiler) override
Override this to register PPCallbacks with Compiler.
std::unique_ptr< ast_matchers::MatchFinder > Finder
Definition: ClangTidy.cpp:210
Holds an identifier name check failure, tracking the kind of the identifer, its possible fixup and th...
static bool matchesStyle(StringRef Name, IdentifierNamingCheck::NamingStyle Style)
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
Preprocessor * PP
Base class for all clang-tidy checks.
Definition: ClangTidy.h:110
SourceManager SourceMgr
Definition: ClangTidy.cpp:193
clang::tidy::readability::IdentifierNamingCheck::NamingCheckId NamingCheckId
IdentifierNamingCheck * Check
std::string get(StringRef LocalName, StringRef Default) const
Read a named option from the Context.
Definition: ClangTidy.cpp:366
static std::string fixupWithStyle(StringRef Name, IdentifierNamingCheck::NamingStyle Style)
void expandMacro(const Token &MacroNameTok, const MacroInfo *MI)
Add a usage of a macro if it already has a violation.
std::pair< SourceLocation, std::string > NamingCheckId
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:385
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
std::map< std::string, std::string > OptionMap
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
static std::string fixupWithCase(StringRef Name, IdentifierNamingCheck::CaseType Case)
void checkMacro(SourceManager &sourceMgr, const Token &MacroNameTok, const MacroInfo *MI)
Check Macros for style violations.
static void addUsage(IdentifierNamingCheck::NamingCheckFailureMap &Failures, const IdentifierNamingCheck::NamingCheckId &Decl, SourceRange Range)
llvm::DenseMap< NamingCheckId, NamingCheckFailure > NamingCheckFailureMap
CharSourceRange Range
SourceRange for the file name.
ClangTidyContext & Context
Definition: ClangTidy.cpp:93
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
#define STRINGIZE(v)
static StringRef const StyleNames[]
#define NAMING_KEYS(m)
llvm::DenseSet< unsigned > RawUsageLocs
A set of all the identifier usages starting SourceLocation, in their encoded form.
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
Definition: ClangTidy.cpp:352
const NamedDecl * Result
Definition: USRFinder.cpp:137
bool ShouldFix
Whether the failure should be fixed or not.