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