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<'tcx>,
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<'tcx>,
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 overloaded_call_type =
567 match self.mc.infcx.node_method_id(ty::MethodCall::expr(call.id)) {
569 OverloadedCallType::from_method_id(self.tcx(), method_id)
574 "unexpected callee type {}",
578 match overloaded_call_type {
579 FnMutOverloadedCall => {
580 let call_scope_r = self.tcx().node_scope_region(call.id);
581 self.borrow_expr(callee,
586 FnOverloadedCall => {
587 let call_scope_r = self.tcx().node_scope_region(call.id);
588 self.borrow_expr(callee,
593 FnOnceOverloadedCall => self.consume_expr(callee),
599 fn walk_stmt(&mut self, stmt: &hir::Stmt) {
601 hir::StmtDecl(ref decl, _) => {
603 hir::DeclLocal(ref local) => {
604 self.walk_local(&local);
607 hir::DeclItem(_) => {
608 // we don't visit nested items in this visitor,
609 // only the fn body we were given.
614 hir::StmtExpr(ref expr, _) |
615 hir::StmtSemi(ref expr, _) => {
616 self.consume_expr(&expr);
621 fn walk_local(&mut self, local: &hir::Local) {
624 let delegate = &mut self.delegate;
625 local.pat.each_binding(|_, id, span, _| {
626 delegate.decl_without_init(id, span);
631 // Variable declarations with
632 // initializers are considered
633 // "assigns", which is handled by
635 self.walk_expr(&expr);
636 let init_cmt = return_if_err!(self.mc.cat_expr(&expr));
637 self.walk_irrefutable_pat(init_cmt, &local.pat);
642 /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
643 /// depending on its type.
644 fn walk_block(&mut self, blk: &hir::Block) {
645 debug!("walk_block(blk.id={})", blk.id);
647 for stmt in &blk.stmts {
648 self.walk_stmt(stmt);
651 if let Some(ref tail_expr) = blk.expr {
652 self.consume_expr(&tail_expr);
656 fn walk_struct_expr(&mut self,
657 fields: &[hir::Field],
658 opt_with: &Option<P<hir::Expr>>) {
659 // Consume the expressions supplying values for each field.
660 for field in fields {
661 self.consume_expr(&field.expr);
664 let with_expr = match *opt_with {
669 let with_cmt = return_if_err!(self.mc.cat_expr(&with_expr));
671 // Select just those fields of the `with`
672 // expression that will actually be used
673 match with_cmt.ty.sty {
674 ty::TyAdt(adt, substs) if adt.is_struct() => {
675 // Consume those fields of the with expression that are needed.
676 for with_field in &adt.struct_variant().fields {
677 if !contains_field_named(with_field, fields) {
678 let cmt_field = self.mc.cat_field(
682 with_field.ty(self.tcx(), substs)
684 self.delegate_consume(with_expr.id, with_expr.span, cmt_field);
689 // the base expression should always evaluate to a
690 // struct; however, when EUV is run during typeck, it
691 // may not. This will generate an error earlier in typeck,
692 // so we can just ignore it.
693 if !self.tcx().sess.has_errors() {
696 "with expression doesn't evaluate to a struct");
701 // walk the with expression so that complex expressions
702 // are properly handled.
703 self.walk_expr(with_expr);
705 fn contains_field_named(field: &ty::FieldDef,
706 fields: &[hir::Field])
710 |f| f.name.node == field.name)
714 // Invoke the appropriate delegate calls for anything that gets
715 // consumed or borrowed as part of the automatic adjustment
717 fn walk_adjustment(&mut self, expr: &hir::Expr) {
718 let infcx = self.mc.infcx;
719 //NOTE(@jroesch): mixed RefCell borrow causes crash
720 let adj = infcx.tables.borrow().adjustments.get(&expr.id).map(|x| x.clone());
721 if let Some(adjustment) = adj {
722 match adjustment.kind {
723 adjustment::Adjust::NeverToAny |
724 adjustment::Adjust::ReifyFnPointer |
725 adjustment::Adjust::UnsafeFnPointer |
726 adjustment::Adjust::ClosureFnPointer |
727 adjustment::Adjust::MutToConstPointer => {
728 // Creating a closure/fn-pointer or unsizing consumes
729 // the input and stores it into the resulting rvalue.
730 debug!("walk_adjustment: trivial adjustment");
732 return_if_err!(self.mc.cat_expr_unadjusted(expr));
733 self.delegate_consume(expr.id, expr.span, cmt_unadjusted);
735 adjustment::Adjust::DerefRef { autoderefs, autoref, unsize } => {
736 debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment);
738 self.walk_autoderefs(expr, autoderefs);
741 return_if_err!(self.mc.cat_expr_autoderefd(expr, autoderefs));
744 self.walk_autoref(expr, cmt_derefd, autoref);
747 // Unsizing consumes the thin pointer and produces a fat one.
748 self.delegate_consume(expr.id, expr.span, cmt_refd);
755 /// Autoderefs for overloaded Deref calls in fact reference their receiver. That is, if we have
756 /// `(*x)` where `x` is of type `Rc<T>`, then this in fact is equivalent to `x.deref()`. Since
757 /// `deref()` is declared with `&self`, this is an autoref of `x`.
758 fn walk_autoderefs(&mut self,
761 debug!("walk_autoderefs expr={:?} autoderefs={}", expr, autoderefs);
763 for i in 0..autoderefs {
764 let deref_id = ty::MethodCall::autoderef(expr.id, i as u32);
765 if let Some(method_ty) = self.mc.infcx.node_method_ty(deref_id) {
766 let cmt = return_if_err!(self.mc.cat_expr_autoderefd(expr, i));
768 // the method call infrastructure should have
769 // replaced all late-bound regions with variables:
770 let self_ty = method_ty.fn_sig().input(0);
771 let self_ty = self.tcx().no_late_bound_regions(&self_ty).unwrap();
773 let (m, r) = match self_ty.sty {
774 ty::TyRef(r, ref m) => (m.mutbl, r),
775 _ => span_bug!(expr.span,
776 "bad overloaded deref type {:?}",
779 let bk = ty::BorrowKind::from_mutbl(m);
780 self.delegate.borrow(expr.id, expr.span, cmt,
786 /// Walks the autoref `opt_autoref` applied to the autoderef'd
787 /// `expr`. `cmt_derefd` is the mem-categorized form of `expr`
788 /// after all relevant autoderefs have occurred. Because AutoRefs
789 /// can be recursive, this function is recursive: it first walks
790 /// deeply all the way down the autoref chain, and then processes
791 /// the autorefs on the way out. At each point, it returns the
792 /// `cmt` for the rvalue that will be produced by introduced an
794 fn walk_autoref(&mut self,
796 cmt_base: mc::cmt<'tcx>,
797 opt_autoref: Option<adjustment::AutoBorrow<'tcx>>)
800 debug!("walk_autoref(expr.id={} cmt_derefd={:?} opt_autoref={:?})",
805 let cmt_base_ty = cmt_base.ty;
807 let autoref = match opt_autoref {
808 Some(ref autoref) => autoref,
816 adjustment::AutoBorrow::Ref(r, m) => {
817 self.delegate.borrow(expr.id,
821 ty::BorrowKind::from_mutbl(m),
825 adjustment::AutoBorrow::RawPtr(m) => {
826 debug!("walk_autoref: expr.id={} cmt_base={:?}",
830 // Converting from a &T to *T (or &mut T to *mut T) is
831 // treated as borrowing it for the enclosing temporary
833 let r = self.tcx().node_scope_region(expr.id);
835 self.delegate.borrow(expr.id,
839 ty::BorrowKind::from_mutbl(m),
844 // Construct the categorization for the result of the autoref.
845 // This is always an rvalue, since we are producing a new
846 // (temporary) indirection.
848 let adj_ty = cmt_base_ty.adjust_for_autoref(self.tcx(), opt_autoref);
850 self.mc.cat_rvalue_node(expr.id, expr.span, adj_ty)
854 // When this returns true, it means that the expression *is* a
855 // method-call (i.e. via the operator-overload). This true result
856 // also implies that walk_overloaded_operator already took care of
857 // recursively processing the input arguments, and thus the caller
859 fn walk_overloaded_operator(&mut self,
861 receiver: &hir::Expr,
862 rhs: Vec<&hir::Expr>,
866 if !self.mc.infcx.is_method_call(expr.id) {
871 PassArgs::ByValue => {
872 self.consume_expr(receiver);
874 self.consume_expr(arg);
879 PassArgs::ByRef => {},
882 self.walk_expr(receiver);
884 // Arguments (but not receivers) to overloaded operator
885 // methods are implicitly autoref'd which sadly does not use
886 // adjustments, so we must hardcode the borrow here.
888 let r = self.tcx().node_scope_region(expr.id);
889 let bk = ty::ImmBorrow;
892 self.borrow_expr(arg, r, bk, OverloadedOperator);
897 fn arm_move_mode(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm) -> TrackMatchMode {
898 let mut mode = Unknown;
899 for pat in &arm.pats {
900 self.determine_pat_move_mode(discr_cmt.clone(), &pat, &mut mode);
905 fn walk_arm(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm, mode: MatchMode) {
906 for pat in &arm.pats {
907 self.walk_pat(discr_cmt.clone(), &pat, mode);
910 if let Some(ref guard) = arm.guard {
911 self.consume_expr(&guard);
914 self.consume_expr(&arm.body);
917 /// Walks a pat that occurs in isolation (i.e. top-level of fn
918 /// arg or let binding. *Not* a match arm or nested pat.)
919 fn walk_irrefutable_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat) {
920 let mut mode = Unknown;
921 self.determine_pat_move_mode(cmt_discr.clone(), pat, &mut mode);
922 let mode = mode.match_mode();
923 self.walk_pat(cmt_discr, pat, mode);
926 /// Identifies any bindings within `pat` and accumulates within
927 /// `mode` whether the overall pattern/match structure is a move,
929 fn determine_pat_move_mode(&mut self,
930 cmt_discr: mc::cmt<'tcx>,
932 mode: &mut TrackMatchMode) {
933 debug!("determine_pat_move_mode cmt_discr={:?} pat={:?}", cmt_discr,
935 return_if_err!(self.mc.cat_pattern(cmt_discr, pat, |_mc, cmt_pat, pat| {
937 PatKind::Binding(hir::BindByRef(..), ..) =>
938 mode.lub(BorrowingMatch),
939 PatKind::Binding(hir::BindByValue(..), ..) => {
940 match copy_or_move(self.mc.infcx, &cmt_pat, PatBindingMove) {
941 Copy => mode.lub(CopyingMatch),
942 Move(..) => mode.lub(MovingMatch),
950 /// The core driver for walking a pattern; `match_mode` must be
951 /// established up front, e.g. via `determine_pat_move_mode` (see
952 /// also `walk_irrefutable_pat` for patterns that stand alone).
953 fn walk_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat, match_mode: MatchMode) {
954 debug!("walk_pat cmt_discr={:?} pat={:?}", cmt_discr, pat);
956 let tcx = &self.tcx();
958 let infcx = self.mc.infcx;
959 let delegate = &mut self.delegate;
960 return_if_err!(mc.cat_pattern(cmt_discr.clone(), pat, |mc, cmt_pat, pat| {
961 if let PatKind::Binding(bmode, def_id, ..) = pat.node {
962 debug!("binding cmt_pat={:?} pat={:?} match_mode={:?}", cmt_pat, pat, match_mode);
964 // pat_ty: the type of the binding being produced.
965 let pat_ty = return_if_err!(infcx.node_ty(pat.id));
967 // Each match binding is effectively an assignment to the
968 // binding being produced.
969 let def = Def::Local(def_id);
970 if let Ok(binding_cmt) = mc.cat_def(pat.id, pat.span, pat_ty, def) {
971 delegate.mutate(pat.id, pat.span, binding_cmt, MutateMode::Init);
974 // It is also a borrow or copy/move of the value being matched.
976 hir::BindByRef(m) => {
977 if let ty::TyRef(r, _) = pat_ty.sty {
978 let bk = ty::BorrowKind::from_mutbl(m);
979 delegate.borrow(pat.id, pat.span, cmt_pat, r, bk, RefBinding);
982 hir::BindByValue(..) => {
983 let mode = copy_or_move(infcx, &cmt_pat, PatBindingMove);
984 debug!("walk_pat binding consuming pat");
985 delegate.consume_pat(pat, cmt_pat, mode);
991 // Do a second pass over the pattern, calling `matched_pat` on
992 // the interior nodes (enum variants and structs), as opposed
993 // to the above loop's visit of than the bindings that form
994 // the leaves of the pattern tree structure.
995 return_if_err!(mc.cat_pattern(cmt_discr, pat, |mc, cmt_pat, pat| {
996 let qpath = match pat.node {
997 PatKind::Path(ref qpath) |
998 PatKind::TupleStruct(ref qpath, ..) |
999 PatKind::Struct(ref qpath, ..) => qpath,
1002 let def = infcx.tables.borrow().qpath_def(qpath, pat.id);
1004 Def::Variant(variant_did) |
1005 Def::VariantCtor(variant_did, ..) => {
1006 let enum_did = tcx.parent_def_id(variant_did).unwrap();
1007 let downcast_cmt = if tcx.adt_def(enum_did).is_univariant() {
1010 let cmt_pat_ty = cmt_pat.ty;
1011 mc.cat_downcast(pat, cmt_pat, cmt_pat_ty, variant_did)
1014 debug!("variant downcast_cmt={:?} pat={:?}", downcast_cmt, pat);
1015 delegate.matched_pat(pat, downcast_cmt, match_mode);
1017 Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
1018 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => {
1019 debug!("struct cmt_pat={:?} pat={:?}", cmt_pat, pat);
1020 delegate.matched_pat(pat, cmt_pat, match_mode);
1027 fn walk_captures(&mut self, closure_expr: &hir::Expr, fn_decl_span: Span) {
1028 debug!("walk_captures({:?})", closure_expr);
1030 self.tcx().with_freevars(closure_expr.id, |freevars| {
1031 for freevar in freevars {
1032 let def_id = freevar.def.def_id();
1033 let id_var = self.tcx().hir.as_local_node_id(def_id).unwrap();
1034 let upvar_id = ty::UpvarId { var_id: id_var,
1035 closure_expr_id: closure_expr.id };
1036 let upvar_capture = self.mc.infcx.upvar_capture(upvar_id).unwrap();
1037 let cmt_var = return_if_err!(self.cat_captured_var(closure_expr.id,
1040 match upvar_capture {
1041 ty::UpvarCapture::ByValue => {
1042 let mode = copy_or_move(self.mc.infcx, &cmt_var, CaptureMove);
1043 self.delegate.consume(closure_expr.id, freevar.span, cmt_var, mode);
1045 ty::UpvarCapture::ByRef(upvar_borrow) => {
1046 self.delegate.borrow(closure_expr.id,
1049 upvar_borrow.region,
1051 ClosureCapture(freevar.span));
1058 fn cat_captured_var(&mut self,
1059 closure_id: ast::NodeId,
1062 -> mc::McResult<mc::cmt<'tcx>> {
1063 // Create the cmt for the variable being borrowed, from the
1064 // caller's perspective
1065 let var_id = self.tcx().hir.as_local_node_id(upvar_def.def_id()).unwrap();
1066 let var_ty = self.mc.infcx.node_ty(var_id)?;
1067 self.mc.cat_def(closure_id, closure_span, var_ty, upvar_def)
1071 fn copy_or_move<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
1072 cmt: &mc::cmt<'tcx>,
1073 move_reason: MoveReason)
1076 if infcx.type_moves_by_default(cmt.ty, cmt.span) {