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.
5 use std::slice::from_ref;
9 // Export these here so that Clippy can use them.
10 pub use rustc_middle::hir::place::{Place, PlaceBase, PlaceWithHirId, Projection};
12 use rustc_data_structures::fx::FxIndexMap;
14 use rustc_hir::def::Res;
15 use rustc_hir::def_id::LocalDefId;
16 use rustc_hir::PatKind;
17 use rustc_index::vec::Idx;
18 use rustc_infer::infer::InferCtxt;
19 use rustc_middle::hir::place::ProjectionKind;
20 use rustc_middle::mir::FakeReadCause;
21 use rustc_middle::ty::{self, adjustment, AdtKind, Ty, TyCtxt};
22 use rustc_target::abi::VariantIdx;
23 use ty::BorrowKind::ImmBorrow;
25 use crate::mem_categorization as mc;
27 /// This trait defines the callbacks you can expect to receive when
28 /// employing the ExprUseVisitor.
29 pub trait Delegate<'tcx> {
30 /// The value found at `place` is moved, depending
31 /// on `mode`. Where `diag_expr_id` is the id used for diagnostics for `place`.
33 /// Use of a `Copy` type in a ByValue context is considered a use
34 /// by `ImmBorrow` and `borrow` is called instead. This is because
35 /// a shared borrow is the "minimum access" that would be needed
36 /// to perform a copy.
39 /// The parameter `diag_expr_id` indicates the HIR id that ought to be used for
40 /// diagnostics. Around pattern matching such as `let pat = expr`, the diagnostic
41 /// id will be the id of the expression `expr` but the place itself will have
42 /// the id of the binding in the pattern `pat`.
43 fn consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId);
45 /// The value found at `place` is being borrowed with kind `bk`.
46 /// `diag_expr_id` is the id used for diagnostics (see `consume` for more details).
49 place_with_id: &PlaceWithHirId<'tcx>,
50 diag_expr_id: hir::HirId,
54 /// The value found at `place` is being copied.
55 /// `diag_expr_id` is the id used for diagnostics (see `consume` for more details).
56 fn copy(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId) {
57 // In most cases, copying data from `x` is equivalent to doing `*&x`, so by default
58 // we treat a copy of `x` as a borrow of `x`.
59 self.borrow(place_with_id, diag_expr_id, ty::BorrowKind::ImmBorrow)
62 /// The path at `assignee_place` is being assigned to.
63 /// `diag_expr_id` is the id used for diagnostics (see `consume` for more details).
64 fn mutate(&mut self, assignee_place: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId);
66 /// The path at `binding_place` is a binding that is being initialized.
68 /// This covers cases such as `let x = 42;`
69 fn bind(&mut self, binding_place: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId) {
70 // Bindings can normally be treated as a regular assignment, so by default we
71 // forward this to the mutate callback.
72 self.mutate(binding_place, diag_expr_id)
75 /// The `place` should be a fake read because of specified `cause`.
78 place_with_id: &PlaceWithHirId<'tcx>,
80 diag_expr_id: hir::HirId,
84 #[derive(Copy, Clone, PartialEq, Debug)]
86 /// reference to x where x has a type that copies
88 /// reference to x where x has a type that moves
92 #[derive(Copy, Clone, PartialEq, Debug)]
101 /// The ExprUseVisitor type
103 /// This is the code that actually walks the tree.
104 pub struct ExprUseVisitor<'a, 'tcx> {
105 mc: mc::MemCategorizationContext<'a, 'tcx>,
106 body_owner: LocalDefId,
107 delegate: &'a mut dyn Delegate<'tcx>,
110 /// If the MC results in an error, it's because the type check
111 /// failed (or will fail, when the error is uncovered and reported
112 /// during writeback). In this case, we just ignore this part of the
115 /// Note that this macro appears similar to try!(), but, unlike try!(),
116 /// it does not propagate the error.
117 macro_rules! return_if_err {
122 debug!("mc reported err");
129 impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
130 /// Creates the ExprUseVisitor, configuring it with the various options provided:
132 /// - `delegate` -- who receives the callbacks
133 /// - `param_env` --- parameter environment for trait lookups (esp. pertaining to `Copy`)
134 /// - `typeck_results` --- typeck results for the code being analyzed
136 delegate: &'a mut (dyn Delegate<'tcx> + 'a),
137 infcx: &'a InferCtxt<'a, 'tcx>,
138 body_owner: LocalDefId,
139 param_env: ty::ParamEnv<'tcx>,
140 typeck_results: &'a ty::TypeckResults<'tcx>,
143 mc: mc::MemCategorizationContext::new(infcx, param_env, body_owner, typeck_results),
149 #[instrument(skip(self), level = "debug")]
150 pub fn consume_body(&mut self, body: &hir::Body<'_>) {
151 for param in body.params {
152 let param_ty = return_if_err!(self.mc.pat_ty_adjusted(param.pat));
153 debug!("consume_body: param_ty = {:?}", param_ty);
155 let param_place = self.mc.cat_rvalue(param.hir_id, param.pat.span, param_ty);
157 self.walk_irrefutable_pat(¶m_place, param.pat);
160 self.consume_expr(&body.value);
163 fn tcx(&self) -> TyCtxt<'tcx> {
167 fn delegate_consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId) {
168 delegate_consume(&self.mc, self.delegate, place_with_id, diag_expr_id)
171 fn consume_exprs(&mut self, exprs: &[hir::Expr<'_>]) {
173 self.consume_expr(expr);
177 pub fn consume_expr(&mut self, expr: &hir::Expr<'_>) {
178 debug!("consume_expr(expr={:?})", expr);
180 let place_with_id = return_if_err!(self.mc.cat_expr(expr));
181 self.delegate_consume(&place_with_id, place_with_id.hir_id);
182 self.walk_expr(expr);
185 fn mutate_expr(&mut self, expr: &hir::Expr<'_>) {
186 let place_with_id = return_if_err!(self.mc.cat_expr(expr));
187 self.delegate.mutate(&place_with_id, place_with_id.hir_id);
188 self.walk_expr(expr);
191 fn borrow_expr(&mut self, expr: &hir::Expr<'_>, bk: ty::BorrowKind) {
192 debug!("borrow_expr(expr={:?}, bk={:?})", expr, bk);
194 let place_with_id = return_if_err!(self.mc.cat_expr(expr));
195 self.delegate.borrow(&place_with_id, place_with_id.hir_id, bk);
200 fn select_from_expr(&mut self, expr: &hir::Expr<'_>) {
204 pub fn walk_expr(&mut self, expr: &hir::Expr<'_>) {
205 debug!("walk_expr(expr={:?})", expr);
207 self.walk_adjustment(expr);
210 hir::ExprKind::Path(_) => {}
212 hir::ExprKind::Type(subexpr, _) => self.walk_expr(subexpr),
214 hir::ExprKind::Unary(hir::UnOp::Deref, base) => {
216 self.select_from_expr(base);
219 hir::ExprKind::Field(base, _) => {
221 self.select_from_expr(base);
224 hir::ExprKind::Index(lhs, rhs) => {
226 self.select_from_expr(lhs);
227 self.consume_expr(rhs);
230 hir::ExprKind::Call(callee, args) => {
232 self.consume_expr(callee);
233 self.consume_exprs(args);
236 hir::ExprKind::MethodCall(.., args, _) => {
238 self.consume_exprs(args);
241 hir::ExprKind::Struct(_, fields, ref opt_with) => {
242 self.walk_struct_expr(fields, opt_with);
245 hir::ExprKind::Tup(exprs) => {
246 self.consume_exprs(exprs);
249 hir::ExprKind::If(ref cond_expr, ref then_expr, ref opt_else_expr) => {
250 self.consume_expr(cond_expr);
251 self.consume_expr(then_expr);
252 if let Some(ref else_expr) = *opt_else_expr {
253 self.consume_expr(else_expr);
257 hir::ExprKind::Let(hir::Let { pat, init, .. }) => {
258 self.walk_local(init, pat, None, |t| t.borrow_expr(init, ty::ImmBorrow))
261 hir::ExprKind::Match(ref discr, arms, _) => {
262 let discr_place = return_if_err!(self.mc.cat_expr(discr));
263 self.maybe_read_scrutinee(
266 arms.iter().map(|arm| arm.pat),
269 // treatment of the discriminant is handled while walking the arms.
271 self.walk_arm(&discr_place, arm);
275 hir::ExprKind::Array(exprs) => {
276 self.consume_exprs(exprs);
279 hir::ExprKind::AddrOf(_, m, ref base) => {
281 // make sure that the thing we are pointing out stays valid
282 // for the lifetime `scope_r` of the resulting ptr:
283 let bk = ty::BorrowKind::from_mutbl(m);
284 self.borrow_expr(base, bk);
287 hir::ExprKind::InlineAsm(asm) => {
288 for (op, _op_sp) in asm.operands {
290 hir::InlineAsmOperand::In { expr, .. } => self.consume_expr(expr),
291 hir::InlineAsmOperand::Out { expr: Some(expr), .. }
292 | hir::InlineAsmOperand::InOut { expr, .. } => {
293 self.mutate_expr(expr);
295 hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
296 self.consume_expr(in_expr);
297 if let Some(out_expr) = out_expr {
298 self.mutate_expr(out_expr);
301 hir::InlineAsmOperand::Out { expr: None, .. }
302 | hir::InlineAsmOperand::Const { .. }
303 | hir::InlineAsmOperand::SymFn { .. }
304 | hir::InlineAsmOperand::SymStatic { .. } => {}
309 hir::ExprKind::Continue(..)
310 | hir::ExprKind::Lit(..)
311 | hir::ExprKind::ConstBlock(..)
312 | hir::ExprKind::Err => {}
314 hir::ExprKind::Loop(blk, ..) => {
315 self.walk_block(blk);
318 hir::ExprKind::Unary(_, lhs) => {
319 self.consume_expr(lhs);
322 hir::ExprKind::Binary(_, lhs, rhs) => {
323 self.consume_expr(lhs);
324 self.consume_expr(rhs);
327 hir::ExprKind::Block(blk, _) => {
328 self.walk_block(blk);
331 hir::ExprKind::Break(_, ref opt_expr) | hir::ExprKind::Ret(ref opt_expr) => {
332 if let Some(expr) = *opt_expr {
333 self.consume_expr(expr);
337 hir::ExprKind::Assign(lhs, rhs, _) => {
338 self.mutate_expr(lhs);
339 self.consume_expr(rhs);
342 hir::ExprKind::Cast(base, _) => {
343 self.consume_expr(base);
346 hir::ExprKind::DropTemps(expr) => {
347 self.consume_expr(expr);
350 hir::ExprKind::AssignOp(_, lhs, rhs) => {
351 if self.mc.typeck_results.is_method_call(expr) {
352 self.consume_expr(lhs);
354 self.mutate_expr(lhs);
356 self.consume_expr(rhs);
359 hir::ExprKind::Repeat(base, _) => {
360 self.consume_expr(base);
363 hir::ExprKind::Closure { .. } => {
364 self.walk_captures(expr);
367 hir::ExprKind::Box(ref base) => {
368 self.consume_expr(base);
371 hir::ExprKind::Yield(value, _) => {
372 self.consume_expr(value);
377 fn walk_stmt(&mut self, stmt: &hir::Stmt<'_>) {
379 hir::StmtKind::Local(hir::Local { pat, init: Some(expr), els, .. }) => {
380 self.walk_local(expr, pat, *els, |_| {})
383 hir::StmtKind::Local(_) => {}
385 hir::StmtKind::Item(_) => {
386 // We don't visit nested items in this visitor,
387 // only the fn body we were given.
390 hir::StmtKind::Expr(ref expr) | hir::StmtKind::Semi(ref expr) => {
391 self.consume_expr(expr);
396 fn maybe_read_scrutinee<'t>(
399 discr_place: PlaceWithHirId<'tcx>,
400 pats: impl Iterator<Item = &'t hir::Pat<'t>>,
402 // Matching should not always be considered a use of the place, hence
403 // discr does not necessarily need to be borrowed.
404 // We only want to borrow discr if the pattern contain something other
406 let ExprUseVisitor { ref mc, body_owner: _, delegate: _ } = *self;
407 let mut needs_to_be_read = false;
409 return_if_err!(mc.cat_pattern(discr_place.clone(), pat, |place, pat| {
411 PatKind::Binding(.., opt_sub_pat) => {
412 // If the opt_sub_pat is None, than the binding does not count as
413 // a wildcard for the purpose of borrowing discr.
414 if opt_sub_pat.is_none() {
415 needs_to_be_read = true;
418 PatKind::Path(qpath) => {
419 // A `Path` pattern is just a name like `Foo`. This is either a
420 // named constant or else it refers to an ADT variant
422 let res = self.mc.typeck_results.qpath_res(qpath, pat.hir_id);
424 Res::Def(DefKind::Const, _) | Res::Def(DefKind::AssocConst, _) => {
425 // Named constants have to be equated with the value
426 // being matched, so that's a read of the value being matched.
428 // FIXME: We don't actually reads for ZSTs.
429 needs_to_be_read = true;
432 // Otherwise, this is a struct/enum variant, and so it's
433 // only a read if we need to read the discriminant.
434 needs_to_be_read |= is_multivariant_adt(place.place.ty());
438 PatKind::TupleStruct(..) | PatKind::Struct(..) | PatKind::Tuple(..) => {
439 // For `Foo(..)`, `Foo { ... }` and `(...)` patterns, check if we are matching
440 // against a multivariant enum or struct. In that case, we have to read
441 // the discriminant. Otherwise this kind of pattern doesn't actually
442 // read anything (we'll get invoked for the `...`, which may indeed
443 // perform some reads).
445 let place_ty = place.place.ty();
446 needs_to_be_read |= is_multivariant_adt(place_ty);
448 PatKind::Lit(_) | PatKind::Range(..) => {
449 // If the PatKind is a Lit or a Range then we want
451 needs_to_be_read = true;
458 // If the PatKind is Or, Box, Slice or Ref, the decision is made later
459 // as these patterns contains subpatterns
460 // If the PatKind is Wild, the decision is made based on the other patterns being
467 if needs_to_be_read {
468 self.borrow_expr(discr, ty::ImmBorrow);
470 let closure_def_id = match discr_place.place.base {
471 PlaceBase::Upvar(upvar_id) => Some(upvar_id.closure_expr_id),
475 self.delegate.fake_read(
477 FakeReadCause::ForMatchedPlace(closure_def_id),
481 // We always want to walk the discriminant. We want to make sure, for instance,
482 // that the discriminant has been initialized.
483 self.walk_expr(discr);
489 expr: &hir::Expr<'_>,
491 els: Option<&hir::Block<'_>>,
496 self.walk_expr(expr);
497 let expr_place = return_if_err!(self.mc.cat_expr(expr));
499 if let Some(els) = els {
500 // borrowing because we need to test the descriminant
501 self.maybe_read_scrutinee(expr, expr_place.clone(), from_ref(pat).iter());
504 self.walk_irrefutable_pat(&expr_place, &pat);
507 /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
508 /// depending on its type.
509 fn walk_block(&mut self, blk: &hir::Block<'_>) {
510 debug!("walk_block(blk.hir_id={})", blk.hir_id);
512 for stmt in blk.stmts {
513 self.walk_stmt(stmt);
516 if let Some(ref tail_expr) = blk.expr {
517 self.consume_expr(tail_expr);
521 fn walk_struct_expr<'hir>(
523 fields: &[hir::ExprField<'_>],
524 opt_with: &Option<&'hir hir::Expr<'_>>,
526 // Consume the expressions supplying values for each field.
527 for field in fields {
528 self.consume_expr(field.expr);
531 let with_expr = match *opt_with {
538 let with_place = return_if_err!(self.mc.cat_expr(with_expr));
540 // Select just those fields of the `with`
541 // expression that will actually be used
542 match with_place.place.ty().kind() {
543 ty::Adt(adt, substs) if adt.is_struct() => {
544 // Consume those fields of the with expression that are needed.
545 for (f_index, with_field) in adt.non_enum_variant().fields.iter().enumerate() {
546 let is_mentioned = fields.iter().any(|f| {
547 self.tcx().field_index(f.hir_id, self.mc.typeck_results) == f_index
550 let field_place = self.mc.cat_projection(
553 with_field.ty(self.tcx(), substs),
554 ProjectionKind::Field(f_index as u32, VariantIdx::new(0)),
556 self.delegate_consume(&field_place, field_place.hir_id);
561 // the base expression should always evaluate to a
562 // struct; however, when EUV is run during typeck, it
563 // may not. This will generate an error earlier in typeck,
564 // so we can just ignore it.
565 if !self.tcx().sess.has_errors().is_some() {
566 span_bug!(with_expr.span, "with expression doesn't evaluate to a struct");
571 // walk the with expression so that complex expressions
572 // are properly handled.
573 self.walk_expr(with_expr);
576 /// Invoke the appropriate delegate calls for anything that gets
577 /// consumed or borrowed as part of the automatic adjustment
579 fn walk_adjustment(&mut self, expr: &hir::Expr<'_>) {
580 let adjustments = self.mc.typeck_results.expr_adjustments(expr);
581 let mut place_with_id = return_if_err!(self.mc.cat_expr_unadjusted(expr));
582 for adjustment in adjustments {
583 debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment);
584 match adjustment.kind {
585 adjustment::Adjust::NeverToAny | adjustment::Adjust::Pointer(_) => {
586 // Creating a closure/fn-pointer or unsizing consumes
587 // the input and stores it into the resulting rvalue.
588 self.delegate_consume(&place_with_id, place_with_id.hir_id);
591 adjustment::Adjust::Deref(None) => {}
593 // Autoderefs for overloaded Deref calls in fact reference
594 // their receiver. That is, if we have `(*x)` where `x`
595 // is of type `Rc<T>`, then this in fact is equivalent to
596 // `x.deref()`. Since `deref()` is declared with `&self`,
597 // this is an autoref of `x`.
598 adjustment::Adjust::Deref(Some(ref deref)) => {
599 let bk = ty::BorrowKind::from_mutbl(deref.mutbl);
600 self.delegate.borrow(&place_with_id, place_with_id.hir_id, bk);
603 adjustment::Adjust::Borrow(ref autoref) => {
604 self.walk_autoref(expr, &place_with_id, autoref);
608 return_if_err!(self.mc.cat_expr_adjusted(expr, place_with_id, adjustment));
612 /// Walks the autoref `autoref` applied to the autoderef'd
613 /// `expr`. `base_place` is the mem-categorized form of `expr`
614 /// after all relevant autoderefs have occurred.
617 expr: &hir::Expr<'_>,
618 base_place: &PlaceWithHirId<'tcx>,
619 autoref: &adjustment::AutoBorrow<'tcx>,
622 "walk_autoref(expr.hir_id={} base_place={:?} autoref={:?})",
623 expr.hir_id, base_place, autoref
627 adjustment::AutoBorrow::Ref(_, m) => {
628 self.delegate.borrow(
631 ty::BorrowKind::from_mutbl(m.into()),
635 adjustment::AutoBorrow::RawPtr(m) => {
636 debug!("walk_autoref: expr.hir_id={} base_place={:?}", expr.hir_id, base_place);
638 self.delegate.borrow(base_place, base_place.hir_id, ty::BorrowKind::from_mutbl(m));
643 fn walk_arm(&mut self, discr_place: &PlaceWithHirId<'tcx>, arm: &hir::Arm<'_>) {
644 let closure_def_id = match discr_place.place.base {
645 PlaceBase::Upvar(upvar_id) => Some(upvar_id.closure_expr_id),
649 self.delegate.fake_read(
651 FakeReadCause::ForMatchedPlace(closure_def_id),
654 self.walk_pat(discr_place, arm.pat, arm.guard.is_some());
656 if let Some(hir::Guard::If(e)) = arm.guard {
658 } else if let Some(hir::Guard::IfLet(ref l)) = arm.guard {
659 self.consume_expr(l.init)
662 self.consume_expr(arm.body);
665 /// Walks a pat that occurs in isolation (i.e., top-level of fn argument or
666 /// let binding, and *not* a match arm or nested pat.)
667 fn walk_irrefutable_pat(&mut self, discr_place: &PlaceWithHirId<'tcx>, pat: &hir::Pat<'_>) {
668 let closure_def_id = match discr_place.place.base {
669 PlaceBase::Upvar(upvar_id) => Some(upvar_id.closure_expr_id),
673 self.delegate.fake_read(
675 FakeReadCause::ForLet(closure_def_id),
678 self.walk_pat(discr_place, pat, false);
681 /// The core driver for walking a pattern
684 discr_place: &PlaceWithHirId<'tcx>,
688 debug!("walk_pat(discr_place={:?}, pat={:?}, has_guard={:?})", discr_place, pat, has_guard);
690 let tcx = self.tcx();
691 let ExprUseVisitor { ref mc, body_owner: _, ref mut delegate } = *self;
692 return_if_err!(mc.cat_pattern(discr_place.clone(), pat, |place, pat| {
693 if let PatKind::Binding(_, canonical_id, ..) = pat.kind {
694 debug!("walk_pat: binding place={:?} pat={:?}", place, pat);
696 mc.typeck_results.extract_binding_mode(tcx.sess, pat.hir_id, pat.span)
698 debug!("walk_pat: pat.hir_id={:?} bm={:?}", pat.hir_id, bm);
700 // pat_ty: the type of the binding being produced.
701 let pat_ty = return_if_err!(mc.node_ty(pat.hir_id));
702 debug!("walk_pat: pat_ty={:?}", pat_ty);
704 let def = Res::Local(canonical_id);
705 if let Ok(ref binding_place) = mc.cat_res(pat.hir_id, pat.span, pat_ty, def) {
706 delegate.bind(binding_place, binding_place.hir_id);
709 // Subtle: MIR desugaring introduces immutable borrows for each pattern
710 // binding when lowering pattern guards to ensure that the guard does not
711 // modify the scrutinee.
713 delegate.borrow(place, discr_place.hir_id, ImmBorrow);
716 // It is also a borrow or copy/move of the value being matched.
717 // In a cases of pattern like `let pat = upvar`, don't use the span
718 // of the pattern, as this just looks confusing, instead use the span
719 // of the discriminant.
721 ty::BindByReference(m) => {
722 let bk = ty::BorrowKind::from_mutbl(m);
723 delegate.borrow(place, discr_place.hir_id, bk);
725 ty::BindByValue(..) => {
726 debug!("walk_pat binding consuming pat");
727 delegate_consume(mc, *delegate, place, discr_place.hir_id);
735 /// Handle the case where the current body contains a closure.
737 /// When the current body being handled is a closure, then we must make sure that
738 /// - The parent closure only captures Places from the nested closure that are not local to it.
740 /// In the following example the closures `c` only captures `p.x` even though `incr`
741 /// is a capture of the nested closure
744 /// struct P { x: i32 }
745 /// let mut p = P { x: 4 };
748 /// let nested = || p.x += incr;
752 /// - When reporting the Place back to the Delegate, ensure that the UpvarId uses the enclosing
753 /// closure as the DefId.
754 fn walk_captures(&mut self, closure_expr: &hir::Expr<'_>) {
755 fn upvar_is_local_variable<'tcx>(
756 upvars: Option<&'tcx FxIndexMap<hir::HirId, hir::Upvar>>,
757 upvar_id: hir::HirId,
758 body_owner_is_closure: bool,
760 upvars.map(|upvars| !upvars.contains_key(&upvar_id)).unwrap_or(body_owner_is_closure)
763 debug!("walk_captures({:?})", closure_expr);
765 let tcx = self.tcx();
766 let closure_def_id = tcx.hir().local_def_id(closure_expr.hir_id);
767 let upvars = tcx.upvars_mentioned(self.body_owner);
769 // For purposes of this function, generator and closures are equivalent.
770 let body_owner_is_closure =
771 matches!(tcx.hir().body_owner_kind(self.body_owner), hir::BodyOwnerKind::Closure,);
773 // If we have a nested closure, we want to include the fake reads present in the nested closure.
774 if let Some(fake_reads) = self.mc.typeck_results.closure_fake_reads.get(&closure_def_id) {
775 for (fake_read, cause, hir_id) in fake_reads.iter() {
776 match fake_read.base {
777 PlaceBase::Upvar(upvar_id) => {
778 if upvar_is_local_variable(
780 upvar_id.var_path.hir_id,
781 body_owner_is_closure,
783 // The nested closure might be fake reading the current (enclosing) closure's local variables.
784 // The only places we want to fake read before creating the parent closure are the ones that
785 // are not local to it/ defined by it.
787 // ```rust,ignore(cannot-test-this-because-pseudo-code)
789 // let c = || { // fake reads: v1
791 // let e = || { // fake reads: v1, v2
797 // This check is performed when visiting the body of the outermost closure (`c`) and ensures
798 // that we don't add a fake read of v2 in c.
804 "Do not know how to get HirId out of Rvalue and StaticItem {:?}",
809 self.delegate.fake_read(
810 &PlaceWithHirId { place: fake_read.clone(), hir_id: *hir_id },
817 if let Some(min_captures) = self.mc.typeck_results.closure_min_captures.get(&closure_def_id)
819 for (var_hir_id, min_list) in min_captures.iter() {
820 if upvars.map_or(body_owner_is_closure, |upvars| !upvars.contains_key(var_hir_id)) {
821 // The nested closure might be capturing the current (enclosing) closure's local variables.
822 // We check if the root variable is ever mentioned within the enclosing closure, if not
823 // then for the current body (if it's a closure) these aren't captures, we will ignore them.
826 for captured_place in min_list {
827 let place = &captured_place.place;
828 let capture_info = captured_place.info;
830 let place_base = if body_owner_is_closure {
831 // Mark the place to be captured by the enclosing closure
832 PlaceBase::Upvar(ty::UpvarId::new(*var_hir_id, self.body_owner))
834 // If the body owner isn't a closure then the variable must
835 // be a local variable
836 PlaceBase::Local(*var_hir_id)
838 let place_with_id = PlaceWithHirId::new(
839 capture_info.path_expr_id.unwrap_or(
840 capture_info.capture_kind_expr_id.unwrap_or(closure_expr.hir_id),
844 place.projections.clone(),
847 match capture_info.capture_kind {
848 ty::UpvarCapture::ByValue => {
849 self.delegate_consume(&place_with_id, place_with_id.hir_id);
851 ty::UpvarCapture::ByRef(upvar_borrow) => {
852 self.delegate.borrow(
854 place_with_id.hir_id,
865 fn copy_or_move<'a, 'tcx>(
866 mc: &mc::MemCategorizationContext<'a, 'tcx>,
867 place_with_id: &PlaceWithHirId<'tcx>,
869 if !mc.type_is_copy_modulo_regions(
870 place_with_id.place.ty(),
871 mc.tcx().hir().span(place_with_id.hir_id),
879 // - If a place is used in a `ByValue` context then move it if it's not a `Copy` type.
880 // - If the place that is a `Copy` type consider it an `ImmBorrow`.
881 fn delegate_consume<'a, 'tcx>(
882 mc: &mc::MemCategorizationContext<'a, 'tcx>,
883 delegate: &mut (dyn Delegate<'tcx> + 'a),
884 place_with_id: &PlaceWithHirId<'tcx>,
885 diag_expr_id: hir::HirId,
887 debug!("delegate_consume(place_with_id={:?})", place_with_id);
889 let mode = copy_or_move(mc, place_with_id);
892 ConsumeMode::Move => delegate.consume(place_with_id, diag_expr_id),
893 ConsumeMode::Copy => delegate.copy(place_with_id, diag_expr_id),
897 fn is_multivariant_adt(ty: Ty<'_>) -> bool {
898 if let ty::Adt(def, _) = ty.kind() {
899 // Note that if a non-exhaustive SingleVariant is defined in another crate, we need
900 // to assume that more cases will be added to the variant in the future. This mean
901 // that we should handle non-exhaustive SingleVariant the same way we would handle
903 // If the variant is not local it must be defined in another crate.
904 let is_non_exhaustive = match def.adt_kind() {
905 AdtKind::Struct | AdtKind::Union => {
906 def.non_enum_variant().is_field_list_non_exhaustive()
908 AdtKind::Enum => def.is_variant_list_non_exhaustive(),
910 def.variants().len() > 1 || (!def.did().is_local() && is_non_exhaustive)