11#include "../GlobList.h"
12#include "../utils/ASTUtils.h"
13#include "clang/AST/CXXInheritance.h"
14#include "clang/Lex/PPCallbacks.h"
15#include "clang/Lex/Preprocessor.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/DenseMapInfo.h"
18#include "llvm/ADT/StringRef.h"
19#include "llvm/Support/Debug.h"
20#include "llvm/Support/Error.h"
21#include "llvm/Support/FormatVariadic.h"
22#include "llvm/Support/Path.h"
23#include "llvm/Support/Regex.h"
24#include "llvm/Support/YAMLParser.h"
27#define DEBUG_TYPE "clang-tidy"
36 std::pair<readability::IdentifierNamingCheck::CaseType, StringRef>>
52 "Leading_upper_snake_case"}};
58 readability::IdentifierNamingCheck::HungarianPrefixType> {
61 static llvm::ArrayRef<std::pair<HungarianPrefixType, StringRef>>
63 static constexpr std::pair<HungarianPrefixType, StringRef> Mapping[] = {
64 {HungarianPrefixType::HPT_Off,
"Off"},
65 {HungarianPrefixType::HPT_On,
"On"},
66 {HungarianPrefixType::HPT_LowerCase,
"LowerCase"},
67 {HungarianPrefixType::HPT_CamelCase,
"CamelCase"}};
72namespace readability {
75#define NAMING_KEYS(m) \
79 m(ScopedEnumConstant) \
80 m(ConstexprVariable) \
89 m(GlobalConstantPointer) \
93 m(LocalConstantPointer) \
100 m(ConstantParameter) \
103 m(PointerParameter) \
104 m(ConstantPointerParameter) \
111 m(ConstexprFunction) \
121 m(TypeTemplateParameter) \
122 m(ValueTemplateParameter) \
123 m(TemplateTemplateParameter) \
124 m(TemplateParameter) \
131#define ENUMERATE(v) SK_ ## v,
139#define STRINGIZE(v) #v,
144#define HUNGARIAN_NOTATION_PRIMITIVE_TYPES(m) \
168 m(signed-short-int) \
169 m(signed-long-long-int) \
170 m(signed-long-long) \
174 m(unsigned-long-long-int) \
175 m(unsigned-long-long) \
176 m(unsigned-long-int) \
178 m(unsigned-short-int) \
192#define STRINGIZE(v) #v,
197#define HUNGARIAN_NOTATION_USER_DEFINED_TYPES(m) \
228#define STRINGIZE(v) #v,
238 std::optional<IdentifierNamingCheck::CaseType> Case, StringRef Prefix,
239 StringRef
Suffix, StringRef IgnoredRegexpStr, HungarianPrefixType HPType)
241 IgnoredRegexpStr(IgnoredRegexpStr), HPType(HPType) {
242 if (!IgnoredRegexpStr.empty()) {
244 llvm::Regex(llvm::SmallString<128>({
"^", IgnoredRegexpStr,
"$"}));
245 if (!IgnoredRegexp.isValid())
246 llvm::errs() <<
"Invalid IgnoredRegexp regular expression: "
258 SmallVector<std::optional<IdentifierNamingCheck::NamingStyle>, 0> Styles;
260 SmallString<64> StyleString;
261 for (
unsigned I = 0; I <
SK_Count; ++I) {
263 StyleString.assign({
StyleNames[I],
"HungarianPrefix"});
268 configurationDiag(
"invalid identifier naming option '%0'") << StyleString;
270 memcpy(&StyleString[StyleSize],
"IgnoredRegexp", 13);
271 StyleString.truncate(StyleSize + 13);
272 std::optional<StringRef> IgnoredRegexpStr = Options.
get(StyleString);
273 memcpy(&StyleString[StyleSize],
"Prefix", 6);
274 StyleString.truncate(StyleSize + 6);
275 std::optional<StringRef> Prefix(Options.
get(StyleString));
277 memcpy(&StyleString[StyleSize],
"Suf", 3);
278 std::optional<StringRef> Postfix(Options.
get(StyleString));
279 memcpy(&StyleString[StyleSize],
"Case", 4);
280 StyleString.pop_back_n(2);
281 std::optional<CaseType> CaseOptional =
284 if (CaseOptional || Prefix || Postfix || IgnoredRegexpStr || HPTOpt)
285 Styles[I].emplace(std::move(CaseOptional), Prefix.value_or(
""),
286 Postfix.value_or(
""), IgnoredRegexpStr.value_or(
""),
287 HPTOpt.value_or(IdentifierNamingCheck::HPT_Off));
289 bool IgnoreMainLike = Options.
get(
"IgnoreMainLikeFunctions",
false);
290 bool CheckAnonFieldInParent = Options.
get(
"CheckAnonFieldInParent",
false);
291 return {std::move(Styles), std::move(HNOption), IgnoreMainLike,
292 CheckAnonFieldInParent};
295std::string IdentifierNamingCheck::HungarianNotation::getDeclTypeName(
296 const NamedDecl *ND)
const {
297 const auto *VD = dyn_cast<ValueDecl>(ND);
301 if (isa<FunctionDecl, EnumConstantDecl>(ND))
305 auto &SM = VD->getASTContext().getSourceManager();
306 const char *Begin = SM.getCharacterData(VD->getBeginLoc());
307 const char *End = SM.getCharacterData(VD->getEndLoc());
308 intptr_t StrLen = End - Begin;
314 const char *EOL = strchr(Begin,
'\n');
316 EOL = Begin + strlen(Begin);
318 const char *PosList[] = {strchr(Begin,
'='), strchr(Begin,
';'),
319 strchr(Begin,
','), strchr(Begin,
')'), EOL};
320 for (
const auto &
Pos : PosList) {
322 EOL = std::min(EOL,
Pos);
325 StrLen = EOL - Begin;
326 std::string TypeName;
328 std::string
Type(Begin, StrLen);
330 static constexpr StringRef Keywords[] = {
332 "constexpr",
"constinit",
"consteval",
334 "const",
"volatile",
"restrict",
"mutable",
336 "register",
"static",
"extern",
"thread_local",
341 for (StringRef Kw : Keywords) {
343 (
Pos =
Type.find(Kw.data(),
Pos)) != std::string::npos;) {
344 Type.replace(
Pos, Kw.size(),
"");
347 TypeName =
Type.erase(0,
Type.find_first_not_of(
' '));
350 const size_t Pos =
Type.find(
'<');
351 if (
Pos != std::string::npos) {
356 for (
size_t Pos = 0; (
Pos =
Type.find(
" ",
Pos)) != std::string::npos;
357 Pos += strlen(
" ")) {
358 Type.replace(
Pos, strlen(
" "),
" ");
362 for (
size_t Pos = 0; (
Pos =
Type.find(
" &",
Pos)) != std::string::npos;
363 Pos += strlen(
"&")) {
364 Type.replace(
Pos, strlen(
" &"),
"&");
368 for (
size_t Pos = 0; (
Pos =
Type.find(
" *",
Pos)) != std::string::npos;
369 Pos += strlen(
"*")) {
370 Type.replace(
Pos, strlen(
" *"),
"* ");
374 static constexpr StringRef TailsOfMultiWordType[] = {
375 " int",
" char",
" double",
" long",
" short"};
376 bool RedundantRemoved =
false;
377 for (
auto Kw : TailsOfMultiWordType) {
378 size_t Pos =
Type.rfind(Kw.data());
379 if (
Pos != std::string::npos) {
380 const size_t PtrCount = getAsteriskCount(
Type, ND);
382 RedundantRemoved =
true;
387 TypeName =
Type.erase(0,
Type.find_first_not_of(
' '));
388 if (!RedundantRemoved) {
389 std::size_t FoundSpace =
Type.find(
' ');
390 if (FoundSpace != std::string::npos)
394 TypeName =
Type.erase(0,
Type.find_first_not_of(
' '));
396 QualType QT = VD->getType();
397 if (!QT.isNull() && QT->isArrayType())
398 TypeName.append(
"[]");
404IdentifierNamingCheck::IdentifierNamingCheck(StringRef
Name,
407 GetConfigPerFile(Options.get(
"GetConfigPerFile", true)),
408 IgnoreFailedSplit(Options.get(
"IgnoreFailedSplit", false)) {
410 auto IterAndInserted = NamingStylesCache.try_emplace(
411 llvm::sys::path::parent_path(Context->getCurrentFile()),
413 assert(IterAndInserted.second &&
"Couldn't insert Style");
416 MainFileStyle = &IterAndInserted.first->getValue();
422 int StyleKindIndex)
const {
423 if ((StyleKindIndex >= SK_EnumConstant) &&
424 (StyleKindIndex <= SK_ConstantParameter))
427 if ((StyleKindIndex >= SK_Parameter) && (StyleKindIndex <= SK_Enum))
434 StringRef OptionKey,
const llvm::StringMap<std::string> &StrMap)
const {
435 if (OptionKey.empty())
438 auto Iter = StrMap.find(OptionKey);
439 if (Iter == StrMap.end())
442 return *llvm::yaml::parseBool(Iter->getValue());
449 static constexpr StringRef HNOpts[] = {
"TreatStructAsClass"};
450 static constexpr StringRef HNDerivedTypes[] = {
"Array",
"Pointer",
453 StringRef Section =
"HungarianNotation.";
455 SmallString<128> Buffer = {Section,
"General."};
456 size_t DefSize = Buffer.size();
457 for (
const auto &Opt : HNOpts) {
458 Buffer.truncate(DefSize);
462 HNOption.
General[Opt] = Val.str();
465 Buffer = {Section,
"DerivedType."};
466 DefSize = Buffer.size();
467 for (
const auto &
Type : HNDerivedTypes) {
468 Buffer.truncate(DefSize);
475 static constexpr std::pair<StringRef, StringRef> HNCStrings[] = {
476 {
"CharPointer",
"char*"},
477 {
"CharArray",
"char[]"},
478 {
"WideCharPointer",
"wchar_t*"},
479 {
"WideCharArray",
"wchar_t[]"}};
481 Buffer = {Section,
"CString."};
482 DefSize = Buffer.size();
483 for (
const auto &CStr : HNCStrings) {
484 Buffer.truncate(DefSize);
485 Buffer.append(CStr.first);
488 HNOption.
CString[CStr.second] = Val.str();
491 Buffer = {Section,
"PrimitiveType."};
492 DefSize = Buffer.size();
494 Buffer.truncate(DefSize);
495 Buffer.append(PrimType);
498 std::string
Type = PrimType.str();
499 std::replace(
Type.begin(),
Type.end(),
'-',
' ');
504 Buffer = {Section,
"UserDefinedType."};
505 DefSize = Buffer.size();
507 Buffer.truncate(DefSize);
520 const auto *ND = dyn_cast<NamedDecl>(D);
525 if (
const auto *ECD = dyn_cast<EnumConstantDecl>(ND)) {
526 Prefix = getEnumPrefix(ECD);
527 }
else if (
const auto *CRD = dyn_cast<CXXRecordDecl>(ND)) {
528 Prefix = getClassPrefix(CRD, HNOption);
529 }
else if (isa<VarDecl, FieldDecl, RecordDecl>(ND)) {
530 std::string TypeName = getDeclTypeName(ND);
531 if (!TypeName.empty())
532 Prefix = getDataTypePrefix(TypeName, ND, HNOption);
539 SmallVector<StringRef, 8> &Words,
541 if (Words.size() <= 1)
544 std::string CorrectName = Words[0].str();
545 std::vector<llvm::StringMap<std::string>> MapList = {
549 for (
const auto &Map : MapList) {
550 for (
const auto &Str : Map) {
551 if (Str.getValue() == CorrectName) {
552 Words.erase(Words.begin(), Words.begin() + 1);
562 StringRef TypeName,
const NamedDecl *ND,
564 if (!ND || TypeName.empty())
565 return TypeName.str();
567 std::string ModifiedTypeName(TypeName);
570 std::string PrefixStr;
571 if (
const auto *TD = dyn_cast<ValueDecl>(ND)) {
572 QualType QT = TD->getType();
573 if (QT->isFunctionPointerType()) {
574 PrefixStr = HNOption.
DerivedType.lookup(
"FunctionPointer");
575 }
else if (QT->isPointerType()) {
576 for (
const auto &CStr : HNOption.
CString) {
577 std::string Key = CStr.getKey().str();
578 if (ModifiedTypeName.find(Key) == 0) {
579 PrefixStr = CStr.getValue();
580 ModifiedTypeName = ModifiedTypeName.substr(
581 Key.size(), ModifiedTypeName.size() - Key.size());
585 }
else if (QT->isArrayType()) {
586 for (
const auto &CStr : HNOption.
CString) {
587 std::string Key = CStr.getKey().str();
588 if (ModifiedTypeName.find(Key) == 0) {
589 PrefixStr = CStr.getValue();
593 if (PrefixStr.empty())
595 }
else if (QT->isReferenceType()) {
596 size_t Pos = ModifiedTypeName.find_last_of(
'&');
597 if (
Pos != std::string::npos)
598 ModifiedTypeName = ModifiedTypeName.substr(0,
Pos);
603 size_t PtrCount = getAsteriskCount(ModifiedTypeName);
605 ModifiedTypeName = [&](std::string Str, StringRef From, StringRef To) {
607 while ((StartPos = Str.find(From.data(), StartPos)) !=
609 Str.replace(StartPos, From.size(), To.data());
610 StartPos += To.size();
613 }(ModifiedTypeName,
"*",
"");
617 if (PrefixStr.empty()) {
619 if (ModifiedTypeName ==
Type.getKey()) {
620 PrefixStr =
Type.getValue();
627 if (PrefixStr.empty()) {
629 if (ModifiedTypeName ==
Type.getKey()) {
630 PrefixStr =
Type.getValue();
636 for (
size_t Idx = 0; Idx < PtrCount; Idx++)
637 PrefixStr.insert(0, HNOption.
DerivedType.lookup(
"Pointer"));
643 const CXXRecordDecl *CRD,
649 if (CRD->isStruct() &&
650 !isOptionEnabled(
"TreatStructAsClass", HNOption.
General))
653 return CRD->isAbstract() ?
"I" :
"C";
657 const EnumConstantDecl *ECD)
const {
658 const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
660 std::string
Name = ED->getName().str();
661 if (StringRef(
Name).contains(
"enum")) {
662 Name =
Name.substr(strlen(
"enum"),
Name.length() - strlen(
"enum"));
666 static llvm::Regex Splitter(
667 "([a-z0-9A-Z]*)(_+)|([A-Z]?[a-z0-9]+)([A-Z]|$)|([A-Z]+)([A-Z]|$)");
669 StringRef EnumName(
Name);
670 SmallVector<StringRef, 8> Substrs;
671 EnumName.split(Substrs,
"_", -1,
false);
673 SmallVector<StringRef, 8> Words;
674 SmallVector<StringRef, 8> Groups;
675 for (
auto Substr : Substrs) {
676 while (!Substr.empty()) {
678 if (!Splitter.match(Substr, &Groups))
681 if (!Groups[2].empty()) {
682 Words.push_back(Groups[1]);
683 Substr = Substr.substr(Groups[0].size());
684 }
else if (!Groups[3].empty()) {
685 Words.push_back(Groups[3]);
686 Substr = Substr.substr(Groups[0].size() - Groups[4].size());
687 }
else if (!Groups[5].empty()) {
688 Words.push_back(Groups[5]);
689 Substr = Substr.substr(Groups[0].size() - Groups[6].size());
695 for (StringRef
Word : Words)
696 Initial += tolower(
Word[0]);
702 const std::string &TypeName)
const {
703 size_t Pos = TypeName.find(
'*');
705 for (;
Pos < TypeName.length();
Pos++, Count++) {
706 if (
'*' != TypeName[
Pos])
713 const std::string &TypeName,
const NamedDecl *ND)
const {
715 if (
const auto *TD = dyn_cast<ValueDecl>(ND)) {
716 QualType QT = TD->getType();
717 if (QT->isPointerType())
718 PtrCount = getAsteriskCount(TypeName);
727 static constexpr std::pair<StringRef, StringRef> General[] = {
728 {
"TreatStructAsClass",
"false"}};
729 for (
const auto &G : General)
730 HNOption.
General.try_emplace(G.first, G.second);
733 static constexpr std::pair<StringRef, StringRef> DerivedTypes[] = {
734 {
"Array",
"a"}, {
"Pointer",
"p"}, {
"FunctionPointer",
"fn"}};
735 for (
const auto &DT : DerivedTypes)
736 HNOption.
DerivedType.try_emplace(DT.first, DT.second);
739 static constexpr std::pair<StringRef, StringRef> CStrings[] = {
743 {
"wchar_t[]",
"wsz"}};
744 for (
const auto &CStr : CStrings)
745 HNOption.
CString.try_emplace(CStr.first, CStr.second);
748 static constexpr std::pair<StringRef, StringRef> PrimitiveTypes[] = {
754 {
"uint16_t",
"u16" },
755 {
"uint32_t",
"u32" },
756 {
"uint64_t",
"u64" },
758 {
"char16_t",
"c16" },
759 {
"char32_t",
"c32" },
768 {
"short int",
"si" },
770 {
"signed int",
"si" },
771 {
"signed short",
"ss" },
772 {
"signed short int",
"ssi" },
773 {
"signed long long int",
"slli"},
774 {
"signed long long",
"sll" },
775 {
"signed long int",
"sli" },
776 {
"signed long",
"sl" },
778 {
"unsigned long long int",
"ulli"},
779 {
"unsigned long long",
"ull" },
780 {
"unsigned long int",
"uli" },
781 {
"unsigned long",
"ul" },
782 {
"unsigned short int",
"usi" },
783 {
"unsigned short",
"us" },
784 {
"unsigned int",
"ui" },
785 {
"unsigned char",
"uc" },
787 {
"long long int",
"lli" },
788 {
"long double",
"ld" },
789 {
"long long",
"ll" },
795 for (
const auto &PT : PrimitiveTypes)
799 static constexpr std::pair<StringRef, StringRef> UserDefinedTypes[] = {
816 {
"ULONGLONG",
"ull" },
830 for (
const auto &UDT : UserDefinedTypes)
836 SmallString<64> StyleString;
837 ArrayRef<std::optional<NamingStyle>> Styles = MainFileStyle->
getStyles();
838 for (
size_t I = 0; I <
SK_Count; ++I) {
842 StyleString.assign({
StyleNames[I],
"HungarianPrefix"});
846 memcpy(&StyleString[StyleSize],
"IgnoredRegexp", 13);
847 StyleString.truncate(StyleSize + 13);
848 Options.
store(Opts, StyleString, Styles[I]->IgnoredRegexpStr);
849 memcpy(&StyleString[StyleSize],
"Prefix", 6);
850 StyleString.truncate(StyleSize + 6);
853 memcpy(&StyleString[StyleSize],
"Suf", 3);
855 if (Styles[I]->Case) {
856 memcpy(&StyleString[StyleSize],
"Case", 4);
857 StyleString.pop_back_n(2);
861 Options.
store(Opts,
"GetConfigPerFile", GetConfigPerFile);
862 Options.
store(Opts,
"IgnoreFailedSplit", IgnoreFailedSplit);
873 const NamedDecl *
Decl)
const {
874 static llvm::Regex Matchers[] = {
876 llvm::Regex(
"^[a-z][a-z0-9_]*$"),
877 llvm::Regex(
"^[a-z][a-zA-Z0-9]*$"),
878 llvm::Regex(
"^[A-Z][A-Z0-9_]*$"),
879 llvm::Regex(
"^[A-Z][a-zA-Z0-9]*$"),
880 llvm::Regex(
"^[A-Z]+([a-z0-9]*_[A-Z0-9]+)*[a-z0-9]*$"),
881 llvm::Regex(
"^[a-z]+([a-z0-9]*_[A-Z0-9]+)*[a-z0-9]*$"),
882 llvm::Regex(
"^[A-Z]([a-z0-9_]*[a-z])*$"),
885 if (!
Name.consume_front(Style.Prefix))
887 if (!
Name.consume_back(Style.Suffix))
891 if (!HNPrefix.empty()) {
892 if (!
Name.consume_front(HNPrefix))
896 !
Name.consume_front(
"_"))
903 if (
Name.starts_with(
"_") ||
Name.ends_with(
"_"))
906 if (Style.Case && !Matchers[
static_cast<size_t>(*Style.Case)].match(
Name))
917 static llvm::Regex Splitter(
918 "([a-z0-9A-Z]*)(_+)|([A-Z]?[a-z0-9]+)([A-Z]|$)|([A-Z]+)([A-Z]|$)");
920 SmallVector<StringRef, 8> Substrs;
921 Name.split(Substrs,
"_", -1,
false);
923 SmallVector<StringRef, 8> Words;
924 SmallVector<StringRef, 8> Groups;
925 for (
auto Substr : Substrs) {
926 while (!Substr.empty()) {
928 if (!Splitter.match(Substr, &Groups))
931 if (!Groups[2].empty()) {
932 Words.push_back(Groups[1]);
933 Substr = Substr.substr(Groups[0].size());
934 }
else if (!Groups[3].empty()) {
935 Words.push_back(Groups[3]);
936 Substr = Substr.substr(Groups[0].size() - Groups[4].size());
937 }
else if (!Groups[5].empty()) {
938 Words.push_back(Groups[5]);
939 Substr = Substr.substr(Groups[0].size() - Groups[6].size());
951 SmallString<128> Fixup;
958 for (
auto const &
Word : Words) {
959 if (&
Word != &Words.front())
961 Fixup +=
Word.lower();
966 for (
auto const &
Word : Words) {
967 if (&
Word != &Words.front())
969 Fixup +=
Word.upper();
974 for (
auto const &
Word : Words) {
975 Fixup += toupper(
Word.front());
976 Fixup +=
Word.substr(1).lower();
981 for (
auto const &
Word : Words) {
982 if (&
Word == &Words.front()) {
983 Fixup +=
Word.lower();
985 Fixup += toupper(
Word.front());
986 Fixup +=
Word.substr(1).lower();
992 for (
auto const &
Word : Words) {
993 if (&
Word != &Words.front())
995 Fixup += toupper(
Word.front());
996 Fixup +=
Word.substr(1).lower();
1001 for (
auto const &
Word : Words) {
1002 if (&
Word != &Words.front()) {
1004 Fixup += toupper(
Word.front());
1006 Fixup += tolower(
Word.front());
1008 Fixup +=
Word.substr(1).lower();
1013 for (
auto const &
Word : Words) {
1014 if (&
Word != &Words.front()) {
1016 Fixup +=
Word.lower();
1018 Fixup += toupper(
Word.front());
1019 Fixup +=
Word.substr(1).lower();
1025 return Fixup.str().str();
1029 const ParmVarDecl &ParmDecl,
bool IncludeMainLike)
const {
1031 dyn_cast_or_null<FunctionDecl>(ParmDecl.getParentFunctionOrMethod());
1034 if (FDecl->isMain())
1036 if (!IncludeMainLike)
1038 if (FDecl->getAccess() != AS_public && FDecl->getAccess() != AS_none)
1042 if (!FDecl->getDeclName().isIdentifier())
1044 enum MainType { None, Main, WMain };
1045 auto IsCharPtrPtr = [](QualType QType) -> MainType {
1048 if (QType = QType->getPointeeType(), QType.isNull())
1050 if (QType = QType->getPointeeType(), QType.isNull())
1052 if (QType->isCharType())
1054 if (QType->isWideCharType())
1058 auto IsIntType = [](QualType QType) {
1061 if (
const auto *Builtin =
1062 dyn_cast<BuiltinType>(QType->getUnqualifiedDesugaredType())) {
1063 return Builtin->getKind() == BuiltinType::Int;
1067 if (!IsIntType(FDecl->getReturnType()))
1069 if (FDecl->getNumParams() < 2 || FDecl->getNumParams() > 3)
1071 if (!IsIntType(FDecl->parameters()[0]->getType()))
1073 MainType
Type = IsCharPtrPtr(FDecl->parameters()[1]->getType());
1076 if (FDecl->getNumParams() == 3 &&
1077 IsCharPtrPtr(FDecl->parameters()[2]->getType()) !=
Type)
1081 static llvm::Regex Matcher(
1082 "(^[Mm]ain([_A-Z]|$))|([a-z0-9_]Main([_A-Z]|$))|(_main(_|$))");
1083 assert(Matcher.isValid() &&
"Invalid Matcher for main like functions.");
1084 return Matcher.match(FDecl->getName());
1086 static llvm::Regex Matcher(
"(^((W[Mm])|(wm))ain([_A-Z]|$))|([a-z0-9_]W[Mm]"
1087 "ain([_A-Z]|$))|(_wmain(_|$))");
1088 assert(Matcher.isValid() &&
"Invalid Matcher for wmain like functions.");
1089 return Matcher.match(FDecl->getName());
1096 const Decl *D)
const {
1097 Name.consume_front(Style.Prefix);
1098 Name.consume_back(Style.Suffix);
1103 std::string HungarianPrefix;
1107 if (!HungarianPrefix.empty()) {
1109 HungarianPrefix +=
"_";
1112 Fixed[0] = toupper(Fixed[0]);
1115 StringRef Mid = StringRef(Fixed).trim(
"_");
1119 return (Style.Prefix + HungarianPrefix + Mid + Style.Suffix).str();
1124 ArrayRef<std::optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
1125 bool IgnoreMainLikeFunctions,
bool CheckAnonFieldInParentScope)
const {
1126 assert(D && D->getIdentifier() && !D->getName().empty() && !D->isImplicit() &&
1127 "Decl must be an explicit identifier with a name.");
1129 if (isa<ObjCIvarDecl>(D) && NamingStyles[SK_ObjcIvar])
1132 if (isa<TypedefDecl>(D) && NamingStyles[SK_Typedef])
1135 if (isa<TypeAliasDecl>(D) && NamingStyles[SK_TypeAlias])
1136 return SK_TypeAlias;
1138 if (
const auto *
Decl = dyn_cast<NamespaceDecl>(D)) {
1139 if (
Decl->isAnonymousNamespace())
1142 if (
Decl->isInline() && NamingStyles[SK_InlineNamespace])
1143 return SK_InlineNamespace;
1145 if (NamingStyles[SK_Namespace])
1146 return SK_Namespace;
1149 if (isa<EnumDecl>(D) && NamingStyles[SK_Enum])
1152 if (
const auto *EnumConst = dyn_cast<EnumConstantDecl>(D)) {
1153 if (cast<EnumDecl>(EnumConst->getDeclContext())->isScoped() &&
1154 NamingStyles[SK_ScopedEnumConstant])
1155 return SK_ScopedEnumConstant;
1157 if (NamingStyles[SK_EnumConstant])
1158 return SK_EnumConstant;
1160 if (NamingStyles[SK_Constant])
1166 if (
const auto *
Decl = dyn_cast<RecordDecl>(D)) {
1167 if (
Decl->isAnonymousStructOrUnion())
1170 if (
const auto *Definition =
Decl->getDefinition()) {
1171 if (
const auto *CxxRecordDecl = dyn_cast<CXXRecordDecl>(Definition)) {
1172 if (CxxRecordDecl->isAbstract() && NamingStyles[SK_AbstractClass])
1173 return SK_AbstractClass;
1176 if (Definition->isStruct() && NamingStyles[SK_Struct])
1179 if (Definition->isStruct() && NamingStyles[SK_Class])
1182 if (Definition->isClass() && NamingStyles[SK_Class])
1185 if (Definition->isClass() && NamingStyles[SK_Struct])
1188 if (Definition->isUnion() && NamingStyles[SK_Union])
1191 if (Definition->isEnum() && NamingStyles[SK_Enum])
1198 if (
const auto *
Decl = dyn_cast<FieldDecl>(D)) {
1199 if (CheckAnonFieldInParentScope) {
1200 const RecordDecl *Record =
Decl->getParent();
1201 if (Record->isAnonymousStructOrUnion()) {
1202 return findStyleKindForAnonField(
Decl, NamingStyles);
1206 return findStyleKindForField(
Decl,
Decl->getType(), NamingStyles);
1209 if (
const auto *
Decl = dyn_cast<ParmVarDecl>(D)) {
1214 if (
Decl->isConstexpr() && NamingStyles[SK_ConstexprVariable])
1215 return SK_ConstexprVariable;
1217 if (!
Type.isNull() &&
Type.isConstQualified()) {
1218 if (
Type.getTypePtr()->isAnyPointerType() &&
1219 NamingStyles[SK_ConstantPointerParameter])
1220 return SK_ConstantPointerParameter;
1222 if (NamingStyles[SK_ConstantParameter])
1223 return SK_ConstantParameter;
1225 if (NamingStyles[SK_Constant])
1229 if (
Decl->isParameterPack() && NamingStyles[SK_ParameterPack])
1230 return SK_ParameterPack;
1232 if (!
Type.isNull() &&
Type.getTypePtr()->isAnyPointerType() &&
1233 NamingStyles[SK_PointerParameter])
1234 return SK_PointerParameter;
1236 if (NamingStyles[SK_Parameter])
1237 return SK_Parameter;
1242 if (
const auto *
Decl = dyn_cast<VarDecl>(D)) {
1243 return findStyleKindForVar(
Decl,
Decl->getType(), NamingStyles);
1246 if (
const auto *
Decl = dyn_cast<CXXMethodDecl>(D)) {
1247 if (
Decl->isMain() || !
Decl->isUserProvided() ||
1248 Decl->size_overridden_methods() > 0 ||
Decl->hasAttr<OverrideAttr>())
1253 for (
const CXXBaseSpecifier &Base :
Decl->getParent()->bases())
1254 if (
const auto *RD = Base.getType()->getAsCXXRecordDecl())
1255 if (RD->hasMemberName(
Decl->getDeclName()))
1258 if (
Decl->isConstexpr() && NamingStyles[SK_ConstexprMethod])
1259 return SK_ConstexprMethod;
1261 if (
Decl->isConstexpr() && NamingStyles[SK_ConstexprFunction])
1262 return SK_ConstexprFunction;
1264 if (
Decl->isStatic() && NamingStyles[SK_ClassMethod])
1265 return SK_ClassMethod;
1267 if (
Decl->isVirtual() && NamingStyles[SK_VirtualMethod])
1268 return SK_VirtualMethod;
1270 if (
Decl->getAccess() == AS_private && NamingStyles[SK_PrivateMethod])
1271 return SK_PrivateMethod;
1273 if (
Decl->getAccess() == AS_protected && NamingStyles[SK_ProtectedMethod])
1274 return SK_ProtectedMethod;
1276 if (
Decl->getAccess() == AS_public && NamingStyles[SK_PublicMethod])
1277 return SK_PublicMethod;
1279 if (NamingStyles[SK_Method])
1282 if (NamingStyles[SK_Function])
1288 if (
const auto *
Decl = dyn_cast<FunctionDecl>(D)) {
1292 if (
Decl->isConstexpr() && NamingStyles[SK_ConstexprFunction])
1293 return SK_ConstexprFunction;
1295 if (
Decl->isGlobal() && NamingStyles[SK_GlobalFunction])
1296 return SK_GlobalFunction;
1298 if (NamingStyles[SK_Function])
1302 if (isa<TemplateTypeParmDecl>(D)) {
1303 if (NamingStyles[SK_TypeTemplateParameter])
1304 return SK_TypeTemplateParameter;
1306 if (NamingStyles[SK_TemplateParameter])
1307 return SK_TemplateParameter;
1312 if (isa<NonTypeTemplateParmDecl>(D)) {
1313 if (NamingStyles[SK_ValueTemplateParameter])
1314 return SK_ValueTemplateParameter;
1316 if (NamingStyles[SK_TemplateParameter])
1317 return SK_TemplateParameter;
1322 if (isa<TemplateTemplateParmDecl>(D)) {
1323 if (NamingStyles[SK_TemplateTemplateParameter])
1324 return SK_TemplateTemplateParameter;
1326 if (NamingStyles[SK_TemplateParameter])
1327 return SK_TemplateParameter;
1332 if (isa<ConceptDecl>(D) && NamingStyles[SK_Concept])
1338std::optional<RenamerClangTidyCheck::FailureInfo>
1340 StringRef
Type, StringRef
Name,
const NamedDecl *ND,
1342 ArrayRef<std::optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
1344 StyleKind SK,
const SourceManager &SM,
bool IgnoreFailedSplit)
const {
1346 return std::nullopt;
1349 if (Style.IgnoredRegexp.isValid() && Style.IgnoredRegexp.match(
Name))
1350 return std::nullopt;
1353 return std::nullopt;
1355 std::string KindName =
1358 std::replace(KindName.begin(), KindName.end(),
'_',
' ');
1361 if (StringRef(Fixup) ==
Name) {
1362 if (!IgnoreFailedSplit) {
1363 LLVM_DEBUG(
Location.print(llvm::dbgs(), SM);
1365 << llvm::formatv(
": unable to split words for {0} '{1}'\n",
1368 return std::nullopt;
1374std::optional<RenamerClangTidyCheck::FailureInfo>
1375IdentifierNamingCheck::getDeclFailureInfo(
const NamedDecl *
Decl,
1376 const SourceManager &SM)
const {
1378 if (
Decl->isImplicit())
1379 return std::nullopt;
1381 SourceLocation
Loc =
Decl->getLocation();
1382 const FileStyle &FileStyle = getStyleForFile(SM.getFilename(
Loc));
1383 if (!FileStyle.isActive())
1384 return std::nullopt;
1388 FileStyle.getStyles(), FileStyle.getHNOption(),
1390 FileStyle.isIgnoringMainLikeFunction(),
1391 FileStyle.isCheckingAnonFieldInParentScope()),
1392 SM, IgnoreFailedSplit);
1395std::optional<RenamerClangTidyCheck::FailureInfo>
1396IdentifierNamingCheck::getMacroFailureInfo(
const Token &MacroNameTok,
1397 const SourceManager &SM)
const {
1398 SourceLocation
Loc = MacroNameTok.getLocation();
1399 const FileStyle &Style = getStyleForFile(SM.getFilename(
Loc));
1400 if (!Style.isActive())
1401 return std::nullopt;
1403 return getFailureInfo(
"", MacroNameTok.getIdentifierInfo()->getName(),
1404 nullptr,
Loc, Style.getStyles(), Style.getHNOption(),
1405 SK_MacroDefinition, SM, IgnoreFailedSplit);
1408RenamerClangTidyCheck::DiagInfo
1410 const NamingCheckFailure &Failure)
const {
1411 return DiagInfo{
"invalid case style for %0 '%1'",
1412 [&](DiagnosticBuilder &Diag) {
1413 Diag << Failure.Info.KindName <<
ID.second;
1417StringRef IdentifierNamingCheck::getRealFileName(StringRef
FileName)
const {
1418 auto Iter = RealFileNameCache.try_emplace(
FileName);
1419 SmallString<256U> &RealFileName = Iter.first->getValue();
1421 return RealFileName;
1422 llvm::sys::fs::real_path(
FileName, RealFileName);
1423 return RealFileName;
1426const IdentifierNamingCheck::FileStyle &
1427IdentifierNamingCheck::getStyleForFile(StringRef
FileName)
const {
1428 if (!GetConfigPerFile)
1429 return *MainFileStyle;
1431 StringRef RealFileName = getRealFileName(
FileName);
1432 StringRef
Parent = llvm::sys::path::parent_path(RealFileName);
1433 auto Iter = NamingStylesCache.find(
Parent);
1434 if (Iter != NamingStylesCache.end())
1435 return Iter->getValue();
1437 llvm::StringRef CheckName =
getID();
1439 if (
Options.Checks && GlobList(*
Options.Checks).contains(CheckName)) {
1440 auto It = NamingStylesCache.try_emplace(
1444 return It.first->getValue();
1447 auto It = NamingStylesCache.try_emplace(
Parent);
1449 return It.first->getValue();
1452StyleKind IdentifierNamingCheck::findStyleKindForAnonField(
1453 const FieldDecl *AnonField,
1454 ArrayRef<std::optional<NamingStyle>> NamingStyles)
const {
1455 const IndirectFieldDecl *IFD =
1457 assert(IFD &&
"Found an anonymous record field without an IndirectFieldDecl");
1459 QualType
Type = AnonField->getType();
1461 if (
const auto *F = dyn_cast<FieldDecl>(IFD->chain().front())) {
1462 return findStyleKindForField(F,
Type, NamingStyles);
1465 if (
const auto *V = IFD->getVarDecl()) {
1466 return findStyleKindForVar(V,
Type, NamingStyles);
1472StyleKind IdentifierNamingCheck::findStyleKindForField(
1473 const FieldDecl *Field, QualType
Type,
1474 ArrayRef<std::optional<NamingStyle>> NamingStyles)
const {
1475 if (!
Type.isNull() &&
Type.isConstQualified()) {
1476 if (NamingStyles[SK_ConstantMember])
1477 return SK_ConstantMember;
1479 if (NamingStyles[SK_Constant])
1483 if (
Field->getAccess() == AS_private && NamingStyles[SK_PrivateMember])
1484 return SK_PrivateMember;
1486 if (
Field->getAccess() == AS_protected && NamingStyles[SK_ProtectedMember])
1487 return SK_ProtectedMember;
1489 if (
Field->getAccess() == AS_public && NamingStyles[SK_PublicMember])
1490 return SK_PublicMember;
1492 if (NamingStyles[SK_Member])
1498StyleKind IdentifierNamingCheck::findStyleKindForVar(
1499 const VarDecl *Var, QualType
Type,
1500 ArrayRef<std::optional<NamingStyle>> NamingStyles)
const {
1501 if (Var->isConstexpr() && NamingStyles[SK_ConstexprVariable])
1502 return SK_ConstexprVariable;
1504 if (!
Type.isNull() &&
Type.isConstQualified()) {
1505 if (Var->isStaticDataMember() && NamingStyles[SK_ClassConstant])
1506 return SK_ClassConstant;
1508 if (Var->isFileVarDecl() &&
Type.getTypePtr()->isAnyPointerType() &&
1509 NamingStyles[SK_GlobalConstantPointer])
1510 return SK_GlobalConstantPointer;
1512 if (Var->isFileVarDecl() && NamingStyles[SK_GlobalConstant])
1513 return SK_GlobalConstant;
1515 if (Var->isStaticLocal() && NamingStyles[SK_StaticConstant])
1516 return SK_StaticConstant;
1518 if (Var->isLocalVarDecl() &&
Type.getTypePtr()->isAnyPointerType() &&
1519 NamingStyles[SK_LocalConstantPointer])
1520 return SK_LocalConstantPointer;
1522 if (Var->isLocalVarDecl() && NamingStyles[SK_LocalConstant])
1523 return SK_LocalConstant;
1525 if (Var->isFunctionOrMethodVarDecl() && NamingStyles[SK_LocalConstant])
1526 return SK_LocalConstant;
1528 if (NamingStyles[SK_Constant])
1532 if (Var->isStaticDataMember() && NamingStyles[SK_ClassMember])
1533 return SK_ClassMember;
1535 if (Var->isFileVarDecl() &&
Type.getTypePtr()->isAnyPointerType() &&
1536 NamingStyles[SK_GlobalPointer])
1537 return SK_GlobalPointer;
1539 if (Var->isFileVarDecl() && NamingStyles[SK_GlobalVariable])
1540 return SK_GlobalVariable;
1542 if (Var->isStaticLocal() && NamingStyles[SK_StaticVariable])
1543 return SK_StaticVariable;
1545 if (Var->isLocalVarDecl() &&
Type.getTypePtr()->isAnyPointerType() &&
1546 NamingStyles[SK_LocalPointer])
1547 return SK_LocalPointer;
1549 if (Var->isLocalVarDecl() && NamingStyles[SK_LocalVariable])
1550 return SK_LocalVariable;
1552 if (Var->isFunctionOrMethodVarDecl() && NamingStyles[SK_LocalVariable])
1553 return SK_LocalVariable;
1555 if (NamingStyles[SK_Variable])
const FunctionDecl * Decl
llvm::SmallString< 256U > Name
#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
std::string fixupWithStyle(StringRef Type, StringRef Name, const IdentifierNamingCheck::NamingStyle &Style, const IdentifierNamingCheck::HungarianNotationOption &HNOption, const Decl *D) const
IdentifierNamingCheck::FileStyle getFileStyleFromOptions(const ClangTidyCheck::OptionsView &Options) const
bool isParamInMainLikeFunction(const ParmVarDecl &ParmDecl, bool IncludeMainLike) const
bool matchesStyle(StringRef Type, StringRef Name, const IdentifierNamingCheck::NamingStyle &Style, const IdentifierNamingCheck::HungarianNotationOption &HNOption, const NamedDecl *Decl) const
StyleKind findStyleKind(const NamedDecl *D, ArrayRef< std::optional< IdentifierNamingCheck::NamingStyle > > NamingStyles, bool IgnoreMainLikeFunctions, bool CheckAnonFieldInParentScope) const
@ 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[]
const IndirectFieldDecl * findOutermostIndirectFieldDeclForField(const FieldDecl *FD)
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
bool isCheckingAnonFieldInParentScope() 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