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 impl<'a, 'gcx, 'tcx> ExprUseVisitor<'a, 'gcx, 'tcx> {
267 pub fn new(delegate: &'a mut (Delegate<'tcx>+'a),
268 region_maps: &'a RegionMaps,
269 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>)
272 ExprUseVisitor::with_options(delegate,
275 mc::MemCategorizationOptions::default())
278 pub fn with_options(delegate: &'a mut (Delegate<'tcx>+'a),
279 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
280 region_maps: &'a RegionMaps,
281 options: mc::MemCategorizationOptions)
285 mc: mc::MemCategorizationContext::with_options(infcx, region_maps, options),
290 pub fn consume_body(&mut self, body: &hir::Body) {
291 debug!("consume_body(body={:?})", body);
293 for arg in &body.arguments {
294 let arg_ty = return_if_err!(self.mc.infcx.node_ty(arg.pat.id));
296 let fn_body_scope_r = self.tcx().node_scope_region(body.value.id);
297 let arg_cmt = self.mc.cat_rvalue(
300 fn_body_scope_r, // Args live only as long as the fn body.
303 self.walk_irrefutable_pat(arg_cmt, &arg.pat);
306 self.consume_expr(&body.value);
309 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
313 fn delegate_consume(&mut self,
314 consume_id: ast::NodeId,
316 cmt: mc::cmt<'tcx>) {
317 debug!("delegate_consume(consume_id={}, cmt={:?})",
320 let mode = copy_or_move(self.mc.infcx, &cmt, DirectRefMove);
321 self.delegate.consume(consume_id, consume_span, cmt, mode);
324 fn consume_exprs(&mut self, exprs: &[hir::Expr]) {
326 self.consume_expr(&expr);
330 pub fn consume_expr(&mut self, expr: &hir::Expr) {
331 debug!("consume_expr(expr={:?})", expr);
333 let cmt = return_if_err!(self.mc.cat_expr(expr));
334 self.delegate_consume(expr.id, expr.span, cmt);
335 self.walk_expr(expr);
338 fn mutate_expr(&mut self,
339 assignment_expr: &hir::Expr,
342 let cmt = return_if_err!(self.mc.cat_expr(expr));
343 self.delegate.mutate(assignment_expr.id, assignment_expr.span, cmt, mode);
344 self.walk_expr(expr);
347 fn borrow_expr(&mut self,
352 debug!("borrow_expr(expr={:?}, r={:?}, bk={:?})",
355 let cmt = return_if_err!(self.mc.cat_expr(expr));
356 self.delegate.borrow(expr.id, expr.span, cmt, r, bk, cause);
361 fn select_from_expr(&mut self, expr: &hir::Expr) {
365 pub fn walk_expr(&mut self, expr: &hir::Expr) {
366 debug!("walk_expr(expr={:?})", expr);
368 self.walk_adjustment(expr);
371 hir::ExprPath(_) => { }
373 hir::ExprType(ref subexpr, _) => {
374 self.walk_expr(&subexpr)
377 hir::ExprUnary(hir::UnDeref, ref base) => { // *base
378 self.select_from_expr(&base);
381 hir::ExprField(ref base, _) => { // base.f
382 self.select_from_expr(&base);
385 hir::ExprTupField(ref base, _) => { // base.<n>
386 self.select_from_expr(&base);
389 hir::ExprIndex(ref lhs, ref rhs) => { // lhs[rhs]
390 self.select_from_expr(&lhs);
391 self.consume_expr(&rhs);
394 hir::ExprCall(ref callee, ref args) => { // callee(args)
395 self.walk_callee(expr, &callee);
396 self.consume_exprs(args);
399 hir::ExprMethodCall(.., ref args) => { // callee.m(args)
400 self.consume_exprs(args);
403 hir::ExprStruct(_, ref fields, ref opt_with) => {
404 self.walk_struct_expr(fields, opt_with);
407 hir::ExprTup(ref exprs) => {
408 self.consume_exprs(exprs);
411 hir::ExprIf(ref cond_expr, ref then_expr, ref opt_else_expr) => {
412 self.consume_expr(&cond_expr);
413 self.walk_expr(&then_expr);
414 if let Some(ref else_expr) = *opt_else_expr {
415 self.consume_expr(&else_expr);
419 hir::ExprMatch(ref discr, ref arms, _) => {
420 let discr_cmt = return_if_err!(self.mc.cat_expr(&discr));
421 let r = self.tcx().types.re_empty;
422 self.borrow_expr(&discr, r, ty::ImmBorrow, MatchDiscriminant);
424 // treatment of the discriminant is handled while walking the arms.
426 let mode = self.arm_move_mode(discr_cmt.clone(), arm);
427 let mode = mode.match_mode();
428 self.walk_arm(discr_cmt.clone(), arm, mode);
432 hir::ExprArray(ref exprs) => {
433 self.consume_exprs(exprs);
436 hir::ExprAddrOf(m, ref base) => { // &base
437 // make sure that the thing we are pointing out stays valid
438 // for the lifetime `scope_r` of the resulting ptr:
439 let expr_ty = return_if_err!(self.mc.infcx.node_ty(expr.id));
440 if let ty::TyRef(r, _) = expr_ty.sty {
441 let bk = ty::BorrowKind::from_mutbl(m);
442 self.borrow_expr(&base, r, bk, AddrOf);
446 hir::ExprInlineAsm(ref ia, ref outputs, ref inputs) => {
447 for (o, output) in ia.outputs.iter().zip(outputs) {
449 self.consume_expr(output);
451 self.mutate_expr(expr, output,
453 MutateMode::WriteAndRead
455 MutateMode::JustWrite
459 self.consume_exprs(inputs);
463 hir::ExprLit(..) => {}
465 hir::ExprLoop(ref blk, _, _) => {
466 self.walk_block(&blk);
469 hir::ExprWhile(ref cond_expr, ref blk, _) => {
470 self.consume_expr(&cond_expr);
471 self.walk_block(&blk);
474 hir::ExprUnary(_, ref lhs) => {
475 self.consume_expr(&lhs);
478 hir::ExprBinary(_, ref lhs, ref rhs) => {
479 self.consume_expr(&lhs);
480 self.consume_expr(&rhs);
483 hir::ExprBlock(ref blk) => {
484 self.walk_block(&blk);
487 hir::ExprBreak(_, ref opt_expr) | hir::ExprRet(ref opt_expr) => {
488 if let Some(ref expr) = *opt_expr {
489 self.consume_expr(&expr);
493 hir::ExprAssign(ref lhs, ref rhs) => {
494 self.mutate_expr(expr, &lhs, MutateMode::JustWrite);
495 self.consume_expr(&rhs);
498 hir::ExprCast(ref base, _) => {
499 self.consume_expr(&base);
502 hir::ExprAssignOp(_, ref lhs, ref rhs) => {
503 if self.mc.infcx.tables.borrow().is_method_call(expr) {
504 self.consume_expr(lhs);
506 self.mutate_expr(expr, &lhs, MutateMode::WriteAndRead);
508 self.consume_expr(&rhs);
511 hir::ExprRepeat(ref base, _) => {
512 self.consume_expr(&base);
515 hir::ExprClosure(.., fn_decl_span) => {
516 self.walk_captures(expr, fn_decl_span)
519 hir::ExprBox(ref base) => {
520 self.consume_expr(&base);
525 fn walk_callee(&mut self, call: &hir::Expr, callee: &hir::Expr) {
526 let callee_ty = return_if_err!(self.mc.infcx.expr_ty_adjusted(callee));
527 debug!("walk_callee: callee={:?} callee_ty={:?}",
529 match callee_ty.sty {
530 ty::TyFnDef(..) | ty::TyFnPtr(_) => {
531 self.consume_expr(callee);
535 let def_id = self.mc.infcx.tables.borrow().type_dependent_defs[&call.id].def_id();
536 match OverloadedCallType::from_method_id(self.tcx(), def_id) {
537 FnMutOverloadedCall => {
538 let call_scope_r = self.tcx().node_scope_region(call.id);
539 self.borrow_expr(callee,
544 FnOverloadedCall => {
545 let call_scope_r = self.tcx().node_scope_region(call.id);
546 self.borrow_expr(callee,
551 FnOnceOverloadedCall => self.consume_expr(callee),
557 fn walk_stmt(&mut self, stmt: &hir::Stmt) {
559 hir::StmtDecl(ref decl, _) => {
561 hir::DeclLocal(ref local) => {
562 self.walk_local(&local);
565 hir::DeclItem(_) => {
566 // we don't visit nested items in this visitor,
567 // only the fn body we were given.
572 hir::StmtExpr(ref expr, _) |
573 hir::StmtSemi(ref expr, _) => {
574 self.consume_expr(&expr);
579 fn walk_local(&mut self, local: &hir::Local) {
582 let delegate = &mut self.delegate;
583 local.pat.each_binding(|_, id, span, _| {
584 delegate.decl_without_init(id, span);
589 // Variable declarations with
590 // initializers are considered
591 // "assigns", which is handled by
593 self.walk_expr(&expr);
594 let init_cmt = return_if_err!(self.mc.cat_expr(&expr));
595 self.walk_irrefutable_pat(init_cmt, &local.pat);
600 /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
601 /// depending on its type.
602 fn walk_block(&mut self, blk: &hir::Block) {
603 debug!("walk_block(blk.id={})", blk.id);
605 for stmt in &blk.stmts {
606 self.walk_stmt(stmt);
609 if let Some(ref tail_expr) = blk.expr {
610 self.consume_expr(&tail_expr);
614 fn walk_struct_expr(&mut self,
615 fields: &[hir::Field],
616 opt_with: &Option<P<hir::Expr>>) {
617 // Consume the expressions supplying values for each field.
618 for field in fields {
619 self.consume_expr(&field.expr);
622 let with_expr = match *opt_with {
627 let with_cmt = return_if_err!(self.mc.cat_expr(&with_expr));
629 // Select just those fields of the `with`
630 // expression that will actually be used
631 match with_cmt.ty.sty {
632 ty::TyAdt(adt, substs) if adt.is_struct() => {
633 // Consume those fields of the with expression that are needed.
634 for with_field in &adt.struct_variant().fields {
635 if !contains_field_named(with_field, fields) {
636 let cmt_field = self.mc.cat_field(
640 with_field.ty(self.tcx(), substs)
642 self.delegate_consume(with_expr.id, with_expr.span, cmt_field);
647 // the base expression should always evaluate to a
648 // struct; however, when EUV is run during typeck, it
649 // may not. This will generate an error earlier in typeck,
650 // so we can just ignore it.
651 if !self.tcx().sess.has_errors() {
654 "with expression doesn't evaluate to a struct");
659 // walk the with expression so that complex expressions
660 // are properly handled.
661 self.walk_expr(with_expr);
663 fn contains_field_named(field: &ty::FieldDef,
664 fields: &[hir::Field])
668 |f| f.name.node == field.name)
672 // Invoke the appropriate delegate calls for anything that gets
673 // consumed or borrowed as part of the automatic adjustment
675 fn walk_adjustment(&mut self, expr: &hir::Expr) {
676 //NOTE(@jroesch): mixed RefCell borrow causes crash
677 let adjustments = self.mc.infcx.tables.borrow().expr_adjustments(expr).to_vec();
678 let mut cmt = return_if_err!(self.mc.cat_expr_unadjusted(expr));
679 for adjustment in adjustments {
680 debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment);
681 match adjustment.kind {
682 adjustment::Adjust::NeverToAny |
683 adjustment::Adjust::ReifyFnPointer |
684 adjustment::Adjust::UnsafeFnPointer |
685 adjustment::Adjust::ClosureFnPointer |
686 adjustment::Adjust::MutToConstPointer |
687 adjustment::Adjust::Unsize => {
688 // Creating a closure/fn-pointer or unsizing consumes
689 // the input and stores it into the resulting rvalue.
690 self.delegate_consume(expr.id, expr.span, cmt.clone());
693 adjustment::Adjust::Deref(None) => {}
695 // Autoderefs for overloaded Deref calls in fact reference
696 // their receiver. That is, if we have `(*x)` where `x`
697 // is of type `Rc<T>`, then this in fact is equivalent to
698 // `x.deref()`. Since `deref()` is declared with `&self`,
699 // this is an autoref of `x`.
700 adjustment::Adjust::Deref(Some(ref deref)) => {
701 let bk = ty::BorrowKind::from_mutbl(deref.mutbl);
702 self.delegate.borrow(expr.id, expr.span, cmt.clone(),
703 deref.region, bk, AutoRef);
706 adjustment::Adjust::Borrow(ref autoref) => {
707 self.walk_autoref(expr, cmt.clone(), autoref);
710 cmt = return_if_err!(self.mc.cat_expr_adjusted(expr, cmt, &adjustment));
714 /// Walks the autoref `autoref` applied to the autoderef'd
715 /// `expr`. `cmt_base` is the mem-categorized form of `expr`
716 /// after all relevant autoderefs have occurred.
717 fn walk_autoref(&mut self,
719 cmt_base: mc::cmt<'tcx>,
720 autoref: &adjustment::AutoBorrow<'tcx>) {
721 debug!("walk_autoref(expr.id={} cmt_base={:?} autoref={:?})",
727 adjustment::AutoBorrow::Ref(r, m) => {
728 self.delegate.borrow(expr.id,
732 ty::BorrowKind::from_mutbl(m),
736 adjustment::AutoBorrow::RawPtr(m) => {
737 debug!("walk_autoref: expr.id={} cmt_base={:?}",
741 // Converting from a &T to *T (or &mut T to *mut T) is
742 // treated as borrowing it for the enclosing temporary
744 let r = self.tcx().node_scope_region(expr.id);
746 self.delegate.borrow(expr.id,
750 ty::BorrowKind::from_mutbl(m),
756 fn arm_move_mode(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm) -> TrackMatchMode {
757 let mut mode = Unknown;
758 for pat in &arm.pats {
759 self.determine_pat_move_mode(discr_cmt.clone(), &pat, &mut mode);
764 fn walk_arm(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm, mode: MatchMode) {
765 for pat in &arm.pats {
766 self.walk_pat(discr_cmt.clone(), &pat, mode);
769 if let Some(ref guard) = arm.guard {
770 self.consume_expr(&guard);
773 self.consume_expr(&arm.body);
776 /// Walks a pat that occurs in isolation (i.e. top-level of fn
777 /// arg or let binding. *Not* a match arm or nested pat.)
778 fn walk_irrefutable_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat) {
779 let mut mode = Unknown;
780 self.determine_pat_move_mode(cmt_discr.clone(), pat, &mut mode);
781 let mode = mode.match_mode();
782 self.walk_pat(cmt_discr, pat, mode);
785 /// Identifies any bindings within `pat` and accumulates within
786 /// `mode` whether the overall pattern/match structure is a move,
788 fn determine_pat_move_mode(&mut self,
789 cmt_discr: mc::cmt<'tcx>,
791 mode: &mut TrackMatchMode) {
792 debug!("determine_pat_move_mode cmt_discr={:?} pat={:?}", cmt_discr,
794 return_if_err!(self.mc.cat_pattern(cmt_discr, pat, |_mc, cmt_pat, pat| {
796 PatKind::Binding(hir::BindByRef(..), ..) =>
797 mode.lub(BorrowingMatch),
798 PatKind::Binding(hir::BindByValue(..), ..) => {
799 match copy_or_move(self.mc.infcx, &cmt_pat, PatBindingMove) {
800 Copy => mode.lub(CopyingMatch),
801 Move(..) => mode.lub(MovingMatch),
809 /// The core driver for walking a pattern; `match_mode` must be
810 /// established up front, e.g. via `determine_pat_move_mode` (see
811 /// also `walk_irrefutable_pat` for patterns that stand alone).
812 fn walk_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat, match_mode: MatchMode) {
813 debug!("walk_pat cmt_discr={:?} pat={:?}", cmt_discr, pat);
815 let tcx = &self.tcx();
817 let infcx = self.mc.infcx;
818 let delegate = &mut self.delegate;
819 return_if_err!(mc.cat_pattern(cmt_discr.clone(), pat, |mc, cmt_pat, pat| {
820 if let PatKind::Binding(bmode, def_id, ..) = pat.node {
821 debug!("binding cmt_pat={:?} pat={:?} match_mode={:?}", cmt_pat, pat, match_mode);
823 // pat_ty: the type of the binding being produced.
824 let pat_ty = return_if_err!(infcx.node_ty(pat.id));
826 // Each match binding is effectively an assignment to the
827 // binding being produced.
828 let def = Def::Local(def_id);
829 if let Ok(binding_cmt) = mc.cat_def(pat.id, pat.span, pat_ty, def) {
830 delegate.mutate(pat.id, pat.span, binding_cmt, MutateMode::Init);
833 // It is also a borrow or copy/move of the value being matched.
835 hir::BindByRef(m) => {
836 if let ty::TyRef(r, _) = pat_ty.sty {
837 let bk = ty::BorrowKind::from_mutbl(m);
838 delegate.borrow(pat.id, pat.span, cmt_pat, r, bk, RefBinding);
841 hir::BindByValue(..) => {
842 let mode = copy_or_move(infcx, &cmt_pat, PatBindingMove);
843 debug!("walk_pat binding consuming pat");
844 delegate.consume_pat(pat, cmt_pat, mode);
850 // Do a second pass over the pattern, calling `matched_pat` on
851 // the interior nodes (enum variants and structs), as opposed
852 // to the above loop's visit of than the bindings that form
853 // the leaves of the pattern tree structure.
854 return_if_err!(mc.cat_pattern(cmt_discr, pat, |mc, cmt_pat, pat| {
855 let qpath = match pat.node {
856 PatKind::Path(ref qpath) |
857 PatKind::TupleStruct(ref qpath, ..) |
858 PatKind::Struct(ref qpath, ..) => qpath,
861 let def = infcx.tables.borrow().qpath_def(qpath, pat.id);
863 Def::Variant(variant_did) |
864 Def::VariantCtor(variant_did, ..) => {
865 let enum_did = tcx.parent_def_id(variant_did).unwrap();
866 let downcast_cmt = if tcx.adt_def(enum_did).is_univariant() {
869 let cmt_pat_ty = cmt_pat.ty;
870 mc.cat_downcast(pat, cmt_pat, cmt_pat_ty, variant_did)
873 debug!("variant downcast_cmt={:?} pat={:?}", downcast_cmt, pat);
874 delegate.matched_pat(pat, downcast_cmt, match_mode);
876 Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
877 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => {
878 debug!("struct cmt_pat={:?} pat={:?}", cmt_pat, pat);
879 delegate.matched_pat(pat, cmt_pat, match_mode);
886 fn walk_captures(&mut self, closure_expr: &hir::Expr, fn_decl_span: Span) {
887 debug!("walk_captures({:?})", closure_expr);
889 self.tcx().with_freevars(closure_expr.id, |freevars| {
890 for freevar in freevars {
891 let def_id = freevar.def.def_id();
892 let id_var = self.tcx().hir.as_local_node_id(def_id).unwrap();
893 let upvar_id = ty::UpvarId { var_id: id_var,
894 closure_expr_id: closure_expr.id };
895 let upvar_capture = self.mc.infcx.upvar_capture(upvar_id).unwrap();
896 let cmt_var = return_if_err!(self.cat_captured_var(closure_expr.id,
899 match upvar_capture {
900 ty::UpvarCapture::ByValue => {
901 let mode = copy_or_move(self.mc.infcx, &cmt_var, CaptureMove);
902 self.delegate.consume(closure_expr.id, freevar.span, cmt_var, mode);
904 ty::UpvarCapture::ByRef(upvar_borrow) => {
905 self.delegate.borrow(closure_expr.id,
910 ClosureCapture(freevar.span));
917 fn cat_captured_var(&mut self,
918 closure_id: ast::NodeId,
921 -> mc::McResult<mc::cmt<'tcx>> {
922 // Create the cmt for the variable being borrowed, from the
923 // caller's perspective
924 let var_id = self.tcx().hir.as_local_node_id(upvar_def.def_id()).unwrap();
925 let var_ty = self.mc.infcx.node_ty(var_id)?;
926 self.mc.cat_def(closure_id, closure_span, var_ty, upvar_def)
930 fn copy_or_move<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
932 move_reason: MoveReason)
935 if infcx.type_moves_by_default(cmt.ty, cmt.span) {