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