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