clang-tools 23.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(Default) \
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 = llvm::Regex(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
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 StrLen = EOL - Begin;
327 std::string TypeName;
328 if (StrLen > 0) {
329 std::string Type(Begin, StrLen);
330
331 static constexpr StringRef Keywords[] = {
332 // Constexpr specifiers
333 "constexpr", "constinit", "consteval",
334 // Qualifier
335 "const", "volatile", "restrict", "mutable",
336 // Storage class specifiers
337 "register", "static", "extern", "thread_local",
338 // Other keywords
339 "virtual"};
340
341 // Remove keywords
342 for (const StringRef Kw : Keywords)
343 for (size_t Pos = 0; (Pos = Type.find(Kw, Pos)) != std::string::npos;)
344 Type.replace(Pos, Kw.size(), "");
345 TypeName = Type.erase(0, Type.find_first_not_of(' '));
346
347 // Remove template parameters
348 const size_t Pos = Type.find('<');
349 if (Pos != std::string::npos)
350 TypeName = Type.erase(Pos, Type.size() - Pos);
351
352 // Replace spaces with single space.
353 for (size_t Pos = 0; (Pos = Type.find(" ", Pos)) != std::string::npos;
354 Pos += strlen(" ")) {
355 Type.replace(Pos, strlen(" "), " ");
356 }
357
358 // Replace " &" with "&".
359 for (size_t Pos = 0; (Pos = Type.find(" &", Pos)) != std::string::npos;
360 Pos += strlen("&")) {
361 Type.replace(Pos, strlen(" &"), "&");
362 }
363
364 // Replace " *" with "* ".
365 for (size_t Pos = 0; (Pos = Type.find(" *", Pos)) != std::string::npos;
366 Pos += strlen("*")) {
367 Type.replace(Pos, strlen(" *"), "* ");
368 }
369
370 // Remove redundant tailing.
371 static constexpr StringRef TailsOfMultiWordType[] = {
372 " int", " char", " double", " long", " short"};
373 bool RedundantRemoved = false;
374 for (auto Kw : TailsOfMultiWordType) {
375 const size_t Pos = Type.rfind(Kw);
376 if (Pos != std::string::npos) {
377 const size_t PtrCount = getAsteriskCount(Type, ND);
378 Type = Type.substr(0, Pos + Kw.size() + PtrCount);
379 RedundantRemoved = true;
380 break;
381 }
382 }
383
384 TypeName = Type.erase(0, Type.find_first_not_of(' '));
385 if (!RedundantRemoved) {
386 const std::size_t FoundSpace = Type.find(' ');
387 if (FoundSpace != std::string::npos)
388 Type = Type.substr(0, FoundSpace);
389 }
390
391 TypeName = Type.erase(0, Type.find_first_not_of(' '));
392
393 const QualType QT = VD->getType();
394 if (!QT.isNull() && QT->isArrayType())
395 TypeName.append("[]");
396 }
397
398 return TypeName;
399}
400
402 ClangTidyContext *Context)
403 : RenamerClangTidyCheck(Name, Context), Context(Context),
404 GetConfigPerFile(Options.get("GetConfigPerFile", true)),
405 IgnoreFailedSplit(Options.get("IgnoreFailedSplit", false)) {
406 auto IterAndInserted = NamingStylesCache.try_emplace(
407 llvm::sys::path::parent_path(Context->getCurrentFile()),
408 getFileStyleFromOptions(Options));
409 assert(IterAndInserted.second && "Couldn't insert Style");
410 // Holding a reference to the data in the vector is safe as it should never
411 // move.
412 MainFileStyle = &IterAndInserted.first->getValue();
413}
414
416
418 int StyleKindIndex) const {
419 if ((StyleKindIndex >= SK_EnumConstant) &&
420 (StyleKindIndex <= SK_ConstantParameter))
421 return true;
422
423 if ((StyleKindIndex >= SK_Parameter) && (StyleKindIndex <= SK_Enum))
424 return true;
425
426 return false;
427}
428
430 StringRef OptionKey, const llvm::StringMap<std::string> &StrMap) const {
431 if (OptionKey.empty())
432 return false;
433
434 auto Iter = StrMap.find(OptionKey);
435 if (Iter == StrMap.end())
436 return false;
437
438 return llvm::yaml::parseBool(Iter->getValue()).value_or(false);
439}
440
442 const ClangTidyCheck::OptionsView &Options,
444 static constexpr StringRef HNOpts[] = {"TreatStructAsClass"};
445 static constexpr StringRef HNDerivedTypes[] = {"Array", "Pointer",
446 "FunctionPointer"};
447
448 const StringRef Section = "HungarianNotation.";
449
450 SmallString<128> Buffer = {Section, "General."};
451 size_t DefSize = Buffer.size();
452 for (const auto &Opt : HNOpts) {
453 Buffer.truncate(DefSize);
454 Buffer.append(Opt);
455 const StringRef Val = Options.get(Buffer, "");
456 if (!Val.empty())
457 HNOption.General[Opt] = Val.str();
458 }
459
460 Buffer = {Section, "DerivedType."};
461 DefSize = Buffer.size();
462 for (const auto &Type : HNDerivedTypes) {
463 Buffer.truncate(DefSize);
464 Buffer.append(Type);
465 const StringRef Val = Options.get(Buffer, "");
466 if (!Val.empty())
467 HNOption.DerivedType[Type] = Val.str();
468 }
469
470 static constexpr std::pair<StringRef, StringRef> HNCStrings[] = {
471 {"CharPointer", "char*"},
472 {"CharArray", "char[]"},
473 {"WideCharPointer", "wchar_t*"},
474 {"WideCharArray", "wchar_t[]"}};
475
476 Buffer = {Section, "CString."};
477 DefSize = Buffer.size();
478 for (const auto &CStr : HNCStrings) {
479 Buffer.truncate(DefSize);
480 Buffer.append(CStr.first);
481 const StringRef Val = Options.get(Buffer, "");
482 if (!Val.empty())
483 HNOption.CString[CStr.second] = Val.str();
484 }
485
486 Buffer = {Section, "PrimitiveType."};
487 DefSize = Buffer.size();
488 for (const auto &PrimType : HungarianNotationPrimitiveTypes) {
489 Buffer.truncate(DefSize);
490 Buffer.append(PrimType);
491 const StringRef Val = Options.get(Buffer, "");
492 if (!Val.empty()) {
493 std::string Type = PrimType.str();
494 llvm::replace(Type, '-', ' ');
495 HNOption.PrimitiveType[Type] = Val.str();
496 }
497 }
498
499 Buffer = {Section, "UserDefinedType."};
500 DefSize = Buffer.size();
501 for (const auto &Type : HungarianNotationUserDefinedTypes) {
502 Buffer.truncate(DefSize);
503 Buffer.append(Type);
504 const StringRef Val = Options.get(Buffer, "");
505 if (!Val.empty())
506 HNOption.UserDefinedType[Type] = Val.str();
507 }
508}
509
511 const Decl *D,
513 if (!D)
514 return {};
515 const auto *ND = dyn_cast<NamedDecl>(D);
516 if (!ND)
517 return {};
518
519 std::string Prefix;
520 if (const auto *ECD = dyn_cast<EnumConstantDecl>(ND)) {
521 Prefix = getEnumPrefix(ECD);
522 } else if (const auto *CRD = dyn_cast<CXXRecordDecl>(ND)) {
523 Prefix = getClassPrefix(CRD, HNOption);
524 } else if (isa<VarDecl, FieldDecl, RecordDecl>(ND)) {
525 const std::string TypeName = getDeclTypeName(ND);
526 if (!TypeName.empty())
527 Prefix = getDataTypePrefix(TypeName, ND, HNOption);
528 }
529
530 return Prefix;
531}
532
536 if (Words.size() <= 1)
537 return true;
538
539 const std::string CorrectName = Words[0].str();
540 const std::vector<llvm::StringMap<std::string>> MapList = {
541 HNOption.CString, HNOption.DerivedType, HNOption.PrimitiveType,
542 HNOption.UserDefinedType};
543
544 for (const auto &Map : MapList) {
545 for (const auto &Str : Map) {
546 if (Str.getValue() == CorrectName) {
547 Words.erase(Words.begin(), Words.begin() + 1);
548 return true;
549 }
550 }
551 }
552
553 return false;
554}
555
557 StringRef TypeName, const NamedDecl *ND,
559 if (!ND || TypeName.empty())
560 return TypeName.str();
561
562 std::string ModifiedTypeName(TypeName);
563
564 // Derived types
565 std::string PrefixStr;
566 if (const auto *TD = dyn_cast<ValueDecl>(ND)) {
567 const QualType QT = TD->getType();
568 if (QT->isFunctionPointerType()) {
569 PrefixStr = HNOption.DerivedType.lookup("FunctionPointer");
570 } else if (QT->isPointerType()) {
571 for (const auto &CStr : HNOption.CString) {
572 const std::string Key = CStr.getKey().str();
573 if (ModifiedTypeName.find(Key) == 0) {
574 PrefixStr = CStr.getValue();
575 ModifiedTypeName = ModifiedTypeName.substr(
576 Key.size(), ModifiedTypeName.size() - Key.size());
577 break;
578 }
579 }
580 } else if (QT->isArrayType()) {
581 for (const auto &CStr : HNOption.CString) {
582 const std::string Key = CStr.getKey().str();
583 if (ModifiedTypeName.find(Key) == 0) {
584 PrefixStr = CStr.getValue();
585 break;
586 }
587 }
588 if (PrefixStr.empty())
589 PrefixStr = HNOption.DerivedType.lookup("Array");
590 } else if (QT->isReferenceType()) {
591 const size_t Pos = ModifiedTypeName.find_last_of('&');
592 if (Pos != std::string::npos)
593 ModifiedTypeName = ModifiedTypeName.substr(0, Pos);
594 }
595 }
596
597 // Pointers
598 const size_t PtrCount = getAsteriskCount(ModifiedTypeName);
599 if (PtrCount > 0) {
600 ModifiedTypeName = [&](std::string Str, StringRef From, StringRef To) {
601 size_t StartPos = 0;
602 while ((StartPos = Str.find(From, StartPos)) != std::string::npos) {
603 Str.replace(StartPos, From.size(), To);
604 StartPos += To.size();
605 }
606 return Str;
607 }(ModifiedTypeName, "*", "");
608 }
609
610 // Primitive types
611 if (PrefixStr.empty()) {
612 for (const auto &Type : HNOption.PrimitiveType) {
613 if (ModifiedTypeName == Type.getKey()) {
614 PrefixStr = Type.getValue();
615 break;
616 }
617 }
618 }
619
620 // User-Defined types
621 if (PrefixStr.empty()) {
622 for (const auto &Type : HNOption.UserDefinedType) {
623 if (ModifiedTypeName == Type.getKey()) {
624 PrefixStr = Type.getValue();
625 break;
626 }
627 }
628 }
629
630 for (size_t Idx = 0; Idx < PtrCount; Idx++)
631 PrefixStr.insert(0, HNOption.DerivedType.lookup("Pointer"));
632
633 return PrefixStr;
634}
635
637 const CXXRecordDecl *CRD,
639 if (CRD->isUnion())
640 return {};
641
642 if (CRD->isStruct() &&
643 !isOptionEnabled("TreatStructAsClass", HNOption.General))
644 return {};
645
646 return CRD->isAbstract() ? "I" : "C";
647}
648
650 const EnumConstantDecl *ECD) const {
651 const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
652
653 std::string Name = ED->getName().str();
654 if (StringRef(Name).contains("enum")) {
655 Name = Name.substr(strlen("enum"), Name.length() - strlen("enum"));
656 Name = Name.erase(0, Name.find_first_not_of(' '));
657 }
658
659 static const llvm::Regex Splitter(
660 "([a-z0-9A-Z]*)(_+)|([A-Z]?[a-z0-9]+)([A-Z]|$)|([A-Z]+)([A-Z]|$)");
661
662 const StringRef EnumName(Name);
664 EnumName.split(Substrs, "_", -1, false);
665
668 for (auto Substr : Substrs) {
669 while (!Substr.empty()) {
670 Groups.clear();
671 if (!Splitter.match(Substr, &Groups))
672 break;
673
674 if (!Groups[2].empty()) {
675 Words.push_back(Groups[1]);
676 Substr = Substr.substr(Groups[0].size());
677 } else if (!Groups[3].empty()) {
678 Words.push_back(Groups[3]);
679 Substr = Substr.substr(Groups[0].size() - Groups[4].size());
680 } else if (!Groups[5].empty()) {
681 Words.push_back(Groups[5]);
682 Substr = Substr.substr(Groups[0].size() - Groups[6].size());
683 }
684 }
685 }
686
687 std::string Initial;
688 for (const StringRef Word : Words)
689 Initial += tolower(Word[0]);
690
691 return Initial;
692}
693
695 const std::string &TypeName) const {
696 size_t Pos = TypeName.find('*');
697 size_t Count = 0;
698 for (; Pos < TypeName.length(); Pos++, Count++)
699 if ('*' != TypeName[Pos])
700 break;
701 return Count;
702}
703
705 const std::string &TypeName, const NamedDecl *ND) const {
706 size_t PtrCount = 0;
707 if (const auto *TD = dyn_cast<ValueDecl>(ND)) {
708 const QualType QT = TD->getType();
709 if (QT->isPointerType())
710 PtrCount = getAsteriskCount(TypeName);
711 }
712 return PtrCount;
713}
714
717 // Options
718 static constexpr std::pair<StringRef, StringRef> General[] = {
719 {"TreatStructAsClass", "false"}};
720 for (const auto &G : General)
721 HNOption.General.try_emplace(G.first, G.second);
722
723 // Derived types
724 static constexpr std::pair<StringRef, StringRef> DerivedTypes[] = {
725 {"Array", "a"}, {"Pointer", "p"}, {"FunctionPointer", "fn"}};
726 for (const auto &DT : DerivedTypes)
727 HNOption.DerivedType.try_emplace(DT.first, DT.second);
728
729 // C strings
730 static constexpr std::pair<StringRef, StringRef> CStrings[] = {
731 {"char*", "sz"},
732 {"char[]", "sz"},
733 {"wchar_t*", "wsz"},
734 {"wchar_t[]", "wsz"}};
735 for (const auto &CStr : CStrings)
736 HNOption.CString.try_emplace(CStr.first, CStr.second);
737
738 // clang-format off
739 static constexpr std::pair<StringRef, StringRef> PrimitiveTypes[] = {
740 {"int8_t", "i8" },
741 {"int16_t", "i16" },
742 {"int32_t", "i32" },
743 {"int64_t", "i64" },
744 {"uint8_t", "u8" },
745 {"uint16_t", "u16" },
746 {"uint32_t", "u32" },
747 {"uint64_t", "u64" },
748 {"char8_t", "c8" },
749 {"char16_t", "c16" },
750 {"char32_t", "c32" },
751 {"float", "f" },
752 {"double", "d" },
753 {"char", "c" },
754 {"bool", "b" },
755 {"_Bool", "b" },
756 {"int", "i" },
757 {"size_t", "n" },
758 {"wchar_t", "wc" },
759 {"short int", "si" },
760 {"short", "s" },
761 {"signed int", "si" },
762 {"signed short", "ss" },
763 {"signed short int", "ssi" },
764 {"signed long long int", "slli"},
765 {"signed long long", "sll" },
766 {"signed long int", "sli" },
767 {"signed long", "sl" },
768 {"signed", "s" },
769 {"unsigned long long int", "ulli"},
770 {"unsigned long long", "ull" },
771 {"unsigned long int", "uli" },
772 {"unsigned long", "ul" },
773 {"unsigned short int", "usi" },
774 {"unsigned short", "us" },
775 {"unsigned int", "ui" },
776 {"unsigned char", "uc" },
777 {"unsigned", "u" },
778 {"long long int", "lli" },
779 {"long double", "ld" },
780 {"long long", "ll" },
781 {"long int", "li" },
782 {"long", "l" },
783 {"ptrdiff_t", "p" },
784 {"void", "" }};
785 // clang-format on
786 for (const auto &PT : PrimitiveTypes)
787 HNOption.PrimitiveType.try_emplace(PT.first, PT.second);
788
789 // clang-format off
790 static constexpr std::pair<StringRef, StringRef> UserDefinedTypes[] = {
791 // Windows data types
792 {"BOOL", "b" },
793 {"BOOLEAN", "b" },
794 {"BYTE", "by" },
795 {"CHAR", "c" },
796 {"UCHAR", "uc" },
797 {"SHORT", "s" },
798 {"USHORT", "us" },
799 {"WORD", "w" },
800 {"DWORD", "dw" },
801 {"DWORD32", "dw32"},
802 {"DWORD64", "dw64"},
803 {"LONG", "l" },
804 {"ULONG", "ul" },
805 {"ULONG32", "ul32"},
806 {"ULONG64", "ul64"},
807 {"ULONGLONG", "ull" },
808 {"HANDLE", "h" },
809 {"INT", "i" },
810 {"INT8", "i8" },
811 {"INT16", "i16" },
812 {"INT32", "i32" },
813 {"INT64", "i64" },
814 {"UINT", "ui" },
815 {"UINT8", "u8" },
816 {"UINT16", "u16" },
817 {"UINT32", "u32" },
818 {"UINT64", "u64" },
819 {"PVOID", "p" } };
820 // clang-format on
821 for (const auto &UDT : UserDefinedTypes)
822 HNOption.UserDefinedType.try_emplace(UDT.first, UDT.second);
823}
824
827 SmallString<64> StyleString;
828 const ArrayRef<std::optional<NamingStyle>> Styles =
829 MainFileStyle->getStyles();
830 for (size_t I = 0; I < SK_Count; ++I) {
831 const auto &StyleOpt = Styles[I];
832 if (!StyleOpt)
833 continue;
834 const NamingStyle &Style = *StyleOpt;
835 const size_t StyleSize = StyleNames[I].size();
836 StyleString.assign({StyleNames[I], "HungarianPrefix"});
837
838 Options.store(Opts, StyleString, Style.HPType);
839
840 memcpy(&StyleString[StyleSize], "IgnoredRegexp", 13);
841 StyleString.truncate(StyleSize + 13);
842 Options.store(Opts, StyleString, Style.IgnoredRegexpStr);
843 memcpy(&StyleString[StyleSize], "Prefix", 6);
844 StyleString.truncate(StyleSize + 6);
845 Options.store(Opts, StyleString, Style.Prefix);
846 // Fast replacement of [Pre]fix -> [Suf]fix.
847 memcpy(&StyleString[StyleSize], "Suf", 3);
848 Options.store(Opts, StyleString, Style.Suffix);
849 if (Style.Case) {
850 memcpy(&StyleString[StyleSize], "Case", 4);
851 StyleString.pop_back_n(2);
852 Options.store(Opts, StyleString, *Style.Case);
853 }
854 }
855 Options.store(Opts, "GetConfigPerFile", GetConfigPerFile);
856 Options.store(Opts, "IgnoreFailedSplit", IgnoreFailedSplit);
857 Options.store(Opts, "IgnoreMainLikeFunctions",
858 MainFileStyle->isIgnoringMainLikeFunction());
859 Options.store(Opts, "CheckAnonFieldInParent",
860 MainFileStyle->isCheckingAnonFieldInParentScope());
861}
862
864 StringRef Type, StringRef Name,
867 const NamedDecl *Decl) const {
868 static const llvm::Regex Matchers[] = {
869 llvm::Regex("^.*$"),
870 llvm::Regex("^[a-z][a-z0-9_]*$"),
871 llvm::Regex("^[a-z][a-zA-Z0-9]*$"),
872 llvm::Regex("^[A-Z][A-Z0-9_]*$"),
873 llvm::Regex("^[A-Z][a-zA-Z0-9]*$"),
874 llvm::Regex("^[A-Z]+([a-z0-9]*_[A-Z0-9]+)*[a-z0-9]*$"),
875 llvm::Regex("^[a-z]+([a-z0-9]*_[A-Z0-9]+)*[a-z0-9]*$"),
876 llvm::Regex("^[A-Z]([a-z0-9_]*[a-z])*$"),
877 };
878
879 if (!Name.consume_front(Style.Prefix))
880 return false;
881 if (!Name.consume_back(Style.Suffix))
882 return false;
884 const std::string HNPrefix = HungarianNotation.getPrefix(Decl, HNOption);
885 if (!HNPrefix.empty()) {
886 if (!Name.consume_front(HNPrefix))
887 return false;
888 if (Style.HPType ==
890 !Name.consume_front("_"))
891 return false;
892 }
893 }
894
895 // Ensure the name doesn't have any extra underscores beyond those specified
896 // in the prefix and suffix.
897 if (Name.starts_with('_') || Name.ends_with('_'))
898 return false;
899
900 if (Style.Case && !Matchers[static_cast<size_t>(*Style.Case)].match(Name))
901 return false;
902
903 return true;
904}
905
907 StringRef Type, StringRef Name, const Decl *D,
911 static const llvm::Regex Splitter(
912 "([a-z0-9A-Z]*)(_+)|([A-Z]?[a-z0-9]+)([A-Z]|$)|([A-Z]+)([A-Z]|$)");
913
915 Name.split(Substrs, "_", -1, false);
916
919 for (auto Substr : Substrs) {
920 while (!Substr.empty()) {
921 Groups.clear();
922 if (!Splitter.match(Substr, &Groups))
923 break;
924
925 if (!Groups[2].empty()) {
926 Words.push_back(Groups[1]);
927 Substr = Substr.substr(Groups[0].size());
928 } else if (!Groups[3].empty()) {
929 Words.push_back(Groups[3]);
930 Substr = Substr.substr(Groups[0].size() - Groups[4].size());
931 } else if (!Groups[5].empty()) {
932 Words.push_back(Groups[5]);
933 Substr = Substr.substr(Groups[0].size() - Groups[6].size());
934 }
935 }
936 }
937
938 if (Words.empty())
939 return Name.str();
940
943
944 SmallString<128> Fixup;
945 switch (Case) {
947 return Name.str();
948 break;
949
951 for (const auto &Word : Words) {
952 if (&Word != &Words.front())
953 Fixup += '_';
954 Fixup += Word.lower();
955 }
956 break;
957
959 for (const auto &Word : Words) {
960 if (&Word != &Words.front())
961 Fixup += '_';
962 Fixup += Word.upper();
963 }
964 break;
965
967 for (const auto &Word : Words) {
968 Fixup += toupper(Word.front());
969 Fixup += Word.substr(1).lower();
970 }
971 break;
972
974 for (const auto &Word : Words) {
975 if (&Word == &Words.front()) {
976 Fixup += Word.lower();
977 } else {
978 Fixup += toupper(Word.front());
979 Fixup += Word.substr(1).lower();
980 }
981 }
982 break;
983
985 for (const auto &Word : Words) {
986 if (&Word != &Words.front())
987 Fixup += '_';
988 Fixup += toupper(Word.front());
989 Fixup += Word.substr(1).lower();
990 }
991 break;
992
994 for (const auto &Word : Words) {
995 if (&Word != &Words.front()) {
996 Fixup += '_';
997 Fixup += toupper(Word.front());
998 } else {
999 Fixup += tolower(Word.front());
1000 }
1001 Fixup += Word.substr(1).lower();
1002 }
1003 break;
1004
1006 for (const auto &Word : Words) {
1007 if (&Word != &Words.front()) {
1008 Fixup += '_';
1009 Fixup += Word.lower();
1010 } else {
1011 Fixup += toupper(Word.front());
1012 Fixup += Word.substr(1).lower();
1013 }
1014 }
1015 break;
1016 }
1017
1018 return Fixup.str().str();
1019}
1020
1022 const ParmVarDecl &ParmDecl, bool IncludeMainLike) const {
1023 const auto *FDecl =
1024 dyn_cast_or_null<FunctionDecl>(ParmDecl.getParentFunctionOrMethod());
1025 if (!FDecl)
1026 return false;
1027 if (FDecl->isMain())
1028 return true;
1029 if (!IncludeMainLike)
1030 return false;
1031 if (FDecl->getAccess() != AS_public && FDecl->getAccess() != AS_none)
1032 return false;
1033 // If the function doesn't have a name that's an identifier, can occur if the
1034 // function is an operator overload, bail out early.
1035 if (!FDecl->getDeclName().isIdentifier())
1036 return false;
1037 enum MainType { None, Main, WMain };
1038 auto IsCharPtrPtr = [](QualType QType) -> MainType {
1039 if (QType.isNull())
1040 return None;
1041 if (QType = QType->getPointeeType(), QType.isNull())
1042 return None;
1043 if (QType = QType->getPointeeType(), QType.isNull())
1044 return None;
1045 if (QType->isCharType())
1046 return Main;
1047 if (QType->isWideCharType())
1048 return WMain;
1049 return None;
1050 };
1051 auto IsIntType = [](QualType QType) {
1052 if (QType.isNull())
1053 return false;
1054 if (const auto *Builtin =
1055 dyn_cast<BuiltinType>(QType->getUnqualifiedDesugaredType())) {
1056 return Builtin->getKind() == BuiltinType::Int;
1057 }
1058 return false;
1059 };
1060 if (!IsIntType(FDecl->getReturnType()))
1061 return false;
1062 if (FDecl->getNumParams() < 2 || FDecl->getNumParams() > 3)
1063 return false;
1064 if (!IsIntType(FDecl->parameters()[0]->getType()))
1065 return false;
1066 const MainType Type = IsCharPtrPtr(FDecl->parameters()[1]->getType());
1067 if (Type == None)
1068 return false;
1069 if (FDecl->getNumParams() == 3 &&
1070 IsCharPtrPtr(FDecl->parameters()[2]->getType()) != Type)
1071 return false;
1072
1073 if (Type == Main) {
1074 static const llvm::Regex Matcher(
1075 "(^[Mm]ain([_A-Z]|$))|([a-z0-9_]Main([_A-Z]|$))|(_main(_|$))");
1076 assert(Matcher.isValid() && "Invalid Matcher for main like functions.");
1077 return Matcher.match(FDecl->getName());
1078 }
1079 static const llvm::Regex Matcher(
1080 "(^((W[Mm])|(wm))ain([_A-Z]|$))|([a-z0-9_]W[Mm]"
1081 "ain([_A-Z]|$))|(_wmain(_|$))");
1082 assert(Matcher.isValid() && "Invalid Matcher for wmain like functions.");
1083 return Matcher.match(FDecl->getName());
1084}
1085
1087 StringRef Type, StringRef Name,
1090 const Decl *D) const {
1091 Name.consume_front(Style.Prefix);
1092 Name.consume_back(Style.Suffix);
1093 std::string Fixed = fixupWithCase(
1094 Type, Name, D, Style, HNOption,
1095 Style.Case.value_or(IdentifierNamingCheck::CaseType::CT_AnyCase));
1096
1097 std::string HungarianPrefix;
1099 if (HungarianPrefixType::HPT_Off != Style.HPType) {
1100 HungarianPrefix = HungarianNotation.getPrefix(D, HNOption);
1101 if (!HungarianPrefix.empty()) {
1102 if (Style.HPType == HungarianPrefixType::HPT_LowerCase)
1103 HungarianPrefix += '_';
1104
1105 if (Style.HPType == HungarianPrefixType::HPT_CamelCase)
1106 Fixed[0] = toupper(Fixed[0]);
1107 }
1108 }
1109 StringRef Mid = StringRef(Fixed).trim("_");
1110 if (Mid.empty())
1111 Mid = "_";
1112
1113 return (Style.Prefix + HungarianPrefix + Mid + Style.Suffix).str();
1114}
1115
1117 const NamedDecl *D,
1118 ArrayRef<std::optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
1119 bool IgnoreMainLikeFunctions, bool CheckAnonFieldInParentScope) const {
1120 assert(D && D->getIdentifier() && !D->getName().empty() && !D->isImplicit() &&
1121 "Decl must be an explicit identifier with a name.");
1122
1123 if (isa<ObjCIvarDecl>(D) && NamingStyles[SK_ObjcIvar])
1124 return SK_ObjcIvar;
1125
1126 if (isa<TypedefDecl>(D) && NamingStyles[SK_Typedef])
1127 return SK_Typedef;
1128
1129 if (isa<TypeAliasDecl>(D) && NamingStyles[SK_TypeAlias])
1130 return SK_TypeAlias;
1131
1132 if (isa<NamespaceAliasDecl>(D) && NamingStyles[SK_Namespace])
1133 return SK_Namespace;
1134
1135 if (const auto *Decl = dyn_cast<NamespaceDecl>(D)) {
1136 if (Decl->isAnonymousNamespace())
1137 return SK_Invalid;
1138
1139 if (Decl->isInline() && NamingStyles[SK_InlineNamespace])
1140 return SK_InlineNamespace;
1141
1142 if (NamingStyles[SK_Namespace])
1143 return SK_Namespace;
1144 }
1145
1146 if (isa<EnumDecl>(D) && NamingStyles[SK_Enum])
1147 return SK_Enum;
1148
1149 if (const auto *EnumConst = dyn_cast<EnumConstantDecl>(D)) {
1150 if (cast<EnumDecl>(EnumConst->getDeclContext())->isScoped() &&
1151 NamingStyles[SK_ScopedEnumConstant])
1152 return SK_ScopedEnumConstant;
1153
1154 if (NamingStyles[SK_EnumConstant])
1155 return SK_EnumConstant;
1156
1157 if (NamingStyles[SK_Constant])
1158 return SK_Constant;
1159
1160 return undefinedStyle(NamingStyles);
1161 }
1162
1163 if (const auto *Decl = dyn_cast<RecordDecl>(D)) {
1164 if (Decl->isAnonymousStructOrUnion())
1165 return SK_Invalid;
1166
1167 if (const auto *Definition = Decl->getDefinition()) {
1168 if (const auto *CxxRecordDecl = dyn_cast<CXXRecordDecl>(Definition)) {
1169 if (CxxRecordDecl->isAbstract() && NamingStyles[SK_AbstractClass])
1170 return SK_AbstractClass;
1171 }
1172
1173 if (Definition->isStruct() && NamingStyles[SK_Struct])
1174 return SK_Struct;
1175
1176 if (Definition->isStruct() && NamingStyles[SK_Class])
1177 return SK_Class;
1178
1179 if (Definition->isClass() && NamingStyles[SK_Class])
1180 return SK_Class;
1181
1182 if (Definition->isClass() && NamingStyles[SK_Struct])
1183 return SK_Struct;
1184
1185 if (Definition->isUnion() && NamingStyles[SK_Union])
1186 return SK_Union;
1187
1188 if (Definition->isEnum() && NamingStyles[SK_Enum])
1189 return SK_Enum;
1190 }
1191
1192 return undefinedStyle(NamingStyles);
1193 }
1194
1195 if (const auto *Decl = dyn_cast<FieldDecl>(D)) {
1196 if (CheckAnonFieldInParentScope) {
1197 const RecordDecl *Record = Decl->getParent();
1198 if (Record->isAnonymousStructOrUnion())
1199 return findStyleKindForAnonField(Decl, NamingStyles);
1200 }
1201
1202 return findStyleKindForField(Decl, Decl->getType(), NamingStyles);
1203 }
1204
1205 if (const auto *Decl = dyn_cast<ParmVarDecl>(D)) {
1206 if (isParamInMainLikeFunction(*Decl, IgnoreMainLikeFunctions))
1207 return SK_Invalid;
1208 const QualType Type = Decl->getType();
1209
1210 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprVariable])
1211 return SK_ConstexprVariable;
1212
1213 if (!Type.isNull() && Type.isConstQualified()) {
1214 if (Type.getTypePtr()->isAnyPointerType() &&
1215 NamingStyles[SK_ConstantPointerParameter])
1216 return SK_ConstantPointerParameter;
1217
1218 if (NamingStyles[SK_ConstantParameter])
1219 return SK_ConstantParameter;
1220
1221 if (NamingStyles[SK_Constant])
1222 return SK_Constant;
1223 }
1224
1225 if (Decl->isParameterPack() && NamingStyles[SK_ParameterPack])
1226 return SK_ParameterPack;
1227
1228 if (!Type.isNull() && Type.getTypePtr()->isAnyPointerType() &&
1229 NamingStyles[SK_PointerParameter])
1230 return SK_PointerParameter;
1231
1232 if (NamingStyles[SK_Parameter])
1233 return SK_Parameter;
1234
1235 return undefinedStyle(NamingStyles);
1236 }
1237
1238 if (const auto *Decl = dyn_cast<VarDecl>(D))
1239 return findStyleKindForVar(Decl, Decl->getType(), NamingStyles);
1240
1241 // C++17 structured bindings: treat each binding as if it were a variable
1242 // with the same storage and qualifiers as the parent DecompositionDecl.
1243 if (const auto *BD = dyn_cast<BindingDecl>(D)) {
1244 if (const auto *Decomp = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()))
1245 if (!BD->getType().isNull())
1246 return findStyleKindForVar(Decomp, BD->getType(), NamingStyles);
1247 return SK_Invalid;
1248 }
1249
1250 if (const auto *Decl = dyn_cast<CXXMethodDecl>(D)) {
1251 if (Decl->isMain() || !Decl->isUserProvided() ||
1252 Decl->size_overridden_methods() > 0 || Decl->hasAttr<OverrideAttr>())
1253 return SK_Invalid;
1254
1255 // If this method has the same name as any base method, this is likely
1256 // necessary even if it's not an override. e.g. CRTP.
1257 for (const CXXBaseSpecifier &Base : Decl->getParent()->bases())
1258 if (const auto *RD = Base.getType()->getAsCXXRecordDecl())
1259 if (RD->hasMemberName(Decl->getDeclName()))
1260 return SK_Invalid;
1261
1262 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprMethod])
1263 return SK_ConstexprMethod;
1264
1265 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprFunction])
1266 return SK_ConstexprFunction;
1267
1268 if (Decl->isStatic() && NamingStyles[SK_ClassMethod])
1269 return SK_ClassMethod;
1270
1271 if (Decl->isVirtual() && NamingStyles[SK_VirtualMethod])
1272 return SK_VirtualMethod;
1273
1274 if (Decl->getAccess() == AS_private && NamingStyles[SK_PrivateMethod])
1275 return SK_PrivateMethod;
1276
1277 if (Decl->getAccess() == AS_protected && NamingStyles[SK_ProtectedMethod])
1278 return SK_ProtectedMethod;
1279
1280 if (Decl->getAccess() == AS_public && NamingStyles[SK_PublicMethod])
1281 return SK_PublicMethod;
1282
1283 if (NamingStyles[SK_Method])
1284 return SK_Method;
1285
1286 if (NamingStyles[SK_Function])
1287 return SK_Function;
1288
1289 return undefinedStyle(NamingStyles);
1290 }
1291
1292 if (const auto *Decl = dyn_cast<FunctionDecl>(D)) {
1293 if (Decl->isMain())
1294 return SK_Invalid;
1295
1296 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprFunction])
1297 return SK_ConstexprFunction;
1298
1299 if (Decl->isGlobal() && NamingStyles[SK_GlobalFunction])
1300 return SK_GlobalFunction;
1301
1302 if (NamingStyles[SK_Function])
1303 return SK_Function;
1304 }
1305
1306 // Ignore template wrapper decls. Their underlying decls are checked with the
1307 // right naming kind, checking the wrappers too can fall back to DefaultCase
1308 // and emit diagnostic for the same identifier.
1309 if (isa<FunctionTemplateDecl, ClassTemplateDecl, VarTemplateDecl,
1310 TypeAliasTemplateDecl>(D))
1311 return SK_Invalid;
1312
1313 if (isa<TemplateTypeParmDecl>(D)) {
1314 if (NamingStyles[SK_TypeTemplateParameter])
1315 return SK_TypeTemplateParameter;
1316
1317 if (NamingStyles[SK_TemplateParameter])
1318 return SK_TemplateParameter;
1319
1320 return undefinedStyle(NamingStyles);
1321 }
1322
1323 if (isa<NonTypeTemplateParmDecl>(D)) {
1324 if (NamingStyles[SK_ValueTemplateParameter])
1325 return SK_ValueTemplateParameter;
1326
1327 if (NamingStyles[SK_TemplateParameter])
1328 return SK_TemplateParameter;
1329
1330 return undefinedStyle(NamingStyles);
1331 }
1332
1333 if (isa<TemplateTemplateParmDecl>(D)) {
1334 if (NamingStyles[SK_TemplateTemplateParameter])
1335 return SK_TemplateTemplateParameter;
1336
1337 if (NamingStyles[SK_TemplateParameter])
1338 return SK_TemplateParameter;
1339
1340 return undefinedStyle(NamingStyles);
1341 }
1342
1343 if (isa<ConceptDecl>(D) && NamingStyles[SK_Concept])
1344 return SK_Concept;
1345
1346 return undefinedStyle(NamingStyles);
1347}
1348
1349std::optional<RenamerClangTidyCheck::FailureInfo>
1351 StringRef Type, StringRef Name, const NamedDecl *ND,
1352 SourceLocation Location,
1353 ArrayRef<std::optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
1355 StyleKind SK, const SourceManager &SM, bool IgnoreFailedSplit) const {
1356 if (SK == SK_Invalid)
1357 return std::nullopt;
1358
1359 const auto &StyleOpt = NamingStyles[SK];
1360 if (!StyleOpt)
1361 return std::nullopt;
1362
1363 const IdentifierNamingCheck::NamingStyle &Style = *StyleOpt;
1364 if (Style.IgnoredRegexp.isValid() && Style.IgnoredRegexp.match(Name))
1365 return std::nullopt;
1366
1367 if (matchesStyle(Type, Name, Style, HNOption, ND))
1368 return std::nullopt;
1369
1370 std::string KindName =
1371 SK == SK_Default
1372 ? "identifier"
1373 : fixupWithCase(Type, StyleNames[SK], ND, Style, HNOption,
1375 llvm::replace(KindName, '_', ' ');
1376
1377 std::string Fixup = fixupWithStyle(Type, Name, Style, HNOption, ND);
1378 if (StringRef(Fixup) == Name) {
1379 if (!IgnoreFailedSplit) {
1380 LLVM_DEBUG(Location.print(llvm::dbgs(), SM);
1381 llvm::dbgs() << ": unable to split words for " << KindName
1382 << " '" << Name << "'\n");
1383 }
1384 return std::nullopt;
1385 }
1386 return RenamerClangTidyCheck::FailureInfo{std::move(KindName),
1387 std::move(Fixup)};
1388}
1389
1390std::optional<RenamerClangTidyCheck::FailureInfo>
1391IdentifierNamingCheck::getDeclFailureInfo(const NamedDecl *Decl,
1392 const SourceManager &SM) const {
1393 // Implicit identifiers cannot be renamed.
1394 if (Decl->isImplicit())
1395 return std::nullopt;
1396
1397 const SourceLocation Loc = Decl->getLocation();
1398 const FileStyle &FileStyle = getStyleForFile(SM.getFilename(Loc));
1399 if (!FileStyle.isActive())
1400 return std::nullopt;
1401
1402 return getFailureInfo(
1403 HungarianNotation.getDeclTypeName(Decl), Decl->getName(), Decl, Loc,
1404 FileStyle.getStyles(), FileStyle.getHNOption(),
1405 findStyleKind(Decl, FileStyle.getStyles(),
1406 FileStyle.isIgnoringMainLikeFunction(),
1407 FileStyle.isCheckingAnonFieldInParentScope()),
1408 SM, IgnoreFailedSplit);
1409}
1410
1411std::optional<RenamerClangTidyCheck::FailureInfo>
1412IdentifierNamingCheck::getMacroFailureInfo(const Token &MacroNameTok,
1413 const SourceManager &SM) const {
1414 const SourceLocation Loc = MacroNameTok.getLocation();
1415 const FileStyle &Style = getStyleForFile(SM.getFilename(Loc));
1416 if (!Style.isActive())
1417 return std::nullopt;
1418
1419 const auto &Styles = Style.getStyles();
1420 const StyleKind UsedKind = !Styles[SK_MacroDefinition] && Styles[SK_Default]
1421 ? SK_Default
1422 : SK_MacroDefinition;
1423
1424 return getFailureInfo("", MacroNameTok.getIdentifierInfo()->getName(),
1425 nullptr, Loc, Style.getStyles(), Style.getHNOption(),
1426 UsedKind, SM, IgnoreFailedSplit);
1427}
1428
1429RenamerClangTidyCheck::DiagInfo
1430IdentifierNamingCheck::getDiagInfo(const NamingCheckId &ID,
1431 const NamingCheckFailure &Failure) const {
1432 return DiagInfo{"invalid case style for %0 '%1'",
1433 [&](DiagnosticBuilder &Diag) {
1434 Diag << Failure.Info.KindName << ID.second;
1435 }};
1436}
1437
1438StringRef IdentifierNamingCheck::getRealFileName(StringRef FileName) const {
1439 auto Iter = RealFileNameCache.try_emplace(FileName);
1440 SmallString<256U> &RealFileName = Iter.first->getValue();
1441 if (!Iter.second)
1442 return RealFileName;
1443 llvm::sys::fs::real_path(FileName, RealFileName);
1444 return RealFileName;
1445}
1446
1447const IdentifierNamingCheck::FileStyle &
1448IdentifierNamingCheck::getStyleForFile(StringRef FileName) const {
1449 if (!GetConfigPerFile)
1450 return *MainFileStyle;
1451
1452 const StringRef RealFileName = getRealFileName(FileName);
1453 const StringRef Parent = llvm::sys::path::parent_path(RealFileName);
1454 auto Iter = NamingStylesCache.find(Parent);
1455 if (Iter != NamingStylesCache.end())
1456 return Iter->getValue();
1457
1458 const StringRef CheckName = getID();
1459 ClangTidyOptions Options = Context->getOptionsForFile(RealFileName);
1460 if (Options.Checks && GlobList(*Options.Checks).contains(CheckName)) {
1461 auto It = NamingStylesCache.try_emplace(
1462 Parent,
1463 getFileStyleFromOptions({CheckName, Options.CheckOptions, Context}));
1464 assert(It.second);
1465 return It.first->getValue();
1466 }
1467 // Default construction gives an empty style.
1468 auto It = NamingStylesCache.try_emplace(Parent);
1469 assert(It.second);
1470 return It.first->getValue();
1471}
1472
1473StyleKind IdentifierNamingCheck::findStyleKindForAnonField(
1474 const FieldDecl *AnonField,
1475 ArrayRef<std::optional<NamingStyle>> NamingStyles) const {
1476 const IndirectFieldDecl *IFD =
1478 assert(IFD && "Found an anonymous record field without an IndirectFieldDecl");
1479
1480 const QualType Type = AnonField->getType();
1481
1482 if (const auto *F = dyn_cast<FieldDecl>(IFD->chain().front()))
1483 return findStyleKindForField(F, Type, NamingStyles);
1484
1485 if (const auto *V = IFD->getVarDecl())
1486 return findStyleKindForVar(V, Type, NamingStyles);
1487
1488 return undefinedStyle(NamingStyles);
1489}
1490
1491StyleKind IdentifierNamingCheck::findStyleKindForField(
1492 const FieldDecl *Field, QualType Type,
1493 ArrayRef<std::optional<NamingStyle>> NamingStyles) const {
1494 if (!Type.isNull() && Type.isConstQualified()) {
1495 if (NamingStyles[SK_ConstantMember])
1496 return SK_ConstantMember;
1497
1498 if (NamingStyles[SK_Constant])
1499 return SK_Constant;
1500 }
1501
1502 if (Field->getAccess() == AS_private && NamingStyles[SK_PrivateMember])
1503 return SK_PrivateMember;
1504
1505 if (Field->getAccess() == AS_protected && NamingStyles[SK_ProtectedMember])
1506 return SK_ProtectedMember;
1507
1508 if (Field->getAccess() == AS_public && NamingStyles[SK_PublicMember])
1509 return SK_PublicMember;
1510
1511 if (NamingStyles[SK_Member])
1512 return SK_Member;
1513
1514 return undefinedStyle(NamingStyles);
1515}
1516
1517StyleKind IdentifierNamingCheck::findStyleKindForVar(
1518 const VarDecl *Var, QualType Type,
1519 ArrayRef<std::optional<NamingStyle>> NamingStyles) const {
1520 if (Var->isConstexpr()) {
1521 if (Var->isStaticDataMember() && NamingStyles[SK_ClassConstexpr])
1522 return SK_ClassConstexpr;
1523
1524 if (Var->isFileVarDecl() && NamingStyles[SK_GlobalConstexprVariable])
1525 return SK_GlobalConstexprVariable;
1526
1527 if (Var->isStaticLocal() && NamingStyles[SK_StaticConstexprVariable])
1528 return SK_StaticConstexprVariable;
1529
1530 if (Var->isLocalVarDecl() && NamingStyles[SK_LocalConstexprVariable])
1531 return SK_LocalConstexprVariable;
1532
1533 if (NamingStyles[SK_ConstexprVariable])
1534 return SK_ConstexprVariable;
1535 }
1536
1537 if (!Type.isNull() && Type.isConstQualified()) {
1538 if (Var->isStaticDataMember() && NamingStyles[SK_ClassConstant])
1539 return SK_ClassConstant;
1540
1541 if (Var->isFileVarDecl() && Type.getTypePtr()->isAnyPointerType() &&
1542 NamingStyles[SK_GlobalConstantPointer])
1543 return SK_GlobalConstantPointer;
1544
1545 if (Var->isFileVarDecl() && NamingStyles[SK_GlobalConstant])
1546 return SK_GlobalConstant;
1547
1548 if (Var->isStaticLocal() && NamingStyles[SK_StaticConstant])
1549 return SK_StaticConstant;
1550
1551 if (Var->isLocalVarDecl() && Type.getTypePtr()->isAnyPointerType() &&
1552 NamingStyles[SK_LocalConstantPointer])
1553 return SK_LocalConstantPointer;
1554
1555 if (Var->isLocalVarDecl() && NamingStyles[SK_LocalConstant])
1556 return SK_LocalConstant;
1557
1558 if (Var->isFunctionOrMethodVarDecl() && NamingStyles[SK_LocalConstant])
1559 return SK_LocalConstant;
1560
1561 if (NamingStyles[SK_Constant])
1562 return SK_Constant;
1563 }
1564
1565 if (Var->isStaticDataMember() && NamingStyles[SK_ClassMember])
1566 return SK_ClassMember;
1567
1568 if (Var->isFileVarDecl() && Type.getTypePtr()->isAnyPointerType() &&
1569 NamingStyles[SK_GlobalPointer])
1570 return SK_GlobalPointer;
1571
1572 if (Var->isFileVarDecl() && NamingStyles[SK_GlobalVariable])
1573 return SK_GlobalVariable;
1574
1575 if (Var->isStaticLocal() && NamingStyles[SK_StaticVariable])
1576 return SK_StaticVariable;
1577
1578 if (Var->isLocalVarDecl() && Type.getTypePtr()->isAnyPointerType() &&
1579 NamingStyles[SK_LocalPointer])
1580 return SK_LocalPointer;
1581
1582 if (Var->isLocalVarDecl() && NamingStyles[SK_LocalVariable])
1583 return SK_LocalVariable;
1584
1585 if (Var->isFunctionOrMethodVarDecl() && NamingStyles[SK_LocalVariable])
1586 return SK_LocalVariable;
1587
1588 if (NamingStyles[SK_Variable])
1589 return SK_Variable;
1590
1591 return undefinedStyle(NamingStyles);
1592}
1593
1594StyleKind IdentifierNamingCheck::undefinedStyle(
1595 ArrayRef<std::optional<NamingStyle>> NamingStyles) const {
1596 return NamingStyles[SK_Default] ? SK_Default : SK_Invalid;
1597}
1598
1599} // namespace readability
1600} // 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:1710
static StringRef const HungarianNotationPrimitiveTypes[]
static StringRef const HungarianNotationUserDefinedTypes[]
static StringRef const StyleNames[]
const IndirectFieldDecl * findOutermostIndirectFieldDeclForField(const FieldDecl *FD)
Definition ASTUtils.cpp:115
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
StringRef getClassPrefix(const CXXRecordDecl *CRD, const IdentifierNamingCheck::HungarianNotationOption &HNOption) 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 getPrefix(const Decl *D, const IdentifierNamingCheck::HungarianNotationOption &HNOption) const
std::string getDataTypePrefix(StringRef TypeName, const NamedDecl *ND, const IdentifierNamingCheck::HungarianNotationOption &HNOption) const