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