]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/expr_use_visitor.rs
Update compiler/rustc_typeck/src/expr_use_visitor.rs
[rust.git] / compiler / rustc_typeck / src / expr_use_visitor.rs
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.
4
5 // Export these here so that Clippy can use them.
6 pub use rustc_middle::hir::place::{Place, PlaceBase, PlaceWithHirId, Projection};
7
8 use rustc_data_structures::fx::FxIndexMap;
9 use rustc_hir as hir;
10 use rustc_hir::def::Res;
11 use rustc_hir::def_id::LocalDefId;
12 use rustc_hir::PatKind;
13 use rustc_index::vec::Idx;
14 use rustc_infer::infer::InferCtxt;
15 use rustc_middle::hir::place::ProjectionKind;
16 use rustc_middle::mir::FakeReadCause;
17 use rustc_middle::ty::{self, adjustment, TyCtxt};
18 use rustc_target::abi::VariantIdx;
19 use std::iter;
20
21 use crate::mem_categorization as mc;
22
23 ///////////////////////////////////////////////////////////////////////////
24 // The Delegate trait
25
26 /// This trait defines the callbacks you can expect to receive when
27 /// employing the ExprUseVisitor.
28 pub trait Delegate<'tcx> {
29     // The value found at `place` is moved, depending
30     // on `mode`. Where `diag_expr_id` is the id used for diagnostics for `place`.
31     //
32     // Use of a `Copy` type in a ByValue context is considered a use
33     // by `ImmBorrow` and `borrow` is called instead. This is because
34     // a shared borrow is the "minimum access" that would be needed
35     // to perform a copy.
36     //
37     //
38     // The parameter `diag_expr_id` indicates the HIR id that ought to be used for
39     // diagnostics. Around pattern matching such as `let pat = expr`, the diagnostic
40     // id will be the id of the expression `expr` but the place itself will have
41     // the id of the binding in the pattern `pat`.
42     fn consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId);
43
44     // The value found at `place` is being borrowed with kind `bk`.
45     // `diag_expr_id` is the id used for diagnostics (see `consume` for more details).
46     fn borrow(
47         &mut self,
48         place_with_id: &PlaceWithHirId<'tcx>,
49         diag_expr_id: hir::HirId,
50         bk: ty::BorrowKind,
51     );
52
53     // The path at `assignee_place` is being assigned to.
54     // `diag_expr_id` is the id used for diagnostics (see `consume` for more details).
55     fn mutate(&mut self, assignee_place: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId);
56
57     // The `place` should be a fake read because of specified `cause`.
58     fn fake_read(&mut self, place: Place<'tcx>, cause: FakeReadCause, diag_expr_id: hir::HirId);
59 }
60
61 #[derive(Copy, Clone, PartialEq, Debug)]
62 enum ConsumeMode {
63     Copy, // reference to x where x has a type that copies
64     Move, // reference to x where x has a type that moves
65 }
66
67 #[derive(Copy, Clone, PartialEq, Debug)]
68 pub enum MutateMode {
69     Init,
70     JustWrite,    // x = y
71     WriteAndRead, // x += y
72 }
73
74 ///////////////////////////////////////////////////////////////////////////
75 // The ExprUseVisitor type
76 //
77 // This is the code that actually walks the tree.
78 pub struct ExprUseVisitor<'a, 'tcx> {
79     mc: mc::MemCategorizationContext<'a, 'tcx>,
80     body_owner: LocalDefId,
81     delegate: &'a mut dyn Delegate<'tcx>,
82 }
83
84 // If the MC results in an error, it's because the type check
85 // failed (or will fail, when the error is uncovered and reported
86 // during writeback). In this case, we just ignore this part of the
87 // code.
88 //
89 // Note that this macro appears similar to try!(), but, unlike try!(),
90 // it does not propagate the error.
91 macro_rules! return_if_err {
92     ($inp: expr) => {
93         match $inp {
94             Ok(v) => v,
95             Err(()) => {
96                 debug!("mc reported err");
97                 return;
98             }
99         }
100     };
101 }
102
103 impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
104     /// Creates the ExprUseVisitor, configuring it with the various options provided:
105     ///
106     /// - `delegate` -- who receives the callbacks
107     /// - `param_env` --- parameter environment for trait lookups (esp. pertaining to `Copy`)
108     /// - `typeck_results` --- typeck results for the code being analyzed
109     pub fn new(
110         delegate: &'a mut (dyn Delegate<'tcx> + 'a),
111         infcx: &'a InferCtxt<'a, 'tcx>,
112         body_owner: LocalDefId,
113         param_env: ty::ParamEnv<'tcx>,
114         typeck_results: &'a ty::TypeckResults<'tcx>,
115     ) -> Self {
116         ExprUseVisitor {
117             mc: mc::MemCategorizationContext::new(infcx, param_env, body_owner, typeck_results),
118             body_owner,
119             delegate,
120         }
121     }
122
123     pub fn consume_body(&mut self, body: &hir::Body<'_>) {
124         debug!("consume_body(body={:?})", body);
125
126         for param in body.params {
127             let param_ty = return_if_err!(self.mc.pat_ty_adjusted(&param.pat));
128             debug!("consume_body: param_ty = {:?}", param_ty);
129
130             let param_place = self.mc.cat_rvalue(param.hir_id, param.pat.span, param_ty);
131
132             self.walk_irrefutable_pat(&param_place, &param.pat);
133         }
134
135         self.consume_expr(&body.value);
136     }
137
138     fn tcx(&self) -> TyCtxt<'tcx> {
139         self.mc.tcx()
140     }
141
142     fn delegate_consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId) {
143         delegate_consume(&self.mc, self.delegate, place_with_id, diag_expr_id)
144     }
145
146     fn consume_exprs(&mut self, exprs: &[hir::Expr<'_>]) {
147         for expr in exprs {
148             self.consume_expr(&expr);
149         }
150     }
151
152     pub fn consume_expr(&mut self, expr: &hir::Expr<'_>) {
153         debug!("consume_expr(expr={:?})", expr);
154
155         let place_with_id = return_if_err!(self.mc.cat_expr(expr));
156         self.delegate_consume(&place_with_id, place_with_id.hir_id);
157         self.walk_expr(expr);
158     }
159
160     fn mutate_expr(&mut self, expr: &hir::Expr<'_>) {
161         let place_with_id = return_if_err!(self.mc.cat_expr(expr));
162         self.delegate.mutate(&place_with_id, place_with_id.hir_id);
163         self.walk_expr(expr);
164     }
165
166     fn borrow_expr(&mut self, expr: &hir::Expr<'_>, bk: ty::BorrowKind) {
167         debug!("borrow_expr(expr={:?}, bk={:?})", expr, bk);
168
169         let place_with_id = return_if_err!(self.mc.cat_expr(expr));
170         self.delegate.borrow(&place_with_id, place_with_id.hir_id, bk);
171
172         self.walk_expr(expr)
173     }
174
175     fn select_from_expr(&mut self, expr: &hir::Expr<'_>) {
176         self.walk_expr(expr)
177     }
178
179     pub fn walk_expr(&mut self, expr: &hir::Expr<'_>) {
180         debug!("walk_expr(expr={:?})", expr);
181
182         self.walk_adjustment(expr);
183
184         match expr.kind {
185             hir::ExprKind::Path(_) => {}
186
187             hir::ExprKind::Type(ref subexpr, _) => self.walk_expr(subexpr),
188
189             hir::ExprKind::Unary(hir::UnOp::Deref, ref base) => {
190                 // *base
191                 self.select_from_expr(base);
192             }
193
194             hir::ExprKind::Field(ref base, _) => {
195                 // base.f
196                 self.select_from_expr(base);
197             }
198
199             hir::ExprKind::Index(ref lhs, ref rhs) => {
200                 // lhs[rhs]
201                 self.select_from_expr(lhs);
202                 self.consume_expr(rhs);
203             }
204
205             hir::ExprKind::Call(ref callee, ref args) => {
206                 // callee(args)
207                 self.consume_expr(callee);
208                 self.consume_exprs(args);
209             }
210
211             hir::ExprKind::MethodCall(.., ref args, _) => {
212                 // callee.m(args)
213                 self.consume_exprs(args);
214             }
215
216             hir::ExprKind::Struct(_, ref fields, ref opt_with) => {
217                 self.walk_struct_expr(fields, opt_with);
218             }
219
220             hir::ExprKind::Tup(ref exprs) => {
221                 self.consume_exprs(exprs);
222             }
223
224             hir::ExprKind::If(ref cond_expr, ref then_expr, ref opt_else_expr) => {
225                 self.consume_expr(&cond_expr);
226                 self.consume_expr(&then_expr);
227                 if let Some(ref else_expr) = *opt_else_expr {
228                     self.consume_expr(&else_expr);
229                 }
230             }
231
232             hir::ExprKind::Match(ref discr, arms, _) => {
233                 let discr_place = return_if_err!(self.mc.cat_expr(&discr));
234
235                 // Matching should not always be considered a use of the place, hence
236                 // discr does not necessarily need to be borrowed.
237                 // We only want to borrow discr if the pattern contain something other
238                 // than wildcards.
239                 let ExprUseVisitor { ref mc, body_owner: _, delegate: _ } = *self;
240                 let mut needs_to_be_read = false;
241                 for arm in arms.iter() {
242                     return_if_err!(mc.cat_pattern(discr_place.clone(), &arm.pat, |place, pat| {
243                         match &pat.kind {
244                             PatKind::Binding(.., opt_sub_pat) => {
245                                 // If the opt_sub_pat is None, than the binding does not count as
246                                 // a wildcard for the purpose of borrowing discr.
247                                 if opt_sub_pat.is_none() {
248                                     needs_to_be_read = true;
249                                 }
250                             }
251                             PatKind::TupleStruct(..)
252                             | PatKind::Path(..)
253                             | PatKind::Struct(..)
254                             | PatKind::Tuple(..) => {
255                                 // If the PatKind is a TupleStruct, Struct or Tuple then we want to check
256                                 // whether the Variant is a MultiVariant or a SingleVariant. We only want
257                                 // to borrow discr if it is a MultiVariant.
258                                 // If it is a SingleVariant and creates a binding we will handle that when
259                                 // this callback gets called again.
260                                 if let ty::Adt(def, _) = place.place.base_ty.kind() {
261                                     if def.variants.len() > 1 {
262                                         needs_to_be_read = true;
263                                     }
264                                 }
265                             }
266                             PatKind::Lit(_) => {
267                                 // If the PatKind is a Lit then we want
268                                 // to borrow discr.
269                                 needs_to_be_read = true;
270                             }
271                             _ => {}
272                         }
273                     }));
274                 }
275
276                 if needs_to_be_read {
277                     self.borrow_expr(&discr, ty::ImmBorrow);
278                 } else {
279                     let closure_def_id = match discr_place.place.base {
280                         PlaceBase::Upvar(upvar_id) => Some(upvar_id.closure_expr_id.to_def_id()),
281                         _ => None,
282                     };
283
284                     self.delegate.fake_read(
285                         discr_place.place.clone(),
286                         FakeReadCause::ForMatchedPlace(closure_def_id),
287                         discr_place.hir_id,
288                     );
289
290                     // We always want to walk the discriminant. We want to make sure, for instance,
291                     // that the discriminant has been initialized.
292                     self.walk_expr(&discr);
293                 }
294
295                 // treatment of the discriminant is handled while walking the arms.
296                 for arm in arms {
297                     self.walk_arm(&discr_place, arm);
298                 }
299             }
300
301             hir::ExprKind::Array(ref exprs) => {
302                 self.consume_exprs(exprs);
303             }
304
305             hir::ExprKind::AddrOf(_, m, ref base) => {
306                 // &base
307                 // make sure that the thing we are pointing out stays valid
308                 // for the lifetime `scope_r` of the resulting ptr:
309                 let bk = ty::BorrowKind::from_mutbl(m);
310                 self.borrow_expr(&base, bk);
311             }
312
313             hir::ExprKind::InlineAsm(ref asm) => {
314                 for (op, _op_sp) in asm.operands {
315                     match op {
316                         hir::InlineAsmOperand::In { expr, .. }
317                         | hir::InlineAsmOperand::Sym { expr, .. } => self.consume_expr(expr),
318                         hir::InlineAsmOperand::Out { expr, .. } => {
319                             if let Some(expr) = expr {
320                                 self.mutate_expr(expr);
321                             }
322                         }
323                         hir::InlineAsmOperand::InOut { expr, .. } => {
324                             self.mutate_expr(expr);
325                         }
326                         hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
327                             self.consume_expr(in_expr);
328                             if let Some(out_expr) = out_expr {
329                                 self.mutate_expr(out_expr);
330                             }
331                         }
332                         hir::InlineAsmOperand::Const { .. } => {}
333                     }
334                 }
335             }
336
337             hir::ExprKind::LlvmInlineAsm(ref ia) => {
338                 for (o, output) in iter::zip(&ia.inner.outputs, ia.outputs_exprs) {
339                     if o.is_indirect {
340                         self.consume_expr(output);
341                     } else {
342                         self.mutate_expr(output);
343                     }
344                 }
345                 self.consume_exprs(&ia.inputs_exprs);
346             }
347
348             hir::ExprKind::Continue(..)
349             | hir::ExprKind::Lit(..)
350             | hir::ExprKind::ConstBlock(..)
351             | hir::ExprKind::Err => {}
352
353             hir::ExprKind::Loop(ref blk, ..) => {
354                 self.walk_block(blk);
355             }
356
357             hir::ExprKind::Unary(_, ref lhs) => {
358                 self.consume_expr(lhs);
359             }
360
361             hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
362                 self.consume_expr(lhs);
363                 self.consume_expr(rhs);
364             }
365
366             hir::ExprKind::Block(ref blk, _) => {
367                 self.walk_block(blk);
368             }
369
370             hir::ExprKind::Break(_, ref opt_expr) | hir::ExprKind::Ret(ref opt_expr) => {
371                 if let Some(ref expr) = *opt_expr {
372                     self.consume_expr(expr);
373                 }
374             }
375
376             hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
377                 self.mutate_expr(lhs);
378                 self.consume_expr(rhs);
379             }
380
381             hir::ExprKind::Cast(ref base, _) => {
382                 self.consume_expr(base);
383             }
384
385             hir::ExprKind::DropTemps(ref expr) => {
386                 self.consume_expr(expr);
387             }
388
389             hir::ExprKind::AssignOp(_, ref lhs, ref rhs) => {
390                 if self.mc.typeck_results.is_method_call(expr) {
391                     self.consume_expr(lhs);
392                 } else {
393                     self.mutate_expr(lhs);
394                 }
395                 self.consume_expr(rhs);
396             }
397
398             hir::ExprKind::Repeat(ref base, _) => {
399                 self.consume_expr(base);
400             }
401
402             hir::ExprKind::Closure(..) => {
403                 self.walk_captures(expr);
404             }
405
406             hir::ExprKind::Box(ref base) => {
407                 self.consume_expr(base);
408             }
409
410             hir::ExprKind::Yield(ref value, _) => {
411                 self.consume_expr(value);
412             }
413         }
414     }
415
416     fn walk_stmt(&mut self, stmt: &hir::Stmt<'_>) {
417         match stmt.kind {
418             hir::StmtKind::Local(ref local) => {
419                 self.walk_local(&local);
420             }
421
422             hir::StmtKind::Item(_) => {
423                 // We don't visit nested items in this visitor,
424                 // only the fn body we were given.
425             }
426
427             hir::StmtKind::Expr(ref expr) | hir::StmtKind::Semi(ref expr) => {
428                 self.consume_expr(&expr);
429             }
430         }
431     }
432
433     fn walk_local(&mut self, local: &hir::Local<'_>) {
434         if let Some(ref expr) = local.init {
435             // Variable declarations with
436             // initializers are considered
437             // "assigns", which is handled by
438             // `walk_pat`:
439             self.walk_expr(&expr);
440             let init_place = return_if_err!(self.mc.cat_expr(&expr));
441             self.walk_irrefutable_pat(&init_place, &local.pat);
442         }
443     }
444
445     /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
446     /// depending on its type.
447     fn walk_block(&mut self, blk: &hir::Block<'_>) {
448         debug!("walk_block(blk.hir_id={})", blk.hir_id);
449
450         for stmt in blk.stmts {
451             self.walk_stmt(stmt);
452         }
453
454         if let Some(ref tail_expr) = blk.expr {
455             self.consume_expr(&tail_expr);
456         }
457     }
458
459     fn walk_struct_expr(
460         &mut self,
461         fields: &[hir::ExprField<'_>],
462         opt_with: &Option<&'hir hir::Expr<'_>>,
463     ) {
464         // Consume the expressions supplying values for each field.
465         for field in fields {
466             self.consume_expr(&field.expr);
467         }
468
469         let with_expr = match *opt_with {
470             Some(ref w) => &**w,
471             None => {
472                 return;
473             }
474         };
475
476         let with_place = return_if_err!(self.mc.cat_expr(&with_expr));
477
478         // Select just those fields of the `with`
479         // expression that will actually be used
480         match with_place.place.ty().kind() {
481             ty::Adt(adt, substs) if adt.is_struct() => {
482                 // Consume those fields of the with expression that are needed.
483                 for (f_index, with_field) in adt.non_enum_variant().fields.iter().enumerate() {
484                     let is_mentioned = fields.iter().any(|f| {
485                         self.tcx().field_index(f.hir_id, self.mc.typeck_results) == f_index
486                     });
487                     if !is_mentioned {
488                         let field_place = self.mc.cat_projection(
489                             &*with_expr,
490                             with_place.clone(),
491                             with_field.ty(self.tcx(), substs),
492                             ProjectionKind::Field(f_index as u32, VariantIdx::new(0)),
493                         );
494                         self.delegate_consume(&field_place, field_place.hir_id);
495                     }
496                 }
497             }
498             _ => {
499                 // the base expression should always evaluate to a
500                 // struct; however, when EUV is run during typeck, it
501                 // may not. This will generate an error earlier in typeck,
502                 // so we can just ignore it.
503                 if !self.tcx().sess.has_errors() {
504                     span_bug!(with_expr.span, "with expression doesn't evaluate to a struct");
505                 }
506             }
507         }
508
509         // walk the with expression so that complex expressions
510         // are properly handled.
511         self.walk_expr(with_expr);
512     }
513
514     // Invoke the appropriate delegate calls for anything that gets
515     // consumed or borrowed as part of the automatic adjustment
516     // process.
517     fn walk_adjustment(&mut self, expr: &hir::Expr<'_>) {
518         let adjustments = self.mc.typeck_results.expr_adjustments(expr);
519         let mut place_with_id = return_if_err!(self.mc.cat_expr_unadjusted(expr));
520         for adjustment in adjustments {
521             debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment);
522             match adjustment.kind {
523                 adjustment::Adjust::NeverToAny | adjustment::Adjust::Pointer(_) => {
524                     // Creating a closure/fn-pointer or unsizing consumes
525                     // the input and stores it into the resulting rvalue.
526                     self.delegate_consume(&place_with_id, place_with_id.hir_id);
527                 }
528
529                 adjustment::Adjust::Deref(None) => {}
530
531                 // Autoderefs for overloaded Deref calls in fact reference
532                 // their receiver. That is, if we have `(*x)` where `x`
533                 // is of type `Rc<T>`, then this in fact is equivalent to
534                 // `x.deref()`. Since `deref()` is declared with `&self`,
535                 // this is an autoref of `x`.
536                 adjustment::Adjust::Deref(Some(ref deref)) => {
537                     let bk = ty::BorrowKind::from_mutbl(deref.mutbl);
538                     self.delegate.borrow(&place_with_id, place_with_id.hir_id, bk);
539                 }
540
541                 adjustment::Adjust::Borrow(ref autoref) => {
542                     self.walk_autoref(expr, &place_with_id, autoref);
543                 }
544             }
545             place_with_id =
546                 return_if_err!(self.mc.cat_expr_adjusted(expr, place_with_id, &adjustment));
547         }
548     }
549
550     /// Walks the autoref `autoref` applied to the autoderef'd
551     /// `expr`. `base_place` is the mem-categorized form of `expr`
552     /// after all relevant autoderefs have occurred.
553     fn walk_autoref(
554         &mut self,
555         expr: &hir::Expr<'_>,
556         base_place: &PlaceWithHirId<'tcx>,
557         autoref: &adjustment::AutoBorrow<'tcx>,
558     ) {
559         debug!(
560             "walk_autoref(expr.hir_id={} base_place={:?} autoref={:?})",
561             expr.hir_id, base_place, autoref
562         );
563
564         match *autoref {
565             adjustment::AutoBorrow::Ref(_, m) => {
566                 self.delegate.borrow(
567                     base_place,
568                     base_place.hir_id,
569                     ty::BorrowKind::from_mutbl(m.into()),
570                 );
571             }
572
573             adjustment::AutoBorrow::RawPtr(m) => {
574                 debug!("walk_autoref: expr.hir_id={} base_place={:?}", expr.hir_id, base_place);
575
576                 self.delegate.borrow(base_place, base_place.hir_id, ty::BorrowKind::from_mutbl(m));
577             }
578         }
579     }
580
581     fn walk_arm(&mut self, discr_place: &PlaceWithHirId<'tcx>, arm: &hir::Arm<'_>) {
582         let closure_def_id = match discr_place.place.base {
583             PlaceBase::Upvar(upvar_id) => Some(upvar_id.closure_expr_id.to_def_id()),
584             _ => None,
585         };
586
587         self.delegate.fake_read(
588             discr_place.place.clone(),
589             FakeReadCause::ForMatchedPlace(closure_def_id),
590             discr_place.hir_id,
591         );
592         self.walk_pat(discr_place, &arm.pat);
593
594         if let Some(hir::Guard::If(ref e)) = arm.guard {
595             self.consume_expr(e)
596         }
597
598         self.consume_expr(&arm.body);
599     }
600
601     /// Walks a pat that occurs in isolation (i.e., top-level of fn argument or
602     /// let binding, and *not* a match arm or nested pat.)
603     fn walk_irrefutable_pat(&mut self, discr_place: &PlaceWithHirId<'tcx>, pat: &hir::Pat<'_>) {
604         let closure_def_id = match discr_place.place.base {
605             PlaceBase::Upvar(upvar_id) => Some(upvar_id.closure_expr_id.to_def_id()),
606             _ => None,
607         };
608
609         self.delegate.fake_read(
610             discr_place.place.clone(),
611             FakeReadCause::ForLet(closure_def_id),
612             discr_place.hir_id,
613         );
614         self.walk_pat(discr_place, pat);
615     }
616
617     /// The core driver for walking a pattern
618     fn walk_pat(&mut self, discr_place: &PlaceWithHirId<'tcx>, pat: &hir::Pat<'_>) {
619         debug!("walk_pat(discr_place={:?}, pat={:?})", discr_place, pat);
620
621         let tcx = self.tcx();
622         let ExprUseVisitor { ref mc, body_owner: _, ref mut delegate } = *self;
623         return_if_err!(mc.cat_pattern(discr_place.clone(), pat, |place, pat| {
624             if let PatKind::Binding(_, canonical_id, ..) = pat.kind {
625                 debug!("walk_pat: binding place={:?} pat={:?}", place, pat,);
626                 if let Some(bm) =
627                     mc.typeck_results.extract_binding_mode(tcx.sess, pat.hir_id, pat.span)
628                 {
629                     debug!("walk_pat: pat.hir_id={:?} bm={:?}", pat.hir_id, bm);
630
631                     // pat_ty: the type of the binding being produced.
632                     let pat_ty = return_if_err!(mc.node_ty(pat.hir_id));
633                     debug!("walk_pat: pat_ty={:?}", pat_ty);
634
635                     // Each match binding is effectively an assignment to the
636                     // binding being produced.
637                     let def = Res::Local(canonical_id);
638                     if let Ok(ref binding_place) = mc.cat_res(pat.hir_id, pat.span, pat_ty, def) {
639                         delegate.mutate(binding_place, binding_place.hir_id);
640                     }
641
642                     // It is also a borrow or copy/move of the value being matched.
643                     // In a cases of pattern like `let pat = upvar`, don't use the span
644                     // of the pattern, as this just looks confusing, instead use the span
645                     // of the discriminant.
646                     match bm {
647                         ty::BindByReference(m) => {
648                             let bk = ty::BorrowKind::from_mutbl(m);
649                             delegate.borrow(place, discr_place.hir_id, bk);
650                         }
651                         ty::BindByValue(..) => {
652                             debug!("walk_pat binding consuming pat");
653                             delegate_consume(mc, *delegate, place, discr_place.hir_id);
654                         }
655                     }
656                 }
657             }
658         }));
659     }
660
661     /// Handle the case where the current body contains a closure.
662     ///
663     /// When the current body being handled is a closure, then we must make sure that
664     /// - The parent closure only captures Places from the nested closure that are not local to it.
665     ///
666     /// In the following example the closures `c` only captures `p.x`` even though `incr`
667     /// is a capture of the nested closure
668     ///
669     /// ```rust,ignore(cannot-test-this-because-pseudo-code)
670     /// let p = ..;
671     /// let c = || {
672     ///    let incr = 10;
673     ///    let nested = || p.x += incr;
674     /// }
675     /// ```
676     ///
677     /// - When reporting the Place back to the Delegate, ensure that the UpvarId uses the enclosing
678     /// closure as the DefId.
679     fn walk_captures(&mut self, closure_expr: &hir::Expr<'_>) {
680         fn upvar_is_local_variable(
681             upvars: Option<&'tcx FxIndexMap<hir::HirId, hir::Upvar>>,
682             upvar_id: &hir::HirId,
683             body_owner_is_closure: bool,
684         ) -> bool {
685             upvars.map(|upvars| !upvars.contains_key(upvar_id)).unwrap_or(body_owner_is_closure)
686         }
687
688         debug!("walk_captures({:?})", closure_expr);
689
690         let closure_def_id = self.tcx().hir().local_def_id(closure_expr.hir_id).to_def_id();
691         let upvars = self.tcx().upvars_mentioned(self.body_owner);
692
693         // For purposes of this function, generator and closures are equivalent.
694         let body_owner_is_closure = matches!(
695             self.tcx().type_of(self.body_owner.to_def_id()).kind(),
696             ty::Closure(..) | ty::Generator(..)
697         );
698
699         // If we have a nested closure, we want to include the fake reads present in the nested closure.
700         if let Some(fake_reads) = self.mc.typeck_results.closure_fake_reads.get(&closure_def_id) {
701             for (fake_read, cause, hir_id) in fake_reads.iter() {
702                 match fake_read.base {
703                     PlaceBase::Upvar(upvar_id) => {
704                         if upvar_is_local_variable(
705                             upvars,
706                             &upvar_id.var_path.hir_id,
707                             body_owner_is_closure,
708                         ) {
709                             // The nested closure might be fake reading the current (enclosing) closure's local variables.
710                             // The only places we want to fake read before creating the parent closure are the ones that
711                             // are not local to it/ defined by it.
712                             //
713                             // ```rust,ignore(cannot-test-this-because-pseudo-code)
714                             // let v1 = (0, 1);
715                             // let c = || { // fake reads: v1
716                             //    let v2 = (0, 1);
717                             //    let e = || { // fake reads: v1, v2
718                             //       let (_, t1) = v1;
719                             //       let (_, t2) = v2;
720                             //    }
721                             // }
722                             // ```
723                             // This check is performed when visiting the body of the outermost closure (`c`) and ensures
724                             // that we don't add a fake read of v2 in c.
725                             continue;
726                         }
727                     }
728                     _ => {
729                         bug!(
730                             "Do not know how to get HirId out of Rvalue and StaticItem {:?}",
731                             fake_read.base
732                         );
733                     }
734                 };
735                 self.delegate.fake_read(fake_read.clone(), *cause, *hir_id);
736             }
737         }
738
739         if let Some(min_captures) = self.mc.typeck_results.closure_min_captures.get(&closure_def_id)
740         {
741             for (var_hir_id, min_list) in min_captures.iter() {
742                 if upvars.map_or(body_owner_is_closure, |upvars| !upvars.contains_key(var_hir_id)) {
743                     // The nested closure might be capturing the current (enclosing) closure's local variables.
744                     // We check if the root variable is ever mentioned within the enclosing closure, if not
745                     // then for the current body (if it's a closure) these aren't captures, we will ignore them.
746                     continue;
747                 }
748                 for captured_place in min_list {
749                     let place = &captured_place.place;
750                     let capture_info = captured_place.info;
751
752                     let place_base = if body_owner_is_closure {
753                         // Mark the place to be captured by the enclosing closure
754                         PlaceBase::Upvar(ty::UpvarId::new(*var_hir_id, self.body_owner))
755                     } else {
756                         // If the body owner isn't a closure then the variable must
757                         // be a local variable
758                         PlaceBase::Local(*var_hir_id)
759                     };
760                     let place_with_id = PlaceWithHirId::new(
761                         capture_info.path_expr_id.unwrap_or(
762                             capture_info.capture_kind_expr_id.unwrap_or(closure_expr.hir_id),
763                         ),
764                         place.base_ty,
765                         place_base,
766                         place.projections.clone(),
767                     );
768
769                     match capture_info.capture_kind {
770                         ty::UpvarCapture::ByValue(_) => {
771                             self.delegate_consume(&place_with_id, place_with_id.hir_id);
772                         }
773                         ty::UpvarCapture::ByRef(upvar_borrow) => {
774                             self.delegate.borrow(
775                                 &place_with_id,
776                                 place_with_id.hir_id,
777                                 upvar_borrow.kind,
778                             );
779                         }
780                     }
781                 }
782             }
783         }
784     }
785 }
786
787 fn copy_or_move<'a, 'tcx>(
788     mc: &mc::MemCategorizationContext<'a, 'tcx>,
789     place_with_id: &PlaceWithHirId<'tcx>,
790 ) -> ConsumeMode {
791     if !mc.type_is_copy_modulo_regions(
792         place_with_id.place.ty(),
793         mc.tcx().hir().span(place_with_id.hir_id),
794     ) {
795         ConsumeMode::Move
796     } else {
797         ConsumeMode::Copy
798     }
799 }
800
801 // - If a place is used in a `ByValue` context then move it if it's not a `Copy` type.
802 // - If the place that is a `Copy` type consider it a `ImmBorrow`.
803 fn delegate_consume<'a, 'tcx>(
804     mc: &mc::MemCategorizationContext<'a, 'tcx>,
805     delegate: &mut (dyn Delegate<'tcx> + 'a),
806     place_with_id: &PlaceWithHirId<'tcx>,
807     diag_expr_id: hir::HirId,
808 ) {
809     debug!("delegate_consume(place_with_id={:?})", place_with_id);
810
811     let mode = copy_or_move(&mc, place_with_id);
812
813     match mode {
814         ConsumeMode::Move => delegate.consume(place_with_id, diag_expr_id),
815         ConsumeMode::Copy => {
816             delegate.borrow(place_with_id, diag_expr_id, ty::BorrowKind::ImmBorrow)
817         }
818     }
819 }