1 use clippy_utils::{diagnostics::span_lint_and_help, is_default_equivalent, path_def_id};
2 use rustc_hir::{Expr, ExprKind, QPath};
3 use rustc_lint::{LateContext, LateLintPass, LintContext};
4 use rustc_middle::lint::in_external_macro;
5 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 /// checks for `Box::new(T::default())`, which is better written as
11 /// `Box::<T>::default()`.
13 /// ### Why is this bad?
14 /// First, it's more complex, involving two calls instead of one.
15 /// Second, `Box::default()` can be faster
16 /// [in certain cases](https://nnethercote.github.io/perf-book/standard-library-types.html#box).
18 /// ### Known problems
19 /// The lint may miss some cases (e.g. Box::new(String::from(""))).
20 /// On the other hand, it will trigger on cases where the `default`
21 /// code comes from a macro that does something different based on
22 /// e.g. target operating system.
26 /// let x: Box<String> = Box::new(Default::default());
30 /// let x: Box<String> = Box::default();
32 #[clippy::version = "1.65.0"]
35 "Using Box::new(T::default()) instead of Box::default()"
38 declare_lint_pass!(BoxDefault => [BOX_DEFAULT]);
40 impl LateLintPass<'_> for BoxDefault {
41 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
42 if let ExprKind::Call(box_new, [arg]) = expr.kind
43 && let ExprKind::Path(QPath::TypeRelative(ty, seg)) = box_new.kind
44 && let ExprKind::Call(..) = arg.kind
45 && !in_external_macro(cx.sess(), expr.span)
46 && expr.span.eq_ctxt(arg.span)
47 && seg.ident.name == sym::new
48 && path_def_id(cx, ty) == cx.tcx.lang_items().owned_box()
49 && is_default_equivalent(cx, arg)
55 "`Box::new(_)` of default value",
57 "use `Box::default()` instead",