]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/expr_use_visitor.rs
rollup merge of #17306 : scialex/fix-zsh
[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 /*!
12  * A different sort of visitor for walking fn bodies.  Unlike the
13  * normal visitor, which just walks the entire body in one shot, the
14  * `ExprUseVisitor` determines how expressions are being used.
15  */
16
17 use middle::mem_categorization as mc;
18 use middle::def;
19 use middle::mem_categorization::Typer;
20 use middle::pat_util;
21 use middle::ty;
22 use middle::typeck::{MethodCall, MethodObject, MethodOrigin, MethodParam};
23 use middle::typeck::{MethodStatic, MethodStaticUnboxedClosure};
24 use middle::typeck;
25 use util::ppaux::Repr;
26
27 use syntax::ast;
28 use syntax::ptr::P;
29 use syntax::codemap::Span;
30
31 ///////////////////////////////////////////////////////////////////////////
32 // The Delegate trait
33
34 /// This trait defines the callbacks you can expect to receive when
35 /// employing the ExprUseVisitor.
36 pub trait Delegate {
37     // The value found at `cmt` is either copied or moved, depending
38     // on mode.
39     fn consume(&mut self,
40                consume_id: ast::NodeId,
41                consume_span: Span,
42                cmt: mc::cmt,
43                mode: ConsumeMode);
44
45     // The value found at `cmt` is either copied or moved via the
46     // pattern binding `consume_pat`, depending on mode.
47     fn consume_pat(&mut self,
48                    consume_pat: &ast::Pat,
49                    cmt: mc::cmt,
50                    mode: ConsumeMode);
51
52     // The value found at `borrow` is being borrowed at the point
53     // `borrow_id` for the region `loan_region` with kind `bk`.
54     fn borrow(&mut self,
55               borrow_id: ast::NodeId,
56               borrow_span: Span,
57               cmt: mc::cmt,
58               loan_region: ty::Region,
59               bk: ty::BorrowKind,
60               loan_cause: LoanCause);
61
62     // The local variable `id` is declared but not initialized.
63     fn decl_without_init(&mut self,
64                          id: ast::NodeId,
65                          span: Span);
66
67     // The path at `cmt` is being assigned to.
68     fn mutate(&mut self,
69               assignment_id: ast::NodeId,
70               assignment_span: Span,
71               assignee_cmt: mc::cmt,
72               mode: MutateMode);
73 }
74
75 #[deriving(PartialEq)]
76 pub enum LoanCause {
77     ClosureCapture(Span),
78     AddrOf,
79     AutoRef,
80     RefBinding,
81     OverloadedOperator,
82     ClosureInvocation,
83     ForLoop,
84 }
85
86 #[deriving(PartialEq,Show)]
87 pub enum ConsumeMode {
88     Copy,                // reference to x where x has a type that copies
89     Move(MoveReason),    // reference to x where x has a type that moves
90 }
91
92 #[deriving(PartialEq,Show)]
93 pub enum MoveReason {
94     DirectRefMove,
95     PatBindingMove,
96     CaptureMove,
97 }
98
99 #[deriving(PartialEq,Show)]
100 pub enum MutateMode {
101     Init,
102     JustWrite,    // x = y
103     WriteAndRead, // x += y
104 }
105
106 enum OverloadedCallType {
107     FnOverloadedCall,
108     FnMutOverloadedCall,
109     FnOnceOverloadedCall,
110 }
111
112 impl OverloadedCallType {
113     fn from_trait_id(tcx: &ty::ctxt, trait_id: ast::DefId)
114                      -> OverloadedCallType {
115         for &(maybe_function_trait, overloaded_call_type) in [
116             (tcx.lang_items.fn_once_trait(), FnOnceOverloadedCall),
117             (tcx.lang_items.fn_mut_trait(), FnMutOverloadedCall),
118             (tcx.lang_items.fn_trait(), FnOverloadedCall)
119         ].iter() {
120             match maybe_function_trait {
121                 Some(function_trait) if function_trait == trait_id => {
122                     return overloaded_call_type
123                 }
124                 _ => continue,
125             }
126         }
127
128         tcx.sess.bug("overloaded call didn't map to known function trait")
129     }
130
131     fn from_method_id(tcx: &ty::ctxt, method_id: ast::DefId)
132                       -> OverloadedCallType {
133         let method_descriptor = match ty::impl_or_trait_item(tcx, method_id) {
134             ty::MethodTraitItem(ref method_descriptor) => {
135                 (*method_descriptor).clone()
136             }
137             ty::TypeTraitItem(_) => {
138                 tcx.sess.bug("overloaded call method wasn't in method map")
139             }
140         };
141         let impl_id = match method_descriptor.container {
142             ty::TraitContainer(_) => {
143                 tcx.sess.bug("statically resolved overloaded call method \
144                               belonged to a trait?!")
145             }
146             ty::ImplContainer(impl_id) => impl_id,
147         };
148         let trait_ref = match ty::impl_trait_ref(tcx, impl_id) {
149             None => {
150                 tcx.sess.bug("statically resolved overloaded call impl \
151                               didn't implement a trait?!")
152             }
153             Some(ref trait_ref) => (*trait_ref).clone(),
154         };
155         OverloadedCallType::from_trait_id(tcx, trait_ref.def_id)
156     }
157
158     fn from_unboxed_closure(tcx: &ty::ctxt, closure_did: ast::DefId)
159                             -> OverloadedCallType {
160         let trait_did =
161             tcx.unboxed_closures
162                .borrow()
163                .find(&closure_did)
164                .expect("OverloadedCallType::from_unboxed_closure: didn't \
165                         find closure id")
166                .kind
167                .trait_did(tcx);
168         OverloadedCallType::from_trait_id(tcx, trait_did)
169     }
170
171     fn from_method_origin(tcx: &ty::ctxt, origin: &MethodOrigin)
172                           -> OverloadedCallType {
173         match *origin {
174             MethodStatic(def_id) => {
175                 OverloadedCallType::from_method_id(tcx, def_id)
176             }
177             MethodStaticUnboxedClosure(def_id) => {
178                 OverloadedCallType::from_unboxed_closure(tcx, def_id)
179             }
180             MethodParam(MethodParam { trait_ref: ref trait_ref, .. }) |
181             MethodObject(MethodObject { trait_ref: ref trait_ref, .. }) => {
182                 OverloadedCallType::from_trait_id(tcx, trait_ref.def_id)
183             }
184         }
185     }
186 }
187
188 ///////////////////////////////////////////////////////////////////////////
189 // The ExprUseVisitor type
190 //
191 // This is the code that actually walks the tree. Like
192 // mem_categorization, it requires a TYPER, which is a type that
193 // supplies types from the tree. After type checking is complete, you
194 // can just use the tcx as the typer.
195
196 pub struct ExprUseVisitor<'d,'t,TYPER:'t> {
197     typer: &'t TYPER,
198     mc: mc::MemCategorizationContext<'t,TYPER>,
199     delegate: &'d mut Delegate+'d,
200 }
201
202 // If the TYPER results in an error, it's because the type check
203 // failed (or will fail, when the error is uncovered and reported
204 // during writeback). In this case, we just ignore this part of the
205 // code.
206 //
207 // Note that this macro appears similar to try!(), but, unlike try!(),
208 // it does not propagate the error.
209 macro_rules! return_if_err(
210     ($inp: expr) => (
211         match $inp {
212             Ok(v) => v,
213             Err(()) => return
214         }
215     )
216 )
217
218 impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,TYPER> {
219     pub fn new(delegate: &'d mut Delegate,
220                typer: &'t TYPER)
221                -> ExprUseVisitor<'d,'t,TYPER> {
222         ExprUseVisitor { typer: typer,
223                          mc: mc::MemCategorizationContext::new(typer),
224                          delegate: delegate }
225     }
226
227     pub fn walk_fn(&mut self,
228                    decl: &ast::FnDecl,
229                    body: &ast::Block) {
230         self.walk_arg_patterns(decl, body);
231         self.walk_block(body);
232     }
233
234     fn walk_arg_patterns(&mut self,
235                          decl: &ast::FnDecl,
236                          body: &ast::Block) {
237         for arg in decl.inputs.iter() {
238             let arg_ty = return_if_err!(self.typer.node_ty(arg.pat.id));
239
240             let arg_cmt = self.mc.cat_rvalue(
241                 arg.id,
242                 arg.pat.span,
243                 ty::ReScope(body.id), // Args live only as long as the fn body.
244                 arg_ty);
245
246             self.walk_pat(arg_cmt, &*arg.pat);
247         }
248     }
249
250     fn tcx(&self) -> &'t ty::ctxt<'tcx> {
251         self.typer.tcx()
252     }
253
254     fn delegate_consume(&mut self,
255                         consume_id: ast::NodeId,
256                         consume_span: Span,
257                         cmt: mc::cmt) {
258         let mode = copy_or_move(self.tcx(), cmt.ty, DirectRefMove);
259         self.delegate.consume(consume_id, consume_span, cmt, mode);
260     }
261
262     fn consume_exprs(&mut self, exprs: &Vec<P<ast::Expr>>) {
263         for expr in exprs.iter() {
264             self.consume_expr(&**expr);
265         }
266     }
267
268     fn consume_expr(&mut self, expr: &ast::Expr) {
269         debug!("consume_expr(expr={})", expr.repr(self.tcx()));
270
271         let cmt = return_if_err!(self.mc.cat_expr(expr));
272         self.delegate_consume(expr.id, expr.span, cmt);
273         self.walk_expr(expr);
274     }
275
276     fn mutate_expr(&mut self,
277                    assignment_expr: &ast::Expr,
278                    expr: &ast::Expr,
279                    mode: MutateMode) {
280         let cmt = return_if_err!(self.mc.cat_expr(expr));
281         self.delegate.mutate(assignment_expr.id, assignment_expr.span, cmt, mode);
282         self.walk_expr(expr);
283     }
284
285     fn borrow_expr(&mut self,
286                    expr: &ast::Expr,
287                    r: ty::Region,
288                    bk: ty::BorrowKind,
289                    cause: LoanCause) {
290         debug!("borrow_expr(expr={}, r={}, bk={})",
291                expr.repr(self.tcx()), r.repr(self.tcx()), bk.repr(self.tcx()));
292
293         let cmt = return_if_err!(self.mc.cat_expr(expr));
294         self.delegate.borrow(expr.id, expr.span, cmt, r, bk, cause);
295
296         // Note: Unlike consume, we can ignore ExprParen. cat_expr
297         // already skips over them, and walk will uncover any
298         // attachments or whatever.
299         self.walk_expr(expr)
300     }
301
302     fn select_from_expr(&mut self, expr: &ast::Expr) {
303         self.walk_expr(expr)
304     }
305
306     pub fn walk_expr(&mut self, expr: &ast::Expr) {
307         debug!("walk_expr(expr={})", expr.repr(self.tcx()));
308
309         self.walk_adjustment(expr);
310
311         match expr.node {
312             ast::ExprParen(ref subexpr) => {
313                 self.walk_expr(&**subexpr)
314             }
315
316             ast::ExprPath(..) => { }
317
318             ast::ExprUnary(ast::UnDeref, ref base) => {      // *base
319                 if !self.walk_overloaded_operator(expr, &**base, None) {
320                     self.select_from_expr(&**base);
321                 }
322             }
323
324             ast::ExprField(ref base, _, _) => {         // base.f
325                 self.select_from_expr(&**base);
326             }
327
328             ast::ExprTupField(ref base, _, _) => {         // base.<n>
329                 self.select_from_expr(&**base);
330             }
331
332             ast::ExprIndex(ref lhs, ref rhs) => {       // lhs[rhs]
333                 if !self.walk_overloaded_operator(expr, &**lhs, Some(&**rhs)) {
334                     self.select_from_expr(&**lhs);
335                     self.consume_expr(&**rhs);
336                 }
337             }
338
339             ast::ExprCall(ref callee, ref args) => {    // callee(args)
340                 self.walk_callee(expr, &**callee);
341                 self.consume_exprs(args);
342             }
343
344             ast::ExprMethodCall(_, _, ref args) => { // callee.m(args)
345                 self.consume_exprs(args);
346             }
347
348             ast::ExprStruct(_, ref fields, ref opt_with) => {
349                 self.walk_struct_expr(expr, fields, opt_with);
350             }
351
352             ast::ExprTup(ref exprs) => {
353                 self.consume_exprs(exprs);
354             }
355
356             ast::ExprIf(ref cond_expr, ref then_blk, ref opt_else_expr) => {
357                 self.consume_expr(&**cond_expr);
358                 self.walk_block(&**then_blk);
359                 for else_expr in opt_else_expr.iter() {
360                     self.consume_expr(&**else_expr);
361                 }
362             }
363
364             ast::ExprMatch(ref discr, ref arms) => {
365                 // treatment of the discriminant is handled while
366                 // walking the arms:
367                 self.walk_expr(&**discr);
368                 let discr_cmt = return_if_err!(self.mc.cat_expr(&**discr));
369                 for arm in arms.iter() {
370                     self.walk_arm(discr_cmt.clone(), arm);
371                 }
372             }
373
374             ast::ExprVec(ref exprs) => {
375                 self.consume_exprs(exprs);
376             }
377
378             ast::ExprAddrOf(m, ref base) => {   // &base
379                 // make sure that the thing we are pointing out stays valid
380                 // for the lifetime `scope_r` of the resulting ptr:
381                 let expr_ty = ty::expr_ty(self.tcx(), expr);
382                 if !ty::type_is_bot(expr_ty) {
383                     let r = ty::ty_region(self.tcx(), expr.span, expr_ty);
384                     let bk = ty::BorrowKind::from_mutbl(m);
385                     self.borrow_expr(&**base, r, bk, AddrOf);
386                 } else {
387                     self.walk_expr(&**base);
388                 }
389             }
390
391             ast::ExprInlineAsm(ref ia) => {
392                 for &(_, ref input) in ia.inputs.iter() {
393                     self.consume_expr(&**input);
394                 }
395
396                 for &(_, ref output, is_rw) in ia.outputs.iter() {
397                     self.mutate_expr(expr, &**output,
398                                            if is_rw { WriteAndRead } else { JustWrite });
399                 }
400             }
401
402             ast::ExprBreak(..) |
403             ast::ExprAgain(..) |
404             ast::ExprLit(..) => {}
405
406             ast::ExprLoop(ref blk, _) => {
407                 self.walk_block(&**blk);
408             }
409
410             ast::ExprWhile(ref cond_expr, ref blk, _) => {
411                 self.consume_expr(&**cond_expr);
412                 self.walk_block(&**blk);
413             }
414
415             ast::ExprForLoop(ref pat, ref head, ref blk, _) => {
416                 // The pattern lives as long as the block.
417                 debug!("walk_expr for loop case: blk id={}", blk.id);
418                 self.consume_expr(&**head);
419
420                 // Fetch the type of the value that the iteration yields to
421                 // produce the pattern's categorized mutable type.
422                 let pattern_type = return_if_err!(self.typer.node_ty(pat.id));
423                 let pat_cmt = self.mc.cat_rvalue(pat.id,
424                                                  pat.span,
425                                                  ty::ReScope(blk.id),
426                                                  pattern_type);
427                 self.walk_pat(pat_cmt, &**pat);
428
429                 self.walk_block(&**blk);
430             }
431
432             ast::ExprUnary(_, ref lhs) => {
433                 if !self.walk_overloaded_operator(expr, &**lhs, None) {
434                     self.consume_expr(&**lhs);
435                 }
436             }
437
438             ast::ExprBinary(_, ref lhs, ref rhs) => {
439                 if !self.walk_overloaded_operator(expr, &**lhs, Some(&**rhs)) {
440                     self.consume_expr(&**lhs);
441                     self.consume_expr(&**rhs);
442                 }
443             }
444
445             ast::ExprBlock(ref blk) => {
446                 self.walk_block(&**blk);
447             }
448
449             ast::ExprRet(ref opt_expr) => {
450                 for expr in opt_expr.iter() {
451                     self.consume_expr(&**expr);
452                 }
453             }
454
455             ast::ExprAssign(ref lhs, ref rhs) => {
456                 self.mutate_expr(expr, &**lhs, JustWrite);
457                 self.consume_expr(&**rhs);
458             }
459
460             ast::ExprCast(ref base, _) => {
461                 self.consume_expr(&**base);
462             }
463
464             ast::ExprAssignOp(_, ref lhs, ref rhs) => {
465                 // This will have to change if/when we support
466                 // overloaded operators for `+=` and so forth.
467                 self.mutate_expr(expr, &**lhs, WriteAndRead);
468                 self.consume_expr(&**rhs);
469             }
470
471             ast::ExprRepeat(ref base, ref count) => {
472                 self.consume_expr(&**base);
473                 self.consume_expr(&**count);
474             }
475
476             ast::ExprFnBlock(..) |
477             ast::ExprUnboxedFn(..) |
478             ast::ExprProc(..) => {
479                 self.walk_captures(expr)
480             }
481
482             ast::ExprBox(ref place, ref base) => {
483                 self.consume_expr(&**place);
484                 self.consume_expr(&**base);
485             }
486
487             ast::ExprMac(..) => {
488                 self.tcx().sess.span_bug(
489                     expr.span,
490                     "macro expression remains after expansion");
491             }
492         }
493     }
494
495     fn walk_callee(&mut self, call: &ast::Expr, callee: &ast::Expr) {
496         let callee_ty = ty::expr_ty_adjusted(self.tcx(), callee);
497         debug!("walk_callee: callee={} callee_ty={}",
498                callee.repr(self.tcx()), callee_ty.repr(self.tcx()));
499         match ty::get(callee_ty).sty {
500             ty::ty_bare_fn(..) => {
501                 self.consume_expr(callee);
502             }
503             ty::ty_closure(ref f) => {
504                 match f.onceness {
505                     ast::Many => {
506                         self.borrow_expr(callee,
507                                          ty::ReScope(call.id),
508                                          ty::UniqueImmBorrow,
509                                          ClosureInvocation);
510                     }
511                     ast::Once => {
512                         self.consume_expr(callee);
513                     }
514                 }
515             }
516             _ => {
517                 let overloaded_call_type =
518                     match self.tcx()
519                               .method_map
520                               .borrow()
521                               .find(&MethodCall::expr(call.id)) {
522                     Some(ref method_callee) => {
523                         OverloadedCallType::from_method_origin(
524                             self.tcx(),
525                             &method_callee.origin)
526                     }
527                     None => {
528                         self.tcx().sess.span_bug(
529                             callee.span,
530                             format!("unexpected callee type {}",
531                                     callee_ty.repr(self.tcx())).as_slice())
532                     }
533                 };
534                 match overloaded_call_type {
535                     FnMutOverloadedCall => {
536                         self.borrow_expr(callee,
537                                          ty::ReScope(call.id),
538                                          ty::MutBorrow,
539                                          ClosureInvocation);
540                     }
541                     FnOverloadedCall => {
542                         self.borrow_expr(callee,
543                                          ty::ReScope(call.id),
544                                          ty::ImmBorrow,
545                                          ClosureInvocation);
546                     }
547                     FnOnceOverloadedCall => self.consume_expr(callee),
548                 }
549             }
550         }
551     }
552
553     fn walk_stmt(&mut self, stmt: &ast::Stmt) {
554         match stmt.node {
555             ast::StmtDecl(ref decl, _) => {
556                 match decl.node {
557                     ast::DeclLocal(ref local) => {
558                         self.walk_local(&**local);
559                     }
560
561                     ast::DeclItem(_) => {
562                         // we don't visit nested items in this visitor,
563                         // only the fn body we were given.
564                     }
565                 }
566             }
567
568             ast::StmtExpr(ref expr, _) |
569             ast::StmtSemi(ref expr, _) => {
570                 self.consume_expr(&**expr);
571             }
572
573             ast::StmtMac(..) => {
574                 self.tcx().sess.span_bug(stmt.span, "unexpanded stmt macro");
575             }
576         }
577     }
578
579     fn walk_local(&mut self, local: &ast::Local) {
580         match local.init {
581             None => {
582                 let delegate = &mut self.delegate;
583                 pat_util::pat_bindings(&self.typer.tcx().def_map, &*local.pat,
584                                        |_, id, span, _| {
585                     delegate.decl_without_init(id, span);
586                 })
587             }
588
589             Some(ref expr) => {
590                 // Variable declarations with
591                 // initializers are considered
592                 // "assigns", which is handled by
593                 // `walk_pat`:
594                 self.walk_expr(&**expr);
595                 let init_cmt = return_if_err!(self.mc.cat_expr(&**expr));
596                 self.walk_pat(init_cmt, &*local.pat);
597             }
598         }
599     }
600
601     fn walk_block(&mut self, blk: &ast::Block) {
602         /*!
603          * Indicates that the value of `blk` will be consumed,
604          * meaning either copied or moved depending on its type.
605          */
606
607         debug!("walk_block(blk.id={:?})", blk.id);
608
609         for stmt in blk.stmts.iter() {
610             self.walk_stmt(&**stmt);
611         }
612
613         for tail_expr in blk.expr.iter() {
614             self.consume_expr(&**tail_expr);
615         }
616     }
617
618     fn walk_struct_expr(&mut self,
619                         _expr: &ast::Expr,
620                         fields: &Vec<ast::Field>,
621                         opt_with: &Option<P<ast::Expr>>) {
622         // Consume the expressions supplying values for each field.
623         for field in fields.iter() {
624             self.consume_expr(&*field.expr);
625         }
626
627         let with_expr = match *opt_with {
628             Some(ref w) => &**w,
629             None => { return; }
630         };
631
632         let with_cmt = return_if_err!(self.mc.cat_expr(&*with_expr));
633
634         // Select just those fields of the `with`
635         // expression that will actually be used
636         let with_fields = match ty::get(with_cmt.ty).sty {
637             ty::ty_struct(did, ref substs) => {
638                 ty::struct_fields(self.tcx(), did, substs)
639             }
640             _ => {
641                 self.tcx().sess.span_bug(
642                     with_expr.span,
643                     "with expression doesn't evaluate to a struct");
644             }
645         };
646
647         // Consume those fields of the with expression that are needed.
648         for with_field in with_fields.iter() {
649             if !contains_field_named(with_field, fields) {
650                 let cmt_field = self.mc.cat_field(&*with_expr,
651                                                   with_cmt.clone(),
652                                                   with_field.ident,
653                                                   with_field.mt.ty);
654                 self.delegate_consume(with_expr.id, with_expr.span, cmt_field);
655             }
656         }
657
658         fn contains_field_named(field: &ty::field,
659                                 fields: &Vec<ast::Field>)
660                                 -> bool
661         {
662             fields.iter().any(
663                 |f| f.ident.node.name == field.ident.name)
664         }
665     }
666
667     // Invoke the appropriate delegate calls for anything that gets
668     // consumed or borrowed as part of the automatic adjustment
669     // process.
670     fn walk_adjustment(&mut self, expr: &ast::Expr) {
671         let typer = self.typer;
672         match typer.adjustments().borrow().find(&expr.id) {
673             None => { }
674             Some(adjustment) => {
675                 match *adjustment {
676                     ty::AutoAddEnv(..) => {
677                         // Creating a closure consumes the input and stores it
678                         // into the resulting rvalue.
679                         debug!("walk_adjustment(AutoAddEnv)");
680                         let cmt_unadjusted =
681                             return_if_err!(self.mc.cat_expr_unadjusted(expr));
682                         self.delegate_consume(expr.id, expr.span, cmt_unadjusted);
683                     }
684                     ty::AutoDerefRef(ty::AutoDerefRef {
685                         autoref: ref opt_autoref,
686                         autoderefs: n
687                     }) => {
688                         self.walk_autoderefs(expr, n);
689
690                         match *opt_autoref {
691                             None => { }
692                             Some(ref r) => {
693                                 self.walk_autoref(expr, r, n);
694                             }
695                         }
696                     }
697                 }
698             }
699         }
700     }
701
702     fn walk_autoderefs(&mut self,
703                        expr: &ast::Expr,
704                        autoderefs: uint) {
705         /*!
706          * Autoderefs for overloaded Deref calls in fact reference
707          * their receiver. That is, if we have `(*x)` where `x` is of
708          * type `Rc<T>`, then this in fact is equivalent to
709          * `x.deref()`. Since `deref()` is declared with `&self`, this
710          * is an autoref of `x`.
711          */
712         debug!("walk_autoderefs expr={} autoderefs={}", expr.repr(self.tcx()), autoderefs);
713
714         for i in range(0, autoderefs) {
715             let deref_id = typeck::MethodCall::autoderef(expr.id, i);
716             match self.typer.node_method_ty(deref_id) {
717                 None => {}
718                 Some(method_ty) => {
719                     let cmt = return_if_err!(self.mc.cat_expr_autoderefd(expr, i));
720                     let self_ty = *ty::ty_fn_args(method_ty).get(0);
721                     let (m, r) = match ty::get(self_ty).sty {
722                         ty::ty_rptr(r, ref m) => (m.mutbl, r),
723                         _ => self.tcx().sess.span_bug(expr.span,
724                                 format!("bad overloaded deref type {}",
725                                     method_ty.repr(self.tcx())).as_slice())
726                     };
727                     let bk = ty::BorrowKind::from_mutbl(m);
728                     self.delegate.borrow(expr.id, expr.span, cmt,
729                                          r, bk, AutoRef);
730                 }
731             }
732         }
733     }
734
735     fn walk_autoref(&mut self,
736                     expr: &ast::Expr,
737                     autoref: &ty::AutoRef,
738                     n: uint) {
739         debug!("walk_autoref expr={}", expr.repr(self.tcx()));
740
741         // Match for unique trait coercions first, since we don't need the
742         // call to cat_expr_autoderefd.
743         match *autoref {
744             ty::AutoUnsizeUniq(ty::UnsizeVtable(..)) |
745             ty::AutoUnsize(ty::UnsizeVtable(..)) => {
746                 assert!(n == 1, format!("Expected exactly 1 deref with Uniq \
747                                          AutoRefs, found: {}", n));
748                 let cmt_unadjusted =
749                     return_if_err!(self.mc.cat_expr_unadjusted(expr));
750                 self.delegate_consume(expr.id, expr.span, cmt_unadjusted);
751                 return;
752             }
753             _ => {}
754         }
755
756         let cmt_derefd = return_if_err!(
757             self.mc.cat_expr_autoderefd(expr, n));
758         debug!("walk_adjustment: cmt_derefd={}",
759                cmt_derefd.repr(self.tcx()));
760
761         match *autoref {
762             ty::AutoPtr(r, m, _) => {
763                 self.delegate.borrow(expr.id,
764                                      expr.span,
765                                      cmt_derefd,
766                                      r,
767                                      ty::BorrowKind::from_mutbl(m),
768                                      AutoRef);
769             }
770             ty::AutoUnsizeUniq(_) | ty::AutoUnsize(_) | ty::AutoUnsafe(..) => {}
771         }
772     }
773
774     fn walk_overloaded_operator(&mut self,
775                                 expr: &ast::Expr,
776                                 receiver: &ast::Expr,
777                                 rhs: Option<&ast::Expr>)
778                                 -> bool
779     {
780         if !self.typer.is_method_call(expr.id) {
781             return false;
782         }
783
784         self.walk_expr(receiver);
785
786         // Arguments (but not receivers) to overloaded operator
787         // methods are implicitly autoref'd which sadly does not use
788         // adjustments, so we must hardcode the borrow here.
789
790         let r = ty::ReScope(expr.id);
791         let bk = ty::ImmBorrow;
792
793         for &arg in rhs.iter() {
794             self.borrow_expr(arg, r, bk, OverloadedOperator);
795         }
796         return true;
797     }
798
799     fn walk_arm(&mut self, discr_cmt: mc::cmt, arm: &ast::Arm) {
800         for pat in arm.pats.iter() {
801             self.walk_pat(discr_cmt.clone(), &**pat);
802         }
803
804         for guard in arm.guard.iter() {
805             self.consume_expr(&**guard);
806         }
807
808         self.consume_expr(&*arm.body);
809     }
810
811     fn walk_pat(&mut self, cmt_discr: mc::cmt, pat: &ast::Pat) {
812         debug!("walk_pat cmt_discr={} pat={}", cmt_discr.repr(self.tcx()),
813                pat.repr(self.tcx()));
814         let mc = &self.mc;
815         let typer = self.typer;
816         let tcx = typer.tcx();
817         let def_map = &self.typer.tcx().def_map;
818         let delegate = &mut self.delegate;
819         return_if_err!(mc.cat_pattern(cmt_discr, &*pat, |mc, cmt_pat, pat| {
820             if pat_util::pat_is_binding(def_map, pat) {
821                 let tcx = typer.tcx();
822
823                 debug!("binding cmt_pat={} pat={}",
824                        cmt_pat.repr(tcx),
825                        pat.repr(tcx));
826
827                 // pat_ty: the type of the binding being produced.
828                 let pat_ty = return_if_err!(typer.node_ty(pat.id));
829
830                 // Each match binding is effectively an assignment to the
831                 // binding being produced.
832                 let def = def_map.borrow().get_copy(&pat.id);
833                 match mc.cat_def(pat.id, pat.span, pat_ty, def) {
834                     Ok(binding_cmt) => {
835                         delegate.mutate(pat.id, pat.span, binding_cmt, Init);
836                     }
837                     Err(_) => { }
838                 }
839
840                 // It is also a borrow or copy/move of the value being matched.
841                 match pat.node {
842                     ast::PatIdent(ast::BindByRef(m), _, _) => {
843                         let (r, bk) = {
844                             (ty::ty_region(tcx, pat.span, pat_ty),
845                              ty::BorrowKind::from_mutbl(m))
846                         };
847                         delegate.borrow(pat.id, pat.span, cmt_pat,
848                                              r, bk, RefBinding);
849                     }
850                     ast::PatIdent(ast::BindByValue(_), _, _) => {
851                         let mode = copy_or_move(typer.tcx(), cmt_pat.ty, PatBindingMove);
852                         debug!("walk_pat binding consuming pat");
853                         delegate.consume_pat(pat, cmt_pat, mode);
854                     }
855                     _ => {
856                         typer.tcx().sess.span_bug(
857                             pat.span,
858                             "binding pattern not an identifier");
859                     }
860                 }
861             } else {
862                 match pat.node {
863                     ast::PatVec(_, Some(ref slice_pat), _) => {
864                         // The `slice_pat` here creates a slice into
865                         // the original vector.  This is effectively a
866                         // borrow of the elements of the vector being
867                         // matched.
868
869                         let (slice_cmt, slice_mutbl, slice_r) = {
870                             match mc.cat_slice_pattern(cmt_pat, &**slice_pat) {
871                                 Ok(v) => v,
872                                 Err(()) => {
873                                     tcx.sess.span_bug(slice_pat.span,
874                                                       "Err from mc")
875                                 }
876                             }
877                         };
878
879                         // Note: We declare here that the borrow
880                         // occurs upon entering the `[...]`
881                         // pattern. This implies that something like
882                         // `[a, ..b]` where `a` is a move is illegal,
883                         // because the borrow is already in effect.
884                         // In fact such a move would be safe-ish, but
885                         // it effectively *requires* that we use the
886                         // nulling out semantics to indicate when a
887                         // value has been moved, which we are trying
888                         // to move away from.  Otherwise, how can we
889                         // indicate that the first element in the
890                         // vector has been moved?  Eventually, we
891                         // could perhaps modify this rule to permit
892                         // `[..a, b]` where `b` is a move, because in
893                         // that case we can adjust the length of the
894                         // original vec accordingly, but we'd have to
895                         // make trans do the right thing, and it would
896                         // only work for `~` vectors. It seems simpler
897                         // to just require that people call
898                         // `vec.pop()` or `vec.unshift()`.
899                         let slice_bk = ty::BorrowKind::from_mutbl(slice_mutbl);
900                         delegate.borrow(pat.id, pat.span,
901                                         slice_cmt, slice_r,
902                                         slice_bk, RefBinding);
903                     }
904                     _ => { }
905                 }
906             }
907         }));
908     }
909
910     fn walk_captures(&mut self, closure_expr: &ast::Expr) {
911         debug!("walk_captures({})", closure_expr.repr(self.tcx()));
912
913         let tcx = self.typer.tcx();
914         ty::with_freevars(tcx, closure_expr.id, |freevars| {
915             match self.tcx().capture_mode(closure_expr.id) {
916                 ast::CaptureByRef => {
917                     self.walk_by_ref_captures(closure_expr, freevars);
918                 }
919                 ast::CaptureByValue => {
920                     self.walk_by_value_captures(closure_expr, freevars);
921                 }
922             }
923         });
924     }
925
926     fn walk_by_ref_captures(&mut self,
927                             closure_expr: &ast::Expr,
928                             freevars: &[ty::Freevar]) {
929         for freevar in freevars.iter() {
930             let id_var = freevar.def.def_id().node;
931             let cmt_var = return_if_err!(self.cat_captured_var(closure_expr.id,
932                                                                closure_expr.span,
933                                                                freevar.def));
934
935             // Lookup the kind of borrow the callee requires, as
936             // inferred by regionbk
937             let upvar_id = ty::UpvarId { var_id: id_var,
938                                          closure_expr_id: closure_expr.id };
939             let upvar_borrow = self.tcx().upvar_borrow_map.borrow()
940                                    .get_copy(&upvar_id);
941
942             self.delegate.borrow(closure_expr.id,
943                                  closure_expr.span,
944                                  cmt_var,
945                                  upvar_borrow.region,
946                                  upvar_borrow.kind,
947                                  ClosureCapture(freevar.span));
948         }
949     }
950
951     fn walk_by_value_captures(&mut self,
952                               closure_expr: &ast::Expr,
953                               freevars: &[ty::Freevar]) {
954         for freevar in freevars.iter() {
955             let cmt_var = return_if_err!(self.cat_captured_var(closure_expr.id,
956                                                                closure_expr.span,
957                                                                freevar.def));
958             let mode = copy_or_move(self.tcx(), cmt_var.ty, CaptureMove);
959             self.delegate.consume(closure_expr.id, freevar.span, cmt_var, mode);
960         }
961     }
962
963     fn cat_captured_var(&mut self,
964                         closure_id: ast::NodeId,
965                         closure_span: Span,
966                         upvar_def: def::Def)
967                         -> mc::McResult<mc::cmt> {
968         // Create the cmt for the variable being borrowed, from the
969         // caller's perspective
970         let var_id = upvar_def.def_id().node;
971         let var_ty = try!(self.typer.node_ty(var_id));
972         self.mc.cat_def(closure_id, closure_span, var_ty, upvar_def)
973     }
974 }
975
976 fn copy_or_move(tcx: &ty::ctxt, ty: ty::t, move_reason: MoveReason) -> ConsumeMode {
977     if ty::type_moves_by_default(tcx, ty) { Move(move_reason) } else { Copy }
978 }
979