-
Notifications
You must be signed in to change notification settings - Fork 15.4k
[clang-tidy] New bugprone-derived-method-shadowing-base-method #154746
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
Conversation
|
Thank you for submitting a Pull Request (PR) to the LLVM Project! This PR will be automatically labeled and the relevant teams will be notified. If you wish to, you can add reviewers by using the "Reviewers" section on this page. If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers. If you have further questions, they may be answered by the LLVM GitHub User Guide. You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums. |
|
@llvm/pr-subscribers-clang-tidy @llvm/pr-subscribers-clang-tools-extra Author: Tom (t-a-james) ChangesThis PR introduces a new bugprone check to find methods in derived classes that hide methods with the same signature in base classes. The best description of what this new check does is the unit test code in Full diff: https://github.com/llvm/llvm-project/pull/154746.diff 8 Files Affected:
diff --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
index 824ebdfbd00dc..d1d1979794743 100644
--- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
@@ -4,6 +4,9 @@
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
+// SPDX-FileCopyrightText: Portions Copyright 2025 Siemens and/or its affiliates
+// May 2025 modified by Siemens and/or its affiliates by Tom James
+//
//===----------------------------------------------------------------------===//
#include "../ClangTidy.h"
@@ -42,6 +45,7 @@
#include "LambdaFunctionNameCheck.h"
#include "MacroParenthesesCheck.h"
#include "MacroRepeatedSideEffectsCheck.h"
+#include "MethodHidingCheck.h"
#include "MisleadingSetterOfReferenceCheck.h"
#include "MisplacedOperatorInStrlenInAllocCheck.h"
#include "MisplacedPointerArithmeticInAllocCheck.h"
@@ -153,6 +157,8 @@ class BugproneModule : public ClangTidyModule {
"bugprone-incorrect-enable-if");
CheckFactories.registerCheck<IncorrectEnableSharedFromThisCheck>(
"bugprone-incorrect-enable-shared-from-this");
+ CheckFactories.registerCheck<MethodHidingCheck>(
+ "bugprone-method-hiding");
CheckFactories.registerCheck<UnintendedCharOstreamOutputCheck>(
"bugprone-unintended-char-ostream-output");
CheckFactories.registerCheck<ReturnConstRefFromParameterCheck>(
diff --git a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
index 59928e5e47a09..5745654855108 100644
--- a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
@@ -1,3 +1,9 @@
+# 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
+# SPDX-FileCopyrightText: Portions Copyright 2025 Siemens and/or its affiliates
+# May 2025 modified by Siemens and/or its affiliates by Tom James
+
set(LLVM_LINK_COMPONENTS
support
FrontendOpenMP
@@ -31,6 +37,7 @@ add_clang_library(clangTidyBugproneModule STATIC
IncorrectEnableIfCheck.cpp
IncorrectEnableSharedFromThisCheck.cpp
InvalidEnumDefaultInitializationCheck.cpp
+ MethodHidingCheck.cpp
UnintendedCharOstreamOutputCheck.cpp
ReturnConstRefFromParameterCheck.cpp
SuspiciousStringviewDataUsageCheck.cpp
diff --git a/clang-tools-extra/clang-tidy/bugprone/MethodHidingCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/MethodHidingCheck.cpp
new file mode 100644
index 0000000000000..865ef115950e6
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/bugprone/MethodHidingCheck.cpp
@@ -0,0 +1,148 @@
+//===--- MethodHidingCheck.cpp - clang-tidy ----------------------------===//
+//
+// SPDX-FileCopyrightText: 2025 Siemens Corporation and/or its affiliates
+//
+// 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 "MethodHidingCheck.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include <stack>
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+namespace {
+
+bool sameBasicType(ParmVarDecl const *Lhs, ParmVarDecl const *Rhs) {
+ if (Lhs && Rhs) {
+ return Lhs->getType()
+ .getCanonicalType()
+ .getNonReferenceType()
+ .getUnqualifiedType() == Rhs->getType()
+ .getCanonicalType()
+ .getNonReferenceType()
+ .getUnqualifiedType();
+ }
+ return false;
+}
+
+bool namesCollide(CXXMethodDecl const &Lhs, CXXMethodDecl const &Rhs) {
+ if (Lhs.getNameAsString() != Rhs.getNameAsString()) {
+ return false;
+ }
+ if (Lhs.isConst() != Rhs.isConst()) {
+ return false;
+ }
+ if (Lhs.getNumParams() != Rhs.getNumParams()) {
+ return false;
+ }
+ for (unsigned int It = 0; It < Lhs.getNumParams(); ++It) {
+ if (!sameBasicType(Lhs.getParamDecl(It), Rhs.getParamDecl(It))) {
+ return false;
+ }
+ }
+ // Templates are not handled yet
+ if (Lhs.isTemplated() || Rhs.isTemplated()) {
+ return false;
+ }
+ if (Lhs.isTemplateInstantiation() || Rhs.isTemplateInstantiation()) {
+ return false;
+ }
+ if (Lhs.isFunctionTemplateSpecialization() ||
+ Rhs.isFunctionTemplateSpecialization()) {
+ return false;
+ }
+ return true;
+}
+
+AST_MATCHER(CXXMethodDecl, nameCollidesWithMethodInBase) {
+ CXXRecordDecl const *DerivedClass = Node.getParent();
+ for (auto const &Base : DerivedClass->bases()) {
+ std::stack<CXXBaseSpecifier const *> Stack;
+ Stack.push(&Base);
+ while (!Stack.empty()) {
+ CXXBaseSpecifier const *CurrentBaseSpec = Stack.top();
+ Stack.pop();
+
+ if (CurrentBaseSpec->getAccessSpecifier() ==
+ clang::AccessSpecifier::AS_private) {
+ continue;
+ }
+
+ const auto *CurrentRecord =
+ CurrentBaseSpec->getType()->getAsCXXRecordDecl();
+ if (!CurrentRecord) {
+ continue;
+ }
+
+ for (auto const &BaseMethod : CurrentRecord->methods()) {
+ if (namesCollide(*BaseMethod, Node)) {
+ ast_matchers::internal::BoundNodesTreeBuilder Result(*Builder);
+ Builder->setBinding("base_method",
+ clang::DynTypedNode::create(*BaseMethod));
+ return true;
+ }
+ }
+
+ for (auto const &SubBase : CurrentRecord->bases()) {
+ Stack.push(&SubBase);
+ }
+ }
+ }
+ return false;
+}
+
+// Same as clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp,
+// similar matchers are used elsewhere in LLVM
+AST_MATCHER(CXXMethodDecl, isOutOfLine) { return Node.isOutOfLine(); }
+
+} // namespace
+
+MethodHidingCheck::MethodHidingCheck(StringRef Name, ClangTidyContext *Context)
+ : ClangTidyCheck(Name, Context) {}
+
+void MethodHidingCheck::registerMatchers(MatchFinder *Finder) {
+ Finder->addMatcher(
+ cxxMethodDecl(
+ unless(anyOf(isOutOfLine(), isStaticStorageClass(), isImplicit(),
+ cxxConstructorDecl(), isOverride(),
+ // isFinal(), //included with isOverride,
+ isPrivate())),
+ ofClass(cxxRecordDecl(
+ isDerivedFrom(cxxRecordDecl(unless(isInStdNamespace()))))
+ .bind("derived_class")),
+ nameCollidesWithMethodInBase())
+ .bind("shadowing_method"),
+ this);
+}
+
+void MethodHidingCheck::check(const MatchFinder::MatchResult &Result) {
+ auto const *ShadowingMethod =
+ Result.Nodes.getNodeAs<CXXMethodDecl>("shadowing_method");
+ auto const *DerivedClass =
+ Result.Nodes.getNodeAs<CXXRecordDecl>("derived_class");
+ auto const *BaseMethod = Result.Nodes.getNodeAs<CXXMethodDecl>("base_method");
+
+ if (!ShadowingMethod || !DerivedClass || !BaseMethod) {
+ llvm_unreachable("Required binding not found");
+ }
+
+ auto const MethodName = ShadowingMethod->getNameInfo().getAsString();
+ auto const DerivedClassName = DerivedClass->getNameAsString();
+ std::string BaseClassName = BaseMethod->getParent()->getNameAsString();
+
+ std::string Message;
+ llvm::raw_string_ostream StringStream(Message);
+ StringStream << "'" << ShadowingMethod->getQualifiedNameAsString()
+ << "' hides same method in '" << BaseClassName << "'";
+ diag(ShadowingMethod->getBeginLoc(), Message);
+ diag(BaseMethod->getBeginLoc(), "previous definition is here",
+ DiagnosticIDs::Note);
+}
+
+} // namespace clang::tidy::bugprone
diff --git a/clang-tools-extra/clang-tidy/bugprone/MethodHidingCheck.h b/clang-tools-extra/clang-tidy/bugprone/MethodHidingCheck.h
new file mode 100644
index 0000000000000..f00f46cdf72e2
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/bugprone/MethodHidingCheck.h
@@ -0,0 +1,37 @@
+//===--- MethodHidingCheck.h - clang-tidy --------------------*- C++ -*-===//
+//
+// SPDX-FileCopyrightText: 2025 Siemens Corporation and/or its affiliates
+//
+// 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_BUGPRONE_METHODHIDINGCHECK_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_METHODHIDINGCHECK_H
+
+#include "../ClangTidyCheck.h"
+
+namespace clang::tidy::bugprone {
+
+/// Checks that a derived class does not define the same (non virtual) method as
+/// a base class
+///
+/// This anti-pattern is a Liskov violation.
+///
+/// For the user-facing documentation see:
+/// http://clang.llvm.org/extra/clang-tidy/checks/bugprone/method-hiding.html
+class MethodHidingCheck : public ClangTidyCheck {
+public:
+ MethodHidingCheck(StringRef Name, ClangTidyContext *Context);
+ void registerMatchers(ast_matchers::MatchFinder *Finder) override;
+ void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+ bool isLanguageVersionSupported(const LangOptions &LangOpts) const override {
+ return LangOpts.CPlusPlus;
+ }
+};
+
+} // namespace clang::tidy::bugprone
+
+#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_METHODHIDINGCHECK_H
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst
index 388979d9577ba..4429580751067 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -1,6 +1,12 @@
.. If you want to modify sections/contents permanently, you should modify both
ReleaseNotes.rst and ReleaseNotesTemplate.txt.
+.. 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
+.. SPDX-FileCopyrightText: Portions Copyright 2025 Siemens and/or its affiliates
+.. May 2025 modified by Siemens and/or its affiliates by Tom James
+
====================================================
Extra Clang Tools |release| |ReleaseNotesTitle|
====================================================
@@ -131,6 +137,11 @@ New checks
Detects default initialization (to 0) of variables with ``enum`` type where
the enum has no enumerator with value of 0.
+- New :doc:`bugprone-method-hiding
+ <clang-tidy/checks/bugprone/method-hiding>` check.
+
+ Finds derived class methods that shadow a (non-virtual) base class method.
+
- New :doc:`llvm-mlir-op-builder
<clang-tidy/checks/llvm/use-new-mlir-op-builder>` check.
diff --git a/clang-tools-extra/docs/clang-tidy/checks/bugprone/method-hiding.rst b/clang-tools-extra/docs/clang-tidy/checks/bugprone/method-hiding.rst
new file mode 100644
index 0000000000000..dd58ec29e60c2
--- /dev/null
+++ b/clang-tools-extra/docs/clang-tidy/checks/bugprone/method-hiding.rst
@@ -0,0 +1,15 @@
+.. SPDX-FileCopyrightText: 2025 Siemens Corporation and/or its affiliates
+.. 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
+
+.. title:: clang-tidy - bugprone-method-hiding
+
+bugprone-method-hiding
+=========================
+
+Finds derived class methods that hide a (non-virtual) base class method.
+
+In order to be considered "hiding", methods must have the same signature
+(i.e. the same name, same number of parameters, same parameter types, etc).
+Only checks public, non-templated methods.
\ No newline at end of file
diff --git a/clang-tools-extra/docs/clang-tidy/checks/list.rst b/clang-tools-extra/docs/clang-tidy/checks/list.rst
index b0961265345c0..c2f305a0223f1 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ b/clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -1,3 +1,9 @@
+.. 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
+.. SPDX-FileCopyrightText: Portions Copyright 2025 Siemens and/or its affiliates
+.. May 2025 modified by Siemens and/or its affiliates by Tom James
+
.. title:: clang-tidy - Clang-Tidy Checks
Clang-Tidy Checks
@@ -110,6 +116,7 @@ Clang-Tidy Checks
:doc:`bugprone-lambda-function-name <bugprone/lambda-function-name>`,
:doc:`bugprone-macro-parentheses <bugprone/macro-parentheses>`, "Yes"
:doc:`bugprone-macro-repeated-side-effects <bugprone/macro-repeated-side-effects>`,
+ :doc:`bugprone-method-hiding <bugprone/method-shadowing>`
:doc:`bugprone-misleading-setter-of-reference <bugprone/misleading-setter-of-reference>`,
:doc:`bugprone-misplaced-operator-in-strlen-in-alloc <bugprone/misplaced-operator-in-strlen-in-alloc>`, "Yes"
:doc:`bugprone-misplaced-pointer-arithmetic-in-alloc <bugprone/misplaced-pointer-arithmetic-in-alloc>`, "Yes"
diff --git a/clang-tools-extra/test/clang-tidy/checkers/bugprone/method-hiding.cpp b/clang-tools-extra/test/clang-tidy/checkers/bugprone/method-hiding.cpp
new file mode 100644
index 0000000000000..38511c8807611
--- /dev/null
+++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone/method-hiding.cpp
@@ -0,0 +1,118 @@
+//===--- MethodHidingCheck.cpp - clang-tidy ----------------------------===//
+//
+// SPDX-FileCopyrightText: 2025 Siemens Corporation and/or its affiliates
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+// RUN: %check_clang_tidy %s bugprone-method-hiding %t
+
+
+class Base
+{
+ void method();
+ void methodWithArg(int I);
+
+ virtual Base* getThis() = 0;
+};
+
+class A : public Base
+{
+public:
+ void method();
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: 'A::method' hides same method in 'Base' [bugprone-method-hiding]
+};
+
+// only declaration should be checked
+void A::method()
+{
+}
+
+class B
+{
+public:
+ void method();
+};
+
+class D: public Base
+{
+
+};
+
+// test indirect inheritance
+class E : public D
+{
+public:
+ void method();
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: 'E::method' hides same method in 'Base' [bugprone-method-hiding]
+};
+
+class H : public Base
+{
+public:
+ Base* getThis() override;
+ Base const* getThis() const;
+};
+
+class I : public Base
+{
+public:
+ // test with inline implementation
+ void method()
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: 'I::method' hides same method in 'Base' [bugprone-method-hiding]
+ {
+
+ }
+};
+
+class J : public Base
+{
+public:
+ Base* getThis() final;
+};
+
+template<typename T>
+class TemplateBase
+{
+public:
+ virtual void size() const = 0;
+};
+
+template<typename T>
+class K : public TemplateBase<T>
+{
+public:
+ void size() const final;
+};
+
+class L : public Base
+{
+public:
+// not same signature (take const ref) but still ambiguous
+ void methodWithArg(int const& I);
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: 'L::methodWithArg' hides same method in 'Base' [bugprone-method-hiding]
+
+ void methodWithArg(int const I);
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: 'L::methodWithArg' hides same method in 'Base' [bugprone-method-hiding]
+
+ void methodWithArg(int *I);
+ void methodWithArg(int const* I);
+};
+
+class M : public Base
+{
+public:
+ static void method();
+};
+
+class N : public Base
+{
+public:
+ template<typename T>
+ void methodWithArg(T I);
+ // TODO: Templates are not handled yet
+ template<> void methodWithArg<int>(int I);
+};
|
|
✅ With the latest revision this PR passed the C/C++ code formatter. |
Co-authored-by: EugeneZelenko <eugene.zelenko@gmail.com>
Co-authored-by: EugeneZelenko <eugene.zelenko@gmail.com>
Co-authored-by: EugeneZelenko <eugene.zelenko@gmail.com>
24af8b5 to
e915796
Compare
|
The check name is a bit too vague/general, I would call it |
Agree, initially I was thinking about |
clang-tools-extra/docs/clang-tidy/checks/bugprone/method-hiding.rst
Outdated
Show resolved
Hide resolved
clang-tools-extra/clang-tidy/bugprone/DerivedMethodShadowingBaseMethodCheck.cpp
Outdated
Show resolved
Hide resolved
clang-tools-extra/clang-tidy/bugprone/DerivedMethodShadowingBaseMethodCheck.cpp
Outdated
Show resolved
Hide resolved
clang-tools-extra/clang-tidy/bugprone/DerivedMethodShadowingBaseMethodCheck.cpp
Outdated
Show resolved
Hide resolved
clang-tools-extra/clang-tidy/bugprone/DerivedMethodShadowingBaseMethodCheck.cpp
Outdated
Show resolved
Hide resolved
clang-tools-extra/clang-tidy/bugprone/DerivedMethodShadowingBaseMethodCheck.cpp
Outdated
Show resolved
Hide resolved
clang-tools-extra/test/clang-tidy/checkers/bugprone/derived-method-shadowing-base-method.cpp
Outdated
Show resolved
Hide resolved
clang-tools-extra/clang-tidy/bugprone/DerivedMethodShadowingBaseMethodCheck.cpp
Outdated
Show resolved
Hide resolved
clang-tools-extra/clang-tidy/bugprone/DerivedMethodShadowingBaseMethodCheck.cpp
Show resolved
Hide resolved
clang-tools-extra/test/clang-tidy/checkers/bugprone/derived-method-shadowing-base-method.cpp
Outdated
Show resolved
Hide resolved
clang-tools-extra/test/clang-tidy/checkers/bugprone/derived-method-shadowing-base-method.cpp
Show resolved
Hide resolved
…seMethodCheck.cpp Co-authored-by: Baranov Victor <bar.victor.2002@gmail.com>
vbvictor
left a comment
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
clang-tools-extra/clang-tidy/bugprone/DerivedMethodShadowingBaseMethodCheck.cpp
Outdated
Show resolved
Hide resolved
|
Thanks for all the reviews so far. @AaronBallman , @carlosgalvezp , @LegalizeAdulthood , @EugeneZelenko , @localspook , @HerrCai0907 , @PiotrZSL , I'm away on holiday next week (15th-19th Sept), and I'm hoping to merge this soon after I get back. If you have a chance to take a look before then, it would be much appeciated. |
HerrCai0907
left a comment
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.
|
@t-a-james Congratulations on having your first Pull Request (PR) merged into the LLVM Project! Your changes will be combined with recent changes from other authors, then tested by our build bots. If there is a problem with a build, you may receive a report in an email or a comment on this PR. Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues. How to do this, and the rest of the post-merge process, is covered in detail here. If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of LLVM development. You can fix your changes and open a new PR to merge them again. If you don't get any reports, no action is required from you. Your changes are working as expected, well done! |
|
LLVM Buildbot has detected a new failure on builder Full details are available at: https://lab.llvm.org/buildbot/#/builders/190/builds/27506 Here is the relevant piece of the build log for the reference |
|
CI failure looks unrelated |
This PR introduces a new bugprone check to find methods in derived classes that hide methods with the same signature in base classes.
The best description of what this new check does is the unit test code in
clang-tools-extra/test/clang-tidy/checkers/bugprone/method-hiding.cpp.