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