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