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;
27 use ty::{self, TyCtxt, adjustment};
29 use hir::{self, PatKind};
34 use util::nodemap::ItemLocalSet;
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<'tcx>,
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: TyCtxt, trait_id: DefId) -> OverloadedCallType {
214 for &(maybe_function_trait, overloaded_call_type) in &[
215 (tcx.lang_items().fn_once_trait(), FnOnceOverloadedCall),
216 (tcx.lang_items().fn_mut_trait(), FnMutOverloadedCall),
217 (tcx.lang_items().fn_trait(), FnOverloadedCall)
219 match maybe_function_trait {
220 Some(function_trait) if function_trait == trait_id => {
221 return overloaded_call_type
227 bug!("overloaded call didn't map to known function trait")
230 fn from_method_id(tcx: TyCtxt, method_id: DefId) -> OverloadedCallType {
231 let method = tcx.associated_item(method_id);
232 OverloadedCallType::from_trait_id(tcx, method.container.id())
236 ///////////////////////////////////////////////////////////////////////////
237 // The ExprUseVisitor type
239 // This is the code that actually walks the tree.
240 pub struct ExprUseVisitor<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
241 mc: mc::MemCategorizationContext<'a, 'gcx, 'tcx>,
242 delegate: &'a mut Delegate<'tcx>,
243 param_env: ty::ParamEnv<'tcx>,
246 // If the MC results in an error, it's because the type check
247 // failed (or will fail, when the error is uncovered and reported
248 // during writeback). In this case, we just ignore this part of the
251 // Note that this macro appears similar to try!(), but, unlike try!(),
252 // it does not propagate the error.
253 macro_rules! return_if_err {
258 debug!("mc reported err");
265 impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx, 'tcx> {
266 /// Creates the ExprUseVisitor, configuring it with the various options provided:
268 /// - `delegate` -- who receives the callbacks
269 /// - `param_env` --- parameter environment for trait lookups (esp. pertaining to `Copy`)
270 /// - `region_scope_tree` --- region scope tree for the code being analyzed
271 /// - `tables` --- typeck results for the code being analyzed
272 /// - `rvalue_promotable_map` --- if you care about rvalue promotion, then provide
273 /// the map here (it can be computed with `tcx.rvalue_promotable_map(def_id)`).
274 /// `None` means that rvalues will be given more conservative lifetimes.
276 /// See also `with_infer`, which is used *during* typeck.
277 pub fn new(delegate: &'a mut (Delegate<'tcx>+'a),
278 tcx: TyCtxt<'a, 'tcx, 'tcx>,
279 param_env: ty::ParamEnv<'tcx>,
280 region_scope_tree: &'a region::ScopeTree,
281 tables: &'a ty::TypeckTables<'tcx>,
282 rvalue_promotable_map: Option<Rc<ItemLocalSet>>)
286 mc: mc::MemCategorizationContext::new(tcx,
289 rvalue_promotable_map),
296 impl<'a, 'gcx, 'tcx> ExprUseVisitor<'a, 'gcx, 'tcx> {
297 pub fn with_infer(delegate: &'a mut (Delegate<'tcx>+'a),
298 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
299 param_env: ty::ParamEnv<'tcx>,
300 region_scope_tree: &'a region::ScopeTree,
301 tables: &'a ty::TypeckTables<'tcx>)
305 mc: mc::MemCategorizationContext::with_infer(infcx, region_scope_tree, tables),
311 pub fn consume_body(&mut self, body: &hir::Body) {
312 debug!("consume_body(body={:?})", body);
314 for arg in &body.arguments {
315 let arg_ty = return_if_err!(self.mc.node_ty(arg.pat.hir_id));
317 let fn_body_scope_r =
318 self.tcx().mk_region(ty::ReScope(region::Scope::Node(body.value.hir_id.local_id)));
319 let arg_cmt = self.mc.cat_rvalue(
322 fn_body_scope_r, // Args live only as long as the fn body.
325 self.walk_irrefutable_pat(arg_cmt, &arg.pat);
328 self.consume_expr(&body.value);
331 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
335 fn delegate_consume(&mut self,
336 consume_id: ast::NodeId,
338 cmt: mc::cmt<'tcx>) {
339 debug!("delegate_consume(consume_id={}, cmt={:?})",
342 let mode = copy_or_move(&self.mc, self.param_env, &cmt, DirectRefMove);
343 self.delegate.consume(consume_id, consume_span, cmt, mode);
346 fn consume_exprs(&mut self, exprs: &[hir::Expr]) {
348 self.consume_expr(&expr);
352 pub fn consume_expr(&mut self, expr: &hir::Expr) {
353 debug!("consume_expr(expr={:?})", expr);
355 let cmt = return_if_err!(self.mc.cat_expr(expr));
356 self.delegate_consume(expr.id, expr.span, cmt);
357 self.walk_expr(expr);
360 fn mutate_expr(&mut self,
361 assignment_expr: &hir::Expr,
364 let cmt = return_if_err!(self.mc.cat_expr(expr));
365 self.delegate.mutate(assignment_expr.id, assignment_expr.span, cmt, mode);
366 self.walk_expr(expr);
369 fn borrow_expr(&mut self,
374 debug!("borrow_expr(expr={:?}, r={:?}, bk={:?})",
377 let cmt = return_if_err!(self.mc.cat_expr(expr));
378 self.delegate.borrow(expr.id, expr.span, cmt, r, bk, cause);
383 fn select_from_expr(&mut self, expr: &hir::Expr) {
387 pub fn walk_expr(&mut self, expr: &hir::Expr) {
388 debug!("walk_expr(expr={:?})", expr);
390 self.walk_adjustment(expr);
393 hir::ExprPath(_) => { }
395 hir::ExprType(ref subexpr, _) => {
396 self.walk_expr(&subexpr)
399 hir::ExprUnary(hir::UnDeref, ref base) => { // *base
400 self.select_from_expr(&base);
403 hir::ExprField(ref base, _) => { // base.f
404 self.select_from_expr(&base);
407 hir::ExprTupField(ref base, _) => { // base.<n>
408 self.select_from_expr(&base);
411 hir::ExprIndex(ref lhs, ref rhs) => { // lhs[rhs]
412 self.select_from_expr(&lhs);
413 self.consume_expr(&rhs);
416 hir::ExprCall(ref callee, ref args) => { // callee(args)
417 self.walk_callee(expr, &callee);
418 self.consume_exprs(args);
421 hir::ExprMethodCall(.., ref args) => { // callee.m(args)
422 self.consume_exprs(args);
425 hir::ExprStruct(_, ref fields, ref opt_with) => {
426 self.walk_struct_expr(fields, opt_with);
429 hir::ExprTup(ref exprs) => {
430 self.consume_exprs(exprs);
433 hir::ExprIf(ref cond_expr, ref then_expr, ref opt_else_expr) => {
434 self.consume_expr(&cond_expr);
435 self.walk_expr(&then_expr);
436 if let Some(ref else_expr) = *opt_else_expr {
437 self.consume_expr(&else_expr);
441 hir::ExprMatch(ref discr, ref arms, _) => {
442 let discr_cmt = return_if_err!(self.mc.cat_expr(&discr));
443 let r = self.tcx().types.re_empty;
444 self.borrow_expr(&discr, r, ty::ImmBorrow, MatchDiscriminant);
446 // treatment of the discriminant is handled while walking the arms.
448 let mode = self.arm_move_mode(discr_cmt.clone(), arm);
449 let mode = mode.match_mode();
450 self.walk_arm(discr_cmt.clone(), arm, mode);
454 hir::ExprArray(ref exprs) => {
455 self.consume_exprs(exprs);
458 hir::ExprAddrOf(m, ref base) => { // &base
459 // make sure that the thing we are pointing out stays valid
460 // for the lifetime `scope_r` of the resulting ptr:
461 let expr_ty = return_if_err!(self.mc.expr_ty(expr));
462 if let ty::TyRef(r, _) = expr_ty.sty {
463 let bk = ty::BorrowKind::from_mutbl(m);
464 self.borrow_expr(&base, r, bk, AddrOf);
468 hir::ExprInlineAsm(ref ia, ref outputs, ref inputs) => {
469 for (o, output) in ia.outputs.iter().zip(outputs) {
471 self.consume_expr(output);
473 self.mutate_expr(expr, output,
475 MutateMode::WriteAndRead
477 MutateMode::JustWrite
481 self.consume_exprs(inputs);
485 hir::ExprLit(..) => {}
487 hir::ExprLoop(ref blk, _, _) => {
488 self.walk_block(&blk);
491 hir::ExprWhile(ref cond_expr, ref blk, _) => {
492 self.consume_expr(&cond_expr);
493 self.walk_block(&blk);
496 hir::ExprUnary(_, ref lhs) => {
497 self.consume_expr(&lhs);
500 hir::ExprBinary(_, ref lhs, ref rhs) => {
501 self.consume_expr(&lhs);
502 self.consume_expr(&rhs);
505 hir::ExprBlock(ref blk) => {
506 self.walk_block(&blk);
509 hir::ExprBreak(_, ref opt_expr) | hir::ExprRet(ref opt_expr) => {
510 if let Some(ref expr) = *opt_expr {
511 self.consume_expr(&expr);
515 hir::ExprAssign(ref lhs, ref rhs) => {
516 self.mutate_expr(expr, &lhs, MutateMode::JustWrite);
517 self.consume_expr(&rhs);
520 hir::ExprCast(ref base, _) => {
521 self.consume_expr(&base);
524 hir::ExprAssignOp(_, ref lhs, ref rhs) => {
525 if self.mc.tables.is_method_call(expr) {
526 self.consume_expr(lhs);
528 self.mutate_expr(expr, &lhs, MutateMode::WriteAndRead);
530 self.consume_expr(&rhs);
533 hir::ExprRepeat(ref base, _) => {
534 self.consume_expr(&base);
537 hir::ExprClosure(.., fn_decl_span, _) => {
538 self.walk_captures(expr, fn_decl_span)
541 hir::ExprBox(ref base) => {
542 self.consume_expr(&base);
545 hir::ExprYield(ref value) => {
546 self.consume_expr(&value);
551 fn walk_callee(&mut self, call: &hir::Expr, callee: &hir::Expr) {
552 let callee_ty = return_if_err!(self.mc.expr_ty_adjusted(callee));
553 debug!("walk_callee: callee={:?} callee_ty={:?}",
555 match callee_ty.sty {
556 ty::TyFnDef(..) | ty::TyFnPtr(_) => {
557 self.consume_expr(callee);
561 if let Some(def) = self.mc.tables.type_dependent_defs().get(call.hir_id) {
562 let def_id = def.def_id();
563 let call_scope = region::Scope::Node(call.hir_id.local_id);
564 match OverloadedCallType::from_method_id(self.tcx(), def_id) {
565 FnMutOverloadedCall => {
566 let call_scope_r = self.tcx().mk_region(ty::ReScope(call_scope));
567 self.borrow_expr(callee,
572 FnOverloadedCall => {
573 let call_scope_r = self.tcx().mk_region(ty::ReScope(call_scope));
574 self.borrow_expr(callee,
579 FnOnceOverloadedCall => self.consume_expr(callee),
582 self.tcx().sess.delay_span_bug(call.span,
583 "no type-dependent def for overloaded call");
589 fn walk_stmt(&mut self, stmt: &hir::Stmt) {
591 hir::StmtDecl(ref decl, _) => {
593 hir::DeclLocal(ref local) => {
594 self.walk_local(&local);
597 hir::DeclItem(_) => {
598 // we don't visit nested items in this visitor,
599 // only the fn body we were given.
604 hir::StmtExpr(ref expr, _) |
605 hir::StmtSemi(ref expr, _) => {
606 self.consume_expr(&expr);
611 fn walk_local(&mut self, local: &hir::Local) {
614 let delegate = &mut self.delegate;
615 local.pat.each_binding(|_, id, span, _| {
616 delegate.decl_without_init(id, span);
621 // Variable declarations with
622 // initializers are considered
623 // "assigns", which is handled by
625 self.walk_expr(&expr);
626 let init_cmt = return_if_err!(self.mc.cat_expr(&expr));
627 self.walk_irrefutable_pat(init_cmt, &local.pat);
632 /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
633 /// depending on its type.
634 fn walk_block(&mut self, blk: &hir::Block) {
635 debug!("walk_block(blk.id={})", blk.id);
637 for stmt in &blk.stmts {
638 self.walk_stmt(stmt);
641 if let Some(ref tail_expr) = blk.expr {
642 self.consume_expr(&tail_expr);
646 fn walk_struct_expr(&mut self,
647 fields: &[hir::Field],
648 opt_with: &Option<P<hir::Expr>>) {
649 // Consume the expressions supplying values for each field.
650 for field in fields {
651 self.consume_expr(&field.expr);
654 let with_expr = match *opt_with {
659 let with_cmt = return_if_err!(self.mc.cat_expr(&with_expr));
661 // Select just those fields of the `with`
662 // expression that will actually be used
663 match with_cmt.ty.sty {
664 ty::TyAdt(adt, substs) if adt.is_struct() => {
665 // Consume those fields of the with expression that are needed.
666 for with_field in &adt.non_enum_variant().fields {
667 if !contains_field_named(with_field, fields) {
668 let cmt_field = self.mc.cat_field(
672 with_field.ty(self.tcx(), substs)
674 self.delegate_consume(with_expr.id, with_expr.span, cmt_field);
679 // the base expression should always evaluate to a
680 // struct; however, when EUV is run during typeck, it
681 // may not. This will generate an error earlier in typeck,
682 // so we can just ignore it.
683 if !self.tcx().sess.has_errors() {
686 "with expression doesn't evaluate to a struct");
691 // walk the with expression so that complex expressions
692 // are properly handled.
693 self.walk_expr(with_expr);
695 fn contains_field_named(field: &ty::FieldDef,
696 fields: &[hir::Field])
700 |f| f.name.node == field.name)
704 // Invoke the appropriate delegate calls for anything that gets
705 // consumed or borrowed as part of the automatic adjustment
707 fn walk_adjustment(&mut self, expr: &hir::Expr) {
708 let adjustments = self.mc.tables.expr_adjustments(expr);
709 let mut cmt = return_if_err!(self.mc.cat_expr_unadjusted(expr));
710 for adjustment in adjustments {
711 debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment);
712 match adjustment.kind {
713 adjustment::Adjust::NeverToAny |
714 adjustment::Adjust::ReifyFnPointer |
715 adjustment::Adjust::UnsafeFnPointer |
716 adjustment::Adjust::ClosureFnPointer |
717 adjustment::Adjust::MutToConstPointer |
718 adjustment::Adjust::Unsize => {
719 // Creating a closure/fn-pointer or unsizing consumes
720 // the input and stores it into the resulting rvalue.
721 self.delegate_consume(expr.id, expr.span, cmt.clone());
724 adjustment::Adjust::Deref(None) => {}
726 // Autoderefs for overloaded Deref calls in fact reference
727 // their receiver. That is, if we have `(*x)` where `x`
728 // is of type `Rc<T>`, then this in fact is equivalent to
729 // `x.deref()`. Since `deref()` is declared with `&self`,
730 // this is an autoref of `x`.
731 adjustment::Adjust::Deref(Some(ref deref)) => {
732 let bk = ty::BorrowKind::from_mutbl(deref.mutbl);
733 self.delegate.borrow(expr.id, expr.span, cmt.clone(),
734 deref.region, bk, AutoRef);
737 adjustment::Adjust::Borrow(ref autoref) => {
738 self.walk_autoref(expr, cmt.clone(), autoref);
741 cmt = return_if_err!(self.mc.cat_expr_adjusted(expr, cmt, &adjustment));
745 /// Walks the autoref `autoref` applied to the autoderef'd
746 /// `expr`. `cmt_base` is the mem-categorized form of `expr`
747 /// after all relevant autoderefs have occurred.
748 fn walk_autoref(&mut self,
750 cmt_base: mc::cmt<'tcx>,
751 autoref: &adjustment::AutoBorrow<'tcx>) {
752 debug!("walk_autoref(expr.id={} cmt_base={:?} autoref={:?})",
758 adjustment::AutoBorrow::Ref(r, m) => {
759 self.delegate.borrow(expr.id,
763 ty::BorrowKind::from_mutbl(m),
767 adjustment::AutoBorrow::RawPtr(m) => {
768 debug!("walk_autoref: expr.id={} cmt_base={:?}",
772 // Converting from a &T to *T (or &mut T to *mut T) is
773 // treated as borrowing it for the enclosing temporary
775 let r = self.tcx().mk_region(ty::ReScope(
776 region::Scope::Node(expr.hir_id.local_id)));
778 self.delegate.borrow(expr.id,
782 ty::BorrowKind::from_mutbl(m),
788 fn arm_move_mode(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm) -> TrackMatchMode {
789 let mut mode = Unknown;
790 for pat in &arm.pats {
791 self.determine_pat_move_mode(discr_cmt.clone(), &pat, &mut mode);
796 fn walk_arm(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm, mode: MatchMode) {
797 for pat in &arm.pats {
798 self.walk_pat(discr_cmt.clone(), &pat, mode);
801 if let Some(ref guard) = arm.guard {
802 self.consume_expr(&guard);
805 self.consume_expr(&arm.body);
808 /// Walks a pat that occurs in isolation (i.e. top-level of fn
809 /// arg or let binding. *Not* a match arm or nested pat.)
810 fn walk_irrefutable_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat) {
811 let mut mode = Unknown;
812 self.determine_pat_move_mode(cmt_discr.clone(), pat, &mut mode);
813 let mode = mode.match_mode();
814 self.walk_pat(cmt_discr, pat, mode);
817 /// Identifies any bindings within `pat` and accumulates within
818 /// `mode` whether the overall pattern/match structure is a move,
820 fn determine_pat_move_mode(&mut self,
821 cmt_discr: mc::cmt<'tcx>,
823 mode: &mut TrackMatchMode) {
824 debug!("determine_pat_move_mode cmt_discr={:?} pat={:?}", cmt_discr,
826 return_if_err!(self.mc.cat_pattern(cmt_discr, pat, |cmt_pat, pat| {
827 if let PatKind::Binding(..) = pat.node {
828 let bm = *self.mc.tables.pat_binding_modes().get(pat.hir_id)
829 .expect("missing binding mode");
831 ty::BindByReference(..) =>
832 mode.lub(BorrowingMatch),
833 ty::BindByValue(..) => {
834 match copy_or_move(&self.mc, self.param_env, &cmt_pat, PatBindingMove) {
835 Copy => mode.lub(CopyingMatch),
836 Move(..) => mode.lub(MovingMatch),
844 /// The core driver for walking a pattern; `match_mode` must be
845 /// established up front, e.g. via `determine_pat_move_mode` (see
846 /// also `walk_irrefutable_pat` for patterns that stand alone).
847 fn walk_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat, match_mode: MatchMode) {
848 debug!("walk_pat cmt_discr={:?} pat={:?}", cmt_discr, pat);
850 let ExprUseVisitor { ref mc, ref mut delegate, param_env } = *self;
851 return_if_err!(mc.cat_pattern(cmt_discr.clone(), pat, |cmt_pat, pat| {
852 if let PatKind::Binding(_, canonical_id, ..) = pat.node {
853 debug!("binding cmt_pat={:?} pat={:?} match_mode={:?}", cmt_pat, pat, match_mode);
854 let bm = *mc.tables.pat_binding_modes().get(pat.hir_id)
855 .expect("missing binding mode");
857 // pat_ty: the type of the binding being produced.
858 let pat_ty = return_if_err!(mc.node_ty(pat.hir_id));
860 // Each match binding is effectively an assignment to the
861 // binding being produced.
862 let def = Def::Local(canonical_id);
863 if let Ok(binding_cmt) = mc.cat_def(pat.id, pat.span, pat_ty, def) {
864 delegate.mutate(pat.id, pat.span, binding_cmt, MutateMode::Init);
867 // It is also a borrow or copy/move of the value being matched.
869 ty::BindByReference(m) => {
870 if let ty::TyRef(r, _) = pat_ty.sty {
871 let bk = ty::BorrowKind::from_mutbl(m);
872 delegate.borrow(pat.id, pat.span, cmt_pat, r, bk, RefBinding);
875 ty::BindByValue(..) => {
876 let mode = copy_or_move(mc, param_env, &cmt_pat, PatBindingMove);
877 debug!("walk_pat binding consuming pat");
878 delegate.consume_pat(pat, cmt_pat, mode);
884 // Do a second pass over the pattern, calling `matched_pat` on
885 // the interior nodes (enum variants and structs), as opposed
886 // to the above loop's visit of than the bindings that form
887 // the leaves of the pattern tree structure.
888 return_if_err!(mc.cat_pattern(cmt_discr, pat, |cmt_pat, pat| {
889 let qpath = match pat.node {
890 PatKind::Path(ref qpath) |
891 PatKind::TupleStruct(ref qpath, ..) |
892 PatKind::Struct(ref qpath, ..) => qpath,
895 let def = mc.tables.qpath_def(qpath, pat.hir_id);
897 Def::Variant(variant_did) |
898 Def::VariantCtor(variant_did, ..) => {
899 let downcast_cmt = mc.cat_downcast_if_needed(pat, cmt_pat, variant_did);
901 debug!("variant downcast_cmt={:?} pat={:?}", downcast_cmt, pat);
902 delegate.matched_pat(pat, downcast_cmt, match_mode);
904 Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
905 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => {
906 debug!("struct cmt_pat={:?} pat={:?}", cmt_pat, pat);
907 delegate.matched_pat(pat, cmt_pat, match_mode);
914 fn walk_captures(&mut self, closure_expr: &hir::Expr, fn_decl_span: Span) {
915 debug!("walk_captures({:?})", closure_expr);
917 self.tcx().with_freevars(closure_expr.id, |freevars| {
918 for freevar in freevars {
919 let var_hir_id = self.tcx().hir.node_to_hir_id(freevar.var_id());
920 let closure_def_id = self.tcx().hir.local_def_id(closure_expr.id);
921 let upvar_id = ty::UpvarId {
923 closure_expr_id: closure_def_id.to_local(),
925 let upvar_capture = self.mc.tables.upvar_capture(upvar_id);
926 let cmt_var = return_if_err!(self.cat_captured_var(closure_expr.id,
929 match upvar_capture {
930 ty::UpvarCapture::ByValue => {
931 let mode = copy_or_move(&self.mc,
935 self.delegate.consume(closure_expr.id, freevar.span, cmt_var, mode);
937 ty::UpvarCapture::ByRef(upvar_borrow) => {
938 self.delegate.borrow(closure_expr.id,
943 ClosureCapture(freevar.span));
950 fn cat_captured_var(&mut self,
951 closure_id: ast::NodeId,
953 upvar: &hir::Freevar)
954 -> mc::McResult<mc::cmt<'tcx>> {
955 // Create the cmt for the variable being borrowed, from the
956 // caller's perspective
957 let var_hir_id = self.tcx().hir.node_to_hir_id(upvar.var_id());
958 let var_ty = self.mc.node_ty(var_hir_id)?;
959 self.mc.cat_def(closure_id, closure_span, var_ty, upvar.def)
963 fn copy_or_move<'a, 'gcx, 'tcx>(mc: &mc::MemCategorizationContext<'a, 'gcx, 'tcx>,
964 param_env: ty::ParamEnv<'tcx>,
966 move_reason: MoveReason)
969 if mc.type_moves_by_default(param_env, cmt.ty, cmt.span) {