-
Notifications
You must be signed in to change notification settings - Fork 13.7k
[clang-tidy] Create bugprone-incorrect-enable-shared-from-this check #102299
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
PiotrZSL
merged 35 commits into
llvm:main
from
MichelleCDjunaidi:clang-tidy-create-bugprone-public-enable-shared-from-this
Jan 12, 2025
Merged
Changes from all commits
Commits
Show all changes
35 commits
Select commit
Hold shift + click to select a range
062fcab
[clang-tidy] Add bugprone-public-enable-shared-from-this check
MichelleCDjunaidi acf73fd
Fix test to be compatible with llvm-lit, add docs
MichelleCDjunaidi 52186f8
Change name to bugprone-incorrect-enable-shared-from-this.
MichelleCDjunaidi 2f05bbc
Fix ``FixItHint`` of public inheritance, implement ``std::`` check
MichelleCDjunaidi 772a8eb
Stated type instead of using auto in the ``check`` method
MichelleCDjunaidi 7aa9232
Refactored const variables and cleanup newlines/formatting
MichelleCDjunaidi 47a6f64
Fix documentation, comments, newlines, sort module registration properly
MichelleCDjunaidi 65eb824
Switch implementation to RecursiveASTVisitor
MichelleCDjunaidi a61eff9
Fix test case formatting
MichelleCDjunaidi 5d489b8
Fix check code formatting to follow LLVM style
MichelleCDjunaidi 9bbc97b
Optimize traversal, add alias and typedef testing, remove missing std…
MichelleCDjunaidi 3f84574
refactor: simplify to VisitCXXRecordDecl only instead of TraverseCXXR…
MichelleCDjunaidi 7f964ee
refactor: exclude non-definitions from repeated processing
MichelleCDjunaidi c7d8559
more detailed diag for classes with bases from EnableSharedClassSet
MichelleCDjunaidi 5849a10
refactor to use diag %select, fix docs typo
MichelleCDjunaidi 15b381a
add space to code block in docs
MichelleCDjunaidi b95ad5d
update test CHECK-MESSAGES to check for class name
MichelleCDjunaidi 05017de
[NFC] in progress change diag
MichelleCDjunaidi a2c5cff
add macros to test file and revise CHECK-MESSAGES
MichelleCDjunaidi fd044a2
change auto vars to explicit typing
MichelleCDjunaidi 10c1933
update docs to fix wording
MichelleCDjunaidi ff2d2ef
change to matcher-based check and cleanup headers
MichelleCDjunaidi 415fb12
synchronize check documentation wording
MichelleCDjunaidi 9e7689b
sort ReleaseNotes.rst new checks by alphabetical
MichelleCDjunaidi 3978355
Change fix to emit only on direct inheritance
MichelleCDjunaidi ebffebb
reworded first sentence of docs
MichelleCDjunaidi b38109c
additional macro testing
MichelleCDjunaidi f915a0c
refactor add newline on eof of test file
MichelleCDjunaidi 93fa16c
refactor to only replace access specifier
MichelleCDjunaidi fb1b306
refactor to remove duplicated arg
MichelleCDjunaidi 1567de5
Merge remote-tracking branch 'origin/main' into HEAD
MichelleCDjunaidi a10c4e1
Merge branch 'main' into clang-tidy-create-bugprone-public-enable-sha…
MichelleCDjunaidi a09955d
Merge branch 'main' into clang-tidy-create-bugprone-public-enable-sha…
MichelleCDjunaidi 33c1cad
Merge remote-tracking branch 'origin/main' into clang-tidy-create-bug…
MichelleCDjunaidi d8f9563
exclude system header and update test flag
MichelleCDjunaidi 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
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
65 changes: 65 additions & 0 deletions
65
clang-tools-extra/clang-tidy/bugprone/IncorrectEnableSharedFromThisCheck.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,65 @@ | ||
//===--- IncorrectEnableSharedFromThisCheck.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 "IncorrectEnableSharedFromThisCheck.h" | ||
#include "clang/AST/ASTContext.h" | ||
#include "clang/AST/DeclCXX.h" | ||
#include "clang/ASTMatchers/ASTMatchFinder.h" | ||
|
||
using namespace clang::ast_matchers; | ||
|
||
namespace clang::tidy::bugprone { | ||
|
||
void IncorrectEnableSharedFromThisCheck::registerMatchers(MatchFinder *Finder) { | ||
const auto EnableSharedFromThis = | ||
cxxRecordDecl(hasName("enable_shared_from_this"), isInStdNamespace()); | ||
const auto QType = hasCanonicalType(hasDeclaration( | ||
cxxRecordDecl( | ||
anyOf(EnableSharedFromThis.bind("enable_rec"), | ||
cxxRecordDecl(hasAnyBase(cxxBaseSpecifier( | ||
isPublic(), hasType(hasCanonicalType( | ||
hasDeclaration(EnableSharedFromThis)))))))) | ||
.bind("base_rec"))); | ||
Finder->addMatcher( | ||
cxxRecordDecl( | ||
unless(isExpansionInSystemHeader()), | ||
hasDirectBase(cxxBaseSpecifier(unless(isPublic()), hasType(QType)) | ||
.bind("base"))) | ||
.bind("derived"), | ||
this); | ||
} | ||
|
||
void IncorrectEnableSharedFromThisCheck::check( | ||
const MatchFinder::MatchResult &Result) { | ||
const auto *BaseSpec = Result.Nodes.getNodeAs<CXXBaseSpecifier>("base"); | ||
const auto *Base = Result.Nodes.getNodeAs<CXXRecordDecl>("base_rec"); | ||
const auto *Derived = Result.Nodes.getNodeAs<CXXRecordDecl>("derived"); | ||
const bool IsEnableSharedFromThisDirectBase = | ||
Result.Nodes.getNodeAs<CXXRecordDecl>("enable_rec") == Base; | ||
const bool HasWrittenAccessSpecifier = | ||
BaseSpec->getAccessSpecifierAsWritten() != AS_none; | ||
const auto ReplacementRange = CharSourceRange( | ||
SourceRange(BaseSpec->getBeginLoc()), HasWrittenAccessSpecifier); | ||
const llvm::StringRef Replacement = | ||
HasWrittenAccessSpecifier ? "public" : "public "; | ||
const FixItHint Hint = | ||
IsEnableSharedFromThisDirectBase | ||
? FixItHint::CreateReplacement(ReplacementRange, Replacement) | ||
: FixItHint(); | ||
diag(Derived->getLocation(), | ||
"%2 is not publicly inheriting from " | ||
"%select{%1 which inherits from |}0'std::enable_shared_" | ||
"from_this', " | ||
"which will cause unintended behaviour " | ||
"when using 'shared_from_this'; make the inheritance " | ||
"public", | ||
DiagnosticIDs::Warning) | ||
<< IsEnableSharedFromThisDirectBase << Base << Derived << Hint; | ||
} | ||
|
||
} // namespace clang::tidy::bugprone | ||
MichelleCDjunaidi marked this conversation as resolved.
Show resolved
Hide resolved
|
35 changes: 35 additions & 0 deletions
35
clang-tools-extra/clang-tidy/bugprone/IncorrectEnableSharedFromThisCheck.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,35 @@ | ||
//===--- IncorrectEnableSharedFromThisCheck.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_BUGPRONE_INCORRECTENABLESHAREDFROMTHISCHECK_H | ||
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_INCORRECTENABLESHAREDFROMTHISCHECK_H | ||
|
||
#include "../ClangTidyCheck.h" | ||
|
||
namespace clang::tidy::bugprone { | ||
|
||
/// Detect classes or structs that do not publicly inherit from | ||
/// ``std::enable_shared_from_this``, because unintended behavior will | ||
/// otherwise occur when calling ``shared_from_this``. | ||
/// | ||
/// For the user-facing documentation see: | ||
/// http://clang.llvm.org/extra/clang-tidy/checks/bugprone/incorrect-enable-shared-from-this.html | ||
class IncorrectEnableSharedFromThisCheck : public ClangTidyCheck { | ||
public: | ||
IncorrectEnableSharedFromThisCheck(StringRef Name, ClangTidyContext *Context) | ||
: ClangTidyCheck(Name, 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.CPlusPlus11; | ||
} | ||
}; | ||
|
||
} // namespace clang::tidy::bugprone | ||
|
||
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_INCORRECTENABLESHAREDFROMTHISCHECK_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
34 changes: 34 additions & 0 deletions
34
...ols-extra/docs/clang-tidy/checks/bugprone/incorrect-enable-shared-from-this.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,34 @@ | ||
.. title:: clang-tidy - bugprone-incorrect-enable-shared-from-this | ||
|
||
bugprone-incorrect-enable-shared-from-this | ||
========================================== | ||
|
||
Detect classes or structs that do not publicly inherit from | ||
``std::enable_shared_from_this``, because unintended behavior will | ||
MichelleCDjunaidi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
otherwise occur when calling ``shared_from_this``. | ||
|
||
Consider the following code: | ||
MichelleCDjunaidi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
.. code-block:: c++ | ||
|
||
#include <memory> | ||
|
||
// private inheritance | ||
class BadExample : std::enable_shared_from_this<BadExample> { | ||
|
||
// ``shared_from_this``` unintended behaviour | ||
// `libstdc++` implementation returns uninitialized ``weak_ptr`` | ||
public: | ||
BadExample* foo() { return shared_from_this().get(); } | ||
void bar() { return; } | ||
}; | ||
|
||
void using_not_public() { | ||
auto bad_example = std::make_shared<BadExample>(); | ||
auto* b_ex = bad_example->foo(); | ||
b_ex->bar(); | ||
} | ||
|
||
Using `libstdc++` implementation, ``shared_from_this`` will throw | ||
``std::bad_weak_ptr``. When ``using_not_public()`` is called, this code will | ||
crash without exception handling. |
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
Oops, something went wrong.
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.