clang-tools 23.0.0git
IdentifierNamingCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10
11#include "../GlobList.h"
12#include "../utils/ASTUtils.h"
13#include "clang/AST/CXXInheritance.h"
14#include "clang/Lex/PPCallbacks.h"
15#include "clang/Lex/Preprocessor.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/StringRef.h"
18#include "llvm/Support/Debug.h"
19#include "llvm/Support/Path.h"
20#include "llvm/Support/Regex.h"
21#include "llvm/Support/YAMLParser.h"
22#include <optional>
23
24#define DEBUG_TYPE "clang-tidy"
25
26// FixItHint
27
28using namespace clang::ast_matchers;
29
30namespace clang::tidy {
31
32llvm::ArrayRef<
33 std::pair<readability::IdentifierNamingCheck::CaseType, StringRef>>
34OptionEnumMapping<
52
53template <>
55 readability::IdentifierNamingCheck::HungarianPrefixType> {
58 static llvm::ArrayRef<std::pair<HungarianPrefixType, StringRef>>
60 static constexpr std::pair<HungarianPrefixType, StringRef> Mapping[] = {
61 {HungarianPrefixType::HPT_Off, "Off"},
62 {HungarianPrefixType::HPT_On, "On"},
63 {HungarianPrefixType::HPT_LowerCase, "LowerCase"},
64 {HungarianPrefixType::HPT_CamelCase, "CamelCase"}};
65 return {Mapping};
66 }
67};
68
69namespace readability {
70
71// clang-format off
72#define NAMING_KEYS(m) \
73 m(Default) \
74 m(Namespace) \
75 m(InlineNamespace) \
76 m(EnumConstant) \
77 m(ScopedEnumConstant) \
78 m(ConstexprVariable) \
79 m(ConstantMember) \
80 m(PrivateMember) \
81 m(ProtectedMember) \
82 m(PublicMember) \
83 m(Member) \
84 m(ClassConstant) \
85 m(ClassMember) \
86 m(ClassConstexpr) \
87 m(GlobalConstexprVariable) \
88 m(GlobalConstant) \
89 m(GlobalConstantPointer) \
90 m(GlobalPointer) \
91 m(GlobalVariable) \
92 m(LocalConstexprVariable) \
93 m(LocalConstant) \
94 m(LocalConstantPointer) \
95 m(LocalPointer) \
96 m(LocalVariable) \
97 m(StaticConstexprVariable) \
98 m(StaticConstant) \
99 m(StaticVariable) \
100 m(Constant) \
101 m(Variable) \
102 m(ConstantParameter) \
103 m(ParameterPack) \
104 m(Parameter) \
105 m(PointerParameter) \
106 m(ConstantPointerParameter) \
107 m(AbstractClass) \
108 m(Struct) \
109 m(Class) \
110 m(Union) \
111 m(Enum) \
112 m(GlobalFunction) \
113 m(ConstexprFunction) \
114 m(Function) \
115 m(ConstexprMethod) \
116 m(VirtualMethod) \
117 m(ClassMethod) \
118 m(PrivateMethod) \
119 m(ProtectedMethod) \
120 m(PublicMethod) \
121 m(Method) \
122 m(Typedef) \
123 m(TypeTemplateParameter) \
124 m(ValueTemplateParameter) \
125 m(TemplateTemplateParameter) \
126 m(TemplateParameter) \
127 m(TypeAlias) \
128 m(MacroDefinition) \
129 m(ObjcIvar) \
130 m(Concept) \
131
132enum StyleKind : int {
133#define ENUMERATE(v) SK_ ## v,
135#undef ENUMERATE
138};
139
140static StringRef const StyleNames[] = {
141#define STRINGIZE(v) #v,
143#undef STRINGIZE
144};
145
146#define HUNGARIAN_NOTATION_PRIMITIVE_TYPES(m) \
147 m(int8_t) \
148 m(int16_t) \
149 m(int32_t) \
150 m(int64_t) \
151 m(uint8_t) \
152 m(uint16_t) \
153 m(uint32_t) \
154 m(uint64_t) \
155 m(char8_t) \
156 m(char16_t) \
157 m(char32_t) \
158 m(float) \
159 m(double) \
160 m(char) \
161 m(bool) \
162 m(_Bool) \
163 m(int) \
164 m(size_t) \
165 m(wchar_t) \
166 m(short-int) \
167 m(short) \
168 m(signed-int) \
169 m(signed-short) \
170 m(signed-short-int) \
171 m(signed-long-long-int) \
172 m(signed-long-long) \
173 m(signed-long-int) \
174 m(signed-long) \
175 m(signed) \
176 m(unsigned-long-long-int) \
177 m(unsigned-long-long) \
178 m(unsigned-long-int) \
179 m(unsigned-long) \
180 m(unsigned-short-int) \
181 m(unsigned-short) \
182 m(unsigned-int) \
183 m(unsigned-char) \
184 m(unsigned) \
185 m(long-long-int) \
186 m(long-double) \
187 m(long-long) \
188 m(long-int) \
189 m(long) \
190 m(ptrdiff_t) \
191 m(void) \
192
193static StringRef const HungarianNotationPrimitiveTypes[] = {
194#define STRINGIZE(v) #v,
196#undef STRINGIZE
197};
198
199#define HUNGARIAN_NOTATION_USER_DEFINED_TYPES(m) \
200 m(BOOL) \
201 m(BOOLEAN) \
202 m(BYTE) \
203 m(CHAR) \
204 m(UCHAR) \
205 m(SHORT) \
206 m(USHORT) \
207 m(WORD) \
208 m(DWORD) \
209 m(DWORD32) \
210 m(DWORD64) \
211 m(LONG) \
212 m(ULONG) \
213 m(ULONG32) \
214 m(ULONG64) \
215 m(ULONGLONG) \
216 m(HANDLE) \
217 m(INT) \
218 m(INT8) \
219 m(INT16) \
220 m(INT32) \
221 m(INT64) \
222 m(UINT) \
223 m(UINT8) \
224 m(UINT16) \
225 m(UINT32) \
226 m(UINT64) \
227 m(PVOID) \
228
229static StringRef const HungarianNotationUserDefinedTypes[] = {
230#define STRINGIZE(v) #v,
232#undef STRINGIZE
233};
234
235
236#undef NAMING_KEYS
237// clang-format on
238
240 std::optional<IdentifierNamingCheck::CaseType> Case, StringRef Prefix,
241 StringRef Suffix, StringRef IgnoredRegexpStr, HungarianPrefixType HPType)
242 : Case(Case), Prefix(Prefix), Suffix(Suffix),
243 IgnoredRegexpStr(IgnoredRegexpStr), HPType(HPType) {
244 if (!IgnoredRegexpStr.empty()) {
245 IgnoredRegexp =
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()).value_or(false);
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 const auto &StyleOpt = Styles[I];
833 if (!StyleOpt)
834 continue;
835 const NamingStyle &Style = *StyleOpt;
836 const size_t StyleSize = StyleNames[I].size();
837 StyleString.assign({StyleNames[I], "HungarianPrefix"});
838
839 Options.store(Opts, StyleString, Style.HPType);
840
841 memcpy(&StyleString[StyleSize], "IgnoredRegexp", 13);
842 StyleString.truncate(StyleSize + 13);
843 Options.store(Opts, StyleString, Style.IgnoredRegexpStr);
844 memcpy(&StyleString[StyleSize], "Prefix", 6);
845 StyleString.truncate(StyleSize + 6);
846 Options.store(Opts, StyleString, Style.Prefix);
847 // Fast replacement of [Pre]fix -> [Suf]fix.
848 memcpy(&StyleString[StyleSize], "Suf", 3);
849 Options.store(Opts, StyleString, Style.Suffix);
850 if (Style.Case) {
851 memcpy(&StyleString[StyleSize], "Case", 4);
852 StyleString.pop_back_n(2);
853 Options.store(Opts, StyleString, *Style.Case);
854 }
855 }
856 Options.store(Opts, "GetConfigPerFile", GetConfigPerFile);
857 Options.store(Opts, "IgnoreFailedSplit", IgnoreFailedSplit);
858 Options.store(Opts, "IgnoreMainLikeFunctions",
859 MainFileStyle->isIgnoringMainLikeFunction());
860 Options.store(Opts, "CheckAnonFieldInParent",
861 MainFileStyle->isCheckingAnonFieldInParentScope());
862}
863
865 StringRef Type, StringRef Name,
868 const NamedDecl *Decl) const {
869 static const llvm::Regex Matchers[] = {
870 llvm::Regex("^.*$"),
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_]*$"),
874 llvm::Regex("^[A-Z][a-zA-Z0-9]*$"),
875 llvm::Regex("^[A-Z]+([a-z0-9]*_[A-Z0-9]+)*[a-z0-9]*$"),
876 llvm::Regex("^[a-z]+([a-z0-9]*_[A-Z0-9]+)*[a-z0-9]*$"),
877 llvm::Regex("^[A-Z]([a-z0-9_]*[a-z])*$"),
878 };
879
880 if (!Name.consume_front(Style.Prefix))
881 return false;
882 if (!Name.consume_back(Style.Suffix))
883 return false;
885 const std::string HNPrefix = HungarianNotation.getPrefix(Decl, HNOption);
886 if (!HNPrefix.empty()) {
887 if (!Name.consume_front(HNPrefix))
888 return false;
889 if (Style.HPType ==
891 !Name.consume_front("_"))
892 return false;
893 }
894 }
895
896 // Ensure the name doesn't have any extra underscores beyond those specified
897 // in the prefix and suffix.
898 if (Name.starts_with("_") || Name.ends_with("_"))
899 return false;
900
901 if (Style.Case && !Matchers[static_cast<size_t>(*Style.Case)].match(Name))
902 return false;
903
904 return true;
905}
906
908 StringRef Type, StringRef Name, const Decl *D,
912 static const llvm::Regex Splitter(
913 "([a-z0-9A-Z]*)(_+)|([A-Z]?[a-z0-9]+)([A-Z]|$)|([A-Z]+)([A-Z]|$)");
914
915 SmallVector<StringRef, 8> Substrs;
916 Name.split(Substrs, "_", -1, false);
917
918 SmallVector<StringRef, 8> Words;
919 SmallVector<StringRef, 8> Groups;
920 for (auto Substr : Substrs) {
921 while (!Substr.empty()) {
922 Groups.clear();
923 if (!Splitter.match(Substr, &Groups))
924 break;
925
926 if (!Groups[2].empty()) {
927 Words.push_back(Groups[1]);
928 Substr = Substr.substr(Groups[0].size());
929 } else if (!Groups[3].empty()) {
930 Words.push_back(Groups[3]);
931 Substr = Substr.substr(Groups[0].size() - Groups[4].size());
932 } else if (!Groups[5].empty()) {
933 Words.push_back(Groups[5]);
934 Substr = Substr.substr(Groups[0].size() - Groups[6].size());
935 }
936 }
937 }
938
939 if (Words.empty())
940 return Name.str();
941
944
945 SmallString<128> Fixup;
946 switch (Case) {
948 return Name.str();
949 break;
950
952 for (const auto &Word : Words) {
953 if (&Word != &Words.front())
954 Fixup += "_";
955 Fixup += Word.lower();
956 }
957 break;
958
960 for (const auto &Word : Words) {
961 if (&Word != &Words.front())
962 Fixup += "_";
963 Fixup += Word.upper();
964 }
965 break;
966
968 for (const auto &Word : Words) {
969 Fixup += toupper(Word.front());
970 Fixup += Word.substr(1).lower();
971 }
972 break;
973
975 for (const auto &Word : Words) {
976 if (&Word == &Words.front()) {
977 Fixup += Word.lower();
978 } else {
979 Fixup += toupper(Word.front());
980 Fixup += Word.substr(1).lower();
981 }
982 }
983 break;
984
986 for (const auto &Word : Words) {
987 if (&Word != &Words.front())
988 Fixup += "_";
989 Fixup += toupper(Word.front());
990 Fixup += Word.substr(1).lower();
991 }
992 break;
993
995 for (const auto &Word : Words) {
996 if (&Word != &Words.front()) {
997 Fixup += "_";
998 Fixup += toupper(Word.front());
999 } else {
1000 Fixup += tolower(Word.front());
1001 }
1002 Fixup += Word.substr(1).lower();
1003 }
1004 break;
1005
1007 for (const auto &Word : Words) {
1008 if (&Word != &Words.front()) {
1009 Fixup += "_";
1010 Fixup += Word.lower();
1011 } else {
1012 Fixup += toupper(Word.front());
1013 Fixup += Word.substr(1).lower();
1014 }
1015 }
1016 break;
1017 }
1018
1019 return Fixup.str().str();
1020}
1021
1023 const ParmVarDecl &ParmDecl, bool IncludeMainLike) const {
1024 const auto *FDecl =
1025 dyn_cast_or_null<FunctionDecl>(ParmDecl.getParentFunctionOrMethod());
1026 if (!FDecl)
1027 return false;
1028 if (FDecl->isMain())
1029 return true;
1030 if (!IncludeMainLike)
1031 return false;
1032 if (FDecl->getAccess() != AS_public && FDecl->getAccess() != AS_none)
1033 return false;
1034 // If the function doesn't have a name that's an identifier, can occur if the
1035 // function is an operator overload, bail out early.
1036 if (!FDecl->getDeclName().isIdentifier())
1037 return false;
1038 enum MainType { None, Main, WMain };
1039 auto IsCharPtrPtr = [](QualType QType) -> MainType {
1040 if (QType.isNull())
1041 return None;
1042 if (QType = QType->getPointeeType(), QType.isNull())
1043 return None;
1044 if (QType = QType->getPointeeType(), QType.isNull())
1045 return None;
1046 if (QType->isCharType())
1047 return Main;
1048 if (QType->isWideCharType())
1049 return WMain;
1050 return None;
1051 };
1052 auto IsIntType = [](QualType QType) {
1053 if (QType.isNull())
1054 return false;
1055 if (const auto *Builtin =
1056 dyn_cast<BuiltinType>(QType->getUnqualifiedDesugaredType())) {
1057 return Builtin->getKind() == BuiltinType::Int;
1058 }
1059 return false;
1060 };
1061 if (!IsIntType(FDecl->getReturnType()))
1062 return false;
1063 if (FDecl->getNumParams() < 2 || FDecl->getNumParams() > 3)
1064 return false;
1065 if (!IsIntType(FDecl->parameters()[0]->getType()))
1066 return false;
1067 const MainType Type = IsCharPtrPtr(FDecl->parameters()[1]->getType());
1068 if (Type == None)
1069 return false;
1070 if (FDecl->getNumParams() == 3 &&
1071 IsCharPtrPtr(FDecl->parameters()[2]->getType()) != Type)
1072 return false;
1073
1074 if (Type == Main) {
1075 static const llvm::Regex Matcher(
1076 "(^[Mm]ain([_A-Z]|$))|([a-z0-9_]Main([_A-Z]|$))|(_main(_|$))");
1077 assert(Matcher.isValid() && "Invalid Matcher for main like functions.");
1078 return Matcher.match(FDecl->getName());
1079 }
1080 static const llvm::Regex Matcher(
1081 "(^((W[Mm])|(wm))ain([_A-Z]|$))|([a-z0-9_]W[Mm]"
1082 "ain([_A-Z]|$))|(_wmain(_|$))");
1083 assert(Matcher.isValid() && "Invalid Matcher for wmain like functions.");
1084 return Matcher.match(FDecl->getName());
1085}
1086
1088 StringRef Type, StringRef Name,
1091 const Decl *D) const {
1092 Name.consume_front(Style.Prefix);
1093 Name.consume_back(Style.Suffix);
1094 std::string Fixed = fixupWithCase(
1095 Type, Name, D, Style, HNOption,
1096 Style.Case.value_or(IdentifierNamingCheck::CaseType::CT_AnyCase));
1097
1098 std::string HungarianPrefix;
1100 if (HungarianPrefixType::HPT_Off != Style.HPType) {
1101 HungarianPrefix = HungarianNotation.getPrefix(D, HNOption);
1102 if (!HungarianPrefix.empty()) {
1103 if (Style.HPType == HungarianPrefixType::HPT_LowerCase)
1104 HungarianPrefix += "_";
1105
1106 if (Style.HPType == HungarianPrefixType::HPT_CamelCase)
1107 Fixed[0] = toupper(Fixed[0]);
1108 }
1109 }
1110 StringRef Mid = StringRef(Fixed).trim("_");
1111 if (Mid.empty())
1112 Mid = "_";
1113
1114 return (Style.Prefix + HungarianPrefix + Mid + Style.Suffix).str();
1115}
1116
1118 const NamedDecl *D,
1119 ArrayRef<std::optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
1120 bool IgnoreMainLikeFunctions, bool CheckAnonFieldInParentScope) const {
1121 assert(D && D->getIdentifier() && !D->getName().empty() && !D->isImplicit() &&
1122 "Decl must be an explicit identifier with a name.");
1123
1124 if (isa<ObjCIvarDecl>(D) && NamingStyles[SK_ObjcIvar])
1125 return SK_ObjcIvar;
1126
1127 if (isa<TypedefDecl>(D) && NamingStyles[SK_Typedef])
1128 return SK_Typedef;
1129
1130 if (isa<TypeAliasDecl>(D) && NamingStyles[SK_TypeAlias])
1131 return SK_TypeAlias;
1132
1133 if (isa<NamespaceAliasDecl>(D) && NamingStyles[SK_Namespace])
1134 return SK_Namespace;
1135
1136 if (const auto *Decl = dyn_cast<NamespaceDecl>(D)) {
1137 if (Decl->isAnonymousNamespace())
1138 return SK_Invalid;
1139
1140 if (Decl->isInline() && NamingStyles[SK_InlineNamespace])
1141 return SK_InlineNamespace;
1142
1143 if (NamingStyles[SK_Namespace])
1144 return SK_Namespace;
1145 }
1146
1147 if (isa<EnumDecl>(D) && NamingStyles[SK_Enum])
1148 return SK_Enum;
1149
1150 if (const auto *EnumConst = dyn_cast<EnumConstantDecl>(D)) {
1151 if (cast<EnumDecl>(EnumConst->getDeclContext())->isScoped() &&
1152 NamingStyles[SK_ScopedEnumConstant])
1153 return SK_ScopedEnumConstant;
1154
1155 if (NamingStyles[SK_EnumConstant])
1156 return SK_EnumConstant;
1157
1158 if (NamingStyles[SK_Constant])
1159 return SK_Constant;
1160
1161 return undefinedStyle(NamingStyles);
1162 }
1163
1164 if (const auto *Decl = dyn_cast<RecordDecl>(D)) {
1165 if (Decl->isAnonymousStructOrUnion())
1166 return SK_Invalid;
1167
1168 if (const auto *Definition = Decl->getDefinition()) {
1169 if (const auto *CxxRecordDecl = dyn_cast<CXXRecordDecl>(Definition)) {
1170 if (CxxRecordDecl->isAbstract() && NamingStyles[SK_AbstractClass])
1171 return SK_AbstractClass;
1172 }
1173
1174 if (Definition->isStruct() && NamingStyles[SK_Struct])
1175 return SK_Struct;
1176
1177 if (Definition->isStruct() && NamingStyles[SK_Class])
1178 return SK_Class;
1179
1180 if (Definition->isClass() && NamingStyles[SK_Class])
1181 return SK_Class;
1182
1183 if (Definition->isClass() && NamingStyles[SK_Struct])
1184 return SK_Struct;
1185
1186 if (Definition->isUnion() && NamingStyles[SK_Union])
1187 return SK_Union;
1188
1189 if (Definition->isEnum() && NamingStyles[SK_Enum])
1190 return SK_Enum;
1191 }
1192
1193 return undefinedStyle(NamingStyles);
1194 }
1195
1196 if (const auto *Decl = dyn_cast<FieldDecl>(D)) {
1197 if (CheckAnonFieldInParentScope) {
1198 const RecordDecl *Record = Decl->getParent();
1199 if (Record->isAnonymousStructOrUnion())
1200 return findStyleKindForAnonField(Decl, NamingStyles);
1201 }
1202
1203 return findStyleKindForField(Decl, Decl->getType(), NamingStyles);
1204 }
1205
1206 if (const auto *Decl = dyn_cast<ParmVarDecl>(D)) {
1207 if (isParamInMainLikeFunction(*Decl, IgnoreMainLikeFunctions))
1208 return SK_Invalid;
1209 const QualType Type = Decl->getType();
1210
1211 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprVariable])
1212 return SK_ConstexprVariable;
1213
1214 if (!Type.isNull() && Type.isConstQualified()) {
1215 if (Type.getTypePtr()->isAnyPointerType() &&
1216 NamingStyles[SK_ConstantPointerParameter])
1217 return SK_ConstantPointerParameter;
1218
1219 if (NamingStyles[SK_ConstantParameter])
1220 return SK_ConstantParameter;
1221
1222 if (NamingStyles[SK_Constant])
1223 return SK_Constant;
1224 }
1225
1226 if (Decl->isParameterPack() && NamingStyles[SK_ParameterPack])
1227 return SK_ParameterPack;
1228
1229 if (!Type.isNull() && Type.getTypePtr()->isAnyPointerType() &&
1230 NamingStyles[SK_PointerParameter])
1231 return SK_PointerParameter;
1232
1233 if (NamingStyles[SK_Parameter])
1234 return SK_Parameter;
1235
1236 return undefinedStyle(NamingStyles);
1237 }
1238
1239 if (const auto *Decl = dyn_cast<VarDecl>(D))
1240 return findStyleKindForVar(Decl, Decl->getType(), NamingStyles);
1241
1242 if (const auto *Decl = dyn_cast<CXXMethodDecl>(D)) {
1243 if (Decl->isMain() || !Decl->isUserProvided() ||
1244 Decl->size_overridden_methods() > 0 || Decl->hasAttr<OverrideAttr>())
1245 return SK_Invalid;
1246
1247 // If this method has the same name as any base method, this is likely
1248 // necessary even if it's not an override. e.g. CRTP.
1249 for (const CXXBaseSpecifier &Base : Decl->getParent()->bases())
1250 if (const auto *RD = Base.getType()->getAsCXXRecordDecl())
1251 if (RD->hasMemberName(Decl->getDeclName()))
1252 return SK_Invalid;
1253
1254 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprMethod])
1255 return SK_ConstexprMethod;
1256
1257 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprFunction])
1258 return SK_ConstexprFunction;
1259
1260 if (Decl->isStatic() && NamingStyles[SK_ClassMethod])
1261 return SK_ClassMethod;
1262
1263 if (Decl->isVirtual() && NamingStyles[SK_VirtualMethod])
1264 return SK_VirtualMethod;
1265
1266 if (Decl->getAccess() == AS_private && NamingStyles[SK_PrivateMethod])
1267 return SK_PrivateMethod;
1268
1269 if (Decl->getAccess() == AS_protected && NamingStyles[SK_ProtectedMethod])
1270 return SK_ProtectedMethod;
1271
1272 if (Decl->getAccess() == AS_public && NamingStyles[SK_PublicMethod])
1273 return SK_PublicMethod;
1274
1275 if (NamingStyles[SK_Method])
1276 return SK_Method;
1277
1278 if (NamingStyles[SK_Function])
1279 return SK_Function;
1280
1281 return undefinedStyle(NamingStyles);
1282 }
1283
1284 if (const auto *Decl = dyn_cast<FunctionDecl>(D)) {
1285 if (Decl->isMain())
1286 return SK_Invalid;
1287
1288 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprFunction])
1289 return SK_ConstexprFunction;
1290
1291 if (Decl->isGlobal() && NamingStyles[SK_GlobalFunction])
1292 return SK_GlobalFunction;
1293
1294 if (NamingStyles[SK_Function])
1295 return SK_Function;
1296 }
1297
1298 if (isa<TemplateTypeParmDecl>(D)) {
1299 if (NamingStyles[SK_TypeTemplateParameter])
1300 return SK_TypeTemplateParameter;
1301
1302 if (NamingStyles[SK_TemplateParameter])
1303 return SK_TemplateParameter;
1304
1305 return undefinedStyle(NamingStyles);
1306 }
1307
1308 if (isa<NonTypeTemplateParmDecl>(D)) {
1309 if (NamingStyles[SK_ValueTemplateParameter])
1310 return SK_ValueTemplateParameter;
1311
1312 if (NamingStyles[SK_TemplateParameter])
1313 return SK_TemplateParameter;
1314
1315 return undefinedStyle(NamingStyles);
1316 }
1317
1318 if (isa<TemplateTemplateParmDecl>(D)) {
1319 if (NamingStyles[SK_TemplateTemplateParameter])
1320 return SK_TemplateTemplateParameter;
1321
1322 if (NamingStyles[SK_TemplateParameter])
1323 return SK_TemplateParameter;
1324
1325 return undefinedStyle(NamingStyles);
1326 }
1327
1328 if (isa<ConceptDecl>(D) && NamingStyles[SK_Concept])
1329 return SK_Concept;
1330
1331 return undefinedStyle(NamingStyles);
1332}
1333
1334std::optional<RenamerClangTidyCheck::FailureInfo>
1336 StringRef Type, StringRef Name, const NamedDecl *ND,
1337 SourceLocation Location,
1338 ArrayRef<std::optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
1340 StyleKind SK, const SourceManager &SM, bool IgnoreFailedSplit) const {
1341 if (SK == SK_Invalid)
1342 return std::nullopt;
1343
1344 const auto &StyleOpt = NamingStyles[SK];
1345 if (!StyleOpt)
1346 return std::nullopt;
1347
1348 const IdentifierNamingCheck::NamingStyle &Style = *StyleOpt;
1349 if (Style.IgnoredRegexp.isValid() && Style.IgnoredRegexp.match(Name))
1350 return std::nullopt;
1351
1352 if (matchesStyle(Type, Name, Style, HNOption, ND))
1353 return std::nullopt;
1354
1355 std::string KindName =
1356 SK == SK_Default
1357 ? "identifier"
1358 : fixupWithCase(Type, StyleNames[SK], ND, Style, HNOption,
1360 llvm::replace(KindName, '_', ' ');
1361
1362 std::string Fixup = fixupWithStyle(Type, Name, Style, HNOption, ND);
1363 if (StringRef(Fixup) == Name) {
1364 if (!IgnoreFailedSplit) {
1365 LLVM_DEBUG(Location.print(llvm::dbgs(), SM);
1366 llvm::dbgs() << ": unable to split words for " << KindName
1367 << " '" << Name << "'\n");
1368 }
1369 return std::nullopt;
1370 }
1371 return RenamerClangTidyCheck::FailureInfo{std::move(KindName),
1372 std::move(Fixup)};
1373}
1374
1375std::optional<RenamerClangTidyCheck::FailureInfo>
1376IdentifierNamingCheck::getDeclFailureInfo(const NamedDecl *Decl,
1377 const SourceManager &SM) const {
1378 // Implicit identifiers cannot be renamed.
1379 if (Decl->isImplicit())
1380 return std::nullopt;
1381
1382 const SourceLocation Loc = Decl->getLocation();
1383 const FileStyle &FileStyle = getStyleForFile(SM.getFilename(Loc));
1384 if (!FileStyle.isActive())
1385 return std::nullopt;
1386
1387 return getFailureInfo(
1388 HungarianNotation.getDeclTypeName(Decl), Decl->getName(), Decl, Loc,
1389 FileStyle.getStyles(), FileStyle.getHNOption(),
1390 findStyleKind(Decl, FileStyle.getStyles(),
1391 FileStyle.isIgnoringMainLikeFunction(),
1392 FileStyle.isCheckingAnonFieldInParentScope()),
1393 SM, IgnoreFailedSplit);
1394}
1395
1396std::optional<RenamerClangTidyCheck::FailureInfo>
1397IdentifierNamingCheck::getMacroFailureInfo(const Token &MacroNameTok,
1398 const SourceManager &SM) const {
1399 const SourceLocation Loc = MacroNameTok.getLocation();
1400 const FileStyle &Style = getStyleForFile(SM.getFilename(Loc));
1401 if (!Style.isActive())
1402 return std::nullopt;
1403
1404 const auto &Styles = Style.getStyles();
1405 const StyleKind UsedKind = !Styles[SK_MacroDefinition] && Styles[SK_Default]
1406 ? SK_Default
1407 : SK_MacroDefinition;
1408
1409 return getFailureInfo("", MacroNameTok.getIdentifierInfo()->getName(),
1410 nullptr, Loc, Style.getStyles(), Style.getHNOption(),
1411 UsedKind, SM, IgnoreFailedSplit);
1412}
1413
1414RenamerClangTidyCheck::DiagInfo
1415IdentifierNamingCheck::getDiagInfo(const NamingCheckId &ID,
1416 const NamingCheckFailure &Failure) const {
1417 return DiagInfo{"invalid case style for %0 '%1'",
1418 [&](DiagnosticBuilder &Diag) {
1419 Diag << Failure.Info.KindName << ID.second;
1420 }};
1421}
1422
1423StringRef IdentifierNamingCheck::getRealFileName(StringRef FileName) const {
1424 auto Iter = RealFileNameCache.try_emplace(FileName);
1425 SmallString<256U> &RealFileName = Iter.first->getValue();
1426 if (!Iter.second)
1427 return RealFileName;
1428 llvm::sys::fs::real_path(FileName, RealFileName);
1429 return RealFileName;
1430}
1431
1432const IdentifierNamingCheck::FileStyle &
1433IdentifierNamingCheck::getStyleForFile(StringRef FileName) const {
1434 if (!GetConfigPerFile)
1435 return *MainFileStyle;
1436
1437 const StringRef RealFileName = getRealFileName(FileName);
1438 const StringRef Parent = llvm::sys::path::parent_path(RealFileName);
1439 auto Iter = NamingStylesCache.find(Parent);
1440 if (Iter != NamingStylesCache.end())
1441 return Iter->getValue();
1442
1443 const llvm::StringRef CheckName = getID();
1444 ClangTidyOptions Options = Context->getOptionsForFile(RealFileName);
1445 if (Options.Checks && GlobList(*Options.Checks).contains(CheckName)) {
1446 auto It = NamingStylesCache.try_emplace(
1447 Parent,
1448 getFileStyleFromOptions({CheckName, Options.CheckOptions, Context}));
1449 assert(It.second);
1450 return It.first->getValue();
1451 }
1452 // Default construction gives an empty style.
1453 auto It = NamingStylesCache.try_emplace(Parent);
1454 assert(It.second);
1455 return It.first->getValue();
1456}
1457
1458StyleKind IdentifierNamingCheck::findStyleKindForAnonField(
1459 const FieldDecl *AnonField,
1460 ArrayRef<std::optional<NamingStyle>> NamingStyles) const {
1461 const IndirectFieldDecl *IFD =
1463 assert(IFD && "Found an anonymous record field without an IndirectFieldDecl");
1464
1465 const QualType Type = AnonField->getType();
1466
1467 if (const auto *F = dyn_cast<FieldDecl>(IFD->chain().front()))
1468 return findStyleKindForField(F, Type, NamingStyles);
1469
1470 if (const auto *V = IFD->getVarDecl())
1471 return findStyleKindForVar(V, Type, NamingStyles);
1472
1473 return undefinedStyle(NamingStyles);
1474}
1475
1476StyleKind IdentifierNamingCheck::findStyleKindForField(
1477 const FieldDecl *Field, QualType Type,
1478 ArrayRef<std::optional<NamingStyle>> NamingStyles) const {
1479 if (!Type.isNull() && Type.isConstQualified()) {
1480 if (NamingStyles[SK_ConstantMember])
1481 return SK_ConstantMember;
1482
1483 if (NamingStyles[SK_Constant])
1484 return SK_Constant;
1485 }
1486
1487 if (Field->getAccess() == AS_private && NamingStyles[SK_PrivateMember])
1488 return SK_PrivateMember;
1489
1490 if (Field->getAccess() == AS_protected && NamingStyles[SK_ProtectedMember])
1491 return SK_ProtectedMember;
1492
1493 if (Field->getAccess() == AS_public && NamingStyles[SK_PublicMember])
1494 return SK_PublicMember;
1495
1496 if (NamingStyles[SK_Member])
1497 return SK_Member;
1498
1499 return undefinedStyle(NamingStyles);
1500}
1501
1502StyleKind IdentifierNamingCheck::findStyleKindForVar(
1503 const VarDecl *Var, QualType Type,
1504 ArrayRef<std::optional<NamingStyle>> NamingStyles) const {
1505 if (Var->isConstexpr()) {
1506 if (Var->isStaticDataMember() && NamingStyles[SK_ClassConstexpr])
1507 return SK_ClassConstexpr;
1508
1509 if (Var->isFileVarDecl() && NamingStyles[SK_GlobalConstexprVariable])
1510 return SK_GlobalConstexprVariable;
1511
1512 if (Var->isStaticLocal() && NamingStyles[SK_StaticConstexprVariable])
1513 return SK_StaticConstexprVariable;
1514
1515 if (Var->isLocalVarDecl() && NamingStyles[SK_LocalConstexprVariable])
1516 return SK_LocalConstexprVariable;
1517
1518 if (NamingStyles[SK_ConstexprVariable])
1519 return SK_ConstexprVariable;
1520 }
1521
1522 if (!Type.isNull() && Type.isConstQualified()) {
1523 if (Var->isStaticDataMember() && NamingStyles[SK_ClassConstant])
1524 return SK_ClassConstant;
1525
1526 if (Var->isFileVarDecl() && Type.getTypePtr()->isAnyPointerType() &&
1527 NamingStyles[SK_GlobalConstantPointer])
1528 return SK_GlobalConstantPointer;
1529
1530 if (Var->isFileVarDecl() && NamingStyles[SK_GlobalConstant])
1531 return SK_GlobalConstant;
1532
1533 if (Var->isStaticLocal() && NamingStyles[SK_StaticConstant])
1534 return SK_StaticConstant;
1535
1536 if (Var->isLocalVarDecl() && Type.getTypePtr()->isAnyPointerType() &&
1537 NamingStyles[SK_LocalConstantPointer])
1538 return SK_LocalConstantPointer;
1539
1540 if (Var->isLocalVarDecl() && NamingStyles[SK_LocalConstant])
1541 return SK_LocalConstant;
1542
1543 if (Var->isFunctionOrMethodVarDecl() && NamingStyles[SK_LocalConstant])
1544 return SK_LocalConstant;
1545
1546 if (NamingStyles[SK_Constant])
1547 return SK_Constant;
1548 }
1549
1550 if (Var->isStaticDataMember() && NamingStyles[SK_ClassMember])
1551 return SK_ClassMember;
1552
1553 if (Var->isFileVarDecl() && Type.getTypePtr()->isAnyPointerType() &&
1554 NamingStyles[SK_GlobalPointer])
1555 return SK_GlobalPointer;
1556
1557 if (Var->isFileVarDecl() && NamingStyles[SK_GlobalVariable])
1558 return SK_GlobalVariable;
1559
1560 if (Var->isStaticLocal() && NamingStyles[SK_StaticVariable])
1561 return SK_StaticVariable;
1562
1563 if (Var->isLocalVarDecl() && Type.getTypePtr()->isAnyPointerType() &&
1564 NamingStyles[SK_LocalPointer])
1565 return SK_LocalPointer;
1566
1567 if (Var->isLocalVarDecl() && NamingStyles[SK_LocalVariable])
1568 return SK_LocalVariable;
1569
1570 if (Var->isFunctionOrMethodVarDecl() && NamingStyles[SK_LocalVariable])
1571 return SK_LocalVariable;
1572
1573 if (NamingStyles[SK_Variable])
1574 return SK_Variable;
1575
1576 return undefinedStyle(NamingStyles);
1577}
1578
1579StyleKind IdentifierNamingCheck::undefinedStyle(
1580 ArrayRef<std::optional<NamingStyle>> NamingStyles) const {
1581 return NamingStyles[SK_Default] ? SK_Default : SK_Invalid;
1582}
1583
1584} // namespace readability
1585} // namespace clang::tidy
#define HUNGARIAN_NOTATION_PRIMITIVE_TYPES(m)
#define ENUMERATE(v)
#define HUNGARIAN_NOTATION_USER_DEFINED_TYPES(m)
#define NAMING_KEYS(m)
#define STRINGIZE(v)
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
std::pair< SourceLocation, StringRef > NamingCheckId
RenamerClangTidyCheck(StringRef CheckName, ClangTidyContext *Context)
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Derived classes that override this function should call this method from the overridden method.
IdentifierNamingCheck(StringRef Name, ClangTidyContext *Context)
std::string fixupWithCase(StringRef Type, StringRef Name, const Decl *D, const IdentifierNamingCheck::NamingStyle &Style, const IdentifierNamingCheck::HungarianNotationOption &HNOption, IdentifierNamingCheck::CaseType Case) const
std::optional< RenamerClangTidyCheck::FailureInfo > getFailureInfo(StringRef Type, StringRef Name, const NamedDecl *ND, SourceLocation Location, ArrayRef< std::optional< IdentifierNamingCheck::NamingStyle > > NamingStyles, const IdentifierNamingCheck::HungarianNotationOption &HNOption, StyleKind SK, const SourceManager &SM, bool IgnoreFailedSplit) const
std::string fixupWithStyle(StringRef Type, StringRef Name, const IdentifierNamingCheck::NamingStyle &Style, const IdentifierNamingCheck::HungarianNotationOption &HNOption, const Decl *D) const
IdentifierNamingCheck::FileStyle getFileStyleFromOptions(const ClangTidyCheck::OptionsView &Options) const
bool isParamInMainLikeFunction(const ParmVarDecl &ParmDecl, bool IncludeMainLike) const
bool matchesStyle(StringRef Type, StringRef Name, const IdentifierNamingCheck::NamingStyle &Style, const IdentifierNamingCheck::HungarianNotationOption &HNOption, const NamedDecl *Decl) const
StyleKind findStyleKind(const NamedDecl *D, ArrayRef< std::optional< IdentifierNamingCheck::NamingStyle > > NamingStyles, bool IgnoreMainLikeFunctions, bool CheckAnonFieldInParentScope) const
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
@ Type
An inlay hint that for a type annotation.
Definition Protocol.h:1710
static StringRef const HungarianNotationPrimitiveTypes[]
static StringRef const HungarianNotationUserDefinedTypes[]
static StringRef const StyleNames[]
const IndirectFieldDecl * findOutermostIndirectFieldDeclForField(const FieldDecl *FD)
Definition ASTUtils.cpp:115
OptionMap CheckOptions
Key-value mapping used to store check-specific options.
std::optional< std::string > Checks
Checks filter.
llvm::StringMap< ClangTidyValue > OptionMap
static llvm::ArrayRef< std::pair< readability::IdentifierNamingCheck::CaseType, StringRef > > getEnumMapping()
static llvm::ArrayRef< std::pair< HungarianPrefixType, StringRef > > getEnumMapping()
This class should be specialized by any enum type that needs to be converted to and from an llvm::Str...
Information describing a failed check.
bool isOptionEnabled(StringRef OptionKey, const llvm::StringMap< std::string > &StrMap) const
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