]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/escape.rs
Rustup to https://github.com/rust-lang/rust/pull/67853
[rust.git] / clippy_lints / src / escape.rs
1 use rustc::hir::intravisit as visit;
2 use rustc::hir::{self, *};
3 use rustc::impl_lint_pass;
4 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
5 use rustc::ty::layout::LayoutOf;
6 use rustc::ty::{self, Ty};
7 use rustc::util::nodemap::HirIdSet;
8 use rustc_session::declare_tool_lint;
9 use rustc_span::source_map::Span;
10 use rustc_typeck::expr_use_visitor::*;
11
12 use crate::utils::span_lint;
13
14 #[derive(Copy, Clone)]
15 pub struct BoxedLocal {
16     pub too_large_for_stack: u64,
17 }
18
19 declare_clippy_lint! {
20     /// **What it does:** Checks for usage of `Box<T>` where an unboxed `T` would
21     /// work fine.
22     ///
23     /// **Why is this bad?** This is an unnecessary allocation, and bad for
24     /// performance. It is only necessary to allocate if you wish to move the box
25     /// into something.
26     ///
27     /// **Known problems:** None.
28     ///
29     /// **Example:**
30     /// ```rust
31     /// # fn foo(bar: usize) {}
32     /// let x = Box::new(1);
33     /// foo(*x);
34     /// println!("{}", *x);
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> {
46     cx: &'a LateContext<'a, 'tcx>,
47     set: HirIdSet,
48     too_large_for_stack: u64,
49 }
50
51 impl_lint_pass!(BoxedLocal => [BOXED_LOCAL]);
52
53 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoxedLocal {
54     fn check_fn(
55         &mut self,
56         cx: &LateContext<'a, 'tcx>,
57         _: visit::FnKind<'tcx>,
58         _: &'tcx FnDecl<'_>,
59         body: &'tcx Body<'_>,
60         _: Span,
61         hir_id: HirId,
62     ) {
63         // If the method is an impl for a trait, don't warn.
64         let parent_id = cx.tcx.hir().get_parent_item(hir_id);
65         let parent_node = cx.tcx.hir().find(parent_id);
66
67         if let Some(Node::Item(item)) = parent_node {
68             if let ItemKind::Impl(_, _, _, _, Some(..), _, _) = item.kind {
69                 return;
70             }
71         }
72
73         let mut v = EscapeDelegate {
74             cx,
75             set: HirIdSet::default(),
76             too_large_for_stack: self.too_large_for_stack,
77         };
78
79         let fn_def_id = cx.tcx.hir().local_def_id(hir_id);
80         cx.tcx.infer_ctxt().enter(|infcx| {
81             ExprUseVisitor::new(&mut v, &infcx, fn_def_id, cx.param_env, cx.tables).consume_body(body);
82         });
83
84         for node in v.set {
85             span_lint(
86                 cx,
87                 BOXED_LOCAL,
88                 cx.tcx.hir().span(node),
89                 "local variable doesn't need to be boxed here",
90             );
91         }
92     }
93 }
94
95 // TODO: Replace with Map::is_argument(..) when it's fixed
96 fn is_argument(map: &hir::map::Map<'_>, id: HirId) -> bool {
97     match map.find(id) {
98         Some(Node::Binding(_)) => (),
99         _ => return false,
100     }
101
102     match map.find(map.get_parent_node(id)) {
103         Some(Node::Param(_)) => true,
104         _ => false,
105     }
106 }
107
108 impl<'a, 'tcx> Delegate<'tcx> for EscapeDelegate<'a, 'tcx> {
109     fn consume(&mut self, cmt: &Place<'tcx>, mode: ConsumeMode) {
110         if cmt.projections.is_empty() {
111             if let PlaceBase::Local(lid) = cmt.base {
112                 if let ConsumeMode::Move = mode {
113                     // moved out or in. clearly can't be localized
114                     self.set.remove(&lid);
115                 }
116                 let map = &self.cx.tcx.hir();
117                 if let Some(Node::Binding(_)) = map.find(cmt.hir_id) {
118                     if self.set.contains(&lid) {
119                         // let y = x where x is known
120                         // remove x, insert y
121                         self.set.insert(cmt.hir_id);
122                         self.set.remove(&lid);
123                     }
124                 }
125             }
126         }
127     }
128
129     fn borrow(&mut self, cmt: &Place<'tcx>, _: ty::BorrowKind) {
130         if cmt.projections.is_empty() {
131             if let PlaceBase::Local(lid) = cmt.base {
132                 self.set.remove(&lid);
133             }
134         }
135     }
136
137     fn mutate(&mut self, cmt: &Place<'tcx>) {
138         if cmt.projections.is_empty() {
139             let map = &self.cx.tcx.hir();
140             if is_argument(map, cmt.hir_id) {
141                 // Skip closure arguments
142                 let parent_id = map.get_parent_node(cmt.hir_id);
143                 if let Some(Node::Expr(..)) = map.find(map.get_parent_node(parent_id)) {
144                     return;
145                 }
146
147                 if is_non_trait_box(cmt.ty) && !self.is_large_box(cmt.ty) {
148                     self.set.insert(cmt.hir_id);
149                 }
150                 return;
151             }
152         }
153     }
154 }
155
156 impl<'a, 'tcx> EscapeDelegate<'a, 'tcx> {
157     fn is_large_box(&self, ty: Ty<'tcx>) -> bool {
158         // Large types need to be boxed to avoid stack overflows.
159         if ty.is_box() {
160             self.cx.layout_of(ty.boxed_ty()).map_or(0, |l| l.size.bytes()) > self.too_large_for_stack
161         } else {
162             false
163         }
164     }
165 }