clang-tools  6.0.0
IdentifierNamingCheck.cpp
Go to the documentation of this file.
1 //===--- IdentifierNamingCheck.cpp - clang-tidy ---------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "IdentifierNamingCheck.h"
11 
12 #include "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(GlobalVariable) \
81  m(LocalConstant) \
82  m(LocalVariable) \
83  m(StaticConstant) \
84  m(StaticVariable) \
85  m(Constant) \
86  m(Variable) \
87  m(ConstantParameter) \
88  m(ParameterPack) \
89  m(Parameter) \
90  m(AbstractClass) \
91  m(Struct) \
92  m(Class) \
93  m(Union) \
94  m(Enum) \
95  m(GlobalFunction) \
96  m(ConstexprFunction) \
97  m(Function) \
98  m(ConstexprMethod) \
99  m(VirtualMethod) \
100  m(ClassMethod) \
101  m(PrivateMethod) \
102  m(ProtectedMethod) \
103  m(PublicMethod) \
104  m(Method) \
105  m(Typedef) \
106  m(TypeTemplateParameter) \
107  m(ValueTemplateParameter) \
108  m(TemplateTemplateParameter) \
109  m(TemplateParameter) \
110  m(TypeAlias) \
111  m(MacroDefinition) \
112 
113 enum StyleKind {
114 #define ENUMERATE(v) SK_ ## v,
116 #undef ENUMERATE
119 };
120 
121 static StringRef const StyleNames[] = {
122 #define STRINGIZE(v) #v,
124 #undef STRINGIZE
125 };
126 
127 #undef NAMING_KEYS
128 // clang-format on
129 
130 namespace {
131 /// Callback supplies macros to IdentifierNamingCheck::checkMacro
132 class IdentifierNamingCheckPPCallbacks : public PPCallbacks {
133 public:
134  IdentifierNamingCheckPPCallbacks(Preprocessor *PP,
135  IdentifierNamingCheck *Check)
136  : PP(PP), Check(Check) {}
137 
138  /// MacroDefined calls checkMacro for macros in the main file
139  void MacroDefined(const Token &MacroNameTok,
140  const MacroDirective *MD) override {
141  Check->checkMacro(PP->getSourceManager(), MacroNameTok, MD->getMacroInfo());
142  }
143 
144  /// MacroExpands calls expandMacro for macros in the main file
145  void MacroExpands(const Token &MacroNameTok, const MacroDefinition &MD,
146  SourceRange /*Range*/,
147  const MacroArgs * /*Args*/) override {
148  Check->expandMacro(MacroNameTok, MD.getMacroInfo());
149  }
150 
151 private:
152  Preprocessor *PP;
153  IdentifierNamingCheck *Check;
154 };
155 } // namespace
156 
157 IdentifierNamingCheck::IdentifierNamingCheck(StringRef Name,
158  ClangTidyContext *Context)
159  : ClangTidyCheck(Name, Context) {
160  auto const fromString = [](StringRef Str) {
161  return llvm::StringSwitch<llvm::Optional<CaseType>>(Str)
162  .Case("aNy_CasE", CT_AnyCase)
163  .Case("lower_case", CT_LowerCase)
164  .Case("UPPER_CASE", CT_UpperCase)
165  .Case("camelBack", CT_CamelBack)
166  .Case("CamelCase", CT_CamelCase)
167  .Case("Camel_Snake_Case", CT_CamelSnakeCase)
168  .Case("camel_Snake_Back", CT_CamelSnakeBack)
169  .Default(llvm::None);
170  };
171 
172  for (auto const &Name : StyleNames) {
173  auto const caseOptional =
174  fromString(Options.get((Name + "Case").str(), ""));
175  auto prefix = Options.get((Name + "Prefix").str(), "");
176  auto postfix = Options.get((Name + "Suffix").str(), "");
177 
178  if (caseOptional || !prefix.empty() || !postfix.empty()) {
179  NamingStyles.push_back(NamingStyle(caseOptional, prefix, postfix));
180  } else {
181  NamingStyles.push_back(llvm::None);
182  }
183  }
184 
185  IgnoreFailedSplit = Options.get("IgnoreFailedSplit", 0);
186 }
187 
189  auto const toString = [](CaseType Type) {
190  switch (Type) {
191  case CT_AnyCase:
192  return "aNy_CasE";
193  case CT_LowerCase:
194  return "lower_case";
195  case CT_CamelBack:
196  return "camelBack";
197  case CT_UpperCase:
198  return "UPPER_CASE";
199  case CT_CamelCase:
200  return "CamelCase";
201  case CT_CamelSnakeCase:
202  return "Camel_Snake_Case";
203  case CT_CamelSnakeBack:
204  return "camel_Snake_Back";
205  }
206 
207  llvm_unreachable("Unknown Case Type");
208  };
209 
210  for (size_t i = 0; i < SK_Count; ++i) {
211  if (NamingStyles[i]) {
212  if (NamingStyles[i]->Case) {
213  Options.store(Opts, (StyleNames[i] + "Case").str(),
214  toString(*NamingStyles[i]->Case));
215  }
216  Options.store(Opts, (StyleNames[i] + "Prefix").str(),
217  NamingStyles[i]->Prefix);
218  Options.store(Opts, (StyleNames[i] + "Suffix").str(),
219  NamingStyles[i]->Suffix);
220  }
221  }
222 
223  Options.store(Opts, "IgnoreFailedSplit", IgnoreFailedSplit);
224 }
225 
226 void IdentifierNamingCheck::registerMatchers(MatchFinder *Finder) {
227  Finder->addMatcher(namedDecl().bind("decl"), this);
228  Finder->addMatcher(usingDecl().bind("using"), this);
229  Finder->addMatcher(declRefExpr().bind("declRef"), this);
230  Finder->addMatcher(cxxConstructorDecl().bind("classRef"), this);
231  Finder->addMatcher(cxxDestructorDecl().bind("classRef"), this);
232  Finder->addMatcher(typeLoc().bind("typeLoc"), this);
233  Finder->addMatcher(nestedNameSpecifierLoc().bind("nestedNameLoc"), this);
234 }
235 
236 void IdentifierNamingCheck::registerPPCallbacks(CompilerInstance &Compiler) {
237  Compiler.getPreprocessor().addPPCallbacks(
238  llvm::make_unique<IdentifierNamingCheckPPCallbacks>(
239  &Compiler.getPreprocessor(), this));
240 }
241 
242 static bool matchesStyle(StringRef Name,
244  static llvm::Regex Matchers[] = {
245  llvm::Regex("^.*$"),
246  llvm::Regex("^[a-z][a-z0-9_]*$"),
247  llvm::Regex("^[a-z][a-zA-Z0-9]*$"),
248  llvm::Regex("^[A-Z][A-Z0-9_]*$"),
249  llvm::Regex("^[A-Z][a-zA-Z0-9]*$"),
250  llvm::Regex("^[A-Z]([a-z0-9]*(_[A-Z])?)*"),
251  llvm::Regex("^[a-z]([a-z0-9]*(_[A-Z])?)*"),
252  };
253 
254  bool Matches = true;
255  if (Name.startswith(Style.Prefix))
256  Name = Name.drop_front(Style.Prefix.size());
257  else
258  Matches = false;
259 
260  if (Name.endswith(Style.Suffix))
261  Name = Name.drop_back(Style.Suffix.size());
262  else
263  Matches = false;
264 
265  // Ensure the name doesn't have any extra underscores beyond those specified
266  // in the prefix and suffix.
267  if (Name.startswith("_") || Name.endswith("_"))
268  Matches = false;
269 
270  if (Style.Case && !Matchers[static_cast<size_t>(*Style.Case)].match(Name))
271  Matches = false;
272 
273  return Matches;
274 }
275 
276 static std::string fixupWithCase(StringRef Name,
278  static llvm::Regex Splitter(
279  "([a-z0-9A-Z]*)(_+)|([A-Z]?[a-z0-9]+)([A-Z]|$)|([A-Z]+)([A-Z]|$)");
280 
281  SmallVector<StringRef, 8> Substrs;
282  Name.split(Substrs, "_", -1, false);
283 
284  SmallVector<StringRef, 8> Words;
285  for (auto Substr : Substrs) {
286  while (!Substr.empty()) {
287  SmallVector<StringRef, 8> Groups;
288  if (!Splitter.match(Substr, &Groups))
289  break;
290 
291  if (Groups[2].size() > 0) {
292  Words.push_back(Groups[1]);
293  Substr = Substr.substr(Groups[0].size());
294  } else if (Groups[3].size() > 0) {
295  Words.push_back(Groups[3]);
296  Substr = Substr.substr(Groups[0].size() - Groups[4].size());
297  } else if (Groups[5].size() > 0) {
298  Words.push_back(Groups[5]);
299  Substr = Substr.substr(Groups[0].size() - Groups[6].size());
300  }
301  }
302  }
303 
304  if (Words.empty())
305  return Name;
306 
307  std::string Fixup;
308  switch (Case) {
310  Fixup += Name;
311  break;
312 
314  for (auto const &Word : Words) {
315  if (&Word != &Words.front())
316  Fixup += "_";
317  Fixup += Word.lower();
318  }
319  break;
320 
322  for (auto const &Word : Words) {
323  if (&Word != &Words.front())
324  Fixup += "_";
325  Fixup += Word.upper();
326  }
327  break;
328 
330  for (auto const &Word : Words) {
331  Fixup += Word.substr(0, 1).upper();
332  Fixup += Word.substr(1).lower();
333  }
334  break;
335 
337  for (auto const &Word : Words) {
338  if (&Word == &Words.front()) {
339  Fixup += Word.lower();
340  } else {
341  Fixup += Word.substr(0, 1).upper();
342  Fixup += Word.substr(1).lower();
343  }
344  }
345  break;
346 
348  for (auto const &Word : Words) {
349  if (&Word != &Words.front())
350  Fixup += "_";
351  Fixup += Word.substr(0, 1).upper();
352  Fixup += Word.substr(1).lower();
353  }
354  break;
355 
357  for (auto const &Word : Words) {
358  if (&Word != &Words.front()) {
359  Fixup += "_";
360  Fixup += Word.substr(0, 1).upper();
361  } else {
362  Fixup += Word.substr(0, 1).lower();
363  }
364  Fixup += Word.substr(1).lower();
365  }
366  break;
367  }
368 
369  return Fixup;
370 }
371 
372 static std::string
374  const IdentifierNamingCheck::NamingStyle &Style) {
375  const std::string Fixed = fixupWithCase(
376  Name, Style.Case.getValueOr(IdentifierNamingCheck::CaseType::CT_AnyCase));
377  StringRef Mid = StringRef(Fixed).trim("_");
378  if (Mid.empty())
379  Mid = "_";
380  return (Style.Prefix + Mid + Style.Suffix).str();
381 }
382 
384  const NamedDecl *D,
385  const std::vector<llvm::Optional<IdentifierNamingCheck::NamingStyle>>
386  &NamingStyles) {
387  if (isa<TypedefDecl>(D) && NamingStyles[SK_Typedef])
388  return SK_Typedef;
389 
390  if (isa<TypeAliasDecl>(D) && NamingStyles[SK_TypeAlias])
391  return SK_TypeAlias;
392 
393  if (const auto *Decl = dyn_cast<NamespaceDecl>(D)) {
394  if (Decl->isAnonymousNamespace())
395  return SK_Invalid;
396 
397  if (Decl->isInline() && NamingStyles[SK_InlineNamespace])
398  return SK_InlineNamespace;
399 
400  if (NamingStyles[SK_Namespace])
401  return SK_Namespace;
402  }
403 
404  if (isa<EnumDecl>(D) && NamingStyles[SK_Enum])
405  return SK_Enum;
406 
407  if (isa<EnumConstantDecl>(D)) {
408  if (NamingStyles[SK_EnumConstant])
409  return SK_EnumConstant;
410 
411  if (NamingStyles[SK_Constant])
412  return SK_Constant;
413 
414  return SK_Invalid;
415  }
416 
417  if (const auto *Decl = dyn_cast<CXXRecordDecl>(D)) {
418  if (Decl->isAnonymousStructOrUnion())
419  return SK_Invalid;
420 
421  if (!Decl->getCanonicalDecl()->isThisDeclarationADefinition())
422  return SK_Invalid;
423 
424  if (Decl->hasDefinition() && Decl->isAbstract() &&
425  NamingStyles[SK_AbstractClass])
426  return SK_AbstractClass;
427 
428  if (Decl->isStruct() && NamingStyles[SK_Struct])
429  return SK_Struct;
430 
431  if (Decl->isStruct() && NamingStyles[SK_Class])
432  return SK_Class;
433 
434  if (Decl->isClass() && NamingStyles[SK_Class])
435  return SK_Class;
436 
437  if (Decl->isClass() && NamingStyles[SK_Struct])
438  return SK_Struct;
439 
440  if (Decl->isUnion() && NamingStyles[SK_Union])
441  return SK_Union;
442 
443  if (Decl->isEnum() && NamingStyles[SK_Enum])
444  return SK_Enum;
445 
446  return SK_Invalid;
447  }
448 
449  if (const auto *Decl = dyn_cast<FieldDecl>(D)) {
450  QualType Type = Decl->getType();
451 
452  if (!Type.isNull() && Type.isConstQualified()) {
453  if (NamingStyles[SK_ConstantMember])
454  return SK_ConstantMember;
455 
456  if (NamingStyles[SK_Constant])
457  return SK_Constant;
458  }
459 
460  if (Decl->getAccess() == AS_private && NamingStyles[SK_PrivateMember])
461  return SK_PrivateMember;
462 
463  if (Decl->getAccess() == AS_protected && NamingStyles[SK_ProtectedMember])
464  return SK_ProtectedMember;
465 
466  if (Decl->getAccess() == AS_public && NamingStyles[SK_PublicMember])
467  return SK_PublicMember;
468 
469  if (NamingStyles[SK_Member])
470  return SK_Member;
471 
472  return SK_Invalid;
473  }
474 
475  if (const auto *Decl = dyn_cast<ParmVarDecl>(D)) {
476  QualType Type = Decl->getType();
477 
478  if (Decl->isConstexpr() && NamingStyles[SK_ConstexprVariable])
479  return SK_ConstexprVariable;
480 
481  if (!Type.isNull() && Type.isConstQualified()) {
482  if (NamingStyles[SK_ConstantParameter])
483  return SK_ConstantParameter;
484 
485  if (NamingStyles[SK_Constant])
486  return SK_Constant;
487  }
488 
489  if (Decl->isParameterPack() && NamingStyles[SK_ParameterPack])
490  return SK_ParameterPack;
491 
492  if (NamingStyles[SK_Parameter])
493  return SK_Parameter;
494 
495  return SK_Invalid;
496  }
497 
498  if (const auto *Decl = dyn_cast<VarDecl>(D)) {
499  QualType Type = Decl->getType();
500 
501  if (Decl->isConstexpr() && NamingStyles[SK_ConstexprVariable])
502  return SK_ConstexprVariable;
503 
504  if (!Type.isNull() && Type.isConstQualified()) {
505  if (Decl->isStaticDataMember() && NamingStyles[SK_ClassConstant])
506  return SK_ClassConstant;
507 
508  if (Decl->isFileVarDecl() && NamingStyles[SK_GlobalConstant])
509  return SK_GlobalConstant;
510 
511  if (Decl->isStaticLocal() && NamingStyles[SK_StaticConstant])
512  return SK_StaticConstant;
513 
514  if (Decl->isLocalVarDecl() && NamingStyles[SK_LocalConstant])
515  return SK_LocalConstant;
516 
517  if (Decl->isFunctionOrMethodVarDecl() && NamingStyles[SK_LocalConstant])
518  return SK_LocalConstant;
519 
520  if (NamingStyles[SK_Constant])
521  return SK_Constant;
522  }
523 
524  if (Decl->isStaticDataMember() && NamingStyles[SK_ClassMember])
525  return SK_ClassMember;
526 
527  if (Decl->isFileVarDecl() && NamingStyles[SK_GlobalVariable])
528  return SK_GlobalVariable;
529 
530  if (Decl->isStaticLocal() && NamingStyles[SK_StaticVariable])
531  return SK_StaticVariable;
532 
533  if (Decl->isLocalVarDecl() && NamingStyles[SK_LocalVariable])
534  return SK_LocalVariable;
535 
536  if (Decl->isFunctionOrMethodVarDecl() && NamingStyles[SK_LocalVariable])
537  return SK_LocalVariable;
538 
539  if (NamingStyles[SK_Variable])
540  return SK_Variable;
541 
542  return SK_Invalid;
543  }
544 
545  if (const auto *Decl = dyn_cast<CXXMethodDecl>(D)) {
546  if (Decl->isMain() || !Decl->isUserProvided() ||
547  Decl->isUsualDeallocationFunction() ||
548  Decl->isCopyAssignmentOperator() || Decl->isMoveAssignmentOperator() ||
549  Decl->size_overridden_methods() > 0)
550  return SK_Invalid;
551 
552  if (Decl->isConstexpr() && NamingStyles[SK_ConstexprMethod])
553  return SK_ConstexprMethod;
554 
555  if (Decl->isConstexpr() && NamingStyles[SK_ConstexprFunction])
556  return SK_ConstexprFunction;
557 
558  if (Decl->isStatic() && NamingStyles[SK_ClassMethod])
559  return SK_ClassMethod;
560 
561  if (Decl->isVirtual() && NamingStyles[SK_VirtualMethod])
562  return SK_VirtualMethod;
563 
564  if (Decl->getAccess() == AS_private && NamingStyles[SK_PrivateMethod])
565  return SK_PrivateMethod;
566 
567  if (Decl->getAccess() == AS_protected && NamingStyles[SK_ProtectedMethod])
568  return SK_ProtectedMethod;
569 
570  if (Decl->getAccess() == AS_public && NamingStyles[SK_PublicMethod])
571  return SK_PublicMethod;
572 
573  if (NamingStyles[SK_Method])
574  return SK_Method;
575 
576  if (NamingStyles[SK_Function])
577  return SK_Function;
578 
579  return SK_Invalid;
580  }
581 
582  if (const auto *Decl = dyn_cast<FunctionDecl>(D)) {
583  if (Decl->isMain())
584  return SK_Invalid;
585 
586  if (Decl->isConstexpr() && NamingStyles[SK_ConstexprFunction])
587  return SK_ConstexprFunction;
588 
589  if (Decl->isGlobal() && NamingStyles[SK_GlobalFunction])
590  return SK_GlobalFunction;
591 
592  if (NamingStyles[SK_Function])
593  return SK_Function;
594  }
595 
596  if (isa<TemplateTypeParmDecl>(D)) {
597  if (NamingStyles[SK_TypeTemplateParameter])
598  return SK_TypeTemplateParameter;
599 
600  if (NamingStyles[SK_TemplateParameter])
601  return SK_TemplateParameter;
602 
603  return SK_Invalid;
604  }
605 
606  if (isa<NonTypeTemplateParmDecl>(D)) {
607  if (NamingStyles[SK_ValueTemplateParameter])
608  return SK_ValueTemplateParameter;
609 
610  if (NamingStyles[SK_TemplateParameter])
611  return SK_TemplateParameter;
612 
613  return SK_Invalid;
614  }
615 
616  if (isa<TemplateTemplateParmDecl>(D)) {
617  if (NamingStyles[SK_TemplateTemplateParameter])
618  return SK_TemplateTemplateParameter;
619 
620  if (NamingStyles[SK_TemplateParameter])
621  return SK_TemplateParameter;
622 
623  return SK_Invalid;
624  }
625 
626  return SK_Invalid;
627 }
628 
631  SourceRange Range, SourceManager *SourceMgr = nullptr) {
632  // Do nothing if the provided range is invalid.
633  if (Range.getBegin().isInvalid() || Range.getEnd().isInvalid())
634  return;
635 
636  // If we have a source manager, use it to convert to the spelling location for
637  // performing the fix. This is necessary because macros can map the same
638  // spelling location to different source locations, and we only want to fix
639  // the token once, before it is expanded by the macro.
640  SourceLocation FixLocation = Range.getBegin();
641  if (SourceMgr)
642  FixLocation = SourceMgr->getSpellingLoc(FixLocation);
643  if (FixLocation.isInvalid())
644  return;
645 
646  // Try to insert the identifier location in the Usages map, and bail out if it
647  // is already in there
648  auto &Failure = Failures[Decl];
649  if (!Failure.RawUsageLocs.insert(FixLocation.getRawEncoding()).second)
650  return;
651 
652  if (!Failure.ShouldFix)
653  return;
654 
655  // Check if the range is entirely contained within a macro argument.
656  SourceLocation MacroArgExpansionStartForRangeBegin;
657  SourceLocation MacroArgExpansionStartForRangeEnd;
658  bool RangeIsEntirelyWithinMacroArgument =
659  SourceMgr &&
660  SourceMgr->isMacroArgExpansion(Range.getBegin(),
661  &MacroArgExpansionStartForRangeBegin) &&
662  SourceMgr->isMacroArgExpansion(Range.getEnd(),
663  &MacroArgExpansionStartForRangeEnd) &&
664  MacroArgExpansionStartForRangeBegin == MacroArgExpansionStartForRangeEnd;
665 
666  // Check if the range contains any locations from a macro expansion.
667  bool RangeContainsMacroExpansion = RangeIsEntirelyWithinMacroArgument ||
668  Range.getBegin().isMacroID() ||
669  Range.getEnd().isMacroID();
670 
671  bool RangeCanBeFixed =
672  RangeIsEntirelyWithinMacroArgument || !RangeContainsMacroExpansion;
673  Failure.ShouldFix = RangeCanBeFixed;
674 }
675 
676 /// Convenience method when the usage to be added is a NamedDecl
678  const NamedDecl *Decl, SourceRange Range,
679  SourceManager *SourceMgr = nullptr) {
680  return addUsage(Failures,
681  IdentifierNamingCheck::NamingCheckId(Decl->getLocation(),
682  Decl->getNameAsString()),
683  Range, SourceMgr);
684 }
685 
686 void IdentifierNamingCheck::check(const MatchFinder::MatchResult &Result) {
687  if (const auto *Decl =
688  Result.Nodes.getNodeAs<CXXConstructorDecl>("classRef")) {
689  if (Decl->isImplicit())
690  return;
691 
692  addUsage(NamingCheckFailures, Decl->getParent(),
693  Decl->getNameInfo().getSourceRange());
694 
695  for (const auto *Init : Decl->inits()) {
696  if (!Init->isWritten() || Init->isInClassMemberInitializer())
697  continue;
698  if (const auto *FD = Init->getAnyMember())
699  addUsage(NamingCheckFailures, FD,
700  SourceRange(Init->getMemberLocation()));
701  // Note: delegating constructors and base class initializers are handled
702  // via the "typeLoc" matcher.
703  }
704  return;
705  }
706 
707  if (const auto *Decl =
708  Result.Nodes.getNodeAs<CXXDestructorDecl>("classRef")) {
709  if (Decl->isImplicit())
710  return;
711 
712  SourceRange Range = Decl->getNameInfo().getSourceRange();
713  if (Range.getBegin().isInvalid())
714  return;
715  // The first token that will be found is the ~ (or the equivalent trigraph),
716  // we want instead to replace the next token, that will be the identifier.
717  Range.setBegin(CharSourceRange::getTokenRange(Range).getEnd());
718 
719  addUsage(NamingCheckFailures, Decl->getParent(), Range);
720  return;
721  }
722 
723  if (const auto *Loc = Result.Nodes.getNodeAs<TypeLoc>("typeLoc")) {
724  NamedDecl *Decl = nullptr;
725  if (const auto &Ref = Loc->getAs<TagTypeLoc>()) {
726  Decl = Ref.getDecl();
727  } else if (const auto &Ref = Loc->getAs<InjectedClassNameTypeLoc>()) {
728  Decl = Ref.getDecl();
729  } else if (const auto &Ref = Loc->getAs<UnresolvedUsingTypeLoc>()) {
730  Decl = Ref.getDecl();
731  } else if (const auto &Ref = Loc->getAs<TemplateTypeParmTypeLoc>()) {
732  Decl = Ref.getDecl();
733  }
734 
735  if (Decl) {
736  addUsage(NamingCheckFailures, Decl, Loc->getSourceRange());
737  return;
738  }
739 
740  if (const auto &Ref = Loc->getAs<TemplateSpecializationTypeLoc>()) {
741  const auto *Decl =
742  Ref.getTypePtr()->getTemplateName().getAsTemplateDecl();
743 
744  SourceRange Range(Ref.getTemplateNameLoc(), Ref.getTemplateNameLoc());
745  if (const auto *ClassDecl = dyn_cast<TemplateDecl>(Decl)) {
746  if (const auto *TemplDecl = ClassDecl->getTemplatedDecl())
747  addUsage(NamingCheckFailures, TemplDecl, Range);
748  return;
749  }
750  }
751 
752  if (const auto &Ref =
753  Loc->getAs<DependentTemplateSpecializationTypeLoc>()) {
754  if (const auto *Decl = Ref.getTypePtr()->getAsTagDecl())
755  addUsage(NamingCheckFailures, Decl, Loc->getSourceRange());
756  return;
757  }
758  }
759 
760  if (const auto *Loc =
761  Result.Nodes.getNodeAs<NestedNameSpecifierLoc>("nestedNameLoc")) {
762  if (NestedNameSpecifier *Spec = Loc->getNestedNameSpecifier()) {
763  if (NamespaceDecl *Decl = Spec->getAsNamespace()) {
764  addUsage(NamingCheckFailures, Decl, Loc->getLocalSourceRange());
765  return;
766  }
767  }
768  }
769 
770  if (const auto *Decl = Result.Nodes.getNodeAs<UsingDecl>("using")) {
771  for (const auto &Shadow : Decl->shadows()) {
772  addUsage(NamingCheckFailures, Shadow->getTargetDecl(),
773  Decl->getNameInfo().getSourceRange());
774  }
775  return;
776  }
777 
778  if (const auto *DeclRef = Result.Nodes.getNodeAs<DeclRefExpr>("declRef")) {
779  SourceRange Range = DeclRef->getNameInfo().getSourceRange();
780  addUsage(NamingCheckFailures, DeclRef->getDecl(), Range,
781  Result.SourceManager);
782  return;
783  }
784 
785  if (const auto *Decl = Result.Nodes.getNodeAs<NamedDecl>("decl")) {
786  if (!Decl->getIdentifier() || Decl->getName().empty() || Decl->isImplicit())
787  return;
788 
789  // Fix type aliases in value declarations
790  if (const auto *Value = Result.Nodes.getNodeAs<ValueDecl>("decl")) {
791  if (const auto *Typedef =
792  Value->getType().getTypePtr()->getAs<TypedefType>()) {
793  addUsage(NamingCheckFailures, Typedef->getDecl(),
794  Value->getSourceRange());
795  }
796  }
797 
798  // Fix type aliases in function declarations
799  if (const auto *Value = Result.Nodes.getNodeAs<FunctionDecl>("decl")) {
800  if (const auto *Typedef =
801  Value->getReturnType().getTypePtr()->getAs<TypedefType>()) {
802  addUsage(NamingCheckFailures, Typedef->getDecl(),
803  Value->getSourceRange());
804  }
805  for (unsigned i = 0; i < Value->getNumParams(); ++i) {
806  if (const auto *Typedef = Value->parameters()[i]
807  ->getType()
808  .getTypePtr()
809  ->getAs<TypedefType>()) {
810  addUsage(NamingCheckFailures, Typedef->getDecl(),
811  Value->getSourceRange());
812  }
813  }
814  }
815 
816  // Ignore ClassTemplateSpecializationDecl which are creating duplicate
817  // replacements with CXXRecordDecl
818  if (isa<ClassTemplateSpecializationDecl>(Decl))
819  return;
820 
821  StyleKind SK = findStyleKind(Decl, NamingStyles);
822  if (SK == SK_Invalid)
823  return;
824 
825  if (!NamingStyles[SK])
826  return;
827 
828  const NamingStyle &Style = *NamingStyles[SK];
829  StringRef Name = Decl->getName();
830  if (matchesStyle(Name, Style))
831  return;
832 
833  std::string KindName = fixupWithCase(StyleNames[SK], CT_LowerCase);
834  std::replace(KindName.begin(), KindName.end(), '_', ' ');
835 
836  std::string Fixup = fixupWithStyle(Name, Style);
837  if (StringRef(Fixup).equals(Name)) {
838  if (!IgnoreFailedSplit) {
839  DEBUG(llvm::dbgs()
840  << Decl->getLocStart().printToString(*Result.SourceManager)
841  << llvm::format(": unable to split words for %s '%s'\n",
842  KindName.c_str(), Name.str().c_str()));
843  }
844  } else {
845  NamingCheckFailure &Failure = NamingCheckFailures[NamingCheckId(
846  Decl->getLocation(), Decl->getNameAsString())];
847  SourceRange Range =
848  DeclarationNameInfo(Decl->getDeclName(), Decl->getLocation())
849  .getSourceRange();
850 
851  Failure.Fixup = std::move(Fixup);
852  Failure.KindName = std::move(KindName);
853  addUsage(NamingCheckFailures, Decl, Range);
854  }
855  }
856 }
857 
858 void IdentifierNamingCheck::checkMacro(SourceManager &SourceMgr,
859  const Token &MacroNameTok,
860  const MacroInfo *MI) {
861  if (!NamingStyles[SK_MacroDefinition])
862  return;
863 
864  StringRef Name = MacroNameTok.getIdentifierInfo()->getName();
865  const NamingStyle &Style = *NamingStyles[SK_MacroDefinition];
866  if (matchesStyle(Name, Style))
867  return;
868 
869  std::string KindName =
870  fixupWithCase(StyleNames[SK_MacroDefinition], CT_LowerCase);
871  std::replace(KindName.begin(), KindName.end(), '_', ' ');
872 
873  std::string Fixup = fixupWithStyle(Name, Style);
874  if (StringRef(Fixup).equals(Name)) {
875  if (!IgnoreFailedSplit) {
876  DEBUG(
877  llvm::dbgs() << MacroNameTok.getLocation().printToString(SourceMgr)
878  << llvm::format(": unable to split words for %s '%s'\n",
879  KindName.c_str(), Name.str().c_str()));
880  }
881  } else {
882  NamingCheckId ID(MI->getDefinitionLoc(), Name);
883  NamingCheckFailure &Failure = NamingCheckFailures[ID];
884  SourceRange Range(MacroNameTok.getLocation(), MacroNameTok.getEndLoc());
885 
886  Failure.Fixup = std::move(Fixup);
887  Failure.KindName = std::move(KindName);
888  addUsage(NamingCheckFailures, ID, Range);
889  }
890 }
891 
892 void IdentifierNamingCheck::expandMacro(const Token &MacroNameTok,
893  const MacroInfo *MI) {
894  StringRef Name = MacroNameTok.getIdentifierInfo()->getName();
895  NamingCheckId ID(MI->getDefinitionLoc(), Name);
896 
897  auto Failure = NamingCheckFailures.find(ID);
898  if (Failure == NamingCheckFailures.end())
899  return;
900 
901  SourceRange Range(MacroNameTok.getLocation(), MacroNameTok.getEndLoc());
902  addUsage(NamingCheckFailures, ID, Range);
903 }
904 
906  for (const auto &Pair : NamingCheckFailures) {
907  const NamingCheckId &Decl = Pair.first;
908  const NamingCheckFailure &Failure = Pair.second;
909 
910  if (Failure.KindName.empty())
911  continue;
912 
913  if (Failure.ShouldFix) {
914  auto Diag = diag(Decl.first, "invalid case style for %0 '%1'")
915  << Failure.KindName << Decl.second;
916 
917  for (const auto &Loc : Failure.RawUsageLocs) {
918  // We assume that the identifier name is made of one token only. This is
919  // always the case as we ignore usages in macros that could build
920  // identifier names by combining multiple tokens.
921  //
922  // For destructors, we alread take care of it by remembering the
923  // location of the start of the identifier and not the start of the
924  // tilde.
925  //
926  // Other multi-token identifiers, such as operators are not checked at
927  // all.
928  Diag << FixItHint::CreateReplacement(
929  SourceRange(SourceLocation::getFromRawEncoding(Loc)),
930  Failure.Fixup);
931  }
932  }
933  }
934 }
935 
936 } // namespace readability
937 } // namespace tidy
938 } // namespace clang
SourceLocation Loc
&#39;#&#39; location in the include directive
void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const
Stores an option with the check-local name LocalName with string value Value to Options.
Definition: ClangTidy.cpp:449
#define ENUMERATE(v)
void registerPPCallbacks(CompilerInstance &Compiler) override
Override this to register PPCallbacks with Compiler.
static void addUsage(IdentifierNamingCheck::NamingCheckFailureMap &Failures, const IdentifierNamingCheck::NamingCheckId &Decl, SourceRange Range, SourceManager *SourceMgr=nullptr)
std::string get(StringRef LocalName, StringRef Default) const
Read a named option from the Context.
Definition: ClangTidy.cpp:430
StringHandle Name
Holds an identifier name check failure, tracking the kind of the identifer, its possible fixup and th...
static bool matchesStyle(StringRef Name, IdentifierNamingCheck::NamingStyle Style)
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
static llvm::StringRef toString(SpecialMemberFunctionsCheck::SpecialMemberFunctionKind K)
Base class for all clang-tidy checks.
Definition: ClangTidy.h:127
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 registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
std::map< std::string, std::string > OptionMap
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
static std::string fixupWithCase(StringRef Name, IdentifierNamingCheck::CaseType Case)
void checkMacro(SourceManager &sourceMgr, const Token &MacroNameTok, const MacroInfo *MI)
Check Macros for style violations.
static std::string fixupWithStyle(StringRef Name, const IdentifierNamingCheck::NamingStyle &Style)
llvm::DenseMap< NamingCheckId, NamingCheckFailure > NamingCheckFailureMap
static StyleKind findStyleKind(const NamedDecl *D, const std::vector< llvm::Optional< IdentifierNamingCheck::NamingStyle >> &NamingStyles)
CharSourceRange Range
SourceRange for the file name.
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.
const DeclRefExpr * DeclRef
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check&#39;s name.
Definition: ClangTidy.cpp:416
Checks for identifiers naming style mismatch.
bool ShouldFix
Whether the failure should be fixed or not.