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"
26#define DEBUG_TYPE "clang-tidy"
35 std::pair<readability::IdentifierNamingCheck::CaseType, StringRef>>
51 "Leading_upper_snake_case"}};
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"}};
71namespace readability {
74#define NAMING_KEYS(m) \
78 m(ScopedEnumConstant) \
79 m(ConstexprVariable) \
88 m(GlobalConstantPointer) \
92 m(LocalConstantPointer) \
99 m(ConstantParameter) \
102 m(PointerParameter) \
103 m(ConstantPointerParameter) \
110 m(ConstexprFunction) \
120 m(TypeTemplateParameter) \
121 m(ValueTemplateParameter) \
122 m(TemplateTemplateParameter) \
123 m(TemplateParameter) \
129#define ENUMERATE(v) SK_ ## v,
137#define STRINGIZE(v) #v,
142#define HUNGARIAN_NOTATION_PRIMITIVE_TYPES(m) \
166 m(signed-short-int) \
167 m(signed-long-long-int) \
168 m(signed-long-long) \
172 m(unsigned-long-long-int) \
173 m(unsigned-long-long) \
174 m(unsigned-long-int) \
176 m(unsigned-short-int) \
190#define STRINGIZE(v) #v,
195#define HUNGARIAN_NOTATION_USER_DEFINED_TYPES(m) \
226#define STRINGIZE(v) #v,
236 std::optional<IdentifierNamingCheck::CaseType> Case, StringRef Prefix,
237 StringRef
Suffix, StringRef IgnoredRegexpStr, HungarianPrefixType HPType)
239 IgnoredRegexpStr(IgnoredRegexpStr), HPType(HPType) {
240 if (!IgnoredRegexpStr.empty()) {
242 llvm::Regex(llvm::SmallString<128>({
"^", IgnoredRegexpStr,
"$"}));
243 if (!IgnoredRegexp.isValid())
244 llvm::errs() <<
"Invalid IgnoredRegexp regular expression: "
256 SmallVector<std::optional<IdentifierNamingCheck::NamingStyle>, 0> Styles;
258 SmallString<64> StyleString;
259 for (
unsigned I = 0; I <
SK_Count; ++I) {
261 StyleString.assign({
StyleNames[I],
"HungarianPrefix"});
266 configurationDiag(
"invalid identifier naming option '%0'") << StyleString;
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));
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 =
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));
287 bool IgnoreMainLike = Options.
get(
"IgnoreMainLikeFunctions",
false);
288 return {std::move(Styles), std::move(HNOption), IgnoreMainLike};
291std::string IdentifierNamingCheck::HungarianNotation::getDeclTypeName(
292 const NamedDecl *ND)
const {
293 const auto *VD = dyn_cast<ValueDecl>(ND);
297 if (isa<FunctionDecl, EnumConstantDecl>(ND))
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;
310 const char *EOL = strchr(Begin,
'\n');
312 EOL = Begin + strlen(Begin);
314 const char *PosList[] = {strchr(Begin,
'='), strchr(Begin,
';'),
315 strchr(Begin,
','), strchr(Begin,
')'), EOL};
316 for (
const auto &
Pos : PosList) {
318 EOL = std::min(EOL,
Pos);
321 StrLen = EOL - Begin;
322 std::string TypeName;
324 std::string
Type(Begin, StrLen);
326 static constexpr StringRef Keywords[] = {
328 "constexpr",
"constinit",
"consteval",
330 "const",
"volatile",
"restrict",
"mutable",
332 "register",
"static",
"extern",
"thread_local",
337 for (StringRef Kw : Keywords) {
339 (
Pos =
Type.find(Kw.data(),
Pos)) != std::string::npos;) {
340 Type.replace(
Pos, Kw.size(),
"");
343 TypeName =
Type.erase(0,
Type.find_first_not_of(
' '));
346 const size_t Pos =
Type.find(
'<');
347 if (
Pos != std::string::npos) {
352 for (
size_t Pos = 0; (
Pos =
Type.find(
" ",
Pos)) != std::string::npos;
353 Pos += strlen(
" ")) {
354 Type.replace(
Pos, strlen(
" "),
" ");
358 for (
size_t Pos = 0; (
Pos =
Type.find(
" &",
Pos)) != std::string::npos;
359 Pos += strlen(
"&")) {
360 Type.replace(
Pos, strlen(
" &"),
"&");
364 for (
size_t Pos = 0; (
Pos =
Type.find(
" *",
Pos)) != std::string::npos;
365 Pos += strlen(
"*")) {
366 Type.replace(
Pos, strlen(
" *"),
"* ");
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);
378 RedundantRemoved =
true;
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)
390 TypeName =
Type.erase(0,
Type.find_first_not_of(
' '));
392 QualType QT = VD->getType();
393 if (!QT.isNull() && QT->isArrayType())
394 TypeName.append(
"[]");
400IdentifierNamingCheck::IdentifierNamingCheck(StringRef
Name,
403 GetConfigPerFile(Options.get(
"GetConfigPerFile", true)),
404 IgnoreFailedSplit(Options.get(
"IgnoreFailedSplit", false)) {
406 auto IterAndInserted = NamingStylesCache.try_emplace(
407 llvm::sys::path::parent_path(Context->getCurrentFile()),
409 assert(IterAndInserted.second &&
"Couldn't insert Style");
412 MainFileStyle = &IterAndInserted.first->getValue();
418 int StyleKindIndex)
const {
419 if ((StyleKindIndex >= SK_EnumConstant) &&
420 (StyleKindIndex <= SK_ConstantParameter))
423 if ((StyleKindIndex >= SK_Parameter) && (StyleKindIndex <= SK_Enum))
430 StringRef OptionKey,
const llvm::StringMap<std::string> &StrMap)
const {
431 if (OptionKey.empty())
434 auto Iter = StrMap.find(OptionKey);
435 if (Iter == StrMap.end())
438 return *llvm::yaml::parseBool(Iter->getValue());
445 static constexpr StringRef HNOpts[] = {
"TreatStructAsClass"};
446 static constexpr StringRef HNDerivedTypes[] = {
"Array",
"Pointer",
449 StringRef Section =
"HungarianNotation.";
451 SmallString<128> Buffer = {Section,
"General."};
452 size_t DefSize = Buffer.size();
453 for (
const auto &Opt : HNOpts) {
454 Buffer.truncate(DefSize);
458 HNOption.
General[Opt] = Val.str();
461 Buffer = {Section,
"DerivedType."};
462 DefSize = Buffer.size();
463 for (
const auto &
Type : HNDerivedTypes) {
464 Buffer.truncate(DefSize);
471 static constexpr std::pair<StringRef, StringRef> HNCStrings[] = {
472 {
"CharPointer",
"char*"},
473 {
"CharArray",
"char[]"},
474 {
"WideCharPointer",
"wchar_t*"},
475 {
"WideCharArray",
"wchar_t[]"}};
477 Buffer = {Section,
"CString."};
478 DefSize = Buffer.size();
479 for (
const auto &CStr : HNCStrings) {
480 Buffer.truncate(DefSize);
481 Buffer.append(CStr.first);
484 HNOption.
CString[CStr.second] = Val.str();
487 Buffer = {Section,
"PrimitiveType."};
488 DefSize = Buffer.size();
490 Buffer.truncate(DefSize);
491 Buffer.append(PrimType);
494 std::string
Type = PrimType.str();
495 std::replace(
Type.begin(),
Type.end(),
'-',
' ');
500 Buffer = {Section,
"UserDefinedType."};
501 DefSize = Buffer.size();
503 Buffer.truncate(DefSize);
516 const auto *ND = dyn_cast<NamedDecl>(D);
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);
535 SmallVector<StringRef, 8> &Words,
537 if (Words.size() <= 1)
540 std::string CorrectName = Words[0].str();
541 std::vector<llvm::StringMap<std::string>> MapList = {
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);
558 StringRef TypeName,
const NamedDecl *ND,
560 if (!ND || TypeName.empty())
561 return TypeName.str();
563 std::string ModifiedTypeName(TypeName);
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());
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();
589 if (PrefixStr.empty())
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);
599 size_t PtrCount = getAsteriskCount(ModifiedTypeName);
601 ModifiedTypeName = [&](std::string Str, StringRef From, StringRef To) {
603 while ((StartPos = Str.find(From.data(), StartPos)) !=
605 Str.replace(StartPos, From.size(), To.data());
606 StartPos += To.size();
609 }(ModifiedTypeName,
"*",
"");
613 if (PrefixStr.empty()) {
615 if (ModifiedTypeName ==
Type.getKey()) {
616 PrefixStr =
Type.getValue();
623 if (PrefixStr.empty()) {
625 if (ModifiedTypeName ==
Type.getKey()) {
626 PrefixStr =
Type.getValue();
632 for (
size_t Idx = 0; Idx < PtrCount; Idx++)
633 PrefixStr.insert(0, HNOption.
DerivedType.lookup(
"Pointer"));
639 const CXXRecordDecl *CRD,
645 if (CRD->isStruct() &&
646 !isOptionEnabled(
"TreatStructAsClass", HNOption.
General))
649 return CRD->isAbstract() ?
"I" :
"C";
653 const EnumConstantDecl *ECD)
const {
654 const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
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"));
662 static llvm::Regex Splitter(
663 "([a-z0-9A-Z]*)(_+)|([A-Z]?[a-z0-9]+)([A-Z]|$)|([A-Z]+)([A-Z]|$)");
665 StringRef EnumName(
Name);
666 SmallVector<StringRef, 8> Substrs;
667 EnumName.split(Substrs,
"_", -1,
false);
669 SmallVector<StringRef, 8> Words;
670 SmallVector<StringRef, 8> Groups;
671 for (
auto Substr : Substrs) {
672 while (!Substr.empty()) {
674 if (!Splitter.match(Substr, &Groups))
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());
691 for (StringRef
Word : Words)
692 Initial += tolower(
Word[0]);
698 const std::string &TypeName)
const {
699 size_t Pos = TypeName.find(
'*');
701 for (;
Pos < TypeName.length();
Pos++, Count++) {
702 if (
'*' != TypeName[
Pos])
709 const std::string &TypeName,
const NamedDecl *ND)
const {
711 if (
const auto *TD = dyn_cast<ValueDecl>(ND)) {
712 QualType QT = TD->getType();
713 if (QT->isPointerType())
714 PtrCount = getAsteriskCount(TypeName);
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);
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);
735 static constexpr std::pair<StringRef, StringRef> CStrings[] = {
739 {
"wchar_t[]",
"wsz"}};
740 for (
const auto &CStr : CStrings)
741 HNOption.
CString.try_emplace(CStr.first, CStr.second);
744 static constexpr std::pair<StringRef, StringRef> PrimitiveTypes[] = {
750 {
"uint16_t",
"u16" },
751 {
"uint32_t",
"u32" },
752 {
"uint64_t",
"u64" },
754 {
"char16_t",
"c16" },
755 {
"char32_t",
"c32" },
764 {
"short int",
"si" },
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" },
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" },
783 {
"long long int",
"lli" },
784 {
"long double",
"ld" },
785 {
"long long",
"ll" },
791 for (
const auto &PT : PrimitiveTypes)
795 static constexpr std::pair<StringRef, StringRef> UserDefinedTypes[] = {
812 {
"ULONGLONG",
"ull" },
826 for (
const auto &UDT : UserDefinedTypes)
832 SmallString<64> StyleString;
833 ArrayRef<std::optional<NamingStyle>> Styles = MainFileStyle->
getStyles();
834 for (
size_t I = 0; I <
SK_Count; ++I) {
838 StyleString.assign({
StyleNames[I],
"HungarianPrefix"});
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);
849 memcpy(&StyleString[StyleSize],
"Suf", 3);
851 if (Styles[I]->Case) {
852 memcpy(&StyleString[StyleSize],
"Case", 4);
853 StyleString.pop_back_n(2);
857 Options.
store(Opts,
"GetConfigPerFile", GetConfigPerFile);
858 Options.
store(Opts,
"IgnoreFailedSplit", IgnoreFailedSplit);
867 const NamedDecl *
Decl)
const {
868 static llvm::Regex Matchers[] = {
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])*$"),
879 if (!
Name.consume_front(Style.Prefix))
881 if (!
Name.consume_back(Style.Suffix))
885 if (!
Name.consume_front(HNPrefix))
891 if (
Name.startswith(
"_") ||
Name.endswith(
"_"))
894 if (Style.Case && !Matchers[
static_cast<size_t>(*Style.Case)].match(
Name))
905 static llvm::Regex Splitter(
906 "([a-z0-9A-Z]*)(_+)|([A-Z]?[a-z0-9]+)([A-Z]|$)|([A-Z]+)([A-Z]|$)");
908 SmallVector<StringRef, 8> Substrs;
909 Name.split(Substrs,
"_", -1,
false);
911 SmallVector<StringRef, 8> Words;
912 SmallVector<StringRef, 8> Groups;
913 for (
auto Substr : Substrs) {
914 while (!Substr.empty()) {
916 if (!Splitter.match(Substr, &Groups))
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());
939 SmallString<128> Fixup;
946 for (
auto const &
Word : Words) {
947 if (&
Word != &Words.front())
949 Fixup +=
Word.lower();
954 for (
auto const &
Word : Words) {
955 if (&
Word != &Words.front())
957 Fixup +=
Word.upper();
962 for (
auto const &
Word : Words) {
963 Fixup += toupper(
Word.front());
964 Fixup +=
Word.substr(1).lower();
969 for (
auto const &
Word : Words) {
970 if (&
Word == &Words.front()) {
971 Fixup +=
Word.lower();
973 Fixup += toupper(
Word.front());
974 Fixup +=
Word.substr(1).lower();
980 for (
auto const &
Word : Words) {
981 if (&
Word != &Words.front())
983 Fixup += toupper(
Word.front());
984 Fixup +=
Word.substr(1).lower();
989 for (
auto const &
Word : Words) {
990 if (&
Word != &Words.front()) {
992 Fixup += toupper(
Word.front());
994 Fixup += tolower(
Word.front());
996 Fixup +=
Word.substr(1).lower();
1001 for (
auto const &
Word : Words) {
1002 if (&
Word != &Words.front()) {
1004 Fixup +=
Word.lower();
1006 Fixup += toupper(
Word.front());
1007 Fixup +=
Word.substr(1).lower();
1013 return Fixup.str().str();
1017 const ParmVarDecl &ParmDecl,
bool IncludeMainLike)
const {
1019 dyn_cast_or_null<FunctionDecl>(ParmDecl.getParentFunctionOrMethod());
1022 if (FDecl->isMain())
1024 if (!IncludeMainLike)
1026 if (FDecl->getAccess() != AS_public && FDecl->getAccess() != AS_none)
1030 if (!FDecl->getDeclName().isIdentifier())
1032 enum MainType { None, Main, WMain };
1033 auto IsCharPtrPtr = [](QualType QType) -> MainType {
1036 if (QType = QType->getPointeeType(), QType.isNull())
1038 if (QType = QType->getPointeeType(), QType.isNull())
1040 if (QType->isCharType())
1042 if (QType->isWideCharType())
1046 auto IsIntType = [](QualType QType) {
1049 if (
const auto *Builtin =
1050 dyn_cast<BuiltinType>(QType->getUnqualifiedDesugaredType())) {
1051 return Builtin->getKind() == BuiltinType::Int;
1055 if (!IsIntType(FDecl->getReturnType()))
1057 if (FDecl->getNumParams() < 2 || FDecl->getNumParams() > 3)
1059 if (!IsIntType(FDecl->parameters()[0]->getType()))
1061 MainType
Type = IsCharPtrPtr(FDecl->parameters()[1]->getType());
1064 if (FDecl->getNumParams() == 3 &&
1065 IsCharPtrPtr(FDecl->parameters()[2]->getType()) !=
Type)
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());
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());
1084 const Decl *D)
const {
1085 Name.consume_front(Style.Prefix);
1086 Name.consume_back(Style.Suffix);
1091 std::string HungarianPrefix;
1095 if (!HungarianPrefix.empty()) {
1097 HungarianPrefix +=
"_";
1100 Fixed[0] = toupper(Fixed[0]);
1103 StringRef Mid = StringRef(Fixed).trim(
"_");
1107 return (Style.Prefix + HungarianPrefix + Mid + Style.Suffix).str();
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.");
1117 if (isa<ObjCIvarDecl>(D) && NamingStyles[SK_ObjcIvar])
1120 if (isa<TypedefDecl>(D) && NamingStyles[SK_Typedef])
1123 if (isa<TypeAliasDecl>(D) && NamingStyles[SK_TypeAlias])
1124 return SK_TypeAlias;
1126 if (
const auto *
Decl = dyn_cast<NamespaceDecl>(D)) {
1127 if (
Decl->isAnonymousNamespace())
1130 if (
Decl->isInline() && NamingStyles[SK_InlineNamespace])
1131 return SK_InlineNamespace;
1133 if (NamingStyles[SK_Namespace])
1134 return SK_Namespace;
1137 if (isa<EnumDecl>(D) && NamingStyles[SK_Enum])
1140 if (
const auto *EnumConst = dyn_cast<EnumConstantDecl>(D)) {
1141 if (cast<EnumDecl>(EnumConst->getDeclContext())->isScoped() &&
1142 NamingStyles[SK_ScopedEnumConstant])
1143 return SK_ScopedEnumConstant;
1145 if (NamingStyles[SK_EnumConstant])
1146 return SK_EnumConstant;
1148 if (NamingStyles[SK_Constant])
1154 if (
const auto *
Decl = dyn_cast<RecordDecl>(D)) {
1155 if (
Decl->isAnonymousStructOrUnion())
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;
1164 if (Definition->isStruct() && NamingStyles[SK_Struct])
1167 if (Definition->isStruct() && NamingStyles[SK_Class])
1170 if (Definition->isClass() && NamingStyles[SK_Class])
1173 if (Definition->isClass() && NamingStyles[SK_Struct])
1176 if (Definition->isUnion() && NamingStyles[SK_Union])
1179 if (Definition->isEnum() && NamingStyles[SK_Enum])
1186 if (
const auto *
Decl = dyn_cast<FieldDecl>(D)) {
1189 if (!
Type.isNull() &&
Type.isConstQualified()) {
1190 if (NamingStyles[SK_ConstantMember])
1191 return SK_ConstantMember;
1193 if (NamingStyles[SK_Constant])
1197 if (
Decl->getAccess() == AS_private && NamingStyles[SK_PrivateMember])
1198 return SK_PrivateMember;
1200 if (
Decl->getAccess() == AS_protected && NamingStyles[SK_ProtectedMember])
1201 return SK_ProtectedMember;
1203 if (
Decl->getAccess() == AS_public && NamingStyles[SK_PublicMember])
1204 return SK_PublicMember;
1206 if (NamingStyles[SK_Member])
1212 if (
const auto *
Decl = dyn_cast<ParmVarDecl>(D)) {
1217 if (
Decl->isConstexpr() && NamingStyles[SK_ConstexprVariable])
1218 return SK_ConstexprVariable;
1220 if (!
Type.isNull() &&
Type.isConstQualified()) {
1221 if (
Type.getTypePtr()->isAnyPointerType() &&
1222 NamingStyles[SK_ConstantPointerParameter])
1223 return SK_ConstantPointerParameter;
1225 if (NamingStyles[SK_ConstantParameter])
1226 return SK_ConstantParameter;
1228 if (NamingStyles[SK_Constant])
1232 if (
Decl->isParameterPack() && NamingStyles[SK_ParameterPack])
1233 return SK_ParameterPack;
1235 if (!
Type.isNull() &&
Type.getTypePtr()->isAnyPointerType() &&
1236 NamingStyles[SK_PointerParameter])
1237 return SK_PointerParameter;
1239 if (NamingStyles[SK_Parameter])
1240 return SK_Parameter;
1245 if (
const auto *
Decl = dyn_cast<VarDecl>(D)) {
1248 if (
Decl->isConstexpr() && NamingStyles[SK_ConstexprVariable])
1249 return SK_ConstexprVariable;
1251 if (!
Type.isNull() &&
Type.isConstQualified()) {
1252 if (
Decl->isStaticDataMember() && NamingStyles[SK_ClassConstant])
1253 return SK_ClassConstant;
1255 if (
Decl->isFileVarDecl() &&
Type.getTypePtr()->isAnyPointerType() &&
1256 NamingStyles[SK_GlobalConstantPointer])
1257 return SK_GlobalConstantPointer;
1259 if (
Decl->isFileVarDecl() && NamingStyles[SK_GlobalConstant])
1260 return SK_GlobalConstant;
1262 if (
Decl->isStaticLocal() && NamingStyles[SK_StaticConstant])
1263 return SK_StaticConstant;
1265 if (
Decl->isLocalVarDecl() &&
Type.getTypePtr()->isAnyPointerType() &&
1266 NamingStyles[SK_LocalConstantPointer])
1267 return SK_LocalConstantPointer;
1269 if (
Decl->isLocalVarDecl() && NamingStyles[SK_LocalConstant])
1270 return SK_LocalConstant;
1272 if (
Decl->isFunctionOrMethodVarDecl() && NamingStyles[SK_LocalConstant])
1273 return SK_LocalConstant;
1275 if (NamingStyles[SK_Constant])
1279 if (
Decl->isStaticDataMember() && NamingStyles[SK_ClassMember])
1280 return SK_ClassMember;
1282 if (
Decl->isFileVarDecl() &&
Type.getTypePtr()->isAnyPointerType() &&
1283 NamingStyles[SK_GlobalPointer])
1284 return SK_GlobalPointer;
1286 if (
Decl->isFileVarDecl() && NamingStyles[SK_GlobalVariable])
1287 return SK_GlobalVariable;
1289 if (
Decl->isStaticLocal() && NamingStyles[SK_StaticVariable])
1290 return SK_StaticVariable;
1292 if (
Decl->isLocalVarDecl() &&
Type.getTypePtr()->isAnyPointerType() &&
1293 NamingStyles[SK_LocalPointer])
1294 return SK_LocalPointer;
1296 if (
Decl->isLocalVarDecl() && NamingStyles[SK_LocalVariable])
1297 return SK_LocalVariable;
1299 if (
Decl->isFunctionOrMethodVarDecl() && NamingStyles[SK_LocalVariable])
1300 return SK_LocalVariable;
1302 if (NamingStyles[SK_Variable])
1308 if (
const auto *
Decl = dyn_cast<CXXMethodDecl>(D)) {
1309 if (
Decl->isMain() || !
Decl->isUserProvided() ||
1310 Decl->size_overridden_methods() > 0 ||
Decl->hasAttr<OverrideAttr>())
1315 for (
const CXXBaseSpecifier &Base :
Decl->getParent()->bases())
1316 if (
const auto *RD = Base.getType()->getAsCXXRecordDecl())
1317 if (RD->hasMemberName(
Decl->getDeclName()))
1320 if (
Decl->isConstexpr() && NamingStyles[SK_ConstexprMethod])
1321 return SK_ConstexprMethod;
1323 if (
Decl->isConstexpr() && NamingStyles[SK_ConstexprFunction])
1324 return SK_ConstexprFunction;
1326 if (
Decl->isStatic() && NamingStyles[SK_ClassMethod])
1327 return SK_ClassMethod;
1329 if (
Decl->isVirtual() && NamingStyles[SK_VirtualMethod])
1330 return SK_VirtualMethod;
1332 if (
Decl->getAccess() == AS_private && NamingStyles[SK_PrivateMethod])
1333 return SK_PrivateMethod;
1335 if (
Decl->getAccess() == AS_protected && NamingStyles[SK_ProtectedMethod])
1336 return SK_ProtectedMethod;
1338 if (
Decl->getAccess() == AS_public && NamingStyles[SK_PublicMethod])
1339 return SK_PublicMethod;
1341 if (NamingStyles[SK_Method])
1344 if (NamingStyles[SK_Function])
1350 if (
const auto *
Decl = dyn_cast<FunctionDecl>(D)) {
1354 if (
Decl->isConstexpr() && NamingStyles[SK_ConstexprFunction])
1355 return SK_ConstexprFunction;
1357 if (
Decl->isGlobal() && NamingStyles[SK_GlobalFunction])
1358 return SK_GlobalFunction;
1360 if (NamingStyles[SK_Function])
1364 if (isa<TemplateTypeParmDecl>(D)) {
1365 if (NamingStyles[SK_TypeTemplateParameter])
1366 return SK_TypeTemplateParameter;
1368 if (NamingStyles[SK_TemplateParameter])
1369 return SK_TemplateParameter;
1374 if (isa<NonTypeTemplateParmDecl>(D)) {
1375 if (NamingStyles[SK_ValueTemplateParameter])
1376 return SK_ValueTemplateParameter;
1378 if (NamingStyles[SK_TemplateParameter])
1379 return SK_TemplateParameter;
1384 if (isa<TemplateTemplateParmDecl>(D)) {
1385 if (NamingStyles[SK_TemplateTemplateParameter])
1386 return SK_TemplateTemplateParameter;
1388 if (NamingStyles[SK_TemplateParameter])
1389 return SK_TemplateParameter;
1397std::optional<RenamerClangTidyCheck::FailureInfo>
1399 StringRef
Type, StringRef
Name,
const NamedDecl *ND,
1401 ArrayRef<std::optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
1403 StyleKind SK,
const SourceManager &SM,
bool IgnoreFailedSplit)
const {
1405 return std::nullopt;
1408 if (Style.IgnoredRegexp.isValid() && Style.IgnoredRegexp.match(
Name))
1409 return std::nullopt;
1412 return std::nullopt;
1414 std::string KindName =
1417 std::replace(KindName.begin(), KindName.end(),
'_',
' ');
1420 if (StringRef(Fixup).equals(
Name)) {
1421 if (!IgnoreFailedSplit) {
1422 LLVM_DEBUG(
Location.print(llvm::dbgs(), SM);
1424 << llvm::formatv(
": unable to split words for {0} '{1}'\n",
1427 return std::nullopt;
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;
1442 Decl->getName(),
Decl,
Loc, FileStyle.getStyles(),
1443 FileStyle.getHNOption(),
1445 FileStyle.isIgnoringMainLikeFunction()),
1446 SM, IgnoreFailedSplit);
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;
1457 return getFailureInfo(
"", MacroNameTok.getIdentifierInfo()->getName(),
1458 nullptr,
Loc, Style.getStyles(), Style.getHNOption(),
1459 SK_MacroDefinition, SM, IgnoreFailedSplit);
1462RenamerClangTidyCheck::DiagInfo
1464 const NamingCheckFailure &Failure)
const {
1465 return DiagInfo{
"invalid case style for %0 '%1'",
1466 [&](DiagnosticBuilder &Diag) {
1467 Diag << Failure.Info.KindName <<
ID.second;
1471const IdentifierNamingCheck::FileStyle &
1472IdentifierNamingCheck::getStyleForFile(StringRef
FileName)
const {
1473 if (!GetConfigPerFile)
1474 return *MainFileStyle;
1476 auto Iter = NamingStylesCache.find(
Parent);
1477 if (Iter != NamingStylesCache.end())
1478 return Iter->getValue();
1480 llvm::StringRef CheckName =
getID();
1482 if (
Options.Checks && GlobList(*
Options.Checks).contains(CheckName)) {
1483 auto It = NamingStylesCache.try_emplace(
1487 return It.first->getValue();
1490 auto It = NamingStylesCache.try_emplace(
Parent);
1492 return It.first->getValue();
const FunctionDecl * Decl
#define HUNGARIAN_NOTATION_PRIMITIVE_TYPES(m)
#define HUNGARIAN_NOTATION_USER_DEFINED_TYPES(m)
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
@ CT_LeadingUpperSnakeCase
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.
bool isIgnoringMainLikeFunction() const
ArrayRef< std::optional< NamingStyle > > getStyles() const
llvm::StringMap< std::string > UserDefinedType
llvm::StringMap< std::string > DerivedType
llvm::StringMap< std::string > CString
llvm::StringMap< std::string > General
llvm::StringMap< std::string > PrimitiveType
std::string getDeclTypeName(const NamedDecl *ND) 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 getEnumPrefix(const EnumConstantDecl *ECD) const
std::string getClassPrefix(const CXXRecordDecl *CRD, const IdentifierNamingCheck::HungarianNotationOption &HNOption) const
bool checkOptionValid(int StyleKindIndex) const
std::string getPrefix(const Decl *D, const IdentifierNamingCheck::HungarianNotationOption &HNOption) const
size_t getAsteriskCount(const std::string &TypeName) const
std::string getDataTypePrefix(StringRef TypeName, const NamedDecl *ND, const IdentifierNamingCheck::HungarianNotationOption &HNOption) const