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