]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/expr_use_visitor.rs
Use a struct instead of a tuple for inline asm output operands
[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+'d
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 output in &ia.outputs {
462                     if output.is_indirect {
463                         self.consume_expr(&*output.expr);
464                     } else {
465                         self.mutate_expr(expr, &*output.expr,
466                                          if output.is_rw { WriteAndRead } else { JustWrite });
467                     }
468                 }
469             }
470
471             hir::ExprBreak(..) |
472             hir::ExprAgain(..) |
473             hir::ExprLit(..) => {}
474
475             hir::ExprLoop(ref blk, _) => {
476                 self.walk_block(&**blk);
477             }
478
479             hir::ExprWhile(ref cond_expr, ref blk, _) => {
480                 self.consume_expr(&**cond_expr);
481                 self.walk_block(&**blk);
482             }
483
484             hir::ExprUnary(op, ref lhs) => {
485                 let pass_args = if ::rustc_front::util::is_by_value_unop(op) {
486                     PassArgs::ByValue
487                 } else {
488                     PassArgs::ByRef
489                 };
490
491                 if !self.walk_overloaded_operator(expr, &**lhs, Vec::new(), pass_args) {
492                     self.consume_expr(&**lhs);
493                 }
494             }
495
496             hir::ExprBinary(op, ref lhs, ref rhs) => {
497                 let pass_args = if ::rustc_front::util::is_by_value_binop(op.node) {
498                     PassArgs::ByValue
499                 } else {
500                     PassArgs::ByRef
501                 };
502
503                 if !self.walk_overloaded_operator(expr, &**lhs, vec![&**rhs], pass_args) {
504                     self.consume_expr(&**lhs);
505                     self.consume_expr(&**rhs);
506                 }
507             }
508
509             hir::ExprBlock(ref blk) => {
510                 self.walk_block(&**blk);
511             }
512
513             hir::ExprRet(ref opt_expr) => {
514                 if let Some(ref expr) = *opt_expr {
515                     self.consume_expr(&**expr);
516                 }
517             }
518
519             hir::ExprAssign(ref lhs, ref rhs) => {
520                 self.mutate_expr(expr, &**lhs, JustWrite);
521                 self.consume_expr(&**rhs);
522             }
523
524             hir::ExprCast(ref base, _) => {
525                 self.consume_expr(&**base);
526             }
527
528             hir::ExprAssignOp(op, ref lhs, ref rhs) => {
529                 // NB All our assignment operations take the RHS by value
530                 assert!(::rustc_front::util::is_by_value_binop(op.node));
531
532                 if !self.walk_overloaded_operator(expr, lhs, vec![rhs], PassArgs::ByValue) {
533                     self.mutate_expr(expr, &**lhs, WriteAndRead);
534                     self.consume_expr(&**rhs);
535                 }
536             }
537
538             hir::ExprRepeat(ref base, ref count) => {
539                 self.consume_expr(&**base);
540                 self.consume_expr(&**count);
541             }
542
543             hir::ExprClosure(..) => {
544                 self.walk_captures(expr)
545             }
546
547             hir::ExprBox(ref base) => {
548                 self.consume_expr(&**base);
549             }
550         }
551     }
552
553     fn walk_callee(&mut self, call: &hir::Expr, callee: &hir::Expr) {
554         let callee_ty = return_if_err!(self.typer.expr_ty_adjusted(callee));
555         debug!("walk_callee: callee={:?} callee_ty={:?}",
556                callee, callee_ty);
557         let call_scope = self.tcx().region_maps.node_extent(call.id);
558         match callee_ty.sty {
559             ty::TyBareFn(..) => {
560                 self.consume_expr(callee);
561             }
562             ty::TyError => { }
563             _ => {
564                 let overloaded_call_type =
565                     match self.typer.node_method_id(ty::MethodCall::expr(call.id)) {
566                         Some(method_id) => {
567                             OverloadedCallType::from_method_id(self.tcx(), method_id)
568                         }
569                         None => {
570                             self.tcx().sess.span_bug(
571                                 callee.span,
572                                 &format!("unexpected callee type {}", callee_ty))
573                         }
574                     };
575                 match overloaded_call_type {
576                     FnMutOverloadedCall => {
577                         self.borrow_expr(callee,
578                                          ty::ReScope(call_scope),
579                                          ty::MutBorrow,
580                                          ClosureInvocation);
581                     }
582                     FnOverloadedCall => {
583                         self.borrow_expr(callee,
584                                          ty::ReScope(call_scope),
585                                          ty::ImmBorrow,
586                                          ClosureInvocation);
587                     }
588                     FnOnceOverloadedCall => self.consume_expr(callee),
589                 }
590             }
591         }
592     }
593
594     fn walk_stmt(&mut self, stmt: &hir::Stmt) {
595         match stmt.node {
596             hir::StmtDecl(ref decl, _) => {
597                 match decl.node {
598                     hir::DeclLocal(ref local) => {
599                         self.walk_local(&**local);
600                     }
601
602                     hir::DeclItem(_) => {
603                         // we don't visit nested items in this visitor,
604                         // only the fn body we were given.
605                     }
606                 }
607             }
608
609             hir::StmtExpr(ref expr, _) |
610             hir::StmtSemi(ref expr, _) => {
611                 self.consume_expr(&**expr);
612             }
613         }
614     }
615
616     fn walk_local(&mut self, local: &hir::Local) {
617         match local.init {
618             None => {
619                 let delegate = &mut self.delegate;
620                 pat_util::pat_bindings(&self.typer.tcx.def_map, &*local.pat,
621                                        |_, id, span, _| {
622                     delegate.decl_without_init(id, span);
623                 })
624             }
625
626             Some(ref expr) => {
627                 // Variable declarations with
628                 // initializers are considered
629                 // "assigns", which is handled by
630                 // `walk_pat`:
631                 self.walk_expr(&**expr);
632                 let init_cmt = return_if_err!(self.mc.cat_expr(&**expr));
633                 self.walk_irrefutable_pat(init_cmt, &*local.pat);
634             }
635         }
636     }
637
638     /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
639     /// depending on its type.
640     fn walk_block(&mut self, blk: &hir::Block) {
641         debug!("walk_block(blk.id={})", blk.id);
642
643         for stmt in &blk.stmts {
644             self.walk_stmt(&**stmt);
645         }
646
647         if let Some(ref tail_expr) = blk.expr {
648             self.consume_expr(&**tail_expr);
649         }
650     }
651
652     fn walk_struct_expr(&mut self,
653                         _expr: &hir::Expr,
654                         fields: &Vec<hir::Field>,
655                         opt_with: &Option<P<hir::Expr>>) {
656         // Consume the expressions supplying values for each field.
657         for field in fields {
658             self.consume_expr(&*field.expr);
659         }
660
661         let with_expr = match *opt_with {
662             Some(ref w) => &**w,
663             None => { return; }
664         };
665
666         let with_cmt = return_if_err!(self.mc.cat_expr(&*with_expr));
667
668         // Select just those fields of the `with`
669         // expression that will actually be used
670         if let ty::TyStruct(def, substs) = with_cmt.ty.sty {
671             // Consume those fields of the with expression that are needed.
672             for with_field in &def.struct_variant().fields {
673                 if !contains_field_named(with_field, fields) {
674                     let cmt_field = self.mc.cat_field(
675                         &*with_expr,
676                         with_cmt.clone(),
677                         with_field.name,
678                         with_field.ty(self.tcx(), substs)
679                     );
680                     self.delegate_consume(with_expr.id, with_expr.span, cmt_field);
681                 }
682             }
683         } else {
684             // the base expression should always evaluate to a
685             // struct; however, when EUV is run during typeck, it
686             // may not. This will generate an error earlier in typeck,
687             // so we can just ignore it.
688             if !self.tcx().sess.has_errors() {
689                 self.tcx().sess.span_bug(
690                     with_expr.span,
691                     "with expression doesn't evaluate to a struct");
692             }
693         };
694
695         // walk the with expression so that complex expressions
696         // are properly handled.
697         self.walk_expr(with_expr);
698
699         fn contains_field_named(field: ty::FieldDef,
700                                 fields: &Vec<hir::Field>)
701                                 -> bool
702         {
703             fields.iter().any(
704                 |f| f.name.node == field.name)
705         }
706     }
707
708     // Invoke the appropriate delegate calls for anything that gets
709     // consumed or borrowed as part of the automatic adjustment
710     // process.
711     fn walk_adjustment(&mut self, expr: &hir::Expr) {
712         let typer = self.typer;
713         //NOTE(@jroesch): mixed RefCell borrow causes crash
714         let adj = typer.adjustments().get(&expr.id).map(|x| x.clone());
715         if let Some(adjustment) = adj {
716             match adjustment {
717                 adjustment::AdjustReifyFnPointer |
718                 adjustment::AdjustUnsafeFnPointer => {
719                     // Creating a closure/fn-pointer or unsizing consumes
720                     // the input and stores it into the resulting rvalue.
721                     debug!("walk_adjustment(AdjustReifyFnPointer|AdjustUnsafeFnPointer)");
722                     let cmt_unadjusted =
723                         return_if_err!(self.mc.cat_expr_unadjusted(expr));
724                     self.delegate_consume(expr.id, expr.span, cmt_unadjusted);
725                 }
726                 adjustment::AdjustDerefRef(ref adj) => {
727                     self.walk_autoderefref(expr, adj);
728                 }
729             }
730         }
731     }
732
733     /// Autoderefs for overloaded Deref calls in fact reference their receiver. That is, if we have
734     /// `(*x)` where `x` is of type `Rc<T>`, then this in fact is equivalent to `x.deref()`. Since
735     /// `deref()` is declared with `&self`, this is an autoref of `x`.
736     fn walk_autoderefs(&mut self,
737                        expr: &hir::Expr,
738                        autoderefs: usize) {
739         debug!("walk_autoderefs expr={:?} autoderefs={}", expr, autoderefs);
740
741         for i in 0..autoderefs {
742             let deref_id = ty::MethodCall::autoderef(expr.id, i as u32);
743             match self.typer.node_method_ty(deref_id) {
744                 None => {}
745                 Some(method_ty) => {
746                     let cmt = return_if_err!(self.mc.cat_expr_autoderefd(expr, i));
747
748                     // the method call infrastructure should have
749                     // replaced all late-bound regions with variables:
750                     let self_ty = method_ty.fn_sig().input(0);
751                     let self_ty = self.tcx().no_late_bound_regions(&self_ty).unwrap();
752
753                     let (m, r) = match self_ty.sty {
754                         ty::TyRef(r, ref m) => (m.mutbl, r),
755                         _ => self.tcx().sess.span_bug(expr.span,
756                                 &format!("bad overloaded deref type {:?}",
757                                     method_ty))
758                     };
759                     let bk = ty::BorrowKind::from_mutbl(m);
760                     self.delegate.borrow(expr.id, expr.span, cmt,
761                                          *r, bk, AutoRef);
762                 }
763             }
764         }
765     }
766
767     fn walk_autoderefref(&mut self,
768                          expr: &hir::Expr,
769                          adj: &adjustment::AutoDerefRef<'tcx>) {
770         debug!("walk_autoderefref expr={:?} adj={:?}",
771                expr,
772                adj);
773
774         self.walk_autoderefs(expr, adj.autoderefs);
775
776         let cmt_derefd =
777             return_if_err!(self.mc.cat_expr_autoderefd(expr, adj.autoderefs));
778
779         let cmt_refd =
780             self.walk_autoref(expr, cmt_derefd, adj.autoref);
781
782         if adj.unsize.is_some() {
783             // Unsizing consumes the thin pointer and produces a fat one.
784             self.delegate_consume(expr.id, expr.span, cmt_refd);
785         }
786     }
787
788
789     /// Walks the autoref `opt_autoref` applied to the autoderef'd
790     /// `expr`. `cmt_derefd` is the mem-categorized form of `expr`
791     /// after all relevant autoderefs have occurred. Because AutoRefs
792     /// can be recursive, this function is recursive: it first walks
793     /// deeply all the way down the autoref chain, and then processes
794     /// the autorefs on the way out. At each point, it returns the
795     /// `cmt` for the rvalue that will be produced by introduced an
796     /// autoref.
797     fn walk_autoref(&mut self,
798                     expr: &hir::Expr,
799                     cmt_base: mc::cmt<'tcx>,
800                     opt_autoref: Option<adjustment::AutoRef<'tcx>>)
801                     -> mc::cmt<'tcx>
802     {
803         debug!("walk_autoref(expr.id={} cmt_derefd={:?} opt_autoref={:?})",
804                expr.id,
805                cmt_base,
806                opt_autoref);
807
808         let cmt_base_ty = cmt_base.ty;
809
810         let autoref = match opt_autoref {
811             Some(ref autoref) => autoref,
812             None => {
813                 // No AutoRef.
814                 return cmt_base;
815             }
816         };
817
818         match *autoref {
819             adjustment::AutoPtr(r, m) => {
820                 self.delegate.borrow(expr.id,
821                                      expr.span,
822                                      cmt_base,
823                                      *r,
824                                      ty::BorrowKind::from_mutbl(m),
825                                      AutoRef);
826             }
827
828             adjustment::AutoUnsafe(m) => {
829                 debug!("walk_autoref: expr.id={} cmt_base={:?}",
830                        expr.id,
831                        cmt_base);
832
833                 // Converting from a &T to *T (or &mut T to *mut T) is
834                 // treated as borrowing it for the enclosing temporary
835                 // scope.
836                 let r = ty::ReScope(self.tcx().region_maps.node_extent(expr.id));
837
838                 self.delegate.borrow(expr.id,
839                                      expr.span,
840                                      cmt_base,
841                                      r,
842                                      ty::BorrowKind::from_mutbl(m),
843                                      AutoUnsafe);
844             }
845         }
846
847         // Construct the categorization for the result of the autoref.
848         // This is always an rvalue, since we are producing a new
849         // (temporary) indirection.
850
851         let adj_ty = cmt_base_ty.adjust_for_autoref(self.tcx(), opt_autoref);
852
853         self.mc.cat_rvalue_node(expr.id, expr.span, adj_ty)
854     }
855
856
857     // When this returns true, it means that the expression *is* a
858     // method-call (i.e. via the operator-overload).  This true result
859     // also implies that walk_overloaded_operator already took care of
860     // recursively processing the input arguments, and thus the caller
861     // should not do so.
862     fn walk_overloaded_operator(&mut self,
863                                 expr: &hir::Expr,
864                                 receiver: &hir::Expr,
865                                 rhs: Vec<&hir::Expr>,
866                                 pass_args: PassArgs)
867                                 -> bool
868     {
869         if !self.typer.is_method_call(expr.id) {
870             return false;
871         }
872
873         match pass_args {
874             PassArgs::ByValue => {
875                 self.consume_expr(receiver);
876                 for &arg in &rhs {
877                     self.consume_expr(arg);
878                 }
879
880                 return true;
881             },
882             PassArgs::ByRef => {},
883         }
884
885         self.walk_expr(receiver);
886
887         // Arguments (but not receivers) to overloaded operator
888         // methods are implicitly autoref'd which sadly does not use
889         // adjustments, so we must hardcode the borrow here.
890
891         let r = ty::ReScope(self.tcx().region_maps.node_extent(expr.id));
892         let bk = ty::ImmBorrow;
893
894         for &arg in &rhs {
895             self.borrow_expr(arg, r, bk, OverloadedOperator);
896         }
897         return true;
898     }
899
900     fn arm_move_mode(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm) -> TrackMatchMode {
901         let mut mode = Unknown;
902         for pat in &arm.pats {
903             self.determine_pat_move_mode(discr_cmt.clone(), &**pat, &mut mode);
904         }
905         mode
906     }
907
908     fn walk_arm(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm, mode: MatchMode) {
909         for pat in &arm.pats {
910             self.walk_pat(discr_cmt.clone(), &**pat, mode);
911         }
912
913         if let Some(ref guard) = arm.guard {
914             self.consume_expr(&**guard);
915         }
916
917         self.consume_expr(&*arm.body);
918     }
919
920     /// Walks a pat that occurs in isolation (i.e. top-level of fn
921     /// arg or let binding.  *Not* a match arm or nested pat.)
922     fn walk_irrefutable_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat) {
923         let mut mode = Unknown;
924         self.determine_pat_move_mode(cmt_discr.clone(), pat, &mut mode);
925         let mode = mode.match_mode();
926         self.walk_pat(cmt_discr, pat, mode);
927     }
928
929     /// Identifies any bindings within `pat` and accumulates within
930     /// `mode` whether the overall pattern/match structure is a move,
931     /// copy, or borrow.
932     fn determine_pat_move_mode(&mut self,
933                                cmt_discr: mc::cmt<'tcx>,
934                                pat: &hir::Pat,
935                                mode: &mut TrackMatchMode) {
936         debug!("determine_pat_move_mode cmt_discr={:?} pat={:?}", cmt_discr,
937                pat);
938         return_if_err!(self.mc.cat_pattern(cmt_discr, pat, |_mc, cmt_pat, pat| {
939             let tcx = self.tcx();
940             let def_map = &self.tcx().def_map;
941             if pat_util::pat_is_binding(&def_map.borrow(), pat) {
942                 match pat.node {
943                     hir::PatIdent(hir::BindByRef(_), _, _) =>
944                         mode.lub(BorrowingMatch),
945                     hir::PatIdent(hir::BindByValue(_), _, _) => {
946                         match copy_or_move(self.typer, &cmt_pat, PatBindingMove) {
947                             Copy => mode.lub(CopyingMatch),
948                             Move(_) => mode.lub(MovingMatch),
949                         }
950                     }
951                     _ => {
952                         tcx.sess.span_bug(
953                             pat.span,
954                             "binding pattern not an identifier");
955                     }
956                 }
957             }
958         }));
959     }
960
961     /// The core driver for walking a pattern; `match_mode` must be
962     /// established up front, e.g. via `determine_pat_move_mode` (see
963     /// also `walk_irrefutable_pat` for patterns that stand alone).
964     fn walk_pat(&mut self,
965                 cmt_discr: mc::cmt<'tcx>,
966                 pat: &hir::Pat,
967                 match_mode: MatchMode) {
968         debug!("walk_pat cmt_discr={:?} pat={:?}", cmt_discr,
969                pat);
970
971         let mc = &self.mc;
972         let typer = self.typer;
973         let def_map = &self.tcx().def_map;
974         let delegate = &mut self.delegate;
975         return_if_err!(mc.cat_pattern(cmt_discr.clone(), pat, |mc, cmt_pat, pat| {
976             if pat_util::pat_is_binding(&def_map.borrow(), pat) {
977                 let tcx = typer.tcx;
978
979                 debug!("binding cmt_pat={:?} pat={:?} match_mode={:?}",
980                        cmt_pat,
981                        pat,
982                        match_mode);
983
984                 // pat_ty: the type of the binding being produced.
985                 let pat_ty = return_if_err!(typer.node_ty(pat.id));
986
987                 // Each match binding is effectively an assignment to the
988                 // binding being produced.
989                 let def = def_map.borrow().get(&pat.id).unwrap().full_def();
990                 match mc.cat_def(pat.id, pat.span, pat_ty, def) {
991                     Ok(binding_cmt) => {
992                         delegate.mutate(pat.id, pat.span, binding_cmt, Init);
993                     }
994                     Err(_) => { }
995                 }
996
997                 // It is also a borrow or copy/move of the value being matched.
998                 match pat.node {
999                     hir::PatIdent(hir::BindByRef(m), _, _) => {
1000                         if let ty::TyRef(&r, _) = pat_ty.sty {
1001                             let bk = ty::BorrowKind::from_mutbl(m);
1002                             delegate.borrow(pat.id, pat.span, cmt_pat,
1003                                             r, bk, RefBinding);
1004                         }
1005                     }
1006                     hir::PatIdent(hir::BindByValue(_), _, _) => {
1007                         let mode = copy_or_move(typer, &cmt_pat, PatBindingMove);
1008                         debug!("walk_pat binding consuming pat");
1009                         delegate.consume_pat(pat, cmt_pat, mode);
1010                     }
1011                     _ => {
1012                         tcx.sess.span_bug(
1013                             pat.span,
1014                             "binding pattern not an identifier");
1015                     }
1016                 }
1017             } else {
1018                 match pat.node {
1019                     hir::PatVec(_, Some(ref slice_pat), _) => {
1020                         // The `slice_pat` here creates a slice into
1021                         // the original vector.  This is effectively a
1022                         // borrow of the elements of the vector being
1023                         // matched.
1024
1025                         let (slice_cmt, slice_mutbl, slice_r) =
1026                             return_if_err!(mc.cat_slice_pattern(cmt_pat, &**slice_pat));
1027
1028                         // Note: We declare here that the borrow
1029                         // occurs upon entering the `[...]`
1030                         // pattern. This implies that something like
1031                         // `[a; b]` where `a` is a move is illegal,
1032                         // because the borrow is already in effect.
1033                         // In fact such a move would be safe-ish, but
1034                         // it effectively *requires* that we use the
1035                         // nulling out semantics to indicate when a
1036                         // value has been moved, which we are trying
1037                         // to move away from.  Otherwise, how can we
1038                         // indicate that the first element in the
1039                         // vector has been moved?  Eventually, we
1040                         // could perhaps modify this rule to permit
1041                         // `[..a, b]` where `b` is a move, because in
1042                         // that case we can adjust the length of the
1043                         // original vec accordingly, but we'd have to
1044                         // make trans do the right thing, and it would
1045                         // only work for `Box<[T]>`s. It seems simpler
1046                         // to just require that people call
1047                         // `vec.pop()` or `vec.unshift()`.
1048                         let slice_bk = ty::BorrowKind::from_mutbl(slice_mutbl);
1049                         delegate.borrow(pat.id, pat.span,
1050                                         slice_cmt, slice_r,
1051                                         slice_bk, RefBinding);
1052                     }
1053                     _ => { }
1054                 }
1055             }
1056         }));
1057
1058         // Do a second pass over the pattern, calling `matched_pat` on
1059         // the interior nodes (enum variants and structs), as opposed
1060         // to the above loop's visit of than the bindings that form
1061         // the leaves of the pattern tree structure.
1062         return_if_err!(mc.cat_pattern(cmt_discr, pat, |mc, cmt_pat, pat| {
1063             let def_map = def_map.borrow();
1064             let tcx = typer.tcx;
1065
1066             match pat.node {
1067                 hir::PatEnum(_, _) | hir::PatQPath(..) |
1068                 hir::PatIdent(_, _, None) | hir::PatStruct(..) => {
1069                     match def_map.get(&pat.id).map(|d| d.full_def()) {
1070                         None => {
1071                             // no definition found: pat is not a
1072                             // struct or enum pattern.
1073                         }
1074
1075                         Some(def::DefVariant(enum_did, variant_did, _is_struct)) => {
1076                             let downcast_cmt =
1077                                 if tcx.lookup_adt_def(enum_did).is_univariant() {
1078                                     cmt_pat
1079                                 } else {
1080                                     let cmt_pat_ty = cmt_pat.ty;
1081                                     mc.cat_downcast(pat, cmt_pat, cmt_pat_ty, variant_did)
1082                                 };
1083
1084                             debug!("variant downcast_cmt={:?} pat={:?}",
1085                                    downcast_cmt,
1086                                    pat);
1087
1088                             delegate.matched_pat(pat, downcast_cmt, match_mode);
1089                         }
1090
1091                         Some(def::DefStruct(..)) | Some(def::DefTy(_, false)) => {
1092                             // A struct (in either the value or type
1093                             // namespace; we encounter the former on
1094                             // e.g. patterns for unit structs).
1095
1096                             debug!("struct cmt_pat={:?} pat={:?}",
1097                                    cmt_pat,
1098                                    pat);
1099
1100                             delegate.matched_pat(pat, cmt_pat, match_mode);
1101                         }
1102
1103                         Some(def::DefConst(..)) |
1104                         Some(def::DefAssociatedConst(..)) |
1105                         Some(def::DefLocal(..)) => {
1106                             // This is a leaf (i.e. identifier binding
1107                             // or constant value to match); thus no
1108                             // `matched_pat` call.
1109                         }
1110
1111                         Some(def @ def::DefTy(_, true)) => {
1112                             // An enum's type -- should never be in a
1113                             // pattern.
1114
1115                             if !tcx.sess.has_errors() {
1116                                 let msg = format!("Pattern has unexpected type: {:?} and type {:?}",
1117                                                   def,
1118                                                   cmt_pat.ty);
1119                                 tcx.sess.span_bug(pat.span, &msg)
1120                             }
1121                         }
1122
1123                         Some(def) => {
1124                             // Remaining cases are e.g. DefFn, to
1125                             // which identifiers within patterns
1126                             // should not resolve. However, we do
1127                             // encouter this when using the
1128                             // expr-use-visitor during typeck. So just
1129                             // ignore it, an error should have been
1130                             // reported.
1131
1132                             if !tcx.sess.has_errors() {
1133                                 let msg = format!("Pattern has unexpected def: {:?} and type {:?}",
1134                                                   def,
1135                                                   cmt_pat.ty);
1136                                 tcx.sess.span_bug(pat.span, &msg[..])
1137                             }
1138                         }
1139                     }
1140                 }
1141
1142                 hir::PatIdent(_, _, Some(_)) => {
1143                     // Do nothing; this is a binding (not an enum
1144                     // variant or struct), and the cat_pattern call
1145                     // will visit the substructure recursively.
1146                 }
1147
1148                 hir::PatWild | hir::PatTup(..) | hir::PatBox(..) |
1149                 hir::PatRegion(..) | hir::PatLit(..) | hir::PatRange(..) |
1150                 hir::PatVec(..) => {
1151                     // Similarly, each of these cases does not
1152                     // correspond to an enum variant or struct, so we
1153                     // do not do any `matched_pat` calls for these
1154                     // cases either.
1155                 }
1156             }
1157         }));
1158     }
1159
1160     fn walk_captures(&mut self, closure_expr: &hir::Expr) {
1161         debug!("walk_captures({:?})", closure_expr);
1162
1163         self.tcx().with_freevars(closure_expr.id, |freevars| {
1164             for freevar in freevars {
1165                 let id_var = freevar.def.var_id();
1166                 let upvar_id = ty::UpvarId { var_id: id_var,
1167                                              closure_expr_id: closure_expr.id };
1168                 let upvar_capture = self.typer.upvar_capture(upvar_id).unwrap();
1169                 let cmt_var = return_if_err!(self.cat_captured_var(closure_expr.id,
1170                                                                    closure_expr.span,
1171                                                                    freevar.def));
1172                 match upvar_capture {
1173                     ty::UpvarCapture::ByValue => {
1174                         let mode = copy_or_move(self.typer, &cmt_var, CaptureMove);
1175                         self.delegate.consume(closure_expr.id, freevar.span, cmt_var, mode);
1176                     }
1177                     ty::UpvarCapture::ByRef(upvar_borrow) => {
1178                         self.delegate.borrow(closure_expr.id,
1179                                              closure_expr.span,
1180                                              cmt_var,
1181                                              upvar_borrow.region,
1182                                              upvar_borrow.kind,
1183                                              ClosureCapture(freevar.span));
1184                     }
1185                 }
1186             }
1187         });
1188     }
1189
1190     fn cat_captured_var(&mut self,
1191                         closure_id: ast::NodeId,
1192                         closure_span: Span,
1193                         upvar_def: def::Def)
1194                         -> mc::McResult<mc::cmt<'tcx>> {
1195         // Create the cmt for the variable being borrowed, from the
1196         // caller's perspective
1197         let var_id = upvar_def.var_id();
1198         let var_ty = try!(self.typer.node_ty(var_id));
1199         self.mc.cat_def(closure_id, closure_span, var_ty, upvar_def)
1200     }
1201 }
1202
1203 fn copy_or_move<'a, 'tcx>(typer: &infer::InferCtxt<'a, 'tcx>,
1204                       cmt: &mc::cmt<'tcx>,
1205                       move_reason: MoveReason)
1206                       -> ConsumeMode
1207 {
1208     if typer.type_moves_by_default(cmt.ty, cmt.span) {
1209         Move(move_reason)
1210     } else {
1211         Copy
1212     }
1213 }