]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/expr_use_visitor.rs
Rollup merge of #61048 - wizAmit:feature/nth_back_chunks, r=scottmcm
[rust.git] / src / librustc / middle / 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::LoanCause::*;
6 pub use self::ConsumeMode::*;
7 pub use self::MoveReason::*;
8 pub use self::MatchMode::*;
9 use self::TrackMatchMode::*;
10 use self::OverloadedCallType::*;
11
12 use crate::hir::def::{CtorOf, Res, DefKind};
13 use crate::hir::def_id::DefId;
14 use crate::infer::InferCtxt;
15 use crate::middle::mem_categorization as mc;
16 use crate::middle::region;
17 use crate::ty::{self, DefIdTree, TyCtxt, adjustment};
18
19 use crate::hir::{self, PatKind};
20 use std::rc::Rc;
21 use syntax::ptr::P;
22 use syntax_pos::Span;
23 use crate::util::nodemap::ItemLocalSet;
24
25 ///////////////////////////////////////////////////////////////////////////
26 // The Delegate trait
27
28 /// This trait defines the callbacks you can expect to receive when
29 /// employing the ExprUseVisitor.
30 pub trait Delegate<'tcx> {
31     // The value found at `cmt` is either copied or moved, depending
32     // on mode.
33     fn consume(&mut self,
34                consume_id: hir::HirId,
35                consume_span: Span,
36                cmt: &mc::cmt_<'tcx>,
37                mode: ConsumeMode);
38
39     // The value found at `cmt` has been determined to match the
40     // pattern binding `matched_pat`, and its subparts are being
41     // copied or moved depending on `mode`.  Note that `matched_pat`
42     // is called on all variant/structs in the pattern (i.e., the
43     // interior nodes of the pattern's tree structure) while
44     // consume_pat is called on the binding identifiers in the pattern
45     // (which are leaves of the pattern's tree structure).
46     //
47     // Note that variants/structs and identifiers are disjoint; thus
48     // `matched_pat` and `consume_pat` are never both called on the
49     // same input pattern structure (though of `consume_pat` can be
50     // called on a subpart of an input passed to `matched_pat).
51     fn matched_pat(&mut self,
52                    matched_pat: &hir::Pat,
53                    cmt: &mc::cmt_<'tcx>,
54                    mode: MatchMode);
55
56     // The value found at `cmt` is either copied or moved via the
57     // pattern binding `consume_pat`, depending on mode.
58     fn consume_pat(&mut self,
59                    consume_pat: &hir::Pat,
60                    cmt: &mc::cmt_<'tcx>,
61                    mode: ConsumeMode);
62
63     // The value found at `borrow` is being borrowed at the point
64     // `borrow_id` for the region `loan_region` with kind `bk`.
65     fn borrow(&mut self,
66               borrow_id: hir::HirId,
67               borrow_span: Span,
68               cmt: &mc::cmt_<'tcx>,
69               loan_region: ty::Region<'tcx>,
70               bk: ty::BorrowKind,
71               loan_cause: LoanCause);
72
73     // The local variable `id` is declared but not initialized.
74     fn decl_without_init(&mut self,
75                          id: hir::HirId,
76                          span: Span);
77
78     // The path at `cmt` is being assigned to.
79     fn mutate(&mut self,
80               assignment_id: hir::HirId,
81               assignment_span: Span,
82               assignee_cmt: &mc::cmt_<'tcx>,
83               mode: MutateMode);
84
85     // A nested closure or generator - only one layer deep.
86     fn nested_body(&mut self, _body_id: hir::BodyId) {}
87 }
88
89 #[derive(Copy, Clone, PartialEq, Debug)]
90 pub enum LoanCause {
91     ClosureCapture(Span),
92     AddrOf,
93     AutoRef,
94     AutoUnsafe,
95     RefBinding,
96     OverloadedOperator,
97     ClosureInvocation,
98     ForLoop,
99     MatchDiscriminant
100 }
101
102 #[derive(Copy, Clone, PartialEq, Debug)]
103 pub enum ConsumeMode {
104     Copy,                // reference to x where x has a type that copies
105     Move(MoveReason),    // reference to x where x has a type that moves
106 }
107
108 #[derive(Copy, Clone, PartialEq, Debug)]
109 pub enum MoveReason {
110     DirectRefMove,
111     PatBindingMove,
112     CaptureMove,
113 }
114
115 #[derive(Copy, Clone, PartialEq, Debug)]
116 pub enum MatchMode {
117     NonBindingMatch,
118     BorrowingMatch,
119     CopyingMatch,
120     MovingMatch,
121 }
122
123 #[derive(Copy, Clone, PartialEq, Debug)]
124 enum TrackMatchMode {
125     Unknown,
126     Definite(MatchMode),
127     Conflicting,
128 }
129
130 impl TrackMatchMode {
131     // Builds up the whole match mode for a pattern from its constituent
132     // parts.  The lattice looks like this:
133     //
134     //          Conflicting
135     //            /     \
136     //           /       \
137     //      Borrowing   Moving
138     //           \       /
139     //            \     /
140     //            Copying
141     //               |
142     //          NonBinding
143     //               |
144     //            Unknown
145     //
146     // examples:
147     //
148     // * `(_, some_int)` pattern is Copying, since
149     //   NonBinding + Copying => Copying
150     //
151     // * `(some_int, some_box)` pattern is Moving, since
152     //   Copying + Moving => Moving
153     //
154     // * `(ref x, some_box)` pattern is Conflicting, since
155     //   Borrowing + Moving => Conflicting
156     //
157     // Note that the `Unknown` and `Conflicting` states are
158     // represented separately from the other more interesting
159     // `Definite` states, which simplifies logic here somewhat.
160     fn lub(&mut self, mode: MatchMode) {
161         *self = match (*self, mode) {
162             // Note that clause order below is very significant.
163             (Unknown, new) => Definite(new),
164             (Definite(old), new) if old == new => Definite(old),
165
166             (Definite(old), NonBindingMatch) => Definite(old),
167             (Definite(NonBindingMatch), new) => Definite(new),
168
169             (Definite(old), CopyingMatch) => Definite(old),
170             (Definite(CopyingMatch), new) => Definite(new),
171
172             (Definite(_), _) => Conflicting,
173             (Conflicting, _) => *self,
174         };
175     }
176
177     fn match_mode(&self) -> MatchMode {
178         match *self {
179             Unknown => NonBindingMatch,
180             Definite(mode) => mode,
181             Conflicting => {
182                 // Conservatively return MovingMatch to let the
183                 // compiler continue to make progress.
184                 MovingMatch
185             }
186         }
187     }
188 }
189
190 #[derive(Copy, Clone, PartialEq, Debug)]
191 pub enum MutateMode {
192     Init,
193     JustWrite,    // x = y
194     WriteAndRead, // x += y
195 }
196
197 #[derive(Copy, Clone)]
198 enum OverloadedCallType {
199     FnOverloadedCall,
200     FnMutOverloadedCall,
201     FnOnceOverloadedCall,
202 }
203
204 impl OverloadedCallType {
205     fn from_trait_id(tcx: TyCtxt<'_, '_, '_>, trait_id: DefId) -> OverloadedCallType {
206         for &(maybe_function_trait, overloaded_call_type) in &[
207             (tcx.lang_items().fn_once_trait(), FnOnceOverloadedCall),
208             (tcx.lang_items().fn_mut_trait(), FnMutOverloadedCall),
209             (tcx.lang_items().fn_trait(), FnOverloadedCall)
210         ] {
211             match maybe_function_trait {
212                 Some(function_trait) if function_trait == trait_id => {
213                     return overloaded_call_type
214                 }
215                 _ => continue,
216             }
217         }
218
219         bug!("overloaded call didn't map to known function trait")
220     }
221
222     fn from_method_id(tcx: TyCtxt<'_, '_, '_>, method_id: DefId) -> OverloadedCallType {
223         let method = tcx.associated_item(method_id);
224         OverloadedCallType::from_trait_id(tcx, method.container.id())
225     }
226 }
227
228 ///////////////////////////////////////////////////////////////////////////
229 // The ExprUseVisitor type
230 //
231 // This is the code that actually walks the tree.
232 pub struct ExprUseVisitor<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
233     mc: mc::MemCategorizationContext<'a, 'gcx, 'tcx>,
234     delegate: &'a mut dyn Delegate<'tcx>,
235     param_env: ty::ParamEnv<'tcx>,
236 }
237
238 // If the MC results in an error, it's because the type check
239 // failed (or will fail, when the error is uncovered and reported
240 // during writeback). In this case, we just ignore this part of the
241 // code.
242 //
243 // Note that this macro appears similar to try!(), but, unlike try!(),
244 // it does not propagate the error.
245 macro_rules! return_if_err {
246     ($inp: expr) => (
247         match $inp {
248             Ok(v) => v,
249             Err(()) => {
250                 debug!("mc reported err");
251                 return
252             }
253         }
254     )
255 }
256
257 impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx, 'tcx> {
258     /// Creates the ExprUseVisitor, configuring it with the various options provided:
259     ///
260     /// - `delegate` -- who receives the callbacks
261     /// - `param_env` --- parameter environment for trait lookups (esp. pertaining to `Copy`)
262     /// - `region_scope_tree` --- region scope tree for the code being analyzed
263     /// - `tables` --- typeck results for the code being analyzed
264     /// - `rvalue_promotable_map` --- if you care about rvalue promotion, then provide
265     ///   the map here (it can be computed with `tcx.rvalue_promotable_map(def_id)`).
266     ///   `None` means that rvalues will be given more conservative lifetimes.
267     ///
268     /// See also `with_infer`, which is used *during* typeck.
269     pub fn new(delegate: &'a mut (dyn Delegate<'tcx>+'a),
270                tcx: TyCtxt<'a, 'tcx, 'tcx>,
271                param_env: ty::ParamEnv<'tcx>,
272                region_scope_tree: &'a region::ScopeTree,
273                tables: &'a ty::TypeckTables<'tcx>,
274                rvalue_promotable_map: Option<&'tcx ItemLocalSet>)
275                -> Self
276     {
277         ExprUseVisitor {
278             mc: mc::MemCategorizationContext::new(tcx,
279                                                   region_scope_tree,
280                                                   tables,
281                                                   rvalue_promotable_map),
282             delegate,
283             param_env,
284         }
285     }
286 }
287
288 impl<'a, 'gcx, 'tcx> ExprUseVisitor<'a, 'gcx, 'tcx> {
289     pub fn with_infer(delegate: &'a mut (dyn Delegate<'tcx>+'a),
290                       infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
291                       param_env: ty::ParamEnv<'tcx>,
292                       region_scope_tree: &'a region::ScopeTree,
293                       tables: &'a ty::TypeckTables<'tcx>)
294                       -> Self
295     {
296         ExprUseVisitor {
297             mc: mc::MemCategorizationContext::with_infer(infcx, region_scope_tree, tables),
298             delegate,
299             param_env,
300         }
301     }
302
303     pub fn consume_body(&mut self, body: &hir::Body) {
304         debug!("consume_body(body={:?})", body);
305
306         for arg in &body.arguments {
307             let arg_ty = return_if_err!(self.mc.pat_ty_adjusted(&arg.pat));
308             debug!("consume_body: arg_ty = {:?}", arg_ty);
309
310             let fn_body_scope_r =
311                 self.tcx().mk_region(ty::ReScope(
312                     region::Scope {
313                         id: body.value.hir_id.local_id,
314                         data: region::ScopeData::Node
315                 }));
316             let arg_cmt = Rc::new(self.mc.cat_rvalue(
317                 arg.hir_id,
318                 arg.pat.span,
319                 fn_body_scope_r, // Args live only as long as the fn body.
320                 arg_ty));
321
322             self.walk_irrefutable_pat(arg_cmt, &arg.pat);
323         }
324
325         self.consume_expr(&body.value);
326     }
327
328     fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
329         self.mc.tcx
330     }
331
332     fn delegate_consume(&mut self,
333                         consume_id: hir::HirId,
334                         consume_span: Span,
335                         cmt: &mc::cmt_<'tcx>) {
336         debug!("delegate_consume(consume_id={}, cmt={:?})",
337                consume_id, cmt);
338
339         let mode = copy_or_move(&self.mc, self.param_env, cmt, DirectRefMove);
340         self.delegate.consume(consume_id, consume_span, cmt, mode);
341     }
342
343     fn consume_exprs(&mut self, exprs: &[hir::Expr]) {
344         for expr in exprs {
345             self.consume_expr(&expr);
346         }
347     }
348
349     pub fn consume_expr(&mut self, expr: &hir::Expr) {
350         debug!("consume_expr(expr={:?})", expr);
351
352         let cmt = return_if_err!(self.mc.cat_expr(expr));
353         self.delegate_consume(expr.hir_id, expr.span, &cmt);
354         self.walk_expr(expr);
355     }
356
357     fn mutate_expr(&mut self,
358                    span: Span,
359                    assignment_expr: &hir::Expr,
360                    expr: &hir::Expr,
361                    mode: MutateMode) {
362         let cmt = return_if_err!(self.mc.cat_expr(expr));
363         self.delegate.mutate(assignment_expr.hir_id, span, &cmt, mode);
364         self.walk_expr(expr);
365     }
366
367     fn borrow_expr(&mut self,
368                    expr: &hir::Expr,
369                    r: ty::Region<'tcx>,
370                    bk: ty::BorrowKind,
371                    cause: LoanCause) {
372         debug!("borrow_expr(expr={:?}, r={:?}, bk={:?})",
373                expr, r, bk);
374
375         let cmt = return_if_err!(self.mc.cat_expr(expr));
376         self.delegate.borrow(expr.hir_id, expr.span, &cmt, r, bk, cause);
377
378         self.walk_expr(expr)
379     }
380
381     fn select_from_expr(&mut self, expr: &hir::Expr) {
382         self.walk_expr(expr)
383     }
384
385     pub fn walk_expr(&mut self, expr: &hir::Expr) {
386         debug!("walk_expr(expr={:?})", expr);
387
388         self.walk_adjustment(expr);
389
390         match expr.node {
391             hir::ExprKind::Path(_) => { }
392
393             hir::ExprKind::Type(ref subexpr, _) => {
394                 self.walk_expr(&subexpr)
395             }
396
397             hir::ExprKind::Unary(hir::UnDeref, ref base) => { // *base
398                 self.select_from_expr(&base);
399             }
400
401             hir::ExprKind::Field(ref base, _) => { // base.f
402                 self.select_from_expr(&base);
403             }
404
405             hir::ExprKind::Index(ref lhs, ref rhs) => { // lhs[rhs]
406                 self.select_from_expr(&lhs);
407                 self.consume_expr(&rhs);
408             }
409
410             hir::ExprKind::Call(ref callee, ref args) => { // callee(args)
411                 self.walk_callee(expr, &callee);
412                 self.consume_exprs(args);
413             }
414
415             hir::ExprKind::MethodCall(.., ref args) => { // callee.m(args)
416                 self.consume_exprs(args);
417             }
418
419             hir::ExprKind::Struct(_, ref fields, ref opt_with) => {
420                 self.walk_struct_expr(fields, opt_with);
421             }
422
423             hir::ExprKind::Tup(ref exprs) => {
424                 self.consume_exprs(exprs);
425             }
426
427             hir::ExprKind::Match(ref discr, ref arms, _) => {
428                 let discr_cmt = Rc::new(return_if_err!(self.mc.cat_expr(&discr)));
429                 let r = self.tcx().lifetimes.re_empty;
430                 self.borrow_expr(&discr, r, ty::ImmBorrow, MatchDiscriminant);
431
432                 // treatment of the discriminant is handled while walking the arms.
433                 for arm in arms {
434                     let mode = self.arm_move_mode(discr_cmt.clone(), arm);
435                     let mode = mode.match_mode();
436                     self.walk_arm(discr_cmt.clone(), arm, mode);
437                 }
438             }
439
440             hir::ExprKind::Array(ref exprs) => {
441                 self.consume_exprs(exprs);
442             }
443
444             hir::ExprKind::AddrOf(m, ref base) => {   // &base
445                 // make sure that the thing we are pointing out stays valid
446                 // for the lifetime `scope_r` of the resulting ptr:
447                 let expr_ty = return_if_err!(self.mc.expr_ty(expr));
448                 if let ty::Ref(r, _, _) = expr_ty.sty {
449                     let bk = ty::BorrowKind::from_mutbl(m);
450                     self.borrow_expr(&base, r, bk, AddrOf);
451                 }
452             }
453
454             hir::ExprKind::InlineAsm(ref ia, ref outputs, ref inputs) => {
455                 for (o, output) in ia.outputs.iter().zip(outputs) {
456                     if o.is_indirect {
457                         self.consume_expr(output);
458                     } else {
459                         self.mutate_expr(
460                             output.span,
461                             expr,
462                             output,
463                             if o.is_rw {
464                                 MutateMode::WriteAndRead
465                             } else {
466                                 MutateMode::JustWrite
467                             },
468                         );
469                     }
470                 }
471                 self.consume_exprs(inputs);
472             }
473
474             hir::ExprKind::Continue(..) |
475             hir::ExprKind::Lit(..) |
476             hir::ExprKind::Err => {}
477
478             hir::ExprKind::Loop(ref blk, _, _) => {
479                 self.walk_block(&blk);
480             }
481
482             hir::ExprKind::While(ref cond_expr, ref blk, _) => {
483                 self.consume_expr(&cond_expr);
484                 self.walk_block(&blk);
485             }
486
487             hir::ExprKind::Unary(_, ref lhs) => {
488                 self.consume_expr(&lhs);
489             }
490
491             hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
492                 self.consume_expr(&lhs);
493                 self.consume_expr(&rhs);
494             }
495
496             hir::ExprKind::Block(ref blk, _) => {
497                 self.walk_block(&blk);
498             }
499
500             hir::ExprKind::Break(_, ref opt_expr) | hir::ExprKind::Ret(ref opt_expr) => {
501                 if let Some(ref expr) = *opt_expr {
502                     self.consume_expr(&expr);
503                 }
504             }
505
506             hir::ExprKind::Assign(ref lhs, ref rhs) => {
507                 self.mutate_expr(expr.span, expr, &lhs, MutateMode::JustWrite);
508                 self.consume_expr(&rhs);
509             }
510
511             hir::ExprKind::Cast(ref base, _) => {
512                 self.consume_expr(&base);
513             }
514
515             hir::ExprKind::DropTemps(ref expr) => {
516                 self.consume_expr(&expr);
517             }
518
519             hir::ExprKind::AssignOp(_, ref lhs, ref rhs) => {
520                 if self.mc.tables.is_method_call(expr) {
521                     self.consume_expr(lhs);
522                 } else {
523                     self.mutate_expr(expr.span, expr, &lhs, MutateMode::WriteAndRead);
524                 }
525                 self.consume_expr(&rhs);
526             }
527
528             hir::ExprKind::Repeat(ref base, _) => {
529                 self.consume_expr(&base);
530             }
531
532             hir::ExprKind::Closure(_, _, body_id, fn_decl_span, _) => {
533                 self.delegate.nested_body(body_id);
534                 self.walk_captures(expr, fn_decl_span);
535             }
536
537             hir::ExprKind::Box(ref base) => {
538                 self.consume_expr(&base);
539             }
540
541             hir::ExprKind::Yield(ref value) => {
542                 self.consume_expr(&value);
543             }
544         }
545     }
546
547     fn walk_callee(&mut self, call: &hir::Expr, callee: &hir::Expr) {
548         let callee_ty = return_if_err!(self.mc.expr_ty_adjusted(callee));
549         debug!("walk_callee: callee={:?} callee_ty={:?}",
550                callee, callee_ty);
551         match callee_ty.sty {
552             ty::FnDef(..) | ty::FnPtr(_) => {
553                 self.consume_expr(callee);
554             }
555             ty::Error => { }
556             _ => {
557                 if let Some(def_id) = self.mc.tables.type_dependent_def_id(call.hir_id) {
558                     let call_scope = region::Scope {
559                         id: call.hir_id.local_id,
560                         data: region::ScopeData::Node
561                     };
562                     match OverloadedCallType::from_method_id(self.tcx(), def_id) {
563                         FnMutOverloadedCall => {
564                             let call_scope_r = self.tcx().mk_region(ty::ReScope(call_scope));
565                             self.borrow_expr(callee,
566                                             call_scope_r,
567                                             ty::MutBorrow,
568                                             ClosureInvocation);
569                         }
570                         FnOverloadedCall => {
571                             let call_scope_r = self.tcx().mk_region(ty::ReScope(call_scope));
572                             self.borrow_expr(callee,
573                                             call_scope_r,
574                                             ty::ImmBorrow,
575                                             ClosureInvocation);
576                         }
577                         FnOnceOverloadedCall => self.consume_expr(callee),
578                     }
579                 } else {
580                     self.tcx().sess.delay_span_bug(call.span,
581                                                    "no type-dependent def for overloaded call");
582                 }
583             }
584         }
585     }
586
587     fn walk_stmt(&mut self, stmt: &hir::Stmt) {
588         match stmt.node {
589             hir::StmtKind::Local(ref local) => {
590                 self.walk_local(&local);
591             }
592
593             hir::StmtKind::Item(_) => {
594                 // we don't visit nested items in this visitor,
595                 // only the fn body we were given.
596             }
597
598             hir::StmtKind::Expr(ref expr) |
599             hir::StmtKind::Semi(ref expr) => {
600                 self.consume_expr(&expr);
601             }
602         }
603     }
604
605     fn walk_local(&mut self, local: &hir::Local) {
606         match local.init {
607             None => {
608                 local.pat.each_binding(|_, hir_id, span, _| {
609                     self.delegate.decl_without_init(hir_id, span);
610                 })
611             }
612
613             Some(ref expr) => {
614                 // Variable declarations with
615                 // initializers are considered
616                 // "assigns", which is handled by
617                 // `walk_pat`:
618                 self.walk_expr(&expr);
619                 let init_cmt = Rc::new(return_if_err!(self.mc.cat_expr(&expr)));
620                 self.walk_irrefutable_pat(init_cmt, &local.pat);
621             }
622         }
623     }
624
625     /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
626     /// depending on its type.
627     fn walk_block(&mut self, blk: &hir::Block) {
628         debug!("walk_block(blk.hir_id={})", blk.hir_id);
629
630         for stmt in &blk.stmts {
631             self.walk_stmt(stmt);
632         }
633
634         if let Some(ref tail_expr) = blk.expr {
635             self.consume_expr(&tail_expr);
636         }
637     }
638
639     fn walk_struct_expr(&mut self,
640                         fields: &[hir::Field],
641                         opt_with: &Option<P<hir::Expr>>) {
642         // Consume the expressions supplying values for each field.
643         for field in fields {
644             self.consume_expr(&field.expr);
645         }
646
647         let with_expr = match *opt_with {
648             Some(ref w) => &**w,
649             None => { return; }
650         };
651
652         let with_cmt = Rc::new(return_if_err!(self.mc.cat_expr(&with_expr)));
653
654         // Select just those fields of the `with`
655         // expression that will actually be used
656         match with_cmt.ty.sty {
657             ty::Adt(adt, substs) if adt.is_struct() => {
658                 // Consume those fields of the with expression that are needed.
659                 for (f_index, with_field) in adt.non_enum_variant().fields.iter().enumerate() {
660                     let is_mentioned = fields.iter().any(|f| {
661                         self.tcx().field_index(f.hir_id, self.mc.tables) == f_index
662                     });
663                     if !is_mentioned {
664                         let cmt_field = self.mc.cat_field(
665                             &*with_expr,
666                             with_cmt.clone(),
667                             f_index,
668                             with_field.ident,
669                             with_field.ty(self.tcx(), substs)
670                         );
671                         self.delegate_consume(with_expr.hir_id, with_expr.span, &cmt_field);
672                     }
673                 }
674             }
675             _ => {
676                 // the base expression should always evaluate to a
677                 // struct; however, when EUV is run during typeck, it
678                 // may not. This will generate an error earlier in typeck,
679                 // so we can just ignore it.
680                 if !self.tcx().sess.has_errors() {
681                     span_bug!(
682                         with_expr.span,
683                         "with expression doesn't evaluate to a struct");
684                 }
685             }
686         }
687
688         // walk the with expression so that complex expressions
689         // are properly handled.
690         self.walk_expr(with_expr);
691     }
692
693     // Invoke the appropriate delegate calls for anything that gets
694     // consumed or borrowed as part of the automatic adjustment
695     // process.
696     fn walk_adjustment(&mut self, expr: &hir::Expr) {
697         let adjustments = self.mc.tables.expr_adjustments(expr);
698         let mut cmt = return_if_err!(self.mc.cat_expr_unadjusted(expr));
699         for adjustment in adjustments {
700             debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment);
701             match adjustment.kind {
702                 adjustment::Adjust::NeverToAny |
703                 adjustment::Adjust::Pointer(_)  => {
704                     // Creating a closure/fn-pointer or unsizing consumes
705                     // the input and stores it into the resulting rvalue.
706                     self.delegate_consume(expr.hir_id, expr.span, &cmt);
707                 }
708
709                 adjustment::Adjust::Deref(None) => {}
710
711                 // Autoderefs for overloaded Deref calls in fact reference
712                 // their receiver. That is, if we have `(*x)` where `x`
713                 // is of type `Rc<T>`, then this in fact is equivalent to
714                 // `x.deref()`. Since `deref()` is declared with `&self`,
715                 // this is an autoref of `x`.
716                 adjustment::Adjust::Deref(Some(ref deref)) => {
717                     let bk = ty::BorrowKind::from_mutbl(deref.mutbl);
718                     self.delegate.borrow(expr.hir_id, expr.span, &cmt, deref.region, bk, AutoRef);
719                 }
720
721                 adjustment::Adjust::Borrow(ref autoref) => {
722                     self.walk_autoref(expr, &cmt, autoref);
723                 }
724             }
725             cmt = return_if_err!(self.mc.cat_expr_adjusted(expr, cmt, &adjustment));
726         }
727     }
728
729     /// Walks the autoref `autoref` applied to the autoderef'd
730     /// `expr`. `cmt_base` is the mem-categorized form of `expr`
731     /// after all relevant autoderefs have occurred.
732     fn walk_autoref(&mut self,
733                     expr: &hir::Expr,
734                     cmt_base: &mc::cmt_<'tcx>,
735                     autoref: &adjustment::AutoBorrow<'tcx>) {
736         debug!("walk_autoref(expr.hir_id={} cmt_base={:?} autoref={:?})",
737                expr.hir_id,
738                cmt_base,
739                autoref);
740
741         match *autoref {
742             adjustment::AutoBorrow::Ref(r, m) => {
743                 self.delegate.borrow(expr.hir_id,
744                                      expr.span,
745                                      cmt_base,
746                                      r,
747                                      ty::BorrowKind::from_mutbl(m.into()),
748                                      AutoRef);
749             }
750
751             adjustment::AutoBorrow::RawPtr(m) => {
752                 debug!("walk_autoref: expr.hir_id={} cmt_base={:?}",
753                        expr.hir_id,
754                        cmt_base);
755
756                 // Converting from a &T to *T (or &mut T to *mut T) is
757                 // treated as borrowing it for the enclosing temporary
758                 // scope.
759                 let r = self.tcx().mk_region(ty::ReScope(
760                     region::Scope {
761                         id: expr.hir_id.local_id,
762                         data: region::ScopeData::Node
763                     }));
764
765                 self.delegate.borrow(expr.hir_id,
766                                      expr.span,
767                                      cmt_base,
768                                      r,
769                                      ty::BorrowKind::from_mutbl(m),
770                                      AutoUnsafe);
771             }
772         }
773     }
774
775     fn arm_move_mode(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm) -> TrackMatchMode {
776         let mut mode = Unknown;
777         for pat in &arm.pats {
778             self.determine_pat_move_mode(discr_cmt.clone(), &pat, &mut mode);
779         }
780         mode
781     }
782
783     fn walk_arm(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm, mode: MatchMode) {
784         for pat in &arm.pats {
785             self.walk_pat(discr_cmt.clone(), &pat, mode);
786         }
787
788         if let Some(hir::Guard::If(ref e)) = arm.guard {
789             self.consume_expr(e)
790         }
791
792         self.consume_expr(&arm.body);
793     }
794
795     /// Walks a pat that occurs in isolation (i.e., top-level of fn argument or
796     /// let binding, and *not* a match arm or nested pat.)
797     fn walk_irrefutable_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat) {
798         let mut mode = Unknown;
799         self.determine_pat_move_mode(cmt_discr.clone(), pat, &mut mode);
800         let mode = mode.match_mode();
801         self.walk_pat(cmt_discr, pat, mode);
802     }
803
804     /// Identifies any bindings within `pat` and accumulates within
805     /// `mode` whether the overall pattern/match structure is a move,
806     /// copy, or borrow.
807     fn determine_pat_move_mode(&mut self,
808                                cmt_discr: mc::cmt<'tcx>,
809                                pat: &hir::Pat,
810                                mode: &mut TrackMatchMode) {
811         debug!("determine_pat_move_mode cmt_discr={:?} pat={:?}", cmt_discr, pat);
812
813         return_if_err!(self.mc.cat_pattern(cmt_discr, pat, |cmt_pat, pat| {
814             if let PatKind::Binding(..) = pat.node {
815                 let bm = *self.mc.tables.pat_binding_modes()
816                                         .get(pat.hir_id)
817                                         .expect("missing binding mode");
818                 match bm {
819                     ty::BindByReference(..) =>
820                         mode.lub(BorrowingMatch),
821                     ty::BindByValue(..) => {
822                         match copy_or_move(&self.mc, self.param_env, &cmt_pat, PatBindingMove) {
823                             Copy => mode.lub(CopyingMatch),
824                             Move(..) => mode.lub(MovingMatch),
825                         }
826                     }
827                 }
828             }
829         }));
830     }
831
832     /// The core driver for walking a pattern; `match_mode` must be
833     /// established up front, e.g., via `determine_pat_move_mode` (see
834     /// also `walk_irrefutable_pat` for patterns that stand alone).
835     fn walk_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat, match_mode: MatchMode) {
836         debug!("walk_pat(cmt_discr={:?}, pat={:?})", cmt_discr, pat);
837
838         let tcx = self.tcx();
839         let ExprUseVisitor { ref mc, ref mut delegate, param_env } = *self;
840         return_if_err!(mc.cat_pattern(cmt_discr.clone(), pat, |cmt_pat, pat| {
841             if let PatKind::Binding(_, canonical_id, ..) = pat.node {
842                 debug!(
843                     "walk_pat: binding cmt_pat={:?} pat={:?} match_mode={:?}",
844                     cmt_pat,
845                     pat,
846                     match_mode,
847                 );
848                 if let Some(&bm) = mc.tables.pat_binding_modes().get(pat.hir_id) {
849                     debug!("walk_pat: pat.hir_id={:?} bm={:?}", pat.hir_id, bm);
850
851                     // pat_ty: the type of the binding being produced.
852                     let pat_ty = return_if_err!(mc.node_ty(pat.hir_id));
853                     debug!("walk_pat: pat_ty={:?}", pat_ty);
854
855                     // Each match binding is effectively an assignment to the
856                     // binding being produced.
857                     let def = Res::Local(canonical_id);
858                     if let Ok(ref binding_cmt) = mc.cat_res(pat.hir_id, pat.span, pat_ty, def) {
859                         delegate.mutate(pat.hir_id, pat.span, binding_cmt, MutateMode::Init);
860                     }
861
862                     // It is also a borrow or copy/move of the value being matched.
863                     match bm {
864                         ty::BindByReference(m) => {
865                             if let ty::Ref(r, _, _) = pat_ty.sty {
866                                 let bk = ty::BorrowKind::from_mutbl(m);
867                                 delegate.borrow(pat.hir_id, pat.span, &cmt_pat, r, bk, RefBinding);
868                             }
869                         }
870                         ty::BindByValue(..) => {
871                             let mode = copy_or_move(mc, param_env, &cmt_pat, PatBindingMove);
872                             debug!("walk_pat binding consuming pat");
873                             delegate.consume_pat(pat, &cmt_pat, mode);
874                         }
875                     }
876                 } else {
877                     tcx.sess.delay_span_bug(pat.span, "missing binding mode");
878                 }
879             }
880         }));
881
882         // Do a second pass over the pattern, calling `matched_pat` on
883         // the interior nodes (enum variants and structs), as opposed
884         // to the above loop's visit of than the bindings that form
885         // the leaves of the pattern tree structure.
886         return_if_err!(mc.cat_pattern(cmt_discr, pat, |cmt_pat, pat| {
887             let qpath = match pat.node {
888                 PatKind::Path(ref qpath) |
889                 PatKind::TupleStruct(ref qpath, ..) |
890                 PatKind::Struct(ref qpath, ..) => qpath,
891                 _ => return
892             };
893             let res = mc.tables.qpath_res(qpath, pat.hir_id);
894             match res {
895                 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
896                     let variant_did = mc.tcx.parent(variant_ctor_did).unwrap();
897                     let downcast_cmt = mc.cat_downcast_if_needed(pat, cmt_pat, variant_did);
898
899                     debug!("variantctor downcast_cmt={:?} pat={:?}", downcast_cmt, pat);
900                     delegate.matched_pat(pat, &downcast_cmt, match_mode);
901                 }
902                 Res::Def(DefKind::Variant, variant_did) => {
903                     let downcast_cmt = mc.cat_downcast_if_needed(pat, cmt_pat, variant_did);
904
905                     debug!("variant downcast_cmt={:?} pat={:?}", downcast_cmt, pat);
906                     delegate.matched_pat(pat, &downcast_cmt, match_mode);
907                 }
908                 Res::Def(DefKind::Struct, _)
909                 | Res::Def(DefKind::Ctor(..), _)
910                 | Res::Def(DefKind::Union, _)
911                 | Res::Def(DefKind::TyAlias, _)
912                 | Res::Def(DefKind::AssocTy, _)
913                 | Res::SelfTy(..) => {
914                     debug!("struct cmt_pat={:?} pat={:?}", cmt_pat, pat);
915                     delegate.matched_pat(pat, &cmt_pat, match_mode);
916                 }
917                 _ => {}
918             }
919         }));
920     }
921
922     fn walk_captures(&mut self, closure_expr: &hir::Expr, fn_decl_span: Span) {
923         debug!("walk_captures({:?})", closure_expr);
924
925         let closure_def_id = self.tcx().hir().local_def_id_from_hir_id(closure_expr.hir_id);
926         if let Some(upvars) = self.tcx().upvars(closure_def_id) {
927             for upvar in upvars.iter() {
928                 let var_hir_id = upvar.var_id();
929                 let upvar_id = ty::UpvarId {
930                     var_path: ty::UpvarPath { hir_id: var_hir_id },
931                     closure_expr_id: closure_def_id.to_local(),
932                 };
933                 let upvar_capture = self.mc.tables.upvar_capture(upvar_id);
934                 let cmt_var = return_if_err!(self.cat_captured_var(closure_expr.hir_id,
935                                                                    fn_decl_span,
936                                                                    upvar));
937                 match upvar_capture {
938                     ty::UpvarCapture::ByValue => {
939                         let mode = copy_or_move(&self.mc,
940                                                 self.param_env,
941                                                 &cmt_var,
942                                                 CaptureMove);
943                         self.delegate.consume(closure_expr.hir_id, upvar.span, &cmt_var, mode);
944                     }
945                     ty::UpvarCapture::ByRef(upvar_borrow) => {
946                         self.delegate.borrow(closure_expr.hir_id,
947                                              fn_decl_span,
948                                              &cmt_var,
949                                              upvar_borrow.region,
950                                              upvar_borrow.kind,
951                                              ClosureCapture(upvar.span));
952                     }
953                 }
954             }
955         }
956     }
957
958     fn cat_captured_var(&mut self,
959                         closure_hir_id: hir::HirId,
960                         closure_span: Span,
961                         upvar: &hir::Upvar)
962                         -> mc::McResult<mc::cmt_<'tcx>> {
963         // Create the cmt for the variable being borrowed, from the
964         // caller's perspective
965         let var_hir_id = upvar.var_id();
966         let var_ty = self.mc.node_ty(var_hir_id)?;
967         self.mc.cat_res(closure_hir_id, closure_span, var_ty, upvar.res)
968     }
969 }
970
971 fn copy_or_move<'a, 'gcx, 'tcx>(mc: &mc::MemCategorizationContext<'a, 'gcx, 'tcx>,
972                                 param_env: ty::ParamEnv<'tcx>,
973                                 cmt: &mc::cmt_<'tcx>,
974                                 move_reason: MoveReason)
975                                 -> ConsumeMode
976 {
977     if !mc.type_is_copy_modulo_regions(param_env, cmt.ty, cmt.span) {
978         Move(move_reason)
979     } else {
980         Copy
981     }
982 }