From 23d533264fd5a4b80cffcefa73a6ddb207c9f6e2 Mon Sep 17 00:00:00 2001 From: Samuel Tardieu Date: Sun, 26 Nov 2023 18:11:50 +0100 Subject: [PATCH] Fix `box_default` behaviour with empty `vec![]` coming from macro arg --- clippy_lints/src/box_default.rs | 10 +++++----- tests/ui/box_default.fixed | 14 ++++++++++++++ tests/ui/box_default.rs | 14 ++++++++++++++ 3 files changed, 33 insertions(+), 5 deletions(-) diff --git a/clippy_lints/src/box_default.rs b/clippy_lints/src/box_default.rs index b69dc5c1291..ef12fe344e4 100644 --- a/clippy_lints/src/box_default.rs +++ b/clippy_lints/src/box_default.rs @@ -45,7 +45,7 @@ impl LateLintPass<'_> for BoxDefault { && let ExprKind::Path(QPath::TypeRelative(ty, seg)) = box_new.kind && let ExprKind::Call(arg_path, ..) = arg.kind && !in_external_macro(cx.sess(), expr.span) - && (expr.span.eq_ctxt(arg.span) || is_vec_expn(cx, arg)) + && (expr.span.eq_ctxt(arg.span) || is_local_vec_expn(cx, arg, expr)) && seg.ident.name == sym::new && path_def_id(cx, ty).map_or(false, |id| Some(id) == cx.tcx.lang_items().owned_box()) && is_default_equivalent(cx, arg) @@ -81,10 +81,10 @@ fn is_plain_default(cx: &LateContext<'_>, arg_path: &Expr<'_>) -> bool { } } -fn is_vec_expn(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { - macro_backtrace(expr.span) - .next() - .map_or(false, |call| cx.tcx.is_diagnostic_item(sym::vec_macro, call.def_id)) +fn is_local_vec_expn(cx: &LateContext<'_>, expr: &Expr<'_>, ref_expr: &Expr<'_>) -> bool { + macro_backtrace(expr.span).next().map_or(false, |call| { + cx.tcx.is_diagnostic_item(sym::vec_macro, call.def_id) && call.span.eq_ctxt(ref_expr.span) + }) } #[derive(Default)] diff --git a/tests/ui/box_default.fixed b/tests/ui/box_default.fixed index 69cabcb32d3..48408e19125 100644 --- a/tests/ui/box_default.fixed +++ b/tests/ui/box_default.fixed @@ -90,3 +90,17 @@ fn issue_10381() { assert!(maybe_get_bar(2).is_some()); } + +#[allow(unused)] +fn issue_11868() { + fn foo(_: &mut Vec) {} + + macro_rules! bar { + ($baz:expr) => { + Box::leak(Box::new($baz)) + }; + } + + foo(bar!(vec![])); + foo(bar!(vec![1])); +} diff --git a/tests/ui/box_default.rs b/tests/ui/box_default.rs index 48fa8bc33bc..58b91270747 100644 --- a/tests/ui/box_default.rs +++ b/tests/ui/box_default.rs @@ -90,3 +90,17 @@ fn issue_10381() { assert!(maybe_get_bar(2).is_some()); } + +#[allow(unused)] +fn issue_11868() { + fn foo(_: &mut Vec) {} + + macro_rules! bar { + ($baz:expr) => { + Box::leak(Box::new($baz)) + }; + } + + foo(bar!(vec![])); + foo(bar!(vec![1])); +}