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