]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/escape.rs
Auto merge of #3834 - ljedrz:HirIdification_fix, r=phansch
[rust.git] / clippy_lints / src / escape.rs
1 use crate::utils::span_lint;
2 use rustc::hir::intravisit as visit;
3 use rustc::hir::*;
4 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
5 use rustc::middle::expr_use_visitor::*;
6 use rustc::middle::mem_categorization::{cmt_, Categorization};
7 use rustc::ty::layout::LayoutOf;
8 use rustc::ty::{self, Ty};
9 use rustc::util::nodemap::HirIdSet;
10 use rustc::{declare_tool_lint, lint_array};
11 use syntax::source_map::Span;
12
13 pub struct Pass {
14     pub too_large_for_stack: u64,
15 }
16
17 /// **What it does:** Checks for usage of `Box<T>` where an unboxed `T` would
18 /// work fine.
19 ///
20 /// **Why is this bad?** This is an unnecessary allocation, and bad for
21 /// performance. It is only necessary to allocate if you wish to move the box
22 /// into something.
23 ///
24 /// **Known problems:** None.
25 ///
26 /// **Example:**
27 /// ```rust
28 /// fn main() {
29 ///     let x = Box::new(1);
30 ///     foo(*x);
31 ///     println!("{}", *x);
32 /// }
33 /// ```
34 declare_clippy_lint! {
35     pub BOXED_LOCAL,
36     perf,
37     "using `Box<T>` where unnecessary"
38 }
39
40 fn is_non_trait_box(ty: Ty<'_>) -> bool {
41     ty.is_box() && !ty.boxed_ty().is_trait()
42 }
43
44 struct EscapeDelegate<'a, 'tcx: 'a> {
45     cx: &'a LateContext<'a, 'tcx>,
46     set: HirIdSet,
47     too_large_for_stack: u64,
48 }
49
50 impl LintPass for Pass {
51     fn get_lints(&self) -> LintArray {
52         lint_array!(BOXED_LOCAL)
53     }
54
55     fn name(&self) -> &'static str {
56         "BoxedLocal"
57     }
58 }
59
60 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
61     fn check_fn(
62         &mut self,
63         cx: &LateContext<'a, 'tcx>,
64         _: visit::FnKind<'tcx>,
65         _: &'tcx FnDecl,
66         body: &'tcx Body,
67         _: Span,
68         hir_id: HirId,
69     ) {
70         // If the method is an impl for a trait, don't warn
71         let parent_id = cx.tcx.hir().get_parent_item(hir_id);
72         let parent_node = cx.tcx.hir().find_by_hir_id(parent_id);
73
74         if let Some(Node::Item(item)) = parent_node {
75             if let ItemKind::Impl(_, _, _, _, Some(..), _, _) = item.node {
76                 return;
77             }
78         }
79
80         let mut v = EscapeDelegate {
81             cx,
82             set: HirIdSet::default(),
83             too_large_for_stack: self.too_large_for_stack,
84         };
85
86         let fn_def_id = cx.tcx.hir().local_def_id_from_hir_id(hir_id);
87         let region_scope_tree = &cx.tcx.region_scope_tree(fn_def_id);
88         ExprUseVisitor::new(&mut v, cx.tcx, cx.param_env, region_scope_tree, cx.tables, None).consume_body(body);
89
90         for node in v.set {
91             span_lint(
92                 cx,
93                 BOXED_LOCAL,
94                 cx.tcx.hir().span_by_hir_id(node),
95                 "local variable doesn't need to be boxed here",
96             );
97         }
98     }
99 }
100
101 impl<'a, 'tcx> Delegate<'tcx> for EscapeDelegate<'a, 'tcx> {
102     fn consume(&mut self, _: HirId, _: Span, cmt: &cmt_<'tcx>, mode: ConsumeMode) {
103         if let Categorization::Local(lid) = cmt.cat {
104             if let Move(DirectRefMove) = mode {
105                 // moved out or in. clearly can't be localized
106                 self.set.remove(&lid);
107             }
108         }
109     }
110     fn matched_pat(&mut self, _: &Pat, _: &cmt_<'tcx>, _: MatchMode) {}
111     fn consume_pat(&mut self, consume_pat: &Pat, cmt: &cmt_<'tcx>, _: ConsumeMode) {
112         let map = &self.cx.tcx.hir();
113         if map.is_argument(map.hir_to_node_id(consume_pat.hir_id)) {
114             // Skip closure arguments
115             if let Some(Node::Expr(..)) = map.find_by_hir_id(map.get_parent_node_by_hir_id(consume_pat.hir_id)) {
116                 return;
117             }
118             if is_non_trait_box(cmt.ty) && !self.is_large_box(cmt.ty) {
119                 self.set.insert(consume_pat.hir_id);
120             }
121             return;
122         }
123         if let Categorization::Rvalue(..) = cmt.cat {
124             let id = map.hir_to_node_id(cmt.hir_id);
125             if let Some(Node::Stmt(st)) = map.find(map.get_parent_node(id)) {
126                 if let StmtKind::Local(ref loc) = st.node {
127                     if let Some(ref ex) = loc.init {
128                         if let ExprKind::Box(..) = ex.node {
129                             if is_non_trait_box(cmt.ty) && !self.is_large_box(cmt.ty) {
130                                 // let x = box (...)
131                                 self.set.insert(consume_pat.hir_id);
132                             }
133                             // TODO Box::new
134                             // TODO vec![]
135                             // TODO "foo".to_owned() and friends
136                         }
137                     }
138                 }
139             }
140         }
141         if let Categorization::Local(lid) = cmt.cat {
142             if self.set.contains(&lid) {
143                 // let y = x where x is known
144                 // remove x, insert y
145                 self.set.insert(consume_pat.hir_id);
146                 self.set.remove(&lid);
147             }
148         }
149     }
150     fn borrow(
151         &mut self,
152         _: HirId,
153         _: Span,
154         cmt: &cmt_<'tcx>,
155         _: ty::Region<'_>,
156         _: ty::BorrowKind,
157         loan_cause: LoanCause,
158     ) {
159         if let Categorization::Local(lid) = cmt.cat {
160             match loan_cause {
161                 // x.foo()
162                 // Used without autodereffing (i.e. x.clone())
163                 LoanCause::AutoRef |
164
165                 // &x
166                 // foo(&x) where no extra autoreffing is happening
167                 LoanCause::AddrOf |
168
169                 // `match x` can move
170                 LoanCause::MatchDiscriminant => {
171                     self.set.remove(&lid);
172                 }
173
174                 // do nothing for matches, etc. These can't escape
175                 _ => {}
176             }
177         }
178     }
179     fn decl_without_init(&mut self, _: HirId, _: Span) {}
180     fn mutate(&mut self, _: HirId, _: Span, _: &cmt_<'tcx>, _: MutateMode) {}
181 }
182
183 impl<'a, 'tcx> EscapeDelegate<'a, 'tcx> {
184     fn is_large_box(&self, ty: Ty<'tcx>) -> bool {
185         // Large types need to be boxed to avoid stack
186         // overflows.
187         if ty.is_box() {
188             self.cx.layout_of(ty.boxed_ty()).ok().map_or(0, |l| l.size.bytes()) > self.too_large_for_stack
189         } else {
190             false
191         }
192     }
193 }