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