]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/escape.rs
Rustup to rust-lang/rust#70634
[rust.git] / clippy_lints / src / escape.rs
1 use rustc_hir::intravisit;
2 use rustc_hir::{self, Body, FnDecl, HirId, HirIdSet, ItemKind, Node};
3 use rustc_infer::infer::TyCtxtInferExt;
4 use rustc_lint::{LateContext, LateLintPass};
5 use rustc_middle::ty::{self, Ty};
6 use rustc_session::{declare_tool_lint, impl_lint_pass};
7 use rustc_span::source_map::Span;
8 use rustc_target::abi::LayoutOf;
9 use rustc_typeck::expr_use_visitor::{ConsumeMode, Delegate, ExprUseVisitor, Place, PlaceBase};
10
11 use crate::utils::span_lint;
12
13 #[derive(Copy, Clone)]
14 pub struct BoxedLocal {
15     pub too_large_for_stack: u64,
16 }
17
18 declare_clippy_lint! {
19     /// **What it does:** Checks for usage of `Box<T>` where an unboxed `T` would
20     /// work fine.
21     ///
22     /// **Why is this bad?** This is an unnecessary allocation, and bad for
23     /// performance. It is only necessary to allocate if you wish to move the box
24     /// into something.
25     ///
26     /// **Known problems:** None.
27     ///
28     /// **Example:**
29     /// ```rust
30     /// # fn foo(bar: usize) {}
31     /// let x = Box::new(1);
32     /// foo(*x);
33     /// println!("{}", *x);
34     /// ```
35     pub BOXED_LOCAL,
36     perf,
37     "using `Box<T>` where unnecessary"
38 }
39
40 fn is_non_trait_box(ty: Ty<'_>) -> bool {
41     ty.is_box() && !ty.boxed_ty().is_trait()
42 }
43
44 struct EscapeDelegate<'a, 'tcx> {
45     cx: &'a LateContext<'a, 'tcx>,
46     set: HirIdSet,
47     too_large_for_stack: u64,
48 }
49
50 impl_lint_pass!(BoxedLocal => [BOXED_LOCAL]);
51
52 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoxedLocal {
53     fn check_fn(
54         &mut self,
55         cx: &LateContext<'a, 'tcx>,
56         _: intravisit::FnKind<'tcx>,
57         _: &'tcx FnDecl<'_>,
58         body: &'tcx Body<'_>,
59         _: Span,
60         hir_id: HirId,
61     ) {
62         // If the method is an impl for a trait, don't warn.
63         let parent_id = cx.tcx.hir().get_parent_item(hir_id);
64         let parent_node = cx.tcx.hir().find(parent_id);
65
66         if let Some(Node::Item(item)) = parent_node {
67             if let ItemKind::Impl { of_trait: Some(_), .. } = item.kind {
68                 return;
69             }
70         }
71
72         let mut v = EscapeDelegate {
73             cx,
74             set: HirIdSet::default(),
75             too_large_for_stack: self.too_large_for_stack,
76         };
77
78         let fn_def_id = cx.tcx.hir().local_def_id(hir_id);
79         cx.tcx.infer_ctxt().enter(|infcx| {
80             ExprUseVisitor::new(&mut v, &infcx, fn_def_id, cx.param_env, cx.tables).consume_body(body);
81         });
82
83         for node in v.set {
84             span_lint(
85                 cx,
86                 BOXED_LOCAL,
87                 cx.tcx.hir().span(node),
88                 "local variable doesn't need to be boxed here",
89             );
90         }
91     }
92 }
93
94 // TODO: Replace with Map::is_argument(..) when it's fixed
95 fn is_argument(map: rustc_middle::hir::map::Map<'_>, id: HirId) -> bool {
96     match map.find(id) {
97         Some(Node::Binding(_)) => (),
98         _ => return false,
99     }
100
101     match map.find(map.get_parent_node(id)) {
102         Some(Node::Param(_)) => true,
103         _ => false,
104     }
105 }
106
107 impl<'a, 'tcx> Delegate<'tcx> for EscapeDelegate<'a, 'tcx> {
108     fn consume(&mut self, cmt: &Place<'tcx>, mode: ConsumeMode) {
109         if cmt.projections.is_empty() {
110             if let PlaceBase::Local(lid) = cmt.base {
111                 if let ConsumeMode::Move = mode {
112                     // moved out or in. clearly can't be localized
113                     self.set.remove(&lid);
114                 }
115                 let map = &self.cx.tcx.hir();
116                 if let Some(Node::Binding(_)) = map.find(cmt.hir_id) {
117                     if self.set.contains(&lid) {
118                         // let y = x where x is known
119                         // remove x, insert y
120                         self.set.insert(cmt.hir_id);
121                         self.set.remove(&lid);
122                     }
123                 }
124             }
125         }
126     }
127
128     fn borrow(&mut self, cmt: &Place<'tcx>, _: ty::BorrowKind) {
129         if cmt.projections.is_empty() {
130             if let PlaceBase::Local(lid) = cmt.base {
131                 self.set.remove(&lid);
132             }
133         }
134     }
135
136     fn mutate(&mut self, cmt: &Place<'tcx>) {
137         if cmt.projections.is_empty() {
138             let map = &self.cx.tcx.hir();
139             if is_argument(*map, cmt.hir_id) {
140                 // Skip closure arguments
141                 let parent_id = map.get_parent_node(cmt.hir_id);
142                 if let Some(Node::Expr(..)) = map.find(map.get_parent_node(parent_id)) {
143                     return;
144                 }
145
146                 if is_non_trait_box(cmt.ty) && !self.is_large_box(cmt.ty) {
147                     self.set.insert(cmt.hir_id);
148                 }
149                 return;
150             }
151         }
152     }
153 }
154
155 impl<'a, 'tcx> EscapeDelegate<'a, 'tcx> {
156     fn is_large_box(&self, ty: Ty<'tcx>) -> bool {
157         // Large types need to be boxed to avoid stack overflows.
158         if ty.is_box() {
159             self.cx.layout_of(ty.boxed_ty()).map_or(0, |l| l.size.bytes()) > self.too_large_for_stack
160         } else {
161             false
162         }
163     }
164 }