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