]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/escape.rs
Merge pull request #2821 from mati865/rust-2018-migration
[rust.git] / clippy_lints / src / escape.rs
1 use rustc::hir::*;
2 use rustc::hir::intravisit as visit;
3 use rustc::hir::map::Node::{NodeExpr, NodeStmt};
4 use rustc::lint::*;
5 use rustc::middle::expr_use_visitor::*;
6 use rustc::middle::mem_categorization::{cmt_, Categorization};
7 use rustc::ty::{self, Ty};
8 use rustc::ty::layout::LayoutOf;
9 use rustc::util::nodemap::NodeSet;
10 use syntax::ast::NodeId;
11 use syntax::codemap::Span;
12 use crate::utils::span_lint;
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         let fn_def_id = cx.tcx.hir.local_def_id(node_id);
68         let mut v = EscapeDelegate {
69             cx,
70             set: NodeSet(),
71             too_large_for_stack: self.too_large_for_stack,
72         };
73
74         let region_scope_tree = &cx.tcx.region_scope_tree(fn_def_id);
75         ExprUseVisitor::new(&mut v, cx.tcx, cx.param_env, region_scope_tree, cx.tables, None).consume_body(body);
76
77         for node in v.set {
78             span_lint(
79                 cx,
80                 BOXED_LOCAL,
81                 cx.tcx.hir.span(node),
82                 "local variable doesn't need to be boxed here",
83             );
84         }
85     }
86 }
87
88 impl<'a, 'tcx> Delegate<'tcx> for EscapeDelegate<'a, 'tcx> {
89     fn consume(&mut self, _: NodeId, _: Span, cmt: &cmt_<'tcx>, mode: ConsumeMode) {
90         if let Categorization::Local(lid) = cmt.cat {
91             if let Move(DirectRefMove) = mode {
92                 // moved out or in. clearly can't be localized
93                 self.set.remove(&lid);
94             }
95         }
96     }
97     fn matched_pat(&mut self, _: &Pat, _: &cmt_<'tcx>, _: MatchMode) {}
98     fn consume_pat(&mut self, consume_pat: &Pat, cmt: &cmt_<'tcx>, _: ConsumeMode) {
99         let map = &self.cx.tcx.hir;
100         if map.is_argument(consume_pat.id) {
101             // Skip closure arguments
102             if let Some(NodeExpr(..)) = map.find(map.get_parent_node(consume_pat.id)) {
103                 return;
104             }
105             if is_non_trait_box(cmt.ty) && !self.is_large_box(cmt.ty) {
106                 self.set.insert(consume_pat.id);
107             }
108             return;
109         }
110         if let Categorization::Rvalue(..) = cmt.cat {
111             if let Some(NodeStmt(st)) = map.find(map.get_parent_node(cmt.id)) {
112                 if let StmtDecl(ref decl, _) = st.node {
113                     if let DeclLocal(ref loc) = decl.node {
114                         if let Some(ref ex) = loc.init {
115                             if let ExprBox(..) = ex.node {
116                                 if is_non_trait_box(cmt.ty) && !self.is_large_box(cmt.ty) {
117                                     // let x = box (...)
118                                     self.set.insert(consume_pat.id);
119                                 }
120                                 // TODO Box::new
121                                 // TODO vec![]
122                                 // TODO "foo".to_owned() and friends
123                             }
124                         }
125                     }
126                 }
127             }
128         }
129         if let Categorization::Local(lid) = cmt.cat {
130             if self.set.contains(&lid) {
131                 // let y = x where x is known
132                 // remove x, insert y
133                 self.set.insert(consume_pat.id);
134                 self.set.remove(&lid);
135             }
136         }
137     }
138     fn borrow(&mut self, _: NodeId, _: Span, cmt: &cmt_<'tcx>, _: ty::Region, _: ty::BorrowKind, loan_cause: LoanCause) {
139         if let Categorization::Local(lid) = cmt.cat {
140             match loan_cause {
141                 // x.foo()
142                 // Used without autodereffing (i.e. x.clone())
143                 LoanCause::AutoRef |
144
145                 // &x
146                 // foo(&x) where no extra autoreffing is happening
147                 LoanCause::AddrOf |
148
149                 // `match x` can move
150                 LoanCause::MatchDiscriminant => {
151                     self.set.remove(&lid);
152                 }
153
154                 // do nothing for matches, etc. These can't escape
155                 _ => {}
156             }
157         }
158     }
159     fn decl_without_init(&mut self, _: NodeId, _: Span) {}
160     fn mutate(&mut self, _: NodeId, _: Span, _: &cmt_<'tcx>, _: MutateMode) {}
161 }
162
163 impl<'a, 'tcx> EscapeDelegate<'a, 'tcx> {
164     fn is_large_box(&self, ty: Ty<'tcx>) -> bool {
165         // Large types need to be boxed to avoid stack
166         // overflows.
167         if ty.is_box() {
168             self.cx.layout_of(ty.boxed_ty()).ok().map_or(0, |l| l.size.bytes()) > self.too_large_for_stack
169         } else {
170             false
171         }
172     }
173 }