blob: b8df167f8ce64ec0f8637ec246198916ec9cc263 [file] [log] [blame]
Alexander Kornienko76c28802015-08-19 11:15:36 +00001//===--- 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 "llvm/Support/Debug.h"
13#include "llvm/Support/Format.h"
14#include "clang/ASTMatchers/ASTMatchFinder.h"
Alexander Kornienko21503902016-06-17 09:25:24 +000015#include "clang/Frontend/CompilerInstance.h"
16#include "clang/Lex/PPCallbacks.h"
17#include "clang/Lex/Preprocessor.h"
18#include "llvm/ADT/DenseMapInfo.h"
Alexander Kornienko76c28802015-08-19 11:15:36 +000019
20#define DEBUG_TYPE "clang-tidy"
21
22using namespace clang::ast_matchers;
23
Alexander Kornienko21503902016-06-17 09:25:24 +000024namespace llvm {
25/// Specialisation of DenseMapInfo to allow NamingCheckId objects in DenseMaps
26template <>
27struct DenseMapInfo<
28 clang::tidy::readability::IdentifierNamingCheck::NamingCheckId> {
29 using NamingCheckId =
30 clang::tidy::readability::IdentifierNamingCheck::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
Alexander Kornienko76c28802015-08-19 11:15:36 +000062namespace clang {
63namespace tidy {
64namespace readability {
65
Alexander Kornienko3d777682015-09-28 08:59:12 +000066// clang-format off
Alexander Kornienko76c28802015-08-19 11:15:36 +000067#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) \
Alexander Kornienko5ae76e02016-06-07 09:11:19 +0000110 m(TypeAlias) \
Alexander Kornienko21503902016-06-17 09:25:24 +0000111 m(MacroDefinition) \
Alexander Kornienko76c28802015-08-19 11:15:36 +0000112
113enum StyleKind {
114#define ENUMERATE(v) SK_ ## v,
115 NAMING_KEYS(ENUMERATE)
116#undef ENUMERATE
117 SK_Count,
118 SK_Invalid
119};
120
121static StringRef const StyleNames[] = {
122#define STRINGIZE(v) #v,
123 NAMING_KEYS(STRINGIZE)
124#undef STRINGIZE
125};
126
127#undef NAMING_KEYS
Alexander Kornienko3d777682015-09-28 08:59:12 +0000128// clang-format on
Alexander Kornienko76c28802015-08-19 11:15:36 +0000129
Alexander Kornienko21503902016-06-17 09:25:24 +0000130namespace {
131/// Callback supplies macros to IdentifierNamingCheck::checkMacro
132class IdentifierNamingCheckPPCallbacks : public PPCallbacks {
133public:
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
151private:
152 Preprocessor *PP;
153 IdentifierNamingCheck *Check;
154};
155} // namespace
156
Alexander Kornienko76c28802015-08-19 11:15:36 +0000157IdentifierNamingCheck::IdentifierNamingCheck(StringRef Name,
158 ClangTidyContext *Context)
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 .Default(CT_AnyCase);
167 };
168
169 for (auto const &Name : StyleNames) {
170 NamingStyles.push_back(
171 NamingStyle(fromString(Options.get((Name + "Case").str(), "")),
172 Options.get((Name + "Prefix").str(), ""),
173 Options.get((Name + "Suffix").str(), "")));
174 }
175
176 IgnoreFailedSplit = Options.get("IgnoreFailedSplit", 0);
177}
178
179void IdentifierNamingCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
180 auto const toString = [](CaseType Type) {
181 switch (Type) {
182 case CT_AnyCase:
183 return "aNy_CasE";
184 case CT_LowerCase:
185 return "lower_case";
186 case CT_CamelBack:
187 return "camelBack";
188 case CT_UpperCase:
189 return "UPPER_CASE";
190 case CT_CamelCase:
191 return "CamelCase";
192 }
193
194 llvm_unreachable("Unknown Case Type");
195 };
196
197 for (size_t i = 0; i < SK_Count; ++i) {
198 Options.store(Opts, (StyleNames[i] + "Case").str(),
199 toString(NamingStyles[i].Case));
200 Options.store(Opts, (StyleNames[i] + "Prefix").str(),
201 NamingStyles[i].Prefix);
202 Options.store(Opts, (StyleNames[i] + "Suffix").str(),
203 NamingStyles[i].Suffix);
204 }
205
206 Options.store(Opts, "IgnoreFailedSplit", IgnoreFailedSplit);
207}
208
209void IdentifierNamingCheck::registerMatchers(MatchFinder *Finder) {
Alexander Kornienko76c28802015-08-19 11:15:36 +0000210 Finder->addMatcher(namedDecl().bind("decl"), this);
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000211 Finder->addMatcher(usingDecl().bind("using"), this);
212 Finder->addMatcher(declRefExpr().bind("declRef"), this);
213 Finder->addMatcher(cxxConstructorDecl().bind("classRef"), this);
214 Finder->addMatcher(cxxDestructorDecl().bind("classRef"), this);
215 Finder->addMatcher(typeLoc().bind("typeLoc"), this);
216 Finder->addMatcher(nestedNameSpecifierLoc().bind("nestedNameLoc"), this);
Alexander Kornienko76c28802015-08-19 11:15:36 +0000217}
218
Alexander Kornienko21503902016-06-17 09:25:24 +0000219void IdentifierNamingCheck::registerPPCallbacks(CompilerInstance &Compiler) {
220 Compiler.getPreprocessor().addPPCallbacks(
221 llvm::make_unique<IdentifierNamingCheckPPCallbacks>(
222 &Compiler.getPreprocessor(), this));
223}
224
Alexander Kornienko76c28802015-08-19 11:15:36 +0000225static bool matchesStyle(StringRef Name,
226 IdentifierNamingCheck::NamingStyle Style) {
227 static llvm::Regex Matchers[] = {
228 llvm::Regex("^.*$"),
229 llvm::Regex("^[a-z][a-z0-9_]*$"),
230 llvm::Regex("^[a-z][a-zA-Z0-9]*$"),
231 llvm::Regex("^[A-Z][A-Z0-9_]*$"),
232 llvm::Regex("^[A-Z][a-zA-Z0-9]*$"),
233 };
234
235 bool Matches = true;
236 if (Name.startswith(Style.Prefix))
237 Name = Name.drop_front(Style.Prefix.size());
238 else
239 Matches = false;
240
241 if (Name.endswith(Style.Suffix))
242 Name = Name.drop_back(Style.Suffix.size());
243 else
244 Matches = false;
245
246 if (!Matchers[static_cast<size_t>(Style.Case)].match(Name))
247 Matches = false;
248
249 return Matches;
250}
251
252static std::string fixupWithCase(StringRef Name,
253 IdentifierNamingCheck::CaseType Case) {
254 static llvm::Regex Splitter(
255 "([a-z0-9A-Z]*)(_+)|([A-Z]?[a-z0-9]+)([A-Z]|$)|([A-Z]+)([A-Z]|$)");
256
257 SmallVector<StringRef, 8> Substrs;
258 Name.split(Substrs, "_", -1, false);
259
260 SmallVector<StringRef, 8> Words;
261 for (auto Substr : Substrs) {
262 while (!Substr.empty()) {
263 SmallVector<StringRef, 8> Groups;
264 if (!Splitter.match(Substr, &Groups))
265 break;
266
267 if (Groups[2].size() > 0) {
268 Words.push_back(Groups[1]);
269 Substr = Substr.substr(Groups[0].size());
270 } else if (Groups[3].size() > 0) {
271 Words.push_back(Groups[3]);
272 Substr = Substr.substr(Groups[0].size() - Groups[4].size());
273 } else if (Groups[5].size() > 0) {
274 Words.push_back(Groups[5]);
275 Substr = Substr.substr(Groups[0].size() - Groups[6].size());
276 }
277 }
278 }
279
280 if (Words.empty())
281 return Name;
282
283 std::string Fixup;
284 switch (Case) {
285 case IdentifierNamingCheck::CT_AnyCase:
286 Fixup += Name;
287 break;
288
289 case IdentifierNamingCheck::CT_LowerCase:
290 for (auto const &Word : Words) {
291 if (&Word != &Words.front())
292 Fixup += "_";
293 Fixup += Word.lower();
294 }
295 break;
296
297 case IdentifierNamingCheck::CT_UpperCase:
298 for (auto const &Word : Words) {
299 if (&Word != &Words.front())
300 Fixup += "_";
301 Fixup += Word.upper();
302 }
303 break;
304
305 case IdentifierNamingCheck::CT_CamelCase:
306 for (auto const &Word : Words) {
307 Fixup += Word.substr(0, 1).upper();
308 Fixup += Word.substr(1).lower();
309 }
310 break;
311
312 case IdentifierNamingCheck::CT_CamelBack:
313 for (auto const &Word : Words) {
314 if (&Word == &Words.front()) {
315 Fixup += Word.lower();
316 } else {
317 Fixup += Word.substr(0, 1).upper();
318 Fixup += Word.substr(1).lower();
319 }
320 }
321 break;
322 }
323
324 return Fixup;
325}
326
327static std::string fixupWithStyle(StringRef Name,
328 IdentifierNamingCheck::NamingStyle Style) {
329 return Style.Prefix + fixupWithCase(Name, Style.Case) + Style.Suffix;
330}
331
332static StyleKind findStyleKind(
333 const NamedDecl *D,
334 const std::vector<IdentifierNamingCheck::NamingStyle> &NamingStyles) {
335 if (isa<TypedefDecl>(D) && NamingStyles[SK_Typedef].isSet())
336 return SK_Typedef;
337
Alexander Kornienko5ae76e02016-06-07 09:11:19 +0000338 if (isa<TypeAliasDecl>(D) && NamingStyles[SK_TypeAlias].isSet())
339 return SK_TypeAlias;
340
Alexander Kornienko76c28802015-08-19 11:15:36 +0000341 if (const auto *Decl = dyn_cast<NamespaceDecl>(D)) {
342 if (Decl->isAnonymousNamespace())
343 return SK_Invalid;
344
345 if (Decl->isInline() && NamingStyles[SK_InlineNamespace].isSet())
346 return SK_InlineNamespace;
347
348 if (NamingStyles[SK_Namespace].isSet())
349 return SK_Namespace;
350 }
351
352 if (isa<EnumDecl>(D) && NamingStyles[SK_Enum].isSet())
353 return SK_Enum;
354
355 if (isa<EnumConstantDecl>(D)) {
356 if (NamingStyles[SK_EnumConstant].isSet())
357 return SK_EnumConstant;
358
359 if (NamingStyles[SK_Constant].isSet())
360 return SK_Constant;
361
362 return SK_Invalid;
363 }
364
365 if (const auto *Decl = dyn_cast<CXXRecordDecl>(D)) {
366 if (Decl->isAnonymousStructOrUnion())
367 return SK_Invalid;
368
369 if (Decl->hasDefinition() && Decl->isAbstract() &&
370 NamingStyles[SK_AbstractClass].isSet())
371 return SK_AbstractClass;
372
373 if (Decl->isStruct() && NamingStyles[SK_Struct].isSet())
374 return SK_Struct;
375
376 if (Decl->isStruct() && NamingStyles[SK_Class].isSet())
377 return SK_Class;
378
379 if (Decl->isClass() && NamingStyles[SK_Class].isSet())
380 return SK_Class;
381
382 if (Decl->isClass() && NamingStyles[SK_Struct].isSet())
383 return SK_Struct;
384
385 if (Decl->isUnion() && NamingStyles[SK_Union].isSet())
386 return SK_Union;
387
388 if (Decl->isEnum() && NamingStyles[SK_Enum].isSet())
389 return SK_Enum;
390
391 return SK_Invalid;
392 }
393
394 if (const auto *Decl = dyn_cast<FieldDecl>(D)) {
395 QualType Type = Decl->getType();
396
397 if (!Type.isNull() && Type.isLocalConstQualified() &&
398 NamingStyles[SK_ConstantMember].isSet())
399 return SK_ConstantMember;
400
401 if (!Type.isNull() && Type.isLocalConstQualified() &&
402 NamingStyles[SK_Constant].isSet())
403 return SK_Constant;
404
405 if (Decl->getAccess() == AS_private &&
406 NamingStyles[SK_PrivateMember].isSet())
407 return SK_PrivateMember;
408
409 if (Decl->getAccess() == AS_protected &&
410 NamingStyles[SK_ProtectedMember].isSet())
411 return SK_ProtectedMember;
412
413 if (Decl->getAccess() == AS_public && NamingStyles[SK_PublicMember].isSet())
414 return SK_PublicMember;
415
416 if (NamingStyles[SK_Member].isSet())
417 return SK_Member;
418
419 return SK_Invalid;
420 }
421
422 if (const auto *Decl = dyn_cast<ParmVarDecl>(D)) {
423 QualType Type = Decl->getType();
424
425 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprVariable].isSet())
426 return SK_ConstexprVariable;
427
428 if (!Type.isNull() && Type.isLocalConstQualified() &&
429 NamingStyles[SK_ConstantParameter].isSet())
430 return SK_ConstantParameter;
431
432 if (!Type.isNull() && Type.isLocalConstQualified() &&
433 NamingStyles[SK_Constant].isSet())
434 return SK_Constant;
435
436 if (Decl->isParameterPack() && NamingStyles[SK_ParameterPack].isSet())
437 return SK_ParameterPack;
438
439 if (NamingStyles[SK_Parameter].isSet())
440 return SK_Parameter;
441
442 return SK_Invalid;
443 }
444
445 if (const auto *Decl = dyn_cast<VarDecl>(D)) {
446 QualType Type = Decl->getType();
447
448 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprVariable].isSet())
449 return SK_ConstexprVariable;
450
451 if (!Type.isNull() && Type.isLocalConstQualified() &&
452 Decl->isStaticDataMember() && NamingStyles[SK_ClassConstant].isSet())
453 return SK_ClassConstant;
454
455 if (!Type.isNull() && Type.isLocalConstQualified() &&
456 Decl->isFileVarDecl() && NamingStyles[SK_GlobalConstant].isSet())
457 return SK_GlobalConstant;
458
459 if (!Type.isNull() && Type.isLocalConstQualified() &&
460 Decl->isStaticLocal() && NamingStyles[SK_StaticConstant].isSet())
461 return SK_StaticConstant;
462
463 if (!Type.isNull() && Type.isLocalConstQualified() &&
464 Decl->isLocalVarDecl() && NamingStyles[SK_LocalConstant].isSet())
465 return SK_LocalConstant;
466
467 if (!Type.isNull() && Type.isLocalConstQualified() &&
468 Decl->isFunctionOrMethodVarDecl() &&
469 NamingStyles[SK_LocalConstant].isSet())
470 return SK_LocalConstant;
471
472 if (!Type.isNull() && Type.isLocalConstQualified() &&
473 NamingStyles[SK_Constant].isSet())
474 return SK_Constant;
475
476 if (Decl->isStaticDataMember() && NamingStyles[SK_ClassMember].isSet())
477 return SK_ClassMember;
478
479 if (Decl->isFileVarDecl() && NamingStyles[SK_GlobalVariable].isSet())
480 return SK_GlobalVariable;
481
482 if (Decl->isStaticLocal() && NamingStyles[SK_StaticVariable].isSet())
483 return SK_StaticVariable;
484
485 if (Decl->isLocalVarDecl() && NamingStyles[SK_LocalVariable].isSet())
486 return SK_LocalVariable;
487
488 if (Decl->isFunctionOrMethodVarDecl() &&
489 NamingStyles[SK_LocalVariable].isSet())
490 return SK_LocalVariable;
491
492 if (NamingStyles[SK_Variable].isSet())
493 return SK_Variable;
494
495 return SK_Invalid;
496 }
497
498 if (const auto *Decl = dyn_cast<CXXMethodDecl>(D)) {
499 if (Decl->isMain() || !Decl->isUserProvided() ||
500 Decl->isUsualDeallocationFunction() ||
501 Decl->isCopyAssignmentOperator() || Decl->isMoveAssignmentOperator() ||
502 Decl->size_overridden_methods() > 0)
503 return SK_Invalid;
504
505 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprMethod].isSet())
506 return SK_ConstexprMethod;
507
508 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprFunction].isSet())
509 return SK_ConstexprFunction;
510
511 if (Decl->isStatic() && NamingStyles[SK_ClassMethod].isSet())
512 return SK_ClassMethod;
513
514 if (Decl->isVirtual() && NamingStyles[SK_VirtualMethod].isSet())
515 return SK_VirtualMethod;
516
517 if (Decl->getAccess() == AS_private &&
518 NamingStyles[SK_PrivateMethod].isSet())
519 return SK_PrivateMethod;
520
521 if (Decl->getAccess() == AS_protected &&
522 NamingStyles[SK_ProtectedMethod].isSet())
523 return SK_ProtectedMethod;
524
525 if (Decl->getAccess() == AS_public && NamingStyles[SK_PublicMethod].isSet())
526 return SK_PublicMethod;
527
528 if (NamingStyles[SK_Method].isSet())
529 return SK_Method;
530
531 if (NamingStyles[SK_Function].isSet())
532 return SK_Function;
533
534 return SK_Invalid;
535 }
536
537 if (const auto *Decl = dyn_cast<FunctionDecl>(D)) {
538 if (Decl->isMain())
539 return SK_Invalid;
540
541 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprFunction].isSet())
542 return SK_ConstexprFunction;
543
544 if (Decl->isGlobal() && NamingStyles[SK_GlobalFunction].isSet())
545 return SK_GlobalFunction;
546
547 if (NamingStyles[SK_Function].isSet())
548 return SK_Function;
549 }
550
551 if (isa<TemplateTypeParmDecl>(D)) {
552 if (NamingStyles[SK_TypeTemplateParameter].isSet())
553 return SK_TypeTemplateParameter;
554
555 if (NamingStyles[SK_TemplateParameter].isSet())
556 return SK_TemplateParameter;
557
558 return SK_Invalid;
559 }
560
561 if (isa<NonTypeTemplateParmDecl>(D)) {
562 if (NamingStyles[SK_ValueTemplateParameter].isSet())
563 return SK_ValueTemplateParameter;
564
565 if (NamingStyles[SK_TemplateParameter].isSet())
566 return SK_TemplateParameter;
567
568 return SK_Invalid;
569 }
570
571 if (isa<TemplateTemplateParmDecl>(D)) {
572 if (NamingStyles[SK_TemplateTemplateParameter].isSet())
573 return SK_TemplateTemplateParameter;
574
575 if (NamingStyles[SK_TemplateParameter].isSet())
576 return SK_TemplateParameter;
577
578 return SK_Invalid;
579 }
580
581 return SK_Invalid;
582}
583
Alexander Kornienko3d777682015-09-28 08:59:12 +0000584static void addUsage(IdentifierNamingCheck::NamingCheckFailureMap &Failures,
Alexander Kornienko21503902016-06-17 09:25:24 +0000585 const IdentifierNamingCheck::NamingCheckId &Decl,
586 SourceRange Range) {
Jonathan Coe2c8592a2016-01-26 18:55:55 +0000587 // Do nothing if the provided range is invalid.
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000588 if (Range.getBegin().isInvalid() || Range.getEnd().isInvalid())
589 return;
590
591 // Try to insert the identifier location in the Usages map, and bail out if it
592 // is already in there
Alexander Kornienko3d777682015-09-28 08:59:12 +0000593 auto &Failure = Failures[Decl];
594 if (!Failure.RawUsageLocs.insert(Range.getBegin().getRawEncoding()).second)
595 return;
596
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000597 Failure.ShouldFix = Failure.ShouldFix && !Range.getBegin().isMacroID() &&
Alexander Kornienko3d777682015-09-28 08:59:12 +0000598 !Range.getEnd().isMacroID();
599}
600
Alexander Kornienko21503902016-06-17 09:25:24 +0000601/// Convenience method when the usage to be added is a NamedDecl
602static void addUsage(IdentifierNamingCheck::NamingCheckFailureMap &Failures,
603 const NamedDecl *Decl, SourceRange Range) {
604 return addUsage(Failures, IdentifierNamingCheck::NamingCheckId(
605 Decl->getLocation(), Decl->getNameAsString()),
606 Range);
607}
608
Alexander Kornienko76c28802015-08-19 11:15:36 +0000609void IdentifierNamingCheck::check(const MatchFinder::MatchResult &Result) {
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000610 if (const auto *Decl =
611 Result.Nodes.getNodeAs<CXXConstructorDecl>("classRef")) {
612 if (Decl->isImplicit())
613 return;
614
615 addUsage(NamingCheckFailures, Decl->getParent(),
Alexander Kornienko21503902016-06-17 09:25:24 +0000616 Decl->getNameInfo().getSourceRange());
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000617 return;
618 }
619
620 if (const auto *Decl =
621 Result.Nodes.getNodeAs<CXXDestructorDecl>("classRef")) {
622 if (Decl->isImplicit())
623 return;
624
625 SourceRange Range = Decl->getNameInfo().getSourceRange();
626 if (Range.getBegin().isInvalid())
627 return;
628 // The first token that will be found is the ~ (or the equivalent trigraph),
629 // we want instead to replace the next token, that will be the identifier.
630 Range.setBegin(CharSourceRange::getTokenRange(Range).getEnd());
631
Alexander Kornienko21503902016-06-17 09:25:24 +0000632 addUsage(NamingCheckFailures, Decl->getParent(), Range);
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000633 return;
634 }
635
636 if (const auto *Loc = Result.Nodes.getNodeAs<TypeLoc>("typeLoc")) {
637 NamedDecl *Decl = nullptr;
638 if (const auto &Ref = Loc->getAs<TagTypeLoc>()) {
639 Decl = Ref.getDecl();
640 } else if (const auto &Ref = Loc->getAs<InjectedClassNameTypeLoc>()) {
641 Decl = Ref.getDecl();
642 } else if (const auto &Ref = Loc->getAs<UnresolvedUsingTypeLoc>()) {
643 Decl = Ref.getDecl();
644 } else if (const auto &Ref = Loc->getAs<TemplateTypeParmTypeLoc>()) {
645 Decl = Ref.getDecl();
646 }
647
648 if (Decl) {
Alexander Kornienko21503902016-06-17 09:25:24 +0000649 addUsage(NamingCheckFailures, Decl, Loc->getSourceRange());
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000650 return;
651 }
652
653 if (const auto &Ref = Loc->getAs<TemplateSpecializationTypeLoc>()) {
654 const auto *Decl =
655 Ref.getTypePtr()->getTemplateName().getAsTemplateDecl();
656
657 SourceRange Range(Ref.getTemplateNameLoc(), Ref.getTemplateNameLoc());
658 if (const auto *ClassDecl = dyn_cast<TemplateDecl>(Decl)) {
Matthias Gehrea9e812b2016-07-09 20:09:28 +0000659 if (const auto *TemplDecl = ClassDecl->getTemplatedDecl())
660 addUsage(NamingCheckFailures, TemplDecl, Range);
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000661 return;
662 }
663 }
664
665 if (const auto &Ref =
666 Loc->getAs<DependentTemplateSpecializationTypeLoc>()) {
Matthias Gehrea9e812b2016-07-09 20:09:28 +0000667 if (const auto *Decl = Ref.getTypePtr()->getAsTagDecl())
668 addUsage(NamingCheckFailures, Decl, Loc->getSourceRange());
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000669 return;
670 }
671 }
672
673 if (const auto *Loc =
674 Result.Nodes.getNodeAs<NestedNameSpecifierLoc>("nestedNameLoc")) {
675 if (NestedNameSpecifier *Spec = Loc->getNestedNameSpecifier()) {
676 if (NamespaceDecl *Decl = Spec->getAsNamespace()) {
Alexander Kornienko21503902016-06-17 09:25:24 +0000677 addUsage(NamingCheckFailures, Decl, Loc->getLocalSourceRange());
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000678 return;
679 }
680 }
681 }
682
683 if (const auto *Decl = Result.Nodes.getNodeAs<UsingDecl>("using")) {
684 for (const auto &Shadow : Decl->shadows()) {
685 addUsage(NamingCheckFailures, Shadow->getTargetDecl(),
Alexander Kornienko21503902016-06-17 09:25:24 +0000686 Decl->getNameInfo().getSourceRange());
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000687 }
688 return;
689 }
690
691 if (const auto *DeclRef = Result.Nodes.getNodeAs<DeclRefExpr>("declRef")) {
Alexander Kornienko76c28802015-08-19 11:15:36 +0000692 SourceRange Range = DeclRef->getNameInfo().getSourceRange();
Alexander Kornienko21503902016-06-17 09:25:24 +0000693 addUsage(NamingCheckFailures, DeclRef->getDecl(), Range);
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000694 return;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000695 }
696
697 if (const auto *Decl = Result.Nodes.getNodeAs<NamedDecl>("decl")) {
698 if (!Decl->getIdentifier() || Decl->getName().empty() || Decl->isImplicit())
699 return;
700
Alexander Kornienko21503902016-06-17 09:25:24 +0000701 // Fix type aliases in value declarations
702 if (const auto *Value = Result.Nodes.getNodeAs<ValueDecl>("decl")) {
703 if (const auto *Typedef =
704 Value->getType().getTypePtr()->getAs<TypedefType>()) {
705 addUsage(NamingCheckFailures, Typedef->getDecl(),
706 Value->getSourceRange());
707 }
708 }
709
710 // Fix type aliases in function declarations
711 if (const auto *Value = Result.Nodes.getNodeAs<FunctionDecl>("decl")) {
712 if (const auto *Typedef =
713 Value->getReturnType().getTypePtr()->getAs<TypedefType>()) {
714 addUsage(NamingCheckFailures, Typedef->getDecl(),
715 Value->getSourceRange());
716 }
717 for (unsigned i = 0; i < Value->getNumParams(); ++i) {
718 if (const auto *Typedef = Value->parameters()[i]
719 ->getType()
720 .getTypePtr()
721 ->getAs<TypedefType>()) {
722 addUsage(NamingCheckFailures, Typedef->getDecl(),
723 Value->getSourceRange());
724 }
725 }
726 }
727
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000728 // Ignore ClassTemplateSpecializationDecl which are creating duplicate
729 // replacements with CXXRecordDecl
730 if (isa<ClassTemplateSpecializationDecl>(Decl))
731 return;
732
Alexander Kornienko76c28802015-08-19 11:15:36 +0000733 StyleKind SK = findStyleKind(Decl, NamingStyles);
734 if (SK == SK_Invalid)
735 return;
736
737 NamingStyle Style = NamingStyles[SK];
738 StringRef Name = Decl->getName();
739 if (matchesStyle(Name, Style))
740 return;
741
742 std::string KindName = fixupWithCase(StyleNames[SK], CT_LowerCase);
743 std::replace(KindName.begin(), KindName.end(), '_', ' ');
744
745 std::string Fixup = fixupWithStyle(Name, Style);
746 if (StringRef(Fixup).equals(Name)) {
747 if (!IgnoreFailedSplit) {
Hans Wennborg53bd9f32016-02-29 21:17:39 +0000748 DEBUG(llvm::dbgs()
749 << Decl->getLocStart().printToString(*Result.SourceManager)
750 << llvm::format(": unable to split words for %s '%s'\n",
751 KindName.c_str(), Name));
Alexander Kornienko76c28802015-08-19 11:15:36 +0000752 }
753 } else {
Alexander Kornienko21503902016-06-17 09:25:24 +0000754 NamingCheckFailure &Failure = NamingCheckFailures[NamingCheckId(
755 Decl->getLocation(), Decl->getNameAsString())];
Alexander Kornienko76c28802015-08-19 11:15:36 +0000756 SourceRange Range =
757 DeclarationNameInfo(Decl->getDeclName(), Decl->getLocation())
758 .getSourceRange();
759
760 Failure.Fixup = std::move(Fixup);
761 Failure.KindName = std::move(KindName);
Alexander Kornienko21503902016-06-17 09:25:24 +0000762 addUsage(NamingCheckFailures, Decl, Range);
Alexander Kornienko76c28802015-08-19 11:15:36 +0000763 }
764 }
765}
766
Alexander Kornienko21503902016-06-17 09:25:24 +0000767void IdentifierNamingCheck::checkMacro(SourceManager &SourceMgr,
768 const Token &MacroNameTok,
769 const MacroInfo *MI) {
770 StringRef Name = MacroNameTok.getIdentifierInfo()->getName();
771 NamingStyle Style = NamingStyles[SK_MacroDefinition];
772 if (matchesStyle(Name, Style))
773 return;
774
775 std::string KindName =
776 fixupWithCase(StyleNames[SK_MacroDefinition], CT_LowerCase);
777 std::replace(KindName.begin(), KindName.end(), '_', ' ');
778
779 std::string Fixup = fixupWithStyle(Name, Style);
780 if (StringRef(Fixup).equals(Name)) {
781 if (!IgnoreFailedSplit) {
782 DEBUG(
783 llvm::dbgs() << MacroNameTok.getLocation().printToString(SourceMgr)
784 << llvm::format(": unable to split words for %s '%s'\n",
785 KindName.c_str(), Name));
786 }
787 } else {
788 NamingCheckId ID(MI->getDefinitionLoc(), Name);
789 NamingCheckFailure &Failure = NamingCheckFailures[ID];
790 SourceRange Range(MacroNameTok.getLocation(), MacroNameTok.getEndLoc());
791
792 Failure.Fixup = std::move(Fixup);
793 Failure.KindName = std::move(KindName);
794 addUsage(NamingCheckFailures, ID, Range);
795 }
796}
797
798void IdentifierNamingCheck::expandMacro(const Token &MacroNameTok,
799 const MacroInfo *MI) {
800 StringRef Name = MacroNameTok.getIdentifierInfo()->getName();
801 NamingCheckId ID(MI->getDefinitionLoc(), Name);
802
803 auto Failure = NamingCheckFailures.find(ID);
804 if (Failure == NamingCheckFailures.end())
805 return;
806
807 SourceRange Range(MacroNameTok.getLocation(), MacroNameTok.getEndLoc());
808 addUsage(NamingCheckFailures, ID, Range);
809}
810
Alexander Kornienko76c28802015-08-19 11:15:36 +0000811void IdentifierNamingCheck::onEndOfTranslationUnit() {
812 for (const auto &Pair : NamingCheckFailures) {
Alexander Kornienko21503902016-06-17 09:25:24 +0000813 const NamingCheckId &Decl = Pair.first;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000814 const NamingCheckFailure &Failure = Pair.second;
815
Alexander Kornienko3d777682015-09-28 08:59:12 +0000816 if (Failure.KindName.empty())
817 continue;
818
Alexander Kornienko76c28802015-08-19 11:15:36 +0000819 if (Failure.ShouldFix) {
Alexander Kornienko21503902016-06-17 09:25:24 +0000820 auto Diag = diag(Decl.first, "invalid case style for %0 '%1'")
821 << Failure.KindName << Decl.second;
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000822
Alexander Kornienko3d777682015-09-28 08:59:12 +0000823 for (const auto &Loc : Failure.RawUsageLocs) {
824 // We assume that the identifier name is made of one token only. This is
825 // always the case as we ignore usages in macros that could build
826 // identifier names by combining multiple tokens.
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000827 //
828 // For destructors, we alread take care of it by remembering the
829 // location of the start of the identifier and not the start of the
830 // tilde.
831 //
832 // Other multi-token identifiers, such as operators are not checked at
833 // all.
Alexander Kornienko76c28802015-08-19 11:15:36 +0000834 Diag << FixItHint::CreateReplacement(
Alexander Kornienko3d777682015-09-28 08:59:12 +0000835 SourceRange(SourceLocation::getFromRawEncoding(Loc)),
836 Failure.Fixup);
Alexander Kornienko76c28802015-08-19 11:15:36 +0000837 }
838 }
839 }
840}
841
842} // namespace readability
843} // namespace tidy
844} // namespace clang