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