blob: f7d7817ce55f8d1f44c43c21d37a8d8999c8e0fc [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)
Kirill Bobyrev5d8f0712016-07-20 12:28:38 +0000166 .Case("Camel_Snake_Case", CT_CamelSnakeCase)
167 .Case("camel_Snake_Back", CT_CamelSnakeBack)
Alexander Kornienko76c28802015-08-19 11:15:36 +0000168 .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
181void IdentifierNamingCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
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";
Kirill Bobyrev5d8f0712016-07-20 12:28:38 +0000194 case CT_CamelSnakeCase:
195 return "Camel_Snake_Case";
196 case CT_CamelSnakeBack:
197 return "camel_Snake_Back";
Alexander Kornienko76c28802015-08-19 11:15:36 +0000198 }
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
215void IdentifierNamingCheck::registerMatchers(MatchFinder *Finder) {
Alexander Kornienko76c28802015-08-19 11:15:36 +0000216 Finder->addMatcher(namedDecl().bind("decl"), this);
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000217 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);
Alexander Kornienko76c28802015-08-19 11:15:36 +0000223}
224
Alexander Kornienko21503902016-06-17 09:25:24 +0000225void IdentifierNamingCheck::registerPPCallbacks(CompilerInstance &Compiler) {
226 Compiler.getPreprocessor().addPPCallbacks(
227 llvm::make_unique<IdentifierNamingCheckPPCallbacks>(
228 &Compiler.getPreprocessor(), this));
229}
230
Alexander Kornienko76c28802015-08-19 11:15:36 +0000231static bool matchesStyle(StringRef Name,
232 IdentifierNamingCheck::NamingStyle Style) {
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]*$"),
Kirill Bobyrev5d8f0712016-07-20 12:28:38 +0000239 llvm::Regex("^[A-Z]([a-z0-9]*(_[A-Z])?)*"),
240 llvm::Regex("^[a-z]([a-z0-9]*(_[A-Z])?)*"),
Alexander Kornienko76c28802015-08-19 11:15:36 +0000241 };
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
260static std::string fixupWithCase(StringRef Name,
261 IdentifierNamingCheck::CaseType Case) {
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) {
293 case IdentifierNamingCheck::CT_AnyCase:
294 Fixup += Name;
295 break;
296
297 case IdentifierNamingCheck::CT_LowerCase:
298 for (auto const &Word : Words) {
299 if (&Word != &Words.front())
300 Fixup += "_";
301 Fixup += Word.lower();
302 }
303 break;
304
305 case IdentifierNamingCheck::CT_UpperCase:
306 for (auto const &Word : Words) {
307 if (&Word != &Words.front())
308 Fixup += "_";
309 Fixup += Word.upper();
310 }
311 break;
312
313 case IdentifierNamingCheck::CT_CamelCase:
314 for (auto const &Word : Words) {
315 Fixup += Word.substr(0, 1).upper();
316 Fixup += Word.substr(1).lower();
317 }
318 break;
319
320 case IdentifierNamingCheck::CT_CamelBack:
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;
Kirill Bobyrev5d8f0712016-07-20 12:28:38 +0000330
331 case IdentifierNamingCheck::CT_CamelSnakeCase:
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
340 case IdentifierNamingCheck::CT_CamelSnakeBack:
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;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000351 }
352
353 return Fixup;
354}
355
356static std::string fixupWithStyle(StringRef Name,
357 IdentifierNamingCheck::NamingStyle Style) {
358 return Style.Prefix + fixupWithCase(Name, Style.Case) + Style.Suffix;
359}
360
361static StyleKind findStyleKind(
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
Alexander Kornienko5ae76e02016-06-07 09:11:19 +0000367 if (isa<TypeAliasDecl>(D) && NamingStyles[SK_TypeAlias].isSet())
368 return SK_TypeAlias;
369
Alexander Kornienko76c28802015-08-19 11:15:36 +0000370 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->hasDefinition() && Decl->isAbstract() &&
399 NamingStyles[SK_AbstractClass].isSet())
400 return SK_AbstractClass;
401
402 if (Decl->isStruct() && NamingStyles[SK_Struct].isSet())
403 return SK_Struct;
404
405 if (Decl->isStruct() && NamingStyles[SK_Class].isSet())
406 return SK_Class;
407
408 if (Decl->isClass() && NamingStyles[SK_Class].isSet())
409 return SK_Class;
410
411 if (Decl->isClass() && NamingStyles[SK_Struct].isSet())
412 return SK_Struct;
413
414 if (Decl->isUnion() && NamingStyles[SK_Union].isSet())
415 return SK_Union;
416
417 if (Decl->isEnum() && NamingStyles[SK_Enum].isSet())
418 return SK_Enum;
419
420 return SK_Invalid;
421 }
422
423 if (const auto *Decl = dyn_cast<FieldDecl>(D)) {
424 QualType Type = Decl->getType();
425
426 if (!Type.isNull() && Type.isLocalConstQualified() &&
427 NamingStyles[SK_ConstantMember].isSet())
428 return SK_ConstantMember;
429
430 if (!Type.isNull() && Type.isLocalConstQualified() &&
431 NamingStyles[SK_Constant].isSet())
432 return SK_Constant;
433
434 if (Decl->getAccess() == AS_private &&
435 NamingStyles[SK_PrivateMember].isSet())
436 return SK_PrivateMember;
437
438 if (Decl->getAccess() == AS_protected &&
439 NamingStyles[SK_ProtectedMember].isSet())
440 return SK_ProtectedMember;
441
442 if (Decl->getAccess() == AS_public && NamingStyles[SK_PublicMember].isSet())
443 return SK_PublicMember;
444
445 if (NamingStyles[SK_Member].isSet())
446 return SK_Member;
447
448 return SK_Invalid;
449 }
450
451 if (const auto *Decl = dyn_cast<ParmVarDecl>(D)) {
452 QualType Type = Decl->getType();
453
454 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprVariable].isSet())
455 return SK_ConstexprVariable;
456
457 if (!Type.isNull() && Type.isLocalConstQualified() &&
458 NamingStyles[SK_ConstantParameter].isSet())
459 return SK_ConstantParameter;
460
461 if (!Type.isNull() && Type.isLocalConstQualified() &&
462 NamingStyles[SK_Constant].isSet())
463 return SK_Constant;
464
465 if (Decl->isParameterPack() && NamingStyles[SK_ParameterPack].isSet())
466 return SK_ParameterPack;
467
468 if (NamingStyles[SK_Parameter].isSet())
469 return SK_Parameter;
470
471 return SK_Invalid;
472 }
473
474 if (const auto *Decl = dyn_cast<VarDecl>(D)) {
475 QualType Type = Decl->getType();
476
477 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprVariable].isSet())
478 return SK_ConstexprVariable;
479
480 if (!Type.isNull() && Type.isLocalConstQualified() &&
481 Decl->isStaticDataMember() && NamingStyles[SK_ClassConstant].isSet())
482 return SK_ClassConstant;
483
484 if (!Type.isNull() && Type.isLocalConstQualified() &&
485 Decl->isFileVarDecl() && NamingStyles[SK_GlobalConstant].isSet())
486 return SK_GlobalConstant;
487
488 if (!Type.isNull() && Type.isLocalConstQualified() &&
489 Decl->isStaticLocal() && NamingStyles[SK_StaticConstant].isSet())
490 return SK_StaticConstant;
491
492 if (!Type.isNull() && Type.isLocalConstQualified() &&
493 Decl->isLocalVarDecl() && NamingStyles[SK_LocalConstant].isSet())
494 return SK_LocalConstant;
495
496 if (!Type.isNull() && Type.isLocalConstQualified() &&
497 Decl->isFunctionOrMethodVarDecl() &&
498 NamingStyles[SK_LocalConstant].isSet())
499 return SK_LocalConstant;
500
501 if (!Type.isNull() && Type.isLocalConstQualified() &&
502 NamingStyles[SK_Constant].isSet())
503 return SK_Constant;
504
505 if (Decl->isStaticDataMember() && NamingStyles[SK_ClassMember].isSet())
506 return SK_ClassMember;
507
508 if (Decl->isFileVarDecl() && NamingStyles[SK_GlobalVariable].isSet())
509 return SK_GlobalVariable;
510
511 if (Decl->isStaticLocal() && NamingStyles[SK_StaticVariable].isSet())
512 return SK_StaticVariable;
513
514 if (Decl->isLocalVarDecl() && NamingStyles[SK_LocalVariable].isSet())
515 return SK_LocalVariable;
516
517 if (Decl->isFunctionOrMethodVarDecl() &&
518 NamingStyles[SK_LocalVariable].isSet())
519 return SK_LocalVariable;
520
521 if (NamingStyles[SK_Variable].isSet())
522 return SK_Variable;
523
524 return SK_Invalid;
525 }
526
527 if (const auto *Decl = dyn_cast<CXXMethodDecl>(D)) {
528 if (Decl->isMain() || !Decl->isUserProvided() ||
529 Decl->isUsualDeallocationFunction() ||
530 Decl->isCopyAssignmentOperator() || Decl->isMoveAssignmentOperator() ||
531 Decl->size_overridden_methods() > 0)
532 return SK_Invalid;
533
534 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprMethod].isSet())
535 return SK_ConstexprMethod;
536
537 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprFunction].isSet())
538 return SK_ConstexprFunction;
539
540 if (Decl->isStatic() && NamingStyles[SK_ClassMethod].isSet())
541 return SK_ClassMethod;
542
543 if (Decl->isVirtual() && NamingStyles[SK_VirtualMethod].isSet())
544 return SK_VirtualMethod;
545
546 if (Decl->getAccess() == AS_private &&
547 NamingStyles[SK_PrivateMethod].isSet())
548 return SK_PrivateMethod;
549
550 if (Decl->getAccess() == AS_protected &&
551 NamingStyles[SK_ProtectedMethod].isSet())
552 return SK_ProtectedMethod;
553
554 if (Decl->getAccess() == AS_public && NamingStyles[SK_PublicMethod].isSet())
555 return SK_PublicMethod;
556
557 if (NamingStyles[SK_Method].isSet())
558 return SK_Method;
559
560 if (NamingStyles[SK_Function].isSet())
561 return SK_Function;
562
563 return SK_Invalid;
564 }
565
566 if (const auto *Decl = dyn_cast<FunctionDecl>(D)) {
567 if (Decl->isMain())
568 return SK_Invalid;
569
570 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprFunction].isSet())
571 return SK_ConstexprFunction;
572
573 if (Decl->isGlobal() && NamingStyles[SK_GlobalFunction].isSet())
574 return SK_GlobalFunction;
575
576 if (NamingStyles[SK_Function].isSet())
577 return SK_Function;
578 }
579
580 if (isa<TemplateTypeParmDecl>(D)) {
581 if (NamingStyles[SK_TypeTemplateParameter].isSet())
582 return SK_TypeTemplateParameter;
583
584 if (NamingStyles[SK_TemplateParameter].isSet())
585 return SK_TemplateParameter;
586
587 return SK_Invalid;
588 }
589
590 if (isa<NonTypeTemplateParmDecl>(D)) {
591 if (NamingStyles[SK_ValueTemplateParameter].isSet())
592 return SK_ValueTemplateParameter;
593
594 if (NamingStyles[SK_TemplateParameter].isSet())
595 return SK_TemplateParameter;
596
597 return SK_Invalid;
598 }
599
600 if (isa<TemplateTemplateParmDecl>(D)) {
601 if (NamingStyles[SK_TemplateTemplateParameter].isSet())
602 return SK_TemplateTemplateParameter;
603
604 if (NamingStyles[SK_TemplateParameter].isSet())
605 return SK_TemplateParameter;
606
607 return SK_Invalid;
608 }
609
610 return SK_Invalid;
611}
612
Alexander Kornienko3d777682015-09-28 08:59:12 +0000613static void addUsage(IdentifierNamingCheck::NamingCheckFailureMap &Failures,
Alexander Kornienko21503902016-06-17 09:25:24 +0000614 const IdentifierNamingCheck::NamingCheckId &Decl,
615 SourceRange Range) {
Jonathan Coe2c8592a2016-01-26 18:55:55 +0000616 // Do nothing if the provided range is invalid.
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000617 if (Range.getBegin().isInvalid() || Range.getEnd().isInvalid())
618 return;
619
620 // Try to insert the identifier location in the Usages map, and bail out if it
621 // is already in there
Alexander Kornienko3d777682015-09-28 08:59:12 +0000622 auto &Failure = Failures[Decl];
623 if (!Failure.RawUsageLocs.insert(Range.getBegin().getRawEncoding()).second)
624 return;
625
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000626 Failure.ShouldFix = Failure.ShouldFix && !Range.getBegin().isMacroID() &&
Alexander Kornienko3d777682015-09-28 08:59:12 +0000627 !Range.getEnd().isMacroID();
628}
629
Alexander Kornienko21503902016-06-17 09:25:24 +0000630/// Convenience method when the usage to be added is a NamedDecl
631static void addUsage(IdentifierNamingCheck::NamingCheckFailureMap &Failures,
632 const NamedDecl *Decl, SourceRange Range) {
633 return addUsage(Failures, IdentifierNamingCheck::NamingCheckId(
634 Decl->getLocation(), Decl->getNameAsString()),
635 Range);
636}
637
Alexander Kornienko76c28802015-08-19 11:15:36 +0000638void IdentifierNamingCheck::check(const MatchFinder::MatchResult &Result) {
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000639 if (const auto *Decl =
640 Result.Nodes.getNodeAs<CXXConstructorDecl>("classRef")) {
641 if (Decl->isImplicit())
642 return;
643
644 addUsage(NamingCheckFailures, Decl->getParent(),
Alexander Kornienko21503902016-06-17 09:25:24 +0000645 Decl->getNameInfo().getSourceRange());
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000646 return;
647 }
648
649 if (const auto *Decl =
650 Result.Nodes.getNodeAs<CXXDestructorDecl>("classRef")) {
651 if (Decl->isImplicit())
652 return;
653
654 SourceRange Range = Decl->getNameInfo().getSourceRange();
655 if (Range.getBegin().isInvalid())
656 return;
657 // The first token that will be found is the ~ (or the equivalent trigraph),
658 // we want instead to replace the next token, that will be the identifier.
659 Range.setBegin(CharSourceRange::getTokenRange(Range).getEnd());
660
Alexander Kornienko21503902016-06-17 09:25:24 +0000661 addUsage(NamingCheckFailures, Decl->getParent(), Range);
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000662 return;
663 }
664
665 if (const auto *Loc = Result.Nodes.getNodeAs<TypeLoc>("typeLoc")) {
666 NamedDecl *Decl = nullptr;
667 if (const auto &Ref = Loc->getAs<TagTypeLoc>()) {
668 Decl = Ref.getDecl();
669 } else if (const auto &Ref = Loc->getAs<InjectedClassNameTypeLoc>()) {
670 Decl = Ref.getDecl();
671 } else if (const auto &Ref = Loc->getAs<UnresolvedUsingTypeLoc>()) {
672 Decl = Ref.getDecl();
673 } else if (const auto &Ref = Loc->getAs<TemplateTypeParmTypeLoc>()) {
674 Decl = Ref.getDecl();
675 }
676
677 if (Decl) {
Alexander Kornienko21503902016-06-17 09:25:24 +0000678 addUsage(NamingCheckFailures, Decl, Loc->getSourceRange());
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000679 return;
680 }
681
682 if (const auto &Ref = Loc->getAs<TemplateSpecializationTypeLoc>()) {
683 const auto *Decl =
684 Ref.getTypePtr()->getTemplateName().getAsTemplateDecl();
685
686 SourceRange Range(Ref.getTemplateNameLoc(), Ref.getTemplateNameLoc());
687 if (const auto *ClassDecl = dyn_cast<TemplateDecl>(Decl)) {
Matthias Gehrea9e812b2016-07-09 20:09:28 +0000688 if (const auto *TemplDecl = ClassDecl->getTemplatedDecl())
689 addUsage(NamingCheckFailures, TemplDecl, Range);
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000690 return;
691 }
692 }
693
694 if (const auto &Ref =
695 Loc->getAs<DependentTemplateSpecializationTypeLoc>()) {
Matthias Gehrea9e812b2016-07-09 20:09:28 +0000696 if (const auto *Decl = Ref.getTypePtr()->getAsTagDecl())
697 addUsage(NamingCheckFailures, Decl, Loc->getSourceRange());
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000698 return;
699 }
700 }
701
702 if (const auto *Loc =
703 Result.Nodes.getNodeAs<NestedNameSpecifierLoc>("nestedNameLoc")) {
704 if (NestedNameSpecifier *Spec = Loc->getNestedNameSpecifier()) {
705 if (NamespaceDecl *Decl = Spec->getAsNamespace()) {
Alexander Kornienko21503902016-06-17 09:25:24 +0000706 addUsage(NamingCheckFailures, Decl, Loc->getLocalSourceRange());
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000707 return;
708 }
709 }
710 }
711
712 if (const auto *Decl = Result.Nodes.getNodeAs<UsingDecl>("using")) {
713 for (const auto &Shadow : Decl->shadows()) {
714 addUsage(NamingCheckFailures, Shadow->getTargetDecl(),
Alexander Kornienko21503902016-06-17 09:25:24 +0000715 Decl->getNameInfo().getSourceRange());
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000716 }
717 return;
718 }
719
720 if (const auto *DeclRef = Result.Nodes.getNodeAs<DeclRefExpr>("declRef")) {
Alexander Kornienko76c28802015-08-19 11:15:36 +0000721 SourceRange Range = DeclRef->getNameInfo().getSourceRange();
Alexander Kornienko21503902016-06-17 09:25:24 +0000722 addUsage(NamingCheckFailures, DeclRef->getDecl(), Range);
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000723 return;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000724 }
725
726 if (const auto *Decl = Result.Nodes.getNodeAs<NamedDecl>("decl")) {
727 if (!Decl->getIdentifier() || Decl->getName().empty() || Decl->isImplicit())
728 return;
729
Alexander Kornienko21503902016-06-17 09:25:24 +0000730 // Fix type aliases in value declarations
731 if (const auto *Value = Result.Nodes.getNodeAs<ValueDecl>("decl")) {
732 if (const auto *Typedef =
733 Value->getType().getTypePtr()->getAs<TypedefType>()) {
734 addUsage(NamingCheckFailures, Typedef->getDecl(),
735 Value->getSourceRange());
736 }
737 }
738
739 // Fix type aliases in function declarations
740 if (const auto *Value = Result.Nodes.getNodeAs<FunctionDecl>("decl")) {
741 if (const auto *Typedef =
742 Value->getReturnType().getTypePtr()->getAs<TypedefType>()) {
743 addUsage(NamingCheckFailures, Typedef->getDecl(),
744 Value->getSourceRange());
745 }
746 for (unsigned i = 0; i < Value->getNumParams(); ++i) {
747 if (const auto *Typedef = Value->parameters()[i]
748 ->getType()
749 .getTypePtr()
750 ->getAs<TypedefType>()) {
751 addUsage(NamingCheckFailures, Typedef->getDecl(),
752 Value->getSourceRange());
753 }
754 }
755 }
756
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000757 // Ignore ClassTemplateSpecializationDecl which are creating duplicate
758 // replacements with CXXRecordDecl
759 if (isa<ClassTemplateSpecializationDecl>(Decl))
760 return;
761
Alexander Kornienko76c28802015-08-19 11:15:36 +0000762 StyleKind SK = findStyleKind(Decl, NamingStyles);
763 if (SK == SK_Invalid)
764 return;
765
766 NamingStyle Style = NamingStyles[SK];
767 StringRef Name = Decl->getName();
768 if (matchesStyle(Name, Style))
769 return;
770
771 std::string KindName = fixupWithCase(StyleNames[SK], CT_LowerCase);
772 std::replace(KindName.begin(), KindName.end(), '_', ' ');
773
774 std::string Fixup = fixupWithStyle(Name, Style);
775 if (StringRef(Fixup).equals(Name)) {
776 if (!IgnoreFailedSplit) {
Hans Wennborg53bd9f32016-02-29 21:17:39 +0000777 DEBUG(llvm::dbgs()
778 << Decl->getLocStart().printToString(*Result.SourceManager)
779 << llvm::format(": unable to split words for %s '%s'\n",
780 KindName.c_str(), Name));
Alexander Kornienko76c28802015-08-19 11:15:36 +0000781 }
782 } else {
Alexander Kornienko21503902016-06-17 09:25:24 +0000783 NamingCheckFailure &Failure = NamingCheckFailures[NamingCheckId(
784 Decl->getLocation(), Decl->getNameAsString())];
Alexander Kornienko76c28802015-08-19 11:15:36 +0000785 SourceRange Range =
786 DeclarationNameInfo(Decl->getDeclName(), Decl->getLocation())
787 .getSourceRange();
788
789 Failure.Fixup = std::move(Fixup);
790 Failure.KindName = std::move(KindName);
Alexander Kornienko21503902016-06-17 09:25:24 +0000791 addUsage(NamingCheckFailures, Decl, Range);
Alexander Kornienko76c28802015-08-19 11:15:36 +0000792 }
793 }
794}
795
Alexander Kornienko21503902016-06-17 09:25:24 +0000796void IdentifierNamingCheck::checkMacro(SourceManager &SourceMgr,
797 const Token &MacroNameTok,
798 const MacroInfo *MI) {
799 StringRef Name = MacroNameTok.getIdentifierInfo()->getName();
800 NamingStyle Style = NamingStyles[SK_MacroDefinition];
801 if (matchesStyle(Name, Style))
802 return;
803
804 std::string KindName =
805 fixupWithCase(StyleNames[SK_MacroDefinition], CT_LowerCase);
806 std::replace(KindName.begin(), KindName.end(), '_', ' ');
807
808 std::string Fixup = fixupWithStyle(Name, Style);
809 if (StringRef(Fixup).equals(Name)) {
810 if (!IgnoreFailedSplit) {
811 DEBUG(
812 llvm::dbgs() << MacroNameTok.getLocation().printToString(SourceMgr)
813 << llvm::format(": unable to split words for %s '%s'\n",
814 KindName.c_str(), Name));
815 }
816 } else {
817 NamingCheckId ID(MI->getDefinitionLoc(), Name);
818 NamingCheckFailure &Failure = NamingCheckFailures[ID];
819 SourceRange Range(MacroNameTok.getLocation(), MacroNameTok.getEndLoc());
820
821 Failure.Fixup = std::move(Fixup);
822 Failure.KindName = std::move(KindName);
823 addUsage(NamingCheckFailures, ID, Range);
824 }
825}
826
827void IdentifierNamingCheck::expandMacro(const Token &MacroNameTok,
828 const MacroInfo *MI) {
829 StringRef Name = MacroNameTok.getIdentifierInfo()->getName();
830 NamingCheckId ID(MI->getDefinitionLoc(), Name);
831
832 auto Failure = NamingCheckFailures.find(ID);
833 if (Failure == NamingCheckFailures.end())
834 return;
835
836 SourceRange Range(MacroNameTok.getLocation(), MacroNameTok.getEndLoc());
837 addUsage(NamingCheckFailures, ID, Range);
838}
839
Alexander Kornienko76c28802015-08-19 11:15:36 +0000840void IdentifierNamingCheck::onEndOfTranslationUnit() {
841 for (const auto &Pair : NamingCheckFailures) {
Alexander Kornienko21503902016-06-17 09:25:24 +0000842 const NamingCheckId &Decl = Pair.first;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000843 const NamingCheckFailure &Failure = Pair.second;
844
Alexander Kornienko3d777682015-09-28 08:59:12 +0000845 if (Failure.KindName.empty())
846 continue;
847
Alexander Kornienko76c28802015-08-19 11:15:36 +0000848 if (Failure.ShouldFix) {
Alexander Kornienko21503902016-06-17 09:25:24 +0000849 auto Diag = diag(Decl.first, "invalid case style for %0 '%1'")
850 << Failure.KindName << Decl.second;
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000851
Alexander Kornienko3d777682015-09-28 08:59:12 +0000852 for (const auto &Loc : Failure.RawUsageLocs) {
853 // We assume that the identifier name is made of one token only. This is
854 // always the case as we ignore usages in macros that could build
855 // identifier names by combining multiple tokens.
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000856 //
857 // For destructors, we alread take care of it by remembering the
858 // location of the start of the identifier and not the start of the
859 // tilde.
860 //
861 // Other multi-token identifiers, such as operators are not checked at
862 // all.
Alexander Kornienko76c28802015-08-19 11:15:36 +0000863 Diag << FixItHint::CreateReplacement(
Alexander Kornienko3d777682015-09-28 08:59:12 +0000864 SourceRange(SourceLocation::getFromRawEncoding(Loc)),
865 Failure.Fixup);
Alexander Kornienko76c28802015-08-19 11:15:36 +0000866 }
867 }
868 }
869}
870
871} // namespace readability
872} // namespace tidy
873} // namespace clang