]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/upvar.rs
Process mentioned upvars for analysis first pass after ExprUseVisitor
[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_hir as hir;
38 use rustc_hir::def_id::DefId;
39 use rustc_hir::def_id::LocalDefId;
40 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
41 use rustc_infer::infer::UpvarRegion;
42 use rustc_middle::hir::place::{Place, PlaceBase, PlaceWithHirId, ProjectionKind};
43 use rustc_middle::ty::{self, Ty, TyCtxt, TypeckResults, UpvarSubsts};
44 use rustc_span::sym;
45 use rustc_span::{MultiSpan, Span, Symbol};
46
47 /// Describe the relationship between the paths of two places
48 /// eg:
49 /// - `foo` is ancestor of `foo.bar.baz`
50 /// - `foo.bar.baz` is an descendant of `foo.bar`
51 /// - `foo.bar` and `foo.baz` are divergent
52 enum PlaceAncestryRelation {
53     Ancestor,
54     Descendant,
55     Divergent,
56 }
57
58 /// Intermediate format to store a captured `Place` and associated `ty::CaptureInfo`
59 /// during capture analysis. Information in this map feeds into the minimum capture
60 /// analysis pass.
61 type InferredCaptureInformation<'tcx> = FxIndexMap<Place<'tcx>, ty::CaptureInfo<'tcx>>;
62
63 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
64     pub fn closure_analyze(&self, body: &'tcx hir::Body<'tcx>) {
65         InferBorrowKindVisitor { fcx: self }.visit_body(body);
66
67         // it's our job to process these.
68         assert!(self.deferred_call_resolutions.borrow().is_empty());
69     }
70 }
71
72 struct InferBorrowKindVisitor<'a, 'tcx> {
73     fcx: &'a FnCtxt<'a, 'tcx>,
74 }
75
76 impl<'a, 'tcx> Visitor<'tcx> for InferBorrowKindVisitor<'a, 'tcx> {
77     type Map = intravisit::ErasedMap<'tcx>;
78
79     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
80         NestedVisitorMap::None
81     }
82
83     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
84         if let hir::ExprKind::Closure(cc, _, body_id, _, _) = expr.kind {
85             let body = self.fcx.tcx.hir().body(body_id);
86             self.visit_body(body);
87             self.fcx.analyze_closure(expr.hir_id, expr.span, body, cc);
88         }
89
90         intravisit::walk_expr(self, expr);
91     }
92 }
93
94 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
95     /// Analysis starting point.
96     fn analyze_closure(
97         &self,
98         closure_hir_id: hir::HirId,
99         span: Span,
100         body: &hir::Body<'_>,
101         capture_clause: hir::CaptureBy,
102     ) {
103         debug!("analyze_closure(id={:?}, body.id={:?})", closure_hir_id, body.id());
104
105         // Extract the type of the closure.
106         let ty = self.node_ty(closure_hir_id);
107         let (closure_def_id, substs) = match *ty.kind() {
108             ty::Closure(def_id, substs) => (def_id, UpvarSubsts::Closure(substs)),
109             ty::Generator(def_id, substs, _) => (def_id, UpvarSubsts::Generator(substs)),
110             ty::Error(_) => {
111                 // #51714: skip analysis when we have already encountered type errors
112                 return;
113             }
114             _ => {
115                 span_bug!(
116                     span,
117                     "type of closure expr {:?} is not a closure {:?}",
118                     closure_hir_id,
119                     ty
120                 );
121             }
122         };
123
124         let infer_kind = if let UpvarSubsts::Closure(closure_substs) = substs {
125             self.closure_kind(closure_substs).is_none().then_some(closure_substs)
126         } else {
127             None
128         };
129
130         let local_def_id = closure_def_id.expect_local();
131
132         let body_owner_def_id = self.tcx.hir().body_owner_def_id(body.id());
133         assert_eq!(body_owner_def_id.to_def_id(), closure_def_id);
134         let mut delegate = InferBorrowKind {
135             fcx: self,
136             closure_def_id,
137             closure_span: span,
138             capture_clause,
139             current_closure_kind: ty::ClosureKind::LATTICE_BOTTOM,
140             current_origin: None,
141             capture_information: Default::default(),
142         };
143         euv::ExprUseVisitor::new(
144             &mut delegate,
145             &self.infcx,
146             body_owner_def_id,
147             self.param_env,
148             &self.typeck_results.borrow(),
149         )
150         .consume_body(body);
151
152         debug!(
153             "For closure={:?}, capture_information={:#?}",
154             closure_def_id, delegate.capture_information
155         );
156         self.log_capture_analysis_first_pass(closure_def_id, &delegate.capture_information, span);
157
158         self.compute_min_captures(closure_def_id, delegate.capture_information);
159
160         // We now fake capture information for all variables that are mentioned within the closure
161         // We do this after handling migrations so that min_captures computes before
162         if !self.tcx.features().capture_disjoint_fields {
163             let mut capture_information: InferredCaptureInformation<'tcx> = Default::default();
164
165             if let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) {
166                 for var_hir_id in upvars.keys() {
167                     let place = self.place_for_root_variable(local_def_id, *var_hir_id);
168
169                     debug!("seed place {:?}", place);
170
171                     let upvar_id = ty::UpvarId::new(*var_hir_id, local_def_id);
172                     let capture_kind = self.init_capture_kind(capture_clause, upvar_id, span);
173                     let fake_info = ty::CaptureInfo {
174                         capture_kind_expr_id: None,
175                         path_expr_id: None,
176                         capture_kind,
177                     };
178
179                     capture_information.insert(place, fake_info);
180                 }
181             }
182
183             // This will update the min captures based on this new fake information.
184             self.compute_min_captures(closure_def_id, capture_information);
185         }
186
187         if let Some(closure_substs) = infer_kind {
188             // Unify the (as yet unbound) type variable in the closure
189             // substs with the kind we inferred.
190             let inferred_kind = delegate.current_closure_kind;
191             let closure_kind_ty = closure_substs.as_closure().kind_ty();
192             self.demand_eqtype(span, inferred_kind.to_ty(self.tcx), closure_kind_ty);
193
194             // If we have an origin, store it.
195             if let Some(origin) = delegate.current_origin.clone() {
196                 let origin = if self.tcx.features().capture_disjoint_fields {
197                     origin
198                 } else {
199                     // FIXME(project-rfc-2229#31): Once the changes to support reborrowing are
200                     //                             made, make sure we are selecting and restricting
201                     //                             the origin correctly.
202                     (origin.0, Place { projections: vec![], ..origin.1 })
203                 };
204
205                 self.typeck_results
206                     .borrow_mut()
207                     .closure_kind_origins_mut()
208                     .insert(closure_hir_id, origin);
209             }
210         }
211
212         self.log_closure_min_capture_info(closure_def_id, span);
213
214         self.min_captures_to_closure_captures_bridge(closure_def_id);
215
216         // Now that we've analyzed the closure, we know how each
217         // variable is borrowed, and we know what traits the closure
218         // implements (Fn vs FnMut etc). We now have some updates to do
219         // with that information.
220         //
221         // Note that no closure type C may have an upvar of type C
222         // (though it may reference itself via a trait object). This
223         // results from the desugaring of closures to a struct like
224         // `Foo<..., UV0...UVn>`. If one of those upvars referenced
225         // C, then the type would have infinite size (and the
226         // inference algorithm will reject it).
227
228         // Equate the type variables for the upvars with the actual types.
229         let final_upvar_tys = self.final_upvar_tys(closure_def_id);
230         debug!(
231             "analyze_closure: id={:?} substs={:?} final_upvar_tys={:?}",
232             closure_hir_id, substs, final_upvar_tys
233         );
234
235         // Build a tuple (U0..Un) of the final upvar types U0..Un
236         // and unify the upvar tupe type in the closure with it:
237         let final_tupled_upvars_type = self.tcx.mk_tup(final_upvar_tys.iter());
238         self.demand_suptype(span, substs.tupled_upvars_ty(), final_tupled_upvars_type);
239
240         // If we are also inferred the closure kind here,
241         // process any deferred resolutions.
242         let deferred_call_resolutions = self.remove_deferred_call_resolutions(closure_def_id);
243         for deferred_call_resolution in deferred_call_resolutions {
244             deferred_call_resolution.resolve(self);
245         }
246     }
247
248     // Returns a list of `Ty`s for each upvar.
249     fn final_upvar_tys(&self, closure_id: DefId) -> Vec<Ty<'tcx>> {
250         // Presently an unboxed closure type cannot "escape" out of a
251         // function, so we will only encounter ones that originated in the
252         // local crate or were inlined into it along with some function.
253         // This may change if abstract return types of some sort are
254         // implemented.
255         let tcx = self.tcx;
256
257         self.typeck_results
258             .borrow()
259             .closure_min_captures_flattened(closure_id)
260             .map(|captured_place| {
261                 let upvar_ty = captured_place.place.ty();
262                 let capture = captured_place.info.capture_kind;
263
264                 debug!(
265                     "final_upvar_tys: place={:?} upvar_ty={:?} capture={:?}, mutability={:?}",
266                     captured_place.place, upvar_ty, capture, captured_place.mutability,
267                 );
268
269                 match capture {
270                     ty::UpvarCapture::ByValue(_) => upvar_ty,
271                     ty::UpvarCapture::ByRef(borrow) => tcx.mk_ref(
272                         borrow.region,
273                         ty::TypeAndMut { ty: upvar_ty, mutbl: borrow.kind.to_mutbl_lossy() },
274                     ),
275                 }
276             })
277             .collect()
278     }
279
280     /// Bridge for closure analysis
281     /// ----------------------------
282     ///
283     /// For closure with DefId `c`, the bridge converts structures required for supporting RFC 2229,
284     /// to structures currently used in the compiler for handling closure captures.
285     ///
286     /// For example the following structure will be converted:
287     ///
288     /// closure_min_captures
289     /// foo -> [ {foo.x, ImmBorrow}, {foo.y, MutBorrow} ]
290     /// bar -> [ {bar.z, ByValue}, {bar.q, MutBorrow} ]
291     ///
292     /// to
293     ///
294     /// 1. closure_captures
295     /// foo -> UpvarId(foo, c), bar -> UpvarId(bar, c)
296     ///
297     /// 2. upvar_capture_map
298     /// UpvarId(foo,c) -> MutBorrow, UpvarId(bar, c) -> ByValue
299     fn min_captures_to_closure_captures_bridge(&self, closure_def_id: DefId) {
300         let mut closure_captures: FxIndexMap<hir::HirId, ty::UpvarId> = Default::default();
301         let mut upvar_capture_map = ty::UpvarCaptureMap::default();
302
303         if let Some(min_captures) =
304             self.typeck_results.borrow().closure_min_captures.get(&closure_def_id)
305         {
306             for (var_hir_id, min_list) in min_captures.iter() {
307                 for captured_place in min_list {
308                     let place = &captured_place.place;
309                     let capture_info = captured_place.info;
310
311                     let upvar_id = match place.base {
312                         PlaceBase::Upvar(upvar_id) => upvar_id,
313                         base => bug!("Expected upvar, found={:?}", base),
314                     };
315
316                     assert_eq!(upvar_id.var_path.hir_id, *var_hir_id);
317                     assert_eq!(upvar_id.closure_expr_id, closure_def_id.expect_local());
318
319                     closure_captures.insert(*var_hir_id, upvar_id);
320
321                     let new_capture_kind =
322                         if let Some(capture_kind) = upvar_capture_map.get(&upvar_id) {
323                             // upvar_capture_map only stores the UpvarCapture (CaptureKind),
324                             // so we create a fake capture info with no expression.
325                             let fake_capture_info = ty::CaptureInfo {
326                                 capture_kind_expr_id: None,
327                                 path_expr_id: None,
328                                 capture_kind: *capture_kind,
329                             };
330                             determine_capture_info(fake_capture_info, capture_info).capture_kind
331                         } else {
332                             capture_info.capture_kind
333                         };
334                     upvar_capture_map.insert(upvar_id, new_capture_kind);
335                 }
336             }
337         }
338         debug!("For closure_def_id={:?}, closure_captures={:#?}", closure_def_id, closure_captures);
339         debug!(
340             "For closure_def_id={:?}, upvar_capture_map={:#?}",
341             closure_def_id, upvar_capture_map
342         );
343
344         if !closure_captures.is_empty() {
345             self.typeck_results
346                 .borrow_mut()
347                 .closure_captures
348                 .insert(closure_def_id, closure_captures);
349
350             self.typeck_results.borrow_mut().upvar_capture_map.extend(upvar_capture_map);
351         }
352     }
353
354     /// Analyzes the information collected by `InferBorrowKind` to compute the min number of
355     /// Places (and corresponding capture kind) that we need to keep track of to support all
356     /// the required captured paths.
357     ///
358     ///
359     /// Note: If this function is called multiple times for the same closure, it will update
360     ///       the existing min_capture map that is stored in TypeckResults.
361     ///
362     /// Eg:
363     /// ```rust,no_run
364     /// struct Point { x: i32, y: i32 }
365     ///
366     /// let s: String;  // hir_id_s
367     /// let mut p: Point; // his_id_p
368     /// let c = || {
369     ///        println!("{}", s);  // L1
370     ///        p.x += 10;  // L2
371     ///        println!("{}" , p.y) // L3
372     ///        println!("{}", p) // L4
373     ///        drop(s);   // L5
374     /// };
375     /// ```
376     /// and let hir_id_L1..5 be the expressions pointing to use of a captured variable on
377     /// the lines L1..5 respectively.
378     ///
379     /// InferBorrowKind results in a structure like this:
380     ///
381     /// ```
382     /// {
383     ///       Place(base: hir_id_s, projections: [], ....) -> {
384     ///                                                            capture_kind_expr: hir_id_L5,
385     ///                                                            path_expr_id: hir_id_L5,
386     ///                                                            capture_kind: ByValue
387     ///                                                       },
388     ///       Place(base: hir_id_p, projections: [Field(0, 0)], ...) -> {
389     ///                                                                     capture_kind_expr: hir_id_L2,
390     ///                                                                     path_expr_id: hir_id_L2,
391     ///                                                                     capture_kind: ByValue
392     ///                                                                 },
393     ///       Place(base: hir_id_p, projections: [Field(1, 0)], ...) -> {
394     ///                                                                     capture_kind_expr: hir_id_L3,
395     ///                                                                     path_expr_id: hir_id_L3,
396     ///                                                                     capture_kind: ByValue
397     ///                                                                 },
398     ///       Place(base: hir_id_p, projections: [], ...) -> {
399     ///                                                          capture_kind_expr: hir_id_L4,
400     ///                                                          path_expr_id: hir_id_L4,
401     ///                                                          capture_kind: ByValue
402     ///                                                      },
403     /// ```
404     ///
405     /// After the min capture analysis, we get:
406     /// ```
407     /// {
408     ///       hir_id_s -> [
409     ///            Place(base: hir_id_s, projections: [], ....) -> {
410     ///                                                                capture_kind_expr: hir_id_L5,
411     ///                                                                path_expr_id: hir_id_L5,
412     ///                                                                capture_kind: ByValue
413     ///                                                            },
414     ///       ],
415     ///       hir_id_p -> [
416     ///            Place(base: hir_id_p, projections: [], ...) -> {
417     ///                                                               capture_kind_expr: hir_id_L2,
418     ///                                                               path_expr_id: hir_id_L4,
419     ///                                                               capture_kind: ByValue
420     ///                                                           },
421     ///       ],
422     /// ```
423     fn compute_min_captures(
424         &self,
425         closure_def_id: DefId,
426         capture_information: InferredCaptureInformation<'tcx>,
427     ) {
428         if capture_information.is_empty() {
429             return;
430         }
431
432         let mut typeck_results = self.typeck_results.borrow_mut();
433
434         let mut root_var_min_capture_list =
435             typeck_results.closure_min_captures.remove(&closure_def_id).unwrap_or_default();
436
437         for (place, capture_info) in capture_information.into_iter() {
438             let var_hir_id = match place.base {
439                 PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
440                 base => bug!("Expected upvar, found={:?}", base),
441             };
442
443             let place = restrict_capture_precision(place, capture_info.capture_kind);
444
445             let min_cap_list = match root_var_min_capture_list.get_mut(&var_hir_id) {
446                 None => {
447                     let mutability = self.determine_capture_mutability(&typeck_results, &place);
448                     let min_cap_list =
449                         vec![ty::CapturedPlace { place, info: capture_info, mutability }];
450                     root_var_min_capture_list.insert(var_hir_id, min_cap_list);
451                     continue;
452                 }
453                 Some(min_cap_list) => min_cap_list,
454             };
455
456             // Go through each entry in the current list of min_captures
457             // - if ancestor is found, update it's capture kind to account for current place's
458             // capture information.
459             //
460             // - if descendant is found, remove it from the list, and update the current place's
461             // capture information to account for the descendants's capture kind.
462             //
463             // We can never be in a case where the list contains both an ancestor and a descendant
464             // Also there can only be ancestor but in case of descendants there might be
465             // multiple.
466
467             let mut descendant_found = false;
468             let mut updated_capture_info = capture_info;
469             min_cap_list.retain(|possible_descendant| {
470                 match determine_place_ancestry_relation(&place, &possible_descendant.place) {
471                     // current place is ancestor of possible_descendant
472                     PlaceAncestryRelation::Ancestor => {
473                         descendant_found = true;
474                         let backup_path_expr_id = updated_capture_info.path_expr_id;
475
476                         updated_capture_info =
477                             determine_capture_info(updated_capture_info, possible_descendant.info);
478
479                         // we need to keep the ancestor's `path_expr_id`
480                         updated_capture_info.path_expr_id = backup_path_expr_id;
481                         false
482                     }
483
484                     _ => true,
485                 }
486             });
487
488             let mut ancestor_found = false;
489             if !descendant_found {
490                 for possible_ancestor in min_cap_list.iter_mut() {
491                     match determine_place_ancestry_relation(&place, &possible_ancestor.place) {
492                         // current place is descendant of possible_ancestor
493                         PlaceAncestryRelation::Descendant => {
494                             ancestor_found = true;
495                             let backup_path_expr_id = possible_ancestor.info.path_expr_id;
496                             possible_ancestor.info =
497                                 determine_capture_info(possible_ancestor.info, capture_info);
498
499                             // we need to keep the ancestor's `path_expr_id`
500                             possible_ancestor.info.path_expr_id = backup_path_expr_id;
501
502                             // Only one ancestor of the current place will be in the list.
503                             break;
504                         }
505                         _ => {}
506                     }
507                 }
508             }
509
510             // Only need to insert when we don't have an ancestor in the existing min capture list
511             if !ancestor_found {
512                 let mutability = self.determine_capture_mutability(&typeck_results, &place);
513                 let captured_place =
514                     ty::CapturedPlace { place, info: updated_capture_info, mutability };
515                 min_cap_list.push(captured_place);
516             }
517         }
518
519         debug!("For closure={:?}, min_captures={:#?}", closure_def_id, root_var_min_capture_list);
520         typeck_results.closure_min_captures.insert(closure_def_id, root_var_min_capture_list);
521     }
522
523     fn init_capture_kind(
524         &self,
525         capture_clause: hir::CaptureBy,
526         upvar_id: ty::UpvarId,
527         closure_span: Span,
528     ) -> ty::UpvarCapture<'tcx> {
529         match capture_clause {
530             hir::CaptureBy::Value => ty::UpvarCapture::ByValue(None),
531             hir::CaptureBy::Ref => {
532                 let origin = UpvarRegion(upvar_id, closure_span);
533                 let upvar_region = self.next_region_var(origin);
534                 let upvar_borrow = ty::UpvarBorrow { kind: ty::ImmBorrow, region: upvar_region };
535                 ty::UpvarCapture::ByRef(upvar_borrow)
536             }
537         }
538     }
539
540     fn place_for_root_variable(
541         &self,
542         closure_def_id: LocalDefId,
543         var_hir_id: hir::HirId,
544     ) -> Place<'tcx> {
545         let upvar_id = ty::UpvarId::new(var_hir_id, closure_def_id);
546
547         Place {
548             base_ty: self.node_ty(var_hir_id),
549             base: PlaceBase::Upvar(upvar_id),
550             projections: Default::default(),
551         }
552     }
553
554     fn should_log_capture_analysis(&self, closure_def_id: DefId) -> bool {
555         self.tcx.has_attr(closure_def_id, sym::rustc_capture_analysis)
556     }
557
558     fn log_capture_analysis_first_pass(
559         &self,
560         closure_def_id: rustc_hir::def_id::DefId,
561         capture_information: &FxIndexMap<Place<'tcx>, ty::CaptureInfo<'tcx>>,
562         closure_span: Span,
563     ) {
564         if self.should_log_capture_analysis(closure_def_id) {
565             let mut diag =
566                 self.tcx.sess.struct_span_err(closure_span, "First Pass analysis includes:");
567             for (place, capture_info) in capture_information {
568                 let capture_str = construct_capture_info_string(self.tcx, place, capture_info);
569                 let output_str = format!("Capturing {}", capture_str);
570
571                 let span =
572                     capture_info.path_expr_id.map_or(closure_span, |e| self.tcx.hir().span(e));
573                 diag.span_note(span, &output_str);
574             }
575             diag.emit();
576         }
577     }
578
579     fn log_closure_min_capture_info(&self, closure_def_id: DefId, closure_span: Span) {
580         if self.should_log_capture_analysis(closure_def_id) {
581             if let Some(min_captures) =
582                 self.typeck_results.borrow().closure_min_captures.get(&closure_def_id)
583             {
584                 let mut diag =
585                     self.tcx.sess.struct_span_err(closure_span, "Min Capture analysis includes:");
586
587                 for (_, min_captures_for_var) in min_captures {
588                     for capture in min_captures_for_var {
589                         let place = &capture.place;
590                         let capture_info = &capture.info;
591
592                         let capture_str =
593                             construct_capture_info_string(self.tcx, place, capture_info);
594                         let output_str = format!("Min Capture {}", capture_str);
595
596                         if capture.info.path_expr_id != capture.info.capture_kind_expr_id {
597                             let path_span = capture_info
598                                 .path_expr_id
599                                 .map_or(closure_span, |e| self.tcx.hir().span(e));
600                             let capture_kind_span = capture_info
601                                 .capture_kind_expr_id
602                                 .map_or(closure_span, |e| self.tcx.hir().span(e));
603
604                             let mut multi_span: MultiSpan =
605                                 MultiSpan::from_spans(vec![path_span, capture_kind_span]);
606
607                             let capture_kind_label =
608                                 construct_capture_kind_reason_string(self.tcx, place, capture_info);
609                             let path_label = construct_path_string(self.tcx, place);
610
611                             multi_span.push_span_label(path_span, path_label);
612                             multi_span.push_span_label(capture_kind_span, capture_kind_label);
613
614                             diag.span_note(multi_span, &output_str);
615                         } else {
616                             let span = capture_info
617                                 .path_expr_id
618                                 .map_or(closure_span, |e| self.tcx.hir().span(e));
619
620                             diag.span_note(span, &output_str);
621                         };
622                     }
623                 }
624                 diag.emit();
625             }
626         }
627     }
628
629     /// A captured place is mutable if
630     /// 1. Projections don't include a Deref of an immut-borrow, **and**
631     /// 2. PlaceBase is mut or projections include a Deref of a mut-borrow.
632     fn determine_capture_mutability(
633         &self,
634         typeck_results: &'a TypeckResults<'tcx>,
635         place: &Place<'tcx>,
636     ) -> hir::Mutability {
637         let var_hir_id = match place.base {
638             PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
639             _ => unreachable!(),
640         };
641
642         let bm = *typeck_results.pat_binding_modes().get(var_hir_id).expect("missing binding mode");
643
644         let mut is_mutbl = match bm {
645             ty::BindByValue(mutability) => mutability,
646             ty::BindByReference(_) => hir::Mutability::Not,
647         };
648
649         for pointer_ty in place.deref_tys() {
650             match pointer_ty.kind() {
651                 // We don't capture derefs of raw ptrs
652                 ty::RawPtr(_) => unreachable!(),
653
654                 // Derefencing a mut-ref allows us to mut the Place if we don't deref
655                 // an immut-ref after on top of this.
656                 ty::Ref(.., hir::Mutability::Mut) => is_mutbl = hir::Mutability::Mut,
657
658                 // The place isn't mutable once we dereference a immutable reference.
659                 ty::Ref(.., hir::Mutability::Not) => return hir::Mutability::Not,
660
661                 // Dereferencing a box doesn't change mutability
662                 ty::Adt(def, ..) if def.is_box() => {}
663
664                 unexpected_ty => bug!("deref of unexpected pointer type {:?}", unexpected_ty),
665             }
666         }
667
668         is_mutbl
669     }
670 }
671
672 struct InferBorrowKind<'a, 'tcx> {
673     fcx: &'a FnCtxt<'a, 'tcx>,
674
675     // The def-id of the closure whose kind and upvar accesses are being inferred.
676     closure_def_id: DefId,
677
678     closure_span: Span,
679
680     capture_clause: hir::CaptureBy,
681
682     // The kind that we have inferred that the current closure
683     // requires. Note that we *always* infer a minimal kind, even if
684     // we don't always *use* that in the final result (i.e., sometimes
685     // we've taken the closure kind from the expectations instead, and
686     // for generators we don't even implement the closure traits
687     // really).
688     current_closure_kind: ty::ClosureKind,
689
690     // If we modified `current_closure_kind`, this field contains a `Some()` with the
691     // variable access that caused us to do so.
692     current_origin: Option<(Span, Place<'tcx>)>,
693
694     /// For each Place that is captured by the closure, we track the minimal kind of
695     /// access we need (ref, ref mut, move, etc) and the expression that resulted in such access.
696     ///
697     /// Consider closure where s.str1 is captured via an ImmutableBorrow and
698     /// s.str2 via a MutableBorrow
699     ///
700     /// ```rust,no_run
701     /// struct SomeStruct { str1: String, str2: String }
702     ///
703     /// // Assume that the HirId for the variable definition is `V1`
704     /// let mut s = SomeStruct { str1: format!("s1"), str2: format!("s2") }
705     ///
706     /// let fix_s = |new_s2| {
707     ///     // Assume that the HirId for the expression `s.str1` is `E1`
708     ///     println!("Updating SomeStruct with str1=", s.str1);
709     ///     // Assume that the HirId for the expression `*s.str2` is `E2`
710     ///     s.str2 = new_s2;
711     /// };
712     /// ```
713     ///
714     /// For closure `fix_s`, (at a high level) the map contains
715     ///
716     /// ```
717     /// Place { V1, [ProjectionKind::Field(Index=0, Variant=0)] } : CaptureKind { E1, ImmutableBorrow }
718     /// Place { V1, [ProjectionKind::Field(Index=1, Variant=0)] } : CaptureKind { E2, MutableBorrow }
719     /// ```
720     capture_information: InferredCaptureInformation<'tcx>,
721 }
722
723 impl<'a, 'tcx> InferBorrowKind<'a, 'tcx> {
724     fn adjust_upvar_borrow_kind_for_consume(
725         &mut self,
726         place_with_id: &PlaceWithHirId<'tcx>,
727         diag_expr_id: hir::HirId,
728         mode: euv::ConsumeMode,
729     ) {
730         debug!(
731             "adjust_upvar_borrow_kind_for_consume(place_with_id={:?}, diag_expr_id={:?}, mode={:?})",
732             place_with_id, diag_expr_id, mode
733         );
734
735         // we only care about moves
736         match mode {
737             euv::Copy => {
738                 return;
739             }
740             euv::Move => {}
741         }
742
743         let tcx = self.fcx.tcx;
744         let upvar_id = if let PlaceBase::Upvar(upvar_id) = place_with_id.place.base {
745             upvar_id
746         } else {
747             return;
748         };
749
750         debug!("adjust_upvar_borrow_kind_for_consume: upvar={:?}", upvar_id);
751
752         let usage_span = tcx.hir().span(diag_expr_id);
753
754         // To move out of an upvar, this must be a FnOnce closure
755         self.adjust_closure_kind(
756             upvar_id.closure_expr_id,
757             ty::ClosureKind::FnOnce,
758             usage_span,
759             place_with_id.place.clone(),
760         );
761
762         let capture_info = ty::CaptureInfo {
763             capture_kind_expr_id: Some(diag_expr_id),
764             path_expr_id: Some(diag_expr_id),
765             capture_kind: ty::UpvarCapture::ByValue(Some(usage_span)),
766         };
767
768         let curr_info = self.capture_information[&place_with_id.place];
769         let updated_info = determine_capture_info(curr_info, capture_info);
770
771         self.capture_information[&place_with_id.place] = updated_info;
772     }
773
774     /// Indicates that `place_with_id` is being directly mutated (e.g., assigned
775     /// to). If the place is based on a by-ref upvar, this implies that
776     /// the upvar must be borrowed using an `&mut` borrow.
777     fn adjust_upvar_borrow_kind_for_mut(
778         &mut self,
779         place_with_id: &PlaceWithHirId<'tcx>,
780         diag_expr_id: hir::HirId,
781     ) {
782         debug!(
783             "adjust_upvar_borrow_kind_for_mut(place_with_id={:?}, diag_expr_id={:?})",
784             place_with_id, diag_expr_id
785         );
786
787         if let PlaceBase::Upvar(_) = place_with_id.place.base {
788             let mut borrow_kind = ty::MutBorrow;
789             for pointer_ty in place_with_id.place.deref_tys() {
790                 match pointer_ty.kind() {
791                     // Raw pointers don't inherit mutability.
792                     ty::RawPtr(_) => return,
793                     // assignment to deref of an `&mut`
794                     // borrowed pointer implies that the
795                     // pointer itself must be unique, but not
796                     // necessarily *mutable*
797                     ty::Ref(.., hir::Mutability::Mut) => borrow_kind = ty::UniqueImmBorrow,
798                     _ => (),
799                 }
800             }
801             self.adjust_upvar_deref(place_with_id, diag_expr_id, borrow_kind);
802         }
803     }
804
805     fn adjust_upvar_borrow_kind_for_unique(
806         &mut self,
807         place_with_id: &PlaceWithHirId<'tcx>,
808         diag_expr_id: hir::HirId,
809     ) {
810         debug!(
811             "adjust_upvar_borrow_kind_for_unique(place_with_id={:?}, diag_expr_id={:?})",
812             place_with_id, diag_expr_id
813         );
814
815         if let PlaceBase::Upvar(_) = place_with_id.place.base {
816             if place_with_id.place.deref_tys().any(ty::TyS::is_unsafe_ptr) {
817                 // Raw pointers don't inherit mutability.
818                 return;
819             }
820             // for a borrowed pointer to be unique, its base must be unique
821             self.adjust_upvar_deref(place_with_id, diag_expr_id, ty::UniqueImmBorrow);
822         }
823     }
824
825     fn adjust_upvar_deref(
826         &mut self,
827         place_with_id: &PlaceWithHirId<'tcx>,
828         diag_expr_id: hir::HirId,
829         borrow_kind: ty::BorrowKind,
830     ) {
831         assert!(match borrow_kind {
832             ty::MutBorrow => true,
833             ty::UniqueImmBorrow => true,
834
835             // imm borrows never require adjusting any kinds, so we don't wind up here
836             ty::ImmBorrow => false,
837         });
838
839         let tcx = self.fcx.tcx;
840
841         // if this is an implicit deref of an
842         // upvar, then we need to modify the
843         // borrow_kind of the upvar to make sure it
844         // is inferred to mutable if necessary
845         self.adjust_upvar_borrow_kind(place_with_id, diag_expr_id, borrow_kind);
846
847         if let PlaceBase::Upvar(upvar_id) = place_with_id.place.base {
848             self.adjust_closure_kind(
849                 upvar_id.closure_expr_id,
850                 ty::ClosureKind::FnMut,
851                 tcx.hir().span(diag_expr_id),
852                 place_with_id.place.clone(),
853             );
854         }
855     }
856
857     /// We infer the borrow_kind with which to borrow upvars in a stack closure.
858     /// The borrow_kind basically follows a lattice of `imm < unique-imm < mut`,
859     /// moving from left to right as needed (but never right to left).
860     /// Here the argument `mutbl` is the borrow_kind that is required by
861     /// some particular use.
862     fn adjust_upvar_borrow_kind(
863         &mut self,
864         place_with_id: &PlaceWithHirId<'tcx>,
865         diag_expr_id: hir::HirId,
866         kind: ty::BorrowKind,
867     ) {
868         let curr_capture_info = self.capture_information[&place_with_id.place];
869
870         debug!(
871             "adjust_upvar_borrow_kind(place={:?}, diag_expr_id={:?}, capture_info={:?}, kind={:?})",
872             place_with_id, diag_expr_id, curr_capture_info, kind
873         );
874
875         if let ty::UpvarCapture::ByValue(_) = curr_capture_info.capture_kind {
876             // It's already captured by value, we don't need to do anything here
877             return;
878         } else if let ty::UpvarCapture::ByRef(curr_upvar_borrow) = curr_capture_info.capture_kind {
879             // Use the same region as the current capture information
880             // Doesn't matter since only one of the UpvarBorrow will be used.
881             let new_upvar_borrow = ty::UpvarBorrow { kind, region: curr_upvar_borrow.region };
882
883             let capture_info = ty::CaptureInfo {
884                 capture_kind_expr_id: Some(diag_expr_id),
885                 path_expr_id: Some(diag_expr_id),
886                 capture_kind: ty::UpvarCapture::ByRef(new_upvar_borrow),
887             };
888             let updated_info = determine_capture_info(curr_capture_info, capture_info);
889             self.capture_information[&place_with_id.place] = updated_info;
890         };
891     }
892
893     fn adjust_closure_kind(
894         &mut self,
895         closure_id: LocalDefId,
896         new_kind: ty::ClosureKind,
897         upvar_span: Span,
898         place: Place<'tcx>,
899     ) {
900         debug!(
901             "adjust_closure_kind(closure_id={:?}, new_kind={:?}, upvar_span={:?}, place={:?})",
902             closure_id, new_kind, upvar_span, place
903         );
904
905         // Is this the closure whose kind is currently being inferred?
906         if closure_id.to_def_id() != self.closure_def_id {
907             debug!("adjust_closure_kind: not current closure");
908             return;
909         }
910
911         // closures start out as `Fn`.
912         let existing_kind = self.current_closure_kind;
913
914         debug!(
915             "adjust_closure_kind: closure_id={:?}, existing_kind={:?}, new_kind={:?}",
916             closure_id, existing_kind, new_kind
917         );
918
919         match (existing_kind, new_kind) {
920             (ty::ClosureKind::Fn, ty::ClosureKind::Fn)
921             | (ty::ClosureKind::FnMut, ty::ClosureKind::Fn | ty::ClosureKind::FnMut)
922             | (ty::ClosureKind::FnOnce, _) => {
923                 // no change needed
924             }
925
926             (ty::ClosureKind::Fn, ty::ClosureKind::FnMut | ty::ClosureKind::FnOnce)
927             | (ty::ClosureKind::FnMut, ty::ClosureKind::FnOnce) => {
928                 // new kind is stronger than the old kind
929                 self.current_closure_kind = new_kind;
930                 self.current_origin = Some((upvar_span, place));
931             }
932         }
933     }
934
935     fn init_capture_info_for_place(
936         &mut self,
937         place_with_id: &PlaceWithHirId<'tcx>,
938         diag_expr_id: hir::HirId,
939     ) {
940         if let PlaceBase::Upvar(upvar_id) = place_with_id.place.base {
941             assert_eq!(self.closure_def_id.expect_local(), upvar_id.closure_expr_id);
942
943             let capture_kind =
944                 self.fcx.init_capture_kind(self.capture_clause, upvar_id, self.closure_span);
945
946             let expr_id = Some(diag_expr_id);
947             let capture_info = ty::CaptureInfo {
948                 capture_kind_expr_id: expr_id,
949                 path_expr_id: expr_id,
950                 capture_kind,
951             };
952
953             debug!("Capturing new place {:?}, capture_info={:?}", place_with_id, capture_info);
954
955             self.capture_information.insert(place_with_id.place.clone(), capture_info);
956         } else {
957             debug!("Not upvar: {:?}", place_with_id);
958         }
959     }
960 }
961
962 impl<'a, 'tcx> euv::Delegate<'tcx> for InferBorrowKind<'a, 'tcx> {
963     fn consume(
964         &mut self,
965         place_with_id: &PlaceWithHirId<'tcx>,
966         diag_expr_id: hir::HirId,
967         mode: euv::ConsumeMode,
968     ) {
969         debug!(
970             "consume(place_with_id={:?}, diag_expr_id={:?}, mode={:?})",
971             place_with_id, diag_expr_id, mode
972         );
973         if !self.capture_information.contains_key(&place_with_id.place) {
974             self.init_capture_info_for_place(place_with_id, diag_expr_id);
975         }
976
977         self.adjust_upvar_borrow_kind_for_consume(place_with_id, diag_expr_id, mode);
978     }
979
980     fn borrow(
981         &mut self,
982         place_with_id: &PlaceWithHirId<'tcx>,
983         diag_expr_id: hir::HirId,
984         bk: ty::BorrowKind,
985     ) {
986         debug!(
987             "borrow(place_with_id={:?}, diag_expr_id={:?}, bk={:?})",
988             place_with_id, diag_expr_id, bk
989         );
990
991         if !self.capture_information.contains_key(&place_with_id.place) {
992             self.init_capture_info_for_place(place_with_id, diag_expr_id);
993         }
994
995         match bk {
996             ty::ImmBorrow => {}
997             ty::UniqueImmBorrow => {
998                 self.adjust_upvar_borrow_kind_for_unique(&place_with_id, diag_expr_id);
999             }
1000             ty::MutBorrow => {
1001                 self.adjust_upvar_borrow_kind_for_mut(&place_with_id, diag_expr_id);
1002             }
1003         }
1004     }
1005
1006     fn mutate(&mut self, assignee_place: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId) {
1007         debug!("mutate(assignee_place={:?}, diag_expr_id={:?})", assignee_place, diag_expr_id);
1008
1009         if !self.capture_information.contains_key(&assignee_place.place) {
1010             self.init_capture_info_for_place(assignee_place, diag_expr_id);
1011         }
1012
1013         self.adjust_upvar_borrow_kind_for_mut(assignee_place, diag_expr_id);
1014     }
1015 }
1016
1017 /// Truncate projections so that following rules are obeyed by the captured `place`:
1018 ///
1019 /// - No Derefs in move closure, this will result in value behind a reference getting moved.
1020 /// - No projections are applied to raw pointers, since these require unsafe blocks. We capture
1021 ///   them completely.
1022 /// - No Index projections are captured, since arrays are captured completely.
1023 fn restrict_capture_precision<'tcx>(
1024     mut place: Place<'tcx>,
1025     capture_kind: ty::UpvarCapture<'tcx>,
1026 ) -> Place<'tcx> {
1027     if place.projections.is_empty() {
1028         // Nothing to do here
1029         return place;
1030     }
1031
1032     if place.base_ty.is_unsafe_ptr() {
1033         place.projections.truncate(0);
1034         return place;
1035     }
1036
1037     let mut truncated_length = usize::MAX;
1038     let mut first_deref_projection = usize::MAX;
1039
1040     for (i, proj) in place.projections.iter().enumerate() {
1041         if proj.ty.is_unsafe_ptr() {
1042             // Don't apply any projections on top of an unsafe ptr
1043             truncated_length = truncated_length.min(i + 1);
1044             break;
1045         }
1046         match proj.kind {
1047             ProjectionKind::Index => {
1048                 // Arrays are completely captured, so we drop Index projections
1049                 truncated_length = truncated_length.min(i);
1050                 break;
1051             }
1052             ProjectionKind::Deref => {
1053                 // We only drop Derefs in case of move closures
1054                 // There might be an index projection or raw ptr ahead, so we don't stop here.
1055                 first_deref_projection = first_deref_projection.min(i);
1056             }
1057             ProjectionKind::Field(..) => {} // ignore
1058             ProjectionKind::Subslice => {}  // We never capture this
1059         }
1060     }
1061
1062     let length = place
1063         .projections
1064         .len()
1065         .min(truncated_length)
1066         // In case of capture `ByValue` we want to not capture derefs
1067         .min(match capture_kind {
1068             ty::UpvarCapture::ByValue(..) => first_deref_projection,
1069             ty::UpvarCapture::ByRef(..) => usize::MAX,
1070         });
1071
1072     place.projections.truncate(length);
1073
1074     place
1075 }
1076
1077 fn construct_place_string(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
1078     let variable_name = match place.base {
1079         PlaceBase::Upvar(upvar_id) => var_name(tcx, upvar_id.var_path.hir_id).to_string(),
1080         _ => bug!("Capture_information should only contain upvars"),
1081     };
1082
1083     let mut projections_str = String::new();
1084     for (i, item) in place.projections.iter().enumerate() {
1085         let proj = match item.kind {
1086             ProjectionKind::Field(a, b) => format!("({:?}, {:?})", a, b),
1087             ProjectionKind::Deref => String::from("Deref"),
1088             ProjectionKind::Index => String::from("Index"),
1089             ProjectionKind::Subslice => String::from("Subslice"),
1090         };
1091         if i != 0 {
1092             projections_str.push_str(",");
1093         }
1094         projections_str.push_str(proj.as_str());
1095     }
1096
1097     format!("{}[{}]", variable_name, projections_str)
1098 }
1099
1100 fn construct_capture_kind_reason_string(
1101     tcx: TyCtxt<'_>,
1102     place: &Place<'tcx>,
1103     capture_info: &ty::CaptureInfo<'tcx>,
1104 ) -> String {
1105     let place_str = construct_place_string(tcx, &place);
1106
1107     let capture_kind_str = match capture_info.capture_kind {
1108         ty::UpvarCapture::ByValue(_) => "ByValue".into(),
1109         ty::UpvarCapture::ByRef(borrow) => format!("{:?}", borrow.kind),
1110     };
1111
1112     format!("{} captured as {} here", place_str, capture_kind_str)
1113 }
1114
1115 fn construct_path_string(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
1116     let place_str = construct_place_string(tcx, &place);
1117
1118     format!("{} used here", place_str)
1119 }
1120
1121 fn construct_capture_info_string(
1122     tcx: TyCtxt<'_>,
1123     place: &Place<'tcx>,
1124     capture_info: &ty::CaptureInfo<'tcx>,
1125 ) -> String {
1126     let place_str = construct_place_string(tcx, &place);
1127
1128     let capture_kind_str = match capture_info.capture_kind {
1129         ty::UpvarCapture::ByValue(_) => "ByValue".into(),
1130         ty::UpvarCapture::ByRef(borrow) => format!("{:?}", borrow.kind),
1131     };
1132     format!("{} -> {}", place_str, capture_kind_str)
1133 }
1134
1135 fn var_name(tcx: TyCtxt<'_>, var_hir_id: hir::HirId) -> Symbol {
1136     tcx.hir().name(var_hir_id)
1137 }
1138
1139 /// Helper function to determine if we need to escalate CaptureKind from
1140 /// CaptureInfo A to B and returns the escalated CaptureInfo.
1141 /// (Note: CaptureInfo contains CaptureKind and an expression that led to capture it in that way)
1142 ///
1143 /// If both `CaptureKind`s are considered equivalent, then the CaptureInfo is selected based
1144 /// on the `CaptureInfo` containing an associated `capture_kind_expr_id`.
1145 ///
1146 /// It is the caller's duty to figure out which path_expr_id to use.
1147 ///
1148 /// If both the CaptureKind and Expression are considered to be equivalent,
1149 /// then `CaptureInfo` A is preferred. This can be useful in cases where we want to priortize
1150 /// expressions reported back to the user as part of diagnostics based on which appears earlier
1151 /// in the closure. This can be acheived simply by calling
1152 /// `determine_capture_info(existing_info, current_info)`. This works out because the
1153 /// expressions that occur earlier in the closure body than the current expression are processed before.
1154 /// Consider the following example
1155 /// ```rust,no_run
1156 /// struct Point { x: i32, y: i32 }
1157 /// let mut p: Point { x: 10, y: 10 };
1158 ///
1159 /// let c = || {
1160 ///     p.x     += 10;
1161 /// // ^ E1 ^
1162 ///     // ...
1163 ///     // More code
1164 ///     // ...
1165 ///     p.x += 10; // E2
1166 /// // ^ E2 ^
1167 /// };
1168 /// ```
1169 /// `CaptureKind` associated with both `E1` and `E2` will be ByRef(MutBorrow),
1170 /// and both have an expression associated, however for diagnostics we prefer reporting
1171 /// `E1` since it appears earlier in the closure body. When `E2` is being processed we
1172 /// would've already handled `E1`, and have an existing capture_information for it.
1173 /// Calling `determine_capture_info(existing_info_e1, current_info_e2)` will return
1174 /// `existing_info_e1` in this case, allowing us to point to `E1` in case of diagnostics.
1175 fn determine_capture_info(
1176     capture_info_a: ty::CaptureInfo<'tcx>,
1177     capture_info_b: ty::CaptureInfo<'tcx>,
1178 ) -> ty::CaptureInfo<'tcx> {
1179     // If the capture kind is equivalent then, we don't need to escalate and can compare the
1180     // expressions.
1181     let eq_capture_kind = match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
1182         (ty::UpvarCapture::ByValue(_), ty::UpvarCapture::ByValue(_)) => {
1183             // We don't need to worry about the spans being ignored here.
1184             //
1185             // The expr_id in capture_info corresponds to the span that is stored within
1186             // ByValue(span) and therefore it gets handled with priortizing based on
1187             // expressions below.
1188             true
1189         }
1190         (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => {
1191             ref_a.kind == ref_b.kind
1192         }
1193         (ty::UpvarCapture::ByValue(_), _) | (ty::UpvarCapture::ByRef(_), _) => false,
1194     };
1195
1196     if eq_capture_kind {
1197         match (capture_info_a.capture_kind_expr_id, capture_info_b.capture_kind_expr_id) {
1198             (Some(_), _) | (None, None) => capture_info_a,
1199             (None, Some(_)) => capture_info_b,
1200         }
1201     } else {
1202         // We select the CaptureKind which ranks higher based the following priority order:
1203         // ByValue > MutBorrow > UniqueImmBorrow > ImmBorrow
1204         match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
1205             (ty::UpvarCapture::ByValue(_), _) => capture_info_a,
1206             (_, ty::UpvarCapture::ByValue(_)) => capture_info_b,
1207             (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => {
1208                 match (ref_a.kind, ref_b.kind) {
1209                     // Take LHS:
1210                     (ty::UniqueImmBorrow | ty::MutBorrow, ty::ImmBorrow)
1211                     | (ty::MutBorrow, ty::UniqueImmBorrow) => capture_info_a,
1212
1213                     // Take RHS:
1214                     (ty::ImmBorrow, ty::UniqueImmBorrow | ty::MutBorrow)
1215                     | (ty::UniqueImmBorrow, ty::MutBorrow) => capture_info_b,
1216
1217                     (ty::ImmBorrow, ty::ImmBorrow)
1218                     | (ty::UniqueImmBorrow, ty::UniqueImmBorrow)
1219                     | (ty::MutBorrow, ty::MutBorrow) => {
1220                         bug!("Expected unequal capture kinds");
1221                     }
1222                 }
1223             }
1224         }
1225     }
1226 }
1227
1228 /// Determines the Ancestry relationship of Place A relative to Place B
1229 ///
1230 /// `PlaceAncestryRelation::Ancestor` implies Place A is ancestor of Place B
1231 /// `PlaceAncestryRelation::Descendant` implies Place A is descendant of Place B
1232 /// `PlaceAncestryRelation::Divergent` implies neither of them is the ancestor of the other.
1233 fn determine_place_ancestry_relation(
1234     place_a: &Place<'tcx>,
1235     place_b: &Place<'tcx>,
1236 ) -> PlaceAncestryRelation {
1237     // If Place A and Place B, don't start off from the same root variable, they are divergent.
1238     if place_a.base != place_b.base {
1239         return PlaceAncestryRelation::Divergent;
1240     }
1241
1242     // Assume of length of projections_a = n
1243     let projections_a = &place_a.projections;
1244
1245     // Assume of length of projections_b = m
1246     let projections_b = &place_b.projections;
1247
1248     let mut same_initial_projections = true;
1249
1250     for (proj_a, proj_b) in projections_a.iter().zip(projections_b.iter()) {
1251         if proj_a != proj_b {
1252             same_initial_projections = false;
1253             break;
1254         }
1255     }
1256
1257     if same_initial_projections {
1258         // First min(n, m) projections are the same
1259         // Select Ancestor/Descendant
1260         if projections_b.len() >= projections_a.len() {
1261             PlaceAncestryRelation::Ancestor
1262         } else {
1263             PlaceAncestryRelation::Descendant
1264         }
1265     } else {
1266         PlaceAncestryRelation::Divergent
1267     }
1268 }