Skip to content

Commit d718995

Browse files
committed
Auto merge of #12355 - Ethiraric:fix-11927, r=Alexendoo
[`box_default`]: Preserve required path segments When encountering code such as: ```rs Box::new(outer::Inner::default()) ``` clippy would suggest replacing with `Box::<Inner>::default()`, dropping the `outer::` segment. This behavior is incorrect and that commit fixes it. What it does is it checks the contents of the `Box::new` and, if it is of the form `A::B::default`, does a text replacement, inserting `A::B` in the `Box`'s quickfix generic list. If the source does not match that pattern (including `Vec::from(..)` or other `T::new()` calls), we then fallback to the original code. Fixes #11927 *Please write a short comment explaining your change (or "none" for internal only changes)* changelog: [`box_default`]: Preserve required path segments
2 parents a11875b + 97dc4b2 commit d718995

File tree

4 files changed

+88
-8
lines changed

4 files changed

+88
-8
lines changed

clippy_lints/src/box_default.rs

+41-5
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
use clippy_utils::diagnostics::span_lint_and_sugg;
22
use clippy_utils::macros::macro_backtrace;
3+
use clippy_utils::source::snippet_opt;
34
use clippy_utils::ty::expr_sig;
45
use clippy_utils::{is_default_equivalent, path_def_id};
56
use rustc_errors::Applicability;
67
use rustc_hir::def::Res;
78
use rustc_hir::intravisit::{walk_ty, Visitor};
8-
use rustc_hir::{Block, Expr, ExprKind, Local, Node, QPath, TyKind};
9+
use rustc_hir::{Block, Expr, ExprKind, Local, Node, QPath, Ty, TyKind};
910
use rustc_lint::{LateContext, LateLintPass, LintContext};
1011
use rustc_middle::lint::in_external_macro;
1112
use rustc_middle::ty::print::with_forced_trimmed_paths;
@@ -41,13 +42,24 @@ declare_lint_pass!(BoxDefault => [BOX_DEFAULT]);
4142

