Skip to content

[clang-tidy] Add bugprone-smartptr-reset-ambiguous-call check #121291

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

Merged
merged 1 commit into from
Mar 11, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
//===--- AmbiguousSmartptrResetCallCheck.cpp - clang-tidy -----------------===//
//
// 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 "AmbiguousSmartptrResetCallCheck.h"
#include "../utils/OptionsUtils.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/Lex/Lexer.h"

using namespace clang::ast_matchers;

namespace clang::tidy::readability {

namespace {

AST_MATCHER(CXXMethodDecl, hasOnlyDefaultParameters) {
for (const auto *Param : Node.parameters()) {
if (!Param->hasDefaultArg())
return false;
}

return true;
}

const auto DefaultSmartPointers = "::std::shared_ptr;::std::unique_ptr;"
"::boost::shared_ptr";
} // namespace

AmbiguousSmartptrResetCallCheck::AmbiguousSmartptrResetCallCheck(
StringRef Name, ClangTidyContext *Context)
: ClangTidyCheck(Name, Context),
SmartPointers(utils::options::parseStringList(
Options.get("SmartPointers", DefaultSmartPointers))) {}

void AmbiguousSmartptrResetCallCheck::storeOptions(
ClangTidyOptions::OptionMap &Opts) {
Options.store(Opts, "SmartPointers",
utils::options::serializeStringList(SmartPointers));
}

void AmbiguousSmartptrResetCallCheck::registerMatchers(MatchFinder *Finder) {
const auto IsSmartptr = hasAnyName(SmartPointers);

const auto ResetMethod =
cxxMethodDecl(hasName("reset"), hasOnlyDefaultParameters());

const auto TypeWithReset =
anyOf(cxxRecordDecl(
anyOf(hasMethod(ResetMethod),
isDerivedFrom(cxxRecordDecl(hasMethod(ResetMethod))))),
classTemplateSpecializationDecl(
hasSpecializedTemplate(classTemplateDecl(has(ResetMethod)))));

const auto SmartptrWithReset = expr(hasType(hasUnqualifiedDesugaredType(
recordType(hasDeclaration(classTemplateSpecializationDecl(
IsSmartptr,
hasTemplateArgument(
0, templateArgument(refersToType(hasUnqualifiedDesugaredType(
recordType(hasDeclaration(TypeWithReset))))))))))));

Finder->addMatcher(
cxxMemberCallExpr(
callee(ResetMethod),
unless(hasAnyArgument(expr(unless(cxxDefaultArgExpr())))),
anyOf(on(cxxOperatorCallExpr(hasOverloadedOperatorName("->"),
hasArgument(0, SmartptrWithReset))
.bind("ArrowOp")),
on(SmartptrWithReset)))
.bind("MemberCall"),
this);
}

void AmbiguousSmartptrResetCallCheck::check(
const MatchFinder::MatchResult &Result) {
const auto *MemberCall =
Result.Nodes.getNodeAs<CXXMemberCallExpr>("MemberCall");
assert(MemberCall);

if (const auto *Arrow =
Result.Nodes.getNodeAs<CXXOperatorCallExpr>("ArrowOp")) {
const CharSourceRange SmartptrSourceRange =
Lexer::getAsCharRange(Arrow->getArg(0)->getSourceRange(),
*Result.SourceManager, getLangOpts());

diag(MemberCall->getBeginLoc(),
"ambiguous call to 'reset()' on a pointee of a smart pointer, prefer "
"more explicit approach");

diag(MemberCall->getBeginLoc(),
"consider dereferencing smart pointer to call 'reset' method "
"of the pointee here",
DiagnosticIDs::Note)
<< FixItHint::CreateInsertion(SmartptrSourceRange.getBegin(), "(*")
<< FixItHint::CreateInsertion(SmartptrSourceRange.getEnd(), ")")
<< FixItHint::CreateReplacement(
CharSourceRange::getCharRange(
Arrow->getOperatorLoc(),
Arrow->getOperatorLoc().getLocWithOffset(2)),
".");
} else {
const auto *Member = cast<MemberExpr>(MemberCall->getCallee());
assert(Member);

diag(MemberCall->getBeginLoc(),
"ambiguous call to 'reset()' on a smart pointer with pointee that "
"also has a 'reset()' method, prefer more explicit approach");

diag(MemberCall->getBeginLoc(),
"consider assigning the pointer to 'nullptr' here",
DiagnosticIDs::Note)
<< FixItHint::CreateReplacement(
SourceRange(Member->getOperatorLoc(), Member->getOperatorLoc()),
" =")
<< FixItHint::CreateReplacement(
SourceRange(Member->getMemberLoc(), MemberCall->getEndLoc()),
" nullptr");
}
}

} // namespace clang::tidy::readability
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
//===--- AmbiguousSmartptrResetCallCheck.h - clang-tidy ---------*- C++ -*-===//
//
// 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_AMBIGUOUSSMARTPTRRESETCALLCHECK_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_READABILITY_AMBIGUOUSSMARTPTRRESETCALLCHECK_H

