rustc_hir_typeck/
upvar.rs

1//! ### Inferring borrow kinds for upvars
2//!
3//! Whenever there is a closure expression, we need to determine how each
4//! upvar is used. We do this by initially assigning each upvar an
5//! immutable "borrow kind" (see `ty::BorrowKind` for details) and then
6//! "escalating" the kind as needed. The borrow kind proceeds according to
7//! the following lattice:
8//! ```ignore (not-rust)
9//! ty::ImmBorrow -> ty::UniqueImmBorrow -> ty::MutBorrow
10//! ```
11//! So, for example, if we see an assignment `x = 5` to an upvar `x`, we
12//! will promote its borrow kind to mutable borrow. If we see an `&mut x`
13//! we'll do the same. Naturally, this applies not just to the upvar, but
14//! to everything owned by `x`, so the result is the same for something
15//! like `x.f = 5` and so on (presuming `x` is not a borrowed pointer to a
16//! struct). These adjustments are performed in
17//! `adjust_for_non_move_closure` (you can trace backwards through the code
18//! from there).
19//!
20//! The fact that we are inferring borrow kinds as we go results in a
21//! semi-hacky interaction with the way `ExprUseVisitor` is computing
22//! `Place`s. In particular, it will query the current borrow kind as it
23//! goes, and we'll return the *current* value, but this may get
24//! adjusted later. Therefore, in this module, we generally ignore the
25//! borrow kind (and derived mutabilities) that `ExprUseVisitor` returns
26//! within `Place`s, since they may be inaccurate. (Another option
27//! would be to use a unification scheme, where instead of returning a
28//! concrete borrow kind like `ty::ImmBorrow`, we return a
29//! `ty::InferBorrow(upvar_id)` or something like that, but this would
30//! then mean that all later passes would have to check for these figments
31//! and report an error, and it just seems like more mess in the end.)
32
33use std::iter;
34
35use rustc_abi::FIRST_VARIANT;
36use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
37use rustc_data_structures::unord::{ExtendUnord, UnordSet};
38use rustc_errors::{Applicability, MultiSpan};
39use rustc_hir as hir;
40use rustc_hir::HirId;
41use rustc_hir::def_id::LocalDefId;
42use rustc_hir::intravisit::{self, Visitor};
43use rustc_middle::hir::place::{Place, PlaceBase, PlaceWithHirId, Projection, ProjectionKind};
44use rustc_middle::mir::FakeReadCause;
45use rustc_middle::traits::ObligationCauseCode;
46use rustc_middle::ty::{
47    self, BorrowKind, ClosureSizeProfileData, Ty, TyCtxt, TypeVisitableExt as _, TypeckResults,
48    UpvarArgs, UpvarCapture,
49};
50use rustc_middle::{bug, span_bug};
51use rustc_session::lint;
52use rustc_span::{BytePos, Pos, Span, Symbol, sym};
53use rustc_trait_selection::infer::InferCtxtExt;
54use tracing::{debug, instrument};
55
56use super::FnCtxt;
57use crate::expr_use_visitor as euv;
58
59/// Describe the relationship between the paths of two places
60/// eg:
61/// - `foo` is ancestor of `foo.bar.baz`
62/// - `foo.bar.baz` is an descendant of `foo.bar`
63/// - `foo.bar` and `foo.baz` are divergent
64enum PlaceAncestryRelation {
65    Ancestor,
66    Descendant,
67    SamePlace,
68    Divergent,
69}
70
71/// Intermediate format to store a captured `Place` and associated `ty::CaptureInfo`
72/// during capture analysis. Information in this map feeds into the minimum capture
73/// analysis pass.
74type InferredCaptureInformation<'tcx> = Vec<(Place<'tcx>, ty::CaptureInfo)>;
75
76impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
77    pub(crate) fn closure_analyze(&self, body: &'tcx hir::Body<'tcx>) {
78        InferBorrowKindVisitor { fcx: self }.visit_body(body);
79
80        // it's our job to process these.
81        assert!(self.deferred_call_resolutions.borrow().is_empty());
82    }
83}
84
85/// Intermediate format to store the hir_id pointing to the use that resulted in the
86/// corresponding place being captured and a String which contains the captured value's
87/// name (i.e: a.b.c)
88#[derive(Clone, Debug, PartialEq, Eq, Hash)]
89enum UpvarMigrationInfo {
90    /// We previously captured all of `x`, but now we capture some sub-path.
91    CapturingPrecise { source_expr: Option<HirId>, var_name: String },
92    CapturingNothing {
93        // where the variable appears in the closure (but is not captured)
94        use_span: Span,
95    },
96}
97
98/// Reasons that we might issue a migration warning.
99#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
100struct MigrationWarningReason {
101    /// When we used to capture `x` in its entirety, we implemented the auto-trait(s)
102    /// in this vec, but now we don't.
103    auto_traits: Vec<&'static str>,
104
105    /// When we used to capture `x` in its entirety, we would execute some destructors
106    /// at a different time.
107    drop_order: bool,
108}
109
110impl MigrationWarningReason {
111    fn migration_message(&self) -> String {
112        let base = "changes to closure capture in Rust 2021 will affect";
113        if !self.auto_traits.is_empty() && self.drop_order {
114            format!("{base} drop order and which traits the closure implements")
115        } else if self.drop_order {
116            format!("{base} drop order")
117        } else {
118            format!("{base} which traits the closure implements")
119        }
120    }
121}
122
123/// Intermediate format to store information needed to generate a note in the migration lint.
124struct MigrationLintNote {
125    captures_info: UpvarMigrationInfo,
126
127    /// reasons why migration is needed for this capture
128    reason: MigrationWarningReason,
129}
130
131/// Intermediate format to store the hir id of the root variable and a HashSet containing
132/// information on why the root variable should be fully captured
133struct NeededMigration {
134    var_hir_id: HirId,
135    diagnostics_info: Vec<MigrationLintNote>,
136}
137
138struct InferBorrowKindVisitor<'a, 'tcx> {
139    fcx: &'a FnCtxt<'a, 'tcx>,
140}
141
142impl<'a, 'tcx> Visitor<'tcx> for InferBorrowKindVisitor<'a, 'tcx> {
143    fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
144        match expr.kind {
145            hir::ExprKind::Closure(&hir::Closure { capture_clause, body: body_id, .. }) => {
146                let body = self.fcx.tcx.hir_body(body_id);
147                self.visit_body(body);
148                self.fcx.analyze_closure(expr.hir_id, expr.span, body_id, body, capture_clause);
149            }
150            _ => {}
151        }
152
153        intravisit::walk_expr(self, expr);
154    }
155
156    fn visit_inline_const(&mut self, c: &'tcx hir::ConstBlock) {
157        let body = self.fcx.tcx.hir_body(c.body);
158        self.visit_body(body);
159    }
160}
161
162impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
163    /// Analysis starting point.
164    #[instrument(skip(self, body), level = "debug")]
165    fn analyze_closure(
166        &self,
167        closure_hir_id: HirId,
168        span: Span,
169        body_id: hir::BodyId,
170        body: &'tcx hir::Body<'tcx>,
171        mut capture_clause: hir::CaptureBy,
172    ) {
173        // Extract the type of the closure.
174        let ty = self.node_ty(closure_hir_id);
175        let (closure_def_id, args, infer_kind) = match *ty.kind() {
176            ty::Closure(def_id, args) => {
177                (def_id, UpvarArgs::Closure(args), self.closure_kind(ty).is_none())
178            }
179            ty::CoroutineClosure(def_id, args) => {
180                (def_id, UpvarArgs::CoroutineClosure(args), self.closure_kind(ty).is_none())
181            }
182            ty::Coroutine(def_id, args) => (def_id, UpvarArgs::Coroutine(args), false),
183            ty::Error(_) => {
184                // #51714: skip analysis when we have already encountered type errors
185                return;
186            }
187            _ => {
188                span_bug!(
189                    span,
190                    "type of closure expr {:?} is not a closure {:?}",
191                    closure_hir_id,
192                    ty
193                );
194            }
195        };
196        let args = self.resolve_vars_if_possible(args);
197        let closure_def_id = closure_def_id.expect_local();
198
199        assert_eq!(self.tcx.hir_body_owner_def_id(body.id()), closure_def_id);
200        let mut delegate = InferBorrowKind {
201            closure_def_id,
202            capture_information: Default::default(),
203            fake_reads: Default::default(),
204        };
205
206        let _ = euv::ExprUseVisitor::new(
207            &FnCtxt::new(self, self.tcx.param_env(closure_def_id), closure_def_id),
208            &mut delegate,
209        )
210        .consume_body(body);
211
212        // There are several curious situations with coroutine-closures where
213        // analysis is too aggressive with borrows when the coroutine-closure is
214        // marked `move`. Specifically:
215        //
216        // 1. If the coroutine-closure was inferred to be `FnOnce` during signature
217        // inference, then it's still possible that we try to borrow upvars from
218        // the coroutine-closure because they are not used by the coroutine body
219        // in a way that forces a move. See the test:
220        // `async-await/async-closures/force-move-due-to-inferred-kind.rs`.
221        //
222        // 2. If the coroutine-closure is forced to be `FnOnce` due to the way it
223        // uses its upvars (e.g. it consumes a non-copy value), but not *all* upvars
224        // would force the closure to `FnOnce`.
225        // See the test: `async-await/async-closures/force-move-due-to-actually-fnonce.rs`.
226        //
227        // This would lead to an impossible to satisfy situation, since `AsyncFnOnce`
228        // coroutine bodies can't borrow from their parent closure. To fix this,
229        // we force the inner coroutine to also be `move`. This only matters for
230        // coroutine-closures that are `move` since otherwise they themselves will
231        // be borrowing from the outer environment, so there's no self-borrows occurring.
232        if let UpvarArgs::Coroutine(..) = args
233            && let hir::CoroutineKind::Desugared(_, hir::CoroutineSource::Closure) =
234                self.tcx.coroutine_kind(closure_def_id).expect("coroutine should have kind")
235            && let parent_hir_id =
236                self.tcx.local_def_id_to_hir_id(self.tcx.local_parent(closure_def_id))
237            && let parent_ty = self.node_ty(parent_hir_id)
238            && let hir::CaptureBy::Value { move_kw } =
239                self.tcx.hir_node(parent_hir_id).expect_closure().capture_clause
240        {
241            // (1.) Closure signature inference forced this closure to `FnOnce`.
242            if let Some(ty::ClosureKind::FnOnce) = self.closure_kind(parent_ty) {
243                capture_clause = hir::CaptureBy::Value { move_kw };
244            }
245            // (2.) The way that the closure uses its upvars means it's `FnOnce`.
246            else if self.coroutine_body_consumes_upvars(closure_def_id, body) {
247                capture_clause = hir::CaptureBy::Value { move_kw };
248            }
249        }
250
251        // As noted in `lower_coroutine_body_with_moved_arguments`, we default the capture mode
252        // to `ByRef` for the `async {}` block internal to async fns/closure. This means
253        // that we would *not* be moving all of the parameters into the async block in all cases.
254        // For example, when one of the arguments is `Copy`, we turn a consuming use into a copy of
255        // a reference, so for `async fn x(t: i32) {}`, we'd only take a reference to `t`.
256        //
257        // We force all of these arguments to be captured by move before we do expr use analysis.
258        //
259        // FIXME(async_closures): This could be cleaned up. It's a bit janky that we're just
260        // moving all of the `LocalSource::AsyncFn` locals here.
261        if let Some(hir::CoroutineKind::Desugared(
262            _,
263            hir::CoroutineSource::Fn | hir::CoroutineSource::Closure,
264        )) = self.tcx.coroutine_kind(closure_def_id)
265        {
266            let hir::ExprKind::Block(block, _) = body.value.kind else {
267                bug!();
268            };
269            for stmt in block.stmts {
270                let hir::StmtKind::Let(hir::LetStmt {
271                    init: Some(init),
272                    source: hir::LocalSource::AsyncFn,
273                    pat,
274                    ..
275                }) = stmt.kind
276                else {
277                    bug!();
278                };
279                let hir::PatKind::Binding(hir::BindingMode(hir::ByRef::No, _), _, _, _) = pat.kind
280                else {
281                    // Complex pattern, skip the non-upvar local.
282                    continue;
283                };
284                let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = init.kind else {
285                    bug!();
286                };
287                let hir::def::Res::Local(local_id) = path.res else {
288                    bug!();
289                };
290                let place = self.place_for_root_variable(closure_def_id, local_id);
291                delegate.capture_information.push((
292                    place,
293                    ty::CaptureInfo {
294                        capture_kind_expr_id: Some(init.hir_id),
295                        path_expr_id: Some(init.hir_id),
296                        capture_kind: UpvarCapture::ByValue,
297                    },
298                ));
299            }
300        }
301
302        debug!(
303            "For closure={:?}, capture_information={:#?}",
304            closure_def_id, delegate.capture_information
305        );
306
307        self.log_capture_analysis_first_pass(closure_def_id, &delegate.capture_information, span);
308
309        let (capture_information, closure_kind, origin) = self
310            .process_collected_capture_information(capture_clause, &delegate.capture_information);
311
312        self.compute_min_captures(closure_def_id, capture_information, span);
313
314        let closure_hir_id = self.tcx.local_def_id_to_hir_id(closure_def_id);
315
316        if should_do_rust_2021_incompatible_closure_captures_analysis(self.tcx, closure_hir_id) {
317            self.perform_2229_migration_analysis(closure_def_id, body_id, capture_clause, span);
318        }
319
320        let after_feature_tys = self.final_upvar_tys(closure_def_id);
321
322        // We now fake capture information for all variables that are mentioned within the closure
323        // We do this after handling migrations so that min_captures computes before
324        if !enable_precise_capture(span) {
325            let mut capture_information: InferredCaptureInformation<'tcx> = Default::default();
326
327            if let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) {
328                for var_hir_id in upvars.keys() {
329                    let place = self.place_for_root_variable(closure_def_id, *var_hir_id);
330
331                    debug!("seed place {:?}", place);
332
333                    let capture_kind = self.init_capture_kind_for_place(&place, capture_clause);
334                    let fake_info = ty::CaptureInfo {
335                        capture_kind_expr_id: None,
336                        path_expr_id: None,
337                        capture_kind,
338                    };
339
340                    capture_information.push((place, fake_info));
341                }
342            }
343
344            // This will update the min captures based on this new fake information.
345            self.compute_min_captures(closure_def_id, capture_information, span);
346        }
347
348        let before_feature_tys = self.final_upvar_tys(closure_def_id);
349
350        if infer_kind {
351            // Unify the (as yet unbound) type variable in the closure
352            // args with the kind we inferred.
353            let closure_kind_ty = match args {
354                UpvarArgs::Closure(args) => args.as_closure().kind_ty(),
355                UpvarArgs::CoroutineClosure(args) => args.as_coroutine_closure().kind_ty(),
356                UpvarArgs::Coroutine(_) => unreachable!("coroutines don't have an inferred kind"),
357            };
358            self.demand_eqtype(
359                span,
360                Ty::from_closure_kind(self.tcx, closure_kind),
361                closure_kind_ty,
362            );
363
364            // If we have an origin, store it.
365            if let Some(mut origin) = origin {
366                if !enable_precise_capture(span) {
367                    // Without precise captures, we just capture the base and ignore
368                    // the projections.
369                    origin.1.projections.clear()
370                }
371
372                self.typeck_results
373                    .borrow_mut()
374                    .closure_kind_origins_mut()
375                    .insert(closure_hir_id, origin);
376            }
377        }
378
379        // For coroutine-closures, we additionally must compute the
380        // `coroutine_captures_by_ref_ty` type, which is used to generate the by-ref
381        // version of the coroutine-closure's output coroutine.
382        if let UpvarArgs::CoroutineClosure(args) = args
383            && !args.references_error()
384        {
385            let closure_env_region: ty::Region<'_> = ty::Region::new_bound(
386                self.tcx,
387                ty::INNERMOST,
388                ty::BoundRegion { var: ty::BoundVar::ZERO, kind: ty::BoundRegionKind::ClosureEnv },
389            );
390
391            let num_args = args
392                .as_coroutine_closure()
393                .coroutine_closure_sig()
394                .skip_binder()
395                .tupled_inputs_ty
396                .tuple_fields()
397                .len();
398            let typeck_results = self.typeck_results.borrow();
399
400            let tupled_upvars_ty_for_borrow = Ty::new_tup_from_iter(
401                self.tcx,
402                ty::analyze_coroutine_closure_captures(
403                    typeck_results.closure_min_captures_flattened(closure_def_id),
404                    typeck_results
405                        .closure_min_captures_flattened(
406                            self.tcx.coroutine_for_closure(closure_def_id).expect_local(),
407                        )
408                        // Skip the captures that are just moving the closure's args
409                        // into the coroutine. These are always by move, and we append
410                        // those later in the `CoroutineClosureSignature` helper functions.
411                        .skip(num_args),
412                    |(_, parent_capture), (_, child_capture)| {
413                        // This is subtle. See documentation on function.
414                        let needs_ref = should_reborrow_from_env_of_parent_coroutine_closure(
415                            parent_capture,
416                            child_capture,
417                        );
418
419                        let upvar_ty = child_capture.place.ty();
420                        let capture = child_capture.info.capture_kind;
421                        // Not all upvars are captured by ref, so use
422                        // `apply_capture_kind_on_capture_ty` to ensure that we
423                        // compute the right captured type.
424                        return apply_capture_kind_on_capture_ty(
425                            self.tcx,
426                            upvar_ty,
427                            capture,
428                            if needs_ref {
429                                closure_env_region
430                            } else {
431                                self.tcx.lifetimes.re_erased
432                            },
433                        );
434                    },
435                ),
436            );
437            let coroutine_captures_by_ref_ty = Ty::new_fn_ptr(
438                self.tcx,
439                ty::Binder::bind_with_vars(
440                    self.tcx.mk_fn_sig(
441                        [],
442                        tupled_upvars_ty_for_borrow,
443                        false,
444                        hir::Safety::Safe,
445                        rustc_abi::ExternAbi::Rust,
446                    ),
447                    self.tcx.mk_bound_variable_kinds(&[ty::BoundVariableKind::Region(
448                        ty::BoundRegionKind::ClosureEnv,
449                    )]),
450                ),
451            );
452            self.demand_eqtype(
453                span,
454                args.as_coroutine_closure().coroutine_captures_by_ref_ty(),
455                coroutine_captures_by_ref_ty,
456            );
457
458            // Additionally, we can now constrain the coroutine's kind type.
459            //
460            // We only do this if `infer_kind`, because if we have constrained
461            // the kind from closure signature inference, the kind inferred
462            // for the inner coroutine may actually be more restrictive.
463            if infer_kind {
464                let ty::Coroutine(_, coroutine_args) =
465                    *self.typeck_results.borrow().expr_ty(body.value).kind()
466                else {
467                    bug!();
468                };
469                self.demand_eqtype(
470                    span,
471                    coroutine_args.as_coroutine().kind_ty(),
472                    Ty::from_coroutine_closure_kind(self.tcx, closure_kind),
473                );
474            }
475        }
476
477        self.log_closure_min_capture_info(closure_def_id, span);
478
479        // Now that we've analyzed the closure, we know how each
480        // variable is borrowed, and we know what traits the closure
481        // implements (Fn vs FnMut etc). We now have some updates to do
482        // with that information.
483        //
484        // Note that no closure type C may have an upvar of type C
485        // (though it may reference itself via a trait object). This
486        // results from the desugaring of closures to a struct like
487        // `Foo<..., UV0...UVn>`. If one of those upvars referenced
488        // C, then the type would have infinite size (and the
489        // inference algorithm will reject it).
490
491        // Equate the type variables for the upvars with the actual types.
492        let final_upvar_tys = self.final_upvar_tys(closure_def_id);
493        debug!(?closure_hir_id, ?args, ?final_upvar_tys);
494
495        if self.tcx.features().unsized_locals() || self.tcx.features().unsized_fn_params() {
496            for capture in
497                self.typeck_results.borrow().closure_min_captures_flattened(closure_def_id)
498            {
499                if let UpvarCapture::ByValue = capture.info.capture_kind {
500                    self.require_type_is_sized(
501                        capture.place.ty(),
502                        capture.get_path_span(self.tcx),
503                        ObligationCauseCode::SizedClosureCapture(closure_def_id),
504                    );
505                }
506            }
507        }
508
509        // Build a tuple (U0..Un) of the final upvar types U0..Un
510        // and unify the upvar tuple type in the closure with it:
511        let final_tupled_upvars_type = Ty::new_tup(self.tcx, &final_upvar_tys);
512        self.demand_suptype(span, args.tupled_upvars_ty(), final_tupled_upvars_type);
513
514        let fake_reads = delegate.fake_reads;
515
516        self.typeck_results.borrow_mut().closure_fake_reads.insert(closure_def_id, fake_reads);
517
518        if self.tcx.sess.opts.unstable_opts.profile_closures {
519            self.typeck_results.borrow_mut().closure_size_eval.insert(
520                closure_def_id,
521                ClosureSizeProfileData {
522                    before_feature_tys: Ty::new_tup(self.tcx, &before_feature_tys),
523                    after_feature_tys: Ty::new_tup(self.tcx, &after_feature_tys),
524                },
525            );
526        }
527
528        // If we are also inferred the closure kind here,
529        // process any deferred resolutions.
530        let deferred_call_resolutions = self.remove_deferred_call_resolutions(closure_def_id);
531        for deferred_call_resolution in deferred_call_resolutions {
532            deferred_call_resolution.resolve(self);
533        }
534    }
535
536    /// Determines whether the body of the coroutine uses its upvars in a way that
537    /// consumes (i.e. moves) the value, which would force the coroutine to `FnOnce`.
538    /// In a more detailed comment above, we care whether this happens, since if
539    /// this happens, we want to force the coroutine to move all of the upvars it
540    /// would've borrowed from the parent coroutine-closure.
541    ///
542    /// This only really makes sense to be called on the child coroutine of a
543    /// coroutine-closure.
544    fn coroutine_body_consumes_upvars(
545        &self,
546        coroutine_def_id: LocalDefId,
547        body: &'tcx hir::Body<'tcx>,
548    ) -> bool {
549        // This block contains argument capturing details. Since arguments
550        // aren't upvars, we do not care about them for determining if the
551        // coroutine body actually consumes its upvars.
552        let hir::ExprKind::Block(&hir::Block { expr: Some(body), .. }, None) = body.value.kind
553        else {
554            bug!();
555        };
556        // Specifically, we only care about the *real* body of the coroutine.
557        // We skip out into the drop-temps within the block of the body in order
558        // to skip over the args of the desugaring.
559        let hir::ExprKind::DropTemps(body) = body.kind else {
560            bug!();
561        };
562
563        let mut delegate = InferBorrowKind {
564            closure_def_id: coroutine_def_id,
565            capture_information: Default::default(),
566            fake_reads: Default::default(),
567        };
568
569        let _ = euv::ExprUseVisitor::new(
570            &FnCtxt::new(self, self.tcx.param_env(coroutine_def_id), coroutine_def_id),
571            &mut delegate,
572        )
573        .consume_expr(body);
574
575        let (_, kind, _) = self.process_collected_capture_information(
576            hir::CaptureBy::Ref,
577            &delegate.capture_information,
578        );
579
580        matches!(kind, ty::ClosureKind::FnOnce)
581    }
582
583    // Returns a list of `Ty`s for each upvar.
584    fn final_upvar_tys(&self, closure_id: LocalDefId) -> Vec<Ty<'tcx>> {
585        self.typeck_results
586            .borrow()
587            .closure_min_captures_flattened(closure_id)
588            .map(|captured_place| {
589                let upvar_ty = captured_place.place.ty();
590                let capture = captured_place.info.capture_kind;
591
592                debug!(?captured_place.place, ?upvar_ty, ?capture, ?captured_place.mutability);
593
594                apply_capture_kind_on_capture_ty(
595                    self.tcx,
596                    upvar_ty,
597                    capture,
598                    self.tcx.lifetimes.re_erased,
599                )
600            })
601            .collect()
602    }
603
604    /// Adjusts the closure capture information to ensure that the operations aren't unsafe,
605    /// and that the path can be captured with required capture kind (depending on use in closure,
606    /// move closure etc.)
607    ///
608    /// Returns the set of adjusted information along with the inferred closure kind and span
609    /// associated with the closure kind inference.
610    ///
611    /// Note that we *always* infer a minimal kind, even if
612    /// we don't always *use* that in the final result (i.e., sometimes
613    /// we've taken the closure kind from the expectations instead, and
614    /// for coroutines we don't even implement the closure traits
615    /// really).
616    ///
617    /// If we inferred that the closure needs to be FnMut/FnOnce, last element of the returned tuple
618    /// contains a `Some()` with the `Place` that caused us to do so.
619    fn process_collected_capture_information(
620        &self,
621        capture_clause: hir::CaptureBy,
622        capture_information: &InferredCaptureInformation<'tcx>,
623    ) -> (InferredCaptureInformation<'tcx>, ty::ClosureKind, Option<(Span, Place<'tcx>)>) {
624        let mut closure_kind = ty::ClosureKind::LATTICE_BOTTOM;
625        let mut origin: Option<(Span, Place<'tcx>)> = None;
626
627        let processed = capture_information
628            .iter()
629            .cloned()
630            .map(|(place, mut capture_info)| {
631                // Apply rules for safety before inferring closure kind
632                let (place, capture_kind) =
633                    restrict_capture_precision(place, capture_info.capture_kind);
634
635                let (place, capture_kind) = truncate_capture_for_optimization(place, capture_kind);
636
637                let usage_span = if let Some(usage_expr) = capture_info.path_expr_id {
638                    self.tcx.hir_span(usage_expr)
639                } else {
640                    unreachable!()
641                };
642
643                let updated = match capture_kind {
644                    ty::UpvarCapture::ByValue => match closure_kind {
645                        ty::ClosureKind::Fn | ty::ClosureKind::FnMut => {
646                            (ty::ClosureKind::FnOnce, Some((usage_span, place.clone())))
647                        }
648                        // If closure is already FnOnce, don't update
649                        ty::ClosureKind::FnOnce => (closure_kind, origin.take()),
650                    },
651
652                    ty::UpvarCapture::ByRef(
653                        ty::BorrowKind::Mutable | ty::BorrowKind::UniqueImmutable,
654                    ) => {
655                        match closure_kind {
656                            ty::ClosureKind::Fn => {
657                                (ty::ClosureKind::FnMut, Some((usage_span, place.clone())))
658                            }
659                            // Don't update the origin
660                            ty::ClosureKind::FnMut | ty::ClosureKind::FnOnce => {
661                                (closure_kind, origin.take())
662                            }
663                        }
664                    }
665
666                    _ => (closure_kind, origin.take()),
667                };
668
669                closure_kind = updated.0;
670                origin = updated.1;
671
672                let (place, capture_kind) = match capture_clause {
673                    hir::CaptureBy::Value { .. } => adjust_for_move_closure(place, capture_kind),
674                    hir::CaptureBy::Use { .. } => adjust_for_use_closure(place, capture_kind),
675                    hir::CaptureBy::Ref => adjust_for_non_move_closure(place, capture_kind),
676                };
677
678                // This restriction needs to be applied after we have handled adjustments for `move`
679                // closures. We want to make sure any adjustment that might make us move the place into
680                // the closure gets handled.
681                let (place, capture_kind) =
682                    restrict_precision_for_drop_types(self, place, capture_kind);
683
684                capture_info.capture_kind = capture_kind;
685                (place, capture_info)
686            })
687            .collect();
688
689        (processed, closure_kind, origin)
690    }
691
692    /// Analyzes the information collected by `InferBorrowKind` to compute the min number of
693    /// Places (and corresponding capture kind) that we need to keep track of to support all
694    /// the required captured paths.
695    ///
696    ///
697    /// Note: If this function is called multiple times for the same closure, it will update
698    ///       the existing min_capture map that is stored in TypeckResults.
699    ///
700    /// Eg:
701    /// ```
702    /// #[derive(Debug)]
703    /// struct Point { x: i32, y: i32 }
704    ///
705    /// let s = String::from("s");  // hir_id_s
706    /// let mut p = Point { x: 2, y: -2 }; // his_id_p
707    /// let c = || {
708    ///        println!("{s:?}");  // L1
709    ///        p.x += 10;  // L2
710    ///        println!("{}" , p.y); // L3
711    ///        println!("{p:?}"); // L4
712    ///        drop(s);   // L5
713    /// };
714    /// ```
715    /// and let hir_id_L1..5 be the expressions pointing to use of a captured variable on
716    /// the lines L1..5 respectively.
717    ///
718    /// InferBorrowKind results in a structure like this:
719    ///
720    /// ```ignore (illustrative)
721    /// {
722    ///       Place(base: hir_id_s, projections: [], ....) -> {
723    ///                                                            capture_kind_expr: hir_id_L5,
724    ///                                                            path_expr_id: hir_id_L5,
725    ///                                                            capture_kind: ByValue
726    ///                                                       },
727    ///       Place(base: hir_id_p, projections: [Field(0, 0)], ...) -> {
728    ///                                                                     capture_kind_expr: hir_id_L2,
729    ///                                                                     path_expr_id: hir_id_L2,
730    ///                                                                     capture_kind: ByValue
731    ///                                                                 },
732    ///       Place(base: hir_id_p, projections: [Field(1, 0)], ...) -> {
733    ///                                                                     capture_kind_expr: hir_id_L3,
734    ///                                                                     path_expr_id: hir_id_L3,
735    ///                                                                     capture_kind: ByValue
736    ///                                                                 },
737    ///       Place(base: hir_id_p, projections: [], ...) -> {
738    ///                                                          capture_kind_expr: hir_id_L4,
739    ///                                                          path_expr_id: hir_id_L4,
740    ///                                                          capture_kind: ByValue
741    ///                                                      },
742    /// }
743    /// ```
744    ///
745    /// After the min capture analysis, we get:
746    /// ```ignore (illustrative)
747    /// {
748    ///       hir_id_s -> [
749    ///            Place(base: hir_id_s, projections: [], ....) -> {
750    ///                                                                capture_kind_expr: hir_id_L5,
751    ///                                                                path_expr_id: hir_id_L5,
752    ///                                                                capture_kind: ByValue
753    ///                                                            },
754    ///       ],
755    ///       hir_id_p -> [
756    ///            Place(base: hir_id_p, projections: [], ...) -> {
757    ///                                                               capture_kind_expr: hir_id_L2,
758    ///                                                               path_expr_id: hir_id_L4,
759    ///                                                               capture_kind: ByValue
760    ///                                                           },
761    ///       ],
762    /// }
763    /// ```
764    fn compute_min_captures(
765        &self,
766        closure_def_id: LocalDefId,
767        capture_information: InferredCaptureInformation<'tcx>,
768        closure_span: Span,
769    ) {
770        if capture_information.is_empty() {
771            return;
772        }
773
774        let mut typeck_results = self.typeck_results.borrow_mut();
775
776        let mut root_var_min_capture_list =
777            typeck_results.closure_min_captures.remove(&closure_def_id).unwrap_or_default();
778
779        for (mut place, capture_info) in capture_information.into_iter() {
780            let var_hir_id = match place.base {
781                PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
782                base => bug!("Expected upvar, found={:?}", base),
783            };
784            let var_ident = self.tcx.hir_ident(var_hir_id);
785
786            let Some(min_cap_list) = root_var_min_capture_list.get_mut(&var_hir_id) else {
787                let mutability = self.determine_capture_mutability(&typeck_results, &place);
788                let min_cap_list =
789                    vec![ty::CapturedPlace { var_ident, place, info: capture_info, mutability }];
790                root_var_min_capture_list.insert(var_hir_id, min_cap_list);
791                continue;
792            };
793
794            // Go through each entry in the current list of min_captures
795            // - if ancestor is found, update its capture kind to account for current place's
796            // capture information.
797            //
798            // - if descendant is found, remove it from the list, and update the current place's
799            // capture information to account for the descendant's capture kind.
800            //
801            // We can never be in a case where the list contains both an ancestor and a descendant
802            // Also there can only be ancestor but in case of descendants there might be
803            // multiple.
804
805            let mut descendant_found = false;
806            let mut updated_capture_info = capture_info;
807            min_cap_list.retain(|possible_descendant| {
808                match determine_place_ancestry_relation(&place, &possible_descendant.place) {
809                    // current place is ancestor of possible_descendant
810                    PlaceAncestryRelation::Ancestor => {
811                        descendant_found = true;
812
813                        let mut possible_descendant = possible_descendant.clone();
814                        let backup_path_expr_id = updated_capture_info.path_expr_id;
815
816                        // Truncate the descendant (already in min_captures) to be same as the ancestor to handle any
817                        // possible change in capture mode.
818                        truncate_place_to_len_and_update_capture_kind(
819                            &mut possible_descendant.place,
820                            &mut possible_descendant.info.capture_kind,
821                            place.projections.len(),
822                        );
823
824                        updated_capture_info =
825                            determine_capture_info(updated_capture_info, possible_descendant.info);
826
827                        // we need to keep the ancestor's `path_expr_id`
828                        updated_capture_info.path_expr_id = backup_path_expr_id;
829                        false
830                    }
831
832                    _ => true,
833                }
834            });
835
836            let mut ancestor_found = false;
837            if !descendant_found {
838                for possible_ancestor in min_cap_list.iter_mut() {
839                    match determine_place_ancestry_relation(&place, &possible_ancestor.place) {
840                        PlaceAncestryRelation::SamePlace => {
841                            ancestor_found = true;
842                            possible_ancestor.info = determine_capture_info(
843                                possible_ancestor.info,
844                                updated_capture_info,
845                            );
846
847                            // Only one related place will be in the list.
848                            break;
849                        }
850                        // current place is descendant of possible_ancestor
851                        PlaceAncestryRelation::Descendant => {
852                            ancestor_found = true;
853                            let backup_path_expr_id = possible_ancestor.info.path_expr_id;
854
855                            // Truncate the descendant (current place) to be same as the ancestor to handle any
856                            // possible change in capture mode.
857                            truncate_place_to_len_and_update_capture_kind(
858                                &mut place,
859                                &mut updated_capture_info.capture_kind,
860                                possible_ancestor.place.projections.len(),
861                            );
862
863                            possible_ancestor.info = determine_capture_info(
864                                possible_ancestor.info,
865                                updated_capture_info,
866                            );
867
868                            // we need to keep the ancestor's `path_expr_id`
869                            possible_ancestor.info.path_expr_id = backup_path_expr_id;
870
871                            // Only one related place will be in the list.
872                            break;
873                        }
874                        _ => {}
875                    }
876                }
877            }
878
879            // Only need to insert when we don't have an ancestor in the existing min capture list
880            if !ancestor_found {
881                let mutability = self.determine_capture_mutability(&typeck_results, &place);
882                let captured_place =
883                    ty::CapturedPlace { var_ident, place, info: updated_capture_info, mutability };
884                min_cap_list.push(captured_place);
885            }
886        }
887
888        debug!(
889            "For closure={:?}, min_captures before sorting={:?}",
890            closure_def_id, root_var_min_capture_list
891        );
892
893        // Now that we have the minimized list of captures, sort the captures by field id.
894        // This causes the closure to capture the upvars in the same order as the fields are
895        // declared which is also the drop order. Thus, in situations where we capture all the
896        // fields of some type, the observable drop order will remain the same as it previously
897        // was even though we're dropping each capture individually.
898        // See https://github.com/rust-lang/project-rfc-2229/issues/42 and
899        // `tests/ui/closures/2229_closure_analysis/preserve_field_drop_order.rs`.
900        for (_, captures) in &mut root_var_min_capture_list {
901            captures.sort_by(|capture1, capture2| {
902                fn is_field<'a>(p: &&Projection<'a>) -> bool {
903                    match p.kind {
904                        ProjectionKind::Field(_, _) => true,
905                        ProjectionKind::Deref | ProjectionKind::OpaqueCast => false,
906                        p @ (ProjectionKind::Subslice | ProjectionKind::Index) => {
907                            bug!("ProjectionKind {:?} was unexpected", p)
908                        }
909                    }
910                }
911
912                // Need to sort only by Field projections, so filter away others.
913                // A previous implementation considered other projection types too
914                // but that caused ICE #118144
915                let capture1_field_projections = capture1.place.projections.iter().filter(is_field);
916                let capture2_field_projections = capture2.place.projections.iter().filter(is_field);
917
918                for (p1, p2) in capture1_field_projections.zip(capture2_field_projections) {
919                    // We do not need to look at the `Projection.ty` fields here because at each
920                    // step of the iteration, the projections will either be the same and therefore
921                    // the types must be as well or the current projection will be different and
922                    // we will return the result of comparing the field indexes.
923                    match (p1.kind, p2.kind) {
924                        (ProjectionKind::Field(i1, _), ProjectionKind::Field(i2, _)) => {
925                            // Compare only if paths are different.
926                            // Otherwise continue to the next iteration
927                            if i1 != i2 {
928                                return i1.cmp(&i2);
929                            }
930                        }
931                        // Given the filter above, this arm should never be hit
932                        (l, r) => bug!("ProjectionKinds {:?} or {:?} were unexpected", l, r),
933                    }
934                }
935
936                self.dcx().span_delayed_bug(
937                    closure_span,
938                    format!(
939                        "two identical projections: ({:?}, {:?})",
940                        capture1.place.projections, capture2.place.projections
941                    ),
942                );
943                std::cmp::Ordering::Equal
944            });
945        }
946
947        debug!(
948            "For closure={:?}, min_captures after sorting={:#?}",
949            closure_def_id, root_var_min_capture_list
950        );
951        typeck_results.closure_min_captures.insert(closure_def_id, root_var_min_capture_list);
952    }
953
954    /// Perform the migration analysis for RFC 2229, and emit lint
955    /// `disjoint_capture_drop_reorder` if needed.
956    fn perform_2229_migration_analysis(
957        &self,
958        closure_def_id: LocalDefId,
959        body_id: hir::BodyId,
960        capture_clause: hir::CaptureBy,
961        span: Span,
962    ) {
963        let (need_migrations, reasons) = self.compute_2229_migrations(
964            closure_def_id,
965            span,
966            capture_clause,
967            self.typeck_results.borrow().closure_min_captures.get(&closure_def_id),
968        );
969
970        if !need_migrations.is_empty() {
971            let (migration_string, migrated_variables_concat) =
972                migration_suggestion_for_2229(self.tcx, &need_migrations);
973
974            let closure_hir_id = self.tcx.local_def_id_to_hir_id(closure_def_id);
975            let closure_head_span = self.tcx.def_span(closure_def_id);
976            self.tcx.node_span_lint(
977                lint::builtin::RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES,
978                closure_hir_id,
979                closure_head_span,
980                |lint| {
981                    lint.primary_message(reasons.migration_message());
982
983                    for NeededMigration { var_hir_id, diagnostics_info } in &need_migrations {
984                        // Labels all the usage of the captured variable and why they are responsible
985                        // for migration being needed
986                        for lint_note in diagnostics_info.iter() {
987                            match &lint_note.captures_info {
988                                UpvarMigrationInfo::CapturingPrecise { source_expr: Some(capture_expr_id), var_name: captured_name } => {
989                                    let cause_span = self.tcx.hir_span(*capture_expr_id);
990                                    lint.span_label(cause_span, format!("in Rust 2018, this closure captures all of `{}`, but in Rust 2021, it will only capture `{}`",
991                                        self.tcx.hir_name(*var_hir_id),
992                                        captured_name,
993                                    ));
994                                }
995                                UpvarMigrationInfo::CapturingNothing { use_span } => {
996                                    lint.span_label(*use_span, format!("in Rust 2018, this causes the closure to capture `{}`, but in Rust 2021, it has no effect",
997                                        self.tcx.hir_name(*var_hir_id),
998                                    ));
999                                }
1000
1001                                _ => { }
1002                            }
1003
1004                            // Add a label pointing to where a captured variable affected by drop order
1005                            // is dropped
1006                            if lint_note.reason.drop_order {
1007                                let drop_location_span = drop_location_span(self.tcx, closure_hir_id);
1008
1009                                match &lint_note.captures_info {
1010                                    UpvarMigrationInfo::CapturingPrecise { var_name: captured_name, .. } => {
1011                                        lint.span_label(drop_location_span, format!("in Rust 2018, `{}` is dropped here, but in Rust 2021, only `{}` will be dropped here as part of the closure",
1012                                            self.tcx.hir_name(*var_hir_id),
1013                                            captured_name,
1014                                        ));
1015                                    }
1016                                    UpvarMigrationInfo::CapturingNothing { use_span: _ } => {
1017                                        lint.span_label(drop_location_span, format!("in Rust 2018, `{v}` is dropped here along with the closure, but in Rust 2021 `{v}` is not part of the closure",
1018                                            v = self.tcx.hir_name(*var_hir_id),
1019                                        ));
1020                                    }
1021                                }
1022                            }
1023
1024                            // Add a label explaining why a closure no longer implements a trait
1025                            for &missing_trait in &lint_note.reason.auto_traits {
1026                                // not capturing something anymore cannot cause a trait to fail to be implemented:
1027                                match &lint_note.captures_info {
1028                                    UpvarMigrationInfo::CapturingPrecise { var_name: captured_name, .. } => {
1029                                        let var_name = self.tcx.hir_name(*var_hir_id);
1030                                        lint.span_label(closure_head_span, format!("\
1031                                        in Rust 2018, this closure implements {missing_trait} \
1032                                        as `{var_name}` implements {missing_trait}, but in Rust 2021, \
1033                                        this closure will no longer implement {missing_trait} \
1034                                        because `{var_name}` is not fully captured \
1035                                        and `{captured_name}` does not implement {missing_trait}"));
1036                                    }
1037
1038                                    // Cannot happen: if we don't capture a variable, we impl strictly more traits
1039                                    UpvarMigrationInfo::CapturingNothing { use_span } => span_bug!(*use_span, "missing trait from not capturing something"),
1040                                }
1041                            }
1042                        }
1043                    }
1044                    lint.note("for more information, see <https://doc.rust-lang.org/nightly/edition-guide/rust-2021/disjoint-capture-in-closures.html>");
1045
1046                    let diagnostic_msg = format!(
1047                        "add a dummy let to cause {migrated_variables_concat} to be fully captured"
1048                    );
1049
1050                    let closure_span = self.tcx.hir_span_with_body(closure_hir_id);
1051                    let mut closure_body_span = {
1052                        // If the body was entirely expanded from a macro
1053                        // invocation, i.e. the body is not contained inside the
1054                        // closure span, then we walk up the expansion until we
1055                        // find the span before the expansion.
1056                        let s = self.tcx.hir_span_with_body(body_id.hir_id);
1057                        s.find_ancestor_inside(closure_span).unwrap_or(s)
1058                    };
1059
1060                    if let Ok(mut s) = self.tcx.sess.source_map().span_to_snippet(closure_body_span) {
1061                        if s.starts_with('$') {
1062                            // Looks like a macro fragment. Try to find the real block.
1063                            if let hir::Node::Expr(&hir::Expr {
1064                                kind: hir::ExprKind::Block(block, ..), ..
1065                            }) = self.tcx.hir_node(body_id.hir_id) {
1066                                // If the body is a block (with `{..}`), we use the span of that block.
1067                                // E.g. with a `|| $body` expanded from a `m!({ .. })`, we use `{ .. }`, and not `$body`.
1068                                // Since we know it's a block, we know we can insert the `let _ = ..` without
1069                                // breaking the macro syntax.
1070                                if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(block.span) {
1071                                    closure_body_span = block.span;
1072                                    s = snippet;
1073                                }
1074                            }
1075                        }
1076
1077                        let mut lines = s.lines();
1078                        let line1 = lines.next().unwrap_or_default();
1079
1080                        if line1.trim_end() == "{" {
1081                            // This is a multi-line closure with just a `{` on the first line,
1082                            // so we put the `let` on its own line.
1083                            // We take the indentation from the next non-empty line.
1084                            let line2 = lines.find(|line| !line.is_empty()).unwrap_or_default();
1085                            let indent = line2.split_once(|c: char| !c.is_whitespace()).unwrap_or_default().0;
1086                            lint.span_suggestion(
1087                                closure_body_span.with_lo(closure_body_span.lo() + BytePos::from_usize(line1.len())).shrink_to_lo(),
1088                                diagnostic_msg,
1089                                format!("\n{indent}{migration_string};"),
1090                                Applicability::MachineApplicable,
1091                            );
1092                        } else if line1.starts_with('{') {
1093                            // This is a closure with its body wrapped in
1094                            // braces, but with more than just the opening
1095                            // brace on the first line. We put the `let`
1096                            // directly after the `{`.
1097                            lint.span_suggestion(
1098                                closure_body_span.with_lo(closure_body_span.lo() + BytePos(1)).shrink_to_lo(),
1099                                diagnostic_msg,
1100                                format!(" {migration_string};"),
1101                                Applicability::MachineApplicable,
1102                            );
1103                        } else {
1104                            // This is a closure without braces around the body.
1105                            // We add braces to add the `let` before the body.
1106                            lint.multipart_suggestion(
1107                                diagnostic_msg,
1108                                vec![
1109                                    (closure_body_span.shrink_to_lo(), format!("{{ {migration_string}; ")),
1110                                    (closure_body_span.shrink_to_hi(), " }".to_string()),
1111                                ],
1112                                Applicability::MachineApplicable
1113                            );
1114                        }
1115                    } else {
1116                        lint.span_suggestion(
1117                            closure_span,
1118                            diagnostic_msg,
1119                            migration_string,
1120                            Applicability::HasPlaceholders
1121                        );
1122                    }
1123                },
1124            );
1125        }
1126    }
1127
1128    /// Combines all the reasons for 2229 migrations
1129    fn compute_2229_migrations_reasons(
1130        &self,
1131        auto_trait_reasons: UnordSet<&'static str>,
1132        drop_order: bool,
1133    ) -> MigrationWarningReason {
1134        MigrationWarningReason {
1135            auto_traits: auto_trait_reasons.into_sorted_stable_ord(),
1136            drop_order,
1137        }
1138    }
1139
1140    /// Figures out the list of root variables (and their types) that aren't completely
1141    /// captured by the closure when `capture_disjoint_fields` is enabled and auto-traits
1142    /// differ between the root variable and the captured paths.
1143    ///
1144    /// Returns a tuple containing a HashMap of CapturesInfo that maps to a HashSet of trait names
1145    /// if migration is needed for traits for the provided var_hir_id, otherwise returns None
1146    fn compute_2229_migrations_for_trait(
1147        &self,
1148        min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
1149        var_hir_id: HirId,
1150        closure_clause: hir::CaptureBy,
1151    ) -> Option<FxIndexMap<UpvarMigrationInfo, UnordSet<&'static str>>> {
1152        let auto_traits_def_id = [
1153            self.tcx.lang_items().clone_trait(),
1154            self.tcx.lang_items().sync_trait(),
1155            self.tcx.get_diagnostic_item(sym::Send),
1156            self.tcx.lang_items().unpin_trait(),
1157            self.tcx.get_diagnostic_item(sym::unwind_safe_trait),
1158            self.tcx.get_diagnostic_item(sym::ref_unwind_safe_trait),
1159        ];
1160        const AUTO_TRAITS: [&str; 6] =
1161            ["`Clone`", "`Sync`", "`Send`", "`Unpin`", "`UnwindSafe`", "`RefUnwindSafe`"];
1162
1163        let root_var_min_capture_list = min_captures.and_then(|m| m.get(&var_hir_id))?;
1164
1165        let ty = self.resolve_vars_if_possible(self.node_ty(var_hir_id));
1166
1167        let ty = match closure_clause {
1168            hir::CaptureBy::Value { .. } => ty, // For move closure the capture kind should be by value
1169            hir::CaptureBy::Ref | hir::CaptureBy::Use { .. } => {
1170                // For non move closure the capture kind is the max capture kind of all captures
1171                // according to the ordering ImmBorrow < UniqueImmBorrow < MutBorrow < ByValue
1172                let mut max_capture_info = root_var_min_capture_list.first().unwrap().info;
1173                for capture in root_var_min_capture_list.iter() {
1174                    max_capture_info = determine_capture_info(max_capture_info, capture.info);
1175                }
1176
1177                apply_capture_kind_on_capture_ty(
1178                    self.tcx,
1179                    ty,
1180                    max_capture_info.capture_kind,
1181                    self.tcx.lifetimes.re_erased,
1182                )
1183            }
1184        };
1185
1186        let mut obligations_should_hold = Vec::new();
1187        // Checks if a root variable implements any of the auto traits
1188        for check_trait in auto_traits_def_id.iter() {
1189            obligations_should_hold.push(check_trait.is_some_and(|check_trait| {
1190                self.infcx
1191                    .type_implements_trait(check_trait, [ty], self.param_env)
1192                    .must_apply_modulo_regions()
1193            }));
1194        }
1195
1196        let mut problematic_captures = FxIndexMap::default();
1197        // Check whether captured fields also implement the trait
1198        for capture in root_var_min_capture_list.iter() {
1199            let ty = apply_capture_kind_on_capture_ty(
1200                self.tcx,
1201                capture.place.ty(),
1202                capture.info.capture_kind,
1203                self.tcx.lifetimes.re_erased,
1204            );
1205
1206            // Checks if a capture implements any of the auto traits
1207            let mut obligations_holds_for_capture = Vec::new();
1208            for check_trait in auto_traits_def_id.iter() {
1209                obligations_holds_for_capture.push(check_trait.is_some_and(|check_trait| {
1210                    self.infcx
1211                        .type_implements_trait(check_trait, [ty], self.param_env)
1212                        .must_apply_modulo_regions()
1213                }));
1214            }
1215
1216            let mut capture_problems = UnordSet::default();
1217
1218            // Checks if for any of the auto traits, one or more trait is implemented
1219            // by the root variable but not by the capture
1220            for (idx, _) in obligations_should_hold.iter().enumerate() {
1221                if !obligations_holds_for_capture[idx] && obligations_should_hold[idx] {
1222                    capture_problems.insert(AUTO_TRAITS[idx]);
1223                }
1224            }
1225
1226            if !capture_problems.is_empty() {
1227                problematic_captures.insert(
1228                    UpvarMigrationInfo::CapturingPrecise {
1229                        source_expr: capture.info.path_expr_id,
1230                        var_name: capture.to_string(self.tcx),
1231                    },
1232                    capture_problems,
1233                );
1234            }
1235        }
1236        if !problematic_captures.is_empty() {
1237            return Some(problematic_captures);
1238        }
1239        None
1240    }
1241
1242    /// Figures out the list of root variables (and their types) that aren't completely
1243    /// captured by the closure when `capture_disjoint_fields` is enabled and drop order of
1244    /// some path starting at that root variable **might** be affected.
1245    ///
1246    /// The output list would include a root variable if:
1247    /// - It would have been moved into the closure when `capture_disjoint_fields` wasn't
1248    ///   enabled, **and**
1249    /// - It wasn't completely captured by the closure, **and**
1250    /// - One of the paths starting at this root variable, that is not captured needs Drop.
1251    ///
1252    /// This function only returns a HashSet of CapturesInfo for significant drops. If there
1253    /// are no significant drops than None is returned
1254    #[instrument(level = "debug", skip(self))]
1255    fn compute_2229_migrations_for_drop(
1256        &self,
1257        closure_def_id: LocalDefId,
1258        closure_span: Span,
1259        min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
1260        closure_clause: hir::CaptureBy,
1261        var_hir_id: HirId,
1262    ) -> Option<FxIndexSet<UpvarMigrationInfo>> {
1263        let ty = self.resolve_vars_if_possible(self.node_ty(var_hir_id));
1264
1265        // FIXME(#132279): Using `non_body_analysis` here feels wrong.
1266        if !ty.has_significant_drop(
1267            self.tcx,
1268            ty::TypingEnv::non_body_analysis(self.tcx, closure_def_id),
1269        ) {
1270            debug!("does not have significant drop");
1271            return None;
1272        }
1273
1274        let Some(root_var_min_capture_list) = min_captures.and_then(|m| m.get(&var_hir_id)) else {
1275            // The upvar is mentioned within the closure but no path starting from it is
1276            // used. This occurs when you have (e.g.)
1277            //
1278            // ```
1279            // let x = move || {
1280            //     let _ = y;
1281            // });
1282            // ```
1283            debug!("no path starting from it is used");
1284
1285            match closure_clause {
1286                // Only migrate if closure is a move closure
1287                hir::CaptureBy::Value { .. } => {
1288                    let mut diagnostics_info = FxIndexSet::default();
1289                    let upvars =
1290                        self.tcx.upvars_mentioned(closure_def_id).expect("must be an upvar");
1291                    let upvar = upvars[&var_hir_id];
1292                    diagnostics_info
1293                        .insert(UpvarMigrationInfo::CapturingNothing { use_span: upvar.span });
1294                    return Some(diagnostics_info);
1295                }
1296                hir::CaptureBy::Ref | hir::CaptureBy::Use { .. } => {}
1297            }
1298
1299            return None;
1300        };
1301        debug!(?root_var_min_capture_list);
1302
1303        let mut projections_list = Vec::new();
1304        let mut diagnostics_info = FxIndexSet::default();
1305
1306        for captured_place in root_var_min_capture_list.iter() {
1307            match captured_place.info.capture_kind {
1308                // Only care about captures that are moved into the closure
1309                ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {
1310                    projections_list.push(captured_place.place.projections.as_slice());
1311                    diagnostics_info.insert(UpvarMigrationInfo::CapturingPrecise {
1312                        source_expr: captured_place.info.path_expr_id,
1313                        var_name: captured_place.to_string(self.tcx),
1314                    });
1315                }
1316                ty::UpvarCapture::ByRef(..) => {}
1317            }
1318        }
1319
1320        debug!(?projections_list);
1321        debug!(?diagnostics_info);
1322
1323        let is_moved = !projections_list.is_empty();
1324        debug!(?is_moved);
1325
1326        let is_not_completely_captured =
1327            root_var_min_capture_list.iter().any(|capture| !capture.place.projections.is_empty());
1328        debug!(?is_not_completely_captured);
1329
1330        if is_moved
1331            && is_not_completely_captured
1332            && self.has_significant_drop_outside_of_captures(
1333                closure_def_id,
1334                closure_span,
1335                ty,
1336                projections_list,
1337            )
1338        {
1339            return Some(diagnostics_info);
1340        }
1341
1342        None
1343    }
1344
1345    /// Figures out the list of root variables (and their types) that aren't completely
1346    /// captured by the closure when `capture_disjoint_fields` is enabled and either drop
1347    /// order of some path starting at that root variable **might** be affected or auto-traits
1348    /// differ between the root variable and the captured paths.
1349    ///
1350    /// The output list would include a root variable if:
1351    /// - It would have been moved into the closure when `capture_disjoint_fields` wasn't
1352    ///   enabled, **and**
1353    /// - It wasn't completely captured by the closure, **and**
1354    /// - One of the paths starting at this root variable, that is not captured needs Drop **or**
1355    /// - One of the paths captured does not implement all the auto-traits its root variable
1356    ///   implements.
1357    ///
1358    /// Returns a tuple containing a vector of MigrationDiagnosticInfo, as well as a String
1359    /// containing the reason why root variables whose HirId is contained in the vector should
1360    /// be captured
1361    #[instrument(level = "debug", skip(self))]
1362    fn compute_2229_migrations(
1363        &self,
1364        closure_def_id: LocalDefId,
1365        closure_span: Span,
1366        closure_clause: hir::CaptureBy,
1367        min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
1368    ) -> (Vec<NeededMigration>, MigrationWarningReason) {
1369        let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) else {
1370            return (Vec::new(), MigrationWarningReason::default());
1371        };
1372
1373        let mut need_migrations = Vec::new();
1374        let mut auto_trait_migration_reasons = UnordSet::default();
1375        let mut drop_migration_needed = false;
1376
1377        // Perform auto-trait analysis
1378        for (&var_hir_id, _) in upvars.iter() {
1379            let mut diagnostics_info = Vec::new();
1380
1381            let auto_trait_diagnostic = self
1382                .compute_2229_migrations_for_trait(min_captures, var_hir_id, closure_clause)
1383                .unwrap_or_default();
1384
1385            let drop_reorder_diagnostic = if let Some(diagnostics_info) = self
1386                .compute_2229_migrations_for_drop(
1387                    closure_def_id,
1388                    closure_span,
1389                    min_captures,
1390                    closure_clause,
1391                    var_hir_id,
1392                ) {
1393                drop_migration_needed = true;
1394                diagnostics_info
1395            } else {
1396                FxIndexSet::default()
1397            };
1398
1399            // Combine all the captures responsible for needing migrations into one IndexSet
1400            let mut capture_diagnostic = drop_reorder_diagnostic.clone();
1401            for key in auto_trait_diagnostic.keys() {
1402                capture_diagnostic.insert(key.clone());
1403            }
1404
1405            let mut capture_diagnostic = capture_diagnostic.into_iter().collect::<Vec<_>>();
1406            capture_diagnostic.sort_by_cached_key(|info| match info {
1407                UpvarMigrationInfo::CapturingPrecise { source_expr: _, var_name } => {
1408                    (0, Some(var_name.clone()))
1409                }
1410                UpvarMigrationInfo::CapturingNothing { use_span: _ } => (1, None),
1411            });
1412            for captures_info in capture_diagnostic {
1413                // Get the auto trait reasons of why migration is needed because of that capture, if there are any
1414                let capture_trait_reasons =
1415                    if let Some(reasons) = auto_trait_diagnostic.get(&captures_info) {
1416                        reasons.clone()
1417                    } else {
1418                        UnordSet::default()
1419                    };
1420
1421                // Check if migration is needed because of drop reorder as a result of that capture
1422                let capture_drop_reorder_reason = drop_reorder_diagnostic.contains(&captures_info);
1423
1424                // Combine all the reasons of why the root variable should be captured as a result of
1425                // auto trait implementation issues
1426                auto_trait_migration_reasons.extend_unord(capture_trait_reasons.items().copied());
1427
1428                diagnostics_info.push(MigrationLintNote {
1429                    captures_info,
1430                    reason: self.compute_2229_migrations_reasons(
1431                        capture_trait_reasons,
1432                        capture_drop_reorder_reason,
1433                    ),
1434                });
1435            }
1436
1437            if !diagnostics_info.is_empty() {
1438                need_migrations.push(NeededMigration { var_hir_id, diagnostics_info });
1439            }
1440        }
1441        (
1442            need_migrations,
1443            self.compute_2229_migrations_reasons(
1444                auto_trait_migration_reasons,
1445                drop_migration_needed,
1446            ),
1447        )
1448    }
1449
1450    /// This is a helper function to `compute_2229_migrations_precise_pass`. Provided the type
1451    /// of a root variable and a list of captured paths starting at this root variable (expressed
1452    /// using list of `Projection` slices), it returns true if there is a path that is not
1453    /// captured starting at this root variable that implements Drop.
1454    ///
1455    /// The way this function works is at a given call it looks at type `base_path_ty` of some base
1456    /// path say P and then list of projection slices which represent the different captures moved
1457    /// into the closure starting off of P.
1458    ///
1459    /// This will make more sense with an example:
1460    ///
1461    /// ```rust,edition2021
1462    ///
1463    /// struct FancyInteger(i32); // This implements Drop
1464    ///
1465    /// struct Point { x: FancyInteger, y: FancyInteger }
1466    /// struct Color;
1467    ///
1468    /// struct Wrapper { p: Point, c: Color }
1469    ///
1470    /// fn f(w: Wrapper) {
1471    ///   let c = || {
1472    ///       // Closure captures w.p.x and w.c by move.
1473    ///   };
1474    ///
1475    ///   c();
1476    /// }
1477    /// ```
1478    ///
1479    /// If `capture_disjoint_fields` wasn't enabled the closure would've moved `w` instead of the
1480    /// precise paths. If we look closely `w.p.y` isn't captured which implements Drop and
1481    /// therefore Drop ordering would change and we want this function to return true.
1482    ///
1483    /// Call stack to figure out if we need to migrate for `w` would look as follows:
1484    ///
1485    /// Our initial base path is just `w`, and the paths captured from it are `w[p, x]` and
1486    /// `w[c]`.
1487    /// Notation:
1488    /// - Ty(place): Type of place
1489    /// - `(a, b)`: Represents the function parameters `base_path_ty` and `captured_by_move_projs`
1490    /// respectively.
1491    /// ```ignore (illustrative)
1492    ///                  (Ty(w), [ &[p, x], &[c] ])
1493    /// //                              |
1494    /// //                 ----------------------------
1495    /// //                 |                          |
1496    /// //                 v                          v
1497    ///        (Ty(w.p), [ &[x] ])          (Ty(w.c), [ &[] ]) // I(1)
1498    /// //                 |                          |
1499    /// //                 v                          v
1500    ///        (Ty(w.p), [ &[x] ])                 false
1501    /// //                 |
1502    /// //                 |
1503    /// //       -------------------------------
1504    /// //       |                             |
1505    /// //       v                             v
1506    ///     (Ty((w.p).x), [ &[] ])     (Ty((w.p).y), []) // IMP 2
1507    /// //       |                             |
1508    /// //       v                             v
1509    ///        false              NeedsSignificantDrop(Ty(w.p.y))
1510    /// //                                     |
1511    /// //                                     v
1512    ///                                      true
1513    /// ```
1514    ///
1515    /// IMP 1 `(Ty(w.c), [ &[] ])`: Notice the single empty slice inside `captured_projs`.
1516    ///                             This implies that the `w.c` is completely captured by the closure.
1517    ///                             Since drop for this path will be called when the closure is
1518    ///                             dropped we don't need to migrate for it.
1519    ///
1520    /// IMP 2 `(Ty((w.p).y), [])`: Notice that `captured_projs` is empty. This implies that this
1521    ///                             path wasn't captured by the closure. Also note that even
1522    ///                             though we didn't capture this path, the function visits it,
1523    ///                             which is kind of the point of this function. We then return
1524    ///                             if the type of `w.p.y` implements Drop, which in this case is
1525    ///                             true.
1526    ///
1527    /// Consider another example:
1528    ///
1529    /// ```ignore (pseudo-rust)
1530    /// struct X;
1531    /// impl Drop for X {}
1532    ///
1533    /// struct Y(X);
1534    /// impl Drop for Y {}
1535    ///
1536    /// fn foo() {
1537    ///     let y = Y(X);
1538    ///     let c = || move(y.0);
1539    /// }
1540    /// ```
1541    ///
1542    /// Note that `y.0` is captured by the closure. When this function is called for `y`, it will
1543    /// return true, because even though all paths starting at `y` are captured, `y` itself
1544    /// implements Drop which will be affected since `y` isn't completely captured.
1545    fn has_significant_drop_outside_of_captures(
1546        &self,
1547        closure_def_id: LocalDefId,
1548        closure_span: Span,
1549        base_path_ty: Ty<'tcx>,
1550        captured_by_move_projs: Vec<&[Projection<'tcx>]>,
1551    ) -> bool {
1552        // FIXME(#132279): Using `non_body_analysis` here feels wrong.
1553        let needs_drop = |ty: Ty<'tcx>| {
1554            ty.has_significant_drop(
1555                self.tcx,
1556                ty::TypingEnv::non_body_analysis(self.tcx, closure_def_id),
1557            )
1558        };
1559
1560        let is_drop_defined_for_ty = |ty: Ty<'tcx>| {
1561            let drop_trait = self.tcx.require_lang_item(hir::LangItem::Drop, Some(closure_span));
1562            self.infcx
1563                .type_implements_trait(drop_trait, [ty], self.tcx.param_env(closure_def_id))
1564                .must_apply_modulo_regions()
1565        };
1566
1567        let is_drop_defined_for_ty = is_drop_defined_for_ty(base_path_ty);
1568
1569        // If there is a case where no projection is applied on top of current place
1570        // then there must be exactly one capture corresponding to such a case. Note that this
1571        // represents the case of the path being completely captured by the variable.
1572        //
1573        // eg. If `a.b` is captured and we are processing `a.b`, then we can't have the closure also
1574        //     capture `a.b.c`, because that violates min capture.
1575        let is_completely_captured = captured_by_move_projs.iter().any(|projs| projs.is_empty());
1576
1577        assert!(!is_completely_captured || (captured_by_move_projs.len() == 1));
1578
1579        if is_completely_captured {
1580            // The place is captured entirely, so doesn't matter if needs dtor, it will be drop
1581            // when the closure is dropped.
1582            return false;
1583        }
1584
1585        if captured_by_move_projs.is_empty() {
1586            return needs_drop(base_path_ty);
1587        }
1588
1589        if is_drop_defined_for_ty {
1590            // If drop is implemented for this type then we need it to be fully captured,
1591            // and we know it is not completely captured because of the previous checks.
1592
1593            // Note that this is a bug in the user code that will be reported by the
1594            // borrow checker, since we can't move out of drop types.
1595
1596            // The bug exists in the user's code pre-migration, and we don't migrate here.
1597            return false;
1598        }
1599
1600        match base_path_ty.kind() {
1601            // Observations:
1602            // - `captured_by_move_projs` is not empty. Therefore we can call
1603            //   `captured_by_move_projs.first().unwrap()` safely.
1604            // - All entries in `captured_by_move_projs` have at least one projection.
1605            //   Therefore we can call `captured_by_move_projs.first().unwrap().first().unwrap()` safely.
1606
1607            // We don't capture derefs in case of move captures, which would have be applied to
1608            // access any further paths.
1609            ty::Adt(def, _) if def.is_box() => unreachable!(),
1610            ty::Ref(..) => unreachable!(),
1611            ty::RawPtr(..) => unreachable!(),
1612
1613            ty::Adt(def, args) => {
1614                // Multi-variant enums are captured in entirety,
1615                // which would've been handled in the case of single empty slice in `captured_by_move_projs`.
1616                assert_eq!(def.variants().len(), 1);
1617
1618                // Only Field projections can be applied to a non-box Adt.
1619                assert!(
1620                    captured_by_move_projs.iter().all(|projs| matches!(
1621                        projs.first().unwrap().kind,
1622                        ProjectionKind::Field(..)
1623                    ))
1624                );
1625                def.variants().get(FIRST_VARIANT).unwrap().fields.iter_enumerated().any(
1626                    |(i, field)| {
1627                        let paths_using_field = captured_by_move_projs
1628                            .iter()
1629                            .filter_map(|projs| {
1630                                if let ProjectionKind::Field(field_idx, _) =
1631                                    projs.first().unwrap().kind
1632                                {
1633                                    if field_idx == i { Some(&projs[1..]) } else { None }
1634                                } else {
1635                                    unreachable!();
1636                                }
1637                            })
1638                            .collect();
1639
1640                        let after_field_ty = field.ty(self.tcx, args);
1641                        self.has_significant_drop_outside_of_captures(
1642                            closure_def_id,
1643                            closure_span,
1644                            after_field_ty,
1645                            paths_using_field,
1646                        )
1647                    },
1648                )
1649            }
1650
1651            ty::Tuple(fields) => {
1652                // Only Field projections can be applied to a tuple.
1653                assert!(
1654                    captured_by_move_projs.iter().all(|projs| matches!(
1655                        projs.first().unwrap().kind,
1656                        ProjectionKind::Field(..)
1657                    ))
1658                );
1659
1660                fields.iter().enumerate().any(|(i, element_ty)| {
1661                    let paths_using_field = captured_by_move_projs
1662                        .iter()
1663                        .filter_map(|projs| {
1664                            if let ProjectionKind::Field(field_idx, _) = projs.first().unwrap().kind
1665                            {
1666                                if field_idx.index() == i { Some(&projs[1..]) } else { None }
1667                            } else {
1668                                unreachable!();
1669                            }
1670                        })
1671                        .collect();
1672
1673                    self.has_significant_drop_outside_of_captures(
1674                        closure_def_id,
1675                        closure_span,
1676                        element_ty,
1677                        paths_using_field,
1678                    )
1679                })
1680            }
1681
1682            // Anything else would be completely captured and therefore handled already.
1683            _ => unreachable!(),
1684        }
1685    }
1686
1687    fn init_capture_kind_for_place(
1688        &self,
1689        place: &Place<'tcx>,
1690        capture_clause: hir::CaptureBy,
1691    ) -> ty::UpvarCapture {
1692        match capture_clause {
1693            // In case of a move closure if the data is accessed through a reference we
1694            // want to capture by ref to allow precise capture using reborrows.
1695            //
1696            // If the data will be moved out of this place, then the place will be truncated
1697            // at the first Deref in `adjust_for_move_closure` and then moved into the closure.
1698            //
1699            // For example:
1700            //
1701            // struct Buffer<'a> {
1702            //     x: &'a String,
1703            //     y: Vec<u8>,
1704            // }
1705            //
1706            // fn get<'a>(b: Buffer<'a>) -> impl Sized + 'a {
1707            //     let c = move || b.x;
1708            //     drop(b);
1709            //     c
1710            // }
1711            //
1712            // Even though the closure is declared as move, when we are capturing borrowed data (in
1713            // this case, *b.x) we prefer to capture by reference.
1714            // Otherwise you'd get an error in 2021 immediately because you'd be trying to take
1715            // ownership of the (borrowed) String or else you'd take ownership of b, as in 2018 and
1716            // before, which is also an error.
1717            hir::CaptureBy::Value { .. } if !place.deref_tys().any(Ty::is_ref) => {
1718                ty::UpvarCapture::ByValue
1719            }
1720            hir::CaptureBy::Use { .. } if !place.deref_tys().any(Ty::is_ref) => {
1721                ty::UpvarCapture::ByUse
1722            }
1723            hir::CaptureBy::Value { .. } | hir::CaptureBy::Use { .. } | hir::CaptureBy::Ref => {
1724                ty::UpvarCapture::ByRef(BorrowKind::Immutable)
1725            }
1726        }
1727    }
1728
1729    fn place_for_root_variable(
1730        &self,
1731        closure_def_id: LocalDefId,
1732        var_hir_id: HirId,
1733    ) -> Place<'tcx> {
1734        let upvar_id = ty::UpvarId::new(var_hir_id, closure_def_id);
1735
1736        Place {
1737            base_ty: self.node_ty(var_hir_id),
1738            base: PlaceBase::Upvar(upvar_id),
1739            projections: Default::default(),
1740        }
1741    }
1742
1743    fn should_log_capture_analysis(&self, closure_def_id: LocalDefId) -> bool {
1744        self.tcx.has_attr(closure_def_id, sym::rustc_capture_analysis)
1745    }
1746
1747    fn log_capture_analysis_first_pass(
1748        &self,
1749        closure_def_id: LocalDefId,
1750        capture_information: &InferredCaptureInformation<'tcx>,
1751        closure_span: Span,
1752    ) {
1753        if self.should_log_capture_analysis(closure_def_id) {
1754            let mut diag =
1755                self.dcx().struct_span_err(closure_span, "First Pass analysis includes:");
1756            for (place, capture_info) in capture_information {
1757                let capture_str = construct_capture_info_string(self.tcx, place, capture_info);
1758                let output_str = format!("Capturing {capture_str}");
1759
1760                let span = capture_info.path_expr_id.map_or(closure_span, |e| self.tcx.hir_span(e));
1761                diag.span_note(span, output_str);
1762            }
1763            diag.emit();
1764        }
1765    }
1766
1767    fn log_closure_min_capture_info(&self, closure_def_id: LocalDefId, closure_span: Span) {
1768        if self.should_log_capture_analysis(closure_def_id) {
1769            if let Some(min_captures) =
1770                self.typeck_results.borrow().closure_min_captures.get(&closure_def_id)
1771            {
1772                let mut diag =
1773                    self.dcx().struct_span_err(closure_span, "Min Capture analysis includes:");
1774
1775                for (_, min_captures_for_var) in min_captures {
1776                    for capture in min_captures_for_var {
1777                        let place = &capture.place;
1778                        let capture_info = &capture.info;
1779
1780                        let capture_str =
1781                            construct_capture_info_string(self.tcx, place, capture_info);
1782                        let output_str = format!("Min Capture {capture_str}");
1783
1784                        if capture.info.path_expr_id != capture.info.capture_kind_expr_id {
1785                            let path_span = capture_info
1786                                .path_expr_id
1787                                .map_or(closure_span, |e| self.tcx.hir_span(e));
1788                            let capture_kind_span = capture_info
1789                                .capture_kind_expr_id
1790                                .map_or(closure_span, |e| self.tcx.hir_span(e));
1791
1792                            let mut multi_span: MultiSpan =
1793                                MultiSpan::from_spans(vec![path_span, capture_kind_span]);
1794
1795                            let capture_kind_label =
1796                                construct_capture_kind_reason_string(self.tcx, place, capture_info);
1797                            let path_label = construct_path_string(self.tcx, place);
1798
1799                            multi_span.push_span_label(path_span, path_label);
1800                            multi_span.push_span_label(capture_kind_span, capture_kind_label);
1801
1802                            diag.span_note(multi_span, output_str);
1803                        } else {
1804                            let span = capture_info
1805                                .path_expr_id
1806                                .map_or(closure_span, |e| self.tcx.hir_span(e));
1807
1808                            diag.span_note(span, output_str);
1809                        };
1810                    }
1811                }
1812                diag.emit();
1813            }
1814        }
1815    }
1816
1817    /// A captured place is mutable if
1818    /// 1. Projections don't include a Deref of an immut-borrow, **and**
1819    /// 2. PlaceBase is mut or projections include a Deref of a mut-borrow.
1820    fn determine_capture_mutability(
1821        &self,
1822        typeck_results: &'a TypeckResults<'tcx>,
1823        place: &Place<'tcx>,
1824    ) -> hir::Mutability {
1825        let var_hir_id = match place.base {
1826            PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
1827            _ => unreachable!(),
1828        };
1829
1830        let bm = *typeck_results.pat_binding_modes().get(var_hir_id).expect("missing binding mode");
1831
1832        let mut is_mutbl = bm.1;
1833
1834        for pointer_ty in place.deref_tys() {
1835            match self.structurally_resolve_type(self.tcx.hir_span(var_hir_id), pointer_ty).kind() {
1836                // We don't capture derefs of raw ptrs
1837                ty::RawPtr(_, _) => unreachable!(),
1838
1839                // Dereferencing a mut-ref allows us to mut the Place if we don't deref
1840                // an immut-ref after on top of this.
1841                ty::Ref(.., hir::Mutability::Mut) => is_mutbl = hir::Mutability::Mut,
1842
1843                // The place isn't mutable once we dereference an immutable reference.
1844                ty::Ref(.., hir::Mutability::Not) => return hir::Mutability::Not,
1845
1846                // Dereferencing a box doesn't change mutability
1847                ty::Adt(def, ..) if def.is_box() => {}
1848
1849                unexpected_ty => span_bug!(
1850                    self.tcx.hir_span(var_hir_id),
1851                    "deref of unexpected pointer type {:?}",
1852                    unexpected_ty
1853                ),
1854            }
1855        }
1856
1857        is_mutbl
1858    }
1859}
1860
1861/// Determines whether a child capture that is derived from a parent capture
1862/// should be borrowed with the lifetime of the parent coroutine-closure's env.
1863///
1864/// There are two cases when this needs to happen:
1865///
1866/// (1.) Are we borrowing data owned by the parent closure? We can determine if
1867/// that is the case by checking if the parent capture is by move, EXCEPT if we
1868/// apply a deref projection of an immutable reference, reborrows of immutable
1869/// references which aren't restricted to the LUB of the lifetimes of the deref
1870/// chain. This is why `&'short mut &'long T` can be reborrowed as `&'long T`.
1871///
1872/// ```rust
1873/// let x = &1i32; // Let's call this lifetime `'1`.
1874/// let c = async move || {
1875///     println!("{:?}", *x);
1876///     // Even though the inner coroutine borrows by ref, we're only capturing `*x`,
1877///     // not `x`, so the inner closure is allowed to reborrow the data for `'1`.
1878/// };
1879/// ```
1880///
1881/// (2.) If a coroutine is mutably borrowing from a parent capture, then that
1882/// mutable borrow cannot live for longer than either the parent *or* the borrow
1883/// that we have on the original upvar. Therefore we always need to borrow the
1884/// child capture with the lifetime of the parent coroutine-closure's env.
1885///
1886/// ```rust
1887/// let mut x = 1i32;
1888/// let c = async || {
1889///     x = 1;
1890///     // The parent borrows `x` for some `&'1 mut i32`.
1891///     // However, when we call `c()`, we implicitly autoref for the signature of
1892///     // `AsyncFnMut::async_call_mut`. Let's call that lifetime `'call`. Since
1893///     // the maximum that `&'call mut &'1 mut i32` can be reborrowed is `&'call mut i32`,
1894///     // the inner coroutine should capture w/ the lifetime of the coroutine-closure.
1895/// };
1896/// ```
1897///
1898/// If either of these cases apply, then we should capture the borrow with the
1899/// lifetime of the parent coroutine-closure's env. Luckily, if this function is
1900/// not correct, then the program is not unsound, since we still borrowck and validate
1901/// the choices made from this function -- the only side-effect is that the user
1902/// may receive unnecessary borrowck errors.
1903fn should_reborrow_from_env_of_parent_coroutine_closure<'tcx>(
1904    parent_capture: &ty::CapturedPlace<'tcx>,
1905    child_capture: &ty::CapturedPlace<'tcx>,
1906) -> bool {
1907    // (1.)
1908    (!parent_capture.is_by_ref()
1909        // This is just inlined `place.deref_tys()` but truncated to just
1910        // the child projections. Namely, look for a `&T` deref, since we
1911        // can always extend `&'short mut &'long T` to `&'long T`.
1912        && !child_capture
1913            .place
1914            .projections
1915            .iter()
1916            .enumerate()
1917            .skip(parent_capture.place.projections.len())
1918            .any(|(idx, proj)| {
1919                matches!(proj.kind, ProjectionKind::Deref)
1920                    && matches!(
1921                        child_capture.place.ty_before_projection(idx).kind(),
1922                        ty::Ref(.., ty::Mutability::Not)
1923                    )
1924            }))
1925        // (2.)
1926        || matches!(child_capture.info.capture_kind, UpvarCapture::ByRef(ty::BorrowKind::Mutable))
1927}
1928
1929/// Truncate the capture so that the place being borrowed is in accordance with RFC 1240,
1930/// which states that it's unsafe to take a reference into a struct marked `repr(packed)`.
1931fn restrict_repr_packed_field_ref_capture<'tcx>(
1932    mut place: Place<'tcx>,
1933    mut curr_borrow_kind: ty::UpvarCapture,
1934) -> (Place<'tcx>, ty::UpvarCapture) {
1935    let pos = place.projections.iter().enumerate().position(|(i, p)| {
1936        let ty = place.ty_before_projection(i);
1937
1938        // Return true for fields of packed structs.
1939        match p.kind {
1940            ProjectionKind::Field(..) => match ty.kind() {
1941                ty::Adt(def, _) if def.repr().packed() => {
1942                    // We stop here regardless of field alignment. Field alignment can change as
1943                    // types change, including the types of private fields in other crates, and that
1944                    // shouldn't affect how we compute our captures.
1945                    true
1946                }
1947
1948                _ => false,
1949            },
1950            _ => false,
1951        }
1952    });
1953
1954    if let Some(pos) = pos {
1955        truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_borrow_kind, pos);
1956    }
1957
1958    (place, curr_borrow_kind)
1959}
1960
1961/// Returns a Ty that applies the specified capture kind on the provided capture Ty
1962fn apply_capture_kind_on_capture_ty<'tcx>(
1963    tcx: TyCtxt<'tcx>,
1964    ty: Ty<'tcx>,
1965    capture_kind: UpvarCapture,
1966    region: ty::Region<'tcx>,
1967) -> Ty<'tcx> {
1968    match capture_kind {
1969        ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => ty,
1970        ty::UpvarCapture::ByRef(kind) => Ty::new_ref(tcx, region, ty, kind.to_mutbl_lossy()),
1971    }
1972}
1973
1974/// Returns the Span of where the value with the provided HirId would be dropped
1975fn drop_location_span(tcx: TyCtxt<'_>, hir_id: HirId) -> Span {
1976    let owner_id = tcx.hir_get_enclosing_scope(hir_id).unwrap();
1977
1978    let owner_node = tcx.hir_node(owner_id);
1979    let owner_span = match owner_node {
1980        hir::Node::Item(item) => match item.kind {
1981            hir::ItemKind::Fn { body: owner_id, .. } => tcx.hir_span(owner_id.hir_id),
1982            _ => {
1983                bug!("Drop location span error: need to handle more ItemKind '{:?}'", item.kind);
1984            }
1985        },
1986        hir::Node::Block(block) => tcx.hir_span(block.hir_id),
1987        hir::Node::TraitItem(item) => tcx.hir_span(item.hir_id()),
1988        hir::Node::ImplItem(item) => tcx.hir_span(item.hir_id()),
1989        _ => {
1990            bug!("Drop location span error: need to handle more Node '{:?}'", owner_node);
1991        }
1992    };
1993    tcx.sess.source_map().end_point(owner_span)
1994}
1995
1996struct InferBorrowKind<'tcx> {
1997    // The def-id of the closure whose kind and upvar accesses are being inferred.
1998    closure_def_id: LocalDefId,
1999
2000    /// For each Place that is captured by the closure, we track the minimal kind of
2001    /// access we need (ref, ref mut, move, etc) and the expression that resulted in such access.
2002    ///
2003    /// Consider closure where s.str1 is captured via an ImmutableBorrow and
2004    /// s.str2 via a MutableBorrow
2005    ///
2006    /// ```rust,no_run
2007    /// struct SomeStruct { str1: String, str2: String };
2008    ///
2009    /// // Assume that the HirId for the variable definition is `V1`
2010    /// let mut s = SomeStruct { str1: format!("s1"), str2: format!("s2") };
2011    ///
2012    /// let fix_s = |new_s2| {
2013    ///     // Assume that the HirId for the expression `s.str1` is `E1`
2014    ///     println!("Updating SomeStruct with str1={0}", s.str1);
2015    ///     // Assume that the HirId for the expression `*s.str2` is `E2`
2016    ///     s.str2 = new_s2;
2017    /// };
2018    /// ```
2019    ///
2020    /// For closure `fix_s`, (at a high level) the map contains
2021    ///
2022    /// ```ignore (illustrative)
2023    /// Place { V1, [ProjectionKind::Field(Index=0, Variant=0)] } : CaptureKind { E1, ImmutableBorrow }
2024    /// Place { V1, [ProjectionKind::Field(Index=1, Variant=0)] } : CaptureKind { E2, MutableBorrow }
2025    /// ```
2026    capture_information: InferredCaptureInformation<'tcx>,
2027    fake_reads: Vec<(Place<'tcx>, FakeReadCause, HirId)>,
2028}
2029
2030impl<'tcx> euv::Delegate<'tcx> for InferBorrowKind<'tcx> {
2031    fn fake_read(
2032        &mut self,
2033        place_with_id: &PlaceWithHirId<'tcx>,
2034        cause: FakeReadCause,
2035        diag_expr_id: HirId,
2036    ) {
2037        let PlaceBase::Upvar(_) = place_with_id.place.base else { return };
2038
2039        // We need to restrict Fake Read precision to avoid fake reading unsafe code,
2040        // such as deref of a raw pointer.
2041        let dummy_capture_kind = ty::UpvarCapture::ByRef(ty::BorrowKind::Immutable);
2042
2043        let (place, _) =
2044            restrict_capture_precision(place_with_id.place.clone(), dummy_capture_kind);
2045
2046        let (place, _) = restrict_repr_packed_field_ref_capture(place, dummy_capture_kind);
2047        self.fake_reads.push((place, cause, diag_expr_id));
2048    }
2049
2050    #[instrument(skip(self), level = "debug")]
2051    fn consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
2052        let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return };
2053        assert_eq!(self.closure_def_id, upvar_id.closure_expr_id);
2054
2055        self.capture_information.push((
2056            place_with_id.place.clone(),
2057            ty::CaptureInfo {
2058                capture_kind_expr_id: Some(diag_expr_id),
2059                path_expr_id: Some(diag_expr_id),
2060                capture_kind: ty::UpvarCapture::ByValue,
2061            },
2062        ));
2063    }
2064
2065    #[instrument(skip(self), level = "debug")]
2066    fn use_cloned(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
2067        let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return };
2068        assert_eq!(self.closure_def_id, upvar_id.closure_expr_id);
2069
2070        self.capture_information.push((
2071            place_with_id.place.clone(),
2072            ty::CaptureInfo {
2073                capture_kind_expr_id: Some(diag_expr_id),
2074                path_expr_id: Some(diag_expr_id),
2075                capture_kind: ty::UpvarCapture::ByUse,
2076            },
2077        ));
2078    }
2079
2080    #[instrument(skip(self), level = "debug")]
2081    fn borrow(
2082        &mut self,
2083        place_with_id: &PlaceWithHirId<'tcx>,
2084        diag_expr_id: HirId,
2085        bk: ty::BorrowKind,
2086    ) {
2087        let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return };
2088        assert_eq!(self.closure_def_id, upvar_id.closure_expr_id);
2089
2090        // The region here will get discarded/ignored
2091        let capture_kind = ty::UpvarCapture::ByRef(bk);
2092
2093        // We only want repr packed restriction to be applied to reading references into a packed
2094        // struct, and not when the data is being moved. Therefore we call this method here instead
2095        // of in `restrict_capture_precision`.
2096        let (place, mut capture_kind) =
2097            restrict_repr_packed_field_ref_capture(place_with_id.place.clone(), capture_kind);
2098
2099        // Raw pointers don't inherit mutability
2100        if place_with_id.place.deref_tys().any(Ty::is_raw_ptr) {
2101            capture_kind = ty::UpvarCapture::ByRef(ty::BorrowKind::Immutable);
2102        }
2103
2104        self.capture_information.push((
2105            place,
2106            ty::CaptureInfo {
2107                capture_kind_expr_id: Some(diag_expr_id),
2108                path_expr_id: Some(diag_expr_id),
2109                capture_kind,
2110            },
2111        ));
2112    }
2113
2114    #[instrument(skip(self), level = "debug")]
2115    fn mutate(&mut self, assignee_place: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
2116        self.borrow(assignee_place, diag_expr_id, ty::BorrowKind::Mutable);
2117    }
2118}
2119
2120/// Rust doesn't permit moving fields out of a type that implements drop
2121fn restrict_precision_for_drop_types<'a, 'tcx>(
2122    fcx: &'a FnCtxt<'a, 'tcx>,
2123    mut place: Place<'tcx>,
2124    mut curr_mode: ty::UpvarCapture,
2125) -> (Place<'tcx>, ty::UpvarCapture) {
2126    let is_copy_type = fcx.infcx.type_is_copy_modulo_regions(fcx.param_env, place.ty());
2127
2128    if let (false, UpvarCapture::ByValue) = (is_copy_type, curr_mode) {
2129        for i in 0..place.projections.len() {
2130            match place.ty_before_projection(i).kind() {
2131                ty::Adt(def, _) if def.destructor(fcx.tcx).is_some() => {
2132                    truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i);
2133                    break;
2134                }
2135                _ => {}
2136            }
2137        }
2138    }
2139
2140    (place, curr_mode)
2141}
2142
2143/// Truncate `place` so that an `unsafe` block isn't required to capture it.
2144/// - No projections are applied to raw pointers, since these require unsafe blocks. We capture
2145///   them completely.
2146/// - No projections are applied on top of Union ADTs, since these require unsafe blocks.
2147fn restrict_precision_for_unsafe(
2148    mut place: Place<'_>,
2149    mut curr_mode: ty::UpvarCapture,
2150) -> (Place<'_>, ty::UpvarCapture) {
2151    if place.base_ty.is_raw_ptr() {
2152        truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, 0);
2153    }
2154
2155    if place.base_ty.is_union() {
2156        truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, 0);
2157    }
2158
2159    for (i, proj) in place.projections.iter().enumerate() {
2160        if proj.ty.is_raw_ptr() {
2161            // Don't apply any projections on top of a raw ptr.
2162            truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i + 1);
2163            break;
2164        }
2165
2166        if proj.ty.is_union() {
2167            // Don't capture precise fields of a union.
2168            truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i + 1);
2169            break;
2170        }
2171    }
2172
2173    (place, curr_mode)
2174}
2175
2176/// Truncate projections so that following rules are obeyed by the captured `place`:
2177/// - No Index projections are captured, since arrays are captured completely.
2178/// - No unsafe block is required to capture `place`
2179/// Returns the truncated place and updated capture mode.
2180fn restrict_capture_precision(
2181    place: Place<'_>,
2182    curr_mode: ty::UpvarCapture,
2183) -> (Place<'_>, ty::UpvarCapture) {
2184    let (mut place, mut curr_mode) = restrict_precision_for_unsafe(place, curr_mode);
2185
2186    if place.projections.is_empty() {
2187        // Nothing to do here
2188        return (place, curr_mode);
2189    }
2190
2191    for (i, proj) in place.projections.iter().enumerate() {
2192        match proj.kind {
2193            ProjectionKind::Index | ProjectionKind::Subslice => {
2194                // Arrays are completely captured, so we drop Index and Subslice projections
2195                truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i);
2196                return (place, curr_mode);
2197            }
2198            ProjectionKind::Deref => {}
2199            ProjectionKind::OpaqueCast => {}
2200            ProjectionKind::Field(..) => {} // ignore
2201        }
2202    }
2203
2204    (place, curr_mode)
2205}
2206
2207/// Truncate deref of any reference.
2208fn adjust_for_move_closure(
2209    mut place: Place<'_>,
2210    mut kind: ty::UpvarCapture,
2211) -> (Place<'_>, ty::UpvarCapture) {
2212    let first_deref = place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
2213
2214    if let Some(idx) = first_deref {
2215        truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
2216    }
2217
2218    (place, ty::UpvarCapture::ByValue)
2219}
2220
2221/// Truncate deref of any reference.
2222fn adjust_for_use_closure(
2223    mut place: Place<'_>,
2224    mut kind: ty::UpvarCapture,
2225) -> (Place<'_>, ty::UpvarCapture) {
2226    let first_deref = place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
2227
2228    if let Some(idx) = first_deref {
2229        truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
2230    }
2231
2232    (place, ty::UpvarCapture::ByUse)
2233}
2234
2235/// Adjust closure capture just that if taking ownership of data, only move data
2236/// from enclosing stack frame.
2237fn adjust_for_non_move_closure(
2238    mut place: Place<'_>,
2239    mut kind: ty::UpvarCapture,
2240) -> (Place<'_>, ty::UpvarCapture) {
2241    let contains_deref =
2242        place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
2243
2244    match kind {
2245        ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {
2246            if let Some(idx) = contains_deref {
2247                truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
2248            }
2249        }
2250
2251        ty::UpvarCapture::ByRef(..) => {}
2252    }
2253
2254    (place, kind)
2255}
2256
2257fn construct_place_string<'tcx>(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
2258    let variable_name = match place.base {
2259        PlaceBase::Upvar(upvar_id) => var_name(tcx, upvar_id.var_path.hir_id).to_string(),
2260        _ => bug!("Capture_information should only contain upvars"),
2261    };
2262
2263    let mut projections_str = String::new();
2264    for (i, item) in place.projections.iter().enumerate() {
2265        let proj = match item.kind {
2266            ProjectionKind::Field(a, b) => format!("({a:?}, {b:?})"),
2267            ProjectionKind::Deref => String::from("Deref"),
2268            ProjectionKind::Index => String::from("Index"),
2269            ProjectionKind::Subslice => String::from("Subslice"),
2270            ProjectionKind::OpaqueCast => String::from("OpaqueCast"),
2271        };
2272        if i != 0 {
2273            projections_str.push(',');
2274        }
2275        projections_str.push_str(proj.as_str());
2276    }
2277
2278    format!("{variable_name}[{projections_str}]")
2279}
2280
2281fn construct_capture_kind_reason_string<'tcx>(
2282    tcx: TyCtxt<'_>,
2283    place: &Place<'tcx>,
2284    capture_info: &ty::CaptureInfo,
2285) -> String {
2286    let place_str = construct_place_string(tcx, place);
2287
2288    let capture_kind_str = match capture_info.capture_kind {
2289        ty::UpvarCapture::ByValue => "ByValue".into(),
2290        ty::UpvarCapture::ByUse => "ByUse".into(),
2291        ty::UpvarCapture::ByRef(kind) => format!("{kind:?}"),
2292    };
2293
2294    format!("{place_str} captured as {capture_kind_str} here")
2295}
2296
2297fn construct_path_string<'tcx>(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
2298    let place_str = construct_place_string(tcx, place);
2299
2300    format!("{place_str} used here")
2301}
2302
2303fn construct_capture_info_string<'tcx>(
2304    tcx: TyCtxt<'_>,
2305    place: &Place<'tcx>,
2306    capture_info: &ty::CaptureInfo,
2307) -> String {
2308    let place_str = construct_place_string(tcx, place);
2309
2310    let capture_kind_str = match capture_info.capture_kind {
2311        ty::UpvarCapture::ByValue => "ByValue".into(),
2312        ty::UpvarCapture::ByUse => "ByUse".into(),
2313        ty::UpvarCapture::ByRef(kind) => format!("{kind:?}"),
2314    };
2315    format!("{place_str} -> {capture_kind_str}")
2316}
2317
2318fn var_name(tcx: TyCtxt<'_>, var_hir_id: HirId) -> Symbol {
2319    tcx.hir_name(var_hir_id)
2320}
2321
2322#[instrument(level = "debug", skip(tcx))]
2323fn should_do_rust_2021_incompatible_closure_captures_analysis(
2324    tcx: TyCtxt<'_>,
2325    closure_id: HirId,
2326) -> bool {
2327    if tcx.sess.at_least_rust_2021() {
2328        return false;
2329    }
2330
2331    let level = tcx
2332        .lint_level_at_node(lint::builtin::RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES, closure_id)
2333        .level;
2334
2335    !matches!(level, lint::Level::Allow)
2336}
2337
2338/// Return a two string tuple (s1, s2)
2339/// - s1: Line of code that is needed for the migration: eg: `let _ = (&x, ...)`.
2340/// - s2: Comma separated names of the variables being migrated.
2341fn migration_suggestion_for_2229(
2342    tcx: TyCtxt<'_>,
2343    need_migrations: &[NeededMigration],
2344) -> (String, String) {
2345    let need_migrations_variables = need_migrations
2346        .iter()
2347        .map(|NeededMigration { var_hir_id: v, .. }| var_name(tcx, *v))
2348        .collect::<Vec<_>>();
2349
2350    let migration_ref_concat =
2351        need_migrations_variables.iter().map(|v| format!("&{v}")).collect::<Vec<_>>().join(", ");
2352
2353    let migration_string = if 1 == need_migrations.len() {
2354        format!("let _ = {migration_ref_concat}")
2355    } else {
2356        format!("let _ = ({migration_ref_concat})")
2357    };
2358
2359    let migrated_variables_concat =
2360        need_migrations_variables.iter().map(|v| format!("`{v}`")).collect::<Vec<_>>().join(", ");
2361
2362    (migration_string, migrated_variables_concat)
2363}
2364
2365/// Helper function to determine if we need to escalate CaptureKind from
2366/// CaptureInfo A to B and returns the escalated CaptureInfo.
2367/// (Note: CaptureInfo contains CaptureKind and an expression that led to capture it in that way)
2368///
2369/// If both `CaptureKind`s are considered equivalent, then the CaptureInfo is selected based
2370/// on the `CaptureInfo` containing an associated `capture_kind_expr_id`.
2371///
2372/// It is the caller's duty to figure out which path_expr_id to use.
2373///
2374/// If both the CaptureKind and Expression are considered to be equivalent,
2375/// then `CaptureInfo` A is preferred. This can be useful in cases where we want to prioritize
2376/// expressions reported back to the user as part of diagnostics based on which appears earlier
2377/// in the closure. This can be achieved simply by calling
2378/// `determine_capture_info(existing_info, current_info)`. This works out because the
2379/// expressions that occur earlier in the closure body than the current expression are processed before.
2380/// Consider the following example
2381/// ```rust,no_run
2382/// struct Point { x: i32, y: i32 }
2383/// let mut p = Point { x: 10, y: 10 };
2384///
2385/// let c = || {
2386///     p.x     += 10;
2387/// // ^ E1 ^
2388///     // ...
2389///     // More code
2390///     // ...
2391///     p.x += 10; // E2
2392/// // ^ E2 ^
2393/// };
2394/// ```
2395/// `CaptureKind` associated with both `E1` and `E2` will be ByRef(MutBorrow),
2396/// and both have an expression associated, however for diagnostics we prefer reporting
2397/// `E1` since it appears earlier in the closure body. When `E2` is being processed we
2398/// would've already handled `E1`, and have an existing capture_information for it.
2399/// Calling `determine_capture_info(existing_info_e1, current_info_e2)` will return
2400/// `existing_info_e1` in this case, allowing us to point to `E1` in case of diagnostics.
2401fn determine_capture_info(
2402    capture_info_a: ty::CaptureInfo,
2403    capture_info_b: ty::CaptureInfo,
2404) -> ty::CaptureInfo {
2405    // If the capture kind is equivalent then, we don't need to escalate and can compare the
2406    // expressions.
2407    let eq_capture_kind = match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
2408        (ty::UpvarCapture::ByValue, ty::UpvarCapture::ByValue) => true,
2409        (ty::UpvarCapture::ByUse, ty::UpvarCapture::ByUse) => true,
2410        (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => ref_a == ref_b,
2411        (ty::UpvarCapture::ByValue, _)
2412        | (ty::UpvarCapture::ByUse, _)
2413        | (ty::UpvarCapture::ByRef(_), _) => false,
2414    };
2415
2416    if eq_capture_kind {
2417        match (capture_info_a.capture_kind_expr_id, capture_info_b.capture_kind_expr_id) {
2418            (Some(_), _) | (None, None) => capture_info_a,
2419            (None, Some(_)) => capture_info_b,
2420        }
2421    } else {
2422        // We select the CaptureKind which ranks higher based the following priority order:
2423        // (ByUse | ByValue) > MutBorrow > UniqueImmBorrow > ImmBorrow
2424        match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
2425            (ty::UpvarCapture::ByUse, ty::UpvarCapture::ByValue)
2426            | (ty::UpvarCapture::ByValue, ty::UpvarCapture::ByUse) => {
2427                bug!("Same capture can't be ByUse and ByValue at the same time")
2428            }
2429            (ty::UpvarCapture::ByValue, ty::UpvarCapture::ByValue)
2430            | (ty::UpvarCapture::ByUse, ty::UpvarCapture::ByUse)
2431            | (ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse, ty::UpvarCapture::ByRef(_)) => {
2432                capture_info_a
2433            }
2434            (ty::UpvarCapture::ByRef(_), ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse) => {
2435                capture_info_b
2436            }
2437            (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => {
2438                match (ref_a, ref_b) {
2439                    // Take LHS:
2440                    (BorrowKind::UniqueImmutable | BorrowKind::Mutable, BorrowKind::Immutable)
2441                    | (BorrowKind::Mutable, BorrowKind::UniqueImmutable) => capture_info_a,
2442
2443                    // Take RHS:
2444                    (BorrowKind::Immutable, BorrowKind::UniqueImmutable | BorrowKind::Mutable)
2445                    | (BorrowKind::UniqueImmutable, BorrowKind::Mutable) => capture_info_b,
2446
2447                    (BorrowKind::Immutable, BorrowKind::Immutable)
2448                    | (BorrowKind::UniqueImmutable, BorrowKind::UniqueImmutable)
2449                    | (BorrowKind::Mutable, BorrowKind::Mutable) => {
2450                        bug!("Expected unequal capture kinds");
2451                    }
2452                }
2453            }
2454        }
2455    }
2456}
2457
2458/// Truncates `place` to have up to `len` projections.
2459/// `curr_mode` is the current required capture kind for the place.
2460/// Returns the truncated `place` and the updated required capture kind.
2461///
2462/// Note: Capture kind changes from `MutBorrow` to `UniqueImmBorrow` if the truncated part of the `place`
2463/// contained `Deref` of `&mut`.
2464fn truncate_place_to_len_and_update_capture_kind<'tcx>(
2465    place: &mut Place<'tcx>,
2466    curr_mode: &mut ty::UpvarCapture,
2467    len: usize,
2468) {
2469    let is_mut_ref = |ty: Ty<'_>| matches!(ty.kind(), ty::Ref(.., hir::Mutability::Mut));
2470
2471    // If the truncated part of the place contains `Deref` of a `&mut` then convert MutBorrow ->
2472    // UniqueImmBorrow
2473    // Note that if the place contained Deref of a raw pointer it would've not been MutBorrow, so
2474    // we don't need to worry about that case here.
2475    match curr_mode {
2476        ty::UpvarCapture::ByRef(ty::BorrowKind::Mutable) => {
2477            for i in len..place.projections.len() {
2478                if place.projections[i].kind == ProjectionKind::Deref
2479                    && is_mut_ref(place.ty_before_projection(i))
2480                {
2481                    *curr_mode = ty::UpvarCapture::ByRef(ty::BorrowKind::UniqueImmutable);
2482                    break;
2483                }
2484            }
2485        }
2486
2487        ty::UpvarCapture::ByRef(..) => {}
2488        ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {}
2489    }
2490
2491    place.projections.truncate(len);
2492}
2493
2494/// Determines the Ancestry relationship of Place A relative to Place B
2495///
2496/// `PlaceAncestryRelation::Ancestor` implies Place A is ancestor of Place B
2497/// `PlaceAncestryRelation::Descendant` implies Place A is descendant of Place B
2498/// `PlaceAncestryRelation::Divergent` implies neither of them is the ancestor of the other.
2499fn determine_place_ancestry_relation<'tcx>(
2500    place_a: &Place<'tcx>,
2501    place_b: &Place<'tcx>,
2502) -> PlaceAncestryRelation {
2503    // If Place A and Place B don't start off from the same root variable, they are divergent.
2504    if place_a.base != place_b.base {
2505        return PlaceAncestryRelation::Divergent;
2506    }
2507
2508    // Assume of length of projections_a = n
2509    let projections_a = &place_a.projections;
2510
2511    // Assume of length of projections_b = m
2512    let projections_b = &place_b.projections;
2513
2514    let same_initial_projections =
2515        iter::zip(projections_a, projections_b).all(|(proj_a, proj_b)| proj_a.kind == proj_b.kind);
2516
2517    if same_initial_projections {
2518        use std::cmp::Ordering;
2519
2520        // First min(n, m) projections are the same
2521        // Select Ancestor/Descendant
2522        match projections_b.len().cmp(&projections_a.len()) {
2523            Ordering::Greater => PlaceAncestryRelation::Ancestor,
2524            Ordering::Equal => PlaceAncestryRelation::SamePlace,
2525            Ordering::Less => PlaceAncestryRelation::Descendant,
2526        }
2527    } else {
2528        PlaceAncestryRelation::Divergent
2529    }
2530}
2531
2532/// Reduces the precision of the captured place when the precision doesn't yield any benefit from
2533/// borrow checking perspective, allowing us to save us on the size of the capture.
2534///
2535///
2536/// Fields that are read through a shared reference will always be read via a shared ref or a copy,
2537/// and therefore capturing precise paths yields no benefit. This optimization truncates the
2538/// rightmost deref of the capture if the deref is applied to a shared ref.
2539///
2540/// Reason we only drop the last deref is because of the following edge case:
2541///
2542/// ```
2543/// # struct A { field_of_a: Box<i32> }
2544/// # struct B {}
2545/// # struct C<'a>(&'a i32);
2546/// struct MyStruct<'a> {
2547///    a: &'static A,
2548///    b: B,
2549///    c: C<'a>,
2550/// }
2551///
2552/// fn foo<'a, 'b>(m: &'a MyStruct<'b>) -> impl FnMut() + 'static {
2553///     || drop(&*m.a.field_of_a)
2554///     // Here we really do want to capture `*m.a` because that outlives `'static`
2555///
2556///     // If we capture `m`, then the closure no longer outlives `'static`
2557///     // it is constrained to `'a`
2558/// }
2559/// ```
2560fn truncate_capture_for_optimization(
2561    mut place: Place<'_>,
2562    mut curr_mode: ty::UpvarCapture,
2563) -> (Place<'_>, ty::UpvarCapture) {
2564    let is_shared_ref = |ty: Ty<'_>| matches!(ty.kind(), ty::Ref(.., hir::Mutability::Not));
2565
2566    // Find the rightmost deref (if any). All the projections that come after this
2567    // are fields or other "in-place pointer adjustments"; these refer therefore to
2568    // data owned by whatever pointer is being dereferenced here.
2569    let idx = place.projections.iter().rposition(|proj| ProjectionKind::Deref == proj.kind);
2570
2571    match idx {
2572        // If that pointer is a shared reference, then we don't need those fields.
2573        Some(idx) if is_shared_ref(place.ty_before_projection(idx)) => {
2574            truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, idx + 1)
2575        }
2576        None | Some(_) => {}
2577    }
2578
2579    (place, curr_mode)
2580}
2581
2582/// Precise capture is enabled if user is using Rust Edition 2021 or higher.
2583/// `span` is the span of the closure.
2584fn enable_precise_capture(span: Span) -> bool {
2585    // We use span here to ensure that if the closure was generated by a macro with a different
2586    // edition.
2587    span.at_least_rust_2021()
2588}