]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/escape.rs
Last PR adjustments
[rust.git] / clippy_lints / src / escape.rs
1 use clippy_utils::diagnostics::span_lint_hir;
2 use rustc_hir::intravisit;
3 use rustc_hir::{self, AssocItemKind, Body, FnDecl, HirId, HirIdSet, Impl, ItemKind, Node, Pat, PatKind};
4 use rustc_hir_typeck::expr_use_visitor::{Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId};
5 use rustc_infer::infer::TyCtxtInferExt;
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_middle::mir::FakeReadCause;
8 use rustc_middle::ty::layout::LayoutOf;
9 use rustc_middle::ty::{self, TraitRef, Ty};
10 use rustc_session::{declare_tool_lint, impl_lint_pass};
11 use rustc_span::source_map::Span;
12 use rustc_span::symbol::kw;
13 use rustc_target::spec::abi::Abi;
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
22     /// Checks for usage of `Box<T>` where an unboxed `T` would
23     /// work fine.
24     ///
25     /// ### Why is this bad?
26     /// This is an unnecessary allocation, and bad for
27     /// performance. It is only necessary to allocate if you wish to move the box
28     /// into something.
29     ///
30     /// ### Example
31     /// ```rust
32     /// fn foo(x: Box<u32>) {}
33     /// ```
34     ///
35     /// Use instead:
36     /// ```rust
37     /// fn foo(x: u32) {}
38     /// ```
39     #[clippy::version = "pre 1.29.0"]
40     pub BOXED_LOCAL,
41     perf,
42     "using `Box<T>` where unnecessary"
43 }
44
45 fn is_non_trait_box(ty: Ty<'_>) -> bool {
46     ty.is_box() && !ty.boxed_ty().is_trait()
47 }
48
49 struct EscapeDelegate<'a, 'tcx> {
50     cx: &'a LateContext<'tcx>,
51     set: HirIdSet,
52     trait_self_ty: Option<Ty<'tcx>>,
53     too_large_for_stack: u64,
54 }
55
56 impl_lint_pass!(BoxedLocal => [BOXED_LOCAL]);
57
58 impl<'tcx> LateLintPass<'tcx> for BoxedLocal {
59     fn check_fn(
60         &mut self,
61         cx: &LateContext<'tcx>,
62         fn_kind: intravisit::FnKind<'tcx>,
63         _: &'tcx FnDecl<'_>,
64         body: &'tcx Body<'_>,
65         _: Span,
66         hir_id: HirId,
67     ) {
68         if let Some(header) = fn_kind.header() {
69             if header.abi != Abi::Rust {
70                 return;
71             }
72         }
73
74         let parent_id = cx.tcx.hir().get_parent_item(hir_id).def_id;
75         let parent_node = cx.tcx.hir().find_by_def_id(parent_id);
76
77         let mut trait_self_ty = None;
78         if let Some(Node::Item(item)) = parent_node {
79             // If the method is an impl for a trait, don't warn.
80             if let ItemKind::Impl(Impl { of_trait: Some(_), .. }) = item.kind {
81                 return;
82             }
83
84             // find `self` ty for this trait if relevant
85             if let ItemKind::Trait(_, _, _, _, items) = item.kind {
86                 for trait_item in items {
87                     if trait_item.id.hir_id() == hir_id {
88                         // be sure we have `self` parameter in this function
89                         if trait_item.kind == (AssocItemKind::Fn { has_self: true }) {
90                             trait_self_ty = Some(
91                                 TraitRef::identity(cx.tcx, trait_item.id.owner_id.to_def_id())
92                                     .self_ty()
93                                     .skip_binder(),
94                             );
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         let infcx = cx.tcx.infer_ctxt().build();
110         ExprUseVisitor::new(&mut v, &infcx, fn_def_id, cx.param_env, cx.typeck_results()).consume_body(body);
111
112         for node in v.set {
113             span_lint_hir(
114                 cx,
115                 BOXED_LOCAL,
116                 node,
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::Pat(Pat {
128             kind: PatKind::Binding(..),
129             ..
130         })) => (),
131         _ => return false,
132     }
133
134     matches!(map.find(map.get_parent_node(id)), Some(Node::Param(_)))
135 }
136
137 impl<'a, 'tcx> Delegate<'tcx> for EscapeDelegate<'a, 'tcx> {
138     fn consume(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId) {
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 borrow(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId, _: ty::BorrowKind) {
147         if cmt.place.projections.is_empty() {
148             if let PlaceBase::Local(lid) = cmt.place.base {
149                 self.set.remove(&lid);
150             }
151         }
152     }
153
154     fn mutate(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId) {
155         if cmt.place.projections.is_empty() {
156             let map = &self.cx.tcx.hir();
157             if is_argument(*map, cmt.hir_id) {
158                 // Skip closure arguments
159                 let parent_id = map.get_parent_node(cmt.hir_id);
160                 if let Some(Node::Expr(..)) = map.find(map.get_parent_node(parent_id)) {
161                     return;
162                 }
163
164                 // skip if there is a `self` parameter binding to a type
165                 // that contains `Self` (i.e.: `self: Box<Self>`), see #4804
166                 if let Some(trait_self_ty) = self.trait_self_ty {
167                     if map.name(cmt.hir_id) == kw::SelfLower && cmt.place.ty().contains(trait_self_ty) {
168                         return;
169                     }
170                 }
171
172                 if is_non_trait_box(cmt.place.ty()) && !self.is_large_box(cmt.place.ty()) {
173                     self.set.insert(cmt.hir_id);
174                 }
175             }
176         }
177     }
178
179     fn fake_read(&mut self, _: &rustc_hir_typeck::expr_use_visitor::PlaceWithHirId<'tcx>, _: FakeReadCause, _: HirId) {}
180 }
181
182 impl<'a, 'tcx> EscapeDelegate<'a, 'tcx> {
183     fn is_large_box(&self, ty: Ty<'tcx>) -> bool {
184         // Large types need to be boxed to avoid stack overflows.
185         if ty.is_box() {
186             self.cx.layout_of(ty.boxed_ty()).map_or(0, |l| l.size.bytes()) > self.too_large_for_stack
187         } else {
188             false
189         }
190     }
191 }