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