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/Support/Debug.h"
18#include "llvm/Support/Error.h"
19#include "llvm/Support/FormatVariadic.h"
20#include "llvm/Support/Path.h"
21#include "llvm/Support/Regex.h"
22#include "llvm/Support/YAMLParser.h"
25#define DEBUG_TYPE "clang-tidy"
34 std::pair<readability::IdentifierNamingCheck::CaseType, StringRef>>
49 return llvm::ArrayRef(Mapping);
54 readability::IdentifierNamingCheck::HungarianPrefixType> {
57 static llvm::ArrayRef<std::pair<HungarianPrefixType, StringRef>>
59 static constexpr std::pair<HungarianPrefixType, StringRef> Mapping[] = {
60 {HungarianPrefixType::HPT_Off,
"Off"},
61 {HungarianPrefixType::HPT_On,
"On"},
62 {HungarianPrefixType::HPT_LowerCase,
"LowerCase"},
63 {HungarianPrefixType::HPT_CamelCase,
"CamelCase"}};
64 return llvm::ArrayRef(Mapping);
68namespace readability {
71#define NAMING_KEYS(m) \
75 m(ScopedEnumConstant) \
76 m(ConstexprVariable) \
85 m(GlobalConstantPointer) \
89 m(LocalConstantPointer) \
96 m(ConstantParameter) \
100 m(ConstantPointerParameter) \
107 m(ConstexprFunction) \
117 m(TypeTemplateParameter) \
118 m(ValueTemplateParameter) \
119 m(TemplateTemplateParameter) \
120 m(TemplateParameter) \
126#define ENUMERATE(v) SK_ ## v,
134#define STRINGIZE(v) #v,
139#define HUNGARIAN_NOTATION_PRIMITIVE_TYPES(m) \
163 m(signed-short-int) \
164 m(signed-long-long-int) \
165 m(signed-long-long) \
169 m(unsigned-long-long-int) \
170 m(unsigned-long-long) \
171 m(unsigned-long-int) \
173 m(unsigned-short-int) \
187#define STRINGIZE(v) #v,
192#define HUNGARIAN_NOTATION_USER_DEFINED_TYPES(m) \
223#define STRINGIZE(v) #v,
233 std::optional<IdentifierNamingCheck::CaseType> Case, StringRef Prefix,
234 StringRef
Suffix, StringRef IgnoredRegexpStr, HungarianPrefixType HPType)
236 IgnoredRegexpStr(IgnoredRegexpStr), HPType(HPType) {
237 if (!IgnoredRegexpStr.empty()) {
239 llvm::Regex(llvm::SmallString<128>({
"^", IgnoredRegexpStr,
"$"}));
240 if (!IgnoredRegexp.isValid())
241 llvm::errs() <<
"Invalid IgnoredRegexp regular expression: "
253 SmallVector<std::optional<IdentifierNamingCheck::NamingStyle>, 0> Styles;
255 SmallString<64> StyleString;
256 for (
unsigned I = 0; I <
SK_Count; ++I) {
258 StyleString.assign({
StyleNames[I],
"HungarianPrefix"});
263 configurationDiag(
"invalid identifier naming option '%0'") << StyleString;
265 memcpy(&StyleString[StyleSize],
"IgnoredRegexp", 13);
266 StyleString.truncate(StyleSize + 13);
267 std::optional<StringRef> IgnoredRegexpStr = Options.
get(StyleString);
268 memcpy(&StyleString[StyleSize],
"Prefix", 6);
269 StyleString.truncate(StyleSize + 6);
270 std::optional<StringRef> Prefix(Options.
get(StyleString));
272 memcpy(&StyleString[StyleSize],
"Suf", 3);
273 std::optional<StringRef> Postfix(Options.
get(StyleString));
274 memcpy(&StyleString[StyleSize],
"Case", 4);
275 StyleString.pop_back_n(2);
276 std::optional<CaseType> CaseOptional =
279 if (CaseOptional || Prefix || Postfix || IgnoredRegexpStr || HPTOpt)
280 Styles[I].emplace(std::move(CaseOptional), Prefix.value_or(
""),
281 Postfix.value_or(
""), IgnoredRegexpStr.value_or(
""),
282 HPTOpt.value_or(IdentifierNamingCheck::HPT_Off));
284 bool IgnoreMainLike = Options.
get(
"IgnoreMainLikeFunctions",
false);
285 return {std::move(Styles), std::move(HNOption), IgnoreMainLike};
288std::string IdentifierNamingCheck::HungarianNotation::getDeclTypeName(
289 const NamedDecl *ND)
const {
290 const auto *VD = dyn_cast<ValueDecl>(ND);
294 if (isa<FunctionDecl, EnumConstantDecl>(ND))
298 auto &SM = VD->getASTContext().getSourceManager();
299 const char *Begin = SM.getCharacterData(VD->getBeginLoc());
300 const char *End = SM.getCharacterData(VD->getEndLoc());
301 intptr_t StrLen = End - Begin;
307 const char *EOL = strchr(Begin,
'\n');
309 EOL = Begin + strlen(Begin);
311 const char *PosList[] = {strchr(Begin,
'='), strchr(Begin,
';'),
312 strchr(Begin,
','), strchr(Begin,
')'), EOL};
313 for (
const auto &
Pos : PosList) {
315 EOL = std::min(EOL,
Pos);
318 StrLen = EOL - Begin;
319 std::string TypeName;
321 std::string
Type(Begin, StrLen);
323 static constexpr StringRef Keywords[] = {
325 "constexpr",
"constinit",
"consteval",
327 "const",
"volatile",
"restrict",
"mutable",
329 "register",
"static",
"extern",
"thread_local",
334 for (StringRef Kw : Keywords) {
336 (
Pos =
Type.find(Kw.data(),
Pos)) != std::string::npos;) {
337 Type.replace(
Pos, Kw.size(),
"");
340 TypeName =
Type.erase(0,
Type.find_first_not_of(
" "));
343 for (
size_t Pos = 0; (
Pos =
Type.find(
" ",
Pos)) != std::string::npos;
344 Pos += strlen(
" ")) {
345 Type.replace(
Pos, strlen(
" "),
" ");
349 for (
size_t Pos = 0; (
Pos =
Type.find(
" &",
Pos)) != std::string::npos;
350 Pos += strlen(
"&")) {
351 Type.replace(
Pos, strlen(
" &"),
"&");
355 for (
size_t Pos = 0; (
Pos =
Type.find(
" *",
Pos)) != std::string::npos;
356 Pos += strlen(
"*")) {
357 Type.replace(
Pos, strlen(
" *"),
"* ");
361 static constexpr StringRef TailsOfMultiWordType[] = {
362 " int",
" char",
" double",
" long",
" short"};
363 bool RedundantRemoved =
false;
364 for (
auto Kw : TailsOfMultiWordType) {
365 size_t Pos =
Type.rfind(Kw.data());
366 if (
Pos != std::string::npos) {
368 RedundantRemoved =
true;
372 TypeName =
Type.erase(0,
Type.find_first_not_of(
" "));
373 if (!RedundantRemoved) {
374 std::size_t FoundSpace =
Type.find(
" ");
375 if (FoundSpace != std::string::npos)
379 TypeName =
Type.erase(0,
Type.find_first_not_of(
" "));
381 QualType QT = VD->getType();
382 if (!QT.isNull() && QT->isArrayType())
383 TypeName.append(
"[]");
389IdentifierNamingCheck::IdentifierNamingCheck(StringRef
Name,
392 GetConfigPerFile(Options.get(
"GetConfigPerFile", true)),
393 IgnoreFailedSplit(Options.get(
"IgnoreFailedSplit", false)) {
395 auto IterAndInserted = NamingStylesCache.try_emplace(
396 llvm::sys::path::parent_path(Context->getCurrentFile()),
398 assert(IterAndInserted.second &&
"Couldn't insert Style");
401 MainFileStyle = &IterAndInserted.first->getValue();
407 int StyleKindIndex)
const {
408 if ((StyleKindIndex >= SK_EnumConstant) &&
409 (StyleKindIndex <= SK_ConstantParameter))
412 if ((StyleKindIndex >= SK_Parameter) && (StyleKindIndex <= SK_Enum))
419 StringRef OptionKey,
const llvm::StringMap<std::string> &StrMap)
const {
420 if (OptionKey.empty())
423 auto Iter = StrMap.find(OptionKey);
424 if (Iter == StrMap.end())
427 return *llvm::yaml::parseBool(Iter->getValue());
434 static constexpr StringRef HNOpts[] = {
"TreatStructAsClass"};
435 static constexpr StringRef HNDerivedTypes[] = {
"Array",
"Pointer",
438 StringRef Section =
"HungarianNotation.";
440 SmallString<128> Buffer = {Section,
"General."};
441 size_t DefSize = Buffer.size();
442 for (
const auto &Opt : HNOpts) {
443 Buffer.truncate(DefSize);
447 HNOption.
General[Opt] = Val.str();
450 Buffer = {Section,
"DerivedType."};
451 DefSize = Buffer.size();
452 for (
const auto &
Type : HNDerivedTypes) {
453 Buffer.truncate(DefSize);
460 static constexpr std::pair<StringRef, StringRef> HNCStrings[] = {
461 {
"CharPointer",
"char*"},
462 {
"CharArray",
"char[]"},
463 {
"WideCharPointer",
"wchar_t*"},
464 {
"WideCharArray",
"wchar_t[]"}};
466 Buffer = {Section,
"CString."};
467 DefSize = Buffer.size();
468 for (
const auto &CStr : HNCStrings) {
469 Buffer.truncate(DefSize);
470 Buffer.append(CStr.first);
473 HNOption.
CString[CStr.second] = Val.str();
476 Buffer = {Section,
"PrimitiveType."};
477 DefSize = Buffer.size();
479 Buffer.truncate(DefSize);
480 Buffer.append(PrimType);
483 std::string
Type = PrimType.str();
484 std::replace(
Type.begin(),
Type.end(),
'-',
' ');
489 Buffer = {Section,
"UserDefinedType."};
490 DefSize = Buffer.size();
492 Buffer.truncate(DefSize);
505 const auto *ND = dyn_cast<NamedDecl>(D);
510 if (
const auto *ECD = dyn_cast<EnumConstantDecl>(ND)) {
511 Prefix = getEnumPrefix(ECD);
512 }
else if (
const auto *CRD = dyn_cast<CXXRecordDecl>(ND)) {
513 Prefix = getClassPrefix(CRD, HNOption);
514 }
else if (isa<VarDecl, FieldDecl, RecordDecl>(ND)) {
515 std::string TypeName = getDeclTypeName(ND);
516 if (!TypeName.empty())
517 Prefix = getDataTypePrefix(TypeName, ND, HNOption);
524 SmallVector<StringRef, 8> &Words,
526 if (Words.size() <= 1)
529 std::string CorrectName = Words[0].str();
530 std::vector<llvm::StringMap<std::string>> MapList = {
534 for (
const auto &Map : MapList) {
535 for (
const auto &Str : Map) {
536 if (Str.getValue() == CorrectName) {
537 Words.erase(Words.begin(), Words.begin() + 1);
547 StringRef TypeName,
const NamedDecl *ND,
549 if (!ND || TypeName.empty())
550 return TypeName.str();
552 std::string ModifiedTypeName(TypeName);
555 std::string PrefixStr;
556 if (
const auto *TD = dyn_cast<ValueDecl>(ND)) {
557 QualType QT = TD->getType();
558 if (QT->isFunctionPointerType()) {
559 PrefixStr = HNOption.
DerivedType.lookup(
"FunctionPointer");
560 }
else if (QT->isPointerType()) {
561 for (
const auto &CStr : HNOption.
CString) {
562 std::string Key = CStr.getKey().str();
563 if (ModifiedTypeName.find(Key) == 0) {
564 PrefixStr = CStr.getValue();
565 ModifiedTypeName = ModifiedTypeName.substr(
566 Key.size(), ModifiedTypeName.size() - Key.size());
570 }
else if (QT->isArrayType()) {
571 for (
const auto &CStr : HNOption.
CString) {
572 std::string Key = CStr.getKey().str();
573 if (ModifiedTypeName.find(Key) == 0) {
574 PrefixStr = CStr.getValue();
578 if (PrefixStr.empty())
580 }
else if (QT->isReferenceType()) {
581 size_t Pos = ModifiedTypeName.find_last_of(
"&");
582 if (
Pos != std::string::npos)
583 ModifiedTypeName = ModifiedTypeName.substr(0,
Pos);
588 size_t PtrCount = [&](std::string TypeName) ->
size_t {
589 size_t Pos = TypeName.find(
'*');
591 for (;
Pos < TypeName.length();
Pos++, Count++) {
592 if (
'*' != TypeName[
Pos])
598 ModifiedTypeName = [&](std::string Str, StringRef From, StringRef To) {
600 while ((StartPos = Str.find(From.data(), StartPos)) !=
602 Str.replace(StartPos, From.size(), To.data());
603 StartPos += To.size();
606 }(ModifiedTypeName,
"*",
"");
610 if (PrefixStr.empty()) {
612 if (ModifiedTypeName ==
Type.getKey()) {
613 PrefixStr =
Type.getValue();
620 if (PrefixStr.empty()) {
622 if (ModifiedTypeName ==
Type.getKey()) {
623 PrefixStr =
Type.getValue();
629 for (
size_t Idx = 0; Idx < PtrCount; Idx++)
630 PrefixStr.insert(0, HNOption.
DerivedType.lookup(
"Pointer"));
636 const CXXRecordDecl *CRD,
642 if (CRD->isStruct() &&
643 !isOptionEnabled(
"TreatStructAsClass", HNOption.
General))
646 return CRD->isAbstract() ?
"I" :
"C";
650 const EnumConstantDecl *ECD)
const {
651 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
653 std::string
Name = ED->getName().str();
654 if (std::string::npos !=
Name.find(
"enum")) {
655 Name =
Name.substr(strlen(
"enum"),
Name.length() - strlen(
"enum"));
659 static llvm::Regex Splitter(
660 "([a-z0-9A-Z]*)(_+)|([A-Z]?[a-z0-9]+)([A-Z]|$)|([A-Z]+)([A-Z]|$)");
662 StringRef EnumName(
Name);
663 SmallVector<StringRef, 8> Substrs;
664 EnumName.split(Substrs,
"_", -1,
false);
666 SmallVector<StringRef, 8> Words;
667 SmallVector<StringRef, 8> Groups;
668 for (
auto Substr : Substrs) {
669 while (!Substr.empty()) {
671 if (!Splitter.match(Substr, &Groups))
674 if (Groups[2].size() > 0) {
675 Words.push_back(Groups[1]);
676 Substr = Substr.substr(Groups[0].size());
677 }
else if (Groups[3].size() > 0) {
678 Words.push_back(Groups[3]);
679 Substr = Substr.substr(Groups[0].size() - Groups[4].size());
680 }
else if (Groups[5].size() > 0) {
681 Words.push_back(Groups[5]);
682 Substr = Substr.substr(Groups[0].size() - Groups[6].size());
688 for (StringRef
Word : Words)
689 Initial += tolower(
Word[0]);
698 static constexpr std::pair<StringRef, StringRef> General[] = {
699 {
"TreatStructAsClass",
"false"}};
700 for (
const auto &G : General)
701 HNOption.
General.try_emplace(G.first, G.second);
704 static constexpr std::pair<StringRef, StringRef> DerivedTypes[] = {
705 {
"Array",
"a"}, {
"Pointer",
"p"}, {
"FunctionPointer",
"fn"}};
706 for (
const auto &DT : DerivedTypes)
707 HNOption.
DerivedType.try_emplace(DT.first, DT.second);
710 static constexpr std::pair<StringRef, StringRef> CStrings[] = {
714 {
"wchar_t[]",
"wsz"}};
715 for (
const auto &CStr : CStrings)
716 HNOption.
CString.try_emplace(CStr.first, CStr.second);
719 static constexpr std::pair<StringRef, StringRef> PrimitiveTypes[] = {
725 {
"uint16_t",
"u16" },
726 {
"uint32_t",
"u32" },
727 {
"uint64_t",
"u64" },
729 {
"char16_t",
"c16" },
730 {
"char32_t",
"c32" },
739 {
"short int",
"si" },
741 {
"signed int",
"si" },
742 {
"signed short",
"ss" },
743 {
"signed short int",
"ssi" },
744 {
"signed long long int",
"slli"},
745 {
"signed long long",
"sll" },
746 {
"signed long int",
"sli" },
747 {
"signed long",
"sl" },
749 {
"unsigned long long int",
"ulli"},
750 {
"unsigned long long",
"ull" },
751 {
"unsigned long int",
"uli" },
752 {
"unsigned long",
"ul" },
753 {
"unsigned short int",
"usi" },
754 {
"unsigned short",
"us" },
755 {
"unsigned int",
"ui" },
756 {
"unsigned char",
"uc" },
758 {
"long long int",
"lli" },
759 {
"long double",
"ld" },
760 {
"long long",
"ll" },
766 for (
const auto &PT : PrimitiveTypes)
770 static constexpr std::pair<StringRef, StringRef> UserDefinedTypes[] = {
787 {
"ULONGLONG",
"ull" },
801 for (
const auto &UDT : UserDefinedTypes)
807 SmallString<64> StyleString;
808 ArrayRef<std::optional<NamingStyle>> Styles = MainFileStyle->
getStyles();
809 for (
size_t I = 0; I <
SK_Count; ++I) {
813 StyleString.assign({
StyleNames[I],
"HungarianPrefix"});
817 memcpy(&StyleString[StyleSize],
"IgnoredRegexp", 13);
818 StyleString.truncate(StyleSize + 13);
819 Options.
store(Opts, StyleString, Styles[I]->IgnoredRegexpStr);
820 memcpy(&StyleString[StyleSize],
"Prefix", 6);
821 StyleString.truncate(StyleSize + 6);
824 memcpy(&StyleString[StyleSize],
"Suf", 3);
826 if (Styles[I]->Case) {
827 memcpy(&StyleString[StyleSize],
"Case", 4);
828 StyleString.pop_back_n(2);
832 Options.
store(Opts,
"GetConfigPerFile", GetConfigPerFile);
833 Options.
store(Opts,
"IgnoreFailedSplit", IgnoreFailedSplit);
842 const NamedDecl *
Decl)
const {
843 static llvm::Regex Matchers[] = {
845 llvm::Regex(
"^[a-z][a-z0-9_]*$"),
846 llvm::Regex(
"^[a-z][a-zA-Z0-9]*$"),
847 llvm::Regex(
"^[A-Z][A-Z0-9_]*$"),
848 llvm::Regex(
"^[A-Z][a-zA-Z0-9]*$"),
849 llvm::Regex(
"^[A-Z]([a-z0-9]*(_[A-Z])?)*"),
850 llvm::Regex(
"^[a-z]([a-z0-9]*(_[A-Z])?)*"),
853 if (!
Name.consume_front(Style.Prefix))
855 if (!
Name.consume_back(Style.Suffix))
859 if (!
Name.consume_front(HNPrefix))
865 if (
Name.startswith(
"_") ||
Name.endswith(
"_"))
868 if (Style.Case && !Matchers[
static_cast<size_t>(*Style.Case)].match(
Name))
879 static llvm::Regex Splitter(
880 "([a-z0-9A-Z]*)(_+)|([A-Z]?[a-z0-9]+)([A-Z]|$)|([A-Z]+)([A-Z]|$)");
882 SmallVector<StringRef, 8> Substrs;
883 Name.split(Substrs,
"_", -1,
false);
885 SmallVector<StringRef, 8> Words;
886 SmallVector<StringRef, 8> Groups;
887 for (
auto Substr : Substrs) {
888 while (!Substr.empty()) {
890 if (!Splitter.match(Substr, &Groups))
893 if (Groups[2].size() > 0) {
894 Words.push_back(Groups[1]);
895 Substr = Substr.substr(Groups[0].size());
896 }
else if (Groups[3].size() > 0) {
897 Words.push_back(Groups[3]);
898 Substr = Substr.substr(Groups[0].size() - Groups[4].size());
899 }
else if (Groups[5].size() > 0) {
900 Words.push_back(Groups[5]);
901 Substr = Substr.substr(Groups[0].size() - Groups[6].size());
913 SmallString<128> Fixup;
920 for (
auto const &
Word : Words) {
921 if (&
Word != &Words.front())
923 Fixup +=
Word.lower();
928 for (
auto const &
Word : Words) {
929 if (&
Word != &Words.front())
931 Fixup +=
Word.upper();
936 for (
auto const &
Word : Words) {
937 Fixup += toupper(
Word.front());
938 Fixup +=
Word.substr(1).lower();
943 for (
auto const &
Word : Words) {
944 if (&
Word == &Words.front()) {
945 Fixup +=
Word.lower();
947 Fixup += toupper(
Word.front());
948 Fixup +=
Word.substr(1).lower();
954 for (
auto const &
Word : Words) {
955 if (&
Word != &Words.front())
957 Fixup += toupper(
Word.front());
958 Fixup +=
Word.substr(1).lower();
963 for (
auto const &
Word : Words) {
964 if (&
Word != &Words.front()) {
966 Fixup += toupper(
Word.front());
968 Fixup += tolower(
Word.front());
970 Fixup +=
Word.substr(1).lower();
975 return Fixup.str().str();
979 const ParmVarDecl &ParmDecl,
bool IncludeMainLike)
const {
981 dyn_cast_or_null<FunctionDecl>(ParmDecl.getParentFunctionOrMethod());
986 if (!IncludeMainLike)
988 if (FDecl->getAccess() != AS_public && FDecl->getAccess() != AS_none)
992 if (!FDecl->getDeclName().isIdentifier())
994 enum MainType { None, Main, WMain };
995 auto IsCharPtrPtr = [](QualType QType) -> MainType {
998 if (QType = QType->getPointeeType(), QType.isNull())
1000 if (QType = QType->getPointeeType(), QType.isNull())
1002 if (QType->isCharType())
1004 if (QType->isWideCharType())
1008 auto IsIntType = [](QualType QType) {
1011 if (
const auto *Builtin =
1012 dyn_cast<BuiltinType>(QType->getUnqualifiedDesugaredType())) {
1013 return Builtin->getKind() == BuiltinType::Int;
1017 if (!IsIntType(FDecl->getReturnType()))
1019 if (FDecl->getNumParams() < 2 || FDecl->getNumParams() > 3)
1021 if (!IsIntType(FDecl->parameters()[0]->getType()))
1023 MainType
Type = IsCharPtrPtr(FDecl->parameters()[1]->getType());
1026 if (FDecl->getNumParams() == 3 &&
1027 IsCharPtrPtr(FDecl->parameters()[2]->getType()) !=
Type)
1031 static llvm::Regex Matcher(
1032 "(^[Mm]ain([_A-Z]|$))|([a-z0-9_]Main([_A-Z]|$))|(_main(_|$))");
1033 assert(Matcher.isValid() &&
"Invalid Matcher for main like functions.");
1034 return Matcher.match(FDecl->getName());
1036 static llvm::Regex Matcher(
"(^((W[Mm])|(wm))ain([_A-Z]|$))|([a-z0-9_]W[Mm]"
1037 "ain([_A-Z]|$))|(_wmain(_|$))");
1038 assert(Matcher.isValid() &&
"Invalid Matcher for wmain like functions.");
1039 return Matcher.match(FDecl->getName());
1046 const Decl *D)
const {
1047 Name.consume_front(Style.Prefix);
1048 Name.consume_back(Style.Suffix);
1053 std::string HungarianPrefix;
1057 if (!HungarianPrefix.empty()) {
1059 HungarianPrefix +=
"_";
1062 Fixed[0] = toupper(Fixed[0]);
1065 StringRef Mid = StringRef(Fixed).trim(
"_");
1069 return (Style.Prefix + HungarianPrefix + Mid + Style.Suffix).str();
1074 ArrayRef<std::optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
1075 bool IgnoreMainLikeFunctions)
const {
1076 assert(D && D->getIdentifier() && !D->getName().empty() && !D->isImplicit() &&
1077 "Decl must be an explicit identifier with a name.");
1079 if (isa<ObjCIvarDecl>(D) && NamingStyles[SK_ObjcIvar])
1082 if (isa<TypedefDecl>(D) && NamingStyles[SK_Typedef])
1085 if (isa<TypeAliasDecl>(D) && NamingStyles[SK_TypeAlias])
1086 return SK_TypeAlias;
1088 if (
const auto *
Decl = dyn_cast<NamespaceDecl>(D)) {
1089 if (
Decl->isAnonymousNamespace())
1092 if (
Decl->isInline() && NamingStyles[SK_InlineNamespace])
1093 return SK_InlineNamespace;
1095 if (NamingStyles[SK_Namespace])
1096 return SK_Namespace;
1099 if (isa<EnumDecl>(D) && NamingStyles[SK_Enum])
1102 if (
const auto *EnumConst = dyn_cast<EnumConstantDecl>(D)) {
1103 if (cast<EnumDecl>(EnumConst->getDeclContext())->isScoped() &&
1104 NamingStyles[SK_ScopedEnumConstant])
1105 return SK_ScopedEnumConstant;
1107 if (NamingStyles[SK_EnumConstant])
1108 return SK_EnumConstant;
1110 if (NamingStyles[SK_Constant])
1116 if (
const auto *
Decl = dyn_cast<CXXRecordDecl>(D)) {
1117 if (
Decl->isAnonymousStructOrUnion())
1120 if (!
Decl->getCanonicalDecl()->isThisDeclarationADefinition())
1123 if (
Decl->hasDefinition() &&
Decl->isAbstract() &&
1124 NamingStyles[SK_AbstractClass])
1125 return SK_AbstractClass;
1127 if (
Decl->isStruct() && NamingStyles[SK_Struct])
1130 if (
Decl->isStruct() && NamingStyles[SK_Class])
1133 if (
Decl->isClass() && NamingStyles[SK_Class])
1136 if (
Decl->isClass() && NamingStyles[SK_Struct])
1139 if (
Decl->isUnion() && NamingStyles[SK_Union])
1142 if (
Decl->isEnum() && NamingStyles[SK_Enum])
1148 if (
const auto *
Decl = dyn_cast<FieldDecl>(D)) {
1151 if (!
Type.isNull() &&
Type.isConstQualified()) {
1152 if (NamingStyles[SK_ConstantMember])
1153 return SK_ConstantMember;
1155 if (NamingStyles[SK_Constant])
1159 if (
Decl->getAccess() == AS_private && NamingStyles[SK_PrivateMember])
1160 return SK_PrivateMember;
1162 if (
Decl->getAccess() == AS_protected && NamingStyles[SK_ProtectedMember])
1163 return SK_ProtectedMember;
1165 if (
Decl->getAccess() == AS_public && NamingStyles[SK_PublicMember])
1166 return SK_PublicMember;
1168 if (NamingStyles[SK_Member])
1174 if (
const auto *
Decl = dyn_cast<ParmVarDecl>(D)) {
1179 if (
Decl->isConstexpr() && NamingStyles[SK_ConstexprVariable])
1180 return SK_ConstexprVariable;
1182 if (!
Type.isNull() &&
Type.isConstQualified()) {
1183 if (
Type.getTypePtr()->isAnyPointerType() &&
1184 NamingStyles[SK_ConstantPointerParameter])
1185 return SK_ConstantPointerParameter;
1187 if (NamingStyles[SK_ConstantParameter])
1188 return SK_ConstantParameter;
1190 if (NamingStyles[SK_Constant])
1194 if (
Decl->isParameterPack() && NamingStyles[SK_ParameterPack])
1195 return SK_ParameterPack;
1197 if (!
Type.isNull() &&
Type.getTypePtr()->isAnyPointerType() &&
1198 NamingStyles[SK_PointerParameter])
1199 return SK_PointerParameter;
1201 if (NamingStyles[SK_Parameter])
1202 return SK_Parameter;
1207 if (
const auto *
Decl = dyn_cast<VarDecl>(D)) {
1210 if (
Decl->isConstexpr() && NamingStyles[SK_ConstexprVariable])
1211 return SK_ConstexprVariable;
1213 if (!
Type.isNull() &&
Type.isConstQualified()) {
1214 if (
Decl->isStaticDataMember() && NamingStyles[SK_ClassConstant])
1215 return SK_ClassConstant;
1217 if (
Decl->isFileVarDecl() &&
Type.getTypePtr()->isAnyPointerType() &&
1218 NamingStyles[SK_GlobalConstantPointer])
1219 return SK_GlobalConstantPointer;
1221 if (
Decl->isFileVarDecl() && NamingStyles[SK_GlobalConstant])
1222 return SK_GlobalConstant;
1224 if (
Decl->isStaticLocal() && NamingStyles[SK_StaticConstant])
1225 return SK_StaticConstant;
1227 if (
Decl->isLocalVarDecl() &&
Type.getTypePtr()->isAnyPointerType() &&
1228 NamingStyles[SK_LocalConstantPointer])
1229 return SK_LocalConstantPointer;
1231 if (
Decl->isLocalVarDecl() && NamingStyles[SK_LocalConstant])
1232 return SK_LocalConstant;
1234 if (
Decl->isFunctionOrMethodVarDecl() && NamingStyles[SK_LocalConstant])
1235 return SK_LocalConstant;
1237 if (NamingStyles[SK_Constant])
1241 if (
Decl->isStaticDataMember() && NamingStyles[SK_ClassMember])
1242 return SK_ClassMember;
1244 if (
Decl->isFileVarDecl() &&
Type.getTypePtr()->isAnyPointerType() &&
1245 NamingStyles[SK_GlobalPointer])
1246 return SK_GlobalPointer;
1248 if (
Decl->isFileVarDecl() && NamingStyles[SK_GlobalVariable])
1249 return SK_GlobalVariable;
1251 if (
Decl->isStaticLocal() && NamingStyles[SK_StaticVariable])
1252 return SK_StaticVariable;
1254 if (
Decl->isLocalVarDecl() &&
Type.getTypePtr()->isAnyPointerType() &&
1255 NamingStyles[SK_LocalPointer])
1256 return SK_LocalPointer;
1258 if (
Decl->isLocalVarDecl() && NamingStyles[SK_LocalVariable])
1259 return SK_LocalVariable;
1261 if (
Decl->isFunctionOrMethodVarDecl() && NamingStyles[SK_LocalVariable])
1262 return SK_LocalVariable;
1264 if (NamingStyles[SK_Variable])
1270 if (
const auto *
Decl = dyn_cast<CXXMethodDecl>(D)) {
1271 if (
Decl->isMain() || !
Decl->isUserProvided() ||
1272 Decl->size_overridden_methods() > 0 ||
Decl->hasAttr<OverrideAttr>())
1277 for (
const CXXBaseSpecifier &Base :
Decl->getParent()->bases())
1278 if (
const auto *RD = Base.getType()->getAsCXXRecordDecl())
1279 if (RD->hasMemberName(
Decl->getDeclName()))
1282 if (
Decl->isConstexpr() && NamingStyles[SK_ConstexprMethod])
1283 return SK_ConstexprMethod;
1285 if (
Decl->isConstexpr() && NamingStyles[SK_ConstexprFunction])
1286 return SK_ConstexprFunction;
1288 if (
Decl->isStatic() && NamingStyles[SK_ClassMethod])
1289 return SK_ClassMethod;
1291 if (
Decl->isVirtual() && NamingStyles[SK_VirtualMethod])
1292 return SK_VirtualMethod;
1294 if (
Decl->getAccess() == AS_private && NamingStyles[SK_PrivateMethod])
1295 return SK_PrivateMethod;
1297 if (
Decl->getAccess() == AS_protected && NamingStyles[SK_ProtectedMethod])
1298 return SK_ProtectedMethod;
1300 if (
Decl->getAccess() == AS_public && NamingStyles[SK_PublicMethod])
1301 return SK_PublicMethod;
1303 if (NamingStyles[SK_Method])
1306 if (NamingStyles[SK_Function])
1312 if (
const auto *
Decl = dyn_cast<FunctionDecl>(D)) {
1316 if (
Decl->isConstexpr() && NamingStyles[SK_ConstexprFunction])
1317 return SK_ConstexprFunction;
1319 if (
Decl->isGlobal() && NamingStyles[SK_GlobalFunction])
1320 return SK_GlobalFunction;
1322 if (NamingStyles[SK_Function])
1326 if (isa<TemplateTypeParmDecl>(D)) {
1327 if (NamingStyles[SK_TypeTemplateParameter])
1328 return SK_TypeTemplateParameter;
1330 if (NamingStyles[SK_TemplateParameter])
1331 return SK_TemplateParameter;
1336 if (isa<NonTypeTemplateParmDecl>(D)) {
1337 if (NamingStyles[SK_ValueTemplateParameter])
1338 return SK_ValueTemplateParameter;
1340 if (NamingStyles[SK_TemplateParameter])
1341 return SK_TemplateParameter;
1346 if (isa<TemplateTemplateParmDecl>(D)) {
1347 if (NamingStyles[SK_TemplateTemplateParameter])
1348 return SK_TemplateTemplateParameter;
1350 if (NamingStyles[SK_TemplateParameter])
1351 return SK_TemplateParameter;
1359std::optional<RenamerClangTidyCheck::FailureInfo>
1361 StringRef
Type, StringRef
Name,
const NamedDecl *ND,
1363 ArrayRef<std::optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
1365 StyleKind SK,
const SourceManager &SM,
bool IgnoreFailedSplit)
const {
1367 return std::nullopt;
1370 if (Style.IgnoredRegexp.isValid() && Style.IgnoredRegexp.match(
Name))
1371 return std::nullopt;
1374 return std::nullopt;
1376 std::string KindName =
1379 std::replace(KindName.begin(), KindName.end(),
'_',
' ');
1382 if (StringRef(Fixup).equals(
Name)) {
1383 if (!IgnoreFailedSplit) {
1384 LLVM_DEBUG(
Location.print(llvm::dbgs(), SM);
1386 << llvm::formatv(
": unable to split words for {0} '{1}'\n",
1389 return std::nullopt;
1395std::optional<RenamerClangTidyCheck::FailureInfo>
1396IdentifierNamingCheck::getDeclFailureInfo(
const NamedDecl *
Decl,
1397 const SourceManager &SM)
const {
1398 SourceLocation
Loc =
Decl->getLocation();
1399 const FileStyle &FileStyle = getStyleForFile(SM.getFilename(
Loc));
1400 if (!FileStyle.isActive())
1401 return std::nullopt;
1404 Decl->getName(),
Decl,
Loc, FileStyle.getStyles(),
1405 FileStyle.getHNOption(),
1407 FileStyle.isIgnoringMainLikeFunction()),
1408 SM, IgnoreFailedSplit);
1411std::optional<RenamerClangTidyCheck::FailureInfo>
1412IdentifierNamingCheck::getMacroFailureInfo(
const Token &MacroNameTok,
1413 const SourceManager &SM)
const {
1414 SourceLocation
Loc = MacroNameTok.getLocation();
1415 const FileStyle &Style = getStyleForFile(SM.getFilename(
Loc));
1416 if (!Style.isActive())
1417 return std::nullopt;
1419 return getFailureInfo(
"", MacroNameTok.getIdentifierInfo()->getName(),
1420 nullptr,
Loc, Style.getStyles(), Style.getHNOption(),
1421 SK_MacroDefinition, SM, IgnoreFailedSplit);
1424RenamerClangTidyCheck::DiagInfo
1426 const NamingCheckFailure &Failure)
const {
1427 return DiagInfo{
"invalid case style for %0 '%1'",
1428 [&](DiagnosticBuilder &Diag) {
1429 Diag << Failure.Info.KindName << ID.second;
1433const IdentifierNamingCheck::FileStyle &
1434IdentifierNamingCheck::getStyleForFile(StringRef
FileName)
const {
1435 if (!GetConfigPerFile)
1436 return *MainFileStyle;
1438 auto Iter = NamingStylesCache.find(
Parent);
1439 if (Iter != NamingStylesCache.end())
1440 return Iter->getValue();
1443 if (
Options.Checks && GlobList(*
Options.Checks).contains(CheckName)) {
1444 auto It = NamingStylesCache.try_emplace(
1448 return It.first->getValue();
1451 auto It = NamingStylesCache.try_emplace(
Parent);
1453 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.
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, std::string > 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.
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
std::string getDataTypePrefix(StringRef TypeName, const NamedDecl *ND, const IdentifierNamingCheck::HungarianNotationOption &HNOption) const