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.
239 pub struct ExprUseVisitor<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
240 mc: mc::MemCategorizationContext<'a, 'gcx, 'tcx>,
241 delegate: &'a mut Delegate<'tcx>,
242 param_env: ty::ParamEnv<'tcx>,
245 // If the MC results in an error, it's because the type check
246 // failed (or will fail, when the error is uncovered and reported
247 // during writeback). In this case, we just ignore this part of the
250 // Note that this macro appears similar to try!(), but, unlike try!(),
251 // it does not propagate the error.
252 macro_rules! return_if_err {
257 debug!("mc reported err");
264 impl<'a, 'gcx, 'tcx> ExprUseVisitor<'a, 'gcx, 'tcx> {
265 pub fn new(delegate: &'a mut (Delegate<'tcx>+'a),
266 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
267 param_env: ty::ParamEnv<'tcx>,
268 region_maps: &'a RegionMaps,
269 tables: &'a ty::TypeckTables<'tcx>)
273 mc: mc::MemCategorizationContext::new(infcx, region_maps, tables),
279 pub fn consume_body(&mut self, body: &hir::Body) {
280 debug!("consume_body(body={:?})", body);
282 for arg in &body.arguments {
283 let arg_ty = return_if_err!(self.mc.node_ty(arg.pat.id));
285 let fn_body_scope_r = self.tcx().node_scope_region(body.value.id);
286 let arg_cmt = self.mc.cat_rvalue(
289 fn_body_scope_r, // Args live only as long as the fn body.
292 self.walk_irrefutable_pat(arg_cmt, &arg.pat);
295 self.consume_expr(&body.value);
298 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
302 fn delegate_consume(&mut self,
303 consume_id: ast::NodeId,
305 cmt: mc::cmt<'tcx>) {
306 debug!("delegate_consume(consume_id={}, cmt={:?})",
309 let mode = copy_or_move(self.mc.infcx, self.param_env, &cmt, DirectRefMove);
310 self.delegate.consume(consume_id, consume_span, cmt, mode);
313 fn consume_exprs(&mut self, exprs: &[hir::Expr]) {
315 self.consume_expr(&expr);
319 pub fn consume_expr(&mut self, expr: &hir::Expr) {
320 debug!("consume_expr(expr={:?})", expr);
322 let cmt = return_if_err!(self.mc.cat_expr(expr));
323 self.delegate_consume(expr.id, expr.span, cmt);
324 self.walk_expr(expr);
327 fn mutate_expr(&mut self,
328 assignment_expr: &hir::Expr,
331 let cmt = return_if_err!(self.mc.cat_expr(expr));
332 self.delegate.mutate(assignment_expr.id, assignment_expr.span, cmt, mode);
333 self.walk_expr(expr);
336 fn borrow_expr(&mut self,
341 debug!("borrow_expr(expr={:?}, r={:?}, bk={:?})",
344 let cmt = return_if_err!(self.mc.cat_expr(expr));
345 self.delegate.borrow(expr.id, expr.span, cmt, r, bk, cause);
350 fn select_from_expr(&mut self, expr: &hir::Expr) {
354 pub fn walk_expr(&mut self, expr: &hir::Expr) {
355 debug!("walk_expr(expr={:?})", expr);
357 self.walk_adjustment(expr);
360 hir::ExprPath(_) => { }
362 hir::ExprType(ref subexpr, _) => {
363 self.walk_expr(&subexpr)
366 hir::ExprUnary(hir::UnDeref, ref base) => { // *base
367 self.select_from_expr(&base);
370 hir::ExprField(ref base, _) => { // base.f
371 self.select_from_expr(&base);
374 hir::ExprTupField(ref base, _) => { // base.<n>
375 self.select_from_expr(&base);
378 hir::ExprIndex(ref lhs, ref rhs) => { // lhs[rhs]
379 self.select_from_expr(&lhs);
380 self.consume_expr(&rhs);
383 hir::ExprCall(ref callee, ref args) => { // callee(args)
384 self.walk_callee(expr, &callee);
385 self.consume_exprs(args);
388 hir::ExprMethodCall(.., ref args) => { // callee.m(args)
389 self.consume_exprs(args);
392 hir::ExprStruct(_, ref fields, ref opt_with) => {
393 self.walk_struct_expr(fields, opt_with);
396 hir::ExprTup(ref exprs) => {
397 self.consume_exprs(exprs);
400 hir::ExprIf(ref cond_expr, ref then_expr, ref opt_else_expr) => {
401 self.consume_expr(&cond_expr);
402 self.walk_expr(&then_expr);
403 if let Some(ref else_expr) = *opt_else_expr {
404 self.consume_expr(&else_expr);
408 hir::ExprMatch(ref discr, ref arms, _) => {
409 let discr_cmt = return_if_err!(self.mc.cat_expr(&discr));
410 let r = self.tcx().types.re_empty;
411 self.borrow_expr(&discr, r, ty::ImmBorrow, MatchDiscriminant);
413 // treatment of the discriminant is handled while walking the arms.
415 let mode = self.arm_move_mode(discr_cmt.clone(), arm);
416 let mode = mode.match_mode();
417 self.walk_arm(discr_cmt.clone(), arm, mode);
421 hir::ExprArray(ref exprs) => {
422 self.consume_exprs(exprs);
425 hir::ExprAddrOf(m, ref base) => { // &base
426 // make sure that the thing we are pointing out stays valid
427 // for the lifetime `scope_r` of the resulting ptr:
428 let expr_ty = return_if_err!(self.mc.expr_ty(expr));
429 if let ty::TyRef(r, _) = expr_ty.sty {
430 let bk = ty::BorrowKind::from_mutbl(m);
431 self.borrow_expr(&base, r, bk, AddrOf);
435 hir::ExprInlineAsm(ref ia, ref outputs, ref inputs) => {
436 for (o, output) in ia.outputs.iter().zip(outputs) {
438 self.consume_expr(output);
440 self.mutate_expr(expr, output,
442 MutateMode::WriteAndRead
444 MutateMode::JustWrite
448 self.consume_exprs(inputs);
452 hir::ExprLit(..) => {}
454 hir::ExprLoop(ref blk, _, _) => {
455 self.walk_block(&blk);
458 hir::ExprWhile(ref cond_expr, ref blk, _) => {
459 self.consume_expr(&cond_expr);
460 self.walk_block(&blk);
463 hir::ExprUnary(_, ref lhs) => {
464 self.consume_expr(&lhs);
467 hir::ExprBinary(_, ref lhs, ref rhs) => {
468 self.consume_expr(&lhs);
469 self.consume_expr(&rhs);
472 hir::ExprBlock(ref blk) => {
473 self.walk_block(&blk);
476 hir::ExprBreak(_, ref opt_expr) | hir::ExprRet(ref opt_expr) => {
477 if let Some(ref expr) = *opt_expr {
478 self.consume_expr(&expr);
482 hir::ExprAssign(ref lhs, ref rhs) => {
483 self.mutate_expr(expr, &lhs, MutateMode::JustWrite);
484 self.consume_expr(&rhs);
487 hir::ExprCast(ref base, _) => {
488 self.consume_expr(&base);
491 hir::ExprAssignOp(_, ref lhs, ref rhs) => {
492 if self.mc.tables.is_method_call(expr) {
493 self.consume_expr(lhs);
495 self.mutate_expr(expr, &lhs, MutateMode::WriteAndRead);
497 self.consume_expr(&rhs);
500 hir::ExprRepeat(ref base, _) => {
501 self.consume_expr(&base);
504 hir::ExprClosure(.., fn_decl_span) => {
505 self.walk_captures(expr, fn_decl_span)
508 hir::ExprBox(ref base) => {
509 self.consume_expr(&base);
514 fn walk_callee(&mut self, call: &hir::Expr, callee: &hir::Expr) {
515 let callee_ty = return_if_err!(self.mc.expr_ty_adjusted(callee));
516 debug!("walk_callee: callee={:?} callee_ty={:?}",
518 match callee_ty.sty {
519 ty::TyFnDef(..) | ty::TyFnPtr(_) => {
520 self.consume_expr(callee);
524 let def_id = self.mc.tables.type_dependent_defs[&call.id].def_id();
525 match OverloadedCallType::from_method_id(self.tcx(), def_id) {
526 FnMutOverloadedCall => {
527 let call_scope_r = self.tcx().node_scope_region(call.id);
528 self.borrow_expr(callee,
533 FnOverloadedCall => {
534 let call_scope_r = self.tcx().node_scope_region(call.id);
535 self.borrow_expr(callee,
540 FnOnceOverloadedCall => self.consume_expr(callee),
546 fn walk_stmt(&mut self, stmt: &hir::Stmt) {
548 hir::StmtDecl(ref decl, _) => {
550 hir::DeclLocal(ref local) => {
551 self.walk_local(&local);
554 hir::DeclItem(_) => {
555 // we don't visit nested items in this visitor,
556 // only the fn body we were given.
561 hir::StmtExpr(ref expr, _) |
562 hir::StmtSemi(ref expr, _) => {
563 self.consume_expr(&expr);
568 fn walk_local(&mut self, local: &hir::Local) {
571 let delegate = &mut self.delegate;
572 local.pat.each_binding(|_, id, span, _| {
573 delegate.decl_without_init(id, span);
578 // Variable declarations with
579 // initializers are considered
580 // "assigns", which is handled by
582 self.walk_expr(&expr);
583 let init_cmt = return_if_err!(self.mc.cat_expr(&expr));
584 self.walk_irrefutable_pat(init_cmt, &local.pat);
589 /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
590 /// depending on its type.
591 fn walk_block(&mut self, blk: &hir::Block) {
592 debug!("walk_block(blk.id={})", blk.id);
594 for stmt in &blk.stmts {
595 self.walk_stmt(stmt);
598 if let Some(ref tail_expr) = blk.expr {
599 self.consume_expr(&tail_expr);
603 fn walk_struct_expr(&mut self,
604 fields: &[hir::Field],
605 opt_with: &Option<P<hir::Expr>>) {
606 // Consume the expressions supplying values for each field.
607 for field in fields {
608 self.consume_expr(&field.expr);
611 let with_expr = match *opt_with {
616 let with_cmt = return_if_err!(self.mc.cat_expr(&with_expr));
618 // Select just those fields of the `with`
619 // expression that will actually be used
620 match with_cmt.ty.sty {
621 ty::TyAdt(adt, substs) if adt.is_struct() => {
622 // Consume those fields of the with expression that are needed.
623 for with_field in &adt.struct_variant().fields {
624 if !contains_field_named(with_field, fields) {
625 let cmt_field = self.mc.cat_field(
629 with_field.ty(self.tcx(), substs)
631 self.delegate_consume(with_expr.id, with_expr.span, cmt_field);
636 // the base expression should always evaluate to a
637 // struct; however, when EUV is run during typeck, it
638 // may not. This will generate an error earlier in typeck,
639 // so we can just ignore it.
640 if !self.tcx().sess.has_errors() {
643 "with expression doesn't evaluate to a struct");
648 // walk the with expression so that complex expressions
649 // are properly handled.
650 self.walk_expr(with_expr);
652 fn contains_field_named(field: &ty::FieldDef,
653 fields: &[hir::Field])
657 |f| f.name.node == field.name)
661 // Invoke the appropriate delegate calls for anything that gets
662 // consumed or borrowed as part of the automatic adjustment
664 fn walk_adjustment(&mut self, expr: &hir::Expr) {
665 let adjustments = self.mc.tables.expr_adjustments(expr);
666 let mut cmt = return_if_err!(self.mc.cat_expr_unadjusted(expr));
667 for adjustment in adjustments {
668 debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment);
669 match adjustment.kind {
670 adjustment::Adjust::NeverToAny |
671 adjustment::Adjust::ReifyFnPointer |
672 adjustment::Adjust::UnsafeFnPointer |
673 adjustment::Adjust::ClosureFnPointer |
674 adjustment::Adjust::MutToConstPointer |
675 adjustment::Adjust::Unsize => {
676 // Creating a closure/fn-pointer or unsizing consumes
677 // the input and stores it into the resulting rvalue.
678 self.delegate_consume(expr.id, expr.span, cmt.clone());
681 adjustment::Adjust::Deref(None) => {}
683 // Autoderefs for overloaded Deref calls in fact reference
684 // their receiver. That is, if we have `(*x)` where `x`
685 // is of type `Rc<T>`, then this in fact is equivalent to
686 // `x.deref()`. Since `deref()` is declared with `&self`,
687 // this is an autoref of `x`.
688 adjustment::Adjust::Deref(Some(ref deref)) => {
689 let bk = ty::BorrowKind::from_mutbl(deref.mutbl);
690 self.delegate.borrow(expr.id, expr.span, cmt.clone(),
691 deref.region, bk, AutoRef);
694 adjustment::Adjust::Borrow(ref autoref) => {
695 self.walk_autoref(expr, cmt.clone(), autoref);
698 cmt = return_if_err!(self.mc.cat_expr_adjusted(expr, cmt, &adjustment));
702 /// Walks the autoref `autoref` applied to the autoderef'd
703 /// `expr`. `cmt_base` is the mem-categorized form of `expr`
704 /// after all relevant autoderefs have occurred.
705 fn walk_autoref(&mut self,
707 cmt_base: mc::cmt<'tcx>,
708 autoref: &adjustment::AutoBorrow<'tcx>) {
709 debug!("walk_autoref(expr.id={} cmt_base={:?} autoref={:?})",
715 adjustment::AutoBorrow::Ref(r, m) => {
716 self.delegate.borrow(expr.id,
720 ty::BorrowKind::from_mutbl(m),
724 adjustment::AutoBorrow::RawPtr(m) => {
725 debug!("walk_autoref: expr.id={} cmt_base={:?}",
729 // Converting from a &T to *T (or &mut T to *mut T) is
730 // treated as borrowing it for the enclosing temporary
732 let r = self.tcx().node_scope_region(expr.id);
734 self.delegate.borrow(expr.id,
738 ty::BorrowKind::from_mutbl(m),
744 fn arm_move_mode(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm) -> TrackMatchMode {
745 let mut mode = Unknown;
746 for pat in &arm.pats {
747 self.determine_pat_move_mode(discr_cmt.clone(), &pat, &mut mode);
752 fn walk_arm(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm, mode: MatchMode) {
753 for pat in &arm.pats {
754 self.walk_pat(discr_cmt.clone(), &pat, mode);
757 if let Some(ref guard) = arm.guard {
758 self.consume_expr(&guard);
761 self.consume_expr(&arm.body);
764 /// Walks a pat that occurs in isolation (i.e. top-level of fn
765 /// arg or let binding. *Not* a match arm or nested pat.)
766 fn walk_irrefutable_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat) {
767 let mut mode = Unknown;
768 self.determine_pat_move_mode(cmt_discr.clone(), pat, &mut mode);
769 let mode = mode.match_mode();
770 self.walk_pat(cmt_discr, pat, mode);
773 /// Identifies any bindings within `pat` and accumulates within
774 /// `mode` whether the overall pattern/match structure is a move,
776 fn determine_pat_move_mode(&mut self,
777 cmt_discr: mc::cmt<'tcx>,
779 mode: &mut TrackMatchMode) {
780 debug!("determine_pat_move_mode cmt_discr={:?} pat={:?}", cmt_discr,
782 return_if_err!(self.mc.cat_pattern(cmt_discr, pat, |cmt_pat, pat| {
784 PatKind::Binding(hir::BindByRef(..), ..) =>
785 mode.lub(BorrowingMatch),
786 PatKind::Binding(hir::BindByValue(..), ..) => {
787 match copy_or_move(self.mc.infcx, self.param_env, &cmt_pat, PatBindingMove) {
788 Copy => mode.lub(CopyingMatch),
789 Move(..) => mode.lub(MovingMatch),
797 /// The core driver for walking a pattern; `match_mode` must be
798 /// established up front, e.g. via `determine_pat_move_mode` (see
799 /// also `walk_irrefutable_pat` for patterns that stand alone).
800 fn walk_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat, match_mode: MatchMode) {
801 debug!("walk_pat cmt_discr={:?} pat={:?}", cmt_discr, pat);
803 let tcx = self.tcx();
804 let infcx = self.mc.infcx;
805 let ExprUseVisitor { ref mc, ref mut delegate, param_env } = *self;
806 return_if_err!(mc.cat_pattern(cmt_discr.clone(), pat, |cmt_pat, pat| {
807 if let PatKind::Binding(bmode, def_id, ..) = pat.node {
808 debug!("binding cmt_pat={:?} pat={:?} match_mode={:?}", cmt_pat, pat, match_mode);
810 // pat_ty: the type of the binding being produced.
811 let pat_ty = return_if_err!(mc.node_ty(pat.id));
813 // Each match binding is effectively an assignment to the
814 // binding being produced.
815 let def = Def::Local(def_id);
816 if let Ok(binding_cmt) = mc.cat_def(pat.id, pat.span, pat_ty, def) {
817 delegate.mutate(pat.id, pat.span, binding_cmt, MutateMode::Init);
820 // It is also a borrow or copy/move of the value being matched.
822 hir::BindByRef(m) => {
823 if let ty::TyRef(r, _) = pat_ty.sty {
824 let bk = ty::BorrowKind::from_mutbl(m);
825 delegate.borrow(pat.id, pat.span, cmt_pat, r, bk, RefBinding);
828 hir::BindByValue(..) => {
829 let mode = copy_or_move(infcx, param_env, &cmt_pat, PatBindingMove);
830 debug!("walk_pat binding consuming pat");
831 delegate.consume_pat(pat, cmt_pat, mode);
837 // Do a second pass over the pattern, calling `matched_pat` on
838 // the interior nodes (enum variants and structs), as opposed
839 // to the above loop's visit of than the bindings that form
840 // the leaves of the pattern tree structure.
841 return_if_err!(mc.cat_pattern(cmt_discr, pat, |cmt_pat, pat| {
842 let qpath = match pat.node {
843 PatKind::Path(ref qpath) |
844 PatKind::TupleStruct(ref qpath, ..) |
845 PatKind::Struct(ref qpath, ..) => qpath,
848 let def = mc.tables.qpath_def(qpath, pat.id);
850 Def::Variant(variant_did) |
851 Def::VariantCtor(variant_did, ..) => {
852 let enum_did = tcx.parent_def_id(variant_did).unwrap();
853 let downcast_cmt = if tcx.adt_def(enum_did).is_univariant() {
856 let cmt_pat_ty = cmt_pat.ty;
857 mc.cat_downcast(pat, cmt_pat, cmt_pat_ty, variant_did)
860 debug!("variant downcast_cmt={:?} pat={:?}", downcast_cmt, pat);
861 delegate.matched_pat(pat, downcast_cmt, match_mode);
863 Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
864 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => {
865 debug!("struct cmt_pat={:?} pat={:?}", cmt_pat, pat);
866 delegate.matched_pat(pat, cmt_pat, match_mode);
873 fn walk_captures(&mut self, closure_expr: &hir::Expr, fn_decl_span: Span) {
874 debug!("walk_captures({:?})", closure_expr);
876 self.tcx().with_freevars(closure_expr.id, |freevars| {
877 for freevar in freevars {
878 let def_id = freevar.def.def_id();
879 let id_var = self.tcx().hir.as_local_node_id(def_id).unwrap();
880 let upvar_id = ty::UpvarId { var_id: id_var,
881 closure_expr_id: closure_expr.id };
882 let upvar_capture = self.mc.tables.upvar_capture(upvar_id);
883 let cmt_var = return_if_err!(self.cat_captured_var(closure_expr.id,
886 match upvar_capture {
887 ty::UpvarCapture::ByValue => {
888 let mode = copy_or_move(self.mc.infcx,
892 self.delegate.consume(closure_expr.id, freevar.span, cmt_var, mode);
894 ty::UpvarCapture::ByRef(upvar_borrow) => {
895 self.delegate.borrow(closure_expr.id,
900 ClosureCapture(freevar.span));
907 fn cat_captured_var(&mut self,
908 closure_id: ast::NodeId,
911 -> mc::McResult<mc::cmt<'tcx>> {
912 // Create the cmt for the variable being borrowed, from the
913 // caller's perspective
914 let var_id = self.tcx().hir.as_local_node_id(upvar_def.def_id()).unwrap();
915 let var_ty = self.mc.node_ty(var_id)?;
916 self.mc.cat_def(closure_id, closure_span, var_ty, upvar_def)
920 fn copy_or_move<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
921 param_env: ty::ParamEnv<'tcx>,
923 move_reason: MoveReason)
926 if infcx.type_moves_by_default(param_env, cmt.ty, cmt.span) {