1 use rustc_hir::intravisit;
2 use rustc_hir::{self, Body, FnDecl, HirId, HirIdSet, ItemKind, Node};
3 use rustc_infer::infer::TyCtxtInferExt;
4 use rustc_lint::{LateContext, LateLintPass};
5 use rustc_middle::ty::{self, Ty};
6 use rustc_session::{declare_tool_lint, impl_lint_pass};
7 use rustc_span::source_map::Span;
8 use rustc_target::abi::LayoutOf;
9 use rustc_typeck::expr_use_visitor::{ConsumeMode, Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId};
11 use crate::utils::span_lint;
13 #[derive(Copy, Clone)]
14 pub struct BoxedLocal {
15 pub too_large_for_stack: u64,
18 declare_clippy_lint! {
19 /// **What it does:** Checks for usage of `Box<T>` where an unboxed `T` would
22 /// **Why is this bad?** This is an unnecessary allocation, and bad for
23 /// performance. It is only necessary to allocate if you wish to move the box
26 /// **Known problems:** None.
30 /// # fn foo(bar: usize) {}
33 /// let x = Box::new(1);
35 /// println!("{}", *x);
40 /// println!("{}", x);
44 "using `Box<T>` where unnecessary"
47 fn is_non_trait_box(ty: Ty<'_>) -> bool {
48 ty.is_box() && !ty.boxed_ty().is_trait()
51 struct EscapeDelegate<'a, 'tcx> {
52 cx: &'a LateContext<'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 _: intravisit::FnKind<'tcx>,
69 // If the method is an impl for a trait, don't warn.
70 let parent_id = cx.tcx.hir().get_parent_item(hir_id);
71 let parent_node = cx.tcx.hir().find(parent_id);
73 if let Some(Node::Item(item)) = parent_node {
74 if let ItemKind::Impl { of_trait: Some(_), .. } = item.kind {
79 let mut v = EscapeDelegate {
81 set: HirIdSet::default(),
82 too_large_for_stack: self.too_large_for_stack,
85 let fn_def_id = cx.tcx.hir().local_def_id(hir_id);
86 cx.tcx.infer_ctxt().enter(|infcx| {
87 ExprUseVisitor::new(&mut v, &infcx, fn_def_id, cx.param_env, cx.typeck_results()).consume_body(body);
94 cx.tcx.hir().span(node),
95 "local variable doesn't need to be boxed here",
101 // TODO: Replace with Map::is_argument(..) when it's fixed
102 fn is_argument(map: rustc_middle::hir::map::Map<'_>, id: HirId) -> bool {
104 Some(Node::Binding(_)) => (),
108 matches!(map.find(map.get_parent_node(id)), Some(Node::Param(_)))
111 impl<'a, 'tcx> Delegate<'tcx> for EscapeDelegate<'a, 'tcx> {
112 fn consume(&mut self, cmt: &PlaceWithHirId<'tcx>, mode: ConsumeMode) {
113 if cmt.place.projections.is_empty() {
114 if let PlaceBase::Local(lid) = cmt.place.base {
115 if let ConsumeMode::Move = mode {
116 // moved out or in. clearly can't be localized
117 self.set.remove(&lid);
119 let map = &self.cx.tcx.hir();
120 if let Some(Node::Binding(_)) = map.find(cmt.hir_id) {
121 if self.set.contains(&lid) {
122 // let y = x where x is known
123 // remove x, insert y
124 self.set.insert(cmt.hir_id);
125 self.set.remove(&lid);
132 fn borrow(&mut self, cmt: &PlaceWithHirId<'tcx>, _: ty::BorrowKind) {
133 if cmt.place.projections.is_empty() {
134 if let PlaceBase::Local(lid) = cmt.place.base {
135 self.set.remove(&lid);
140 fn mutate(&mut self, cmt: &PlaceWithHirId<'tcx>) {
141 if cmt.place.projections.is_empty() {
142 let map = &self.cx.tcx.hir();
143 if is_argument(*map, cmt.hir_id) {
144 // Skip closure arguments
145 let parent_id = map.get_parent_node(cmt.hir_id);
146 if let Some(Node::Expr(..)) = map.find(map.get_parent_node(parent_id)) {
150 if is_non_trait_box(cmt.place.ty()) && !self.is_large_box(cmt.place.ty()) {
151 self.set.insert(cmt.hir_id);
159 impl<'a, 'tcx> EscapeDelegate<'a, 'tcx> {
160 fn is_large_box(&self, ty: Ty<'tcx>) -> bool {
161 // Large types need to be boxed to avoid stack overflows.
163 self.cx.layout_of(ty.boxed_ty()).map_or(0, |l| l.size.bytes()) > self.too_large_for_stack