]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/escape.rs
Merge pull request #1441 from Manishearth/rustup
[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::ty::layout::TargetDataLayout;
9 use rustc::traits::Reveal;
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> {
50     set: NodeSet,
51     tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
52     tables: &'a ty::Tables<'tcx>,
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(
65         &mut self,
66         cx: &LateContext<'a, 'tcx>,
67         _: visit::FnKind<'tcx>,
68         _: &'tcx FnDecl,
69         body: &'tcx Body,
70         _: Span,
71         _id: NodeId
72     ) {
73         // we store the infcx because it is expensive to recreate
74         // the context each time.
75         let mut v = EscapeDelegate {
76             set: NodeSet(),
77             tcx: cx.tcx,
78             tables: cx.tables,
79             target: TargetDataLayout::parse(cx.sess()),
80             too_large_for_stack: self.too_large_for_stack,
81         };
82
83         let infcx = cx.tcx.borrowck_fake_infer_ctxt(body.id());
84         {
85             let mut vis = ExprUseVisitor::new(&mut v, &infcx);
86             vis.consume_body(body);
87         }
88
89         for node in v.set {
90             span_lint(cx,
91                       BOXED_LOCAL,
92                       cx.tcx.map.span(node),
93                       "local variable doesn't need to be boxed here");
94         }
95     }
96 }
97
98 impl<'a, 'tcx: 'a> Delegate<'tcx> for EscapeDelegate<'a, 'tcx> {
99     fn consume(&mut self, _: NodeId, _: Span, cmt: cmt<'tcx>, mode: ConsumeMode) {
100         if let Categorization::Local(lid) = cmt.cat {
101             if self.set.contains(&lid) {
102                 if let Move(DirectRefMove) = mode {
103                     // moved out or in. clearly can't be localized
104                     self.set.remove(&lid);
105                 }
106             }
107         }
108     }
109     fn matched_pat(&mut self, _: &Pat, _: cmt<'tcx>, _: MatchMode) {}
110     fn consume_pat(&mut self, consume_pat: &Pat, cmt: cmt<'tcx>, _: ConsumeMode) {
111         let map = &self.tcx.map;
112         if map.is_argument(consume_pat.id) {
113             // Skip closure arguments
114             if let Some(NodeExpr(..)) = map.find(map.get_parent_node(consume_pat.id)) {
115                 return;
116             }
117             if is_non_trait_box(cmt.ty) && !self.is_large_box(cmt.ty) {
118                 self.set.insert(consume_pat.id);
119             }
120             return;
121         }
122         if let Categorization::Rvalue(..) = cmt.cat {
123             if let Some(NodeStmt(st)) = map.find(map.get_parent_node(cmt.id)) {
124                 if let StmtDecl(ref decl, _) = st.node {
125                     if let DeclLocal(ref loc) = decl.node {
126                         if let Some(ref ex) = loc.init {
127                             if let ExprBox(..) = ex.node {
128                                 if is_non_trait_box(cmt.ty) && !self.is_large_box(cmt.ty) {
129                                     // let x = box (...)
130                                     self.set.insert(consume_pat.id);
131                                 }
132                                 // TODO Box::new
133                                 // TODO vec![]
134                                 // TODO "foo".to_owned() and friends
135                             }
136                         }
137                     }
138                 }
139             }
140         }
141         if let Categorization::Local(lid) = cmt.cat {
142             if self.set.contains(&lid) {
143                 // let y = x where x is known
144                 // remove x, insert y
145                 self.set.insert(consume_pat.id);
146                 self.set.remove(&lid);
147             }
148         }
149
150     }
151     fn borrow(
152         &mut self,
153         borrow_id: NodeId,
154         _: Span,
155         cmt: cmt<'tcx>,
156         _: &ty::Region,
157         _: ty::BorrowKind,
158         loan_cause: LoanCause
159     ) {
160         use rustc::ty::adjustment::Adjust;
161
162         if let Categorization::Local(lid) = cmt.cat {
163             if self.set.contains(&lid) {
164                 if let Some(&Adjust::DerefRef { autoderefs, .. }) =
165                     self.tables
166                         .adjustments
167                         .get(&borrow_id)
168                         .map(|a| &a.kind) {
169                     if LoanCause::AutoRef == loan_cause {
170                         // x.foo()
171                         if autoderefs == 0 {
172                             self.set.remove(&lid); // Used without autodereffing (i.e. x.clone())
173                         }
174                     } else {
175                         span_bug!(cmt.span, "Unknown adjusted AutoRef");
176                     }
177                 } else if LoanCause::AddrOf == loan_cause {
178                     // &x
179                     if let Some(&Adjust::DerefRef { autoderefs, .. }) =
180                         self.tables
181                             .adjustments
182                             .get(&self.tcx
183                                 .map
184                                 .get_parent_node(borrow_id))
185                             .map(|a| &a.kind) {
186                         if autoderefs <= 1 {
187                             // foo(&x) where no extra autoreffing is happening
188                             self.set.remove(&lid);
189                         }
190                     }
191
192                 } else if LoanCause::MatchDiscriminant == loan_cause {
193                     self.set.remove(&lid); // `match x` can move
194                 }
195                 // do nothing for matches, etc. These can't escape
196             }
197         }
198     }
199     fn decl_without_init(&mut self, _: NodeId, _: Span) {}
200     fn mutate(&mut self, _: NodeId, _: Span, _: cmt<'tcx>, _: MutateMode) {}
201 }
202
203 impl<'a, 'tcx: 'a> EscapeDelegate<'a, 'tcx> {
204     fn is_large_box(&self, ty: ty::Ty<'tcx>) -> bool {
205         // Large types need to be boxed to avoid stack
206         // overflows.
207         match ty.sty {
208             ty::TyBox(inner) => {
209                 self.tcx.infer_ctxt((), Reveal::All).enter(|infcx| {
210                     if let Ok(layout) = inner.layout(&infcx) {
211                         let size = layout.size(&self.target);
212                         size.bytes() > self.too_large_for_stack
213                     } else {
214                         false
215                     }
216                 })
217             },
218             _ => false,
219         }
220     }
221 }