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