]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/expr_use_visitor.rs
Rollup merge of #28788 - tsurai:master, r=bluss
[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::MutateMode::*;
16 pub use self::LoanCause::*;
17 pub use self::ConsumeMode::*;
18 pub use self::MoveReason::*;
19 pub use self::MatchMode::*;
20 use self::TrackMatchMode::*;
21 use self::OverloadedCallType::*;
22
23 use middle::{def, pat_util};
24 use middle::def_id::{DefId};
25 use middle::infer;
26 use middle::mem_categorization as mc;
27 use middle::ty;
28 use middle::ty::adjustment;
29
30 use rustc_front::hir;
31
32 use syntax::ast;
33 use syntax::ptr::P;
34 use syntax::codemap::Span;
35
36 ///////////////////////////////////////////////////////////////////////////
37 // The Delegate trait
38
39 /// This trait defines the callbacks you can expect to receive when
40 /// employing the ExprUseVisitor.
41 pub trait Delegate<'tcx> {
42     // The value found at `cmt` is either copied or moved, depending
43     // on mode.
44     fn consume(&mut self,
45                consume_id: ast::NodeId,
46                consume_span: Span,
47                cmt: mc::cmt<'tcx>,
48                mode: ConsumeMode);
49
50     // The value found at `cmt` has been determined to match the
51     // pattern binding `matched_pat`, and its subparts are being
52     // copied or moved depending on `mode`.  Note that `matched_pat`
53     // is called on all variant/structs in the pattern (i.e., the
54     // interior nodes of the pattern's tree structure) while
55     // consume_pat is called on the binding identifiers in the pattern
56     // (which are leaves of the pattern's tree structure).
57     //
58     // Note that variants/structs and identifiers are disjoint; thus
59     // `matched_pat` and `consume_pat` are never both called on the
60     // same input pattern structure (though of `consume_pat` can be
61     // called on a subpart of an input passed to `matched_pat).
62     fn matched_pat(&mut self,
63                    matched_pat: &hir::Pat,
64                    cmt: mc::cmt<'tcx>,
65                    mode: MatchMode);
66
67     // The value found at `cmt` is either copied or moved via the
68     // pattern binding `consume_pat`, depending on mode.
69     fn consume_pat(&mut self,
70                    consume_pat: &hir::Pat,
71                    cmt: mc::cmt<'tcx>,
72                    mode: ConsumeMode);
73
74     // The value found at `borrow` is being borrowed at the point
75     // `borrow_id` for the region `loan_region` with kind `bk`.
76     fn borrow(&mut self,
77               borrow_id: ast::NodeId,
78               borrow_span: Span,
79               cmt: mc::cmt<'tcx>,
80               loan_region: ty::Region,
81               bk: ty::BorrowKind,
82               loan_cause: LoanCause);
83
84     // The local variable `id` is declared but not initialized.
85     fn decl_without_init(&mut self,
86                          id: ast::NodeId,
87                          span: Span);
88
89     // The path at `cmt` is being assigned to.
90     fn mutate(&mut self,
91               assignment_id: ast::NodeId,
92               assignment_span: Span,
93               assignee_cmt: mc::cmt<'tcx>,
94               mode: MutateMode);
95 }
96
97 #[derive(Copy, Clone, PartialEq, Debug)]
98 pub enum LoanCause {
99     ClosureCapture(Span),
100     AddrOf,
101     AutoRef,
102     AutoUnsafe,
103     RefBinding,
104     OverloadedOperator,
105     ClosureInvocation,
106     ForLoop,
107     MatchDiscriminant
108 }
109
110 #[derive(Copy, Clone, PartialEq, Debug)]
111 pub enum ConsumeMode {
112     Copy,                // reference to x where x has a type that copies
113     Move(MoveReason),    // reference to x where x has a type that moves
114 }
115
116 #[derive(Copy, Clone, PartialEq, Debug)]
117 pub enum MoveReason {
118     DirectRefMove,
119     PatBindingMove,
120     CaptureMove,
121 }
122
123 #[derive(Copy, Clone, PartialEq, Debug)]
124 pub enum MatchMode {
125     NonBindingMatch,
126     BorrowingMatch,
127     CopyingMatch,
128     MovingMatch,
129 }
130
131 #[derive(Copy, Clone, PartialEq, Debug)]
132 enum TrackMatchMode {
133     Unknown,
134     Definite(MatchMode),
135     Conflicting,
136 }
137
138 impl TrackMatchMode {
139     // Builds up the whole match mode for a pattern from its constituent
140     // parts.  The lattice looks like this:
141     //
142     //          Conflicting
143     //            /     \
144     //           /       \
145     //      Borrowing   Moving
146     //           \       /
147     //            \     /
148     //            Copying
149     //               |
150     //          NonBinding
151     //               |
152     //            Unknown
153     //
154     // examples:
155     //
156     // * `(_, some_int)` pattern is Copying, since
157     //   NonBinding + Copying => Copying
158     //
159     // * `(some_int, some_box)` pattern is Moving, since
160     //   Copying + Moving => Moving
161     //
162     // * `(ref x, some_box)` pattern is Conflicting, since
163     //   Borrowing + Moving => Conflicting
164     //
165     // Note that the `Unknown` and `Conflicting` states are
166     // represented separately from the other more interesting
167     // `Definite` states, which simplifies logic here somewhat.
168     fn lub(&mut self, mode: MatchMode) {
169         *self = match (*self, mode) {
170             // Note that clause order below is very significant.
171             (Unknown, new) => Definite(new),
172             (Definite(old), new) if old == new => Definite(old),
173
174             (Definite(old), NonBindingMatch) => Definite(old),
175             (Definite(NonBindingMatch), new) => Definite(new),
176
177             (Definite(old), CopyingMatch) => Definite(old),
178             (Definite(CopyingMatch), new) => Definite(new),
179
180             (Definite(_), _) => Conflicting,
181             (Conflicting, _) => *self,
182         };
183     }
184
185     fn match_mode(&self) -> MatchMode {
186         match *self {
187             Unknown => NonBindingMatch,
188             Definite(mode) => mode,
189             Conflicting => {
190                 // Conservatively return MovingMatch to let the
191                 // compiler continue to make progress.
192                 MovingMatch
193             }
194         }
195     }
196 }
197
198 #[derive(Copy, Clone, PartialEq, Debug)]
199 pub enum MutateMode {
200     Init,
201     JustWrite,    // x = y
202     WriteAndRead, // x += y
203 }
204
205 #[derive(Copy, Clone)]
206 enum OverloadedCallType {
207     FnOverloadedCall,
208     FnMutOverloadedCall,
209     FnOnceOverloadedCall,
210 }
211
212 impl OverloadedCallType {
213     fn from_trait_id(tcx: &ty::ctxt, trait_id: DefId)
214                      -> OverloadedCallType {
215         for &(maybe_function_trait, overloaded_call_type) in &[
216             (tcx.lang_items.fn_once_trait(), FnOnceOverloadedCall),
217             (tcx.lang_items.fn_mut_trait(), FnMutOverloadedCall),
218             (tcx.lang_items.fn_trait(), FnOverloadedCall)
219         ] {
220             match maybe_function_trait {
221                 Some(function_trait) if function_trait == trait_id => {
222                     return overloaded_call_type
223                 }
224                 _ => continue,
225             }
226         }
227
228         tcx.sess.bug("overloaded call didn't map to known function trait")
229     }
230
231     fn from_method_id(tcx: &ty::ctxt, method_id: DefId)
232                       -> OverloadedCallType {
233         let method = tcx.impl_or_trait_item(method_id);
234         OverloadedCallType::from_trait_id(tcx, method.container().id())
235     }
236 }
237
238 ///////////////////////////////////////////////////////////////////////////
239 // The ExprUseVisitor type
240 //
241 // This is the code that actually walks the tree. Like
242 // mem_categorization, it requires a TYPER, which is a type that
243 // supplies types from the tree. After type checking is complete, you
244 // can just use the tcx as the typer.
245 //
246 // FIXME(stage0): the :'t here is probably only important for stage0
247 pub struct ExprUseVisitor<'d, 't, 'a: 't, 'tcx:'a+'d> {
248     typer: &'t infer::InferCtxt<'a, 'tcx>,
249     mc: mc::MemCategorizationContext<'t, 'a, 'tcx>,
250     delegate: &'d mut Delegate<'tcx>,
251 }
252
253 // If the TYPER results in an error, it's because the type check
254 // failed (or will fail, when the error is uncovered and reported
255 // during writeback). In this case, we just ignore this part of the
256 // code.
257 //
258 // Note that this macro appears similar to try!(), but, unlike try!(),
259 // it does not propagate the error.
260 macro_rules! return_if_err {
261     ($inp: expr) => (
262         match $inp {
263             Ok(v) => v,
264             Err(()) => {
265                 debug!("mc reported err");
266                 return
267             }
268         }
269     )
270 }
271
272 /// Whether the elements of an overloaded operation are passed by value or by reference
273 enum PassArgs {
274     ByValue,
275     ByRef,
276 }
277
278 impl<'d,'t,'a,'tcx> ExprUseVisitor<'d,'t,'a,'tcx> {
279     pub fn new(delegate: &'d mut (Delegate<'tcx>),
280                typer: &'t infer::InferCtxt<'a, 'tcx>)
281                -> ExprUseVisitor<'d,'t,'a,'tcx> where 'tcx:'a
282     {
283         let mc: mc::MemCategorizationContext<'t, 'a, 'tcx> =
284             mc::MemCategorizationContext::new(typer);
285         ExprUseVisitor { typer: typer, mc: mc, delegate: delegate }
286     }
287
288     pub fn walk_fn(&mut self,
289                    decl: &hir::FnDecl,
290                    body: &hir::Block) {
291         self.walk_arg_patterns(decl, body);
292         self.walk_block(body);
293     }
294
295     fn walk_arg_patterns(&mut self,
296                          decl: &hir::FnDecl,
297                          body: &hir::Block) {
298         for arg in &decl.inputs {
299             let arg_ty = return_if_err!(self.typer.node_ty(arg.pat.id));
300
301             let fn_body_scope = self.tcx().region_maps.node_extent(body.id);
302             let arg_cmt = self.mc.cat_rvalue(
303                 arg.id,
304                 arg.pat.span,
305                 ty::ReScope(fn_body_scope), // Args live only as long as the fn body.
306                 arg_ty);
307
308             self.walk_irrefutable_pat(arg_cmt, &*arg.pat);
309         }
310     }
311
312     fn tcx(&self) -> &'t ty::ctxt<'tcx> {
313         self.typer.tcx
314     }
315
316     fn delegate_consume(&mut self,
317                         consume_id: ast::NodeId,
318                         consume_span: Span,
319                         cmt: mc::cmt<'tcx>) {
320         debug!("delegate_consume(consume_id={}, cmt={:?})",
321                consume_id, cmt);
322
323         let mode = copy_or_move(self.typer, &cmt, DirectRefMove);
324         self.delegate.consume(consume_id, consume_span, cmt, mode);
325     }
326
327     fn consume_exprs(&mut self, exprs: &Vec<P<hir::Expr>>) {
328         for expr in exprs {
329             self.consume_expr(&**expr);
330         }
331     }
332
333     pub fn consume_expr(&mut self, expr: &hir::Expr) {
334         debug!("consume_expr(expr={:?})", expr);
335
336         let cmt = return_if_err!(self.mc.cat_expr(expr));
337         self.delegate_consume(expr.id, expr.span, cmt);
338         self.walk_expr(expr);
339     }
340
341     fn mutate_expr(&mut self,
342                    assignment_expr: &hir::Expr,
343                    expr: &hir::Expr,
344                    mode: MutateMode) {
345         let cmt = return_if_err!(self.mc.cat_expr(expr));
346         self.delegate.mutate(assignment_expr.id, assignment_expr.span, cmt, mode);
347         self.walk_expr(expr);
348     }
349
350     fn borrow_expr(&mut self,
351                    expr: &hir::Expr,
352                    r: ty::Region,
353                    bk: ty::BorrowKind,
354                    cause: LoanCause) {
355         debug!("borrow_expr(expr={:?}, r={:?}, bk={:?})",
356                expr, r, bk);
357
358         let cmt = return_if_err!(self.mc.cat_expr(expr));
359         self.delegate.borrow(expr.id, expr.span, cmt, r, bk, cause);
360
361         self.walk_expr(expr)
362     }
363
364     fn select_from_expr(&mut self, expr: &hir::Expr) {
365         self.walk_expr(expr)
366     }
367
368     pub fn walk_expr(&mut self, expr: &hir::Expr) {
369         debug!("walk_expr(expr={:?})", expr);
370
371         self.walk_adjustment(expr);
372
373         match expr.node {
374             hir::ExprPath(..) => { }
375
376             hir::ExprUnary(hir::UnDeref, ref base) => {      // *base
377                 if !self.walk_overloaded_operator(expr, &**base, Vec::new(), PassArgs::ByRef) {
378                     self.select_from_expr(&**base);
379                 }
380             }
381
382             hir::ExprField(ref base, _) => {         // base.f
383                 self.select_from_expr(&**base);
384             }
385
386             hir::ExprTupField(ref base, _) => {         // base.<n>
387                 self.select_from_expr(&**base);
388             }
389
390             hir::ExprIndex(ref lhs, ref rhs) => {       // lhs[rhs]
391                 if !self.walk_overloaded_operator(expr,
392                                                   &**lhs,
393                                                   vec![&**rhs],
394                                                   PassArgs::ByValue) {
395                     self.select_from_expr(&**lhs);
396                     self.consume_expr(&**rhs);
397                 }
398             }
399
400             hir::ExprRange(ref start, ref end) => {
401                 start.as_ref().map(|e| self.consume_expr(&**e));
402                 end.as_ref().map(|e| self.consume_expr(&**e));
403             }
404
405             hir::ExprCall(ref callee, ref args) => {    // callee(args)
406                 self.walk_callee(expr, &**callee);
407                 self.consume_exprs(args);
408             }
409
410             hir::ExprMethodCall(_, _, ref args) => { // callee.m(args)
411                 self.consume_exprs(args);
412             }
413
414             hir::ExprStruct(_, ref fields, ref opt_with) => {
415                 self.walk_struct_expr(expr, fields, opt_with);
416             }
417
418             hir::ExprTup(ref exprs) => {
419                 self.consume_exprs(exprs);
420             }
421
422             hir::ExprIf(ref cond_expr, ref then_blk, ref opt_else_expr) => {
423                 self.consume_expr(&**cond_expr);
424                 self.walk_block(&**then_blk);
425                 if let Some(ref else_expr) = *opt_else_expr {
426                     self.consume_expr(&**else_expr);
427                 }
428             }
429
430             hir::ExprMatch(ref discr, ref arms, _) => {
431                 let discr_cmt = return_if_err!(self.mc.cat_expr(&**discr));
432                 self.borrow_expr(&**discr, ty::ReEmpty, ty::ImmBorrow, MatchDiscriminant);
433
434                 // treatment of the discriminant is handled while walking the arms.
435                 for arm in arms {
436                     let mode = self.arm_move_mode(discr_cmt.clone(), arm);
437                     let mode = mode.match_mode();
438                     self.walk_arm(discr_cmt.clone(), arm, mode);
439                 }
440             }
441
442             hir::ExprVec(ref exprs) => {
443                 self.consume_exprs(exprs);
444             }
445
446             hir::ExprAddrOf(m, ref base) => {   // &base
447                 // make sure that the thing we are pointing out stays valid
448                 // for the lifetime `scope_r` of the resulting ptr:
449                 let expr_ty = return_if_err!(self.typer.node_ty(expr.id));
450                 if let ty::TyRef(&r, _) = expr_ty.sty {
451                     let bk = ty::BorrowKind::from_mutbl(m);
452                     self.borrow_expr(&**base, r, bk, AddrOf);
453                 }
454             }
455
456             hir::ExprInlineAsm(ref ia) => {
457                 for &(_, ref input) in &ia.inputs {
458                     self.consume_expr(&**input);
459                 }
460
461                 for &(_, ref output, is_rw) in &ia.outputs {
462                     self.mutate_expr(expr, &**output,
463                                            if is_rw { WriteAndRead } else { JustWrite });
464                 }
465             }
466
467             hir::ExprBreak(..) |
468             hir::ExprAgain(..) |
469             hir::ExprLit(..) => {}
470
471             hir::ExprLoop(ref blk, _) => {
472                 self.walk_block(&**blk);
473             }
474
475             hir::ExprWhile(ref cond_expr, ref blk, _) => {
476                 self.consume_expr(&**cond_expr);
477                 self.walk_block(&**blk);
478             }
479
480             hir::ExprUnary(op, ref lhs) => {
481                 let pass_args = if ::rustc_front::util::is_by_value_unop(op) {
482                     PassArgs::ByValue
483                 } else {
484                     PassArgs::ByRef
485                 };
486
487                 if !self.walk_overloaded_operator(expr, &**lhs, Vec::new(), pass_args) {
488                     self.consume_expr(&**lhs);
489                 }
490             }
491
492             hir::ExprBinary(op, ref lhs, ref rhs) => {
493                 let pass_args = if ::rustc_front::util::is_by_value_binop(op.node) {
494                     PassArgs::ByValue
495                 } else {
496                     PassArgs::ByRef
497                 };
498
499                 if !self.walk_overloaded_operator(expr, &**lhs, vec![&**rhs], pass_args) {
500                     self.consume_expr(&**lhs);
501                     self.consume_expr(&**rhs);
502                 }
503             }
504
505             hir::ExprBlock(ref blk) => {
506                 self.walk_block(&**blk);
507             }
508
509             hir::ExprRet(ref opt_expr) => {
510                 if let Some(ref expr) = *opt_expr {
511                     self.consume_expr(&**expr);
512                 }
513             }
514
515             hir::ExprAssign(ref lhs, ref rhs) => {
516                 self.mutate_expr(expr, &**lhs, JustWrite);
517                 self.consume_expr(&**rhs);
518             }
519
520             hir::ExprCast(ref base, _) => {
521                 self.consume_expr(&**base);
522             }
523
524             hir::ExprAssignOp(op, ref lhs, ref rhs) => {
525                 // NB All our assignment operations take the RHS by value
526                 assert!(::rustc_front::util::is_by_value_binop(op.node));
527
528                 if !self.walk_overloaded_operator(expr, lhs, vec![rhs], PassArgs::ByValue) {
529                     self.mutate_expr(expr, &**lhs, WriteAndRead);
530                     self.consume_expr(&**rhs);
531                 }
532             }
533
534             hir::ExprRepeat(ref base, ref count) => {
535                 self.consume_expr(&**base);
536                 self.consume_expr(&**count);
537             }
538
539             hir::ExprClosure(..) => {
540                 self.walk_captures(expr)
541             }
542
543             hir::ExprBox(ref base) => {
544                 self.consume_expr(&**base);
545             }
546         }
547     }
548
549     fn walk_callee(&mut self, call: &hir::Expr, callee: &hir::Expr) {
550         let callee_ty = return_if_err!(self.typer.expr_ty_adjusted(callee));
551         debug!("walk_callee: callee={:?} callee_ty={:?}",
552                callee, callee_ty);
553         let call_scope = self.tcx().region_maps.node_extent(call.id);
554         match callee_ty.sty {
555             ty::TyBareFn(..) => {
556                 self.consume_expr(callee);
557             }
558             ty::TyError => { }
559             _ => {
560                 let overloaded_call_type =
561                     match self.typer.node_method_id(ty::MethodCall::expr(call.id)) {
562                         Some(method_id) => {
563                             OverloadedCallType::from_method_id(self.tcx(), method_id)
564                         }
565                         None => {
566                             self.tcx().sess.span_bug(
567                                 callee.span,
568                                 &format!("unexpected callee type {}", callee_ty))
569                         }
570                     };
571                 match overloaded_call_type {
572                     FnMutOverloadedCall => {
573                         self.borrow_expr(callee,
574                                          ty::ReScope(call_scope),
575                                          ty::MutBorrow,
576                                          ClosureInvocation);
577                     }
578                     FnOverloadedCall => {
579                         self.borrow_expr(callee,
580                                          ty::ReScope(call_scope),
581                                          ty::ImmBorrow,
582                                          ClosureInvocation);
583                     }
584                     FnOnceOverloadedCall => self.consume_expr(callee),
585                 }
586             }
587         }
588     }
589
590     fn walk_stmt(&mut self, stmt: &hir::Stmt) {
591         match stmt.node {
592             hir::StmtDecl(ref decl, _) => {
593                 match decl.node {
594                     hir::DeclLocal(ref local) => {
595                         self.walk_local(&**local);
596                     }
597
598                     hir::DeclItem(_) => {
599                         // we don't visit nested items in this visitor,
600                         // only the fn body we were given.
601                     }
602                 }
603             }
604
605             hir::StmtExpr(ref expr, _) |
606             hir::StmtSemi(ref expr, _) => {
607                 self.consume_expr(&**expr);
608             }
609         }
610     }
611
612     fn walk_local(&mut self, local: &hir::Local) {
613         match local.init {
614             None => {
615                 let delegate = &mut self.delegate;
616                 pat_util::pat_bindings(&self.typer.tcx.def_map, &*local.pat,
617                                        |_, id, span, _| {
618                     delegate.decl_without_init(id, span);
619                 })
620             }
621
622             Some(ref expr) => {
623                 // Variable declarations with
624                 // initializers are considered
625                 // "assigns", which is handled by
626                 // `walk_pat`:
627                 self.walk_expr(&**expr);
628                 let init_cmt = return_if_err!(self.mc.cat_expr(&**expr));
629                 self.walk_irrefutable_pat(init_cmt, &*local.pat);
630             }
631         }
632     }
633
634     /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
635     /// depending on its type.
636     fn walk_block(&mut self, blk: &hir::Block) {
637         debug!("walk_block(blk.id={})", blk.id);
638
639         for stmt in &blk.stmts {
640             self.walk_stmt(&**stmt);
641         }
642
643         if let Some(ref tail_expr) = blk.expr {
644             self.consume_expr(&**tail_expr);
645         }
646     }
647
648     fn walk_struct_expr(&mut self,
649                         _expr: &hir::Expr,
650                         fields: &Vec<hir::Field>,
651                         opt_with: &Option<P<hir::Expr>>) {
652         // Consume the expressions supplying values for each field.
653         for field in fields {
654             self.consume_expr(&*field.expr);
655         }
656
657         let with_expr = match *opt_with {
658             Some(ref w) => &**w,
659             None => { return; }
660         };
661
662         let with_cmt = return_if_err!(self.mc.cat_expr(&*with_expr));
663
664         // Select just those fields of the `with`
665         // expression that will actually be used
666         if let ty::TyStruct(def, substs) = with_cmt.ty.sty {
667             // Consume those fields of the with expression that are needed.
668             for with_field in &def.struct_variant().fields {
669                 if !contains_field_named(with_field, fields) {
670                     let cmt_field = self.mc.cat_field(
671                         &*with_expr,
672                         with_cmt.clone(),
673                         with_field.name,
674                         with_field.ty(self.tcx(), substs)
675                     );
676                     self.delegate_consume(with_expr.id, with_expr.span, cmt_field);
677                 }
678             }
679         } else {
680             // the base expression should always evaluate to a
681             // struct; however, when EUV is run during typeck, it
682             // may not. This will generate an error earlier in typeck,
683             // so we can just ignore it.
684             if !self.tcx().sess.has_errors() {
685                 self.tcx().sess.span_bug(
686                     with_expr.span,
687                     "with expression doesn't evaluate to a struct");
688             }
689         };
690
691         // walk the with expression so that complex expressions
692         // are properly handled.
693         self.walk_expr(with_expr);
694
695         fn contains_field_named(field: ty::FieldDef,
696                                 fields: &Vec<hir::Field>)
697                                 -> bool
698         {
699             fields.iter().any(
700                 |f| f.name.node == field.name)
701         }
702     }
703
704     // Invoke the appropriate delegate calls for anything that gets
705     // consumed or borrowed as part of the automatic adjustment
706     // process.
707     fn walk_adjustment(&mut self, expr: &hir::Expr) {
708         let typer = self.typer;
709         //NOTE(@jroesch): mixed RefCell borrow causes crash
710         let adj = typer.adjustments().get(&expr.id).map(|x| x.clone());
711         if let Some(adjustment) = adj {
712             match adjustment {
713                 adjustment::AdjustReifyFnPointer |
714                 adjustment::AdjustUnsafeFnPointer => {
715                     // Creating a closure/fn-pointer or unsizing consumes
716                     // the input and stores it into the resulting rvalue.
717                     debug!("walk_adjustment(AdjustReifyFnPointer|AdjustUnsafeFnPointer)");
718                     let cmt_unadjusted =
719                         return_if_err!(self.mc.cat_expr_unadjusted(expr));
720                     self.delegate_consume(expr.id, expr.span, cmt_unadjusted);
721                 }
722                 adjustment::AdjustDerefRef(ref adj) => {
723                     self.walk_autoderefref(expr, adj);
724                 }
725             }
726         }
727     }
728
729     /// Autoderefs for overloaded Deref calls in fact reference their receiver. That is, if we have
730     /// `(*x)` where `x` is of type `Rc<T>`, then this in fact is equivalent to `x.deref()`. Since
731     /// `deref()` is declared with `&self`, this is an autoref of `x`.
732     fn walk_autoderefs(&mut self,
733                        expr: &hir::Expr,
734                        autoderefs: usize) {
735         debug!("walk_autoderefs expr={:?} autoderefs={}", expr, autoderefs);
736
737         for i in 0..autoderefs {
738             let deref_id = ty::MethodCall::autoderef(expr.id, i as u32);
739             match self.typer.node_method_ty(deref_id) {
740                 None => {}
741                 Some(method_ty) => {
742                     let cmt = return_if_err!(self.mc.cat_expr_autoderefd(expr, i));
743
744                     // the method call infrastructure should have
745                     // replaced all late-bound regions with variables:
746                     let self_ty = method_ty.fn_sig().input(0);
747                     let self_ty = self.tcx().no_late_bound_regions(&self_ty).unwrap();
748
749                     let (m, r) = match self_ty.sty {
750                         ty::TyRef(r, ref m) => (m.mutbl, r),
751                         _ => self.tcx().sess.span_bug(expr.span,
752                                 &format!("bad overloaded deref type {:?}",
753                                     method_ty))
754                     };
755                     let bk = ty::BorrowKind::from_mutbl(m);
756                     self.delegate.borrow(expr.id, expr.span, cmt,
757                                          *r, bk, AutoRef);
758                 }
759             }
760         }
761     }
762
763     fn walk_autoderefref(&mut self,
764                          expr: &hir::Expr,
765                          adj: &adjustment::AutoDerefRef<'tcx>) {
766         debug!("walk_autoderefref expr={:?} adj={:?}",
767                expr,
768                adj);
769
770         self.walk_autoderefs(expr, adj.autoderefs);
771
772         let cmt_derefd =
773             return_if_err!(self.mc.cat_expr_autoderefd(expr, adj.autoderefs));
774
775         let cmt_refd =
776             self.walk_autoref(expr, cmt_derefd, adj.autoref);
777
778         if adj.unsize.is_some() {
779             // Unsizing consumes the thin pointer and produces a fat one.
780             self.delegate_consume(expr.id, expr.span, cmt_refd);
781         }
782     }
783
784
785     /// Walks the autoref `opt_autoref` applied to the autoderef'd
786     /// `expr`. `cmt_derefd` is the mem-categorized form of `expr`
787     /// after all relevant autoderefs have occurred. Because AutoRefs
788     /// can be recursive, this function is recursive: it first walks
789     /// deeply all the way down the autoref chain, and then processes
790     /// the autorefs on the way out. At each point, it returns the
791     /// `cmt` for the rvalue that will be produced by introduced an
792     /// autoref.
793     fn walk_autoref(&mut self,
794                     expr: &hir::Expr,
795                     cmt_base: mc::cmt<'tcx>,
796                     opt_autoref: Option<adjustment::AutoRef<'tcx>>)
797                     -> mc::cmt<'tcx>
798     {
799         debug!("walk_autoref(expr.id={} cmt_derefd={:?} opt_autoref={:?})",
800                expr.id,
801                cmt_base,
802                opt_autoref);
803
804         let cmt_base_ty = cmt_base.ty;
805
806         let autoref = match opt_autoref {
807             Some(ref autoref) => autoref,
808             None => {
809                 // No AutoRef.
810                 return cmt_base;
811             }
812         };
813
814         match *autoref {
815             adjustment::AutoPtr(r, m) => {
816                 self.delegate.borrow(expr.id,
817                                      expr.span,
818                                      cmt_base,
819                                      *r,
820                                      ty::BorrowKind::from_mutbl(m),
821                                      AutoRef);
822             }
823
824             adjustment::AutoUnsafe(m) => {
825                 debug!("walk_autoref: expr.id={} cmt_base={:?}",
826                        expr.id,
827                        cmt_base);
828
829                 // Converting from a &T to *T (or &mut T to *mut T) is
830                 // treated as borrowing it for the enclosing temporary
831                 // scope.
832                 let r = ty::ReScope(self.tcx().region_maps.node_extent(expr.id));
833
834                 self.delegate.borrow(expr.id,
835                                      expr.span,
836                                      cmt_base,
837                                      r,
838                                      ty::BorrowKind::from_mutbl(m),
839                                      AutoUnsafe);
840             }
841         }
842
843         // Construct the categorization for the result of the autoref.
844         // This is always an rvalue, since we are producing a new
845         // (temporary) indirection.
846
847         let adj_ty = cmt_base_ty.adjust_for_autoref(self.tcx(), opt_autoref);
848
849         self.mc.cat_rvalue_node(expr.id, expr.span, adj_ty)
850     }
851
852
853     // When this returns true, it means that the expression *is* a
854     // method-call (i.e. via the operator-overload).  This true result
855     // also implies that walk_overloaded_operator already took care of
856     // recursively processing the input arguments, and thus the caller
857     // should not do so.
858     fn walk_overloaded_operator(&mut self,
859                                 expr: &hir::Expr,
860                                 receiver: &hir::Expr,
861                                 rhs: Vec<&hir::Expr>,
862                                 pass_args: PassArgs)
863                                 -> bool
864     {
865         if !self.typer.is_method_call(expr.id) {
866             return false;
867         }
868
869         match pass_args {
870             PassArgs::ByValue => {
871                 self.consume_expr(receiver);
872                 for &arg in &rhs {
873                     self.consume_expr(arg);
874                 }
875
876                 return true;
877             },
878             PassArgs::ByRef => {},
879         }
880
881         self.walk_expr(receiver);
882
883         // Arguments (but not receivers) to overloaded operator
884         // methods are implicitly autoref'd which sadly does not use
885         // adjustments, so we must hardcode the borrow here.
886
887         let r = ty::ReScope(self.tcx().region_maps.node_extent(expr.id));
888         let bk = ty::ImmBorrow;
889
890         for &arg in &rhs {
891             self.borrow_expr(arg, r, bk, OverloadedOperator);
892         }
893         return true;
894     }
895
896     fn arm_move_mode(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm) -> TrackMatchMode {
897         let mut mode = Unknown;
898         for pat in &arm.pats {
899             self.determine_pat_move_mode(discr_cmt.clone(), &**pat, &mut mode);
900         }
901         mode
902     }
903
904     fn walk_arm(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm, mode: MatchMode) {
905         for pat in &arm.pats {
906             self.walk_pat(discr_cmt.clone(), &**pat, mode);
907         }
908
909         if let Some(ref guard) = arm.guard {
910             self.consume_expr(&**guard);
911         }
912
913         self.consume_expr(&*arm.body);
914     }
915
916     /// Walks an pat that occurs in isolation (i.e. top-level of fn
917     /// arg or let binding.  *Not* a match arm or nested pat.)
918     fn walk_irrefutable_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat) {
919         let mut mode = Unknown;
920         self.determine_pat_move_mode(cmt_discr.clone(), pat, &mut mode);
921         let mode = mode.match_mode();
922         self.walk_pat(cmt_discr, pat, mode);
923     }
924
925     /// Identifies any bindings within `pat` and accumulates within
926     /// `mode` whether the overall pattern/match structure is a move,
927     /// copy, or borrow.
928     fn determine_pat_move_mode(&mut self,
929                                cmt_discr: mc::cmt<'tcx>,
930                                pat: &hir::Pat,
931                                mode: &mut TrackMatchMode) {
932         debug!("determine_pat_move_mode cmt_discr={:?} pat={:?}", cmt_discr,
933                pat);
934         return_if_err!(self.mc.cat_pattern(cmt_discr, pat, |_mc, cmt_pat, pat| {
935             let tcx = self.tcx();
936             let def_map = &self.tcx().def_map;
937             if pat_util::pat_is_binding(def_map, pat) {
938                 match pat.node {
939                     hir::PatIdent(hir::BindByRef(_), _, _) =>
940                         mode.lub(BorrowingMatch),
941                     hir::PatIdent(hir::BindByValue(_), _, _) => {
942                         match copy_or_move(self.typer, &cmt_pat, PatBindingMove) {
943                             Copy => mode.lub(CopyingMatch),
944                             Move(_) => mode.lub(MovingMatch),
945                         }
946                     }
947                     _ => {
948                         tcx.sess.span_bug(
949                             pat.span,
950                             "binding pattern not an identifier");
951                     }
952                 }
953             }
954         }));
955     }
956
957     /// The core driver for walking a pattern; `match_mode` must be
958     /// established up front, e.g. via `determine_pat_move_mode` (see
959     /// also `walk_irrefutable_pat` for patterns that stand alone).
960     fn walk_pat(&mut self,
961                 cmt_discr: mc::cmt<'tcx>,
962                 pat: &hir::Pat,
963                 match_mode: MatchMode) {
964         debug!("walk_pat cmt_discr={:?} pat={:?}", cmt_discr,
965                pat);
966
967         let mc = &self.mc;
968         let typer = self.typer;
969         let def_map = &self.tcx().def_map;
970         let delegate = &mut self.delegate;
971         return_if_err!(mc.cat_pattern(cmt_discr.clone(), pat, |mc, cmt_pat, pat| {
972             if pat_util::pat_is_binding(def_map, pat) {
973                 let tcx = typer.tcx;
974
975                 debug!("binding cmt_pat={:?} pat={:?} match_mode={:?}",
976                        cmt_pat,
977                        pat,
978                        match_mode);
979
980                 // pat_ty: the type of the binding being produced.
981                 let pat_ty = return_if_err!(typer.node_ty(pat.id));
982
983                 // Each match binding is effectively an assignment to the
984                 // binding being produced.
985                 let def = def_map.borrow().get(&pat.id).unwrap().full_def();
986                 match mc.cat_def(pat.id, pat.span, pat_ty, def) {
987                     Ok(binding_cmt) => {
988                         delegate.mutate(pat.id, pat.span, binding_cmt, Init);
989                     }
990                     Err(_) => { }
991                 }
992
993                 // It is also a borrow or copy/move of the value being matched.
994                 match pat.node {
995                     hir::PatIdent(hir::BindByRef(m), _, _) => {
996                         if let ty::TyRef(&r, _) = pat_ty.sty {
997                             let bk = ty::BorrowKind::from_mutbl(m);
998                             delegate.borrow(pat.id, pat.span, cmt_pat,
999                                             r, bk, RefBinding);
1000                         }
1001                     }
1002                     hir::PatIdent(hir::BindByValue(_), _, _) => {
1003                         let mode = copy_or_move(typer, &cmt_pat, PatBindingMove);
1004                         debug!("walk_pat binding consuming pat");
1005                         delegate.consume_pat(pat, cmt_pat, mode);
1006                     }
1007                     _ => {
1008                         tcx.sess.span_bug(
1009                             pat.span,
1010                             "binding pattern not an identifier");
1011                     }
1012                 }
1013             } else {
1014                 match pat.node {
1015                     hir::PatVec(_, Some(ref slice_pat), _) => {
1016                         // The `slice_pat` here creates a slice into
1017                         // the original vector.  This is effectively a
1018                         // borrow of the elements of the vector being
1019                         // matched.
1020
1021                         let (slice_cmt, slice_mutbl, slice_r) =
1022                             return_if_err!(mc.cat_slice_pattern(cmt_pat, &**slice_pat));
1023
1024                         // Note: We declare here that the borrow
1025                         // occurs upon entering the `[...]`
1026                         // pattern. This implies that something like
1027                         // `[a; b]` where `a` is a move is illegal,
1028                         // because the borrow is already in effect.
1029                         // In fact such a move would be safe-ish, but
1030                         // it effectively *requires* that we use the
1031                         // nulling out semantics to indicate when a
1032                         // value has been moved, which we are trying
1033                         // to move away from.  Otherwise, how can we
1034                         // indicate that the first element in the
1035                         // vector has been moved?  Eventually, we
1036                         // could perhaps modify this rule to permit
1037                         // `[..a, b]` where `b` is a move, because in
1038                         // that case we can adjust the length of the
1039                         // original vec accordingly, but we'd have to
1040                         // make trans do the right thing, and it would
1041                         // only work for `Box<[T]>`s. It seems simpler
1042                         // to just require that people call
1043                         // `vec.pop()` or `vec.unshift()`.
1044                         let slice_bk = ty::BorrowKind::from_mutbl(slice_mutbl);
1045                         delegate.borrow(pat.id, pat.span,
1046                                         slice_cmt, slice_r,
1047                                         slice_bk, RefBinding);
1048                     }
1049                     _ => { }
1050                 }
1051             }
1052         }));
1053
1054         // Do a second pass over the pattern, calling `matched_pat` on
1055         // the interior nodes (enum variants and structs), as opposed
1056         // to the above loop's visit of than the bindings that form
1057         // the leaves of the pattern tree structure.
1058         return_if_err!(mc.cat_pattern(cmt_discr, pat, |mc, cmt_pat, pat| {
1059             let def_map = def_map.borrow();
1060             let tcx = typer.tcx;
1061
1062             match pat.node {
1063                 hir::PatEnum(_, _) | hir::PatQPath(..) |
1064                 hir::PatIdent(_, _, None) | hir::PatStruct(..) => {
1065                     match def_map.get(&pat.id).map(|d| d.full_def()) {
1066                         None => {
1067                             // no definition found: pat is not a
1068                             // struct or enum pattern.
1069                         }
1070
1071                         Some(def::DefVariant(enum_did, variant_did, _is_struct)) => {
1072                             let downcast_cmt =
1073                                 if tcx.lookup_adt_def(enum_did).is_univariant() {
1074                                     cmt_pat
1075                                 } else {
1076                                     let cmt_pat_ty = cmt_pat.ty;
1077                                     mc.cat_downcast(pat, cmt_pat, cmt_pat_ty, variant_did)
1078                                 };
1079
1080                             debug!("variant downcast_cmt={:?} pat={:?}",
1081                                    downcast_cmt,
1082                                    pat);
1083
1084                             delegate.matched_pat(pat, downcast_cmt, match_mode);
1085                         }
1086
1087                         Some(def::DefStruct(..)) | Some(def::DefTy(_, false)) => {
1088                             // A struct (in either the value or type
1089                             // namespace; we encounter the former on
1090                             // e.g. patterns for unit structs).
1091
1092                             debug!("struct cmt_pat={:?} pat={:?}",
1093                                    cmt_pat,
1094                                    pat);
1095
1096                             delegate.matched_pat(pat, cmt_pat, match_mode);
1097                         }
1098
1099                         Some(def::DefConst(..)) |
1100                         Some(def::DefAssociatedConst(..)) |
1101                         Some(def::DefLocal(..)) => {
1102                             // This is a leaf (i.e. identifier binding
1103                             // or constant value to match); thus no
1104                             // `matched_pat` call.
1105                         }
1106
1107                         Some(def @ def::DefTy(_, true)) => {
1108                             // An enum's type -- should never be in a
1109                             // pattern.
1110
1111                             if !tcx.sess.has_errors() {
1112                                 let msg = format!("Pattern has unexpected type: {:?} and type {:?}",
1113                                                   def,
1114                                                   cmt_pat.ty);
1115                                 tcx.sess.span_bug(pat.span, &msg)
1116                             }
1117                         }
1118
1119                         Some(def) => {
1120                             // Remaining cases are e.g. DefFn, to
1121                             // which identifiers within patterns
1122                             // should not resolve. However, we do
1123                             // encouter this when using the
1124                             // expr-use-visitor during typeck. So just
1125                             // ignore it, an error should have been
1126                             // reported.
1127
1128                             if !tcx.sess.has_errors() {
1129                                 let msg = format!("Pattern has unexpected def: {:?} and type {:?}",
1130                                                   def,
1131                                                   cmt_pat.ty);
1132                                 tcx.sess.span_bug(pat.span, &msg[..])
1133                             }
1134                         }
1135                     }
1136                 }
1137
1138                 hir::PatIdent(_, _, Some(_)) => {
1139                     // Do nothing; this is a binding (not a enum
1140                     // variant or struct), and the cat_pattern call
1141                     // will visit the substructure recursively.
1142                 }
1143
1144                 hir::PatWild(_) | hir::PatTup(..) | hir::PatBox(..) |
1145                 hir::PatRegion(..) | hir::PatLit(..) | hir::PatRange(..) |
1146                 hir::PatVec(..) => {
1147                     // Similarly, each of these cases does not
1148                     // correspond to a enum variant or struct, so we
1149                     // do not do any `matched_pat` calls for these
1150                     // cases either.
1151                 }
1152             }
1153         }));
1154     }
1155
1156     fn walk_captures(&mut self, closure_expr: &hir::Expr) {
1157         debug!("walk_captures({:?})", closure_expr);
1158
1159         self.tcx().with_freevars(closure_expr.id, |freevars| {
1160             for freevar in freevars {
1161                 let id_var = freevar.def.var_id();
1162                 let upvar_id = ty::UpvarId { var_id: id_var,
1163                                              closure_expr_id: closure_expr.id };
1164                 let upvar_capture = self.typer.upvar_capture(upvar_id).unwrap();
1165                 let cmt_var = return_if_err!(self.cat_captured_var(closure_expr.id,
1166                                                                    closure_expr.span,
1167                                                                    freevar.def));
1168                 match upvar_capture {
1169                     ty::UpvarCapture::ByValue => {
1170                         let mode = copy_or_move(self.typer, &cmt_var, CaptureMove);
1171                         self.delegate.consume(closure_expr.id, freevar.span, cmt_var, mode);
1172                     }
1173                     ty::UpvarCapture::ByRef(upvar_borrow) => {
1174                         self.delegate.borrow(closure_expr.id,
1175                                              closure_expr.span,
1176                                              cmt_var,
1177                                              upvar_borrow.region,
1178                                              upvar_borrow.kind,
1179                                              ClosureCapture(freevar.span));
1180                     }
1181                 }
1182             }
1183         });
1184     }
1185
1186     fn cat_captured_var(&mut self,
1187                         closure_id: ast::NodeId,
1188                         closure_span: Span,
1189                         upvar_def: def::Def)
1190                         -> mc::McResult<mc::cmt<'tcx>> {
1191         // Create the cmt for the variable being borrowed, from the
1192         // caller's perspective
1193         let var_id = upvar_def.var_id();
1194         let var_ty = try!(self.typer.node_ty(var_id));
1195         self.mc.cat_def(closure_id, closure_span, var_ty, upvar_def)
1196     }
1197 }
1198
1199 fn copy_or_move<'a, 'tcx>(typer: &infer::InferCtxt<'a, 'tcx>,
1200                       cmt: &mc::cmt<'tcx>,
1201                       move_reason: MoveReason)
1202                       -> ConsumeMode
1203 {
1204     if typer.type_moves_by_default(cmt.ty, cmt.span) {
1205         Move(move_reason)
1206     } else {
1207         Copy
1208     }
1209 }