[clang-tidy][NFC] Fix "llvm-prefer-static-over-anonymous-namespace" warnings 1/N (#153885)

This commit is contained in:
Baranov Victor 2025-08-22 11:54:17 +03:00 committed by GitHub
parent 8bf105cb01
commit 00a405f666
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
17 changed files with 131 additions and 134 deletions

View File

@ -15,14 +15,12 @@ using namespace clang::ast_matchers;
namespace clang::tidy::bugprone { namespace clang::tidy::bugprone {
namespace {
// Determine if the result of an expression is "stored" in some way. // Determine if the result of an expression is "stored" in some way.
// It is true if the value is stored into a variable or used as initialization // It is true if the value is stored into a variable or used as initialization
// or passed to a function or constructor. // or passed to a function or constructor.
// For this use case compound assignments are not counted as a "store" (the 'E' // For this use case compound assignments are not counted as a "store" (the 'E'
// expression should have pointer type). // expression should have pointer type).
bool isExprValueStored(const Expr *E, ASTContext &C) { static bool isExprValueStored(const Expr *E, ASTContext &C) {
E = E->IgnoreParenCasts(); E = E->IgnoreParenCasts();
// Get first non-paren, non-cast parent. // Get first non-paren, non-cast parent.
ParentMapContext &PMap = C.getParentMapContext(); ParentMapContext &PMap = C.getParentMapContext();
@ -49,6 +47,8 @@ bool isExprValueStored(const Expr *E, ASTContext &C) {
return isa<CallExpr, CXXConstructExpr>(ParentE); return isa<CallExpr, CXXConstructExpr>(ParentE);
} }
namespace {
AST_MATCHER_P(CXXTryStmt, hasHandlerFor, AST_MATCHER_P(CXXTryStmt, hasHandlerFor,
ast_matchers::internal::Matcher<QualType>, InnerMatcher) { ast_matchers::internal::Matcher<QualType>, InnerMatcher) {
for (unsigned NH = Node.getNumHandlers(), I = 0; I < NH; ++I) { for (unsigned NH = Node.getNumHandlers(), I = 0; I < NH; ++I) {

View File

@ -14,10 +14,8 @@ using namespace clang::ast_matchers;
namespace clang::tidy::bugprone { namespace clang::tidy::bugprone {
namespace { static bool isConcatenatedLiteralsOnPurpose(ASTContext *Ctx,
const StringLiteral *Lit) {
bool isConcatenatedLiteralsOnPurpose(ASTContext *Ctx,
const StringLiteral *Lit) {
// String literals surrounded by parentheses are assumed to be on purpose. // String literals surrounded by parentheses are assumed to be on purpose.
// i.e.: const char* Array[] = { ("a" "b" "c"), "d", [...] }; // i.e.: const char* Array[] = { ("a" "b" "c"), "d", [...] };
@ -58,6 +56,8 @@ bool isConcatenatedLiteralsOnPurpose(ASTContext *Ctx,
return false; return false;
} }
namespace {
AST_MATCHER_P(StringLiteral, isConcatenatedLiteral, unsigned, AST_MATCHER_P(StringLiteral, isConcatenatedLiteral, unsigned,
MaxConcatenatedTokens) { MaxConcatenatedTokens) {
return Node.getNumConcatenated() > 1 && return Node.getNumConcatenated() > 1 &&

View File

@ -46,7 +46,9 @@ enum class ConversionKind {
ToLongDouble ToLongDouble
}; };
ConversionKind classifyConversionFunc(const FunctionDecl *FD) { } // namespace
static ConversionKind classifyConversionFunc(const FunctionDecl *FD) {
return llvm::StringSwitch<ConversionKind>(FD->getName()) return llvm::StringSwitch<ConversionKind>(FD->getName())
.Cases("atoi", "atol", ConversionKind::ToInt) .Cases("atoi", "atol", ConversionKind::ToInt)
.Case("atoll", ConversionKind::ToLongInt) .Case("atoll", ConversionKind::ToLongInt)
@ -54,8 +56,8 @@ ConversionKind classifyConversionFunc(const FunctionDecl *FD) {
.Default(ConversionKind::None); .Default(ConversionKind::None);
} }
ConversionKind classifyFormatString(StringRef Fmt, const LangOptions &LO, static ConversionKind classifyFormatString(StringRef Fmt, const LangOptions &LO,
const TargetInfo &TI) { const TargetInfo &TI) {
// Scan the format string for the first problematic format specifier, then // Scan the format string for the first problematic format specifier, then
// report that as the conversion type. This will miss additional conversion // report that as the conversion type. This will miss additional conversion
// specifiers, but that is acceptable behavior. // specifiers, but that is acceptable behavior.
@ -128,7 +130,7 @@ ConversionKind classifyFormatString(StringRef Fmt, const LangOptions &LO,
return H.get(); return H.get();
} }
StringRef classifyConversionType(ConversionKind K) { static StringRef classifyConversionType(ConversionKind K) {
switch (K) { switch (K) {
case ConversionKind::None: case ConversionKind::None:
llvm_unreachable("Unexpected conversion kind"); llvm_unreachable("Unexpected conversion kind");
@ -148,7 +150,7 @@ StringRef classifyConversionType(ConversionKind K) {
llvm_unreachable("Unknown conversion kind"); llvm_unreachable("Unknown conversion kind");
} }
StringRef classifyReplacement(ConversionKind K) { static StringRef classifyReplacement(ConversionKind K) {
switch (K) { switch (K) {
case ConversionKind::None: case ConversionKind::None:
llvm_unreachable("Unexpected conversion kind"); llvm_unreachable("Unexpected conversion kind");
@ -173,7 +175,6 @@ StringRef classifyReplacement(ConversionKind K) {
} }
llvm_unreachable("Unknown conversion kind"); llvm_unreachable("Unknown conversion kind");
} }
} // unnamed namespace
void StrToNumCheck::check(const MatchFinder::MatchResult &Result) { void StrToNumCheck::check(const MatchFinder::MatchResult &Result) {
const auto *Call = Result.Nodes.getNodeAs<CallExpr>("expr"); const auto *Call = Result.Nodes.getNodeAs<CallExpr>("expr");

View File

@ -59,7 +59,9 @@ AST_MATCHER(FunctionDecl, isPlacementOverload) {
return true; return true;
} }
OverloadedOperatorKind getCorrespondingOverload(const FunctionDecl *FD) { } // namespace
static OverloadedOperatorKind getCorrespondingOverload(const FunctionDecl *FD) {
switch (FD->getOverloadedOperator()) { switch (FD->getOverloadedOperator()) {
default: default:
break; break;
@ -75,7 +77,7 @@ OverloadedOperatorKind getCorrespondingOverload(const FunctionDecl *FD) {
llvm_unreachable("Not an overloaded allocation operator"); llvm_unreachable("Not an overloaded allocation operator");
} }
const char *getOperatorName(OverloadedOperatorKind K) { static const char *getOperatorName(OverloadedOperatorKind K) {
switch (K) { switch (K) {
default: default:
break; break;
@ -91,13 +93,14 @@ const char *getOperatorName(OverloadedOperatorKind K) {
llvm_unreachable("Not an overloaded allocation operator"); llvm_unreachable("Not an overloaded allocation operator");
} }
bool areCorrespondingOverloads(const FunctionDecl *LHS, static bool areCorrespondingOverloads(const FunctionDecl *LHS,
const FunctionDecl *RHS) { const FunctionDecl *RHS) {
return RHS->getOverloadedOperator() == getCorrespondingOverload(LHS); return RHS->getOverloadedOperator() == getCorrespondingOverload(LHS);
} }
bool hasCorrespondingOverloadInBaseClass(const CXXMethodDecl *MD, static bool
const CXXRecordDecl *RD = nullptr) { hasCorrespondingOverloadInBaseClass(const CXXMethodDecl *MD,
const CXXRecordDecl *RD = nullptr) {
if (RD) { if (RD) {
// Check the methods in the given class and accessible to derived classes. // Check the methods in the given class and accessible to derived classes.
for (const auto *BMD : RD->methods()) for (const auto *BMD : RD->methods())
@ -124,8 +127,6 @@ bool hasCorrespondingOverloadInBaseClass(const CXXMethodDecl *MD,
return false; return false;
} }
} // anonymous namespace
void NewDeleteOverloadsCheck::registerMatchers(MatchFinder *Finder) { void NewDeleteOverloadsCheck::registerMatchers(MatchFinder *Finder) {
// Match all operator new and operator delete overloads (including the array // Match all operator new and operator delete overloads (including the array
// forms). Do not match implicit operators, placement operators, or // forms). Do not match implicit operators, placement operators, or

View File

@ -395,16 +395,12 @@ void MacroToEnumCallbacks::Endif(SourceLocation Loc, SourceLocation IfLoc) {
--CurrentFile->ConditionScopes; --CurrentFile->ConditionScopes;
} }
namespace {
template <size_t N> template <size_t N>
bool textEquals(const char (&Needle)[N], const char *HayStack) { static bool textEquals(const char (&Needle)[N], const char *HayStack) {
return StringRef{HayStack, N - 1} == Needle; return StringRef{HayStack, N - 1} == Needle;
} }
template <size_t N> size_t len(const char (&)[N]) { return N - 1; } template <size_t N> static size_t len(const char (&)[N]) { return N - 1; }
} // namespace
void MacroToEnumCallbacks::PragmaDirective(SourceLocation Loc, void MacroToEnumCallbacks::PragmaDirective(SourceLocation Loc,
PragmaIntroducerKind Introducer) { PragmaIntroducerKind Introducer) {

View File

@ -16,14 +16,13 @@ using namespace clang::ast_matchers;
namespace clang::tidy::modernize { namespace clang::tidy::modernize {
namespace { static constexpr char ConstructorCall[] = "constructorCall";
static constexpr char ResetCall[] = "resetCall";
static constexpr char NewExpression[] = "newExpression";
constexpr char ConstructorCall[] = "constructorCall"; static std::string getNewExprName(const CXXNewExpr *NewExpr,
constexpr char ResetCall[] = "resetCall"; const SourceManager &SM,
constexpr char NewExpression[] = "newExpression"; const LangOptions &Lang) {
std::string getNewExprName(const CXXNewExpr *NewExpr, const SourceManager &SM,
const LangOptions &Lang) {
StringRef WrittenName = Lexer::getSourceText( StringRef WrittenName = Lexer::getSourceText(
CharSourceRange::getTokenRange( CharSourceRange::getTokenRange(
NewExpr->getAllocatedTypeSourceInfo()->getTypeLoc().getSourceRange()), NewExpr->getAllocatedTypeSourceInfo()->getTypeLoc().getSourceRange()),
@ -34,8 +33,6 @@ std::string getNewExprName(const CXXNewExpr *NewExpr, const SourceManager &SM,
return WrittenName.str(); return WrittenName.str();
} }
} // namespace
const char MakeSmartPtrCheck::PointerType[] = "pointerType"; const char MakeSmartPtrCheck::PointerType[] = "pointerType";
MakeSmartPtrCheck::MakeSmartPtrCheck(StringRef Name, ClangTidyContext *Context, MakeSmartPtrCheck::MakeSmartPtrCheck(StringRef Name, ClangTidyContext *Context,

View File

@ -19,9 +19,7 @@ using namespace clang::ast_matchers;
namespace clang::tidy::modernize { namespace clang::tidy::modernize {
namespace { static bool containsEscapes(StringRef HayStack, StringRef Escapes) {
bool containsEscapes(StringRef HayStack, StringRef Escapes) {
size_t BackSlash = HayStack.find('\\'); size_t BackSlash = HayStack.find('\\');
if (BackSlash == StringRef::npos) if (BackSlash == StringRef::npos)
return false; return false;
@ -35,16 +33,16 @@ bool containsEscapes(StringRef HayStack, StringRef Escapes) {
return true; return true;
} }
bool isRawStringLiteral(StringRef Text) { static bool isRawStringLiteral(StringRef Text) {
// Already a raw string literal if R comes before ". // Already a raw string literal if R comes before ".
const size_t QuotePos = Text.find('"'); const size_t QuotePos = Text.find('"');
assert(QuotePos != StringRef::npos); assert(QuotePos != StringRef::npos);
return (QuotePos > 0) && (Text[QuotePos - 1] == 'R'); return (QuotePos > 0) && (Text[QuotePos - 1] == 'R');
} }
bool containsEscapedCharacters(const MatchFinder::MatchResult &Result, static bool containsEscapedCharacters(const MatchFinder::MatchResult &Result,
const StringLiteral *Literal, const StringLiteral *Literal,
const CharsBitSet &DisallowedChars) { const CharsBitSet &DisallowedChars) {
// FIXME: Handle L"", u8"", u"" and U"" literals. // FIXME: Handle L"", u8"", u"" and U"" literals.
if (!Literal->isOrdinary()) if (!Literal->isOrdinary())
return false; return false;
@ -64,14 +62,12 @@ bool containsEscapedCharacters(const MatchFinder::MatchResult &Result,
return containsEscapes(Text, R"('\"?x01)"); return containsEscapes(Text, R"('\"?x01)");
} }
bool containsDelimiter(StringRef Bytes, const std::string &Delimiter) { static bool containsDelimiter(StringRef Bytes, const std::string &Delimiter) {
return Bytes.find(Delimiter.empty() return Bytes.find(Delimiter.empty()
? std::string(R"lit()")lit") ? std::string(R"lit()")lit")
: (")" + Delimiter + R"(")")) != StringRef::npos; : (")" + Delimiter + R"(")")) != StringRef::npos;
} }
} // namespace
RawStringLiteralCheck::RawStringLiteralCheck(StringRef Name, RawStringLiteralCheck::RawStringLiteralCheck(StringRef Name,
ClangTidyContext *Context) ClangTidyContext *Context)
: ClangTidyCheck(Name, Context), : ClangTidyCheck(Name, Context),

View File

@ -29,12 +29,13 @@
using namespace clang::ast_matchers; using namespace clang::ast_matchers;
namespace clang::tidy::objc { namespace clang::tidy::objc {
namespace {
static constexpr StringRef WeakText = "__weak"; static constexpr StringRef WeakText = "__weak";
static constexpr StringRef StrongText = "__strong"; static constexpr StringRef StrongText = "__strong";
static constexpr StringRef UnsafeUnretainedText = "__unsafe_unretained"; static constexpr StringRef UnsafeUnretainedText = "__unsafe_unretained";
namespace {
/// Matches ObjCIvarRefExpr, DeclRefExpr, or MemberExpr that reference /// Matches ObjCIvarRefExpr, DeclRefExpr, or MemberExpr that reference
/// Objective-C object (or block) variables or fields whose object lifetimes /// Objective-C object (or block) variables or fields whose object lifetimes
/// are not __unsafe_unretained. /// are not __unsafe_unretained.
@ -49,6 +50,8 @@ AST_POLYMORPHIC_MATCHER(isObjCManagedLifetime,
QT.getQualifiers().getObjCLifetime() > Qualifiers::OCL_ExplicitNone; QT.getQualifiers().getObjCLifetime() > Qualifiers::OCL_ExplicitNone;
} }
} // namespace
static std::optional<FixItHint> static std::optional<FixItHint>
fixItHintReplacementForOwnershipString(StringRef Text, CharSourceRange Range, fixItHintReplacementForOwnershipString(StringRef Text, CharSourceRange Range,
StringRef Ownership) { StringRef Ownership) {
@ -93,8 +96,6 @@ fixItHintForVarDecl(const VarDecl *VD, const SourceManager &SM,
return FixItHint::CreateInsertion(Range.getBegin(), "__unsafe_unretained "); return FixItHint::CreateInsertion(Range.getBegin(), "__unsafe_unretained ");
} }
} // namespace
void NSInvocationArgumentLifetimeCheck::registerMatchers(MatchFinder *Finder) { void NSInvocationArgumentLifetimeCheck::registerMatchers(MatchFinder *Finder) {
Finder->addMatcher( Finder->addMatcher(
traverse( traverse(

View File

@ -27,11 +27,14 @@ enum NamingStyle {
CategoryProperty = 2, CategoryProperty = 2,
}; };
} // namespace
/// For now we will only fix 'CamelCase' or 'abc_CamelCase' property to /// For now we will only fix 'CamelCase' or 'abc_CamelCase' property to
/// 'camelCase' or 'abc_camelCase'. For other cases the users need to /// 'camelCase' or 'abc_camelCase'. For other cases the users need to
/// come up with a proper name by their own. /// come up with a proper name by their own.
/// FIXME: provide fix for snake_case to snakeCase /// FIXME: provide fix for snake_case to snakeCase
FixItHint generateFixItHint(const ObjCPropertyDecl *Decl, NamingStyle Style) { static FixItHint generateFixItHint(const ObjCPropertyDecl *Decl,
NamingStyle Style) {
auto Name = Decl->getName(); auto Name = Decl->getName();
auto NewName = Decl->getName().str(); auto NewName = Decl->getName().str();
size_t Index = 0; size_t Index = 0;
@ -50,7 +53,7 @@ FixItHint generateFixItHint(const ObjCPropertyDecl *Decl, NamingStyle Style) {
return {}; return {};
} }
std::string validPropertyNameRegex(bool UsedInMatcher) { static std::string validPropertyNameRegex(bool UsedInMatcher) {
// Allow any of these names: // Allow any of these names:
// foo // foo
// fooBar // fooBar
@ -72,13 +75,13 @@ std::string validPropertyNameRegex(bool UsedInMatcher) {
return StartMatcher + "([a-z]|[A-Z][A-Z0-9])[a-z0-9A-Z]*$"; return StartMatcher + "([a-z]|[A-Z][A-Z0-9])[a-z0-9A-Z]*$";
} }
bool hasCategoryPropertyPrefix(llvm::StringRef PropertyName) { static bool hasCategoryPropertyPrefix(llvm::StringRef PropertyName) {
auto RegexExp = auto RegexExp =
llvm::Regex("^[a-zA-Z][a-zA-Z0-9]*_[a-zA-Z0-9][a-zA-Z0-9_]+$"); llvm::Regex("^[a-zA-Z][a-zA-Z0-9]*_[a-zA-Z0-9][a-zA-Z0-9_]+$");
return RegexExp.match(PropertyName); return RegexExp.match(PropertyName);
} }
bool prefixedPropertyNameValid(llvm::StringRef PropertyName) { static bool prefixedPropertyNameValid(llvm::StringRef PropertyName) {
size_t Start = PropertyName.find_first_of('_'); size_t Start = PropertyName.find_first_of('_');
assert(Start != llvm::StringRef::npos && Start + 1 < PropertyName.size()); assert(Start != llvm::StringRef::npos && Start + 1 < PropertyName.size());
auto Prefix = PropertyName.substr(0, Start); auto Prefix = PropertyName.substr(0, Start);
@ -88,7 +91,6 @@ bool prefixedPropertyNameValid(llvm::StringRef PropertyName) {
auto RegexExp = llvm::Regex(llvm::StringRef(validPropertyNameRegex(false))); auto RegexExp = llvm::Regex(llvm::StringRef(validPropertyNameRegex(false)));
return RegexExp.match(PropertyName.substr(Start + 1)); return RegexExp.match(PropertyName.substr(Start + 1));
} }
} // namespace
void PropertyDeclarationCheck::registerMatchers(MatchFinder *Finder) { void PropertyDeclarationCheck::registerMatchers(MatchFinder *Finder) {
Finder->addMatcher(objcPropertyDecl( Finder->addMatcher(objcPropertyDecl(

View File

@ -17,7 +17,6 @@
#include <optional> #include <optional>
namespace clang::tidy::performance { namespace clang::tidy::performance {
namespace {
using namespace ::clang::ast_matchers; using namespace ::clang::ast_matchers;
using llvm::StringRef; using llvm::StringRef;
@ -30,8 +29,8 @@ static constexpr StringRef MethodDeclId = "methodDecl";
static constexpr StringRef FunctionDeclId = "functionDecl"; static constexpr StringRef FunctionDeclId = "functionDecl";
static constexpr StringRef OldVarDeclId = "oldVarDecl"; static constexpr StringRef OldVarDeclId = "oldVarDecl";
void recordFixes(const VarDecl &Var, ASTContext &Context, static void recordFixes(const VarDecl &Var, ASTContext &Context,
DiagnosticBuilder &Diagnostic) { DiagnosticBuilder &Diagnostic) {
Diagnostic << utils::fixit::changeVarDeclToReference(Var, Context); Diagnostic << utils::fixit::changeVarDeclToReference(Var, Context);
if (!Var.getType().isLocalConstQualified()) { if (!Var.getType().isLocalConstQualified()) {
if (std::optional<FixItHint> Fix = utils::fixit::addQualifierToVarDecl( if (std::optional<FixItHint> Fix = utils::fixit::addQualifierToVarDecl(
@ -40,8 +39,8 @@ void recordFixes(const VarDecl &Var, ASTContext &Context,
} }
} }
std::optional<SourceLocation> firstLocAfterNewLine(SourceLocation Loc, static std::optional<SourceLocation> firstLocAfterNewLine(SourceLocation Loc,
SourceManager &SM) { SourceManager &SM) {
bool Invalid = false; bool Invalid = false;
const char *TextAfter = SM.getCharacterData(Loc, &Invalid); const char *TextAfter = SM.getCharacterData(Loc, &Invalid);
if (Invalid) { if (Invalid) {
@ -51,8 +50,8 @@ std::optional<SourceLocation> firstLocAfterNewLine(SourceLocation Loc,
return Loc.getLocWithOffset(TextAfter[Offset] == '\0' ? Offset : Offset + 1); return Loc.getLocWithOffset(TextAfter[Offset] == '\0' ? Offset : Offset + 1);
} }
void recordRemoval(const DeclStmt &Stmt, ASTContext &Context, static void recordRemoval(const DeclStmt &Stmt, ASTContext &Context,
DiagnosticBuilder &Diagnostic) { DiagnosticBuilder &Diagnostic) {
auto &SM = Context.getSourceManager(); auto &SM = Context.getSourceManager();
// Attempt to remove trailing comments as well. // Attempt to remove trailing comments as well.
auto Tok = utils::lexer::findNextTokenSkippingComments(Stmt.getEndLoc(), SM, auto Tok = utils::lexer::findNextTokenSkippingComments(Stmt.getEndLoc(), SM,
@ -74,6 +73,8 @@ void recordRemoval(const DeclStmt &Stmt, ASTContext &Context,
} }
} }
namespace {
AST_MATCHER_FUNCTION_P(StatementMatcher, AST_MATCHER_FUNCTION_P(StatementMatcher,
isRefReturningMethodCallWithConstOverloads, isRefReturningMethodCallWithConstOverloads,
std::vector<StringRef>, ExcludedContainerTypes) { std::vector<StringRef>, ExcludedContainerTypes) {
@ -130,6 +131,8 @@ AST_MATCHER_FUNCTION_P(StatementMatcher, initializerReturnsReferenceToConst,
hasUnaryOperand(OldVarDeclRef))))); hasUnaryOperand(OldVarDeclRef)))));
} }
} // namespace
// This checks that the variable itself is only used as const, and also makes // This checks that the variable itself is only used as const, and also makes
// sure that it does not reference another variable that could be modified in // sure that it does not reference another variable that could be modified in
// the BlockStmt. It does this by checking the following: // the BlockStmt. It does this by checking the following:
@ -180,13 +183,13 @@ static bool isInitializingVariableImmutable(
return false; return false;
} }
bool isVariableUnused(const VarDecl &Var, const Stmt &BlockStmt, static bool isVariableUnused(const VarDecl &Var, const Stmt &BlockStmt,
ASTContext &Context) { ASTContext &Context) {
return allDeclRefExprs(Var, BlockStmt, Context).empty(); return allDeclRefExprs(Var, BlockStmt, Context).empty();
} }
const SubstTemplateTypeParmType *getSubstitutedType(const QualType &Type, static const SubstTemplateTypeParmType *
ASTContext &Context) { getSubstitutedType(const QualType &Type, ASTContext &Context) {
auto Matches = match( auto Matches = match(
qualType(anyOf(substTemplateTypeParmType().bind("subst"), qualType(anyOf(substTemplateTypeParmType().bind("subst"),
hasDescendant(substTemplateTypeParmType().bind("subst")))), hasDescendant(substTemplateTypeParmType().bind("subst")))),
@ -194,9 +197,9 @@ const SubstTemplateTypeParmType *getSubstitutedType(const QualType &Type,
return selectFirst<SubstTemplateTypeParmType>("subst", Matches); return selectFirst<SubstTemplateTypeParmType>("subst", Matches);
} }
bool differentReplacedTemplateParams(const QualType &VarType, static bool differentReplacedTemplateParams(const QualType &VarType,
const QualType &InitializerType, const QualType &InitializerType,
ASTContext &Context) { ASTContext &Context) {
if (const SubstTemplateTypeParmType *VarTmplType = if (const SubstTemplateTypeParmType *VarTmplType =
getSubstitutedType(VarType, Context)) { getSubstitutedType(VarType, Context)) {
if (const SubstTemplateTypeParmType *InitializerTmplType = if (const SubstTemplateTypeParmType *InitializerTmplType =
@ -212,8 +215,8 @@ bool differentReplacedTemplateParams(const QualType &VarType,
return false; return false;
} }
QualType constructorArgumentType(const VarDecl *OldVar, static QualType constructorArgumentType(const VarDecl *OldVar,
const BoundNodes &Nodes) { const BoundNodes &Nodes) {
if (OldVar) { if (OldVar) {
return OldVar->getType(); return OldVar->getType();
} }
@ -224,8 +227,6 @@ QualType constructorArgumentType(const VarDecl *OldVar,
return MethodDecl->getReturnType(); return MethodDecl->getReturnType();
} }
} // namespace
UnnecessaryCopyInitialization::UnnecessaryCopyInitialization( UnnecessaryCopyInitialization::UnnecessaryCopyInitialization(
StringRef Name, ClangTidyContext *Context) StringRef Name, ClangTidyContext *Context)
: ClangTidyCheck(Name, Context), : ClangTidyCheck(Name, Context),

View File

@ -21,16 +21,14 @@ using namespace clang::ast_matchers;
namespace clang::tidy::performance { namespace clang::tidy::performance {
namespace { static std::string paramNameOrIndex(StringRef Name, size_t Index) {
std::string paramNameOrIndex(StringRef Name, size_t Index) {
return (Name.empty() ? llvm::Twine('#') + llvm::Twine(Index + 1) return (Name.empty() ? llvm::Twine('#') + llvm::Twine(Index + 1)
: llvm::Twine('\'') + Name + llvm::Twine('\'')) : llvm::Twine('\'') + Name + llvm::Twine('\''))
.str(); .str();
} }
bool hasLoopStmtAncestor(const DeclRefExpr &DeclRef, const Decl &Decl, static bool hasLoopStmtAncestor(const DeclRefExpr &DeclRef, const Decl &Decl,
ASTContext &Context) { ASTContext &Context) {
auto Matches = match( auto Matches = match(
traverse(TK_AsIs, traverse(TK_AsIs,
decl(forEachDescendant(declRefExpr( decl(forEachDescendant(declRefExpr(
@ -41,8 +39,6 @@ bool hasLoopStmtAncestor(const DeclRefExpr &DeclRef, const Decl &Decl,
return Matches.empty(); return Matches.empty();
} }
} // namespace
UnnecessaryValueParamCheck::UnnecessaryValueParamCheck( UnnecessaryValueParamCheck::UnnecessaryValueParamCheck(
StringRef Name, ClangTidyContext *Context) StringRef Name, ClangTidyContext *Context)
: ClangTidyCheck(Name, Context), : ClangTidyCheck(Name, Context),

View File

@ -122,15 +122,15 @@ AST_MATCHER(EnumDecl, hasSequentialInitialValues) {
return !AllEnumeratorsArePowersOfTwo; return !AllEnumeratorsArePowersOfTwo;
} }
std::string getName(const EnumDecl *Decl) { } // namespace
static std::string getName(const EnumDecl *Decl) {
if (!Decl->getDeclName()) if (!Decl->getDeclName())
return "<unnamed>"; return "<unnamed>";
return Decl->getQualifiedNameAsString(); return Decl->getQualifiedNameAsString();
} }
} // namespace
EnumInitialValueCheck::EnumInitialValueCheck(StringRef Name, EnumInitialValueCheck::EnumInitialValueCheck(StringRef Name,
ClangTidyContext *Context) ClangTidyContext *Context)
: ClangTidyCheck(Name, Context), : ClangTidyCheck(Name, Context),

View File

@ -144,6 +144,8 @@ struct CognitiveComplexity final {
void account(SourceLocation Loc, unsigned short Nesting, Criteria C); void account(SourceLocation Loc, unsigned short Nesting, Criteria C);
}; };
} // namespace
// All the possible messages that can be output. The choice of the message // All the possible messages that can be output. The choice of the message
// to use is based of the combination of the CognitiveComplexity::Criteria. // to use is based of the combination of the CognitiveComplexity::Criteria.
// It would be nice to have it in CognitiveComplexity struct, but then it is // It would be nice to have it in CognitiveComplexity struct, but then it is
@ -163,23 +165,27 @@ static const std::array<const StringRef, 4> Msgs = {{
}}; }};
// Criteria is a bitset, thus a few helpers are needed. // Criteria is a bitset, thus a few helpers are needed.
CognitiveComplexity::Criteria operator|(CognitiveComplexity::Criteria LHS, static CognitiveComplexity::Criteria
CognitiveComplexity::Criteria RHS) { operator|(CognitiveComplexity::Criteria LHS,
CognitiveComplexity::Criteria RHS) {
return static_cast<CognitiveComplexity::Criteria>(llvm::to_underlying(LHS) | return static_cast<CognitiveComplexity::Criteria>(llvm::to_underlying(LHS) |
llvm::to_underlying(RHS)); llvm::to_underlying(RHS));
} }
CognitiveComplexity::Criteria operator&(CognitiveComplexity::Criteria LHS, static CognitiveComplexity::Criteria
CognitiveComplexity::Criteria RHS) { operator&(CognitiveComplexity::Criteria LHS,
CognitiveComplexity::Criteria RHS) {
return static_cast<CognitiveComplexity::Criteria>(llvm::to_underlying(LHS) & return static_cast<CognitiveComplexity::Criteria>(llvm::to_underlying(LHS) &
llvm::to_underlying(RHS)); llvm::to_underlying(RHS));
} }
CognitiveComplexity::Criteria &operator|=(CognitiveComplexity::Criteria &LHS, static CognitiveComplexity::Criteria &
CognitiveComplexity::Criteria RHS) { operator|=(CognitiveComplexity::Criteria &LHS,
CognitiveComplexity::Criteria RHS) {
LHS = operator|(LHS, RHS); LHS = operator|(LHS, RHS);
return LHS; return LHS;
} }
CognitiveComplexity::Criteria &operator&=(CognitiveComplexity::Criteria &LHS, static CognitiveComplexity::Criteria &
CognitiveComplexity::Criteria RHS) { operator&=(CognitiveComplexity::Criteria &LHS,
CognitiveComplexity::Criteria RHS) {
LHS = operator&(LHS, RHS); LHS = operator&(LHS, RHS);
return LHS; return LHS;
} }
@ -199,6 +205,8 @@ void CognitiveComplexity::account(SourceLocation Loc, unsigned short Nesting,
Total += Increase; Total += Increase;
} }
namespace {
class FunctionASTVisitor final class FunctionASTVisitor final
: public RecursiveASTVisitor<FunctionASTVisitor> { : public RecursiveASTVisitor<FunctionASTVisitor> {
using Base = RecursiveASTVisitor<FunctionASTVisitor>; using Base = RecursiveASTVisitor<FunctionASTVisitor>;

View File

@ -41,9 +41,11 @@ AST_MATCHER(Stmt, isNULLMacroExpansion) {
return isNULLMacroExpansion(&Node, Finder->getASTContext()); return isNULLMacroExpansion(&Node, Finder->getASTContext());
} }
StringRef getZeroLiteralToCompareWithForType(CastKind CastExprKind, } // namespace
QualType Type,
ASTContext &Context) { static StringRef getZeroLiteralToCompareWithForType(CastKind CastExprKind,
QualType Type,
ASTContext &Context) {
switch (CastExprKind) { switch (CastExprKind) {
case CK_IntegralToBoolean: case CK_IntegralToBoolean:
return Type->isUnsignedIntegerType() ? "0u" : "0"; return Type->isUnsignedIntegerType() ? "0u" : "0";
@ -62,15 +64,15 @@ StringRef getZeroLiteralToCompareWithForType(CastKind CastExprKind,
} }
} }
bool isUnaryLogicalNotOperator(const Stmt *Statement) { static bool isUnaryLogicalNotOperator(const Stmt *Statement) {
const auto *UnaryOperatorExpr = dyn_cast<UnaryOperator>(Statement); const auto *UnaryOperatorExpr = dyn_cast<UnaryOperator>(Statement);
return UnaryOperatorExpr && UnaryOperatorExpr->getOpcode() == UO_LNot; return UnaryOperatorExpr && UnaryOperatorExpr->getOpcode() == UO_LNot;
} }
void fixGenericExprCastToBool(DiagnosticBuilder &Diag, static void fixGenericExprCastToBool(DiagnosticBuilder &Diag,
const ImplicitCastExpr *Cast, const Stmt *Parent, const ImplicitCastExpr *Cast,
ASTContext &Context, const Stmt *Parent, ASTContext &Context,
bool UseUpperCaseLiteralSuffix) { bool UseUpperCaseLiteralSuffix) {
// In case of expressions like (! integer), we should remove the redundant not // In case of expressions like (! integer), we should remove the redundant not
// operator and use inverted comparison (integer == 0). // operator and use inverted comparison (integer == 0).
bool InvertComparison = bool InvertComparison =
@ -133,8 +135,8 @@ void fixGenericExprCastToBool(DiagnosticBuilder &Diag,
Diag << FixItHint::CreateInsertion(EndLoc, EndLocInsertion); Diag << FixItHint::CreateInsertion(EndLoc, EndLocInsertion);
} }
StringRef getEquivalentBoolLiteralForExpr(const Expr *Expression, static StringRef getEquivalentBoolLiteralForExpr(const Expr *Expression,
ASTContext &Context) { ASTContext &Context) {
if (isNULLMacroExpansion(Expression, Context)) { if (isNULLMacroExpansion(Expression, Context)) {
return "false"; return "false";
} }
@ -161,7 +163,7 @@ StringRef getEquivalentBoolLiteralForExpr(const Expr *Expression,
return {}; return {};
} }
bool needsSpacePrefix(SourceLocation Loc, ASTContext &Context) { static bool needsSpacePrefix(SourceLocation Loc, ASTContext &Context) {
SourceRange PrefixRange(Loc.getLocWithOffset(-1), Loc); SourceRange PrefixRange(Loc.getLocWithOffset(-1), Loc);
StringRef SpaceBeforeStmtStr = Lexer::getSourceText( StringRef SpaceBeforeStmtStr = Lexer::getSourceText(
CharSourceRange::getCharRange(PrefixRange), Context.getSourceManager(), CharSourceRange::getCharRange(PrefixRange), Context.getSourceManager(),
@ -173,9 +175,10 @@ bool needsSpacePrefix(SourceLocation Loc, ASTContext &Context) {
return !AllowedCharacters.contains(SpaceBeforeStmtStr.back()); return !AllowedCharacters.contains(SpaceBeforeStmtStr.back());
} }
void fixGenericExprCastFromBool(DiagnosticBuilder &Diag, static void fixGenericExprCastFromBool(DiagnosticBuilder &Diag,
const ImplicitCastExpr *Cast, const ImplicitCastExpr *Cast,
ASTContext &Context, StringRef OtherType) { ASTContext &Context,
StringRef OtherType) {
if (!Context.getLangOpts().CPlusPlus) { if (!Context.getLangOpts().CPlusPlus) {
Diag << FixItHint::CreateInsertion(Cast->getBeginLoc(), Diag << FixItHint::CreateInsertion(Cast->getBeginLoc(),
(Twine("(") + OtherType + ")").str()); (Twine("(") + OtherType + ")").str());
@ -200,8 +203,9 @@ void fixGenericExprCastFromBool(DiagnosticBuilder &Diag,
} }
} }
StringRef getEquivalentForBoolLiteral(const CXXBoolLiteralExpr *BoolLiteral, static StringRef
QualType DestType, ASTContext &Context) { getEquivalentForBoolLiteral(const CXXBoolLiteralExpr *BoolLiteral,
QualType DestType, ASTContext &Context) {
// Prior to C++11, false literal could be implicitly converted to pointer. // Prior to C++11, false literal could be implicitly converted to pointer.
if (!Context.getLangOpts().CPlusPlus11 && if (!Context.getLangOpts().CPlusPlus11 &&
(DestType->isPointerType() || DestType->isMemberPointerType()) && (DestType->isPointerType() || DestType->isMemberPointerType()) &&
@ -222,8 +226,8 @@ StringRef getEquivalentForBoolLiteral(const CXXBoolLiteralExpr *BoolLiteral,
return BoolLiteral->getValue() ? "1" : "0"; return BoolLiteral->getValue() ? "1" : "0";
} }
bool isCastAllowedInCondition(const ImplicitCastExpr *Cast, static bool isCastAllowedInCondition(const ImplicitCastExpr *Cast,
ASTContext &Context) { ASTContext &Context) {
std::queue<const Stmt *> Q; std::queue<const Stmt *> Q;
Q.push(Cast); Q.push(Cast);
@ -251,8 +255,6 @@ bool isCastAllowedInCondition(const ImplicitCastExpr *Cast,
return false; return false;
} }
} // anonymous namespace
ImplicitBoolConversionCheck::ImplicitBoolConversionCheck( ImplicitBoolConversionCheck::ImplicitBoolConversionCheck(
StringRef Name, ClangTidyContext *Context) StringRef Name, ClangTidyContext *Context)
: ClangTidyCheck(Name, Context), : ClangTidyCheck(Name, Context),

View File

@ -28,8 +28,11 @@ AST_MATCHER_P(QualType, hasUnqualifiedType,
enum class Qualifier { Const, Volatile, Restrict }; enum class Qualifier { Const, Volatile, Restrict };
std::optional<Token> findQualToken(const VarDecl *Decl, Qualifier Qual, } // namespace
const MatchFinder::MatchResult &Result) {
static std::optional<Token>
findQualToken(const VarDecl *Decl, Qualifier Qual,
const MatchFinder::MatchResult &Result) {
// Since either of the locs can be in a macro, use `makeFileCharRange` to be // Since either of the locs can be in a macro, use `makeFileCharRange` to be
// sure that we have a consistent `CharSourceRange`, located entirely in the // sure that we have a consistent `CharSourceRange`, located entirely in the
// source file. // source file.
@ -58,7 +61,7 @@ std::optional<Token> findQualToken(const VarDecl *Decl, Qualifier Qual,
*Result.SourceManager); *Result.SourceManager);
} }
std::optional<SourceRange> static std::optional<SourceRange>
getTypeSpecifierLocation(const VarDecl *Var, getTypeSpecifierLocation(const VarDecl *Var,
const MatchFinder::MatchResult &Result) { const MatchFinder::MatchResult &Result) {
SourceRange TypeSpecifier( SourceRange TypeSpecifier(
@ -73,8 +76,8 @@ getTypeSpecifierLocation(const VarDecl *Var,
return TypeSpecifier; return TypeSpecifier;
} }
std::optional<SourceRange> mergeReplacementRange(SourceRange &TypeSpecifier, static std::optional<SourceRange>
const Token &ConstToken) { mergeReplacementRange(SourceRange &TypeSpecifier, const Token &ConstToken) {
if (TypeSpecifier.getBegin().getLocWithOffset(-1) == ConstToken.getEndLoc()) { if (TypeSpecifier.getBegin().getLocWithOffset(-1) == ConstToken.getEndLoc()) {
TypeSpecifier.setBegin(ConstToken.getLocation()); TypeSpecifier.setBegin(ConstToken.getLocation());
return std::nullopt; return std::nullopt;
@ -86,21 +89,19 @@ std::optional<SourceRange> mergeReplacementRange(SourceRange &TypeSpecifier,
return SourceRange(ConstToken.getLocation(), ConstToken.getEndLoc()); return SourceRange(ConstToken.getLocation(), ConstToken.getEndLoc());
} }
bool isPointerConst(QualType QType) { static bool isPointerConst(QualType QType) {
QualType Pointee = QType->getPointeeType(); QualType Pointee = QType->getPointeeType();
assert(!Pointee.isNull() && "can't have a null Pointee"); assert(!Pointee.isNull() && "can't have a null Pointee");
return Pointee.isConstQualified(); return Pointee.isConstQualified();
} }
bool isAutoPointerConst(QualType QType) { static bool isAutoPointerConst(QualType QType) {
QualType Pointee = QualType Pointee =
cast<AutoType>(QType->getPointeeType().getTypePtr())->desugar(); cast<AutoType>(QType->getPointeeType().getTypePtr())->desugar();
assert(!Pointee.isNull() && "can't have a null Pointee"); assert(!Pointee.isNull() && "can't have a null Pointee");
return Pointee.isConstQualified(); return Pointee.isConstQualified();
} }
} // namespace
QualifiedAutoCheck::QualifiedAutoCheck(StringRef Name, QualifiedAutoCheck::QualifiedAutoCheck(StringRef Name,
ClangTidyContext *Context) ClangTidyContext *Context)
: ClangTidyCheck(Name, Context), : ClangTidyCheck(Name, Context),

View File

@ -14,19 +14,18 @@ using namespace clang::ast_matchers;
namespace clang::tidy::readability { namespace clang::tidy::readability {
namespace { static const char *const RedundantReturnDiag =
"redundant return statement at the end "
"of a function with a void return type";
static const char *const RedundantContinueDiag =
"redundant continue statement at the "
"end of loop statement";
const char *const RedundantReturnDiag = "redundant return statement at the end " static bool isLocationInMacroExpansion(const SourceManager &SM,
"of a function with a void return type"; SourceLocation Loc) {
const char *const RedundantContinueDiag = "redundant continue statement at the "
"end of loop statement";
bool isLocationInMacroExpansion(const SourceManager &SM, SourceLocation Loc) {
return SM.isMacroBodyExpansion(Loc) || SM.isMacroArgExpansion(Loc); return SM.isMacroBodyExpansion(Loc) || SM.isMacroArgExpansion(Loc);
} }
} // namespace
void RedundantControlFlowCheck::registerMatchers(MatchFinder *Finder) { void RedundantControlFlowCheck::registerMatchers(MatchFinder *Finder) {
Finder->addMatcher( Finder->addMatcher(
functionDecl(isDefinition(), returns(voidType()), functionDecl(isDefinition(), returns(voidType()),

View File

@ -13,16 +13,14 @@
namespace clang::tidy::utils::type_traits { namespace clang::tidy::utils::type_traits {
namespace { static bool classHasTrivialCopyAndDestroy(QualType Type) {
bool classHasTrivialCopyAndDestroy(QualType Type) {
auto *Record = Type->getAsCXXRecordDecl(); auto *Record = Type->getAsCXXRecordDecl();
return Record && Record->hasDefinition() && return Record && Record->hasDefinition() &&
!Record->hasNonTrivialCopyConstructor() && !Record->hasNonTrivialCopyConstructor() &&
!Record->hasNonTrivialDestructor(); !Record->hasNonTrivialDestructor();
} }
bool hasDeletedCopyConstructor(QualType Type) { static bool hasDeletedCopyConstructor(QualType Type) {
auto *Record = Type->getAsCXXRecordDecl(); auto *Record = Type->getAsCXXRecordDecl();
if (!Record || !Record->hasDefinition()) if (!Record || !Record->hasDefinition())
return false; return false;
@ -33,8 +31,6 @@ bool hasDeletedCopyConstructor(QualType Type) {
return false; return false;
} }
} // namespace
std::optional<bool> isExpensiveToCopy(QualType Type, std::optional<bool> isExpensiveToCopy(QualType Type,
const ASTContext &Context) { const ASTContext &Context) {
if (Type->isDependentType() || Type->isIncompleteType()) if (Type->isDependentType() || Type->isIncompleteType())