]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/expr_use_visitor.rs
rustc: avoid using MethodCallee's signature where possible.
[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 method = self.mc.infcx.tables.borrow().method_map[&call.id];
567                 match OverloadedCallType::from_method_id(self.tcx(), method.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 cmt_unadjusted =
711             return_if_err!(self.mc.cat_expr_unadjusted(expr));
712         if let Some(adjustment) = adj {
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                     debug!("walk_adjustment: trivial adjustment");
722                     self.delegate_consume(expr.id, expr.span, cmt_unadjusted);
723                 }
724                 adjustment::Adjust::DerefRef { ref autoderefs, autoref, unsize } => {
725                     debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment);
726
727                     let cmt_derefd =
728                         return_if_err!(self.walk_autoderefs(expr, cmt_unadjusted, autoderefs));
729
730                     let cmt_refd =
731                         self.walk_autoref(expr, cmt_derefd, autoref);
732
733                     if unsize {
734                         // Unsizing consumes the thin pointer and produces a fat one.
735                         self.delegate_consume(expr.id, expr.span, cmt_refd);
736                     }
737                 }
738             }
739         }
740     }
741
742     /// Autoderefs for overloaded Deref calls in fact reference their receiver. That is, if we have
743     /// `(*x)` where `x` is of type `Rc<T>`, then this in fact is equivalent to `x.deref()`. Since
744     /// `deref()` is declared with `&self`, this is an autoref of `x`.
745     fn walk_autoderefs(&mut self,
746                        expr: &hir::Expr,
747                        mut cmt: mc::cmt<'tcx>,
748                        autoderefs: &[Option<ty::MethodCallee<'tcx>>])
749                        -> mc::McResult<mc::cmt<'tcx>> {
750         debug!("walk_autoderefs expr={:?} autoderefs={:?}", expr, autoderefs);
751
752         for &overloaded in autoderefs {
753             if let Some(method) = overloaded {
754                 let self_ty = method.sig.inputs()[0];
755                 let self_ty = self.mc.infcx.resolve_type_vars_if_possible(&self_ty);
756
757                 let (m, r) = match self_ty.sty {
758                     ty::TyRef(r, ref m) => (m.mutbl, r),
759                     _ => span_bug!(expr.span, "bad overloaded deref type {:?}", self_ty)
760                 };
761                 let bk = ty::BorrowKind::from_mutbl(m);
762                 self.delegate.borrow(expr.id, expr.span, cmt.clone(),
763                                      r, bk, AutoRef);
764                 cmt = self.mc.cat_overloaded_autoderef(expr, method)?;
765             } else {
766                 cmt = self.mc.cat_deref(expr, cmt, false)?;
767             }
768         }
769         Ok(cmt)
770     }
771
772     /// Walks the autoref `opt_autoref` applied to the autoderef'd
773     /// `expr`. `cmt_derefd` is the mem-categorized form of `expr`
774     /// after all relevant autoderefs have occurred. Because AutoRefs
775     /// can be recursive, this function is recursive: it first walks
776     /// deeply all the way down the autoref chain, and then processes
777     /// the autorefs on the way out. At each point, it returns the
778     /// `cmt` for the rvalue that will be produced by introduced an
779     /// autoref.
780     fn walk_autoref(&mut self,
781                     expr: &hir::Expr,
782                     cmt_base: mc::cmt<'tcx>,
783                     opt_autoref: Option<adjustment::AutoBorrow<'tcx>>)
784                     -> mc::cmt<'tcx>
785     {
786         debug!("walk_autoref(expr.id={} cmt_derefd={:?} opt_autoref={:?})",
787                expr.id,
788                cmt_base,
789                opt_autoref);
790
791         let cmt_base_ty = cmt_base.ty;
792
793         let autoref = match opt_autoref {
794             Some(ref autoref) => autoref,
795             None => {
796                 // No AutoRef.
797                 return cmt_base;
798             }
799         };
800
801         match *autoref {
802             adjustment::AutoBorrow::Ref(r, m) => {
803                 self.delegate.borrow(expr.id,
804                                      expr.span,
805                                      cmt_base,
806                                      r,
807                                      ty::BorrowKind::from_mutbl(m),
808                                      AutoRef);
809             }
810
811             adjustment::AutoBorrow::RawPtr(m) => {
812                 debug!("walk_autoref: expr.id={} cmt_base={:?}",
813                        expr.id,
814                        cmt_base);
815
816                 // Converting from a &T to *T (or &mut T to *mut T) is
817                 // treated as borrowing it for the enclosing temporary
818                 // scope.
819                 let r = self.tcx().node_scope_region(expr.id);
820
821                 self.delegate.borrow(expr.id,
822                                      expr.span,
823                                      cmt_base,
824                                      r,
825                                      ty::BorrowKind::from_mutbl(m),
826                                      AutoUnsafe);
827             }
828         }
829
830         // Construct the categorization for the result of the autoref.
831         // This is always an rvalue, since we are producing a new
832         // (temporary) indirection.
833
834         let adj_ty = cmt_base_ty.adjust_for_autoref(self.tcx(), opt_autoref);
835
836         self.mc.cat_rvalue_node(expr.id, expr.span, adj_ty)
837     }
838
839
840     // When this returns true, it means that the expression *is* a
841     // method-call (i.e. via the operator-overload).  This true result
842     // also implies that walk_overloaded_operator already took care of
843     // recursively processing the input arguments, and thus the caller
844     // should not do so.
845     fn walk_overloaded_operator(&mut self,
846                                 expr: &hir::Expr,
847                                 receiver: &hir::Expr,
848                                 rhs: Vec<&hir::Expr>,
849                                 pass_args: PassArgs)
850                                 -> bool
851     {
852         if !self.mc.infcx.tables.borrow().is_method_call(expr.id) {
853             return false;
854         }
855
856         match pass_args {
857             PassArgs::ByValue => {
858                 self.consume_expr(receiver);
859                 for &arg in &rhs {
860                     self.consume_expr(arg);
861                 }
862
863                 return true;
864             },
865             PassArgs::ByRef => {},
866         }
867
868         self.walk_expr(receiver);
869
870         // Arguments (but not receivers) to overloaded operator
871         // methods are implicitly autoref'd which sadly does not use
872         // adjustments, so we must hardcode the borrow here.
873
874         let r = self.tcx().node_scope_region(expr.id);
875         let bk = ty::ImmBorrow;
876
877         for &arg in &rhs {
878             self.borrow_expr(arg, r, bk, OverloadedOperator);
879         }
880         return true;
881     }
882
883     fn arm_move_mode(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm) -> TrackMatchMode {
884         let mut mode = Unknown;
885         for pat in &arm.pats {
886             self.determine_pat_move_mode(discr_cmt.clone(), &pat, &mut mode);
887         }
888         mode
889     }
890
891     fn walk_arm(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm, mode: MatchMode) {
892         for pat in &arm.pats {
893             self.walk_pat(discr_cmt.clone(), &pat, mode);
894         }
895
896         if let Some(ref guard) = arm.guard {
897             self.consume_expr(&guard);
898         }
899
900         self.consume_expr(&arm.body);
901     }
902
903     /// Walks a pat that occurs in isolation (i.e. top-level of fn
904     /// arg or let binding.  *Not* a match arm or nested pat.)
905     fn walk_irrefutable_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat) {
906         let mut mode = Unknown;
907         self.determine_pat_move_mode(cmt_discr.clone(), pat, &mut mode);
908         let mode = mode.match_mode();
909         self.walk_pat(cmt_discr, pat, mode);
910     }
911
912     /// Identifies any bindings within `pat` and accumulates within
913     /// `mode` whether the overall pattern/match structure is a move,
914     /// copy, or borrow.
915     fn determine_pat_move_mode(&mut self,
916                                cmt_discr: mc::cmt<'tcx>,
917                                pat: &hir::Pat,
918                                mode: &mut TrackMatchMode) {
919         debug!("determine_pat_move_mode cmt_discr={:?} pat={:?}", cmt_discr,
920                pat);
921         return_if_err!(self.mc.cat_pattern(cmt_discr, pat, |_mc, cmt_pat, pat| {
922             match pat.node {
923                 PatKind::Binding(hir::BindByRef(..), ..) =>
924                     mode.lub(BorrowingMatch),
925                 PatKind::Binding(hir::BindByValue(..), ..) => {
926                     match copy_or_move(self.mc.infcx, &cmt_pat, PatBindingMove) {
927                         Copy => mode.lub(CopyingMatch),
928                         Move(..) => mode.lub(MovingMatch),
929                     }
930                 }
931                 _ => {}
932             }
933         }));
934     }
935
936     /// The core driver for walking a pattern; `match_mode` must be
937     /// established up front, e.g. via `determine_pat_move_mode` (see
938     /// also `walk_irrefutable_pat` for patterns that stand alone).
939     fn walk_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat, match_mode: MatchMode) {
940         debug!("walk_pat cmt_discr={:?} pat={:?}", cmt_discr, pat);
941
942         let tcx = &self.tcx();
943         let mc = &self.mc;
944         let infcx = self.mc.infcx;
945         let delegate = &mut self.delegate;
946         return_if_err!(mc.cat_pattern(cmt_discr.clone(), pat, |mc, cmt_pat, pat| {
947             if let PatKind::Binding(bmode, def_id, ..) = pat.node {
948                 debug!("binding cmt_pat={:?} pat={:?} match_mode={:?}", cmt_pat, pat, match_mode);
949
950                 // pat_ty: the type of the binding being produced.
951                 let pat_ty = return_if_err!(infcx.node_ty(pat.id));
952
953                 // Each match binding is effectively an assignment to the
954                 // binding being produced.
955                 let def = Def::Local(def_id);
956                 if let Ok(binding_cmt) = mc.cat_def(pat.id, pat.span, pat_ty, def) {
957                     delegate.mutate(pat.id, pat.span, binding_cmt, MutateMode::Init);
958                 }
959
960                 // It is also a borrow or copy/move of the value being matched.
961                 match bmode {
962                     hir::BindByRef(m) => {
963                         if let ty::TyRef(r, _) = pat_ty.sty {
964                             let bk = ty::BorrowKind::from_mutbl(m);
965                             delegate.borrow(pat.id, pat.span, cmt_pat, r, bk, RefBinding);
966                         }
967                     }
968                     hir::BindByValue(..) => {
969                         let mode = copy_or_move(infcx, &cmt_pat, PatBindingMove);
970                         debug!("walk_pat binding consuming pat");
971                         delegate.consume_pat(pat, cmt_pat, mode);
972                     }
973                 }
974             }
975         }));
976
977         // Do a second pass over the pattern, calling `matched_pat` on
978         // the interior nodes (enum variants and structs), as opposed
979         // to the above loop's visit of than the bindings that form
980         // the leaves of the pattern tree structure.
981         return_if_err!(mc.cat_pattern(cmt_discr, pat, |mc, cmt_pat, pat| {
982             let qpath = match pat.node {
983                 PatKind::Path(ref qpath) |
984                 PatKind::TupleStruct(ref qpath, ..) |
985                 PatKind::Struct(ref qpath, ..) => qpath,
986                 _ => return
987             };
988             let def = infcx.tables.borrow().qpath_def(qpath, pat.id);
989             match def {
990                 Def::Variant(variant_did) |
991                 Def::VariantCtor(variant_did, ..) => {
992                     let enum_did = tcx.parent_def_id(variant_did).unwrap();
993                     let downcast_cmt = if tcx.adt_def(enum_did).is_univariant() {
994                         cmt_pat
995                     } else {
996                         let cmt_pat_ty = cmt_pat.ty;
997                         mc.cat_downcast(pat, cmt_pat, cmt_pat_ty, variant_did)
998                     };
999
1000                     debug!("variant downcast_cmt={:?} pat={:?}", downcast_cmt, pat);
1001                     delegate.matched_pat(pat, downcast_cmt, match_mode);
1002                 }
1003                 Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
1004                 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => {
1005                     debug!("struct cmt_pat={:?} pat={:?}", cmt_pat, pat);
1006                     delegate.matched_pat(pat, cmt_pat, match_mode);
1007                 }
1008                 _ => {}
1009             }
1010         }));
1011     }
1012
1013     fn walk_captures(&mut self, closure_expr: &hir::Expr, fn_decl_span: Span) {
1014         debug!("walk_captures({:?})", closure_expr);
1015
1016         self.tcx().with_freevars(closure_expr.id, |freevars| {
1017             for freevar in freevars {
1018                 let def_id = freevar.def.def_id();
1019                 let id_var = self.tcx().hir.as_local_node_id(def_id).unwrap();
1020                 let upvar_id = ty::UpvarId { var_id: id_var,
1021                                              closure_expr_id: closure_expr.id };
1022                 let upvar_capture = self.mc.infcx.upvar_capture(upvar_id).unwrap();
1023                 let cmt_var = return_if_err!(self.cat_captured_var(closure_expr.id,
1024                                                                    fn_decl_span,
1025                                                                    freevar.def));
1026                 match upvar_capture {
1027                     ty::UpvarCapture::ByValue => {
1028                         let mode = copy_or_move(self.mc.infcx, &cmt_var, CaptureMove);
1029                         self.delegate.consume(closure_expr.id, freevar.span, cmt_var, mode);
1030                     }
1031                     ty::UpvarCapture::ByRef(upvar_borrow) => {
1032                         self.delegate.borrow(closure_expr.id,
1033                                              fn_decl_span,
1034                                              cmt_var,
1035                                              upvar_borrow.region,
1036                                              upvar_borrow.kind,
1037                                              ClosureCapture(freevar.span));
1038                     }
1039                 }
1040             }
1041         });
1042     }
1043
1044     fn cat_captured_var(&mut self,
1045                         closure_id: ast::NodeId,
1046                         closure_span: Span,
1047                         upvar_def: Def)
1048                         -> mc::McResult<mc::cmt<'tcx>> {
1049         // Create the cmt for the variable being borrowed, from the
1050         // caller's perspective
1051         let var_id = self.tcx().hir.as_local_node_id(upvar_def.def_id()).unwrap();
1052         let var_ty = self.mc.infcx.node_ty(var_id)?;
1053         self.mc.cat_def(closure_id, closure_span, var_ty, upvar_def)
1054     }
1055 }
1056
1057 fn copy_or_move<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
1058                                 cmt: &mc::cmt<'tcx>,
1059                                 move_reason: MoveReason)
1060                                 -> ConsumeMode
1061 {
1062     if infcx.type_moves_by_default(cmt.ty, cmt.span) {
1063         Move(move_reason)
1064     } else {
1065         Copy
1066     }
1067 }