-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Added the [unnecessary_box_returns]
lint
#9102
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
Show all changes
4 commits
Select commit
Hold shift + click to select a range
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,120 @@ | ||
use clippy_utils::diagnostics::span_lint_and_then; | ||
use rustc_errors::Applicability; | ||
use rustc_hir::{def_id::LocalDefId, FnDecl, FnRetTy, ImplItemKind, Item, ItemKind, Node, TraitItem, TraitItemKind}; | ||
use rustc_lint::{LateContext, LateLintPass}; | ||
use rustc_session::{declare_tool_lint, impl_lint_pass}; | ||
use rustc_span::Symbol; | ||
|
||
declare_clippy_lint! { | ||
/// ### What it does | ||
/// | ||
/// Checks for a return type containing a `Box<T>` where `T` implements `Sized` | ||
/// | ||
/// ### Why is this bad? | ||
/// | ||
/// It's better to just return `T` in these cases. The caller may not need | ||
/// the value to be boxed, and it's expensive to free the memory once the | ||
/// `Box<T>` been dropped. | ||
/// | ||
/// ### Example | ||
/// ```rust | ||
/// fn foo() -> Box<String> { | ||
/// Box::new(String::from("Hello, world!")) | ||
/// } | ||
/// ``` | ||
/// Use instead: | ||
/// ```rust | ||
/// fn foo() -> String { | ||
/// String::from("Hello, world!") | ||
/// } | ||
/// ``` | ||
#[clippy::version = "1.70.0"] | ||
pub UNNECESSARY_BOX_RETURNS, | ||
pedantic, | ||
"Needlessly returning a Box" | ||
} | ||
|
||
pub struct UnnecessaryBoxReturns { | ||
avoid_breaking_exported_api: bool, | ||
} | ||
|
||
impl_lint_pass!(UnnecessaryBoxReturns => [UNNECESSARY_BOX_RETURNS]); | ||
|
||
impl UnnecessaryBoxReturns { | ||
pub fn new(avoid_breaking_exported_api: bool) -> Self { | ||
Self { | ||
avoid_breaking_exported_api, | ||
} | ||
} | ||
|
||
fn check_fn_item(&mut self, cx: &LateContext<'_>, decl: &FnDecl<'_>, def_id: LocalDefId, name: Symbol) { | ||
// we don't want to tell someone to break an exported function if they ask us not to | ||
if self.avoid_breaking_exported_api && cx.effective_visibilities.is_exported(def_id) { | ||
xFrednet marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return; | ||
} | ||
|
||
// functions which contain the word "box" are exempt from this lint | ||
if name.as_str().contains("box") { | ||
return; | ||
} | ||
|
||
let FnRetTy::Return(return_ty_hir) = &decl.output else { return }; | ||
|
||
let return_ty = cx | ||
.tcx | ||
.erase_late_bound_regions(cx.tcx.fn_sig(def_id).skip_binder()) | ||
.output(); | ||
|
||
if !return_ty.is_box() { | ||
xFrednet marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return; | ||
} | ||
|
||
let boxed_ty = return_ty.boxed_ty(); | ||
|
||
// it's sometimes useful to return Box<T> if T is unsized, so don't lint those | ||
if boxed_ty.is_sized(cx.tcx, cx.param_env) { | ||
span_lint_and_then( | ||
cx, | ||
UNNECESSARY_BOX_RETURNS, | ||
return_ty_hir.span, | ||
format!("boxed return of the sized type `{boxed_ty}`").as_str(), | ||
|diagnostic| { | ||
diagnostic.span_suggestion( | ||
return_ty_hir.span, | ||
"try", | ||
boxed_ty.to_string(), | ||
// the return value and function callers also needs to | ||
// be changed, so this can't be MachineApplicable | ||
Applicability::Unspecified, | ||
); | ||
diagnostic.help("changing this also requires a change to the return expressions in this function"); | ||
}, | ||
); | ||
} | ||
} | ||
} | ||
|
||
impl LateLintPass<'_> for UnnecessaryBoxReturns { | ||
fn check_trait_item(&mut self, cx: &LateContext<'_>, item: &TraitItem<'_>) { | ||
let TraitItemKind::Fn(signature, _) = &item.kind else { return }; | ||
self.check_fn_item(cx, signature.decl, item.owner_id.def_id, item.ident.name); | ||
} | ||
|
||
fn check_impl_item(&mut self, cx: &LateContext<'_>, item: &rustc_hir::ImplItem<'_>) { | ||
// Ignore implementations of traits, because the lint should be on the | ||
// trait, not on the implmentation of it. | ||
let Node::Item(parent) = cx.tcx.hir().get_parent(item.hir_id()) else { return }; | ||
let ItemKind::Impl(parent) = parent.kind else { return }; | ||
if parent.of_trait.is_some() { | ||
return; | ||
} | ||
|
||
let ImplItemKind::Fn(signature, ..) = &item.kind else { return }; | ||
self.check_fn_item(cx, signature.decl, item.owner_id.def_id, item.ident.name); | ||
} | ||
|
||
fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) { | ||
let ItemKind::Fn(signature, ..) = &item.kind else { return }; | ||
self.check_fn_item(cx, signature.decl, item.owner_id.def_id, item.ident.name); | ||
} | ||
} |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
#![warn(clippy::unnecessary_box_returns)] | ||
|
||
trait Bar { | ||
// lint | ||
fn baz(&self) -> Box<usize>; | ||
} | ||
|
||
pub struct Foo {} | ||
|
||
impl Bar for Foo { | ||
// don't lint: this is a problem with the trait, not the implementation | ||
fn baz(&self) -> Box<usize> { | ||
Box::new(42) | ||
} | ||
} | ||
|
||
impl Foo { | ||
fn baz(&self) -> Box<usize> { | ||
// lint | ||
Box::new(13) | ||
} | ||
} | ||
|
||
// lint | ||
fn bxed_usize() -> Box<usize> { | ||
Box::new(5) | ||
} | ||
|
||
// lint | ||
fn _bxed_foo() -> Box<Foo> { | ||
Box::new(Foo {}) | ||
} | ||
|
||
// don't lint: this is exported | ||
pub fn bxed_foo() -> Box<Foo> { | ||
Box::new(Foo {}) | ||
} | ||
|
||
// don't lint: str is unsized | ||
fn bxed_str() -> Box<str> { | ||
"Hello, world!".to_string().into_boxed_str() | ||
} | ||
|
||
// don't lint: function contains the word, "box" | ||
fn boxed_usize() -> Box<usize> { | ||
Box::new(7) | ||
} | ||
|
||
// don't lint: this has an unspecified return type | ||
fn default() {} | ||
|
||
// don't lint: this doesn't return a Box | ||
fn string() -> String { | ||
String::from("Hello, world") | ||
} | ||
|
||
fn main() { | ||
// don't lint: this is a closure | ||
let a = || -> Box<usize> { Box::new(5) }; | ||
} |
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 @@ | ||
error: boxed return of the sized type `usize` | ||
--> $DIR/unnecessary_box_returns.rs:5:22 | ||
| | ||
LL | fn baz(&self) -> Box<usize>; | ||
| ^^^^^^^^^^ help: try: `usize` | ||
| | ||
= help: changing this also requires a change to the return expressions in this function | ||
= note: `-D clippy::unnecessary-box-returns` implied by `-D warnings` | ||
|
||
error: boxed return of the sized type `usize` | ||
--> $DIR/unnecessary_box_returns.rs:18:22 | ||
| | ||
LL | fn baz(&self) -> Box<usize> { | ||
| ^^^^^^^^^^ help: try: `usize` | ||
| | ||
= help: changing this also requires a change to the return expressions in this function | ||
|
||
error: boxed return of the sized type `usize` | ||
--> $DIR/unnecessary_box_returns.rs:25:20 | ||
| | ||
LL | fn bxed_usize() -> Box<usize> { | ||
| ^^^^^^^^^^ help: try: `usize` | ||
| | ||
= help: changing this also requires a change to the return expressions in this function | ||
|
||
error: boxed return of the sized type `Foo` | ||
--> $DIR/unnecessary_box_returns.rs:30:19 | ||
| | ||
LL | fn _bxed_foo() -> Box<Foo> { | ||
| ^^^^^^^^ help: try: `Foo` | ||
| | ||
= help: changing this also requires a change to the return expressions in this function | ||
|
||
error: aborting due to 4 previous errors | ||
|
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.