Debian Codegraph @

llvm-project/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp

raw
1 //===--- IdentifierNamingCheck.cpp - clang-tidy ---------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "IdentifierNamingCheck.h"
10
11 #include "../GlobList.h"
12 #include "clang/AST/CXXInheritance.h"
13 #include "clang/Lex/PPCallbacks.h"
14 #include "clang/Lex/Preprocessor.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/DenseMapInfo.h"
17 #include "llvm/Support/Debug.h"
18 #include "llvm/Support/Error.h"
19 #include "llvm/Support/FormatVariadic.h"
20 #include "llvm/Support/Path.h"
21 #include "llvm/Support/Regex.h"
22 #include "llvm/Support/YAMLParser.h"
23 #include <optional>
24
25 #define DEBUG_TYPE "clang-tidy"
26
27 // FixItHint
28
29 using namespace clang::ast_matchers;
30
31 namespace clang::tidy {
32
33 llvm::ArrayRef<
34 std::pair<readability::IdentifierNamingCheck::CaseType, StringRef>>
35 OptionEnumMapping<
36 readability::IdentifierNamingCheck::CaseType>::getEnumMapping() {
37 static constexpr std::pair<readability::IdentifierNamingCheck::CaseType,
38 StringRef>
39 Mapping[] = {
40 {readability::IdentifierNamingCheck::CT_AnyCase, "aNy_CasE"},
41 {readability::IdentifierNamingCheck::CT_LowerCase, "lower_case"},
42 {readability::IdentifierNamingCheck::CT_UpperCase, "UPPER_CASE"},
43 {readability::IdentifierNamingCheck::CT_CamelBack, "camelBack"},
44 {readability::IdentifierNamingCheck::CT_CamelCase, "CamelCase"},
45 {readability::IdentifierNamingCheck::CT_CamelSnakeCase,
46 "Camel_Snake_Case"},
47 {readability::IdentifierNamingCheck::CT_CamelSnakeBack,
48 "camel_Snake_Back"}};
49 return llvm::ArrayRef(Mapping);
50 }
51
52 template <>
53 struct OptionEnumMapping<
54 readability::IdentifierNamingCheck::HungarianPrefixType> {
55 using HungarianPrefixType =
56 readability::IdentifierNamingCheck::HungarianPrefixType;
57 static llvm::ArrayRef<std::pair<HungarianPrefixType, StringRef>>
58 getEnumMapping() {
59 static constexpr std::pair<HungarianPrefixType, StringRef> Mapping[] = {
60 {HungarianPrefixType::HPT_Off, "Off"},
61 {HungarianPrefixType::HPT_On, "On"},
62 {HungarianPrefixType::HPT_LowerCase, "LowerCase"},
63 {HungarianPrefixType::HPT_CamelCase, "CamelCase"}};
64 return llvm::ArrayRef(Mapping);
65 }
66 };
67
68 namespace readability {
69
70 // clang-format off
71 #define NAMING_KEYS(m) \
72 m(Namespace) \
73 m(InlineNamespace) \
74 m(EnumConstant) \
75 m(ScopedEnumConstant) \
76 m(ConstexprVariable) \
77 m(ConstantMember) \
78 m(PrivateMember) \
79 m(ProtectedMember) \
80 m(PublicMember) \
81 m(Member) \
82 m(ClassConstant) \
83 m(ClassMember) \
84 m(GlobalConstant) \
85 m(GlobalConstantPointer) \
86 m(GlobalPointer) \
87 m(GlobalVariable) \
88 m(LocalConstant) \
89 m(LocalConstantPointer) \
90 m(LocalPointer) \
91 m(LocalVariable) \
92 m(StaticConstant) \
93 m(StaticVariable) \
94 m(Constant) \
95 m(Variable) \
96 m(ConstantParameter) \
97 m(ParameterPack) \
98 m(Parameter) \
99 m(PointerParameter) \
100 m(ConstantPointerParameter) \
101 m(AbstractClass) \
102 m(Struct) \
103 m(Class) \
104 m(Union) \
105 m(Enum) \
106 m(GlobalFunction) \
107 m(ConstexprFunction) \
108 m(Function) \
109 m(ConstexprMethod) \
110 m(VirtualMethod) \
111 m(ClassMethod) \
112 m(PrivateMethod) \
113 m(ProtectedMethod) \
114 m(PublicMethod) \
115 m(Method) \
116 m(Typedef) \
117 m(TypeTemplateParameter) \
118 m(ValueTemplateParameter) \
119 m(TemplateTemplateParameter) \
120 m(TemplateParameter) \
121 m(TypeAlias) \
122 m(MacroDefinition) \
123 m(ObjcIvar) \
124
125 enum StyleKind : int {
126 #define ENUMERATE(v) SK_ ## v,
127 NAMING_KEYS(ENUMERATE)
128 #undef ENUMERATE
129 SK_Count,
130 SK_Invalid
131 };
132
133 static StringRef const StyleNames[] = {
134 #define STRINGIZE(v) #v,
135 NAMING_KEYS(STRINGIZE)
136 #undef STRINGIZE
137 };
138
139 #define HUNGARIAN_NOTATION_PRIMITIVE_TYPES(m) \
140 m(int8_t) \
141 m(int16_t) \
142 m(int32_t) \
143 m(int64_t) \
144 m(uint8_t) \
145 m(uint16_t) \
146 m(uint32_t) \
147 m(uint64_t) \
148 m(char8_t) \
149 m(char16_t) \
150 m(char32_t) \
151 m(float) \
152 m(double) \
153 m(char) \
154 m(bool) \
155 m(_Bool) \
156 m(int) \
157 m(size_t) \
158 m(wchar_t) \
159 m(short-int) \
160 m(short) \
161 m(signed-int) \
162 m(signed-short) \
163 m(signed-short-int) \
164 m(signed-long-long-int) \
165 m(signed-long-long) \
166 m(signed-long-int) \
167 m(signed-long) \
168 m(signed) \
169 m(unsigned-long-long-int) \
170 m(unsigned-long-long) \
171 m(unsigned-long-int) \
172 m(unsigned-long) \
173 m(unsigned-short-int) \
174 m(unsigned-short) \
175 m(unsigned-int) \
176 m(unsigned) \
177 m(long-long-int) \
178 m(long-double) \
179 m(long-long) \
180 m(long-int) \
181 m(long) \
182 m(ptrdiff_t) \
183
184 static StringRef const HungarainNotationPrimitiveTypes[] = {
185 #define STRINGIZE(v) #v,
186 HUNGARIAN_NOTATION_PRIMITIVE_TYPES(STRINGIZE)
187 #undef STRINGIZE
188 };
189
190 #define HUNGARIAN_NOTATION_USER_DEFINED_TYPES(m) \
191 m(BOOL) \
192 m(BOOLEAN) \
193 m(BYTE) \
194 m(CHAR) \
195 m(UCHAR) \
196 m(SHORT) \
197 m(USHORT) \
198 m(WORD) \
199 m(DWORD) \
200 m(DWORD32) \
201 m(DWORD64) \
202 m(LONG) \
203 m(ULONG) \
204 m(ULONG32) \
205 m(ULONG64) \
206 m(ULONGLONG) \
207 m(HANDLE) \
208 m(INT) \
209 m(INT8) \
210 m(INT16) \
211 m(INT32) \
212 m(INT64) \
213 m(UINT) \
214 m(UINT8) \
215 m(UINT16) \
216 m(UINT32) \
217 m(UINT64) \
218 m(PVOID) \
219
220 static StringRef const HungarainNotationUserDefinedTypes[] = {
221 #define STRINGIZE(v) #v,
222 HUNGARIAN_NOTATION_USER_DEFINED_TYPES(STRINGIZE)
223 #undef STRINGIZE
224 };
225
226
227 #undef NAMING_KEYS
228 // clang-format on
229
230 IdentifierNamingCheck::NamingStyle::NamingStyle(
231 std::optional<IdentifierNamingCheck::CaseType> Case,
232 const std::string &Prefix, const std::string &Suffix,
233 const std::string &IgnoredRegexpStr, HungarianPrefixType HPType)
234 : Case(Case), Prefix(Prefix), Suffix(Suffix),
235 IgnoredRegexpStr(IgnoredRegexpStr), HPType(HPType) {
236 if (!IgnoredRegexpStr.empty()) {
237 IgnoredRegexp =
238 llvm::Regex(llvm::SmallString<128>({"^", IgnoredRegexpStr, "$"}));
239 if (!IgnoredRegexp.isValid())
240 llvm::errs() << "Invalid IgnoredRegexp regular expression: "
241 << IgnoredRegexpStr;
242 }
243 }
244
245 IdentifierNamingCheck::FileStyle IdentifierNamingCheck::getFileStyleFromOptions(
246 const ClangTidyCheck::OptionsView &Options) const {
247 IdentifierNamingCheck::HungarianNotationOption HNOption;
248
249 HungarianNotation.loadDefaultConfig(HNOption);
250 HungarianNotation.loadFileConfig(Options, HNOption);
251
252 SmallVector<std::optional<IdentifierNamingCheck::NamingStyle>, 0> Styles;
253 Styles.resize(SK_Count);
254 SmallString<64> StyleString;
255 for (unsigned I = 0; I < SK_Count; ++I) {
256 size_t StyleSize = StyleNames[I].size();
257 StyleString.assign({StyleNames[I], "HungarianPrefix"});
258
259 auto HPTOpt =
260 Options.get<IdentifierNamingCheck::HungarianPrefixType>(StyleString);
261 if (HPTOpt && !HungarianNotation.checkOptionValid(I))
262 configurationDiag("invalid identifier naming option '%0'") << StyleString;
263
264 memcpy(&StyleString[StyleSize], "IgnoredRegexp", 13);
265 StyleString.truncate(StyleSize + 13);
266 StringRef IgnoredRegexpStr = Options.get(StyleString, "");
267 memcpy(&StyleString[StyleSize], "Prefix", 6);
268 StyleString.truncate(StyleSize + 6);
269 std::string Prefix(Options.get(StyleString, ""));
270 // Fast replacement of [Pre]fix -> [Suf]fix.
271 memcpy(&StyleString[StyleSize], "Suf", 3);
272 std::string Postfix(Options.get(StyleString, ""));
273 memcpy(&StyleString[StyleSize], "Case", 4);
274 StyleString.pop_back_n(2);
275 auto CaseOptional =
276 Options.get<IdentifierNamingCheck::CaseType>(StyleString);
277
278 if (CaseOptional || !Prefix.empty() || !Postfix.empty() ||
279 !IgnoredRegexpStr.empty() || HPTOpt)
280 Styles[I].emplace(std::move(CaseOptional), std::move(Prefix),
281 std::move(Postfix), IgnoredRegexpStr.str(),
282 HPTOpt.value_or(IdentifierNamingCheck::HPT_Off));
283 }
284 bool IgnoreMainLike = Options.get("IgnoreMainLikeFunctions", false);
285 return {std::move(Styles), std::move(HNOption), IgnoreMainLike};
286 }
287
288 std::string IdentifierNamingCheck::HungarianNotation::getDeclTypeName(
289 const NamedDecl *ND) const {
290 const auto *VD = dyn_cast<ValueDecl>(ND);
291 if (!VD)
292 return {};
293
294 if (isa<FunctionDecl, EnumConstantDecl>(ND))
295 return {};
296
297 // Get type text of variable declarations.
298 auto &SM = VD->getASTContext().getSourceManager();
299 const char *Begin = SM.getCharacterData(VD->getBeginLoc());
300 const char *End = SM.getCharacterData(VD->getEndLoc());
301 intptr_t StrLen = End - Begin;
302
303 // FIXME: Sometimes the value that returns from ValDecl->getEndLoc()
304 // is wrong(out of location of Decl). This causes `StrLen` will be assigned
305 // an unexpected large value. Current workaround to find the terminated
306 // character instead of the `getEndLoc()` function.
307 const char *EOL = strchr(Begin, '\n');
308 if (!EOL)
309 EOL = Begin + strlen(Begin);
310
311 const char *PosList[] = {strchr(Begin, '='), strchr(Begin, ';'),
312 strchr(Begin, ','), strchr(Begin, ')'), EOL};
313 for (const auto &Pos : PosList) {
314 if (Pos > Begin)
315 EOL = std::min(EOL, Pos);
316 }
317
318 StrLen = EOL - Begin;
319 std::string TypeName;
320 if (StrLen > 0) {
321 std::string Type(Begin, StrLen);
322
323 static constexpr StringRef Keywords[] = {
324 // Constexpr specifiers
325 "constexpr", "constinit", "consteval",
326 // Qualifier
327 "const", "volatile", "restrict", "mutable",
328 // Storage class specifiers
329 "register", "static", "extern", "thread_local",
330 // Other keywords
331 "virtual"};
332
333 // Remove keywords
334 for (StringRef Kw : Keywords) {
335 for (size_t Pos = 0;
336 (Pos = Type.find(Kw.data(), Pos)) != std::string::npos;) {
337 Type.replace(Pos, Kw.size(), "");
338 }
339 }
340 TypeName = Type.erase(0, Type.find_first_not_of(" "));
341
342 // Replace spaces with single space.
343 for (size_t Pos = 0; (Pos = Type.find(" ", Pos)) != std::string::npos;
344 Pos += strlen(" ")) {
345 Type.replace(Pos, strlen(" "), " ");
346 }
347
348 // Replace " &" with "&".
349 for (size_t Pos = 0; (Pos = Type.find(" &", Pos)) != std::string::npos;
350 Pos += strlen("&")) {
351 Type.replace(Pos, strlen(" &"), "&");
352 }
353
354 // Replace " *" with "* ".
355 for (size_t Pos = 0; (Pos = Type.find(" *", Pos)) != std::string::npos;
356 Pos += strlen("*")) {
357 Type.replace(Pos, strlen(" *"), "* ");
358 }
359
360 // Remove redundant tailing.
361 static constexpr StringRef TailsOfMultiWordType[] = {
362 " int", " char", " double", " long", " short"};
363 bool RedundantRemoved = false;
364 for (auto Kw : TailsOfMultiWordType) {
365 size_t Pos = Type.rfind(Kw.data());
366 if (Pos != std::string::npos) {
367 Type = Type.substr(0, Pos + Kw.size());
368 RedundantRemoved = true;
369 break;
370 }
371 }
372 TypeName = Type.erase(0, Type.find_first_not_of(" "));
373 if (!RedundantRemoved) {
374 std::size_t FoundSpace = Type.find(" ");
375 if (FoundSpace != std::string::npos)
376 Type = Type.substr(0, FoundSpace);
377 }
378
379 TypeName = Type.erase(0, Type.find_first_not_of(" "));
380
381 QualType QT = VD->getType();
382 if (!QT.isNull() && QT->isArrayType())
383 TypeName.append("[]");
384 }
385
386 return TypeName;
387 }
388
389 IdentifierNamingCheck::IdentifierNamingCheck(StringRef Name,
390 ClangTidyContext *Context)
391 : RenamerClangTidyCheck(Name, Context), Context(Context), CheckName(Name),
392 GetConfigPerFile(Options.get("GetConfigPerFile", true)),
393 IgnoreFailedSplit(Options.get("IgnoreFailedSplit", false)) {
394
395 auto IterAndInserted = NamingStylesCache.try_emplace(
396 llvm::sys::path::parent_path(Context->getCurrentFile()),
397 getFileStyleFromOptions(Options));
398 assert(IterAndInserted.second && "Couldn't insert Style");
399 // Holding a reference to the data in the vector is safe as it should never
400 // move.
401 MainFileStyle = &IterAndInserted.first->getValue();
402 }
403
404 IdentifierNamingCheck::~IdentifierNamingCheck() = default;
405
406 bool IdentifierNamingCheck::HungarianNotation::checkOptionValid(
407 int StyleKindIndex) const {
408 if ((StyleKindIndex >= SK_EnumConstant) &&
409 (StyleKindIndex <= SK_ConstantParameter))
410 return true;
411
412 if ((StyleKindIndex >= SK_Parameter) && (StyleKindIndex <= SK_Enum))
413 return true;
414
415 return false;
416 }
417
418 bool IdentifierNamingCheck::HungarianNotation::isOptionEnabled(
419 StringRef OptionKey, const llvm::StringMap<std::string> &StrMap) const {
420 if (OptionKey.empty())
421 return false;
422
423 auto Iter = StrMap.find(OptionKey);
424 if (Iter == StrMap.end())
425 return false;
426
427 return *llvm::yaml::parseBool(Iter->getValue());
428 }
429
430 void IdentifierNamingCheck::HungarianNotation::loadFileConfig(
431 const ClangTidyCheck::OptionsView &Options,
432 IdentifierNamingCheck::HungarianNotationOption &HNOption) const {
433
434 static constexpr StringRef HNOpts[] = {"TreatStructAsClass"};
435 static constexpr StringRef HNDerivedTypes[] = {"Array", "Pointer",
436 "FunctionPointer"};
437
438 StringRef Section = "HungarianNotation.";
439
440 SmallString<128> Buffer = {Section, "General."};
441 size_t DefSize = Buffer.size();
442 for (const auto &Opt : HNOpts) {
443 Buffer.truncate(DefSize);
444 Buffer.append(Opt);
445 StringRef Val = Options.get(Buffer, "");
446 if (!Val.empty())
447 HNOption.General[Opt] = Val.str();
448 }
449
450 Buffer = {Section, "DerivedType."};
451 DefSize = Buffer.size();
452 for (const auto &Type : HNDerivedTypes) {
453 Buffer.truncate(DefSize);
454 Buffer.append(Type);
455 StringRef Val = Options.get(Buffer, "");
456 if (!Val.empty())
457 HNOption.DerivedType[Type] = Val.str();
458 }
459
460 static constexpr std::pair<StringRef, StringRef> HNCStrings[] = {
461 {"CharPrinter", "char*"},
462 {"CharArray", "char[]"},
463 {"WideCharPrinter", "wchar_t*"},
464 {"WideCharArray", "wchar_t[]"}};
465
466 Buffer = {Section, "CString."};
467 DefSize = Buffer.size();
468 for (const auto &CStr : HNCStrings) {
469 Buffer.truncate(DefSize);
470 Buffer.append(CStr.first);
471 StringRef Val = Options.get(Buffer, "");
472 if (!Val.empty())
473 HNOption.CString[CStr.first] = Val.str();
474 }
475
476 Buffer = {Section, "PrimitiveType."};
477 DefSize = Buffer.size();
478 for (const auto &PrimType : HungarainNotationPrimitiveTypes) {
479 Buffer.truncate(DefSize);
480 Buffer.append(PrimType);
481 StringRef Val = Options.get(Buffer, "");
482 if (!Val.empty()) {
483 std::string Type = PrimType.str();
484 std::replace(Type.begin(), Type.end(), '-', ' ');
485 HNOption.PrimitiveType[Type] = Val.str();
486 }
487 }
488
489 Buffer = {Section, "UserDefinedType."};
490 DefSize = Buffer.size();
491 for (const auto &Type : HungarainNotationUserDefinedTypes) {
492 Buffer.truncate(DefSize);
493 Buffer.append(Type);
494 StringRef Val = Options.get(Buffer, "");
495 if (!Val.empty())
496 HNOption.UserDefinedType[Type] = Val.str();
497 }
498 }
499
500 std::string IdentifierNamingCheck::HungarianNotation::getPrefix(
501 const Decl *D,
502 const IdentifierNamingCheck::HungarianNotationOption &HNOption) const {
503 if (!D)
504 return {};
505 const auto *ND = dyn_cast<NamedDecl>(D);
506 if (!ND)
507 return {};
508
509 std::string Prefix;
510 if (const auto *ECD = dyn_cast<EnumConstantDecl>(ND)) {
511 Prefix = getEnumPrefix(ECD);
512 } else if (const auto *CRD = dyn_cast<CXXRecordDecl>(ND)) {
513 Prefix = getClassPrefix(CRD, HNOption);
514 } else if (isa<VarDecl, FieldDecl, RecordDecl>(ND)) {
515 std::string TypeName = getDeclTypeName(ND);
516 if (!TypeName.empty())
517 Prefix = getDataTypePrefix(TypeName, ND, HNOption);
518 }
519
520 return Prefix;
521 }
522
523 bool IdentifierNamingCheck::HungarianNotation::removeDuplicatedPrefix(
524 SmallVector<StringRef, 8> &Words,
525 const IdentifierNamingCheck::HungarianNotationOption &HNOption) const {
526 if (Words.size() <= 1)
527 return true;
528
529 std::string CorrectName = Words[0].str();
530 std::vector<llvm::StringMap<std::string>> MapList = {
531 HNOption.CString, HNOption.DerivedType, HNOption.PrimitiveType,
532 HNOption.UserDefinedType};
533
534 for (const auto &Map : MapList) {
535 for (const auto &Str : Map) {
536 if (Str.getValue() == CorrectName) {
537 Words.erase(Words.begin(), Words.begin() + 1);
538 return true;
539 }
540 }
541 }
542
543 return false;
544 }
545
546 std::string IdentifierNamingCheck::HungarianNotation::getDataTypePrefix(
547 StringRef TypeName, const NamedDecl *ND,
548 const IdentifierNamingCheck::HungarianNotationOption &HNOption) const {
549 if (!ND || TypeName.empty())
550 return TypeName.str();
551
552 std::string ModifiedTypeName(TypeName);
553
554 // Derived types
555 std::string PrefixStr;
556 if (const auto *TD = dyn_cast<ValueDecl>(ND)) {
557 QualType QT = TD->getType();
558 if (QT->isFunctionPointerType()) {
559 PrefixStr = HNOption.DerivedType.lookup("FunctionPointer");
560 } else if (QT->isPointerType()) {
561 for (const auto &CStr : HNOption.CString) {
562 std::string Key = CStr.getKey().str();
563 if (ModifiedTypeName.find(Key) == 0) {
564 PrefixStr = CStr.getValue();
565 ModifiedTypeName = ModifiedTypeName.substr(
566 Key.size(), ModifiedTypeName.size() - Key.size());
567 break;
568 }
569 }
570 } else if (QT->isArrayType()) {
571 for (const auto &CStr : HNOption.CString) {
572 std::string Key = CStr.getKey().str();
573 if (ModifiedTypeName.find(Key) == 0) {
574 PrefixStr = CStr.getValue();
575 break;
576 }
577 }
578 if (PrefixStr.empty())
579 PrefixStr = HNOption.DerivedType.lookup("Array");
580 } else if (QT->isReferenceType()) {
581 size_t Pos = ModifiedTypeName.find_last_of("&");
582 if (Pos != std::string::npos)
583 ModifiedTypeName = ModifiedTypeName.substr(0, Pos);
584 }
585 }
586
587 // Pointers
588 size_t PtrCount = [&](std::string TypeName) -> size_t {
589 size_t Pos = TypeName.find('*');
590 size_t Count = 0;
591 for (; Pos < TypeName.length(); Pos++, Count++) {
592 if ('*' != TypeName[Pos])
593 break;
594 }
595 return Count;
596 }(ModifiedTypeName);
597 if (PtrCount > 0) {
598 ModifiedTypeName = [&](std::string Str, StringRef From, StringRef To) {
599 size_t StartPos = 0;
600 while ((StartPos = Str.find(From.data(), StartPos)) !=
601 std::string::npos) {
602 Str.replace(StartPos, From.size(), To.data());
603 StartPos += To.size();
604 }
605 return Str;
606 }(ModifiedTypeName, "*", "");
607 }
608
609 // Primitive types
610 if (PrefixStr.empty()) {
611 for (const auto &Type : HNOption.PrimitiveType) {
612 if (ModifiedTypeName == Type.getKey()) {
613 PrefixStr = Type.getValue();
614 break;
615 }
616 }
617 }
618
619 // User-Defined types
620 if (PrefixStr.empty()) {
621 for (const auto &Type : HNOption.UserDefinedType) {
622 if (ModifiedTypeName == Type.getKey()) {
623 PrefixStr = Type.getValue();
624 break;
625 }
626 }
627 }
628
629 for (size_t Idx = 0; Idx < PtrCount; Idx++)
630 PrefixStr.insert(0, HNOption.DerivedType.lookup("Pointer"));
631
632 return PrefixStr;
633 }
634
635 std::string IdentifierNamingCheck::HungarianNotation::getClassPrefix(
636 const CXXRecordDecl *CRD,
637 const IdentifierNamingCheck::HungarianNotationOption &HNOption) const {
638
639 if (CRD->isUnion())
640 return {};
641
642 if (CRD->isStruct() &&
643 !isOptionEnabled("TreatStructAsClass", HNOption.General))
644 return {};
645
646 return CRD->isAbstract() ? "I" : "C";
647 }
648
649 std::string IdentifierNamingCheck::HungarianNotation::getEnumPrefix(
650 const EnumConstantDecl *ECD) const {
651 std::string Name = ECD->getType().getAsString();
652 if (std::string::npos != Name.find("enum")) {
653 Name = Name.substr(strlen("enum"), Name.length() - strlen("enum"));
654 Name = Name.erase(0, Name.find_first_not_of(" "));
655 }
656
657 static llvm::Regex Splitter(
658 "([a-z0-9A-Z]*)(_+)|([A-Z]?[a-z0-9]+)([A-Z]|$)|([A-Z]+)([A-Z]|$)");
659
660 StringRef EnumName(Name);
661 SmallVector<StringRef, 8> Substrs;
662 EnumName.split(Substrs, "_", -1, false);
663
664 SmallVector<StringRef, 8> Words;
665 SmallVector<StringRef, 8> Groups;
666 for (auto Substr : Substrs) {
667 while (!Substr.empty()) {
668 Groups.clear();
669 if (!Splitter.match(Substr, &Groups))
670 break;
671
672 if (Groups[2].size() > 0) {
673 Words.push_back(Groups[1]);
674 Substr = Substr.substr(Groups[0].size());
675 } else if (Groups[3].size() > 0) {
676 Words.push_back(Groups[3]);
677 Substr = Substr.substr(Groups[0].size() - Groups[4].size());
678 } else if (Groups[5].size() > 0) {
679 Words.push_back(Groups[5]);
680 Substr = Substr.substr(Groups[0].size() - Groups[6].size());
681 }
682 }
683 }
684
685 std::string Initial;
686 for (StringRef Word : Words)
687 Initial += tolower(Word[0]);
688
689 return Initial;
690 }
691
692 void IdentifierNamingCheck::HungarianNotation::loadDefaultConfig(
693 IdentifierNamingCheck::HungarianNotationOption &HNOption) const {
694
695 // Options
696 static constexpr std::pair<StringRef, StringRef> General[] = {
697 {"TreatStructAsClass", "false"}};
698 for (const auto &G : General)
699 HNOption.General.try_emplace(G.first, G.second);
700
701 // Derived types
702 static constexpr std::pair<StringRef, StringRef> DerivedTypes[] = {
703 {"Array", "a"}, {"Pointer", "p"}, {"FunctionPointer", "fn"}};
704 for (const auto &DT : DerivedTypes)
705 HNOption.DerivedType.try_emplace(DT.first, DT.second);
706
707 // C strings
708 static constexpr std::pair<StringRef, StringRef> CStrings[] = {
709 {"char*", "sz"},
710 {"char[]", "sz"},
711 {"wchar_t*", "wsz"},
712 {"wchar_t[]", "wsz"}};
713 for (const auto &CStr : CStrings)
714 HNOption.CString.try_emplace(CStr.first, CStr.second);
715
716 // clang-format off
717 static constexpr std::pair<StringRef, StringRef> PrimitiveTypes[] = {
718 {"int8_t", "i8" },
719 {"int16_t", "i16" },
720 {"int32_t", "i32" },
721 {"int64_t", "i64" },
722 {"uint8_t", "u8" },
723 {"uint16_t", "u16" },
724 {"uint32_t", "u32" },
725 {"uint64_t", "u64" },
726 {"char8_t", "c8" },
727 {"char16_t", "c16" },
728 {"char32_t", "c32" },
729 {"float", "f" },
730 {"double", "d" },
731 {"char", "c" },
732 {"bool", "b" },
733 {"_Bool", "b" },
734 {"int", "i" },
735 {"size_t", "n" },
736 {"wchar_t", "wc" },
737 {"short int", "si" },
738 {"short", "s" },
739 {"signed int", "si" },
740 {"signed short", "ss" },
741 {"signed short int", "ssi" },
742 {"signed long long int", "slli"},
743 {"signed long long", "sll" },
744 {"signed long int", "sli" },
745 {"signed long", "sl" },
746 {"signed", "s" },
747 {"unsigned long long int", "ulli"},
748 {"unsigned long long", "ull" },
749 {"unsigned long int", "uli" },
750 {"unsigned long", "ul" },
751 {"unsigned short int", "usi" },
752 {"unsigned short", "us" },
753 {"unsigned int", "ui" },
754 {"unsigned", "u" },
755 {"long long int", "lli" },
756 {"long double", "ld" },
757 {"long long", "ll" },
758 {"long int", "li" },
759 {"long", "l" },
760 {"ptrdiff_t", "p" }};
761 // clang-format on
762 for (const auto &PT : PrimitiveTypes)
763 HNOption.PrimitiveType.try_emplace(PT.first, PT.second);
764
765 // clang-format off
766 static constexpr std::pair<StringRef, StringRef> UserDefinedTypes[] = {
767 // Windows data types
768 {"BOOL", "b" },
769 {"BOOLEAN", "b" },
770 {"BYTE", "by" },
771 {"CHAR", "c" },
772 {"UCHAR", "uc" },
773 {"SHORT", "s" },
774 {"USHORT", "us" },
775 {"WORD", "w" },
776 {"DWORD", "dw" },
777 {"DWORD32", "dw32"},
778 {"DWORD64", "dw64"},
779 {"LONG", "l" },
780 {"ULONG", "ul" },
781 {"ULONG32", "ul32"},
782 {"ULONG64", "ul64"},
783 {"ULONGLONG", "ull" },
784 {"HANDLE", "h" },
785 {"INT", "i" },
786 {"INT8", "i8" },
787 {"INT16", "i16" },
788 {"INT32", "i32" },
789 {"INT64", "i64" },
790 {"UINT", "ui" },
791 {"UINT8", "u8" },
792 {"UINT16", "u16" },
793 {"UINT32", "u32" },
794 {"UINT64", "u64" },
795 {"PVOID", "p" } };
796 // clang-format on
797 for (const auto &UDT : UserDefinedTypes)
798 HNOption.UserDefinedType.try_emplace(UDT.first, UDT.second);
799 }
800
801 void IdentifierNamingCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
802 RenamerClangTidyCheck::storeOptions(Opts);
803 SmallString<64> StyleString;
804 ArrayRef<std::optional<NamingStyle>> Styles = MainFileStyle->getStyles();
805 for (size_t I = 0; I < SK_Count; ++I) {
806 if (!Styles[I])
807 continue;
808 size_t StyleSize = StyleNames[I].size();
809 StyleString.assign({StyleNames[I], "HungarianPrefix"});
810
811 Options.store(Opts, StyleString, Styles[I]->HPType);
812
813 memcpy(&StyleString[StyleSize], "IgnoredRegexp", 13);
814 StyleString.truncate(StyleSize + 13);
815 Options.store(Opts, StyleString, Styles[I]->IgnoredRegexpStr);
816 memcpy(&StyleString[StyleSize], "Prefix", 6);
817 StyleString.truncate(StyleSize + 6);
818 Options.store(Opts, StyleString, Styles[I]->Prefix);
819 // Fast replacement of [Pre]fix -> [Suf]fix.
820 memcpy(&StyleString[StyleSize], "Suf", 3);
821 Options.store(Opts, StyleString, Styles[I]->Suffix);
822 if (Styles[I]->Case) {
823 memcpy(&StyleString[StyleSize], "Case", 4);
824 StyleString.pop_back_n(2);
825 Options.store(Opts, StyleString, *Styles[I]->Case);
826 }
827 }
828 Options.store(Opts, "GetConfigPerFile", GetConfigPerFile);
829 Options.store(Opts, "IgnoreFailedSplit", IgnoreFailedSplit);
830 Options.store(Opts, "IgnoreMainLikeFunctions",
831 MainFileStyle->isIgnoringMainLikeFunction());
832 }
833
834 bool IdentifierNamingCheck::matchesStyle(
835 StringRef Type, StringRef Name,
836 const IdentifierNamingCheck::NamingStyle &Style,
837 const IdentifierNamingCheck::HungarianNotationOption &HNOption,
838 const NamedDecl *Decl) const {
839 static llvm::Regex Matchers[] = {
840 llvm::Regex("^.*$"),
841 llvm::Regex("^[a-z][a-z0-9_]*$"),
842 llvm::Regex("^[a-z][a-zA-Z0-9]*$"),
843 llvm::Regex("^[A-Z][A-Z0-9_]*$"),
844 llvm::Regex("^[A-Z][a-zA-Z0-9]*$"),
845 llvm::Regex("^[A-Z]([a-z0-9]*(_[A-Z])?)*"),
846 llvm::Regex("^[a-z]([a-z0-9]*(_[A-Z])?)*"),
847 };
848
849 if (!Name.consume_front(Style.Prefix))
850 return false;
851 if (!Name.consume_back(Style.Suffix))
852 return false;
853 if (IdentifierNamingCheck::HungarianPrefixType::HPT_Off != Style.HPType) {
854 std::string HNPrefix = HungarianNotation.getPrefix(Decl, HNOption);
855 if (!Name.consume_front(HNPrefix))
856 return false;
857 }
858
859 // Ensure the name doesn't have any extra underscores beyond those specified
860 // in the prefix and suffix.
861 if (Name.startswith("_") || Name.endswith("_"))
862 return false;
863
864 if (Style.Case && !Matchers[static_cast<size_t>(*Style.Case)].match(Name))
865 return false;
866
867 return true;
868 }
869
870 std::string IdentifierNamingCheck::fixupWithCase(
871 StringRef Type, StringRef Name, const Decl *D,
872 const IdentifierNamingCheck::NamingStyle &Style,
873 const IdentifierNamingCheck::HungarianNotationOption &HNOption,
874 IdentifierNamingCheck::CaseType Case) const {
875 static llvm::Regex Splitter(
876 "([a-z0-9A-Z]*)(_+)|([A-Z]?[a-z0-9]+)([A-Z]|$)|([A-Z]+)([A-Z]|$)");
877
878 SmallVector<StringRef, 8> Substrs;
879 Name.split(Substrs, "_", -1, false);
880
881 SmallVector<StringRef, 8> Words;
882 SmallVector<StringRef, 8> Groups;
883 for (auto Substr : Substrs) {
884 while (!Substr.empty()) {
885 Groups.clear();
886 if (!Splitter.match(Substr, &Groups))
887 break;
888
889 if (Groups[2].size() > 0) {
890 Words.push_back(Groups[1]);
891 Substr = Substr.substr(Groups[0].size());
892 } else if (Groups[3].size() > 0) {
893 Words.push_back(Groups[3]);
894 Substr = Substr.substr(Groups[0].size() - Groups[4].size());
895 } else if (Groups[5].size() > 0) {
896 Words.push_back(Groups[5]);
897 Substr = Substr.substr(Groups[0].size() - Groups[6].size());
898 }
899 }
900 }
901
902 if (Words.empty())
903 return Name.str();
904
905 if (IdentifierNamingCheck::HungarianPrefixType::HPT_Off != Style.HPType) {
906 HungarianNotation.removeDuplicatedPrefix(Words, HNOption);
907 }
908
909 SmallString<128> Fixup;
910 switch (Case) {
911 case IdentifierNamingCheck::CT_AnyCase:
912 return Name.str();
913 break;
914
915 case IdentifierNamingCheck::CT_LowerCase:
916 for (auto const &Word : Words) {
917 if (&Word != &Words.front())
918 Fixup += "_";
919 Fixup += Word.lower();
920 }
921 break;
922
923 case IdentifierNamingCheck::CT_UpperCase:
924 for (auto const &Word : Words) {
925 if (&Word != &Words.front())
926 Fixup += "_";
927 Fixup += Word.upper();
928 }
929 break;
930
931 case IdentifierNamingCheck::CT_CamelCase:
932 for (auto const &Word : Words) {
933 Fixup += toupper(Word.front());
934 Fixup += Word.substr(1).lower();
935 }
936 break;
937
938 case IdentifierNamingCheck::CT_CamelBack:
939 for (auto const &Word : Words) {
940 if (&Word == &Words.front()) {
941 Fixup += Word.lower();
942 } else {
943 Fixup += toupper(Word.front());
944 Fixup += Word.substr(1).lower();
945 }
946 }
947 break;
948
949 case IdentifierNamingCheck::CT_CamelSnakeCase:
950 for (auto const &Word : Words) {
951 if (&Word != &Words.front())
952 Fixup += "_";
953 Fixup += toupper(Word.front());
954 Fixup += Word.substr(1).lower();
955 }
956 break;
957
958 case IdentifierNamingCheck::CT_CamelSnakeBack:
959 for (auto const &Word : Words) {
960 if (&Word != &Words.front()) {
961 Fixup += "_";
962 Fixup += toupper(Word.front());
963 } else {
964 Fixup += tolower(Word.front());
965 }
966 Fixup += Word.substr(1).lower();
967 }
968 break;
969 }
970
971 return Fixup.str().str();
972 }
973
974 bool IdentifierNamingCheck::isParamInMainLikeFunction(
975 const ParmVarDecl &ParmDecl, bool IncludeMainLike) const {
976 const auto *FDecl =
977 dyn_cast_or_null<FunctionDecl>(ParmDecl.getParentFunctionOrMethod());
978 if (!FDecl)
979 return false;
980 if (FDecl->isMain())
981 return true;
982 if (!IncludeMainLike)
983 return false;
984 if (FDecl->getAccess() != AS_public && FDecl->getAccess() != AS_none)
985 return false;
986 // If the function doesn't have a name that's an identifier, can occur if the
987 // function is an operator overload, bail out early.
988 if (!FDecl->getDeclName().isIdentifier())
989 return false;
990 enum MainType { None, Main, WMain };
991 auto IsCharPtrPtr = [](QualType QType) -> MainType {
992 if (QType.isNull())
993 return None;
994 if (QType = QType->getPointeeType(), QType.isNull())
995 return None;
996 if (QType = QType->getPointeeType(), QType.isNull())
997 return None;
998 if (QType->isCharType())
999 return Main;
1000 if (QType->isWideCharType())
1001 return WMain;
1002 return None;
1003 };
1004 auto IsIntType = [](QualType QType) {
1005 if (QType.isNull())
1006 return false;
1007 if (const auto *Builtin =
1008 dyn_cast<BuiltinType>(QType->getUnqualifiedDesugaredType())) {
1009 return Builtin->getKind() == BuiltinType::Int;
1010 }
1011 return false;
1012 };
1013 if (!IsIntType(FDecl->getReturnType()))
1014 return false;
1015 if (FDecl->getNumParams() < 2 || FDecl->getNumParams() > 3)
1016 return false;
1017 if (!IsIntType(FDecl->parameters()[0]->getType()))
1018 return false;
1019 MainType Type = IsCharPtrPtr(FDecl->parameters()[1]->getType());
1020 if (Type == None)
1021 return false;
1022 if (FDecl->getNumParams() == 3 &&
1023 IsCharPtrPtr(FDecl->parameters()[2]->getType()) != Type)
1024 return false;
1025
1026 if (Type == Main) {
1027 static llvm::Regex Matcher(
1028 "(^[Mm]ain([_A-Z]|$))|([a-z0-9_]Main([_A-Z]|$))|(_main(_|$))");
1029 assert(Matcher.isValid() && "Invalid Matcher for main like functions.");
1030 return Matcher.match(FDecl->getName());
1031 }
1032 static llvm::Regex Matcher("(^((W[Mm])|(wm))ain([_A-Z]|$))|([a-z0-9_]W[Mm]"
1033 "ain([_A-Z]|$))|(_wmain(_|$))");
1034 assert(Matcher.isValid() && "Invalid Matcher for wmain like functions.");
1035 return Matcher.match(FDecl->getName());
1036 }
1037
1038 std::string IdentifierNamingCheck::fixupWithStyle(
1039 StringRef Type, StringRef Name,
1040 const IdentifierNamingCheck::NamingStyle &Style,
1041 const IdentifierNamingCheck::HungarianNotationOption &HNOption,
1042 const Decl *D) const {
1043 Name.consume_front(Style.Prefix);
1044 Name.consume_back(Style.Suffix);
1045 std::string Fixed = fixupWithCase(
1046 Type, Name, D, Style, HNOption,
1047 Style.Case.value_or(IdentifierNamingCheck::CaseType::CT_AnyCase));
1048
1049 std::string HungarianPrefix;
1050 using HungarianPrefixType = IdentifierNamingCheck::HungarianPrefixType;
1051 if (HungarianPrefixType::HPT_Off != Style.HPType) {
1052 HungarianPrefix = HungarianNotation.getPrefix(D, HNOption);
1053 if (!HungarianPrefix.empty()) {
1054 if (Style.HPType == HungarianPrefixType::HPT_LowerCase)
1055 HungarianPrefix += "_";
1056
1057 if (Style.HPType == HungarianPrefixType::HPT_CamelCase)
1058 Fixed[0] = toupper(Fixed[0]);
1059 }
1060 }
1061 StringRef Mid = StringRef(Fixed).trim("_");
1062 if (Mid.empty())
1063 Mid = "_";
1064
1065 return (Style.Prefix + HungarianPrefix + Mid + Style.Suffix).str();
1066 }
1067
1068 StyleKind IdentifierNamingCheck::findStyleKind(
1069 const NamedDecl *D,
1070 ArrayRef<std::optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
1071 bool IgnoreMainLikeFunctions) const {
1072 assert(D && D->getIdentifier() && !D->getName().empty() && !D->isImplicit() &&
1073 "Decl must be an explicit identifier with a name.");
1074
1075 if (isa<ObjCIvarDecl>(D) && NamingStyles[SK_ObjcIvar])
1076 return SK_ObjcIvar;
1077
1078 if (isa<TypedefDecl>(D) && NamingStyles[SK_Typedef])
1079 return SK_Typedef;
1080
1081 if (isa<TypeAliasDecl>(D) && NamingStyles[SK_TypeAlias])
1082 return SK_TypeAlias;
1083
1084 if (const auto *Decl = dyn_cast<NamespaceDecl>(D)) {
1085 if (Decl->isAnonymousNamespace())
1086 return SK_Invalid;
1087
1088 if (Decl->isInline() && NamingStyles[SK_InlineNamespace])
1089 return SK_InlineNamespace;
1090
1091 if (NamingStyles[SK_Namespace])
1092 return SK_Namespace;
1093 }
1094
1095 if (isa<EnumDecl>(D) && NamingStyles[SK_Enum])
1096 return SK_Enum;
1097
1098 if (const auto *EnumConst = dyn_cast<EnumConstantDecl>(D)) {
1099 if (cast<EnumDecl>(EnumConst->getDeclContext())->isScoped() &&
1100 NamingStyles[SK_ScopedEnumConstant])
1101 return SK_ScopedEnumConstant;
1102
1103 if (NamingStyles[SK_EnumConstant])
1104 return SK_EnumConstant;
1105
1106 if (NamingStyles[SK_Constant])
1107 return SK_Constant;
1108
1109 return SK_Invalid;
1110 }
1111
1112 if (const auto *Decl = dyn_cast<CXXRecordDecl>(D)) {
1113 if (Decl->isAnonymousStructOrUnion())
1114 return SK_Invalid;
1115
1116 if (!Decl->getCanonicalDecl()->isThisDeclarationADefinition())
1117 return SK_Invalid;
1118
1119 if (Decl->hasDefinition() && Decl->isAbstract() &&
1120 NamingStyles[SK_AbstractClass])
1121 return SK_AbstractClass;
1122
1123 if (Decl->isStruct() && NamingStyles[SK_Struct])
1124 return SK_Struct;
1125
1126 if (Decl->isStruct() && NamingStyles[SK_Class])
1127 return SK_Class;
1128
1129 if (Decl->isClass() && NamingStyles[SK_Class])
1130 return SK_Class;
1131
1132 if (Decl->isClass() && NamingStyles[SK_Struct])
1133 return SK_Struct;
1134
1135 if (Decl->isUnion() && NamingStyles[SK_Union])
1136 return SK_Union;
1137
1138 if (Decl->isEnum() && NamingStyles[SK_Enum])
1139 return SK_Enum;
1140
1141 return SK_Invalid;
1142 }
1143
1144 if (const auto *Decl = dyn_cast<FieldDecl>(D)) {
1145 QualType Type = Decl->getType();
1146
1147 if (!Type.isNull() && Type.isConstQualified()) {
1148 if (NamingStyles[SK_ConstantMember])
1149 return SK_ConstantMember;
1150
1151 if (NamingStyles[SK_Constant])
1152 return SK_Constant;
1153 }
1154
1155 if (Decl->getAccess() == AS_private && NamingStyles[SK_PrivateMember])
1156 return SK_PrivateMember;
1157
1158 if (Decl->getAccess() == AS_protected && NamingStyles[SK_ProtectedMember])
1159 return SK_ProtectedMember;
1160
1161 if (Decl->getAccess() == AS_public && NamingStyles[SK_PublicMember])
1162 return SK_PublicMember;
1163
1164 if (NamingStyles[SK_Member])
1165 return SK_Member;
1166
1167 return SK_Invalid;
1168 }
1169
1170 if (const auto *Decl = dyn_cast<ParmVarDecl>(D)) {
1171 if (isParamInMainLikeFunction(*Decl, IgnoreMainLikeFunctions))
1172 return SK_Invalid;
1173 QualType Type = Decl->getType();
1174
1175 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprVariable])
1176 return SK_ConstexprVariable;
1177
1178 if (!Type.isNull() && Type.isConstQualified()) {
1179 if (Type.getTypePtr()->isAnyPointerType() &&
1180 NamingStyles[SK_ConstantPointerParameter])
1181 return SK_ConstantPointerParameter;
1182
1183 if (NamingStyles[SK_ConstantParameter])
1184 return SK_ConstantParameter;
1185
1186 if (NamingStyles[SK_Constant])
1187 return SK_Constant;
1188 }
1189
1190 if (Decl->isParameterPack() && NamingStyles[SK_ParameterPack])
1191 return SK_ParameterPack;
1192
1193 if (!Type.isNull() && Type.getTypePtr()->isAnyPointerType() &&
1194 NamingStyles[SK_PointerParameter])
1195 return SK_PointerParameter;
1196
1197 if (NamingStyles[SK_Parameter])
1198 return SK_Parameter;
1199
1200 return SK_Invalid;
1201 }
1202
1203 if (const auto *Decl = dyn_cast<VarDecl>(D)) {
1204 QualType Type = Decl->getType();
1205
1206 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprVariable])
1207 return SK_ConstexprVariable;
1208
1209 if (!Type.isNull() && Type.isConstQualified()) {
1210 if (Decl->isStaticDataMember() && NamingStyles[SK_ClassConstant])
1211 return SK_ClassConstant;
1212
1213 if (Decl->isFileVarDecl() && Type.getTypePtr()->isAnyPointerType() &&
1214 NamingStyles[SK_GlobalConstantPointer])
1215 return SK_GlobalConstantPointer;
1216
1217 if (Decl->isFileVarDecl() && NamingStyles[SK_GlobalConstant])
1218 return SK_GlobalConstant;
1219
1220 if (Decl->isStaticLocal() && NamingStyles[SK_StaticConstant])
1221 return SK_StaticConstant;
1222
1223 if (Decl->isLocalVarDecl() && Type.getTypePtr()->isAnyPointerType() &&
1224 NamingStyles[SK_LocalConstantPointer])
1225 return SK_LocalConstantPointer;
1226
1227 if (Decl->isLocalVarDecl() && NamingStyles[SK_LocalConstant])
1228 return SK_LocalConstant;
1229
1230 if (Decl->isFunctionOrMethodVarDecl() && NamingStyles[SK_LocalConstant])
1231 return SK_LocalConstant;
1232
1233 if (NamingStyles[SK_Constant])
1234 return SK_Constant;
1235 }
1236
1237 if (Decl->isStaticDataMember() && NamingStyles[SK_ClassMember])
1238 return SK_ClassMember;
1239
1240 if (Decl->isFileVarDecl() && Type.getTypePtr()->isAnyPointerType() &&
1241 NamingStyles[SK_GlobalPointer])
1242 return SK_GlobalPointer;
1243
1244 if (Decl->isFileVarDecl() && NamingStyles[SK_GlobalVariable])
1245 return SK_GlobalVariable;
1246
1247 if (Decl->isStaticLocal() && NamingStyles[SK_StaticVariable])
1248 return SK_StaticVariable;
1249
1250 if (Decl->isLocalVarDecl() && Type.getTypePtr()->isAnyPointerType() &&
1251 NamingStyles[SK_LocalPointer])
1252 return SK_LocalPointer;
1253
1254 if (Decl->isLocalVarDecl() && NamingStyles[SK_LocalVariable])
1255 return SK_LocalVariable;
1256
1257 if (Decl->isFunctionOrMethodVarDecl() && NamingStyles[SK_LocalVariable])
1258 return SK_LocalVariable;
1259
1260 if (NamingStyles[SK_Variable])
1261 return SK_Variable;
1262
1263 return SK_Invalid;
1264 }
1265
1266 if (const auto *Decl = dyn_cast<CXXMethodDecl>(D)) {
1267 if (Decl->isMain() || !Decl->isUserProvided() ||
1268 Decl->size_overridden_methods() > 0 || Decl->hasAttr<OverrideAttr>())
1269 return SK_Invalid;
1270
1271 // If this method has the same name as any base method, this is likely
1272 // necessary even if it's not an override. e.g. CRTP.
1273 for (const CXXBaseSpecifier &Base : Decl->getParent()->bases())
1274 if (const auto *RD = Base.getType()->getAsCXXRecordDecl())
1275 if (RD->hasMemberName(Decl->getDeclName()))
1276 return SK_Invalid;
1277
1278 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprMethod])
1279 return SK_ConstexprMethod;
1280
1281 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprFunction])
1282 return SK_ConstexprFunction;
1283
1284 if (Decl->isStatic() && NamingStyles[SK_ClassMethod])
1285 return SK_ClassMethod;
1286
1287 if (Decl->isVirtual() && NamingStyles[SK_VirtualMethod])
1288 return SK_VirtualMethod;
1289
1290 if (Decl->getAccess() == AS_private && NamingStyles[SK_PrivateMethod])
1291 return SK_PrivateMethod;
1292
1293 if (Decl->getAccess() == AS_protected && NamingStyles[SK_ProtectedMethod])
1294 return SK_ProtectedMethod;
1295
1296 if (Decl->getAccess() == AS_public && NamingStyles[SK_PublicMethod])
1297 return SK_PublicMethod;
1298
1299 if (NamingStyles[SK_Method])
1300 return SK_Method;
1301
1302 if (NamingStyles[SK_Function])
1303 return SK_Function;
1304
1305 return SK_Invalid;
1306 }
1307
1308 if (const auto *Decl = dyn_cast<FunctionDecl>(D)) {
1309 if (Decl->isMain())
1310 return SK_Invalid;
1311
1312 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprFunction])
1313 return SK_ConstexprFunction;
1314
1315 if (Decl->isGlobal() && NamingStyles[SK_GlobalFunction])
1316 return SK_GlobalFunction;
1317
1318 if (NamingStyles[SK_Function])
1319 return SK_Function;
1320 }
1321
1322 if (isa<TemplateTypeParmDecl>(D)) {
1323 if (NamingStyles[SK_TypeTemplateParameter])
1324 return SK_TypeTemplateParameter;
1325
1326 if (NamingStyles[SK_TemplateParameter])
1327 return SK_TemplateParameter;
1328
1329 return SK_Invalid;
1330 }
1331
1332 if (isa<NonTypeTemplateParmDecl>(D)) {
1333 if (NamingStyles[SK_ValueTemplateParameter])
1334 return SK_ValueTemplateParameter;
1335
1336 if (NamingStyles[SK_TemplateParameter])
1337 return SK_TemplateParameter;
1338
1339 return SK_Invalid;
1340 }
1341
1342 if (isa<TemplateTemplateParmDecl>(D)) {
1343 if (NamingStyles[SK_TemplateTemplateParameter])
1344 return SK_TemplateTemplateParameter;
1345
1346 if (NamingStyles[SK_TemplateParameter])
1347 return SK_TemplateParameter;
1348
1349 return SK_Invalid;
1350 }
1351
1352 return SK_Invalid;
1353 }
1354
1355 std::optional<RenamerClangTidyCheck::FailureInfo>
1356 IdentifierNamingCheck::getFailureInfo(
1357 StringRef Type, StringRef Name, const NamedDecl *ND,
1358 SourceLocation Location,
1359 ArrayRef<std::optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
1360 const IdentifierNamingCheck::HungarianNotationOption &HNOption,
1361 StyleKind SK, const SourceManager &SM, bool IgnoreFailedSplit) const {
1362 if (SK == SK_Invalid || !NamingStyles[SK])
1363 return std::nullopt;
1364
1365 const IdentifierNamingCheck::NamingStyle &Style = *NamingStyles[SK];
1366 if (Style.IgnoredRegexp.isValid() && Style.IgnoredRegexp.match(Name))
1367 return std::nullopt;
1368
1369 if (matchesStyle(Type, Name, Style, HNOption, ND))
1370 return std::nullopt;
1371
1372 std::string KindName =
1373 fixupWithCase(Type, StyleNames[SK], ND, Style, HNOption,
1374 IdentifierNamingCheck::CT_LowerCase);
1375 std::replace(KindName.begin(), KindName.end(), '_', ' ');
1376
1377 std::string Fixup = fixupWithStyle(Type, Name, Style, HNOption, ND);
1378 if (StringRef(Fixup).equals(Name)) {
1379 if (!IgnoreFailedSplit) {
1380 LLVM_DEBUG(Location.print(llvm::dbgs(), SM);
1381 llvm::dbgs()
1382 << llvm::formatv(": unable to split words for {0} '{1}'\n",
1383 KindName, Name));
1384 }
1385 return std::nullopt;
1386 }
1387 return RenamerClangTidyCheck::FailureInfo{std::move(KindName),
1388 std::move(Fixup)};
1389 }
1390
1391 std::optional<RenamerClangTidyCheck::FailureInfo>
1392 IdentifierNamingCheck::getDeclFailureInfo(const NamedDecl *Decl,
1393 const SourceManager &SM) const {
1394 SourceLocation Loc = Decl->getLocation();
1395 const FileStyle &FileStyle = getStyleForFile(SM.getFilename(Loc));
1396 if (!FileStyle.isActive())
1397 return std::nullopt;
1398
1399 return getFailureInfo(HungarianNotation.getDeclTypeName(Decl),
1400 Decl->getName(), Decl, Loc, FileStyle.getStyles(),
1401 FileStyle.getHNOption(),
1402 findStyleKind(Decl, FileStyle.getStyles(),
1403 FileStyle.isIgnoringMainLikeFunction()),
1404 SM, IgnoreFailedSplit);
1405 }
1406
1407 std::optional<RenamerClangTidyCheck::FailureInfo>
1408 IdentifierNamingCheck::getMacroFailureInfo(const Token &MacroNameTok,
1409 const SourceManager &SM) const {
1410 SourceLocation Loc = MacroNameTok.getLocation();
1411 const FileStyle &Style = getStyleForFile(SM.getFilename(Loc));
1412 if (!Style.isActive())
1413 return std::nullopt;
1414
1415 return getFailureInfo("", MacroNameTok.getIdentifierInfo()->getName(),
1416 nullptr, Loc, Style.getStyles(), Style.getHNOption(),
1417 SK_MacroDefinition, SM, IgnoreFailedSplit);
1418 }
1419
1420 RenamerClangTidyCheck::DiagInfo
1421 IdentifierNamingCheck::getDiagInfo(const NamingCheckId &ID,
1422 const NamingCheckFailure &Failure) const {
1423 return DiagInfo{"invalid case style for %0 '%1'",
1424 [&](DiagnosticBuilder &Diag) {
1425 Diag << Failure.Info.KindName << ID.second;
1426 }};
1427 }
1428
1429 const IdentifierNamingCheck::FileStyle &
1430 IdentifierNamingCheck::getStyleForFile(StringRef FileName) const {
1431 if (!GetConfigPerFile)
1432 return *MainFileStyle;
1433 StringRef Parent = llvm::sys::path::parent_path(FileName);
1434 auto Iter = NamingStylesCache.find(Parent);
1435 if (Iter != NamingStylesCache.end())
1436 return Iter->getValue();
1437
1438 ClangTidyOptions Options = Context->getOptionsForFile(FileName);
1439 if (Options.Checks && GlobList(*Options.Checks).contains(CheckName)) {
1440 auto It = NamingStylesCache.try_emplace(
1441 Parent,
1442 getFileStyleFromOptions({CheckName, Options.CheckOptions, Context}));
1443 assert(It.second);
1444 return It.first->getValue();
1445 }
1446 // Default construction gives an empty style.
1447 auto It = NamingStylesCache.try_emplace(Parent);
1448 assert(It.second);
1449 return It.first->getValue();
1450 }
1451
1452 } // namespace readability
1453 } // namespace clang::tidy