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::LoanCause::*;
16 pub use self::ConsumeMode::*;
17 pub use self::MoveReason::*;
18 pub use self::MatchMode::*;
19 use self::TrackMatchMode::*;
20 use self::OverloadedCallType::*;
23 use hir::def_id::{DefId};
25 use middle::mem_categorization as mc;
26 use middle::region::RegionMaps;
27 use ty::{self, TyCtxt, adjustment};
29 use hir::{self, PatKind};
35 ///////////////////////////////////////////////////////////////////////////
38 /// This trait defines the callbacks you can expect to receive when
39 /// employing the ExprUseVisitor.
40 pub trait Delegate<'tcx> {
41 // The value found at `cmt` is either copied or moved, depending
44 consume_id: ast::NodeId,
49 // The value found at `cmt` has been determined to match the
50 // pattern binding `matched_pat`, and its subparts are being
51 // copied or moved depending on `mode`. Note that `matched_pat`
52 // is called on all variant/structs in the pattern (i.e., the
53 // interior nodes of the pattern's tree structure) while
54 // consume_pat is called on the binding identifiers in the pattern
55 // (which are leaves of the pattern's tree structure).
57 // Note that variants/structs and identifiers are disjoint; thus
58 // `matched_pat` and `consume_pat` are never both called on the
59 // same input pattern structure (though of `consume_pat` can be
60 // called on a subpart of an input passed to `matched_pat).
61 fn matched_pat(&mut self,
62 matched_pat: &hir::Pat,
66 // The value found at `cmt` is either copied or moved via the
67 // pattern binding `consume_pat`, depending on mode.
68 fn consume_pat(&mut self,
69 consume_pat: &hir::Pat,
73 // The value found at `borrow` is being borrowed at the point
74 // `borrow_id` for the region `loan_region` with kind `bk`.
76 borrow_id: ast::NodeId,
79 loan_region: ty::Region<'tcx>,
81 loan_cause: LoanCause);
83 // The local variable `id` is declared but not initialized.
84 fn decl_without_init(&mut self,
88 // The path at `cmt` is being assigned to.
90 assignment_id: ast::NodeId,
91 assignment_span: Span,
92 assignee_cmt: mc::cmt<'tcx>,
96 #[derive(Copy, Clone, PartialEq, Debug)]
109 #[derive(Copy, Clone, PartialEq, Debug)]
110 pub enum ConsumeMode {
111 Copy, // reference to x where x has a type that copies
112 Move(MoveReason), // reference to x where x has a type that moves
115 #[derive(Copy, Clone, PartialEq, Debug)]
116 pub enum MoveReason {
122 #[derive(Copy, Clone, PartialEq, Debug)]
130 #[derive(Copy, Clone, PartialEq, Debug)]
131 enum TrackMatchMode {
137 impl TrackMatchMode {
138 // Builds up the whole match mode for a pattern from its constituent
139 // parts. The lattice looks like this:
155 // * `(_, some_int)` pattern is Copying, since
156 // NonBinding + Copying => Copying
158 // * `(some_int, some_box)` pattern is Moving, since
159 // Copying + Moving => Moving
161 // * `(ref x, some_box)` pattern is Conflicting, since
162 // Borrowing + Moving => Conflicting
164 // Note that the `Unknown` and `Conflicting` states are
165 // represented separately from the other more interesting
166 // `Definite` states, which simplifies logic here somewhat.
167 fn lub(&mut self, mode: MatchMode) {
168 *self = match (*self, mode) {
169 // Note that clause order below is very significant.
170 (Unknown, new) => Definite(new),
171 (Definite(old), new) if old == new => Definite(old),
173 (Definite(old), NonBindingMatch) => Definite(old),
174 (Definite(NonBindingMatch), new) => Definite(new),
176 (Definite(old), CopyingMatch) => Definite(old),
177 (Definite(CopyingMatch), new) => Definite(new),
179 (Definite(_), _) => Conflicting,
180 (Conflicting, _) => *self,
184 fn match_mode(&self) -> MatchMode {
186 Unknown => NonBindingMatch,
187 Definite(mode) => mode,
189 // Conservatively return MovingMatch to let the
190 // compiler continue to make progress.
197 #[derive(Copy, Clone, PartialEq, Debug)]
198 pub enum MutateMode {
201 WriteAndRead, // x += y
204 #[derive(Copy, Clone)]
205 enum OverloadedCallType {
208 FnOnceOverloadedCall,
211 impl OverloadedCallType {
212 fn from_trait_id(tcx: TyCtxt, trait_id: DefId) -> OverloadedCallType {
213 for &(maybe_function_trait, overloaded_call_type) in &[
214 (tcx.lang_items.fn_once_trait(), FnOnceOverloadedCall),
215 (tcx.lang_items.fn_mut_trait(), FnMutOverloadedCall),
216 (tcx.lang_items.fn_trait(), FnOverloadedCall)
218 match maybe_function_trait {
219 Some(function_trait) if function_trait == trait_id => {
220 return overloaded_call_type
226 bug!("overloaded call didn't map to known function trait")
229 fn from_method_id(tcx: TyCtxt, method_id: DefId) -> OverloadedCallType {
230 let method = tcx.associated_item(method_id);
231 OverloadedCallType::from_trait_id(tcx, method.container.id())
235 ///////////////////////////////////////////////////////////////////////////
236 // The ExprUseVisitor type
238 // This is the code that actually walks the tree. Like
239 // mem_categorization, it requires a TYPER, which is a type that
240 // supplies types from the tree. After type checking is complete, you
241 // can just use the tcx as the typer.
242 pub struct ExprUseVisitor<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
243 mc: mc::MemCategorizationContext<'a, 'gcx, 'tcx>,
244 delegate: &'a mut Delegate<'tcx>,
247 // If the TYPER results in an error, it's because the type check
248 // failed (or will fail, when the error is uncovered and reported
249 // during writeback). In this case, we just ignore this part of the
252 // Note that this macro appears similar to try!(), but, unlike try!(),
253 // it does not propagate the error.
254 macro_rules! return_if_err {
259 debug!("mc reported err");
266 /// Whether the elements of an overloaded operation are passed by value or by reference
272 impl<'a, 'gcx, 'tcx> ExprUseVisitor<'a, 'gcx, 'tcx> {
273 pub fn new(delegate: &'a mut (Delegate<'tcx>+'a),
274 region_maps: &'a RegionMaps,
275 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>)
278 ExprUseVisitor::with_options(delegate,
281 mc::MemCategorizationOptions::default())
284 pub fn with_options(delegate: &'a mut (Delegate<'tcx>+'a),
285 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
286 region_maps: &'a RegionMaps,
287 options: mc::MemCategorizationOptions)
291 mc: mc::MemCategorizationContext::with_options(infcx, region_maps, options),
296 pub fn consume_body(&mut self, body: &hir::Body) {
297 debug!("consume_body(body={:?})", body);
299 for arg in &body.arguments {
300 let arg_ty = return_if_err!(self.mc.infcx.node_ty(arg.pat.id));
302 let fn_body_scope_r = self.tcx().node_scope_region(body.value.id);
303 let arg_cmt = self.mc.cat_rvalue(
306 fn_body_scope_r, // Args live only as long as the fn body.
310 self.walk_irrefutable_pat(arg_cmt, &arg.pat);
313 self.consume_expr(&body.value);
316 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
320 fn delegate_consume(&mut self,
321 consume_id: ast::NodeId,
323 cmt: mc::cmt<'tcx>) {
324 debug!("delegate_consume(consume_id={}, cmt={:?})",
327 let mode = copy_or_move(self.mc.infcx, &cmt, DirectRefMove);
328 self.delegate.consume(consume_id, consume_span, cmt, mode);
331 fn consume_exprs(&mut self, exprs: &[hir::Expr]) {
333 self.consume_expr(&expr);
337 pub fn consume_expr(&mut self, expr: &hir::Expr) {
338 debug!("consume_expr(expr={:?})", expr);
340 let cmt = return_if_err!(self.mc.cat_expr(expr));
341 self.delegate_consume(expr.id, expr.span, cmt);
342 self.walk_expr(expr);
345 fn mutate_expr(&mut self,
346 assignment_expr: &hir::Expr,
349 let cmt = return_if_err!(self.mc.cat_expr(expr));
350 self.delegate.mutate(assignment_expr.id, assignment_expr.span, cmt, mode);
351 self.walk_expr(expr);
354 fn borrow_expr(&mut self,
359 debug!("borrow_expr(expr={:?}, r={:?}, bk={:?})",
362 let cmt = return_if_err!(self.mc.cat_expr(expr));
363 self.delegate.borrow(expr.id, expr.span, cmt, r, bk, cause);
368 fn select_from_expr(&mut self, expr: &hir::Expr) {
372 pub fn walk_expr(&mut self, expr: &hir::Expr) {
373 debug!("walk_expr(expr={:?})", expr);
375 self.walk_adjustment(expr);
378 hir::ExprPath(_) => { }
380 hir::ExprType(ref subexpr, _) => {
381 self.walk_expr(&subexpr)
384 hir::ExprUnary(hir::UnDeref, ref base) => { // *base
385 if !self.walk_overloaded_operator(expr, &base, Vec::new(), PassArgs::ByRef) {
386 self.select_from_expr(&base);
390 hir::ExprField(ref base, _) => { // base.f
391 self.select_from_expr(&base);
394 hir::ExprTupField(ref base, _) => { // base.<n>
395 self.select_from_expr(&base);
398 hir::ExprIndex(ref lhs, ref rhs) => { // lhs[rhs]
399 if !self.walk_overloaded_operator(expr,
403 self.select_from_expr(&lhs);
404 self.consume_expr(&rhs);
408 hir::ExprCall(ref callee, ref args) => { // callee(args)
409 self.walk_callee(expr, &callee);
410 self.consume_exprs(args);
413 hir::ExprMethodCall(.., ref args) => { // callee.m(args)
414 self.consume_exprs(args);
417 hir::ExprStruct(_, ref fields, ref opt_with) => {
418 self.walk_struct_expr(fields, opt_with);
421 hir::ExprTup(ref exprs) => {
422 self.consume_exprs(exprs);
425 hir::ExprIf(ref cond_expr, ref then_expr, ref opt_else_expr) => {
426 self.consume_expr(&cond_expr);
427 self.walk_expr(&then_expr);
428 if let Some(ref else_expr) = *opt_else_expr {
429 self.consume_expr(&else_expr);
433 hir::ExprMatch(ref discr, ref arms, _) => {
434 let discr_cmt = return_if_err!(self.mc.cat_expr(&discr));
435 let r = self.tcx().types.re_empty;
436 self.borrow_expr(&discr, r, ty::ImmBorrow, MatchDiscriminant);
438 // treatment of the discriminant is handled while walking the arms.
440 let mode = self.arm_move_mode(discr_cmt.clone(), arm);
441 let mode = mode.match_mode();
442 self.walk_arm(discr_cmt.clone(), arm, mode);
446 hir::ExprArray(ref exprs) => {
447 self.consume_exprs(exprs);
450 hir::ExprAddrOf(m, ref base) => { // &base
451 // make sure that the thing we are pointing out stays valid
452 // for the lifetime `scope_r` of the resulting ptr:
453 let expr_ty = return_if_err!(self.mc.infcx.node_ty(expr.id));
454 if let ty::TyRef(r, _) = expr_ty.sty {
455 let bk = ty::BorrowKind::from_mutbl(m);
456 self.borrow_expr(&base, r, bk, AddrOf);
460 hir::ExprInlineAsm(ref ia, ref outputs, ref inputs) => {
461 for (o, output) in ia.outputs.iter().zip(outputs) {
463 self.consume_expr(output);
465 self.mutate_expr(expr, output,
467 MutateMode::WriteAndRead
469 MutateMode::JustWrite
473 self.consume_exprs(inputs);
477 hir::ExprLit(..) => {}
479 hir::ExprLoop(ref blk, _, _) => {
480 self.walk_block(&blk);
483 hir::ExprWhile(ref cond_expr, ref blk, _) => {
484 self.consume_expr(&cond_expr);
485 self.walk_block(&blk);
488 hir::ExprUnary(op, ref lhs) => {
489 let pass_args = if op.is_by_value() {
495 if !self.walk_overloaded_operator(expr, &lhs, Vec::new(), pass_args) {
496 self.consume_expr(&lhs);
500 hir::ExprBinary(op, ref lhs, ref rhs) => {
501 let pass_args = if op.node.is_by_value() {
507 if !self.walk_overloaded_operator(expr, &lhs, vec![&rhs], pass_args) {
508 self.consume_expr(&lhs);
509 self.consume_expr(&rhs);
513 hir::ExprBlock(ref blk) => {
514 self.walk_block(&blk);
517 hir::ExprBreak(_, ref opt_expr) | hir::ExprRet(ref opt_expr) => {
518 if let Some(ref expr) = *opt_expr {
519 self.consume_expr(&expr);
523 hir::ExprAssign(ref lhs, ref rhs) => {
524 self.mutate_expr(expr, &lhs, MutateMode::JustWrite);
525 self.consume_expr(&rhs);
528 hir::ExprCast(ref base, _) => {
529 self.consume_expr(&base);
532 hir::ExprAssignOp(op, ref lhs, ref rhs) => {
533 // NB All our assignment operations take the RHS by value
534 assert!(op.node.is_by_value());
536 if !self.walk_overloaded_operator(expr, lhs, vec![rhs], PassArgs::ByValue) {
537 self.mutate_expr(expr, &lhs, MutateMode::WriteAndRead);
538 self.consume_expr(&rhs);
542 hir::ExprRepeat(ref base, _) => {
543 self.consume_expr(&base);
546 hir::ExprClosure(.., fn_decl_span) => {
547 self.walk_captures(expr, fn_decl_span)
550 hir::ExprBox(ref base) => {
551 self.consume_expr(&base);
556 fn walk_callee(&mut self, call: &hir::Expr, callee: &hir::Expr) {
557 let callee_ty = return_if_err!(self.mc.infcx.expr_ty_adjusted(callee));
558 debug!("walk_callee: callee={:?} callee_ty={:?}",
560 match callee_ty.sty {
561 ty::TyFnDef(..) | ty::TyFnPtr(_) => {
562 self.consume_expr(callee);
566 let method = self.mc.infcx.tables.borrow().method_map[&call.id];
567 match OverloadedCallType::from_method_id(self.tcx(), method.def_id) {
568 FnMutOverloadedCall => {
569 let call_scope_r = self.tcx().node_scope_region(call.id);
570 self.borrow_expr(callee,
575 FnOverloadedCall => {
576 let call_scope_r = self.tcx().node_scope_region(call.id);
577 self.borrow_expr(callee,
582 FnOnceOverloadedCall => self.consume_expr(callee),
588 fn walk_stmt(&mut self, stmt: &hir::Stmt) {
590 hir::StmtDecl(ref decl, _) => {
592 hir::DeclLocal(ref local) => {
593 self.walk_local(&local);
596 hir::DeclItem(_) => {
597 // we don't visit nested items in this visitor,
598 // only the fn body we were given.
603 hir::StmtExpr(ref expr, _) |
604 hir::StmtSemi(ref expr, _) => {
605 self.consume_expr(&expr);
610 fn walk_local(&mut self, local: &hir::Local) {
613 let delegate = &mut self.delegate;
614 local.pat.each_binding(|_, id, span, _| {
615 delegate.decl_without_init(id, span);
620 // Variable declarations with
621 // initializers are considered
622 // "assigns", which is handled by
624 self.walk_expr(&expr);
625 let init_cmt = return_if_err!(self.mc.cat_expr(&expr));
626 self.walk_irrefutable_pat(init_cmt, &local.pat);
631 /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
632 /// depending on its type.
633 fn walk_block(&mut self, blk: &hir::Block) {
634 debug!("walk_block(blk.id={})", blk.id);
636 for stmt in &blk.stmts {
637 self.walk_stmt(stmt);
640 if let Some(ref tail_expr) = blk.expr {
641 self.consume_expr(&tail_expr);
645 fn walk_struct_expr(&mut self,
646 fields: &[hir::Field],
647 opt_with: &Option<P<hir::Expr>>) {
648 // Consume the expressions supplying values for each field.
649 for field in fields {
650 self.consume_expr(&field.expr);
653 let with_expr = match *opt_with {
658 let with_cmt = return_if_err!(self.mc.cat_expr(&with_expr));
660 // Select just those fields of the `with`
661 // expression that will actually be used
662 match with_cmt.ty.sty {
663 ty::TyAdt(adt, substs) if adt.is_struct() => {
664 // Consume those fields of the with expression that are needed.
665 for with_field in &adt.struct_variant().fields {
666 if !contains_field_named(with_field, fields) {
667 let cmt_field = self.mc.cat_field(
671 with_field.ty(self.tcx(), substs)
673 self.delegate_consume(with_expr.id, with_expr.span, cmt_field);
678 // the base expression should always evaluate to a
679 // struct; however, when EUV is run during typeck, it
680 // may not. This will generate an error earlier in typeck,
681 // so we can just ignore it.
682 if !self.tcx().sess.has_errors() {
685 "with expression doesn't evaluate to a struct");
690 // walk the with expression so that complex expressions
691 // are properly handled.
692 self.walk_expr(with_expr);
694 fn contains_field_named(field: &ty::FieldDef,
695 fields: &[hir::Field])
699 |f| f.name.node == field.name)
703 // Invoke the appropriate delegate calls for anything that gets
704 // consumed or borrowed as part of the automatic adjustment
706 fn walk_adjustment(&mut self, expr: &hir::Expr) {
707 let infcx = self.mc.infcx;
708 //NOTE(@jroesch): mixed RefCell borrow causes crash
709 let adj = infcx.tables.borrow().adjustments.get(&expr.id).cloned();
711 return_if_err!(self.mc.cat_expr_unadjusted(expr));
712 if let Some(adjustment) = adj {
713 match adjustment.kind {
714 adjustment::Adjust::NeverToAny |
715 adjustment::Adjust::ReifyFnPointer |
716 adjustment::Adjust::UnsafeFnPointer |
717 adjustment::Adjust::ClosureFnPointer |
718 adjustment::Adjust::MutToConstPointer => {
719 // Creating a closure/fn-pointer or unsizing consumes
720 // the input and stores it into the resulting rvalue.
721 debug!("walk_adjustment: trivial adjustment");
722 self.delegate_consume(expr.id, expr.span, cmt_unadjusted);
724 adjustment::Adjust::DerefRef { ref autoderefs, autoref, unsize } => {
725 debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment);
728 return_if_err!(self.walk_autoderefs(expr, cmt_unadjusted, autoderefs));
731 self.walk_autoref(expr, cmt_derefd, autoref);
734 // Unsizing consumes the thin pointer and produces a fat one.
735 self.delegate_consume(expr.id, expr.span, cmt_refd);
742 /// Autoderefs for overloaded Deref calls in fact reference their receiver. That is, if we have
743 /// `(*x)` where `x` is of type `Rc<T>`, then this in fact is equivalent to `x.deref()`. Since
744 /// `deref()` is declared with `&self`, this is an autoref of `x`.
745 fn walk_autoderefs(&mut self,
747 mut cmt: mc::cmt<'tcx>,
748 autoderefs: &[Option<ty::MethodCallee<'tcx>>])
749 -> mc::McResult<mc::cmt<'tcx>> {
750 debug!("walk_autoderefs expr={:?} autoderefs={:?}", expr, autoderefs);
752 for &overloaded in autoderefs {
753 if let Some(method) = overloaded {
754 let self_ty = method.sig.inputs()[0];
755 let self_ty = self.mc.infcx.resolve_type_vars_if_possible(&self_ty);
757 let (m, r) = match self_ty.sty {
758 ty::TyRef(r, ref m) => (m.mutbl, r),
759 _ => span_bug!(expr.span, "bad overloaded deref type {:?}", self_ty)
761 let bk = ty::BorrowKind::from_mutbl(m);
762 self.delegate.borrow(expr.id, expr.span, cmt.clone(),
764 cmt = self.mc.cat_overloaded_autoderef(expr, method)?;
766 cmt = self.mc.cat_deref(expr, cmt, false)?;
772 /// Walks the autoref `opt_autoref` applied to the autoderef'd
773 /// `expr`. `cmt_derefd` is the mem-categorized form of `expr`
774 /// after all relevant autoderefs have occurred. Because AutoRefs
775 /// can be recursive, this function is recursive: it first walks
776 /// deeply all the way down the autoref chain, and then processes
777 /// the autorefs on the way out. At each point, it returns the
778 /// `cmt` for the rvalue that will be produced by introduced an
780 fn walk_autoref(&mut self,
782 cmt_base: mc::cmt<'tcx>,
783 opt_autoref: Option<adjustment::AutoBorrow<'tcx>>)
786 debug!("walk_autoref(expr.id={} cmt_derefd={:?} opt_autoref={:?})",
791 let cmt_base_ty = cmt_base.ty;
793 let autoref = match opt_autoref {
794 Some(ref autoref) => autoref,
802 adjustment::AutoBorrow::Ref(r, m) => {
803 self.delegate.borrow(expr.id,
807 ty::BorrowKind::from_mutbl(m),
811 adjustment::AutoBorrow::RawPtr(m) => {
812 debug!("walk_autoref: expr.id={} cmt_base={:?}",
816 // Converting from a &T to *T (or &mut T to *mut T) is
817 // treated as borrowing it for the enclosing temporary
819 let r = self.tcx().node_scope_region(expr.id);
821 self.delegate.borrow(expr.id,
825 ty::BorrowKind::from_mutbl(m),
830 // Construct the categorization for the result of the autoref.
831 // This is always an rvalue, since we are producing a new
832 // (temporary) indirection.
834 let adj_ty = cmt_base_ty.adjust_for_autoref(self.tcx(), opt_autoref);
836 self.mc.cat_rvalue_node(expr.id, expr.span, adj_ty)
840 // When this returns true, it means that the expression *is* a
841 // method-call (i.e. via the operator-overload). This true result
842 // also implies that walk_overloaded_operator already took care of
843 // recursively processing the input arguments, and thus the caller
845 fn walk_overloaded_operator(&mut self,
847 receiver: &hir::Expr,
848 rhs: Vec<&hir::Expr>,
852 if !self.mc.infcx.tables.borrow().is_method_call(expr.id) {
857 PassArgs::ByValue => {
858 self.consume_expr(receiver);
860 self.consume_expr(arg);
865 PassArgs::ByRef => {},
868 self.walk_expr(receiver);
870 // Arguments (but not receivers) to overloaded operator
871 // methods are implicitly autoref'd which sadly does not use
872 // adjustments, so we must hardcode the borrow here.
874 let r = self.tcx().node_scope_region(expr.id);
875 let bk = ty::ImmBorrow;
878 self.borrow_expr(arg, r, bk, OverloadedOperator);
883 fn arm_move_mode(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm) -> TrackMatchMode {
884 let mut mode = Unknown;
885 for pat in &arm.pats {
886 self.determine_pat_move_mode(discr_cmt.clone(), &pat, &mut mode);
891 fn walk_arm(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm, mode: MatchMode) {
892 for pat in &arm.pats {
893 self.walk_pat(discr_cmt.clone(), &pat, mode);
896 if let Some(ref guard) = arm.guard {
897 self.consume_expr(&guard);
900 self.consume_expr(&arm.body);
903 /// Walks a pat that occurs in isolation (i.e. top-level of fn
904 /// arg or let binding. *Not* a match arm or nested pat.)
905 fn walk_irrefutable_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat) {
906 let mut mode = Unknown;
907 self.determine_pat_move_mode(cmt_discr.clone(), pat, &mut mode);
908 let mode = mode.match_mode();
909 self.walk_pat(cmt_discr, pat, mode);
912 /// Identifies any bindings within `pat` and accumulates within
913 /// `mode` whether the overall pattern/match structure is a move,
915 fn determine_pat_move_mode(&mut self,
916 cmt_discr: mc::cmt<'tcx>,
918 mode: &mut TrackMatchMode) {
919 debug!("determine_pat_move_mode cmt_discr={:?} pat={:?}", cmt_discr,
921 return_if_err!(self.mc.cat_pattern(cmt_discr, pat, |_mc, cmt_pat, pat| {
923 PatKind::Binding(hir::BindByRef(..), ..) =>
924 mode.lub(BorrowingMatch),
925 PatKind::Binding(hir::BindByValue(..), ..) => {
926 match copy_or_move(self.mc.infcx, &cmt_pat, PatBindingMove) {
927 Copy => mode.lub(CopyingMatch),
928 Move(..) => mode.lub(MovingMatch),
936 /// The core driver for walking a pattern; `match_mode` must be
937 /// established up front, e.g. via `determine_pat_move_mode` (see
938 /// also `walk_irrefutable_pat` for patterns that stand alone).
939 fn walk_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat, match_mode: MatchMode) {
940 debug!("walk_pat cmt_discr={:?} pat={:?}", cmt_discr, pat);
942 let tcx = &self.tcx();
944 let infcx = self.mc.infcx;
945 let delegate = &mut self.delegate;
946 return_if_err!(mc.cat_pattern(cmt_discr.clone(), pat, |mc, cmt_pat, pat| {
947 if let PatKind::Binding(bmode, def_id, ..) = pat.node {
948 debug!("binding cmt_pat={:?} pat={:?} match_mode={:?}", cmt_pat, pat, match_mode);
950 // pat_ty: the type of the binding being produced.
951 let pat_ty = return_if_err!(infcx.node_ty(pat.id));
953 // Each match binding is effectively an assignment to the
954 // binding being produced.
955 let def = Def::Local(def_id);
956 if let Ok(binding_cmt) = mc.cat_def(pat.id, pat.span, pat_ty, def) {
957 delegate.mutate(pat.id, pat.span, binding_cmt, MutateMode::Init);
960 // It is also a borrow or copy/move of the value being matched.
962 hir::BindByRef(m) => {
963 if let ty::TyRef(r, _) = pat_ty.sty {
964 let bk = ty::BorrowKind::from_mutbl(m);
965 delegate.borrow(pat.id, pat.span, cmt_pat, r, bk, RefBinding);
968 hir::BindByValue(..) => {
969 let mode = copy_or_move(infcx, &cmt_pat, PatBindingMove);
970 debug!("walk_pat binding consuming pat");
971 delegate.consume_pat(pat, cmt_pat, mode);
977 // Do a second pass over the pattern, calling `matched_pat` on
978 // the interior nodes (enum variants and structs), as opposed
979 // to the above loop's visit of than the bindings that form
980 // the leaves of the pattern tree structure.
981 return_if_err!(mc.cat_pattern(cmt_discr, pat, |mc, cmt_pat, pat| {
982 let qpath = match pat.node {
983 PatKind::Path(ref qpath) |
984 PatKind::TupleStruct(ref qpath, ..) |
985 PatKind::Struct(ref qpath, ..) => qpath,
988 let def = infcx.tables.borrow().qpath_def(qpath, pat.id);
990 Def::Variant(variant_did) |
991 Def::VariantCtor(variant_did, ..) => {
992 let enum_did = tcx.parent_def_id(variant_did).unwrap();
993 let downcast_cmt = if tcx.adt_def(enum_did).is_univariant() {
996 let cmt_pat_ty = cmt_pat.ty;
997 mc.cat_downcast(pat, cmt_pat, cmt_pat_ty, variant_did)
1000 debug!("variant downcast_cmt={:?} pat={:?}", downcast_cmt, pat);
1001 delegate.matched_pat(pat, downcast_cmt, match_mode);
1003 Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
1004 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => {
1005 debug!("struct cmt_pat={:?} pat={:?}", cmt_pat, pat);
1006 delegate.matched_pat(pat, cmt_pat, match_mode);
1013 fn walk_captures(&mut self, closure_expr: &hir::Expr, fn_decl_span: Span) {
1014 debug!("walk_captures({:?})", closure_expr);
1016 self.tcx().with_freevars(closure_expr.id, |freevars| {
1017 for freevar in freevars {
1018 let def_id = freevar.def.def_id();
1019 let id_var = self.tcx().hir.as_local_node_id(def_id).unwrap();
1020 let upvar_id = ty::UpvarId { var_id: id_var,
1021 closure_expr_id: closure_expr.id };
1022 let upvar_capture = self.mc.infcx.upvar_capture(upvar_id).unwrap();
1023 let cmt_var = return_if_err!(self.cat_captured_var(closure_expr.id,
1026 match upvar_capture {
1027 ty::UpvarCapture::ByValue => {
1028 let mode = copy_or_move(self.mc.infcx, &cmt_var, CaptureMove);
1029 self.delegate.consume(closure_expr.id, freevar.span, cmt_var, mode);
1031 ty::UpvarCapture::ByRef(upvar_borrow) => {
1032 self.delegate.borrow(closure_expr.id,
1035 upvar_borrow.region,
1037 ClosureCapture(freevar.span));
1044 fn cat_captured_var(&mut self,
1045 closure_id: ast::NodeId,
1048 -> mc::McResult<mc::cmt<'tcx>> {
1049 // Create the cmt for the variable being borrowed, from the
1050 // caller's perspective
1051 let var_id = self.tcx().hir.as_local_node_id(upvar_def.def_id()).unwrap();
1052 let var_ty = self.mc.infcx.node_ty(var_id)?;
1053 self.mc.cat_def(closure_id, closure_span, var_ty, upvar_def)
1057 fn copy_or_move<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
1058 cmt: &mc::cmt<'tcx>,
1059 move_reason: MoveReason)
1062 if infcx.type_moves_by_default(cmt.ty, cmt.span) {