- Notifications
You must be signed in to change notification settings - Fork 14.9k
[clang-tidy][NFC] Fix "llvm-prefer-static-over-anonymous-namespace" warnings 1/N #153885
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[clang-tidy][NFC] Fix "llvm-prefer-static-over-anonymous-namespace" warnings 1/N #153885
Conversation
@llvm/pr-subscribers-clang-tools-extra @llvm/pr-subscribers-clang-tidy Author: Baranov Victor (vbvictor) ChangesPatch is 35.47 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/153885.diff 17 Files Affected:
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<CallExpr, CXXConstructExpr>(ParentE); } +namespace { + AST_MATCHER_P(CXXTryStmt, hasHandlerFor, ast_matchers::internal::Matcher<QualType>, 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<ConversionKind>(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<CallExpr>("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 <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; } -template <size_t N> size_t len(const char (&)[N]) { return N - 1; } - -} // namespace +template <size_t N> 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<FixItHint> 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 <optional> 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<FixItHint> Fix = utils::fixit::addQualifierToVarDecl( @@ -40,8 +39,8 @@ void recordFixes(const VarDecl &Var, ASTContext &Context, } } -std::optional<SourceLocation> firstLocAfterNewLine(SourceLocation Loc, - SourceManager &SM) { +static std::optional<SourceLocation> firstLocAfterNewLine(SourceLocation Loc, + SourceManager &SM) { bool Invalid = false; const char *TextAfter = SM.getCharacterData(Loc, &Invalid); if (Invalid) { @@ -51,8 +50,8 @@ std::optional<SourceLocation> 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<StringRef>, 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<SubstTemplateTypeParmType>("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 cons... [truncated] |
Should be fairly easy to review @carlosgalvezp |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM!
Personally I find the guidelines a bit silly since they lead to a sandwich of static-anon namespace-static-anon-namespace. But those are the guidelines we have :)
Yeah, but I guess it makes a lot easier to spot a function without internal linkage during review (although it should be caught by |
…mespace warnings 2/N (#164083) Continue llvm/llvm-project#153885.
…mespace warnings 3/N (#164085) Continue llvm/llvm-project#153885.
No description provided.