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