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;
15 #[derive(Copy, Clone)]
16 pub struct BoxedLocal {
17 pub too_large_for_stack: u64,
20 declare_clippy_lint! {
22 /// Checks for usage of `Box<T>` where an unboxed `T` would
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
32 /// fn foo(x: Box<u32>) {}
39 #[clippy::version = "pre 1.29.0"]
42 "using `Box<T>` where unnecessary"
45 fn is_non_trait_box(ty: Ty<'_>) -> bool {
46 ty.is_box() && !ty.boxed_ty().is_trait()
49 struct EscapeDelegate<'a, 'tcx> {
50 cx: &'a LateContext<'tcx>,
52 trait_self_ty: Option<Ty<'tcx>>,
53 too_large_for_stack: u64,
56 impl_lint_pass!(BoxedLocal => [BOXED_LOCAL]);
58 impl<'tcx> LateLintPass<'tcx> for BoxedLocal {
61 cx: &LateContext<'tcx>,
62 fn_kind: intravisit::FnKind<'tcx>,
68 if let Some(header) = fn_kind.header() {
69 if header.abi != Abi::Rust {
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);
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 {
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 }) {
91 TraitRef::identity(cx.tcx, trait_item.id.owner_id.to_def_id())
101 let mut v = EscapeDelegate {
103 set: HirIdSet::default(),
105 too_large_for_stack: self.too_large_for_stack,
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);
117 cx.tcx.hir().span(node),
118 "local variable doesn't need to be boxed here",
124 // TODO: Replace with Map::is_argument(..) when it's fixed
125 fn is_argument(map: rustc_middle::hir::map::Map<'_>, id: HirId) -> bool {
128 kind: PatKind::Binding(..),
134 matches!(map.find_parent(id), Some(Node::Param(_)))
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);
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);
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.parent_id(cmt.hir_id);
160 if let Some(Node::Expr(..)) = map.find_parent(parent_id) {
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) {
172 if is_non_trait_box(cmt.place.ty()) && !self.is_large_box(cmt.place.ty()) {
173 self.set.insert(cmt.hir_id);
179 fn fake_read(&mut self, _: &rustc_hir_typeck::expr_use_visitor::PlaceWithHirId<'tcx>, _: FakeReadCause, _: HirId) {}
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.
186 self.cx.layout_of(ty.boxed_ty()).map_or(0, |l| l.size.bytes()) > self.too_large_for_stack