]> git.lizzy.rs Git - rust.git/blob - src/escape.rs
fixed #606
[rust.git] / src / escape.rs
1 use rustc::lint::*;
2 use rustc::front::map::Node::{NodeExpr, NodeStmt};
3 use rustc_front::hir::*;
4 use rustc_front::intravisit as visit;
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. It is `Warn` by default.
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!(pub BOXED_LOCAL, Warn, "using Box<T> where unnecessary");
33
34 fn is_non_trait_box(ty: ty::Ty) -> bool {
35     match ty.sty {
36         ty::TyBox(ref inner) => !inner.is_trait(),
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, cx: &LateContext, _: visit::FnKind, decl: &FnDecl, body: &Block, _: Span, id: NodeId) {
54         let param_env = ty::ParameterEnvironment::for_item(cx.tcx, id);
55         let infcx = infer::new_infer_ctxt(cx.tcx, &cx.tcx.tables, Some(param_env));
56         let mut v = EscapeDelegate {
57             cx: cx,
58             set: NodeSet(),
59         };
60         {
61             let mut vis = ExprUseVisitor::new(&mut v, &infcx);
62             vis.walk_fn(decl, body);
63         }
64         for node in v.set {
65             span_lint(cx,
66                       BOXED_LOCAL,
67                       cx.tcx.map.span(node),
68                       "local variable doesn't need to be boxed here");
69         }
70     }
71 }
72
73 impl<'a, 'tcx: 'a> Delegate<'tcx> for EscapeDelegate<'a, 'tcx> {
74     fn consume(&mut self, _: NodeId, _: Span, cmt: cmt<'tcx>, mode: ConsumeMode) {
75
76         if let Categorization::Local(lid) = cmt.cat {
77             if self.set.contains(&lid) {
78                 if let Move(DirectRefMove) = mode {
79                     // moved out or in. clearly can't be localized
80                     self.set.remove(&lid);
81                 }
82             }
83         }
84     }
85     fn matched_pat(&mut self, _: &Pat, _: cmt<'tcx>, _: MatchMode) {}
86     fn consume_pat(&mut self, consume_pat: &Pat, cmt: cmt<'tcx>, _: ConsumeMode) {
87         let map = &self.cx.tcx.map;
88         if map.is_argument(consume_pat.id) {
89             // Skip closure arguments
90             if let Some(NodeExpr(..)) = map.find(map.get_parent_node(consume_pat.id)) {
91                 return;
92             }
93             if is_non_trait_box(cmt.ty) {
94                 self.set.insert(consume_pat.id);
95             }
96             return;
97         }
98         if let Categorization::Rvalue(..) = cmt.cat {
99             if let Some(NodeStmt(st)) = map.find(map.get_parent_node(cmt.id)) {
100                 if let StmtDecl(ref decl, _) = st.node {
101                     if let DeclLocal(ref loc) = decl.node {
102                         if let Some(ref ex) = loc.init {
103                             if let ExprBox(..) = ex.node {
104                                 if is_non_trait_box(cmt.ty) {
105                                     // let x = box (...)
106                                     self.set.insert(consume_pat.id);
107                                 }
108                                 // TODO Box::new
109                                 // TODO vec![]
110                                 // TODO "foo".to_owned() and friends
111                             }
112                         }
113                     }
114                 }
115             }
116         }
117         if let Categorization::Local(lid) = cmt.cat {
118             if self.set.contains(&lid) {
119                 // let y = x where x is known
120                 // remove x, insert y
121                 self.set.insert(consume_pat.id);
122                 self.set.remove(&lid);
123             }
124         }
125
126     }
127     fn borrow(&mut self, borrow_id: NodeId, _: Span, cmt: cmt<'tcx>, _: ty::Region, _: 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)) = self.cx
149                                                                             .tcx
150                                                                             .tables
151                                                                             .borrow()
152                                                                             .adjustments
153                                                                             .get(&self.cx
154                                                                                       .tcx
155                                                                                       .map
156                                                                                       .get_parent_node(borrow_id)) {
157                         if adj.autoderefs <= 1 {
158                             // foo(&x) where no extra autoreffing is happening
159                             self.set.remove(&lid);
160                         }
161                     }
162
163                 } else if LoanCause::MatchDiscriminant == loan_cause {
164                     self.set.remove(&lid); // `match x` can move
165                 }
166                 // do nothing for matches, etc. These can't escape
167             }
168         }
169     }
170     fn decl_without_init(&mut self, _: NodeId, _: Span) {}
171     fn mutate(&mut self, _: NodeId, _: Span, _: cmt<'tcx>, _: MutateMode) {}
172 }