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