]> git.lizzy.rs Git - rust.git/blob - src/escape.rs
Merge pull request #499 from devonhollowood/underscore_binding
[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 struct EscapeDelegate<'a, 'tcx: 'a> {
35     cx: &'a LateContext<'a, 'tcx>,
36     set: NodeSet,
37 }
38
39 impl LintPass for EscapePass {
40     fn get_lints(&self) -> LintArray {
41         lint_array!(BOXED_LOCAL)
42     }
43 }
44
45 impl LateLintPass for EscapePass {
46     fn check_fn(&mut self,
47                 cx: &LateContext,
48                 _: visit::FnKind,
49                 decl: &FnDecl,
50                 body: &Block,
51                 _: Span,
52                 id: NodeId) {
53         let param_env = ty::ParameterEnvironment::for_item(cx.tcx, id);
54         let infcx = infer::new_infer_ctxt(cx.tcx, &cx.tcx.tables, Some(param_env), false);
55         let mut v = EscapeDelegate {
56             cx: cx,
57             set: NodeSet(),
58         };
59         {
60             let mut vis = ExprUseVisitor::new(&mut v, &infcx);
61             vis.walk_fn(decl, body);
62         }
63         for node in v.set {
64             span_lint(cx,
65                       BOXED_LOCAL,
66                       cx.tcx.map.span(node),
67                       "local variable doesn't need to be boxed here");
68         }
69     }
70 }
71
72 impl<'a, 'tcx: 'a> Delegate<'tcx> for EscapeDelegate<'a, 'tcx> {
73     fn consume(&mut self,
74                _: NodeId,
75                _: Span,
76                cmt: cmt<'tcx>,
77                mode: ConsumeMode) {
78
79         if let Categorization::Local(lid) = cmt.cat {
80             if self.set.contains(&lid) {
81                 if let Move(DirectRefMove) = mode {
82                     // moved out or in. clearly can't be localized
83                     self.set.remove(&lid);
84                 }
85             }
86         }
87     }
88     fn matched_pat(&mut self, _: &Pat, _: cmt<'tcx>, _: MatchMode) {}
89     fn consume_pat(&mut self, consume_pat: &Pat, cmt: cmt<'tcx>, _: ConsumeMode) {
90         if let Categorization::Rvalue(..) = cmt.cat {
91             if let Some(Node::NodeStmt(st)) = self.cx
92                                                   .tcx
93                                                   .map
94                                                   .find(self.cx.tcx.map.get_parent_node(cmt.id)) {
95                 if let StmtDecl(ref decl, _) = st.node {
96                     if let DeclLocal(ref loc) = decl.node {
97                         if let Some(ref ex) = loc.init {
98                             if let ExprBox(..) = ex.node {
99                                 if let ty::TyBox(..) = cmt.ty.sty {
100                                     // let x = box (...)
101                                     self.set.insert(consume_pat.id);
102                                 }
103                                 // TODO Box::new
104                                 // TODO vec![]
105                                 // TODO "foo".to_owned() and friends
106                             }
107                         }
108                     }
109                 }
110             }
111         }
112         if let Categorization::Local(lid) = cmt.cat {
113             if self.set.contains(&lid) {
114                 // let y = x where x is known
115                 // remove x, insert y
116                 self.set.insert(consume_pat.id);
117                 self.set.remove(&lid);
118             }
119         }
120
121     }
122     fn borrow(&mut self,
123               borrow_id: NodeId,
124               _: Span,
125               cmt: cmt<'tcx>,
126               _: ty::Region,
127               _: ty::BorrowKind,
128               loan_cause: LoanCause) {
129
130         if let Categorization::Local(lid) = cmt.cat {
131             if self.set.contains(&lid) {
132                 if let Some(&AutoAdjustment::AdjustDerefRef(adj)) = self.cx
133                                                                         .tcx
134                                                                         .tables
135                                                                         .borrow()
136                                                                         .adjustments
137                                                                         .get(&borrow_id) {
138                     if LoanCause::AutoRef == loan_cause {
139                         // x.foo()
140                         if adj.autoderefs <= 0 {
141                             self.set.remove(&lid); // Used without autodereffing (i.e. x.clone())
142                         }
143                     } else {
144                         self.cx.sess().span_bug(cmt.span, "Unknown adjusted AutoRef");
145                     }
146                 } else if LoanCause::AddrOf == loan_cause {
147                     // &x
148                     if let Some(&AutoAdjustment::AdjustDerefRef(adj)) =
149                            self.cx.tcx.tables.borrow().adjustments
150                                .get(&self.cx.tcx.map.get_parent_node(borrow_id)) {
151                         if adj.autoderefs <= 1 {
152                             // foo(&x) where no extra autoreffing is happening
153                             self.set.remove(&lid);
154                         }
155                     }
156
157                 } else if LoanCause::MatchDiscriminant == loan_cause {
158                     self.set.remove(&lid); // `match x` can move
159                 }
160                 // do nothing for matches, etc. These can't escape
161             }
162         }
163     }
164     fn decl_without_init(&mut self, _: NodeId, _: Span) {}
165     fn mutate(&mut self,
166               _: NodeId,
167               _: Span,
168               _: cmt<'tcx>,
169               _: MutateMode) {
170     }
171 }