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