]> git.lizzy.rs Git - rust.git/blob - src/escape.rs
Update rust-clippy to rustc 1.9.0-nightly (d5a91e695 2016-03-26)
[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::infer;
5 use rustc::middle::mem_categorization::{cmt, Categorization};
6 use rustc::traits::ProjectionMode;
7 use rustc::ty::adjustment::AutoAdjustment;
8 use rustc::ty;
9 use rustc::util::nodemap::NodeSet;
10 use rustc_front::hir::*;
11 use rustc_front::intravisit as visit;
12 use syntax::ast::NodeId;
13 use syntax::codemap::Span;
14 use utils::span_lint;
15
16 pub struct EscapePass;
17
18 /// **What it does:** This lint checks for usage of `Box<T>` where an unboxed `T` would work fine.
19 ///
20 /// **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.
21 ///
22 /// **Known problems:** None
23 ///
24 /// **Example:**
25 ///
26 /// ```rust
27 /// fn main() {
28 ///     let x = Box::new(1);
29 ///     foo(*x);
30 ///     println!("{}", *x);
31 /// }
32 /// ```
33 declare_lint! {
34     pub BOXED_LOCAL, Warn, "using Box<T> where unnecessary"
35 }
36
37 fn is_non_trait_box(ty: ty::Ty) -> bool {
38     match ty.sty {
39         ty::TyBox(ref inner) => !inner.is_trait(),
40         _ => false,
41     }
42 }
43
44 struct EscapeDelegate<'a, 'tcx: 'a> {
45     cx: &'a LateContext<'a, 'tcx>,
46     set: NodeSet,
47 }
48
49 impl LintPass for EscapePass {
50     fn get_lints(&self) -> LintArray {
51         lint_array!(BOXED_LOCAL)
52     }
53 }
54
55 impl LateLintPass for EscapePass {
56     fn check_fn(&mut self, cx: &LateContext, _: visit::FnKind, decl: &FnDecl, body: &Block, _: Span, id: NodeId) {
57         let param_env = ty::ParameterEnvironment::for_item(cx.tcx, id);
58         let infcx = infer::new_infer_ctxt(cx.tcx, &cx.tcx.tables, Some(param_env), ProjectionMode::Any);
59         let mut v = EscapeDelegate {
60             cx: cx,
61             set: NodeSet(),
62         };
63         {
64             let mut vis = ExprUseVisitor::new(&mut v, &infcx);
65             vis.walk_fn(decl, body);
66         }
67         for node in v.set {
68             span_lint(cx,
69                       BOXED_LOCAL,
70                       cx.tcx.map.span(node),
71                       "local variable doesn't need to be boxed here");
72         }
73     }
74 }
75
76 impl<'a, 'tcx: 'a> Delegate<'tcx> for EscapeDelegate<'a, 'tcx> {
77     fn consume(&mut self, _: NodeId, _: Span, cmt: cmt<'tcx>, 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         let map = &self.cx.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.cx
136                                                                         .tcx
137                                                                         .tables
138                                                                         .borrow()
139                                                                         .adjustments
140                                                                         .get(&borrow_id) {
141                     if LoanCause::AutoRef == loan_cause {
142                         // x.foo()
143                         if adj.autoderefs == 0 {
144                             self.set.remove(&lid); // Used without autodereffing (i.e. x.clone())
145                         }
146                     } else {
147                         self.cx.sess().span_bug(cmt.span, "Unknown adjusted AutoRef");
148                     }
149                 } else if LoanCause::AddrOf == loan_cause {
150                     // &x
151                     if let Some(&AutoAdjustment::AdjustDerefRef(adj)) = self.cx
152                                                                             .tcx
153                                                                             .tables
154                                                                             .borrow()
155                                                                             .adjustments
156                                                                             .get(&self.cx
157                                                                                       .tcx
158                                                                                       .map
159                                                                                       .get_parent_node(borrow_id)) {
160                         if adj.autoderefs <= 1 {
161                             // foo(&x) where no extra autoreffing is happening
162                             self.set.remove(&lid);
163                         }
164                     }
165
166                 } else if LoanCause::MatchDiscriminant == loan_cause {
167                     self.set.remove(&lid); // `match x` can move
168                 }
169                 // do nothing for matches, etc. These can't escape
170             }
171         }
172     }
173     fn decl_without_init(&mut self, _: NodeId, _: Span) {}
174     fn mutate(&mut self, _: NodeId, _: Span, _: cmt<'tcx>, _: MutateMode) {}
175 }