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