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