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