]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/escape.rs
Auto merge of #4327 - phansch:doctests_perf, r=flip1995
[rust.git] / clippy_lints / src / escape.rs
1 use rustc::hir::intravisit as visit;
2 use rustc::hir::{self, *};
3 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
4 use rustc::middle::expr_use_visitor::*;
5 use rustc::middle::mem_categorization::{cmt_, Categorization};
6 use rustc::ty::layout::LayoutOf;
7 use rustc::ty::{self, Ty};
8 use rustc::util::nodemap::HirIdSet;
9 use rustc::{declare_tool_lint, impl_lint_pass};
10 use syntax::source_map::Span;
11
12 use crate::utils::span_lint;
13
14 #[derive(Copy, Clone)]
15 pub struct BoxedLocal {
16     pub too_large_for_stack: u64,
17 }
18
19 declare_clippy_lint! {
20     /// **What it does:** Checks for usage of `Box<T>` where an unboxed `T` would
21     /// work fine.
22     ///
23     /// **Why is this bad?** This is an unnecessary allocation, and bad for
24     /// performance. It is only necessary to allocate if you wish to move the box
25     /// into something.
26     ///
27     /// **Known problems:** None.
28     ///
29     /// **Example:**
30     /// ```rust
31     /// # fn foo(bar: usize) {}
32     /// let x = Box::new(1);
33     /// foo(*x);
34     /// println!("{}", *x);
35     /// ```
36     pub BOXED_LOCAL,
37     perf,
38     "using `Box<T>` where unnecessary"
39 }
40
41 fn is_non_trait_box(ty: Ty<'_>) -> bool {
42     ty.is_box() && !ty.boxed_ty().is_trait()
43 }
44
45 struct EscapeDelegate<'a, 'tcx> {
46     cx: &'a LateContext<'a, 'tcx>,
47     set: HirIdSet,
48     too_large_for_stack: u64,
49 }
50
51 impl_lint_pass!(BoxedLocal => [BOXED_LOCAL]);
52
53 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoxedLocal {
54     fn check_fn(
55         &mut self,
56         cx: &LateContext<'a, 'tcx>,
57         _: visit::FnKind<'tcx>,
58         _: &'tcx FnDecl,
59         body: &'tcx Body,
60         _: Span,
61         hir_id: HirId,
62     ) {
63         // If the method is an impl for a trait, don't warn.
64         let parent_id = cx.tcx.hir().get_parent_item(hir_id);
65         let parent_node = cx.tcx.hir().find(parent_id);
66
67         if let Some(Node::Item(item)) = parent_node {
68             if let ItemKind::Impl(_, _, _, _, Some(..), _, _) = item.node {
69                 return;
70             }
71         }
72
73         let mut v = EscapeDelegate {
74             cx,
75             set: HirIdSet::default(),
76             too_large_for_stack: self.too_large_for_stack,
77         };
78
79         let fn_def_id = cx.tcx.hir().local_def_id(hir_id);
80         let region_scope_tree = &cx.tcx.region_scope_tree(fn_def_id);
81         ExprUseVisitor::new(
82             &mut v,
83             cx.tcx,
84             fn_def_id,
85             cx.param_env,
86             region_scope_tree,
87             cx.tables,
88             None,
89         )
90         .consume_body(body);
91
92         for node in v.set {
93             span_lint(
94                 cx,
95                 BOXED_LOCAL,
96                 cx.tcx.hir().span(node),
97                 "local variable doesn't need to be boxed here",
98             );
99         }
100     }
101 }
102
103 // TODO: Replace with Map::is_argument(..) when it's fixed
104 fn is_argument(map: &hir::map::Map<'_>, id: HirId) -> bool {
105     match map.find(id) {
106         Some(Node::Binding(_)) => (),
107         _ => return false,
108     }
109
110     match map.find(map.get_parent_node(id)) {
111         Some(Node::Arg(_)) => true,
112         _ => false,
113     }
114 }
115
116 impl<'a, 'tcx> Delegate<'tcx> for EscapeDelegate<'a, 'tcx> {
117     fn consume(&mut self, _: HirId, _: Span, cmt: &cmt_<'tcx>, mode: ConsumeMode) {
118         if let Categorization::Local(lid) = cmt.cat {
119             if let Move(DirectRefMove) | Move(CaptureMove) = mode {
120                 // moved out or in. clearly can't be localized
121                 self.set.remove(&lid);
122             }
123         }
124     }
125     fn matched_pat(&mut self, _: &Pat, _: &cmt_<'tcx>, _: MatchMode) {}
126     fn consume_pat(&mut self, consume_pat: &Pat, cmt: &cmt_<'tcx>, _: ConsumeMode) {
127         let map = &self.cx.tcx.hir();
128         if is_argument(map, consume_pat.hir_id) {
129             // Skip closure arguments
130             let parent_id = map.get_parent_node(consume_pat.hir_id);
131             if let Some(Node::Expr(..)) = map.find(map.get_parent_node(parent_id)) {
132                 return;
133             }
134
135             if is_non_trait_box(cmt.ty) && !self.is_large_box(cmt.ty) {
136                 self.set.insert(consume_pat.hir_id);
137             }
138             return;
139         }
140         if let Categorization::Rvalue(..) = cmt.cat {
141             if let Some(Node::Stmt(st)) = map.find(map.get_parent_node(cmt.hir_id)) {
142                 if let StmtKind::Local(ref loc) = st.node {
143                     if let Some(ref ex) = loc.init {
144                         if let ExprKind::Box(..) = ex.node {
145                             if is_non_trait_box(cmt.ty) && !self.is_large_box(cmt.ty) {
146                                 // let x = box (...)
147                                 self.set.insert(consume_pat.hir_id);
148                             }
149                             // TODO Box::new
150                             // TODO vec![]
151                             // TODO "foo".to_owned() and friends
152                         }
153                     }
154                 }
155             }
156         }
157         if let Categorization::Local(lid) = cmt.cat {
158             if self.set.contains(&lid) {
159                 // let y = x where x is known
160                 // remove x, insert y
161                 self.set.insert(consume_pat.hir_id);
162                 self.set.remove(&lid);
163             }
164         }
165     }
166     fn borrow(
167         &mut self,
168         _: HirId,
169         _: Span,
170         cmt: &cmt_<'tcx>,
171         _: ty::Region<'_>,
172         _: ty::BorrowKind,
173         loan_cause: LoanCause,
174     ) {
175         if let Categorization::Local(lid) = cmt.cat {
176             match loan_cause {
177                 // `x.foo()`
178                 // Used without autoderef-ing (i.e., `x.clone()`).
179                 LoanCause::AutoRef |
180
181                 // `&x`
182                 // `foo(&x)` where no extra autoref-ing is happening.
183                 LoanCause::AddrOf |
184
185                 // `match x` can move.
186                 LoanCause::MatchDiscriminant => {
187                     self.set.remove(&lid);
188                 }
189
190                 // Do nothing for matches, etc. These can't escape.
191                 _ => {}
192             }
193         }
194     }
195     fn decl_without_init(&mut self, _: HirId, _: Span) {}
196     fn mutate(&mut self, _: HirId, _: Span, _: &cmt_<'tcx>, _: MutateMode) {}
197 }
198
199 impl<'a, 'tcx> EscapeDelegate<'a, 'tcx> {
200     fn is_large_box(&self, ty: Ty<'tcx>) -> bool {
201         // Large types need to be boxed to avoid stack overflows.
202         if ty.is_box() {
203             self.cx.layout_of(ty.boxed_ty()).ok().map_or(0, |l| l.size.bytes()) > self.too_large_for_stack
204         } else {
205             false
206         }
207     }
208 }