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