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>,
245 param_env: ty::ParamEnv<'tcx>,
248 // If the TYPER results in an error, it's because the type check
249 // failed (or will fail, when the error is uncovered and reported
250 // during writeback). In this case, we just ignore this part of the
253 // Note that this macro appears similar to try!(), but, unlike try!(),
254 // it does not propagate the error.
255 macro_rules! return_if_err {
260 debug!("mc reported err");
267 impl<'a, 'gcx, 'tcx> ExprUseVisitor<'a, 'gcx, 'tcx> {
268 pub fn new(delegate: &'a mut (Delegate<'tcx>+'a),
269 region_maps: &'a RegionMaps,
270 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
271 param_env: ty::ParamEnv<'tcx>)
274 ExprUseVisitor::with_options(delegate,
278 mc::MemCategorizationOptions::default())
281 pub fn with_options(delegate: &'a mut (Delegate<'tcx>+'a),
282 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
283 param_env: ty::ParamEnv<'tcx>,
284 region_maps: &'a RegionMaps,
285 options: mc::MemCategorizationOptions)
289 mc: mc::MemCategorizationContext::with_options(infcx, region_maps, options),
295 pub fn consume_body(&mut self, body: &hir::Body) {
296 debug!("consume_body(body={:?})", body);
298 for arg in &body.arguments {
299 let arg_ty = return_if_err!(self.mc.infcx.node_ty(arg.pat.id));
301 let fn_body_scope_r = self.tcx().node_scope_region(body.value.id);
302 let arg_cmt = self.mc.cat_rvalue(
305 fn_body_scope_r, // Args live only as long as the fn body.
309 self.walk_irrefutable_pat(arg_cmt, &arg.pat);
312 self.consume_expr(&body.value);
315 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
319 fn delegate_consume(&mut self,
320 consume_id: ast::NodeId,
322 cmt: mc::cmt<'tcx>) {
323 debug!("delegate_consume(consume_id={}, cmt={:?})",
326 let mode = copy_or_move(self.mc.infcx, self.param_env, &cmt, DirectRefMove);
327 self.delegate.consume(consume_id, consume_span, cmt, mode);
330 fn consume_exprs(&mut self, exprs: &[hir::Expr]) {
332 self.consume_expr(&expr);
336 pub fn consume_expr(&mut self, expr: &hir::Expr) {
337 debug!("consume_expr(expr={:?})", expr);
339 let cmt = return_if_err!(self.mc.cat_expr(expr));
340 self.delegate_consume(expr.id, expr.span, cmt);
341 self.walk_expr(expr);
344 fn mutate_expr(&mut self,
345 assignment_expr: &hir::Expr,
348 let cmt = return_if_err!(self.mc.cat_expr(expr));
349 self.delegate.mutate(assignment_expr.id, assignment_expr.span, cmt, mode);
350 self.walk_expr(expr);
353 fn borrow_expr(&mut self,
358 debug!("borrow_expr(expr={:?}, r={:?}, bk={:?})",
361 let cmt = return_if_err!(self.mc.cat_expr(expr));
362 self.delegate.borrow(expr.id, expr.span, cmt, r, bk, cause);
367 fn select_from_expr(&mut self, expr: &hir::Expr) {
371 pub fn walk_expr(&mut self, expr: &hir::Expr) {
372 debug!("walk_expr(expr={:?})", expr);
374 self.walk_adjustment(expr);
377 hir::ExprPath(_) => { }
379 hir::ExprType(ref subexpr, _) => {
380 self.walk_expr(&subexpr)
383 hir::ExprUnary(hir::UnDeref, ref base) => { // *base
384 self.select_from_expr(&base);
387 hir::ExprField(ref base, _) => { // base.f
388 self.select_from_expr(&base);
391 hir::ExprTupField(ref base, _) => { // base.<n>
392 self.select_from_expr(&base);
395 hir::ExprIndex(ref lhs, ref rhs) => { // lhs[rhs]
396 self.select_from_expr(&lhs);
397 self.consume_expr(&rhs);
400 hir::ExprCall(ref callee, ref args) => { // callee(args)
401 self.walk_callee(expr, &callee);
402 self.consume_exprs(args);
405 hir::ExprMethodCall(.., ref args) => { // callee.m(args)
406 self.consume_exprs(args);
409 hir::ExprStruct(_, ref fields, ref opt_with) => {
410 self.walk_struct_expr(fields, opt_with);
413 hir::ExprTup(ref exprs) => {
414 self.consume_exprs(exprs);
417 hir::ExprIf(ref cond_expr, ref then_expr, ref opt_else_expr) => {
418 self.consume_expr(&cond_expr);
419 self.walk_expr(&then_expr);
420 if let Some(ref else_expr) = *opt_else_expr {
421 self.consume_expr(&else_expr);
425 hir::ExprMatch(ref discr, ref arms, _) => {
426 let discr_cmt = return_if_err!(self.mc.cat_expr(&discr));
427 let r = self.tcx().types.re_empty;
428 self.borrow_expr(&discr, r, ty::ImmBorrow, MatchDiscriminant);
430 // treatment of the discriminant is handled while walking the arms.
432 let mode = self.arm_move_mode(discr_cmt.clone(), arm);
433 let mode = mode.match_mode();
434 self.walk_arm(discr_cmt.clone(), arm, mode);
438 hir::ExprArray(ref exprs) => {
439 self.consume_exprs(exprs);
442 hir::ExprAddrOf(m, ref base) => { // &base
443 // make sure that the thing we are pointing out stays valid
444 // for the lifetime `scope_r` of the resulting ptr:
445 let expr_ty = return_if_err!(self.mc.infcx.node_ty(expr.id));
446 if let ty::TyRef(r, _) = expr_ty.sty {
447 let bk = ty::BorrowKind::from_mutbl(m);
448 self.borrow_expr(&base, r, bk, AddrOf);
452 hir::ExprInlineAsm(ref ia, ref outputs, ref inputs) => {
453 for (o, output) in ia.outputs.iter().zip(outputs) {
455 self.consume_expr(output);
457 self.mutate_expr(expr, output,
459 MutateMode::WriteAndRead
461 MutateMode::JustWrite
465 self.consume_exprs(inputs);
469 hir::ExprLit(..) => {}
471 hir::ExprLoop(ref blk, _, _) => {
472 self.walk_block(&blk);
475 hir::ExprWhile(ref cond_expr, ref blk, _) => {
476 self.consume_expr(&cond_expr);
477 self.walk_block(&blk);
480 hir::ExprUnary(_, ref lhs) => {
481 self.consume_expr(&lhs);
484 hir::ExprBinary(_, ref lhs, ref rhs) => {
485 self.consume_expr(&lhs);
486 self.consume_expr(&rhs);
489 hir::ExprBlock(ref blk) => {
490 self.walk_block(&blk);
493 hir::ExprBreak(_, ref opt_expr) | hir::ExprRet(ref opt_expr) => {
494 if let Some(ref expr) = *opt_expr {
495 self.consume_expr(&expr);
499 hir::ExprAssign(ref lhs, ref rhs) => {
500 self.mutate_expr(expr, &lhs, MutateMode::JustWrite);
501 self.consume_expr(&rhs);
504 hir::ExprCast(ref base, _) => {
505 self.consume_expr(&base);
508 hir::ExprAssignOp(_, ref lhs, ref rhs) => {
509 if self.mc.infcx.tables.borrow().is_method_call(expr) {
510 self.consume_expr(lhs);
512 self.mutate_expr(expr, &lhs, MutateMode::WriteAndRead);
514 self.consume_expr(&rhs);
517 hir::ExprRepeat(ref base, _) => {
518 self.consume_expr(&base);
521 hir::ExprClosure(.., fn_decl_span) => {
522 self.walk_captures(expr, fn_decl_span)
525 hir::ExprBox(ref base) => {
526 self.consume_expr(&base);
531 fn walk_callee(&mut self, call: &hir::Expr, callee: &hir::Expr) {
532 let callee_ty = return_if_err!(self.mc.infcx.expr_ty_adjusted(callee));
533 debug!("walk_callee: callee={:?} callee_ty={:?}",
535 match callee_ty.sty {
536 ty::TyFnDef(..) | ty::TyFnPtr(_) => {
537 self.consume_expr(callee);
541 let def_id = self.mc.infcx.tables.borrow().type_dependent_defs[&call.id].def_id();
542 match OverloadedCallType::from_method_id(self.tcx(), def_id) {
543 FnMutOverloadedCall => {
544 let call_scope_r = self.tcx().node_scope_region(call.id);
545 self.borrow_expr(callee,
550 FnOverloadedCall => {
551 let call_scope_r = self.tcx().node_scope_region(call.id);
552 self.borrow_expr(callee,
557 FnOnceOverloadedCall => self.consume_expr(callee),
563 fn walk_stmt(&mut self, stmt: &hir::Stmt) {
565 hir::StmtDecl(ref decl, _) => {
567 hir::DeclLocal(ref local) => {
568 self.walk_local(&local);
571 hir::DeclItem(_) => {
572 // we don't visit nested items in this visitor,
573 // only the fn body we were given.
578 hir::StmtExpr(ref expr, _) |
579 hir::StmtSemi(ref expr, _) => {
580 self.consume_expr(&expr);
585 fn walk_local(&mut self, local: &hir::Local) {
588 let delegate = &mut self.delegate;
589 local.pat.each_binding(|_, id, span, _| {
590 delegate.decl_without_init(id, span);
595 // Variable declarations with
596 // initializers are considered
597 // "assigns", which is handled by
599 self.walk_expr(&expr);
600 let init_cmt = return_if_err!(self.mc.cat_expr(&expr));
601 self.walk_irrefutable_pat(init_cmt, &local.pat);
606 /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
607 /// depending on its type.
608 fn walk_block(&mut self, blk: &hir::Block) {
609 debug!("walk_block(blk.id={})", blk.id);
611 for stmt in &blk.stmts {
612 self.walk_stmt(stmt);
615 if let Some(ref tail_expr) = blk.expr {
616 self.consume_expr(&tail_expr);
620 fn walk_struct_expr(&mut self,
621 fields: &[hir::Field],
622 opt_with: &Option<P<hir::Expr>>) {
623 // Consume the expressions supplying values for each field.
624 for field in fields {
625 self.consume_expr(&field.expr);
628 let with_expr = match *opt_with {
633 let with_cmt = return_if_err!(self.mc.cat_expr(&with_expr));
635 // Select just those fields of the `with`
636 // expression that will actually be used
637 match with_cmt.ty.sty {
638 ty::TyAdt(adt, substs) if adt.is_struct() => {
639 // Consume those fields of the with expression that are needed.
640 for with_field in &adt.struct_variant().fields {
641 if !contains_field_named(with_field, fields) {
642 let cmt_field = self.mc.cat_field(
646 with_field.ty(self.tcx(), substs)
648 self.delegate_consume(with_expr.id, with_expr.span, cmt_field);
653 // the base expression should always evaluate to a
654 // struct; however, when EUV is run during typeck, it
655 // may not. This will generate an error earlier in typeck,
656 // so we can just ignore it.
657 if !self.tcx().sess.has_errors() {
660 "with expression doesn't evaluate to a struct");
665 // walk the with expression so that complex expressions
666 // are properly handled.
667 self.walk_expr(with_expr);
669 fn contains_field_named(field: &ty::FieldDef,
670 fields: &[hir::Field])
674 |f| f.name.node == field.name)
678 // Invoke the appropriate delegate calls for anything that gets
679 // consumed or borrowed as part of the automatic adjustment
681 fn walk_adjustment(&mut self, expr: &hir::Expr) {
682 //NOTE(@jroesch): mixed RefCell borrow causes crash
683 let adjustments = self.mc.infcx.tables.borrow().expr_adjustments(expr).to_vec();
684 let mut cmt = return_if_err!(self.mc.cat_expr_unadjusted(expr));
685 for adjustment in adjustments {
686 debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment);
687 match adjustment.kind {
688 adjustment::Adjust::NeverToAny |
689 adjustment::Adjust::ReifyFnPointer |
690 adjustment::Adjust::UnsafeFnPointer |
691 adjustment::Adjust::ClosureFnPointer |
692 adjustment::Adjust::MutToConstPointer |
693 adjustment::Adjust::Unsize => {
694 // Creating a closure/fn-pointer or unsizing consumes
695 // the input and stores it into the resulting rvalue.
696 self.delegate_consume(expr.id, expr.span, cmt.clone());
699 adjustment::Adjust::Deref(None) => {}
701 // Autoderefs for overloaded Deref calls in fact reference
702 // their receiver. That is, if we have `(*x)` where `x`
703 // is of type `Rc<T>`, then this in fact is equivalent to
704 // `x.deref()`. Since `deref()` is declared with `&self`,
705 // this is an autoref of `x`.
706 adjustment::Adjust::Deref(Some(ref deref)) => {
707 let bk = ty::BorrowKind::from_mutbl(deref.mutbl);
708 self.delegate.borrow(expr.id, expr.span, cmt.clone(),
709 deref.region, bk, AutoRef);
712 adjustment::Adjust::Borrow(ref autoref) => {
713 self.walk_autoref(expr, cmt.clone(), autoref);
716 cmt = return_if_err!(self.mc.cat_expr_adjusted(expr, cmt, &adjustment));
720 /// Walks the autoref `autoref` applied to the autoderef'd
721 /// `expr`. `cmt_base` is the mem-categorized form of `expr`
722 /// after all relevant autoderefs have occurred.
723 fn walk_autoref(&mut self,
725 cmt_base: mc::cmt<'tcx>,
726 autoref: &adjustment::AutoBorrow<'tcx>) {
727 debug!("walk_autoref(expr.id={} cmt_base={:?} autoref={:?})",
733 adjustment::AutoBorrow::Ref(r, m) => {
734 self.delegate.borrow(expr.id,
738 ty::BorrowKind::from_mutbl(m),
742 adjustment::AutoBorrow::RawPtr(m) => {
743 debug!("walk_autoref: expr.id={} cmt_base={:?}",
747 // Converting from a &T to *T (or &mut T to *mut T) is
748 // treated as borrowing it for the enclosing temporary
750 let r = self.tcx().node_scope_region(expr.id);
752 self.delegate.borrow(expr.id,
756 ty::BorrowKind::from_mutbl(m),
762 fn arm_move_mode(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm) -> TrackMatchMode {
763 let mut mode = Unknown;
764 for pat in &arm.pats {
765 self.determine_pat_move_mode(discr_cmt.clone(), &pat, &mut mode);
770 fn walk_arm(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm, mode: MatchMode) {
771 for pat in &arm.pats {
772 self.walk_pat(discr_cmt.clone(), &pat, mode);
775 if let Some(ref guard) = arm.guard {
776 self.consume_expr(&guard);
779 self.consume_expr(&arm.body);
782 /// Walks a pat that occurs in isolation (i.e. top-level of fn
783 /// arg or let binding. *Not* a match arm or nested pat.)
784 fn walk_irrefutable_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat) {
785 let mut mode = Unknown;
786 self.determine_pat_move_mode(cmt_discr.clone(), pat, &mut mode);
787 let mode = mode.match_mode();
788 self.walk_pat(cmt_discr, pat, mode);
791 /// Identifies any bindings within `pat` and accumulates within
792 /// `mode` whether the overall pattern/match structure is a move,
794 fn determine_pat_move_mode(&mut self,
795 cmt_discr: mc::cmt<'tcx>,
797 mode: &mut TrackMatchMode) {
798 debug!("determine_pat_move_mode cmt_discr={:?} pat={:?}", cmt_discr,
800 return_if_err!(self.mc.cat_pattern(cmt_discr, pat, |_mc, cmt_pat, pat| {
802 PatKind::Binding(hir::BindByRef(..), ..) =>
803 mode.lub(BorrowingMatch),
804 PatKind::Binding(hir::BindByValue(..), ..) => {
805 match copy_or_move(self.mc.infcx, self.param_env, &cmt_pat, PatBindingMove) {
806 Copy => mode.lub(CopyingMatch),
807 Move(..) => mode.lub(MovingMatch),
815 /// The core driver for walking a pattern; `match_mode` must be
816 /// established up front, e.g. via `determine_pat_move_mode` (see
817 /// also `walk_irrefutable_pat` for patterns that stand alone).
818 fn walk_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat, match_mode: MatchMode) {
819 debug!("walk_pat cmt_discr={:?} pat={:?}", cmt_discr, pat);
821 let tcx = self.tcx();
822 let infcx = self.mc.infcx;
823 let ExprUseVisitor { ref mc, ref mut delegate, param_env } = *self;
824 return_if_err!(mc.cat_pattern(cmt_discr.clone(), pat, |mc, cmt_pat, pat| {
825 if let PatKind::Binding(bmode, def_id, ..) = pat.node {
826 debug!("binding cmt_pat={:?} pat={:?} match_mode={:?}", cmt_pat, pat, match_mode);
828 // pat_ty: the type of the binding being produced.
829 let pat_ty = return_if_err!(infcx.node_ty(pat.id));
831 // Each match binding is effectively an assignment to the
832 // binding being produced.
833 let def = Def::Local(def_id);
834 if let Ok(binding_cmt) = mc.cat_def(pat.id, pat.span, pat_ty, def) {
835 delegate.mutate(pat.id, pat.span, binding_cmt, MutateMode::Init);
838 // It is also a borrow or copy/move of the value being matched.
840 hir::BindByRef(m) => {
841 if let ty::TyRef(r, _) = pat_ty.sty {
842 let bk = ty::BorrowKind::from_mutbl(m);
843 delegate.borrow(pat.id, pat.span, cmt_pat, r, bk, RefBinding);
846 hir::BindByValue(..) => {
847 let mode = copy_or_move(infcx, param_env, &cmt_pat, PatBindingMove);
848 debug!("walk_pat binding consuming pat");
849 delegate.consume_pat(pat, cmt_pat, mode);
855 // Do a second pass over the pattern, calling `matched_pat` on
856 // the interior nodes (enum variants and structs), as opposed
857 // to the above loop's visit of than the bindings that form
858 // the leaves of the pattern tree structure.
859 return_if_err!(mc.cat_pattern(cmt_discr, pat, |mc, cmt_pat, pat| {
860 let qpath = match pat.node {
861 PatKind::Path(ref qpath) |
862 PatKind::TupleStruct(ref qpath, ..) |
863 PatKind::Struct(ref qpath, ..) => qpath,
866 let def = infcx.tables.borrow().qpath_def(qpath, pat.id);
868 Def::Variant(variant_did) |
869 Def::VariantCtor(variant_did, ..) => {
870 let enum_did = tcx.parent_def_id(variant_did).unwrap();
871 let downcast_cmt = if tcx.adt_def(enum_did).is_univariant() {
874 let cmt_pat_ty = cmt_pat.ty;
875 mc.cat_downcast(pat, cmt_pat, cmt_pat_ty, variant_did)
878 debug!("variant downcast_cmt={:?} pat={:?}", downcast_cmt, pat);
879 delegate.matched_pat(pat, downcast_cmt, match_mode);
881 Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
882 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => {
883 debug!("struct cmt_pat={:?} pat={:?}", cmt_pat, pat);
884 delegate.matched_pat(pat, cmt_pat, match_mode);
891 fn walk_captures(&mut self, closure_expr: &hir::Expr, fn_decl_span: Span) {
892 debug!("walk_captures({:?})", closure_expr);
894 self.tcx().with_freevars(closure_expr.id, |freevars| {
895 for freevar in freevars {
896 let def_id = freevar.def.def_id();
897 let id_var = self.tcx().hir.as_local_node_id(def_id).unwrap();
898 let upvar_id = ty::UpvarId { var_id: id_var,
899 closure_expr_id: closure_expr.id };
900 let upvar_capture = self.mc.infcx.upvar_capture(upvar_id).unwrap();
901 let cmt_var = return_if_err!(self.cat_captured_var(closure_expr.id,
904 match upvar_capture {
905 ty::UpvarCapture::ByValue => {
906 let mode = copy_or_move(self.mc.infcx,
910 self.delegate.consume(closure_expr.id, freevar.span, cmt_var, mode);
912 ty::UpvarCapture::ByRef(upvar_borrow) => {
913 self.delegate.borrow(closure_expr.id,
918 ClosureCapture(freevar.span));
925 fn cat_captured_var(&mut self,
926 closure_id: ast::NodeId,
929 -> mc::McResult<mc::cmt<'tcx>> {
930 // Create the cmt for the variable being borrowed, from the
931 // caller's perspective
932 let var_id = self.tcx().hir.as_local_node_id(upvar_def.def_id()).unwrap();
933 let var_ty = self.mc.infcx.node_ty(var_id)?;
934 self.mc.cat_def(closure_id, closure_span, var_ty, upvar_def)
938 fn copy_or_move<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
939 param_env: ty::ParamEnv<'tcx>,
941 move_reason: MoveReason)
944 if infcx.type_moves_by_default(param_env, cmt.ty, cmt.span) {