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