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`.
75 place_with_id: &PlaceWithHirId<'tcx>,
77 diag_expr_id: hir::HirId,
81 #[derive(Copy, Clone, PartialEq, Debug)]
83 /// reference to x where x has a type that copies
85 /// reference to x where x has a type that moves
89 #[derive(Copy, Clone, PartialEq, Debug)]
98 /// The ExprUseVisitor type
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>,
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
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 {
119 debug!("mc reported err");
126 impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
127 /// Creates the ExprUseVisitor, configuring it with the various options provided:
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
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>,
140 mc: mc::MemCategorizationContext::new(infcx, param_env, body_owner, typeck_results),
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);
152 let param_place = self.mc.cat_rvalue(param.hir_id, param.pat.span, param_ty);
154 self.walk_irrefutable_pat(¶m_place, param.pat);
157 self.consume_expr(&body.value);
160 fn tcx(&self) -> TyCtxt<'tcx> {
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)
168 fn consume_exprs(&mut self, exprs: &[hir::Expr<'_>]) {
170 self.consume_expr(expr);
174 pub fn consume_expr(&mut self, expr: &hir::Expr<'_>) {
175 debug!("consume_expr(expr={:?})", expr);
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);
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);
188 fn borrow_expr(&mut self, expr: &hir::Expr<'_>, bk: ty::BorrowKind) {
189 debug!("borrow_expr(expr={:?}, bk={:?})", expr, bk);
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);
197 fn select_from_expr(&mut self, expr: &hir::Expr<'_>) {
201 pub fn walk_expr(&mut self, expr: &hir::Expr<'_>) {
202 debug!("walk_expr(expr={:?})", expr);
204 self.walk_adjustment(expr);
207 hir::ExprKind::Path(_) => {}
209 hir::ExprKind::Type(subexpr, _) => self.walk_expr(subexpr),
211 hir::ExprKind::Unary(hir::UnOp::Deref, base) => {
213 self.select_from_expr(base);
216 hir::ExprKind::Field(base, _) => {
218 self.select_from_expr(base);
221 hir::ExprKind::Index(lhs, rhs) => {
223 self.select_from_expr(lhs);
224 self.consume_expr(rhs);
227 hir::ExprKind::Call(callee, args) => {
229 self.consume_expr(callee);
230 self.consume_exprs(args);
233 hir::ExprKind::MethodCall(.., args, _) => {
235 self.consume_exprs(args);
238 hir::ExprKind::Struct(_, fields, ref opt_with) => {
239 self.walk_struct_expr(fields, opt_with);
242 hir::ExprKind::Tup(exprs) => {
243 self.consume_exprs(exprs);
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);
254 hir::ExprKind::Let(hir::Let { pat, init, .. }) => {
255 self.walk_local(init, pat, |t| t.borrow_expr(init, ty::ImmBorrow));
258 hir::ExprKind::Match(ref discr, arms, _) => {
259 let discr_place = return_if_err!(self.mc.cat_expr(discr));
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
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| {
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;
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
281 let res = self.mc.typeck_results.qpath_res(qpath, pat.hir_id);
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.
288 // FIXME: We don't actually reads for ZSTs.
289 needs_to_be_read = true;
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());
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).
305 let place_ty = place.place.ty();
306 needs_to_be_read |= is_multivariant_adt(place_ty);
308 PatKind::Lit(_) | PatKind::Range(..) => {
309 // If the PatKind is a Lit or a Range then we want
311 needs_to_be_read = true;
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
327 if needs_to_be_read {
328 self.borrow_expr(discr, ty::ImmBorrow);
330 let closure_def_id = match discr_place.place.base {
331 PlaceBase::Upvar(upvar_id) => Some(upvar_id.closure_expr_id.to_def_id()),
335 self.delegate.fake_read(
337 FakeReadCause::ForMatchedPlace(closure_def_id),
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);
346 // treatment of the discriminant is handled while walking the arms.
348 self.walk_arm(&discr_place, arm);
352 hir::ExprKind::Array(exprs) => {
353 self.consume_exprs(exprs);
356 hir::ExprKind::AddrOf(_, m, ref 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);
364 hir::ExprKind::InlineAsm(asm) => {
365 for (op, _op_sp) in asm.operands {
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);
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);
378 hir::InlineAsmOperand::Out { expr: None, .. }
379 | hir::InlineAsmOperand::Const { .. }
380 | hir::InlineAsmOperand::SymFn { .. }
381 | hir::InlineAsmOperand::SymStatic { .. } => {}
386 hir::ExprKind::Continue(..)
387 | hir::ExprKind::Lit(..)
388 | hir::ExprKind::ConstBlock(..)
389 | hir::ExprKind::Err => {}
391 hir::ExprKind::Loop(blk, ..) => {
392 self.walk_block(blk);
395 hir::ExprKind::Unary(_, lhs) => {
396 self.consume_expr(lhs);
399 hir::ExprKind::Binary(_, lhs, rhs) => {
400 self.consume_expr(lhs);
401 self.consume_expr(rhs);
404 hir::ExprKind::Block(blk, _) => {
405 self.walk_block(blk);
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);
414 hir::ExprKind::Assign(lhs, rhs, _) => {
415 self.mutate_expr(lhs);
416 self.consume_expr(rhs);
419 hir::ExprKind::Cast(base, _) => {
420 self.consume_expr(base);
423 hir::ExprKind::DropTemps(expr) => {
424 self.consume_expr(expr);
427 hir::ExprKind::AssignOp(_, lhs, rhs) => {
428 if self.mc.typeck_results.is_method_call(expr) {
429 self.consume_expr(lhs);
431 self.mutate_expr(lhs);
433 self.consume_expr(rhs);
436 hir::ExprKind::Repeat(base, _) => {
437 self.consume_expr(base);
440 hir::ExprKind::Closure(..) => {
441 self.walk_captures(expr);
444 hir::ExprKind::Box(ref base) => {
445 self.consume_expr(base);
448 hir::ExprKind::Yield(value, _) => {
449 self.consume_expr(value);
454 fn walk_stmt(&mut self, stmt: &hir::Stmt<'_>) {
456 hir::StmtKind::Local(hir::Local { pat, init: Some(expr), .. }) => {
457 self.walk_local(expr, pat, |_| {});
460 hir::StmtKind::Local(_) => {}
462 hir::StmtKind::Item(_) => {
463 // We don't visit nested items in this visitor,
464 // only the fn body we were given.
467 hir::StmtKind::Expr(ref expr) | hir::StmtKind::Semi(ref expr) => {
468 self.consume_expr(expr);
473 fn walk_local<F>(&mut self, expr: &hir::Expr<'_>, pat: &hir::Pat<'_>, mut f: F)
477 self.walk_expr(expr);
478 let expr_place = return_if_err!(self.mc.cat_expr(expr));
480 self.walk_irrefutable_pat(&expr_place, &pat);
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);
488 for stmt in blk.stmts {
489 self.walk_stmt(stmt);
492 if let Some(ref tail_expr) = blk.expr {
493 self.consume_expr(tail_expr);
497 fn walk_struct_expr<'hir>(
499 fields: &[hir::ExprField<'_>],
500 opt_with: &Option<&'hir hir::Expr<'_>>,
502 // Consume the expressions supplying values for each field.
503 for field in fields {
504 self.consume_expr(field.expr);
507 let with_expr = match *opt_with {
514 let with_place = return_if_err!(self.mc.cat_expr(with_expr));
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
526 let field_place = self.mc.cat_projection(
529 with_field.ty(self.tcx(), substs),
530 ProjectionKind::Field(f_index as u32, VariantIdx::new(0)),
532 self.delegate_consume(&field_place, field_place.hir_id);
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");
547 // walk the with expression so that complex expressions
548 // are properly handled.
549 self.walk_expr(with_expr);
552 /// Invoke the appropriate delegate calls for anything that gets
553 /// consumed or borrowed as part of the automatic adjustment
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);
567 adjustment::Adjust::Deref(None) => {}
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);
579 adjustment::Adjust::Borrow(ref autoref) => {
580 self.walk_autoref(expr, &place_with_id, autoref);
584 return_if_err!(self.mc.cat_expr_adjusted(expr, place_with_id, adjustment));
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.
593 expr: &hir::Expr<'_>,
594 base_place: &PlaceWithHirId<'tcx>,
595 autoref: &adjustment::AutoBorrow<'tcx>,
598 "walk_autoref(expr.hir_id={} base_place={:?} autoref={:?})",
599 expr.hir_id, base_place, autoref
603 adjustment::AutoBorrow::Ref(_, m) => {
604 self.delegate.borrow(
607 ty::BorrowKind::from_mutbl(m.into()),
611 adjustment::AutoBorrow::RawPtr(m) => {
612 debug!("walk_autoref: expr.hir_id={} base_place={:?}", expr.hir_id, base_place);
614 self.delegate.borrow(base_place, base_place.hir_id, ty::BorrowKind::from_mutbl(m));
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()),
625 self.delegate.fake_read(
627 FakeReadCause::ForMatchedPlace(closure_def_id),
630 self.walk_pat(discr_place, arm.pat, arm.guard.is_some());
632 if let Some(hir::Guard::If(e)) = arm.guard {
634 } else if let Some(hir::Guard::IfLet(ref l)) = arm.guard {
635 self.consume_expr(l.init)
638 self.consume_expr(arm.body);
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()),
649 self.delegate.fake_read(
651 FakeReadCause::ForLet(closure_def_id),
654 self.walk_pat(discr_place, pat, false);
657 /// The core driver for walking a pattern
660 discr_place: &PlaceWithHirId<'tcx>,
664 debug!("walk_pat(discr_place={:?}, pat={:?}, has_guard={:?})", discr_place, pat, has_guard);
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,);
672 mc.typeck_results.extract_binding_mode(tcx.sess, pat.hir_id, pat.span)
674 debug!("walk_pat: pat.hir_id={:?} bm={:?}", pat.hir_id, bm);
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);
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);
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.
689 delegate.borrow(place, discr_place.hir_id, ImmBorrow);
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.
697 ty::BindByReference(m) => {
698 let bk = ty::BorrowKind::from_mutbl(m);
699 delegate.borrow(place, discr_place.hir_id, bk);
701 ty::BindByValue(..) => {
702 debug!("walk_pat binding consuming pat");
703 delegate_consume(mc, *delegate, place, discr_place.hir_id);
711 /// Handle the case where the current body contains a closure.
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.
716 /// In the following example the closures `c` only captures `p.x` even though `incr`
717 /// is a capture of the nested closure
720 /// struct P { x: i32 }
721 /// let mut p = P { x: 4 };
724 /// let nested = || p.x += incr;
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,
736 upvars.map(|upvars| !upvars.contains_key(&upvar_id)).unwrap_or(body_owner_is_closure)
739 debug!("walk_captures({:?})", closure_expr);
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);
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,);
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(
756 upvar_id.var_path.hir_id,
757 body_owner_is_closure,
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.
763 // ```rust,ignore(cannot-test-this-because-pseudo-code)
765 // let c = || { // fake reads: v1
767 // let e = || { // fake reads: v1, v2
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.
780 "Do not know how to get HirId out of Rvalue and StaticItem {:?}",
785 self.delegate.fake_read(
786 &PlaceWithHirId { place: fake_read.clone(), hir_id: *hir_id },
793 if let Some(min_captures) = self.mc.typeck_results.closure_min_captures.get(&closure_def_id)
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.
802 for captured_place in min_list {
803 let place = &captured_place.place;
804 let capture_info = captured_place.info;
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))
810 // If the body owner isn't a closure then the variable must
811 // be a local variable
812 PlaceBase::Local(*var_hir_id)
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),
820 place.projections.clone(),
823 match capture_info.capture_kind {
824 ty::UpvarCapture::ByValue => {
825 self.delegate_consume(&place_with_id, place_with_id.hir_id);
827 ty::UpvarCapture::ByRef(upvar_borrow) => {
828 self.delegate.borrow(
830 place_with_id.hir_id,
841 fn copy_or_move<'a, 'tcx>(
842 mc: &mc::MemCategorizationContext<'a, 'tcx>,
843 place_with_id: &PlaceWithHirId<'tcx>,
845 if !mc.type_is_copy_modulo_regions(
846 place_with_id.place.ty(),
847 mc.tcx().hir().span(place_with_id.hir_id),
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,
863 debug!("delegate_consume(place_with_id={:?})", place_with_id);
865 let mode = copy_or_move(mc, place_with_id);
868 ConsumeMode::Move => delegate.consume(place_with_id, diag_expr_id),
869 ConsumeMode::Copy => delegate.copy(place_with_id, diag_expr_id),
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
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()
884 AdtKind::Enum => def.is_variant_list_non_exhaustive(),
886 def.variants().len() > 1 || (!def.did().is_local() && is_non_exhaustive)