]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/escape.rs
Auto merge of #81993 - flip1995:clippyup, r=Manishearth
[rust.git] / clippy_lints / src / escape.rs
1 use rustc_hir::intravisit;
2 use rustc_hir::{self, AssocItemKind, Body, FnDecl, HirId, HirIdSet, Impl, ItemKind, Node};
3 use rustc_infer::infer::TyCtxtInferExt;
4 use rustc_lint::{LateContext, LateLintPass};
5 use rustc_middle::ty::{self, TraitRef, Ty};
6 use rustc_session::{declare_tool_lint, impl_lint_pass};
7 use rustc_span::source_map::Span;
8 use rustc_span::symbol::kw;
9 use rustc_target::abi::LayoutOf;
10 use rustc_target::spec::abi::Abi;
11 use rustc_typeck::expr_use_visitor::{ConsumeMode, Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId};
12
13 use crate::utils::{contains_ty, span_lint};
14
15 #[derive(Copy, Clone)]
16 pub struct BoxedLocal {
17     pub too_large_for_stack: u64,
18 }
19
20 declare_clippy_lint! {
21     /// **What it does:** Checks for usage of `Box<T>` where an unboxed `T` would
22     /// work fine.
23     ///
24     /// **Why is this bad?** This is an unnecessary allocation, and bad for
25     /// performance. It is only necessary to allocate if you wish to move the box
26     /// into something.
27     ///
28     /// **Known problems:** None.
29     ///
30     /// **Example:**
31     /// ```rust
32     /// # fn foo(bar: usize) {}
33     /// // Bad
34     /// let x = Box::new(1);
35     /// foo(*x);
36     /// println!("{}", *x);
37     ///
38     /// // Good
39     /// let x = 1;
40     /// foo(x);
41     /// println!("{}", x);
42     /// ```
43     pub BOXED_LOCAL,
44     perf,
45     "using `Box<T>` where unnecessary"
46 }
47
48 fn is_non_trait_box(ty: Ty<'_>) -> bool {
49     ty.is_box() && !ty.boxed_ty().is_trait()
50 }
51
52 struct EscapeDelegate<'a, 'tcx> {
53     cx: &'a LateContext<'tcx>,
54     set: HirIdSet,
55     trait_self_ty: Option<Ty<'a>>,
56     too_large_for_stack: u64,
57 }
58
59 impl_lint_pass!(BoxedLocal => [BOXED_LOCAL]);
60
61 impl<'tcx> LateLintPass<'tcx> for BoxedLocal {
62     fn check_fn(
63         &mut self,
64         cx: &LateContext<'tcx>,
65         fn_kind: intravisit::FnKind<'tcx>,
66         _: &'tcx FnDecl<'_>,
67         body: &'tcx Body<'_>,
68         _: Span,
69         hir_id: HirId,
70     ) {
71         if let Some(header) = fn_kind.header() {
72             if header.abi != Abi::Rust {
73                 return;
74             }
75         }
76
77         let parent_id = cx.tcx.hir().get_parent_item(hir_id);
78         let parent_node = cx.tcx.hir().find(parent_id);
79
80         let mut trait_self_ty = None;
81         if let Some(Node::Item(item)) = parent_node {
82             // If the method is an impl for a trait, don't warn.
83             if let ItemKind::Impl(Impl { of_trait: Some(_), .. }) = item.kind {
84                 return;
85             }
86
87             // find `self` ty for this trait if relevant
88             if let ItemKind::Trait(_, _, _, _, items) = item.kind {
89                 for trait_item in items {
90                     if trait_item.id.hir_id() == hir_id {
91                         // be sure we have `self` parameter in this function
92                         if let AssocItemKind::Fn { has_self: true } = trait_item.kind {
93                             trait_self_ty =
94                                 Some(TraitRef::identity(cx.tcx, trait_item.id.def_id.to_def_id()).self_ty());
95                         }
96                     }
97                 }
98             }
99         }
100
101         let mut v = EscapeDelegate {
102             cx,
103             set: HirIdSet::default(),
104             trait_self_ty,
105             too_large_for_stack: self.too_large_for_stack,
106         };
107
108         let fn_def_id = cx.tcx.hir().local_def_id(hir_id);
109         cx.tcx.infer_ctxt().enter(|infcx| {
110             ExprUseVisitor::new(&mut v, &infcx, fn_def_id, cx.param_env, cx.typeck_results()).consume_body(body);
111         });
112
113         for node in v.set {
114             span_lint(
115                 cx,
116                 BOXED_LOCAL,
117                 cx.tcx.hir().span(node),
118                 "local variable doesn't need to be boxed here",
119             );
120         }
121     }
122 }
123
124 // TODO: Replace with Map::is_argument(..) when it's fixed
125 fn is_argument(map: rustc_middle::hir::map::Map<'_>, id: HirId) -> bool {
126     match map.find(id) {
127         Some(Node::Binding(_)) => (),
128         _ => return false,
129     }
130
131     matches!(map.find(map.get_parent_node(id)), Some(Node::Param(_)))
132 }
133
134 impl<'a, 'tcx> Delegate<'tcx> for EscapeDelegate<'a, 'tcx> {
135     fn consume(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId, mode: ConsumeMode) {
136         if cmt.place.projections.is_empty() {
137             if let PlaceBase::Local(lid) = cmt.place.base {
138                 if let ConsumeMode::Move = mode {
139                     // moved out or in. clearly can't be localized
140                     self.set.remove(&lid);
141                 }
142                 let map = &self.cx.tcx.hir();
143                 if let Some(Node::Binding(_)) = map.find(cmt.hir_id) {
144                     if self.set.contains(&lid) {
145                         // let y = x where x is known
146                         // remove x, insert y
147                         self.set.insert(cmt.hir_id);
148                         self.set.remove(&lid);
149                     }
150                 }
151             }
152         }
153     }
154
155     fn borrow(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId, _: ty::BorrowKind) {
156         if cmt.place.projections.is_empty() {
157             if let PlaceBase::Local(lid) = cmt.place.base {
158                 self.set.remove(&lid);
159             }
160         }
161     }
162
163     fn mutate(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId) {
164         if cmt.place.projections.is_empty() {
165             let map = &self.cx.tcx.hir();
166             if is_argument(*map, cmt.hir_id) {
167                 // Skip closure arguments
168                 let parent_id = map.get_parent_node(cmt.hir_id);
169                 if let Some(Node::Expr(..)) = map.find(map.get_parent_node(parent_id)) {
170                     return;
171                 }
172
173                 // skip if there is a `self` parameter binding to a type
174                 // that contains `Self` (i.e.: `self: Box<Self>`), see #4804
175                 if let Some(trait_self_ty) = self.trait_self_ty {
176                     if map.name(cmt.hir_id) == kw::SelfLower && contains_ty(cmt.place.ty(), trait_self_ty) {
177                         return;
178                     }
179                 }
180
181                 if is_non_trait_box(cmt.place.ty()) && !self.is_large_box(cmt.place.ty()) {
182                     self.set.insert(cmt.hir_id);
183                 }
184             }
185         }
186     }
187 }
188
189 impl<'a, 'tcx> EscapeDelegate<'a, 'tcx> {
190     fn is_large_box(&self, ty: Ty<'tcx>) -> bool {
191         // Large types need to be boxed to avoid stack overflows.
192         if ty.is_box() {
193             self.cx.layout_of(ty.boxed_ty()).map_or(0, |l| l.size.bytes()) > self.too_large_for_stack
194         } else {
195             false
196         }
197     }
198 }