]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/escape.rs
Auto merge of #77649 - dash2507:replace_run_compiler, r=matthewjasper
[rust.git] / clippy_lints / src / escape.rs
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_target::spec::abi::Abi;
10 use rustc_typeck::expr_use_visitor::{ConsumeMode, Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId};
11
12 use crate::utils::span_lint;
13
14 #[derive(Copy, Clone)]
15 pub struct BoxedLocal {
16     pub too_large_for_stack: u64,
17 }
18
19 declare_clippy_lint! {
20     /// **What it does:** Checks for usage of `Box<T>` where an unboxed `T` would
21     /// work fine.
22     ///
23     /// **Why is this bad?** This is an unnecessary allocation, and bad for
24     /// performance. It is only necessary to allocate if you wish to move the box
25     /// into something.
26     ///
27     /// **Known problems:** None.
28     ///
29     /// **Example:**
30     /// ```rust
31     /// # fn foo(bar: usize) {}
32     ///
33     /// // Bad
34     /// let x = Box::new(1);
35     /// foo(*x);
36     /// println!("{}", *x);
37     ///
38     /// // Good
39     /// let x = 1;
40     /// foo(x);
41     /// println!("{}", x);
42     /// ```
43     pub BOXED_LOCAL,
44     perf,
45     "using `Box<T>` where unnecessary"
46 }
47
48 fn is_non_trait_box(ty: Ty<'_>) -> bool {
49     ty.is_box() && !ty.boxed_ty().is_trait()
50 }
51
52 struct EscapeDelegate<'a, 'tcx> {
53     cx: &'a LateContext<'tcx>,
54     set: HirIdSet,
55     too_large_for_stack: u64,
56 }
57
58 impl_lint_pass!(BoxedLocal => [BOXED_LOCAL]);
59
60 impl<'tcx> LateLintPass<'tcx> for BoxedLocal {
61     fn check_fn(
62         &mut self,
63         cx: &LateContext<'tcx>,
64         fn_kind: intravisit::FnKind<'tcx>,
65         _: &'tcx FnDecl<'_>,
66         body: &'tcx Body<'_>,
67         _: Span,
68         hir_id: HirId,
69     ) {
70         if let Some(header) = fn_kind.header() {
71             if header.abi != Abi::Rust {
72                 return;
73             }
74         }
75
76         // If the method is an impl for a trait, don't warn.
77         let parent_id = cx.tcx.hir().get_parent_item(hir_id);
78         let parent_node = cx.tcx.hir().find(parent_id);
79
80         if let Some(Node::Item(item)) = parent_node {
81             if let ItemKind::Impl { of_trait: Some(_), .. } = item.kind {
82                 return;
83             }
84         }
85
86         let mut v = EscapeDelegate {
87             cx,
88             set: HirIdSet::default(),
89             too_large_for_stack: self.too_large_for_stack,
90         };
91
92         let fn_def_id = cx.tcx.hir().local_def_id(hir_id);
93         cx.tcx.infer_ctxt().enter(|infcx| {
94             ExprUseVisitor::new(&mut v, &infcx, fn_def_id, cx.param_env, cx.typeck_results()).consume_body(body);
95         });
96
97         for node in v.set {
98             span_lint(
99                 cx,
100                 BOXED_LOCAL,
101                 cx.tcx.hir().span(node),
102                 "local variable doesn't need to be boxed here",
103             );
104         }
105     }
106 }
107
108 // TODO: Replace with Map::is_argument(..) when it's fixed
109 fn is_argument(map: rustc_middle::hir::map::Map<'_>, id: HirId) -> bool {
110     match map.find(id) {
111         Some(Node::Binding(_)) => (),
112         _ => return false,
113     }
114
115     matches!(map.find(map.get_parent_node(id)), Some(Node::Param(_)))
116 }
117
118 impl<'a, 'tcx> Delegate<'tcx> for EscapeDelegate<'a, 'tcx> {
119     fn consume(&mut self, cmt: &PlaceWithHirId<'tcx>, mode: ConsumeMode) {
120         if cmt.place.projections.is_empty() {
121             if let PlaceBase::Local(lid) = cmt.place.base {
122                 if let ConsumeMode::Move = mode {
123                     // moved out or in. clearly can't be localized
124                     self.set.remove(&lid);
125                 }
126                 let map = &self.cx.tcx.hir();
127                 if let Some(Node::Binding(_)) = map.find(cmt.hir_id) {
128                     if self.set.contains(&lid) {
129                         // let y = x where x is known
130                         // remove x, insert y
131                         self.set.insert(cmt.hir_id);
132                         self.set.remove(&lid);
133                     }
134                 }
135             }
136         }
137     }
138
139     fn borrow(&mut self, cmt: &PlaceWithHirId<'tcx>, _: ty::BorrowKind) {
140         if cmt.place.projections.is_empty() {
141             if let PlaceBase::Local(lid) = cmt.place.base {
142                 self.set.remove(&lid);
143             }
144         }
145     }
146
147     fn mutate(&mut self, cmt: &PlaceWithHirId<'tcx>) {
148         if cmt.place.projections.is_empty() {
149             let map = &self.cx.tcx.hir();
150             if is_argument(*map, cmt.hir_id) {
151                 // Skip closure arguments
152                 let parent_id = map.get_parent_node(cmt.hir_id);
153                 if let Some(Node::Expr(..)) = map.find(map.get_parent_node(parent_id)) {
154                     return;
155                 }
156
157                 if is_non_trait_box(cmt.place.ty()) && !self.is_large_box(cmt.place.ty()) {
158                     self.set.insert(cmt.hir_id);
159                 }
160                 return;
161             }
162         }
163     }
164 }
165
166 impl<'a, 'tcx> EscapeDelegate<'a, 'tcx> {
167     fn is_large_box(&self, ty: Ty<'tcx>) -> bool {
168         // Large types need to be boxed to avoid stack overflows.
169         if ty.is_box() {
170             self.cx.layout_of(ty.boxed_ty()).map_or(0, |l| l.size.bytes()) > self.too_large_for_stack
171         } else {
172             false
173         }
174     }
175 }