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};
30 use rustc_data_structures::sync::Lrc;
35 use util::nodemap::ItemLocalSet;
37 ///////////////////////////////////////////////////////////////////////////
40 /// This trait defines the callbacks you can expect to receive when
41 /// employing the ExprUseVisitor.
42 pub trait Delegate<'tcx> {
43 // The value found at `cmt` is either copied or moved, depending
46 consume_id: ast::NodeId,
51 // The value found at `cmt` has been determined to match the
52 // pattern binding `matched_pat`, and its subparts are being
53 // copied or moved depending on `mode`. Note that `matched_pat`
54 // is called on all variant/structs in the pattern (i.e., the
55 // interior nodes of the pattern's tree structure) while
56 // consume_pat is called on the binding identifiers in the pattern
57 // (which are leaves of the pattern's tree structure).
59 // Note that variants/structs and identifiers are disjoint; thus
60 // `matched_pat` and `consume_pat` are never both called on the
61 // same input pattern structure (though of `consume_pat` can be
62 // called on a subpart of an input passed to `matched_pat).
63 fn matched_pat(&mut self,
64 matched_pat: &hir::Pat,
68 // The value found at `cmt` is either copied or moved via the
69 // pattern binding `consume_pat`, depending on mode.
70 fn consume_pat(&mut self,
71 consume_pat: &hir::Pat,
75 // The value found at `borrow` is being borrowed at the point
76 // `borrow_id` for the region `loan_region` with kind `bk`.
78 borrow_id: ast::NodeId,
81 loan_region: ty::Region<'tcx>,
83 loan_cause: LoanCause);
85 // The local variable `id` is declared but not initialized.
86 fn decl_without_init(&mut self,
90 // The path at `cmt` is being assigned to.
92 assignment_id: ast::NodeId,
93 assignment_span: Span,
94 assignee_cmt: &mc::cmt_<'tcx>,
98 #[derive(Copy, Clone, PartialEq, Debug)]
100 ClosureCapture(Span),
111 #[derive(Copy, Clone, PartialEq, Debug)]
112 pub enum ConsumeMode {
113 Copy, // reference to x where x has a type that copies
114 Move(MoveReason), // reference to x where x has a type that moves
117 #[derive(Copy, Clone, PartialEq, Debug)]
118 pub enum MoveReason {
124 #[derive(Copy, Clone, PartialEq, Debug)]
132 #[derive(Copy, Clone, PartialEq, Debug)]
133 enum TrackMatchMode {
139 impl TrackMatchMode {
140 // Builds up the whole match mode for a pattern from its constituent
141 // parts. The lattice looks like this:
157 // * `(_, some_int)` pattern is Copying, since
158 // NonBinding + Copying => Copying
160 // * `(some_int, some_box)` pattern is Moving, since
161 // Copying + Moving => Moving
163 // * `(ref x, some_box)` pattern is Conflicting, since
164 // Borrowing + Moving => Conflicting
166 // Note that the `Unknown` and `Conflicting` states are
167 // represented separately from the other more interesting
168 // `Definite` states, which simplifies logic here somewhat.
169 fn lub(&mut self, mode: MatchMode) {
170 *self = match (*self, mode) {
171 // Note that clause order below is very significant.
172 (Unknown, new) => Definite(new),
173 (Definite(old), new) if old == new => Definite(old),
175 (Definite(old), NonBindingMatch) => Definite(old),
176 (Definite(NonBindingMatch), new) => Definite(new),
178 (Definite(old), CopyingMatch) => Definite(old),
179 (Definite(CopyingMatch), new) => Definite(new),
181 (Definite(_), _) => Conflicting,
182 (Conflicting, _) => *self,
186 fn match_mode(&self) -> MatchMode {
188 Unknown => NonBindingMatch,
189 Definite(mode) => mode,
191 // Conservatively return MovingMatch to let the
192 // compiler continue to make progress.
199 #[derive(Copy, Clone, PartialEq, Debug)]
200 pub enum MutateMode {
203 WriteAndRead, // x += y
206 #[derive(Copy, Clone)]
207 enum OverloadedCallType {
210 FnOnceOverloadedCall,
213 impl OverloadedCallType {
214 fn from_trait_id(tcx: TyCtxt<'_, '_, '_>, trait_id: DefId) -> OverloadedCallType {
215 for &(maybe_function_trait, overloaded_call_type) in &[
216 (tcx.lang_items().fn_once_trait(), FnOnceOverloadedCall),
217 (tcx.lang_items().fn_mut_trait(), FnMutOverloadedCall),
218 (tcx.lang_items().fn_trait(), FnOverloadedCall)
220 match maybe_function_trait {
221 Some(function_trait) if function_trait == trait_id => {
222 return overloaded_call_type
228 bug!("overloaded call didn't map to known function trait")
231 fn from_method_id(tcx: TyCtxt<'_, '_, '_>, method_id: DefId) -> OverloadedCallType {
232 let method = tcx.associated_item(method_id);
233 OverloadedCallType::from_trait_id(tcx, method.container.id())
237 ///////////////////////////////////////////////////////////////////////////
238 // The ExprUseVisitor type
240 // This is the code that actually walks the tree.
241 pub struct ExprUseVisitor<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
242 mc: mc::MemCategorizationContext<'a, 'gcx, 'tcx>,
243 delegate: &'a mut dyn Delegate<'tcx>,
244 param_env: ty::ParamEnv<'tcx>,
247 // If the MC 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, 'tcx> ExprUseVisitor<'a, 'tcx, 'tcx> {
267 /// Creates the ExprUseVisitor, configuring it with the various options provided:
269 /// - `delegate` -- who receives the callbacks
270 /// - `param_env` --- parameter environment for trait lookups (esp. pertaining to `Copy`)
271 /// - `region_scope_tree` --- region scope tree for the code being analyzed
272 /// - `tables` --- typeck results for the code being analyzed
273 /// - `rvalue_promotable_map` --- if you care about rvalue promotion, then provide
274 /// the map here (it can be computed with `tcx.rvalue_promotable_map(def_id)`).
275 /// `None` means that rvalues will be given more conservative lifetimes.
277 /// See also `with_infer`, which is used *during* typeck.
278 pub fn new(delegate: &'a mut (dyn Delegate<'tcx>+'a),
279 tcx: TyCtxt<'a, 'tcx, 'tcx>,
280 param_env: ty::ParamEnv<'tcx>,
281 region_scope_tree: &'a region::ScopeTree,
282 tables: &'a ty::TypeckTables<'tcx>,
283 rvalue_promotable_map: Option<Lrc<ItemLocalSet>>)
287 mc: mc::MemCategorizationContext::new(tcx,
290 rvalue_promotable_map),
297 impl<'a, 'gcx, 'tcx> ExprUseVisitor<'a, 'gcx, 'tcx> {
298 pub fn with_infer(delegate: &'a mut (dyn Delegate<'tcx>+'a),
299 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
300 param_env: ty::ParamEnv<'tcx>,
301 region_scope_tree: &'a region::ScopeTree,
302 tables: &'a ty::TypeckTables<'tcx>)
306 mc: mc::MemCategorizationContext::with_infer(infcx, region_scope_tree, tables),
312 pub fn consume_body(&mut self, body: &hir::Body) {
313 debug!("consume_body(body={:?})", body);
315 for arg in &body.arguments {
316 let arg_ty = return_if_err!(self.mc.pat_ty_adjusted(&arg.pat));
317 debug!("consume_body: arg_ty = {:?}", arg_ty);
319 let fn_body_scope_r =
320 self.tcx().mk_region(ty::ReScope(
322 id: body.value.hir_id.local_id,
323 data: region::ScopeData::Node
325 let arg_cmt = Rc::new(self.mc.cat_rvalue(
328 fn_body_scope_r, // Args live only as long as the fn body.
331 self.walk_irrefutable_pat(arg_cmt, &arg.pat);
334 self.consume_expr(&body.value);
337 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
341 fn delegate_consume(&mut self,
342 consume_id: ast::NodeId,
344 cmt: &mc::cmt_<'tcx>) {
345 debug!("delegate_consume(consume_id={}, cmt={:?})",
348 let mode = copy_or_move(&self.mc, self.param_env, cmt, DirectRefMove);
349 self.delegate.consume(consume_id, consume_span, cmt, mode);
352 fn consume_exprs(&mut self, exprs: &[hir::Expr]) {
354 self.consume_expr(&expr);
358 pub fn consume_expr(&mut self, expr: &hir::Expr) {
359 debug!("consume_expr(expr={:?})", expr);
361 let cmt = return_if_err!(self.mc.cat_expr(expr));
362 self.delegate_consume(expr.id, expr.span, &cmt);
363 self.walk_expr(expr);
366 fn mutate_expr(&mut self,
367 assignment_expr: &hir::Expr,
370 let cmt = return_if_err!(self.mc.cat_expr(expr));
371 self.delegate.mutate(assignment_expr.id, assignment_expr.span, &cmt, mode);
372 self.walk_expr(expr);
375 fn borrow_expr(&mut self,
380 debug!("borrow_expr(expr={:?}, r={:?}, bk={:?})",
383 let cmt = return_if_err!(self.mc.cat_expr(expr));
384 self.delegate.borrow(expr.id, expr.span, &cmt, r, bk, cause);
389 fn select_from_expr(&mut self, expr: &hir::Expr) {
393 pub fn walk_expr(&mut self, expr: &hir::Expr) {
394 debug!("walk_expr(expr={:?})", expr);
396 self.walk_adjustment(expr);
399 hir::ExprKind::Path(_) => { }
401 hir::ExprKind::Type(ref subexpr, _) => {
402 self.walk_expr(&subexpr)
405 hir::ExprKind::Unary(hir::UnDeref, ref base) => { // *base
406 self.select_from_expr(&base);
409 hir::ExprKind::Field(ref base, _) => { // base.f
410 self.select_from_expr(&base);
413 hir::ExprKind::Index(ref lhs, ref rhs) => { // lhs[rhs]
414 self.select_from_expr(&lhs);
415 self.consume_expr(&rhs);
418 hir::ExprKind::Call(ref callee, ref args) => { // callee(args)
419 self.walk_callee(expr, &callee);
420 self.consume_exprs(args);
423 hir::ExprKind::MethodCall(.., ref args) => { // callee.m(args)
424 self.consume_exprs(args);
427 hir::ExprKind::Struct(_, ref fields, ref opt_with) => {
428 self.walk_struct_expr(fields, opt_with);
431 hir::ExprKind::Tup(ref exprs) => {
432 self.consume_exprs(exprs);
435 hir::ExprKind::If(ref cond_expr, ref then_expr, ref opt_else_expr) => {
436 self.consume_expr(&cond_expr);
437 self.walk_expr(&then_expr);
438 if let Some(ref else_expr) = *opt_else_expr {
439 self.consume_expr(&else_expr);
443 hir::ExprKind::Match(ref discr, ref arms, _) => {
444 let discr_cmt = Rc::new(return_if_err!(self.mc.cat_expr(&discr)));
445 let r = self.tcx().types.re_empty;
446 self.borrow_expr(&discr, r, ty::ImmBorrow, MatchDiscriminant);
448 // treatment of the discriminant is handled while walking the arms.
450 let mode = self.arm_move_mode(discr_cmt.clone(), arm);
451 let mode = mode.match_mode();
452 self.walk_arm(discr_cmt.clone(), arm, mode);
456 hir::ExprKind::Array(ref exprs) => {
457 self.consume_exprs(exprs);
460 hir::ExprKind::AddrOf(m, ref base) => { // &base
461 // make sure that the thing we are pointing out stays valid
462 // for the lifetime `scope_r` of the resulting ptr:
463 let expr_ty = return_if_err!(self.mc.expr_ty(expr));
464 if let ty::Ref(r, _, _) = expr_ty.sty {
465 let bk = ty::BorrowKind::from_mutbl(m);
466 self.borrow_expr(&base, r, bk, AddrOf);
470 hir::ExprKind::InlineAsm(ref ia, ref outputs, ref inputs) => {
471 for (o, output) in ia.outputs.iter().zip(outputs) {
473 self.consume_expr(output);
475 self.mutate_expr(expr, output,
477 MutateMode::WriteAndRead
479 MutateMode::JustWrite
483 self.consume_exprs(inputs);
486 hir::ExprKind::Continue(..) |
487 hir::ExprKind::Lit(..) => {}
489 hir::ExprKind::Loop(ref blk, _, _) => {
490 self.walk_block(&blk);
493 hir::ExprKind::While(ref cond_expr, ref blk, _) => {
494 self.consume_expr(&cond_expr);
495 self.walk_block(&blk);
498 hir::ExprKind::Unary(_, ref lhs) => {
499 self.consume_expr(&lhs);
502 hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
503 self.consume_expr(&lhs);
504 self.consume_expr(&rhs);
507 hir::ExprKind::Block(ref blk, _) => {
508 self.walk_block(&blk);
511 hir::ExprKind::Break(_, ref opt_expr) | hir::ExprKind::Ret(ref opt_expr) => {
512 if let Some(ref expr) = *opt_expr {
513 self.consume_expr(&expr);
517 hir::ExprKind::Assign(ref lhs, ref rhs) => {
518 self.mutate_expr(expr, &lhs, MutateMode::JustWrite);
519 self.consume_expr(&rhs);
522 hir::ExprKind::Cast(ref base, _) => {
523 self.consume_expr(&base);
526 hir::ExprKind::AssignOp(_, ref lhs, ref rhs) => {
527 if self.mc.tables.is_method_call(expr) {
528 self.consume_expr(lhs);
530 self.mutate_expr(expr, &lhs, MutateMode::WriteAndRead);
532 self.consume_expr(&rhs);
535 hir::ExprKind::Repeat(ref base, _) => {
536 self.consume_expr(&base);
539 hir::ExprKind::Closure(.., fn_decl_span, _) => {
540 self.walk_captures(expr, fn_decl_span)
543 hir::ExprKind::Box(ref base) => {
544 self.consume_expr(&base);
547 hir::ExprKind::Yield(ref value) => {
548 self.consume_expr(&value);
553 fn walk_callee(&mut self, call: &hir::Expr, callee: &hir::Expr) {
554 let callee_ty = return_if_err!(self.mc.expr_ty_adjusted(callee));
555 debug!("walk_callee: callee={:?} callee_ty={:?}",
557 match callee_ty.sty {
558 ty::FnDef(..) | ty::FnPtr(_) => {
559 self.consume_expr(callee);
563 if let Some(def) = self.mc.tables.type_dependent_defs().get(call.hir_id) {
564 let def_id = def.def_id();
565 let call_scope = region::Scope {
566 id: call.hir_id.local_id,
567 data: region::ScopeData::Node
569 match OverloadedCallType::from_method_id(self.tcx(), def_id) {
570 FnMutOverloadedCall => {
571 let call_scope_r = self.tcx().mk_region(ty::ReScope(call_scope));
572 self.borrow_expr(callee,
577 FnOverloadedCall => {
578 let call_scope_r = self.tcx().mk_region(ty::ReScope(call_scope));
579 self.borrow_expr(callee,
584 FnOnceOverloadedCall => self.consume_expr(callee),
587 self.tcx().sess.delay_span_bug(call.span,
588 "no type-dependent def for overloaded call");
594 fn walk_stmt(&mut self, stmt: &hir::Stmt) {
596 hir::StmtKind::Decl(ref decl, _) => {
598 hir::DeclKind::Local(ref local) => {
599 self.walk_local(&local);
602 hir::DeclKind::Item(_) => {
603 // we don't visit nested items in this visitor,
604 // only the fn body we were given.
609 hir::StmtKind::Expr(ref expr, _) |
610 hir::StmtKind::Semi(ref expr, _) => {
611 self.consume_expr(&expr);
616 fn walk_local(&mut self, local: &hir::Local) {
619 local.pat.each_binding(|_, hir_id, span, _| {
620 let node_id = self.mc.tcx.hir.hir_to_node_id(hir_id);
621 self.delegate.decl_without_init(node_id, span);
626 // Variable declarations with
627 // initializers are considered
628 // "assigns", which is handled by
630 self.walk_expr(&expr);
631 let init_cmt = Rc::new(return_if_err!(self.mc.cat_expr(&expr)));
632 self.walk_irrefutable_pat(init_cmt, &local.pat);
637 /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
638 /// depending on its type.
639 fn walk_block(&mut self, blk: &hir::Block) {
640 debug!("walk_block(blk.id={})", blk.id);
642 for stmt in &blk.stmts {
643 self.walk_stmt(stmt);
646 if let Some(ref tail_expr) = blk.expr {
647 self.consume_expr(&tail_expr);
651 fn walk_struct_expr(&mut self,
652 fields: &[hir::Field],
653 opt_with: &Option<P<hir::Expr>>) {
654 // Consume the expressions supplying values for each field.
655 for field in fields {
656 self.consume_expr(&field.expr);
659 let with_expr = match *opt_with {
664 let with_cmt = Rc::new(return_if_err!(self.mc.cat_expr(&with_expr)));
666 // Select just those fields of the `with`
667 // expression that will actually be used
668 match with_cmt.ty.sty {
669 ty::Adt(adt, substs) if adt.is_struct() => {
670 // Consume those fields of the with expression that are needed.
671 for (f_index, with_field) in adt.non_enum_variant().fields.iter().enumerate() {
672 let is_mentioned = fields.iter().any(|f| {
673 self.tcx().field_index(f.id, self.mc.tables) == f_index
676 let cmt_field = self.mc.cat_field(
681 with_field.ty(self.tcx(), substs)
683 self.delegate_consume(with_expr.id, with_expr.span, &cmt_field);
688 // the base expression should always evaluate to a
689 // struct; however, when EUV is run during typeck, it
690 // may not. This will generate an error earlier in typeck,
691 // so we can just ignore it.
692 if !self.tcx().sess.has_errors() {
695 "with expression doesn't evaluate to a struct");
700 // walk the with expression so that complex expressions
701 // are properly handled.
702 self.walk_expr(with_expr);
705 // Invoke the appropriate delegate calls for anything that gets
706 // consumed or borrowed as part of the automatic adjustment
708 fn walk_adjustment(&mut self, expr: &hir::Expr) {
709 let adjustments = self.mc.tables.expr_adjustments(expr);
710 let mut cmt = return_if_err!(self.mc.cat_expr_unadjusted(expr));
711 for adjustment in adjustments {
712 debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment);
713 match adjustment.kind {
714 adjustment::Adjust::NeverToAny |
715 adjustment::Adjust::ReifyFnPointer |
716 adjustment::Adjust::UnsafeFnPointer |
717 adjustment::Adjust::ClosureFnPointer |
718 adjustment::Adjust::MutToConstPointer |
719 adjustment::Adjust::Unsize => {
720 // Creating a closure/fn-pointer or unsizing consumes
721 // the input and stores it into the resulting rvalue.
722 self.delegate_consume(expr.id, expr.span, &cmt);
725 adjustment::Adjust::Deref(None) => {}
727 // Autoderefs for overloaded Deref calls in fact reference
728 // their receiver. That is, if we have `(*x)` where `x`
729 // is of type `Rc<T>`, then this in fact is equivalent to
730 // `x.deref()`. Since `deref()` is declared with `&self`,
731 // this is an autoref of `x`.
732 adjustment::Adjust::Deref(Some(ref deref)) => {
733 let bk = ty::BorrowKind::from_mutbl(deref.mutbl);
734 self.delegate.borrow(expr.id, expr.span, &cmt, deref.region, bk, AutoRef);
737 adjustment::Adjust::Borrow(ref autoref) => {
738 self.walk_autoref(expr, &cmt, 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.into()),
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(
777 id: expr.hir_id.local_id,
778 data: region::ScopeData::Node
781 self.delegate.borrow(expr.id,
785 ty::BorrowKind::from_mutbl(m),
791 fn arm_move_mode(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm) -> TrackMatchMode {
792 let mut mode = Unknown;
793 for pat in &arm.pats {
794 self.determine_pat_move_mode(discr_cmt.clone(), &pat, &mut mode);
799 fn walk_arm(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm, mode: MatchMode) {
800 for pat in &arm.pats {
801 self.walk_pat(discr_cmt.clone(), &pat, mode);
804 if let Some(ref guard) = arm.guard {
806 hir::Guard::If(ref e) => self.consume_expr(e),
810 self.consume_expr(&arm.body);
813 /// Walks a pat that occurs in isolation (i.e. top-level of fn
814 /// arg or let binding. *Not* a match arm or nested pat.)
815 fn walk_irrefutable_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat) {
816 let mut mode = Unknown;
817 self.determine_pat_move_mode(cmt_discr.clone(), pat, &mut mode);
818 let mode = mode.match_mode();
819 self.walk_pat(cmt_discr, pat, mode);
822 /// Identifies any bindings within `pat` and accumulates within
823 /// `mode` whether the overall pattern/match structure is a move,
825 fn determine_pat_move_mode(&mut self,
826 cmt_discr: mc::cmt<'tcx>,
828 mode: &mut TrackMatchMode) {
829 debug!("determine_pat_move_mode cmt_discr={:?} pat={:?}", cmt_discr,
831 return_if_err!(self.mc.cat_pattern(cmt_discr, pat, |cmt_pat, pat| {
832 if let PatKind::Binding(..) = pat.node {
833 let bm = *self.mc.tables.pat_binding_modes().get(pat.hir_id)
834 .expect("missing binding mode");
836 ty::BindByReference(..) =>
837 mode.lub(BorrowingMatch),
838 ty::BindByValue(..) => {
839 match copy_or_move(&self.mc, self.param_env, &cmt_pat, PatBindingMove) {
840 Copy => mode.lub(CopyingMatch),
841 Move(..) => mode.lub(MovingMatch),
849 /// The core driver for walking a pattern; `match_mode` must be
850 /// established up front, e.g. via `determine_pat_move_mode` (see
851 /// also `walk_irrefutable_pat` for patterns that stand alone).
852 fn walk_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat, match_mode: MatchMode) {
853 debug!("walk_pat(cmt_discr={:?}, pat={:?})", cmt_discr, pat);
855 let tcx = self.tcx();
856 let ExprUseVisitor { ref mc, ref mut delegate, param_env } = *self;
857 return_if_err!(mc.cat_pattern(cmt_discr.clone(), pat, |cmt_pat, pat| {
858 if let PatKind::Binding(_, canonical_id, ..) = pat.node {
860 "walk_pat: binding cmt_pat={:?} pat={:?} match_mode={:?}",
865 if let Some(&bm) = mc.tables.pat_binding_modes().get(pat.hir_id) {
866 debug!("walk_pat: pat.hir_id={:?} bm={:?}", pat.hir_id, bm);
868 // pat_ty: the type of the binding being produced.
869 let pat_ty = return_if_err!(mc.node_ty(pat.hir_id));
870 debug!("walk_pat: pat_ty={:?}", pat_ty);
872 // Each match binding is effectively an assignment to the
873 // binding being produced.
874 let def = Def::Local(canonical_id);
875 if let Ok(ref binding_cmt) = mc.cat_def(pat.hir_id, pat.span, pat_ty, def) {
876 delegate.mutate(pat.id, pat.span, binding_cmt, MutateMode::Init);
879 // It is also a borrow or copy/move of the value being matched.
881 ty::BindByReference(m) => {
882 if let ty::Ref(r, _, _) = pat_ty.sty {
883 let bk = ty::BorrowKind::from_mutbl(m);
884 delegate.borrow(pat.id, pat.span, &cmt_pat, r, bk, RefBinding);
887 ty::BindByValue(..) => {
888 let mode = copy_or_move(mc, param_env, &cmt_pat, PatBindingMove);
889 debug!("walk_pat binding consuming pat");
890 delegate.consume_pat(pat, &cmt_pat, mode);
894 tcx.sess.delay_span_bug(pat.span, "missing binding mode");
899 // Do a second pass over the pattern, calling `matched_pat` on
900 // the interior nodes (enum variants and structs), as opposed
901 // to the above loop's visit of than the bindings that form
902 // the leaves of the pattern tree structure.
903 return_if_err!(mc.cat_pattern(cmt_discr, pat, |cmt_pat, pat| {
904 let qpath = match pat.node {
905 PatKind::Path(ref qpath) |
906 PatKind::TupleStruct(ref qpath, ..) |
907 PatKind::Struct(ref qpath, ..) => qpath,
910 let def = mc.tables.qpath_def(qpath, pat.hir_id);
912 Def::Variant(variant_did) |
913 Def::VariantCtor(variant_did, ..) => {
914 let downcast_cmt = mc.cat_downcast_if_needed(pat, cmt_pat, variant_did);
916 debug!("variant downcast_cmt={:?} pat={:?}", downcast_cmt, pat);
917 delegate.matched_pat(pat, &downcast_cmt, match_mode);
919 Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
920 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => {
921 debug!("struct cmt_pat={:?} pat={:?}", cmt_pat, pat);
922 delegate.matched_pat(pat, &cmt_pat, match_mode);
929 fn walk_captures(&mut self, closure_expr: &hir::Expr, fn_decl_span: Span) {
930 debug!("walk_captures({:?})", closure_expr);
932 self.tcx().with_freevars(closure_expr.id, |freevars| {
933 for freevar in freevars {
934 let var_hir_id = self.tcx().hir.node_to_hir_id(freevar.var_id());
935 let closure_def_id = self.tcx().hir.local_def_id(closure_expr.id);
936 let upvar_id = ty::UpvarId {
938 closure_expr_id: closure_def_id.to_local(),
940 let upvar_capture = self.mc.tables.upvar_capture(upvar_id);
941 let cmt_var = return_if_err!(self.cat_captured_var(closure_expr.hir_id,
944 match upvar_capture {
945 ty::UpvarCapture::ByValue => {
946 let mode = copy_or_move(&self.mc,
950 self.delegate.consume(closure_expr.id, freevar.span, &cmt_var, mode);
952 ty::UpvarCapture::ByRef(upvar_borrow) => {
953 self.delegate.borrow(closure_expr.id,
958 ClosureCapture(freevar.span));
965 fn cat_captured_var(&mut self,
966 closure_hir_id: hir::HirId,
968 upvar: &hir::Freevar)
969 -> mc::McResult<mc::cmt_<'tcx>> {
970 // Create the cmt for the variable being borrowed, from the
971 // caller's perspective
972 let var_hir_id = self.tcx().hir.node_to_hir_id(upvar.var_id());
973 let var_ty = self.mc.node_ty(var_hir_id)?;
974 self.mc.cat_def(closure_hir_id, closure_span, var_ty, upvar.def)
978 fn copy_or_move<'a, 'gcx, 'tcx>(mc: &mc::MemCategorizationContext<'a, 'gcx, 'tcx>,
979 param_env: ty::ParamEnv<'tcx>,
980 cmt: &mc::cmt_<'tcx>,
981 move_reason: MoveReason)
984 if mc.type_moves_by_default(param_env, cmt.ty, cmt.span) {