clang-tools  10.0.0svn
IdentifierNamingCheck.cpp
Go to the documentation of this file.
1 //===--- IdentifierNamingCheck.cpp - clang-tidy ---------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
10 
11 #include "../utils/ASTUtils.h"
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 #include "clang/AST/CXXInheritance.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<
30  using 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,
124 #undef ENUMERATE
127 };
128 
129 static StringRef const StyleNames[] = {
130 #define STRINGIZE(v) #v,
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 
197 
199  auto const toString = [](CaseType Type) {
200  switch (Type) {
201  case CT_AnyCase:
202  return "aNy_CasE";
203  case CT_LowerCase:
204  return "lower_case";
205  case CT_CamelBack:
206  return "camelBack";
207  case CT_UpperCase:
208  return "UPPER_CASE";
209  case CT_CamelCase:
210  return "CamelCase";
211  case CT_CamelSnakeCase:
212  return "Camel_Snake_Case";
213  case CT_CamelSnakeBack:
214  return "camel_Snake_Back";
215  }
216 
217  llvm_unreachable("Unknown Case Type");
218  };
219 
220  for (size_t i = 0; i < SK_Count; ++i) {
221  if (NamingStyles[i]) {
222  if (NamingStyles[i]->Case) {
223  Options.store(Opts, (StyleNames[i] + "Case").str(),
224  toString(*NamingStyles[i]->Case));
225  }
226  Options.store(Opts, (StyleNames[i] + "Prefix").str(),
227  NamingStyles[i]->Prefix);
228  Options.store(Opts, (StyleNames[i] + "Suffix").str(),
229  NamingStyles[i]->Suffix);
230  }
231  }
232 
233  Options.store(Opts, "IgnoreFailedSplit", IgnoreFailedSplit);
234 }
235 
236 void IdentifierNamingCheck::registerMatchers(MatchFinder *Finder) {
237  Finder->addMatcher(namedDecl().bind("decl"), this);
238  Finder->addMatcher(usingDecl().bind("using"), this);
239  Finder->addMatcher(declRefExpr().bind("declRef"), this);
240  Finder->addMatcher(cxxConstructorDecl().bind("classRef"), this);
241  Finder->addMatcher(cxxDestructorDecl().bind("classRef"), this);
242  Finder->addMatcher(typeLoc().bind("typeLoc"), this);
243  Finder->addMatcher(nestedNameSpecifierLoc().bind("nestedNameLoc"), this);
244 }
245 
247  const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) {
248  ModuleExpanderPP->addPPCallbacks(
249  std::make_unique<IdentifierNamingCheckPPCallbacks>(ModuleExpanderPP,
250  this));
251 }
252 
253 static bool matchesStyle(StringRef Name,
255  static llvm::Regex Matchers[] = {
256  llvm::Regex("^.*$"),
257  llvm::Regex("^[a-z][a-z0-9_]*$"),
258  llvm::Regex("^[a-z][a-zA-Z0-9]*$"),
259  llvm::Regex("^[A-Z][A-Z0-9_]*$"),
260  llvm::Regex("^[A-Z][a-zA-Z0-9]*$"),
261  llvm::Regex("^[A-Z]([a-z0-9]*(_[A-Z])?)*"),
262  llvm::Regex("^[a-z]([a-z0-9]*(_[A-Z])?)*"),
263  };
264 
265  bool Matches = true;
266  if (Name.startswith(Style.Prefix))
267  Name = Name.drop_front(Style.Prefix.size());
268  else
269  Matches = false;
270 
271  if (Name.endswith(Style.Suffix))
272  Name = Name.drop_back(Style.Suffix.size());
273  else
274  Matches = false;
275 
276  // Ensure the name doesn't have any extra underscores beyond those specified
277  // in the prefix and suffix.
278  if (Name.startswith("_") || Name.endswith("_"))
279  Matches = false;
280 
281  if (Style.Case && !Matchers[static_cast<size_t>(*Style.Case)].match(Name))
282  Matches = false;
283 
284  return Matches;
285 }
286 
287 static std::string fixupWithCase(StringRef Name,
289  static llvm::Regex Splitter(
290  "([a-z0-9A-Z]*)(_+)|([A-Z]?[a-z0-9]+)([A-Z]|$)|([A-Z]+)([A-Z]|$)");
291 
292  SmallVector<StringRef, 8> Substrs;
293  Name.split(Substrs, "_", -1, false);
294 
295  SmallVector<StringRef, 8> Words;
296  for (auto Substr : Substrs) {
297  while (!Substr.empty()) {
298  SmallVector<StringRef, 8> Groups;
299  if (!Splitter.match(Substr, &Groups))
300  break;
301 
302  if (Groups[2].size() > 0) {
303  Words.push_back(Groups[1]);
304  Substr = Substr.substr(Groups[0].size());
305  } else if (Groups[3].size() > 0) {
306  Words.push_back(Groups[3]);
307  Substr = Substr.substr(Groups[0].size() - Groups[4].size());
308  } else if (Groups[5].size() > 0) {
309  Words.push_back(Groups[5]);
310  Substr = Substr.substr(Groups[0].size() - Groups[6].size());
311  }
312  }
313  }
314 
315  if (Words.empty())
316  return Name;
317 
318  std::string Fixup;
319  switch (Case) {
321  Fixup += Name;
322  break;
323 
325  for (auto const &Word : Words) {
326  if (&Word != &Words.front())
327  Fixup += "_";
328  Fixup += Word.lower();
329  }
330  break;
331 
333  for (auto const &Word : Words) {
334  if (&Word != &Words.front())
335  Fixup += "_";
336  Fixup += Word.upper();
337  }
338  break;
339 
341  for (auto const &Word : Words) {
342  Fixup += Word.substr(0, 1).upper();
343  Fixup += Word.substr(1).lower();
344  }
345  break;
346 
348  for (auto const &Word : Words) {
349  if (&Word == &Words.front()) {
350  Fixup += Word.lower();
351  } else {
352  Fixup += Word.substr(0, 1).upper();
353  Fixup += Word.substr(1).lower();
354  }
355  }
356  break;
357 
359  for (auto const &Word : Words) {
360  if (&Word != &Words.front())
361  Fixup += "_";
362  Fixup += Word.substr(0, 1).upper();
363  Fixup += Word.substr(1).lower();
364  }
365  break;
366 
368  for (auto const &Word : Words) {
369  if (&Word != &Words.front()) {
370  Fixup += "_";
371  Fixup += Word.substr(0, 1).upper();
372  } else {
373  Fixup += Word.substr(0, 1).lower();
374  }
375  Fixup += Word.substr(1).lower();
376  }
377  break;
378  }
379 
380  return Fixup;
381 }
382 
383 static std::string
385  const IdentifierNamingCheck::NamingStyle &Style) {
386  const std::string Fixed = fixupWithCase(
387  Name, Style.Case.getValueOr(IdentifierNamingCheck::CaseType::CT_AnyCase));
388  StringRef Mid = StringRef(Fixed).trim("_");
389  if (Mid.empty())
390  Mid = "_";
391  return (Style.Prefix + Mid + Style.Suffix).str();
392 }
393 
395  const NamedDecl *D,
396  const std::vector<llvm::Optional<IdentifierNamingCheck::NamingStyle>>
397  &NamingStyles) {
398  assert(D && D->getIdentifier() && !D->getName().empty() && !D->isImplicit() &&
399  "Decl must be an explicit identifier with a name.");
400 
401  if (isa<ObjCIvarDecl>(D) && NamingStyles[SK_ObjcIvar])
402  return SK_ObjcIvar;
403 
404  if (isa<TypedefDecl>(D) && NamingStyles[SK_Typedef])
405  return SK_Typedef;
406 
407  if (isa<TypeAliasDecl>(D) && NamingStyles[SK_TypeAlias])
408  return SK_TypeAlias;
409 
410  if (const auto *Decl = dyn_cast<NamespaceDecl>(D)) {
411  if (Decl->isAnonymousNamespace())
412  return SK_Invalid;
413 
414  if (Decl->isInline() && NamingStyles[SK_InlineNamespace])
415  return SK_InlineNamespace;
416 
417  if (NamingStyles[SK_Namespace])
418  return SK_Namespace;
419  }
420 
421  if (isa<EnumDecl>(D) && NamingStyles[SK_Enum])
422  return SK_Enum;
423 
424  if (isa<EnumConstantDecl>(D)) {
425  if (NamingStyles[SK_EnumConstant])
426  return SK_EnumConstant;
427 
428  if (NamingStyles[SK_Constant])
429  return SK_Constant;
430 
431  return SK_Invalid;
432  }
433 
434  if (const auto *Decl = dyn_cast<CXXRecordDecl>(D)) {
435  if (Decl->isAnonymousStructOrUnion())
436  return SK_Invalid;
437 
438  if (!Decl->getCanonicalDecl()->isThisDeclarationADefinition())
439  return SK_Invalid;
440 
441  if (Decl->hasDefinition() && Decl->isAbstract() &&
442  NamingStyles[SK_AbstractClass])
443  return SK_AbstractClass;
444 
445  if (Decl->isStruct() && NamingStyles[SK_Struct])
446  return SK_Struct;
447 
448  if (Decl->isStruct() && NamingStyles[SK_Class])
449  return SK_Class;
450 
451  if (Decl->isClass() && NamingStyles[SK_Class])
452  return SK_Class;
453 
454  if (Decl->isClass() && NamingStyles[SK_Struct])
455  return SK_Struct;
456 
457  if (Decl->isUnion() && NamingStyles[SK_Union])
458  return SK_Union;
459 
460  if (Decl->isEnum() && NamingStyles[SK_Enum])
461  return SK_Enum;
462 
463  return SK_Invalid;
464  }
465 
466  if (const auto *Decl = dyn_cast<FieldDecl>(D)) {
467  QualType Type = Decl->getType();
468 
469  if (!Type.isNull() && Type.isConstQualified()) {
470  if (NamingStyles[SK_ConstantMember])
471  return SK_ConstantMember;
472 
473  if (NamingStyles[SK_Constant])
474  return SK_Constant;
475  }
476 
477  if (Decl->getAccess() == AS_private && NamingStyles[SK_PrivateMember])
478  return SK_PrivateMember;
479 
480  if (Decl->getAccess() == AS_protected && NamingStyles[SK_ProtectedMember])
481  return SK_ProtectedMember;
482 
483  if (Decl->getAccess() == AS_public && NamingStyles[SK_PublicMember])
484  return SK_PublicMember;
485 
486  if (NamingStyles[SK_Member])
487  return SK_Member;
488 
489  return SK_Invalid;
490  }
491 
492  if (const auto *Decl = dyn_cast<ParmVarDecl>(D)) {
493  QualType Type = Decl->getType();
494 
495  if (Decl->isConstexpr() && NamingStyles[SK_ConstexprVariable])
496  return SK_ConstexprVariable;
497 
498  if (!Type.isNull() && Type.isConstQualified()) {
499  if (Type.getTypePtr()->isAnyPointerType() && NamingStyles[SK_ConstantPointerParameter])
500  return SK_ConstantPointerParameter;
501 
502  if (NamingStyles[SK_ConstantParameter])
503  return SK_ConstantParameter;
504 
505  if (NamingStyles[SK_Constant])
506  return SK_Constant;
507  }
508 
509  if (Decl->isParameterPack() && NamingStyles[SK_ParameterPack])
510  return SK_ParameterPack;
511 
512  if (!Type.isNull() && Type.getTypePtr()->isAnyPointerType() && NamingStyles[SK_PointerParameter])
513  return SK_PointerParameter;
514 
515  if (NamingStyles[SK_Parameter])
516  return SK_Parameter;
517 
518  return SK_Invalid;
519  }
520 
521  if (const auto *Decl = dyn_cast<VarDecl>(D)) {
522  QualType Type = Decl->getType();
523 
524  if (Decl->isConstexpr() && NamingStyles[SK_ConstexprVariable])
525  return SK_ConstexprVariable;
526 
527  if (!Type.isNull() && Type.isConstQualified()) {
528  if (Decl->isStaticDataMember() && NamingStyles[SK_ClassConstant])
529  return SK_ClassConstant;
530 
531  if (Decl->isFileVarDecl() && Type.getTypePtr()->isAnyPointerType() && NamingStyles[SK_GlobalConstantPointer])
532  return SK_GlobalConstantPointer;
533 
534  if (Decl->isFileVarDecl() && NamingStyles[SK_GlobalConstant])
535  return SK_GlobalConstant;
536 
537  if (Decl->isStaticLocal() && NamingStyles[SK_StaticConstant])
538  return SK_StaticConstant;
539 
540  if (Decl->isLocalVarDecl() && Type.getTypePtr()->isAnyPointerType() && NamingStyles[SK_LocalConstantPointer])
541  return SK_LocalConstantPointer;
542 
543  if (Decl->isLocalVarDecl() && NamingStyles[SK_LocalConstant])
544  return SK_LocalConstant;
545 
546  if (Decl->isFunctionOrMethodVarDecl() && NamingStyles[SK_LocalConstant])
547  return SK_LocalConstant;
548 
549  if (NamingStyles[SK_Constant])
550  return SK_Constant;
551  }
552 
553  if (Decl->isStaticDataMember() && NamingStyles[SK_ClassMember])
554  return SK_ClassMember;
555 
556  if (Decl->isFileVarDecl() && Type.getTypePtr()->isAnyPointerType() && NamingStyles[SK_GlobalPointer])
557  return SK_GlobalPointer;
558 
559  if (Decl->isFileVarDecl() && NamingStyles[SK_GlobalVariable])
560  return SK_GlobalVariable;
561 
562  if (Decl->isStaticLocal() && NamingStyles[SK_StaticVariable])
563  return SK_StaticVariable;
564 
565  if (Decl->isLocalVarDecl() && Type.getTypePtr()->isAnyPointerType() && NamingStyles[SK_LocalPointer])
566  return SK_LocalPointer;
567 
568  if (Decl->isLocalVarDecl() && NamingStyles[SK_LocalVariable])
569  return SK_LocalVariable;
570 
571  if (Decl->isFunctionOrMethodVarDecl() && NamingStyles[SK_LocalVariable])
572  return SK_LocalVariable;
573 
574  if (NamingStyles[SK_Variable])
575  return SK_Variable;
576 
577  return SK_Invalid;
578  }
579 
580  if (const auto *Decl = dyn_cast<CXXMethodDecl>(D)) {
581  if (Decl->isMain() || !Decl->isUserProvided() ||
582  Decl->size_overridden_methods() > 0)
583  return SK_Invalid;
584 
585  // If this method has the same name as any base method, this is likely
586  // necessary even if it's not an override. e.g. CRTP.
587  auto FindHidden = [&](const CXXBaseSpecifier *S, clang::CXXBasePath &P) {
588  return CXXRecordDecl::FindOrdinaryMember(S, P, Decl->getDeclName());
589  };
590  CXXBasePaths UnusedPaths;
591  if (Decl->getParent()->lookupInBases(FindHidden, UnusedPaths))
592  return SK_Invalid;
593 
594  if (Decl->isConstexpr() && NamingStyles[SK_ConstexprMethod])
595  return SK_ConstexprMethod;
596 
597  if (Decl->isConstexpr() && NamingStyles[SK_ConstexprFunction])
598  return SK_ConstexprFunction;
599 
600  if (Decl->isStatic() && NamingStyles[SK_ClassMethod])
601  return SK_ClassMethod;
602 
603  if (Decl->isVirtual() && NamingStyles[SK_VirtualMethod])
604  return SK_VirtualMethod;
605 
606  if (Decl->getAccess() == AS_private && NamingStyles[SK_PrivateMethod])
607  return SK_PrivateMethod;
608 
609  if (Decl->getAccess() == AS_protected && NamingStyles[SK_ProtectedMethod])
610  return SK_ProtectedMethod;
611 
612  if (Decl->getAccess() == AS_public && NamingStyles[SK_PublicMethod])
613  return SK_PublicMethod;
614 
615  if (NamingStyles[SK_Method])
616  return SK_Method;
617 
618  if (NamingStyles[SK_Function])
619  return SK_Function;
620 
621  return SK_Invalid;
622  }
623 
624  if (const auto *Decl = dyn_cast<FunctionDecl>(D)) {
625  if (Decl->isMain())
626  return SK_Invalid;
627 
628  if (Decl->isConstexpr() && NamingStyles[SK_ConstexprFunction])
629  return SK_ConstexprFunction;
630 
631  if (Decl->isGlobal() && NamingStyles[SK_GlobalFunction])
632  return SK_GlobalFunction;
633 
634  if (NamingStyles[SK_Function])
635  return SK_Function;
636  }
637 
638  if (isa<TemplateTypeParmDecl>(D)) {
639  if (NamingStyles[SK_TypeTemplateParameter])
640  return SK_TypeTemplateParameter;
641 
642  if (NamingStyles[SK_TemplateParameter])
643  return SK_TemplateParameter;
644 
645  return SK_Invalid;
646  }
647 
648  if (isa<NonTypeTemplateParmDecl>(D)) {
649  if (NamingStyles[SK_ValueTemplateParameter])
650  return SK_ValueTemplateParameter;
651 
652  if (NamingStyles[SK_TemplateParameter])
653  return SK_TemplateParameter;
654 
655  return SK_Invalid;
656  }
657 
658  if (isa<TemplateTemplateParmDecl>(D)) {
659  if (NamingStyles[SK_TemplateTemplateParameter])
660  return SK_TemplateTemplateParameter;
661 
662  if (NamingStyles[SK_TemplateParameter])
663  return SK_TemplateParameter;
664 
665  return SK_Invalid;
666  }
667 
668  return SK_Invalid;
669 }
670 
673  SourceRange Range, SourceManager *SourceMgr = nullptr) {
674  // Do nothing if the provided range is invalid.
675  if (Range.getBegin().isInvalid() || Range.getEnd().isInvalid())
676  return;
677 
678  // If we have a source manager, use it to convert to the spelling location for
679  // performing the fix. This is necessary because macros can map the same
680  // spelling location to different source locations, and we only want to fix
681  // the token once, before it is expanded by the macro.
682  SourceLocation FixLocation = Range.getBegin();
683  if (SourceMgr)
684  FixLocation = SourceMgr->getSpellingLoc(FixLocation);
685  if (FixLocation.isInvalid())
686  return;
687 
688  // Try to insert the identifier location in the Usages map, and bail out if it
689  // is already in there
690  auto &Failure = Failures[Decl];
691  if (!Failure.RawUsageLocs.insert(FixLocation.getRawEncoding()).second)
692  return;
693 
694  if (!Failure.ShouldFix)
695  return;
696 
697  Failure.ShouldFix = utils::rangeCanBeFixed(Range, SourceMgr);
698 }
699 
700 /// Convenience method when the usage to be added is a NamedDecl
702  const NamedDecl *Decl, SourceRange Range,
703  SourceManager *SourceMgr = nullptr) {
704  return addUsage(Failures,
705  IdentifierNamingCheck::NamingCheckId(Decl->getLocation(),
706  Decl->getNameAsString()),
707  Range, SourceMgr);
708 }
709 
710 void IdentifierNamingCheck::check(const MatchFinder::MatchResult &Result) {
711  if (const auto *Decl =
712  Result.Nodes.getNodeAs<CXXConstructorDecl>("classRef")) {
713  if (Decl->isImplicit())
714  return;
715 
716  addUsage(NamingCheckFailures, Decl->getParent(),
717  Decl->getNameInfo().getSourceRange());
718 
719  for (const auto *Init : Decl->inits()) {
720  if (!Init->isWritten() || Init->isInClassMemberInitializer())
721  continue;
722  if (const auto *FD = Init->getAnyMember())
723  addUsage(NamingCheckFailures, FD,
724  SourceRange(Init->getMemberLocation()));
725  // Note: delegating constructors and base class initializers are handled
726  // via the "typeLoc" matcher.
727  }
728  return;
729  }
730 
731  if (const auto *Decl =
732  Result.Nodes.getNodeAs<CXXDestructorDecl>("classRef")) {
733  if (Decl->isImplicit())
734  return;
735 
736  SourceRange Range = Decl->getNameInfo().getSourceRange();
737  if (Range.getBegin().isInvalid())
738  return;
739  // The first token that will be found is the ~ (or the equivalent trigraph),
740  // we want instead to replace the next token, that will be the identifier.
741  Range.setBegin(CharSourceRange::getTokenRange(Range).getEnd());
742 
743  addUsage(NamingCheckFailures, Decl->getParent(), Range);
744  return;
745  }
746 
747  if (const auto *Loc = Result.Nodes.getNodeAs<TypeLoc>("typeLoc")) {
748  NamedDecl *Decl = nullptr;
749  if (const auto &Ref = Loc->getAs<TagTypeLoc>()) {
750  Decl = Ref.getDecl();
751  } else if (const auto &Ref = Loc->getAs<InjectedClassNameTypeLoc>()) {
752  Decl = Ref.getDecl();
753  } else if (const auto &Ref = Loc->getAs<UnresolvedUsingTypeLoc>()) {
754  Decl = Ref.getDecl();
755  } else if (const auto &Ref = Loc->getAs<TemplateTypeParmTypeLoc>()) {
756  Decl = Ref.getDecl();
757  }
758 
759  if (Decl) {
760  addUsage(NamingCheckFailures, Decl, Loc->getSourceRange());
761  return;
762  }
763 
764  if (const auto &Ref = Loc->getAs<TemplateSpecializationTypeLoc>()) {
765  const auto *Decl =
766  Ref.getTypePtr()->getTemplateName().getAsTemplateDecl();
767 
768  SourceRange Range(Ref.getTemplateNameLoc(), Ref.getTemplateNameLoc());
769  if (const auto *ClassDecl = dyn_cast<TemplateDecl>(Decl)) {
770  if (const auto *TemplDecl = ClassDecl->getTemplatedDecl())
771  addUsage(NamingCheckFailures, TemplDecl, Range);
772  return;
773  }
774  }
775 
776  if (const auto &Ref =
777  Loc->getAs<DependentTemplateSpecializationTypeLoc>()) {
778  if (const auto *Decl = Ref.getTypePtr()->getAsTagDecl())
779  addUsage(NamingCheckFailures, Decl, Loc->getSourceRange());
780  return;
781  }
782  }
783 
784  if (const auto *Loc =
785  Result.Nodes.getNodeAs<NestedNameSpecifierLoc>("nestedNameLoc")) {
786  if (NestedNameSpecifier *Spec = Loc->getNestedNameSpecifier()) {
787  if (NamespaceDecl *Decl = Spec->getAsNamespace()) {
788  addUsage(NamingCheckFailures, Decl, Loc->getLocalSourceRange());
789  return;
790  }
791  }
792  }
793 
794  if (const auto *Decl = Result.Nodes.getNodeAs<UsingDecl>("using")) {
795  for (const auto &Shadow : Decl->shadows()) {
796  addUsage(NamingCheckFailures, Shadow->getTargetDecl(),
797  Decl->getNameInfo().getSourceRange());
798  }
799  return;
800  }
801 
802  if (const auto *DeclRef = Result.Nodes.getNodeAs<DeclRefExpr>("declRef")) {
803  SourceRange Range = DeclRef->getNameInfo().getSourceRange();
804  addUsage(NamingCheckFailures, DeclRef->getDecl(), Range,
805  Result.SourceManager);
806  return;
807  }
808 
809  if (const auto *Decl = Result.Nodes.getNodeAs<NamedDecl>("decl")) {
810  if (!Decl->getIdentifier() || Decl->getName().empty() || Decl->isImplicit())
811  return;
812 
813  // Fix type aliases in value declarations
814  if (const auto *Value = Result.Nodes.getNodeAs<ValueDecl>("decl")) {
815  if (const auto *TypePtr = Value->getType().getTypePtrOrNull()) {
816  if (const auto *Typedef = TypePtr->getAs<TypedefType>()) {
817  addUsage(NamingCheckFailures, Typedef->getDecl(),
818  Value->getSourceRange());
819  }
820  }
821  }
822 
823  // Fix type aliases in function declarations
824  if (const auto *Value = Result.Nodes.getNodeAs<FunctionDecl>("decl")) {
825  if (const auto *Typedef =
826  Value->getReturnType().getTypePtr()->getAs<TypedefType>()) {
827  addUsage(NamingCheckFailures, Typedef->getDecl(),
828  Value->getSourceRange());
829  }
830  for (unsigned i = 0; i < Value->getNumParams(); ++i) {
831  if (const auto *Typedef = Value->parameters()[i]
832  ->getType()
833  .getTypePtr()
834  ->getAs<TypedefType>()) {
835  addUsage(NamingCheckFailures, Typedef->getDecl(),
836  Value->getSourceRange());
837  }
838  }
839  }
840 
841  // Ignore ClassTemplateSpecializationDecl which are creating duplicate
842  // replacements with CXXRecordDecl
843  if (isa<ClassTemplateSpecializationDecl>(Decl))
844  return;
845 
846  StyleKind SK = findStyleKind(Decl, NamingStyles);
847  if (SK == SK_Invalid)
848  return;
849 
850  if (!NamingStyles[SK])
851  return;
852 
853  const NamingStyle &Style = *NamingStyles[SK];
854  StringRef Name = Decl->getName();
855  if (matchesStyle(Name, Style))
856  return;
857 
858  std::string KindName = fixupWithCase(StyleNames[SK], CT_LowerCase);
859  std::replace(KindName.begin(), KindName.end(), '_', ' ');
860 
861  std::string Fixup = fixupWithStyle(Name, Style);
862  if (StringRef(Fixup).equals(Name)) {
863  if (!IgnoreFailedSplit) {
864  LLVM_DEBUG(llvm::dbgs()
865  << Decl->getBeginLoc().printToString(*Result.SourceManager)
866  << llvm::format(": unable to split words for %s '%s'\n",
867  KindName.c_str(), Name.str().c_str()));
868  }
869  } else {
870  NamingCheckFailure &Failure = NamingCheckFailures[NamingCheckId(
871  Decl->getLocation(), Decl->getNameAsString())];
872  SourceRange Range =
873  DeclarationNameInfo(Decl->getDeclName(), Decl->getLocation())
874  .getSourceRange();
875 
876  Failure.Fixup = std::move(Fixup);
877  Failure.KindName = std::move(KindName);
878  addUsage(NamingCheckFailures, Decl, Range);
879  }
880  }
881 }
882 
883 void IdentifierNamingCheck::checkMacro(SourceManager &SourceMgr,
884  const Token &MacroNameTok,
885  const MacroInfo *MI) {
886  if (!NamingStyles[SK_MacroDefinition])
887  return;
888 
889  StringRef Name = MacroNameTok.getIdentifierInfo()->getName();
890  const NamingStyle &Style = *NamingStyles[SK_MacroDefinition];
891  if (matchesStyle(Name, Style))
892  return;
893 
894  std::string KindName =
895  fixupWithCase(StyleNames[SK_MacroDefinition], CT_LowerCase);
896  std::replace(KindName.begin(), KindName.end(), '_', ' ');
897 
898  std::string Fixup = fixupWithStyle(Name, Style);
899  if (StringRef(Fixup).equals(Name)) {
900  if (!IgnoreFailedSplit) {
901  LLVM_DEBUG(llvm::dbgs()
902  << MacroNameTok.getLocation().printToString(SourceMgr)
903  << llvm::format(": unable to split words for %s '%s'\n",
904  KindName.c_str(), Name.str().c_str()));
905  }
906  } else {
907  NamingCheckId ID(MI->getDefinitionLoc(), Name);
908  NamingCheckFailure &Failure = NamingCheckFailures[ID];
909  SourceRange Range(MacroNameTok.getLocation(), MacroNameTok.getEndLoc());
910 
911  Failure.Fixup = std::move(Fixup);
912  Failure.KindName = std::move(KindName);
913  addUsage(NamingCheckFailures, ID, Range);
914  }
915 }
916 
917 void IdentifierNamingCheck::expandMacro(const Token &MacroNameTok,
918  const MacroInfo *MI) {
919  StringRef Name = MacroNameTok.getIdentifierInfo()->getName();
920  NamingCheckId ID(MI->getDefinitionLoc(), Name);
921 
922  auto Failure = NamingCheckFailures.find(ID);
923  if (Failure == NamingCheckFailures.end())
924  return;
925 
926  SourceRange Range(MacroNameTok.getLocation(), MacroNameTok.getEndLoc());
927  addUsage(NamingCheckFailures, ID, Range);
928 }
929 
931  for (const auto &Pair : NamingCheckFailures) {
932  const NamingCheckId &Decl = Pair.first;
933  const NamingCheckFailure &Failure = Pair.second;
934 
935  if (Failure.KindName.empty())
936  continue;
937 
938  if (Failure.ShouldFix) {
939  auto Diag = diag(Decl.first, "invalid case style for %0 '%1'")
940  << Failure.KindName << Decl.second;
941 
942  for (const auto &Loc : Failure.RawUsageLocs) {
943  // We assume that the identifier name is made of one token only. This is
944  // always the case as we ignore usages in macros that could build
945  // identifier names by combining multiple tokens.
946  //
947  // For destructors, we alread take care of it by remembering the
948  // location of the start of the identifier and not the start of the
949  // tilde.
950  //
951  // Other multi-token identifiers, such as operators are not checked at
952  // all.
953  Diag << FixItHint::CreateReplacement(
954  SourceRange(SourceLocation::getFromRawEncoding(Loc)),
955  Failure.Fixup);
956  }
957  }
958  }
959 }
960 
961 } // namespace readability
962 } // namespace tidy
963 } // namespace clang
SourceLocation Loc
&#39;#&#39; location in the include directive
#define ENUMERATE(v)
Some operations such as code completion produce a set of candidates.
static void addUsage(IdentifierNamingCheck::NamingCheckFailureMap &Failures, const IdentifierNamingCheck::NamingCheckId &Decl, SourceRange Range, SourceManager *SourceMgr=nullptr)
Holds an identifier name check failure, tracking the kind of the identifer, its possible fixup and th...
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) override
Override this to register PPCallbacks in the preprocessor.
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.
static llvm::StringRef toString(SpecialMemberFunctionsCheck::SpecialMemberFunctionKind K)
Base class for all clang-tidy checks.
static std::string replace(llvm::StringRef Haystack, llvm::StringRef Needle, llvm::StringRef Repl)
Definition: TestIndex.cpp:30
static bool isEqual(const NamingCheckId &LHS, const NamingCheckId &RHS)
clang::tidy::readability::IdentifierNamingCheck::NamingCheckId NamingCheckId
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.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
static constexpr llvm::StringLiteral Name
std::map< std::string, std::string > OptionMap
const Decl * D
Definition: XRefs.cpp:849
llvm::Optional< Range > getTokenRange(const SourceManager &SM, const LangOptions &LangOpts, SourceLocation TokLoc)
Returns the taken range at TokLoc.
Definition: SourceCode.cpp:229
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.
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
static std::string fixupWithStyle(StringRef Name, const IdentifierNamingCheck::NamingStyle &Style)
llvm::DenseMap< NamingCheckId, NamingCheckFailure > NamingCheckFailureMap
static GeneratorRegistry::Add< MDGenerator > MD(MDGenerator::Format, "Generator for MD output.")
static StyleKind findStyleKind(const NamedDecl *D, const std::vector< llvm::Optional< IdentifierNamingCheck::NamingStyle >> &NamingStyles)
CharSourceRange Range
SourceRange for the file name.
bool rangeCanBeFixed(SourceRange Range, const SourceManager *SM)
Definition: ASTUtils.cpp:90
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.
std::string Word
std::string get(StringRef LocalName, StringRef Default) const
Read a named option from the Context.
const DeclRefExpr * DeclRef
NodeType Type
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check&#39;s name.
Checks for identifiers naming style mismatch.
bool ShouldFix
Whether the failure should be fixed or not.