Skip to content

Commit 022f76d

Browse files
committed
Added the new lint with some docs and tests
1 parent 5ed64d4 commit 022f76d

File tree

6 files changed

+142
-0
lines changed

6 files changed

+142
-0
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -4974,6 +4974,7 @@ Released 2018-09-13
49744974
[`unit_hash`]: https://rust-lang.github.io/rust-clippy/master/index.html#unit_hash
49754975
[`unit_return_expecting_ord`]: https://rust-lang.github.io/rust-clippy/master/index.html#unit_return_expecting_ord
49764976
[`unknown_clippy_lints`]: https://rust-lang.github.io/rust-clippy/master/index.html#unknown_clippy_lints
4977+
[`unnecessary_box_returns`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_box_returns
49774978
[`unnecessary_cast`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_cast
49784979
[`unnecessary_filter_map`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_filter_map
49794980
[`unnecessary_find_map`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_find_map

clippy_lints/src/declared_lints.rs

+1
Original file line numberDiff line numberDiff line change
@@ -616,6 +616,7 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[
616616
crate::unit_types::UNIT_CMP_INFO,
617617
crate::unnamed_address::FN_ADDRESS_COMPARISONS_INFO,
618618
crate::unnamed_address::VTABLE_ADDRESS_COMPARISONS_INFO,
619+
crate::unnecessary_box_returns::UNNECESSARY_BOX_RETURNS_INFO,
619620
crate::unnecessary_owned_empty_strings::UNNECESSARY_OWNED_EMPTY_STRINGS_INFO,
620621
crate::unnecessary_self_imports::UNNECESSARY_SELF_IMPORTS_INFO,
621622
crate::unnecessary_struct_initialization::UNNECESSARY_STRUCT_INITIALIZATION_INFO,

clippy_lints/src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,7 @@ mod uninit_vec;
300300
mod unit_return_expecting_ord;
301301
mod unit_types;
302302
mod unnamed_address;
303+
mod unnecessary_box_returns;
303304
mod unnecessary_owned_empty_strings;
304305
mod unnecessary_self_imports;
305306
mod unnecessary_struct_initialization;
@@ -940,6 +941,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
940941
store.register_late_pass(|_| Box::new(allow_attributes::AllowAttribute));
941942
store.register_late_pass(move |_| Box::new(manual_main_separator_str::ManualMainSeparatorStr::new(msrv())));
942943
store.register_late_pass(|_| Box::new(unnecessary_struct_initialization::UnnecessaryStruct));
944+
store.register_late_pass(|_| Box::new(unnecessary_box_returns::UnnecessaryBoxReturns));
943945
// add lints here, do not remove this comment, it's used in `new_lint`
944946
}
945947

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
use clippy_utils::diagnostics::span_lint_and_then;
2+
use rustc_errors::Applicability;
3+
use rustc_hir::{def_id::LocalDefId, intravisit::FnKind, Body, FnDecl, FnRetTy};
4+
use rustc_lint::{LateContext, LateLintPass};
5+
use rustc_session::{declare_lint_pass, declare_tool_lint};
6+
use rustc_span::Span;
7+
8+
declare_clippy_lint! {
9+
/// ### What it does
10+
///
11+
/// Checks for a return type containing a `Box<T>` where `T` implements `Sized`
12+
///
13+
/// ### Why is this bad?
14+
///
15+
/// It's better to just return `T` in these cases. The caller may not need
16+
/// the value to be boxed, and it's expensive to free the memory once the
17+
/// `Box<T>` been dropped.
18+
///
19+
/// ### Example
20+
/// ```rust
21+
/// fn foo() -> Box<String> {
22+
/// Box::new(String::from("Hello, world!"))
23+
/// }
24+
/// ```
25+
/// Use instead:
26+
/// ```rust
27+
/// fn foo() -> String {
28+
/// String::from("Hello, world!")
29+
/// }
30+
/// ```
31+
#[clippy::version = "1.70.0"]
32+
pub UNNECESSARY_BOX_RETURNS,
33+
pedantic,
34+
"Needlessly returning a Box"
35+
}
36+
declare_lint_pass!(UnnecessaryBoxReturns => [UNNECESSARY_BOX_RETURNS]);
37+
38+
impl LateLintPass<'_> for UnnecessaryBoxReturns {
39+
fn check_fn(
40+
&mut self,
41+
cx: &LateContext<'_>,
42+
fn_kind: FnKind<'_>,
43+
decl: &FnDecl<'_>,
44+
_: &Body<'_>,
45+
_: Span,
46+
def_id: LocalDefId,
47+
) {
48+
// it's unclear what part of a closure you would span, so for now it's ignored
49+
// if this is changed, please also make sure not to call `hir_ty_to_ty` below
50+
if matches!(fn_kind, FnKind::Closure) {
51+
return;
52+
}
53+
54+
let FnRetTy::Return(return_ty_hir) = &decl.output else { return };
55+
56+
let return_ty = cx
57+
.tcx
58+
.erase_late_bound_regions(cx.tcx.fn_sig(def_id).skip_binder())
59+
.output();
60+
61+
if !return_ty.is_box() {
62+
return;
63+
}
64+
65+
let boxed_ty = return_ty.boxed_ty();
66+
67+
// it's sometimes useful to return Box<T> if T is unsized, so don't lint those
68+
if boxed_ty.is_sized(cx.tcx, cx.param_env) {
69+
span_lint_and_then(
70+
cx,
71+
UNNECESSARY_BOX_RETURNS,
72+
return_ty_hir.span,
73+
format!("boxed return of the sized type `{boxed_ty}`").as_str(),
74+
|diagnostic| {
75+
diagnostic.span_suggestion(
76+
return_ty_hir.span,
77+
"try",
78+
boxed_ty.to_string(),
79+
// the return value and function callers also needs to
80+
// be changed, so this can't be MachineApplicable
81+
Applicability::Unspecified,
82+
);
83+
diagnostic.help("changing this also requires a change to the return expressions in this function");
84+
},
85+
);
86+
}
87+
}
88+
}

tests/ui/unnecessary_box_returns.rs

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#![warn(clippy::unnecessary_box_returns)]
2+
3+
struct Foo {}
4+
5+
// lint
6+
fn boxed_usize() -> Box<usize> {
7+
Box::new(5)
8+
}
9+
10+
// lint
11+
fn boxed_foo() -> Box<Foo> {
12+
Box::new(Foo {})
13+
}
14+
15+
// don't lint: str is unsized
16+
fn boxed_str() -> Box<str> {
17+
"Hello, world!".to_string().into_boxed_str()
18+
}
19+
20+
// don't lint: this has an unspecified return type
21+
fn default() {}
22+
23+
// don't lint: this doesn't return a Box
24+
fn string() -> String {
25+
String::from("Hello, world")
26+
}
27+
28+
fn main() {
29+
// don't lint: this is a closure
30+
let a = || -> Box<usize> { Box::new(5) };
31+
}
+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
error: boxed return of the sized type `usize`
2+
--> $DIR/unnecessary_box_returns.rs:6:21
3+
|
4+
LL | fn boxed_usize() -> Box<usize> {
5+
| ^^^^^^^^^^ help: try: `usize`
6+
|
7+
= help: changing this also requires a change to the return expressions in this function
8+
= note: `-D clippy::unnecessary-box-returns` implied by `-D warnings`
9+
10+
error: boxed return of the sized type `Foo`
11+
--> $DIR/unnecessary_box_returns.rs:11:19
12+
|
13+
LL | fn boxed_foo() -> Box<Foo> {
14+
| ^^^^^^^^ help: try: `Foo`
15+
|
16+
= help: changing this also requires a change to the return expressions in this function
17+
18+
error: aborting due to 2 previous errors
19+

0 commit comments

Comments
 (0)