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