#include "../ClangTidyCheck.h"

namespace clang::tidy::readability {

/// Finds potentially erroneous calls to 'reset' method on smart pointers when
/// the pointee type also has a 'reset' method
///
/// For the user-facing documentation see:
/// http://clang.llvm.org/extra/clang-tidy/checks/readability/ambiguous-smartptr-reset-call.html
class AmbiguousSmartptrResetCallCheck : public ClangTidyCheck {
public:
AmbiguousSmartptrResetCallCheck(StringRef Name, ClangTidyContext *Context);
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
void storeOptions(ClangTidyOptions::OptionMap &Opts) override;
bool isLanguageVersionSupported(const LangOptions &LangOpts) const override {
return LangOpts.CPlusPlus;
}

private:
const std::vector<StringRef> SmartPointers;
};

} // namespace clang::tidy::readability

#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_READABILITY_AMBIGUOUSSMARTPTRRESETCALLCHECK_H
1 change: 1 addition & 0 deletions clang-tools-extra/clang-tidy/readability/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ set(LLVM_LINK_COMPONENTS
)

add_clang_library(clangTidyReadabilityModule STATIC
AmbiguousSmartptrResetCallCheck.cpp
AvoidConstParamsInDecls.cpp
AvoidNestedConditionalOperatorCheck.cpp
AvoidReturnWithVoidValueCheck.cpp
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
#include "../ClangTidy.h"
#include "../ClangTidyModule.h"
#include "../ClangTidyModuleRegistry.h"
#include "AmbiguousSmartptrResetCallCheck.h"
#include "AvoidConstParamsInDecls.h"
#include "AvoidNestedConditionalOperatorCheck.h"
#include "AvoidReturnWithVoidValueCheck.h"
Expand Down Expand Up @@ -68,6 +69,8 @@ namespace readability {
class ReadabilityModule : public ClangTidyModule {
public:
void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override {
CheckFactories.registerCheck<AmbiguousSmartptrResetCallCheck>(
"readability-ambiguous-smartptr-reset-call");
CheckFactories.registerCheck<AvoidConstParamsInDecls>(
"readability-avoid-const-params-in-decls");
CheckFactories.registerCheck<AvoidNestedConditionalOperatorCheck>(
Expand Down
6 changes: 6 additions & 0 deletions clang-tools-extra/docs/ReleaseNotes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,12 @@ New checks
Finds unintended character output from ``unsigned char`` and ``signed char`` to an
``ostream``.

- New :doc:`readability-ambiguous-smartptr-reset-call
<clang-tidy/checks/readability/ambiguous-smartptr-reset-call>` check.

Finds potentially erroneous calls to ``reset`` method on smart pointers when
the pointee type also has a ``reset`` method.

New check aliases
^^^^^^^^^^^^^^^^^

Expand Down
1 change: 1 addition & 0 deletions clang-tools-extra/docs/clang-tidy/checks/list.rst
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,7 @@ Clang-Tidy Checks
:doc:`portability-simd-intrinsics <portability/simd-intrinsics>`,
:doc:`portability-std-allocator-const <portability/std-allocator-const>`,
:doc:`portability-template-virtual-member-function <portability/template-virtual-member-function>`,
:doc:`readability-ambiguous-smartptr-reset-call <readability/ambiguous-smartptr-reset-call>`, "Yes"
:doc:`readability-avoid-const-params-in-decls <readability/avoid-const-params-in-decls>`, "Yes"
:doc:`readability-avoid-nested-conditional-operator <readability/avoid-nested-conditional-operator>`,
:doc:`readability-avoid-return-with-void-value <readability/avoid-return-with-void-value>`, "Yes"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
.. title:: clang-tidy - readability-ambiguous-smartptr-reset-call

readability-ambiguous-smartptr-reset-call
=========================================

Finds potentially erroneous calls to ``reset`` method on smart pointers when
the pointee type also has a ``reset`` method. Having a ``reset`` method in
both classes makes it easy to accidentally make the pointer null when
intending to reset the underlying object.

.. code-block:: c++

struct Resettable {
void reset() { /* Own reset logic */ }
};

auto ptr = std::make_unique<Resettable>();

ptr->reset(); // Calls underlying reset method
ptr.reset(); // Makes the pointer null

Both calls are valid C++ code, but the second one might not be what the
developer intended, as it destroys the pointed-to object rather than resetting
its state. It's easy to make such a typo because the difference between
``.`` and ``->`` is really small.

The recommended approach is to make the intent explicit by using either member
access or direct assignment:

.. code-block:: c++

std::unique_ptr<Resettable> ptr = std::make_unique<Resettable>();

(*ptr).reset(); // Clearly calls underlying reset method
ptr = nullptr; // Clearly makes the pointer null

The default smart pointers and classes that are considered are
``std::unique_ptr``, ``std::shared_ptr``, ``boost::shared_ptr``. To specify
other smart pointers or other classes use the :option:`SmartPointers` option.


.. note::

The check may emit invalid fix-its and misleading warning messages when
specifying custom smart pointers or other classes in the
:option:`SmartPointers` option. For example, ``boost::scoped_ptr`` does not
have an ``operator=`` which makes fix-its invalid.

.. note::

Automatic fix-its are enabled only if :program:`clang-tidy` is invoked with
the `--fix-notes` option.


Options
-------

.. option:: SmartPointers

Semicolon-separated list of fully qualified class names of custom smart
pointers. Default value is `::std::unique_ptr;::std::shared_ptr;
::boost::shared_ptr`.
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// RUN: %check_clang_tidy %s readability-ambiguous-smartptr-reset-call %t -- \
// RUN: -config='{CheckOptions: \
// RUN: {readability-ambiguous-smartptr-reset-call.SmartPointers: "::std::unique_ptr;::other_ptr"}}' \
// RUN: --fix-notes -- -I %S/../modernize/Inputs/smart-ptr

#include "unique_ptr.h"
#include "shared_ptr.h"

template <typename T>
struct other_ptr {
T& operator*() const;
T* operator->() const;
void reset();
};

struct Resettable {
void reset();
void doSomething();
};

void Positive() {
std::unique_ptr<Resettable> u;
u.reset();
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: ambiguous call to 'reset()' on a smart pointer with pointee that also has a 'reset()' method, prefer more explicit approach
// CHECK-MESSAGES: :[[@LINE-2]]:3: note: consider assigning the pointer to 'nullptr' here
// CHECK-FIXES: u = nullptr;
u->reset();
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: ambiguous call to 'reset()' on a pointee of a smart pointer, prefer more explicit approach
// CHECK-MESSAGES: :[[@LINE-2]]:3: note: consider dereferencing smart pointer to call 'reset' method of the pointee here
// CHECK-FIXES: (*u).reset();

other_ptr<Resettable> s;
s.reset();
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: ambiguous call to 'reset()' on a smart pointer with pointee that also has a 'reset()' method, prefer more explicit approach
// CHECK-MESSAGES: :[[@LINE-2]]:3: note: consider assigning the pointer to 'nullptr' here
// CHECK-FIXES: s = nullptr;
s->reset();
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: ambiguous call to 'reset()' on a pointee of a smart pointer, prefer more explicit approach
// CHECK-MESSAGES: :[[@LINE-2]]:3: note: consider dereferencing smart pointer to call 'reset' method of the pointee here
// CHECK-FIXES: (*s).reset();
}

void Negative() {
std::shared_ptr<Resettable> s_ptr;
s_ptr.reset();
s_ptr->reset();
s_ptr->doSomething();

std::unique_ptr<Resettable> u_ptr;
u_ptr.reset(nullptr);
u_ptr->doSomething();
}
Loading