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