]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/escape.rs
Fix lines that exceed max width manually
[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::{self, 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) -> 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_scope_tree = &cx.tcx.region_scope_tree(fn_def_id);
74         ExprUseVisitor::new(&mut v, cx.tcx, cx.param_env, region_scope_tree, cx.tables, None).consume_body(body);
75
76         for node in v.set {
77             span_lint(
78                 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
87 impl<'a, 'tcx> Delegate<'tcx> for EscapeDelegate<'a, 'tcx> {
88     fn consume(&mut self, _: NodeId, _: Span, cmt: cmt<'tcx>, mode: ConsumeMode) {
89         if let Categorization::Local(lid) = cmt.cat {
90             if let Move(DirectRefMove) = mode {
91                 // moved out or in. clearly can't be localized
92                 self.set.remove(&lid);
93             }
94         }
95     }
96     fn matched_pat(&mut self, _: &Pat, _: cmt<'tcx>, _: MatchMode) {}
97     fn consume_pat(&mut self, consume_pat: &Pat, cmt: cmt<'tcx>, _: ConsumeMode) {
98         let map = &self.cx.tcx.hir;
99         if map.is_argument(consume_pat.id) {
100             // Skip closure arguments
101             if let Some(NodeExpr(..)) = map.find(map.get_parent_node(consume_pat.id)) {
102                 return;
103             }
104             if is_non_trait_box(cmt.ty) && !self.is_large_box(cmt.ty) {
105                 self.set.insert(consume_pat.id);
106             }
107             return;
108         }
109         if let Categorization::Rvalue(..) = cmt.cat {
110             if let Some(NodeStmt(st)) = map.find(map.get_parent_node(cmt.id)) {
111                 if let StmtDecl(ref decl, _) = st.node {
112                     if let DeclLocal(ref loc) = decl.node {
113                         if let Some(ref ex) = loc.init {
114                             if let ExprBox(..) = ex.node {
115                                 if is_non_trait_box(cmt.ty) && !self.is_large_box(cmt.ty) {
116                                     // let x = box (...)
117                                     self.set.insert(consume_pat.id);
118                                 }
119                                 // TODO Box::new
120                                 // TODO vec![]
121                                 // TODO "foo".to_owned() and friends
122                             }
123                         }
124                     }
125                 }
126             }
127         }
128         if let Categorization::Local(lid) = cmt.cat {
129             if self.set.contains(&lid) {
130                 // let y = x where x is known
131                 // remove x, insert y
132                 self.set.insert(consume_pat.id);
133                 self.set.remove(&lid);
134             }
135         }
136     }
137     fn borrow(&mut self, _: NodeId, _: Span, cmt: cmt<'tcx>, _: ty::Region, _: ty::BorrowKind, loan_cause: LoanCause) {
138         if let Categorization::Local(lid) = cmt.cat {
139             match loan_cause {
140                 // x.foo()
141                 // Used without autodereffing (i.e. x.clone())
142                 LoanCause::AutoRef |
143
144                 // &x
145                 // foo(&x) where no extra autoreffing is happening
146                 LoanCause::AddrOf |
147
148                 // `match x` can move
149                 LoanCause::MatchDiscriminant => {
150                     self.set.remove(&lid);
151                 }
152
153                 // do nothing for matches, etc. These can't escape
154                 _ => {}
155             }
156         }
157     }
158     fn decl_without_init(&mut self, _: NodeId, _: Span) {}
159     fn mutate(&mut self, _: NodeId, _: Span, _: cmt<'tcx>, _: MutateMode) {}
160 }
161
162 impl<'a, 'tcx> EscapeDelegate<'a, 'tcx> {
163     fn is_large_box(&self, ty: Ty<'tcx>) -> bool {
164         // Large types need to be boxed to avoid stack
165         // overflows.
166         if ty.is_box() {
167             type_size(self.cx, ty.boxed_ty()).unwrap_or(0) > self.too_large_for_stack
168         } else {
169             false
170         }
171     }
172 }