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