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