diff --git a/clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.cpp index b68888cb5b928..6344b4bb6271e 100644 --- a/clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.cpp @@ -15,14 +15,12 @@ using namespace clang::ast_matchers; namespace clang::tidy::bugprone { -namespace { - // 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 // or passed to a function or constructor. // For this use case compound assignments are not counted as a "store" (the 'E' // expression should have pointer type). -bool isExprValueStored(const Expr *E, ASTContext &C) { +static bool isExprValueStored(const Expr *E, ASTContext &C) { E = E->IgnoreParenCasts(); // Get first non-paren, non-cast parent. ParentMapContext &PMap = C.getParentMapContext(); @@ -49,6 +47,8 @@ bool isExprValueStored(const Expr *E, ASTContext &C) { return isa(ParentE); } +namespace { + AST_MATCHER_P(CXXTryStmt, hasHandlerFor, ast_matchers::internal::Matcher, InnerMatcher) { for (unsigned NH = Node.getNumHandlers(), I = 0; I < NH; ++I) { diff --git a/clang-tools-extra/clang-tidy/bugprone/SuspiciousMissingCommaCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/SuspiciousMissingCommaCheck.cpp index 81c38d07a0c7e..5b1b28dbfbadd 100644 --- a/clang-tools-extra/clang-tidy/bugprone/SuspiciousMissingCommaCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/SuspiciousMissingCommaCheck.cpp @@ -14,10 +14,8 @@ using namespace clang::ast_matchers; namespace clang::tidy::bugprone { -namespace { - -bool isConcatenatedLiteralsOnPurpose(ASTContext *Ctx, - const StringLiteral *Lit) { +static bool isConcatenatedLiteralsOnPurpose(ASTContext *Ctx, + const StringLiteral *Lit) { // String literals surrounded by parentheses are assumed to be on purpose. // i.e.: const char* Array[] = { ("a" "b" "c"), "d", [...] }; @@ -58,6 +56,8 @@ bool isConcatenatedLiteralsOnPurpose(ASTContext *Ctx, return false; } +namespace { + AST_MATCHER_P(StringLiteral, isConcatenatedLiteral, unsigned, MaxConcatenatedTokens) { return Node.getNumConcatenated() > 1 && diff --git a/clang-tools-extra/clang-tidy/cert/StrToNumCheck.cpp b/clang-tools-extra/clang-tidy/cert/StrToNumCheck.cpp index 3b59d2357fe29..95536bb1cfdb2 100644 --- a/clang-tools-extra/clang-tidy/cert/StrToNumCheck.cpp +++ b/clang-tools-extra/clang-tidy/cert/StrToNumCheck.cpp @@ -46,7 +46,9 @@ enum class ConversionKind { ToLongDouble }; -ConversionKind classifyConversionFunc(const FunctionDecl *FD) { +} // namespace + +static ConversionKind classifyConversionFunc(const FunctionDecl *FD) { return llvm::StringSwitch(FD->getName()) .Cases("atoi", "atol", ConversionKind::ToInt) .Case("atoll", ConversionKind::ToLongInt) @@ -54,8 +56,8 @@ ConversionKind classifyConversionFunc(const FunctionDecl *FD) { .Default(ConversionKind::None); } -ConversionKind classifyFormatString(StringRef Fmt, const LangOptions &LO, - const TargetInfo &TI) { +static ConversionKind classifyFormatString(StringRef Fmt, const LangOptions &LO, + const TargetInfo &TI) { // Scan the format string for the first problematic format specifier, then // report that as the conversion type. This will miss additional conversion // specifiers, but that is acceptable behavior. @@ -128,7 +130,7 @@ ConversionKind classifyFormatString(StringRef Fmt, const LangOptions &LO, return H.get(); } -StringRef classifyConversionType(ConversionKind K) { +static StringRef classifyConversionType(ConversionKind K) { switch (K) { case ConversionKind::None: llvm_unreachable("Unexpected conversion kind"); @@ -148,7 +150,7 @@ StringRef classifyConversionType(ConversionKind K) { llvm_unreachable("Unknown conversion kind"); } -StringRef classifyReplacement(ConversionKind K) { +static StringRef classifyReplacement(ConversionKind K) { switch (K) { case ConversionKind::None: llvm_unreachable("Unexpected conversion kind"); @@ -173,7 +175,6 @@ StringRef classifyReplacement(ConversionKind K) { } llvm_unreachable("Unknown conversion kind"); } -} // unnamed namespace void StrToNumCheck::check(const MatchFinder::MatchResult &Result) { const auto *Call = Result.Nodes.getNodeAs("expr"); diff --git a/clang-tools-extra/clang-tidy/misc/NewDeleteOverloadsCheck.cpp b/clang-tools-extra/clang-tidy/misc/NewDeleteOverloadsCheck.cpp index 40808aaf7c3da..2837f40bc49b8 100644 --- a/clang-tools-extra/clang-tidy/misc/NewDeleteOverloadsCheck.cpp +++ b/clang-tools-extra/clang-tidy/misc/NewDeleteOverloadsCheck.cpp @@ -59,7 +59,9 @@ AST_MATCHER(FunctionDecl, isPlacementOverload) { return true; } -OverloadedOperatorKind getCorrespondingOverload(const FunctionDecl *FD) { +} // namespace + +static OverloadedOperatorKind getCorrespondingOverload(const FunctionDecl *FD) { switch (FD->getOverloadedOperator()) { default: break; @@ -75,7 +77,7 @@ OverloadedOperatorKind getCorrespondingOverload(const FunctionDecl *FD) { llvm_unreachable("Not an overloaded allocation operator"); } -const char *getOperatorName(OverloadedOperatorKind K) { +static const char *getOperatorName(OverloadedOperatorKind K) { switch (K) { default: break; @@ -91,13 +93,14 @@ const char *getOperatorName(OverloadedOperatorKind K) { llvm_unreachable("Not an overloaded allocation operator"); } -bool areCorrespondingOverloads(const FunctionDecl *LHS, - const FunctionDecl *RHS) { +static bool areCorrespondingOverloads(const FunctionDecl *LHS, + const FunctionDecl *RHS) { return RHS->getOverloadedOperator() == getCorrespondingOverload(LHS); } -bool hasCorrespondingOverloadInBaseClass(const CXXMethodDecl *MD, - const CXXRecordDecl *RD = nullptr) { +static bool +hasCorrespondingOverloadInBaseClass(const CXXMethodDecl *MD, + const CXXRecordDecl *RD = nullptr) { if (RD) { // Check the methods in the given class and accessible to derived classes. for (const auto *BMD : RD->methods()) @@ -124,8 +127,6 @@ bool hasCorrespondingOverloadInBaseClass(const CXXMethodDecl *MD, return false; } -} // anonymous namespace - void NewDeleteOverloadsCheck::registerMatchers(MatchFinder *Finder) { // Match all operator new and operator delete overloads (including the array // forms). Do not match implicit operators, placement operators, or diff --git a/clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp b/clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp index c2db858f72e32..118e96a6f34ae 100644 --- a/clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp @@ -395,16 +395,12 @@ void MacroToEnumCallbacks::Endif(SourceLocation Loc, SourceLocation IfLoc) { --CurrentFile->ConditionScopes; } -namespace { - template -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; } -template size_t len(const char (&)[N]) { return N - 1; } - -} // namespace +template static size_t len(const char (&)[N]) { return N - 1; } void MacroToEnumCallbacks::PragmaDirective(SourceLocation Loc, PragmaIntroducerKind Introducer) { diff --git a/clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.cpp b/clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.cpp index deef3586628c6..cea48ce6f4564 100644 --- a/clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.cpp @@ -16,14 +16,13 @@ using namespace clang::ast_matchers; namespace clang::tidy::modernize { -namespace { +static constexpr char ConstructorCall[] = "constructorCall"; +static constexpr char ResetCall[] = "resetCall"; +static constexpr char NewExpression[] = "newExpression"; -constexpr char ConstructorCall[] = "constructorCall"; -constexpr char ResetCall[] = "resetCall"; -constexpr char NewExpression[] = "newExpression"; - -std::string getNewExprName(const CXXNewExpr *NewExpr, const SourceManager &SM, - const LangOptions &Lang) { +static std::string getNewExprName(const CXXNewExpr *NewExpr, + const SourceManager &SM, + const LangOptions &Lang) { StringRef WrittenName = Lexer::getSourceText( CharSourceRange::getTokenRange( NewExpr->getAllocatedTypeSourceInfo()->getTypeLoc().getSourceRange()), @@ -34,8 +33,6 @@ std::string getNewExprName(const CXXNewExpr *NewExpr, const SourceManager &SM, return WrittenName.str(); } -} // namespace - const char MakeSmartPtrCheck::PointerType[] = "pointerType"; MakeSmartPtrCheck::MakeSmartPtrCheck(StringRef Name, ClangTidyContext *Context, diff --git a/clang-tools-extra/clang-tidy/modernize/RawStringLiteralCheck.cpp b/clang-tools-extra/clang-tidy/modernize/RawStringLiteralCheck.cpp index 24674a407cb36..0c9e909fea7f9 100644 --- a/clang-tools-extra/clang-tidy/modernize/RawStringLiteralCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/RawStringLiteralCheck.cpp @@ -19,9 +19,7 @@ using namespace clang::ast_matchers; namespace clang::tidy::modernize { -namespace { - -bool containsEscapes(StringRef HayStack, StringRef Escapes) { +static bool containsEscapes(StringRef HayStack, StringRef Escapes) { size_t BackSlash = HayStack.find('\\'); if (BackSlash == StringRef::npos) return false; @@ -35,16 +33,16 @@ bool containsEscapes(StringRef HayStack, StringRef Escapes) { return true; } -bool isRawStringLiteral(StringRef Text) { +static bool isRawStringLiteral(StringRef Text) { // Already a raw string literal if R comes before ". const size_t QuotePos = Text.find('"'); assert(QuotePos != StringRef::npos); return (QuotePos > 0) && (Text[QuotePos - 1] == 'R'); } -bool containsEscapedCharacters(const MatchFinder::MatchResult &Result, - const StringLiteral *Literal, - const CharsBitSet &DisallowedChars) { +static bool containsEscapedCharacters(const MatchFinder::MatchResult &Result, + const StringLiteral *Literal, + const CharsBitSet &DisallowedChars) { // FIXME: Handle L"", u8"", u"" and U"" literals. if (!Literal->isOrdinary()) return false; @@ -64,14 +62,12 @@ bool containsEscapedCharacters(const MatchFinder::MatchResult &Result, 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() ? std::string(R"lit()")lit") : (")" + Delimiter + R"(")")) != StringRef::npos; } -} // namespace - RawStringLiteralCheck::RawStringLiteralCheck(StringRef Name, ClangTidyContext *Context) : ClangTidyCheck(Name, Context), diff --git a/clang-tools-extra/clang-tidy/objc/NSInvocationArgumentLifetimeCheck.cpp b/clang-tools-extra/clang-tidy/objc/NSInvocationArgumentLifetimeCheck.cpp index bd9bdd1701975..8e4ed41c5f501 100644 --- a/clang-tools-extra/clang-tidy/objc/NSInvocationArgumentLifetimeCheck.cpp +++ b/clang-tools-extra/clang-tidy/objc/NSInvocationArgumentLifetimeCheck.cpp @@ -29,12 +29,13 @@ using namespace clang::ast_matchers; namespace clang::tidy::objc { -namespace { static constexpr StringRef WeakText = "__weak"; static constexpr StringRef StrongText = "__strong"; static constexpr StringRef UnsafeUnretainedText = "__unsafe_unretained"; +namespace { + /// Matches ObjCIvarRefExpr, DeclRefExpr, or MemberExpr that reference /// Objective-C object (or block) variables or fields whose object lifetimes /// are not __unsafe_unretained. @@ -49,6 +50,8 @@ AST_POLYMORPHIC_MATCHER(isObjCManagedLifetime, QT.getQualifiers().getObjCLifetime() > Qualifiers::OCL_ExplicitNone; } +} // namespace + static std::optional fixItHintReplacementForOwnershipString(StringRef Text, CharSourceRange Range, StringRef Ownership) { @@ -93,8 +96,6 @@ fixItHintForVarDecl(const VarDecl *VD, const SourceManager &SM, return FixItHint::CreateInsertion(Range.getBegin(), "__unsafe_unretained "); } -} // namespace - void NSInvocationArgumentLifetimeCheck::registerMatchers(MatchFinder *Finder) { Finder->addMatcher( traverse( diff --git a/clang-tools-extra/clang-tidy/objc/PropertyDeclarationCheck.cpp b/clang-tools-extra/clang-tidy/objc/PropertyDeclarationCheck.cpp index ffbdb025848d7..01ee4d518b97c 100644 --- a/clang-tools-extra/clang-tidy/objc/PropertyDeclarationCheck.cpp +++ b/clang-tools-extra/clang-tidy/objc/PropertyDeclarationCheck.cpp @@ -27,11 +27,14 @@ enum NamingStyle { CategoryProperty = 2, }; +} // namespace + /// For now we will only fix 'CamelCase' or 'abc_CamelCase' property to /// 'camelCase' or 'abc_camelCase'. For other cases the users need to /// come up with a proper name by their own. /// 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 NewName = Decl->getName().str(); size_t Index = 0; @@ -50,7 +53,7 @@ FixItHint generateFixItHint(const ObjCPropertyDecl *Decl, NamingStyle Style) { return {}; } -std::string validPropertyNameRegex(bool UsedInMatcher) { +static std::string validPropertyNameRegex(bool UsedInMatcher) { // Allow any of these names: // foo // fooBar @@ -72,13 +75,13 @@ std::string validPropertyNameRegex(bool UsedInMatcher) { 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 = llvm::Regex("^[a-zA-Z][a-zA-Z0-9]*_[a-zA-Z0-9][a-zA-Z0-9_]+$"); return RegexExp.match(PropertyName); } -bool prefixedPropertyNameValid(llvm::StringRef PropertyName) { +static bool prefixedPropertyNameValid(llvm::StringRef PropertyName) { size_t Start = PropertyName.find_first_of('_'); assert(Start != llvm::StringRef::npos && Start + 1 < PropertyName.size()); auto Prefix = PropertyName.substr(0, Start); @@ -88,7 +91,6 @@ bool prefixedPropertyNameValid(llvm::StringRef PropertyName) { auto RegexExp = llvm::Regex(llvm::StringRef(validPropertyNameRegex(false))); return RegexExp.match(PropertyName.substr(Start + 1)); } -} // namespace void PropertyDeclarationCheck::registerMatchers(MatchFinder *Finder) { Finder->addMatcher(objcPropertyDecl( diff --git a/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp b/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp index 120f7fb749493..c413090b3a0a4 100644 --- a/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp +++ b/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp @@ -17,7 +17,6 @@ #include namespace clang::tidy::performance { -namespace { using namespace ::clang::ast_matchers; using llvm::StringRef; @@ -30,8 +29,8 @@ static constexpr StringRef MethodDeclId = "methodDecl"; static constexpr StringRef FunctionDeclId = "functionDecl"; static constexpr StringRef OldVarDeclId = "oldVarDecl"; -void recordFixes(const VarDecl &Var, ASTContext &Context, - DiagnosticBuilder &Diagnostic) { +static void recordFixes(const VarDecl &Var, ASTContext &Context, + DiagnosticBuilder &Diagnostic) { Diagnostic << utils::fixit::changeVarDeclToReference(Var, Context); if (!Var.getType().isLocalConstQualified()) { if (std::optional Fix = utils::fixit::addQualifierToVarDecl( @@ -40,8 +39,8 @@ void recordFixes(const VarDecl &Var, ASTContext &Context, } } -std::optional firstLocAfterNewLine(SourceLocation Loc, - SourceManager &SM) { +static std::optional firstLocAfterNewLine(SourceLocation Loc, + SourceManager &SM) { bool Invalid = false; const char *TextAfter = SM.getCharacterData(Loc, &Invalid); if (Invalid) { @@ -51,8 +50,8 @@ std::optional firstLocAfterNewLine(SourceLocation Loc, return Loc.getLocWithOffset(TextAfter[Offset] == '\0' ? Offset : Offset + 1); } -void recordRemoval(const DeclStmt &Stmt, ASTContext &Context, - DiagnosticBuilder &Diagnostic) { +static void recordRemoval(const DeclStmt &Stmt, ASTContext &Context, + DiagnosticBuilder &Diagnostic) { auto &SM = Context.getSourceManager(); // Attempt to remove trailing comments as well. 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, isRefReturningMethodCallWithConstOverloads, std::vector, ExcludedContainerTypes) { @@ -130,6 +131,8 @@ AST_MATCHER_FUNCTION_P(StatementMatcher, initializerReturnsReferenceToConst, hasUnaryOperand(OldVarDeclRef))))); } +} // namespace + // 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 // the BlockStmt. It does this by checking the following: @@ -180,13 +183,13 @@ static bool isInitializingVariableImmutable( return false; } -bool isVariableUnused(const VarDecl &Var, const Stmt &BlockStmt, - ASTContext &Context) { +static bool isVariableUnused(const VarDecl &Var, const Stmt &BlockStmt, + ASTContext &Context) { return allDeclRefExprs(Var, BlockStmt, Context).empty(); } -const SubstTemplateTypeParmType *getSubstitutedType(const QualType &Type, - ASTContext &Context) { +static const SubstTemplateTypeParmType * +getSubstitutedType(const QualType &Type, ASTContext &Context) { auto Matches = match( qualType(anyOf(substTemplateTypeParmType().bind("subst"), hasDescendant(substTemplateTypeParmType().bind("subst")))), @@ -194,9 +197,9 @@ const SubstTemplateTypeParmType *getSubstitutedType(const QualType &Type, return selectFirst("subst", Matches); } -bool differentReplacedTemplateParams(const QualType &VarType, - const QualType &InitializerType, - ASTContext &Context) { +static bool differentReplacedTemplateParams(const QualType &VarType, + const QualType &InitializerType, + ASTContext &Context) { if (const SubstTemplateTypeParmType *VarTmplType = getSubstitutedType(VarType, Context)) { if (const SubstTemplateTypeParmType *InitializerTmplType = @@ -212,8 +215,8 @@ bool differentReplacedTemplateParams(const QualType &VarType, return false; } -QualType constructorArgumentType(const VarDecl *OldVar, - const BoundNodes &Nodes) { +static QualType constructorArgumentType(const VarDecl *OldVar, + const BoundNodes &Nodes) { if (OldVar) { return OldVar->getType(); } @@ -224,8 +227,6 @@ QualType constructorArgumentType(const VarDecl *OldVar, return MethodDecl->getReturnType(); } -} // namespace - UnnecessaryCopyInitialization::UnnecessaryCopyInitialization( StringRef Name, ClangTidyContext *Context) : ClangTidyCheck(Name, Context), diff --git a/clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp b/clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp index fbd2ba67805d9..c1aa52bacf99f 100644 --- a/clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp +++ b/clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp @@ -21,16 +21,14 @@ using namespace clang::ast_matchers; namespace clang::tidy::performance { -namespace { - -std::string paramNameOrIndex(StringRef Name, size_t Index) { +static std::string paramNameOrIndex(StringRef Name, size_t Index) { return (Name.empty() ? llvm::Twine('#') + llvm::Twine(Index + 1) : llvm::Twine('\'') + Name + llvm::Twine('\'')) .str(); } -bool hasLoopStmtAncestor(const DeclRefExpr &DeclRef, const Decl &Decl, - ASTContext &Context) { +static bool hasLoopStmtAncestor(const DeclRefExpr &DeclRef, const Decl &Decl, + ASTContext &Context) { auto Matches = match( traverse(TK_AsIs, decl(forEachDescendant(declRefExpr( @@ -41,8 +39,6 @@ bool hasLoopStmtAncestor(const DeclRefExpr &DeclRef, const Decl &Decl, return Matches.empty(); } -} // namespace - UnnecessaryValueParamCheck::UnnecessaryValueParamCheck( StringRef Name, ClangTidyContext *Context) : ClangTidyCheck(Name, Context), diff --git a/clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.cpp b/clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.cpp index b4a157c153bb9..9eef5c4db2d01 100644 --- a/clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.cpp @@ -122,15 +122,15 @@ AST_MATCHER(EnumDecl, hasSequentialInitialValues) { return !AllEnumeratorsArePowersOfTwo; } -std::string getName(const EnumDecl *Decl) { +} // namespace + +static std::string getName(const EnumDecl *Decl) { if (!Decl->getDeclName()) return ""; return Decl->getQualifiedNameAsString(); } -} // namespace - EnumInitialValueCheck::EnumInitialValueCheck(StringRef Name, ClangTidyContext *Context) : ClangTidyCheck(Name, Context), diff --git a/clang-tools-extra/clang-tidy/readability/FunctionCognitiveComplexityCheck.cpp b/clang-tools-extra/clang-tidy/readability/FunctionCognitiveComplexityCheck.cpp index e1fb42b8210e2..2f59aaa86b157 100644 --- a/clang-tools-extra/clang-tidy/readability/FunctionCognitiveComplexityCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/FunctionCognitiveComplexityCheck.cpp @@ -144,6 +144,8 @@ struct CognitiveComplexity final { void account(SourceLocation Loc, unsigned short Nesting, Criteria C); }; +} // namespace + // All the possible messages that can be output. The choice of the message // 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 @@ -163,23 +165,27 @@ static const std::array Msgs = {{ }}; // Criteria is a bitset, thus a few helpers are needed. -CognitiveComplexity::Criteria operator|(CognitiveComplexity::Criteria LHS, - CognitiveComplexity::Criteria RHS) { +static CognitiveComplexity::Criteria +operator|(CognitiveComplexity::Criteria LHS, + CognitiveComplexity::Criteria RHS) { return static_cast(llvm::to_underlying(LHS) | llvm::to_underlying(RHS)); } -CognitiveComplexity::Criteria operator&(CognitiveComplexity::Criteria LHS, - CognitiveComplexity::Criteria RHS) { +static CognitiveComplexity::Criteria +operator&(CognitiveComplexity::Criteria LHS, + CognitiveComplexity::Criteria RHS) { return static_cast(llvm::to_underlying(LHS) & llvm::to_underlying(RHS)); } -CognitiveComplexity::Criteria &operator|=(CognitiveComplexity::Criteria &LHS, - CognitiveComplexity::Criteria RHS) { +static CognitiveComplexity::Criteria & +operator|=(CognitiveComplexity::Criteria &LHS, + CognitiveComplexity::Criteria RHS) { LHS = operator|(LHS, RHS); return LHS; } -CognitiveComplexity::Criteria &operator&=(CognitiveComplexity::Criteria &LHS, - CognitiveComplexity::Criteria RHS) { +static CognitiveComplexity::Criteria & +operator&=(CognitiveComplexity::Criteria &LHS, + CognitiveComplexity::Criteria RHS) { LHS = operator&(LHS, RHS); return LHS; } @@ -199,6 +205,8 @@ void CognitiveComplexity::account(SourceLocation Loc, unsigned short Nesting, Total += Increase; } +namespace { + class FunctionASTVisitor final : public RecursiveASTVisitor { using Base = RecursiveASTVisitor; diff --git a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp index 5f19706e16866..6b10e6b206a31 100644 --- a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp @@ -41,9 +41,11 @@ AST_MATCHER(Stmt, isNULLMacroExpansion) { return isNULLMacroExpansion(&Node, Finder->getASTContext()); } -StringRef getZeroLiteralToCompareWithForType(CastKind CastExprKind, - QualType Type, - ASTContext &Context) { +} // namespace + +static StringRef getZeroLiteralToCompareWithForType(CastKind CastExprKind, + QualType Type, + ASTContext &Context) { switch (CastExprKind) { case CK_IntegralToBoolean: 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(Statement); return UnaryOperatorExpr && UnaryOperatorExpr->getOpcode() == UO_LNot; } -void fixGenericExprCastToBool(DiagnosticBuilder &Diag, - const ImplicitCastExpr *Cast, const Stmt *Parent, - ASTContext &Context, - bool UseUpperCaseLiteralSuffix) { +static void fixGenericExprCastToBool(DiagnosticBuilder &Diag, + const ImplicitCastExpr *Cast, + const Stmt *Parent, ASTContext &Context, + bool UseUpperCaseLiteralSuffix) { // In case of expressions like (! integer), we should remove the redundant not // operator and use inverted comparison (integer == 0). bool InvertComparison = @@ -133,8 +135,8 @@ void fixGenericExprCastToBool(DiagnosticBuilder &Diag, Diag << FixItHint::CreateInsertion(EndLoc, EndLocInsertion); } -StringRef getEquivalentBoolLiteralForExpr(const Expr *Expression, - ASTContext &Context) { +static StringRef getEquivalentBoolLiteralForExpr(const Expr *Expression, + ASTContext &Context) { if (isNULLMacroExpansion(Expression, Context)) { return "false"; } @@ -161,7 +163,7 @@ StringRef getEquivalentBoolLiteralForExpr(const Expr *Expression, return {}; } -bool needsSpacePrefix(SourceLocation Loc, ASTContext &Context) { +static bool needsSpacePrefix(SourceLocation Loc, ASTContext &Context) { SourceRange PrefixRange(Loc.getLocWithOffset(-1), Loc); StringRef SpaceBeforeStmtStr = Lexer::getSourceText( CharSourceRange::getCharRange(PrefixRange), Context.getSourceManager(), @@ -173,9 +175,10 @@ bool needsSpacePrefix(SourceLocation Loc, ASTContext &Context) { return !AllowedCharacters.contains(SpaceBeforeStmtStr.back()); } -void fixGenericExprCastFromBool(DiagnosticBuilder &Diag, - const ImplicitCastExpr *Cast, - ASTContext &Context, StringRef OtherType) { +static void fixGenericExprCastFromBool(DiagnosticBuilder &Diag, + const ImplicitCastExpr *Cast, + ASTContext &Context, + StringRef OtherType) { if (!Context.getLangOpts().CPlusPlus) { Diag << FixItHint::CreateInsertion(Cast->getBeginLoc(), (Twine("(") + OtherType + ")").str()); @@ -200,8 +203,9 @@ void fixGenericExprCastFromBool(DiagnosticBuilder &Diag, } } -StringRef getEquivalentForBoolLiteral(const CXXBoolLiteralExpr *BoolLiteral, - QualType DestType, ASTContext &Context) { +static StringRef +getEquivalentForBoolLiteral(const CXXBoolLiteralExpr *BoolLiteral, + QualType DestType, ASTContext &Context) { // Prior to C++11, false literal could be implicitly converted to pointer. if (!Context.getLangOpts().CPlusPlus11 && (DestType->isPointerType() || DestType->isMemberPointerType()) && @@ -222,8 +226,8 @@ StringRef getEquivalentForBoolLiteral(const CXXBoolLiteralExpr *BoolLiteral, return BoolLiteral->getValue() ? "1" : "0"; } -bool isCastAllowedInCondition(const ImplicitCastExpr *Cast, - ASTContext &Context) { +static bool isCastAllowedInCondition(const ImplicitCastExpr *Cast, + ASTContext &Context) { std::queue Q; Q.push(Cast); @@ -251,8 +255,6 @@ bool isCastAllowedInCondition(const ImplicitCastExpr *Cast, return false; } -} // anonymous namespace - ImplicitBoolConversionCheck::ImplicitBoolConversionCheck( StringRef Name, ClangTidyContext *Context) : ClangTidyCheck(Name, Context), diff --git a/clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp b/clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp index 561f067d471d1..44a784bc9f21a 100644 --- a/clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp @@ -28,8 +28,11 @@ AST_MATCHER_P(QualType, hasUnqualifiedType, enum class Qualifier { Const, Volatile, Restrict }; -std::optional findQualToken(const VarDecl *Decl, Qualifier Qual, - const MatchFinder::MatchResult &Result) { +} // namespace + +static std::optional +findQualToken(const VarDecl *Decl, Qualifier Qual, + const MatchFinder::MatchResult &Result) { // 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 // source file. @@ -58,7 +61,7 @@ std::optional findQualToken(const VarDecl *Decl, Qualifier Qual, *Result.SourceManager); } -std::optional +static std::optional getTypeSpecifierLocation(const VarDecl *Var, const MatchFinder::MatchResult &Result) { SourceRange TypeSpecifier( @@ -73,8 +76,8 @@ getTypeSpecifierLocation(const VarDecl *Var, return TypeSpecifier; } -std::optional mergeReplacementRange(SourceRange &TypeSpecifier, - const Token &ConstToken) { +static std::optional +mergeReplacementRange(SourceRange &TypeSpecifier, const Token &ConstToken) { if (TypeSpecifier.getBegin().getLocWithOffset(-1) == ConstToken.getEndLoc()) { TypeSpecifier.setBegin(ConstToken.getLocation()); return std::nullopt; @@ -86,21 +89,19 @@ std::optional mergeReplacementRange(SourceRange &TypeSpecifier, return SourceRange(ConstToken.getLocation(), ConstToken.getEndLoc()); } -bool isPointerConst(QualType QType) { +static bool isPointerConst(QualType QType) { QualType Pointee = QType->getPointeeType(); assert(!Pointee.isNull() && "can't have a null Pointee"); return Pointee.isConstQualified(); } -bool isAutoPointerConst(QualType QType) { +static bool isAutoPointerConst(QualType QType) { QualType Pointee = cast(QType->getPointeeType().getTypePtr())->desugar(); assert(!Pointee.isNull() && "can't have a null Pointee"); return Pointee.isConstQualified(); } -} // namespace - QualifiedAutoCheck::QualifiedAutoCheck(StringRef Name, ClangTidyContext *Context) : ClangTidyCheck(Name, Context), diff --git a/clang-tools-extra/clang-tidy/readability/RedundantControlFlowCheck.cpp b/clang-tools-extra/clang-tidy/readability/RedundantControlFlowCheck.cpp index 70016a372b8bd..d93077cc6884e 100644 --- a/clang-tools-extra/clang-tidy/readability/RedundantControlFlowCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/RedundantControlFlowCheck.cpp @@ -14,19 +14,18 @@ using namespace clang::ast_matchers; 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 " - "of a function with a void return type"; -const char *const RedundantContinueDiag = "redundant continue statement at the " - "end of loop statement"; - -bool isLocationInMacroExpansion(const SourceManager &SM, SourceLocation Loc) { +static bool isLocationInMacroExpansion(const SourceManager &SM, + SourceLocation Loc) { return SM.isMacroBodyExpansion(Loc) || SM.isMacroArgExpansion(Loc); } -} // namespace - void RedundantControlFlowCheck::registerMatchers(MatchFinder *Finder) { Finder->addMatcher( functionDecl(isDefinition(), returns(voidType()), diff --git a/clang-tools-extra/clang-tidy/utils/TypeTraits.cpp b/clang-tools-extra/clang-tidy/utils/TypeTraits.cpp index 96d3a5bbd86a2..5518afd32e7f0 100644 --- a/clang-tools-extra/clang-tidy/utils/TypeTraits.cpp +++ b/clang-tools-extra/clang-tidy/utils/TypeTraits.cpp @@ -13,16 +13,14 @@ namespace clang::tidy::utils::type_traits { -namespace { - -bool classHasTrivialCopyAndDestroy(QualType Type) { +static bool classHasTrivialCopyAndDestroy(QualType Type) { auto *Record = Type->getAsCXXRecordDecl(); return Record && Record->hasDefinition() && !Record->hasNonTrivialCopyConstructor() && !Record->hasNonTrivialDestructor(); } -bool hasDeletedCopyConstructor(QualType Type) { +static bool hasDeletedCopyConstructor(QualType Type) { auto *Record = Type->getAsCXXRecordDecl(); if (!Record || !Record->hasDefinition()) return false; @@ -33,8 +31,6 @@ bool hasDeletedCopyConstructor(QualType Type) { return false; } -} // namespace - std::optional isExpensiveToCopy(QualType Type, const ASTContext &Context) { if (Type->isDependentType() || Type->isIncompleteType())