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