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