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