]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/escape.rs
rustc_typeck to rustc_hir_analysis
[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_infer::infer::TyCtxtInferExt;
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_middle::mir::FakeReadCause;
7 use rustc_middle::ty::layout::LayoutOf;
8 use rustc_middle::ty::{self, TraitRef, Ty};
9 use rustc_session::{declare_tool_lint, impl_lint_pass};
10 use rustc_span::source_map::Span;
11 use rustc_span::symbol::kw;
12 use rustc_target::spec::abi::Abi;
13 use rustc_hir_analysis::expr_use_visitor::{Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId};
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.def_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         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_hir(
115                 cx,
116                 BOXED_LOCAL,
117                 node,
118                 cx.tcx.hir().span(node),
119                 "local variable doesn't need to be boxed here",
120             );
121         }
122     }
123 }
124
125 // TODO: Replace with Map::is_argument(..) when it's fixed
126 fn is_argument(map: rustc_middle::hir::map::Map<'_>, id: HirId) -> bool {
127     match map.find(id) {
128         Some(Node::Pat(Pat {
129             kind: PatKind::Binding(..),
130             ..
131         })) => (),
132         _ => return false,
133     }
134
135     matches!(map.find(map.get_parent_node(id)), Some(Node::Param(_)))
136 }
137
138 impl<'a, 'tcx> Delegate<'tcx> for EscapeDelegate<'a, 'tcx> {
139     fn consume(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId) {
140         if cmt.place.projections.is_empty() {
141             if let PlaceBase::Local(lid) = cmt.place.base {
142                 self.set.remove(&lid);
143             }
144         }
145     }
146
147     fn borrow(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId, _: ty::BorrowKind) {
148         if cmt.place.projections.is_empty() {
149             if let PlaceBase::Local(lid) = cmt.place.base {
150                 self.set.remove(&lid);
151             }
152         }
153     }
154
155     fn mutate(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId) {
156         if cmt.place.projections.is_empty() {
157             let map = &self.cx.tcx.hir();
158             if is_argument(*map, cmt.hir_id) {
159                 // Skip closure arguments
160                 let parent_id = map.get_parent_node(cmt.hir_id);
161                 if let Some(Node::Expr(..)) = map.find(map.get_parent_node(parent_id)) {
162                     return;
163                 }
164
165                 // skip if there is a `self` parameter binding to a type
166                 // that contains `Self` (i.e.: `self: Box<Self>`), see #4804
167                 if let Some(trait_self_ty) = self.trait_self_ty {
168                     if map.name(cmt.hir_id) == kw::SelfLower && cmt.place.ty().contains(trait_self_ty) {
169                         return;
170                     }
171                 }
172
173                 if is_non_trait_box(cmt.place.ty()) && !self.is_large_box(cmt.place.ty()) {
174                     self.set.insert(cmt.hir_id);
175                 }
176             }
177         }
178     }
179
180     fn fake_read(&mut self, _: &rustc_hir_analysis::expr_use_visitor::PlaceWithHirId<'tcx>, _: FakeReadCause, _: HirId) {}
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()).map_or(0, |l| l.size.bytes()) > self.too_large_for_stack
188         } else {
189             false
190         }
191     }
192 }