]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/upvar.rs
Use () for all_traits.
[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::{self, Ty, TyCtxt, TypeckResults, UpvarSubsts};
46 use rustc_session::lint;
47 use rustc_span::sym;
48 use rustc_span::{MultiSpan, Span, Symbol};
49
50 use rustc_index::vec::Idx;
51 use rustc_target::abi::VariantIdx;
52
53 use std::iter;
54
55 /// Describe the relationship between the paths of two places
56 /// eg:
57 /// - `foo` is ancestor of `foo.bar.baz`
58 /// - `foo.bar.baz` is an descendant of `foo.bar`
59 /// - `foo.bar` and `foo.baz` are divergent
60 enum PlaceAncestryRelation {
61     Ancestor,
62     Descendant,
63     Divergent,
64 }
65
66 /// Intermediate format to store a captured `Place` and associated `ty::CaptureInfo`
67 /// during capture analysis. Information in this map feeds into the minimum capture
68 /// analysis pass.
69 type InferredCaptureInformation<'tcx> = FxIndexMap<Place<'tcx>, ty::CaptureInfo<'tcx>>;
70
71 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
72     pub fn closure_analyze(&self, body: &'tcx hir::Body<'tcx>) {
73         InferBorrowKindVisitor { fcx: self }.visit_body(body);
74
75         // it's our job to process these.
76         assert!(self.deferred_call_resolutions.borrow().is_empty());
77     }
78 }
79
80 struct InferBorrowKindVisitor<'a, 'tcx> {
81     fcx: &'a FnCtxt<'a, 'tcx>,
82 }
83
84 impl<'a, 'tcx> Visitor<'tcx> for InferBorrowKindVisitor<'a, 'tcx> {
85     type Map = intravisit::ErasedMap<'tcx>;
86
87     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
88         NestedVisitorMap::None
89     }
90
91     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
92         if let hir::ExprKind::Closure(cc, _, body_id, _, _) = expr.kind {
93             let body = self.fcx.tcx.hir().body(body_id);
94             self.visit_body(body);
95             self.fcx.analyze_closure(expr.hir_id, expr.span, body_id, body, cc);
96         }
97
98         intravisit::walk_expr(self, expr);
99     }
100 }
101
102 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
103     /// Analysis starting point.
104     fn analyze_closure(
105         &self,
106         closure_hir_id: hir::HirId,
107         span: Span,
108         body_id: hir::BodyId,
109         body: &'tcx hir::Body<'tcx>,
110         capture_clause: hir::CaptureBy,
111     ) {
112         debug!("analyze_closure(id={:?}, body.id={:?})", closure_hir_id, body.id());
113
114         // Extract the type of the closure.
115         let ty = self.node_ty(closure_hir_id);
116         let (closure_def_id, substs) = match *ty.kind() {
117             ty::Closure(def_id, substs) => (def_id, UpvarSubsts::Closure(substs)),
118             ty::Generator(def_id, substs, _) => (def_id, UpvarSubsts::Generator(substs)),
119             ty::Error(_) => {
120                 // #51714: skip analysis when we have already encountered type errors
121                 return;
122             }
123             _ => {
124                 span_bug!(
125                     span,
126                     "type of closure expr {:?} is not a closure {:?}",
127                     closure_hir_id,
128                     ty
129                 );
130             }
131         };
132
133         let infer_kind = if let UpvarSubsts::Closure(closure_substs) = substs {
134             self.closure_kind(closure_substs).is_none().then_some(closure_substs)
135         } else {
136             None
137         };
138
139         let local_def_id = closure_def_id.expect_local();
140
141         let body_owner_def_id = self.tcx.hir().body_owner_def_id(body.id());
142         assert_eq!(body_owner_def_id.to_def_id(), closure_def_id);
143         let mut delegate = InferBorrowKind {
144             fcx: self,
145             closure_def_id,
146             closure_span: span,
147             capture_clause,
148             current_closure_kind: ty::ClosureKind::LATTICE_BOTTOM,
149             current_origin: None,
150             capture_information: Default::default(),
151             fake_reads: Default::default(),
152         };
153         euv::ExprUseVisitor::new(
154             &mut delegate,
155             &self.infcx,
156             body_owner_def_id,
157             self.param_env,
158             &self.typeck_results.borrow(),
159         )
160         .consume_body(body);
161
162         debug!(
163             "For closure={:?}, capture_information={:#?}",
164             closure_def_id, delegate.capture_information
165         );
166         self.log_capture_analysis_first_pass(closure_def_id, &delegate.capture_information, span);
167
168         self.compute_min_captures(closure_def_id, delegate.capture_information);
169
170         let closure_hir_id = self.tcx.hir().local_def_id_to_hir_id(local_def_id);
171         if should_do_migration_analysis(self.tcx, closure_hir_id) {
172             self.perform_2229_migration_anaysis(closure_def_id, body_id, capture_clause, span);
173         }
174
175         // We now fake capture information for all variables that are mentioned within the closure
176         // We do this after handling migrations so that min_captures computes before
177         if !self.tcx.features().capture_disjoint_fields {
178             let mut capture_information: InferredCaptureInformation<'tcx> = Default::default();
179
180             if let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) {
181                 for var_hir_id in upvars.keys() {
182                     let place = self.place_for_root_variable(local_def_id, *var_hir_id);
183
184                     debug!("seed place {:?}", place);
185
186                     let upvar_id = ty::UpvarId::new(*var_hir_id, local_def_id);
187                     let capture_kind =
188                         self.init_capture_kind_for_place(&place, capture_clause, upvar_id, span);
189                     let fake_info = ty::CaptureInfo {
190                         capture_kind_expr_id: None,
191                         path_expr_id: None,
192                         capture_kind,
193                     };
194
195                     capture_information.insert(place, fake_info);
196                 }
197             }
198
199             // This will update the min captures based on this new fake information.
200             self.compute_min_captures(closure_def_id, capture_information);
201         }
202
203         if let Some(closure_substs) = infer_kind {
204             // Unify the (as yet unbound) type variable in the closure
205             // substs with the kind we inferred.
206             let inferred_kind = delegate.current_closure_kind;
207             let closure_kind_ty = closure_substs.as_closure().kind_ty();
208             self.demand_eqtype(span, inferred_kind.to_ty(self.tcx), closure_kind_ty);
209
210             // If we have an origin, store it.
211             if let Some(origin) = delegate.current_origin.clone() {
212                 let origin = if self.tcx.features().capture_disjoint_fields {
213                     (origin.0, restrict_capture_precision(origin.1))
214                 } else {
215                     (origin.0, Place { projections: vec![], ..origin.1 })
216                 };
217
218                 self.typeck_results
219                     .borrow_mut()
220                     .closure_kind_origins_mut()
221                     .insert(closure_hir_id, origin);
222             }
223         }
224
225         self.log_closure_min_capture_info(closure_def_id, span);
226
227         // Now that we've analyzed the closure, we know how each
228         // variable is borrowed, and we know what traits the closure
229         // implements (Fn vs FnMut etc). We now have some updates to do
230         // with that information.
231         //
232         // Note that no closure type C may have an upvar of type C
233         // (though it may reference itself via a trait object). This
234         // results from the desugaring of closures to a struct like
235         // `Foo<..., UV0...UVn>`. If one of those upvars referenced
236         // C, then the type would have infinite size (and the
237         // inference algorithm will reject it).
238
239         // Equate the type variables for the upvars with the actual types.
240         let final_upvar_tys = self.final_upvar_tys(closure_def_id);
241         debug!(
242             "analyze_closure: id={:?} substs={:?} final_upvar_tys={:?}",
243             closure_hir_id, substs, final_upvar_tys
244         );
245
246         // Build a tuple (U0..Un) of the final upvar types U0..Un
247         // and unify the upvar tupe type in the closure with it:
248         let final_tupled_upvars_type = self.tcx.mk_tup(final_upvar_tys.iter());
249         self.demand_suptype(span, substs.tupled_upvars_ty(), final_tupled_upvars_type);
250
251         let fake_reads = delegate
252             .fake_reads
253             .into_iter()
254             .map(|(place, cause, hir_id)| (place, cause, hir_id))
255             .collect();
256         self.typeck_results.borrow_mut().closure_fake_reads.insert(closure_def_id, fake_reads);
257
258         // If we are also inferred the closure kind here,
259         // process any deferred resolutions.
260         let deferred_call_resolutions = self.remove_deferred_call_resolutions(closure_def_id);
261         for deferred_call_resolution in deferred_call_resolutions {
262             deferred_call_resolution.resolve(self);
263         }
264     }
265
266     // Returns a list of `Ty`s for each upvar.
267     fn final_upvar_tys(&self, closure_id: DefId) -> Vec<Ty<'tcx>> {
268         // Presently an unboxed closure type cannot "escape" out of a
269         // function, so we will only encounter ones that originated in the
270         // local crate or were inlined into it along with some function.
271         // This may change if abstract return types of some sort are
272         // implemented.
273         self.typeck_results
274             .borrow()
275             .closure_min_captures_flattened(closure_id)
276             .map(|captured_place| {
277                 let upvar_ty = captured_place.place.ty();
278                 let capture = captured_place.info.capture_kind;
279
280                 debug!(
281                     "final_upvar_tys: place={:?} upvar_ty={:?} capture={:?}, mutability={:?}",
282                     captured_place.place, upvar_ty, capture, captured_place.mutability,
283                 );
284
285                 match capture {
286                     ty::UpvarCapture::ByValue(_) => upvar_ty,
287                     ty::UpvarCapture::ByRef(borrow) => self.tcx.mk_ref(
288                         borrow.region,
289                         ty::TypeAndMut { ty: upvar_ty, mutbl: borrow.kind.to_mutbl_lossy() },
290                     ),
291                 }
292             })
293             .collect()
294     }
295
296     /// Analyzes the information collected by `InferBorrowKind` to compute the min number of
297     /// Places (and corresponding capture kind) that we need to keep track of to support all
298     /// the required captured paths.
299     ///
300     ///
301     /// Note: If this function is called multiple times for the same closure, it will update
302     ///       the existing min_capture map that is stored in TypeckResults.
303     ///
304     /// Eg:
305     /// ```rust,no_run
306     /// struct Point { x: i32, y: i32 }
307     ///
308     /// let s: String;  // hir_id_s
309     /// let mut p: Point; // his_id_p
310     /// let c = || {
311     ///        println!("{}", s);  // L1
312     ///        p.x += 10;  // L2
313     ///        println!("{}" , p.y) // L3
314     ///        println!("{}", p) // L4
315     ///        drop(s);   // L5
316     /// };
317     /// ```
318     /// and let hir_id_L1..5 be the expressions pointing to use of a captured variable on
319     /// the lines L1..5 respectively.
320     ///
321     /// InferBorrowKind results in a structure like this:
322     ///
323     /// ```
324     /// {
325     ///       Place(base: hir_id_s, projections: [], ....) -> {
326     ///                                                            capture_kind_expr: hir_id_L5,
327     ///                                                            path_expr_id: hir_id_L5,
328     ///                                                            capture_kind: ByValue
329     ///                                                       },
330     ///       Place(base: hir_id_p, projections: [Field(0, 0)], ...) -> {
331     ///                                                                     capture_kind_expr: hir_id_L2,
332     ///                                                                     path_expr_id: hir_id_L2,
333     ///                                                                     capture_kind: ByValue
334     ///                                                                 },
335     ///       Place(base: hir_id_p, projections: [Field(1, 0)], ...) -> {
336     ///                                                                     capture_kind_expr: hir_id_L3,
337     ///                                                                     path_expr_id: hir_id_L3,
338     ///                                                                     capture_kind: ByValue
339     ///                                                                 },
340     ///       Place(base: hir_id_p, projections: [], ...) -> {
341     ///                                                          capture_kind_expr: hir_id_L4,
342     ///                                                          path_expr_id: hir_id_L4,
343     ///                                                          capture_kind: ByValue
344     ///                                                      },
345     /// ```
346     ///
347     /// After the min capture analysis, we get:
348     /// ```
349     /// {
350     ///       hir_id_s -> [
351     ///            Place(base: hir_id_s, projections: [], ....) -> {
352     ///                                                                capture_kind_expr: hir_id_L5,
353     ///                                                                path_expr_id: hir_id_L5,
354     ///                                                                capture_kind: ByValue
355     ///                                                            },
356     ///       ],
357     ///       hir_id_p -> [
358     ///            Place(base: hir_id_p, projections: [], ...) -> {
359     ///                                                               capture_kind_expr: hir_id_L2,
360     ///                                                               path_expr_id: hir_id_L4,
361     ///                                                               capture_kind: ByValue
362     ///                                                           },
363     ///       ],
364     /// ```
365     fn compute_min_captures(
366         &self,
367         closure_def_id: DefId,
368         capture_information: InferredCaptureInformation<'tcx>,
369     ) {
370         if capture_information.is_empty() {
371             return;
372         }
373
374         let mut typeck_results = self.typeck_results.borrow_mut();
375
376         let mut root_var_min_capture_list =
377             typeck_results.closure_min_captures.remove(&closure_def_id).unwrap_or_default();
378
379         for (place, capture_info) in capture_information.into_iter() {
380             let var_hir_id = match place.base {
381                 PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
382                 base => bug!("Expected upvar, found={:?}", base),
383             };
384
385             let place = restrict_capture_precision(place);
386
387             let min_cap_list = match root_var_min_capture_list.get_mut(&var_hir_id) {
388                 None => {
389                     let mutability = self.determine_capture_mutability(&typeck_results, &place);
390                     let min_cap_list =
391                         vec![ty::CapturedPlace { place, info: capture_info, mutability }];
392                     root_var_min_capture_list.insert(var_hir_id, min_cap_list);
393                     continue;
394                 }
395                 Some(min_cap_list) => min_cap_list,
396             };
397
398             // Go through each entry in the current list of min_captures
399             // - if ancestor is found, update it's capture kind to account for current place's
400             // capture information.
401             //
402             // - if descendant is found, remove it from the list, and update the current place's
403             // capture information to account for the descendants's capture kind.
404             //
405             // We can never be in a case where the list contains both an ancestor and a descendant
406             // Also there can only be ancestor but in case of descendants there might be
407             // multiple.
408
409             let mut descendant_found = false;
410             let mut updated_capture_info = capture_info;
411             min_cap_list.retain(|possible_descendant| {
412                 match determine_place_ancestry_relation(&place, &possible_descendant.place) {
413                     // current place is ancestor of possible_descendant
414                     PlaceAncestryRelation::Ancestor => {
415                         descendant_found = true;
416                         let backup_path_expr_id = updated_capture_info.path_expr_id;
417
418                         updated_capture_info =
419                             determine_capture_info(updated_capture_info, possible_descendant.info);
420
421                         // we need to keep the ancestor's `path_expr_id`
422                         updated_capture_info.path_expr_id = backup_path_expr_id;
423                         false
424                     }
425
426                     _ => true,
427                 }
428             });
429
430             let mut ancestor_found = false;
431             if !descendant_found {
432                 for possible_ancestor in min_cap_list.iter_mut() {
433                     match determine_place_ancestry_relation(&place, &possible_ancestor.place) {
434                         // current place is descendant of possible_ancestor
435                         PlaceAncestryRelation::Descendant => {
436                             ancestor_found = true;
437                             let backup_path_expr_id = possible_ancestor.info.path_expr_id;
438                             possible_ancestor.info =
439                                 determine_capture_info(possible_ancestor.info, capture_info);
440
441                             // we need to keep the ancestor's `path_expr_id`
442                             possible_ancestor.info.path_expr_id = backup_path_expr_id;
443
444                             // Only one ancestor of the current place will be in the list.
445                             break;
446                         }
447                         _ => {}
448                     }
449                 }
450             }
451
452             // Only need to insert when we don't have an ancestor in the existing min capture list
453             if !ancestor_found {
454                 let mutability = self.determine_capture_mutability(&typeck_results, &place);
455                 let captured_place =
456                     ty::CapturedPlace { place, info: updated_capture_info, mutability };
457                 min_cap_list.push(captured_place);
458             }
459         }
460
461         debug!("For closure={:?}, min_captures={:#?}", closure_def_id, root_var_min_capture_list);
462         typeck_results.closure_min_captures.insert(closure_def_id, root_var_min_capture_list);
463     }
464
465     /// Perform the migration analysis for RFC 2229, and emit lint
466     /// `disjoint_capture_drop_reorder` if needed.
467     fn perform_2229_migration_anaysis(
468         &self,
469         closure_def_id: DefId,
470         body_id: hir::BodyId,
471         capture_clause: hir::CaptureBy,
472         span: Span,
473     ) {
474         let need_migrations = self.compute_2229_migrations(
475             closure_def_id,
476             span,
477             capture_clause,
478             self.typeck_results.borrow().closure_min_captures.get(&closure_def_id),
479         );
480
481         if !need_migrations.is_empty() {
482             let (migration_string, migrated_variables_concat) =
483                 migration_suggestion_for_2229(self.tcx, &need_migrations);
484
485             let local_def_id = closure_def_id.expect_local();
486             let closure_hir_id = self.tcx.hir().local_def_id_to_hir_id(local_def_id);
487             self.tcx.struct_span_lint_hir(
488                 lint::builtin::DISJOINT_CAPTURE_DROP_REORDER,
489                 closure_hir_id,
490                 span,
491                 |lint| {
492                     let mut diagnostics_builder = lint.build(
493                         "drop order affected for closure because of `capture_disjoint_fields`",
494                     );
495                     let closure_body_span = self.tcx.hir().span(body_id.hir_id);
496                     let (sugg, app) =
497                         match self.tcx.sess.source_map().span_to_snippet(closure_body_span) {
498                             Ok(s) => {
499                                 let trimmed = s.trim_start();
500
501                                 // If the closure contains a block then replace the opening brace
502                                 // with "{ let _ = (..); "
503                                 let sugg = if let Some('{') = trimmed.chars().next() {
504                                     format!("{{ {}; {}", migration_string, &trimmed[1..])
505                                 } else {
506                                     format!("{{ {}; {} }}", migration_string, s)
507                                 };
508                                 (sugg, Applicability::MachineApplicable)
509                             }
510                             Err(_) => (migration_string.clone(), Applicability::HasPlaceholders),
511                         };
512
513                     let diagnostic_msg = format!(
514                         "add a dummy let to cause {} to be fully captured",
515                         migrated_variables_concat
516                     );
517
518                     diagnostics_builder.span_suggestion(
519                         closure_body_span,
520                         &diagnostic_msg,
521                         sugg,
522                         app,
523                     );
524                     diagnostics_builder.emit();
525                 },
526             );
527         }
528     }
529
530     /// Figures out the list of root variables (and their types) that aren't completely
531     /// captured by the closure when `capture_disjoint_fields` is enabled and drop order of
532     /// some path starting at that root variable **might** be affected.
533     ///
534     /// The output list would include a root variable if:
535     /// - It would have been moved into the closure when `capture_disjoint_fields` wasn't
536     ///   enabled, **and**
537     /// - It wasn't completely captured by the closure, **and**
538     /// - One of the paths starting at this root variable, that is not captured needs Drop.
539     fn compute_2229_migrations(
540         &self,
541         closure_def_id: DefId,
542         closure_span: Span,
543         closure_clause: hir::CaptureBy,
544         min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
545     ) -> Vec<hir::HirId> {
546         let upvars = if let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) {
547             upvars
548         } else {
549             return vec![];
550         };
551
552         let mut need_migrations = Vec::new();
553
554         for (&var_hir_id, _) in upvars.iter() {
555             let ty = self.infcx.resolve_vars_if_possible(self.node_ty(var_hir_id));
556
557             if !ty.needs_drop(self.tcx, self.tcx.param_env(closure_def_id.expect_local())) {
558                 continue;
559             }
560
561             let root_var_min_capture_list = if let Some(root_var_min_capture_list) =
562                 min_captures.and_then(|m| m.get(&var_hir_id))
563             {
564                 root_var_min_capture_list
565             } else {
566                 // The upvar is mentioned within the closure but no path starting from it is
567                 // used.
568
569                 match closure_clause {
570                     // Only migrate if closure is a move closure
571                     hir::CaptureBy::Value => need_migrations.push(var_hir_id),
572
573                     hir::CaptureBy::Ref => {}
574                 }
575
576                 continue;
577             };
578
579             let projections_list = root_var_min_capture_list
580                 .iter()
581                 .filter_map(|captured_place| match captured_place.info.capture_kind {
582                     // Only care about captures that are moved into the closure
583                     ty::UpvarCapture::ByValue(..) => {
584                         Some(captured_place.place.projections.as_slice())
585                     }
586                     ty::UpvarCapture::ByRef(..) => None,
587                 })
588                 .collect::<Vec<_>>();
589
590             let is_moved = !projections_list.is_empty();
591
592             let is_not_completely_captured =
593                 root_var_min_capture_list.iter().any(|capture| capture.place.projections.len() > 0);
594
595             if is_moved
596                 && is_not_completely_captured
597                 && self.has_significant_drop_outside_of_captures(
598                     closure_def_id,
599                     closure_span,
600                     ty,
601                     projections_list,
602                 )
603             {
604                 need_migrations.push(var_hir_id);
605             }
606         }
607
608         need_migrations
609     }
610
611     /// This is a helper function to `compute_2229_migrations_precise_pass`. Provided the type
612     /// of a root variable and a list of captured paths starting at this root variable (expressed
613     /// using list of `Projection` slices), it returns true if there is a path that is not
614     /// captured starting at this root variable that implements Drop.
615     ///
616     /// FIXME(project-rfc-2229#35): This should return true only for significant drops.
617     ///                             A drop is significant if it's implemented by the user or does
618     ///                             anything that will have any observable behavior (other than
619     ///                             freeing up memory).
620     ///
621     /// The way this function works is at a given call it looks at type `base_path_ty` of some base
622     /// path say P and then list of projection slices which represent the different captures moved
623     /// into the closure starting off of P.
624     ///
625     /// This will make more sense with an example:
626     ///
627     /// ```rust
628     /// #![feature(capture_disjoint_fields)]
629     ///
630     /// struct FancyInteger(i32); // This implements Drop
631     ///
632     /// struct Point { x: FancyInteger, y: FancyInteger }
633     /// struct Color;
634     ///
635     /// struct Wrapper { p: Point, c: Color }
636     ///
637     /// fn f(w: Wrapper) {
638     ///   let c = || {
639     ///       // Closure captures w.p.x and w.c by move.
640     ///   };
641     ///
642     ///   c();
643     /// }
644     /// ```
645     ///
646     /// If `capture_disjoint_fields` wasn't enabled the closure would've moved `w` instead of the
647     /// precise paths. If we look closely `w.p.y` isn't captured which implements Drop and
648     /// therefore Drop ordering would change and we want this function to return true.
649     ///
650     /// Call stack to figure out if we need to migrate for `w` would look as follows:
651     ///
652     /// Our initial base path is just `w`, and the paths captured from it are `w[p, x]` and
653     /// `w[c]`.
654     /// Notation:
655     /// - Ty(place): Type of place
656     /// - `(a, b)`: Represents the function parameters `base_path_ty` and `captured_by_move_projs`
657     /// respectively.
658     /// ```
659     ///                  (Ty(w), [ &[p, x], &[c] ])
660     ///                                 |
661     ///                    ----------------------------
662     ///                    |                          |
663     ///                    v                          v
664     ///        (Ty(w.p), [ &[x] ])          (Ty(w.c), [ &[] ]) // I(1)
665     ///                    |                          |
666     ///                    v                          v
667     ///        (Ty(w.p), [ &[x] ])                 false
668     ///                    |
669     ///                    |
670     ///          -------------------------------
671     ///          |                             |
672     ///          v                             v
673     ///     (Ty((w.p).x), [ &[] ])     (Ty((w.p).y), []) // IMP 2
674     ///          |                             |
675     ///          v                             v
676     ///        false                     NeedsDrop(Ty(w.p.y))
677     ///                                        |
678     ///                                        v
679     ///                                      true
680     /// ```
681     ///
682     /// IMP 1 `(Ty(w.c), [ &[] ])`: Notice the single empty slice inside `captured_projs`.
683     ///                             This implies that the `w.c` is completely captured by the closure.
684     ///                             Since drop for this path will be called when the closure is
685     ///                             dropped we don't need to migrate for it.
686     ///
687     /// IMP 2 `(Ty((w.p).y), [])`: Notice that `captured_projs` is empty. This implies that this
688     ///                             path wasn't captured by the closure. Also note that even
689     ///                             though we didn't capture this path, the function visits it,
690     ///                             which is kind of the point of this function. We then return
691     ///                             if the type of `w.p.y` implements Drop, which in this case is
692     ///                             true.
693     ///
694     /// Consider another example:
695     ///
696     /// ```rust
697     /// struct X;
698     /// impl Drop for X {}
699     ///
700     /// struct Y(X);
701     /// impl Drop for Y {}
702     ///
703     /// fn foo() {
704     ///     let y = Y(X);
705     ///     let c = || move(y.0);
706     /// }
707     /// ```
708     ///
709     /// Note that `y.0` is captured by the closure. When this function is called for `y`, it will
710     /// return true, because even though all paths starting at `y` are captured, `y` itself
711     /// implements Drop which will be affected since `y` isn't completely captured.
712     fn has_significant_drop_outside_of_captures(
713         &self,
714         closure_def_id: DefId,
715         closure_span: Span,
716         base_path_ty: Ty<'tcx>,
717         captured_by_move_projs: Vec<&[Projection<'tcx>]>,
718     ) -> bool {
719         let needs_drop = |ty: Ty<'tcx>| {
720             ty.needs_drop(self.tcx, self.tcx.param_env(closure_def_id.expect_local()))
721         };
722
723         let is_drop_defined_for_ty = |ty: Ty<'tcx>| {
724             let drop_trait = self.tcx.require_lang_item(hir::LangItem::Drop, Some(closure_span));
725             let ty_params = self.tcx.mk_substs_trait(base_path_ty, &[]);
726             self.tcx.type_implements_trait((
727                 drop_trait,
728                 ty,
729                 ty_params,
730                 self.tcx.param_env(closure_def_id.expect_local()),
731             ))
732         };
733
734         let is_drop_defined_for_ty = is_drop_defined_for_ty(base_path_ty);
735
736         // If there is a case where no projection is applied on top of current place
737         // then there must be exactly one capture corresponding to such a case. Note that this
738         // represents the case of the path being completely captured by the variable.
739         //
740         // eg. If `a.b` is captured and we are processing `a.b`, then we can't have the closure also
741         //     capture `a.b.c`, because that voilates min capture.
742         let is_completely_captured = captured_by_move_projs.iter().any(|projs| projs.is_empty());
743
744         assert!(!is_completely_captured || (captured_by_move_projs.len() == 1));
745
746         if is_completely_captured {
747             // The place is captured entirely, so doesn't matter if needs dtor, it will be drop
748             // when the closure is dropped.
749             return false;
750         }
751
752         if captured_by_move_projs.is_empty() {
753             return needs_drop(base_path_ty);
754         }
755
756         if is_drop_defined_for_ty {
757             // If drop is implemented for this type then we need it to be fully captured,
758             // and we know it is not completely captured because of the previous checks.
759
760             // Note that this is a bug in the user code that will be reported by the
761             // borrow checker, since we can't move out of drop types.
762
763             // The bug exists in the user's code pre-migration, and we don't migrate here.
764             return false;
765         }
766
767         match base_path_ty.kind() {
768             // Observations:
769             // - `captured_by_move_projs` is not empty. Therefore we can call
770             //   `captured_by_move_projs.first().unwrap()` safely.
771             // - All entries in `captured_by_move_projs` have atleast one projection.
772             //   Therefore we can call `captured_by_move_projs.first().unwrap().first().unwrap()` safely.
773
774             // We don't capture derefs in case of move captures, which would have be applied to
775             // access any further paths.
776             ty::Adt(def, _) if def.is_box() => unreachable!(),
777             ty::Ref(..) => unreachable!(),
778             ty::RawPtr(..) => unreachable!(),
779
780             ty::Adt(def, substs) => {
781                 // Multi-varaint enums are captured in entirety,
782                 // which would've been handled in the case of single empty slice in `captured_by_move_projs`.
783                 assert_eq!(def.variants.len(), 1);
784
785                 // Only Field projections can be applied to a non-box Adt.
786                 assert!(
787                     captured_by_move_projs.iter().all(|projs| matches!(
788                         projs.first().unwrap().kind,
789                         ProjectionKind::Field(..)
790                     ))
791                 );
792                 def.variants.get(VariantIdx::new(0)).unwrap().fields.iter().enumerate().any(
793                     |(i, field)| {
794                         let paths_using_field = captured_by_move_projs
795                             .iter()
796                             .filter_map(|projs| {
797                                 if let ProjectionKind::Field(field_idx, _) =
798                                     projs.first().unwrap().kind
799                                 {
800                                     if (field_idx as usize) == i { Some(&projs[1..]) } else { None }
801                                 } else {
802                                     unreachable!();
803                                 }
804                             })
805                             .collect();
806
807                         let after_field_ty = field.ty(self.tcx, substs);
808                         self.has_significant_drop_outside_of_captures(
809                             closure_def_id,
810                             closure_span,
811                             after_field_ty,
812                             paths_using_field,
813                         )
814                     },
815                 )
816             }
817
818             ty::Tuple(..) => {
819                 // Only Field projections can be applied to a tuple.
820                 assert!(
821                     captured_by_move_projs.iter().all(|projs| matches!(
822                         projs.first().unwrap().kind,
823                         ProjectionKind::Field(..)
824                     ))
825                 );
826
827                 base_path_ty.tuple_fields().enumerate().any(|(i, element_ty)| {
828                     let paths_using_field = captured_by_move_projs
829                         .iter()
830                         .filter_map(|projs| {
831                             if let ProjectionKind::Field(field_idx, _) = projs.first().unwrap().kind
832                             {
833                                 if (field_idx as usize) == i { Some(&projs[1..]) } else { None }
834                             } else {
835                                 unreachable!();
836                             }
837                         })
838                         .collect();
839
840                     self.has_significant_drop_outside_of_captures(
841                         closure_def_id,
842                         closure_span,
843                         element_ty,
844                         paths_using_field,
845                     )
846                 })
847             }
848
849             // Anything else would be completely captured and therefore handled already.
850             _ => unreachable!(),
851         }
852     }
853
854     fn init_capture_kind_for_place(
855         &self,
856         place: &Place<'tcx>,
857         capture_clause: hir::CaptureBy,
858         upvar_id: ty::UpvarId,
859         closure_span: Span,
860     ) -> ty::UpvarCapture<'tcx> {
861         match capture_clause {
862             // In case of a move closure if the data is accessed through a reference we
863             // want to capture by ref to allow precise capture using reborrows.
864             //
865             // If the data will be moved out of this place, then the place will be truncated
866             // at the first Deref in `adjust_upvar_borrow_kind_for_consume` and then moved into
867             // the closure.
868             hir::CaptureBy::Value if !place.deref_tys().any(ty::TyS::is_ref) => {
869                 ty::UpvarCapture::ByValue(None)
870             }
871             hir::CaptureBy::Value | hir::CaptureBy::Ref => {
872                 let origin = UpvarRegion(upvar_id, closure_span);
873                 let upvar_region = self.next_region_var(origin);
874                 let upvar_borrow = ty::UpvarBorrow { kind: ty::ImmBorrow, region: upvar_region };
875                 ty::UpvarCapture::ByRef(upvar_borrow)
876             }
877         }
878     }
879
880     fn place_for_root_variable(
881         &self,
882         closure_def_id: LocalDefId,
883         var_hir_id: hir::HirId,
884     ) -> Place<'tcx> {
885         let upvar_id = ty::UpvarId::new(var_hir_id, closure_def_id);
886
887         Place {
888             base_ty: self.node_ty(var_hir_id),
889             base: PlaceBase::Upvar(upvar_id),
890             projections: Default::default(),
891         }
892     }
893
894     fn should_log_capture_analysis(&self, closure_def_id: DefId) -> bool {
895         self.tcx.has_attr(closure_def_id, sym::rustc_capture_analysis)
896     }
897
898     fn log_capture_analysis_first_pass(
899         &self,
900         closure_def_id: rustc_hir::def_id::DefId,
901         capture_information: &FxIndexMap<Place<'tcx>, ty::CaptureInfo<'tcx>>,
902         closure_span: Span,
903     ) {
904         if self.should_log_capture_analysis(closure_def_id) {
905             let mut diag =
906                 self.tcx.sess.struct_span_err(closure_span, "First Pass analysis includes:");
907             for (place, capture_info) in capture_information {
908                 let capture_str = construct_capture_info_string(self.tcx, place, capture_info);
909                 let output_str = format!("Capturing {}", capture_str);
910
911                 let span =
912                     capture_info.path_expr_id.map_or(closure_span, |e| self.tcx.hir().span(e));
913                 diag.span_note(span, &output_str);
914             }
915             diag.emit();
916         }
917     }
918
919     fn log_closure_min_capture_info(&self, closure_def_id: DefId, closure_span: Span) {
920         if self.should_log_capture_analysis(closure_def_id) {
921             if let Some(min_captures) =
922                 self.typeck_results.borrow().closure_min_captures.get(&closure_def_id)
923             {
924                 let mut diag =
925                     self.tcx.sess.struct_span_err(closure_span, "Min Capture analysis includes:");
926
927                 for (_, min_captures_for_var) in min_captures {
928                     for capture in min_captures_for_var {
929                         let place = &capture.place;
930                         let capture_info = &capture.info;
931
932                         let capture_str =
933                             construct_capture_info_string(self.tcx, place, capture_info);
934                         let output_str = format!("Min Capture {}", capture_str);
935
936                         if capture.info.path_expr_id != capture.info.capture_kind_expr_id {
937                             let path_span = capture_info
938                                 .path_expr_id
939                                 .map_or(closure_span, |e| self.tcx.hir().span(e));
940                             let capture_kind_span = capture_info
941                                 .capture_kind_expr_id
942                                 .map_or(closure_span, |e| self.tcx.hir().span(e));
943
944                             let mut multi_span: MultiSpan =
945                                 MultiSpan::from_spans(vec![path_span, capture_kind_span]);
946
947                             let capture_kind_label =
948                                 construct_capture_kind_reason_string(self.tcx, place, capture_info);
949                             let path_label = construct_path_string(self.tcx, place);
950
951                             multi_span.push_span_label(path_span, path_label);
952                             multi_span.push_span_label(capture_kind_span, capture_kind_label);
953
954                             diag.span_note(multi_span, &output_str);
955                         } else {
956                             let span = capture_info
957                                 .path_expr_id
958                                 .map_or(closure_span, |e| self.tcx.hir().span(e));
959
960                             diag.span_note(span, &output_str);
961                         };
962                     }
963                 }
964                 diag.emit();
965             }
966         }
967     }
968
969     /// A captured place is mutable if
970     /// 1. Projections don't include a Deref of an immut-borrow, **and**
971     /// 2. PlaceBase is mut or projections include a Deref of a mut-borrow.
972     fn determine_capture_mutability(
973         &self,
974         typeck_results: &'a TypeckResults<'tcx>,
975         place: &Place<'tcx>,
976     ) -> hir::Mutability {
977         let var_hir_id = match place.base {
978             PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
979             _ => unreachable!(),
980         };
981
982         let bm = *typeck_results.pat_binding_modes().get(var_hir_id).expect("missing binding mode");
983
984         let mut is_mutbl = match bm {
985             ty::BindByValue(mutability) => mutability,
986             ty::BindByReference(_) => hir::Mutability::Not,
987         };
988
989         for pointer_ty in place.deref_tys() {
990             match pointer_ty.kind() {
991                 // We don't capture derefs of raw ptrs
992                 ty::RawPtr(_) => unreachable!(),
993
994                 // Derefencing a mut-ref allows us to mut the Place if we don't deref
995                 // an immut-ref after on top of this.
996                 ty::Ref(.., hir::Mutability::Mut) => is_mutbl = hir::Mutability::Mut,
997
998                 // The place isn't mutable once we dereference a immutable reference.
999                 ty::Ref(.., hir::Mutability::Not) => return hir::Mutability::Not,
1000
1001                 // Dereferencing a box doesn't change mutability
1002                 ty::Adt(def, ..) if def.is_box() => {}
1003
1004                 unexpected_ty => bug!("deref of unexpected pointer type {:?}", unexpected_ty),
1005             }
1006         }
1007
1008         is_mutbl
1009     }
1010 }
1011
1012 /// Truncate the capture so that the place being borrowed is in accordance with RFC 1240,
1013 /// which states that it's unsafe to take a reference into a struct marked `repr(packed)`.
1014 fn restrict_repr_packed_field_ref_capture<'tcx>(
1015     tcx: TyCtxt<'tcx>,
1016     param_env: ty::ParamEnv<'tcx>,
1017     place: &Place<'tcx>,
1018 ) -> Place<'tcx> {
1019     let pos = place.projections.iter().enumerate().position(|(i, p)| {
1020         let ty = place.ty_before_projection(i);
1021
1022         // Return true for fields of packed structs, unless those fields have alignment 1.
1023         match p.kind {
1024             ProjectionKind::Field(..) => match ty.kind() {
1025                 ty::Adt(def, _) if def.repr.packed() => {
1026                     match tcx.layout_raw(param_env.and(p.ty)) {
1027                         Ok(layout) if layout.align.abi.bytes() == 1 => {
1028                             // if the alignment is 1, the type can't be further
1029                             // disaligned.
1030                             debug!(
1031                                 "restrict_repr_packed_field_ref_capture: ({:?}) - align = 1",
1032                                 place
1033                             );
1034                             false
1035                         }
1036                         _ => {
1037                             debug!("restrict_repr_packed_field_ref_capture: ({:?}) - true", place);
1038                             true
1039                         }
1040                     }
1041                 }
1042
1043                 _ => false,
1044             },
1045             _ => false,
1046         }
1047     });
1048
1049     let mut place = place.clone();
1050
1051     if let Some(pos) = pos {
1052         place.projections.truncate(pos);
1053     }
1054
1055     place
1056 }
1057
1058 struct InferBorrowKind<'a, 'tcx> {
1059     fcx: &'a FnCtxt<'a, 'tcx>,
1060
1061     // The def-id of the closure whose kind and upvar accesses are being inferred.
1062     closure_def_id: DefId,
1063
1064     closure_span: Span,
1065
1066     capture_clause: hir::CaptureBy,
1067
1068     // The kind that we have inferred that the current closure
1069     // requires. Note that we *always* infer a minimal kind, even if
1070     // we don't always *use* that in the final result (i.e., sometimes
1071     // we've taken the closure kind from the expectations instead, and
1072     // for generators we don't even implement the closure traits
1073     // really).
1074     current_closure_kind: ty::ClosureKind,
1075
1076     // If we modified `current_closure_kind`, this field contains a `Some()` with the
1077     // variable access that caused us to do so.
1078     current_origin: Option<(Span, Place<'tcx>)>,
1079
1080     /// For each Place that is captured by the closure, we track the minimal kind of
1081     /// access we need (ref, ref mut, move, etc) and the expression that resulted in such access.
1082     ///
1083     /// Consider closure where s.str1 is captured via an ImmutableBorrow and
1084     /// s.str2 via a MutableBorrow
1085     ///
1086     /// ```rust,no_run
1087     /// struct SomeStruct { str1: String, str2: String }
1088     ///
1089     /// // Assume that the HirId for the variable definition is `V1`
1090     /// let mut s = SomeStruct { str1: format!("s1"), str2: format!("s2") }
1091     ///
1092     /// let fix_s = |new_s2| {
1093     ///     // Assume that the HirId for the expression `s.str1` is `E1`
1094     ///     println!("Updating SomeStruct with str1=", s.str1);
1095     ///     // Assume that the HirId for the expression `*s.str2` is `E2`
1096     ///     s.str2 = new_s2;
1097     /// };
1098     /// ```
1099     ///
1100     /// For closure `fix_s`, (at a high level) the map contains
1101     ///
1102     /// ```
1103     /// Place { V1, [ProjectionKind::Field(Index=0, Variant=0)] } : CaptureKind { E1, ImmutableBorrow }
1104     /// Place { V1, [ProjectionKind::Field(Index=1, Variant=0)] } : CaptureKind { E2, MutableBorrow }
1105     /// ```
1106     capture_information: InferredCaptureInformation<'tcx>,
1107     fake_reads: Vec<(Place<'tcx>, FakeReadCause, hir::HirId)>,
1108 }
1109
1110 impl<'a, 'tcx> InferBorrowKind<'a, 'tcx> {
1111     fn adjust_upvar_borrow_kind_for_consume(
1112         &mut self,
1113         place_with_id: &PlaceWithHirId<'tcx>,
1114         diag_expr_id: hir::HirId,
1115         mode: euv::ConsumeMode,
1116     ) {
1117         debug!(
1118             "adjust_upvar_borrow_kind_for_consume(place_with_id={:?}, diag_expr_id={:?}, mode={:?})",
1119             place_with_id, diag_expr_id, mode
1120         );
1121
1122         match (self.capture_clause, mode) {
1123             // In non-move closures, we only care about moves
1124             (hir::CaptureBy::Ref, euv::Copy) => return,
1125
1126             // We want to capture Copy types that read through a ref via a reborrow
1127             (hir::CaptureBy::Value, euv::Copy)
1128                 if place_with_id.place.deref_tys().any(ty::TyS::is_ref) =>
1129             {
1130                 return;
1131             }
1132
1133             (hir::CaptureBy::Ref, euv::Move) | (hir::CaptureBy::Value, euv::Move | euv::Copy) => {}
1134         };
1135
1136         let place = truncate_capture_for_move(place_with_id.place.clone());
1137         let place_with_id = PlaceWithHirId { place: place.clone(), hir_id: place_with_id.hir_id };
1138
1139         if !self.capture_information.contains_key(&place) {
1140             self.init_capture_info_for_place(&place_with_id, diag_expr_id);
1141         }
1142
1143         let tcx = self.fcx.tcx;
1144         let upvar_id = if let PlaceBase::Upvar(upvar_id) = place_with_id.place.base {
1145             upvar_id
1146         } else {
1147             return;
1148         };
1149
1150         debug!("adjust_upvar_borrow_kind_for_consume: upvar={:?}", upvar_id);
1151
1152         let usage_span = tcx.hir().span(diag_expr_id);
1153
1154         if matches!(mode, euv::Move) {
1155             // To move out of an upvar, this must be a FnOnce closure
1156             self.adjust_closure_kind(
1157                 upvar_id.closure_expr_id,
1158                 ty::ClosureKind::FnOnce,
1159                 usage_span,
1160                 place.clone(),
1161             );
1162         }
1163
1164         let capture_info = ty::CaptureInfo {
1165             capture_kind_expr_id: Some(diag_expr_id),
1166             path_expr_id: Some(diag_expr_id),
1167             capture_kind: ty::UpvarCapture::ByValue(Some(usage_span)),
1168         };
1169
1170         let curr_info = self.capture_information[&place_with_id.place];
1171         let updated_info = determine_capture_info(curr_info, capture_info);
1172
1173         self.capture_information[&place_with_id.place] = updated_info;
1174     }
1175
1176     /// Indicates that `place_with_id` is being directly mutated (e.g., assigned
1177     /// to). If the place is based on a by-ref upvar, this implies that
1178     /// the upvar must be borrowed using an `&mut` borrow.
1179     fn adjust_upvar_borrow_kind_for_mut(
1180         &mut self,
1181         place_with_id: &PlaceWithHirId<'tcx>,
1182         diag_expr_id: hir::HirId,
1183     ) {
1184         debug!(
1185             "adjust_upvar_borrow_kind_for_mut(place_with_id={:?}, diag_expr_id={:?})",
1186             place_with_id, diag_expr_id
1187         );
1188
1189         if let PlaceBase::Upvar(_) = place_with_id.place.base {
1190             let mut borrow_kind = ty::MutBorrow;
1191             for pointer_ty in place_with_id.place.deref_tys() {
1192                 match pointer_ty.kind() {
1193                     // Raw pointers don't inherit mutability.
1194                     ty::RawPtr(_) => return,
1195                     // assignment to deref of an `&mut`
1196                     // borrowed pointer implies that the
1197                     // pointer itself must be unique, but not
1198                     // necessarily *mutable*
1199                     ty::Ref(.., hir::Mutability::Mut) => borrow_kind = ty::UniqueImmBorrow,
1200                     _ => (),
1201                 }
1202             }
1203             self.adjust_upvar_deref(place_with_id, diag_expr_id, borrow_kind);
1204         }
1205     }
1206
1207     fn adjust_upvar_borrow_kind_for_unique(
1208         &mut self,
1209         place_with_id: &PlaceWithHirId<'tcx>,
1210         diag_expr_id: hir::HirId,
1211     ) {
1212         debug!(
1213             "adjust_upvar_borrow_kind_for_unique(place_with_id={:?}, diag_expr_id={:?})",
1214             place_with_id, diag_expr_id
1215         );
1216
1217         if let PlaceBase::Upvar(_) = place_with_id.place.base {
1218             if place_with_id.place.deref_tys().any(ty::TyS::is_unsafe_ptr) {
1219                 // Raw pointers don't inherit mutability.
1220                 return;
1221             }
1222             // for a borrowed pointer to be unique, its base must be unique
1223             self.adjust_upvar_deref(place_with_id, diag_expr_id, ty::UniqueImmBorrow);
1224         }
1225     }
1226
1227     fn adjust_upvar_deref(
1228         &mut self,
1229         place_with_id: &PlaceWithHirId<'tcx>,
1230         diag_expr_id: hir::HirId,
1231         borrow_kind: ty::BorrowKind,
1232     ) {
1233         assert!(match borrow_kind {
1234             ty::MutBorrow => true,
1235             ty::UniqueImmBorrow => true,
1236
1237             // imm borrows never require adjusting any kinds, so we don't wind up here
1238             ty::ImmBorrow => false,
1239         });
1240
1241         let tcx = self.fcx.tcx;
1242
1243         // if this is an implicit deref of an
1244         // upvar, then we need to modify the
1245         // borrow_kind of the upvar to make sure it
1246         // is inferred to mutable if necessary
1247         self.adjust_upvar_borrow_kind(place_with_id, diag_expr_id, borrow_kind);
1248
1249         if let PlaceBase::Upvar(upvar_id) = place_with_id.place.base {
1250             self.adjust_closure_kind(
1251                 upvar_id.closure_expr_id,
1252                 ty::ClosureKind::FnMut,
1253                 tcx.hir().span(diag_expr_id),
1254                 place_with_id.place.clone(),
1255             );
1256         }
1257     }
1258
1259     /// We infer the borrow_kind with which to borrow upvars in a stack closure.
1260     /// The borrow_kind basically follows a lattice of `imm < unique-imm < mut`,
1261     /// moving from left to right as needed (but never right to left).
1262     /// Here the argument `mutbl` is the borrow_kind that is required by
1263     /// some particular use.
1264     fn adjust_upvar_borrow_kind(
1265         &mut self,
1266         place_with_id: &PlaceWithHirId<'tcx>,
1267         diag_expr_id: hir::HirId,
1268         kind: ty::BorrowKind,
1269     ) {
1270         let curr_capture_info = self.capture_information[&place_with_id.place];
1271
1272         debug!(
1273             "adjust_upvar_borrow_kind(place={:?}, diag_expr_id={:?}, capture_info={:?}, kind={:?})",
1274             place_with_id, diag_expr_id, curr_capture_info, kind
1275         );
1276
1277         if let ty::UpvarCapture::ByValue(_) = curr_capture_info.capture_kind {
1278             // It's already captured by value, we don't need to do anything here
1279             return;
1280         } else if let ty::UpvarCapture::ByRef(curr_upvar_borrow) = curr_capture_info.capture_kind {
1281             // Use the same region as the current capture information
1282             // Doesn't matter since only one of the UpvarBorrow will be used.
1283             let new_upvar_borrow = ty::UpvarBorrow { kind, region: curr_upvar_borrow.region };
1284
1285             let capture_info = ty::CaptureInfo {
1286                 capture_kind_expr_id: Some(diag_expr_id),
1287                 path_expr_id: Some(diag_expr_id),
1288                 capture_kind: ty::UpvarCapture::ByRef(new_upvar_borrow),
1289             };
1290             let updated_info = determine_capture_info(curr_capture_info, capture_info);
1291             self.capture_information[&place_with_id.place] = updated_info;
1292         };
1293     }
1294
1295     fn adjust_closure_kind(
1296         &mut self,
1297         closure_id: LocalDefId,
1298         new_kind: ty::ClosureKind,
1299         upvar_span: Span,
1300         place: Place<'tcx>,
1301     ) {
1302         debug!(
1303             "adjust_closure_kind(closure_id={:?}, new_kind={:?}, upvar_span={:?}, place={:?})",
1304             closure_id, new_kind, upvar_span, place
1305         );
1306
1307         // Is this the closure whose kind is currently being inferred?
1308         if closure_id.to_def_id() != self.closure_def_id {
1309             debug!("adjust_closure_kind: not current closure");
1310             return;
1311         }
1312
1313         // closures start out as `Fn`.
1314         let existing_kind = self.current_closure_kind;
1315
1316         debug!(
1317             "adjust_closure_kind: closure_id={:?}, existing_kind={:?}, new_kind={:?}",
1318             closure_id, existing_kind, new_kind
1319         );
1320
1321         match (existing_kind, new_kind) {
1322             (ty::ClosureKind::Fn, ty::ClosureKind::Fn)
1323             | (ty::ClosureKind::FnMut, ty::ClosureKind::Fn | ty::ClosureKind::FnMut)
1324             | (ty::ClosureKind::FnOnce, _) => {
1325                 // no change needed
1326             }
1327
1328             (ty::ClosureKind::Fn, ty::ClosureKind::FnMut | ty::ClosureKind::FnOnce)
1329             | (ty::ClosureKind::FnMut, ty::ClosureKind::FnOnce) => {
1330                 // new kind is stronger than the old kind
1331                 self.current_closure_kind = new_kind;
1332                 self.current_origin = Some((upvar_span, place));
1333             }
1334         }
1335     }
1336
1337     fn init_capture_info_for_place(
1338         &mut self,
1339         place_with_id: &PlaceWithHirId<'tcx>,
1340         diag_expr_id: hir::HirId,
1341     ) {
1342         if let PlaceBase::Upvar(upvar_id) = place_with_id.place.base {
1343             assert_eq!(self.closure_def_id.expect_local(), upvar_id.closure_expr_id);
1344
1345             let capture_kind = self.fcx.init_capture_kind_for_place(
1346                 &place_with_id.place,
1347                 self.capture_clause,
1348                 upvar_id,
1349                 self.closure_span,
1350             );
1351
1352             let expr_id = Some(diag_expr_id);
1353             let capture_info = ty::CaptureInfo {
1354                 capture_kind_expr_id: expr_id,
1355                 path_expr_id: expr_id,
1356                 capture_kind,
1357             };
1358
1359             debug!("Capturing new place {:?}, capture_info={:?}", place_with_id, capture_info);
1360
1361             self.capture_information.insert(place_with_id.place.clone(), capture_info);
1362         } else {
1363             debug!("Not upvar: {:?}", place_with_id);
1364         }
1365     }
1366 }
1367
1368 impl<'a, 'tcx> euv::Delegate<'tcx> for InferBorrowKind<'a, 'tcx> {
1369     fn fake_read(&mut self, place: Place<'tcx>, cause: FakeReadCause, diag_expr_id: hir::HirId) {
1370         if let PlaceBase::Upvar(_) = place.base {
1371             self.fake_reads.push((place, cause, diag_expr_id));
1372         }
1373     }
1374
1375     fn consume(
1376         &mut self,
1377         place_with_id: &PlaceWithHirId<'tcx>,
1378         diag_expr_id: hir::HirId,
1379         mode: euv::ConsumeMode,
1380     ) {
1381         debug!(
1382             "consume(place_with_id={:?}, diag_expr_id={:?}, mode={:?})",
1383             place_with_id, diag_expr_id, mode
1384         );
1385         if !self.capture_information.contains_key(&place_with_id.place) {
1386             self.init_capture_info_for_place(place_with_id, diag_expr_id);
1387         }
1388
1389         self.adjust_upvar_borrow_kind_for_consume(place_with_id, diag_expr_id, mode);
1390     }
1391
1392     fn borrow(
1393         &mut self,
1394         place_with_id: &PlaceWithHirId<'tcx>,
1395         diag_expr_id: hir::HirId,
1396         bk: ty::BorrowKind,
1397     ) {
1398         debug!(
1399             "borrow(place_with_id={:?}, diag_expr_id={:?}, bk={:?})",
1400             place_with_id, diag_expr_id, bk
1401         );
1402
1403         let place = restrict_repr_packed_field_ref_capture(
1404             self.fcx.tcx,
1405             self.fcx.param_env,
1406             &place_with_id.place,
1407         );
1408         let place_with_id = PlaceWithHirId { place, ..*place_with_id };
1409
1410         if !self.capture_information.contains_key(&place_with_id.place) {
1411             self.init_capture_info_for_place(&place_with_id, diag_expr_id);
1412         }
1413
1414         match bk {
1415             ty::ImmBorrow => {}
1416             ty::UniqueImmBorrow => {
1417                 self.adjust_upvar_borrow_kind_for_unique(&place_with_id, diag_expr_id);
1418             }
1419             ty::MutBorrow => {
1420                 self.adjust_upvar_borrow_kind_for_mut(&place_with_id, diag_expr_id);
1421             }
1422         }
1423     }
1424
1425     fn mutate(&mut self, assignee_place: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId) {
1426         debug!("mutate(assignee_place={:?}, diag_expr_id={:?})", assignee_place, diag_expr_id);
1427
1428         self.borrow(assignee_place, diag_expr_id, ty::BorrowKind::MutBorrow);
1429     }
1430 }
1431
1432 /// Truncate projections so that following rules are obeyed by the captured `place`:
1433 /// - No projections are applied to raw pointers, since these require unsafe blocks. We capture
1434 ///   them completely.
1435 /// - No Index projections are captured, since arrays are captured completely.
1436 fn restrict_capture_precision<'tcx>(mut place: Place<'tcx>) -> Place<'tcx> {
1437     if place.projections.is_empty() {
1438         // Nothing to do here
1439         return place;
1440     }
1441
1442     if place.base_ty.is_unsafe_ptr() {
1443         place.projections.truncate(0);
1444         return place;
1445     }
1446
1447     let mut truncated_length = usize::MAX;
1448
1449     for (i, proj) in place.projections.iter().enumerate() {
1450         if proj.ty.is_unsafe_ptr() {
1451             // Don't apply any projections on top of an unsafe ptr
1452             truncated_length = truncated_length.min(i + 1);
1453             break;
1454         }
1455         match proj.kind {
1456             ProjectionKind::Index => {
1457                 // Arrays are completely captured, so we drop Index projections
1458                 truncated_length = truncated_length.min(i);
1459                 break;
1460             }
1461             ProjectionKind::Deref => {}
1462             ProjectionKind::Field(..) => {} // ignore
1463             ProjectionKind::Subslice => {}  // We never capture this
1464         }
1465     }
1466
1467     let length = place.projections.len().min(truncated_length);
1468
1469     place.projections.truncate(length);
1470
1471     place
1472 }
1473
1474 /// Truncates a place so that the resultant capture doesn't move data out of a reference
1475 fn truncate_capture_for_move(mut place: Place<'tcx>) -> Place<'tcx> {
1476     if let Some(i) = place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref) {
1477         // We only drop Derefs in case of move closures
1478         // There might be an index projection or raw ptr ahead, so we don't stop here.
1479         place.projections.truncate(i);
1480     }
1481
1482     place
1483 }
1484
1485 fn construct_place_string(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
1486     let variable_name = match place.base {
1487         PlaceBase::Upvar(upvar_id) => var_name(tcx, upvar_id.var_path.hir_id).to_string(),
1488         _ => bug!("Capture_information should only contain upvars"),
1489     };
1490
1491     let mut projections_str = String::new();
1492     for (i, item) in place.projections.iter().enumerate() {
1493         let proj = match item.kind {
1494             ProjectionKind::Field(a, b) => format!("({:?}, {:?})", a, b),
1495             ProjectionKind::Deref => String::from("Deref"),
1496             ProjectionKind::Index => String::from("Index"),
1497             ProjectionKind::Subslice => String::from("Subslice"),
1498         };
1499         if i != 0 {
1500             projections_str.push(',');
1501         }
1502         projections_str.push_str(proj.as_str());
1503     }
1504
1505     format!("{}[{}]", variable_name, projections_str)
1506 }
1507
1508 fn construct_capture_kind_reason_string(
1509     tcx: TyCtxt<'_>,
1510     place: &Place<'tcx>,
1511     capture_info: &ty::CaptureInfo<'tcx>,
1512 ) -> String {
1513     let place_str = construct_place_string(tcx, &place);
1514
1515     let capture_kind_str = match capture_info.capture_kind {
1516         ty::UpvarCapture::ByValue(_) => "ByValue".into(),
1517         ty::UpvarCapture::ByRef(borrow) => format!("{:?}", borrow.kind),
1518     };
1519
1520     format!("{} captured as {} here", place_str, capture_kind_str)
1521 }
1522
1523 fn construct_path_string(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
1524     let place_str = construct_place_string(tcx, &place);
1525
1526     format!("{} used here", place_str)
1527 }
1528
1529 fn construct_capture_info_string(
1530     tcx: TyCtxt<'_>,
1531     place: &Place<'tcx>,
1532     capture_info: &ty::CaptureInfo<'tcx>,
1533 ) -> String {
1534     let place_str = construct_place_string(tcx, &place);
1535
1536     let capture_kind_str = match capture_info.capture_kind {
1537         ty::UpvarCapture::ByValue(_) => "ByValue".into(),
1538         ty::UpvarCapture::ByRef(borrow) => format!("{:?}", borrow.kind),
1539     };
1540     format!("{} -> {}", place_str, capture_kind_str)
1541 }
1542
1543 fn var_name(tcx: TyCtxt<'_>, var_hir_id: hir::HirId) -> Symbol {
1544     tcx.hir().name(var_hir_id)
1545 }
1546
1547 fn should_do_migration_analysis(tcx: TyCtxt<'_>, closure_id: hir::HirId) -> bool {
1548     let (level, _) =
1549         tcx.lint_level_at_node(lint::builtin::DISJOINT_CAPTURE_DROP_REORDER, closure_id);
1550
1551     !matches!(level, lint::Level::Allow)
1552 }
1553
1554 /// Return a two string tuple (s1, s2)
1555 /// - s1: Line of code that is needed for the migration: eg: `let _ = (&x, ...)`.
1556 /// - s2: Comma separated names of the variables being migrated.
1557 fn migration_suggestion_for_2229(
1558     tcx: TyCtxt<'_>,
1559     need_migrations: &Vec<hir::HirId>,
1560 ) -> (String, String) {
1561     let need_migrations_variables =
1562         need_migrations.iter().map(|v| var_name(tcx, *v)).collect::<Vec<_>>();
1563
1564     let migration_ref_concat =
1565         need_migrations_variables.iter().map(|v| format!("&{}", v)).collect::<Vec<_>>().join(", ");
1566
1567     let migration_string = if 1 == need_migrations.len() {
1568         format!("let _ = {}", migration_ref_concat)
1569     } else {
1570         format!("let _ = ({})", migration_ref_concat)
1571     };
1572
1573     let migrated_variables_concat =
1574         need_migrations_variables.iter().map(|v| format!("`{}`", v)).collect::<Vec<_>>().join(", ");
1575
1576     (migration_string, migrated_variables_concat)
1577 }
1578
1579 /// Helper function to determine if we need to escalate CaptureKind from
1580 /// CaptureInfo A to B and returns the escalated CaptureInfo.
1581 /// (Note: CaptureInfo contains CaptureKind and an expression that led to capture it in that way)
1582 ///
1583 /// If both `CaptureKind`s are considered equivalent, then the CaptureInfo is selected based
1584 /// on the `CaptureInfo` containing an associated `capture_kind_expr_id`.
1585 ///
1586 /// It is the caller's duty to figure out which path_expr_id to use.
1587 ///
1588 /// If both the CaptureKind and Expression are considered to be equivalent,
1589 /// then `CaptureInfo` A is preferred. This can be useful in cases where we want to priortize
1590 /// expressions reported back to the user as part of diagnostics based on which appears earlier
1591 /// in the closure. This can be achieved simply by calling
1592 /// `determine_capture_info(existing_info, current_info)`. This works out because the
1593 /// expressions that occur earlier in the closure body than the current expression are processed before.
1594 /// Consider the following example
1595 /// ```rust,no_run
1596 /// struct Point { x: i32, y: i32 }
1597 /// let mut p: Point { x: 10, y: 10 };
1598 ///
1599 /// let c = || {
1600 ///     p.x     += 10;
1601 /// // ^ E1 ^
1602 ///     // ...
1603 ///     // More code
1604 ///     // ...
1605 ///     p.x += 10; // E2
1606 /// // ^ E2 ^
1607 /// };
1608 /// ```
1609 /// `CaptureKind` associated with both `E1` and `E2` will be ByRef(MutBorrow),
1610 /// and both have an expression associated, however for diagnostics we prefer reporting
1611 /// `E1` since it appears earlier in the closure body. When `E2` is being processed we
1612 /// would've already handled `E1`, and have an existing capture_information for it.
1613 /// Calling `determine_capture_info(existing_info_e1, current_info_e2)` will return
1614 /// `existing_info_e1` in this case, allowing us to point to `E1` in case of diagnostics.
1615 fn determine_capture_info(
1616     capture_info_a: ty::CaptureInfo<'tcx>,
1617     capture_info_b: ty::CaptureInfo<'tcx>,
1618 ) -> ty::CaptureInfo<'tcx> {
1619     // If the capture kind is equivalent then, we don't need to escalate and can compare the
1620     // expressions.
1621     let eq_capture_kind = match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
1622         (ty::UpvarCapture::ByValue(_), ty::UpvarCapture::ByValue(_)) => {
1623             // We don't need to worry about the spans being ignored here.
1624             //
1625             // The expr_id in capture_info corresponds to the span that is stored within
1626             // ByValue(span) and therefore it gets handled with priortizing based on
1627             // expressions below.
1628             true
1629         }
1630         (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => {
1631             ref_a.kind == ref_b.kind
1632         }
1633         (ty::UpvarCapture::ByValue(_), _) | (ty::UpvarCapture::ByRef(_), _) => false,
1634     };
1635
1636     if eq_capture_kind {
1637         match (capture_info_a.capture_kind_expr_id, capture_info_b.capture_kind_expr_id) {
1638             (Some(_), _) | (None, None) => capture_info_a,
1639             (None, Some(_)) => capture_info_b,
1640         }
1641     } else {
1642         // We select the CaptureKind which ranks higher based the following priority order:
1643         // ByValue > MutBorrow > UniqueImmBorrow > ImmBorrow
1644         match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
1645             (ty::UpvarCapture::ByValue(_), _) => capture_info_a,
1646             (_, ty::UpvarCapture::ByValue(_)) => capture_info_b,
1647             (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => {
1648                 match (ref_a.kind, ref_b.kind) {
1649                     // Take LHS:
1650                     (ty::UniqueImmBorrow | ty::MutBorrow, ty::ImmBorrow)
1651                     | (ty::MutBorrow, ty::UniqueImmBorrow) => capture_info_a,
1652
1653                     // Take RHS:
1654                     (ty::ImmBorrow, ty::UniqueImmBorrow | ty::MutBorrow)
1655                     | (ty::UniqueImmBorrow, ty::MutBorrow) => capture_info_b,
1656
1657                     (ty::ImmBorrow, ty::ImmBorrow)
1658                     | (ty::UniqueImmBorrow, ty::UniqueImmBorrow)
1659                     | (ty::MutBorrow, ty::MutBorrow) => {
1660                         bug!("Expected unequal capture kinds");
1661                     }
1662                 }
1663             }
1664         }
1665     }
1666 }
1667
1668 /// Determines the Ancestry relationship of Place A relative to Place B
1669 ///
1670 /// `PlaceAncestryRelation::Ancestor` implies Place A is ancestor of Place B
1671 /// `PlaceAncestryRelation::Descendant` implies Place A is descendant of Place B
1672 /// `PlaceAncestryRelation::Divergent` implies neither of them is the ancestor of the other.
1673 fn determine_place_ancestry_relation(
1674     place_a: &Place<'tcx>,
1675     place_b: &Place<'tcx>,
1676 ) -> PlaceAncestryRelation {
1677     // If Place A and Place B, don't start off from the same root variable, they are divergent.
1678     if place_a.base != place_b.base {
1679         return PlaceAncestryRelation::Divergent;
1680     }
1681
1682     // Assume of length of projections_a = n
1683     let projections_a = &place_a.projections;
1684
1685     // Assume of length of projections_b = m
1686     let projections_b = &place_b.projections;
1687
1688     let same_initial_projections =
1689         iter::zip(projections_a, projections_b).all(|(proj_a, proj_b)| proj_a == proj_b);
1690
1691     if same_initial_projections {
1692         // First min(n, m) projections are the same
1693         // Select Ancestor/Descendant
1694         if projections_b.len() >= projections_a.len() {
1695             PlaceAncestryRelation::Ancestor
1696         } else {
1697             PlaceAncestryRelation::Descendant
1698         }
1699     } else {
1700         PlaceAncestryRelation::Divergent
1701     }
1702 }