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