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