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