]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/escape.rs
6f073478027ac45ccb1c6aa950073dac1abf5a19
[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;
8 use rustc::util::nodemap::NodeSet;
9 use syntax::ast::NodeId;
10 use syntax::codemap::Span;
11 use utils::span_lint;
12
13 pub struct Pass {
14     pub too_large_for_stack: u64,
15 }
16
17 /// **What it does:** Checks for usage of `Box<T>` where an unboxed `T` would
18 /// work fine.
19 ///
20 /// **Why is this bad?** This is an unnecessary allocation, and bad for
21 /// performance. It is only necessary to allocate if you wish to move the box
22 /// into something.
23 ///
24 /// **Known problems:** None.
25 ///
26 /// **Example:**
27 /// ```rust
28 /// fn main() {
29 ///     let x = Box::new(1);
30 ///     foo(*x);
31 ///     println!("{}", *x);
32 /// }
33 /// ```
34 declare_lint! {
35     pub BOXED_LOCAL,
36     Warn,
37     "using `Box<T>` where unnecessary"
38 }
39
40 fn is_non_trait_box(ty: ty::Ty) -> bool {
41     ty.is_box() && !ty.boxed_ty().is_trait()
42 }
43
44 struct EscapeDelegate<'a, 'tcx: 'a> {
45     set: NodeSet,
46     tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
47     param_env: ty::ParamEnv<'tcx>,
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 param_env = cx.tcx.param_env(fn_def_id).reveal_all();
69         let mut v = EscapeDelegate {
70             set: NodeSet(),
71             tcx: cx.tcx,
72             param_env: param_env,
73             too_large_for_stack: self.too_large_for_stack,
74         };
75
76         cx.tcx.infer_ctxt(body.id()).enter(|infcx| {
77             let region_maps = &cx.tcx.region_maps(fn_def_id);
78             let mut vis = ExprUseVisitor::new(&mut v, region_maps, &infcx, param_env);
79             vis.consume_body(body);
80         });
81
82         for node in v.set {
83             span_lint(cx,
84                       BOXED_LOCAL,
85                       cx.tcx.hir.span(node),
86                       "local variable doesn't need to be boxed here");
87         }
88     }
89 }
90
91 impl<'a, 'gcx: 'tcx, 'tcx> Delegate<'tcx> for EscapeDelegate<'a, 'gcx> {
92     fn consume(&mut self, _: NodeId, _: Span, cmt: cmt<'tcx>, mode: ConsumeMode) {
93         if let Categorization::Local(lid) = cmt.cat {
94             if let Move(DirectRefMove) = mode {
95                 // moved out or in. clearly can't be localized
96                 self.set.remove(&lid);
97             }
98         }
99     }
100     fn matched_pat(&mut self, _: &Pat, _: cmt<'tcx>, _: MatchMode) {}
101     fn consume_pat(&mut self, consume_pat: &Pat, cmt: cmt<'tcx>, _: ConsumeMode) {
102         let map = &self.tcx.hir;
103         if map.is_argument(consume_pat.id) {
104             // Skip closure arguments
105             if let Some(NodeExpr(..)) = map.find(map.get_parent_node(consume_pat.id)) {
106                 return;
107             }
108             if is_non_trait_box(cmt.ty) && !self.is_large_box(cmt.ty) {
109                 self.set.insert(consume_pat.id);
110             }
111             return;
112         }
113         if let Categorization::Rvalue(..) = cmt.cat {
114             if let Some(NodeStmt(st)) = map.find(map.get_parent_node(cmt.id)) {
115                 if let StmtDecl(ref decl, _) = st.node {
116                     if let DeclLocal(ref loc) = decl.node {
117                         if let Some(ref ex) = loc.init {
118                             if let ExprBox(..) = ex.node {
119                                 if is_non_trait_box(cmt.ty) && !self.is_large_box(cmt.ty) {
120                                     // let x = box (...)
121                                     self.set.insert(consume_pat.id);
122                                 }
123                                 // TODO Box::new
124                                 // TODO vec![]
125                                 // TODO "foo".to_owned() and friends
126                             }
127                         }
128                     }
129                 }
130             }
131         }
132         if let Categorization::Local(lid) = cmt.cat {
133             if self.set.contains(&lid) {
134                 // let y = x where x is known
135                 // remove x, insert y
136                 self.set.insert(consume_pat.id);
137                 self.set.remove(&lid);
138             }
139         }
140
141     }
142     fn borrow(
143         &mut self,
144         _: NodeId,
145         _: Span,
146         cmt: cmt<'tcx>,
147         _: ty::Region,
148         _: ty::BorrowKind,
149         loan_cause: LoanCause
150     ) {
151         if let Categorization::Local(lid) = cmt.cat {
152             match loan_cause {
153                 // x.foo()
154                 // Used without autodereffing (i.e. x.clone())
155                 LoanCause::AutoRef |
156
157                 // &x
158                 // foo(&x) where no extra autoreffing is happening
159                 LoanCause::AddrOf |
160
161                 // `match x` can move
162                 LoanCause::MatchDiscriminant => {
163                     self.set.remove(&lid);
164                 }
165
166                 // do nothing for matches, etc. These can't escape
167                 _ => {}
168             }
169         }
170     }
171     fn decl_without_init(&mut self, _: NodeId, _: Span) {}
172     fn mutate(&mut self, _: NodeId, _: Span, _: cmt<'tcx>, _: MutateMode) {}
173 }
174
175 impl<'a, 'tcx: 'a> EscapeDelegate<'a, 'tcx> {
176     fn is_large_box(&self, ty: ty::Ty) -> bool {
177         // Large types need to be boxed to avoid stack
178         // overflows.
179         if ty.is_box() {
180             if let Some(inner) = self.tcx.lift(&ty.boxed_ty()) {
181                 if let Ok(layout) = inner.layout(self.tcx, self.param_env) {
182                     return layout.size(self.tcx).bytes() > self.too_large_for_stack;
183                 }
184             }
185         }
186
187         false
188     }
189 }