blob: bca5d465f602a8b4943dbb11e9513fb42d4a05b1 [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
Aaron Ballman2931002c2016-07-29 21:41:18 +000012#include "llvm/ADT/DenseMapInfo.h"
Alexander Kornienko76c28802015-08-19 11:15:36 +000013#include "llvm/Support/Debug.h"
14#include "llvm/Support/Format.h"
15#include "clang/ASTMatchers/ASTMatchFinder.h"
Alexander Kornienko21503902016-06-17 09:25:24 +000016#include "clang/Frontend/CompilerInstance.h"
17#include "clang/Lex/PPCallbacks.h"
18#include "clang/Lex/Preprocessor.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,
Jason Henline481e6aa2016-10-24 17:20:32 +0000615 SourceRange Range, SourceManager *SourceMgr = nullptr) {
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
Jason Henline481e6aa2016-10-24 17:20:32 +0000620 // If we have a source manager, use it to convert to the spelling location for
621 // performing the fix. This is necessary because macros can map the same
622 // spelling location to different source locations, and we only want to fix
623 // the token once, before it is expanded by the macro.
624 SourceLocation FixLocation = Range.getBegin();
625 if (SourceMgr)
626 FixLocation = SourceMgr->getSpellingLoc(FixLocation);
627 if (FixLocation.isInvalid())
628 return;
629
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000630 // Try to insert the identifier location in the Usages map, and bail out if it
631 // is already in there
Alexander Kornienko3d777682015-09-28 08:59:12 +0000632 auto &Failure = Failures[Decl];
Jason Henline481e6aa2016-10-24 17:20:32 +0000633 if (!Failure.RawUsageLocs.insert(FixLocation.getRawEncoding()).second)
Alexander Kornienko3d777682015-09-28 08:59:12 +0000634 return;
635
Jason Henline481e6aa2016-10-24 17:20:32 +0000636 if (!Failure.ShouldFix)
637 return;
638
639 // Check if the range is entirely contained within a macro argument.
640 SourceLocation MacroArgExpansionStartForRangeBegin;
641 SourceLocation MacroArgExpansionStartForRangeEnd;
642 bool RangeIsEntirelyWithinMacroArgument =
643 SourceMgr &&
644 SourceMgr->isMacroArgExpansion(Range.getBegin(),
645 &MacroArgExpansionStartForRangeBegin) &&
646 SourceMgr->isMacroArgExpansion(Range.getEnd(),
647 &MacroArgExpansionStartForRangeEnd) &&
648 MacroArgExpansionStartForRangeBegin == MacroArgExpansionStartForRangeEnd;
649
650 // Check if the range contains any locations from a macro expansion.
651 bool RangeContainsMacroExpansion = RangeIsEntirelyWithinMacroArgument ||
652 Range.getBegin().isMacroID() ||
653 Range.getEnd().isMacroID();
654
655 bool RangeCanBeFixed =
656 RangeIsEntirelyWithinMacroArgument || !RangeContainsMacroExpansion;
657 Failure.ShouldFix = RangeCanBeFixed;
Alexander Kornienko3d777682015-09-28 08:59:12 +0000658}
659
Alexander Kornienko21503902016-06-17 09:25:24 +0000660/// Convenience method when the usage to be added is a NamedDecl
661static void addUsage(IdentifierNamingCheck::NamingCheckFailureMap &Failures,
Jason Henline481e6aa2016-10-24 17:20:32 +0000662 const NamedDecl *Decl, SourceRange Range, SourceManager *SourceMgr = nullptr) {
Alexander Kornienko21503902016-06-17 09:25:24 +0000663 return addUsage(Failures, IdentifierNamingCheck::NamingCheckId(
664 Decl->getLocation(), Decl->getNameAsString()),
Jason Henline481e6aa2016-10-24 17:20:32 +0000665 Range, SourceMgr);
Alexander Kornienko21503902016-06-17 09:25:24 +0000666}
667
Alexander Kornienko76c28802015-08-19 11:15:36 +0000668void IdentifierNamingCheck::check(const MatchFinder::MatchResult &Result) {
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000669 if (const auto *Decl =
670 Result.Nodes.getNodeAs<CXXConstructorDecl>("classRef")) {
671 if (Decl->isImplicit())
672 return;
673
674 addUsage(NamingCheckFailures, Decl->getParent(),
Alexander Kornienko21503902016-06-17 09:25:24 +0000675 Decl->getNameInfo().getSourceRange());
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000676 return;
677 }
678
679 if (const auto *Decl =
680 Result.Nodes.getNodeAs<CXXDestructorDecl>("classRef")) {
681 if (Decl->isImplicit())
682 return;
683
684 SourceRange Range = Decl->getNameInfo().getSourceRange();
685 if (Range.getBegin().isInvalid())
686 return;
687 // The first token that will be found is the ~ (or the equivalent trigraph),
688 // we want instead to replace the next token, that will be the identifier.
689 Range.setBegin(CharSourceRange::getTokenRange(Range).getEnd());
690
Alexander Kornienko21503902016-06-17 09:25:24 +0000691 addUsage(NamingCheckFailures, Decl->getParent(), Range);
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000692 return;
693 }
694
695 if (const auto *Loc = Result.Nodes.getNodeAs<TypeLoc>("typeLoc")) {
696 NamedDecl *Decl = nullptr;
697 if (const auto &Ref = Loc->getAs<TagTypeLoc>()) {
698 Decl = Ref.getDecl();
699 } else if (const auto &Ref = Loc->getAs<InjectedClassNameTypeLoc>()) {
700 Decl = Ref.getDecl();
701 } else if (const auto &Ref = Loc->getAs<UnresolvedUsingTypeLoc>()) {
702 Decl = Ref.getDecl();
703 } else if (const auto &Ref = Loc->getAs<TemplateTypeParmTypeLoc>()) {
704 Decl = Ref.getDecl();
705 }
706
707 if (Decl) {
Alexander Kornienko21503902016-06-17 09:25:24 +0000708 addUsage(NamingCheckFailures, Decl, Loc->getSourceRange());
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000709 return;
710 }
711
712 if (const auto &Ref = Loc->getAs<TemplateSpecializationTypeLoc>()) {
713 const auto *Decl =
714 Ref.getTypePtr()->getTemplateName().getAsTemplateDecl();
715
716 SourceRange Range(Ref.getTemplateNameLoc(), Ref.getTemplateNameLoc());
717 if (const auto *ClassDecl = dyn_cast<TemplateDecl>(Decl)) {
Matthias Gehrea9e812b2016-07-09 20:09:28 +0000718 if (const auto *TemplDecl = ClassDecl->getTemplatedDecl())
719 addUsage(NamingCheckFailures, TemplDecl, Range);
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000720 return;
721 }
722 }
723
724 if (const auto &Ref =
725 Loc->getAs<DependentTemplateSpecializationTypeLoc>()) {
Matthias Gehrea9e812b2016-07-09 20:09:28 +0000726 if (const auto *Decl = Ref.getTypePtr()->getAsTagDecl())
727 addUsage(NamingCheckFailures, Decl, Loc->getSourceRange());
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000728 return;
729 }
730 }
731
732 if (const auto *Loc =
733 Result.Nodes.getNodeAs<NestedNameSpecifierLoc>("nestedNameLoc")) {
734 if (NestedNameSpecifier *Spec = Loc->getNestedNameSpecifier()) {
735 if (NamespaceDecl *Decl = Spec->getAsNamespace()) {
Alexander Kornienko21503902016-06-17 09:25:24 +0000736 addUsage(NamingCheckFailures, Decl, Loc->getLocalSourceRange());
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000737 return;
738 }
739 }
740 }
741
742 if (const auto *Decl = Result.Nodes.getNodeAs<UsingDecl>("using")) {
743 for (const auto &Shadow : Decl->shadows()) {
744 addUsage(NamingCheckFailures, Shadow->getTargetDecl(),
Alexander Kornienko21503902016-06-17 09:25:24 +0000745 Decl->getNameInfo().getSourceRange());
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000746 }
747 return;
748 }
749
750 if (const auto *DeclRef = Result.Nodes.getNodeAs<DeclRefExpr>("declRef")) {
Alexander Kornienko76c28802015-08-19 11:15:36 +0000751 SourceRange Range = DeclRef->getNameInfo().getSourceRange();
Jason Henline481e6aa2016-10-24 17:20:32 +0000752 addUsage(NamingCheckFailures, DeclRef->getDecl(), Range, Result.SourceManager);
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000753 return;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000754 }
755
756 if (const auto *Decl = Result.Nodes.getNodeAs<NamedDecl>("decl")) {
757 if (!Decl->getIdentifier() || Decl->getName().empty() || Decl->isImplicit())
758 return;
759
Alexander Kornienko21503902016-06-17 09:25:24 +0000760 // Fix type aliases in value declarations
761 if (const auto *Value = Result.Nodes.getNodeAs<ValueDecl>("decl")) {
762 if (const auto *Typedef =
763 Value->getType().getTypePtr()->getAs<TypedefType>()) {
764 addUsage(NamingCheckFailures, Typedef->getDecl(),
765 Value->getSourceRange());
766 }
767 }
768
769 // Fix type aliases in function declarations
770 if (const auto *Value = Result.Nodes.getNodeAs<FunctionDecl>("decl")) {
771 if (const auto *Typedef =
772 Value->getReturnType().getTypePtr()->getAs<TypedefType>()) {
773 addUsage(NamingCheckFailures, Typedef->getDecl(),
774 Value->getSourceRange());
775 }
776 for (unsigned i = 0; i < Value->getNumParams(); ++i) {
777 if (const auto *Typedef = Value->parameters()[i]
778 ->getType()
779 .getTypePtr()
780 ->getAs<TypedefType>()) {
781 addUsage(NamingCheckFailures, Typedef->getDecl(),
782 Value->getSourceRange());
783 }
784 }
785 }
786
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000787 // Ignore ClassTemplateSpecializationDecl which are creating duplicate
788 // replacements with CXXRecordDecl
789 if (isa<ClassTemplateSpecializationDecl>(Decl))
790 return;
791
Alexander Kornienko76c28802015-08-19 11:15:36 +0000792 StyleKind SK = findStyleKind(Decl, NamingStyles);
793 if (SK == SK_Invalid)
794 return;
795
796 NamingStyle Style = NamingStyles[SK];
797 StringRef Name = Decl->getName();
798 if (matchesStyle(Name, Style))
799 return;
800
801 std::string KindName = fixupWithCase(StyleNames[SK], CT_LowerCase);
802 std::replace(KindName.begin(), KindName.end(), '_', ' ');
803
804 std::string Fixup = fixupWithStyle(Name, Style);
805 if (StringRef(Fixup).equals(Name)) {
806 if (!IgnoreFailedSplit) {
Hans Wennborg53bd9f32016-02-29 21:17:39 +0000807 DEBUG(llvm::dbgs()
808 << Decl->getLocStart().printToString(*Result.SourceManager)
809 << llvm::format(": unable to split words for %s '%s'\n",
Mehdi Amini9ff8e872016-10-07 08:25:42 +0000810 KindName.c_str(), Name.str().c_str()));
Alexander Kornienko76c28802015-08-19 11:15:36 +0000811 }
812 } else {
Alexander Kornienko21503902016-06-17 09:25:24 +0000813 NamingCheckFailure &Failure = NamingCheckFailures[NamingCheckId(
814 Decl->getLocation(), Decl->getNameAsString())];
Alexander Kornienko76c28802015-08-19 11:15:36 +0000815 SourceRange Range =
816 DeclarationNameInfo(Decl->getDeclName(), Decl->getLocation())
817 .getSourceRange();
818
819 Failure.Fixup = std::move(Fixup);
820 Failure.KindName = std::move(KindName);
Alexander Kornienko21503902016-06-17 09:25:24 +0000821 addUsage(NamingCheckFailures, Decl, Range);
Alexander Kornienko76c28802015-08-19 11:15:36 +0000822 }
823 }
824}
825
Alexander Kornienko21503902016-06-17 09:25:24 +0000826void IdentifierNamingCheck::checkMacro(SourceManager &SourceMgr,
827 const Token &MacroNameTok,
828 const MacroInfo *MI) {
829 StringRef Name = MacroNameTok.getIdentifierInfo()->getName();
830 NamingStyle Style = NamingStyles[SK_MacroDefinition];
831 if (matchesStyle(Name, Style))
832 return;
833
834 std::string KindName =
835 fixupWithCase(StyleNames[SK_MacroDefinition], CT_LowerCase);
836 std::replace(KindName.begin(), KindName.end(), '_', ' ');
837
838 std::string Fixup = fixupWithStyle(Name, Style);
839 if (StringRef(Fixup).equals(Name)) {
840 if (!IgnoreFailedSplit) {
841 DEBUG(
842 llvm::dbgs() << MacroNameTok.getLocation().printToString(SourceMgr)
843 << llvm::format(": unable to split words for %s '%s'\n",
Mehdi Amini9ff8e872016-10-07 08:25:42 +0000844 KindName.c_str(), Name.str().c_str()));
Alexander Kornienko21503902016-06-17 09:25:24 +0000845 }
846 } else {
847 NamingCheckId ID(MI->getDefinitionLoc(), Name);
848 NamingCheckFailure &Failure = NamingCheckFailures[ID];
849 SourceRange Range(MacroNameTok.getLocation(), MacroNameTok.getEndLoc());
850
851 Failure.Fixup = std::move(Fixup);
852 Failure.KindName = std::move(KindName);
853 addUsage(NamingCheckFailures, ID, Range);
854 }
855}
856
857void IdentifierNamingCheck::expandMacro(const Token &MacroNameTok,
858 const MacroInfo *MI) {
859 StringRef Name = MacroNameTok.getIdentifierInfo()->getName();
860 NamingCheckId ID(MI->getDefinitionLoc(), Name);
861
862 auto Failure = NamingCheckFailures.find(ID);
863 if (Failure == NamingCheckFailures.end())
864 return;
865
866 SourceRange Range(MacroNameTok.getLocation(), MacroNameTok.getEndLoc());
867 addUsage(NamingCheckFailures, ID, Range);
868}
869
Alexander Kornienko76c28802015-08-19 11:15:36 +0000870void IdentifierNamingCheck::onEndOfTranslationUnit() {
871 for (const auto &Pair : NamingCheckFailures) {
Alexander Kornienko21503902016-06-17 09:25:24 +0000872 const NamingCheckId &Decl = Pair.first;
Alexander Kornienko76c28802015-08-19 11:15:36 +0000873 const NamingCheckFailure &Failure = Pair.second;
874
Alexander Kornienko3d777682015-09-28 08:59:12 +0000875 if (Failure.KindName.empty())
876 continue;
877
Alexander Kornienko76c28802015-08-19 11:15:36 +0000878 if (Failure.ShouldFix) {
Alexander Kornienko21503902016-06-17 09:25:24 +0000879 auto Diag = diag(Decl.first, "invalid case style for %0 '%1'")
880 << Failure.KindName << Decl.second;
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000881
Alexander Kornienko3d777682015-09-28 08:59:12 +0000882 for (const auto &Loc : Failure.RawUsageLocs) {
883 // We assume that the identifier name is made of one token only. This is
884 // always the case as we ignore usages in macros that could build
885 // identifier names by combining multiple tokens.
Alexander Kornienko30c423b2015-10-01 09:19:40 +0000886 //
887 // For destructors, we alread take care of it by remembering the
888 // location of the start of the identifier and not the start of the
889 // tilde.
890 //
891 // Other multi-token identifiers, such as operators are not checked at
892 // all.
Alexander Kornienko76c28802015-08-19 11:15:36 +0000893 Diag << FixItHint::CreateReplacement(
Alexander Kornienko3d777682015-09-28 08:59:12 +0000894 SourceRange(SourceLocation::getFromRawEncoding(Loc)),
895 Failure.Fixup);
Alexander Kornienko76c28802015-08-19 11:15:36 +0000896 }
897 }
898 }
899}
900
901} // namespace readability
902} // namespace tidy
903} // namespace clang