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.
6 // Export these here so that Clippy can use them.
7 pub use rustc_middle::hir::place::{Place, PlaceBase, PlaceWithHirId, Projection};
9 use rustc_data_structures::fx::FxIndexMap;
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;
22 use crate::mem_categorization as mc;
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`.
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.
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);
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).
46 place_with_id: &PlaceWithHirId<'tcx>,
47 diag_expr_id: hir::HirId,
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)
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);
63 /// The path at `binding_place` is a binding that is being initialized.
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)
72 /// The `place` should be a fake read because of specified `cause`.
73 fn fake_read(&mut self, place: Place<'tcx>, cause: FakeReadCause, diag_expr_id: hir::HirId);
76 #[derive(Copy, Clone, PartialEq, Debug)]
78 /// reference to x where x has a type that copies
80 /// reference to x where x has a type that moves
84 #[derive(Copy, Clone, PartialEq, Debug)]
93 /// The ExprUseVisitor type
95 /// This is the code that actually walks the tree.
96 pub struct ExprUseVisitor<'a, 'tcx> {
97 mc: mc::MemCategorizationContext<'a, 'tcx>,
98 body_owner: LocalDefId,
99 delegate: &'a mut dyn Delegate<'tcx>,
102 /// If the MC results in an error, it's because the type check
103 /// failed (or will fail, when the error is uncovered and reported
104 /// during writeback). In this case, we just ignore this part of the
107 /// Note that this macro appears similar to try!(), but, unlike try!(),
108 /// it does not propagate the error.
109 macro_rules! return_if_err {
114 debug!("mc reported err");
121 impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
122 /// Creates the ExprUseVisitor, configuring it with the various options provided:
124 /// - `delegate` -- who receives the callbacks
125 /// - `param_env` --- parameter environment for trait lookups (esp. pertaining to `Copy`)
126 /// - `typeck_results` --- typeck results for the code being analyzed
128 delegate: &'a mut (dyn Delegate<'tcx> + 'a),
129 infcx: &'a InferCtxt<'a, 'tcx>,
130 body_owner: LocalDefId,
131 param_env: ty::ParamEnv<'tcx>,
132 typeck_results: &'a ty::TypeckResults<'tcx>,
135 mc: mc::MemCategorizationContext::new(infcx, param_env, body_owner, typeck_results),
141 #[instrument(skip(self), level = "debug")]
142 pub fn consume_body(&mut self, body: &hir::Body<'_>) {
143 for param in body.params {
144 let param_ty = return_if_err!(self.mc.pat_ty_adjusted(param.pat));
145 debug!("consume_body: param_ty = {:?}", param_ty);
147 let param_place = self.mc.cat_rvalue(param.hir_id, param.pat.span, param_ty);
149 self.walk_irrefutable_pat(¶m_place, param.pat);
152 self.consume_expr(&body.value);
155 fn tcx(&self) -> TyCtxt<'tcx> {
159 fn delegate_consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId) {
160 delegate_consume(&self.mc, self.delegate, place_with_id, diag_expr_id)
163 fn consume_exprs(&mut self, exprs: &[hir::Expr<'_>]) {
165 self.consume_expr(expr);
169 pub fn consume_expr(&mut self, expr: &hir::Expr<'_>) {
170 debug!("consume_expr(expr={:?})", expr);
172 let place_with_id = return_if_err!(self.mc.cat_expr(expr));
173 self.delegate_consume(&place_with_id, place_with_id.hir_id);
174 self.walk_expr(expr);
177 fn mutate_expr(&mut self, expr: &hir::Expr<'_>) {
178 let place_with_id = return_if_err!(self.mc.cat_expr(expr));
179 self.delegate.mutate(&place_with_id, place_with_id.hir_id);
180 self.walk_expr(expr);
183 fn borrow_expr(&mut self, expr: &hir::Expr<'_>, bk: ty::BorrowKind) {
184 debug!("borrow_expr(expr={:?}, bk={:?})", expr, bk);
186 let place_with_id = return_if_err!(self.mc.cat_expr(expr));
187 self.delegate.borrow(&place_with_id, place_with_id.hir_id, bk);
192 fn select_from_expr(&mut self, expr: &hir::Expr<'_>) {
196 pub fn walk_expr(&mut self, expr: &hir::Expr<'_>) {
197 debug!("walk_expr(expr={:?})", expr);
199 self.walk_adjustment(expr);
202 hir::ExprKind::Path(_) => {}
204 hir::ExprKind::Type(subexpr, _) => self.walk_expr(subexpr),
206 hir::ExprKind::Unary(hir::UnOp::Deref, base) => {
208 self.select_from_expr(base);
211 hir::ExprKind::Field(base, _) => {
213 self.select_from_expr(base);
216 hir::ExprKind::Index(lhs, rhs) => {
218 self.select_from_expr(lhs);
219 self.consume_expr(rhs);
222 hir::ExprKind::Call(callee, args) => {
224 self.consume_expr(callee);
225 self.consume_exprs(args);
228 hir::ExprKind::MethodCall(.., args, _) => {
230 self.consume_exprs(args);
233 hir::ExprKind::Struct(_, fields, ref opt_with) => {
234 self.walk_struct_expr(fields, opt_with);
237 hir::ExprKind::Tup(exprs) => {
238 self.consume_exprs(exprs);
241 hir::ExprKind::If(ref cond_expr, ref then_expr, ref opt_else_expr) => {
242 self.consume_expr(cond_expr);
243 self.consume_expr(then_expr);
244 if let Some(ref else_expr) = *opt_else_expr {
245 self.consume_expr(else_expr);
249 hir::ExprKind::Let(hir::Let { pat, init, .. }) => {
250 self.walk_local(init, pat, |t| t.borrow_expr(init, ty::ImmBorrow));
253 hir::ExprKind::Match(ref discr, arms, _) => {
254 let discr_place = return_if_err!(self.mc.cat_expr(discr));
256 // Matching should not always be considered a use of the place, hence
257 // discr does not necessarily need to be borrowed.
258 // We only want to borrow discr if the pattern contain something other
260 let ExprUseVisitor { ref mc, body_owner: _, delegate: _ } = *self;
261 let mut needs_to_be_read = false;
262 for arm in arms.iter() {
263 return_if_err!(mc.cat_pattern(discr_place.clone(), arm.pat, |place, pat| {
265 PatKind::Binding(.., opt_sub_pat) => {
266 // If the opt_sub_pat is None, than the binding does not count as
267 // a wildcard for the purpose of borrowing discr.
268 if opt_sub_pat.is_none() {
269 needs_to_be_read = true;
272 PatKind::Path(qpath) => {
273 // A `Path` pattern is just a name like `Foo`. This is either a
274 // named constant or else it refers to an ADT variant
276 let res = self.mc.typeck_results.qpath_res(qpath, pat.hir_id);
278 Res::Def(DefKind::Const, _)
279 | Res::Def(DefKind::AssocConst, _) => {
280 // Named constants have to be equated with the value
281 // being matched, so that's a read of the value being matched.
283 // FIXME: We don't actually reads for ZSTs.
284 needs_to_be_read = true;
287 // Otherwise, this is a struct/enum variant, and so it's
288 // only a read if we need to read the discriminant.
289 needs_to_be_read |= is_multivariant_adt(place.place.ty());
293 PatKind::TupleStruct(..) | PatKind::Struct(..) | PatKind::Tuple(..) => {
294 // For `Foo(..)`, `Foo { ... }` and `(...)` patterns, check if we are matching
295 // against a multivariant enum or struct. In that case, we have to read
296 // the discriminant. Otherwise this kind of pattern doesn't actually
297 // read anything (we'll get invoked for the `...`, which may indeed
298 // perform some reads).
300 let place_ty = place.place.ty();
301 needs_to_be_read |= is_multivariant_adt(place_ty);
303 PatKind::Lit(_) | PatKind::Range(..) => {
304 // If the PatKind is a Lit or a Range then we want
306 needs_to_be_read = true;
313 // If the PatKind is Or, Box, Slice or Ref, the decision is made later
314 // as these patterns contains subpatterns
315 // If the PatKind is Wild, the decision is made based on the other patterns being
322 if needs_to_be_read {
323 self.borrow_expr(discr, ty::ImmBorrow);
325 let closure_def_id = match discr_place.place.base {
326 PlaceBase::Upvar(upvar_id) => Some(upvar_id.closure_expr_id.to_def_id()),
330 self.delegate.fake_read(
331 discr_place.place.clone(),
332 FakeReadCause::ForMatchedPlace(closure_def_id),
336 // We always want to walk the discriminant. We want to make sure, for instance,
337 // that the discriminant has been initialized.
338 self.walk_expr(discr);
341 // treatment of the discriminant is handled while walking the arms.
343 self.walk_arm(&discr_place, arm);
347 hir::ExprKind::Array(exprs) => {
348 self.consume_exprs(exprs);
351 hir::ExprKind::AddrOf(_, m, ref base) => {
353 // make sure that the thing we are pointing out stays valid
354 // for the lifetime `scope_r` of the resulting ptr:
355 let bk = ty::BorrowKind::from_mutbl(m);
356 self.borrow_expr(base, bk);
359 hir::ExprKind::InlineAsm(asm) => {
360 for (op, _op_sp) in asm.operands {
362 hir::InlineAsmOperand::In { expr, .. } => self.consume_expr(expr),
363 hir::InlineAsmOperand::Out { expr: Some(expr), .. }
364 | hir::InlineAsmOperand::InOut { expr, .. } => {
365 self.mutate_expr(expr);
367 hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
368 self.consume_expr(in_expr);
369 if let Some(out_expr) = out_expr {
370 self.mutate_expr(out_expr);
373 hir::InlineAsmOperand::Out { expr: None, .. }
374 | hir::InlineAsmOperand::Const { .. }
375 | hir::InlineAsmOperand::SymFn { .. }
376 | hir::InlineAsmOperand::SymStatic { .. } => {}
381 hir::ExprKind::Continue(..)
382 | hir::ExprKind::Lit(..)
383 | hir::ExprKind::ConstBlock(..)
384 | hir::ExprKind::Err => {}
386 hir::ExprKind::Loop(blk, ..) => {
387 self.walk_block(blk);
390 hir::ExprKind::Unary(_, lhs) => {
391 self.consume_expr(lhs);
394 hir::ExprKind::Binary(_, lhs, rhs) => {
395 self.consume_expr(lhs);
396 self.consume_expr(rhs);
399 hir::ExprKind::Block(blk, _) => {
400 self.walk_block(blk);
403 hir::ExprKind::Break(_, ref opt_expr) | hir::ExprKind::Ret(ref opt_expr) => {
404 if let Some(expr) = *opt_expr {
405 self.consume_expr(expr);
409 hir::ExprKind::Assign(lhs, rhs, _) => {
410 self.mutate_expr(lhs);
411 self.consume_expr(rhs);
414 hir::ExprKind::Cast(base, _) => {
415 self.consume_expr(base);
418 hir::ExprKind::DropTemps(expr) => {
419 self.consume_expr(expr);
422 hir::ExprKind::AssignOp(_, lhs, rhs) => {
423 if self.mc.typeck_results.is_method_call(expr) {
424 self.consume_expr(lhs);
426 self.mutate_expr(lhs);
428 self.consume_expr(rhs);
431 hir::ExprKind::Repeat(base, _) => {
432 self.consume_expr(base);
435 hir::ExprKind::Closure(..) => {
436 self.walk_captures(expr);
439 hir::ExprKind::Box(ref base) => {
440 self.consume_expr(base);
443 hir::ExprKind::Yield(value, _) => {
444 self.consume_expr(value);
449 fn walk_stmt(&mut self, stmt: &hir::Stmt<'_>) {
451 hir::StmtKind::Local(hir::Local { pat, init: Some(expr), .. }) => {
452 self.walk_local(expr, pat, |_| {});
455 hir::StmtKind::Local(_) => {}
457 hir::StmtKind::Item(_) => {
458 // We don't visit nested items in this visitor,
459 // only the fn body we were given.
462 hir::StmtKind::Expr(ref expr) | hir::StmtKind::Semi(ref expr) => {
463 self.consume_expr(expr);
468 fn walk_local<F>(&mut self, expr: &hir::Expr<'_>, pat: &hir::Pat<'_>, mut f: F)
472 self.walk_expr(expr);
473 let expr_place = return_if_err!(self.mc.cat_expr(expr));
475 self.walk_irrefutable_pat(&expr_place, &pat);
478 /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
479 /// depending on its type.
480 fn walk_block(&mut self, blk: &hir::Block<'_>) {
481 debug!("walk_block(blk.hir_id={})", blk.hir_id);
483 for stmt in blk.stmts {
484 self.walk_stmt(stmt);
487 if let Some(ref tail_expr) = blk.expr {
488 self.consume_expr(tail_expr);
492 fn walk_struct_expr<'hir>(
494 fields: &[hir::ExprField<'_>],
495 opt_with: &Option<&'hir hir::Expr<'_>>,
497 // Consume the expressions supplying values for each field.
498 for field in fields {
499 self.consume_expr(field.expr);
502 let with_expr = match *opt_with {
509 let with_place = return_if_err!(self.mc.cat_expr(with_expr));
511 // Select just those fields of the `with`
512 // expression that will actually be used
513 match with_place.place.ty().kind() {
514 ty::Adt(adt, substs) if adt.is_struct() => {
515 // Consume those fields of the with expression that are needed.
516 for (f_index, with_field) in adt.non_enum_variant().fields.iter().enumerate() {
517 let is_mentioned = fields.iter().any(|f| {
518 self.tcx().field_index(f.hir_id, self.mc.typeck_results) == f_index
521 let field_place = self.mc.cat_projection(
524 with_field.ty(self.tcx(), substs),
525 ProjectionKind::Field(f_index as u32, VariantIdx::new(0)),
527 self.delegate_consume(&field_place, field_place.hir_id);
532 // the base expression should always evaluate to a
533 // struct; however, when EUV is run during typeck, it
534 // may not. This will generate an error earlier in typeck,
535 // so we can just ignore it.
536 if !self.tcx().sess.has_errors().is_some() {
537 span_bug!(with_expr.span, "with expression doesn't evaluate to a struct");
542 // walk the with expression so that complex expressions
543 // are properly handled.
544 self.walk_expr(with_expr);
547 /// Invoke the appropriate delegate calls for anything that gets
548 /// consumed or borrowed as part of the automatic adjustment
550 fn walk_adjustment(&mut self, expr: &hir::Expr<'_>) {
551 let adjustments = self.mc.typeck_results.expr_adjustments(expr);
552 let mut place_with_id = return_if_err!(self.mc.cat_expr_unadjusted(expr));
553 for adjustment in adjustments {
554 debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment);
555 match adjustment.kind {
556 adjustment::Adjust::NeverToAny | adjustment::Adjust::Pointer(_) => {
557 // Creating a closure/fn-pointer or unsizing consumes
558 // the input and stores it into the resulting rvalue.
559 self.delegate_consume(&place_with_id, place_with_id.hir_id);
562 adjustment::Adjust::Deref(None) => {}
564 // Autoderefs for overloaded Deref calls in fact reference
565 // their receiver. That is, if we have `(*x)` where `x`
566 // is of type `Rc<T>`, then this in fact is equivalent to
567 // `x.deref()`. Since `deref()` is declared with `&self`,
568 // this is an autoref of `x`.
569 adjustment::Adjust::Deref(Some(ref deref)) => {
570 let bk = ty::BorrowKind::from_mutbl(deref.mutbl);
571 self.delegate.borrow(&place_with_id, place_with_id.hir_id, bk);
574 adjustment::Adjust::Borrow(ref autoref) => {
575 self.walk_autoref(expr, &place_with_id, autoref);
579 return_if_err!(self.mc.cat_expr_adjusted(expr, place_with_id, adjustment));
583 /// Walks the autoref `autoref` applied to the autoderef'd
584 /// `expr`. `base_place` is the mem-categorized form of `expr`
585 /// after all relevant autoderefs have occurred.
588 expr: &hir::Expr<'_>,
589 base_place: &PlaceWithHirId<'tcx>,
590 autoref: &adjustment::AutoBorrow<'tcx>,
593 "walk_autoref(expr.hir_id={} base_place={:?} autoref={:?})",
594 expr.hir_id, base_place, autoref
598 adjustment::AutoBorrow::Ref(_, m) => {
599 self.delegate.borrow(
602 ty::BorrowKind::from_mutbl(m.into()),
606 adjustment::AutoBorrow::RawPtr(m) => {
607 debug!("walk_autoref: expr.hir_id={} base_place={:?}", expr.hir_id, base_place);
609 self.delegate.borrow(base_place, base_place.hir_id, ty::BorrowKind::from_mutbl(m));
614 fn walk_arm(&mut self, discr_place: &PlaceWithHirId<'tcx>, arm: &hir::Arm<'_>) {
615 let closure_def_id = match discr_place.place.base {
616 PlaceBase::Upvar(upvar_id) => Some(upvar_id.closure_expr_id.to_def_id()),
620 self.delegate.fake_read(
621 discr_place.place.clone(),
622 FakeReadCause::ForMatchedPlace(closure_def_id),
625 self.walk_pat(discr_place, arm.pat, arm.guard.is_some());
627 if let Some(hir::Guard::If(e)) = arm.guard {
629 } else if let Some(hir::Guard::IfLet(ref l)) = arm.guard {
630 self.consume_expr(l.init)
633 self.consume_expr(arm.body);
636 /// Walks a pat that occurs in isolation (i.e., top-level of fn argument or
637 /// let binding, and *not* a match arm or nested pat.)
638 fn walk_irrefutable_pat(&mut self, discr_place: &PlaceWithHirId<'tcx>, pat: &hir::Pat<'_>) {
639 let closure_def_id = match discr_place.place.base {
640 PlaceBase::Upvar(upvar_id) => Some(upvar_id.closure_expr_id.to_def_id()),
644 self.delegate.fake_read(
645 discr_place.place.clone(),
646 FakeReadCause::ForLet(closure_def_id),
649 self.walk_pat(discr_place, pat, false);
652 /// The core driver for walking a pattern
655 discr_place: &PlaceWithHirId<'tcx>,
659 debug!("walk_pat(discr_place={:?}, pat={:?}, has_guard={:?})", discr_place, pat, has_guard);
661 let tcx = self.tcx();
662 let ExprUseVisitor { ref mc, body_owner: _, ref mut delegate } = *self;
663 return_if_err!(mc.cat_pattern(discr_place.clone(), pat, |place, pat| {
664 if let PatKind::Binding(_, canonical_id, ..) = pat.kind {
665 debug!("walk_pat: binding place={:?} pat={:?}", place, pat,);
667 mc.typeck_results.extract_binding_mode(tcx.sess, pat.hir_id, pat.span)
669 debug!("walk_pat: pat.hir_id={:?} bm={:?}", pat.hir_id, bm);
671 // pat_ty: the type of the binding being produced.
672 let pat_ty = return_if_err!(mc.node_ty(pat.hir_id));
673 debug!("walk_pat: pat_ty={:?}", pat_ty);
675 let def = Res::Local(canonical_id);
676 if let Ok(ref binding_place) = mc.cat_res(pat.hir_id, pat.span, pat_ty, def) {
677 delegate.bind(binding_place, binding_place.hir_id);
680 // Subtle: MIR desugaring introduces immutable borrows for each pattern
681 // binding when lowering pattern guards to ensure that the guard does not
682 // modify the scrutinee.
684 delegate.borrow(place, discr_place.hir_id, ImmBorrow);
687 // It is also a borrow or copy/move of the value being matched.
688 // In a cases of pattern like `let pat = upvar`, don't use the span
689 // of the pattern, as this just looks confusing, instead use the span
690 // of the discriminant.
692 ty::BindByReference(m) => {
693 let bk = ty::BorrowKind::from_mutbl(m);
694 delegate.borrow(place, discr_place.hir_id, bk);
696 ty::BindByValue(..) => {
697 debug!("walk_pat binding consuming pat");
698 delegate_consume(mc, *delegate, place, discr_place.hir_id);
706 /// Handle the case where the current body contains a closure.
708 /// When the current body being handled is a closure, then we must make sure that
709 /// - The parent closure only captures Places from the nested closure that are not local to it.
711 /// In the following example the closures `c` only captures `p.x` even though `incr`
712 /// is a capture of the nested closure
715 /// struct P { x: i32 }
716 /// let mut p = P { x: 4 };
719 /// let nested = || p.x += incr;
723 /// - When reporting the Place back to the Delegate, ensure that the UpvarId uses the enclosing
724 /// closure as the DefId.
725 fn walk_captures(&mut self, closure_expr: &hir::Expr<'_>) {
726 fn upvar_is_local_variable<'tcx>(
727 upvars: Option<&'tcx FxIndexMap<hir::HirId, hir::Upvar>>,
728 upvar_id: hir::HirId,
729 body_owner_is_closure: bool,
731 upvars.map(|upvars| !upvars.contains_key(&upvar_id)).unwrap_or(body_owner_is_closure)
734 debug!("walk_captures({:?})", closure_expr);
736 let tcx = self.tcx();
737 let closure_def_id = tcx.hir().local_def_id(closure_expr.hir_id).to_def_id();
738 let upvars = tcx.upvars_mentioned(self.body_owner);
740 // For purposes of this function, generator and closures are equivalent.
741 let body_owner_is_closure =
742 matches!(tcx.hir().body_owner_kind(self.body_owner), hir::BodyOwnerKind::Closure,);
744 // If we have a nested closure, we want to include the fake reads present in the nested closure.
745 if let Some(fake_reads) = self.mc.typeck_results.closure_fake_reads.get(&closure_def_id) {
746 for (fake_read, cause, hir_id) in fake_reads.iter() {
747 match fake_read.base {
748 PlaceBase::Upvar(upvar_id) => {
749 if upvar_is_local_variable(
751 upvar_id.var_path.hir_id,
752 body_owner_is_closure,
754 // The nested closure might be fake reading the current (enclosing) closure's local variables.
755 // The only places we want to fake read before creating the parent closure are the ones that
756 // are not local to it/ defined by it.
758 // ```rust,ignore(cannot-test-this-because-pseudo-code)
760 // let c = || { // fake reads: v1
762 // let e = || { // fake reads: v1, v2
768 // This check is performed when visiting the body of the outermost closure (`c`) and ensures
769 // that we don't add a fake read of v2 in c.
775 "Do not know how to get HirId out of Rvalue and StaticItem {:?}",
780 self.delegate.fake_read(fake_read.clone(), *cause, *hir_id);
784 if let Some(min_captures) = self.mc.typeck_results.closure_min_captures.get(&closure_def_id)
786 for (var_hir_id, min_list) in min_captures.iter() {
787 if upvars.map_or(body_owner_is_closure, |upvars| !upvars.contains_key(var_hir_id)) {
788 // The nested closure might be capturing the current (enclosing) closure's local variables.
789 // We check if the root variable is ever mentioned within the enclosing closure, if not
790 // then for the current body (if it's a closure) these aren't captures, we will ignore them.
793 for captured_place in min_list {
794 let place = &captured_place.place;
795 let capture_info = captured_place.info;
797 let place_base = if body_owner_is_closure {
798 // Mark the place to be captured by the enclosing closure
799 PlaceBase::Upvar(ty::UpvarId::new(*var_hir_id, self.body_owner))
801 // If the body owner isn't a closure then the variable must
802 // be a local variable
803 PlaceBase::Local(*var_hir_id)
805 let place_with_id = PlaceWithHirId::new(
806 capture_info.path_expr_id.unwrap_or(
807 capture_info.capture_kind_expr_id.unwrap_or(closure_expr.hir_id),
811 place.projections.clone(),
814 match capture_info.capture_kind {
815 ty::UpvarCapture::ByValue => {
816 self.delegate_consume(&place_with_id, place_with_id.hir_id);
818 ty::UpvarCapture::ByRef(upvar_borrow) => {
819 self.delegate.borrow(
821 place_with_id.hir_id,
832 fn copy_or_move<'a, 'tcx>(
833 mc: &mc::MemCategorizationContext<'a, 'tcx>,
834 place_with_id: &PlaceWithHirId<'tcx>,
836 if !mc.type_is_copy_modulo_regions(
837 place_with_id.place.ty(),
838 mc.tcx().hir().span(place_with_id.hir_id),
846 // - If a place is used in a `ByValue` context then move it if it's not a `Copy` type.
847 // - If the place that is a `Copy` type consider it an `ImmBorrow`.
848 fn delegate_consume<'a, 'tcx>(
849 mc: &mc::MemCategorizationContext<'a, 'tcx>,
850 delegate: &mut (dyn Delegate<'tcx> + 'a),
851 place_with_id: &PlaceWithHirId<'tcx>,
852 diag_expr_id: hir::HirId,
854 debug!("delegate_consume(place_with_id={:?})", place_with_id);
856 let mode = copy_or_move(mc, place_with_id);
859 ConsumeMode::Move => delegate.consume(place_with_id, diag_expr_id),
860 ConsumeMode::Copy => delegate.copy(place_with_id, diag_expr_id),
864 fn is_multivariant_adt(ty: Ty<'_>) -> bool {
865 if let ty::Adt(def, _) = ty.kind() {
866 // Note that if a non-exhaustive SingleVariant is defined in another crate, we need
867 // to assume that more cases will be added to the variant in the future. This mean
868 // that we should handle non-exhaustive SingleVariant the same way we would handle
870 // If the variant is not local it must be defined in another crate.
871 let is_non_exhaustive = match def.adt_kind() {
872 AdtKind::Struct | AdtKind::Union => {
873 def.non_enum_variant().is_field_list_non_exhaustive()
875 AdtKind::Enum => def.is_variant_list_non_exhaustive(),
877 def.variants().len() > 1 || (!def.did().is_local() && is_non_exhaustive)