clang-tools 18.0.0git
IdentifierNamingCheck.cpp
Go to the documentation of this file.
1//===--- IdentifierNamingCheck.cpp - clang-tidy ---------------------------===//
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 "clang/AST/CXXInheritance.h"
13#include "clang/Lex/PPCallbacks.h"
14#include "clang/Lex/Preprocessor.h"
15#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/DenseMapInfo.h"
17#include "llvm/ADT/StringRef.h"
18#include "llvm/Support/Debug.h"
19#include "llvm/Support/Error.h"
20#include "llvm/Support/FormatVariadic.h"
21#include "llvm/Support/Path.h"
22#include "llvm/Support/Regex.h"
23#include "llvm/Support/YAMLParser.h"
24#include <optional>
25
26#define DEBUG_TYPE "clang-tidy"
27
28// FixItHint
29
30using namespace clang::ast_matchers;
31
32namespace clang::tidy {
33
34llvm::ArrayRef<
35 std::pair<readability::IdentifierNamingCheck::CaseType, StringRef>>
36OptionEnumMapping<
38 static constexpr std::pair<readability::IdentifierNamingCheck::CaseType,
39 StringRef>
40 Mapping[] = {
47 "Camel_Snake_Case"},
49 "camel_Snake_Back"},
51 "Leading_upper_snake_case"}};
52 return {Mapping};
53}
54
55template <>
57 readability::IdentifierNamingCheck::HungarianPrefixType> {
60 static llvm::ArrayRef<std::pair<HungarianPrefixType, StringRef>>
62 static constexpr std::pair<HungarianPrefixType, StringRef> Mapping[] = {
63 {HungarianPrefixType::HPT_Off, "Off"},
64 {HungarianPrefixType::HPT_On, "On"},
65 {HungarianPrefixType::HPT_LowerCase, "LowerCase"},
66 {HungarianPrefixType::HPT_CamelCase, "CamelCase"}};
67 return {Mapping};
68 }
69};
70
71namespace readability {
72
73// clang-format off
74#define NAMING_KEYS(m) \
75 m(Namespace) \
76 m(InlineNamespace) \
77 m(EnumConstant) \
78 m(ScopedEnumConstant) \
79 m(ConstexprVariable) \
80 m(ConstantMember) \
81 m(PrivateMember) \
82 m(ProtectedMember) \
83 m(PublicMember) \
84 m(Member) \
85 m(ClassConstant) \
86 m(ClassMember) \
87 m(GlobalConstant) \
88 m(GlobalConstantPointer) \
89 m(GlobalPointer) \
90 m(GlobalVariable) \
91 m(LocalConstant) \
92 m(LocalConstantPointer) \
93 m(LocalPointer) \
94 m(LocalVariable) \
95 m(StaticConstant) \
96 m(StaticVariable) \
97 m(Constant) \
98 m(Variable) \
99 m(ConstantParameter) \
100 m(ParameterPack) \
101 m(Parameter) \
102 m(PointerParameter) \
103 m(ConstantPointerParameter) \
104 m(AbstractClass) \
105 m(Struct) \
106 m(Class) \
107 m(Union) \
108 m(Enum) \
109 m(GlobalFunction) \
110 m(ConstexprFunction) \
111 m(Function) \
112 m(ConstexprMethod) \
113 m(VirtualMethod) \
114 m(ClassMethod) \
115 m(PrivateMethod) \
116 m(ProtectedMethod) \
117 m(PublicMethod) \
118 m(Method) \
119 m(Typedef) \
120 m(TypeTemplateParameter) \
121 m(ValueTemplateParameter) \
122 m(TemplateTemplateParameter) \
123 m(TemplateParameter) \
124 m(TypeAlias) \
125 m(MacroDefinition) \
126 m(ObjcIvar) \
127
128enum StyleKind : int {
129#define ENUMERATE(v) SK_ ## v,
131#undef ENUMERATE
135
136static StringRef const StyleNames[] = {
137#define STRINGIZE(v) #v,
139#undef STRINGIZE
140};
141
142#define HUNGARIAN_NOTATION_PRIMITIVE_TYPES(m) \
143 m(int8_t) \
144 m(int16_t) \
145 m(int32_t) \
146 m(int64_t) \
147 m(uint8_t) \
148 m(uint16_t) \
149 m(uint32_t) \
150 m(uint64_t) \
151 m(char8_t) \
152 m(char16_t) \
153 m(char32_t) \
154 m(float) \
155 m(double) \
156 m(char) \
157 m(bool) \
158 m(_Bool) \
159 m(int) \
160 m(size_t) \
161 m(wchar_t) \
162 m(short-int) \
163 m(short) \
164 m(signed-int) \
165 m(signed-short) \
166 m(signed-short-int) \
167 m(signed-long-long-int) \
168 m(signed-long-long) \
169 m(signed-long-int) \
170 m(signed-long) \
171 m(signed) \
172 m(unsigned-long-long-int) \
173 m(unsigned-long-long) \
174 m(unsigned-long-int) \
175 m(unsigned-long) \
176 m(unsigned-short-int) \
177 m(unsigned-short) \
178 m(unsigned-int) \
179 m(unsigned-char) \
180 m(unsigned) \
181 m(long-long-int) \
182 m(long-double) \
183 m(long-long) \
184 m(long-int) \
185 m(long) \
186 m(ptrdiff_t) \
187 m(void) \
188
189static StringRef const HungarainNotationPrimitiveTypes[] = {
190#define STRINGIZE(v) #v,
192#undef STRINGIZE
193};
194
195#define HUNGARIAN_NOTATION_USER_DEFINED_TYPES(m) \
196 m(BOOL) \
197 m(BOOLEAN) \
198 m(BYTE) \
199 m(CHAR) \
200 m(UCHAR) \
201 m(SHORT) \
202 m(USHORT) \
203 m(WORD) \
204 m(DWORD) \
205 m(DWORD32) \
206 m(DWORD64) \
207 m(LONG) \
208 m(ULONG) \
209 m(ULONG32) \
210 m(ULONG64) \
211 m(ULONGLONG) \
212 m(HANDLE) \
213 m(INT) \
214 m(INT8) \
215 m(INT16) \
216 m(INT32) \
217 m(INT64) \
218 m(UINT) \
219 m(UINT8) \
220 m(UINT16) \
221 m(UINT32) \
222 m(UINT64) \
223 m(PVOID) \
224
225static StringRef const HungarainNotationUserDefinedTypes[] = {
226#define STRINGIZE(v) #v,
228#undef STRINGIZE
229};
230
231
232#undef NAMING_KEYS
233// clang-format on
234
236 std::optional<IdentifierNamingCheck::CaseType> Case, StringRef Prefix,
237 StringRef Suffix, StringRef IgnoredRegexpStr, HungarianPrefixType HPType)
238 : Case(Case), Prefix(Prefix), Suffix(Suffix),
239 IgnoredRegexpStr(IgnoredRegexpStr), HPType(HPType) {
240 if (!IgnoredRegexpStr.empty()) {
241 IgnoredRegexp =
242 llvm::Regex(llvm::SmallString<128>({"^", IgnoredRegexpStr, "$"}));
243 if (!IgnoredRegexp.isValid())
244 llvm::errs() << "Invalid IgnoredRegexp regular expression: "
245 << IgnoredRegexpStr;
246 }
247}
248
249IdentifierNamingCheck::FileStyle IdentifierNamingCheck::getFileStyleFromOptions(
250 const ClangTidyCheck::OptionsView &Options) const {
252
254 HungarianNotation.loadFileConfig(Options, HNOption);
255
256 SmallVector<std::optional<IdentifierNamingCheck::NamingStyle>, 0> Styles;
257 Styles.resize(SK_Count);
258 SmallString<64> StyleString;
259 for (unsigned I = 0; I < SK_Count; ++I) {
260 size_t StyleSize = StyleNames[I].size();
261 StyleString.assign({StyleNames[I], "HungarianPrefix"});
262
263 auto HPTOpt =
265 if (HPTOpt && !HungarianNotation.checkOptionValid(I))
266 configurationDiag("invalid identifier naming option '%0'") << StyleString;
267
268 memcpy(&StyleString[StyleSize], "IgnoredRegexp", 13);
269 StyleString.truncate(StyleSize + 13);
270 std::optional<StringRef> IgnoredRegexpStr = Options.get(StyleString);
271 memcpy(&StyleString[StyleSize], "Prefix", 6);
272 StyleString.truncate(StyleSize + 6);
273 std::optional<StringRef> Prefix(Options.get(StyleString));
274 // Fast replacement of [Pre]fix -> [Suf]fix.
275 memcpy(&StyleString[StyleSize], "Suf", 3);
276 std::optional<StringRef> Postfix(Options.get(StyleString));
277 memcpy(&StyleString[StyleSize], "Case", 4);
278 StyleString.pop_back_n(2);
279 std::optional<CaseType> CaseOptional =
280 Options.get<IdentifierNamingCheck::CaseType>(StyleString);
281
282 if (CaseOptional || Prefix || Postfix || IgnoredRegexpStr || HPTOpt)
283 Styles[I].emplace(std::move(CaseOptional), Prefix.value_or(""),
284 Postfix.value_or(""), IgnoredRegexpStr.value_or(""),
285 HPTOpt.value_or(IdentifierNamingCheck::HPT_Off));
286 }
287 bool IgnoreMainLike = Options.get("IgnoreMainLikeFunctions", false);
288 return {std::move(Styles), std::move(HNOption), IgnoreMainLike};
289}
290
291std::string IdentifierNamingCheck::HungarianNotation::getDeclTypeName(
292 const NamedDecl *ND) const {
293 const auto *VD = dyn_cast<ValueDecl>(ND);
294 if (!VD)
295 return {};
296
297 if (isa<FunctionDecl, EnumConstantDecl>(ND))
298 return {};
299
300 // Get type text of variable declarations.
301 auto &SM = VD->getASTContext().getSourceManager();
302 const char *Begin = SM.getCharacterData(VD->getBeginLoc());
303 const char *End = SM.getCharacterData(VD->getEndLoc());
304 intptr_t StrLen = End - Begin;
305
306 // FIXME: Sometimes the value that returns from ValDecl->getEndLoc()
307 // is wrong(out of location of Decl). This causes `StrLen` will be assigned
308 // an unexpected large value. Current workaround to find the terminated
309 // character instead of the `getEndLoc()` function.
310 const char *EOL = strchr(Begin, '\n');
311 if (!EOL)
312 EOL = Begin + strlen(Begin);
313
314 const char *PosList[] = {strchr(Begin, '='), strchr(Begin, ';'),
315 strchr(Begin, ','), strchr(Begin, ')'), EOL};
316 for (const auto &Pos : PosList) {
317 if (Pos > Begin)
318 EOL = std::min(EOL, Pos);
319 }
320
321 StrLen = EOL - Begin;
322 std::string TypeName;
323 if (StrLen > 0) {
324 std::string Type(Begin, StrLen);
325
326 static constexpr StringRef Keywords[] = {
327 // Constexpr specifiers
328 "constexpr", "constinit", "consteval",
329 // Qualifier
330 "const", "volatile", "restrict", "mutable",
331 // Storage class specifiers
332 "register", "static", "extern", "thread_local",
333 // Other keywords
334 "virtual"};
335
336 // Remove keywords
337 for (StringRef Kw : Keywords) {
338 for (size_t Pos = 0;
339 (Pos = Type.find(Kw.data(), Pos)) != std::string::npos;) {
340 Type.replace(Pos, Kw.size(), "");
341 }
342 }
343 TypeName = Type.erase(0, Type.find_first_not_of(' '));
344
345 // Remove template parameters
346 const size_t Pos = Type.find('<');
347 if (Pos != std::string::npos) {
348 TypeName = Type.erase(Pos, Type.size() - Pos);
349 }
350
351 // Replace spaces with single space.
352 for (size_t Pos = 0; (Pos = Type.find(" ", Pos)) != std::string::npos;
353 Pos += strlen(" ")) {
354 Type.replace(Pos, strlen(" "), " ");
355 }
356
357 // Replace " &" with "&".
358 for (size_t Pos = 0; (Pos = Type.find(" &", Pos)) != std::string::npos;
359 Pos += strlen("&")) {
360 Type.replace(Pos, strlen(" &"), "&");
361 }
362
363 // Replace " *" with "* ".
364 for (size_t Pos = 0; (Pos = Type.find(" *", Pos)) != std::string::npos;
365 Pos += strlen("*")) {
366 Type.replace(Pos, strlen(" *"), "* ");
367 }
368
369 // Remove redundant tailing.
370 static constexpr StringRef TailsOfMultiWordType[] = {
371 " int", " char", " double", " long", " short"};
372 bool RedundantRemoved = false;
373 for (auto Kw : TailsOfMultiWordType) {
374 size_t Pos = Type.rfind(Kw.data());
375 if (Pos != std::string::npos) {
376 const size_t PtrCount = getAsteriskCount(Type, ND);
377 Type = Type.substr(0, Pos + Kw.size() + PtrCount);
378 RedundantRemoved = true;
379 break;
380 }
381 }
382
383 TypeName = Type.erase(0, Type.find_first_not_of(' '));
384 if (!RedundantRemoved) {
385 std::size_t FoundSpace = Type.find(' ');
386 if (FoundSpace != std::string::npos)
387 Type = Type.substr(0, FoundSpace);
388 }
389
390 TypeName = Type.erase(0, Type.find_first_not_of(' '));
391
392 QualType QT = VD->getType();
393 if (!QT.isNull() && QT->isArrayType())
394 TypeName.append("[]");
395 }
396
397 return TypeName;
398}
399
400IdentifierNamingCheck::IdentifierNamingCheck(StringRef Name,
401 ClangTidyContext *Context)
402 : RenamerClangTidyCheck(Name, Context), Context(Context),
403 GetConfigPerFile(Options.get("GetConfigPerFile", true)),
404 IgnoreFailedSplit(Options.get("IgnoreFailedSplit", false)) {
405
406 auto IterAndInserted = NamingStylesCache.try_emplace(
407 llvm::sys::path::parent_path(Context->getCurrentFile()),
409 assert(IterAndInserted.second && "Couldn't insert Style");
410 // Holding a reference to the data in the vector is safe as it should never
411 // move.
412 MainFileStyle = &IterAndInserted.first->getValue();
413}
414
416
418 int StyleKindIndex) const {
419 if ((StyleKindIndex >= SK_EnumConstant) &&
420 (StyleKindIndex <= SK_ConstantParameter))
421 return true;
422
423 if ((StyleKindIndex >= SK_Parameter) && (StyleKindIndex <= SK_Enum))
424 return true;
425
426 return false;
427}
428
430 StringRef OptionKey, const llvm::StringMap<std::string> &StrMap) const {
431 if (OptionKey.empty())
432 return false;
433
434 auto Iter = StrMap.find(OptionKey);
435 if (Iter == StrMap.end())
436 return false;
437
438 return *llvm::yaml::parseBool(Iter->getValue());
439}
440
444
445 static constexpr StringRef HNOpts[] = {"TreatStructAsClass"};
446 static constexpr StringRef HNDerivedTypes[] = {"Array", "Pointer",
447 "FunctionPointer"};
448
449 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 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 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 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 : HungarainNotationPrimitiveTypes) {
490 Buffer.truncate(DefSize);
491 Buffer.append(PrimType);
492 StringRef Val = Options.get(Buffer, "");
493 if (!Val.empty()) {
494 std::string Type = PrimType.str();
495 std::replace(Type.begin(), Type.end(), '-', ' ');
496 HNOption.PrimitiveType[Type] = Val.str();
497 }
498 }
499
500 Buffer = {Section, "UserDefinedType."};
501 DefSize = Buffer.size();
502 for (const auto &Type : HungarainNotationUserDefinedTypes) {
503 Buffer.truncate(DefSize);
504 Buffer.append(Type);
505 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 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 std::string CorrectName = Words[0].str();
541 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 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 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 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 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 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.data(), StartPos)) !=
604 std::string::npos) {
605 Str.replace(StartPos, From.size(), To.data());
606 StartPos += To.size();
607 }
608 return Str;
609 }(ModifiedTypeName, "*", "");
610 }
611
612 // Primitive types
613 if (PrefixStr.empty()) {
614 for (const auto &Type : HNOption.PrimitiveType) {
615 if (ModifiedTypeName == Type.getKey()) {
616 PrefixStr = Type.getValue();
617 break;
618 }
619 }
620 }
621
622 // User-Defined types
623 if (PrefixStr.empty()) {
624 for (const auto &Type : HNOption.UserDefinedType) {
625 if (ModifiedTypeName == Type.getKey()) {
626 PrefixStr = Type.getValue();
627 break;
628 }
629 }
630 }
631
632 for (size_t Idx = 0; Idx < PtrCount; Idx++)
633 PrefixStr.insert(0, HNOption.DerivedType.lookup("Pointer"));
634
635 return PrefixStr;
636}
637
639 const CXXRecordDecl *CRD,
641
642 if (CRD->isUnion())
643 return {};
644
645 if (CRD->isStruct() &&
646 !isOptionEnabled("TreatStructAsClass", HNOption.General))
647 return {};
648
649 return CRD->isAbstract() ? "I" : "C";
650}
651
653 const EnumConstantDecl *ECD) const {
654 const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
655
656 std::string Name = ED->getName().str();
657 if (std::string::npos != Name.find("enum")) {
658 Name = Name.substr(strlen("enum"), Name.length() - strlen("enum"));
659 Name = Name.erase(0, Name.find_first_not_of(' '));
660 }
661
662 static llvm::Regex Splitter(
663 "([a-z0-9A-Z]*)(_+)|([A-Z]?[a-z0-9]+)([A-Z]|$)|([A-Z]+)([A-Z]|$)");
664
665 StringRef EnumName(Name);
666 SmallVector<StringRef, 8> Substrs;
667 EnumName.split(Substrs, "_", -1, false);
668
669 SmallVector<StringRef, 8> Words;
670 SmallVector<StringRef, 8> Groups;
671 for (auto Substr : Substrs) {
672 while (!Substr.empty()) {
673 Groups.clear();
674 if (!Splitter.match(Substr, &Groups))
675 break;
676
677 if (!Groups[2].empty()) {
678 Words.push_back(Groups[1]);
679 Substr = Substr.substr(Groups[0].size());
680 } else if (!Groups[3].empty()) {
681 Words.push_back(Groups[3]);
682 Substr = Substr.substr(Groups[0].size() - Groups[4].size());
683 } else if (!Groups[5].empty()) {
684 Words.push_back(Groups[5]);
685 Substr = Substr.substr(Groups[0].size() - Groups[6].size());
686 }
687 }
688 }
689
690 std::string Initial;
691 for (StringRef Word : Words)
692 Initial += tolower(Word[0]);
693
694 return Initial;
695}
696
698 const std::string &TypeName) const {
699 size_t Pos = TypeName.find('*');
700 size_t Count = 0;
701 for (; Pos < TypeName.length(); Pos++, Count++) {
702 if ('*' != TypeName[Pos])
703 break;
704 }
705 return Count;
706}
707
709 const std::string &TypeName, const NamedDecl *ND) const {
710 size_t PtrCount = 0;
711 if (const auto *TD = dyn_cast<ValueDecl>(ND)) {
712 QualType QT = TD->getType();
713 if (QT->isPointerType())
714 PtrCount = getAsteriskCount(TypeName);
715 }
716 return PtrCount;
717}
718
721
722 // Options
723 static constexpr std::pair<StringRef, StringRef> General[] = {
724 {"TreatStructAsClass", "false"}};
725 for (const auto &G : General)
726 HNOption.General.try_emplace(G.first, G.second);
727
728 // Derived types
729 static constexpr std::pair<StringRef, StringRef> DerivedTypes[] = {
730 {"Array", "a"}, {"Pointer", "p"}, {"FunctionPointer", "fn"}};
731 for (const auto &DT : DerivedTypes)
732 HNOption.DerivedType.try_emplace(DT.first, DT.second);
733
734 // C strings
735 static constexpr std::pair<StringRef, StringRef> CStrings[] = {
736 {"char*", "sz"},
737 {"char[]", "sz"},
738 {"wchar_t*", "wsz"},
739 {"wchar_t[]", "wsz"}};
740 for (const auto &CStr : CStrings)
741 HNOption.CString.try_emplace(CStr.first, CStr.second);
742
743 // clang-format off
744 static constexpr std::pair<StringRef, StringRef> PrimitiveTypes[] = {
745 {"int8_t", "i8" },
746 {"int16_t", "i16" },
747 {"int32_t", "i32" },
748 {"int64_t", "i64" },
749 {"uint8_t", "u8" },
750 {"uint16_t", "u16" },
751 {"uint32_t", "u32" },
752 {"uint64_t", "u64" },
753 {"char8_t", "c8" },
754 {"char16_t", "c16" },
755 {"char32_t", "c32" },
756 {"float", "f" },
757 {"double", "d" },
758 {"char", "c" },
759 {"bool", "b" },
760 {"_Bool", "b" },
761 {"int", "i" },
762 {"size_t", "n" },
763 {"wchar_t", "wc" },
764 {"short int", "si" },
765 {"short", "s" },
766 {"signed int", "si" },
767 {"signed short", "ss" },
768 {"signed short int", "ssi" },
769 {"signed long long int", "slli"},
770 {"signed long long", "sll" },
771 {"signed long int", "sli" },
772 {"signed long", "sl" },
773 {"signed", "s" },
774 {"unsigned long long int", "ulli"},
775 {"unsigned long long", "ull" },
776 {"unsigned long int", "uli" },
777 {"unsigned long", "ul" },
778 {"unsigned short int", "usi" },
779 {"unsigned short", "us" },
780 {"unsigned int", "ui" },
781 {"unsigned char", "uc" },
782 {"unsigned", "u" },
783 {"long long int", "lli" },
784 {"long double", "ld" },
785 {"long long", "ll" },
786 {"long int", "li" },
787 {"long", "l" },
788 {"ptrdiff_t", "p" },
789 {"void", "" }};
790 // clang-format on
791 for (const auto &PT : PrimitiveTypes)
792 HNOption.PrimitiveType.try_emplace(PT.first, PT.second);
793
794 // clang-format off
795 static constexpr std::pair<StringRef, StringRef> UserDefinedTypes[] = {
796 // Windows data types
797 {"BOOL", "b" },
798 {"BOOLEAN", "b" },
799 {"BYTE", "by" },
800 {"CHAR", "c" },
801 {"UCHAR", "uc" },
802 {"SHORT", "s" },
803 {"USHORT", "us" },
804 {"WORD", "w" },
805 {"DWORD", "dw" },
806 {"DWORD32", "dw32"},
807 {"DWORD64", "dw64"},
808 {"LONG", "l" },
809 {"ULONG", "ul" },
810 {"ULONG32", "ul32"},
811 {"ULONG64", "ul64"},
812 {"ULONGLONG", "ull" },
813 {"HANDLE", "h" },
814 {"INT", "i" },
815 {"INT8", "i8" },
816 {"INT16", "i16" },
817 {"INT32", "i32" },
818 {"INT64", "i64" },
819 {"UINT", "ui" },
820 {"UINT8", "u8" },
821 {"UINT16", "u16" },
822 {"UINT32", "u32" },
823 {"UINT64", "u64" },
824 {"PVOID", "p" } };
825 // clang-format on
826 for (const auto &UDT : UserDefinedTypes)
827 HNOption.UserDefinedType.try_emplace(UDT.first, UDT.second);
828}
829
832 SmallString<64> StyleString;
833 ArrayRef<std::optional<NamingStyle>> Styles = MainFileStyle->getStyles();
834 for (size_t I = 0; I < SK_Count; ++I) {
835 if (!Styles[I])
836 continue;
837 size_t StyleSize = StyleNames[I].size();
838 StyleString.assign({StyleNames[I], "HungarianPrefix"});
839
840 Options.store(Opts, StyleString, Styles[I]->HPType);
841
842 memcpy(&StyleString[StyleSize], "IgnoredRegexp", 13);
843 StyleString.truncate(StyleSize + 13);
844 Options.store(Opts, StyleString, Styles[I]->IgnoredRegexpStr);
845 memcpy(&StyleString[StyleSize], "Prefix", 6);
846 StyleString.truncate(StyleSize + 6);
847 Options.store(Opts, StyleString, Styles[I]->Prefix);
848 // Fast replacement of [Pre]fix -> [Suf]fix.
849 memcpy(&StyleString[StyleSize], "Suf", 3);
850 Options.store(Opts, StyleString, Styles[I]->Suffix);
851 if (Styles[I]->Case) {
852 memcpy(&StyleString[StyleSize], "Case", 4);
853 StyleString.pop_back_n(2);
854 Options.store(Opts, StyleString, *Styles[I]->Case);
855 }
856 }
857 Options.store(Opts, "GetConfigPerFile", GetConfigPerFile);
858 Options.store(Opts, "IgnoreFailedSplit", IgnoreFailedSplit);
859 Options.store(Opts, "IgnoreMainLikeFunctions",
860 MainFileStyle->isIgnoringMainLikeFunction());
861}
862
864 StringRef Type, StringRef Name,
867 const NamedDecl *Decl) const {
868 static llvm::Regex Matchers[] = {
869 llvm::Regex("^.*$"),
870 llvm::Regex("^[a-z][a-z0-9_]*$"),
871 llvm::Regex("^[a-z][a-zA-Z0-9]*$"),
872 llvm::Regex("^[A-Z][A-Z0-9_]*$"),
873 llvm::Regex("^[A-Z][a-zA-Z0-9]*$"),
874 llvm::Regex("^[A-Z]([a-z0-9]*(_[A-Z])?)*"),
875 llvm::Regex("^[a-z]([a-z0-9]*(_[A-Z])?)*"),
876 llvm::Regex("^[A-Z]([a-z0-9_]*[a-z])*$"),
877 };
878
879 if (!Name.consume_front(Style.Prefix))
880 return false;
881 if (!Name.consume_back(Style.Suffix))
882 return false;
884 std::string HNPrefix = HungarianNotation.getPrefix(Decl, HNOption);
885 if (!Name.consume_front(HNPrefix))
886 return false;
887 }
888
889 // Ensure the name doesn't have any extra underscores beyond those specified
890 // in the prefix and suffix.
891 if (Name.startswith("_") || Name.endswith("_"))
892 return false;
893
894 if (Style.Case && !Matchers[static_cast<size_t>(*Style.Case)].match(Name))
895 return false;
896
897 return true;
898}
899
901 StringRef Type, StringRef Name, const Decl *D,
905 static llvm::Regex Splitter(
906 "([a-z0-9A-Z]*)(_+)|([A-Z]?[a-z0-9]+)([A-Z]|$)|([A-Z]+)([A-Z]|$)");
907
908 SmallVector<StringRef, 8> Substrs;
909 Name.split(Substrs, "_", -1, false);
910
911 SmallVector<StringRef, 8> Words;
912 SmallVector<StringRef, 8> Groups;
913 for (auto Substr : Substrs) {
914 while (!Substr.empty()) {
915 Groups.clear();
916 if (!Splitter.match(Substr, &Groups))
917 break;
918
919 if (!Groups[2].empty()) {
920 Words.push_back(Groups[1]);
921 Substr = Substr.substr(Groups[0].size());
922 } else if (!Groups[3].empty()) {
923 Words.push_back(Groups[3]);
924 Substr = Substr.substr(Groups[0].size() - Groups[4].size());
925 } else if (!Groups[5].empty()) {
926 Words.push_back(Groups[5]);
927 Substr = Substr.substr(Groups[0].size() - Groups[6].size());
928 }
929 }
930 }
931
932 if (Words.empty())
933 return Name.str();
934
937 }
938
939 SmallString<128> Fixup;
940 switch (Case) {
942 return Name.str();
943 break;
944
946 for (auto const &Word : Words) {
947 if (&Word != &Words.front())
948 Fixup += "_";
949 Fixup += Word.lower();
950 }
951 break;
952
954 for (auto const &Word : Words) {
955 if (&Word != &Words.front())
956 Fixup += "_";
957 Fixup += Word.upper();
958 }
959 break;
960
962 for (auto const &Word : Words) {
963 Fixup += toupper(Word.front());
964 Fixup += Word.substr(1).lower();
965 }
966 break;
967
969 for (auto const &Word : Words) {
970 if (&Word == &Words.front()) {
971 Fixup += Word.lower();
972 } else {
973 Fixup += toupper(Word.front());
974 Fixup += Word.substr(1).lower();
975 }
976 }
977 break;
978
980 for (auto const &Word : Words) {
981 if (&Word != &Words.front())
982 Fixup += "_";
983 Fixup += toupper(Word.front());
984 Fixup += Word.substr(1).lower();
985 }
986 break;
987
989 for (auto const &Word : Words) {
990 if (&Word != &Words.front()) {
991 Fixup += "_";
992 Fixup += toupper(Word.front());
993 } else {
994 Fixup += tolower(Word.front());
995 }
996 Fixup += Word.substr(1).lower();
997 }
998 break;
999
1001 for (auto const &Word : Words) {
1002 if (&Word != &Words.front()) {
1003 Fixup += "_";
1004 Fixup += Word.lower();
1005 } else {
1006 Fixup += toupper(Word.front());
1007 Fixup += Word.substr(1).lower();
1008 }
1009 }
1010 break;
1011 }
1012
1013 return Fixup.str().str();
1014}
1015
1017 const ParmVarDecl &ParmDecl, bool IncludeMainLike) const {
1018 const auto *FDecl =
1019 dyn_cast_or_null<FunctionDecl>(ParmDecl.getParentFunctionOrMethod());
1020 if (!FDecl)
1021 return false;
1022 if (FDecl->isMain())
1023 return true;
1024 if (!IncludeMainLike)
1025 return false;
1026 if (FDecl->getAccess() != AS_public && FDecl->getAccess() != AS_none)
1027 return false;
1028 // If the function doesn't have a name that's an identifier, can occur if the
1029 // function is an operator overload, bail out early.
1030 if (!FDecl->getDeclName().isIdentifier())
1031 return false;
1032 enum MainType { None, Main, WMain };
1033 auto IsCharPtrPtr = [](QualType QType) -> MainType {
1034 if (QType.isNull())
1035 return None;
1036 if (QType = QType->getPointeeType(), QType.isNull())
1037 return None;
1038 if (QType = QType->getPointeeType(), QType.isNull())
1039 return None;
1040 if (QType->isCharType())
1041 return Main;
1042 if (QType->isWideCharType())
1043 return WMain;
1044 return None;
1045 };
1046 auto IsIntType = [](QualType QType) {
1047 if (QType.isNull())
1048 return false;
1049 if (const auto *Builtin =
1050 dyn_cast<BuiltinType>(QType->getUnqualifiedDesugaredType())) {
1051 return Builtin->getKind() == BuiltinType::Int;
1052 }
1053 return false;
1054 };
1055 if (!IsIntType(FDecl->getReturnType()))
1056 return false;
1057 if (FDecl->getNumParams() < 2 || FDecl->getNumParams() > 3)
1058 return false;
1059 if (!IsIntType(FDecl->parameters()[0]->getType()))
1060 return false;
1061 MainType Type = IsCharPtrPtr(FDecl->parameters()[1]->getType());
1062 if (Type == None)
1063 return false;
1064 if (FDecl->getNumParams() == 3 &&
1065 IsCharPtrPtr(FDecl->parameters()[2]->getType()) != Type)
1066 return false;
1067
1068 if (Type == Main) {
1069 static llvm::Regex Matcher(
1070 "(^[Mm]ain([_A-Z]|$))|([a-z0-9_]Main([_A-Z]|$))|(_main(_|$))");
1071 assert(Matcher.isValid() && "Invalid Matcher for main like functions.");
1072 return Matcher.match(FDecl->getName());
1073 }
1074 static llvm::Regex Matcher("(^((W[Mm])|(wm))ain([_A-Z]|$))|([a-z0-9_]W[Mm]"
1075 "ain([_A-Z]|$))|(_wmain(_|$))");
1076 assert(Matcher.isValid() && "Invalid Matcher for wmain like functions.");
1077 return Matcher.match(FDecl->getName());
1078}
1079
1081 StringRef Type, StringRef Name,
1084 const Decl *D) const {
1085 Name.consume_front(Style.Prefix);
1086 Name.consume_back(Style.Suffix);
1087 std::string Fixed = fixupWithCase(
1088 Type, Name, D, Style, HNOption,
1089 Style.Case.value_or(IdentifierNamingCheck::CaseType::CT_AnyCase));
1090
1091 std::string HungarianPrefix;
1093 if (HungarianPrefixType::HPT_Off != Style.HPType) {
1094 HungarianPrefix = HungarianNotation.getPrefix(D, HNOption);
1095 if (!HungarianPrefix.empty()) {
1096 if (Style.HPType == HungarianPrefixType::HPT_LowerCase)
1097 HungarianPrefix += "_";
1098
1099 if (Style.HPType == HungarianPrefixType::HPT_CamelCase)
1100 Fixed[0] = toupper(Fixed[0]);
1101 }
1102 }
1103 StringRef Mid = StringRef(Fixed).trim("_");
1104 if (Mid.empty())
1105 Mid = "_";
1106
1107 return (Style.Prefix + HungarianPrefix + Mid + Style.Suffix).str();
1108}
1109
1111 const NamedDecl *D,
1112 ArrayRef<std::optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
1113 bool IgnoreMainLikeFunctions) const {
1114 assert(D && D->getIdentifier() && !D->getName().empty() && !D->isImplicit() &&
1115 "Decl must be an explicit identifier with a name.");
1116
1117 if (isa<ObjCIvarDecl>(D) && NamingStyles[SK_ObjcIvar])
1118 return SK_ObjcIvar;
1119
1120 if (isa<TypedefDecl>(D) && NamingStyles[SK_Typedef])
1121 return SK_Typedef;
1122
1123 if (isa<TypeAliasDecl>(D) && NamingStyles[SK_TypeAlias])
1124 return SK_TypeAlias;
1125
1126 if (const auto *Decl = dyn_cast<NamespaceDecl>(D)) {
1127 if (Decl->isAnonymousNamespace())
1128 return SK_Invalid;
1129
1130 if (Decl->isInline() && NamingStyles[SK_InlineNamespace])
1131 return SK_InlineNamespace;
1132
1133 if (NamingStyles[SK_Namespace])
1134 return SK_Namespace;
1135 }
1136
1137 if (isa<EnumDecl>(D) && NamingStyles[SK_Enum])
1138 return SK_Enum;
1139
1140 if (const auto *EnumConst = dyn_cast<EnumConstantDecl>(D)) {
1141 if (cast<EnumDecl>(EnumConst->getDeclContext())->isScoped() &&
1142 NamingStyles[SK_ScopedEnumConstant])
1143 return SK_ScopedEnumConstant;
1144
1145 if (NamingStyles[SK_EnumConstant])
1146 return SK_EnumConstant;
1147
1148 if (NamingStyles[SK_Constant])
1149 return SK_Constant;
1150
1151 return SK_Invalid;
1152 }
1153
1154 if (const auto *Decl = dyn_cast<RecordDecl>(D)) {
1155 if (Decl->isAnonymousStructOrUnion())
1156 return SK_Invalid;
1157
1158 if (const auto *Definition = Decl->getDefinition()) {
1159 if (const auto *CxxRecordDecl = dyn_cast<CXXRecordDecl>(Definition)) {
1160 if (CxxRecordDecl->isAbstract() && NamingStyles[SK_AbstractClass])
1161 return SK_AbstractClass;
1162 }
1163
1164 if (Definition->isStruct() && NamingStyles[SK_Struct])
1165 return SK_Struct;
1166
1167 if (Definition->isStruct() && NamingStyles[SK_Class])
1168 return SK_Class;
1169
1170 if (Definition->isClass() && NamingStyles[SK_Class])
1171 return SK_Class;
1172
1173 if (Definition->isClass() && NamingStyles[SK_Struct])
1174 return SK_Struct;
1175
1176 if (Definition->isUnion() && NamingStyles[SK_Union])
1177 return SK_Union;
1178
1179 if (Definition->isEnum() && NamingStyles[SK_Enum])
1180 return SK_Enum;
1181 }
1182
1183 return SK_Invalid;
1184 }
1185
1186 if (const auto *Decl = dyn_cast<FieldDecl>(D)) {
1187 QualType Type = Decl->getType();
1188
1189 if (!Type.isNull() && Type.isConstQualified()) {
1190 if (NamingStyles[SK_ConstantMember])
1191 return SK_ConstantMember;
1192
1193 if (NamingStyles[SK_Constant])
1194 return SK_Constant;
1195 }
1196
1197 if (Decl->getAccess() == AS_private && NamingStyles[SK_PrivateMember])
1198 return SK_PrivateMember;
1199
1200 if (Decl->getAccess() == AS_protected && NamingStyles[SK_ProtectedMember])
1201 return SK_ProtectedMember;
1202
1203 if (Decl->getAccess() == AS_public && NamingStyles[SK_PublicMember])
1204 return SK_PublicMember;
1205
1206 if (NamingStyles[SK_Member])
1207 return SK_Member;
1208
1209 return SK_Invalid;
1210 }
1211
1212 if (const auto *Decl = dyn_cast<ParmVarDecl>(D)) {
1213 if (isParamInMainLikeFunction(*Decl, IgnoreMainLikeFunctions))
1214 return SK_Invalid;
1215 QualType Type = Decl->getType();
1216
1217 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprVariable])
1218 return SK_ConstexprVariable;
1219
1220 if (!Type.isNull() && Type.isConstQualified()) {
1221 if (Type.getTypePtr()->isAnyPointerType() &&
1222 NamingStyles[SK_ConstantPointerParameter])
1223 return SK_ConstantPointerParameter;
1224
1225 if (NamingStyles[SK_ConstantParameter])
1226 return SK_ConstantParameter;
1227
1228 if (NamingStyles[SK_Constant])
1229 return SK_Constant;
1230 }
1231
1232 if (Decl->isParameterPack() && NamingStyles[SK_ParameterPack])
1233 return SK_ParameterPack;
1234
1235 if (!Type.isNull() && Type.getTypePtr()->isAnyPointerType() &&
1236 NamingStyles[SK_PointerParameter])
1237 return SK_PointerParameter;
1238
1239 if (NamingStyles[SK_Parameter])
1240 return SK_Parameter;
1241
1242 return SK_Invalid;
1243 }
1244
1245 if (const auto *Decl = dyn_cast<VarDecl>(D)) {
1246 QualType Type = Decl->getType();
1247
1248 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprVariable])
1249 return SK_ConstexprVariable;
1250
1251 if (!Type.isNull() && Type.isConstQualified()) {
1252 if (Decl->isStaticDataMember() && NamingStyles[SK_ClassConstant])
1253 return SK_ClassConstant;
1254
1255 if (Decl->isFileVarDecl() && Type.getTypePtr()->isAnyPointerType() &&
1256 NamingStyles[SK_GlobalConstantPointer])
1257 return SK_GlobalConstantPointer;
1258
1259 if (Decl->isFileVarDecl() && NamingStyles[SK_GlobalConstant])
1260 return SK_GlobalConstant;
1261
1262 if (Decl->isStaticLocal() && NamingStyles[SK_StaticConstant])
1263 return SK_StaticConstant;
1264
1265 if (Decl->isLocalVarDecl() && Type.getTypePtr()->isAnyPointerType() &&
1266 NamingStyles[SK_LocalConstantPointer])
1267 return SK_LocalConstantPointer;
1268
1269 if (Decl->isLocalVarDecl() && NamingStyles[SK_LocalConstant])
1270 return SK_LocalConstant;
1271
1272 if (Decl->isFunctionOrMethodVarDecl() && NamingStyles[SK_LocalConstant])
1273 return SK_LocalConstant;
1274
1275 if (NamingStyles[SK_Constant])
1276 return SK_Constant;
1277 }
1278
1279 if (Decl->isStaticDataMember() && NamingStyles[SK_ClassMember])
1280 return SK_ClassMember;
1281
1282 if (Decl->isFileVarDecl() && Type.getTypePtr()->isAnyPointerType() &&
1283 NamingStyles[SK_GlobalPointer])
1284 return SK_GlobalPointer;
1285
1286 if (Decl->isFileVarDecl() && NamingStyles[SK_GlobalVariable])
1287 return SK_GlobalVariable;
1288
1289 if (Decl->isStaticLocal() && NamingStyles[SK_StaticVariable])
1290 return SK_StaticVariable;
1291
1292 if (Decl->isLocalVarDecl() && Type.getTypePtr()->isAnyPointerType() &&
1293 NamingStyles[SK_LocalPointer])
1294 return SK_LocalPointer;
1295
1296 if (Decl->isLocalVarDecl() && NamingStyles[SK_LocalVariable])
1297 return SK_LocalVariable;
1298
1299 if (Decl->isFunctionOrMethodVarDecl() && NamingStyles[SK_LocalVariable])
1300 return SK_LocalVariable;
1301
1302 if (NamingStyles[SK_Variable])
1303 return SK_Variable;
1304
1305 return SK_Invalid;
1306 }
1307
1308 if (const auto *Decl = dyn_cast<CXXMethodDecl>(D)) {
1309 if (Decl->isMain() || !Decl->isUserProvided() ||
1310 Decl->size_overridden_methods() > 0 || Decl->hasAttr<OverrideAttr>())
1311 return SK_Invalid;
1312
1313 // If this method has the same name as any base method, this is likely
1314 // necessary even if it's not an override. e.g. CRTP.
1315 for (const CXXBaseSpecifier &Base : Decl->getParent()->bases())
1316 if (const auto *RD = Base.getType()->getAsCXXRecordDecl())
1317 if (RD->hasMemberName(Decl->getDeclName()))
1318 return SK_Invalid;
1319
1320 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprMethod])
1321 return SK_ConstexprMethod;
1322
1323 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprFunction])
1324 return SK_ConstexprFunction;
1325
1326 if (Decl->isStatic() && NamingStyles[SK_ClassMethod])
1327 return SK_ClassMethod;
1328
1329 if (Decl->isVirtual() && NamingStyles[SK_VirtualMethod])
1330 return SK_VirtualMethod;
1331
1332 if (Decl->getAccess() == AS_private && NamingStyles[SK_PrivateMethod])
1333 return SK_PrivateMethod;
1334
1335 if (Decl->getAccess() == AS_protected && NamingStyles[SK_ProtectedMethod])
1336 return SK_ProtectedMethod;
1337
1338 if (Decl->getAccess() == AS_public && NamingStyles[SK_PublicMethod])
1339 return SK_PublicMethod;
1340
1341 if (NamingStyles[SK_Method])
1342 return SK_Method;
1343
1344 if (NamingStyles[SK_Function])
1345 return SK_Function;
1346
1347 return SK_Invalid;
1348 }
1349
1350 if (const auto *Decl = dyn_cast<FunctionDecl>(D)) {
1351 if (Decl->isMain())
1352 return SK_Invalid;
1353
1354 if (Decl->isConstexpr() && NamingStyles[SK_ConstexprFunction])
1355 return SK_ConstexprFunction;
1356
1357 if (Decl->isGlobal() && NamingStyles[SK_GlobalFunction])
1358 return SK_GlobalFunction;
1359
1360 if (NamingStyles[SK_Function])
1361 return SK_Function;
1362 }
1363
1364 if (isa<TemplateTypeParmDecl>(D)) {
1365 if (NamingStyles[SK_TypeTemplateParameter])
1366 return SK_TypeTemplateParameter;
1367
1368 if (NamingStyles[SK_TemplateParameter])
1369 return SK_TemplateParameter;
1370
1371 return SK_Invalid;
1372 }
1373
1374 if (isa<NonTypeTemplateParmDecl>(D)) {
1375 if (NamingStyles[SK_ValueTemplateParameter])
1376 return SK_ValueTemplateParameter;
1377
1378 if (NamingStyles[SK_TemplateParameter])
1379 return SK_TemplateParameter;
1380
1381 return SK_Invalid;
1382 }
1383
1384 if (isa<TemplateTemplateParmDecl>(D)) {
1385 if (NamingStyles[SK_TemplateTemplateParameter])
1386 return SK_TemplateTemplateParameter;
1387
1388 if (NamingStyles[SK_TemplateParameter])
1389 return SK_TemplateParameter;
1390
1391 return SK_Invalid;
1392 }
1393
1394 return SK_Invalid;
1395}
1396
1397std::optional<RenamerClangTidyCheck::FailureInfo>
1399 StringRef Type, StringRef Name, const NamedDecl *ND,
1400 SourceLocation Location,
1401 ArrayRef<std::optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
1403 StyleKind SK, const SourceManager &SM, bool IgnoreFailedSplit) const {
1404 if (SK == SK_Invalid || !NamingStyles[SK])
1405 return std::nullopt;
1406
1407 const IdentifierNamingCheck::NamingStyle &Style = *NamingStyles[SK];
1408 if (Style.IgnoredRegexp.isValid() && Style.IgnoredRegexp.match(Name))
1409 return std::nullopt;
1410
1411 if (matchesStyle(Type, Name, Style, HNOption, ND))
1412 return std::nullopt;
1413
1414 std::string KindName =
1415 fixupWithCase(Type, StyleNames[SK], ND, Style, HNOption,
1417 std::replace(KindName.begin(), KindName.end(), '_', ' ');
1418
1419 std::string Fixup = fixupWithStyle(Type, Name, Style, HNOption, ND);
1420 if (StringRef(Fixup).equals(Name)) {
1421 if (!IgnoreFailedSplit) {
1422 LLVM_DEBUG(Location.print(llvm::dbgs(), SM);
1423 llvm::dbgs()
1424 << llvm::formatv(": unable to split words for {0} '{1}'\n",
1425 KindName, Name));
1426 }
1427 return std::nullopt;
1428 }
1429 return RenamerClangTidyCheck::FailureInfo{std::move(KindName),
1430 std::move(Fixup)};
1431}
1432
1433std::optional<RenamerClangTidyCheck::FailureInfo>
1434IdentifierNamingCheck::getDeclFailureInfo(const NamedDecl *Decl,
1435 const SourceManager &SM) const {
1436 SourceLocation Loc = Decl->getLocation();
1437 const FileStyle &FileStyle = getStyleForFile(SM.getFilename(Loc));
1438 if (!FileStyle.isActive())
1439 return std::nullopt;
1440
1441 return getFailureInfo(HungarianNotation.getDeclTypeName(Decl),
1442 Decl->getName(), Decl, Loc, FileStyle.getStyles(),
1443 FileStyle.getHNOption(),
1444 findStyleKind(Decl, FileStyle.getStyles(),
1445 FileStyle.isIgnoringMainLikeFunction()),
1446 SM, IgnoreFailedSplit);
1447}
1448
1449std::optional<RenamerClangTidyCheck::FailureInfo>
1450IdentifierNamingCheck::getMacroFailureInfo(const Token &MacroNameTok,
1451 const SourceManager &SM) const {
1452 SourceLocation Loc = MacroNameTok.getLocation();
1453 const FileStyle &Style = getStyleForFile(SM.getFilename(Loc));
1454 if (!Style.isActive())
1455 return std::nullopt;
1456
1457 return getFailureInfo("", MacroNameTok.getIdentifierInfo()->getName(),
1458 nullptr, Loc, Style.getStyles(), Style.getHNOption(),
1459 SK_MacroDefinition, SM, IgnoreFailedSplit);
1460}
1461
1462RenamerClangTidyCheck::DiagInfo
1463IdentifierNamingCheck::getDiagInfo(const NamingCheckId &ID,
1464 const NamingCheckFailure &Failure) const {
1465 return DiagInfo{"invalid case style for %0 '%1'",
1466 [&](DiagnosticBuilder &Diag) {
1467 Diag << Failure.Info.KindName << ID.second;
1468 }};
1469}
1470
1471const IdentifierNamingCheck::FileStyle &
1472IdentifierNamingCheck::getStyleForFile(StringRef FileName) const {
1473 if (!GetConfigPerFile)
1474 return *MainFileStyle;
1475 StringRef Parent = llvm::sys::path::parent_path(FileName);
1476 auto Iter = NamingStylesCache.find(Parent);
1477 if (Iter != NamingStylesCache.end())
1478 return Iter->getValue();
1479
1480 llvm::StringRef CheckName = getID();
1481 ClangTidyOptions Options = Context->getOptionsForFile(FileName);
1482 if (Options.Checks && GlobList(*Options.Checks).contains(CheckName)) {
1483 auto It = NamingStylesCache.try_emplace(
1484 Parent,
1485 getFileStyleFromOptions({CheckName, Options.CheckOptions, Context}));
1486 assert(It.second);
1487 return It.first->getValue();
1488 }
1489 // Default construction gives an empty style.
1490 auto It = NamingStylesCache.try_emplace(Parent);
1491 assert(It.second);
1492 return It.first->getValue();
1493}
1494
1495} // namespace readability
1496} // namespace clang::tidy
std::string Suffix
Definition: AddUsing.cpp:132
const FunctionDecl * Decl
const Node * Parent
std::string Word
NodeType Type
llvm::StringRef Name
#define HUNGARIAN_NOTATION_PRIMITIVE_TYPES(m)
#define ENUMERATE(v)
#define HUNGARIAN_NOTATION_USER_DEFINED_TYPES(m)
#define NAMING_KEYS(m)
#define STRINGIZE(v)
StringRef FileName
SourceLocation Loc
size_t Pos
Provides access to the ClangTidyCheck options via check-local names.
std::optional< StringRef > get(StringRef LocalName) const
Read a named option from the Context.
void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const
Stores an option with the check-local name LocalName with string value Value to Options.
StringRef getID() const override
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
ClangTidyOptions getOptionsForFile(StringRef File) const
Returns options for File.
Base class for clang-tidy checks that want to flag declarations and/or macros for renaming based on c...
std::pair< SourceLocation, StringRef > NamingCheckId
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Derived classes that override this function should call this method from the overridden method.
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
StyleKind findStyleKind(const NamedDecl *D, ArrayRef< std::optional< IdentifierNamingCheck::NamingStyle > > NamingStyles, bool IgnoreMainLikeFunctions) 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
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
static StringRef const StyleNames[]
static StringRef const HungarainNotationPrimitiveTypes[]
static StringRef const HungarainNotationUserDefinedTypes[]
llvm::StringMap< ClangTidyValue > OptionMap
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.
ArrayRef< std::optional< NamingStyle > > getStyles() const
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