1 //! ### Inferring borrow kinds for upvars
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:
9 //! ty::ImmBorrow -> ty::UniqueImmBorrow -> ty::MutBorrow
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
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.)
35 use crate::expr_use_visitor as euv;
36 use rustc_data_structures::fx::FxIndexMap;
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};
45 use rustc_span::{Span, Symbol};
47 /// Describe the relationship between the paths of two places
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 {
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);
62 // it's our job to process these.
63 assert!(self.deferred_call_resolutions.borrow().is_empty());
67 struct InferBorrowKindVisitor<'a, 'tcx> {
68 fcx: &'a FnCtxt<'a, 'tcx>,
71 impl<'a, 'tcx> Visitor<'tcx> for InferBorrowKindVisitor<'a, 'tcx> {
72 type Map = intravisit::ErasedMap<'tcx>;
74 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
75 NestedVisitorMap::None
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);
85 intravisit::walk_expr(self, expr);
89 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
90 /// Analysis starting point.
93 closure_hir_id: hir::HirId,
96 capture_clause: hir::CaptureBy,
98 debug!("analyze_closure(id={:?}, body.id={:?})", closure_hir_id, body.id());
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)),
106 // #51714: skip analysis when we have already encountered type errors
112 "type of closure expr {:?} is not a closure {:?}",
119 let infer_kind = if let UpvarSubsts::Closure(closure_substs) = substs {
120 self.closure_kind(closure_substs).is_none().then_some(closure_substs)
125 let local_def_id = closure_def_id.expect_local();
127 let mut capture_information: FxIndexMap<Place<'tcx>, ty::CaptureInfo<'tcx>> =
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);
134 debug!("seed place {:?}", place);
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 };
140 capture_information.insert(place, info);
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 {
152 current_closure_kind: ty::ClosureKind::LATTICE_BOTTOM,
153 current_origin: None,
156 euv::ExprUseVisitor::new(
161 &self.typeck_results.borrow(),
166 "For closure={:?}, capture_information={:#?}",
167 closure_def_id, delegate.capture_information
169 self.log_capture_analysis_first_pass(closure_def_id, &delegate.capture_information, span);
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);
178 // If we have an origin, store it.
179 if let Some(origin) = delegate.current_origin {
182 .closure_kind_origins_mut()
183 .insert(closure_hir_id, origin);
187 self.compute_min_captures(closure_def_id, delegate);
188 self.log_closure_min_capture_info(closure_def_id, span);
190 self.min_captures_to_closure_captures_bridge(closure_def_id);
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.
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).
204 // Equate the type variables for the upvars with the actual types.
205 let final_upvar_tys = self.final_upvar_tys(closure_def_id);
207 "analyze_closure: id={:?} substs={:?} final_upvar_tys={:?}",
208 closure_hir_id, substs, final_upvar_tys
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);
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);
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
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;
241 "place={:?} upvar_ty={:?} capture={:?}",
242 captured_place.place, upvar_ty, capture
246 ty::UpvarCapture::ByValue(_) => upvar_ty,
247 ty::UpvarCapture::ByRef(borrow) => tcx.mk_ref(
249 ty::TypeAndMut { ty: upvar_ty, mutbl: borrow.kind.to_mutbl_lossy() },
256 /// Bridge for closure analysis
257 /// ----------------------------
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.
262 /// For example the following structure will be converted:
264 /// closure_min_captures
265 /// foo -> [ {foo.x, ImmBorrow}, {foo.y, MutBorrow} ]
266 /// bar -> [ {bar.z, ByValue}, {bar.q, MutBorrow} ]
270 /// 1. closure_captures
271 /// foo -> UpvarId(foo, c), bar -> UpvarId(bar, c)
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();
279 if let Some(min_captures) =
280 self.typeck_results.borrow().closure_min_captures.get(&closure_def_id)
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;
287 let upvar_id = match place.base {
288 PlaceBase::Upvar(upvar_id) => upvar_id,
289 base => bug!("Expected upvar, found={:?}", base),
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());
295 closure_captures.insert(*var_hir_id, upvar_id);
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
305 capture_info.capture_kind
307 upvar_capture_map.insert(upvar_id, new_capture_kind);
311 debug!("For closure_def_id={:?}, closure_captures={:#?}", closure_def_id, closure_captures);
313 "For closure_def_id={:?}, upvar_capture_map={:#?}",
314 closure_def_id, upvar_capture_map
317 if !closure_captures.is_empty() {
321 .insert(closure_def_id, closure_captures);
323 self.typeck_results.borrow_mut().upvar_capture_map.extend(upvar_capture_map);
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.
333 /// struct Point { x: i32, y: i32 }
335 /// let s: String; // hir_id_s
336 /// let mut p: Point; // his_id_p
338 /// println!("{}", s); // L1
340 /// println!("{}" , p.y) // L3
341 /// println!("{}", p) // L4
345 /// and let hir_id_L1..5 be the expressions pointing to use of a captured variable on
346 /// the lines L1..5 respectively.
348 /// InferBorrowKind results in a structure like this:
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))
358 /// After the min capture analysis, we get:
362 /// Place(base: hir_id_s, projections: [], ....) -> (hir_id_L4, ByValue)
365 /// Place(base: hir_id_p, projections: [], ...) -> (hir_id_L2, ByRef(MutBorrow)),
368 fn compute_min_captures(
370 closure_def_id: DefId,
371 inferred_info: InferBorrowKind<'_, 'tcx>,
373 let mut root_var_min_capture_list: ty::RootVariableMinCaptureList<'_> = Default::default();
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),
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();
386 base_ty: place.base_ty,
388 projections: first_index_projection.map_or(Vec::new(), |p| p.to_vec()),
391 let min_cap_list = match root_var_min_capture_list.get_mut(&var_hir_id) {
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);
397 Some(min_cap_list) => min_cap_list,
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.
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.
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
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);
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);
437 // Only one ancestor of the current place will be in the list.
445 // Only need to insert when we don't have an ancestor in the existing min capture list
448 ty::CapturedPlace { place: place.clone(), info: updated_capture_info };
449 min_cap_list.push(captured_place);
453 debug!("For closure={:?}, min_captures={:#?}", closure_def_id, root_var_min_capture_list);
455 if !root_var_min_capture_list.is_empty() {
458 .closure_min_captures
459 .insert(closure_def_id, root_var_min_capture_list);
463 fn init_capture_kind(
465 capture_clause: hir::CaptureBy,
466 upvar_id: ty::UpvarId,
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)
480 fn place_for_root_variable(
482 closure_def_id: LocalDefId,
483 var_hir_id: hir::HirId,
485 let upvar_id = ty::UpvarId::new(var_hir_id, closure_def_id);
488 base_ty: self.node_ty(var_hir_id),
489 base: PlaceBase::Upvar(upvar_id),
490 projections: Default::default(),
494 fn should_log_capture_analysis(&self, closure_def_id: DefId) -> bool {
495 self.tcx.has_attr(closure_def_id, sym::rustc_capture_analysis)
498 fn log_capture_analysis_first_pass(
500 closure_def_id: rustc_hir::def_id::DefId,
501 capture_information: &FxIndexMap<Place<'tcx>, ty::CaptureInfo<'tcx>>,
504 if self.should_log_capture_analysis(closure_def_id) {
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);
511 let span = capture_info.expr_id.map_or(closure_span, |e| self.tcx.hir().span(e));
512 diag.span_note(span, &output_str);
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)
524 self.tcx.sess.struct_span_err(closure_span, "Min Capture analysis includes:");
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;
532 construct_capture_info_string(self.tcx, place, capture_info);
533 let output_str = format!("Min Capture {}", capture_str);
536 capture_info.expr_id.map_or(closure_span, |e| self.tcx.hir().span(e));
537 diag.span_note(span, &output_str);
546 struct InferBorrowKind<'a, 'tcx> {
547 fcx: &'a FnCtxt<'a, 'tcx>,
549 // The def-id of the closure whose kind and upvar accesses are being inferred.
550 closure_def_id: DefId,
554 capture_clause: hir::CaptureBy,
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
562 current_closure_kind: ty::ClosureKind,
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)>,
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.
571 /// Consider closure where s.str1 is captured via an ImmutableBorrow and
572 /// s.str2 via a MutableBorrow
575 /// struct SomeStruct { str1: String, str2: String }
577 /// // Assume that the HirId for the variable definition is `V1`
578 /// let mut s = SomeStruct { str1: format!("s1"), str2: format!("s2") }
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`
588 /// For closure `fix_s`, (at a high level) the map contains
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>>,
595 impl<'a, 'tcx> InferBorrowKind<'a, 'tcx> {
596 fn adjust_upvar_borrow_kind_for_consume(
598 place_with_id: &PlaceWithHirId<'tcx>,
599 diag_expr_id: hir::HirId,
600 mode: euv::ConsumeMode,
603 "adjust_upvar_borrow_kind_for_consume(place_with_id={:?}, diag_expr_id={:?}, mode={:?})",
604 place_with_id, diag_expr_id, mode
607 // we only care about moves
615 let tcx = self.fcx.tcx;
616 let upvar_id = if let PlaceBase::Upvar(upvar_id) = place_with_id.place.base {
622 debug!("adjust_upvar_borrow_kind_for_consume: upvar={:?}", upvar_id);
624 let usage_span = tcx.hir().span(diag_expr_id);
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,
631 var_name(tcx, upvar_id.var_path.hir_id),
634 let capture_info = ty::CaptureInfo {
635 expr_id: Some(diag_expr_id),
636 capture_kind: ty::UpvarCapture::ByValue(Some(usage_span)),
639 let curr_info = self.capture_information[&place_with_id.place];
640 let updated_info = determine_capture_info(curr_info, capture_info);
642 self.capture_information[&place_with_id.place] = updated_info;
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(
650 place_with_id: &PlaceWithHirId<'tcx>,
651 diag_expr_id: hir::HirId,
654 "adjust_upvar_borrow_kind_for_mut(place_with_id={:?}, diag_expr_id={:?})",
655 place_with_id, diag_expr_id
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,
672 self.adjust_upvar_deref(place_with_id, diag_expr_id, borrow_kind);
676 fn adjust_upvar_borrow_kind_for_unique(
678 place_with_id: &PlaceWithHirId<'tcx>,
679 diag_expr_id: hir::HirId,
682 "adjust_upvar_borrow_kind_for_unique(place_with_id={:?}, diag_expr_id={:?})",
683 place_with_id, diag_expr_id
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.
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);
696 fn adjust_upvar_deref(
698 place_with_id: &PlaceWithHirId<'tcx>,
699 diag_expr_id: hir::HirId,
700 borrow_kind: ty::BorrowKind,
702 assert!(match borrow_kind {
703 ty::MutBorrow => true,
704 ty::UniqueImmBorrow => true,
706 // imm borrows never require adjusting any kinds, so we don't wind up here
707 ty::ImmBorrow => false,
710 let tcx = self.fcx.tcx;
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);
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),
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(
735 place_with_id: &PlaceWithHirId<'tcx>,
736 diag_expr_id: hir::HirId,
737 kind: ty::BorrowKind,
739 let curr_capture_info = self.capture_information[&place_with_id.place];
742 "adjust_upvar_borrow_kind(place={:?}, diag_expr_id={:?}, capture_info={:?}, kind={:?})",
743 place_with_id, diag_expr_id, curr_capture_info, kind
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
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 };
754 let capture_info = ty::CaptureInfo {
755 expr_id: Some(diag_expr_id),
756 capture_kind: ty::UpvarCapture::ByRef(new_upvar_borrow),
758 let updated_info = determine_capture_info(curr_capture_info, capture_info);
759 self.capture_information[&place_with_id.place] = updated_info;
763 fn adjust_closure_kind(
765 closure_id: LocalDefId,
766 new_kind: ty::ClosureKind,
771 "adjust_closure_kind(closure_id={:?}, new_kind={:?}, upvar_span={:?}, var_name={})",
772 closure_id, new_kind, upvar_span, var_name
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");
781 // closures start out as `Fn`.
782 let existing_kind = self.current_closure_kind;
785 "adjust_closure_kind: closure_id={:?}, existing_kind={:?}, new_kind={:?}",
786 closure_id, existing_kind, new_kind
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, _) => {
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));
805 fn init_capture_info_for_place(
807 place_with_id: &PlaceWithHirId<'tcx>,
808 diag_expr_id: hir::HirId,
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);
814 self.fcx.init_capture_kind(self.capture_clause, upvar_id, self.closure_span);
816 let expr_id = Some(diag_expr_id);
817 let capture_info = ty::CaptureInfo { expr_id, capture_kind };
819 debug!("Capturing new place {:?}, capture_info={:?}", place_with_id, capture_info);
821 self.capture_information.insert(place_with_id.place.clone(), capture_info);
823 debug!("Not upvar: {:?}", place_with_id);
828 impl<'a, 'tcx> euv::Delegate<'tcx> for InferBorrowKind<'a, 'tcx> {
831 place_with_id: &PlaceWithHirId<'tcx>,
832 diag_expr_id: hir::HirId,
833 mode: euv::ConsumeMode,
836 "consume(place_with_id={:?}, diag_expr_id={:?}, mode={:?})",
837 place_with_id, diag_expr_id, mode
839 if !self.capture_information.contains_key(&place_with_id.place) {
840 self.init_capture_info_for_place(place_with_id, diag_expr_id);
843 self.adjust_upvar_borrow_kind_for_consume(place_with_id, diag_expr_id, mode);
848 place_with_id: &PlaceWithHirId<'tcx>,
849 diag_expr_id: hir::HirId,
853 "borrow(place_with_id={:?}, diag_expr_id={:?}, bk={:?})",
854 place_with_id, diag_expr_id, bk
857 if !self.capture_information.contains_key(&place_with_id.place) {
858 self.init_capture_info_for_place(place_with_id, diag_expr_id);
863 ty::UniqueImmBorrow => {
864 self.adjust_upvar_borrow_kind_for_unique(&place_with_id, diag_expr_id);
867 self.adjust_upvar_borrow_kind_for_mut(&place_with_id, diag_expr_id);
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);
875 if !self.capture_information.contains_key(&assignee_place.place) {
876 self.init_capture_info_for_place(assignee_place, diag_expr_id);
879 self.adjust_upvar_borrow_kind_for_mut(assignee_place, diag_expr_id);
883 fn construct_capture_info_string(
886 capture_info: &ty::CaptureInfo<'tcx>,
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"),
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"),
902 projections_str.push_str(",");
904 projections_str.push_str(proj.as_str());
907 let capture_kind_str = match capture_info.capture_kind {
908 ty::UpvarCapture::ByValue(_) => "ByValue".into(),
909 ty::UpvarCapture::ByRef(borrow) => format!("{:?}", borrow.kind),
911 format!("{}[{}] -> {}", variable_name, projections_str, capture_kind_str)
914 fn var_name(tcx: TyCtxt<'_>, var_hir_id: hir::HirId) -> Symbol {
915 tcx.hir().name(var_hir_id)
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)
922 /// If both `CaptureKind`s are considered equivalent, then the CaptureInfo is selected based
923 /// on the `CaptureInfo` containing an associated expression id.
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
933 /// struct Point { x: i32, y: i32 }
934 /// let mut p: Point { x: 10, y: 10 };
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
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.
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.
967 (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => {
968 ref_a.kind == ref_b.kind
970 (ty::UpvarCapture::ByValue(_), _) | (ty::UpvarCapture::ByRef(_), _) => false,
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,
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) {
987 (ty::UniqueImmBorrow | ty::MutBorrow, ty::ImmBorrow)
988 | (ty::MutBorrow, ty::UniqueImmBorrow) => capture_info_a,
991 (ty::ImmBorrow, ty::UniqueImmBorrow | ty::MutBorrow)
992 | (ty::UniqueImmBorrow, ty::MutBorrow) => capture_info_b,
994 (ty::ImmBorrow, ty::ImmBorrow)
995 | (ty::UniqueImmBorrow, ty::UniqueImmBorrow)
996 | (ty::MutBorrow, ty::MutBorrow) => {
997 bug!("Expected unequal capture kinds");
1005 /// Determines the Ancestry relationship of Place A relative to Place B
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;
1019 // Assume of length of projections_a = n
1020 let projections_a = &place_a.projections;
1022 // Assume of length of projections_b = m
1023 let projections_b = &place_b.projections;
1025 let mut same_initial_projections = true;
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;
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
1040 PlaceAncestryRelation::Descendant
1043 PlaceAncestryRelation::Divergent