]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/escape.rs
also run rustfmt on clippy-lints
[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<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
64     fn check_fn(&mut self, cx: &LateContext<'a, 'tcx>, _: visit::FnKind<'tcx>, decl: &'tcx FnDecl, body: &'tcx Expr,
65                 _: 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         use rustc::ty::adjustment::Adjust;
150
151         if let Categorization::Local(lid) = cmt.cat {
152             if self.set.contains(&lid) {
153                 if let Some(&Adjust::DerefRef { autoderefs, .. }) =
154                     self.tcx
155                         .tables
156                         .borrow()
157                         .adjustments
158                         .get(&borrow_id)
159                         .map(|a| &a.kind) {
160                     if LoanCause::AutoRef == loan_cause {
161                         // x.foo()
162                         if autoderefs == 0 {
163                             self.set.remove(&lid); // Used without autodereffing (i.e. x.clone())
164                         }
165                     } else {
166                         span_bug!(cmt.span, "Unknown adjusted AutoRef");
167                     }
168                 } else if LoanCause::AddrOf == loan_cause {
169                     // &x
170                     if let Some(&Adjust::DerefRef { autoderefs, .. }) =
171                         self.tcx
172                             .tables
173                             .borrow()
174                             .adjustments
175                             .get(&self.tcx
176                                 .map
177                                 .get_parent_node(borrow_id))
178                             .map(|a| &a.kind) {
179                         if autoderefs <= 1 {
180                             // foo(&x) where no extra autoreffing is happening
181                             self.set.remove(&lid);
182                         }
183                     }
184
185                 } else if LoanCause::MatchDiscriminant == loan_cause {
186                     self.set.remove(&lid); // `match x` can move
187                 }
188                 // do nothing for matches, etc. These can't escape
189             }
190         }
191     }
192     fn decl_without_init(&mut self, _: NodeId, _: Span) {}
193     fn mutate(&mut self, _: NodeId, _: Span, _: cmt<'tcx>, _: MutateMode) {}
194 }
195
196 impl<'a, 'tcx: 'a + 'gcx, 'gcx: 'a> EscapeDelegate<'a, 'tcx, 'gcx> {
197     fn is_large_box(&self, ty: ty::Ty<'gcx>) -> bool {
198         // Large types need to be boxed to avoid stack
199         // overflows.
200         match ty.sty {
201             ty::TyBox(inner) => {
202                 if let Ok(layout) = inner.layout(self.infcx) {
203                     let size = layout.size(&self.target);
204                     size.bytes() > self.too_large_for_stack
205                 } else {
206                     false
207                 }
208             },
209             _ => false,
210         }
211     }
212 }