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