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