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