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