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