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