llvmorg-github-actions[bot] wrote:
<!--LLVM PR SUMMARY COMMENT--> @llvm/pr-subscribers-clang-tidy Author: Richard Thomson (LegalizeAdulthood) <details> <summary>Changes</summary> Find overrides that only forward to an inherited implementation. Support inline definitions and paired removal of header declarations and out-of-line definitions. Restrict removal to public methods inherited publicly. Preserve cases that affect access, contracts, overload resolution, copies, or known member-pointer uses, and never offer partial fixes. Add documentation and regression coverage, including compilation of fixed code under native and Linux targets. Fixes #<!-- -->27431. --- Patch is 30.65 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/242955.diff 11 Files Affected: - (modified) clang-tools-extra/clang-tidy/readability/CMakeLists.txt (+1) - (modified) clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp (+3) - (added) clang-tools-extra/clang-tidy/readability/RedundantOverrideCheck.cpp (+223) - (added) clang-tools-extra/clang-tidy/readability/RedundantOverrideCheck.h (+40) - (modified) clang-tools-extra/docs/ReleaseNotes.md (+7) - (modified) clang-tools-extra/docs/clang-tidy/checks/list.md (+1) - (added) clang-tools-extra/docs/clang-tidy/checks/readability/redundant-override.md (+59) - (added) clang-tools-extra/test/clang-tidy/checkers/readability/Inputs/redundant-override/header.h (+24) - (added) clang-tools-extra/test/clang-tidy/checkers/readability/redundant-override-cxx98.cpp (+13) - (added) clang-tools-extra/test/clang-tidy/checkers/readability/redundant-override-header.cpp (+20) - (added) clang-tools-extra/test/clang-tidy/checkers/readability/redundant-override.cpp (+370) ``````````diff diff --git a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt index 11cadf9f398792..f3a94a7cc30258 100644 --- a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt +++ b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt @@ -47,6 +47,7 @@ add_clang_library(clangTidyReadabilityModule STATIC RedundantLambdaParameterListCheck.cpp RedundantMemberInitCheck.cpp RedundantNestedIfCheck.cpp + RedundantOverrideCheck.cpp RedundantParenthesesCheck.cpp RedundantPreprocessorCheck.cpp RedundantQualifiedAliasCheck.cpp diff --git a/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp b/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp index 0592ae5f1bf606..8dbedbd7d643e1 100644 --- a/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp +++ b/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp @@ -49,6 +49,7 @@ #include "RedundantLambdaParameterListCheck.h" #include "RedundantMemberInitCheck.h" #include "RedundantNestedIfCheck.h" +#include "RedundantOverrideCheck.h" #include "RedundantParenthesesCheck.h" #include "RedundantPreprocessorCheck.h" #include "RedundantQualifiedAliasCheck.h" @@ -153,6 +154,8 @@ class ReadabilityModule : public ClangTidyModule { "readability-redundant-member-init"); CheckFactories.registerCheck<RedundantNestedIfCheck>( "readability-redundant-nested-if"); + CheckFactories.registerCheck<RedundantOverrideCheck>( + "readability-redundant-override"); CheckFactories.registerCheck<RedundantParenthesesCheck>( "readability-redundant-parentheses"); CheckFactories.registerCheck<RedundantPreprocessorCheck>( diff --git a/clang-tools-extra/clang-tidy/readability/RedundantOverrideCheck.cpp b/clang-tools-extra/clang-tidy/readability/RedundantOverrideCheck.cpp new file mode 100644 index 00000000000000..93ad5a8c618344 --- /dev/null +++ b/clang-tools-extra/clang-tidy/readability/RedundantOverrideCheck.cpp @@ -0,0 +1,223 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "RedundantOverrideCheck.h" +#include "clang/AST/ASTContext.h" +#include "clang/AST/Attr.h" +#include "clang/AST/DeclCXX.h" +#include "clang/AST/ExprCXX.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/Lex/Lexer.h" +#include "llvm/ADT/STLExtras.h" +#include <algorithm> + +using namespace clang::ast_matchers; + +namespace clang::tidy::readability { + +static bool isForwardingType(QualType Type) { + return Type->isVoidType() || Type->isReferenceType() || + (Type->isScalarType() && !Type.isVolatileQualified()); +} + +static bool hasAdditionalInterface(const CXXMethodDecl *Method) { + for (const FunctionDecl *Redecl : Method->redecls()) { + if (Redecl->getBeginLoc().isMacroID() || Redecl->getEndLoc().isMacroID()) + return true; + if (llvm::any_of(Redecl->attrs(), + [](const Attr *A) { return !isa<OverrideAttr>(A); })) + return true; + if (llvm::any_of(Redecl->parameters(), [](const ParmVarDecl *P) { + return P->hasDefaultArg() || P->hasAttrs() || + !isForwardingType(P->getType()); + })) + return true; + } + return false; +} + +static bool hasOtherOverloads(const CXXRecordDecl *Record, + const CXXMethodDecl *Method) { + return llvm::any_of( + Record->lookup(Method->getDeclName()), [Method](const NamedDecl *D) { + return D->getCanonicalDecl() != Method->getCanonicalDecl(); + }); +} + +static const CXXMethodDecl *getRedundantBase(const CXXMethodDecl *Method, + ASTContext &Context) { + const CXXRecordDecl *Record = Method->getParent(); + if (Method->size_overridden_methods() != 1 || Method->isPureVirtual() || + !Method->getDeclName().isIdentifier() || Record->isDependentContext() || + isa<ClassTemplateSpecializationDecl>(Record) || + Method->getTemplatedKind() != FunctionDecl::TK_NonTemplate || + Record->getNumBases() != 1 || Record->hasAttrs() || + hasAdditionalInterface(Method)) + return nullptr; + + const CXXMethodDecl *Base = *Method->begin_overridden_methods(); + const CXXBaseSpecifier &Inheritance = *Record->bases_begin(); + const CXXRecordDecl *BaseRecord = Inheritance.getType()->getAsCXXRecordDecl(); + if (!BaseRecord || Inheritance.isVirtual() || Base->isPureVirtual() || + Base->getAccess() != AS_public || + isa<ClassTemplateSpecializationDecl>(BaseRecord) || + BaseRecord->hasAttrs() || + BaseRecord->getCanonicalDecl() != Base->getParent()->getCanonicalDecl() || + hasAdditionalInterface(Base) || hasOtherOverloads(Record, Method) || + hasOtherOverloads(BaseRecord, Base)) + return nullptr; + + // Removing the override must preserve access through the derived class, + // including access restricted by protected or private inheritance. + const AccessSpecifier InheritedAccess = + std::max(Base->getAccess(), Inheritance.getAccessSpecifier()); + if (InheritedAccess != AS_public || Method->getAccess() != InheritedAccess || + !Context.hasSameType(Method->getType(), Base->getType()) || + !isForwardingType(Method->getReturnType()) || + Method->isConstexpr() != Base->isConstexpr() || + Method->isConsteval() != Base->isConsteval()) + return nullptr; + + const auto *MethodType = Method->getType()->castAs<FunctionProtoType>(); + const auto *BaseType = Base->getType()->castAs<FunctionProtoType>(); + if (MethodType->isVariadic() || MethodType->hasDynamicExceptionSpec() || + MethodType->getExceptionSpecType() != BaseType->getExceptionSpecType() || + isUnresolvedExceptionSpec(MethodType->getExceptionSpecType()) || + MethodType->canThrow() == CT_Dependent || + MethodType->canThrow() != BaseType->canThrow()) + return nullptr; + + const auto *Body = dyn_cast<CompoundStmt>(Method->getBody()); + if (!Body || Body->size() != 1) + return nullptr; + const Stmt *Statement = Body->body_front(); + const Expr *Expression = nullptr; + if (const auto *Return = dyn_cast<ReturnStmt>(Statement)) + Expression = Return->getRetValue(); + else if (Method->getReturnType()->isVoidType()) + Expression = dyn_cast<Expr>(Statement); + if (!Expression) + return nullptr; + + const auto *Call = + dyn_cast<CXXMemberCallExpr>(Expression->IgnoreParenImpCasts()); + if (!Call || !Call->getMethodDecl() || Call->getExprLoc().isMacroID() || + Call->getMethodDecl()->getCanonicalDecl() != Base->getCanonicalDecl() || + Call->getNumArgs() != Method->getNumParams()) + return nullptr; + const auto *Member = + dyn_cast<MemberExpr>(Call->getCallee()->IgnoreParenImpCasts()); + if (!Member || !Member->hasQualifier() || + !isa<CXXThisExpr>( + Call->getImplicitObjectArgument()->IgnoreParenImpCasts())) + return nullptr; + for (unsigned I = 0; I != Call->getNumArgs(); ++I) { + const auto *Argument = + dyn_cast<DeclRefExpr>(Call->getArg(I)->IgnoreParenImpCasts()); + if (!Argument || Argument->getLocation().isMacroID() || + Argument->getDecl() != Method->getParamDecl(I)) + return nullptr; + } + return Base; +} + +static bool getRemovalRanges(const CXXMethodDecl *Method, + const SourceManager &SM, + const LangOptions &LangOpts, + SmallVectorImpl<CharSourceRange> &Ranges) { + for (const FunctionDecl *Redecl : Method->redecls()) { + const SourceRange Range = Redecl->getSourceRange(); + if (Range.isInvalid() || Range.getBegin().isMacroID() || + Range.getEnd().isMacroID() || SM.isInSystemHeader(Range.getBegin())) + return false; + // A shared declaration such as "void f(), g();" cannot be removed whole. + for (const Decl *Other : Redecl->getLexicalDeclContext()->decls()) + if (Other->getCanonicalDecl() != Redecl->getCanonicalDecl() && + Other->getBeginLoc() == Range.getBegin()) + return false; + + CharSourceRange FileRange = Lexer::makeFileCharRange( + CharSourceRange::getTokenRange(Range), SM, LangOpts); + if (FileRange.isInvalid()) + return false; + if (!Redecl->doesThisDeclarationHaveABody()) { + const SourceLocation AfterSemicolon = Lexer::findLocationAfterToken( + Range.getEnd(), tok::semi, SM, LangOpts, + /*SkipTrailingWhitespaceAndNewLine=*/false); + if (AfterSemicolon.isInvalid()) + return false; + FileRange.setEnd(AfterSemicolon); + } + SourceLocation Loc = FileRange.getBegin(); + while (Loc < FileRange.getEnd()) { + Token Tok; + if (Lexer::getRawToken(Loc, Tok, SM, LangOpts, + /*IgnoreWhiteSpace=*/true)) + return false; + if (Tok.getLocation() >= FileRange.getEnd()) + break; + if (Tok.isOneOf(tok::hash, tok::eof)) + return false; + Loc = Tok.getEndLoc(); + } + Ranges.push_back(FileRange); + } + return true; +} + +bool RedundantOverrideCheck::isLanguageVersionSupported( + const LangOptions &LangOpts) const { + return LangOpts.CPlusPlus; +} + +std::optional<TraversalKind> +RedundantOverrideCheck::getCheckTraversalKind() const { + return TK_IgnoreUnlessSpelledInSource; +} + +void RedundantOverrideCheck::registerMatchers(MatchFinder *Finder) { + Finder->addMatcher(cxxMethodDecl(isDefinition(), isVirtual(), + unless(cxxDestructorDecl()), + hasBody(compoundStmt(statementCountIs(1)))) + .bind("method"), + this); + Finder->addMatcher(declRefExpr(to(cxxMethodDecl().bind("referenced-method"))), + this); +} + +void RedundantOverrideCheck::check(const MatchFinder::MatchResult &Result) { + if (const auto *Reference = + Result.Nodes.getNodeAs<CXXMethodDecl>("referenced-method")) { + // A pointer-to-member or its type can depend on the derived declaration. + ReferencedMethods.insert(Reference->getCanonicalDecl()); + return; + } + const auto *Method = Result.Nodes.getNodeAs<CXXMethodDecl>("method"); + if (getRedundantBase(Method, *Result.Context)) + Candidates.push_back(Method); +} + +void RedundantOverrideCheck::onEndOfTranslationUnit() { + for (const CXXMethodDecl *Method : Candidates) { + if (ReferencedMethods.contains(Method->getCanonicalDecl()) || + Method->getLocation().isMacroID()) + continue; + SmallVector<CharSourceRange, 2> Ranges; + if (!getRemovalRanges(Method, Method->getASTContext().getSourceManager(), + getLangOpts(), Ranges)) + continue; + const auto Diag = diag(Method->getLocation(), "redundant override of %0") + << *Method->begin_overridden_methods(); + for (CharSourceRange Range : Ranges) + Diag << FixItHint::CreateRemoval(Range); + } + Candidates.clear(); + ReferencedMethods.clear(); +} + +} // namespace clang::tidy::readability diff --git a/clang-tools-extra/clang-tidy/readability/RedundantOverrideCheck.h b/clang-tools-extra/clang-tidy/readability/RedundantOverrideCheck.h new file mode 100644 index 00000000000000..f325097e96021a --- /dev/null +++ b/clang-tools-extra/clang-tidy/readability/RedundantOverrideCheck.h @@ -0,0 +1,40 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_READABILITY_REDUNDANTOVERRIDECHECK_H +#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_READABILITY_REDUNDANTOVERRIDECHECK_H + +#include "../ClangTidyCheck.h" +#include "llvm/ADT/SmallPtrSet.h" +#include "llvm/ADT/SmallVector.h" + +namespace clang::tidy::readability { + +/// Finds overrides that only forward to the inherited implementation without +/// changing its interface. +/// +/// For the user-facing documentation see: +/// https://clang.llvm.org/extra/clang-tidy/checks/readability/redundant-override.html +class RedundantOverrideCheck : public ClangTidyCheck { +public: + using ClangTidyCheck::ClangTidyCheck; + bool isLanguageVersionSupported(const LangOptions &LangOpts) const override; + void registerMatchers(ast_matchers::MatchFinder *Finder) override; + void check(const ast_matchers::MatchFinder::MatchResult &Result) override; + void onEndOfTranslationUnit() override; + +private: + std::optional<TraversalKind> getCheckTraversalKind() const override; + + SmallVector<const CXXMethodDecl *, 8> Candidates; + llvm::SmallPtrSet<const CXXMethodDecl *, 8> ReferencedMethods; +}; + +} // namespace clang::tidy::readability + +#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_READABILITY_REDUNDANTOVERRIDECHECK_H diff --git a/clang-tools-extra/docs/ReleaseNotes.md b/clang-tools-extra/docs/ReleaseNotes.md index b6774370511feb..b5ddec9e413341 100644 --- a/clang-tools-extra/docs/ReleaseNotes.md +++ b/clang-tools-extra/docs/ReleaseNotes.md @@ -174,6 +174,13 @@ infrastructure are described first, followed by tool-specific sections. Finds uses of `#pragma comment` and, for `lib` or `linker` comments, suggests using the build system for improved portability. +- New {doc}`readability-redundant-override + <clang-tidy/checks/readability/redundant-override>` check. + + Removes overrides that only forward to an inherited implementation + without changing its interface, including declarations and out-of-line + definitions in different files. + - New {doc}`readability-redundant-zero-initializer <clang-tidy/checks/readability/redundant-zero-initializer>` check. diff --git a/clang-tools-extra/docs/clang-tidy/checks/list.md b/clang-tools-extra/docs/clang-tidy/checks/list.md index ec20c380131852..c17a3cde342b9e 100644 --- a/clang-tools-extra/docs/clang-tidy/checks/list.md +++ b/clang-tools-extra/docs/clang-tidy/checks/list.md @@ -427,6 +427,7 @@ readability/* | {doc}`readability-redundant-lambda-parameter-list <readability/redundant-lambda-parameter-list>` | Yes | | {doc}`readability-redundant-member-init <readability/redundant-member-init>` | Yes | | {doc}`readability-redundant-nested-if <readability/redundant-nested-if>` | Yes | +| {doc}`readability/redundant-override` | Yes | | {doc}`readability-redundant-parentheses <readability/redundant-parentheses>` | Yes | | {doc}`readability-redundant-preprocessor <readability/redundant-preprocessor>` | | | {doc}`readability-redundant-qualified-alias <readability/redundant-qualified-alias>` | Yes | diff --git a/clang-tools-extra/docs/clang-tidy/checks/readability/redundant-override.md b/clang-tools-extra/docs/clang-tidy/checks/readability/redundant-override.md new file mode 100644 index 00000000000000..c1722c1e3154b0 --- /dev/null +++ b/clang-tools-extra/docs/clang-tidy/checks/readability/redundant-override.md @@ -0,0 +1,59 @@ +```{title} clang-tidy - readability-redundant-override +``` + +# readability-redundant-override + +Finds virtual overrides that only forward their arguments to the inherited +implementation on the same object, without changing its interface. + +For example: + +```c++ +struct Base { + virtual void f() {} +}; + +struct Derived : Base { + void f() override { Base::f(); } +}; +``` + +becomes: + +```c++ +struct Base { + virtual void f() {} +}; + +struct Derived : Base {}; +``` + +Both inline definitions and out-of-line definitions are supported. When an +override is declared in a header and defined in a source file, the fix +removes both declarations. The check skips an override if any declaration +or definition cannot be safely removed, including shared declarations and +ranges containing preprocessor directives. It never offers a partial fix. + +Access is compared after accounting for the inheritance access specifier. +Only public methods inherited publicly are considered for removal. +Non-public methods and non-public inheritance are preserved. Even matching +non-public access can change access from code in the base class when an +override is removed. + +The check is deliberately conservative. It requires one non-virtual direct +base class declaring the overridden method, a single forwarding call, and +unchanged function types and exception specifications. It does not diagnose +overrides involving: + +- Pure virtual base methods, `final`, or additional attributes. +- Default arguments or overload sets that would affect name lookup. +- Class objects passed or returned by value, or changed argument order or + expressions. +- Templates, multiple inheritance, or virtual inheritance. +- Macro-generated declarations or forwarding calls. +- References to the overriding method that can observe its member-pointer + identity or type in the analyzed translation unit. + +As with removing any member function, uses outside the analyzed translation +unit and binary compatibility require review. All affected translation +units should be rebuilt after applying the fix. diff --git a/clang-tools-extra/test/clang-tidy/checkers/readability/Inputs/redundant-override/header.h b/clang-tools-extra/test/clang-tidy/checkers/readability/Inputs/redundant-override/header.h new file mode 100644 index 00000000000000..7a61a56f7fa2d2 --- /dev/null +++ b/clang-tools-extra/test/clang-tidy/checkers/readability/Inputs/redundant-override/header.h @@ -0,0 +1,24 @@ +#ifndef REDUNDANT_OVERRIDE_HEADER_H +#define REDUNDANT_OVERRIDE_HEADER_H + +struct HeaderBase { + virtual void f() {} + virtual int value(int n) const { return n; } +}; + +struct HeaderDerived : HeaderBase { + void f() override; + int value(int n) const override; +}; +// CHECK-FIXES: struct HeaderDerived : HeaderBase { +// CHECK-FIXES-NOT: f() +// CHECK-FIXES-NOT: value( +// CHECK-FIXES: }; + +struct HeaderVisibility : protected HeaderBase { + void f() override; +}; +// CHECK-FIXES: struct HeaderVisibility : protected HeaderBase { +// CHECK-FIXES-NEXT: void f() override; + +#endif diff --git a/clang-tools-extra/test/clang-tidy/checkers/readability/redundant-override-cxx98.cpp b/clang-tools-extra/test/clang-tidy/checkers/readability/redundant-override-cxx98.cpp new file mode 100644 index 00000000000000..01c99b610b5ebd --- /dev/null +++ b/clang-tools-extra/test/clang-tidy/checkers/readability/redundant-override-cxx98.cpp @@ -0,0 +1,13 @@ +// RUN: %check_clang_tidy -std=c++98 %s readability-redundant-override %t +// RUN: %clang_cc1 -std=c++98 -fsyntax-only %t.cpp + +struct Base { + virtual void f() {} +}; +struct Derived : Base { + virtual void f() { Base::f(); } +}; +// CHECK-MESSAGES: :[[@LINE-2]]:16: warning: redundant override +// CHECK-FIXES: struct Derived : Base { +// CHECK-FIXES-NOT: f() +// CHECK-FIXES: }; diff --git a/clang-tools-extra/test/clang-tidy/checkers/readability/redundant-override-header.cpp b/clang-tools-extra/test/clang-tidy/checkers/readability/redundant-override-header.cpp new file mode 100644 index 00000000000000..be83baf7fdfa53 --- /dev/null +++ b/clang-tools-extra/test/clang-tidy/checkers/readability/redundant-override-header.cpp @@ -0,0 +1,20 @@ +// RUN: %check_clang_tidy -check-header %S/Inputs/redundant-override/header.h \ +// RUN: %s readability-redundant-override %t +// RUN: %clang_cc1 -std=c++11 -fsyntax-only -I%t.cpp.headers %t.cpp + +#include "header.h" + +void HeaderDerived::f() { HeaderBase::f(); } +// CHECK-MESSAGES: :[[@LINE-1]]:21: warning: redundant override +// CHECK-FIXES-NOT: void HeaderDerived::f() +int HeaderDerived::value(int n) const { return HeaderBase::value(n); } +// CHECK-MESSAGES: :[[@LINE-1]]:20: warning: redundant override +// CHECK-FIXES-NOT: int HeaderDerived::value( + +void HeaderVisibility::f() { HeaderBase::f(); } +// CHECK-FIXES: void HeaderVisibility::f() { HeaderBase::f(); } + +void use(HeaderDerived &object) { + object.f(); + object.value(1); +} diff --git a/clang-tools-extra/test/clang-tidy/checkers/readability/redundant-overri... [truncated] `````````` </details> https://github.com/llvm/llvm-project/pull/242955 _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
