1 //! A different sort of visitor for walking fn bodies. Unlike the
2 //! normal visitor, which just walks the entire body in one shot, the
3 //! `ExprUseVisitor` determines how expressions are being used.
5 pub use self::LoanCause::*;
6 pub use self::ConsumeMode::*;
7 pub use self::MoveReason::*;
8 pub use self::MatchMode::*;
9 use self::TrackMatchMode::*;
10 use self::OverloadedCallType::*;
12 use crate::hir::def::Def;
13 use crate::hir::def_id::DefId;
14 use crate::infer::InferCtxt;
15 use crate::middle::mem_categorization as mc;
16 use crate::middle::region;
17 use crate::ty::{self, TyCtxt, adjustment};
19 use crate::hir::{self, PatKind};
20 use rustc_data_structures::sync::Lrc;
24 use crate::util::nodemap::ItemLocalSet;
26 ///////////////////////////////////////////////////////////////////////////
29 /// This trait defines the callbacks you can expect to receive when
30 /// employing the ExprUseVisitor.
31 pub trait Delegate<'tcx> {
32 // The value found at `cmt` is either copied or moved, depending
35 consume_id: hir::HirId,
40 // The value found at `cmt` has been determined to match the
41 // pattern binding `matched_pat`, and its subparts are being
42 // copied or moved depending on `mode`. Note that `matched_pat`
43 // is called on all variant/structs in the pattern (i.e., the
44 // interior nodes of the pattern's tree structure) while
45 // consume_pat is called on the binding identifiers in the pattern
46 // (which are leaves of the pattern's tree structure).
48 // Note that variants/structs and identifiers are disjoint; thus
49 // `matched_pat` and `consume_pat` are never both called on the
50 // same input pattern structure (though of `consume_pat` can be
51 // called on a subpart of an input passed to `matched_pat).
52 fn matched_pat(&mut self,
53 matched_pat: &hir::Pat,
57 // The value found at `cmt` is either copied or moved via the
58 // pattern binding `consume_pat`, depending on mode.
59 fn consume_pat(&mut self,
60 consume_pat: &hir::Pat,
64 // The value found at `borrow` is being borrowed at the point
65 // `borrow_id` for the region `loan_region` with kind `bk`.
67 borrow_id: hir::HirId,
70 loan_region: ty::Region<'tcx>,
72 loan_cause: LoanCause);
74 // The local variable `id` is declared but not initialized.
75 fn decl_without_init(&mut self,
79 // The path at `cmt` is being assigned to.
81 assignment_id: hir::HirId,
82 assignment_span: Span,
83 assignee_cmt: &mc::cmt_<'tcx>,
86 // A nested closure or generator - only one layer deep.
87 fn nested_body(&mut self, _body_id: hir::BodyId) {}
90 #[derive(Copy, Clone, PartialEq, Debug)]
103 #[derive(Copy, Clone, PartialEq, Debug)]
104 pub enum ConsumeMode {
105 Copy, // reference to x where x has a type that copies
106 Move(MoveReason), // reference to x where x has a type that moves
109 #[derive(Copy, Clone, PartialEq, Debug)]
110 pub enum MoveReason {
116 #[derive(Copy, Clone, PartialEq, Debug)]
124 #[derive(Copy, Clone, PartialEq, Debug)]
125 enum TrackMatchMode {
131 impl TrackMatchMode {
132 // Builds up the whole match mode for a pattern from its constituent
133 // parts. The lattice looks like this:
149 // * `(_, some_int)` pattern is Copying, since
150 // NonBinding + Copying => Copying
152 // * `(some_int, some_box)` pattern is Moving, since
153 // Copying + Moving => Moving
155 // * `(ref x, some_box)` pattern is Conflicting, since
156 // Borrowing + Moving => Conflicting
158 // Note that the `Unknown` and `Conflicting` states are
159 // represented separately from the other more interesting
160 // `Definite` states, which simplifies logic here somewhat.
161 fn lub(&mut self, mode: MatchMode) {
162 *self = match (*self, mode) {
163 // Note that clause order below is very significant.
164 (Unknown, new) => Definite(new),
165 (Definite(old), new) if old == new => Definite(old),
167 (Definite(old), NonBindingMatch) => Definite(old),
168 (Definite(NonBindingMatch), new) => Definite(new),
170 (Definite(old), CopyingMatch) => Definite(old),
171 (Definite(CopyingMatch), new) => Definite(new),
173 (Definite(_), _) => Conflicting,
174 (Conflicting, _) => *self,
178 fn match_mode(&self) -> MatchMode {
180 Unknown => NonBindingMatch,
181 Definite(mode) => mode,
183 // Conservatively return MovingMatch to let the
184 // compiler continue to make progress.
191 #[derive(Copy, Clone, PartialEq, Debug)]
192 pub enum MutateMode {
195 WriteAndRead, // x += y
198 #[derive(Copy, Clone)]
199 enum OverloadedCallType {
202 FnOnceOverloadedCall,
205 impl OverloadedCallType {
206 fn from_trait_id(tcx: TyCtxt<'_, '_, '_>, trait_id: DefId) -> OverloadedCallType {
207 for &(maybe_function_trait, overloaded_call_type) in &[
208 (tcx.lang_items().fn_once_trait(), FnOnceOverloadedCall),
209 (tcx.lang_items().fn_mut_trait(), FnMutOverloadedCall),
210 (tcx.lang_items().fn_trait(), FnOverloadedCall)
212 match maybe_function_trait {
213 Some(function_trait) if function_trait == trait_id => {
214 return overloaded_call_type
220 bug!("overloaded call didn't map to known function trait")
223 fn from_method_id(tcx: TyCtxt<'_, '_, '_>, method_id: DefId) -> OverloadedCallType {
224 let method = tcx.associated_item(method_id);
225 OverloadedCallType::from_trait_id(tcx, method.container.id())
229 ///////////////////////////////////////////////////////////////////////////
230 // The ExprUseVisitor type
232 // This is the code that actually walks the tree.
233 pub struct ExprUseVisitor<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
234 mc: mc::MemCategorizationContext<'a, 'gcx, 'tcx>,
235 delegate: &'a mut dyn Delegate<'tcx>,
236 param_env: ty::ParamEnv<'tcx>,
239 // If the MC results in an error, it's because the type check
240 // failed (or will fail, when the error is uncovered and reported
241 // during writeback). In this case, we just ignore this part of the
244 // Note that this macro appears similar to try!(), but, unlike try!(),
245 // it does not propagate the error.
246 macro_rules! return_if_err {
251 debug!("mc reported err");
258 impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx, 'tcx> {
259 /// Creates the ExprUseVisitor, configuring it with the various options provided:
261 /// - `delegate` -- who receives the callbacks
262 /// - `param_env` --- parameter environment for trait lookups (esp. pertaining to `Copy`)
263 /// - `region_scope_tree` --- region scope tree for the code being analyzed
264 /// - `tables` --- typeck results for the code being analyzed
265 /// - `rvalue_promotable_map` --- if you care about rvalue promotion, then provide
266 /// the map here (it can be computed with `tcx.rvalue_promotable_map(def_id)`).
267 /// `None` means that rvalues will be given more conservative lifetimes.
269 /// See also `with_infer`, which is used *during* typeck.
270 pub fn new(delegate: &'a mut (dyn Delegate<'tcx>+'a),
271 tcx: TyCtxt<'a, 'tcx, 'tcx>,
272 param_env: ty::ParamEnv<'tcx>,
273 region_scope_tree: &'a region::ScopeTree,
274 tables: &'a ty::TypeckTables<'tcx>,
275 rvalue_promotable_map: Option<Lrc<ItemLocalSet>>)
279 mc: mc::MemCategorizationContext::new(tcx,
282 rvalue_promotable_map),
289 impl<'a, 'gcx, 'tcx> ExprUseVisitor<'a, 'gcx, 'tcx> {
290 pub fn with_infer(delegate: &'a mut (dyn Delegate<'tcx>+'a),
291 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
292 param_env: ty::ParamEnv<'tcx>,
293 region_scope_tree: &'a region::ScopeTree,
294 tables: &'a ty::TypeckTables<'tcx>)
298 mc: mc::MemCategorizationContext::with_infer(infcx, region_scope_tree, tables),
304 pub fn consume_body(&mut self, body: &hir::Body) {
305 debug!("consume_body(body={:?})", body);
307 for arg in &body.arguments {
308 let arg_ty = return_if_err!(self.mc.pat_ty_adjusted(&arg.pat));
309 debug!("consume_body: arg_ty = {:?}", arg_ty);
311 let fn_body_scope_r =
312 self.tcx().mk_region(ty::ReScope(
314 id: body.value.hir_id.local_id,
315 data: region::ScopeData::Node
317 let arg_cmt = Rc::new(self.mc.cat_rvalue(
320 fn_body_scope_r, // Args live only as long as the fn body.
323 self.walk_irrefutable_pat(arg_cmt, &arg.pat);
326 self.consume_expr(&body.value);
329 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
333 fn delegate_consume(&mut self,
334 consume_id: hir::HirId,
336 cmt: &mc::cmt_<'tcx>) {
337 debug!("delegate_consume(consume_id={}, cmt={:?})",
340 let mode = copy_or_move(&self.mc, self.param_env, cmt, DirectRefMove);
341 self.delegate.consume(consume_id, consume_span, cmt, mode);
344 fn consume_exprs(&mut self, exprs: &[hir::Expr]) {
346 self.consume_expr(&expr);
350 pub fn consume_expr(&mut self, expr: &hir::Expr) {
351 debug!("consume_expr(expr={:?})", expr);
353 let cmt = return_if_err!(self.mc.cat_expr(expr));
354 self.delegate_consume(expr.hir_id, expr.span, &cmt);
355 self.walk_expr(expr);
358 fn mutate_expr(&mut self,
360 assignment_expr: &hir::Expr,
363 let cmt = return_if_err!(self.mc.cat_expr(expr));
364 self.delegate.mutate(assignment_expr.hir_id, span, &cmt, mode);
365 self.walk_expr(expr);
368 fn borrow_expr(&mut self,
373 debug!("borrow_expr(expr={:?}, r={:?}, bk={:?})",
376 let cmt = return_if_err!(self.mc.cat_expr(expr));
377 self.delegate.borrow(expr.hir_id, expr.span, &cmt, r, bk, cause);
382 fn select_from_expr(&mut self, expr: &hir::Expr) {
386 pub fn walk_expr(&mut self, expr: &hir::Expr) {
387 debug!("walk_expr(expr={:?})", expr);
389 self.walk_adjustment(expr);
392 hir::ExprKind::Path(_) => { }
394 hir::ExprKind::Type(ref subexpr, _) => {
395 self.walk_expr(&subexpr)
398 hir::ExprKind::Unary(hir::UnDeref, ref base) => { // *base
399 self.select_from_expr(&base);
402 hir::ExprKind::Field(ref base, _) => { // base.f
403 self.select_from_expr(&base);
406 hir::ExprKind::Index(ref lhs, ref rhs) => { // lhs[rhs]
407 self.select_from_expr(&lhs);
408 self.consume_expr(&rhs);
411 hir::ExprKind::Call(ref callee, ref args) => { // callee(args)
412 self.walk_callee(expr, &callee);
413 self.consume_exprs(args);
416 hir::ExprKind::MethodCall(.., ref args) => { // callee.m(args)
417 self.consume_exprs(args);
420 hir::ExprKind::Struct(_, ref fields, ref opt_with) => {
421 self.walk_struct_expr(fields, opt_with);
424 hir::ExprKind::Tup(ref exprs) => {
425 self.consume_exprs(exprs);
428 hir::ExprKind::If(ref cond_expr, ref then_expr, ref opt_else_expr) => {
429 self.consume_expr(&cond_expr);
430 self.walk_expr(&then_expr);
431 if let Some(ref else_expr) = *opt_else_expr {
432 self.consume_expr(&else_expr);
436 hir::ExprKind::Match(ref discr, ref arms, _) => {
437 let discr_cmt = Rc::new(return_if_err!(self.mc.cat_expr(&discr)));
438 let r = self.tcx().types.re_empty;
439 self.borrow_expr(&discr, r, ty::ImmBorrow, MatchDiscriminant);
441 // treatment of the discriminant is handled while walking the arms.
443 let mode = self.arm_move_mode(discr_cmt.clone(), arm);
444 let mode = mode.match_mode();
445 self.walk_arm(discr_cmt.clone(), arm, mode);
449 hir::ExprKind::Array(ref exprs) => {
450 self.consume_exprs(exprs);
453 hir::ExprKind::AddrOf(m, ref base) => { // &base
454 // make sure that the thing we are pointing out stays valid
455 // for the lifetime `scope_r` of the resulting ptr:
456 let expr_ty = return_if_err!(self.mc.expr_ty(expr));
457 if let ty::Ref(r, _, _) = expr_ty.sty {
458 let bk = ty::BorrowKind::from_mutbl(m);
459 self.borrow_expr(&base, r, bk, AddrOf);
463 hir::ExprKind::InlineAsm(ref ia, ref outputs, ref inputs) => {
464 for (o, output) in ia.outputs.iter().zip(outputs) {
466 self.consume_expr(output);
473 MutateMode::WriteAndRead
475 MutateMode::JustWrite
480 self.consume_exprs(inputs);
483 hir::ExprKind::Continue(..) |
484 hir::ExprKind::Lit(..) |
485 hir::ExprKind::Err => {}
487 hir::ExprKind::Loop(ref blk, _, _) => {
488 self.walk_block(&blk);
491 hir::ExprKind::While(ref cond_expr, ref blk, _) => {
492 self.consume_expr(&cond_expr);
493 self.walk_block(&blk);
496 hir::ExprKind::Unary(_, ref lhs) => {
497 self.consume_expr(&lhs);
500 hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
501 self.consume_expr(&lhs);
502 self.consume_expr(&rhs);
505 hir::ExprKind::Block(ref blk, _) => {
506 self.walk_block(&blk);
509 hir::ExprKind::Break(_, ref opt_expr) | hir::ExprKind::Ret(ref opt_expr) => {
510 if let Some(ref expr) = *opt_expr {
511 self.consume_expr(&expr);
515 hir::ExprKind::Assign(ref lhs, ref rhs) => {
516 self.mutate_expr(expr.span, expr, &lhs, MutateMode::JustWrite);
517 self.consume_expr(&rhs);
520 hir::ExprKind::Cast(ref base, _) => {
521 self.consume_expr(&base);
524 hir::ExprKind::AssignOp(_, ref lhs, ref rhs) => {
525 if self.mc.tables.is_method_call(expr) {
526 self.consume_expr(lhs);
528 self.mutate_expr(expr.span, expr, &lhs, MutateMode::WriteAndRead);
530 self.consume_expr(&rhs);
533 hir::ExprKind::Repeat(ref base, _) => {
534 self.consume_expr(&base);
537 hir::ExprKind::Closure(_, _, body_id, fn_decl_span, _) => {
538 self.delegate.nested_body(body_id);
539 self.walk_captures(expr, fn_decl_span);
542 hir::ExprKind::Box(ref base) => {
543 self.consume_expr(&base);
546 hir::ExprKind::Yield(ref value) => {
547 self.consume_expr(&value);
552 fn walk_callee(&mut self, call: &hir::Expr, callee: &hir::Expr) {
553 let callee_ty = return_if_err!(self.mc.expr_ty_adjusted(callee));
554 debug!("walk_callee: callee={:?} callee_ty={:?}",
556 match callee_ty.sty {
557 ty::FnDef(..) | ty::FnPtr(_) => {
558 self.consume_expr(callee);
562 if let Some(def) = self.mc.tables.type_dependent_defs().get(call.hir_id) {
563 let def_id = def.def_id();
564 let call_scope = region::Scope {
565 id: call.hir_id.local_id,
566 data: region::ScopeData::Node
568 match OverloadedCallType::from_method_id(self.tcx(), def_id) {
569 FnMutOverloadedCall => {
570 let call_scope_r = self.tcx().mk_region(ty::ReScope(call_scope));
571 self.borrow_expr(callee,
576 FnOverloadedCall => {
577 let call_scope_r = self.tcx().mk_region(ty::ReScope(call_scope));
578 self.borrow_expr(callee,
583 FnOnceOverloadedCall => self.consume_expr(callee),
586 self.tcx().sess.delay_span_bug(call.span,
587 "no type-dependent def for overloaded call");
593 fn walk_stmt(&mut self, stmt: &hir::Stmt) {
595 hir::StmtKind::Local(ref local) => {
596 self.walk_local(&local);
599 hir::StmtKind::Item(_) => {
600 // we don't visit nested items in this visitor,
601 // only the fn body we were given.
604 hir::StmtKind::Expr(ref expr) |
605 hir::StmtKind::Semi(ref expr) => {
606 self.consume_expr(&expr);
611 fn walk_local(&mut self, local: &hir::Local) {
614 local.pat.each_binding(|_, hir_id, span, _| {
615 self.delegate.decl_without_init(hir_id, span);
620 // Variable declarations with
621 // initializers are considered
622 // "assigns", which is handled by
624 self.walk_expr(&expr);
625 let init_cmt = Rc::new(return_if_err!(self.mc.cat_expr(&expr)));
626 self.walk_irrefutable_pat(init_cmt, &local.pat);
631 /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
632 /// depending on its type.
633 fn walk_block(&mut self, blk: &hir::Block) {
634 debug!("walk_block(blk.hir_id={})", blk.hir_id);
636 for stmt in &blk.stmts {
637 self.walk_stmt(stmt);
640 if let Some(ref tail_expr) = blk.expr {
641 self.consume_expr(&tail_expr);
645 fn walk_struct_expr(&mut self,
646 fields: &[hir::Field],
647 opt_with: &Option<P<hir::Expr>>) {
648 // Consume the expressions supplying values for each field.
649 for field in fields {
650 self.consume_expr(&field.expr);
653 let with_expr = match *opt_with {
658 let with_cmt = Rc::new(return_if_err!(self.mc.cat_expr(&with_expr)));
660 // Select just those fields of the `with`
661 // expression that will actually be used
662 match with_cmt.ty.sty {
663 ty::Adt(adt, substs) if adt.is_struct() => {
664 // Consume those fields of the with expression that are needed.
665 for (f_index, with_field) in adt.non_enum_variant().fields.iter().enumerate() {
666 let is_mentioned = fields.iter().any(|f| {
667 self.tcx().field_index(f.hir_id, self.mc.tables) == f_index
670 let cmt_field = self.mc.cat_field(
675 with_field.ty(self.tcx(), substs)
677 self.delegate_consume(with_expr.hir_id, with_expr.span, &cmt_field);
682 // the base expression should always evaluate to a
683 // struct; however, when EUV is run during typeck, it
684 // may not. This will generate an error earlier in typeck,
685 // so we can just ignore it.
686 if !self.tcx().sess.has_errors() {
689 "with expression doesn't evaluate to a struct");
694 // walk the with expression so that complex expressions
695 // are properly handled.
696 self.walk_expr(with_expr);
699 // Invoke the appropriate delegate calls for anything that gets
700 // consumed or borrowed as part of the automatic adjustment
702 fn walk_adjustment(&mut self, expr: &hir::Expr) {
703 let adjustments = self.mc.tables.expr_adjustments(expr);
704 let mut cmt = return_if_err!(self.mc.cat_expr_unadjusted(expr));
705 for adjustment in adjustments {
706 debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment);
707 match adjustment.kind {
708 adjustment::Adjust::NeverToAny |
709 adjustment::Adjust::ReifyFnPointer |
710 adjustment::Adjust::UnsafeFnPointer |
711 adjustment::Adjust::ClosureFnPointer |
712 adjustment::Adjust::MutToConstPointer |
713 adjustment::Adjust::Unsize => {
714 // Creating a closure/fn-pointer or unsizing consumes
715 // the input and stores it into the resulting rvalue.
716 self.delegate_consume(expr.hir_id, expr.span, &cmt);
719 adjustment::Adjust::Deref(None) => {}
721 // Autoderefs for overloaded Deref calls in fact reference
722 // their receiver. That is, if we have `(*x)` where `x`
723 // is of type `Rc<T>`, then this in fact is equivalent to
724 // `x.deref()`. Since `deref()` is declared with `&self`,
725 // this is an autoref of `x`.
726 adjustment::Adjust::Deref(Some(ref deref)) => {
727 let bk = ty::BorrowKind::from_mutbl(deref.mutbl);
728 self.delegate.borrow(expr.hir_id, expr.span, &cmt, deref.region, bk, AutoRef);
731 adjustment::Adjust::Borrow(ref autoref) => {
732 self.walk_autoref(expr, &cmt, autoref);
735 cmt = return_if_err!(self.mc.cat_expr_adjusted(expr, cmt, &adjustment));
739 /// Walks the autoref `autoref` applied to the autoderef'd
740 /// `expr`. `cmt_base` is the mem-categorized form of `expr`
741 /// after all relevant autoderefs have occurred.
742 fn walk_autoref(&mut self,
744 cmt_base: &mc::cmt_<'tcx>,
745 autoref: &adjustment::AutoBorrow<'tcx>) {
746 debug!("walk_autoref(expr.hir_id={} cmt_base={:?} autoref={:?})",
752 adjustment::AutoBorrow::Ref(r, m) => {
753 self.delegate.borrow(expr.hir_id,
757 ty::BorrowKind::from_mutbl(m.into()),
761 adjustment::AutoBorrow::RawPtr(m) => {
762 debug!("walk_autoref: expr.hir_id={} cmt_base={:?}",
766 // Converting from a &T to *T (or &mut T to *mut T) is
767 // treated as borrowing it for the enclosing temporary
769 let r = self.tcx().mk_region(ty::ReScope(
771 id: expr.hir_id.local_id,
772 data: region::ScopeData::Node
775 self.delegate.borrow(expr.hir_id,
779 ty::BorrowKind::from_mutbl(m),
785 fn arm_move_mode(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm) -> TrackMatchMode {
786 let mut mode = Unknown;
787 for pat in &arm.pats {
788 self.determine_pat_move_mode(discr_cmt.clone(), &pat, &mut mode);
793 fn walk_arm(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm, mode: MatchMode) {
794 for pat in &arm.pats {
795 self.walk_pat(discr_cmt.clone(), &pat, mode);
798 if let Some(hir::Guard::If(ref e)) = arm.guard {
802 self.consume_expr(&arm.body);
805 /// Walks a pat that occurs in isolation (i.e., top-level of fn argument or
806 /// let binding, and *not* a match arm or nested pat.)
807 fn walk_irrefutable_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat) {
808 let mut mode = Unknown;
809 self.determine_pat_move_mode(cmt_discr.clone(), pat, &mut mode);
810 let mode = mode.match_mode();
811 self.walk_pat(cmt_discr, pat, mode);
814 /// Identifies any bindings within `pat` and accumulates within
815 /// `mode` whether the overall pattern/match structure is a move,
817 fn determine_pat_move_mode(&mut self,
818 cmt_discr: mc::cmt<'tcx>,
820 mode: &mut TrackMatchMode) {
821 debug!("determine_pat_move_mode cmt_discr={:?} pat={:?}", cmt_discr, pat);
823 return_if_err!(self.mc.cat_pattern(cmt_discr, pat, |cmt_pat, pat| {
824 if let PatKind::Binding(..) = pat.node {
825 let bm = *self.mc.tables.pat_binding_modes()
827 .expect("missing binding mode");
829 ty::BindByReference(..) =>
830 mode.lub(BorrowingMatch),
831 ty::BindByValue(..) => {
832 match copy_or_move(&self.mc, self.param_env, &cmt_pat, PatBindingMove) {
833 Copy => mode.lub(CopyingMatch),
834 Move(..) => mode.lub(MovingMatch),
842 /// The core driver for walking a pattern; `match_mode` must be
843 /// established up front, e.g., via `determine_pat_move_mode` (see
844 /// also `walk_irrefutable_pat` for patterns that stand alone).
845 fn walk_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat, match_mode: MatchMode) {
846 debug!("walk_pat(cmt_discr={:?}, pat={:?})", cmt_discr, pat);
848 let tcx = self.tcx();
849 let ExprUseVisitor { ref mc, ref mut delegate, param_env } = *self;
850 return_if_err!(mc.cat_pattern(cmt_discr.clone(), pat, |cmt_pat, pat| {
851 if let PatKind::Binding(_, canonical_id, ..) = pat.node {
853 "walk_pat: binding cmt_pat={:?} pat={:?} match_mode={:?}",
858 if let Some(&bm) = mc.tables.pat_binding_modes().get(pat.hir_id) {
859 debug!("walk_pat: pat.hir_id={:?} bm={:?}", pat.hir_id, bm);
861 // pat_ty: the type of the binding being produced.
862 let pat_ty = return_if_err!(mc.node_ty(pat.hir_id));
863 debug!("walk_pat: pat_ty={:?}", pat_ty);
865 // Each match binding is effectively an assignment to the
866 // binding being produced.
867 let def = Def::Local(mc.tcx.hir().hir_to_node_id(canonical_id));
868 if let Ok(ref binding_cmt) = mc.cat_def(pat.hir_id, pat.span, pat_ty, def) {
869 delegate.mutate(pat.hir_id, pat.span, binding_cmt, MutateMode::Init);
872 // It is also a borrow or copy/move of the value being matched.
874 ty::BindByReference(m) => {
875 if let ty::Ref(r, _, _) = pat_ty.sty {
876 let bk = ty::BorrowKind::from_mutbl(m);
877 delegate.borrow(pat.hir_id, pat.span, &cmt_pat, r, bk, RefBinding);
880 ty::BindByValue(..) => {
881 let mode = copy_or_move(mc, param_env, &cmt_pat, PatBindingMove);
882 debug!("walk_pat binding consuming pat");
883 delegate.consume_pat(pat, &cmt_pat, mode);
887 tcx.sess.delay_span_bug(pat.span, "missing binding mode");
892 // Do a second pass over the pattern, calling `matched_pat` on
893 // the interior nodes (enum variants and structs), as opposed
894 // to the above loop's visit of than the bindings that form
895 // the leaves of the pattern tree structure.
896 return_if_err!(mc.cat_pattern(cmt_discr, pat, |cmt_pat, pat| {
897 let qpath = match pat.node {
898 PatKind::Path(ref qpath) |
899 PatKind::TupleStruct(ref qpath, ..) |
900 PatKind::Struct(ref qpath, ..) => qpath,
903 let def = mc.tables.qpath_def(qpath, pat.hir_id);
905 Def::Variant(variant_did) |
906 Def::VariantCtor(variant_did, ..) => {
907 let downcast_cmt = mc.cat_downcast_if_needed(pat, cmt_pat, variant_did);
909 debug!("variant downcast_cmt={:?} pat={:?}", downcast_cmt, pat);
910 delegate.matched_pat(pat, &downcast_cmt, match_mode);
912 Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
913 Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => {
914 debug!("struct cmt_pat={:?} pat={:?}", cmt_pat, pat);
915 delegate.matched_pat(pat, &cmt_pat, match_mode);
922 fn walk_captures(&mut self, closure_expr: &hir::Expr, fn_decl_span: Span) {
923 debug!("walk_captures({:?})", closure_expr);
925 let closure_def_id = self.tcx().hir().local_def_id_from_hir_id(closure_expr.hir_id);
926 self.tcx().with_freevars(closure_expr.hir_id, |freevars| {
927 for freevar in freevars {
928 let var_hir_id = self.tcx().hir().node_to_hir_id(freevar.var_id());
929 let upvar_id = ty::UpvarId {
930 var_path: ty::UpvarPath { hir_id: var_hir_id },
931 closure_expr_id: closure_def_id.to_local(),
933 let upvar_capture = self.mc.tables.upvar_capture(upvar_id);
934 let cmt_var = return_if_err!(self.cat_captured_var(closure_expr.hir_id,
937 match upvar_capture {
938 ty::UpvarCapture::ByValue => {
939 let mode = copy_or_move(&self.mc,
943 self.delegate.consume(closure_expr.hir_id, freevar.span, &cmt_var, mode);
945 ty::UpvarCapture::ByRef(upvar_borrow) => {
946 self.delegate.borrow(closure_expr.hir_id,
951 ClosureCapture(freevar.span));
958 fn cat_captured_var(&mut self,
959 closure_hir_id: hir::HirId,
961 upvar: &hir::Freevar)
962 -> mc::McResult<mc::cmt_<'tcx>> {
963 // Create the cmt for the variable being borrowed, from the
964 // caller's perspective
965 let var_hir_id = self.tcx().hir().node_to_hir_id(upvar.var_id());
966 let var_ty = self.mc.node_ty(var_hir_id)?;
967 self.mc.cat_def(closure_hir_id, closure_span, var_ty, upvar.def)
971 fn copy_or_move<'a, 'gcx, 'tcx>(mc: &mc::MemCategorizationContext<'a, 'gcx, 'tcx>,
972 param_env: ty::ParamEnv<'tcx>,
973 cmt: &mc::cmt_<'tcx>,
974 move_reason: MoveReason)
977 if !mc.type_is_copy_modulo_regions(param_env, cmt.ty, cmt.span) {