]> git.lizzy.rs Git - rust.git/blob - src/escape.rs
Merge pull request #689 from mcarton/entries
[rust.git] / src / escape.rs
1 use rustc::front::map::Node::{NodeExpr, NodeStmt};
2 use rustc::lint::*;
3 use rustc::middle::expr_use_visitor::*;
4 use rustc::middle::infer;
5 use rustc::middle::mem_categorization::{cmt, Categorization};
6 use rustc::middle::ty::adjustment::AutoAdjustment;
7 use rustc::middle::ty;
8 use rustc::util::nodemap::NodeSet;
9 use rustc_front::hir::*;
10 use rustc_front::intravisit as visit;
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. It is only necessary to allocate if you wish to move the box into something.
20 ///
21 /// **Known problems:** None
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! {
33     pub BOXED_LOCAL, Warn, "using Box<T> where unnecessary"
34 }
35
36 fn is_non_trait_box(ty: ty::Ty) -> bool {
37     match ty.sty {
38         ty::TyBox(ref inner) => !inner.is_trait(),
39         _ => false,
40     }
41 }
42
43 struct EscapeDelegate<'a, 'tcx: 'a> {
44     cx: &'a LateContext<'a, 'tcx>,
45     set: NodeSet,
46 }
47
48 impl LintPass for EscapePass {
49     fn get_lints(&self) -> LintArray {
50         lint_array!(BOXED_LOCAL)
51     }
52 }
53
54 impl LateLintPass for EscapePass {
55     fn check_fn(&mut self, cx: &LateContext, _: visit::FnKind, decl: &FnDecl, body: &Block, _: Span, id: NodeId) {
56         let param_env = ty::ParameterEnvironment::for_item(cx.tcx, id);
57         let infcx = infer::new_infer_ctxt(cx.tcx, &cx.tcx.tables, Some(param_env));
58         let mut v = EscapeDelegate {
59             cx: cx,
60             set: NodeSet(),
61         };
62         {
63             let mut vis = ExprUseVisitor::new(&mut v, &infcx);
64             vis.walk_fn(decl, body);
65         }
66         for node in v.set {
67             span_lint(cx,
68                       BOXED_LOCAL,
69                       cx.tcx.map.span(node),
70                       "local variable doesn't need to be boxed here");
71         }
72     }
73 }
74
75 impl<'a, 'tcx: 'a> Delegate<'tcx> for EscapeDelegate<'a, 'tcx> {
76     fn consume(&mut self, _: NodeId, _: Span, cmt: cmt<'tcx>, 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         let map = &self.cx.tcx.map;
90         if map.is_argument(consume_pat.id) {
91             // Skip closure arguments
92             if let Some(NodeExpr(..)) = map.find(map.get_parent_node(consume_pat.id)) {
93                 return;
94             }
95             if is_non_trait_box(cmt.ty) {
96                 self.set.insert(consume_pat.id);
97             }
98             return;
99         }
100         if let Categorization::Rvalue(..) = cmt.cat {
101             if let Some(NodeStmt(st)) = map.find(map.get_parent_node(cmt.id)) {
102                 if let StmtDecl(ref decl, _) = st.node {
103                     if let DeclLocal(ref loc) = decl.node {
104                         if let Some(ref ex) = loc.init {
105                             if let ExprBox(..) = ex.node {
106                                 if is_non_trait_box(cmt.ty) {
107                                     // let x = box (...)
108                                     self.set.insert(consume_pat.id);
109                                 }
110                                 // TODO Box::new
111                                 // TODO vec![]
112                                 // TODO "foo".to_owned() and friends
113                             }
114                         }
115                     }
116                 }
117             }
118         }
119         if let Categorization::Local(lid) = cmt.cat {
120             if self.set.contains(&lid) {
121                 // let y = x where x is known
122                 // remove x, insert y
123                 self.set.insert(consume_pat.id);
124                 self.set.remove(&lid);
125             }
126         }
127
128     }
129     fn borrow(&mut self, borrow_id: NodeId, _: Span, cmt: cmt<'tcx>, _: ty::Region, _: ty::BorrowKind,
130               loan_cause: LoanCause) {
131
132         if let Categorization::Local(lid) = cmt.cat {
133             if self.set.contains(&lid) {
134                 if let Some(&AutoAdjustment::AdjustDerefRef(adj)) = self.cx
135                                                                         .tcx
136                                                                         .tables
137                                                                         .borrow()
138                                                                         .adjustments
139                                                                         .get(&borrow_id) {
140                     if LoanCause::AutoRef == loan_cause {
141                         // x.foo()
142                         if adj.autoderefs == 0 {
143                             self.set.remove(&lid); // Used without autodereffing (i.e. x.clone())
144                         }
145                     } else {
146                         self.cx.sess().span_bug(cmt.span, "Unknown adjusted AutoRef");
147                     }
148                 } else if LoanCause::AddrOf == loan_cause {
149                     // &x
150                     if let Some(&AutoAdjustment::AdjustDerefRef(adj)) = self.cx
151                                                                             .tcx
152                                                                             .tables
153                                                                             .borrow()
154                                                                             .adjustments
155                                                                             .get(&self.cx
156                                                                                       .tcx
157                                                                                       .map
158                                                                                       .get_parent_node(borrow_id)) {
159                         if adj.autoderefs <= 1 {
160                             // foo(&x) where no extra autoreffing is happening
161                             self.set.remove(&lid);
162                         }
163                     }
164
165                 } else if LoanCause::MatchDiscriminant == loan_cause {
166                     self.set.remove(&lid); // `match x` can move
167                 }
168                 // do nothing for matches, etc. These can't escape
169             }
170         }
171     }
172     fn decl_without_init(&mut self, _: NodeId, _: Span) {}
173     fn mutate(&mut self, _: NodeId, _: Span, _: cmt<'tcx>, _: MutateMode) {}
174 }