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