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