]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/escape.rs
Merge commit '4911ab124c481430672a3833b37075e6435ec34d' into clippyup
[rust.git] / clippy_lints / src / escape.rs
1 use rustc_hir::intravisit;
2 use rustc_hir::{self, Body, FnDecl, HirId, HirIdSet, ItemKind, Node};
3 use rustc_infer::infer::TyCtxtInferExt;
4 use rustc_lint::{LateContext, LateLintPass};
5 use rustc_middle::ty::{self, Ty};
6 use rustc_session::{declare_tool_lint, impl_lint_pass};
7 use rustc_span::source_map::Span;
8 use rustc_target::abi::LayoutOf;
9 use rustc_target::spec::abi::Abi;
10 use rustc_typeck::expr_use_visitor::{ConsumeMode, Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId};
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     /// // Bad
33     /// let x = Box::new(1);
34     /// foo(*x);
35     /// println!("{}", *x);
36     ///
37     /// // Good
38     /// let x = 1;
39     /// foo(x);
40     /// println!("{}", x);
41     /// ```
42     pub BOXED_LOCAL,
43     perf,
44     "using `Box<T>` where unnecessary"
45 }
46
47 fn is_non_trait_box(ty: Ty<'_>) -> bool {
48     ty.is_box() && !ty.boxed_ty().is_trait()
49 }
50
51 struct EscapeDelegate<'a, 'tcx> {
52     cx: &'a LateContext<'tcx>,
53     set: HirIdSet,
54     too_large_for_stack: u64,
55 }
56
57 impl_lint_pass!(BoxedLocal => [BOXED_LOCAL]);
58
59 impl<'tcx> LateLintPass<'tcx> for BoxedLocal {
60     fn check_fn(
61         &mut self,
62         cx: &LateContext<'tcx>,
63         fn_kind: intravisit::FnKind<'tcx>,
64         _: &'tcx FnDecl<'_>,
65         body: &'tcx Body<'_>,
66         _: Span,
67         hir_id: HirId,
68     ) {
69         if let Some(header) = fn_kind.header() {
70             if header.abi != Abi::Rust {
71                 return;
72             }
73         }
74
75         // If the method is an impl for a trait, don't warn.
76         let parent_id = cx.tcx.hir().get_parent_item(hir_id);
77         let parent_node = cx.tcx.hir().find(parent_id);
78
79         if let Some(Node::Item(item)) = parent_node {
80             if let ItemKind::Impl { of_trait: Some(_), .. } = item.kind {
81                 return;
82             }
83         }
84
85         let mut v = EscapeDelegate {
86             cx,
87             set: HirIdSet::default(),
88             too_large_for_stack: self.too_large_for_stack,
89         };
90
91         let fn_def_id = cx.tcx.hir().local_def_id(hir_id);
92         cx.tcx.infer_ctxt().enter(|infcx| {
93             ExprUseVisitor::new(&mut v, &infcx, fn_def_id, cx.param_env, cx.typeck_results()).consume_body(body);
94         });
95
96         for node in v.set {
97             span_lint(
98                 cx,
99                 BOXED_LOCAL,
100                 cx.tcx.hir().span(node),
101                 "local variable doesn't need to be boxed here",
102             );
103         }
104     }
105 }
106
107 // TODO: Replace with Map::is_argument(..) when it's fixed
108 fn is_argument(map: rustc_middle::hir::map::Map<'_>, id: HirId) -> bool {
109     match map.find(id) {
110         Some(Node::Binding(_)) => (),
111         _ => return false,
112     }
113
114     matches!(map.find(map.get_parent_node(id)), Some(Node::Param(_)))
115 }
116
117 impl<'a, 'tcx> Delegate<'tcx> for EscapeDelegate<'a, 'tcx> {
118     fn consume(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId, mode: ConsumeMode) {
119         if cmt.place.projections.is_empty() {
120             if let PlaceBase::Local(lid) = cmt.place.base {
121                 if let ConsumeMode::Move = mode {
122                     // moved out or in. clearly can't be localized
123                     self.set.remove(&lid);
124                 }
125                 let map = &self.cx.tcx.hir();
126                 if let Some(Node::Binding(_)) = map.find(cmt.hir_id) {
127                     if self.set.contains(&lid) {
128                         // let y = x where x is known
129                         // remove x, insert y
130                         self.set.insert(cmt.hir_id);
131                         self.set.remove(&lid);
132                     }
133                 }
134             }
135         }
136     }
137
138     fn borrow(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId, _: ty::BorrowKind) {
139         if cmt.place.projections.is_empty() {
140             if let PlaceBase::Local(lid) = cmt.place.base {
141                 self.set.remove(&lid);
142             }
143         }
144     }
145
146     fn mutate(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId) {
147         if cmt.place.projections.is_empty() {
148             let map = &self.cx.tcx.hir();
149             if is_argument(*map, cmt.hir_id) {
150                 // Skip closure arguments
151                 let parent_id = map.get_parent_node(cmt.hir_id);
152                 if let Some(Node::Expr(..)) = map.find(map.get_parent_node(parent_id)) {
153                     return;
154                 }
155
156                 if is_non_trait_box(cmt.place.ty()) && !self.is_large_box(cmt.place.ty()) {
157                     self.set.insert(cmt.hir_id);
158                 }
159                 return;
160             }
161         }
162     }
163 }
164
165 impl<'a, 'tcx> EscapeDelegate<'a, 'tcx> {
166     fn is_large_box(&self, ty: Ty<'tcx>) -> bool {
167         // Large types need to be boxed to avoid stack overflows.
168         if ty.is_box() {
169             self.cx.layout_of(ty.boxed_ty()).map_or(0, |l| l.size.bytes()) > self.too_large_for_stack
170         } else {
171             false
172         }
173     }
174 }