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