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