Skip to main content

hir_ty/infer/closure/
analysis.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 `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, mem};
34
35use hir_def::{
36    expr_store::ExpressionStore,
37    hir::{
38        BindingAnnotation, BindingId, CaptureBy, CoroutineSource, Expr, ExprId, ExprOrPatIdPacked,
39        Pat, PatId, Statement,
40    },
41    resolver::ValueNs,
42};
43use macros::{TypeFoldable, TypeVisitable};
44use rustc_abi::ExternAbi;
45use rustc_ast_ir::Mutability;
46use rustc_hash::{FxBuildHasher, FxHashMap};
47use rustc_type_ir::{
48    BoundVar, ClosureKind,
49    inherent::{AdtDef as _, GenericArgs as _, IntoKind as _, Ty as _},
50};
51use smallvec::{SmallVec, smallvec};
52use span::Edition;
53use tracing::{debug, instrument};
54
55use crate::{
56    Span,
57    infer::{
58        CaptureInfo, CaptureSourceStack, CapturedPlace, InferenceContext, UpvarCapture,
59        closure::analysis::expr_use_visitor::{
60            self as euv, FakeReadCause, Place, PlaceBase, PlaceWithOrigin, Projection,
61            ProjectionKind,
62        },
63    },
64    next_solver::{
65        Binder, BoundRegion, BoundRegionKind, DbInterner, GenericArgs, Region, Ty, TyKind,
66        abi::Safety, infer::traits::ObligationCause, normalize,
67    },
68    upvars::{Upvars, UpvarsRef},
69};
70
71pub(crate) mod expr_use_visitor;
72
73#[derive(Debug, Copy, Clone, TypeVisitable, TypeFoldable)]
74enum UpvarArgs<'db> {
75    Closure(GenericArgs<'db>),
76    Coroutine(GenericArgs<'db>),
77    CoroutineClosure(GenericArgs<'db>),
78}
79
80impl<'db> UpvarArgs<'db> {
81    #[inline]
82    fn tupled_upvars_ty(self) -> Ty<'db> {
83        match self {
84            UpvarArgs::Closure(args) => args.as_closure().tupled_upvars_ty(),
85            UpvarArgs::Coroutine(args) => args.as_coroutine().tupled_upvars_ty(),
86            UpvarArgs::CoroutineClosure(args) => args.as_coroutine_closure().tupled_upvars_ty(),
87        }
88    }
89}
90
91#[derive(Eq, Clone, PartialEq, Debug, Copy, Hash)]
92pub enum BorrowKind {
93    /// Data must be immutable and is aliasable.
94    Immutable,
95
96    /// Data must be immutable but not aliasable. This kind of borrow
97    /// cannot currently be expressed by the user and is used only in
98    /// implicit closure bindings. It is needed when the closure
99    /// is borrowing or mutating a mutable referent, e.g.:
100    ///
101    /// ```
102    /// let mut z = 3;
103    /// let x: &mut isize = &mut z;
104    /// let y = || *x += 5;
105    /// ```
106    ///
107    /// If we were to try to translate this closure into a more explicit
108    /// form, we'd encounter an error with the code as written:
109    ///
110    /// ```compile_fail,E0594
111    /// struct Env<'a> { x: &'a &'a mut isize }
112    /// let mut z = 3;
113    /// let x: &mut isize = &mut z;
114    /// let y = (&mut Env { x: &x }, fn_ptr);  // Closure is pair of env and fn
115    /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
116    /// ```
117    ///
118    /// This is then illegal because you cannot mutate a `&mut` found
119    /// in an aliasable location. To solve, you'd have to translate with
120    /// an `&mut` borrow:
121    ///
122    /// ```compile_fail,E0596
123    /// struct Env<'a> { x: &'a mut &'a mut isize }
124    /// let mut z = 3;
125    /// let x: &mut isize = &mut z;
126    /// let y = (&mut Env { x: &mut x }, fn_ptr); // changed from &x to &mut x
127    /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
128    /// ```
129    ///
130    /// Now the assignment to `**env.x` is legal, but creating a
131    /// mutable pointer to `x` is not because `x` is not mutable. We
132    /// could fix this by declaring `x` as `let mut x`. This is ok in
133    /// user code, if awkward, but extra weird for closures, since the
134    /// borrow is hidden.
135    ///
136    /// So we introduce a "unique imm" borrow -- the referent is
137    /// immutable, but not aliasable. This solves the problem. For
138    /// simplicity, we don't give users the way to express this
139    /// borrow, it's just used when translating closures.
140    ///
141    /// FIXME: Rename this to indicate the borrow is actually not immutable.
142    UniqueImmutable,
143
144    /// Data is mutable and not aliasable.
145    Mutable,
146}
147
148impl BorrowKind {
149    pub fn from_hir_mutbl(m: hir_def::hir::type_ref::Mutability) -> BorrowKind {
150        match m {
151            hir_def::hir::type_ref::Mutability::Mut => BorrowKind::Mutable,
152            hir_def::hir::type_ref::Mutability::Shared => BorrowKind::Immutable,
153        }
154    }
155
156    pub fn from_mutbl(m: Mutability) -> BorrowKind {
157        match m {
158            Mutability::Mut => BorrowKind::Mutable,
159            Mutability::Not => BorrowKind::Immutable,
160        }
161    }
162
163    /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow
164    /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a
165    /// mutability that is stronger than necessary so that it at least *would permit* the borrow in
166    /// question.
167    pub fn to_mutbl_lossy(self) -> Mutability {
168        match self {
169            BorrowKind::Mutable => Mutability::Mut,
170            BorrowKind::Immutable => Mutability::Not,
171
172            // We have no type corresponding to a unique imm borrow, so
173            // use `&mut`. It gives all the capabilities of a `&uniq`
174            // and hence is a safe "over approximation".
175            BorrowKind::UniqueImmutable => Mutability::Mut,
176        }
177    }
178}
179
180/// Describe the relationship between the paths of two places
181/// eg:
182/// - `foo` is ancestor of `foo.bar.baz`
183/// - `foo.bar.baz` is an descendant of `foo.bar`
184/// - `foo.bar` and `foo.baz` are divergent
185enum PlaceAncestryRelation {
186    Ancestor,
187    Descendant,
188    SamePlace,
189    Divergent,
190}
191
192/// Intermediate format to store a captured `Place` and associated `CaptureInfo`
193/// during capture analysis. Information in this map feeds into the minimum capture
194/// analysis pass.
195type InferredCaptureInformation = Vec<(Place, CaptureInfo)>;
196
197impl<'db> InferenceContext<'db> {
198    pub(crate) fn closure_analyze(&mut self) {
199        let upvars = crate::upvars::upvars_mentioned(self.db, self.store_owner)
200            .unwrap_or(const { &FxHashMap::with_hasher(FxBuildHasher) });
201        for root_expr in self.store.expr_roots() {
202            self.analyze_closures_in_expr(root_expr, upvars);
203        }
204
205        // it's our job to process these.
206        assert!(self.deferred_call_resolutions.is_empty());
207    }
208
209    fn analyze_closures_in_expr(&mut self, expr: ExprId, upvars: &'db FxHashMap<ExprId, Upvars>) {
210        self.store.walk_child_exprs(expr, |expr| self.analyze_closures_in_expr(expr, upvars));
211
212        match &self.store[expr] {
213            Expr::Closure { args, body, closure_kind, capture_by, .. } => {
214                self.analyze_closure(
215                    expr,
216                    args,
217                    *body,
218                    *capture_by,
219                    *closure_kind,
220                    upvars.get(&expr).map(|upvars| upvars.as_ref()).unwrap_or_default(),
221                );
222            }
223            _ => {}
224        }
225    }
226
227    /// Analysis starting point.
228    #[instrument(skip(self, body), level = "debug")]
229    fn analyze_closure(
230        &mut self,
231        closure_expr_id: ExprId,
232        params: &[PatId],
233        body: ExprId,
234        mut capture_clause: CaptureBy,
235        closure_kind: hir_def::hir::ClosureKind,
236        upvars: UpvarsRef<'db>,
237    ) {
238        // Extract the type of the closure.
239        let ty = self.expr_ty(closure_expr_id);
240        let (args, infer_kind) = match ty.kind() {
241            TyKind::Closure(_def_id, args) => {
242                (UpvarArgs::Closure(args), self.infcx().closure_kind(ty).is_none())
243            }
244            TyKind::CoroutineClosure(_def_id, args) => {
245                (UpvarArgs::CoroutineClosure(args), self.infcx().closure_kind(ty).is_none())
246            }
247            TyKind::Coroutine(_def_id, args) => (UpvarArgs::Coroutine(args), false),
248            TyKind::Error(_) => {
249                // #51714: skip analysis when we have already encountered type errors
250                return;
251            }
252            _ => {
253                panic!("type of closure expr {:?} is not a closure {:?}", closure_expr_id, ty);
254            }
255        };
256        let args = self.infcx().resolve_vars_if_possible(args);
257
258        let mut delegate = InferBorrowKind {
259            closure_def_id: closure_expr_id,
260            capture_information: Default::default(),
261            fake_reads: Default::default(),
262        };
263
264        let _ = euv::ExprUseVisitor::new(self, closure_expr_id, upvars, &mut delegate)
265            .consume_closure_body(params, body);
266
267        // There are several curious situations with coroutine-closures where
268        // analysis is too aggressive with borrows when the coroutine-closure is
269        // marked `move`. Specifically:
270        //
271        // 1. If the coroutine-closure was inferred to be `FnOnce` during signature
272        // inference, then it's still possible that we try to borrow upvars from
273        // the coroutine-closure because they are not used by the coroutine body
274        // in a way that forces a move. See the test:
275        // `async-await/async-closures/force-move-due-to-inferred-kind.rs`.
276        //
277        // 2. If the coroutine-closure is forced to be `FnOnce` due to the way it
278        // uses its upvars (e.g. it consumes a non-copy value), but not *all* upvars
279        // would force the closure to `FnOnce`.
280        // See the test: `async-await/async-closures/force-move-due-to-actually-fnonce.rs`.
281        //
282        // This would lead to an impossible to satisfy situation, since `AsyncFnOnce`
283        // coroutine bodies can't borrow from their parent closure. To fix this,
284        // we force the inner coroutine to also be `move`. This only matters for
285        // coroutine-closures that are `move` since otherwise they themselves will
286        // be borrowing from the outer environment, so there's no self-borrows occurring.
287        if let UpvarArgs::Coroutine(..) = args
288            && let hir_def::hir::ClosureKind::Coroutine { source: CoroutineSource::Closure, .. } =
289                closure_kind
290            && let parent_hir_id = ExpressionStore::closure_for_coroutine(closure_expr_id)
291            && let parent_ty = self.result.expr_ty(parent_hir_id)
292            && let Expr::Closure { capture_by: CaptureBy::Value, .. } = self.store[parent_hir_id]
293        {
294            // (1.) Closure signature inference forced this closure to `FnOnce`.
295            if let Some(ClosureKind::FnOnce) = self.infcx().closure_kind(parent_ty) {
296                capture_clause = CaptureBy::Value;
297            }
298            // (2.) The way that the closure uses its upvars means it's `FnOnce`.
299            else if self.coroutine_body_consumes_upvars(closure_expr_id, body, upvars) {
300                capture_clause = CaptureBy::Value;
301            }
302        }
303
304        // As noted in `lower_coroutine_body_with_moved_arguments`, we default the capture mode
305        // to `ByRef` for the `async {}` block internal to async fns/closure. This means
306        // that we would *not* be moving all of the parameters into the async block in all cases.
307        // For example, when one of the arguments is `Copy`, we turn a consuming use into a copy of
308        // a reference, so for `async fn x(t: i32) {}`, we'd only take a reference to `t`.
309        //
310        // We force all of these arguments to be captured by move before we do expr use analysis.
311        //
312        // FIXME(async_closures): This could be cleaned up. It's a bit janky that we're just
313        // moving all of the `LocalSource::AsyncFn` locals here.
314        if let hir_def::hir::ClosureKind::Coroutine {
315            source: CoroutineSource::Fn | CoroutineSource::Closure,
316            ..
317        } = closure_kind
318        {
319            let Expr::Block { statements, .. } = &self.store[body] else {
320                panic!();
321            };
322            for stmt in statements {
323                let Statement::Let { pat, initializer: Some(init), .. } = *stmt else {
324                    panic!();
325                };
326                let Pat::Bind { .. } = self.store[pat] else {
327                    // Complex pattern, skip the non-upvar local.
328                    continue;
329                };
330                let Expr::Path(path) = &self.store[init] else {
331                    panic!();
332                };
333                let update_guard =
334                    self.resolver.update_to_inner_scope(self.db, self.store_owner, init);
335                let Some(ValueNs::LocalBinding(local_id)) =
336                    self.resolver.resolve_path_in_value_ns_fully(
337                        self.db,
338                        path,
339                        self.store.expr_path_hygiene(init),
340                    )
341                else {
342                    panic!();
343                };
344                self.resolver.reset_to_guard(update_guard);
345                let place = self.place_for_root_variable(closure_expr_id, local_id);
346                delegate.capture_information.push((
347                    place,
348                    CaptureInfo {
349                        sources: smallvec![CaptureSourceStack::from_single(init.into())],
350                        capture_kind: UpvarCapture::ByValue,
351                    },
352                ));
353            }
354        }
355
356        debug!(
357            "For closure={:?}, capture_information={:#?}",
358            closure_expr_id, delegate.capture_information
359        );
360
361        let (capture_information, closure_kind, _origin) = self
362            .process_collected_capture_information(capture_clause, &delegate.capture_information);
363
364        self.compute_min_captures(closure_expr_id, capture_information);
365
366        // We now fake capture information for all variables that are mentioned within the closure
367        // We do this after handling migrations so that min_captures computes before
368        if !enable_precise_capture(self.edition) {
369            let mut capture_information: InferredCaptureInformation = Default::default();
370
371            for var_hir_id in upvars.iter() {
372                let place = Place {
373                    base_ty: self.result.binding_ty(var_hir_id).store(),
374                    base: PlaceBase::Upvar { closure: closure_expr_id, var_id: var_hir_id },
375                    projections: Vec::new(),
376                };
377
378                debug!("seed place {:?}", place);
379
380                let capture_kind = self.init_capture_kind_for_place(&place, capture_clause);
381                let fake_info = CaptureInfo { sources: SmallVec::new(), capture_kind };
382
383                capture_information.push((place, fake_info));
384            }
385
386            // This will update the min captures based on this new fake information.
387            self.compute_min_captures(closure_expr_id, capture_information);
388        }
389
390        if infer_kind {
391            // Unify the (as yet unbound) type variable in the closure
392            // args with the kind we inferred.
393            let closure_kind_ty = match args {
394                UpvarArgs::Closure(args) => args.as_closure().kind_ty(),
395                UpvarArgs::CoroutineClosure(args) => args.as_coroutine_closure().kind_ty(),
396                UpvarArgs::Coroutine(_) => unreachable!("coroutines don't have an inferred kind"),
397            };
398            _ = self.demand_eqtype(
399                closure_expr_id.into(),
400                Ty::from_closure_kind(self.interner(), closure_kind),
401                closure_kind_ty,
402            );
403        }
404
405        // For coroutine-closures, we additionally must compute the
406        // `coroutine_captures_by_ref_ty` type, which is used to generate the by-ref
407        // version of the coroutine-closure's output coroutine.
408        if let UpvarArgs::CoroutineClosure(args) = args {
409            let closure_env_region: Region<'_> = Region::new_bound(
410                self.interner(),
411                rustc_type_ir::INNERMOST,
412                BoundRegion { var: BoundVar::ZERO, kind: BoundRegionKind::ClosureEnv },
413            );
414
415            let num_args = args
416                .as_coroutine_closure()
417                .coroutine_closure_sig()
418                .skip_binder()
419                .tupled_inputs_ty
420                .tuple_fields()
421                .len();
422
423            let tupled_upvars_ty_for_borrow = Ty::new_tup_from_iter(
424                self.interner(),
425                analyze_coroutine_closure_captures(
426                    self.closure_min_captures_flattened(closure_expr_id),
427                    self.closure_min_captures_flattened(ExpressionStore::coroutine_for_closure(
428                        closure_expr_id,
429                    ))
430                    // Skip the captures that are just moving the closure's args
431                    // into the coroutine. These are always by move, and we append
432                    // those later in the `CoroutineClosureSignature` helper functions.
433                    .skip(num_args),
434                    |(_, parent_capture), (_, child_capture)| {
435                        // This is subtle. See documentation on function.
436                        let needs_ref = should_reborrow_from_env_of_parent_coroutine_closure(
437                            parent_capture,
438                            child_capture,
439                        );
440
441                        let upvar_ty = child_capture.place.ty();
442                        let capture = child_capture.info.capture_kind;
443                        // Not all upvars are captured by ref, so use
444                        // `apply_capture_kind_on_capture_ty` to ensure that we
445                        // compute the right captured type.
446                        apply_capture_kind_on_capture_ty(
447                            self.interner(),
448                            upvar_ty,
449                            capture,
450                            if needs_ref { closure_env_region } else { self.types.regions.erased },
451                        )
452                    },
453                ),
454            );
455            let coroutine_captures_by_ref_ty = Ty::new_fn_ptr(
456                self.interner(),
457                Binder::bind_with_vars(
458                    self.interner().mk_fn_sig(
459                        [],
460                        tupled_upvars_ty_for_borrow,
461                        false,
462                        Safety::Safe,
463                        ExternAbi::Rust,
464                    ),
465                    self.types.coroutine_captures_by_ref_bound_var_kinds,
466                ),
467            );
468            _ = self.demand_eqtype(
469                closure_expr_id.into(),
470                args.as_coroutine_closure().coroutine_captures_by_ref_ty(),
471                coroutine_captures_by_ref_ty,
472            );
473
474            // Additionally, we can now constrain the coroutine's kind type.
475            //
476            // We only do this if `infer_kind`, because if we have constrained
477            // the kind from closure signature inference, the kind inferred
478            // for the inner coroutine may actually be more restrictive.
479            if infer_kind {
480                let TyKind::Coroutine(_, coroutine_args) = self.result.expr_ty(body).kind() else {
481                    panic!();
482                };
483                _ = self.demand_eqtype(
484                    closure_expr_id.into(),
485                    coroutine_args.as_coroutine().kind_ty(),
486                    Ty::from_coroutine_closure_kind(self.interner(), closure_kind),
487                );
488            }
489        }
490
491        // Now that we've analyzed the closure, we know how each
492        // variable is borrowed, and we know what traits the closure
493        // implements (Fn vs FnMut etc). We now have some updates to do
494        // with that information.
495        //
496        // Note that no closure type C may have an upvar of type C
497        // (though it may reference itself via a trait object). This
498        // results from the desugaring of closures to a struct like
499        // `Foo<..., UV0...UVn>`. If one of those upvars referenced
500        // C, then the type would have infinite size (and the
501        // inference algorithm will reject it).
502
503        // Equate the type variables for the upvars with the actual types.
504        let final_upvar_tys = self.final_upvar_tys(closure_expr_id);
505        debug!(?closure_expr_id, ?args, ?final_upvar_tys);
506
507        // Build a tuple (U0..Un) of the final upvar types U0..Un
508        // and unify the upvar tuple type in the closure with it:
509        let final_tupled_upvars_type = Ty::new_tup(self.interner(), &final_upvar_tys);
510        _ = self.demand_suptype(
511            closure_expr_id.into(),
512            args.tupled_upvars_ty(),
513            final_tupled_upvars_type,
514        );
515
516        let fake_reads = delegate.fake_reads;
517
518        self.result.closures_data.entry(closure_expr_id).or_default().fake_reads =
519            fake_reads.into_boxed_slice();
520
521        // If we are also inferred the closure kind here,
522        // process any deferred resolutions.
523        let deferred_call_resolutions = self.remove_deferred_call_resolutions(closure_expr_id);
524        for deferred_call_resolution in deferred_call_resolutions {
525            deferred_call_resolution.resolve(self);
526        }
527    }
528
529    /// Determines whether the body of the coroutine uses its upvars in a way that
530    /// consumes (i.e. moves) the value, which would force the coroutine to `FnOnce`.
531    /// In a more detailed comment above, we care whether this happens, since if
532    /// this happens, we want to force the coroutine to move all of the upvars it
533    /// would've borrowed from the parent coroutine-closure.
534    ///
535    /// This only really makes sense to be called on the child coroutine of a
536    /// coroutine-closure.
537    fn coroutine_body_consumes_upvars(
538        &mut self,
539        coroutine_def_id: ExprId,
540        body: ExprId,
541        upvars: UpvarsRef<'db>,
542    ) -> bool {
543        let mut delegate = InferBorrowKind {
544            closure_def_id: coroutine_def_id,
545            capture_information: Default::default(),
546            fake_reads: Default::default(),
547        };
548
549        let _ = euv::ExprUseVisitor::new(self, coroutine_def_id, upvars, &mut delegate)
550            .consume_expr(body);
551
552        let (_, kind, _) = self
553            .process_collected_capture_information(CaptureBy::Ref, &delegate.capture_information);
554
555        matches!(kind, ClosureKind::FnOnce)
556    }
557
558    // Returns a list of `Ty`s for each upvar.
559    fn final_upvar_tys(&self, closure_id: ExprId) -> Vec<Ty<'db>> {
560        self.closure_min_captures_flattened(closure_id)
561            .map(|captured_place| {
562                let upvar_ty = captured_place.place.ty();
563                let capture = captured_place.info.capture_kind;
564
565                debug!(?captured_place.place, ?upvar_ty, ?capture, ?captured_place.mutability);
566
567                apply_capture_kind_on_capture_ty(
568                    self.interner(),
569                    upvar_ty,
570                    capture,
571                    self.types.regions.erased,
572                )
573            })
574            .collect()
575    }
576
577    /// Adjusts the closure capture information to ensure that the operations aren't unsafe,
578    /// and that the path can be captured with required capture kind (depending on use in closure,
579    /// move closure etc.)
580    ///
581    /// Returns the set of adjusted information along with the inferred closure kind and span
582    /// associated with the closure kind inference.
583    ///
584    /// Note that we *always* infer a minimal kind, even if
585    /// we don't always *use* that in the final result (i.e., sometimes
586    /// we've taken the closure kind from the expectations instead, and
587    /// for coroutines we don't even implement the closure traits
588    /// really).
589    ///
590    /// If we inferred that the closure needs to be FnMut/FnOnce, last element of the returned tuple
591    /// contains a `Some()` with the `Place` that caused us to do so.
592    fn process_collected_capture_information(
593        &mut self,
594        capture_clause: CaptureBy,
595        capture_information: &InferredCaptureInformation,
596    ) -> (InferredCaptureInformation, ClosureKind, Option<Place>) {
597        let mut closure_kind = ClosureKind::LATTICE_BOTTOM;
598        let mut origin: Option<Place> = None;
599
600        let processed = capture_information
601            .iter()
602            .cloned()
603            .map(|(place, mut capture_info)| {
604                // Apply rules for safety before inferring closure kind
605                let place = restrict_capture_precision(place, &mut capture_info);
606
607                let place = truncate_capture_for_optimization(place, &mut capture_info);
608
609                let updated = match capture_info.capture_kind {
610                    UpvarCapture::ByValue => match closure_kind {
611                        ClosureKind::Fn | ClosureKind::FnMut => {
612                            (ClosureKind::FnOnce, Some(place.clone()))
613                        }
614                        // If closure is already FnOnce, don't update
615                        ClosureKind::FnOnce => (closure_kind, origin.take()),
616                    },
617
618                    UpvarCapture::ByRef(BorrowKind::Mutable | BorrowKind::UniqueImmutable) => {
619                        match closure_kind {
620                            ClosureKind::Fn => (ClosureKind::FnMut, Some(place.clone())),
621                            // Don't update the origin
622                            ClosureKind::FnMut | ClosureKind::FnOnce => {
623                                (closure_kind, origin.take())
624                            }
625                        }
626                    }
627
628                    _ => (closure_kind, origin.take()),
629                };
630
631                closure_kind = updated.0;
632                origin = updated.1;
633
634                let place = match capture_clause {
635                    CaptureBy::Value => adjust_for_move_closure(place, &mut capture_info),
636                    CaptureBy::Ref => adjust_for_non_move_closure(place, &mut capture_info),
637                };
638
639                // This restriction needs to be applied after we have handled adjustments for `move`
640                // closures. We want to make sure any adjustment that might make us move the place into
641                // the closure gets handled.
642                let place = restrict_precision_for_drop_types(self, place, &mut capture_info);
643
644                (place, capture_info)
645            })
646            .collect();
647
648        (processed, closure_kind, origin)
649    }
650
651    /// Analyzes the information collected by `InferBorrowKind` to compute the min number of
652    /// Places (and corresponding capture kind) that we need to keep track of to support all
653    /// the required captured paths.
654    ///
655    ///
656    /// Note: If this function is called multiple times for the same closure, it will update
657    ///       the existing min_capture map that is stored in TypeckResults.
658    ///
659    /// Eg:
660    /// ```
661    /// #[derive(Debug)]
662    /// struct Point { x: i32, y: i32 }
663    ///
664    /// let s = String::from("s");  // hir_id_s
665    /// let mut p = Point { x: 2, y: -2 }; // his_id_p
666    /// let c = || {
667    ///        println!("{s:?}");  // L1
668    ///        p.x += 10;  // L2
669    ///        println!("{}" , p.y); // L3
670    ///        println!("{p:?}"); // L4
671    ///        drop(s);   // L5
672    /// };
673    /// ```
674    /// and let hir_id_L1..5 be the expressions pointing to use of a captured variable on
675    /// the lines L1..5 respectively.
676    ///
677    /// InferBorrowKind results in a structure like this:
678    ///
679    /// ```ignore (illustrative)
680    /// {
681    ///       Place(base: hir_id_s, projections: [], ....) -> {
682    ///                                                            capture_kind_expr: hir_id_L5,
683    ///                                                            path_expr_id: hir_id_L5,
684    ///                                                            capture_kind: ByValue
685    ///                                                       },
686    ///       Place(base: hir_id_p, projections: [Field(0, 0)], ...) -> {
687    ///                                                                     capture_kind_expr: hir_id_L2,
688    ///                                                                     path_expr_id: hir_id_L2,
689    ///                                                                     capture_kind: ByValue
690    ///                                                                 },
691    ///       Place(base: hir_id_p, projections: [Field(1, 0)], ...) -> {
692    ///                                                                     capture_kind_expr: hir_id_L3,
693    ///                                                                     path_expr_id: hir_id_L3,
694    ///                                                                     capture_kind: ByValue
695    ///                                                                 },
696    ///       Place(base: hir_id_p, projections: [], ...) -> {
697    ///                                                          capture_kind_expr: hir_id_L4,
698    ///                                                          path_expr_id: hir_id_L4,
699    ///                                                          capture_kind: ByValue
700    ///                                                      },
701    /// }
702    /// ```
703    ///
704    /// After the min capture analysis, we get:
705    /// ```ignore (illustrative)
706    /// {
707    ///       hir_id_s -> [
708    ///            Place(base: hir_id_s, projections: [], ....) -> {
709    ///                                                                capture_kind_expr: hir_id_L5,
710    ///                                                                path_expr_id: hir_id_L5,
711    ///                                                                capture_kind: ByValue
712    ///                                                            },
713    ///       ],
714    ///       hir_id_p -> [
715    ///            Place(base: hir_id_p, projections: [], ...) -> {
716    ///                                                               capture_kind_expr: hir_id_L2,
717    ///                                                               path_expr_id: hir_id_L4,
718    ///                                                               capture_kind: ByValue
719    ///                                                           },
720    ///       ],
721    /// }
722    /// ```
723    #[instrument(level = "debug", skip(self))]
724    fn compute_min_captures(
725        &mut self,
726        closure_def_id: ExprId,
727        capture_information: InferredCaptureInformation,
728    ) {
729        if capture_information.is_empty() {
730            return;
731        }
732
733        let mut closure_data =
734            self.result.closures_data.remove(&closure_def_id).unwrap_or_default();
735        let root_var_min_capture_list = &mut closure_data.min_captures;
736        let mut dedup_sources_scratch = FxHashMap::default();
737
738        for (mut place, capture_info) in capture_information.into_iter() {
739            let var_hir_id = match place.base {
740                PlaceBase::Upvar { var_id, .. } => var_id,
741                base => panic!("Expected upvar, found={:?}", base),
742            };
743
744            let Some(min_cap_list) = root_var_min_capture_list.get_mut(&var_hir_id) else {
745                let mutability = self.determine_capture_mutability(closure_def_id, &place);
746                let min_cap_list = vec![CapturedPlace { place, info: capture_info, mutability }];
747                root_var_min_capture_list.insert(var_hir_id, min_cap_list);
748                continue;
749            };
750
751            // Go through each entry in the current list of min_captures
752            // - if ancestor is found, update its capture kind to account for current place's
753            // capture information.
754            //
755            // - if descendant is found, remove it from the list, and update the current place's
756            // capture information to account for the descendant's capture kind.
757            //
758            // We can never be in a case where the list contains both an ancestor and a descendant
759            // Also there can only be ancestor but in case of descendants there might be
760            // multiple.
761
762            let mut descendant_found = false;
763            let mut updated_capture_info = capture_info;
764            min_cap_list.retain(|possible_descendant| {
765                match determine_place_ancestry_relation(&place, &possible_descendant.place) {
766                    // current place is ancestor of possible_descendant
767                    PlaceAncestryRelation::Ancestor => {
768                        descendant_found = true;
769
770                        let mut possible_descendant = possible_descendant.clone();
771
772                        // Truncate the descendant (already in min_captures) to be same as the ancestor to handle any
773                        // possible change in capture mode.
774                        truncate_place_to_len_and_update_capture_kind(
775                            &mut possible_descendant.place,
776                            &mut possible_descendant.info,
777                            place.projections.len(),
778                        );
779
780                        let backup_path_sources = determine_capture_sources(
781                            &mut updated_capture_info,
782                            &mut possible_descendant.info,
783                            &mut dedup_sources_scratch,
784                        );
785                        determine_capture_info(
786                            &mut updated_capture_info,
787                            &mut possible_descendant.info,
788                        );
789
790                        // we need to keep the ancestor's `path_expr_id`
791                        updated_capture_info.sources = backup_path_sources;
792                        false
793                    }
794
795                    _ => true,
796                }
797            });
798
799            let mut ancestor_found = false;
800            if !descendant_found {
801                for possible_ancestor in min_cap_list.iter_mut() {
802                    match determine_place_ancestry_relation(&place, &possible_ancestor.place) {
803                        PlaceAncestryRelation::SamePlace => {
804                            ancestor_found = true;
805                            let backup_path_sources = determine_capture_sources(
806                                &mut updated_capture_info,
807                                &mut possible_ancestor.info,
808                                &mut dedup_sources_scratch,
809                            );
810                            determine_capture_info(
811                                &mut possible_ancestor.info,
812                                &mut updated_capture_info,
813                            );
814                            possible_ancestor.info.sources = backup_path_sources;
815
816                            // Only one related place will be in the list.
817                            break;
818                        }
819                        // current place is descendant of possible_ancestor
820                        PlaceAncestryRelation::Descendant => {
821                            ancestor_found = true;
822
823                            // Truncate the descendant (current place) to be same as the ancestor to handle any
824                            // possible change in capture mode.
825                            truncate_place_to_len_and_update_capture_kind(
826                                &mut place,
827                                &mut updated_capture_info,
828                                possible_ancestor.place.projections.len(),
829                            );
830
831                            let backup_path_sources = determine_capture_sources(
832                                &mut updated_capture_info,
833                                &mut possible_ancestor.info,
834                                &mut dedup_sources_scratch,
835                            );
836                            determine_capture_info(
837                                &mut possible_ancestor.info,
838                                &mut updated_capture_info,
839                            );
840
841                            // we need to keep the ancestor's `sources`
842                            possible_ancestor.info.sources = backup_path_sources;
843
844                            // Only one related place will be in the list.
845                            break;
846                        }
847                        _ => {}
848                    }
849                }
850            }
851
852            // Only need to insert when we don't have an ancestor in the existing min capture list
853            if !ancestor_found {
854                let mutability = self.determine_capture_mutability(closure_def_id, &place);
855                let captured_place =
856                    CapturedPlace { place, info: updated_capture_info, mutability };
857                min_cap_list.push(captured_place);
858            }
859        }
860
861        debug!(
862            "For closure={:?}, min_captures before sorting={:?}",
863            closure_def_id, root_var_min_capture_list
864        );
865
866        // Now that we have the minimized list of captures, sort the captures by field id.
867        // This causes the closure to capture the upvars in the same order as the fields are
868        // declared which is also the drop order. Thus, in situations where we capture all the
869        // fields of some type, the observable drop order will remain the same as it previously
870        // was even though we're dropping each capture individually.
871        // See https://github.com/rust-lang/project-rfc-2229/issues/42 and
872        // `tests/ui/closures/2229_closure_analysis/preserve_field_drop_order.rs`.
873        for (_, captures) in &mut *root_var_min_capture_list {
874            captures.sort_by(|capture1, capture2| {
875                fn is_field(p: &&Projection) -> bool {
876                    match p.kind {
877                        ProjectionKind::Field { .. } => true,
878                        ProjectionKind::Deref | ProjectionKind::UnwrapUnsafeBinder => false,
879                        p @ (ProjectionKind::Subslice | ProjectionKind::Index) => {
880                            panic!("ProjectionKind {:?} was unexpected", p)
881                        }
882                    }
883                }
884
885                // Need to sort only by Field projections, so filter away others.
886                // A previous implementation considered other projection types too
887                // but that caused ICE #118144
888                let capture1_field_projections = capture1.place.projections.iter().filter(is_field);
889                let capture2_field_projections = capture2.place.projections.iter().filter(is_field);
890
891                for (p1, p2) in capture1_field_projections.zip(capture2_field_projections) {
892                    // We do not need to look at the `Projection.ty` fields here because at each
893                    // step of the iteration, the projections will either be the same and therefore
894                    // the types must be as well or the current projection will be different and
895                    // we will return the result of comparing the field indexes.
896                    match (p1.kind, p2.kind) {
897                        (
898                            ProjectionKind::Field { field_idx: i1, .. },
899                            ProjectionKind::Field { field_idx: i2, .. },
900                        ) => {
901                            // Compare only if paths are different.
902                            // Otherwise continue to the next iteration
903                            if i1 != i2 {
904                                return i1.cmp(&i2);
905                            }
906                        }
907                        // Given the filter above, this arm should never be hit
908                        (l, r) => panic!("ProjectionKinds {:?} or {:?} were unexpected", l, r),
909                    }
910                }
911
912                std::cmp::Ordering::Equal
913            });
914        }
915
916        debug!(
917            "For closure={:?}, min_captures after sorting={:#?}",
918            closure_def_id, root_var_min_capture_list
919        );
920        self.result.closures_data.insert(closure_def_id, closure_data);
921    }
922
923    fn normalize_capture_place(&mut self, span: Span, place: Place) -> Place {
924        let place = self.infcx().resolve_vars_if_possible(place);
925
926        // In the new solver, types in HIR `Place`s can contain unnormalized aliases,
927        // which can ICE later (e.g. when projecting fields for diagnostics).
928        let cause = ObligationCause::new(span);
929        let at = self.table.at(&cause);
930        match normalize::deeply_normalize_with_skipped_universes_and_ambiguous_coroutine_goals(
931            at,
932            place.clone(),
933            vec![],
934        ) {
935            Ok((normalized, goals)) => {
936                if !goals.is_empty() {
937                    // FIXME: Insert coroutine stalled predicates, this matters for MIR.
938                    // let mut typeck_results = self.typeck_results.borrow_mut();
939                    // typeck_results.coroutine_stalled_predicates.extend(
940                    //     goals
941                    //         .into_iter()
942                    //         // FIXME: throwing away the param-env :(
943                    //         .map(|goal| (goal.predicate, self.misc(span))),
944                    // );
945                }
946                normalized
947            }
948            Err(errors) => {
949                self.table.trait_errors.extend(errors);
950                place
951            }
952        }
953    }
954
955    fn closure_min_captures_flattened(
956        &self,
957        closure_expr_id: ExprId,
958    ) -> impl Iterator<Item = &CapturedPlace> {
959        self.result
960            .closures_data
961            .get(&closure_expr_id)
962            .map(|closure_data| closure_data.min_captures.values().flatten())
963            .into_iter()
964            .flatten()
965    }
966
967    fn init_capture_kind_for_place(
968        &self,
969        place: &Place,
970        capture_clause: CaptureBy,
971    ) -> UpvarCapture {
972        match capture_clause {
973            // In case of a move closure if the data is accessed through a reference we
974            // want to capture by ref to allow precise capture using reborrows.
975            //
976            // If the data will be moved out of this place, then the place will be truncated
977            // at the first Deref in `adjust_for_move_closure` and then moved into the closure.
978            //
979            // For example:
980            //
981            // struct Buffer<'a> {
982            //     x: &'a String,
983            //     y: Vec<u8>,
984            // }
985            //
986            // fn get<'a>(b: Buffer<'a>) -> impl Sized + 'a {
987            //     let c = move || b.x;
988            //     drop(b);
989            //     c
990            // }
991            //
992            // Even though the closure is declared as move, when we are capturing borrowed data (in
993            // this case, *b.x) we prefer to capture by reference.
994            // Otherwise you'd get an error in 2021 immediately because you'd be trying to take
995            // ownership of the (borrowed) String or else you'd take ownership of b, as in 2018 and
996            // before, which is also an error.
997            CaptureBy::Value if !place.deref_tys().any(Ty::is_ref) => UpvarCapture::ByValue,
998            CaptureBy::Value | CaptureBy::Ref => UpvarCapture::ByRef(BorrowKind::Immutable),
999        }
1000    }
1001
1002    fn place_for_root_variable(&mut self, closure_def_id: ExprId, var_hir_id: BindingId) -> Place {
1003        let place = Place {
1004            base_ty: self.result.binding_ty(var_hir_id).store(),
1005            base: PlaceBase::Upvar { closure: closure_def_id, var_id: var_hir_id },
1006            projections: Default::default(),
1007        };
1008
1009        // Normalize eagerly when inserting into `capture_information`, so all downstream
1010        // capture analysis can assume a normalized `Place`.
1011        self.normalize_capture_place(var_hir_id.into(), place)
1012    }
1013
1014    /// A captured place is mutable if
1015    /// 1. Projections don't include a Deref of an immut-borrow, **and**
1016    /// 2. PlaceBase is mut or projections include a Deref of a mut-borrow.
1017    fn determine_capture_mutability(&mut self, closure_expr: ExprId, place: &Place) -> Mutability {
1018        let var_hir_id = match place.base {
1019            PlaceBase::Upvar { var_id, .. } => var_id,
1020            _ => unreachable!(),
1021        };
1022
1023        let mut is_mutbl = if self.store[var_hir_id].mode == BindingAnnotation::Mutable {
1024            Mutability::Mut
1025        } else {
1026            Mutability::Not
1027        };
1028
1029        for pointer_ty in place.deref_tys() {
1030            match self.structurally_resolve_type(closure_expr.into(), pointer_ty).kind() {
1031                // We don't capture derefs of raw ptrs
1032                TyKind::RawPtr(_, _) => unreachable!(),
1033
1034                // Dereferencing a mut-ref allows us to mut the Place if we don't deref
1035                // an immut-ref after on top of this.
1036                TyKind::Ref(.., Mutability::Mut) => is_mutbl = Mutability::Mut,
1037
1038                // The place isn't mutable once we dereference an immutable reference.
1039                TyKind::Ref(.., Mutability::Not) => return Mutability::Not,
1040
1041                // Dereferencing a box doesn't change mutability
1042                TyKind::Adt(def, ..) if def.is_box() => {}
1043
1044                unexpected_ty => panic!("deref of unexpected pointer type {:?}", unexpected_ty),
1045            }
1046        }
1047
1048        is_mutbl
1049    }
1050}
1051
1052/// Determines whether a child capture that is derived from a parent capture
1053/// should be borrowed with the lifetime of the parent coroutine-closure's env.
1054///
1055/// There are two cases when this needs to happen:
1056///
1057/// (1.) Are we borrowing data owned by the parent closure? We can determine if
1058/// that is the case by checking if the parent capture is by move, EXCEPT if we
1059/// apply a deref projection of an immutable reference, reborrows of immutable
1060/// references which aren't restricted to the LUB of the lifetimes of the deref
1061/// chain. This is why `&'short mut &'long T` can be reborrowed as `&'long T`.
1062///
1063/// ```rust
1064/// let x = &1i32; // Let's call this lifetime `'1`.
1065/// let c = async move || {
1066///     println!("{:?}", *x);
1067///     // Even though the inner coroutine borrows by ref, we're only capturing `*x`,
1068///     // not `x`, so the inner closure is allowed to reborrow the data for `'1`.
1069/// };
1070/// ```
1071///
1072/// (2.) If a coroutine is mutably borrowing from a parent capture, then that
1073/// mutable borrow cannot live for longer than either the parent *or* the borrow
1074/// that we have on the original upvar. Therefore we always need to borrow the
1075/// child capture with the lifetime of the parent coroutine-closure's env.
1076///
1077/// ```rust
1078/// let mut x = 1i32;
1079/// let c = async || {
1080///     x = 1;
1081///     // The parent borrows `x` for some `&'1 mut i32`.
1082///     // However, when we call `c()`, we implicitly autoref for the signature of
1083///     // `AsyncFnMut::async_call_mut`. Let's call that lifetime `'call`. Since
1084///     // the maximum that `&'call mut &'1 mut i32` can be reborrowed is `&'call mut i32`,
1085///     // the inner coroutine should capture w/ the lifetime of the coroutine-closure.
1086/// };
1087/// ```
1088///
1089/// If either of these cases apply, then we should capture the borrow with the
1090/// lifetime of the parent coroutine-closure's env. Luckily, if this function is
1091/// not correct, then the program is not unsound, since we still borrowck and validate
1092/// the choices made from this function -- the only side-effect is that the user
1093/// may receive unnecessary borrowck errors.
1094fn should_reborrow_from_env_of_parent_coroutine_closure(
1095    parent_capture: &CapturedPlace,
1096    child_capture: &CapturedPlace,
1097) -> bool {
1098    // (1.)
1099    (!parent_capture.is_by_ref()
1100        // This is just inlined `place.deref_tys()` but truncated to just
1101        // the child projections. Namely, look for a `&T` deref, since we
1102        // can always extend `&'short mut &'long T` to `&'long T`.
1103        && !child_capture
1104            .place
1105            .projections
1106            .iter()
1107            .enumerate()
1108            .skip(parent_capture.place.projections.len())
1109            .any(|(idx, proj)| {
1110                matches!(proj.kind, ProjectionKind::Deref)
1111                    && matches!(
1112                        child_capture.place.ty_before_projection(idx).kind(),
1113                        TyKind::Ref(.., Mutability::Not)
1114                    )
1115            }))
1116        // (2.)
1117        || matches!(child_capture.info.capture_kind, UpvarCapture::ByRef(BorrowKind::Mutable))
1118}
1119
1120/// Truncate the capture so that the place being borrowed is in accordance with RFC 1240,
1121/// which states that it's unsafe to take a reference into a struct marked `repr(packed)`.
1122fn restrict_repr_packed_field_ref_capture(
1123    mut place: Place,
1124    capture_info: &mut CaptureInfo,
1125) -> Place {
1126    let pos = place.projections.iter().enumerate().position(|(i, p)| {
1127        let ty = place.ty_before_projection(i);
1128
1129        // Return true for fields of packed structs.
1130        match p.kind {
1131            ProjectionKind::Field { .. } => match ty.kind() {
1132                TyKind::Adt(def, _) if def.is_packed() => {
1133                    // We stop here regardless of field alignment. Field alignment can change as
1134                    // types change, including the types of private fields in other crates, and that
1135                    // shouldn't affect how we compute our captures.
1136                    true
1137                }
1138
1139                _ => false,
1140            },
1141            _ => false,
1142        }
1143    });
1144
1145    if let Some(pos) = pos {
1146        truncate_place_to_len_and_update_capture_kind(&mut place, capture_info, pos);
1147    }
1148
1149    place
1150}
1151
1152/// Returns a Ty that applies the specified capture kind on the provided capture Ty
1153fn apply_capture_kind_on_capture_ty<'db>(
1154    interner: DbInterner<'db>,
1155    ty: Ty<'db>,
1156    capture_kind: UpvarCapture,
1157    region: Region<'db>,
1158) -> Ty<'db> {
1159    match capture_kind {
1160        UpvarCapture::ByValue | UpvarCapture::ByUse => ty,
1161        UpvarCapture::ByRef(kind) => Ty::new_ref(interner, region, ty, kind.to_mutbl_lossy()),
1162    }
1163}
1164
1165struct InferBorrowKind {
1166    // The def-id of the closure whose kind and upvar accesses are being inferred.
1167    closure_def_id: ExprId,
1168
1169    /// For each Place that is captured by the closure, we track the minimal kind of
1170    /// access we need (ref, ref mut, move, etc) and the expression that resulted in such access.
1171    ///
1172    /// Consider closure where s.str1 is captured via an ImmutableBorrow and
1173    /// s.str2 via a MutableBorrow
1174    ///
1175    /// ```rust,no_run
1176    /// struct SomeStruct { str1: String, str2: String };
1177    ///
1178    /// // Assume that the HirId for the variable definition is `V1`
1179    /// let mut s = SomeStruct { str1: format!("s1"), str2: format!("s2") };
1180    ///
1181    /// let fix_s = |new_s2| {
1182    ///     // Assume that the HirId for the expression `s.str1` is `E1`
1183    ///     println!("Updating SomeStruct with str1={0}", s.str1);
1184    ///     // Assume that the HirId for the expression `*s.str2` is `E2`
1185    ///     s.str2 = new_s2;
1186    /// };
1187    /// ```
1188    ///
1189    /// For closure `fix_s`, (at a high level) the map contains
1190    ///
1191    /// ```ignore (illustrative)
1192    /// Place { V1, [ProjectionKind::Field(Index=0, Variant=0)] } : CaptureKind { E1, ImmutableBorrow }
1193    /// Place { V1, [ProjectionKind::Field(Index=1, Variant=0)] } : CaptureKind { E2, MutableBorrow }
1194    /// ```
1195    capture_information: InferredCaptureInformation,
1196    fake_reads: Vec<(Place, FakeReadCause, SmallVec<[CaptureSourceStack; 2]>)>,
1197}
1198
1199impl<'db> euv::Delegate<'db> for InferBorrowKind {
1200    #[instrument(skip(self), level = "debug")]
1201    fn fake_read(
1202        &mut self,
1203        place_with_id: PlaceWithOrigin,
1204        cause: FakeReadCause,
1205        ctx: &mut InferenceContext<'db>,
1206    ) {
1207        let PlaceBase::Upvar { .. } = place_with_id.place.base else { return };
1208
1209        // We need to restrict Fake Read precision to avoid fake reading unsafe code,
1210        // such as deref of a raw pointer.
1211        let dummy_capture_kind = UpvarCapture::ByRef(BorrowKind::Immutable);
1212        let mut dummy_capture_info =
1213            CaptureInfo { sources: SmallVec::new(), capture_kind: dummy_capture_kind };
1214
1215        let place = ctx.normalize_capture_place(place_with_id.span(), place_with_id.place.clone());
1216
1217        let place = restrict_capture_precision(place, &mut dummy_capture_info);
1218
1219        dummy_capture_info.capture_kind = dummy_capture_kind;
1220        let place = restrict_repr_packed_field_ref_capture(place, &mut dummy_capture_info);
1221        self.fake_reads.push((place, cause, place_with_id.origins));
1222    }
1223
1224    #[instrument(skip(self), level = "debug")]
1225    fn consume(&mut self, place_with_id: PlaceWithOrigin, ctx: &mut InferenceContext<'db>) {
1226        let PlaceBase::Upvar { closure: upvar_closure, .. } = place_with_id.place.base else {
1227            return;
1228        };
1229        assert_eq!(self.closure_def_id, upvar_closure);
1230
1231        let place = ctx.normalize_capture_place(place_with_id.span(), place_with_id.place.clone());
1232
1233        self.capture_information.push((
1234            place,
1235            CaptureInfo { sources: place_with_id.origins, capture_kind: UpvarCapture::ByValue },
1236        ));
1237    }
1238
1239    #[instrument(skip(self), level = "debug")]
1240    fn use_cloned(&mut self, place_with_id: PlaceWithOrigin, ctx: &mut InferenceContext<'db>) {
1241        let PlaceBase::Upvar { closure: upvar_closure, .. } = place_with_id.place.base else {
1242            return;
1243        };
1244        assert_eq!(self.closure_def_id, upvar_closure);
1245
1246        let place = ctx.normalize_capture_place(place_with_id.span(), place_with_id.place.clone());
1247
1248        self.capture_information.push((
1249            place,
1250            CaptureInfo { sources: place_with_id.origins, capture_kind: UpvarCapture::ByUse },
1251        ));
1252    }
1253
1254    #[instrument(skip(self), level = "debug")]
1255    fn borrow(
1256        &mut self,
1257        place_with_id: PlaceWithOrigin,
1258        bk: BorrowKind,
1259        ctx: &mut InferenceContext<'db>,
1260    ) {
1261        let PlaceBase::Upvar { closure: upvar_closure, .. } = place_with_id.place.base else {
1262            return;
1263        };
1264        assert_eq!(self.closure_def_id, upvar_closure);
1265
1266        // The region here will get discarded/ignored
1267        let capture_kind = UpvarCapture::ByRef(bk);
1268        let mut capture_info =
1269            CaptureInfo { sources: place_with_id.origins.iter().cloned().collect(), capture_kind };
1270
1271        let place = ctx.normalize_capture_place(place_with_id.span(), place_with_id.place.clone());
1272
1273        // We only want repr packed restriction to be applied to reading references into a packed
1274        // struct, and not when the data is being moved. Therefore we call this method here instead
1275        // of in `restrict_capture_precision`.
1276        let place = restrict_repr_packed_field_ref_capture(place, &mut capture_info);
1277
1278        // Raw pointers don't inherit mutability
1279        if place.deref_tys().any(Ty::is_raw_ptr) {
1280            capture_info.capture_kind = UpvarCapture::ByRef(BorrowKind::Immutable);
1281        }
1282
1283        self.capture_information.push((place, capture_info));
1284    }
1285
1286    #[instrument(skip(self), level = "debug")]
1287    fn mutate(&mut self, assignee_place: PlaceWithOrigin, ctx: &mut InferenceContext<'db>) {
1288        self.borrow(assignee_place, BorrowKind::Mutable, ctx);
1289    }
1290}
1291
1292/// Rust doesn't permit moving fields out of a type that implements drop
1293#[instrument(skip(fcx), ret, level = "debug")]
1294fn restrict_precision_for_drop_types<'db>(
1295    fcx: &mut InferenceContext<'db>,
1296    mut place: Place,
1297    capture_info: &mut CaptureInfo,
1298) -> Place {
1299    let is_copy_type = fcx.infcx().type_is_copy_modulo_regions(fcx.table.param_env, place.ty());
1300
1301    if let (false, UpvarCapture::ByValue) = (is_copy_type, capture_info.capture_kind) {
1302        for i in 0..place.projections.len() {
1303            match place.ty_before_projection(i).kind() {
1304                TyKind::Adt(def, _) if def.destructor(fcx.interner()).is_some() => {
1305                    truncate_place_to_len_and_update_capture_kind(&mut place, capture_info, i);
1306                    break;
1307                }
1308                _ => {}
1309            }
1310        }
1311    }
1312
1313    place
1314}
1315
1316/// Truncate `place` so that an `unsafe` block isn't required to capture it.
1317/// - No projections are applied to raw pointers, since these require unsafe blocks. We capture
1318///   them completely.
1319/// - No projections are applied on top of Union ADTs, since these require unsafe blocks.
1320fn restrict_precision_for_unsafe(mut place: Place, capture_info: &mut CaptureInfo) -> Place {
1321    if place.base_ty.as_ref().is_raw_ptr() {
1322        truncate_place_to_len_and_update_capture_kind(&mut place, capture_info, 0);
1323    }
1324
1325    if place.base_ty.as_ref().is_union() {
1326        truncate_place_to_len_and_update_capture_kind(&mut place, capture_info, 0);
1327    }
1328
1329    for (i, proj) in place.projections.iter().enumerate() {
1330        if proj.ty.as_ref().is_raw_ptr() {
1331            // Don't apply any projections on top of a raw ptr.
1332            truncate_place_to_len_and_update_capture_kind(&mut place, capture_info, i + 1);
1333            break;
1334        }
1335
1336        if proj.ty.as_ref().is_union() {
1337            // Don't capture precise fields of a union.
1338            truncate_place_to_len_and_update_capture_kind(&mut place, capture_info, i + 1);
1339            break;
1340        }
1341    }
1342
1343    place
1344}
1345
1346/// Truncate projections so that the following rules are obeyed by the captured `place`:
1347/// - No Index projections are captured, since arrays are captured completely.
1348/// - No unsafe block is required to capture `place`.
1349///
1350/// Returns the truncated place and updated capture mode.
1351#[instrument(ret, level = "debug")]
1352fn restrict_capture_precision(place: Place, capture_info: &mut CaptureInfo) -> Place {
1353    let mut place = restrict_precision_for_unsafe(place, capture_info);
1354
1355    if place.projections.is_empty() {
1356        // Nothing to do here
1357        return place;
1358    }
1359
1360    for (i, proj) in place.projections.iter().enumerate() {
1361        match proj.kind {
1362            ProjectionKind::Index | ProjectionKind::Subslice => {
1363                // Arrays are completely captured, so we drop Index and Subslice projections
1364                truncate_place_to_len_and_update_capture_kind(&mut place, capture_info, i);
1365                return place;
1366            }
1367            ProjectionKind::Deref => {}
1368            ProjectionKind::Field { .. } => {}
1369            ProjectionKind::UnwrapUnsafeBinder => {}
1370        }
1371    }
1372
1373    place
1374}
1375
1376/// Truncate deref of any reference.
1377#[instrument(ret, level = "debug")]
1378fn adjust_for_move_closure(mut place: Place, capture_info: &mut CaptureInfo) -> Place {
1379    let first_deref = place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
1380
1381    if let Some(idx) = first_deref {
1382        truncate_place_to_len_and_update_capture_kind(&mut place, capture_info, idx);
1383    }
1384
1385    capture_info.capture_kind = UpvarCapture::ByValue;
1386    place
1387}
1388
1389/// Adjust closure capture just that if taking ownership of data, only move data
1390/// from enclosing stack frame.
1391#[instrument(ret, level = "debug")]
1392fn adjust_for_non_move_closure(mut place: Place, capture_info: &mut CaptureInfo) -> Place {
1393    let contains_deref =
1394        place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
1395
1396    match capture_info.capture_kind {
1397        UpvarCapture::ByValue | UpvarCapture::ByUse => {
1398            if let Some(idx) = contains_deref {
1399                truncate_place_to_len_and_update_capture_kind(&mut place, capture_info, idx);
1400            }
1401        }
1402
1403        UpvarCapture::ByRef(..) => {}
1404    }
1405
1406    place
1407}
1408
1409/// At the end, `capture_info_a` will contain the selected info.
1410fn determine_capture_info(capture_info_a: &mut CaptureInfo, capture_info_b: &mut CaptureInfo) {
1411    // If the capture kind is equivalent then, we don't need to escalate and can compare the
1412    // expressions.
1413    let eq_capture_kind = match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
1414        (UpvarCapture::ByValue, UpvarCapture::ByValue) => true,
1415        (UpvarCapture::ByUse, UpvarCapture::ByUse) => true,
1416        (UpvarCapture::ByRef(ref_a), UpvarCapture::ByRef(ref_b)) => ref_a == ref_b,
1417        (UpvarCapture::ByValue, _) | (UpvarCapture::ByUse, _) | (UpvarCapture::ByRef(_), _) => {
1418            false
1419        }
1420    };
1421
1422    let swap = if eq_capture_kind {
1423        false
1424    } else {
1425        // We select the CaptureKind which ranks higher based the following priority order:
1426        // (ByUse | ByValue) > MutBorrow > UniqueImmBorrow > ImmBorrow
1427        match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
1428            (UpvarCapture::ByUse, UpvarCapture::ByValue)
1429            | (UpvarCapture::ByValue, UpvarCapture::ByUse) => {
1430                panic!("Same capture can't be ByUse and ByValue at the same time")
1431            }
1432            (UpvarCapture::ByValue, UpvarCapture::ByValue)
1433            | (UpvarCapture::ByUse, UpvarCapture::ByUse)
1434            | (UpvarCapture::ByValue | UpvarCapture::ByUse, UpvarCapture::ByRef(_)) => false,
1435            (UpvarCapture::ByRef(_), UpvarCapture::ByValue | UpvarCapture::ByUse) => true,
1436            (UpvarCapture::ByRef(ref_a), UpvarCapture::ByRef(ref_b)) => {
1437                match (ref_a, ref_b) {
1438                    // Take LHS:
1439                    (BorrowKind::UniqueImmutable | BorrowKind::Mutable, BorrowKind::Immutable)
1440                    | (BorrowKind::Mutable, BorrowKind::UniqueImmutable) => false,
1441
1442                    // Take RHS:
1443                    (BorrowKind::Immutable, BorrowKind::UniqueImmutable | BorrowKind::Mutable)
1444                    | (BorrowKind::UniqueImmutable, BorrowKind::Mutable) => true,
1445
1446                    (BorrowKind::Immutable, BorrowKind::Immutable)
1447                    | (BorrowKind::UniqueImmutable, BorrowKind::UniqueImmutable)
1448                    | (BorrowKind::Mutable, BorrowKind::Mutable) => {
1449                        panic!("Expected unequal capture kinds");
1450                    }
1451                }
1452            }
1453        }
1454    };
1455
1456    if swap {
1457        mem::swap(capture_info_a, capture_info_b);
1458    }
1459}
1460
1461fn determine_capture_sources(
1462    capture_info_a: &mut CaptureInfo,
1463    capture_info_b: &mut CaptureInfo,
1464    dedup_sources_scratch: &mut FxHashMap<ExprOrPatIdPacked, CaptureSourceStack>,
1465) -> SmallVec<[CaptureSourceStack; 2]> {
1466    dedup_sources_scratch.clear();
1467    dedup_sources_scratch.extend(
1468        mem::take(&mut capture_info_a.sources).into_iter().map(|it| (it.final_source(), it)),
1469    );
1470    dedup_sources_scratch.extend(
1471        mem::take(&mut capture_info_b.sources).into_iter().map(|it| (it.final_source(), it)),
1472    );
1473
1474    let mut result = mem::take(&mut capture_info_a.sources);
1475    result.clear();
1476    result.extend(dedup_sources_scratch.values().cloned());
1477    result
1478}
1479
1480/// Truncates `place` to have up to `len` projections.
1481/// `curr_mode` is the current required capture kind for the place.
1482/// Returns the truncated `place` and the updated required capture kind.
1483///
1484/// Note: Capture kind changes from `MutBorrow` to `UniqueImmBorrow` if the truncated part of the `place`
1485/// contained `Deref` of `&mut`.
1486fn truncate_place_to_len_and_update_capture_kind(
1487    place: &mut Place,
1488    info: &mut CaptureInfo,
1489    len: usize,
1490) {
1491    let is_mut_ref = |ty: Ty<'_>| matches!(ty.kind(), TyKind::Ref(.., Mutability::Mut));
1492
1493    // If the truncated part of the place contains `Deref` of a `&mut` then convert MutBorrow ->
1494    // UniqueImmBorrow
1495    // Note that if the place contained Deref of a raw pointer it would've not been MutBorrow, so
1496    // we don't need to worry about that case here.
1497    match info.capture_kind {
1498        UpvarCapture::ByRef(BorrowKind::Mutable) => {
1499            for i in len..place.projections.len() {
1500                if place.projections[i].kind == ProjectionKind::Deref
1501                    && is_mut_ref(place.ty_before_projection(i))
1502                {
1503                    info.capture_kind = UpvarCapture::ByRef(BorrowKind::UniqueImmutable);
1504                    break;
1505                }
1506            }
1507        }
1508
1509        UpvarCapture::ByRef(..) => {}
1510        UpvarCapture::ByValue | UpvarCapture::ByUse => {}
1511    }
1512
1513    // Now fix the sources, to point at the smaller place.
1514    for source in &mut info.sources {
1515        // +1 because the first place is the base.
1516        source.truncate(len + 1);
1517    }
1518
1519    place.projections.truncate(len);
1520}
1521
1522/// Determines the Ancestry relationship of Place A relative to Place B
1523///
1524/// `PlaceAncestryRelation::Ancestor` implies Place A is ancestor of Place B
1525/// `PlaceAncestryRelation::Descendant` implies Place A is descendant of Place B
1526/// `PlaceAncestryRelation::Divergent` implies neither of them is the ancestor of the other.
1527fn determine_place_ancestry_relation(place_a: &Place, place_b: &Place) -> PlaceAncestryRelation {
1528    // If Place A and Place B don't start off from the same root variable, they are divergent.
1529    if place_a.base != place_b.base {
1530        return PlaceAncestryRelation::Divergent;
1531    }
1532
1533    // Assume of length of projections_a = n
1534    let projections_a = &place_a.projections;
1535
1536    // Assume of length of projections_b = m
1537    let projections_b = &place_b.projections;
1538
1539    let same_initial_projections =
1540        iter::zip(projections_a, projections_b).all(|(proj_a, proj_b)| proj_a.kind == proj_b.kind);
1541
1542    if same_initial_projections {
1543        use std::cmp::Ordering;
1544
1545        // First min(n, m) projections are the same
1546        // Select Ancestor/Descendant
1547        match projections_b.len().cmp(&projections_a.len()) {
1548            Ordering::Greater => PlaceAncestryRelation::Ancestor,
1549            Ordering::Equal => PlaceAncestryRelation::SamePlace,
1550            Ordering::Less => PlaceAncestryRelation::Descendant,
1551        }
1552    } else {
1553        PlaceAncestryRelation::Divergent
1554    }
1555}
1556
1557/// Reduces the precision of the captured place when the precision doesn't yield any benefit from
1558/// borrow checking perspective, allowing us to save us on the size of the capture.
1559///
1560///
1561/// Fields that are read through a shared reference will always be read via a shared ref or a copy,
1562/// and therefore capturing precise paths yields no benefit. This optimization truncates the
1563/// rightmost deref of the capture if the deref is applied to a shared ref.
1564///
1565/// Reason we only drop the last deref is because of the following edge case:
1566///
1567/// ```
1568/// # struct A { field_of_a: Box<i32> }
1569/// # struct B {}
1570/// # struct C<'a>(&'a i32);
1571/// struct MyStruct<'a> {
1572///    a: &'static A,
1573///    b: B,
1574///    c: C<'a>,
1575/// }
1576///
1577/// fn foo<'a, 'b>(m: &'a MyStruct<'b>) -> impl FnMut() + 'static {
1578///     || drop(&*m.a.field_of_a)
1579///     // Here we really do want to capture `*m.a` because that outlives `'static`
1580///
1581///     // If we capture `m`, then the closure no longer outlives `'static`
1582///     // it is constrained to `'a`
1583/// }
1584/// ```
1585#[instrument(ret, level = "debug")]
1586fn truncate_capture_for_optimization(mut place: Place, info: &mut CaptureInfo) -> Place {
1587    let is_shared_ref = |ty: Ty<'_>| matches!(ty.kind(), TyKind::Ref(.., Mutability::Not));
1588
1589    // Find the rightmost deref (if any). All the projections that come after this
1590    // are fields or other "in-place pointer adjustments"; these refer therefore to
1591    // data owned by whatever pointer is being dereferenced here.
1592    let idx = place.projections.iter().rposition(|proj| ProjectionKind::Deref == proj.kind);
1593
1594    match idx {
1595        // If that pointer is a shared reference, then we don't need those fields.
1596        Some(idx) if is_shared_ref(place.ty_before_projection(idx)) => {
1597            truncate_place_to_len_and_update_capture_kind(&mut place, info, idx + 1)
1598        }
1599        None | Some(_) => {}
1600    }
1601
1602    place
1603}
1604
1605/// Precise capture is enabled if user is using Rust Edition 2021 or higher.
1606/// `span` is the span of the closure.
1607fn enable_precise_capture(edition: Edition) -> bool {
1608    // FIXME: We should use the edition from the closure expr.
1609    edition.at_least_2021()
1610}
1611
1612fn analyze_coroutine_closure_captures<'a, T>(
1613    parent_captures: impl IntoIterator<Item = &'a CapturedPlace>,
1614    child_captures: impl IntoIterator<Item = &'a CapturedPlace>,
1615    mut for_each: impl FnMut((usize, &'a CapturedPlace), (usize, &'a CapturedPlace)) -> T,
1616) -> impl Iterator<Item = T> {
1617    let mut result = SmallVec::<[_; 10]>::new();
1618
1619    let mut child_captures = child_captures.into_iter().enumerate().peekable();
1620
1621    // One parent capture may correspond to several child captures if we end up
1622    // refining the set of captures via edition-2021 precise captures. We want to
1623    // match up any number of child captures with one parent capture, so we keep
1624    // peeking off this `Peekable` until the child doesn't match anymore.
1625    for (parent_field_idx, parent_capture) in parent_captures.into_iter().enumerate() {
1626        // Make sure we use every field at least once, b/c why are we capturing something
1627        // if it's not used in the inner coroutine.
1628        let mut field_used_at_least_once = false;
1629
1630        // A parent matches a child if they share the same prefix of projections.
1631        // The child may have more, if it is capturing sub-fields out of
1632        // something that is captured by-move in the parent closure.
1633        while child_captures.peek().is_some_and(|(_, child_capture)| {
1634            child_prefix_matches_parent_projections(parent_capture, child_capture)
1635        }) {
1636            let (child_field_idx, child_capture) = child_captures.next().unwrap();
1637            // This analysis only makes sense if the parent capture is a
1638            // prefix of the child capture.
1639            assert!(
1640                child_capture.place.projections.len() >= parent_capture.place.projections.len(),
1641                "parent capture ({parent_capture:#?}) expected to be prefix of \
1642                    child capture ({child_capture:#?})"
1643            );
1644
1645            result.push(for_each(
1646                (parent_field_idx, parent_capture),
1647                (child_field_idx, child_capture),
1648            ));
1649
1650            field_used_at_least_once = true;
1651        }
1652
1653        // Make sure the field was used at least once.
1654        assert!(
1655            field_used_at_least_once,
1656            "we captured {parent_capture:#?} but it was not used in the child coroutine?"
1657        );
1658    }
1659    assert_eq!(child_captures.next(), None, "leftover child captures?");
1660
1661    result.into_iter()
1662}
1663
1664fn child_prefix_matches_parent_projections(
1665    parent_capture: &CapturedPlace,
1666    child_capture: &CapturedPlace,
1667) -> bool {
1668    let PlaceBase::Upvar { var_id: parent_base, .. } = parent_capture.place.base else {
1669        panic!("expected capture to be an upvar");
1670    };
1671    let PlaceBase::Upvar { var_id: child_base, .. } = child_capture.place.base else {
1672        panic!("expected capture to be an upvar");
1673    };
1674
1675    parent_base == child_base
1676        && std::iter::zip(&child_capture.place.projections, &parent_capture.place.projections)
1677            .all(|(child, parent)| child.kind == parent.kind)
1678}