]> git.lizzy.rs Git - rust.git/blob - src/escape.rs
Merge pull request #940 from oli-obk/simplify/mut_mut
[rust.git] / src / escape.rs
1 use rustc::hir::*;
2 use rustc::hir::intravisit as visit;
3 use rustc::hir::map::Node::{NodeExpr, NodeStmt};
4 use rustc::lint::*;
5 use rustc::middle::expr_use_visitor::*;
6 use rustc::middle::mem_categorization::{cmt, Categorization};
7 use rustc::ty::adjustment::AutoAdjustment;
8 use rustc::ty;
9 use rustc::util::nodemap::NodeSet;
10 use syntax::ast::NodeId;
11 use syntax::codemap::Span;
12 use utils::span_lint;
13
14 pub struct EscapePass;
15
16 /// **What it does:** This lint checks for usage of `Box<T>` where an unboxed `T` would work fine.
17 ///
18 /// **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.
19 ///
20 /// **Known problems:** None
21 ///
22 /// **Example:**
23 ///
24 /// ```rust
25 /// fn main() {
26 ///     let x = Box::new(1);
27 ///     foo(*x);
28 ///     println!("{}", *x);
29 /// }
30 /// ```
31 declare_lint! {
32     pub BOXED_LOCAL, Warn, "using `Box<T>` where unnecessary"
33 }
34
35 fn is_non_trait_box(ty: ty::Ty) -> bool {
36     match ty.sty {
37         ty::TyBox(ref inner) => !inner.is_trait(),
38         _ => false,
39     }
40 }
41
42 struct EscapeDelegate<'a, 'tcx: 'a> {
43     tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
44     set: NodeSet,
45 }
46
47 impl LintPass for EscapePass {
48     fn get_lints(&self) -> LintArray {
49         lint_array!(BOXED_LOCAL)
50     }
51 }
52
53 impl LateLintPass for EscapePass {
54     fn check_fn(&mut self, cx: &LateContext, _: visit::FnKind, decl: &FnDecl, body: &Block, _: Span, id: NodeId) {
55         let param_env = ty::ParameterEnvironment::for_item(cx.tcx, id);
56
57         let infcx = cx.tcx.borrowck_fake_infer_ctxt(param_env);
58         let mut v = EscapeDelegate {
59             tcx: cx.tcx,
60             set: NodeSet(),
61         };
62
63         {
64             let mut vis = ExprUseVisitor::new(&mut v, &infcx);
65             vis.walk_fn(decl, body);
66         }
67
68         for node in v.set {
69             span_lint(cx,
70                       BOXED_LOCAL,
71                       cx.tcx.map.span(node),
72                       "local variable doesn't need to be boxed here");
73         }
74     }
75 }
76
77 impl<'a, 'tcx: 'a> Delegate<'tcx> for EscapeDelegate<'a, 'tcx> {
78     fn consume(&mut self, _: NodeId, _: Span, cmt: cmt<'tcx>, mode: ConsumeMode) {
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         let map = &self.tcx.map;
91         if map.is_argument(consume_pat.id) {
92             // Skip closure arguments
93             if let Some(NodeExpr(..)) = map.find(map.get_parent_node(consume_pat.id)) {
94                 return;
95             }
96             if is_non_trait_box(cmt.ty) {
97                 self.set.insert(consume_pat.id);
98             }
99             return;
100         }
101         if let Categorization::Rvalue(..) = cmt.cat {
102             if let Some(NodeStmt(st)) = map.find(map.get_parent_node(cmt.id)) {
103                 if let StmtDecl(ref decl, _) = st.node {
104                     if let DeclLocal(ref loc) = decl.node {
105                         if let Some(ref ex) = loc.init {
106                             if let ExprBox(..) = ex.node {
107                                 if is_non_trait_box(cmt.ty) {
108                                     // let x = box (...)
109                                     self.set.insert(consume_pat.id);
110                                 }
111                                 // TODO Box::new
112                                 // TODO vec![]
113                                 // TODO "foo".to_owned() and friends
114                             }
115                         }
116                     }
117                 }
118             }
119         }
120         if let Categorization::Local(lid) = cmt.cat {
121             if self.set.contains(&lid) {
122                 // let y = x where x is known
123                 // remove x, insert y
124                 self.set.insert(consume_pat.id);
125                 self.set.remove(&lid);
126             }
127         }
128
129     }
130     fn borrow(&mut self, borrow_id: NodeId, _: Span, cmt: cmt<'tcx>, _: ty::Region, _: ty::BorrowKind,
131               loan_cause: LoanCause) {
132
133         if let Categorization::Local(lid) = cmt.cat {
134             if self.set.contains(&lid) {
135                 if let Some(&AutoAdjustment::AdjustDerefRef(adj)) = self.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                         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.tcx
151                                                                             .tables
152                                                                             .borrow()
153                                                                             .adjustments
154                                                                             .get(&self.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 }