diff options
Diffstat (limited to 'clang-tools-extra/clang-tidy')
33 files changed, 211 insertions, 194 deletions
diff --git a/clang-tools-extra/clang-tidy/ClangTidyForceLinker.h b/clang-tools-extra/clang-tidy/ClangTidyForceLinker.h index cdf6ce2..afc358a 100644 --- a/clang-tools-extra/clang-tidy/ClangTidyForceLinker.h +++ b/clang-tools-extra/clang-tidy/ClangTidyForceLinker.h @@ -16,132 +16,131 @@ namespace clang::tidy { // This anchor is used to force the linker to link the AbseilModule. extern volatile int AbseilModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED AbseilModuleAnchorDestination = +[[maybe_unused]] static int AbseilModuleAnchorDestination = AbseilModuleAnchorSource; // This anchor is used to force the linker to link the AlteraModule. extern volatile int AlteraModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED AlteraModuleAnchorDestination = +[[maybe_unused]] static int AlteraModuleAnchorDestination = AlteraModuleAnchorSource; // This anchor is used to force the linker to link the AndroidModule. extern volatile int AndroidModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED AndroidModuleAnchorDestination = +[[maybe_unused]] static int AndroidModuleAnchorDestination = AndroidModuleAnchorSource; // This anchor is used to force the linker to link the BoostModule. extern volatile int BoostModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED BoostModuleAnchorDestination = +[[maybe_unused]] static int BoostModuleAnchorDestination = BoostModuleAnchorSource; // This anchor is used to force the linker to link the BugproneModule. extern volatile int BugproneModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED BugproneModuleAnchorDestination = +[[maybe_unused]] static int BugproneModuleAnchorDestination = BugproneModuleAnchorSource; // This anchor is used to force the linker to link the CERTModule. extern volatile int CERTModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED CERTModuleAnchorDestination = +[[maybe_unused]] static int CERTModuleAnchorDestination = CERTModuleAnchorSource; // This anchor is used to force the linker to link the ConcurrencyModule. extern volatile int ConcurrencyModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED ConcurrencyModuleAnchorDestination = +[[maybe_unused]] static int ConcurrencyModuleAnchorDestination = ConcurrencyModuleAnchorSource; // This anchor is used to force the linker to link the CppCoreGuidelinesModule. extern volatile int CppCoreGuidelinesModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED CppCoreGuidelinesModuleAnchorDestination = +[[maybe_unused]] static int CppCoreGuidelinesModuleAnchorDestination = CppCoreGuidelinesModuleAnchorSource; #if CLANG_TIDY_ENABLE_QUERY_BASED_CUSTOM_CHECKS // This anchor is used to force the linker to link the CustomModule. extern volatile int CustomModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED CustomModuleAnchorDestination = +[[maybe_unused]] static int CustomModuleAnchorDestination = CustomModuleAnchorSource; #endif // This anchor is used to force the linker to link the DarwinModule. extern volatile int DarwinModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED DarwinModuleAnchorDestination = +[[maybe_unused]] static int DarwinModuleAnchorDestination = DarwinModuleAnchorSource; // This anchor is used to force the linker to link the FuchsiaModule. extern volatile int FuchsiaModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED FuchsiaModuleAnchorDestination = +[[maybe_unused]] static int FuchsiaModuleAnchorDestination = FuchsiaModuleAnchorSource; // This anchor is used to force the linker to link the GoogleModule. extern volatile int GoogleModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED GoogleModuleAnchorDestination = +[[maybe_unused]] static int GoogleModuleAnchorDestination = GoogleModuleAnchorSource; // This anchor is used to force the linker to link the HICPPModule. extern volatile int HICPPModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED HICPPModuleAnchorDestination = +[[maybe_unused]] static int HICPPModuleAnchorDestination = HICPPModuleAnchorSource; // This anchor is used to force the linker to link the LinuxKernelModule. extern volatile int LinuxKernelModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED LinuxKernelModuleAnchorDestination = +[[maybe_unused]] static int LinuxKernelModuleAnchorDestination = LinuxKernelModuleAnchorSource; // This anchor is used to force the linker to link the LLVMModule. extern volatile int LLVMModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED LLVMModuleAnchorDestination = +[[maybe_unused]] static int LLVMModuleAnchorDestination = LLVMModuleAnchorSource; // This anchor is used to force the linker to link the LLVMLibcModule. extern volatile int LLVMLibcModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED LLVMLibcModuleAnchorDestination = +[[maybe_unused]] static int LLVMLibcModuleAnchorDestination = LLVMLibcModuleAnchorSource; // This anchor is used to force the linker to link the MiscModule. extern volatile int MiscModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED MiscModuleAnchorDestination = +[[maybe_unused]] static int MiscModuleAnchorDestination = MiscModuleAnchorSource; // This anchor is used to force the linker to link the ModernizeModule. extern volatile int ModernizeModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED ModernizeModuleAnchorDestination = +[[maybe_unused]] static int ModernizeModuleAnchorDestination = ModernizeModuleAnchorSource; #if CLANG_TIDY_ENABLE_STATIC_ANALYZER && \ !defined(CLANG_TIDY_DISABLE_STATIC_ANALYZER_CHECKS) // This anchor is used to force the linker to link the MPIModule. extern volatile int MPIModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED MPIModuleAnchorDestination = - MPIModuleAnchorSource; +[[maybe_unused]] static int MPIModuleAnchorDestination = MPIModuleAnchorSource; #endif // This anchor is used to force the linker to link the ObjCModule. extern volatile int ObjCModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED ObjCModuleAnchorDestination = +[[maybe_unused]] static int ObjCModuleAnchorDestination = ObjCModuleAnchorSource; // This anchor is used to force the linker to link the OpenMPModule. extern volatile int OpenMPModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED OpenMPModuleAnchorDestination = +[[maybe_unused]] static int OpenMPModuleAnchorDestination = OpenMPModuleAnchorSource; // This anchor is used to force the linker to link the PerformanceModule. extern volatile int PerformanceModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED PerformanceModuleAnchorDestination = +[[maybe_unused]] static int PerformanceModuleAnchorDestination = PerformanceModuleAnchorSource; // This anchor is used to force the linker to link the PortabilityModule. extern volatile int PortabilityModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED PortabilityModuleAnchorDestination = +[[maybe_unused]] static int PortabilityModuleAnchorDestination = PortabilityModuleAnchorSource; // This anchor is used to force the linker to link the ReadabilityModule. extern volatile int ReadabilityModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED ReadabilityModuleAnchorDestination = +[[maybe_unused]] static int ReadabilityModuleAnchorDestination = ReadabilityModuleAnchorSource; // This anchor is used to force the linker to link the ZirconModule. extern volatile int ZirconModuleAnchorSource; -static int LLVM_ATTRIBUTE_UNUSED ZirconModuleAnchorDestination = +[[maybe_unused]] static int ZirconModuleAnchorDestination = ZirconModuleAnchorSource; } // namespace clang::tidy diff --git a/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp b/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp index b752a9b..21455db 100644 --- a/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp +++ b/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp @@ -154,6 +154,7 @@ template <> struct ScalarEnumerationTraits<clang::DiagnosticIDs::Level> { } }; template <> struct SequenceElementTraits<ClangTidyOptions::CustomCheckDiag> { + // NOLINTNEXTLINE(readability-identifier-naming) Defined by YAMLTraits.h static const bool flow = false; }; template <> struct MappingTraits<ClangTidyOptions::CustomCheckDiag> { @@ -165,6 +166,7 @@ template <> struct MappingTraits<ClangTidyOptions::CustomCheckDiag> { } }; template <> struct SequenceElementTraits<ClangTidyOptions::CustomCheckValue> { + // NOLINTNEXTLINE(readability-identifier-naming) Defined by YAMLTraits.h static const bool flow = false; }; template <> struct MappingTraits<ClangTidyOptions::CustomCheckValue> { diff --git a/clang-tools-extra/clang-tidy/abseil/RedundantStrcatCallsCheck.cpp b/clang-tools-extra/clang-tidy/abseil/RedundantStrcatCallsCheck.cpp index d7cc0ca..a58c041 100644 --- a/clang-tools-extra/clang-tidy/abseil/RedundantStrcatCallsCheck.cpp +++ b/clang-tools-extra/clang-tidy/abseil/RedundantStrcatCallsCheck.cpp @@ -45,7 +45,10 @@ struct StrCatCheckResult { std::vector<FixItHint> Hints; }; -void removeCallLeaveArgs(const CallExpr *Call, StrCatCheckResult *CheckResult) { +} // namespace + +static void removeCallLeaveArgs(const CallExpr *Call, + StrCatCheckResult *CheckResult) { if (Call->getNumArgs() == 0) return; // Remove 'Foo(' @@ -58,9 +61,9 @@ void removeCallLeaveArgs(const CallExpr *Call, StrCatCheckResult *CheckResult) { Call->getRParenLoc(), Call->getEndLoc().getLocWithOffset(1)))); } -const clang::CallExpr *processArgument(const Expr *Arg, - const MatchFinder::MatchResult &Result, - StrCatCheckResult *CheckResult) { +static const clang::CallExpr * +processArgument(const Expr *Arg, const MatchFinder::MatchResult &Result, + StrCatCheckResult *CheckResult) { const auto IsAlphanum = hasDeclaration(cxxMethodDecl(hasName("AlphaNum"))); static const auto *const Strcat = new auto(hasName("::absl::StrCat")); const auto IsStrcat = cxxBindTemporaryExpr( @@ -78,8 +81,8 @@ const clang::CallExpr *processArgument(const Expr *Arg, return nullptr; } -StrCatCheckResult processCall(const CallExpr *RootCall, bool IsAppend, - const MatchFinder::MatchResult &Result) { +static StrCatCheckResult processCall(const CallExpr *RootCall, bool IsAppend, + const MatchFinder::MatchResult &Result) { StrCatCheckResult CheckResult; std::deque<const CallExpr *> CallsToProcess = {RootCall}; @@ -101,7 +104,6 @@ StrCatCheckResult processCall(const CallExpr *RootCall, bool IsAppend, } return CheckResult; } -} // namespace void RedundantStrcatCallsCheck::check(const MatchFinder::MatchResult &Result) { bool IsAppend = false; diff --git a/clang-tools-extra/clang-tidy/altera/UnrollLoopsCheck.cpp b/clang-tools-extra/clang-tidy/altera/UnrollLoopsCheck.cpp index 6aad3c6..e90cdd0 100644 --- a/clang-tools-extra/clang-tidy/altera/UnrollLoopsCheck.cpp +++ b/clang-tools-extra/clang-tidy/altera/UnrollLoopsCheck.cpp @@ -215,13 +215,13 @@ bool UnrollLoopsCheck::hasLargeNumIterations(const Stmt *Statement, break; case (BO_MulAssign): Iterations = - 1 + (std::log((double)EndValue) - std::log((double)InitValue)) / - std::log((double)ConstantValue); + 1 + ((std::log((double)EndValue) - std::log((double)InitValue)) / + std::log((double)ConstantValue)); break; case (BO_DivAssign): Iterations = - 1 + (std::log((double)InitValue) - std::log((double)EndValue)) / - std::log((double)ConstantValue); + 1 + ((std::log((double)InitValue) - std::log((double)EndValue)) / + std::log((double)ConstantValue)); break; default: // All other operators are not handled; assume large bounds. diff --git a/clang-tools-extra/clang-tidy/android/CloexecCheck.cpp b/clang-tools-extra/clang-tidy/android/CloexecCheck.cpp index cd83423..48c54c0 100644 --- a/clang-tools-extra/clang-tidy/android/CloexecCheck.cpp +++ b/clang-tools-extra/clang-tidy/android/CloexecCheck.cpp @@ -16,12 +16,13 @@ using namespace clang::ast_matchers; namespace clang::tidy::android { -namespace { // Helper function to form the correct string mode for Type3. // Build the replace text. If it's string constant, add <Mode> directly in the // end of the string. Else, add <Mode>. -std::string buildFixMsgForStringFlag(const Expr *Arg, const SourceManager &SM, - const LangOptions &LangOpts, char Mode) { +static std::string buildFixMsgForStringFlag(const Expr *Arg, + const SourceManager &SM, + const LangOptions &LangOpts, + char Mode) { if (Arg->getBeginLoc().isMacroID()) return (Lexer::getSourceText( CharSourceRange::getTokenRange(Arg->getSourceRange()), SM, @@ -32,11 +33,6 @@ std::string buildFixMsgForStringFlag(const Expr *Arg, const SourceManager &SM, StringRef SR = cast<StringLiteral>(Arg->IgnoreParenCasts())->getString(); return ("\"" + SR + Twine(Mode) + "\"").str(); } -} // namespace - -const char *CloexecCheck::FuncDeclBindingStr = "funcDecl"; - -const char *CloexecCheck::FuncBindingStr = "func"; void CloexecCheck::registerMatchersImpl( MatchFinder *Finder, internal::Matcher<FunctionDecl> Function) { diff --git a/clang-tools-extra/clang-tidy/android/CloexecCheck.h b/clang-tools-extra/clang-tidy/android/CloexecCheck.h index 79f7ab3..b2b59f5 100644 --- a/clang-tools-extra/clang-tidy/android/CloexecCheck.h +++ b/clang-tools-extra/clang-tidy/android/CloexecCheck.h @@ -89,10 +89,10 @@ protected: int N) const; /// Binding name of the FuncDecl of a function call. - static const char *FuncDeclBindingStr; + static constexpr char FuncDeclBindingStr[] = "funcDecl"; /// Binding name of the function call expression. - static const char *FuncBindingStr; + static constexpr char FuncBindingStr[] = "func"; }; } // namespace clang::tidy::android diff --git a/clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp index d8207b3..b4ee351 100644 --- a/clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp @@ -1074,7 +1074,7 @@ approximateStandardConversionSequence(const TheCheck &Check, QualType From, WorkType = To; } - if (Ctx.hasSameType(WorkType, To)) { + if (ASTContext::hasSameType(WorkType, To)) { LLVM_DEBUG(llvm::dbgs() << "<<< approximateStdConv. Reached 'To' type.\n"); return {Ctx.getCommonSugaredType(WorkType, To)}; } diff --git a/clang-tools-extra/clang-tidy/bugprone/MultipleStatementMacroCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/MultipleStatementMacroCheck.cpp index 390f3dd..54ed899 100644 --- a/clang-tools-extra/clang-tidy/bugprone/MultipleStatementMacroCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/MultipleStatementMacroCheck.cpp @@ -18,8 +18,11 @@ namespace { AST_MATCHER(Expr, isInMacro) { return Node.getBeginLoc().isMacroID(); } +} // namespace + /// Find the next statement after `S`. -const Stmt *nextStmt(const MatchFinder::MatchResult &Result, const Stmt *S) { +static const Stmt *nextStmt(const MatchFinder::MatchResult &Result, + const Stmt *S) { auto Parents = Result.Context->getParents(*S); if (Parents.empty()) return nullptr; @@ -40,8 +43,8 @@ using ExpansionRanges = std::vector<SourceRange>; /// \brief Get all the macro expansion ranges related to `Loc`. /// /// The result is ordered from most inner to most outer. -ExpansionRanges getExpansionRanges(SourceLocation Loc, - const MatchFinder::MatchResult &Result) { +static ExpansionRanges +getExpansionRanges(SourceLocation Loc, const MatchFinder::MatchResult &Result) { ExpansionRanges Locs; while (Loc.isMacroID()) { Locs.push_back( @@ -51,8 +54,6 @@ ExpansionRanges getExpansionRanges(SourceLocation Loc, return Locs; } -} // namespace - void MultipleStatementMacroCheck::registerMatchers(MatchFinder *Finder) { const auto Inner = expr(isInMacro(), unless(compoundStmt())).bind("inner"); Finder->addMatcher( diff --git a/clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp index 86af5cb..c262b1c 100644 --- a/clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp @@ -245,12 +245,10 @@ struct OptionEnumMapping< namespace bugprone { -namespace { - /// Returns if a function is declared inside a system header. /// These functions are considered to be "standard" (system-provided) library /// functions. -bool isStandardFunction(const FunctionDecl *FD) { +static bool isStandardFunction(const FunctionDecl *FD) { // Find a possible redeclaration in system header. // FIXME: Looking at the canonical declaration is not the most exact way // to do this. @@ -284,7 +282,7 @@ bool isStandardFunction(const FunctionDecl *FD) { /// Check if a statement is "C++-only". /// This includes all statements that have a class name with "CXX" prefix /// and every other statement that is declared in file ExprCXX.h. -bool isCXXOnlyStmt(const Stmt *S) { +static bool isCXXOnlyStmt(const Stmt *S) { StringRef Name = S->getStmtClassName(); if (Name.starts_with("CXX")) return true; @@ -304,7 +302,8 @@ bool isCXXOnlyStmt(const Stmt *S) { /// called from \p Caller, get a \c CallExpr of the corresponding function call. /// It is unspecified which call is found if multiple calls exist, but the order /// should be deterministic (depend only on the AST). -Expr *findCallExpr(const CallGraphNode *Caller, const CallGraphNode *Callee) { +static Expr *findCallExpr(const CallGraphNode *Caller, + const CallGraphNode *Callee) { const auto *FoundCallee = llvm::find_if( Caller->callees(), [Callee](const CallGraphNode::CallRecord &Call) { return Call.Callee == Callee; @@ -314,7 +313,7 @@ Expr *findCallExpr(const CallGraphNode *Caller, const CallGraphNode *Callee) { return FoundCallee->CallExpr; } -SourceRange getSourceRangeOfStmt(const Stmt *S, ASTContext &Ctx) { +static SourceRange getSourceRangeOfStmt(const Stmt *S, ASTContext &Ctx) { ParentMapContext &PM = Ctx.getParentMapContext(); DynTypedNode P = DynTypedNode::create(*S); while (P.getSourceRange().isInvalid()) { @@ -326,9 +325,9 @@ SourceRange getSourceRangeOfStmt(const Stmt *S, ASTContext &Ctx) { return P.getSourceRange(); } -AST_MATCHER(FunctionDecl, isStandardFunction) { - return isStandardFunction(&Node); -} +namespace { + +AST_MATCHER(FunctionDecl, isStandard) { return isStandardFunction(&Node); } } // namespace @@ -354,7 +353,7 @@ bool SignalHandlerCheck::isLanguageVersionSupported( void SignalHandlerCheck::registerMatchers(MatchFinder *Finder) { auto SignalFunction = functionDecl(hasAnyName("::signal", "::std::signal"), - parameterCountIs(2), isStandardFunction()); + parameterCountIs(2), isStandard()); auto HandlerExpr = declRefExpr(hasDeclaration(functionDecl().bind("handler_decl")), unless(isExpandedFromMacro("SIG_IGN")), diff --git a/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp index cdb6a08..cf55dd7 100644 --- a/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp @@ -424,7 +424,7 @@ void SizeofExpressionCheck::check(const MatchFinder::MatchResult &Result) { "suspicious usage of 'sizeof(array)/sizeof(...)';" " denominator differs from the size of array elements") << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); - } else if (NumTy && DenomTy && Ctx.hasSameType(NumTy, DenomTy) && + } else if (NumTy && DenomTy && ASTContext::hasSameType(NumTy, DenomTy) && !NumTy->isDependentType()) { // Dependent type should not be compared. diag(E->getOperatorLoc(), @@ -433,7 +433,7 @@ void SizeofExpressionCheck::check(const MatchFinder::MatchResult &Result) { << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); } else if (!WarnOnSizeOfPointer) { // When 'WarnOnSizeOfPointer' is enabled, these messages become redundant: - if (PointedTy && DenomTy && Ctx.hasSameType(PointedTy, DenomTy)) { + if (PointedTy && DenomTy && ASTContext::hasSameType(PointedTy, DenomTy)) { diag(E->getOperatorLoc(), "suspicious usage of 'sizeof(...)/sizeof(...)'; size of pointer " "is divided by size of pointed type") @@ -462,8 +462,8 @@ void SizeofExpressionCheck::check(const MatchFinder::MatchResult &Result) { const auto *SizeOfExpr = Result.Nodes.getNodeAs<UnaryExprOrTypeTraitExpr>("sizeof-ptr-mul-expr"); - if (Ctx.hasSameType(LPtrTy, RPtrTy) && - Ctx.hasSameType(LPtrTy, SizeofArgTy)) { + if (ASTContext::hasSameType(LPtrTy, RPtrTy) && + ASTContext::hasSameType(LPtrTy, SizeofArgTy)) { diag(SizeOfExpr->getBeginLoc(), "suspicious usage of 'sizeof(...)' in " "pointer arithmetic") << SizeOfExpr->getSourceRange() << E->getOperatorLoc() @@ -477,8 +477,8 @@ void SizeofExpressionCheck::check(const MatchFinder::MatchResult &Result) { const auto *SizeOfExpr = Result.Nodes.getNodeAs<UnaryExprOrTypeTraitExpr>("sizeof-ptr-div-expr"); - if (Ctx.hasSameType(LPtrTy, RPtrTy) && - Ctx.hasSameType(LPtrTy, SizeofArgTy)) { + if (ASTContext::hasSameType(LPtrTy, RPtrTy) && + ASTContext::hasSameType(LPtrTy, SizeofArgTy)) { diag(SizeOfExpr->getBeginLoc(), "suspicious usage of 'sizeof(...)' in " "pointer arithmetic") << SizeOfExpr->getSourceRange() << E->getOperatorLoc() diff --git a/clang-tools-extra/clang-tidy/bugprone/VirtualNearMissCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/VirtualNearMissCheck.cpp index 0c8d2b8..cef8b4d 100644 --- a/clang-tools-extra/clang-tidy/bugprone/VirtualNearMissCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/VirtualNearMissCheck.cpp @@ -50,7 +50,7 @@ static bool checkOverridingFunctionReturnType(const ASTContext *Context, return false; // Check if return types are identical. - if (Context->hasSameType(DerivedReturnTy, BaseReturnTy)) + if (ASTContext::hasSameType(DerivedReturnTy, BaseReturnTy)) return true; /// Check if the return types are covariant. @@ -77,7 +77,7 @@ static bool checkOverridingFunctionReturnType(const ASTContext *Context, if (DRD == BRD) return true; - if (!Context->hasSameUnqualifiedType(DTy, BTy)) { + if (!ASTContext::hasSameUnqualifiedType(DTy, BTy)) { // Begin checking whether the conversion from D to B is valid. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, /*DetectVirtual=*/false); @@ -87,7 +87,8 @@ static bool checkOverridingFunctionReturnType(const ASTContext *Context, return false; // Check ambiguity. - if (Paths.isAmbiguous(Context->getCanonicalType(BTy).getUnqualifiedType())) + if (Paths.isAmbiguous( + ASTContext::getCanonicalType(BTy).getUnqualifiedType())) return false; // Check accessibility. diff --git a/clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp b/clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp index 37d737a..1ac9b8b 100644 --- a/clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp +++ b/clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp @@ -28,10 +28,13 @@ AST_MATCHER(CXXRecordDecl, hasDefaultConstructor) { return Node.hasDefaultConstructor(); } +} // namespace + // Iterate over all the fields in a record type, both direct and indirect (e.g. // if the record contains an anonymous struct). template <typename T, typename Func> -void forEachField(const RecordDecl &Record, const T &Fields, const Func &Fn) { +static void forEachField(const RecordDecl &Record, const T &Fields, + const Func &Fn) { for (const FieldDecl *F : Fields) { if (F->isAnonymousStructOrUnion()) { if (const CXXRecordDecl *R = F->getType()->getAsCXXRecordDecl()) @@ -43,8 +46,9 @@ void forEachField(const RecordDecl &Record, const T &Fields, const Func &Fn) { } template <typename T, typename Func> -void forEachFieldWithFilter(const RecordDecl &Record, const T &Fields, - bool &AnyMemberHasInitPerUnion, const Func &Fn) { +static void forEachFieldWithFilter(const RecordDecl &Record, const T &Fields, + bool &AnyMemberHasInitPerUnion, + const Func &Fn) { for (const FieldDecl *F : Fields) { if (F->isAnonymousStructOrUnion()) { if (const CXXRecordDecl *R = F->getType()->getAsCXXRecordDecl()) { @@ -59,8 +63,9 @@ void forEachFieldWithFilter(const RecordDecl &Record, const T &Fields, } } -void removeFieldInitialized(const FieldDecl *M, - SmallPtrSetImpl<const FieldDecl *> &FieldDecls) { +static void +removeFieldInitialized(const FieldDecl *M, + SmallPtrSetImpl<const FieldDecl *> &FieldDecls) { const RecordDecl *R = M->getParent(); if (R && R->isUnion()) { // Erase all members in a union if any member of it is initialized. @@ -70,9 +75,9 @@ void removeFieldInitialized(const FieldDecl *M, FieldDecls.erase(M); } -void removeFieldsInitializedInBody( - const Stmt &Stmt, ASTContext &Context, - SmallPtrSetImpl<const FieldDecl *> &FieldDecls) { +static void +removeFieldsInitializedInBody(const Stmt &Stmt, ASTContext &Context, + SmallPtrSetImpl<const FieldDecl *> &FieldDecls) { auto Matches = match(findAll(binaryOperator( hasOperatorName("="), @@ -82,9 +87,9 @@ void removeFieldsInitializedInBody( removeFieldInitialized(Match.getNodeAs<FieldDecl>("fieldDecl"), FieldDecls); } -StringRef getName(const FieldDecl *Field) { return Field->getName(); } +static StringRef getName(const FieldDecl *Field) { return Field->getName(); } -StringRef getName(const RecordDecl *Record) { +static StringRef getName(const RecordDecl *Record) { // Get the typedef name if this is a C-style anonymous struct and typedef. if (const TypedefNameDecl *Typedef = Record->getTypedefNameForAnonDecl()) return Typedef->getName(); @@ -94,7 +99,7 @@ StringRef getName(const RecordDecl *Record) { // Creates comma separated list of decls requiring initialization in order of // declaration. template <typename R, typename T> -std::string +static std::string toCommaSeparatedString(const R &OrderedDecls, const SmallPtrSetImpl<const T *> &DeclsToInit) { SmallVector<StringRef, 16> Names; @@ -105,12 +110,14 @@ toCommaSeparatedString(const R &OrderedDecls, return llvm::join(Names.begin(), Names.end(), ", "); } -SourceLocation getLocationForEndOfToken(const ASTContext &Context, - SourceLocation Location) { +static SourceLocation getLocationForEndOfToken(const ASTContext &Context, + SourceLocation Location) { return Lexer::getLocForEndOfToken(Location, 0, Context.getSourceManager(), Context.getLangOpts()); } +namespace { + // There are 3 kinds of insertion placements: enum class InitializerPlacement { // 1. The fields are inserted after an existing CXXCtorInitializer stored in @@ -187,15 +194,17 @@ struct InitializerInsertion { SmallVector<std::string, 4> Initializers; }; +} // namespace + // Convenience utility to get a RecordDecl from a QualType. -const RecordDecl *getCanonicalRecordDecl(const QualType &Type) { +static const RecordDecl *getCanonicalRecordDecl(const QualType &Type) { if (const auto *RT = Type->getAsCanonical<RecordType>()) return RT->getDecl(); return nullptr; } template <typename R, typename T> -SmallVector<InitializerInsertion, 16> +static SmallVector<InitializerInsertion, 16> computeInsertions(const CXXConstructorDecl::init_const_range &Inits, const R &OrderedDecls, const SmallPtrSetImpl<const T *> &DeclsToInit) { @@ -239,8 +248,9 @@ computeInsertions(const CXXConstructorDecl::init_const_range &Inits, // Gets the list of bases and members that could possibly be initialized, in // order as they appear in the class declaration. -void getInitializationsInOrder(const CXXRecordDecl &ClassDecl, - SmallVectorImpl<const NamedDecl *> &Decls) { +static void +getInitializationsInOrder(const CXXRecordDecl &ClassDecl, + SmallVectorImpl<const NamedDecl *> &Decls) { Decls.clear(); for (const auto &Base : ClassDecl.bases()) { // Decl may be null if the base class is a template parameter. @@ -253,9 +263,10 @@ void getInitializationsInOrder(const CXXRecordDecl &ClassDecl, } template <typename T> -void fixInitializerList(const ASTContext &Context, DiagnosticBuilder &Diag, - const CXXConstructorDecl *Ctor, - const SmallPtrSetImpl<const T *> &DeclsToInit) { +static void fixInitializerList(const ASTContext &Context, + DiagnosticBuilder &Diag, + const CXXConstructorDecl *Ctor, + const SmallPtrSetImpl<const T *> &DeclsToInit) { // Do not propose fixes in macros since we cannot place them correctly. if (Ctor->getBeginLoc().isMacroID()) return; @@ -271,8 +282,6 @@ void fixInitializerList(const ASTContext &Context, DiagnosticBuilder &Diag, } } -} // anonymous namespace - ProTypeMemberInitCheck::ProTypeMemberInitCheck(StringRef Name, ClangTidyContext *Context) : ClangTidyCheck(Name, Context), diff --git a/clang-tools-extra/clang-tidy/llvm/UseNewMLIROpBuilderCheck.cpp b/clang-tools-extra/clang-tidy/llvm/UseNewMLIROpBuilderCheck.cpp index 0d81b9a..bd51cc5 100644 --- a/clang-tools-extra/clang-tidy/llvm/UseNewMLIROpBuilderCheck.cpp +++ b/clang-tools-extra/clang-tidy/llvm/UseNewMLIROpBuilderCheck.cpp @@ -111,10 +111,10 @@ EditGenerator rewrite(RangeSelector Call, RangeSelector Builder, } RewriteRuleWith<std::string> useNewMlirOpBuilderCheckRule() { - Stencil message = cat("use 'OpType::create(builder, ...)' instead of " + Stencil Message = cat("use 'OpType::create(builder, ...)' instead of " "'builder.create<OpType>(...)'"); // Match a create call on an OpBuilder. - ast_matchers::internal::Matcher<Stmt> base = + ast_matchers::internal::Matcher<Stmt> Base = cxxMemberCallExpr( on(expr(hasType( cxxRecordDecl(isSameOrDerivedFrom("::mlir::OpBuilder")))) @@ -124,10 +124,10 @@ RewriteRuleWith<std::string> useNewMlirOpBuilderCheckRule() { .bind("call"); return applyFirst( // Attempt rewrite given an lvalue builder, else just warn. - {makeRule(cxxMemberCallExpr(unless(on(cxxTemporaryObjectExpr())), base), + {makeRule(cxxMemberCallExpr(unless(on(cxxTemporaryObjectExpr())), Base), rewrite(node("call"), node("builder"), callArgs("call")), - message), - makeRule(base, noopEdit(node("call")), message)}); + Message), + makeRule(Base, noopEdit(node("call")), Message)}); } } // namespace diff --git a/clang-tools-extra/clang-tidy/misc/CoroutineHostileRAIICheck.cpp b/clang-tools-extra/clang-tidy/misc/CoroutineHostileRAIICheck.cpp index 8ec7695..3b9b8e0 100644 --- a/clang-tools-extra/clang-tidy/misc/CoroutineHostileRAIICheck.cpp +++ b/clang-tools-extra/clang-tidy/misc/CoroutineHostileRAIICheck.cpp @@ -60,12 +60,12 @@ AST_MATCHER_P(CoawaitExpr, awaitable, ast_matchers::internal::Matcher<Expr>, return InnerMatcher.matches(*E, Finder, Builder); return false; } +} // namespace -auto typeWithNameIn(const std::vector<StringRef> &Names) { +static auto typeWithNameIn(const std::vector<StringRef> &Names) { return hasType( hasCanonicalType(hasDeclaration(namedDecl(hasAnyName(Names))))); } -} // namespace CoroutineHostileRAIICheck::CoroutineHostileRAIICheck(StringRef Name, ClangTidyContext *Context) diff --git a/clang-tools-extra/clang-tidy/misc/NewDeleteOverloadsCheck.cpp b/clang-tools-extra/clang-tidy/misc/NewDeleteOverloadsCheck.cpp index 5e0f32a..9801c9e 100644 --- a/clang-tools-extra/clang-tidy/misc/NewDeleteOverloadsCheck.cpp +++ b/clang-tools-extra/clang-tidy/misc/NewDeleteOverloadsCheck.cpp @@ -53,7 +53,7 @@ AST_MATCHER(FunctionDecl, isPlacementOverload) { const auto *FPT = Node.getType()->castAs<FunctionProtoType>(); ASTContext &Ctx = Node.getASTContext(); if (Ctx.getLangOpts().SizedDeallocation && - Ctx.hasSameType(FPT->getParamType(1), Ctx.getSizeType())) + ASTContext::hasSameType(FPT->getParamType(1), Ctx.getSizeType())) return false; return true; diff --git a/clang-tools-extra/clang-tidy/misc/NoRecursionCheck.cpp b/clang-tools-extra/clang-tidy/misc/NoRecursionCheck.cpp index 0d7667c..035598d 100644 --- a/clang-tools-extra/clang-tidy/misc/NoRecursionCheck.cpp +++ b/clang-tools-extra/clang-tidy/misc/NoRecursionCheck.cpp @@ -151,10 +151,12 @@ constexpr unsigned SmallSCCSize = 32; using CallStackTy = llvm::SmallVector<CallGraphNode::CallRecord, SmallCallStackSize>; +} // namespace + // In given SCC, find *some* call stack that will be cyclic. // This will only find *one* such stack, it might not be the smallest one, // and there may be other loops. -CallStackTy pathfindSomeCycle(ArrayRef<CallGraphNode *> SCC) { +static CallStackTy pathfindSomeCycle(ArrayRef<CallGraphNode *> SCC) { // We'll need to be able to performantly look up whether some CallGraphNode // is in SCC or not, so cache all the SCC elements in a set. const ImmutableSmallSet<CallGraphNode *, SmallSCCSize> SCCElts(SCC); @@ -190,8 +192,6 @@ CallStackTy pathfindSomeCycle(ArrayRef<CallGraphNode *> SCC) { return CallStack; } -} // namespace - void NoRecursionCheck::registerMatchers(MatchFinder *Finder) { Finder->addMatcher(translationUnitDecl().bind("TUDecl"), this); } diff --git a/clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp b/clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp index 17a8a50..6baa12a 100644 --- a/clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp +++ b/clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp @@ -29,7 +29,6 @@ using namespace clang::ast_matchers; using namespace clang::tidy::matchers; namespace clang::tidy::misc { -namespace { using llvm::APSInt; static constexpr llvm::StringLiteral KnownBannedMacroNames[] = { @@ -420,6 +419,8 @@ markDuplicateOperands(const TExpr *TheExpr, return Duplicates.any(); } +namespace { + AST_MATCHER(Expr, isIntegerConstantExpr) { if (Node.isInstantiationDependent()) return false; @@ -470,6 +471,8 @@ AST_MATCHER_P(Expr, expandedByMacro, ArrayRef<llvm::StringLiteral>, Names) { return false; } +} // namespace + // Returns a matcher for integer constant expressions. static ast_matchers::internal::Matcher<Expr> matchIntegerConstantExpr(StringRef Id) { @@ -805,7 +808,8 @@ static bool isSameRawIdentifierToken(const Token &T1, const Token &T2, StringRef(SM.getCharacterData(T2.getLocation()), T2.getLength()); } -bool isTokAtEndOfExpr(SourceRange ExprSR, Token T, const SourceManager &SM) { +static bool isTokAtEndOfExpr(SourceRange ExprSR, Token T, + const SourceManager &SM) { return SM.getExpansionLoc(ExprSR.getEnd()) == T.getLocation(); } @@ -921,7 +925,6 @@ static bool areExprsSameMacroOrLiteral(const BinaryOperator *BinOp, return false; } -} // namespace void RedundantExpressionCheck::registerMatchers(MatchFinder *Finder) { const auto BannedIntegerLiteral = diff --git a/clang-tools-extra/clang-tidy/misc/UniqueptrResetReleaseCheck.cpp b/clang-tools-extra/clang-tidy/misc/UniqueptrResetReleaseCheck.cpp index 27ddb7c..ab2077b 100644 --- a/clang-tools-extra/clang-tidy/misc/UniqueptrResetReleaseCheck.cpp +++ b/clang-tools-extra/clang-tidy/misc/UniqueptrResetReleaseCheck.cpp @@ -53,9 +53,8 @@ void UniqueptrResetReleaseCheck::registerMatchers(MatchFinder *Finder) { this); } -namespace { -const Type *getDeleterForUniquePtr(const MatchFinder::MatchResult &Result, - StringRef ID) { +static const Type * +getDeleterForUniquePtr(const MatchFinder::MatchResult &Result, StringRef ID) { const auto *Class = Result.Nodes.getNodeAs<ClassTemplateSpecializationDecl>(ID); if (!Class) @@ -66,7 +65,7 @@ const Type *getDeleterForUniquePtr(const MatchFinder::MatchResult &Result, return DeleterArgument.getAsType().getTypePtr(); } -bool areDeletersCompatible(const MatchFinder::MatchResult &Result) { +static bool areDeletersCompatible(const MatchFinder::MatchResult &Result) { const Type *LeftDeleterType = getDeleterForUniquePtr(Result, "left_class"); const Type *RightDeleterType = getDeleterForUniquePtr(Result, "right_class"); @@ -103,8 +102,6 @@ bool areDeletersCompatible(const MatchFinder::MatchResult &Result) { return false; } -} // namespace - void UniqueptrResetReleaseCheck::check(const MatchFinder::MatchResult &Result) { if (!areDeletersCompatible(Result)) return; diff --git a/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp b/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp index 37482583..fea5ac6 100644 --- a/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp @@ -499,7 +499,7 @@ static bool canBeModified(ASTContext *Context, const Expr *E) { return true; if (const auto *Cast = Parents[0].get<ImplicitCastExpr>()) { if ((Cast->getCastKind() == CK_NoOp && - Context->hasSameType(Cast->getType(), E->getType().withConst())) || + ASTContext::hasSameType(Cast->getType(), E->getType().withConst())) || (Cast->getCastKind() == CK_LValueToRValue && !Cast->getType().isNull() && Cast->getType()->isFundamentalType())) return false; @@ -664,7 +664,8 @@ void LoopConvertCheck::doConversion( AliasVarIsRef = true; } if (Descriptor.ElemType.isNull() || - !Context->hasSameUnqualifiedType(AliasVarType, Descriptor.ElemType)) + !ASTContext::hasSameUnqualifiedType(AliasVarType, + Descriptor.ElemType)) Descriptor.ElemType = AliasVarType; } @@ -944,7 +945,7 @@ bool LoopConvertCheck::isConvertible(ASTContext *Context, CanonicalInitVarType->isPointerType()) { // If the initializer and the variable are both pointers check if the // un-qualified pointee types match, otherwise we don't use auto. - return Context->hasSameUnqualifiedType( + return ASTContext::hasSameUnqualifiedType( CanonicalBeginType->getPointeeType(), CanonicalInitVarType->getPointeeType()); } diff --git a/clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.cpp b/clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.cpp index 286c39b..586deea 100644 --- a/clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.cpp +++ b/clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.cpp @@ -370,7 +370,7 @@ static bool isAliasDecl(ASTContext *Context, const Decl *TheDecl, DeclarationType = DeclarationType.getNonReferenceType(); if (InitType.isNull() || DeclarationType.isNull() || - !Context->hasSameUnqualifiedType(DeclarationType, InitType)) + !ASTContext::hasSameUnqualifiedType(DeclarationType, InitType)) return false; } diff --git a/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp index c7fd0a9..01796a6 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp @@ -316,7 +316,7 @@ void UseAutoCheck::replaceIterators(const DeclStmt *D, ASTContext *Context) { if (NestedConstruct->getConstructor()->isConvertingConstructor(false)) return; } - if (!Context->hasSameType(V->getType(), E->getType())) + if (!ASTContext::hasSameType(V->getType(), E->getType())) return; } @@ -378,7 +378,7 @@ void UseAutoCheck::replaceExpr( return; // If VarDecl and Initializer have mismatching unqualified types. - if (!Context->hasSameUnqualifiedType(V->getType(), GetType(Expr))) + if (!ASTContext::hasSameUnqualifiedType(V->getType(), GetType(Expr))) return; // All subsequent variables in this declaration should have the same diff --git a/clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp index b921819..b6834c6 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp @@ -21,8 +21,6 @@ using namespace llvm; namespace clang::tidy::modernize { namespace { -const char CastSequence[] = "sequence"; - AST_MATCHER(Type, sugaredNullptrType) { const Type *DesugaredType = Node.getUnqualifiedDesugaredType(); if (const auto *BT = dyn_cast<BuiltinType>(DesugaredType)) @@ -30,6 +28,10 @@ AST_MATCHER(Type, sugaredNullptrType) { return false; } +} // namespace + +static const char CastSequence[] = "sequence"; + /// Create a matcher that finds implicit casts as well as the head of a /// sequence of zero or more nested explicit casts that have an implicit cast /// to null within. @@ -43,7 +45,8 @@ AST_MATCHER(Type, sugaredNullptrType) { /// would check for the "NULL" macro instead, but that'd be harder to express. /// In practice, "NULL" is often defined as "__null", and this is a useful /// condition. -StatementMatcher makeCastSequenceMatcher(llvm::ArrayRef<StringRef> NameList) { +static StatementMatcher +makeCastSequenceMatcher(llvm::ArrayRef<StringRef> NameList) { auto ImplicitCastToNull = implicitCastExpr( anyOf(hasCastKind(CK_NullToPointer), hasCastKind(CK_NullToMemberPointer)), anyOf(hasSourceExpression(gnuNullExpr()), @@ -79,16 +82,16 @@ StatementMatcher makeCastSequenceMatcher(llvm::ArrayRef<StringRef> NameList) { unless(hasAncestor(functionDecl(isDefaulted())))))); } -bool isReplaceableRange(SourceLocation StartLoc, SourceLocation EndLoc, - const SourceManager &SM) { +static bool isReplaceableRange(SourceLocation StartLoc, SourceLocation EndLoc, + const SourceManager &SM) { return SM.isWrittenInSameFile(StartLoc, EndLoc); } /// Replaces the provided range with the text "nullptr", but only if /// the start and end location are both in main file. /// Returns true if and only if a replacement was made. -void replaceWithNullptr(ClangTidyCheck &Check, SourceManager &SM, - SourceLocation StartLoc, SourceLocation EndLoc) { +static void replaceWithNullptr(ClangTidyCheck &Check, SourceManager &SM, + SourceLocation StartLoc, SourceLocation EndLoc) { CharSourceRange Range(SourceRange(StartLoc, EndLoc), true); // Add a space if nullptr follows an alphanumeric character. This happens // whenever there is an c-style explicit cast to nullptr not surrounded by @@ -106,8 +109,9 @@ void replaceWithNullptr(ClangTidyCheck &Check, SourceManager &SM, /// #define MY_NULL NULL /// \endcode /// If \p Loc points to NULL, this function will return the name MY_NULL. -StringRef getOutermostMacroName(SourceLocation Loc, const SourceManager &SM, - const LangOptions &LO) { +static StringRef getOutermostMacroName(SourceLocation Loc, + const SourceManager &SM, + const LangOptions &LO) { assert(Loc.isMacroID()); SourceLocation OutermostMacroLoc; @@ -119,6 +123,8 @@ StringRef getOutermostMacroName(SourceLocation Loc, const SourceManager &SM, return Lexer::getImmediateMacroName(OutermostMacroLoc, SM, LO); } +namespace { + /// RecursiveASTVisitor for ensuring all nodes rooted at a given AST /// subtree that have file-level source locations corresponding to a macro /// argument have implicit NullTo(Member)Pointer nodes as ancestors. diff --git a/clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.cpp b/clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.cpp index d26480f..7c90130 100644 --- a/clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.cpp +++ b/clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.cpp @@ -17,9 +17,8 @@ using namespace clang::ast_matchers; namespace clang::tidy::performance { -namespace { - -std::optional<std::string> makeCharacterLiteral(const StringLiteral *Literal) { +static std::optional<std::string> +makeCharacterLiteral(const StringLiteral *Literal) { std::string Result; { llvm::raw_string_ostream OS(Result); @@ -43,6 +42,8 @@ std::optional<std::string> makeCharacterLiteral(const StringLiteral *Literal) { return Result; } +namespace { + AST_MATCHER_FUNCTION(ast_matchers::internal::Matcher<Expr>, hasSubstitutedType) { return hasType(qualType(anyOf(substTemplateTypeParmType(), diff --git a/clang-tools-extra/clang-tidy/performance/InefficientVectorOperationCheck.cpp b/clang-tools-extra/clang-tidy/performance/InefficientVectorOperationCheck.cpp index 3da1469..4a8f292 100644 --- a/clang-tools-extra/clang-tidy/performance/InefficientVectorOperationCheck.cpp +++ b/clang-tools-extra/clang-tidy/performance/InefficientVectorOperationCheck.cpp @@ -17,8 +17,6 @@ using namespace clang::ast_matchers; namespace clang::tidy::performance { -namespace { - // Matcher names. Given the code: // // \code @@ -60,12 +58,14 @@ static const char LoopInitVarName[] = "loop_init_var"; static const char LoopEndExprName[] = "loop_end_expr"; static const char RangeLoopName[] = "for_range_loop"; -ast_matchers::internal::Matcher<Expr> supportedContainerTypesMatcher() { +static ast_matchers::internal::Matcher<Expr> supportedContainerTypesMatcher() { return hasType(cxxRecordDecl(hasAnyName( "::std::vector", "::std::set", "::std::unordered_set", "::std::map", "::std::unordered_map", "::std::array", "::std::deque"))); } +namespace { + AST_MATCHER(Expr, hasSideEffects) { return Node.HasSideEffects(Finder->getASTContext()); } diff --git a/clang-tools-extra/clang-tidy/readability/DuplicateIncludeCheck.cpp b/clang-tools-extra/clang-tidy/readability/DuplicateIncludeCheck.cpp index 570a109..0237c05 100644 --- a/clang-tools-extra/clang-tidy/readability/DuplicateIncludeCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/DuplicateIncludeCheck.cpp @@ -64,6 +64,8 @@ private: const SourceManager &SM; }; +} // namespace + void DuplicateIncludeCallbacks::FileChanged(SourceLocation Loc, FileChangeReason Reason, SrcMgr::CharacteristicKind FileType, @@ -107,8 +109,6 @@ void DuplicateIncludeCallbacks::MacroUndefined(const Token &MacroNameTok, Files.back().clear(); } -} // namespace - void DuplicateIncludeCheck::registerPPCallbacks( const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) { PP->addPPCallbacks(std::make_unique<DuplicateIncludeCallbacks>(*this, SM)); diff --git a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp index bfdf9cb..6f6da57 100644 --- a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp @@ -51,7 +51,7 @@ static StringRef getZeroLiteralToCompareWithForType(CastKind CastExprKind, return Type->isUnsignedIntegerType() ? "0u" : "0"; case CK_FloatingToBoolean: - return Context.hasSameType(Type, Context.FloatTy) ? "0.0f" : "0.0"; + return ASTContext::hasSameType(Type, Context.FloatTy) ? "0.0f" : "0.0"; case CK_PointerToBoolean: case CK_MemberPointerToBoolean: // Fall-through on purpose. @@ -215,7 +215,7 @@ getEquivalentForBoolLiteral(const CXXBoolLiteralExpr *BoolLiteral, } if (DestType->isFloatingType()) { - if (Context.hasSameType(DestType, Context.FloatTy)) { + if (ASTContext::hasSameType(DestType, Context.FloatTy)) { return BoolLiteral->getValue() ? "1.0f" : "0.0f"; } return BoolLiteral->getValue() ? "1.0" : "0.0"; diff --git a/clang-tools-extra/clang-tidy/readability/InconsistentDeclarationParameterNameCheck.cpp b/clang-tools-extra/clang-tidy/readability/InconsistentDeclarationParameterNameCheck.cpp index 2eb26fc..93580a7 100644 --- a/clang-tools-extra/clang-tidy/readability/InconsistentDeclarationParameterNameCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/InconsistentDeclarationParameterNameCheck.cpp @@ -54,9 +54,12 @@ struct InconsistentDeclarationInfo { using InconsistentDeclarationsContainer = llvm::SmallVector<InconsistentDeclarationInfo, 2>; -bool checkIfFixItHintIsApplicable( - const FunctionDecl *ParameterSourceDeclaration, - const ParmVarDecl *SourceParam, const FunctionDecl *OriginalDeclaration) { +} // namespace + +static bool +checkIfFixItHintIsApplicable(const FunctionDecl *ParameterSourceDeclaration, + const ParmVarDecl *SourceParam, + const FunctionDecl *OriginalDeclaration) { // Assumptions with regard to function declarations/definition: // * If both function declaration and definition are seen, assume that // definition is most up-to-date, and use it to generate replacements. @@ -83,7 +86,7 @@ bool checkIfFixItHintIsApplicable( return true; } -bool nameMatch(StringRef L, StringRef R, bool Strict) { +static bool nameMatch(StringRef L, StringRef R, bool Strict) { if (Strict) return L.empty() || R.empty() || L == R; // We allow two names if one is a prefix/suffix of the other, ignoring case. @@ -92,7 +95,7 @@ bool nameMatch(StringRef L, StringRef R, bool Strict) { L.ends_with_insensitive(R) || R.ends_with_insensitive(L); } -DifferingParamsContainer +static DifferingParamsContainer findDifferingParamsInDeclaration(const FunctionDecl *ParameterSourceDeclaration, const FunctionDecl *OtherDeclaration, const FunctionDecl *OriginalDeclaration, @@ -129,7 +132,7 @@ findDifferingParamsInDeclaration(const FunctionDecl *ParameterSourceDeclaration, return DifferingParams; } -InconsistentDeclarationsContainer +static InconsistentDeclarationsContainer findInconsistentDeclarations(const FunctionDecl *OriginalDeclaration, const FunctionDecl *ParameterSourceDeclaration, SourceManager &SM, bool Strict) { @@ -162,7 +165,7 @@ findInconsistentDeclarations(const FunctionDecl *OriginalDeclaration, return InconsistentDeclarations; } -const FunctionDecl * +static const FunctionDecl * getParameterSourceDeclaration(const FunctionDecl *OriginalDeclaration) { const FunctionTemplateDecl *PrimaryTemplate = OriginalDeclaration->getPrimaryTemplate(); @@ -187,7 +190,7 @@ getParameterSourceDeclaration(const FunctionDecl *OriginalDeclaration) { return OriginalDeclaration; } -std::string joinParameterNames( +static std::string joinParameterNames( const DifferingParamsContainer &DifferingParams, llvm::function_ref<StringRef(const DifferingParamInfo &)> ChooseParamName) { llvm::SmallString<40> Str; @@ -202,7 +205,7 @@ std::string joinParameterNames( return std::string(Str); } -void formatDifferingParamsDiagnostic( +static void formatDifferingParamsDiagnostic( InconsistentDeclarationParameterNameCheck *Check, SourceLocation Location, StringRef OtherDeclarationDescription, const DifferingParamsContainer &DifferingParams) { @@ -230,7 +233,7 @@ void formatDifferingParamsDiagnostic( } } -void formatDiagnosticsForDeclarations( +static void formatDiagnosticsForDeclarations( InconsistentDeclarationParameterNameCheck *Check, const FunctionDecl *ParameterSourceDeclaration, const FunctionDecl *OriginalDeclaration, @@ -256,7 +259,7 @@ void formatDiagnosticsForDeclarations( } } -void formatDiagnostics( +static void formatDiagnostics( InconsistentDeclarationParameterNameCheck *Check, const FunctionDecl *ParameterSourceDeclaration, const FunctionDecl *OriginalDeclaration, @@ -279,8 +282,6 @@ void formatDiagnostics( } } -} // anonymous namespace - void InconsistentDeclarationParameterNameCheck::storeOptions( ClangTidyOptions::OptionMap &Opts) { Options.store(Opts, "IgnoreMacros", IgnoreMacros); diff --git a/clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp b/clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp index dc9510d..942a0a8 100644 --- a/clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp @@ -142,12 +142,11 @@ void QualifiedAutoCheck::registerMatchers(MatchFinder *Finder) { if (this->IgnoreAliasing) { return qualType( hasUnqualifiedDesugaredType(pointerType(pointee(InnerMatchers...)))); - } else { - return qualType( - anyOf(qualType(pointerType(pointee(InnerMatchers...))), - qualType(substTemplateTypeParmType(hasReplacementType( - pointerType(pointee(InnerMatchers...))))))); } + return qualType(anyOf(qualType(pointerType(pointee(InnerMatchers...))), + qualType(substTemplateTypeParmType(hasReplacementType( + pointerType(pointee(InnerMatchers...))))))); + }; auto IsAutoDeducedToPointer = diff --git a/clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.cpp b/clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.cpp index 0598683..107291d 100644 --- a/clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.cpp @@ -14,8 +14,8 @@ using namespace clang::ast_matchers; namespace clang::tidy::readability { -namespace { -internal::Matcher<Expr> callToGet(const internal::Matcher<Decl> &OnClass) { +static internal::Matcher<Expr> +callToGet(const internal::Matcher<Decl> &OnClass) { return expr( anyOf(cxxMemberCallExpr( on(expr(anyOf(hasType(OnClass), @@ -43,12 +43,13 @@ internal::Matcher<Expr> callToGet(const internal::Matcher<Decl> &OnClass) { .bind("redundant_get"); } -internal::Matcher<Decl> knownSmartptr() { +static internal::Matcher<Decl> knownSmartptr() { return recordDecl(hasAnyName("::std::unique_ptr", "::std::shared_ptr")); } -void registerMatchersForGetArrowStart(MatchFinder *Finder, - MatchFinder::MatchCallback *Callback) { +static void +registerMatchersForGetArrowStart(MatchFinder *Finder, + MatchFinder::MatchCallback *Callback) { const auto MatchesOpArrow = allOf(hasName("operator->"), returns(qualType(pointsTo(type().bind("op->Type"))))); @@ -100,8 +101,8 @@ void registerMatchersForGetArrowStart(MatchFinder *Finder, Callback); } -void registerMatchersForGetEquals(MatchFinder *Finder, - MatchFinder::MatchCallback *Callback) { +static void registerMatchersForGetEquals(MatchFinder *Finder, + MatchFinder::MatchCallback *Callback) { // This one is harder to do with duck typing. // The operator==/!= that we are looking for might be member or non-member, // might be on global namespace or found by ADL, might be a template, etc. @@ -118,8 +119,6 @@ void registerMatchersForGetEquals(MatchFinder *Finder, // FIXME: Match and fix if (l.get() == r.get()). } -} // namespace - void RedundantSmartptrGetCheck::storeOptions( ClangTidyOptions::OptionMap &Opts) { Options.store(Opts, "IgnoreMacros", IgnoreMacros); diff --git a/clang-tools-extra/clang-tidy/readability/SuspiciousCallArgumentCheck.cpp b/clang-tools-extra/clang-tidy/readability/SuspiciousCallArgumentCheck.cpp index d1738f1..feb248d 100644 --- a/clang-tools-extra/clang-tidy/readability/SuspiciousCallArgumentCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/SuspiciousCallArgumentCheck.cpp @@ -288,8 +288,8 @@ static bool applyDiceHeuristic(StringRef Arg, StringRef Param, std::size_t Intersection = 0; // Find the intersection between the two sets. - for (auto IT = ParamBigrams.begin(); IT != ParamBigrams.end(); ++IT) - Intersection += ArgBigrams.count((IT->getKey())); + for (const auto &[Key, _] : ParamBigrams) + Intersection += ArgBigrams.count(Key); // Calculate Dice coefficient. return percentage(Intersection * 2.0, diff --git a/clang-tools-extra/clang-tidy/readability/UppercaseLiteralSuffixCheck.cpp b/clang-tools-extra/clang-tidy/readability/UppercaseLiteralSuffixCheck.cpp index c1dc209..740a68d 100644 --- a/clang-tools-extra/clang-tidy/readability/UppercaseLiteralSuffixCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/UppercaseLiteralSuffixCheck.cpp @@ -55,8 +55,10 @@ struct NewSuffix { std::optional<FixItHint> FixIt; }; -std::optional<SourceLocation> getMacroAwareLocation(SourceLocation Loc, - const SourceManager &SM) { +} // namespace + +static std::optional<SourceLocation> +getMacroAwareLocation(SourceLocation Loc, const SourceManager &SM) { // Do nothing if the provided location is invalid. if (Loc.isInvalid()) return std::nullopt; @@ -67,8 +69,8 @@ std::optional<SourceLocation> getMacroAwareLocation(SourceLocation Loc, return SpellingLoc; } -std::optional<SourceRange> getMacroAwareSourceRange(SourceRange Loc, - const SourceManager &SM) { +static std::optional<SourceRange> +getMacroAwareSourceRange(SourceRange Loc, const SourceManager &SM) { std::optional<SourceLocation> Begin = getMacroAwareLocation(Loc.getBegin(), SM); std::optional<SourceLocation> End = getMacroAwareLocation(Loc.getEnd(), SM); @@ -77,7 +79,7 @@ std::optional<SourceRange> getMacroAwareSourceRange(SourceRange Loc, return SourceRange(*Begin, *End); } -std::optional<std::string> +static std::optional<std::string> getNewSuffix(llvm::StringRef OldSuffix, const std::vector<StringRef> &NewSuffixes) { // If there is no config, just uppercase the entirety of the suffix. @@ -96,7 +98,7 @@ getNewSuffix(llvm::StringRef OldSuffix, } template <typename LiteralType> -std::optional<NewSuffix> +static std::optional<NewSuffix> shouldReplaceLiteralSuffix(const Expr &Literal, const std::vector<StringRef> &NewSuffixes, const SourceManager &SM, const LangOptions &LO) { @@ -174,8 +176,6 @@ shouldReplaceLiteralSuffix(const Expr &Literal, return ReplacementDsc; } -} // namespace - UppercaseLiteralSuffixCheck::UppercaseLiteralSuffixCheck( StringRef Name, ClangTidyContext *Context) : ClangTidyCheck(Name, Context), diff --git a/clang-tools-extra/clang-tidy/utils/DeclRefExprUtils.cpp b/clang-tools-extra/clang-tidy/utils/DeclRefExprUtils.cpp index 57453ad..a5b0883 100644 --- a/clang-tools-extra/clang-tidy/utils/DeclRefExprUtils.cpp +++ b/clang-tools-extra/clang-tidy/utils/DeclRefExprUtils.cpp @@ -19,9 +19,8 @@ namespace clang::tidy::utils::decl_ref_expr { using namespace ::clang::ast_matchers; using llvm::SmallPtrSet; -namespace { - -template <typename S> bool isSetDifferenceEmpty(const S &S1, const S &S2) { +template <typename S> +static bool isSetDifferenceEmpty(const S &S1, const S &S2) { for (auto E : S1) if (S2.count(E) == 0) return false; @@ -30,15 +29,15 @@ template <typename S> bool isSetDifferenceEmpty(const S &S1, const S &S2) { // Extracts all Nodes keyed by ID from Matches and inserts them into Nodes. template <typename Node> -void extractNodesByIdTo(ArrayRef<BoundNodes> Matches, StringRef ID, - SmallPtrSet<const Node *, 16> &Nodes) { +static void extractNodesByIdTo(ArrayRef<BoundNodes> Matches, StringRef ID, + SmallPtrSet<const Node *, 16> &Nodes) { for (const auto &Match : Matches) Nodes.insert(Match.getNodeAs<Node>(ID)); } // Returns true if both types refer to the same type, // ignoring the const-qualifier. -bool isSameTypeIgnoringConst(QualType A, QualType B) { +static bool isSameTypeIgnoringConst(QualType A, QualType B) { A = A.getCanonicalType(); B = B.getCanonicalType(); A.addConst(); @@ -47,7 +46,8 @@ bool isSameTypeIgnoringConst(QualType A, QualType B) { } // Returns true if `D` and `O` have the same parameter types. -bool hasSameParameterTypes(const CXXMethodDecl &D, const CXXMethodDecl &O) { +static bool hasSameParameterTypes(const CXXMethodDecl &D, + const CXXMethodDecl &O) { if (D.getNumParams() != O.getNumParams()) return false; for (int I = 0, E = D.getNumParams(); I < E; ++I) { @@ -60,7 +60,7 @@ bool hasSameParameterTypes(const CXXMethodDecl &D, const CXXMethodDecl &O) { // If `D` has a const-qualified overload with otherwise identical // ref-qualifiers and parameter types, returns that overload. -const CXXMethodDecl *findConstOverload(const CXXMethodDecl &D) { +static const CXXMethodDecl *findConstOverload(const CXXMethodDecl &D) { assert(!D.isConst()); DeclContext::lookup_result LookupResult = @@ -81,7 +81,7 @@ const CXXMethodDecl *findConstOverload(const CXXMethodDecl &D) { // Returns true if both types are pointers or reference to the same type, // ignoring the const-qualifier. -bool pointsToSameTypeIgnoringConst(QualType A, QualType B) { +static bool pointsToSameTypeIgnoringConst(QualType A, QualType B) { assert(A->isPointerType() || A->isReferenceType()); assert(B->isPointerType() || B->isReferenceType()); return isSameTypeIgnoringConst(A->getPointeeType(), B->getPointeeType()); @@ -122,7 +122,7 @@ bool pointsToSameTypeIgnoringConst(QualType A, QualType B) { // // This function checks (A) ad (B), but the caller should make sure that the // object is not mutated through the return value. -bool isLikelyShallowConst(const CXXMethodDecl &M) { +static bool isLikelyShallowConst(const CXXMethodDecl &M) { assert(!M.isConst()); // The method can mutate our variable. @@ -146,6 +146,8 @@ bool isLikelyShallowConst(const CXXMethodDecl &M) { return isSameTypeIgnoringConst(CallTy, OverloadTy); } +namespace { + // A matcher that matches DeclRefExprs that are used in ways such that the // underlying declaration is not modified. // If the declaration is of pointer type, `Indirections` specifies the level diff --git a/clang-tools-extra/clang-tidy/utils/DesignatedInitializers.cpp b/clang-tools-extra/clang-tidy/utils/DesignatedInitializers.cpp index 044f89b..b068ae2 100644 --- a/clang-tools-extra/clang-tidy/utils/DesignatedInitializers.cpp +++ b/clang-tools-extra/clang-tidy/utils/DesignatedInitializers.cpp @@ -19,8 +19,6 @@ namespace clang::tidy::utils { -namespace { - /// Returns true if Name is reserved, like _Foo or __Vector_base. static inline bool isReservedName(llvm::StringRef Name) { // This doesn't catch all cases, but the most common. @@ -28,6 +26,8 @@ static inline bool isReservedName(llvm::StringRef Name) { (isUppercase(Name[1]) || Name[1] == '_'); } +namespace { + // Helper class to iterate over the designator names of an aggregate type. // // For an array type, yields [0], [1], [2]... @@ -112,6 +112,8 @@ private: RecordDecl::field_iterator FieldsEnd; }; +} // namespace + // Collect designator labels describing the elements of an init list. // // This function contributes the designators of some (sub)object, which is @@ -127,10 +129,9 @@ private: // '.a:' is produced directly without recursing into the written sublist. // (The written sublist will have a separate collectDesignators() call later). // Recursion with Prefix='.b' and Sem = {3, ImplicitValue} produces '.b.x:'. -void collectDesignators(const InitListExpr *Sem, - llvm::DenseMap<SourceLocation, std::string> &Out, - const llvm::DenseSet<SourceLocation> &NestedBraces, - std::string &Prefix) { +static void collectDesignators( + const InitListExpr *Sem, llvm::DenseMap<SourceLocation, std::string> &Out, + const llvm::DenseSet<SourceLocation> &NestedBraces, std::string &Prefix) { if (!Sem || Sem->isTransparent()) return; assert(Sem->isSemanticForm()); @@ -170,8 +171,6 @@ void collectDesignators(const InitListExpr *Sem, } } -} // namespace - llvm::DenseMap<SourceLocation, std::string> getUnwrittenDesignators(const InitListExpr *Syn) { assert(Syn->isSyntacticForm()); |