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.get_mut(&closure_expr_id).unwrap().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 = self.result.closures_data.remove(&closure_def_id).unwrap();
734 let root_var_min_capture_list = &mut closure_data.min_captures;
735 let mut dedup_sources_scratch = FxHashMap::default();
736
737 for (mut place, capture_info) in capture_information.into_iter() {
738 let var_hir_id = match place.base {
739 PlaceBase::Upvar { var_id, .. } => var_id,
740 base => panic!("Expected upvar, found={:?}", base),
741 };
742
743 let Some(min_cap_list) = root_var_min_capture_list.get_mut(&var_hir_id) else {
744 let mutability = self.determine_capture_mutability(closure_def_id, &place);
745 let min_cap_list = vec![CapturedPlace { place, info: capture_info, mutability }];
746 root_var_min_capture_list.insert(var_hir_id, min_cap_list);
747 continue;
748 };
749
750 // Go through each entry in the current list of min_captures
751 // - if ancestor is found, update its capture kind to account for current place's
752 // capture information.
753 //
754 // - if descendant is found, remove it from the list, and update the current place's
755 // capture information to account for the descendant's capture kind.
756 //
757 // We can never be in a case where the list contains both an ancestor and a descendant
758 // Also there can only be ancestor but in case of descendants there might be
759 // multiple.
760
761 let mut descendant_found = false;
762 let mut updated_capture_info = capture_info;
763 min_cap_list.retain(|possible_descendant| {
764 match determine_place_ancestry_relation(&place, &possible_descendant.place) {
765 // current place is ancestor of possible_descendant
766 PlaceAncestryRelation::Ancestor => {
767 descendant_found = true;
768
769 let mut possible_descendant = possible_descendant.clone();
770
771 // Truncate the descendant (already in min_captures) to be same as the ancestor to handle any
772 // possible change in capture mode.
773 truncate_place_to_len_and_update_capture_kind(
774 &mut possible_descendant.place,
775 &mut possible_descendant.info,
776 place.projections.len(),
777 );
778
779 let backup_path_sources = determine_capture_sources(
780 &mut updated_capture_info,
781 &mut possible_descendant.info,
782 &mut dedup_sources_scratch,
783 );
784 determine_capture_info(
785 &mut updated_capture_info,
786 &mut possible_descendant.info,
787 );
788
789 // we need to keep the ancestor's `path_expr_id`
790 updated_capture_info.sources = backup_path_sources;
791 false
792 }
793
794 _ => true,
795 }
796 });
797
798 let mut ancestor_found = false;
799 if !descendant_found {
800 for possible_ancestor in min_cap_list.iter_mut() {
801 match determine_place_ancestry_relation(&place, &possible_ancestor.place) {
802 PlaceAncestryRelation::SamePlace => {
803 ancestor_found = true;
804 let backup_path_sources = determine_capture_sources(
805 &mut updated_capture_info,
806 &mut possible_ancestor.info,
807 &mut dedup_sources_scratch,
808 );
809 determine_capture_info(
810 &mut possible_ancestor.info,
811 &mut updated_capture_info,
812 );
813 possible_ancestor.info.sources = backup_path_sources;
814
815 // Only one related place will be in the list.
816 break;
817 }
818 // current place is descendant of possible_ancestor
819 PlaceAncestryRelation::Descendant => {
820 ancestor_found = true;
821
822 // Truncate the descendant (current place) to be same as the ancestor to handle any
823 // possible change in capture mode.
824 truncate_place_to_len_and_update_capture_kind(
825 &mut place,
826 &mut updated_capture_info,
827 possible_ancestor.place.projections.len(),
828 );
829
830 let backup_path_sources = determine_capture_sources(
831 &mut updated_capture_info,
832 &mut possible_ancestor.info,
833 &mut dedup_sources_scratch,
834 );
835 determine_capture_info(
836 &mut possible_ancestor.info,
837 &mut updated_capture_info,
838 );
839
840 // we need to keep the ancestor's `sources`
841 possible_ancestor.info.sources = backup_path_sources;
842
843 // Only one related place will be in the list.
844 break;
845 }
846 _ => {}
847 }
848 }
849 }
850
851 // Only need to insert when we don't have an ancestor in the existing min capture list
852 if !ancestor_found {
853 let mutability = self.determine_capture_mutability(closure_def_id, &place);
854 let captured_place =
855 CapturedPlace { place, info: updated_capture_info, mutability };
856 min_cap_list.push(captured_place);
857 }
858 }
859
860 debug!(
861 "For closure={:?}, min_captures before sorting={:?}",
862 closure_def_id, root_var_min_capture_list
863 );
864
865 // Now that we have the minimized list of captures, sort the captures by field id.
866 // This causes the closure to capture the upvars in the same order as the fields are
867 // declared which is also the drop order. Thus, in situations where we capture all the
868 // fields of some type, the observable drop order will remain the same as it previously
869 // was even though we're dropping each capture individually.
870 // See https://github.com/rust-lang/project-rfc-2229/issues/42 and
871 // `tests/ui/closures/2229_closure_analysis/preserve_field_drop_order.rs`.
872 for (_, captures) in &mut *root_var_min_capture_list {
873 captures.sort_by(|capture1, capture2| {
874 fn is_field(p: &&Projection) -> bool {
875 match p.kind {
876 ProjectionKind::Field { .. } => true,
877 ProjectionKind::Deref | ProjectionKind::UnwrapUnsafeBinder => false,
878 p @ (ProjectionKind::Subslice | ProjectionKind::Index) => {
879 panic!("ProjectionKind {:?} was unexpected", p)
880 }
881 }
882 }
883
884 // Need to sort only by Field projections, so filter away others.
885 // A previous implementation considered other projection types too
886 // but that caused ICE #118144
887 let capture1_field_projections = capture1.place.projections.iter().filter(is_field);
888 let capture2_field_projections = capture2.place.projections.iter().filter(is_field);
889
890 for (p1, p2) in capture1_field_projections.zip(capture2_field_projections) {
891 // We do not need to look at the `Projection.ty` fields here because at each
892 // step of the iteration, the projections will either be the same and therefore
893 // the types must be as well or the current projection will be different and
894 // we will return the result of comparing the field indexes.
895 match (p1.kind, p2.kind) {
896 (
897 ProjectionKind::Field { field_idx: i1, .. },
898 ProjectionKind::Field { field_idx: i2, .. },
899 ) => {
900 // Compare only if paths are different.
901 // Otherwise continue to the next iteration
902 if i1 != i2 {
903 return i1.cmp(&i2);
904 }
905 }
906 // Given the filter above, this arm should never be hit
907 (l, r) => panic!("ProjectionKinds {:?} or {:?} were unexpected", l, r),
908 }
909 }
910
911 std::cmp::Ordering::Equal
912 });
913 }
914
915 debug!(
916 "For closure={:?}, min_captures after sorting={:#?}",
917 closure_def_id, root_var_min_capture_list
918 );
919 self.result.closures_data.insert(closure_def_id, closure_data);
920 }
921
922 fn normalize_capture_place(&mut self, span: Span, place: Place) -> Place {
923 let place = self.infcx().resolve_vars_if_possible(place);
924
925 // In the new solver, types in HIR `Place`s can contain unnormalized aliases,
926 // which can ICE later (e.g. when projecting fields for diagnostics).
927 let cause = ObligationCause::new(span);
928 let at = self.table.at(&cause);
929 match normalize::deeply_normalize_with_skipped_universes_and_ambiguous_coroutine_goals(
930 at,
931 place.clone(),
932 vec![],
933 ) {
934 Ok((normalized, goals)) => {
935 if !goals.is_empty() {
936 // FIXME: Insert coroutine stalled predicates, this matters for MIR.
937 // let mut typeck_results = self.typeck_results.borrow_mut();
938 // typeck_results.coroutine_stalled_predicates.extend(
939 // goals
940 // .into_iter()
941 // // FIXME: throwing away the param-env :(
942 // .map(|goal| (goal.predicate, self.misc(span))),
943 // );
944 }
945 normalized
946 }
947 Err(errors) => {
948 self.table.trait_errors.extend(errors);
949 place
950 }
951 }
952 }
953
954 fn closure_min_captures_flattened(
955 &self,
956 closure_expr_id: ExprId,
957 ) -> impl Iterator<Item = &CapturedPlace> {
958 self.result
959 .closures_data
960 .get(&closure_expr_id)
961 .map(|closure_data| closure_data.min_captures.values().flatten())
962 .into_iter()
963 .flatten()
964 }
965
966 fn init_capture_kind_for_place(
967 &self,
968 place: &Place,
969 capture_clause: CaptureBy,
970 ) -> UpvarCapture {
971 match capture_clause {
972 // In case of a move closure if the data is accessed through a reference we
973 // want to capture by ref to allow precise capture using reborrows.
974 //
975 // If the data will be moved out of this place, then the place will be truncated
976 // at the first Deref in `adjust_for_move_closure` and then moved into the closure.
977 //
978 // For example:
979 //
980 // struct Buffer<'a> {
981 // x: &'a String,
982 // y: Vec<u8>,
983 // }
984 //
985 // fn get<'a>(b: Buffer<'a>) -> impl Sized + 'a {
986 // let c = move || b.x;
987 // drop(b);
988 // c
989 // }
990 //
991 // Even though the closure is declared as move, when we are capturing borrowed data (in
992 // this case, *b.x) we prefer to capture by reference.
993 // Otherwise you'd get an error in 2021 immediately because you'd be trying to take
994 // ownership of the (borrowed) String or else you'd take ownership of b, as in 2018 and
995 // before, which is also an error.
996 CaptureBy::Value if !place.deref_tys().any(Ty::is_ref) => UpvarCapture::ByValue,
997 CaptureBy::Value | CaptureBy::Ref => UpvarCapture::ByRef(BorrowKind::Immutable),
998 }
999 }
1000
1001 fn place_for_root_variable(&mut self, closure_def_id: ExprId, var_hir_id: BindingId) -> Place {
1002 let place = Place {
1003 base_ty: self.result.binding_ty(var_hir_id).store(),
1004 base: PlaceBase::Upvar { closure: closure_def_id, var_id: var_hir_id },
1005 projections: Default::default(),
1006 };
1007
1008 // Normalize eagerly when inserting into `capture_information`, so all downstream
1009 // capture analysis can assume a normalized `Place`.
1010 self.normalize_capture_place(var_hir_id.into(), place)
1011 }
1012
1013 /// A captured place is mutable if
1014 /// 1. Projections don't include a Deref of an immut-borrow, **and**
1015 /// 2. PlaceBase is mut or projections include a Deref of a mut-borrow.
1016 fn determine_capture_mutability(&mut self, closure_expr: ExprId, place: &Place) -> Mutability {
1017 let var_hir_id = match place.base {
1018 PlaceBase::Upvar { var_id, .. } => var_id,
1019 _ => unreachable!(),
1020 };
1021
1022 let mut is_mutbl = if self.store[var_hir_id].mode == BindingAnnotation::Mutable {
1023 Mutability::Mut
1024 } else {
1025 Mutability::Not
1026 };
1027
1028 for pointer_ty in place.deref_tys() {
1029 match self.structurally_resolve_type(closure_expr.into(), pointer_ty).kind() {
1030 // We don't capture derefs of raw ptrs
1031 TyKind::RawPtr(_, _) => unreachable!(),
1032
1033 // Dereferencing a mut-ref allows us to mut the Place if we don't deref
1034 // an immut-ref after on top of this.
1035 TyKind::Ref(.., Mutability::Mut) => is_mutbl = Mutability::Mut,
1036
1037 // The place isn't mutable once we dereference an immutable reference.
1038 TyKind::Ref(.., Mutability::Not) => return Mutability::Not,
1039
1040 // Dereferencing a box doesn't change mutability
1041 TyKind::Adt(def, ..) if def.is_box() => {}
1042
1043 unexpected_ty => panic!("deref of unexpected pointer type {:?}", unexpected_ty),
1044 }
1045 }
1046
1047 is_mutbl
1048 }
1049}
1050
1051/// Determines whether a child capture that is derived from a parent capture
1052/// should be borrowed with the lifetime of the parent coroutine-closure's env.
1053///
1054/// There are two cases when this needs to happen:
1055///
1056/// (1.) Are we borrowing data owned by the parent closure? We can determine if
1057/// that is the case by checking if the parent capture is by move, EXCEPT if we
1058/// apply a deref projection of an immutable reference, reborrows of immutable
1059/// references which aren't restricted to the LUB of the lifetimes of the deref
1060/// chain. This is why `&'short mut &'long T` can be reborrowed as `&'long T`.
1061///
1062/// ```rust
1063/// let x = &1i32; // Let's call this lifetime `'1`.
1064/// let c = async move || {
1065/// println!("{:?}", *x);
1066/// // Even though the inner coroutine borrows by ref, we're only capturing `*x`,
1067/// // not `x`, so the inner closure is allowed to reborrow the data for `'1`.
1068/// };
1069/// ```
1070///
1071/// (2.) If a coroutine is mutably borrowing from a parent capture, then that
1072/// mutable borrow cannot live for longer than either the parent *or* the borrow
1073/// that we have on the original upvar. Therefore we always need to borrow the
1074/// child capture with the lifetime of the parent coroutine-closure's env.
1075///
1076/// ```rust
1077/// let mut x = 1i32;
1078/// let c = async || {
1079/// x = 1;
1080/// // The parent borrows `x` for some `&'1 mut i32`.
1081/// // However, when we call `c()`, we implicitly autoref for the signature of
1082/// // `AsyncFnMut::async_call_mut`. Let's call that lifetime `'call`. Since
1083/// // the maximum that `&'call mut &'1 mut i32` can be reborrowed is `&'call mut i32`,
1084/// // the inner coroutine should capture w/ the lifetime of the coroutine-closure.
1085/// };
1086/// ```
1087///
1088/// If either of these cases apply, then we should capture the borrow with the
1089/// lifetime of the parent coroutine-closure's env. Luckily, if this function is
1090/// not correct, then the program is not unsound, since we still borrowck and validate
1091/// the choices made from this function -- the only side-effect is that the user
1092/// may receive unnecessary borrowck errors.
1093fn should_reborrow_from_env_of_parent_coroutine_closure(
1094 parent_capture: &CapturedPlace,
1095 child_capture: &CapturedPlace,
1096) -> bool {
1097 // (1.)
1098 (!parent_capture.is_by_ref()
1099 // This is just inlined `place.deref_tys()` but truncated to just
1100 // the child projections. Namely, look for a `&T` deref, since we
1101 // can always extend `&'short mut &'long T` to `&'long T`.
1102 && !child_capture
1103 .place
1104 .projections
1105 .iter()
1106 .enumerate()
1107 .skip(parent_capture.place.projections.len())
1108 .any(|(idx, proj)| {
1109 matches!(proj.kind, ProjectionKind::Deref)
1110 && matches!(
1111 child_capture.place.ty_before_projection(idx).kind(),
1112 TyKind::Ref(.., Mutability::Not)
1113 )
1114 }))
1115 // (2.)
1116 || matches!(child_capture.info.capture_kind, UpvarCapture::ByRef(BorrowKind::Mutable))
1117}
1118
1119/// Truncate the capture so that the place being borrowed is in accordance with RFC 1240,
1120/// which states that it's unsafe to take a reference into a struct marked `repr(packed)`.
1121fn restrict_repr_packed_field_ref_capture(
1122 mut place: Place,
1123 capture_info: &mut CaptureInfo,
1124) -> Place {
1125 let pos = place.projections.iter().enumerate().position(|(i, p)| {
1126 let ty = place.ty_before_projection(i);
1127
1128 // Return true for fields of packed structs.
1129 match p.kind {
1130 ProjectionKind::Field { .. } => match ty.kind() {
1131 TyKind::Adt(def, _) if def.is_packed() => {
1132 // We stop here regardless of field alignment. Field alignment can change as
1133 // types change, including the types of private fields in other crates, and that
1134 // shouldn't affect how we compute our captures.
1135 true
1136 }
1137
1138 _ => false,
1139 },
1140 _ => false,
1141 }
1142 });
1143
1144 if let Some(pos) = pos {
1145 truncate_place_to_len_and_update_capture_kind(&mut place, capture_info, pos);
1146 }
1147
1148 place
1149}
1150
1151/// Returns a Ty that applies the specified capture kind on the provided capture Ty
1152fn apply_capture_kind_on_capture_ty<'db>(
1153 interner: DbInterner<'db>,
1154 ty: Ty<'db>,
1155 capture_kind: UpvarCapture,
1156 region: Region<'db>,
1157) -> Ty<'db> {
1158 match capture_kind {
1159 UpvarCapture::ByValue | UpvarCapture::ByUse => ty,
1160 UpvarCapture::ByRef(kind) => Ty::new_ref(interner, region, ty, kind.to_mutbl_lossy()),
1161 }
1162}
1163
1164struct InferBorrowKind {
1165 // The def-id of the closure whose kind and upvar accesses are being inferred.
1166 closure_def_id: ExprId,
1167
1168 /// For each Place that is captured by the closure, we track the minimal kind of
1169 /// access we need (ref, ref mut, move, etc) and the expression that resulted in such access.
1170 ///
1171 /// Consider closure where s.str1 is captured via an ImmutableBorrow and
1172 /// s.str2 via a MutableBorrow
1173 ///
1174 /// ```rust,no_run
1175 /// struct SomeStruct { str1: String, str2: String };
1176 ///
1177 /// // Assume that the HirId for the variable definition is `V1`
1178 /// let mut s = SomeStruct { str1: format!("s1"), str2: format!("s2") };
1179 ///
1180 /// let fix_s = |new_s2| {
1181 /// // Assume that the HirId for the expression `s.str1` is `E1`
1182 /// println!("Updating SomeStruct with str1={0}", s.str1);
1183 /// // Assume that the HirId for the expression `*s.str2` is `E2`
1184 /// s.str2 = new_s2;
1185 /// };
1186 /// ```
1187 ///
1188 /// For closure `fix_s`, (at a high level) the map contains
1189 ///
1190 /// ```ignore (illustrative)
1191 /// Place { V1, [ProjectionKind::Field(Index=0, Variant=0)] } : CaptureKind { E1, ImmutableBorrow }
1192 /// Place { V1, [ProjectionKind::Field(Index=1, Variant=0)] } : CaptureKind { E2, MutableBorrow }
1193 /// ```
1194 capture_information: InferredCaptureInformation,
1195 fake_reads: Vec<(Place, FakeReadCause, SmallVec<[CaptureSourceStack; 2]>)>,
1196}
1197
1198impl<'db> euv::Delegate<'db> for InferBorrowKind {
1199 #[instrument(skip(self), level = "debug")]
1200 fn fake_read(
1201 &mut self,
1202 place_with_id: PlaceWithOrigin,
1203 cause: FakeReadCause,
1204 ctx: &mut InferenceContext<'db>,
1205 ) {
1206 let PlaceBase::Upvar { .. } = place_with_id.place.base else { return };
1207
1208 // We need to restrict Fake Read precision to avoid fake reading unsafe code,
1209 // such as deref of a raw pointer.
1210 let dummy_capture_kind = UpvarCapture::ByRef(BorrowKind::Immutable);
1211 let mut dummy_capture_info =
1212 CaptureInfo { sources: SmallVec::new(), capture_kind: dummy_capture_kind };
1213
1214 let place = ctx.normalize_capture_place(place_with_id.span(), place_with_id.place.clone());
1215
1216 let place = restrict_capture_precision(place, &mut dummy_capture_info);
1217
1218 dummy_capture_info.capture_kind = dummy_capture_kind;
1219 let place = restrict_repr_packed_field_ref_capture(place, &mut dummy_capture_info);
1220 self.fake_reads.push((place, cause, place_with_id.origins));
1221 }
1222
1223 #[instrument(skip(self), level = "debug")]
1224 fn consume(&mut self, place_with_id: PlaceWithOrigin, ctx: &mut InferenceContext<'db>) {
1225 let PlaceBase::Upvar { closure: upvar_closure, .. } = place_with_id.place.base else {
1226 return;
1227 };
1228 assert_eq!(self.closure_def_id, upvar_closure);
1229
1230 let place = ctx.normalize_capture_place(place_with_id.span(), place_with_id.place.clone());
1231
1232 self.capture_information.push((
1233 place,
1234 CaptureInfo { sources: place_with_id.origins, capture_kind: UpvarCapture::ByValue },
1235 ));
1236 }
1237
1238 #[instrument(skip(self), level = "debug")]
1239 fn use_cloned(&mut self, place_with_id: PlaceWithOrigin, ctx: &mut InferenceContext<'db>) {
1240 let PlaceBase::Upvar { closure: upvar_closure, .. } = place_with_id.place.base else {
1241 return;
1242 };
1243 assert_eq!(self.closure_def_id, upvar_closure);
1244
1245 let place = ctx.normalize_capture_place(place_with_id.span(), place_with_id.place.clone());
1246
1247 self.capture_information.push((
1248 place,
1249 CaptureInfo { sources: place_with_id.origins, capture_kind: UpvarCapture::ByUse },
1250 ));
1251 }
1252
1253 #[instrument(skip(self), level = "debug")]
1254 fn borrow(
1255 &mut self,
1256 place_with_id: PlaceWithOrigin,
1257 bk: BorrowKind,
1258 ctx: &mut InferenceContext<'db>,
1259 ) {
1260 let PlaceBase::Upvar { closure: upvar_closure, .. } = place_with_id.place.base else {
1261 return;
1262 };
1263 assert_eq!(self.closure_def_id, upvar_closure);
1264
1265 // The region here will get discarded/ignored
1266 let capture_kind = UpvarCapture::ByRef(bk);
1267 let mut capture_info =
1268 CaptureInfo { sources: place_with_id.origins.iter().cloned().collect(), capture_kind };
1269
1270 let place = ctx.normalize_capture_place(place_with_id.span(), place_with_id.place.clone());
1271
1272 // We only want repr packed restriction to be applied to reading references into a packed
1273 // struct, and not when the data is being moved. Therefore we call this method here instead
1274 // of in `restrict_capture_precision`.
1275 let place = restrict_repr_packed_field_ref_capture(place, &mut capture_info);
1276
1277 // Raw pointers don't inherit mutability
1278 if place.deref_tys().any(Ty::is_raw_ptr) {
1279 capture_info.capture_kind = UpvarCapture::ByRef(BorrowKind::Immutable);
1280 }
1281
1282 self.capture_information.push((place, capture_info));
1283 }
1284
1285 #[instrument(skip(self), level = "debug")]
1286 fn mutate(&mut self, assignee_place: PlaceWithOrigin, ctx: &mut InferenceContext<'db>) {
1287 self.borrow(assignee_place, BorrowKind::Mutable, ctx);
1288 }
1289}
1290
1291/// Rust doesn't permit moving fields out of a type that implements drop
1292#[instrument(skip(fcx), ret, level = "debug")]
1293fn restrict_precision_for_drop_types<'db>(
1294 fcx: &mut InferenceContext<'db>,
1295 mut place: Place,
1296 capture_info: &mut CaptureInfo,
1297) -> Place {
1298 let is_copy_type = fcx.infcx().type_is_copy_modulo_regions(fcx.table.param_env, place.ty());
1299
1300 if let (false, UpvarCapture::ByValue) = (is_copy_type, capture_info.capture_kind) {
1301 for i in 0..place.projections.len() {
1302 match place.ty_before_projection(i).kind() {
1303 TyKind::Adt(def, _) if def.destructor(fcx.interner()).is_some() => {
1304 truncate_place_to_len_and_update_capture_kind(&mut place, capture_info, i);
1305 break;
1306 }
1307 _ => {}
1308 }
1309 }
1310 }
1311
1312 place
1313}
1314
1315/// Truncate `place` so that an `unsafe` block isn't required to capture it.
1316/// - No projections are applied to raw pointers, since these require unsafe blocks. We capture
1317/// them completely.
1318/// - No projections are applied on top of Union ADTs, since these require unsafe blocks.
1319fn restrict_precision_for_unsafe(mut place: Place, capture_info: &mut CaptureInfo) -> Place {
1320 if place.base_ty.as_ref().is_raw_ptr() {
1321 truncate_place_to_len_and_update_capture_kind(&mut place, capture_info, 0);
1322 }
1323
1324 if place.base_ty.as_ref().is_union() {
1325 truncate_place_to_len_and_update_capture_kind(&mut place, capture_info, 0);
1326 }
1327
1328 for (i, proj) in place.projections.iter().enumerate() {
1329 if proj.ty.as_ref().is_raw_ptr() {
1330 // Don't apply any projections on top of a raw ptr.
1331 truncate_place_to_len_and_update_capture_kind(&mut place, capture_info, i + 1);
1332 break;
1333 }
1334
1335 if proj.ty.as_ref().is_union() {
1336 // Don't capture precise fields of a union.
1337 truncate_place_to_len_and_update_capture_kind(&mut place, capture_info, i + 1);
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")]
1351fn restrict_capture_precision(place: Place, capture_info: &mut CaptureInfo) -> Place {
1352 let mut place = restrict_precision_for_unsafe(place, capture_info);
1353
1354 if place.projections.is_empty() {
1355 // Nothing to do here
1356 return place;
1357 }
1358
1359 for (i, proj) in place.projections.iter().enumerate() {
1360 match proj.kind {
1361 ProjectionKind::Index | ProjectionKind::Subslice => {
1362 // Arrays are completely captured, so we drop Index and Subslice projections
1363 truncate_place_to_len_and_update_capture_kind(&mut place, capture_info, i);
1364 return place;
1365 }
1366 ProjectionKind::Deref => {}
1367 ProjectionKind::Field { .. } => {}
1368 ProjectionKind::UnwrapUnsafeBinder => {}
1369 }
1370 }
1371
1372 place
1373}
1374
1375/// Truncate deref of any reference.
1376#[instrument(ret, level = "debug")]
1377fn adjust_for_move_closure(mut place: Place, capture_info: &mut CaptureInfo) -> Place {
1378 let first_deref = place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
1379
1380 if let Some(idx) = first_deref {
1381 truncate_place_to_len_and_update_capture_kind(&mut place, capture_info, idx);
1382 }
1383
1384 capture_info.capture_kind = UpvarCapture::ByValue;
1385 place
1386}
1387
1388/// Adjust closure capture just that if taking ownership of data, only move data
1389/// from enclosing stack frame.
1390#[instrument(ret, level = "debug")]
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 // If the capture kind is equivalent then, we don't need to escalate and can compare the
1411 // expressions.
1412 let eq_capture_kind = match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
1413 (UpvarCapture::ByValue, UpvarCapture::ByValue) => true,
1414 (UpvarCapture::ByUse, UpvarCapture::ByUse) => true,
1415 (UpvarCapture::ByRef(ref_a), UpvarCapture::ByRef(ref_b)) => ref_a == ref_b,
1416 (UpvarCapture::ByValue, _) | (UpvarCapture::ByUse, _) | (UpvarCapture::ByRef(_), _) => {
1417 false
1418 }
1419 };
1420
1421 let swap = if eq_capture_kind {
1422 false
1423 } else {
1424 // We select the CaptureKind which ranks higher based the following priority order:
1425 // (ByUse | ByValue) > MutBorrow > UniqueImmBorrow > ImmBorrow
1426 match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
1427 (UpvarCapture::ByUse, UpvarCapture::ByValue)
1428 | (UpvarCapture::ByValue, UpvarCapture::ByUse) => {
1429 panic!("Same capture can't be ByUse and ByValue at the same time")
1430 }
1431 (UpvarCapture::ByValue, UpvarCapture::ByValue)
1432 | (UpvarCapture::ByUse, UpvarCapture::ByUse)
1433 | (UpvarCapture::ByValue | UpvarCapture::ByUse, UpvarCapture::ByRef(_)) => false,
1434 (UpvarCapture::ByRef(_), UpvarCapture::ByValue | UpvarCapture::ByUse) => true,
1435 (UpvarCapture::ByRef(ref_a), UpvarCapture::ByRef(ref_b)) => {
1436 match (ref_a, ref_b) {
1437 // Take LHS:
1438 (BorrowKind::UniqueImmutable | BorrowKind::Mutable, BorrowKind::Immutable)
1439 | (BorrowKind::Mutable, BorrowKind::UniqueImmutable) => false,
1440
1441 // Take RHS:
1442 (BorrowKind::Immutable, BorrowKind::UniqueImmutable | BorrowKind::Mutable)
1443 | (BorrowKind::UniqueImmutable, BorrowKind::Mutable) => true,
1444
1445 (BorrowKind::Immutable, BorrowKind::Immutable)
1446 | (BorrowKind::UniqueImmutable, BorrowKind::UniqueImmutable)
1447 | (BorrowKind::Mutable, BorrowKind::Mutable) => {
1448 panic!("Expected unequal capture kinds");
1449 }
1450 }
1451 }
1452 }
1453 };
1454
1455 if swap {
1456 mem::swap(capture_info_a, capture_info_b);
1457 }
1458}
1459
1460fn determine_capture_sources(
1461 capture_info_a: &mut CaptureInfo,
1462 capture_info_b: &mut CaptureInfo,
1463 dedup_sources_scratch: &mut FxHashMap<ExprOrPatIdPacked, CaptureSourceStack>,
1464) -> SmallVec<[CaptureSourceStack; 2]> {
1465 dedup_sources_scratch.clear();
1466 dedup_sources_scratch.extend(
1467 mem::take(&mut capture_info_a.sources).into_iter().map(|it| (it.final_source(), it)),
1468 );
1469 dedup_sources_scratch.extend(
1470 mem::take(&mut capture_info_b.sources).into_iter().map(|it| (it.final_source(), it)),
1471 );
1472
1473 let mut result = mem::take(&mut capture_info_a.sources);
1474 result.clear();
1475 result.extend(dedup_sources_scratch.values().cloned());
1476 result
1477}
1478
1479/// Truncates `place` to have up to `len` projections.
1480/// `curr_mode` is the current required capture kind for the place.
1481/// Returns the truncated `place` and the updated required capture kind.
1482///
1483/// Note: Capture kind changes from `MutBorrow` to `UniqueImmBorrow` if the truncated part of the `place`
1484/// contained `Deref` of `&mut`.
1485fn truncate_place_to_len_and_update_capture_kind(
1486 place: &mut Place,
1487 info: &mut CaptureInfo,
1488 len: usize,
1489) {
1490 let is_mut_ref = |ty: Ty<'_>| matches!(ty.kind(), TyKind::Ref(.., Mutability::Mut));
1491
1492 // If the truncated part of the place contains `Deref` of a `&mut` then convert MutBorrow ->
1493 // UniqueImmBorrow
1494 // Note that if the place contained Deref of a raw pointer it would've not been MutBorrow, so
1495 // we don't need to worry about that case here.
1496 match info.capture_kind {
1497 UpvarCapture::ByRef(BorrowKind::Mutable) => {
1498 for i in len..place.projections.len() {
1499 if place.projections[i].kind == ProjectionKind::Deref
1500 && is_mut_ref(place.ty_before_projection(i))
1501 {
1502 info.capture_kind = UpvarCapture::ByRef(BorrowKind::UniqueImmutable);
1503 break;
1504 }
1505 }
1506 }
1507
1508 UpvarCapture::ByRef(..) => {}
1509 UpvarCapture::ByValue | UpvarCapture::ByUse => {}
1510 }
1511
1512 // Now fix the sources, to point at the smaller place.
1513 for source in &mut info.sources {
1514 // +1 because the first place is the base.
1515 source.truncate(len + 1);
1516 }
1517
1518 place.projections.truncate(len);
1519}
1520
1521/// Determines the Ancestry relationship of Place A relative to Place B
1522///
1523/// `PlaceAncestryRelation::Ancestor` implies Place A is ancestor of Place B
1524/// `PlaceAncestryRelation::Descendant` implies Place A is descendant of Place B
1525/// `PlaceAncestryRelation::Divergent` implies neither of them is the ancestor of the other.
1526fn determine_place_ancestry_relation(place_a: &Place, place_b: &Place) -> PlaceAncestryRelation {
1527 // If Place A and Place B don't start off from the same root variable, they are divergent.
1528 if place_a.base != place_b.base {
1529 return PlaceAncestryRelation::Divergent;
1530 }
1531
1532 // Assume of length of projections_a = n
1533 let projections_a = &place_a.projections;
1534
1535 // Assume of length of projections_b = m
1536 let projections_b = &place_b.projections;
1537
1538 let same_initial_projections =
1539 iter::zip(projections_a, projections_b).all(|(proj_a, proj_b)| proj_a.kind == proj_b.kind);
1540
1541 if same_initial_projections {
1542 use std::cmp::Ordering;
1543
1544 // First min(n, m) projections are the same
1545 // Select Ancestor/Descendant
1546 match projections_b.len().cmp(&projections_a.len()) {
1547 Ordering::Greater => PlaceAncestryRelation::Ancestor,
1548 Ordering::Equal => PlaceAncestryRelation::SamePlace,
1549 Ordering::Less => PlaceAncestryRelation::Descendant,
1550 }
1551 } else {
1552 PlaceAncestryRelation::Divergent
1553 }
1554}
1555
1556/// Reduces the precision of the captured place when the precision doesn't yield any benefit from
1557/// borrow checking perspective, allowing us to save us on the size of the capture.
1558///
1559///
1560/// Fields that are read through a shared reference will always be read via a shared ref or a copy,
1561/// and therefore capturing precise paths yields no benefit. This optimization truncates the
1562/// rightmost deref of the capture if the deref is applied to a shared ref.
1563///
1564/// Reason we only drop the last deref is because of the following edge case:
1565///
1566/// ```
1567/// # struct A { field_of_a: Box<i32> }
1568/// # struct B {}
1569/// # struct C<'a>(&'a i32);
1570/// struct MyStruct<'a> {
1571/// a: &'static A,
1572/// b: B,
1573/// c: C<'a>,
1574/// }
1575///
1576/// fn foo<'a, 'b>(m: &'a MyStruct<'b>) -> impl FnMut() + 'static {
1577/// || drop(&*m.a.field_of_a)
1578/// // Here we really do want to capture `*m.a` because that outlives `'static`
1579///
1580/// // If we capture `m`, then the closure no longer outlives `'static`
1581/// // it is constrained to `'a`
1582/// }
1583/// ```
1584#[instrument(ret, level = "debug")]
1585fn truncate_capture_for_optimization(mut place: Place, info: &mut CaptureInfo) -> Place {
1586 let is_shared_ref = |ty: Ty<'_>| matches!(ty.kind(), TyKind::Ref(.., Mutability::Not));
1587
1588 // Find the rightmost deref (if any). All the projections that come after this
1589 // are fields or other "in-place pointer adjustments"; these refer therefore to
1590 // data owned by whatever pointer is being dereferenced here.
1591 let idx = place.projections.iter().rposition(|proj| ProjectionKind::Deref == proj.kind);
1592
1593 match idx {
1594 // If that pointer is a shared reference, then we don't need those fields.
1595 Some(idx) if is_shared_ref(place.ty_before_projection(idx)) => {
1596 truncate_place_to_len_and_update_capture_kind(&mut place, info, idx + 1)
1597 }
1598 None | Some(_) => {}
1599 }
1600
1601 place
1602}
1603
1604/// Precise capture is enabled if user is using Rust Edition 2021 or higher.
1605/// `span` is the span of the closure.
1606fn enable_precise_capture(edition: Edition) -> bool {
1607 // FIXME: We should use the edition from the closure expr.
1608 edition.at_least_2021()
1609}
1610
1611fn analyze_coroutine_closure_captures<'a, T>(
1612 parent_captures: impl IntoIterator<Item = &'a CapturedPlace>,
1613 child_captures: impl IntoIterator<Item = &'a CapturedPlace>,
1614 mut for_each: impl FnMut((usize, &'a CapturedPlace), (usize, &'a CapturedPlace)) -> T,
1615) -> impl Iterator<Item = T> {
1616 let mut result = SmallVec::<[_; 10]>::new();
1617
1618 let mut child_captures = child_captures.into_iter().enumerate().peekable();
1619
1620 // One parent capture may correspond to several child captures if we end up
1621 // refining the set of captures via edition-2021 precise captures. We want to
1622 // match up any number of child captures with one parent capture, so we keep
1623 // peeking off this `Peekable` until the child doesn't match anymore.
1624 for (parent_field_idx, parent_capture) in parent_captures.into_iter().enumerate() {
1625 // Make sure we use every field at least once, b/c why are we capturing something
1626 // if it's not used in the inner coroutine.
1627 let mut field_used_at_least_once = false;
1628
1629 // A parent matches a child if they share the same prefix of projections.
1630 // The child may have more, if it is capturing sub-fields out of
1631 // something that is captured by-move in the parent closure.
1632 while child_captures.peek().is_some_and(|(_, child_capture)| {
1633 child_prefix_matches_parent_projections(parent_capture, child_capture)
1634 }) {
1635 let (child_field_idx, child_capture) = child_captures.next().unwrap();
1636 // This analysis only makes sense if the parent capture is a
1637 // prefix of the child capture.
1638 assert!(
1639 child_capture.place.projections.len() >= parent_capture.place.projections.len(),
1640 "parent capture ({parent_capture:#?}) expected to be prefix of \
1641 child capture ({child_capture:#?})"
1642 );
1643
1644 result.push(for_each(
1645 (parent_field_idx, parent_capture),
1646 (child_field_idx, child_capture),
1647 ));
1648
1649 field_used_at_least_once = true;
1650 }
1651
1652 // Make sure the field was used at least once.
1653 assert!(
1654 field_used_at_least_once,
1655 "we captured {parent_capture:#?} but it was not used in the child coroutine?"
1656 );
1657 }
1658 assert_eq!(child_captures.next(), None, "leftover child captures?");
1659
1660 result.into_iter()
1661}
1662
1663fn child_prefix_matches_parent_projections(
1664 parent_capture: &CapturedPlace,
1665 child_capture: &CapturedPlace,
1666) -> bool {
1667 let PlaceBase::Upvar { var_id: parent_base, .. } = parent_capture.place.base else {
1668 panic!("expected capture to be an upvar");
1669 };
1670 let PlaceBase::Upvar { var_id: child_base, .. } = child_capture.place.base else {
1671 panic!("expected capture to be an upvar");
1672 };
1673
1674 parent_base == child_base
1675 && std::iter::zip(&child_capture.place.projections, &parent_capture.place.projections)
1676 .all(|(child, parent)| child.kind == parent.kind)
1677}