]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/escape.rs
Merge pull request #3285 from devonhollowood/pedantic-dogfood-items-after-statements
[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     fn check_fn(
69         &mut self,
70         cx: &LateContext<'a, 'tcx>,
71         _: visit::FnKind<'tcx>,
72         _: &'tcx FnDecl,
73         body: &'tcx Body,
74         _: Span,
75         node_id: NodeId,
76     ) {
77         let fn_def_id = cx.tcx.hir.local_def_id(node_id);
78         let mut v = EscapeDelegate {
79             cx,
80             set: NodeSet(),
81             too_large_for_stack: self.too_large_for_stack,
82         };
83
84         let region_scope_tree = &cx.tcx.region_scope_tree(fn_def_id);
85         ExprUseVisitor::new(&mut v, cx.tcx, cx.param_env, region_scope_tree, cx.tables, None).consume_body(body);
86
87         for node in v.set {
88             span_lint(
89                 cx,
90                 BOXED_LOCAL,
91                 cx.tcx.hir.span(node),
92                 "local variable doesn't need to be boxed here",
93             );
94         }
95     }
96 }
97
98 impl<'a, 'tcx> Delegate<'tcx> for EscapeDelegate<'a, 'tcx> {
99     fn consume(&mut self, _: NodeId, _: Span, cmt: &cmt_<'tcx>, mode: ConsumeMode) {
100         if let Categorization::Local(lid) = cmt.cat {
101             if let Move(DirectRefMove) = mode {
102                 // moved out or in. clearly can't be localized
103                 self.set.remove(&lid);
104             }
105         }
106     }
107     fn matched_pat(&mut self, _: &Pat, _: &cmt_<'tcx>, _: MatchMode) {}
108     fn consume_pat(&mut self, consume_pat: &Pat, cmt: &cmt_<'tcx>, _: ConsumeMode) {
109         let map = &self.cx.tcx.hir;
110         if map.is_argument(consume_pat.id) {
111             // Skip closure arguments
112             if let Some(Node::Expr(..)) = map.find(map.get_parent_node(consume_pat.id)) {
113                 return;
114             }
115             if is_non_trait_box(cmt.ty) && !self.is_large_box(cmt.ty) {
116                 self.set.insert(consume_pat.id);
117             }
118             return;
119         }
120         if let Categorization::Rvalue(..) = cmt.cat {
121             let id = map.hir_to_node_id(cmt.hir_id);
122             if let Some(Node::Stmt(st)) = map.find(map.get_parent_node(id)) {
123                 if let StmtKind::Decl(ref decl, _) = st.node {
124                     if let DeclKind::Local(ref loc) = decl.node {
125                         if let Some(ref ex) = loc.init {
126                             if let ExprKind::Box(..) = ex.node {
127                                 if is_non_trait_box(cmt.ty) && !self.is_large_box(cmt.ty) {
128                                     // let x = box (...)
129                                     self.set.insert(consume_pat.id);
130                                 }
131                                 // TODO Box::new
132                                 // TODO vec![]
133                                 // TODO "foo".to_owned() and friends
134                             }
135                         }
136                     }
137                 }
138             }
139         }
140         if let Categorization::Local(lid) = cmt.cat {
141             if self.set.contains(&lid) {
142                 // let y = x where x is known
143                 // remove x, insert y
144                 self.set.insert(consume_pat.id);
145                 self.set.remove(&lid);
146             }
147         }
148     }
149     fn borrow(&mut self, _: NodeId, _: Span, cmt: &cmt_<'tcx>, _: ty::Region<'_>, _: ty::BorrowKind, loan_cause: LoanCause) {
150         if let Categorization::Local(lid) = cmt.cat {
151             match loan_cause {
152                 // x.foo()
153                 // Used without autodereffing (i.e. x.clone())
154                 LoanCause::AutoRef |
155
156                 // &x
157                 // foo(&x) where no extra autoreffing is happening
158                 LoanCause::AddrOf |
159
160                 // `match x` can move
161                 LoanCause::MatchDiscriminant => {
162                     self.set.remove(&lid);
163                 }
164
165                 // do nothing for matches, etc. These can't escape
166                 _ => {}
167             }
168         }
169     }
170     fn decl_without_init(&mut self, _: NodeId, _: Span) {}
171     fn mutate(&mut self, _: NodeId, _: Span, _: &cmt_<'tcx>, _: MutateMode) {}
172 }
173
174 impl<'a, 'tcx> EscapeDelegate<'a, 'tcx> {
175     fn is_large_box(&self, ty: Ty<'tcx>) -> bool {
176         // Large types need to be boxed to avoid stack
177         // overflows.
178         if ty.is_box() {
179             self.cx.layout_of(ty.boxed_ty()).ok().map_or(0, |l| l.size.bytes()) > self.too_large_for_stack
180         } else {
181             false
182         }
183     }
184 }