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