]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/expr_use_visitor.rs
Add some type-alias-impl-trait regression tests
[rust.git] / src / librustc_typeck / expr_use_visitor.rs
1 //! A different sort of visitor for walking fn bodies. Unlike the
2 //! normal visitor, which just walks the entire body in one shot, the
3 //! `ExprUseVisitor` determines how expressions are being used.
4
5 pub use self::ConsumeMode::*;
6
7 // Export these here so that Clippy can use them.
8 pub use mc::{Place, PlaceBase, Projection};
9
10 use rustc::infer::InferCtxt;
11 use rustc::ty::{self, adjustment, TyCtxt};
12 use rustc_hir as hir;
13 use rustc_hir::def::Res;
14 use rustc_hir::def_id::DefId;
15 use rustc_hir::PatKind;
16
17 use crate::mem_categorization as mc;
18 use rustc_span::Span;
19
20 ///////////////////////////////////////////////////////////////////////////
21 // The Delegate trait
22
23 /// This trait defines the callbacks you can expect to receive when
24 /// employing the ExprUseVisitor.
25 pub trait Delegate<'tcx> {
26     // The value found at `place` is either copied or moved, depending
27     // on mode.
28     fn consume(&mut self, place: &mc::Place<'tcx>, mode: ConsumeMode);
29
30     // The value found at `place` is being borrowed with kind `bk`.
31     fn borrow(&mut self, place: &mc::Place<'tcx>, bk: ty::BorrowKind);
32
33     // The path at `place` is being assigned to.
34     fn mutate(&mut self, assignee_place: &mc::Place<'tcx>);
35 }
36
37 #[derive(Copy, Clone, PartialEq, Debug)]
38 pub enum ConsumeMode {
39     Copy, // reference to x where x has a type that copies
40     Move, // reference to x where x has a type that moves
41 }
42
43 #[derive(Copy, Clone, PartialEq, Debug)]
44 pub enum MutateMode {
45     Init,
46     JustWrite,    // x = y
47     WriteAndRead, // x += y
48 }
49
50 ///////////////////////////////////////////////////////////////////////////
51 // The ExprUseVisitor type
52 //
53 // This is the code that actually walks the tree.
54 pub struct ExprUseVisitor<'a, 'tcx> {
55     mc: mc::MemCategorizationContext<'a, 'tcx>,
56     delegate: &'a mut dyn Delegate<'tcx>,
57 }
58
59 // If the MC results in an error, it's because the type check
60 // failed (or will fail, when the error is uncovered and reported
61 // during writeback). In this case, we just ignore this part of the
62 // code.
63 //
64 // Note that this macro appears similar to try!(), but, unlike try!(),
65 // it does not propagate the error.
66 macro_rules! return_if_err {
67     ($inp: expr) => {
68         match $inp {
69             Ok(v) => v,
70             Err(()) => {
71                 debug!("mc reported err");
72                 return;
73             }
74         }
75     };
76 }
77
78 impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
79     /// Creates the ExprUseVisitor, configuring it with the various options provided:
80     ///
81     /// - `delegate` -- who receives the callbacks
82     /// - `param_env` --- parameter environment for trait lookups (esp. pertaining to `Copy`)
83     /// - `tables` --- typeck results for the code being analyzed
84     pub fn new(
85         delegate: &'a mut (dyn Delegate<'tcx> + 'a),
86         infcx: &'a InferCtxt<'a, 'tcx>,
87         body_owner: DefId,
88         param_env: ty::ParamEnv<'tcx>,
89         tables: &'a ty::TypeckTables<'tcx>,
90     ) -> Self {
91         ExprUseVisitor {
92             mc: mc::MemCategorizationContext::new(infcx, param_env, body_owner, tables),
93             delegate,
94         }
95     }
96
97     pub fn consume_body(&mut self, body: &hir::Body<'_>) {
98         debug!("consume_body(body={:?})", body);
99
100         for param in body.params {
101             let param_ty = return_if_err!(self.mc.pat_ty_adjusted(&param.pat));
102             debug!("consume_body: param_ty = {:?}", param_ty);
103
104             let param_place = self.mc.cat_rvalue(param.hir_id, param.pat.span, param_ty);
105
106             self.walk_irrefutable_pat(&param_place, &param.pat);
107         }
108
109         self.consume_expr(&body.value);
110     }
111
112     fn tcx(&self) -> TyCtxt<'tcx> {
113         self.mc.tcx()
114     }
115
116     fn delegate_consume(&mut self, place: &Place<'tcx>) {
117         debug!("delegate_consume(place={:?})", place);
118
119         let mode = copy_or_move(&self.mc, place);
120         self.delegate.consume(place, mode);
121     }
122
123     fn consume_exprs(&mut self, exprs: &[hir::Expr<'_>]) {
124         for expr in exprs {
125             self.consume_expr(&expr);
126         }
127     }
128
129     pub fn consume_expr(&mut self, expr: &hir::Expr<'_>) {
130         debug!("consume_expr(expr={:?})", expr);
131
132         let place = return_if_err!(self.mc.cat_expr(expr));
133         self.delegate_consume(&place);
134         self.walk_expr(expr);
135     }
136
137     fn mutate_expr(&mut self, expr: &hir::Expr<'_>) {
138         let place = return_if_err!(self.mc.cat_expr(expr));
139         self.delegate.mutate(&place);
140         self.walk_expr(expr);
141     }
142
143     fn borrow_expr(&mut self, expr: &hir::Expr<'_>, bk: ty::BorrowKind) {
144         debug!("borrow_expr(expr={:?}, bk={:?})", expr, bk);
145
146         let place = return_if_err!(self.mc.cat_expr(expr));
147         self.delegate.borrow(&place, bk);
148
149         self.walk_expr(expr)
150     }
151
152     fn select_from_expr(&mut self, expr: &hir::Expr<'_>) {
153         self.walk_expr(expr)
154     }
155
156     pub fn walk_expr(&mut self, expr: &hir::Expr<'_>) {
157         debug!("walk_expr(expr={:?})", expr);
158
159         self.walk_adjustment(expr);
160
161         match expr.kind {
162             hir::ExprKind::Path(_) => {}
163
164             hir::ExprKind::Type(ref subexpr, _) => self.walk_expr(subexpr),
165
166             hir::ExprKind::Unary(hir::UnOp::UnDeref, ref base) => {
167                 // *base
168                 self.select_from_expr(base);
169             }
170
171             hir::ExprKind::Field(ref base, _) => {
172                 // base.f
173                 self.select_from_expr(base);
174             }
175
176             hir::ExprKind::Index(ref lhs, ref rhs) => {
177                 // lhs[rhs]
178                 self.select_from_expr(lhs);
179                 self.consume_expr(rhs);
180             }
181
182             hir::ExprKind::Call(ref callee, ref args) => {
183                 // callee(args)
184                 self.consume_expr(callee);
185                 self.consume_exprs(args);
186             }
187
188             hir::ExprKind::MethodCall(.., ref args) => {
189                 // callee.m(args)
190                 self.consume_exprs(args);
191             }
192
193             hir::ExprKind::Struct(_, ref fields, ref opt_with) => {
194                 self.walk_struct_expr(fields, opt_with);
195             }
196
197             hir::ExprKind::Tup(ref exprs) => {
198                 self.consume_exprs(exprs);
199             }
200
201             hir::ExprKind::Match(ref discr, arms, _) => {
202                 let discr_place = return_if_err!(self.mc.cat_expr(&discr));
203                 self.borrow_expr(&discr, ty::ImmBorrow);
204
205                 // treatment of the discriminant is handled while walking the arms.
206                 for arm in arms {
207                     self.walk_arm(&discr_place, arm);
208                 }
209             }
210
211             hir::ExprKind::Array(ref exprs) => {
212                 self.consume_exprs(exprs);
213             }
214
215             hir::ExprKind::AddrOf(_, m, ref base) => {
216                 // &base
217                 // make sure that the thing we are pointing out stays valid
218                 // for the lifetime `scope_r` of the resulting ptr:
219                 let bk = ty::BorrowKind::from_mutbl(m);
220                 self.borrow_expr(&base, bk);
221             }
222
223             hir::ExprKind::InlineAsm(ref ia) => {
224                 for (o, output) in ia.inner.outputs.iter().zip(ia.outputs_exprs) {
225                     if o.is_indirect {
226                         self.consume_expr(output);
227                     } else {
228                         self.mutate_expr(output);
229                     }
230                 }
231                 self.consume_exprs(&ia.inputs_exprs);
232             }
233
234             hir::ExprKind::Continue(..) | hir::ExprKind::Lit(..) | hir::ExprKind::Err => {}
235
236             hir::ExprKind::Loop(ref blk, _, _) => {
237                 self.walk_block(blk);
238             }
239
240             hir::ExprKind::Unary(_, ref lhs) => {
241                 self.consume_expr(lhs);
242             }
243
244             hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
245                 self.consume_expr(lhs);
246                 self.consume_expr(rhs);
247             }
248
249             hir::ExprKind::Block(ref blk, _) => {
250                 self.walk_block(blk);
251             }
252
253             hir::ExprKind::Break(_, ref opt_expr) | hir::ExprKind::Ret(ref opt_expr) => {
254                 if let Some(ref expr) = *opt_expr {
255                     self.consume_expr(expr);
256                 }
257             }
258
259             hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
260                 self.mutate_expr(lhs);
261                 self.consume_expr(rhs);
262             }
263
264             hir::ExprKind::Cast(ref base, _) => {
265                 self.consume_expr(base);
266             }
267
268             hir::ExprKind::DropTemps(ref expr) => {
269                 self.consume_expr(expr);
270             }
271
272             hir::ExprKind::AssignOp(_, ref lhs, ref rhs) => {
273                 if self.mc.tables.is_method_call(expr) {
274                     self.consume_expr(lhs);
275                 } else {
276                     self.mutate_expr(lhs);
277                 }
278                 self.consume_expr(rhs);
279             }
280
281             hir::ExprKind::Repeat(ref base, _) => {
282                 self.consume_expr(base);
283             }
284
285             hir::ExprKind::Closure(_, _, _, fn_decl_span, _) => {
286                 self.walk_captures(expr, fn_decl_span);
287             }
288
289             hir::ExprKind::Box(ref base) => {
290                 self.consume_expr(base);
291             }
292
293             hir::ExprKind::Yield(ref value, _) => {
294                 self.consume_expr(value);
295             }
296         }
297     }
298
299     fn walk_stmt(&mut self, stmt: &hir::Stmt<'_>) {
300         match stmt.kind {
301             hir::StmtKind::Local(ref local) => {
302                 self.walk_local(&local);
303             }
304
305             hir::StmtKind::Item(_) => {
306                 // We don't visit nested items in this visitor,
307                 // only the fn body we were given.
308             }
309
310             hir::StmtKind::Expr(ref expr) | hir::StmtKind::Semi(ref expr) => {
311                 self.consume_expr(&expr);
312             }
313         }
314     }
315
316     fn walk_local(&mut self, local: &hir::Local<'_>) {
317         if let Some(ref expr) = local.init {
318             // Variable declarations with
319             // initializers are considered
320             // "assigns", which is handled by
321             // `walk_pat`:
322             self.walk_expr(&expr);
323             let init_place = return_if_err!(self.mc.cat_expr(&expr));
324             self.walk_irrefutable_pat(&init_place, &local.pat);
325         }
326     }
327
328     /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
329     /// depending on its type.
330     fn walk_block(&mut self, blk: &hir::Block<'_>) {
331         debug!("walk_block(blk.hir_id={})", blk.hir_id);
332
333         for stmt in blk.stmts {
334             self.walk_stmt(stmt);
335         }
336
337         if let Some(ref tail_expr) = blk.expr {
338             self.consume_expr(&tail_expr);
339         }
340     }
341
342     fn walk_struct_expr(
343         &mut self,
344         fields: &[hir::Field<'_>],
345         opt_with: &Option<&'hir hir::Expr<'_>>,
346     ) {
347         // Consume the expressions supplying values for each field.
348         for field in fields {
349             self.consume_expr(&field.expr);
350         }
351
352         let with_expr = match *opt_with {
353             Some(ref w) => &**w,
354             None => {
355                 return;
356             }
357         };
358
359         let with_place = return_if_err!(self.mc.cat_expr(&with_expr));
360
361         // Select just those fields of the `with`
362         // expression that will actually be used
363         match with_place.ty.kind {
364             ty::Adt(adt, substs) if adt.is_struct() => {
365                 // Consume those fields of the with expression that are needed.
366                 for (f_index, with_field) in adt.non_enum_variant().fields.iter().enumerate() {
367                     let is_mentioned = fields
368                         .iter()
369                         .any(|f| self.tcx().field_index(f.hir_id, self.mc.tables) == f_index);
370                     if !is_mentioned {
371                         let field_place = self.mc.cat_projection(
372                             &*with_expr,
373                             with_place.clone(),
374                             with_field.ty(self.tcx(), substs),
375                         );
376                         self.delegate_consume(&field_place);
377                     }
378                 }
379             }
380             _ => {
381                 // the base expression should always evaluate to a
382                 // struct; however, when EUV is run during typeck, it
383                 // may not. This will generate an error earlier in typeck,
384                 // so we can just ignore it.
385                 if !self.tcx().sess.has_errors() {
386                     span_bug!(with_expr.span, "with expression doesn't evaluate to a struct");
387                 }
388             }
389         }
390
391         // walk the with expression so that complex expressions
392         // are properly handled.
393         self.walk_expr(with_expr);
394     }
395
396     // Invoke the appropriate delegate calls for anything that gets
397     // consumed or borrowed as part of the automatic adjustment
398     // process.
399     fn walk_adjustment(&mut self, expr: &hir::Expr<'_>) {
400         let adjustments = self.mc.tables.expr_adjustments(expr);
401         let mut place = return_if_err!(self.mc.cat_expr_unadjusted(expr));
402         for adjustment in adjustments {
403             debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment);
404             match adjustment.kind {
405                 adjustment::Adjust::NeverToAny | adjustment::Adjust::Pointer(_) => {
406                     // Creating a closure/fn-pointer or unsizing consumes
407                     // the input and stores it into the resulting rvalue.
408                     self.delegate_consume(&place);
409                 }
410
411                 adjustment::Adjust::Deref(None) => {}
412
413                 // Autoderefs for overloaded Deref calls in fact reference
414                 // their receiver. That is, if we have `(*x)` where `x`
415                 // is of type `Rc<T>`, then this in fact is equivalent to
416                 // `x.deref()`. Since `deref()` is declared with `&self`,
417                 // this is an autoref of `x`.
418                 adjustment::Adjust::Deref(Some(ref deref)) => {
419                     let bk = ty::BorrowKind::from_mutbl(deref.mutbl);
420                     self.delegate.borrow(&place, bk);
421                 }
422
423                 adjustment::Adjust::Borrow(ref autoref) => {
424                     self.walk_autoref(expr, &place, autoref);
425                 }
426             }
427             place = return_if_err!(self.mc.cat_expr_adjusted(expr, place, &adjustment));
428         }
429     }
430
431     /// Walks the autoref `autoref` applied to the autoderef'd
432     /// `expr`. `base_place` is the mem-categorized form of `expr`
433     /// after all relevant autoderefs have occurred.
434     fn walk_autoref(
435         &mut self,
436         expr: &hir::Expr<'_>,
437         base_place: &mc::Place<'tcx>,
438         autoref: &adjustment::AutoBorrow<'tcx>,
439     ) {
440         debug!(
441             "walk_autoref(expr.hir_id={} base_place={:?} autoref={:?})",
442             expr.hir_id, base_place, autoref
443         );
444
445         match *autoref {
446             adjustment::AutoBorrow::Ref(_, m) => {
447                 self.delegate.borrow(base_place, ty::BorrowKind::from_mutbl(m.into()));
448             }
449
450             adjustment::AutoBorrow::RawPtr(m) => {
451                 debug!("walk_autoref: expr.hir_id={} base_place={:?}", expr.hir_id, base_place);
452
453                 self.delegate.borrow(base_place, ty::BorrowKind::from_mutbl(m));
454             }
455         }
456     }
457
458     fn walk_arm(&mut self, discr_place: &Place<'tcx>, arm: &hir::Arm<'_>) {
459         self.walk_pat(discr_place, &arm.pat);
460
461         if let Some(hir::Guard::If(ref e)) = arm.guard {
462             self.consume_expr(e)
463         }
464
465         self.consume_expr(&arm.body);
466     }
467
468     /// Walks a pat that occurs in isolation (i.e., top-level of fn argument or
469     /// let binding, and *not* a match arm or nested pat.)
470     fn walk_irrefutable_pat(&mut self, discr_place: &Place<'tcx>, pat: &hir::Pat<'_>) {
471         self.walk_pat(discr_place, pat);
472     }
473
474     /// The core driver for walking a pattern
475     fn walk_pat(&mut self, discr_place: &Place<'tcx>, pat: &hir::Pat<'_>) {
476         debug!("walk_pat(discr_place={:?}, pat={:?})", discr_place, pat);
477
478         let tcx = self.tcx();
479         let ExprUseVisitor { ref mc, ref mut delegate } = *self;
480         return_if_err!(mc.cat_pattern(discr_place.clone(), pat, |place, pat| {
481             if let PatKind::Binding(_, canonical_id, ..) = pat.kind {
482                 debug!("walk_pat: binding place={:?} pat={:?}", place, pat,);
483                 if let Some(bm) = mc.tables.extract_binding_mode(tcx.sess, pat.hir_id, pat.span) {
484                     debug!("walk_pat: pat.hir_id={:?} bm={:?}", pat.hir_id, bm);
485
486                     // pat_ty: the type of the binding being produced.
487                     let pat_ty = return_if_err!(mc.node_ty(pat.hir_id));
488                     debug!("walk_pat: pat_ty={:?}", pat_ty);
489
490                     // Each match binding is effectively an assignment to the
491                     // binding being produced.
492                     let def = Res::Local(canonical_id);
493                     if let Ok(ref binding_place) = mc.cat_res(pat.hir_id, pat.span, pat_ty, def) {
494                         delegate.mutate(binding_place);
495                     }
496
497                     // It is also a borrow or copy/move of the value being matched.
498                     match bm {
499                         ty::BindByReference(m) => {
500                             let bk = ty::BorrowKind::from_mutbl(m);
501                             delegate.borrow(place, bk);
502                         }
503                         ty::BindByValue(..) => {
504                             let mode = copy_or_move(mc, place);
505                             debug!("walk_pat binding consuming pat");
506                             delegate.consume(place, mode);
507                         }
508                     }
509                 }
510             }
511         }));
512     }
513
514     fn walk_captures(&mut self, closure_expr: &hir::Expr<'_>, fn_decl_span: Span) {
515         debug!("walk_captures({:?})", closure_expr);
516
517         let closure_def_id = self.tcx().hir().local_def_id(closure_expr.hir_id);
518         if let Some(upvars) = self.tcx().upvars(closure_def_id) {
519             for &var_id in upvars.keys() {
520                 let upvar_id = ty::UpvarId {
521                     var_path: ty::UpvarPath { hir_id: var_id },
522                     closure_expr_id: closure_def_id.to_local(),
523                 };
524                 let upvar_capture = self.mc.tables.upvar_capture(upvar_id);
525                 let captured_place = return_if_err!(self.cat_captured_var(
526                     closure_expr.hir_id,
527                     fn_decl_span,
528                     var_id,
529                 ));
530                 match upvar_capture {
531                     ty::UpvarCapture::ByValue => {
532                         let mode = copy_or_move(&self.mc, &captured_place);
533                         self.delegate.consume(&captured_place, mode);
534                     }
535                     ty::UpvarCapture::ByRef(upvar_borrow) => {
536                         self.delegate.borrow(&captured_place, upvar_borrow.kind);
537                     }
538                 }
539             }
540         }
541     }
542
543     fn cat_captured_var(
544         &mut self,
545         closure_hir_id: hir::HirId,
546         closure_span: Span,
547         var_id: hir::HirId,
548     ) -> mc::McResult<mc::Place<'tcx>> {
549         // Create the place for the variable being borrowed, from the
550         // perspective of the creator (parent) of the closure.
551         let var_ty = self.mc.node_ty(var_id)?;
552         self.mc.cat_res(closure_hir_id, closure_span, var_ty, Res::Local(var_id))
553     }
554 }
555
556 fn copy_or_move<'a, 'tcx>(
557     mc: &mc::MemCategorizationContext<'a, 'tcx>,
558     place: &Place<'tcx>,
559 ) -> ConsumeMode {
560     if !mc.type_is_copy_modulo_regions(place.ty, place.span) { Move } else { Copy }
561 }