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