4243
impl LateLintPass<'_> for BoxDefault {
4344
fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
45+
// If the expression is a call (`Box::new(...)`)
4446
if let ExprKind::Call(box_new, [arg]) = expr.kind
47+
// And call is of the form `<T>::something`
48+
// Here, it would be `<Box>::new`
4549
&& let ExprKind::Path(QPath::TypeRelative(ty, seg)) = box_new.kind
46-
&& let ExprKind::Call(arg_path, ..) = arg.kind
47-
&& !in_external_macro(cx.sess(), expr.span)
48-
&& (expr.span.eq_ctxt(arg.span) || is_local_vec_expn(cx, arg, expr))
50+
// And that method is `new`
4951
&& seg.ident.name == sym::new
52+
// And the call is that of a `Box` method
5053
&& path_def_id(cx, ty).map_or(false, |id| Some(id) == cx.tcx.lang_items().owned_box())
54+
// And the single argument to the call is another function call
55+
// This is the `T::default()` of `Box::new(T::default())`
56+
&& let ExprKind::Call(arg_path, inner_call_args) = arg.kind
57+
// And we are not in a foreign crate's macro
58+
&& !in_external_macro(cx.sess(), expr.span)
59+
// And the argument expression has the same context as the outer call expression
60+
// or that we are inside a `vec!` macro expansion
61+
&& (expr.span.eq_ctxt(arg.span) || is_local_vec_expn(cx, arg, expr))
62+
// And the argument is equivalent to `Default::default()`
5163
&& is_default_equivalent(cx, arg)
5264
{
5365
span_lint_and_sugg(
@@ -59,7 +71,17 @@ impl LateLintPass<'_> for BoxDefault {
5971
if is_plain_default(cx, arg_path) || given_type(cx, expr) {
6072
"Box::default()".into()
6173
} else if let Some(arg_ty) = cx.typeck_results().expr_ty(arg).make_suggestable(cx.tcx, true) {
62-
with_forced_trimmed_paths!(format!("Box::<{arg_ty}>::default()"))
74+
// Check if we can copy from the source expression in the replacement.
75+
// We need the call to have no argument (see `explicit_default_type`).
76+
if inner_call_args.is_empty()
77+
&& let Some(ty) = explicit_default_type(arg_path)
78+
&& let Some(s) = snippet_opt(cx, ty.span)
79+
{
80+
format!("Box::<{s}>::default()")
81+
} else {
82+
// Otherwise, use the inferred type's formatting.
83+
with_forced_trimmed_paths!(format!("Box::<{arg_ty}>::default()"))
84+
}
6385
} else {
6486
return;
6587
},
@@ -81,6 +103,20 @@ fn is_plain_default(cx: &LateContext<'_>, arg_path: &Expr<'_>) -> bool {
81103
}
82104
}
83105

106+
// Checks whether the call is of the form `A::B::f()`. Returns `A::B` if it is.
107+
//
108+
// In the event we have this kind of construct, it's easy to use `A::B` as a replacement in the
109+
// quickfix. `f` must however have no parameter. Should `f` have some, then some of the type of
110+
// `A::B` may be inferred from the arguments. This would be the case for `Vec::from([0; false])`,
111+
// where the argument to `from` allows inferring this is a `Vec<bool>`
112+
fn explicit_default_type<'a>(arg_path: &'a Expr<'_>) -> Option<&'a Ty<'a>> {
113+
if let ExprKind::Path(QPath::TypeRelative(ty, _)) = &arg_path.kind {
114+
Some(ty)
115+
} else {
116+
None
117+
}
118+
}
119+
84120
fn is_local_vec_expn(cx: &LateContext<'_>, expr: &Expr<'_>, ref_expr: &Expr<'_>) -> bool {
85121
macro_backtrace(expr.span).next().map_or(false, |call| {
86122
cx.tcx.is_diagnostic_item(sym::vec_macro, call.def_id) && call.span.eq_ctxt(ref_expr.span)

tests/ui/box_default.fixed

+17-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ macro_rules! outer {
2121
fn main() {
2222
let _string: Box<String> = Box::default();
2323
let _byte = Box::<u8>::default();
24-
let _vec = Box::<Vec<u8>>::default();
24+
let _vec = Box::<Vec::<u8>>::default();
2525
let _impl = Box::<ImplementsDefault>::default();
2626
let _impl2 = Box::<ImplementsDefault>::default();
2727
let _impl3: Box<ImplementsDefault> = Box::default();
@@ -104,3 +104,19 @@ fn issue_11868() {
104104
foo(bar!(vec![]));
105105
foo(bar!(vec![1]));
106106
}
107+
108+
// Issue #11927: The quickfix for the `Box::new` suggests replacing with `Box::<Inner>::default()`,
109+
// removing the `outer::` segment.
110+
fn issue_11927() {
111+
mod outer {
112+
#[derive(Default)]
113+
pub struct Inner {
114+
_i: usize,
115+
}
116+
}
117+
118+
fn foo() {
119+
let _b = Box::<outer::Inner>::default();
120+
let _b = Box::<std::collections::HashSet::<i32>>::default();
121+
}
122+
}

tests/ui/box_default.rs

+16
Original file line numberDiff line numberDiff line change
@@ -104,3 +104,19 @@ fn issue_11868() {
104104
foo(bar!(vec![]));
105105
foo(bar!(vec![1]));
106106
}
107+
108+
// Issue #11927: The quickfix for the `Box::new` suggests replacing with `Box::<Inner>::default()`,
109+
// removing the `outer::` segment.
110+
fn issue_11927() {
111+
mod outer {
112+
#[derive(Default)]
113+
pub struct Inner {
114+
_i: usize,
115+
}
116+
}
117+
118+
fn foo() {
119+
let _b = Box::new(outer::Inner::default());
120+
let _b = Box::new(std::collections::HashSet::<i32>::new());
121+
}
122+
}

tests/ui/box_default.stderr

+14-2
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ error: `Box::new(_)` of default value
1717
--> tests/ui/box_default.rs:24:16
1818
|
1919
LL | let _vec = Box::new(Vec::<u8>::new());
20-
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `Box::<Vec<u8>>::default()`
20+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `Box::<Vec::<u8>>::default()`
2121

2222
error: `Box::new(_)` of default value
2323
--> tests/ui/box_default.rs:25:17
@@ -97,5 +97,17 @@ error: `Box::new(_)` of default value
9797
LL | Some(Box::new(Foo::default()))
9898
| ^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `Box::<Foo>::default()`
9999

100-
error: aborting due to 16 previous errors
100+
error: `Box::new(_)` of default value
101+
--> tests/ui/box_default.rs:119:18
102+
|
103+
LL | let _b = Box::new(outer::Inner::default());
104+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `Box::<outer::Inner>::default()`
105+
106+
error: `Box::new(_)` of default value
107+
--> tests/ui/box_default.rs:120:18
108+
|
109+
LL | let _b = Box::new(std::collections::HashSet::<i32>::new());
110+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `Box::<std::collections::HashSet::<i32>>::default()`
111+
112+
error: aborting due to 18 previous errors
101113

0 commit comments

Comments
 (0)