• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 use clippy_utils::{
2     diagnostics::span_lint_and_sugg, get_parent_node, is_default_equivalent, macros::macro_backtrace, match_path,
3     path_def_id, paths, ty::expr_sig,
4 };
5 use rustc_errors::Applicability;
6 use rustc_hir::{
7     intravisit::{walk_ty, Visitor},
8     Block, Expr, ExprKind, Local, Node, QPath, TyKind,
9 };
10 use rustc_lint::{LateContext, LateLintPass, LintContext};
11 use rustc_middle::lint::in_external_macro;
12 use rustc_middle::ty::print::with_forced_trimmed_paths;
13 use rustc_middle::ty::IsSuggestable;
14 use rustc_session::{declare_lint_pass, declare_tool_lint};
15 use rustc_span::sym;
16 
17 declare_clippy_lint! {
18     /// ### What it does
19     /// checks for `Box::new(T::default())`, which is better written as
20     /// `Box::<T>::default()`.
21     ///
22     /// ### Why is this bad?
23     /// First, it's more complex, involving two calls instead of one.
24     /// Second, `Box::default()` can be faster
25     /// [in certain cases](https://nnethercote.github.io/perf-book/standard-library-types.html#box).
26     ///
27     /// ### Example
28     /// ```rust
29     /// let x: Box<String> = Box::new(Default::default());
30     /// ```
31     /// Use instead:
32     /// ```rust
33     /// let x: Box<String> = Box::default();
34     /// ```
35     #[clippy::version = "1.66.0"]
36     pub BOX_DEFAULT,
37     perf,
38     "Using Box::new(T::default()) instead of Box::default()"
39 }
40 
41 declare_lint_pass!(BoxDefault => [BOX_DEFAULT]);
42 
43 impl LateLintPass<'_> for BoxDefault {
check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>)44     fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
45         if let ExprKind::Call(box_new, [arg]) = expr.kind
46             && let ExprKind::Path(QPath::TypeRelative(ty, seg)) = box_new.kind
47             && let ExprKind::Call(arg_path, ..) = arg.kind
48             && !in_external_macro(cx.sess(), expr.span)
49             && (expr.span.eq_ctxt(arg.span) || is_vec_expn(cx, arg))
50             && seg.ident.name == sym::new
51             && path_def_id(cx, ty).map_or(false, |id| Some(id) == cx.tcx.lang_items().owned_box())
52             && is_default_equivalent(cx, arg)
53         {
54             span_lint_and_sugg(
55                 cx,
56                 BOX_DEFAULT,
57                 expr.span,
58                 "`Box::new(_)` of default value",
59                 "try",
60                 if is_plain_default(arg_path) || given_type(cx, expr) {
61                     "Box::default()".into()
62                 } else if let Some(arg_ty) = cx.typeck_results().expr_ty(arg).make_suggestable(cx.tcx, true) {
63                     with_forced_trimmed_paths!(format!("Box::<{arg_ty}>::default()"))
64                 } else {
65                     return
66                 },
67                 Applicability::MachineApplicable
68             );
69         }
70     }
71 }
72 
is_plain_default(arg_path: &Expr<'_>) -> bool73 fn is_plain_default(arg_path: &Expr<'_>) -> bool {
74     // we need to match the actual path so we don't match e.g. "u8::default"
75     if let ExprKind::Path(QPath::Resolved(None, path)) = &arg_path.kind {
76         // avoid generic parameters
77         match_path(path, &paths::DEFAULT_TRAIT_METHOD) && path.segments.iter().all(|seg| seg.args.is_none())
78     } else {
79         false
80     }
81 }
82 
is_vec_expn(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool83 fn is_vec_expn(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
84     macro_backtrace(expr.span)
85         .next()
86         .map_or(false, |call| cx.tcx.is_diagnostic_item(sym::vec_macro, call.def_id))
87 }
88 
89 #[derive(Default)]
90 struct InferVisitor(bool);
91 
92 impl<'tcx> Visitor<'tcx> for InferVisitor {
visit_ty(&mut self, t: &rustc_hir::Ty<'_>)93     fn visit_ty(&mut self, t: &rustc_hir::Ty<'_>) {
94         self.0 |= matches!(t.kind, TyKind::Infer | TyKind::OpaqueDef(..) | TyKind::TraitObject(..));
95         if !self.0 {
96             walk_ty(self, t);
97         }
98     }
99 }
100 
given_type(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool101 fn given_type(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
102     match get_parent_node(cx.tcx, expr.hir_id) {
103         Some(Node::Local(Local { ty: Some(ty), .. })) => {
104             let mut v = InferVisitor::default();
105             v.visit_ty(ty);
106             !v.0
107         },
108         Some(
109             Node::Expr(Expr {
110                 kind: ExprKind::Call(path, args),
111                 ..
112             }) | Node::Block(Block {
113                 expr:
114                     Some(Expr {
115                         kind: ExprKind::Call(path, args),
116                         ..
117                     }),
118                 ..
119             }),
120         ) => {
121             if let Some(index) = args.iter().position(|arg| arg.hir_id == expr.hir_id) &&
122                 let Some(sig) = expr_sig(cx, path) &&
123                 let Some(input) = sig.input(index) &&
124                 !cx.typeck_results().expr_ty_adjusted(expr).boxed_ty().is_trait()
125             {
126                 input.no_bound_vars().is_some()
127             } else {
128                 false
129             }
130         },
131         _ => false,
132     }
133 }
134