]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/escape.rs
Merge remote-tracking branch 'origin/master' into examples
[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::infer::InferCtxt;
5 use rustc::lint::*;
6 use rustc::middle::expr_use_visitor::*;
7 use rustc::middle::mem_categorization::{cmt, Categorization};
8 use rustc::ty::adjustment::AutoAdjustment;
9 use rustc::ty;
10 use rustc::ty::layout::TargetDataLayout;
11 use rustc::util::nodemap::NodeSet;
12 use syntax::ast::NodeId;
13 use syntax::codemap::Span;
14 use utils::span_lint;
15
16 pub struct Pass {
17     pub too_large_for_stack: u64,
18 }
19
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 main() {
32 ///     let x = Box::new(1);
33 ///     foo(*x);
34 ///     println!("{}", *x);
35 /// }
36 /// ```
37 declare_lint! {
38     pub BOXED_LOCAL,
39     Warn,
40     "using `Box<T>` where unnecessary"
41 }
42
43 fn is_non_trait_box(ty: ty::Ty) -> bool {
44     match ty.sty {
45         ty::TyBox(inner) => !inner.is_trait(),
46         _ => false,
47     }
48 }
49
50 struct EscapeDelegate<'a, 'tcx: 'a+'gcx, 'gcx: 'a> {
51     tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
52     set: NodeSet,
53     infcx: &'a InferCtxt<'a, 'gcx, 'gcx>,
54     target: TargetDataLayout,
55     too_large_for_stack: u64,
56 }
57
58 impl LintPass for Pass {
59     fn get_lints(&self) -> LintArray {
60         lint_array!(BOXED_LOCAL)
61     }
62 }
63
64 impl LateLintPass for Pass {
65     fn check_fn(&mut self, cx: &LateContext, _: visit::FnKind, decl: &FnDecl, body: &Block, _: Span, id: NodeId) {
66         let param_env = ty::ParameterEnvironment::for_item(cx.tcx, id);
67
68         let infcx = cx.tcx.borrowck_fake_infer_ctxt(param_env);
69
70         // we store the infcx because it is expensive to recreate
71         // the context each time.
72         let mut v = EscapeDelegate {
73             tcx: cx.tcx,
74             set: NodeSet(),
75             infcx: &infcx,
76             target: TargetDataLayout::parse(cx.sess()),
77             too_large_for_stack: self.too_large_for_stack,
78         };
79
80         {
81             let mut vis = ExprUseVisitor::new(&mut v, &infcx);
82             vis.walk_fn(decl, body);
83         }
84
85         for node in v.set {
86             span_lint(cx,
87                       BOXED_LOCAL,
88                       cx.tcx.map.span(node),
89                       "local variable doesn't need to be boxed here");
90         }
91     }
92 }
93
94 impl<'a, 'tcx: 'a+'gcx, 'gcx: 'a> Delegate<'tcx> for EscapeDelegate<'a, 'tcx, 'gcx> {
95     fn consume(&mut self, _: NodeId, _: Span, cmt: cmt<'tcx>, mode: ConsumeMode) {
96         if let Categorization::Local(lid) = cmt.cat {
97             if self.set.contains(&lid) {
98                 if let Move(DirectRefMove) = mode {
99                     // moved out or in. clearly can't be localized
100                     self.set.remove(&lid);
101                 }
102             }
103         }
104     }
105     fn matched_pat(&mut self, _: &Pat, _: cmt<'tcx>, _: MatchMode) {}
106     fn consume_pat(&mut self, consume_pat: &Pat, cmt: cmt<'tcx>, _: ConsumeMode) {
107         let map = &self.tcx.map;
108         if map.is_argument(consume_pat.id) {
109             // Skip closure arguments
110             if let Some(NodeExpr(..)) = map.find(map.get_parent_node(consume_pat.id)) {
111                 return;
112             }
113             if is_non_trait_box(cmt.ty) && !self.is_large_box(cmt.ty) {
114                 self.set.insert(consume_pat.id);
115             }
116             return;
117         }
118         if let Categorization::Rvalue(..) = cmt.cat {
119             if let Some(NodeStmt(st)) = map.find(map.get_parent_node(cmt.id)) {
120                 if let StmtDecl(ref decl, _) = st.node {
121                     if let DeclLocal(ref loc) = decl.node {
122                         if let Some(ref ex) = loc.init {
123                             if let ExprBox(..) = ex.node {
124                                 if is_non_trait_box(cmt.ty) && !self.is_large_box(cmt.ty) {
125                                     // let x = box (...)
126                                     self.set.insert(consume_pat.id);
127                                 }
128                                 // TODO Box::new
129                                 // TODO vec![]
130                                 // TODO "foo".to_owned() and friends
131                             }
132                         }
133                     }
134                 }
135             }
136         }
137         if let Categorization::Local(lid) = cmt.cat {
138             if self.set.contains(&lid) {
139                 // let y = x where x is known
140                 // remove x, insert y
141                 self.set.insert(consume_pat.id);
142                 self.set.remove(&lid);
143             }
144         }
145
146     }
147     fn borrow(&mut self, borrow_id: NodeId, _: Span, cmt: cmt<'tcx>, _: &ty::Region, _: ty::BorrowKind,
148               loan_cause: LoanCause) {
149
150         if let Categorization::Local(lid) = cmt.cat {
151             if self.set.contains(&lid) {
152                 if let Some(&AutoAdjustment::AdjustDerefRef(adj)) = self.tcx
153                                                                         .tables
154                                                                         .borrow()
155                                                                         .adjustments
156                                                                         .get(&borrow_id) {
157                     if LoanCause::AutoRef == loan_cause {
158                         // x.foo()
159                         if adj.autoderefs == 0 {
160                             self.set.remove(&lid); // Used without autodereffing (i.e. x.clone())
161                         }
162                     } else {
163                         span_bug!(cmt.span, "Unknown adjusted AutoRef");
164                     }
165                 } else if LoanCause::AddrOf == loan_cause {
166                     // &x
167                     if let Some(&AutoAdjustment::AdjustDerefRef(adj)) = self.tcx
168                                                                             .tables
169                                                                             .borrow()
170                                                                             .adjustments
171                                                                             .get(&self.tcx
172                                                                                       .map
173                                                                                       .get_parent_node(borrow_id)) {
174                         if adj.autoderefs <= 1 {
175                             // foo(&x) where no extra autoreffing is happening
176                             self.set.remove(&lid);
177                         }
178                     }
179
180                 } else if LoanCause::MatchDiscriminant == loan_cause {
181                     self.set.remove(&lid); // `match x` can move
182                 }
183                 // do nothing for matches, etc. These can't escape
184             }
185         }
186     }
187     fn decl_without_init(&mut self, _: NodeId, _: Span) {}
188     fn mutate(&mut self, _: NodeId, _: Span, _: cmt<'tcx>, _: MutateMode) {}
189 }
190
191 impl<'a, 'tcx: 'a+'gcx, 'gcx: 'a> EscapeDelegate<'a, 'tcx, 'gcx> {
192     fn is_large_box(&self, ty: ty::Ty<'gcx>) -> bool {
193         // Large types need to be boxed to avoid stack
194         // overflows.
195         match ty.sty {
196             ty::TyBox(inner) => {
197                 if let Ok(layout) = inner.layout(self.infcx) {
198                     let size = layout.size(&self.target);
199                     size.bytes() > self.too_large_for_stack
200                 } else {
201                     false
202                 }
203             },
204             _ => false,
205         }
206     }
207 }