]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/escape.rs
Merge commit 'c2c07fa9d095931eb5684a42942a7b573a0c5238' into clippyup
[rust.git] / src / tools / clippy / 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, PlaceBase, PlaceWithHirId};
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     ///
32     /// // Bad
33     /// let x = Box::new(1);
34     /// foo(*x);
35     /// println!("{}", *x);
36     ///
37     /// // Good
38     /// let x = 1;
39     /// foo(x);
40     /// println!("{}", x);
41     /// ```
42     pub BOXED_LOCAL,
43     perf,
44     "using `Box<T>` where unnecessary"
45 }
46
47 fn is_non_trait_box(ty: Ty<'_>) -> bool {
48     ty.is_box() && !ty.boxed_ty().is_trait()
49 }
50
51 struct EscapeDelegate<'a, 'tcx> {
52     cx: &'a LateContext<'a, 'tcx>,
53     set: HirIdSet,
54     too_large_for_stack: u64,
55 }
56
57 impl_lint_pass!(BoxedLocal => [BOXED_LOCAL]);
58
59 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoxedLocal {
60     fn check_fn(
61         &mut self,
62         cx: &LateContext<'a, 'tcx>,
63         _: intravisit::FnKind<'tcx>,
64         _: &'tcx FnDecl<'_>,
65         body: &'tcx Body<'_>,
66         _: Span,
67         hir_id: HirId,
68     ) {
69         // If the method is an impl for a trait, don't warn.
70         let parent_id = cx.tcx.hir().get_parent_item(hir_id);
71         let parent_node = cx.tcx.hir().find(parent_id);
72
73         if let Some(Node::Item(item)) = parent_node {
74             if let ItemKind::Impl { of_trait: Some(_), .. } = item.kind {
75                 return;
76             }
77         }
78
79         let mut v = EscapeDelegate {
80             cx,
81             set: HirIdSet::default(),
82             too_large_for_stack: self.too_large_for_stack,
83         };
84
85         let fn_def_id = cx.tcx.hir().local_def_id(hir_id);
86         cx.tcx.infer_ctxt().enter(|infcx| {
87             ExprUseVisitor::new(&mut v, &infcx, fn_def_id, cx.param_env, cx.tables).consume_body(body);
88         });
89
90         for node in v.set {
91             span_lint(
92                 cx,
93                 BOXED_LOCAL,
94                 cx.tcx.hir().span(node),
95                 "local variable doesn't need to be boxed here",
96             );
97         }
98     }
99 }
100
101 // TODO: Replace with Map::is_argument(..) when it's fixed
102 fn is_argument(map: rustc_middle::hir::map::Map<'_>, id: HirId) -> bool {
103     match map.find(id) {
104         Some(Node::Binding(_)) => (),
105         _ => return false,
106     }
107
108     match map.find(map.get_parent_node(id)) {
109         Some(Node::Param(_)) => true,
110         _ => false,
111     }
112 }
113
114 impl<'a, 'tcx> Delegate<'tcx> for EscapeDelegate<'a, 'tcx> {
115     fn consume(&mut self, cmt: &PlaceWithHirId<'tcx>, mode: ConsumeMode) {
116         if cmt.place.projections.is_empty() {
117             if let PlaceBase::Local(lid) = cmt.place.base {
118                 if let ConsumeMode::Move = mode {
119                     // moved out or in. clearly can't be localized
120                     self.set.remove(&lid);
121                 }
122                 let map = &self.cx.tcx.hir();
123                 if let Some(Node::Binding(_)) = map.find(cmt.hir_id) {
124                     if self.set.contains(&lid) {
125                         // let y = x where x is known
126                         // remove x, insert y
127                         self.set.insert(cmt.hir_id);
128                         self.set.remove(&lid);
129                     }
130                 }
131             }
132         }
133     }
134
135     fn borrow(&mut self, cmt: &PlaceWithHirId<'tcx>, _: ty::BorrowKind) {
136         if cmt.place.projections.is_empty() {
137             if let PlaceBase::Local(lid) = cmt.place.base {
138                 self.set.remove(&lid);
139             }
140         }
141     }
142
143     fn mutate(&mut self, cmt: &PlaceWithHirId<'tcx>) {
144         if cmt.place.projections.is_empty() {
145             let map = &self.cx.tcx.hir();
146             if is_argument(*map, cmt.hir_id) {
147                 // Skip closure arguments
148                 let parent_id = map.get_parent_node(cmt.hir_id);
149                 if let Some(Node::Expr(..)) = map.find(map.get_parent_node(parent_id)) {
150                     return;
151                 }
152
153                 if is_non_trait_box(cmt.place.ty) && !self.is_large_box(cmt.place.ty) {
154                     self.set.insert(cmt.hir_id);
155                 }
156                 return;
157             }
158         }
159     }
160 }
161
162 impl<'a, 'tcx> EscapeDelegate<'a, 'tcx> {
163     fn is_large_box(&self, ty: Ty<'tcx>) -> bool {
164         // Large types need to be boxed to avoid stack overflows.
165         if ty.is_box() {
166             self.cx.layout_of(ty.boxed_ty()).map_or(0, |l| l.size.bytes()) > self.too_large_for_stack
167         } else {
168             false
169         }
170     }
171 }