]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/expr_use_visitor.rs
rustdoc: Hide `self: Box<Self>` in list of deref methods
[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 overloaded_call_type =
567                     match self.mc.infcx.node_method_id(ty::MethodCall::expr(call.id)) {
568                         Some(method_id) => {
569                             OverloadedCallType::from_method_id(self.tcx(), method_id)
570                         }
571                         None => {
572                             span_bug!(
573                                 callee.span,
574                                 "unexpected callee type {}",
575                                 callee_ty)
576                         }
577                     };
578                 match overloaded_call_type {
579                     FnMutOverloadedCall => {
580                         let call_scope_r = self.tcx().node_scope_region(call.id);
581                         self.borrow_expr(callee,
582                                          call_scope_r,
583                                          ty::MutBorrow,
584                                          ClosureInvocation);
585                     }
586                     FnOverloadedCall => {
587                         let call_scope_r = self.tcx().node_scope_region(call.id);
588                         self.borrow_expr(callee,
589                                          call_scope_r,
590                                          ty::ImmBorrow,
591                                          ClosureInvocation);
592                     }
593                     FnOnceOverloadedCall => self.consume_expr(callee),
594                 }
595             }
596         }
597     }
598
599     fn walk_stmt(&mut self, stmt: &hir::Stmt) {
600         match stmt.node {
601             hir::StmtDecl(ref decl, _) => {
602                 match decl.node {
603                     hir::DeclLocal(ref local) => {
604                         self.walk_local(&local);
605                     }
606
607                     hir::DeclItem(_) => {
608                         // we don't visit nested items in this visitor,
609                         // only the fn body we were given.
610                     }
611                 }
612             }
613
614             hir::StmtExpr(ref expr, _) |
615             hir::StmtSemi(ref expr, _) => {
616                 self.consume_expr(&expr);
617             }
618         }
619     }
620
621     fn walk_local(&mut self, local: &hir::Local) {
622         match local.init {
623             None => {
624                 let delegate = &mut self.delegate;
625                 local.pat.each_binding(|_, id, span, _| {
626                     delegate.decl_without_init(id, span);
627                 })
628             }
629
630             Some(ref expr) => {
631                 // Variable declarations with
632                 // initializers are considered
633                 // "assigns", which is handled by
634                 // `walk_pat`:
635                 self.walk_expr(&expr);
636                 let init_cmt = return_if_err!(self.mc.cat_expr(&expr));
637                 self.walk_irrefutable_pat(init_cmt, &local.pat);
638             }
639         }
640     }
641
642     /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
643     /// depending on its type.
644     fn walk_block(&mut self, blk: &hir::Block) {
645         debug!("walk_block(blk.id={})", blk.id);
646
647         for stmt in &blk.stmts {
648             self.walk_stmt(stmt);
649         }
650
651         if let Some(ref tail_expr) = blk.expr {
652             self.consume_expr(&tail_expr);
653         }
654     }
655
656     fn walk_struct_expr(&mut self,
657                         fields: &[hir::Field],
658                         opt_with: &Option<P<hir::Expr>>) {
659         // Consume the expressions supplying values for each field.
660         for field in fields {
661             self.consume_expr(&field.expr);
662         }
663
664         let with_expr = match *opt_with {
665             Some(ref w) => &**w,
666             None => { return; }
667         };
668
669         let with_cmt = return_if_err!(self.mc.cat_expr(&with_expr));
670
671         // Select just those fields of the `with`
672         // expression that will actually be used
673         match with_cmt.ty.sty {
674             ty::TyAdt(adt, substs) if adt.is_struct() => {
675                 // Consume those fields of the with expression that are needed.
676                 for with_field in &adt.struct_variant().fields {
677                     if !contains_field_named(with_field, fields) {
678                         let cmt_field = self.mc.cat_field(
679                             &*with_expr,
680                             with_cmt.clone(),
681                             with_field.name,
682                             with_field.ty(self.tcx(), substs)
683                         );
684                         self.delegate_consume(with_expr.id, with_expr.span, cmt_field);
685                     }
686                 }
687             }
688             _ => {
689                 // the base expression should always evaluate to a
690                 // struct; however, when EUV is run during typeck, it
691                 // may not. This will generate an error earlier in typeck,
692                 // so we can just ignore it.
693                 if !self.tcx().sess.has_errors() {
694                     span_bug!(
695                         with_expr.span,
696                         "with expression doesn't evaluate to a struct");
697                 }
698             }
699         }
700
701         // walk the with expression so that complex expressions
702         // are properly handled.
703         self.walk_expr(with_expr);
704
705         fn contains_field_named(field: &ty::FieldDef,
706                                 fields: &[hir::Field])
707                                 -> bool
708         {
709             fields.iter().any(
710                 |f| f.name.node == field.name)
711         }
712     }
713
714     // Invoke the appropriate delegate calls for anything that gets
715     // consumed or borrowed as part of the automatic adjustment
716     // process.
717     fn walk_adjustment(&mut self, expr: &hir::Expr) {
718         let infcx = self.mc.infcx;
719         //NOTE(@jroesch): mixed RefCell borrow causes crash
720         let adj = infcx.tables.borrow().adjustments.get(&expr.id).map(|x| x.clone());
721         if let Some(adjustment) = adj {
722             match adjustment.kind {
723                 adjustment::Adjust::NeverToAny |
724                 adjustment::Adjust::ReifyFnPointer |
725                 adjustment::Adjust::UnsafeFnPointer |
726                 adjustment::Adjust::ClosureFnPointer |
727                 adjustment::Adjust::MutToConstPointer => {
728                     // Creating a closure/fn-pointer or unsizing consumes
729                     // the input and stores it into the resulting rvalue.
730                     debug!("walk_adjustment: trivial adjustment");
731                     let cmt_unadjusted =
732                         return_if_err!(self.mc.cat_expr_unadjusted(expr));
733                     self.delegate_consume(expr.id, expr.span, cmt_unadjusted);
734                 }
735                 adjustment::Adjust::DerefRef { autoderefs, autoref, unsize } => {
736                     debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment);
737
738                     self.walk_autoderefs(expr, autoderefs);
739
740                     let cmt_derefd =
741                         return_if_err!(self.mc.cat_expr_autoderefd(expr, autoderefs));
742
743                     let cmt_refd =
744                         self.walk_autoref(expr, cmt_derefd, autoref);
745
746                     if unsize {
747                         // Unsizing consumes the thin pointer and produces a fat one.
748                         self.delegate_consume(expr.id, expr.span, cmt_refd);
749                     }
750                 }
751             }
752         }
753     }
754
755     /// Autoderefs for overloaded Deref calls in fact reference their receiver. That is, if we have
756     /// `(*x)` where `x` is of type `Rc<T>`, then this in fact is equivalent to `x.deref()`. Since
757     /// `deref()` is declared with `&self`, this is an autoref of `x`.
758     fn walk_autoderefs(&mut self,
759                        expr: &hir::Expr,
760                        autoderefs: usize) {
761         debug!("walk_autoderefs expr={:?} autoderefs={}", expr, autoderefs);
762
763         for i in 0..autoderefs {
764             let deref_id = ty::MethodCall::autoderef(expr.id, i as u32);
765             if let Some(method_ty) = self.mc.infcx.node_method_ty(deref_id) {
766                 let cmt = return_if_err!(self.mc.cat_expr_autoderefd(expr, i));
767
768                 // the method call infrastructure should have
769                 // replaced all late-bound regions with variables:
770                 let self_ty = method_ty.fn_sig().input(0);
771                 let self_ty = self.tcx().no_late_bound_regions(&self_ty).unwrap();
772
773                 let (m, r) = match self_ty.sty {
774                     ty::TyRef(r, ref m) => (m.mutbl, r),
775                     _ => span_bug!(expr.span,
776                                    "bad overloaded deref type {:?}",
777                                    method_ty)
778                 };
779                 let bk = ty::BorrowKind::from_mutbl(m);
780                 self.delegate.borrow(expr.id, expr.span, cmt,
781                                      r, bk, AutoRef);
782             }
783         }
784     }
785
786     /// Walks the autoref `opt_autoref` applied to the autoderef'd
787     /// `expr`. `cmt_derefd` is the mem-categorized form of `expr`
788     /// after all relevant autoderefs have occurred. Because AutoRefs
789     /// can be recursive, this function is recursive: it first walks
790     /// deeply all the way down the autoref chain, and then processes
791     /// the autorefs on the way out. At each point, it returns the
792     /// `cmt` for the rvalue that will be produced by introduced an
793     /// autoref.
794     fn walk_autoref(&mut self,
795                     expr: &hir::Expr,
796                     cmt_base: mc::cmt<'tcx>,
797                     opt_autoref: Option<adjustment::AutoBorrow<'tcx>>)
798                     -> mc::cmt<'tcx>
799     {
800         debug!("walk_autoref(expr.id={} cmt_derefd={:?} opt_autoref={:?})",
801                expr.id,
802                cmt_base,
803                opt_autoref);
804
805         let cmt_base_ty = cmt_base.ty;
806
807         let autoref = match opt_autoref {
808             Some(ref autoref) => autoref,
809             None => {
810                 // No AutoRef.
811                 return cmt_base;
812             }
813         };
814
815         match *autoref {
816             adjustment::AutoBorrow::Ref(r, m) => {
817                 self.delegate.borrow(expr.id,
818                                      expr.span,
819                                      cmt_base,
820                                      r,
821                                      ty::BorrowKind::from_mutbl(m),
822                                      AutoRef);
823             }
824
825             adjustment::AutoBorrow::RawPtr(m) => {
826                 debug!("walk_autoref: expr.id={} cmt_base={:?}",
827                        expr.id,
828                        cmt_base);
829
830                 // Converting from a &T to *T (or &mut T to *mut T) is
831                 // treated as borrowing it for the enclosing temporary
832                 // scope.
833                 let r = self.tcx().node_scope_region(expr.id);
834
835                 self.delegate.borrow(expr.id,
836                                      expr.span,
837                                      cmt_base,
838                                      r,
839                                      ty::BorrowKind::from_mutbl(m),
840                                      AutoUnsafe);
841             }
842         }
843
844         // Construct the categorization for the result of the autoref.
845         // This is always an rvalue, since we are producing a new
846         // (temporary) indirection.
847
848         let adj_ty = cmt_base_ty.adjust_for_autoref(self.tcx(), opt_autoref);
849
850         self.mc.cat_rvalue_node(expr.id, expr.span, adj_ty)
851     }
852
853
854     // When this returns true, it means that the expression *is* a
855     // method-call (i.e. via the operator-overload).  This true result
856     // also implies that walk_overloaded_operator already took care of
857     // recursively processing the input arguments, and thus the caller
858     // should not do so.
859     fn walk_overloaded_operator(&mut self,
860                                 expr: &hir::Expr,
861                                 receiver: &hir::Expr,
862                                 rhs: Vec<&hir::Expr>,
863                                 pass_args: PassArgs)
864                                 -> bool
865     {
866         if !self.mc.infcx.is_method_call(expr.id) {
867             return false;
868         }
869
870         match pass_args {
871             PassArgs::ByValue => {
872                 self.consume_expr(receiver);
873                 for &arg in &rhs {
874                     self.consume_expr(arg);
875                 }
876
877                 return true;
878             },
879             PassArgs::ByRef => {},
880         }
881
882         self.walk_expr(receiver);
883
884         // Arguments (but not receivers) to overloaded operator
885         // methods are implicitly autoref'd which sadly does not use
886         // adjustments, so we must hardcode the borrow here.
887
888         let r = self.tcx().node_scope_region(expr.id);
889         let bk = ty::ImmBorrow;
890
891         for &arg in &rhs {
892             self.borrow_expr(arg, r, bk, OverloadedOperator);
893         }
894         return true;
895     }
896
897     fn arm_move_mode(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm) -> TrackMatchMode {
898         let mut mode = Unknown;
899         for pat in &arm.pats {
900             self.determine_pat_move_mode(discr_cmt.clone(), &pat, &mut mode);
901         }
902         mode
903     }
904
905     fn walk_arm(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm, mode: MatchMode) {
906         for pat in &arm.pats {
907             self.walk_pat(discr_cmt.clone(), &pat, mode);
908         }
909
910         if let Some(ref guard) = arm.guard {
911             self.consume_expr(&guard);
912         }
913
914         self.consume_expr(&arm.body);
915     }
916
917     /// Walks a pat that occurs in isolation (i.e. top-level of fn
918     /// arg or let binding.  *Not* a match arm or nested pat.)
919     fn walk_irrefutable_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat) {
920         let mut mode = Unknown;
921         self.determine_pat_move_mode(cmt_discr.clone(), pat, &mut mode);
922         let mode = mode.match_mode();
923         self.walk_pat(cmt_discr, pat, mode);
924     }
925
926     /// Identifies any bindings within `pat` and accumulates within
927     /// `mode` whether the overall pattern/match structure is a move,
928     /// copy, or borrow.
929     fn determine_pat_move_mode(&mut self,
930                                cmt_discr: mc::cmt<'tcx>,
931                                pat: &hir::Pat,
932                                mode: &mut TrackMatchMode) {
933         debug!("determine_pat_move_mode cmt_discr={:?} pat={:?}", cmt_discr,
934                pat);
935         return_if_err!(self.mc.cat_pattern(cmt_discr, pat, |_mc, cmt_pat, pat| {
936             match pat.node {
937                 PatKind::Binding(hir::BindByRef(..), ..) =>
938                     mode.lub(BorrowingMatch),
939                 PatKind::Binding(hir::BindByValue(..), ..) => {
940                     match copy_or_move(self.mc.infcx, &cmt_pat, PatBindingMove) {
941                         Copy => mode.lub(CopyingMatch),
942                         Move(..) => mode.lub(MovingMatch),
943                     }
944                 }
945                 _ => {}
946             }
947         }));
948     }
949
950     /// The core driver for walking a pattern; `match_mode` must be
951     /// established up front, e.g. via `determine_pat_move_mode` (see
952     /// also `walk_irrefutable_pat` for patterns that stand alone).
953     fn walk_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat, match_mode: MatchMode) {
954         debug!("walk_pat cmt_discr={:?} pat={:?}", cmt_discr, pat);
955
956         let tcx = &self.tcx();
957         let mc = &self.mc;
958         let infcx = self.mc.infcx;
959         let delegate = &mut self.delegate;
960         return_if_err!(mc.cat_pattern(cmt_discr.clone(), pat, |mc, cmt_pat, pat| {
961             if let PatKind::Binding(bmode, def_id, ..) = pat.node {
962                 debug!("binding cmt_pat={:?} pat={:?} match_mode={:?}", cmt_pat, pat, match_mode);
963
964                 // pat_ty: the type of the binding being produced.
965                 let pat_ty = return_if_err!(infcx.node_ty(pat.id));
966
967                 // Each match binding is effectively an assignment to the
968                 // binding being produced.
969                 let def = Def::Local(def_id);
970                 if let Ok(binding_cmt) = mc.cat_def(pat.id, pat.span, pat_ty, def) {
971                     delegate.mutate(pat.id, pat.span, binding_cmt, MutateMode::Init);
972                 }
973
974                 // It is also a borrow or copy/move of the value being matched.
975                 match bmode {
976                     hir::BindByRef(m) => {
977                         if let ty::TyRef(r, _) = pat_ty.sty {
978                             let bk = ty::BorrowKind::from_mutbl(m);
979                             delegate.borrow(pat.id, pat.span, cmt_pat, r, bk, RefBinding);
980                         }
981                     }
982                     hir::BindByValue(..) => {
983                         let mode = copy_or_move(infcx, &cmt_pat, PatBindingMove);
984                         debug!("walk_pat binding consuming pat");
985                         delegate.consume_pat(pat, cmt_pat, mode);
986                     }
987                 }
988             }
989         }));
990
991         // Do a second pass over the pattern, calling `matched_pat` on
992         // the interior nodes (enum variants and structs), as opposed
993         // to the above loop's visit of than the bindings that form
994         // the leaves of the pattern tree structure.
995         return_if_err!(mc.cat_pattern(cmt_discr, pat, |mc, cmt_pat, pat| {
996             let qpath = match pat.node {
997                 PatKind::Path(ref qpath) |
998                 PatKind::TupleStruct(ref qpath, ..) |
999                 PatKind::Struct(ref qpath, ..) => qpath,
1000                 _ => return
1001             };
1002             let def = infcx.tables.borrow().qpath_def(qpath, pat.id);
1003             match def {
1004                 Def::Variant(variant_did) |
1005                 Def::VariantCtor(variant_did, ..) => {
1006                     let enum_did = tcx.parent_def_id(variant_did).unwrap();
1007                     let downcast_cmt = if tcx.adt_def(enum_did).is_univariant() {
1008                         cmt_pat
1009                     } else {
1010                         let cmt_pat_ty = cmt_pat.ty;
1011                         mc.cat_downcast(pat, cmt_pat, cmt_pat_ty, variant_did)
1012                     };
1013
1014                     debug!("variant downcast_cmt={:?} pat={:?}", downcast_cmt, pat);
1015                     delegate.matched_pat(pat, downcast_cmt, match_mode);
1016                 }
1017                 Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
1018                 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => {
1019                     debug!("struct cmt_pat={:?} pat={:?}", cmt_pat, pat);
1020                     delegate.matched_pat(pat, cmt_pat, match_mode);
1021                 }
1022                 _ => {}
1023             }
1024         }));
1025     }
1026
1027     fn walk_captures(&mut self, closure_expr: &hir::Expr, fn_decl_span: Span) {
1028         debug!("walk_captures({:?})", closure_expr);
1029
1030         self.tcx().with_freevars(closure_expr.id, |freevars| {
1031             for freevar in freevars {
1032                 let def_id = freevar.def.def_id();
1033                 let id_var = self.tcx().hir.as_local_node_id(def_id).unwrap();
1034                 let upvar_id = ty::UpvarId { var_id: id_var,
1035                                              closure_expr_id: closure_expr.id };
1036                 let upvar_capture = self.mc.infcx.upvar_capture(upvar_id).unwrap();
1037                 let cmt_var = return_if_err!(self.cat_captured_var(closure_expr.id,
1038                                                                    fn_decl_span,
1039                                                                    freevar.def));
1040                 match upvar_capture {
1041                     ty::UpvarCapture::ByValue => {
1042                         let mode = copy_or_move(self.mc.infcx, &cmt_var, CaptureMove);
1043                         self.delegate.consume(closure_expr.id, freevar.span, cmt_var, mode);
1044                     }
1045                     ty::UpvarCapture::ByRef(upvar_borrow) => {
1046                         self.delegate.borrow(closure_expr.id,
1047                                              fn_decl_span,
1048                                              cmt_var,
1049                                              upvar_borrow.region,
1050                                              upvar_borrow.kind,
1051                                              ClosureCapture(freevar.span));
1052                     }
1053                 }
1054             }
1055         });
1056     }
1057
1058     fn cat_captured_var(&mut self,
1059                         closure_id: ast::NodeId,
1060                         closure_span: Span,
1061                         upvar_def: Def)
1062                         -> mc::McResult<mc::cmt<'tcx>> {
1063         // Create the cmt for the variable being borrowed, from the
1064         // caller's perspective
1065         let var_id = self.tcx().hir.as_local_node_id(upvar_def.def_id()).unwrap();
1066         let var_ty = self.mc.infcx.node_ty(var_id)?;
1067         self.mc.cat_def(closure_id, closure_span, var_ty, upvar_def)
1068     }
1069 }
1070
1071 fn copy_or_move<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
1072                                 cmt: &mc::cmt<'tcx>,
1073                                 move_reason: MoveReason)
1074                                 -> ConsumeMode
1075 {
1076     if infcx.type_moves_by_default(cmt.ty, cmt.span) {
1077         Move(move_reason)
1078     } else {
1079         Copy
1080     }
1081 }