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