]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/escape.rs
Update for rustc 1.19.0-nightly (4bf5c99af 2017-06-10).
[rust.git] / clippy_lints / 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;
8 use rustc::util::nodemap::NodeSet;
9 use syntax::ast::NodeId;
10 use syntax::codemap::Span;
11 use utils::{span_lint, type_size};
12
13 pub struct Pass {
14     pub too_large_for_stack: u64,
15 }
16
17 /// **What it does:** Checks for usage of `Box<T>` where an unboxed `T` would
18 /// work fine.
19 ///
20 /// **Why is this bad?** This is an unnecessary allocation, and bad for
21 /// performance. It is only necessary to allocate if you wish to move the box
22 /// into something.
23 ///
24 /// **Known problems:** None.
25 ///
26 /// **Example:**
27 /// ```rust
28 /// fn main() {
29 ///     let x = Box::new(1);
30 ///     foo(*x);
31 ///     println!("{}", *x);
32 /// }
33 /// ```
34 declare_lint! {
35     pub BOXED_LOCAL,
36     Warn,
37     "using `Box<T>` where unnecessary"
38 }
39
40 fn is_non_trait_box(ty: ty::Ty) -> bool {
41     ty.is_box() && !ty.boxed_ty().is_trait()
42 }
43
44 struct EscapeDelegate<'a, 'tcx: 'a> {
45     cx: &'a LateContext<'a, 'tcx>,
46     set: NodeSet,
47     too_large_for_stack: u64,
48 }
49
50 impl LintPass for Pass {
51     fn get_lints(&self) -> LintArray {
52         lint_array!(BOXED_LOCAL)
53     }
54 }
55
56 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
57     fn check_fn(
58         &mut self,
59         cx: &LateContext<'a, 'tcx>,
60         _: visit::FnKind<'tcx>,
61         _: &'tcx FnDecl,
62         body: &'tcx Body,
63         _: Span,
64         node_id: NodeId
65     ) {
66         let fn_def_id = cx.tcx.hir.local_def_id(node_id);
67         let mut v = EscapeDelegate {
68             cx: cx,
69             set: NodeSet(),
70             too_large_for_stack: self.too_large_for_stack,
71         };
72
73         let region_maps = &cx.tcx.region_maps(fn_def_id);
74         ExprUseVisitor::new(&mut v, cx.tcx, cx.param_env, region_maps, cx.tables)
75             .consume_body(body);
76
77         for node in v.set {
78             span_lint(cx,
79                       BOXED_LOCAL,
80                       cx.tcx.hir.span(node),
81                       "local variable doesn't need to be boxed here");
82         }
83     }
84 }
85
86 impl<'a, 'tcx> Delegate<'tcx> for EscapeDelegate<'a, 'tcx> {
87     fn consume(&mut self, _: NodeId, _: Span, cmt: cmt<'tcx>, mode: ConsumeMode) {
88         if let Categorization::Local(lid) = cmt.cat {
89             if let Move(DirectRefMove) = mode {
90                 // moved out or in. clearly can't be localized
91                 self.set.remove(&lid);
92             }
93         }
94     }
95     fn matched_pat(&mut self, _: &Pat, _: cmt<'tcx>, _: MatchMode) {}
96     fn consume_pat(&mut self, consume_pat: &Pat, cmt: cmt<'tcx>, _: ConsumeMode) {
97         let map = &self.cx.tcx.hir;
98         if map.is_argument(consume_pat.id) {
99             // Skip closure arguments
100             if let Some(NodeExpr(..)) = map.find(map.get_parent_node(consume_pat.id)) {
101                 return;
102             }
103             if is_non_trait_box(cmt.ty) && !self.is_large_box(cmt.ty) {
104                 self.set.insert(consume_pat.id);
105             }
106             return;
107         }
108         if let Categorization::Rvalue(..) = cmt.cat {
109             if let Some(NodeStmt(st)) = map.find(map.get_parent_node(cmt.id)) {
110                 if let StmtDecl(ref decl, _) = st.node {
111                     if let DeclLocal(ref loc) = decl.node {
112                         if let Some(ref ex) = loc.init {
113                             if let ExprBox(..) = ex.node {
114                                 if is_non_trait_box(cmt.ty) && !self.is_large_box(cmt.ty) {
115                                     // let x = box (...)
116                                     self.set.insert(consume_pat.id);
117                                 }
118                                 // TODO Box::new
119                                 // TODO vec![]
120                                 // TODO "foo".to_owned() and friends
121                             }
122                         }
123                     }
124                 }
125             }
126         }
127         if let Categorization::Local(lid) = cmt.cat {
128             if self.set.contains(&lid) {
129                 // let y = x where x is known
130                 // remove x, insert y
131                 self.set.insert(consume_pat.id);
132                 self.set.remove(&lid);
133             }
134         }
135
136     }
137     fn borrow(
138         &mut self,
139         _: NodeId,
140         _: Span,
141         cmt: cmt<'tcx>,
142         _: ty::Region,
143         _: ty::BorrowKind,
144         loan_cause: LoanCause
145     ) {
146         if let Categorization::Local(lid) = cmt.cat {
147             match loan_cause {
148                 // x.foo()
149                 // Used without autodereffing (i.e. x.clone())
150                 LoanCause::AutoRef |
151
152                 // &x
153                 // foo(&x) where no extra autoreffing is happening
154                 LoanCause::AddrOf |
155
156                 // `match x` can move
157                 LoanCause::MatchDiscriminant => {
158                     self.set.remove(&lid);
159                 }
160
161                 // do nothing for matches, etc. These can't escape
162                 _ => {}
163             }
164         }
165     }
166     fn decl_without_init(&mut self, _: NodeId, _: Span) {}
167     fn mutate(&mut self, _: NodeId, _: Span, _: cmt<'tcx>, _: MutateMode) {}
168 }
169
170 impl<'a, 'tcx> EscapeDelegate<'a, 'tcx> {
171     fn is_large_box(&self, ty: ty::Ty<'tcx>) -> bool {
172         // Large types need to be boxed to avoid stack
173         // overflows.
174         if ty.is_box() {
175             type_size(self.cx, ty.boxed_ty()).unwrap_or(0) > self.too_large_for_stack
176         } else {
177             false
178         }
179     }
180 }