|
| 1 | +use clippy_utils::diagnostics::span_lint_and_then; |
| 2 | +use clippy_utils::sugg::Sugg; |
| 3 | +use clippy_utils::ty::implements_trait; |
| 4 | +use clippy_utils::{is_default_equivalent_call, local_is_initialized, path_def_id, path_to_local}; |
| 5 | +use rustc_errors::Applicability; |
| 6 | +use rustc_hir::{Expr, ExprKind, LangItem, QPath}; |
| 7 | +use rustc_lint::{LateContext, LateLintPass}; |
| 8 | +use rustc_middle::ty::{self, Ty}; |
| 9 | +use rustc_session::declare_lint_pass; |
| 10 | +use rustc_span::sym; |
| 11 | + |
| 12 | +declare_clippy_lint! { |
| 13 | + /// ### What it does |
| 14 | + /// Detects assignments of `Default::default()` or `Box::new(value)` |
| 15 | + /// to a place of type `Box<T>`. |
| 16 | + /// |
| 17 | + /// ### Why is this bad? |
| 18 | + /// This incurs an extra heap allocation compared to assigning the boxed |
| 19 | + /// storage. |
| 20 | + /// |
| 21 | + /// ### Example |
| 22 | + /// ```no_run |
| 23 | + /// let mut b = Box::new(1u32); |
| 24 | + /// b = Default::default(); |
| 25 | + /// ``` |
| 26 | + /// Use instead: |
| 27 | + /// ```no_run |
| 28 | + /// let mut b = Box::new(1u32); |
| 29 | + /// *b = Default::default(); |
| 30 | + /// ``` |
| 31 | + #[clippy::version = "1.92.0"] |
| 32 | + pub REPLACE_BOX, |
| 33 | + perf, |
| 34 | + "assigning a newly created box to `Box<T>` is inefficient" |
| 35 | +} |
| 36 | +declare_lint_pass!(ReplaceBox => [REPLACE_BOX]); |
| 37 | + |
| 38 | +impl LateLintPass<'_> for ReplaceBox { |
| 39 | + fn check_expr(&mut self, cx: &LateContext<'_>, expr: &'_ Expr<'_>) { |
| 40 | + if let ExprKind::Assign(lhs, rhs, _) = &expr.kind |
| 41 | + && !lhs.span.from_expansion() |
| 42 | + && !rhs.span.from_expansion() |
| 43 | + { |
| 44 | + let lhs_ty = cx.typeck_results().expr_ty(lhs); |
| 45 | + |
| 46 | + // No diagnostic for late-initialized locals |
| 47 | + if let Some(local) = path_to_local(lhs) |
| 48 | + && !local_is_initialized(cx, local) |
| 49 | + { |
| 50 | + return; |
| 51 | + } |
| 52 | + |
| 53 | + let Some(inner_ty) = get_box_inner_type(cx, lhs_ty) else { |
| 54 | + return; |
| 55 | + }; |
| 56 | + |
| 57 | + if let Some(default_trait_id) = cx.tcx.get_diagnostic_item(sym::Default) |
| 58 | + && implements_trait(cx, inner_ty, default_trait_id, &[]) |
| 59 | + && is_default_call(cx, rhs) |
| 60 | + { |
| 61 | + span_lint_and_then( |
| 62 | + cx, |
| 63 | + REPLACE_BOX, |
| 64 | + expr.span, |
| 65 | + "creating a new box with default content", |
| 66 | + |diag| { |
| 67 | + let mut app = Applicability::MachineApplicable; |
| 68 | + let suggestion = format!( |
| 69 | + "{} = Default::default()", |
| 70 | + Sugg::hir_with_applicability(cx, lhs, "_", &mut app).deref() |
| 71 | + ); |
| 72 | + |
| 73 | + diag.note("this creates a needless allocation").span_suggestion( |
| 74 | + expr.span, |
| 75 | + "replace existing content with default instead", |
| 76 | + suggestion, |
| 77 | + app, |
| 78 | + ); |
| 79 | + }, |
| 80 | + ); |
| 81 | + } |
| 82 | + |
| 83 | + if inner_ty.is_sized(cx.tcx, cx.typing_env()) |
| 84 | + && let Some(rhs_inner) = get_box_new_payload(cx, rhs) |
| 85 | + { |
| 86 | + span_lint_and_then(cx, REPLACE_BOX, expr.span, "creating a new box", |diag| { |
| 87 | + let mut app = Applicability::MachineApplicable; |
| 88 | + let suggestion = format!( |
| 89 | + "{} = {}", |
| 90 | + Sugg::hir_with_applicability(cx, lhs, "_", &mut app).deref(), |
| 91 | + Sugg::hir_with_context(cx, rhs_inner, expr.span.ctxt(), "_", &mut app), |
| 92 | + ); |
| 93 | + |
| 94 | + diag.note("this creates a needless allocation").span_suggestion( |
| 95 | + expr.span, |
| 96 | + "replace existing content with inner value instead", |
| 97 | + suggestion, |
| 98 | + app, |
| 99 | + ); |
| 100 | + }); |
| 101 | + } |
| 102 | + } |
| 103 | + } |
| 104 | +} |
| 105 | + |
| 106 | +fn get_box_inner_type<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<Ty<'tcx>> { |
| 107 | + if let ty::Adt(def, args) = ty.kind() |
| 108 | + && cx.tcx.is_lang_item(def.did(), LangItem::OwnedBox) |
| 109 | + { |
| 110 | + Some(args.type_at(0)) |
| 111 | + } else { |
| 112 | + None |
| 113 | + } |
| 114 | +} |
| 115 | + |
| 116 | +fn is_default_call(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { |
| 117 | + matches!(expr.kind, ExprKind::Call(func, _args) if is_default_equivalent_call(cx, func, Some(expr))) |
| 118 | +} |
| 119 | + |
| 120 | +fn get_box_new_payload<'tcx>(cx: &LateContext<'_>, expr: &Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> { |
| 121 | + if let ExprKind::Call(box_new, [arg]) = expr.kind |
| 122 | + && let ExprKind::Path(QPath::TypeRelative(ty, seg)) = box_new.kind |
| 123 | + && seg.ident.name == sym::new |
| 124 | + && path_def_id(cx, ty).is_some_and(|id| Some(id) == cx.tcx.lang_items().owned_box()) |
| 125 | + { |
| 126 | + Some(arg) |
| 127 | + } else { |
| 128 | + None |
| 129 | + } |
| 130 | +} |
0 commit comments