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