]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/expr_use_visitor.rs
4075d28a396a513ec61e90f52b75cc83bfb1021d
[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     param_env: ty::ParamEnv<'tcx>,
246 }
247
248 // If the TYPER results in an error, it's because the type check
249 // failed (or will fail, when the error is uncovered and reported
250 // during writeback). In this case, we just ignore this part of the
251 // code.
252 //
253 // Note that this macro appears similar to try!(), but, unlike try!(),
254 // it does not propagate the error.
255 macro_rules! return_if_err {
256     ($inp: expr) => (
257         match $inp {
258             Ok(v) => v,
259             Err(()) => {
260                 debug!("mc reported err");
261                 return
262             }
263         }
264     )
265 }
266
267 impl<'a, 'gcx, 'tcx> ExprUseVisitor<'a, 'gcx, 'tcx> {
268     pub fn new(delegate: &'a mut (Delegate<'tcx>+'a),
269                region_maps: &'a RegionMaps,
270                infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
271                param_env: ty::ParamEnv<'tcx>)
272                -> Self
273     {
274         ExprUseVisitor {
275             mc: mc::MemCategorizationContext::new(infcx, region_maps),
276             delegate,
277             param_env,
278         }
279     }
280
281     pub fn consume_body(&mut self, body: &hir::Body) {
282         debug!("consume_body(body={:?})", body);
283
284         for arg in &body.arguments {
285             let arg_ty = return_if_err!(self.mc.infcx.node_ty(arg.pat.id));
286
287             let fn_body_scope_r = self.tcx().node_scope_region(body.value.id);
288             let arg_cmt = self.mc.cat_rvalue(
289                 arg.id,
290                 arg.pat.span,
291                 fn_body_scope_r, // Args live only as long as the fn body.
292                 arg_ty);
293
294             self.walk_irrefutable_pat(arg_cmt, &arg.pat);
295         }
296
297         self.consume_expr(&body.value);
298     }
299
300     fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
301         self.mc.infcx.tcx
302     }
303
304     fn delegate_consume(&mut self,
305                         consume_id: ast::NodeId,
306                         consume_span: Span,
307                         cmt: mc::cmt<'tcx>) {
308         debug!("delegate_consume(consume_id={}, cmt={:?})",
309                consume_id, cmt);
310
311         let mode = copy_or_move(self.mc.infcx, self.param_env, &cmt, DirectRefMove);
312         self.delegate.consume(consume_id, consume_span, cmt, mode);
313     }
314
315     fn consume_exprs(&mut self, exprs: &[hir::Expr]) {
316         for expr in exprs {
317             self.consume_expr(&expr);
318         }
319     }
320
321     pub fn consume_expr(&mut self, expr: &hir::Expr) {
322         debug!("consume_expr(expr={:?})", expr);
323
324         let cmt = return_if_err!(self.mc.cat_expr(expr));
325         self.delegate_consume(expr.id, expr.span, cmt);
326         self.walk_expr(expr);
327     }
328
329     fn mutate_expr(&mut self,
330                    assignment_expr: &hir::Expr,
331                    expr: &hir::Expr,
332                    mode: MutateMode) {
333         let cmt = return_if_err!(self.mc.cat_expr(expr));
334         self.delegate.mutate(assignment_expr.id, assignment_expr.span, cmt, mode);
335         self.walk_expr(expr);
336     }
337
338     fn borrow_expr(&mut self,
339                    expr: &hir::Expr,
340                    r: ty::Region<'tcx>,
341                    bk: ty::BorrowKind,
342                    cause: LoanCause) {
343         debug!("borrow_expr(expr={:?}, r={:?}, bk={:?})",
344                expr, r, bk);
345
346         let cmt = return_if_err!(self.mc.cat_expr(expr));
347         self.delegate.borrow(expr.id, expr.span, cmt, r, bk, cause);
348
349         self.walk_expr(expr)
350     }
351
352     fn select_from_expr(&mut self, expr: &hir::Expr) {
353         self.walk_expr(expr)
354     }
355
356     pub fn walk_expr(&mut self, expr: &hir::Expr) {
357         debug!("walk_expr(expr={:?})", expr);
358
359         self.walk_adjustment(expr);
360
361         match expr.node {
362             hir::ExprPath(_) => { }
363
364             hir::ExprType(ref subexpr, _) => {
365                 self.walk_expr(&subexpr)
366             }
367
368             hir::ExprUnary(hir::UnDeref, ref base) => {      // *base
369                 self.select_from_expr(&base);
370             }
371
372             hir::ExprField(ref base, _) => {         // base.f
373                 self.select_from_expr(&base);
374             }
375
376             hir::ExprTupField(ref base, _) => {         // base.<n>
377                 self.select_from_expr(&base);
378             }
379
380             hir::ExprIndex(ref lhs, ref rhs) => {       // lhs[rhs]
381                 self.select_from_expr(&lhs);
382                 self.consume_expr(&rhs);
383             }
384
385             hir::ExprCall(ref callee, ref args) => {    // callee(args)
386                 self.walk_callee(expr, &callee);
387                 self.consume_exprs(args);
388             }
389
390             hir::ExprMethodCall(.., ref args) => { // callee.m(args)
391                 self.consume_exprs(args);
392             }
393
394             hir::ExprStruct(_, ref fields, ref opt_with) => {
395                 self.walk_struct_expr(fields, opt_with);
396             }
397
398             hir::ExprTup(ref exprs) => {
399                 self.consume_exprs(exprs);
400             }
401
402             hir::ExprIf(ref cond_expr, ref then_expr, ref opt_else_expr) => {
403                 self.consume_expr(&cond_expr);
404                 self.walk_expr(&then_expr);
405                 if let Some(ref else_expr) = *opt_else_expr {
406                     self.consume_expr(&else_expr);
407                 }
408             }
409
410             hir::ExprMatch(ref discr, ref arms, _) => {
411                 let discr_cmt = return_if_err!(self.mc.cat_expr(&discr));
412                 let r = self.tcx().types.re_empty;
413                 self.borrow_expr(&discr, r, ty::ImmBorrow, MatchDiscriminant);
414
415                 // treatment of the discriminant is handled while walking the arms.
416                 for arm in arms {
417                     let mode = self.arm_move_mode(discr_cmt.clone(), arm);
418                     let mode = mode.match_mode();
419                     self.walk_arm(discr_cmt.clone(), arm, mode);
420                 }
421             }
422
423             hir::ExprArray(ref exprs) => {
424                 self.consume_exprs(exprs);
425             }
426
427             hir::ExprAddrOf(m, ref base) => {   // &base
428                 // make sure that the thing we are pointing out stays valid
429                 // for the lifetime `scope_r` of the resulting ptr:
430                 let expr_ty = return_if_err!(self.mc.infcx.node_ty(expr.id));
431                 if let ty::TyRef(r, _) = expr_ty.sty {
432                     let bk = ty::BorrowKind::from_mutbl(m);
433                     self.borrow_expr(&base, r, bk, AddrOf);
434                 }
435             }
436
437             hir::ExprInlineAsm(ref ia, ref outputs, ref inputs) => {
438                 for (o, output) in ia.outputs.iter().zip(outputs) {
439                     if o.is_indirect {
440                         self.consume_expr(output);
441                     } else {
442                         self.mutate_expr(expr, output,
443                                          if o.is_rw {
444                                              MutateMode::WriteAndRead
445                                          } else {
446                                              MutateMode::JustWrite
447                                          });
448                     }
449                 }
450                 self.consume_exprs(inputs);
451             }
452
453             hir::ExprAgain(..) |
454             hir::ExprLit(..) => {}
455
456             hir::ExprLoop(ref blk, _, _) => {
457                 self.walk_block(&blk);
458             }
459
460             hir::ExprWhile(ref cond_expr, ref blk, _) => {
461                 self.consume_expr(&cond_expr);
462                 self.walk_block(&blk);
463             }
464
465             hir::ExprUnary(_, ref lhs) => {
466                 self.consume_expr(&lhs);
467             }
468
469             hir::ExprBinary(_, ref lhs, ref rhs) => {
470                 self.consume_expr(&lhs);
471                 self.consume_expr(&rhs);
472             }
473
474             hir::ExprBlock(ref blk) => {
475                 self.walk_block(&blk);
476             }
477
478             hir::ExprBreak(_, ref opt_expr) | hir::ExprRet(ref opt_expr) => {
479                 if let Some(ref expr) = *opt_expr {
480                     self.consume_expr(&expr);
481                 }
482             }
483
484             hir::ExprAssign(ref lhs, ref rhs) => {
485                 self.mutate_expr(expr, &lhs, MutateMode::JustWrite);
486                 self.consume_expr(&rhs);
487             }
488
489             hir::ExprCast(ref base, _) => {
490                 self.consume_expr(&base);
491             }
492
493             hir::ExprAssignOp(_, ref lhs, ref rhs) => {
494                 if self.mc.infcx.tables.borrow().is_method_call(expr) {
495                     self.consume_expr(lhs);
496                 } else {
497                     self.mutate_expr(expr, &lhs, MutateMode::WriteAndRead);
498                 }
499                 self.consume_expr(&rhs);
500             }
501
502             hir::ExprRepeat(ref base, _) => {
503                 self.consume_expr(&base);
504             }
505
506             hir::ExprClosure(.., fn_decl_span) => {
507                 self.walk_captures(expr, fn_decl_span)
508             }
509
510             hir::ExprBox(ref base) => {
511                 self.consume_expr(&base);
512             }
513         }
514     }
515
516     fn walk_callee(&mut self, call: &hir::Expr, callee: &hir::Expr) {
517         let callee_ty = return_if_err!(self.mc.infcx.expr_ty_adjusted(callee));
518         debug!("walk_callee: callee={:?} callee_ty={:?}",
519                callee, callee_ty);
520         match callee_ty.sty {
521             ty::TyFnDef(..) | ty::TyFnPtr(_) => {
522                 self.consume_expr(callee);
523             }
524             ty::TyError => { }
525             _ => {
526                 let def_id = self.mc.infcx.tables.borrow().type_dependent_defs[&call.id].def_id();
527                 match OverloadedCallType::from_method_id(self.tcx(), def_id) {
528                     FnMutOverloadedCall => {
529                         let call_scope_r = self.tcx().node_scope_region(call.id);
530                         self.borrow_expr(callee,
531                                          call_scope_r,
532                                          ty::MutBorrow,
533                                          ClosureInvocation);
534                     }
535                     FnOverloadedCall => {
536                         let call_scope_r = self.tcx().node_scope_region(call.id);
537                         self.borrow_expr(callee,
538                                          call_scope_r,
539                                          ty::ImmBorrow,
540                                          ClosureInvocation);
541                     }
542                     FnOnceOverloadedCall => self.consume_expr(callee),
543                 }
544             }
545         }
546     }
547
548     fn walk_stmt(&mut self, stmt: &hir::Stmt) {
549         match stmt.node {
550             hir::StmtDecl(ref decl, _) => {
551                 match decl.node {
552                     hir::DeclLocal(ref local) => {
553                         self.walk_local(&local);
554                     }
555
556                     hir::DeclItem(_) => {
557                         // we don't visit nested items in this visitor,
558                         // only the fn body we were given.
559                     }
560                 }
561             }
562
563             hir::StmtExpr(ref expr, _) |
564             hir::StmtSemi(ref expr, _) => {
565                 self.consume_expr(&expr);
566             }
567         }
568     }
569
570     fn walk_local(&mut self, local: &hir::Local) {
571         match local.init {
572             None => {
573                 let delegate = &mut self.delegate;
574                 local.pat.each_binding(|_, id, span, _| {
575                     delegate.decl_without_init(id, span);
576                 })
577             }
578
579             Some(ref expr) => {
580                 // Variable declarations with
581                 // initializers are considered
582                 // "assigns", which is handled by
583                 // `walk_pat`:
584                 self.walk_expr(&expr);
585                 let init_cmt = return_if_err!(self.mc.cat_expr(&expr));
586                 self.walk_irrefutable_pat(init_cmt, &local.pat);
587             }
588         }
589     }
590
591     /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
592     /// depending on its type.
593     fn walk_block(&mut self, blk: &hir::Block) {
594         debug!("walk_block(blk.id={})", blk.id);
595
596         for stmt in &blk.stmts {
597             self.walk_stmt(stmt);
598         }
599
600         if let Some(ref tail_expr) = blk.expr {
601             self.consume_expr(&tail_expr);
602         }
603     }
604
605     fn walk_struct_expr(&mut self,
606                         fields: &[hir::Field],
607                         opt_with: &Option<P<hir::Expr>>) {
608         // Consume the expressions supplying values for each field.
609         for field in fields {
610             self.consume_expr(&field.expr);
611         }
612
613         let with_expr = match *opt_with {
614             Some(ref w) => &**w,
615             None => { return; }
616         };
617
618         let with_cmt = return_if_err!(self.mc.cat_expr(&with_expr));
619
620         // Select just those fields of the `with`
621         // expression that will actually be used
622         match with_cmt.ty.sty {
623             ty::TyAdt(adt, substs) if adt.is_struct() => {
624                 // Consume those fields of the with expression that are needed.
625                 for with_field in &adt.struct_variant().fields {
626                     if !contains_field_named(with_field, fields) {
627                         let cmt_field = self.mc.cat_field(
628                             &*with_expr,
629                             with_cmt.clone(),
630                             with_field.name,
631                             with_field.ty(self.tcx(), substs)
632                         );
633                         self.delegate_consume(with_expr.id, with_expr.span, cmt_field);
634                     }
635                 }
636             }
637             _ => {
638                 // the base expression should always evaluate to a
639                 // struct; however, when EUV is run during typeck, it
640                 // may not. This will generate an error earlier in typeck,
641                 // so we can just ignore it.
642                 if !self.tcx().sess.has_errors() {
643                     span_bug!(
644                         with_expr.span,
645                         "with expression doesn't evaluate to a struct");
646                 }
647             }
648         }
649
650         // walk the with expression so that complex expressions
651         // are properly handled.
652         self.walk_expr(with_expr);
653
654         fn contains_field_named(field: &ty::FieldDef,
655                                 fields: &[hir::Field])
656                                 -> bool
657         {
658             fields.iter().any(
659                 |f| f.name.node == field.name)
660         }
661     }
662
663     // Invoke the appropriate delegate calls for anything that gets
664     // consumed or borrowed as part of the automatic adjustment
665     // process.
666     fn walk_adjustment(&mut self, expr: &hir::Expr) {
667         let tables = self.mc.infcx.tables.borrow();
668         let adjustments = tables.expr_adjustments(expr);
669         let mut cmt = return_if_err!(self.mc.cat_expr_unadjusted(expr));
670         for adjustment in adjustments {
671             debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment);
672             match adjustment.kind {
673                 adjustment::Adjust::NeverToAny |
674                 adjustment::Adjust::ReifyFnPointer |
675                 adjustment::Adjust::UnsafeFnPointer |
676                 adjustment::Adjust::ClosureFnPointer |
677                 adjustment::Adjust::MutToConstPointer |
678                 adjustment::Adjust::Unsize => {
679                     // Creating a closure/fn-pointer or unsizing consumes
680                     // the input and stores it into the resulting rvalue.
681                     self.delegate_consume(expr.id, expr.span, cmt.clone());
682                 }
683
684                 adjustment::Adjust::Deref(None) => {}
685
686                 // Autoderefs for overloaded Deref calls in fact reference
687                 // their receiver. That is, if we have `(*x)` where `x`
688                 // is of type `Rc<T>`, then this in fact is equivalent to
689                 // `x.deref()`. Since `deref()` is declared with `&self`,
690                 // this is an autoref of `x`.
691                 adjustment::Adjust::Deref(Some(ref deref)) => {
692                     let bk = ty::BorrowKind::from_mutbl(deref.mutbl);
693                     self.delegate.borrow(expr.id, expr.span, cmt.clone(),
694                                          deref.region, bk, AutoRef);
695                 }
696
697                 adjustment::Adjust::Borrow(ref autoref) => {
698                     self.walk_autoref(expr, cmt.clone(), autoref);
699                 }
700             }
701             cmt = return_if_err!(self.mc.cat_expr_adjusted(expr, cmt, &adjustment));
702         }
703     }
704
705     /// Walks the autoref `autoref` applied to the autoderef'd
706     /// `expr`. `cmt_base` is the mem-categorized form of `expr`
707     /// after all relevant autoderefs have occurred.
708     fn walk_autoref(&mut self,
709                     expr: &hir::Expr,
710                     cmt_base: mc::cmt<'tcx>,
711                     autoref: &adjustment::AutoBorrow<'tcx>) {
712         debug!("walk_autoref(expr.id={} cmt_base={:?} autoref={:?})",
713                expr.id,
714                cmt_base,
715                autoref);
716
717         match *autoref {
718             adjustment::AutoBorrow::Ref(r, m) => {
719                 self.delegate.borrow(expr.id,
720                                      expr.span,
721                                      cmt_base,
722                                      r,
723                                      ty::BorrowKind::from_mutbl(m),
724                                      AutoRef);
725             }
726
727             adjustment::AutoBorrow::RawPtr(m) => {
728                 debug!("walk_autoref: expr.id={} cmt_base={:?}",
729                        expr.id,
730                        cmt_base);
731
732                 // Converting from a &T to *T (or &mut T to *mut T) is
733                 // treated as borrowing it for the enclosing temporary
734                 // scope.
735                 let r = self.tcx().node_scope_region(expr.id);
736
737                 self.delegate.borrow(expr.id,
738                                      expr.span,
739                                      cmt_base,
740                                      r,
741                                      ty::BorrowKind::from_mutbl(m),
742                                      AutoUnsafe);
743             }
744         }
745     }
746
747     fn arm_move_mode(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm) -> TrackMatchMode {
748         let mut mode = Unknown;
749         for pat in &arm.pats {
750             self.determine_pat_move_mode(discr_cmt.clone(), &pat, &mut mode);
751         }
752         mode
753     }
754
755     fn walk_arm(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm, mode: MatchMode) {
756         for pat in &arm.pats {
757             self.walk_pat(discr_cmt.clone(), &pat, mode);
758         }
759
760         if let Some(ref guard) = arm.guard {
761             self.consume_expr(&guard);
762         }
763
764         self.consume_expr(&arm.body);
765     }
766
767     /// Walks a pat that occurs in isolation (i.e. top-level of fn
768     /// arg or let binding.  *Not* a match arm or nested pat.)
769     fn walk_irrefutable_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat) {
770         let mut mode = Unknown;
771         self.determine_pat_move_mode(cmt_discr.clone(), pat, &mut mode);
772         let mode = mode.match_mode();
773         self.walk_pat(cmt_discr, pat, mode);
774     }
775
776     /// Identifies any bindings within `pat` and accumulates within
777     /// `mode` whether the overall pattern/match structure is a move,
778     /// copy, or borrow.
779     fn determine_pat_move_mode(&mut self,
780                                cmt_discr: mc::cmt<'tcx>,
781                                pat: &hir::Pat,
782                                mode: &mut TrackMatchMode) {
783         debug!("determine_pat_move_mode cmt_discr={:?} pat={:?}", cmt_discr,
784                pat);
785         return_if_err!(self.mc.cat_pattern(cmt_discr, pat, |_mc, cmt_pat, pat| {
786             match pat.node {
787                 PatKind::Binding(hir::BindByRef(..), ..) =>
788                     mode.lub(BorrowingMatch),
789                 PatKind::Binding(hir::BindByValue(..), ..) => {
790                     match copy_or_move(self.mc.infcx, self.param_env, &cmt_pat, PatBindingMove) {
791                         Copy => mode.lub(CopyingMatch),
792                         Move(..) => mode.lub(MovingMatch),
793                     }
794                 }
795                 _ => {}
796             }
797         }));
798     }
799
800     /// The core driver for walking a pattern; `match_mode` must be
801     /// established up front, e.g. via `determine_pat_move_mode` (see
802     /// also `walk_irrefutable_pat` for patterns that stand alone).
803     fn walk_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat, match_mode: MatchMode) {
804         debug!("walk_pat cmt_discr={:?} pat={:?}", cmt_discr, pat);
805
806         let tcx = self.tcx();
807         let infcx = self.mc.infcx;
808         let ExprUseVisitor { ref mc, ref mut delegate, param_env } = *self;
809         return_if_err!(mc.cat_pattern(cmt_discr.clone(), pat, |mc, cmt_pat, pat| {
810             if let PatKind::Binding(bmode, def_id, ..) = pat.node {
811                 debug!("binding cmt_pat={:?} pat={:?} match_mode={:?}", cmt_pat, pat, match_mode);
812
813                 // pat_ty: the type of the binding being produced.
814                 let pat_ty = return_if_err!(infcx.node_ty(pat.id));
815
816                 // Each match binding is effectively an assignment to the
817                 // binding being produced.
818                 let def = Def::Local(def_id);
819                 if let Ok(binding_cmt) = mc.cat_def(pat.id, pat.span, pat_ty, def) {
820                     delegate.mutate(pat.id, pat.span, binding_cmt, MutateMode::Init);
821                 }
822
823                 // It is also a borrow or copy/move of the value being matched.
824                 match bmode {
825                     hir::BindByRef(m) => {
826                         if let ty::TyRef(r, _) = pat_ty.sty {
827                             let bk = ty::BorrowKind::from_mutbl(m);
828                             delegate.borrow(pat.id, pat.span, cmt_pat, r, bk, RefBinding);
829                         }
830                     }
831                     hir::BindByValue(..) => {
832                         let mode = copy_or_move(infcx, param_env, &cmt_pat, PatBindingMove);
833                         debug!("walk_pat binding consuming pat");
834                         delegate.consume_pat(pat, cmt_pat, mode);
835                     }
836                 }
837             }
838         }));
839
840         // Do a second pass over the pattern, calling `matched_pat` on
841         // the interior nodes (enum variants and structs), as opposed
842         // to the above loop's visit of than the bindings that form
843         // the leaves of the pattern tree structure.
844         return_if_err!(mc.cat_pattern(cmt_discr, pat, |mc, cmt_pat, pat| {
845             let qpath = match pat.node {
846                 PatKind::Path(ref qpath) |
847                 PatKind::TupleStruct(ref qpath, ..) |
848                 PatKind::Struct(ref qpath, ..) => qpath,
849                 _ => return
850             };
851             let def = infcx.tables.borrow().qpath_def(qpath, pat.id);
852             match def {
853                 Def::Variant(variant_did) |
854                 Def::VariantCtor(variant_did, ..) => {
855                     let enum_did = tcx.parent_def_id(variant_did).unwrap();
856                     let downcast_cmt = if tcx.adt_def(enum_did).is_univariant() {
857                         cmt_pat
858                     } else {
859                         let cmt_pat_ty = cmt_pat.ty;
860                         mc.cat_downcast(pat, cmt_pat, cmt_pat_ty, variant_did)
861                     };
862
863                     debug!("variant downcast_cmt={:?} pat={:?}", downcast_cmt, pat);
864                     delegate.matched_pat(pat, downcast_cmt, match_mode);
865                 }
866                 Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
867                 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => {
868                     debug!("struct cmt_pat={:?} pat={:?}", cmt_pat, pat);
869                     delegate.matched_pat(pat, cmt_pat, match_mode);
870                 }
871                 _ => {}
872             }
873         }));
874     }
875
876     fn walk_captures(&mut self, closure_expr: &hir::Expr, fn_decl_span: Span) {
877         debug!("walk_captures({:?})", closure_expr);
878
879         self.tcx().with_freevars(closure_expr.id, |freevars| {
880             for freevar in freevars {
881                 let def_id = freevar.def.def_id();
882                 let id_var = self.tcx().hir.as_local_node_id(def_id).unwrap();
883                 let upvar_id = ty::UpvarId { var_id: id_var,
884                                              closure_expr_id: closure_expr.id };
885                 let upvar_capture = self.mc.infcx.tables.borrow().upvar_capture(upvar_id);
886                 let cmt_var = return_if_err!(self.cat_captured_var(closure_expr.id,
887                                                                    fn_decl_span,
888                                                                    freevar.def));
889                 match upvar_capture {
890                     ty::UpvarCapture::ByValue => {
891                         let mode = copy_or_move(self.mc.infcx,
892                                                 self.param_env,
893                                                 &cmt_var,
894                                                 CaptureMove);
895                         self.delegate.consume(closure_expr.id, freevar.span, cmt_var, mode);
896                     }
897                     ty::UpvarCapture::ByRef(upvar_borrow) => {
898                         self.delegate.borrow(closure_expr.id,
899                                              fn_decl_span,
900                                              cmt_var,
901                                              upvar_borrow.region,
902                                              upvar_borrow.kind,
903                                              ClosureCapture(freevar.span));
904                     }
905                 }
906             }
907         });
908     }
909
910     fn cat_captured_var(&mut self,
911                         closure_id: ast::NodeId,
912                         closure_span: Span,
913                         upvar_def: Def)
914                         -> mc::McResult<mc::cmt<'tcx>> {
915         // Create the cmt for the variable being borrowed, from the
916         // caller's perspective
917         let var_id = self.tcx().hir.as_local_node_id(upvar_def.def_id()).unwrap();
918         let var_ty = self.mc.infcx.node_ty(var_id)?;
919         self.mc.cat_def(closure_id, closure_span, var_ty, upvar_def)
920     }
921 }
922
923 fn copy_or_move<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
924                                 param_env: ty::ParamEnv<'tcx>,
925                                 cmt: &mc::cmt<'tcx>,
926                                 move_reason: MoveReason)
927                                 -> ConsumeMode
928 {
929     if infcx.type_moves_by_default(param_env, cmt.ty, cmt.span) {
930         Move(move_reason)
931     } else {
932         Copy
933     }
934 }