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