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