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