]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/escape.rs
Merge pull request #1345 from EpocSquadron/epocsquadron-documentation
[rust.git] / clippy_lints / src / escape.rs
1 use rustc::hir::*;
2 use rustc::hir::intravisit as visit;
3 use rustc::hir::map::Node::{NodeExpr, NodeStmt};
4 use rustc::infer::InferCtxt;
5 use rustc::lint::*;
6 use rustc::middle::expr_use_visitor::*;
7 use rustc::middle::mem_categorization::{cmt, Categorization};
8 use rustc::ty;
9 use rustc::ty::layout::TargetDataLayout;
10 use rustc::util::nodemap::NodeSet;
11 use syntax::ast::NodeId;
12 use syntax::codemap::Span;
13 use utils::span_lint;
14
15 pub struct Pass {
16     pub too_large_for_stack: u64,
17 }
18
19 /// **What it does:** Checks for usage of `Box<T>` where an unboxed `T` would
20 /// work fine.
21 ///
22 /// **Why is this bad?** This is an unnecessary allocation, and bad for
23 /// performance. It is only necessary to allocate if you wish to move the box
24 /// into something.
25 ///
26 /// **Known problems:** None.
27 ///
28 /// **Example:**
29 /// ```rust
30 /// fn main() {
31 ///     let x = Box::new(1);
32 ///     foo(*x);
33 ///     println!("{}", *x);
34 /// }
35 /// ```
36 declare_lint! {
37     pub BOXED_LOCAL,
38     Warn,
39     "using `Box<T>` where unnecessary"
40 }
41
42 fn is_non_trait_box(ty: ty::Ty) -> bool {
43     match ty.sty {
44         ty::TyBox(inner) => !inner.is_trait(),
45         _ => false,
46     }
47 }
48
49 struct EscapeDelegate<'a, 'tcx: 'a+'gcx, 'gcx: 'a> {
50     tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
51     set: NodeSet,
52     infcx: &'a InferCtxt<'a, 'gcx, 'gcx>,
53     target: TargetDataLayout,
54     too_large_for_stack: u64,
55 }
56
57 impl LintPass for Pass {
58     fn get_lints(&self) -> LintArray {
59         lint_array!(BOXED_LOCAL)
60     }
61 }
62
63 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
64     fn check_fn(
65         &mut self,
66         cx: &LateContext<'a, 'tcx>,
67         _: visit::FnKind<'tcx>,
68         decl: &'tcx FnDecl,
69         body: &'tcx Expr,
70         _: Span,
71         id: NodeId,
72     ) {
73         let param_env = ty::ParameterEnvironment::for_item(cx.tcx, id);
74
75         let infcx = cx.tcx.borrowck_fake_infer_ctxt(param_env);
76
77         // we store the infcx because it is expensive to recreate
78         // the context each time.
79         let mut v = EscapeDelegate {
80             tcx: cx.tcx,
81             set: NodeSet(),
82             infcx: &infcx,
83             target: TargetDataLayout::parse(cx.sess()),
84             too_large_for_stack: self.too_large_for_stack,
85         };
86
87         {
88             let mut vis = ExprUseVisitor::new(&mut v, &infcx);
89             vis.walk_fn(decl, body);
90         }
91
92         for node in v.set {
93             span_lint(cx,
94                       BOXED_LOCAL,
95                       cx.tcx.map.span(node),
96                       "local variable doesn't need to be boxed here");
97         }
98     }
99 }
100
101 impl<'a, 'tcx: 'a+'gcx, 'gcx: 'a> Delegate<'tcx> for EscapeDelegate<'a, 'tcx, 'gcx> {
102     fn consume(&mut self, _: NodeId, _: Span, cmt: cmt<'tcx>, mode: ConsumeMode) {
103         if let Categorization::Local(lid) = cmt.cat {
104             if self.set.contains(&lid) {
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     }
112     fn matched_pat(&mut self, _: &Pat, _: cmt<'tcx>, _: MatchMode) {}
113     fn consume_pat(&mut self, consume_pat: &Pat, cmt: cmt<'tcx>, _: ConsumeMode) {
114         let map = &self.tcx.map;
115         if map.is_argument(consume_pat.id) {
116             // Skip closure arguments
117             if let Some(NodeExpr(..)) = map.find(map.get_parent_node(consume_pat.id)) {
118                 return;
119             }
120             if is_non_trait_box(cmt.ty) && !self.is_large_box(cmt.ty) {
121                 self.set.insert(consume_pat.id);
122             }
123             return;
124         }
125         if let Categorization::Rvalue(..) = cmt.cat {
126             if let Some(NodeStmt(st)) = map.find(map.get_parent_node(cmt.id)) {
127                 if let StmtDecl(ref decl, _) = st.node {
128                     if let DeclLocal(ref loc) = decl.node {
129                         if let Some(ref ex) = loc.init {
130                             if let ExprBox(..) = ex.node {
131                                 if is_non_trait_box(cmt.ty) && !self.is_large_box(cmt.ty) {
132                                     // let x = box (...)
133                                     self.set.insert(consume_pat.id);
134                                 }
135                                 // TODO Box::new
136                                 // TODO vec![]
137                                 // TODO "foo".to_owned() and friends
138                             }
139                         }
140                     }
141                 }
142             }
143         }
144         if let Categorization::Local(lid) = cmt.cat {
145             if self.set.contains(&lid) {
146                 // let y = x where x is known
147                 // remove x, insert y
148                 self.set.insert(consume_pat.id);
149                 self.set.remove(&lid);
150             }
151         }
152
153     }
154     fn borrow(&mut self, borrow_id: NodeId, _: Span, cmt: cmt<'tcx>, _: &ty::Region, _: ty::BorrowKind,
155               loan_cause: LoanCause) {
156         use rustc::ty::adjustment::Adjust;
157
158         if let Categorization::Local(lid) = cmt.cat {
159             if self.set.contains(&lid) {
160                 if let Some(&Adjust::DerefRef { autoderefs, .. }) = self.tcx
161                                                                         .tables
162                                                                         .borrow()
163                                                                         .adjustments
164                                                                         .get(&borrow_id)
165                                                                         .map(|a| &a.kind) {
166                     if LoanCause::AutoRef == loan_cause {
167                         // x.foo()
168                         if autoderefs == 0 {
169                             self.set.remove(&lid); // Used without autodereffing (i.e. x.clone())
170                         }
171                     } else {
172                         span_bug!(cmt.span, "Unknown adjusted AutoRef");
173                     }
174                 } else if LoanCause::AddrOf == loan_cause {
175                     // &x
176                     if let Some(&Adjust::DerefRef { autoderefs, .. }) = self.tcx
177                                                                             .tables
178                                                                             .borrow()
179                                                                             .adjustments
180                                                                             .get(&self.tcx
181                                                                             .map
182                                                                             .get_parent_node(borrow_id))
183                                                                             .map(|a| &a.kind) {
184                         if autoderefs <= 1 {
185                             // foo(&x) where no extra autoreffing is happening
186                             self.set.remove(&lid);
187                         }
188                     }
189
190                 } else if LoanCause::MatchDiscriminant == loan_cause {
191                     self.set.remove(&lid); // `match x` can move
192                 }
193                 // do nothing for matches, etc. These can't escape
194             }
195         }
196     }
197     fn decl_without_init(&mut self, _: NodeId, _: Span) {}
198     fn mutate(&mut self, _: NodeId, _: Span, _: cmt<'tcx>, _: MutateMode) {}
199 }
200
201 impl<'a, 'tcx: 'a+'gcx, 'gcx: 'a> EscapeDelegate<'a, 'tcx, 'gcx> {
202     fn is_large_box(&self, ty: ty::Ty<'gcx>) -> bool {
203         // Large types need to be boxed to avoid stack
204         // overflows.
205         match ty.sty {
206             ty::TyBox(inner) => {
207                 if let Ok(layout) = inner.layout(self.infcx) {
208                     let size = layout.size(&self.target);
209                     size.bytes() > self.too_large_for_stack
210                 } else {
211                     false
212                 }
213             },
214             _ => false,
215         }
216     }
217 }