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