clang-tools  9.0.0
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/Frontend/CompilerInstance.h"
14 #include "clang/Lex/PPCallbacks.h"
15 #include "clang/Lex/Preprocessor.h"
16 #include "llvm/ADT/DenseMapInfo.h"
17 #include "llvm/Support/Debug.h"
18 #include "llvm/Support/Format.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(const NamingCheckId &LHS, const 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(GlobalConstantPointer) \
81  m(GlobalPointer) \
82  m(GlobalVariable) \
83  m(LocalConstant) \
84  m(LocalConstantPointer) \
85  m(LocalPointer) \
86  m(LocalVariable) \
87  m(StaticConstant) \
88  m(StaticVariable) \
89  m(Constant) \
90  m(Variable) \
91  m(ConstantParameter) \
92  m(ParameterPack) \
93  m(Parameter) \
94  m(PointerParameter) \
95  m(ConstantPointerParameter) \
96  m(AbstractClass) \
97  m(Struct) \
98  m(Class) \
99  m(Union) \
100  m(Enum) \
101  m(GlobalFunction) \
102  m(ConstexprFunction) \
103  m(Function) \
104  m(ConstexprMethod) \
105  m(VirtualMethod) \
106  m(ClassMethod) \
107  m(PrivateMethod) \
108  m(ProtectedMethod) \
109  m(PublicMethod) \
110  m(Method) \
111  m(Typedef) \
112  m(TypeTemplateParameter) \
113  m(ValueTemplateParameter) \
114  m(TemplateTemplateParameter) \
115  m(TemplateParameter) \
116  m(TypeAlias) \
117  m(MacroDefinition) \
118  m(ObjcIvar) \
119 
120 enum StyleKind {
121 #define ENUMERATE(v) SK_ ## v,
123 #undef ENUMERATE
126 };
127 
128 static StringRef const StyleNames[] = {
129 #define STRINGIZE(v) #v,
131 #undef STRINGIZE
132 };
133 
134 #undef NAMING_KEYS
135 // clang-format on
136 
137 namespace {
138 /// Callback supplies macros to IdentifierNamingCheck::checkMacro
139 class IdentifierNamingCheckPPCallbacks : public PPCallbacks {
140 public:
141  IdentifierNamingCheckPPCallbacks(Preprocessor *PP,
142  IdentifierNamingCheck *Check)
143  : PP(PP), Check(Check) {}
144 
145  /// MacroDefined calls checkMacro for macros in the main file
146  void MacroDefined(const Token &MacroNameTok,
147  const MacroDirective *MD) override {
148  Check->checkMacro(PP->getSourceManager(), MacroNameTok, MD->getMacroInfo());
149  }
150 
151  /// MacroExpands calls expandMacro for macros in the main file
152  void MacroExpands(const Token &MacroNameTok, const MacroDefinition &MD,
153  SourceRange /*Range*/,
154  const MacroArgs * /*Args*/) override {
155  Check->expandMacro(MacroNameTok, MD.getMacroInfo());
156  }
157 
158 private:
159  Preprocessor *PP;
160  IdentifierNamingCheck *Check;
161 };
162 } // namespace
163 
164 IdentifierNamingCheck::IdentifierNamingCheck(StringRef Name,
165  ClangTidyContext *Context)
166  : ClangTidyCheck(Name, Context) {
167  auto const fromString = [](StringRef Str) {
168  return llvm::StringSwitch<llvm::Optional<CaseType>>(Str)
169  .Case("aNy_CasE", CT_AnyCase)
170  .Case("lower_case", CT_LowerCase)
171  .Case("UPPER_CASE", CT_UpperCase)
172  .Case("camelBack", CT_CamelBack)
173  .Case("CamelCase", CT_CamelCase)
174  .Case("Camel_Snake_Case", CT_CamelSnakeCase)
175  .Case("camel_Snake_Back", CT_CamelSnakeBack)
176  .Default(llvm::None);
177  };
178 
179  for (auto const &Name : StyleNames) {
180  auto const caseOptional =
181  fromString(Options.get((Name + "Case").str(), ""));
182  auto prefix = Options.get((Name + "Prefix").str(), "");
183  auto postfix = Options.get((Name + "Suffix").str(), "");
184 
185  if (caseOptional || !prefix.empty() || !postfix.empty()) {
186  NamingStyles.push_back(NamingStyle(caseOptional, prefix, postfix));
187  } else {
188  NamingStyles.push_back(llvm::None);
189  }
190  }
191 
192  IgnoreFailedSplit = Options.get("IgnoreFailedSplit", 0);
193 }
194 
196  auto const toString = [](CaseType Type) {
197  switch (Type) {
198  case CT_AnyCase:
199  return "aNy_CasE";
200  case CT_LowerCase:
201  return "lower_case";
202  case CT_CamelBack:
203  return "camelBack";
204  case CT_UpperCase:
205  return "UPPER_CASE";
206  case CT_CamelCase:
207  return "CamelCase";
208  case CT_CamelSnakeCase:
209  return "Camel_Snake_Case";
210  case CT_CamelSnakeBack:
211  return "camel_Snake_Back";
212  }
213 
214  llvm_unreachable("Unknown Case Type");
215  };
216 
217  for (size_t i = 0; i < SK_Count; ++i) {
218  if (NamingStyles[i]) {
219  if (NamingStyles[i]->Case) {
220  Options.store(Opts, (StyleNames[i] + "Case").str(),
221  toString(*NamingStyles[i]->Case));
222  }
223  Options.store(Opts, (StyleNames[i] + "Prefix").str(),
224  NamingStyles[i]->Prefix);
225  Options.store(Opts, (StyleNames[i] + "Suffix").str(),
226  NamingStyles[i]->Suffix);
227  }
228  }
229 
230  Options.store(Opts, "IgnoreFailedSplit", IgnoreFailedSplit);
231 }
232 
233 void IdentifierNamingCheck::registerMatchers(MatchFinder *Finder) {
234  Finder->addMatcher(namedDecl().bind("decl"), this);
235  Finder->addMatcher(usingDecl().bind("using"), this);
236  Finder->addMatcher(declRefExpr().bind("declRef"), this);
237  Finder->addMatcher(cxxConstructorDecl().bind("classRef"), this);
238  Finder->addMatcher(cxxDestructorDecl().bind("classRef"), this);
239  Finder->addMatcher(typeLoc().bind("typeLoc"), this);
240  Finder->addMatcher(nestedNameSpecifierLoc().bind("nestedNameLoc"), this);
241 }
242 
244  const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) {
245  ModuleExpanderPP->addPPCallbacks(
246  llvm::make_unique<IdentifierNamingCheckPPCallbacks>(ModuleExpanderPP,
247  this));
248 }
249 
250 static bool matchesStyle(StringRef Name,
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,
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) {
318  Fixup += Name;
319  break;
320 
322  for (auto const &Word : Words) {
323  if (&Word != &Words.front())
324  Fixup += "_";
325  Fixup += Word.lower();
326  }
327  break;
328 
330  for (auto const &Word : Words) {
331  if (&Word != &Words.front())
332  Fixup += "_";
333  Fixup += Word.upper();
334  }
335  break;
336 
338  for (auto const &Word : Words) {
339  Fixup += Word.substr(0, 1).upper();
340  Fixup += Word.substr(1).lower();
341  }
342  break;
343 
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 
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 
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
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 
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 
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
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 *TypePtr = Value->getType().getTypePtrOrNull()) {
804  if (const auto *Typedef = TypePtr->getAs<TypedefType>()) {
805  addUsage(NamingCheckFailures, Typedef->getDecl(),
806  Value->getSourceRange());
807  }
808  }
809  }
810 
811  // Fix type aliases in function declarations
812  if (const auto *Value = Result.Nodes.getNodeAs<FunctionDecl>("decl")) {
813  if (const auto *Typedef =
814  Value->getReturnType().getTypePtr()->getAs<TypedefType>()) {
815  addUsage(NamingCheckFailures, Typedef->getDecl(),
816  Value->getSourceRange());
817  }
818  for (unsigned i = 0; i < Value->getNumParams(); ++i) {
819  if (const auto *Typedef = Value->parameters()[i]
820  ->getType()
821  .getTypePtr()
822  ->getAs<TypedefType>()) {
823  addUsage(NamingCheckFailures, Typedef->getDecl(),
824  Value->getSourceRange());
825  }
826  }
827  }
828 
829  // Ignore ClassTemplateSpecializationDecl which are creating duplicate
830  // replacements with CXXRecordDecl
831  if (isa<ClassTemplateSpecializationDecl>(Decl))
832  return;
833 
834  StyleKind SK = findStyleKind(Decl, NamingStyles);
835  if (SK == SK_Invalid)
836  return;
837 
838  if (!NamingStyles[SK])
839  return;
840 
841  const NamingStyle &Style = *NamingStyles[SK];
842  StringRef Name = Decl->getName();
843  if (matchesStyle(Name, Style))
844  return;
845 
846  std::string KindName = fixupWithCase(StyleNames[SK], CT_LowerCase);
847  std::replace(KindName.begin(), KindName.end(), '_', ' ');
848 
849  std::string Fixup = fixupWithStyle(Name, Style);
850  if (StringRef(Fixup).equals(Name)) {
851  if (!IgnoreFailedSplit) {
852  LLVM_DEBUG(llvm::dbgs()
853  << Decl->getBeginLoc().printToString(*Result.SourceManager)
854  << llvm::format(": unable to split words for %s '%s'\n",
855  KindName.c_str(), Name.str().c_str()));
856  }
857  } else {
858  NamingCheckFailure &Failure = NamingCheckFailures[NamingCheckId(
859  Decl->getLocation(), Decl->getNameAsString())];
860  SourceRange Range =
861  DeclarationNameInfo(Decl->getDeclName(), Decl->getLocation())
862  .getSourceRange();
863 
864  Failure.Fixup = std::move(Fixup);
865  Failure.KindName = std::move(KindName);
866  addUsage(NamingCheckFailures, Decl, Range);
867  }
868  }
869 }
870 
871 void IdentifierNamingCheck::checkMacro(SourceManager &SourceMgr,
872  const Token &MacroNameTok,
873  const MacroInfo *MI) {
874  if (!NamingStyles[SK_MacroDefinition])
875  return;
876 
877  StringRef Name = MacroNameTok.getIdentifierInfo()->getName();
878  const NamingStyle &Style = *NamingStyles[SK_MacroDefinition];
879  if (matchesStyle(Name, Style))
880  return;
881 
882  std::string KindName =
883  fixupWithCase(StyleNames[SK_MacroDefinition], CT_LowerCase);
884  std::replace(KindName.begin(), KindName.end(), '_', ' ');
885 
886  std::string Fixup = fixupWithStyle(Name, Style);
887  if (StringRef(Fixup).equals(Name)) {
888  if (!IgnoreFailedSplit) {
889  LLVM_DEBUG(llvm::dbgs()
890  << MacroNameTok.getLocation().printToString(SourceMgr)
891  << llvm::format(": unable to split words for %s '%s'\n",
892  KindName.c_str(), Name.str().c_str()));
893  }
894  } else {
895  NamingCheckId ID(MI->getDefinitionLoc(), Name);
896  NamingCheckFailure &Failure = NamingCheckFailures[ID];
897  SourceRange Range(MacroNameTok.getLocation(), MacroNameTok.getEndLoc());
898 
899  Failure.Fixup = std::move(Fixup);
900  Failure.KindName = std::move(KindName);
901  addUsage(NamingCheckFailures, ID, Range);
902  }
903 }
904 
905 void IdentifierNamingCheck::expandMacro(const Token &MacroNameTok,
906  const MacroInfo *MI) {
907  StringRef Name = MacroNameTok.getIdentifierInfo()->getName();
908  NamingCheckId ID(MI->getDefinitionLoc(), Name);
909 
910  auto Failure = NamingCheckFailures.find(ID);
911  if (Failure == NamingCheckFailures.end())
912  return;
913 
914  SourceRange Range(MacroNameTok.getLocation(), MacroNameTok.getEndLoc());
915  addUsage(NamingCheckFailures, ID, Range);
916 }
917 
919  for (const auto &Pair : NamingCheckFailures) {
920  const NamingCheckId &Decl = Pair.first;
921  const NamingCheckFailure &Failure = Pair.second;
922 
923  if (Failure.KindName.empty())
924  continue;
925 
926  if (Failure.ShouldFix) {
927  auto Diag = diag(Decl.first, "invalid case style for %0 '%1'")
928  << Failure.KindName << Decl.second;
929 
930  for (const auto &Loc : Failure.RawUsageLocs) {
931  // We assume that the identifier name is made of one token only. This is
932  // always the case as we ignore usages in macros that could build
933  // identifier names by combining multiple tokens.
934  //
935  // For destructors, we alread take care of it by remembering the
936  // location of the start of the identifier and not the start of the
937  // tilde.
938  //
939  // Other multi-token identifiers, such as operators are not checked at
940  // all.
941  Diag << FixItHint::CreateReplacement(
942  SourceRange(SourceLocation::getFromRawEncoding(Loc)),
943  Failure.Fixup);
944  }
945  }
946  }
947 }
948 
949 } // namespace readability
950 } // namespace tidy
951 } // 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:868
llvm::Optional< Range > getTokenRange(const SourceManager &SM, const LangOptions &LangOpts, SourceLocation TokLoc)
Returns the taken range at TokLoc.
Definition: SourceCode.cpp:203
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.
llvm::Optional< llvm::Expected< tooling::AtomicChanges > > Result
Definition: Rename.cpp:36
#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.