-
Notifications
You must be signed in to change notification settings - Fork 13.9k
[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
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
126 changes: 126 additions & 0 deletions
126
clang-tools-extra/clang-tidy/readability/AmbiguousSmartptrResetCallCheck.cpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
37 changes: 37 additions & 0 deletions
37
clang-tools-extra/clang-tidy/readability/AmbiguousSmartptrResetCallCheck.h
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
62 changes: 62 additions & 0 deletions
62
...ools-extra/docs/clang-tidy/checks/readability/ambiguous-smartptr-reset-call.rst
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. | ||
|
||
|
||
vbvictor marked this conversation as resolved.
Show resolved
Hide resolved
|
||
.. 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; | ||
vbvictor marked this conversation as resolved.
Show resolved
Hide resolved
|
||
::boost::shared_ptr`. | ||
PiotrZSL marked this conversation as resolved.
Show resolved
Hide resolved
|
52 changes: 52 additions & 0 deletions
52
...ra/test/clang-tidy/checkers/readability/ambiguous-smartptr-reset-call-custom-pointers.cpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.