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