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