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