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