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};
16 #[derive(Copy, Clone)]
17 pub struct BoxedLocal {
18 pub too_large_for_stack: u64,
21 declare_clippy_lint! {
23 /// Checks for usage of `Box<T>` where an unboxed `T` would
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
33 /// fn foo(x: Box<u32>) {}
40 #[clippy::version = "pre 1.29.0"]
43 "using `Box<T>` where unnecessary"
46 fn is_non_trait_box(ty: Ty<'_>) -> bool {
47 ty.is_box() && !ty.boxed_ty().is_trait()
50 struct EscapeDelegate<'a, 'tcx> {
51 cx: &'a LateContext<'tcx>,
53 trait_self_ty: Option<Ty<'tcx>>,
54 too_large_for_stack: u64,
57 impl_lint_pass!(BoxedLocal => [BOXED_LOCAL]);
59 impl<'tcx> LateLintPass<'tcx> for BoxedLocal {
62 cx: &LateContext<'tcx>,
63 fn_kind: intravisit::FnKind<'tcx>,
69 if let Some(header) = fn_kind.header() {
70 if header.abi != Abi::Rust {
75 let parent_id = cx.tcx.hir().get_parent_item(hir_id);
76 let parent_node = cx.tcx.hir().find_by_def_id(parent_id);
78 let mut trait_self_ty = None;
79 if let Some(Node::Item(item)) = parent_node {
80 // If the method is an impl for a trait, don't warn.
81 if let ItemKind::Impl(Impl { of_trait: Some(_), .. }) = item.kind {
85 // find `self` ty for this trait if relevant
86 if let ItemKind::Trait(_, _, _, _, items) = item.kind {
87 for trait_item in items {
88 if trait_item.id.hir_id() == hir_id {
89 // be sure we have `self` parameter in this function
90 if trait_item.kind == (AssocItemKind::Fn { has_self: true }) {
92 TraitRef::identity(cx.tcx, trait_item.id.def_id.to_def_id())
102 let mut v = EscapeDelegate {
104 set: HirIdSet::default(),
106 too_large_for_stack: self.too_large_for_stack,
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);
119 cx.tcx.hir().span(node),
120 "local variable doesn't need to be boxed here",
126 // TODO: Replace with Map::is_argument(..) when it's fixed
127 fn is_argument(map: rustc_middle::hir::map::Map<'_>, id: HirId) -> bool {
130 kind: PatKind::Binding(..),
136 matches!(map.find(map.get_parent_node(id)), Some(Node::Param(_)))
139 impl<'a, 'tcx> Delegate<'tcx> for EscapeDelegate<'a, 'tcx> {
140 fn consume(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId) {
141 if cmt.place.projections.is_empty() {
142 if let PlaceBase::Local(lid) = cmt.place.base {
143 self.set.remove(&lid);
148 fn borrow(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId, _: ty::BorrowKind) {
149 if cmt.place.projections.is_empty() {
150 if let PlaceBase::Local(lid) = cmt.place.base {
151 self.set.remove(&lid);
156 fn mutate(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId) {
157 if cmt.place.projections.is_empty() {
158 let map = &self.cx.tcx.hir();
159 if is_argument(*map, cmt.hir_id) {
160 // Skip closure arguments
161 let parent_id = map.get_parent_node(cmt.hir_id);
162 if let Some(Node::Expr(..)) = map.find(map.get_parent_node(parent_id)) {
166 // skip if there is a `self` parameter binding to a type
167 // that contains `Self` (i.e.: `self: Box<Self>`), see #4804
168 if let Some(trait_self_ty) = self.trait_self_ty {
169 if map.name(cmt.hir_id) == kw::SelfLower && contains_ty(cmt.place.ty(), trait_self_ty) {
174 if is_non_trait_box(cmt.place.ty()) && !self.is_large_box(cmt.place.ty()) {
175 self.set.insert(cmt.hir_id);
181 fn fake_read(&mut self, _: &rustc_typeck::expr_use_visitor::PlaceWithHirId<'tcx>, _: FakeReadCause, _: HirId) {}
184 impl<'a, 'tcx> EscapeDelegate<'a, 'tcx> {
185 fn is_large_box(&self, ty: Ty<'tcx>) -> bool {
186 // Large types need to be boxed to avoid stack overflows.
188 self.cx.layout_of(ty.boxed_ty()).map_or(0, |l| l.size.bytes()) > self.too_large_for_stack