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.
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.
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.
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::*;
23 use middle::{def, pat_util};
24 use middle::def_id::{DefId};
26 use middle::mem_categorization as mc;
28 use middle::ty::adjustment;
34 use syntax::codemap::Span;
36 ///////////////////////////////////////////////////////////////////////////
39 /// This trait defines the callbacks you can expect to receive when
40 /// employing the ExprUseVisitor.
41 pub trait Delegate<'tcx> {
42 // The value found at `cmt` is either copied or moved, depending
45 consume_id: ast::NodeId,
50 // The value found at `cmt` has been determined to match the
51 // pattern binding `matched_pat`, and its subparts are being
52 // copied or moved depending on `mode`. Note that `matched_pat`
53 // is called on all variant/structs in the pattern (i.e., the
54 // interior nodes of the pattern's tree structure) while
55 // consume_pat is called on the binding identifiers in the pattern
56 // (which are leaves of the pattern's tree structure).
58 // Note that variants/structs and identifiers are disjoint; thus
59 // `matched_pat` and `consume_pat` are never both called on the
60 // same input pattern structure (though of `consume_pat` can be
61 // called on a subpart of an input passed to `matched_pat).
62 fn matched_pat(&mut self,
63 matched_pat: &hir::Pat,
67 // The value found at `cmt` is either copied or moved via the
68 // pattern binding `consume_pat`, depending on mode.
69 fn consume_pat(&mut self,
70 consume_pat: &hir::Pat,
74 // The value found at `borrow` is being borrowed at the point
75 // `borrow_id` for the region `loan_region` with kind `bk`.
77 borrow_id: ast::NodeId,
80 loan_region: ty::Region,
82 loan_cause: LoanCause);
84 // The local variable `id` is declared but not initialized.
85 fn decl_without_init(&mut self,
89 // The path at `cmt` is being assigned to.
91 assignment_id: ast::NodeId,
92 assignment_span: Span,
93 assignee_cmt: mc::cmt<'tcx>,
97 #[derive(Copy, Clone, PartialEq, Debug)]
110 #[derive(Copy, Clone, PartialEq, Debug)]
111 pub enum ConsumeMode {
112 Copy, // reference to x where x has a type that copies
113 Move(MoveReason), // reference to x where x has a type that moves
116 #[derive(Copy, Clone, PartialEq, Debug)]
117 pub enum MoveReason {
123 #[derive(Copy, Clone, PartialEq, Debug)]
131 #[derive(Copy, Clone, PartialEq, Debug)]
132 enum TrackMatchMode {
138 impl TrackMatchMode {
139 // Builds up the whole match mode for a pattern from its constituent
140 // parts. The lattice looks like this:
156 // * `(_, some_int)` pattern is Copying, since
157 // NonBinding + Copying => Copying
159 // * `(some_int, some_box)` pattern is Moving, since
160 // Copying + Moving => Moving
162 // * `(ref x, some_box)` pattern is Conflicting, since
163 // Borrowing + Moving => Conflicting
165 // Note that the `Unknown` and `Conflicting` states are
166 // represented separately from the other more interesting
167 // `Definite` states, which simplifies logic here somewhat.
168 fn lub(&mut self, mode: MatchMode) {
169 *self = match (*self, mode) {
170 // Note that clause order below is very significant.
171 (Unknown, new) => Definite(new),
172 (Definite(old), new) if old == new => Definite(old),
174 (Definite(old), NonBindingMatch) => Definite(old),
175 (Definite(NonBindingMatch), new) => Definite(new),
177 (Definite(old), CopyingMatch) => Definite(old),
178 (Definite(CopyingMatch), new) => Definite(new),
180 (Definite(_), _) => Conflicting,
181 (Conflicting, _) => *self,
185 fn match_mode(&self) -> MatchMode {
187 Unknown => NonBindingMatch,
188 Definite(mode) => mode,
190 // Conservatively return MovingMatch to let the
191 // compiler continue to make progress.
198 #[derive(Copy, Clone, PartialEq, Debug)]
199 pub enum MutateMode {
202 WriteAndRead, // x += y
205 #[derive(Copy, Clone)]
206 enum OverloadedCallType {
209 FnOnceOverloadedCall,
212 impl OverloadedCallType {
213 fn from_trait_id(tcx: &ty::ctxt, trait_id: DefId)
214 -> OverloadedCallType {
215 for &(maybe_function_trait, overloaded_call_type) in &[
216 (tcx.lang_items.fn_once_trait(), FnOnceOverloadedCall),
217 (tcx.lang_items.fn_mut_trait(), FnMutOverloadedCall),
218 (tcx.lang_items.fn_trait(), FnOverloadedCall)
220 match maybe_function_trait {
221 Some(function_trait) if function_trait == trait_id => {
222 return overloaded_call_type
228 tcx.sess.bug("overloaded call didn't map to known function trait")
231 fn from_method_id(tcx: &ty::ctxt, method_id: DefId)
232 -> OverloadedCallType {
233 let method = tcx.impl_or_trait_item(method_id);
234 OverloadedCallType::from_trait_id(tcx, method.container().id())
238 ///////////////////////////////////////////////////////////////////////////
239 // The ExprUseVisitor type
241 // This is the code that actually walks the tree. Like
242 // mem_categorization, it requires a TYPER, which is a type that
243 // supplies types from the tree. After type checking is complete, you
244 // can just use the tcx as the typer.
245 pub struct ExprUseVisitor<'d, 't, 'a: 't, 'tcx:'a+'d> {
246 typer: &'t infer::InferCtxt<'a, 'tcx>,
247 mc: mc::MemCategorizationContext<'t, 'a, 'tcx>,
248 delegate: &'d mut Delegate<'tcx>,
251 // If the TYPER results in an error, it's because the type check
252 // failed (or will fail, when the error is uncovered and reported
253 // during writeback). In this case, we just ignore this part of the
256 // Note that this macro appears similar to try!(), but, unlike try!(),
257 // it does not propagate the error.
258 macro_rules! return_if_err {
263 debug!("mc reported err");
270 /// Whether the elements of an overloaded operation are passed by value or by reference
276 impl<'d,'t,'a,'tcx> ExprUseVisitor<'d,'t,'a,'tcx> {
277 pub fn new(delegate: &'d mut (Delegate<'tcx>),
278 typer: &'t infer::InferCtxt<'a, 'tcx>)
279 -> ExprUseVisitor<'d,'t,'a,'tcx> where 'tcx:'a+'d
281 let mc: mc::MemCategorizationContext<'t, 'a, 'tcx> =
282 mc::MemCategorizationContext::new(typer);
283 ExprUseVisitor { typer: typer, mc: mc, delegate: delegate }
286 pub fn walk_fn(&mut self,
289 self.walk_arg_patterns(decl, body);
290 self.walk_block(body);
293 fn walk_arg_patterns(&mut self,
296 for arg in &decl.inputs {
297 let arg_ty = return_if_err!(self.typer.node_ty(arg.pat.id));
299 let fn_body_scope = self.tcx().region_maps.node_extent(body.id);
300 let arg_cmt = self.mc.cat_rvalue(
303 ty::ReScope(fn_body_scope), // Args live only as long as the fn body.
306 self.walk_irrefutable_pat(arg_cmt, &*arg.pat);
310 fn tcx(&self) -> &'t ty::ctxt<'tcx> {
314 fn delegate_consume(&mut self,
315 consume_id: ast::NodeId,
317 cmt: mc::cmt<'tcx>) {
318 debug!("delegate_consume(consume_id={}, cmt={:?})",
321 let mode = copy_or_move(self.typer, &cmt, DirectRefMove);
322 self.delegate.consume(consume_id, consume_span, cmt, mode);
325 fn consume_exprs(&mut self, exprs: &[P<hir::Expr>]) {
327 self.consume_expr(&**expr);
331 pub fn consume_expr(&mut self, expr: &hir::Expr) {
332 debug!("consume_expr(expr={:?})", expr);
334 let cmt = return_if_err!(self.mc.cat_expr(expr));
335 self.delegate_consume(expr.id, expr.span, cmt);
336 self.walk_expr(expr);
339 fn mutate_expr(&mut self,
340 assignment_expr: &hir::Expr,
343 let cmt = return_if_err!(self.mc.cat_expr(expr));
344 self.delegate.mutate(assignment_expr.id, assignment_expr.span, cmt, mode);
345 self.walk_expr(expr);
348 fn borrow_expr(&mut self,
353 debug!("borrow_expr(expr={:?}, r={:?}, bk={:?})",
356 let cmt = return_if_err!(self.mc.cat_expr(expr));
357 self.delegate.borrow(expr.id, expr.span, cmt, r, bk, cause);
362 fn select_from_expr(&mut self, expr: &hir::Expr) {
366 pub fn walk_expr(&mut self, expr: &hir::Expr) {
367 debug!("walk_expr(expr={:?})", expr);
369 self.walk_adjustment(expr);
372 hir::ExprPath(..) => { }
374 hir::ExprType(ref subexpr, _) => {
375 self.walk_expr(&**subexpr)
378 hir::ExprUnary(hir::UnDeref, ref base) => { // *base
379 if !self.walk_overloaded_operator(expr, &**base, Vec::new(), PassArgs::ByRef) {
380 self.select_from_expr(&**base);
384 hir::ExprField(ref base, _) => { // base.f
385 self.select_from_expr(&**base);
388 hir::ExprTupField(ref base, _) => { // base.<n>
389 self.select_from_expr(&**base);
392 hir::ExprIndex(ref lhs, ref rhs) => { // lhs[rhs]
393 if !self.walk_overloaded_operator(expr,
397 self.select_from_expr(&**lhs);
398 self.consume_expr(&**rhs);
402 hir::ExprRange(ref start, ref end) => {
403 start.as_ref().map(|e| self.consume_expr(&**e));
404 end.as_ref().map(|e| self.consume_expr(&**e));
407 hir::ExprCall(ref callee, ref args) => { // callee(args)
408 self.walk_callee(expr, &**callee);
409 self.consume_exprs(args);
412 hir::ExprMethodCall(_, _, ref args) => { // callee.m(args)
413 self.consume_exprs(args);
416 hir::ExprStruct(_, ref fields, ref opt_with) => {
417 self.walk_struct_expr(expr, fields, opt_with);
420 hir::ExprTup(ref exprs) => {
421 self.consume_exprs(exprs);
424 hir::ExprIf(ref cond_expr, ref then_blk, ref opt_else_expr) => {
425 self.consume_expr(&**cond_expr);
426 self.walk_block(&**then_blk);
427 if let Some(ref else_expr) = *opt_else_expr {
428 self.consume_expr(&**else_expr);
432 hir::ExprMatch(ref discr, ref arms, _) => {
433 let discr_cmt = return_if_err!(self.mc.cat_expr(&**discr));
434 self.borrow_expr(&**discr, ty::ReEmpty, ty::ImmBorrow, MatchDiscriminant);
436 // treatment of the discriminant is handled while walking the arms.
438 let mode = self.arm_move_mode(discr_cmt.clone(), arm);
439 let mode = mode.match_mode();
440 self.walk_arm(discr_cmt.clone(), arm, mode);
444 hir::ExprVec(ref exprs) => {
445 self.consume_exprs(exprs);
448 hir::ExprAddrOf(m, ref base) => { // &base
449 // make sure that the thing we are pointing out stays valid
450 // for the lifetime `scope_r` of the resulting ptr:
451 let expr_ty = return_if_err!(self.typer.node_ty(expr.id));
452 if let ty::TyRef(&r, _) = expr_ty.sty {
453 let bk = ty::BorrowKind::from_mutbl(m);
454 self.borrow_expr(&**base, r, bk, AddrOf);
458 hir::ExprInlineAsm(ref ia) => {
459 for &(_, ref input) in &ia.inputs {
460 self.consume_expr(&**input);
463 for output in &ia.outputs {
464 if output.is_indirect {
465 self.consume_expr(&*output.expr);
467 self.mutate_expr(expr, &*output.expr,
468 if output.is_rw { WriteAndRead } else { JustWrite });
475 hir::ExprLit(..) => {}
477 hir::ExprLoop(ref blk, _) => {
478 self.walk_block(&**blk);
481 hir::ExprWhile(ref cond_expr, ref blk, _) => {
482 self.consume_expr(&**cond_expr);
483 self.walk_block(&**blk);
486 hir::ExprUnary(op, ref lhs) => {
487 let pass_args = if ::rustc_front::util::is_by_value_unop(op) {
493 if !self.walk_overloaded_operator(expr, &**lhs, Vec::new(), pass_args) {
494 self.consume_expr(&**lhs);
498 hir::ExprBinary(op, ref lhs, ref rhs) => {
499 let pass_args = if ::rustc_front::util::is_by_value_binop(op.node) {
505 if !self.walk_overloaded_operator(expr, &**lhs, vec![&**rhs], pass_args) {
506 self.consume_expr(&**lhs);
507 self.consume_expr(&**rhs);
511 hir::ExprBlock(ref blk) => {
512 self.walk_block(&**blk);
515 hir::ExprRet(ref opt_expr) => {
516 if let Some(ref expr) = *opt_expr {
517 self.consume_expr(&**expr);
521 hir::ExprAssign(ref lhs, ref rhs) => {
522 self.mutate_expr(expr, &**lhs, JustWrite);
523 self.consume_expr(&**rhs);
526 hir::ExprCast(ref base, _) => {
527 self.consume_expr(&**base);
530 hir::ExprAssignOp(op, ref lhs, ref rhs) => {
531 // NB All our assignment operations take the RHS by value
532 assert!(::rustc_front::util::is_by_value_binop(op.node));
534 if !self.walk_overloaded_operator(expr, lhs, vec![rhs], PassArgs::ByValue) {
535 self.mutate_expr(expr, &**lhs, WriteAndRead);
536 self.consume_expr(&**rhs);
540 hir::ExprRepeat(ref base, ref count) => {
541 self.consume_expr(&**base);
542 self.consume_expr(&**count);
545 hir::ExprClosure(..) => {
546 self.walk_captures(expr)
549 hir::ExprBox(ref base) => {
550 self.consume_expr(&**base);
555 fn walk_callee(&mut self, call: &hir::Expr, callee: &hir::Expr) {
556 let callee_ty = return_if_err!(self.typer.expr_ty_adjusted(callee));
557 debug!("walk_callee: callee={:?} callee_ty={:?}",
559 let call_scope = self.tcx().region_maps.node_extent(call.id);
560 match callee_ty.sty {
561 ty::TyBareFn(..) => {
562 self.consume_expr(callee);
566 let overloaded_call_type =
567 match self.typer.node_method_id(ty::MethodCall::expr(call.id)) {
569 OverloadedCallType::from_method_id(self.tcx(), method_id)
572 self.tcx().sess.span_bug(
574 &format!("unexpected callee type {}", callee_ty))
577 match overloaded_call_type {
578 FnMutOverloadedCall => {
579 self.borrow_expr(callee,
580 ty::ReScope(call_scope),
584 FnOverloadedCall => {
585 self.borrow_expr(callee,
586 ty::ReScope(call_scope),
590 FnOnceOverloadedCall => self.consume_expr(callee),
596 fn walk_stmt(&mut self, stmt: &hir::Stmt) {
598 hir::StmtDecl(ref decl, _) => {
600 hir::DeclLocal(ref local) => {
601 self.walk_local(&**local);
604 hir::DeclItem(_) => {
605 // we don't visit nested items in this visitor,
606 // only the fn body we were given.
611 hir::StmtExpr(ref expr, _) |
612 hir::StmtSemi(ref expr, _) => {
613 self.consume_expr(&**expr);
618 fn walk_local(&mut self, local: &hir::Local) {
621 let delegate = &mut self.delegate;
622 pat_util::pat_bindings(&self.typer.tcx.def_map, &*local.pat,
624 delegate.decl_without_init(id, span);
629 // Variable declarations with
630 // initializers are considered
631 // "assigns", which is handled by
633 self.walk_expr(&**expr);
634 let init_cmt = return_if_err!(self.mc.cat_expr(&**expr));
635 self.walk_irrefutable_pat(init_cmt, &*local.pat);
640 /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
641 /// depending on its type.
642 fn walk_block(&mut self, blk: &hir::Block) {
643 debug!("walk_block(blk.id={})", blk.id);
645 for stmt in &blk.stmts {
646 self.walk_stmt(stmt);
649 if let Some(ref tail_expr) = blk.expr {
650 self.consume_expr(&**tail_expr);
654 fn walk_struct_expr(&mut self,
656 fields: &[hir::Field],
657 opt_with: &Option<P<hir::Expr>>) {
658 // Consume the expressions supplying values for each field.
659 for field in fields {
660 self.consume_expr(&*field.expr);
663 let with_expr = match *opt_with {
668 let with_cmt = return_if_err!(self.mc.cat_expr(&*with_expr));
670 // Select just those fields of the `with`
671 // expression that will actually be used
672 if let ty::TyStruct(def, substs) = with_cmt.ty.sty {
673 // Consume those fields of the with expression that are needed.
674 for with_field in &def.struct_variant().fields {
675 if !contains_field_named(with_field, fields) {
676 let cmt_field = self.mc.cat_field(
680 with_field.ty(self.tcx(), substs)
682 self.delegate_consume(with_expr.id, with_expr.span, cmt_field);
686 // the base expression should always evaluate to a
687 // struct; however, when EUV is run during typeck, it
688 // may not. This will generate an error earlier in typeck,
689 // so we can just ignore it.
690 if !self.tcx().sess.has_errors() {
691 self.tcx().sess.span_bug(
693 "with expression doesn't evaluate to a struct");
697 // walk the with expression so that complex expressions
698 // are properly handled.
699 self.walk_expr(with_expr);
701 fn contains_field_named(field: ty::FieldDef,
702 fields: &[hir::Field])
706 |f| f.name.node == field.name)
710 // Invoke the appropriate delegate calls for anything that gets
711 // consumed or borrowed as part of the automatic adjustment
713 fn walk_adjustment(&mut self, expr: &hir::Expr) {
714 let typer = self.typer;
715 //NOTE(@jroesch): mixed RefCell borrow causes crash
716 let adj = typer.adjustments().get(&expr.id).map(|x| x.clone());
717 if let Some(adjustment) = adj {
719 adjustment::AdjustReifyFnPointer |
720 adjustment::AdjustUnsafeFnPointer => {
721 // Creating a closure/fn-pointer or unsizing consumes
722 // the input and stores it into the resulting rvalue.
723 debug!("walk_adjustment(AdjustReifyFnPointer|AdjustUnsafeFnPointer)");
725 return_if_err!(self.mc.cat_expr_unadjusted(expr));
726 self.delegate_consume(expr.id, expr.span, cmt_unadjusted);
728 adjustment::AdjustDerefRef(ref adj) => {
729 self.walk_autoderefref(expr, adj);
735 /// Autoderefs for overloaded Deref calls in fact reference their receiver. That is, if we have
736 /// `(*x)` where `x` is of type `Rc<T>`, then this in fact is equivalent to `x.deref()`. Since
737 /// `deref()` is declared with `&self`, this is an autoref of `x`.
738 fn walk_autoderefs(&mut self,
741 debug!("walk_autoderefs expr={:?} autoderefs={}", expr, autoderefs);
743 for i in 0..autoderefs {
744 let deref_id = ty::MethodCall::autoderef(expr.id, i as u32);
745 match self.typer.node_method_ty(deref_id) {
748 let cmt = return_if_err!(self.mc.cat_expr_autoderefd(expr, i));
750 // the method call infrastructure should have
751 // replaced all late-bound regions with variables:
752 let self_ty = method_ty.fn_sig().input(0);
753 let self_ty = self.tcx().no_late_bound_regions(&self_ty).unwrap();
755 let (m, r) = match self_ty.sty {
756 ty::TyRef(r, ref m) => (m.mutbl, r),
757 _ => self.tcx().sess.span_bug(expr.span,
758 &format!("bad overloaded deref type {:?}",
761 let bk = ty::BorrowKind::from_mutbl(m);
762 self.delegate.borrow(expr.id, expr.span, cmt,
769 fn walk_autoderefref(&mut self,
771 adj: &adjustment::AutoDerefRef<'tcx>) {
772 debug!("walk_autoderefref expr={:?} adj={:?}",
776 self.walk_autoderefs(expr, adj.autoderefs);
779 return_if_err!(self.mc.cat_expr_autoderefd(expr, adj.autoderefs));
782 self.walk_autoref(expr, cmt_derefd, adj.autoref);
784 if adj.unsize.is_some() {
785 // Unsizing consumes the thin pointer and produces a fat one.
786 self.delegate_consume(expr.id, expr.span, cmt_refd);
791 /// Walks the autoref `opt_autoref` applied to the autoderef'd
792 /// `expr`. `cmt_derefd` is the mem-categorized form of `expr`
793 /// after all relevant autoderefs have occurred. Because AutoRefs
794 /// can be recursive, this function is recursive: it first walks
795 /// deeply all the way down the autoref chain, and then processes
796 /// the autorefs on the way out. At each point, it returns the
797 /// `cmt` for the rvalue that will be produced by introduced an
799 fn walk_autoref(&mut self,
801 cmt_base: mc::cmt<'tcx>,
802 opt_autoref: Option<adjustment::AutoRef<'tcx>>)
805 debug!("walk_autoref(expr.id={} cmt_derefd={:?} opt_autoref={:?})",
810 let cmt_base_ty = cmt_base.ty;
812 let autoref = match opt_autoref {
813 Some(ref autoref) => autoref,
821 adjustment::AutoPtr(r, m) => {
822 self.delegate.borrow(expr.id,
826 ty::BorrowKind::from_mutbl(m),
830 adjustment::AutoUnsafe(m) => {
831 debug!("walk_autoref: expr.id={} cmt_base={:?}",
835 // Converting from a &T to *T (or &mut T to *mut T) is
836 // treated as borrowing it for the enclosing temporary
838 let r = ty::ReScope(self.tcx().region_maps.node_extent(expr.id));
840 self.delegate.borrow(expr.id,
844 ty::BorrowKind::from_mutbl(m),
849 // Construct the categorization for the result of the autoref.
850 // This is always an rvalue, since we are producing a new
851 // (temporary) indirection.
853 let adj_ty = cmt_base_ty.adjust_for_autoref(self.tcx(), opt_autoref);
855 self.mc.cat_rvalue_node(expr.id, expr.span, adj_ty)
859 // When this returns true, it means that the expression *is* a
860 // method-call (i.e. via the operator-overload). This true result
861 // also implies that walk_overloaded_operator already took care of
862 // recursively processing the input arguments, and thus the caller
864 fn walk_overloaded_operator(&mut self,
866 receiver: &hir::Expr,
867 rhs: Vec<&hir::Expr>,
871 if !self.typer.is_method_call(expr.id) {
876 PassArgs::ByValue => {
877 self.consume_expr(receiver);
879 self.consume_expr(arg);
884 PassArgs::ByRef => {},
887 self.walk_expr(receiver);
889 // Arguments (but not receivers) to overloaded operator
890 // methods are implicitly autoref'd which sadly does not use
891 // adjustments, so we must hardcode the borrow here.
893 let r = ty::ReScope(self.tcx().region_maps.node_extent(expr.id));
894 let bk = ty::ImmBorrow;
897 self.borrow_expr(arg, r, bk, OverloadedOperator);
902 fn arm_move_mode(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm) -> TrackMatchMode {
903 let mut mode = Unknown;
904 for pat in &arm.pats {
905 self.determine_pat_move_mode(discr_cmt.clone(), &**pat, &mut mode);
910 fn walk_arm(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm, mode: MatchMode) {
911 for pat in &arm.pats {
912 self.walk_pat(discr_cmt.clone(), &**pat, mode);
915 if let Some(ref guard) = arm.guard {
916 self.consume_expr(&**guard);
919 self.consume_expr(&*arm.body);
922 /// Walks a pat that occurs in isolation (i.e. top-level of fn
923 /// arg or let binding. *Not* a match arm or nested pat.)
924 fn walk_irrefutable_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat) {
925 let mut mode = Unknown;
926 self.determine_pat_move_mode(cmt_discr.clone(), pat, &mut mode);
927 let mode = mode.match_mode();
928 self.walk_pat(cmt_discr, pat, mode);
931 /// Identifies any bindings within `pat` and accumulates within
932 /// `mode` whether the overall pattern/match structure is a move,
934 fn determine_pat_move_mode(&mut self,
935 cmt_discr: mc::cmt<'tcx>,
937 mode: &mut TrackMatchMode) {
938 debug!("determine_pat_move_mode cmt_discr={:?} pat={:?}", cmt_discr,
940 return_if_err!(self.mc.cat_pattern(cmt_discr, pat, |_mc, cmt_pat, pat| {
941 let tcx = self.tcx();
942 let def_map = &self.tcx().def_map;
943 if pat_util::pat_is_binding(&def_map.borrow(), pat) {
945 hir::PatIdent(hir::BindByRef(_), _, _) =>
946 mode.lub(BorrowingMatch),
947 hir::PatIdent(hir::BindByValue(_), _, _) => {
948 match copy_or_move(self.typer, &cmt_pat, PatBindingMove) {
949 Copy => mode.lub(CopyingMatch),
950 Move(_) => mode.lub(MovingMatch),
956 "binding pattern not an identifier");
963 /// The core driver for walking a pattern; `match_mode` must be
964 /// established up front, e.g. via `determine_pat_move_mode` (see
965 /// also `walk_irrefutable_pat` for patterns that stand alone).
966 fn walk_pat(&mut self,
967 cmt_discr: mc::cmt<'tcx>,
969 match_mode: MatchMode) {
970 debug!("walk_pat cmt_discr={:?} pat={:?}", cmt_discr,
974 let typer = self.typer;
975 let def_map = &self.tcx().def_map;
976 let delegate = &mut self.delegate;
977 return_if_err!(mc.cat_pattern(cmt_discr.clone(), pat, |mc, cmt_pat, pat| {
978 if pat_util::pat_is_binding(&def_map.borrow(), pat) {
981 debug!("binding cmt_pat={:?} pat={:?} match_mode={:?}",
986 // pat_ty: the type of the binding being produced.
987 let pat_ty = return_if_err!(typer.node_ty(pat.id));
989 // Each match binding is effectively an assignment to the
990 // binding being produced.
991 let def = def_map.borrow().get(&pat.id).unwrap().full_def();
992 match mc.cat_def(pat.id, pat.span, pat_ty, def) {
994 delegate.mutate(pat.id, pat.span, binding_cmt, Init);
999 // It is also a borrow or copy/move of the value being matched.
1001 hir::PatIdent(hir::BindByRef(m), _, _) => {
1002 if let ty::TyRef(&r, _) = pat_ty.sty {
1003 let bk = ty::BorrowKind::from_mutbl(m);
1004 delegate.borrow(pat.id, pat.span, cmt_pat,
1008 hir::PatIdent(hir::BindByValue(_), _, _) => {
1009 let mode = copy_or_move(typer, &cmt_pat, PatBindingMove);
1010 debug!("walk_pat binding consuming pat");
1011 delegate.consume_pat(pat, cmt_pat, mode);
1016 "binding pattern not an identifier");
1021 hir::PatVec(_, Some(ref slice_pat), _) => {
1022 // The `slice_pat` here creates a slice into
1023 // the original vector. This is effectively a
1024 // borrow of the elements of the vector being
1027 let (slice_cmt, slice_mutbl, slice_r) =
1028 return_if_err!(mc.cat_slice_pattern(cmt_pat, &**slice_pat));
1030 // Note: We declare here that the borrow
1031 // occurs upon entering the `[...]`
1032 // pattern. This implies that something like
1033 // `[a; b]` where `a` is a move is illegal,
1034 // because the borrow is already in effect.
1035 // In fact such a move would be safe-ish, but
1036 // it effectively *requires* that we use the
1037 // nulling out semantics to indicate when a
1038 // value has been moved, which we are trying
1039 // to move away from. Otherwise, how can we
1040 // indicate that the first element in the
1041 // vector has been moved? Eventually, we
1042 // could perhaps modify this rule to permit
1043 // `[..a, b]` where `b` is a move, because in
1044 // that case we can adjust the length of the
1045 // original vec accordingly, but we'd have to
1046 // make trans do the right thing, and it would
1047 // only work for `Box<[T]>`s. It seems simpler
1048 // to just require that people call
1049 // `vec.pop()` or `vec.unshift()`.
1050 let slice_bk = ty::BorrowKind::from_mutbl(slice_mutbl);
1051 delegate.borrow(pat.id, pat.span,
1053 slice_bk, RefBinding);
1060 // Do a second pass over the pattern, calling `matched_pat` on
1061 // the interior nodes (enum variants and structs), as opposed
1062 // to the above loop's visit of than the bindings that form
1063 // the leaves of the pattern tree structure.
1064 return_if_err!(mc.cat_pattern(cmt_discr, pat, |mc, cmt_pat, pat| {
1065 let def_map = def_map.borrow();
1066 let tcx = typer.tcx;
1069 hir::PatEnum(_, _) | hir::PatQPath(..) |
1070 hir::PatIdent(_, _, None) | hir::PatStruct(..) => {
1071 match def_map.get(&pat.id).map(|d| d.full_def()) {
1073 // no definition found: pat is not a
1074 // struct or enum pattern.
1077 Some(def::DefVariant(enum_did, variant_did, _is_struct)) => {
1079 if tcx.lookup_adt_def(enum_did).is_univariant() {
1082 let cmt_pat_ty = cmt_pat.ty;
1083 mc.cat_downcast(pat, cmt_pat, cmt_pat_ty, variant_did)
1086 debug!("variant downcast_cmt={:?} pat={:?}",
1090 delegate.matched_pat(pat, downcast_cmt, match_mode);
1093 Some(def::DefStruct(..)) | Some(def::DefTy(_, false)) => {
1094 // A struct (in either the value or type
1095 // namespace; we encounter the former on
1096 // e.g. patterns for unit structs).
1098 debug!("struct cmt_pat={:?} pat={:?}",
1102 delegate.matched_pat(pat, cmt_pat, match_mode);
1105 Some(def::DefConst(..)) |
1106 Some(def::DefAssociatedConst(..)) |
1107 Some(def::DefLocal(..)) => {
1108 // This is a leaf (i.e. identifier binding
1109 // or constant value to match); thus no
1110 // `matched_pat` call.
1113 Some(def @ def::DefTy(_, true)) => {
1114 // An enum's type -- should never be in a
1117 if !tcx.sess.has_errors() {
1118 let msg = format!("Pattern has unexpected type: {:?} and type {:?}",
1121 tcx.sess.span_bug(pat.span, &msg)
1126 // Remaining cases are e.g. DefFn, to
1127 // which identifiers within patterns
1128 // should not resolve. However, we do
1129 // encouter this when using the
1130 // expr-use-visitor during typeck. So just
1131 // ignore it, an error should have been
1134 if !tcx.sess.has_errors() {
1135 let msg = format!("Pattern has unexpected def: {:?} and type {:?}",
1138 tcx.sess.span_bug(pat.span, &msg[..])
1144 hir::PatIdent(_, _, Some(_)) => {
1145 // Do nothing; this is a binding (not an enum
1146 // variant or struct), and the cat_pattern call
1147 // will visit the substructure recursively.
1150 hir::PatWild | hir::PatTup(..) | hir::PatBox(..) |
1151 hir::PatRegion(..) | hir::PatLit(..) | hir::PatRange(..) |
1152 hir::PatVec(..) => {
1153 // Similarly, each of these cases does not
1154 // correspond to an enum variant or struct, so we
1155 // do not do any `matched_pat` calls for these
1162 fn walk_captures(&mut self, closure_expr: &hir::Expr) {
1163 debug!("walk_captures({:?})", closure_expr);
1165 self.tcx().with_freevars(closure_expr.id, |freevars| {
1166 for freevar in freevars {
1167 let id_var = freevar.def.var_id();
1168 let upvar_id = ty::UpvarId { var_id: id_var,
1169 closure_expr_id: closure_expr.id };
1170 let upvar_capture = self.typer.upvar_capture(upvar_id).unwrap();
1171 let cmt_var = return_if_err!(self.cat_captured_var(closure_expr.id,
1174 match upvar_capture {
1175 ty::UpvarCapture::ByValue => {
1176 let mode = copy_or_move(self.typer, &cmt_var, CaptureMove);
1177 self.delegate.consume(closure_expr.id, freevar.span, cmt_var, mode);
1179 ty::UpvarCapture::ByRef(upvar_borrow) => {
1180 self.delegate.borrow(closure_expr.id,
1183 upvar_borrow.region,
1185 ClosureCapture(freevar.span));
1192 fn cat_captured_var(&mut self,
1193 closure_id: ast::NodeId,
1195 upvar_def: def::Def)
1196 -> mc::McResult<mc::cmt<'tcx>> {
1197 // Create the cmt for the variable being borrowed, from the
1198 // caller's perspective
1199 let var_id = upvar_def.var_id();
1200 let var_ty = try!(self.typer.node_ty(var_id));
1201 self.mc.cat_def(closure_id, closure_span, var_ty, upvar_def)
1205 fn copy_or_move<'a, 'tcx>(typer: &infer::InferCtxt<'a, 'tcx>,
1206 cmt: &mc::cmt<'tcx>,
1207 move_reason: MoveReason)
1210 if typer.type_moves_by_default(cmt.ty, cmt.span) {