]> git.lizzy.rs Git - rust.git/blob - src/escape.rs
Add a lint to suggest uint == 0 over uint <= 0
[rust.git] / src / escape.rs
1 use rustc::lint::*;
2 use rustc::front::map::Node::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_box(ty: ty::Ty) -> bool {
35     match ty.sty {
36         ty::TyBox(..) => true,
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         if self.cx.tcx.map.is_argument(consume_pat.id) {
88             if is_box(cmt.ty) {
89                 self.set.insert(consume_pat.id);
90             }
91             return;
92         }
93         if let Categorization::Rvalue(..) = cmt.cat {
94             if let Some(NodeStmt(st)) = self.cx
95                                                   .tcx
96                                                   .map
97                                                   .find(self.cx.tcx.map.get_parent_node(cmt.id)) {
98                 if let StmtDecl(ref decl, _) = st.node {
99                     if let DeclLocal(ref loc) = decl.node {
100                         if let Some(ref ex) = loc.init {
101                             if let ExprBox(..) = ex.node {
102                                 if is_box(cmt.ty) {
103                                     // let x = box (...)
104                                     self.set.insert(consume_pat.id);
105                                 }
106                                 // TODO Box::new
107                                 // TODO vec![]
108                                 // TODO "foo".to_owned() and friends
109                             }
110                         }
111                     }
112                 }
113             }
114         }
115         if let Categorization::Local(lid) = cmt.cat {
116             if self.set.contains(&lid) {
117                 // let y = x where x is known
118                 // remove x, insert y
119                 self.set.insert(consume_pat.id);
120                 self.set.remove(&lid);
121             }
122         }
123
124     }
125     fn borrow(&mut self, borrow_id: NodeId, _: Span, cmt: cmt<'tcx>, _: ty::Region, _: ty::BorrowKind,
126               loan_cause: LoanCause) {
127
128         if let Categorization::Local(lid) = cmt.cat {
129             if self.set.contains(&lid) {
130                 if let Some(&AutoAdjustment::AdjustDerefRef(adj)) = self.cx
131                                                                         .tcx
132                                                                         .tables
133                                                                         .borrow()
134                                                                         .adjustments
135                                                                         .get(&borrow_id) {
136                     if LoanCause::AutoRef == loan_cause {
137                         // x.foo()
138                         if adj.autoderefs == 0 {
139                             self.set.remove(&lid); // Used without autodereffing (i.e. x.clone())
140                         }
141                     } else {
142                         self.cx.sess().span_bug(cmt.span, "Unknown adjusted AutoRef");
143                     }
144                 } else if LoanCause::AddrOf == loan_cause {
145                     // &x
146                     if let Some(&AutoAdjustment::AdjustDerefRef(adj)) = self.cx
147                                                                             .tcx
148                                                                             .tables
149                                                                             .borrow()
150                                                                             .adjustments
151                                                                             .get(&self.cx
152                                                                                       .tcx
153                                                                                       .map
154                                                                                       .get_parent_node(borrow_id)) {
155                         if adj.autoderefs <= 1 {
156                             // foo(&x) where no extra autoreffing is happening
157                             self.set.remove(&lid);
158                         }
159                     }
160
161                 } else if LoanCause::MatchDiscriminant == loan_cause {
162                     self.set.remove(&lid); // `match x` can move
163                 }
164                 // do nothing for matches, etc. These can't escape
165             }
166         }
167     }
168     fn decl_without_init(&mut self, _: NodeId, _: Span) {}
169     fn mutate(&mut self, _: NodeId, _: Span, _: cmt<'tcx>, _: MutateMode) {}
170 }