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.)
33 use super::writeback::Resolver;
36 use crate::expr_use_visitor as euv;
37 use rustc_data_structures::fx::FxIndexMap;
39 use rustc_hir::def_id::DefId;
40 use rustc_hir::def_id::LocalDefId;
41 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
42 use rustc_infer::infer::UpvarRegion;
43 use rustc_middle::hir::place::{Place, PlaceBase, PlaceWithHirId, Projection, ProjectionKind};
44 use rustc_middle::ty::fold::TypeFoldable;
45 use rustc_middle::ty::{self, Ty, TyCtxt, TypeckResults, UpvarSubsts};
46 use rustc_session::lint;
48 use rustc_span::{MultiSpan, Span, Symbol};
50 use rustc_index::vec::Idx;
51 use rustc_target::abi::VariantIdx;
53 /// Describe the relationship between the paths of two places
55 /// - `foo` is ancestor of `foo.bar.baz`
56 /// - `foo.bar.baz` is an descendant of `foo.bar`
57 /// - `foo.bar` and `foo.baz` are divergent
58 enum PlaceAncestryRelation {
64 /// Intermediate format to store a captured `Place` and associated `ty::CaptureInfo`
65 /// during capture analysis. Information in this map feeds into the minimum capture
67 type InferredCaptureInformation<'tcx> = FxIndexMap<Place<'tcx>, ty::CaptureInfo<'tcx>>;
69 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
70 pub fn closure_analyze(&self, body: &'tcx hir::Body<'tcx>) {
71 InferBorrowKindVisitor { fcx: self }.visit_body(body);
73 // it's our job to process these.
74 assert!(self.deferred_call_resolutions.borrow().is_empty());
78 struct InferBorrowKindVisitor<'a, 'tcx> {
79 fcx: &'a FnCtxt<'a, 'tcx>,
82 impl<'a, 'tcx> Visitor<'tcx> for InferBorrowKindVisitor<'a, 'tcx> {
83 type Map = intravisit::ErasedMap<'tcx>;
85 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
86 NestedVisitorMap::None
89 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
90 if let hir::ExprKind::Closure(cc, _, body_id, _, _) = expr.kind {
91 let body = self.fcx.tcx.hir().body(body_id);
92 self.visit_body(body);
93 self.fcx.analyze_closure(expr.hir_id, expr.span, body, cc);
96 intravisit::walk_expr(self, expr);
100 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
101 /// Analysis starting point.
104 closure_hir_id: hir::HirId,
106 body: &'tcx hir::Body<'tcx>,
107 capture_clause: hir::CaptureBy,
109 debug!("analyze_closure(id={:?}, body.id={:?})", closure_hir_id, body.id());
111 // Extract the type of the closure.
112 let ty = self.node_ty(closure_hir_id);
113 let (closure_def_id, substs) = match *ty.kind() {
114 ty::Closure(def_id, substs) => (def_id, UpvarSubsts::Closure(substs)),
115 ty::Generator(def_id, substs, _) => (def_id, UpvarSubsts::Generator(substs)),
117 // #51714: skip analysis when we have already encountered type errors
123 "type of closure expr {:?} is not a closure {:?}",
130 let infer_kind = if let UpvarSubsts::Closure(closure_substs) = substs {
131 self.closure_kind(closure_substs).is_none().then_some(closure_substs)
136 let local_def_id = closure_def_id.expect_local();
138 let body_owner_def_id = self.tcx.hir().body_owner_def_id(body.id());
139 assert_eq!(body_owner_def_id.to_def_id(), closure_def_id);
140 let mut delegate = InferBorrowKind {
145 current_closure_kind: ty::ClosureKind::LATTICE_BOTTOM,
146 current_origin: None,
147 capture_information: Default::default(),
149 euv::ExprUseVisitor::new(
154 &self.typeck_results.borrow(),
159 "For closure={:?}, capture_information={:#?}",
160 closure_def_id, delegate.capture_information
162 self.log_capture_analysis_first_pass(closure_def_id, &delegate.capture_information, span);
164 self.compute_min_captures(closure_def_id, delegate.capture_information);
166 let closure_hir_id = self.tcx.hir().local_def_id_to_hir_id(local_def_id);
167 if should_do_migration_analysis(self.tcx, closure_hir_id) {
168 self.perform_2229_migration_anaysis(closure_def_id, capture_clause, span, body);
171 // We now fake capture information for all variables that are mentioned within the closure
172 // We do this after handling migrations so that min_captures computes before
173 if !self.tcx.features().capture_disjoint_fields {
174 let mut capture_information: InferredCaptureInformation<'tcx> = Default::default();
176 if let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) {
177 for var_hir_id in upvars.keys() {
178 let place = self.place_for_root_variable(local_def_id, *var_hir_id);
180 debug!("seed place {:?}", place);
182 let upvar_id = ty::UpvarId::new(*var_hir_id, local_def_id);
183 let capture_kind = self.init_capture_kind(capture_clause, upvar_id, span);
184 let fake_info = ty::CaptureInfo {
185 capture_kind_expr_id: None,
190 capture_information.insert(place, fake_info);
194 // This will update the min captures based on this new fake information.
195 self.compute_min_captures(closure_def_id, capture_information);
198 if let Some(closure_substs) = infer_kind {
199 // Unify the (as yet unbound) type variable in the closure
200 // substs with the kind we inferred.
201 let inferred_kind = delegate.current_closure_kind;
202 let closure_kind_ty = closure_substs.as_closure().kind_ty();
203 self.demand_eqtype(span, inferred_kind.to_ty(self.tcx), closure_kind_ty);
205 // If we have an origin, store it.
206 if let Some(origin) = delegate.current_origin.clone() {
207 let origin = if self.tcx.features().capture_disjoint_fields {
210 // FIXME(project-rfc-2229#31): Once the changes to support reborrowing are
211 // made, make sure we are selecting and restricting
212 // the origin correctly.
213 (origin.0, Place { projections: vec![], ..origin.1 })
218 .closure_kind_origins_mut()
219 .insert(closure_hir_id, origin);
223 self.log_closure_min_capture_info(closure_def_id, span);
225 self.min_captures_to_closure_captures_bridge(closure_def_id);
227 // Now that we've analyzed the closure, we know how each
228 // variable is borrowed, and we know what traits the closure
229 // implements (Fn vs FnMut etc). We now have some updates to do
230 // with that information.
232 // Note that no closure type C may have an upvar of type C
233 // (though it may reference itself via a trait object). This
234 // results from the desugaring of closures to a struct like
235 // `Foo<..., UV0...UVn>`. If one of those upvars referenced
236 // C, then the type would have infinite size (and the
237 // inference algorithm will reject it).
239 // Equate the type variables for the upvars with the actual types.
240 let final_upvar_tys = self.final_upvar_tys(closure_def_id);
242 "analyze_closure: id={:?} substs={:?} final_upvar_tys={:?}",
243 closure_hir_id, substs, final_upvar_tys
246 // Build a tuple (U0..Un) of the final upvar types U0..Un
247 // and unify the upvar tupe type in the closure with it:
248 let final_tupled_upvars_type = self.tcx.mk_tup(final_upvar_tys.iter());
249 self.demand_suptype(span, substs.tupled_upvars_ty(), final_tupled_upvars_type);
251 // If we are also inferred the closure kind here,
252 // process any deferred resolutions.
253 let deferred_call_resolutions = self.remove_deferred_call_resolutions(closure_def_id);
254 for deferred_call_resolution in deferred_call_resolutions {
255 deferred_call_resolution.resolve(self);
259 // Returns a list of `Ty`s for each upvar.
260 fn final_upvar_tys(&self, closure_id: DefId) -> Vec<Ty<'tcx>> {
261 // Presently an unboxed closure type cannot "escape" out of a
262 // function, so we will only encounter ones that originated in the
263 // local crate or were inlined into it along with some function.
264 // This may change if abstract return types of some sort are
270 .closure_min_captures_flattened(closure_id)
271 .map(|captured_place| {
272 let upvar_ty = captured_place.place.ty();
273 let capture = captured_place.info.capture_kind;
276 "final_upvar_tys: place={:?} upvar_ty={:?} capture={:?}, mutability={:?}",
277 captured_place.place, upvar_ty, capture, captured_place.mutability,
281 ty::UpvarCapture::ByValue(_) => upvar_ty,
282 ty::UpvarCapture::ByRef(borrow) => tcx.mk_ref(
284 ty::TypeAndMut { ty: upvar_ty, mutbl: borrow.kind.to_mutbl_lossy() },
291 /// Bridge for closure analysis
292 /// ----------------------------
294 /// For closure with DefId `c`, the bridge converts structures required for supporting RFC 2229,
295 /// to structures currently used in the compiler for handling closure captures.
297 /// For example the following structure will be converted:
299 /// closure_min_captures
300 /// foo -> [ {foo.x, ImmBorrow}, {foo.y, MutBorrow} ]
301 /// bar -> [ {bar.z, ByValue}, {bar.q, MutBorrow} ]
305 /// 1. closure_captures
306 /// foo -> UpvarId(foo, c), bar -> UpvarId(bar, c)
308 /// 2. upvar_capture_map
309 /// UpvarId(foo,c) -> MutBorrow, UpvarId(bar, c) -> ByValue
310 fn min_captures_to_closure_captures_bridge(&self, closure_def_id: DefId) {
311 let mut closure_captures: FxIndexMap<hir::HirId, ty::UpvarId> = Default::default();
312 let mut upvar_capture_map = ty::UpvarCaptureMap::default();
314 if let Some(min_captures) =
315 self.typeck_results.borrow().closure_min_captures.get(&closure_def_id)
317 for (var_hir_id, min_list) in min_captures.iter() {
318 for captured_place in min_list {
319 let place = &captured_place.place;
320 let capture_info = captured_place.info;
322 let upvar_id = match place.base {
323 PlaceBase::Upvar(upvar_id) => upvar_id,
324 base => bug!("Expected upvar, found={:?}", base),
327 assert_eq!(upvar_id.var_path.hir_id, *var_hir_id);
328 assert_eq!(upvar_id.closure_expr_id, closure_def_id.expect_local());
330 closure_captures.insert(*var_hir_id, upvar_id);
332 let new_capture_kind =
333 if let Some(capture_kind) = upvar_capture_map.get(&upvar_id) {
334 // upvar_capture_map only stores the UpvarCapture (CaptureKind),
335 // so we create a fake capture info with no expression.
336 let fake_capture_info = ty::CaptureInfo {
337 capture_kind_expr_id: None,
339 capture_kind: *capture_kind,
341 determine_capture_info(fake_capture_info, capture_info).capture_kind
343 capture_info.capture_kind
345 upvar_capture_map.insert(upvar_id, new_capture_kind);
349 debug!("For closure_def_id={:?}, closure_captures={:#?}", closure_def_id, closure_captures);
351 "For closure_def_id={:?}, upvar_capture_map={:#?}",
352 closure_def_id, upvar_capture_map
355 if !closure_captures.is_empty() {
359 .insert(closure_def_id, closure_captures);
361 self.typeck_results.borrow_mut().upvar_capture_map.extend(upvar_capture_map);
365 /// Analyzes the information collected by `InferBorrowKind` to compute the min number of
366 /// Places (and corresponding capture kind) that we need to keep track of to support all
367 /// the required captured paths.
370 /// Note: If this function is called multiple times for the same closure, it will update
371 /// the existing min_capture map that is stored in TypeckResults.
375 /// struct Point { x: i32, y: i32 }
377 /// let s: String; // hir_id_s
378 /// let mut p: Point; // his_id_p
380 /// println!("{}", s); // L1
382 /// println!("{}" , p.y) // L3
383 /// println!("{}", p) // L4
387 /// and let hir_id_L1..5 be the expressions pointing to use of a captured variable on
388 /// the lines L1..5 respectively.
390 /// InferBorrowKind results in a structure like this:
394 /// Place(base: hir_id_s, projections: [], ....) -> {
395 /// capture_kind_expr: hir_id_L5,
396 /// path_expr_id: hir_id_L5,
397 /// capture_kind: ByValue
399 /// Place(base: hir_id_p, projections: [Field(0, 0)], ...) -> {
400 /// capture_kind_expr: hir_id_L2,
401 /// path_expr_id: hir_id_L2,
402 /// capture_kind: ByValue
404 /// Place(base: hir_id_p, projections: [Field(1, 0)], ...) -> {
405 /// capture_kind_expr: hir_id_L3,
406 /// path_expr_id: hir_id_L3,
407 /// capture_kind: ByValue
409 /// Place(base: hir_id_p, projections: [], ...) -> {
410 /// capture_kind_expr: hir_id_L4,
411 /// path_expr_id: hir_id_L4,
412 /// capture_kind: ByValue
416 /// After the min capture analysis, we get:
420 /// Place(base: hir_id_s, projections: [], ....) -> {
421 /// capture_kind_expr: hir_id_L5,
422 /// path_expr_id: hir_id_L5,
423 /// capture_kind: ByValue
427 /// Place(base: hir_id_p, projections: [], ...) -> {
428 /// capture_kind_expr: hir_id_L2,
429 /// path_expr_id: hir_id_L4,
430 /// capture_kind: ByValue
434 fn compute_min_captures(
436 closure_def_id: DefId,
437 capture_information: InferredCaptureInformation<'tcx>,
439 if capture_information.is_empty() {
443 let mut typeck_results = self.typeck_results.borrow_mut();
445 let mut root_var_min_capture_list =
446 typeck_results.closure_min_captures.remove(&closure_def_id).unwrap_or_default();
448 for (place, capture_info) in capture_information.into_iter() {
449 let var_hir_id = match place.base {
450 PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
451 base => bug!("Expected upvar, found={:?}", base),
454 let place = restrict_capture_precision(place, capture_info.capture_kind);
456 let min_cap_list = match root_var_min_capture_list.get_mut(&var_hir_id) {
458 let mutability = self.determine_capture_mutability(&typeck_results, &place);
460 vec![ty::CapturedPlace { place, info: capture_info, mutability }];
461 root_var_min_capture_list.insert(var_hir_id, min_cap_list);
464 Some(min_cap_list) => min_cap_list,
467 // Go through each entry in the current list of min_captures
468 // - if ancestor is found, update it's capture kind to account for current place's
469 // capture information.
471 // - if descendant is found, remove it from the list, and update the current place's
472 // capture information to account for the descendants's capture kind.
474 // We can never be in a case where the list contains both an ancestor and a descendant
475 // Also there can only be ancestor but in case of descendants there might be
478 let mut descendant_found = false;
479 let mut updated_capture_info = capture_info;
480 min_cap_list.retain(|possible_descendant| {
481 match determine_place_ancestry_relation(&place, &possible_descendant.place) {
482 // current place is ancestor of possible_descendant
483 PlaceAncestryRelation::Ancestor => {
484 descendant_found = true;
485 let backup_path_expr_id = updated_capture_info.path_expr_id;
487 updated_capture_info =
488 determine_capture_info(updated_capture_info, possible_descendant.info);
490 // we need to keep the ancestor's `path_expr_id`
491 updated_capture_info.path_expr_id = backup_path_expr_id;
499 let mut ancestor_found = false;
500 if !descendant_found {
501 for possible_ancestor in min_cap_list.iter_mut() {
502 match determine_place_ancestry_relation(&place, &possible_ancestor.place) {
503 // current place is descendant of possible_ancestor
504 PlaceAncestryRelation::Descendant => {
505 ancestor_found = true;
506 let backup_path_expr_id = possible_ancestor.info.path_expr_id;
507 possible_ancestor.info =
508 determine_capture_info(possible_ancestor.info, capture_info);
510 // we need to keep the ancestor's `path_expr_id`
511 possible_ancestor.info.path_expr_id = backup_path_expr_id;
513 // Only one ancestor of the current place will be in the list.
521 // Only need to insert when we don't have an ancestor in the existing min capture list
523 let mutability = self.determine_capture_mutability(&typeck_results, &place);
525 ty::CapturedPlace { place, info: updated_capture_info, mutability };
526 min_cap_list.push(captured_place);
530 debug!("For closure={:?}, min_captures={:#?}", closure_def_id, root_var_min_capture_list);
531 typeck_results.closure_min_captures.insert(closure_def_id, root_var_min_capture_list);
534 /// Perform the migration analysis for RFC 2229, and emit lint
535 /// `disjoint_capture_drop_reorder` if needed.
536 fn perform_2229_migration_anaysis(
538 closure_def_id: DefId,
539 capture_clause: hir::CaptureBy,
541 body: &'tcx hir::Body<'tcx>,
543 let need_migrations_first_pass = self.compute_2229_migrations_first_pass(
548 self.typeck_results.borrow().closure_min_captures.get(&closure_def_id),
551 let need_migrations = self.compute_2229_migrations_precise_pass(
554 self.typeck_results.borrow().closure_min_captures.get(&closure_def_id),
555 &need_migrations_first_pass,
558 if !need_migrations.is_empty() {
559 let migrations_text = migration_suggestion_for_2229(self.tcx, &need_migrations);
561 let local_def_id = closure_def_id.expect_local();
562 let closure_hir_id = self.tcx.hir().local_def_id_to_hir_id(local_def_id);
563 self.tcx.struct_span_lint_hir(
564 lint::builtin::DISJOINT_CAPTURE_DROP_REORDER,
568 let mut diagnostics_builder = lint.build(
569 "drop order affected for closure because of `capture_disjoint_fields`",
571 diagnostics_builder.note(&migrations_text);
572 diagnostics_builder.emit();
578 /// Figures out the list of root variables (and their types) that aren't completely
579 /// captured by the closure when `capture_disjoint_fields` is enabled and drop order of
580 /// some path starting at that root variable **might** be affected.
582 /// The output list would include a root variable if:
583 /// - It would have been moved into the closure when `capture_disjoint_fields` wasn't
585 /// - It wasn't completely captured by the closure, **and**
586 /// - The type of the root variable needs Drop.
587 fn compute_2229_migrations_first_pass(
589 closure_def_id: DefId,
591 closure_clause: hir::CaptureBy,
592 body: &'tcx hir::Body<'tcx>,
593 min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
594 ) -> Vec<(hir::HirId, Ty<'tcx>)> {
595 fn resolve_ty<T: TypeFoldable<'tcx>>(
596 fcx: &FnCtxt<'_, 'tcx>,
598 body: &'tcx hir::Body<'tcx>,
601 let mut resolver = Resolver::new(fcx, &span, body);
602 ty.fold_with(&mut resolver)
605 let upvars = if let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) {
611 let mut need_migrations = Vec::new();
613 for (&var_hir_id, _) in upvars.iter() {
614 let ty = resolve_ty(self, closure_span, body, self.node_ty(var_hir_id));
616 if !ty.needs_drop(self.tcx, self.tcx.param_env(closure_def_id.expect_local())) {
620 let root_var_min_capture_list = if let Some(root_var_min_capture_list) =
621 min_captures.and_then(|m| m.get(&var_hir_id))
623 root_var_min_capture_list
625 // The upvar is mentioned within the closure but no path starting from it is
628 match closure_clause {
629 // Only migrate if closure is a move closure
630 hir::CaptureBy::Value => need_migrations.push((var_hir_id, ty)),
632 hir::CaptureBy::Ref => {}
638 let is_moved = root_var_min_capture_list
640 .any(|capture| matches!(capture.info.capture_kind, ty::UpvarCapture::ByValue(_)));
642 let is_not_completely_captured =
643 root_var_min_capture_list.iter().any(|capture| capture.place.projections.len() > 0);
645 if is_moved && is_not_completely_captured {
646 need_migrations.push((var_hir_id, ty));
653 fn compute_2229_migrations_precise_pass(
655 closure_def_id: DefId,
657 min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
658 need_migrations: &[(hir::HirId, Ty<'tcx>)],
659 ) -> Vec<hir::HirId> {
660 // Need migrations -- second pass
661 let mut need_migrations_2 = Vec::new();
663 for (hir_id, ty) in need_migrations {
664 let projections_list = min_captures
665 .and_then(|m| m.get(hir_id))
668 .filter_map(|captured_place| match captured_place.info.capture_kind {
669 // Only care about captures that are moved into the closure
670 ty::UpvarCapture::ByValue(..) => {
671 Some(captured_place.place.projections.as_slice())
673 ty::UpvarCapture::ByRef(..) => None,
677 if self.has_significant_drop_outside_of_captures(
683 need_migrations_2.push(*hir_id);
690 /// This is a helper function to `compute_2229_migrations_precise_pass`. Provided the type
691 /// of a root variable and a list of captured paths starting at this root variable (expressed
692 /// using list of `Projection` slices), it returns true if there is a path that is not
693 /// captured starting at this root variable that implements Drop.
695 /// FIXME(project-rfc-2229#35): This should return true only for significant drops.
696 /// A drop is significant if it's implemented by the user or does
697 /// anything that will have any observable behavior (other than
698 /// freeing up memory).
700 /// The way this function works is at a given call it looks at type `base_path_ty` of some base
701 /// path say P and then vector of projection slices which represent the different captures
702 /// starting off of P.
704 /// This will make more sense with an example:
707 /// #![feature(capture_disjoint_fields)]
709 /// struct FancyInteger(i32); // This implements Drop
711 /// struct Point { x: FancyInteger, y: FancyInteger }
714 /// struct Wrapper { p: Point, c: Color }
716 /// fn f(w: Wrapper) {
718 /// // Closure captures w.p.x and w.c by move.
725 /// If `capture_disjoint_fields` wasn't enabled the closure would've moved `w` instead of the
726 /// precise paths. If we look closely `w.p.y` isn't captured which implements Drop and
727 /// therefore Drop ordering would change and we want this function to return true.
729 /// Call stack to figure out if we need to migrate for `w` would look as follows:
731 /// Our initial base path is just `w`, and the paths captured from it are `w[p, x]` and
734 /// - Ty(place): Type of place
735 /// - `(a, b)`: Represents the function parameters `base_path_ty` and `captured_projs`
738 /// (Ty(w), [ &[p, x], &[c] ])
740 /// ----------------------------
743 /// (Ty(w.p), [ &[x] ]) (Ty(w.c), [ &[] ]) // I(1)
746 /// (Ty(w.p), [ &[x] ]) false
749 /// -------------------------------
752 /// (Ty((w.p).x), [ &[] ]) (Ty((w.p).y), []) // IMP 2
755 /// false NeedsDrop(Ty(w.p.y))
761 /// IMP 1 `(Ty(w.c), [ &[] ])`: Notice the single empty slice inside `captured_projs`.
762 /// This implies that the `w.c` is completely captured by the closure.
763 /// Since drop for this path will be called when the closure is
764 /// dropped we don't need to migrate for it.
766 /// IMP 2 `(Ty((w.p).y), [])`: Notice that `captured_projs` is empty. This implies that this
767 /// path wasn't captured by the closure. Also note that even
768 /// though we didn't capture this path, the function visits it,
769 /// which is kind of the point of this function. We then return
770 /// if the type of `w.p.y` implements Drop, which in this case is
773 /// Consider another example:
777 /// impl Drop for X {}
780 /// impl Drop for Y {}
784 /// let c = || move(y.0);
788 /// Note that `y.0` is captured by the closure. When this function is called for `y`, it will
789 /// return true, because even though all paths starting at `y` are captured, `y` itself
790 /// implements Drop which will be affected since `y` isn't completely captured.
791 fn has_significant_drop_outside_of_captures(
793 closure_def_id: DefId,
795 base_path_ty: Ty<'tcx>,
796 captured_projs: Vec<&[Projection<'tcx>]>,
798 let needs_drop = |ty: Ty<'tcx>| {
799 ty.needs_drop(self.tcx, self.tcx.param_env(closure_def_id.expect_local()))
802 let is_drop_defined_for_ty = |ty: Ty<'tcx>| {
803 let drop_trait = self.tcx.require_lang_item(hir::LangItem::Drop, Some(closure_span));
804 let ty_params = self.tcx.mk_substs_trait(base_path_ty, &[]);
805 self.tcx.type_implements_trait((
809 self.tcx.param_env(closure_def_id.expect_local()),
813 let is_drop_defined_for_ty = is_drop_defined_for_ty(base_path_ty);
815 // If there is a case where no projection is applied on top of current place
816 // then there must be exactly one capture corresponding to such a case. Note that this
817 // represents the case of the path being completely captured by the variable.
819 // eg. If `a.b` is captured and we are processing `a.b`, then we can't have the closure also
820 // capture `a.b.c`, because that voilates min capture.
821 let is_completely_captured = captured_projs.iter().any(|projs| projs.is_empty());
823 assert!(!is_completely_captured || (captured_projs.len() == 1));
825 if is_drop_defined_for_ty {
826 // If drop is implemented for this type then we need it to be fully captured, or
827 // it will require migration.
828 return !is_completely_captured;
831 if is_completely_captured {
832 // The place is captured entirely, so doesn't matter if needs dtor, it will be drop
833 // when the closure is dropped.
837 match base_path_ty.kind() {
838 _ if captured_projs.is_empty() => needs_drop(base_path_ty),
841 // - `captured_projs` is not empty. Therefore we can call
842 // `captured_projs.first().unwrap()` safely.
843 // - All entries in `captured_projs` have atleast one projection.
844 // Therefore we can call `captured_projs.first().unwrap().first().unwrap()` safely.
845 ty::Adt(def, _) if def.is_box() => {
846 // We must deref to access paths on top of a Box.
850 .all(|projs| matches!(projs.first().unwrap().kind, ProjectionKind::Deref))
853 let next_ty = captured_projs.first().unwrap().first().unwrap().ty;
854 let captured_projs = captured_projs.iter().map(|projs| &projs[1..]).collect();
855 self.has_significant_drop_outside_of_captures(
863 ty::Adt(def, substs) => {
864 // Multi-varaint enums are captured in entirety,
865 // which would've been handled in the case of single empty slice in `captured_projs`.
866 assert_eq!(def.variants.len(), 1);
868 // Only Field projections can be applied to a non-box Adt.
870 captured_projs.iter().all(|projs| matches!(
871 projs.first().unwrap().kind,
872 ProjectionKind::Field(..)
875 def.variants.get(VariantIdx::new(0)).unwrap().fields.iter().enumerate().any(
877 let paths_using_field = captured_projs
879 .filter_map(|projs| {
880 if let ProjectionKind::Field(field_idx, _) =
881 projs.first().unwrap().kind
883 if (field_idx as usize) == i { Some(&projs[1..]) } else { None }
890 let after_field_ty = field.ty(self.tcx, substs);
891 self.has_significant_drop_outside_of_captures(
902 // Only Field projections can be applied to a tuple.
904 captured_projs.iter().all(|projs| matches!(
905 projs.first().unwrap().kind,
906 ProjectionKind::Field(..)
910 base_path_ty.tuple_fields().enumerate().any(|(i, element_ty)| {
911 let paths_using_field = captured_projs
913 .filter_map(|projs| {
914 if let ProjectionKind::Field(field_idx, _) = projs.first().unwrap().kind
916 if (field_idx as usize) == i { Some(&projs[1..]) } else { None }
923 self.has_significant_drop_outside_of_captures(
932 ty::Ref(_, deref_ty, _) => {
933 // Only Derefs can be applied to a Ref
937 .all(|projs| matches!(projs.first().unwrap().kind, ProjectionKind::Deref))
940 let captured_projs = captured_projs.iter().map(|projs| &projs[1..]).collect();
941 self.has_significant_drop_outside_of_captures(
949 // Unsafe Ptrs are captured in their entirety, which would've have been handled in
950 // the case of single empty slice in `captured_projs`.
951 ty::RawPtr(..) => unreachable!(),
957 fn init_capture_kind(
959 capture_clause: hir::CaptureBy,
960 upvar_id: ty::UpvarId,
962 ) -> ty::UpvarCapture<'tcx> {
963 match capture_clause {
964 hir::CaptureBy::Value => ty::UpvarCapture::ByValue(None),
965 hir::CaptureBy::Ref => {
966 let origin = UpvarRegion(upvar_id, closure_span);
967 let upvar_region = self.next_region_var(origin);
968 let upvar_borrow = ty::UpvarBorrow { kind: ty::ImmBorrow, region: upvar_region };
969 ty::UpvarCapture::ByRef(upvar_borrow)
974 fn place_for_root_variable(
976 closure_def_id: LocalDefId,
977 var_hir_id: hir::HirId,
979 let upvar_id = ty::UpvarId::new(var_hir_id, closure_def_id);
982 base_ty: self.node_ty(var_hir_id),
983 base: PlaceBase::Upvar(upvar_id),
984 projections: Default::default(),
988 fn should_log_capture_analysis(&self, closure_def_id: DefId) -> bool {
989 self.tcx.has_attr(closure_def_id, sym::rustc_capture_analysis)
992 fn log_capture_analysis_first_pass(
994 closure_def_id: rustc_hir::def_id::DefId,
995 capture_information: &FxIndexMap<Place<'tcx>, ty::CaptureInfo<'tcx>>,
998 if self.should_log_capture_analysis(closure_def_id) {
1000 self.tcx.sess.struct_span_err(closure_span, "First Pass analysis includes:");
1001 for (place, capture_info) in capture_information {
1002 let capture_str = construct_capture_info_string(self.tcx, place, capture_info);
1003 let output_str = format!("Capturing {}", capture_str);
1006 capture_info.path_expr_id.map_or(closure_span, |e| self.tcx.hir().span(e));
1007 diag.span_note(span, &output_str);
1013 fn log_closure_min_capture_info(&self, closure_def_id: DefId, closure_span: Span) {
1014 if self.should_log_capture_analysis(closure_def_id) {
1015 if let Some(min_captures) =
1016 self.typeck_results.borrow().closure_min_captures.get(&closure_def_id)
1019 self.tcx.sess.struct_span_err(closure_span, "Min Capture analysis includes:");
1021 for (_, min_captures_for_var) in min_captures {
1022 for capture in min_captures_for_var {
1023 let place = &capture.place;
1024 let capture_info = &capture.info;
1027 construct_capture_info_string(self.tcx, place, capture_info);
1028 let output_str = format!("Min Capture {}", capture_str);
1030 if capture.info.path_expr_id != capture.info.capture_kind_expr_id {
1031 let path_span = capture_info
1033 .map_or(closure_span, |e| self.tcx.hir().span(e));
1034 let capture_kind_span = capture_info
1035 .capture_kind_expr_id
1036 .map_or(closure_span, |e| self.tcx.hir().span(e));
1038 let mut multi_span: MultiSpan =
1039 MultiSpan::from_spans(vec![path_span, capture_kind_span]);
1041 let capture_kind_label =
1042 construct_capture_kind_reason_string(self.tcx, place, capture_info);
1043 let path_label = construct_path_string(self.tcx, place);
1045 multi_span.push_span_label(path_span, path_label);
1046 multi_span.push_span_label(capture_kind_span, capture_kind_label);
1048 diag.span_note(multi_span, &output_str);
1050 let span = capture_info
1052 .map_or(closure_span, |e| self.tcx.hir().span(e));
1054 diag.span_note(span, &output_str);
1063 /// A captured place is mutable if
1064 /// 1. Projections don't include a Deref of an immut-borrow, **and**
1065 /// 2. PlaceBase is mut or projections include a Deref of a mut-borrow.
1066 fn determine_capture_mutability(
1068 typeck_results: &'a TypeckResults<'tcx>,
1069 place: &Place<'tcx>,
1070 ) -> hir::Mutability {
1071 let var_hir_id = match place.base {
1072 PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
1073 _ => unreachable!(),
1076 let bm = *typeck_results.pat_binding_modes().get(var_hir_id).expect("missing binding mode");
1078 let mut is_mutbl = match bm {
1079 ty::BindByValue(mutability) => mutability,
1080 ty::BindByReference(_) => hir::Mutability::Not,
1083 for pointer_ty in place.deref_tys() {
1084 match pointer_ty.kind() {
1085 // We don't capture derefs of raw ptrs
1086 ty::RawPtr(_) => unreachable!(),
1088 // Derefencing a mut-ref allows us to mut the Place if we don't deref
1089 // an immut-ref after on top of this.
1090 ty::Ref(.., hir::Mutability::Mut) => is_mutbl = hir::Mutability::Mut,
1092 // The place isn't mutable once we dereference a immutable reference.
1093 ty::Ref(.., hir::Mutability::Not) => return hir::Mutability::Not,
1095 // Dereferencing a box doesn't change mutability
1096 ty::Adt(def, ..) if def.is_box() => {}
1098 unexpected_ty => bug!("deref of unexpected pointer type {:?}", unexpected_ty),
1106 struct InferBorrowKind<'a, 'tcx> {
1107 fcx: &'a FnCtxt<'a, 'tcx>,
1109 // The def-id of the closure whose kind and upvar accesses are being inferred.
1110 closure_def_id: DefId,
1114 capture_clause: hir::CaptureBy,
1116 // The kind that we have inferred that the current closure
1117 // requires. Note that we *always* infer a minimal kind, even if
1118 // we don't always *use* that in the final result (i.e., sometimes
1119 // we've taken the closure kind from the expectations instead, and
1120 // for generators we don't even implement the closure traits
1122 current_closure_kind: ty::ClosureKind,
1124 // If we modified `current_closure_kind`, this field contains a `Some()` with the
1125 // variable access that caused us to do so.
1126 current_origin: Option<(Span, Place<'tcx>)>,
1128 /// For each Place that is captured by the closure, we track the minimal kind of
1129 /// access we need (ref, ref mut, move, etc) and the expression that resulted in such access.
1131 /// Consider closure where s.str1 is captured via an ImmutableBorrow and
1132 /// s.str2 via a MutableBorrow
1135 /// struct SomeStruct { str1: String, str2: String }
1137 /// // Assume that the HirId for the variable definition is `V1`
1138 /// let mut s = SomeStruct { str1: format!("s1"), str2: format!("s2") }
1140 /// let fix_s = |new_s2| {
1141 /// // Assume that the HirId for the expression `s.str1` is `E1`
1142 /// println!("Updating SomeStruct with str1=", s.str1);
1143 /// // Assume that the HirId for the expression `*s.str2` is `E2`
1144 /// s.str2 = new_s2;
1148 /// For closure `fix_s`, (at a high level) the map contains
1151 /// Place { V1, [ProjectionKind::Field(Index=0, Variant=0)] } : CaptureKind { E1, ImmutableBorrow }
1152 /// Place { V1, [ProjectionKind::Field(Index=1, Variant=0)] } : CaptureKind { E2, MutableBorrow }
1154 capture_information: InferredCaptureInformation<'tcx>,
1157 impl<'a, 'tcx> InferBorrowKind<'a, 'tcx> {
1158 fn adjust_upvar_borrow_kind_for_consume(
1160 place_with_id: &PlaceWithHirId<'tcx>,
1161 diag_expr_id: hir::HirId,
1162 mode: euv::ConsumeMode,
1165 "adjust_upvar_borrow_kind_for_consume(place_with_id={:?}, diag_expr_id={:?}, mode={:?})",
1166 place_with_id, diag_expr_id, mode
1169 // we only care about moves
1177 let tcx = self.fcx.tcx;
1178 let upvar_id = if let PlaceBase::Upvar(upvar_id) = place_with_id.place.base {
1184 debug!("adjust_upvar_borrow_kind_for_consume: upvar={:?}", upvar_id);
1186 let usage_span = tcx.hir().span(diag_expr_id);
1188 // To move out of an upvar, this must be a FnOnce closure
1189 self.adjust_closure_kind(
1190 upvar_id.closure_expr_id,
1191 ty::ClosureKind::FnOnce,
1193 place_with_id.place.clone(),
1196 let capture_info = ty::CaptureInfo {
1197 capture_kind_expr_id: Some(diag_expr_id),
1198 path_expr_id: Some(diag_expr_id),
1199 capture_kind: ty::UpvarCapture::ByValue(Some(usage_span)),
1202 let curr_info = self.capture_information[&place_with_id.place];
1203 let updated_info = determine_capture_info(curr_info, capture_info);
1205 self.capture_information[&place_with_id.place] = updated_info;
1208 /// Indicates that `place_with_id` is being directly mutated (e.g., assigned
1209 /// to). If the place is based on a by-ref upvar, this implies that
1210 /// the upvar must be borrowed using an `&mut` borrow.
1211 fn adjust_upvar_borrow_kind_for_mut(
1213 place_with_id: &PlaceWithHirId<'tcx>,
1214 diag_expr_id: hir::HirId,
1217 "adjust_upvar_borrow_kind_for_mut(place_with_id={:?}, diag_expr_id={:?})",
1218 place_with_id, diag_expr_id
1221 if let PlaceBase::Upvar(_) = place_with_id.place.base {
1222 let mut borrow_kind = ty::MutBorrow;
1223 for pointer_ty in place_with_id.place.deref_tys() {
1224 match pointer_ty.kind() {
1225 // Raw pointers don't inherit mutability.
1226 ty::RawPtr(_) => return,
1227 // assignment to deref of an `&mut`
1228 // borrowed pointer implies that the
1229 // pointer itself must be unique, but not
1230 // necessarily *mutable*
1231 ty::Ref(.., hir::Mutability::Mut) => borrow_kind = ty::UniqueImmBorrow,
1235 self.adjust_upvar_deref(place_with_id, diag_expr_id, borrow_kind);
1239 fn adjust_upvar_borrow_kind_for_unique(
1241 place_with_id: &PlaceWithHirId<'tcx>,
1242 diag_expr_id: hir::HirId,
1245 "adjust_upvar_borrow_kind_for_unique(place_with_id={:?}, diag_expr_id={:?})",
1246 place_with_id, diag_expr_id
1249 if let PlaceBase::Upvar(_) = place_with_id.place.base {
1250 if place_with_id.place.deref_tys().any(ty::TyS::is_unsafe_ptr) {
1251 // Raw pointers don't inherit mutability.
1254 // for a borrowed pointer to be unique, its base must be unique
1255 self.adjust_upvar_deref(place_with_id, diag_expr_id, ty::UniqueImmBorrow);
1259 fn adjust_upvar_deref(
1261 place_with_id: &PlaceWithHirId<'tcx>,
1262 diag_expr_id: hir::HirId,
1263 borrow_kind: ty::BorrowKind,
1265 assert!(match borrow_kind {
1266 ty::MutBorrow => true,
1267 ty::UniqueImmBorrow => true,
1269 // imm borrows never require adjusting any kinds, so we don't wind up here
1270 ty::ImmBorrow => false,
1273 let tcx = self.fcx.tcx;
1275 // if this is an implicit deref of an
1276 // upvar, then we need to modify the
1277 // borrow_kind of the upvar to make sure it
1278 // is inferred to mutable if necessary
1279 self.adjust_upvar_borrow_kind(place_with_id, diag_expr_id, borrow_kind);
1281 if let PlaceBase::Upvar(upvar_id) = place_with_id.place.base {
1282 self.adjust_closure_kind(
1283 upvar_id.closure_expr_id,
1284 ty::ClosureKind::FnMut,
1285 tcx.hir().span(diag_expr_id),
1286 place_with_id.place.clone(),
1291 /// We infer the borrow_kind with which to borrow upvars in a stack closure.
1292 /// The borrow_kind basically follows a lattice of `imm < unique-imm < mut`,
1293 /// moving from left to right as needed (but never right to left).
1294 /// Here the argument `mutbl` is the borrow_kind that is required by
1295 /// some particular use.
1296 fn adjust_upvar_borrow_kind(
1298 place_with_id: &PlaceWithHirId<'tcx>,
1299 diag_expr_id: hir::HirId,
1300 kind: ty::BorrowKind,
1302 let curr_capture_info = self.capture_information[&place_with_id.place];
1305 "adjust_upvar_borrow_kind(place={:?}, diag_expr_id={:?}, capture_info={:?}, kind={:?})",
1306 place_with_id, diag_expr_id, curr_capture_info, kind
1309 if let ty::UpvarCapture::ByValue(_) = curr_capture_info.capture_kind {
1310 // It's already captured by value, we don't need to do anything here
1312 } else if let ty::UpvarCapture::ByRef(curr_upvar_borrow) = curr_capture_info.capture_kind {
1313 // Use the same region as the current capture information
1314 // Doesn't matter since only one of the UpvarBorrow will be used.
1315 let new_upvar_borrow = ty::UpvarBorrow { kind, region: curr_upvar_borrow.region };
1317 let capture_info = ty::CaptureInfo {
1318 capture_kind_expr_id: Some(diag_expr_id),
1319 path_expr_id: Some(diag_expr_id),
1320 capture_kind: ty::UpvarCapture::ByRef(new_upvar_borrow),
1322 let updated_info = determine_capture_info(curr_capture_info, capture_info);
1323 self.capture_information[&place_with_id.place] = updated_info;
1327 fn adjust_closure_kind(
1329 closure_id: LocalDefId,
1330 new_kind: ty::ClosureKind,
1335 "adjust_closure_kind(closure_id={:?}, new_kind={:?}, upvar_span={:?}, place={:?})",
1336 closure_id, new_kind, upvar_span, place
1339 // Is this the closure whose kind is currently being inferred?
1340 if closure_id.to_def_id() != self.closure_def_id {
1341 debug!("adjust_closure_kind: not current closure");
1345 // closures start out as `Fn`.
1346 let existing_kind = self.current_closure_kind;
1349 "adjust_closure_kind: closure_id={:?}, existing_kind={:?}, new_kind={:?}",
1350 closure_id, existing_kind, new_kind
1353 match (existing_kind, new_kind) {
1354 (ty::ClosureKind::Fn, ty::ClosureKind::Fn)
1355 | (ty::ClosureKind::FnMut, ty::ClosureKind::Fn | ty::ClosureKind::FnMut)
1356 | (ty::ClosureKind::FnOnce, _) => {
1360 (ty::ClosureKind::Fn, ty::ClosureKind::FnMut | ty::ClosureKind::FnOnce)
1361 | (ty::ClosureKind::FnMut, ty::ClosureKind::FnOnce) => {
1362 // new kind is stronger than the old kind
1363 self.current_closure_kind = new_kind;
1364 self.current_origin = Some((upvar_span, place));
1369 fn init_capture_info_for_place(
1371 place_with_id: &PlaceWithHirId<'tcx>,
1372 diag_expr_id: hir::HirId,
1374 if let PlaceBase::Upvar(upvar_id) = place_with_id.place.base {
1375 assert_eq!(self.closure_def_id.expect_local(), upvar_id.closure_expr_id);
1378 self.fcx.init_capture_kind(self.capture_clause, upvar_id, self.closure_span);
1380 let expr_id = Some(diag_expr_id);
1381 let capture_info = ty::CaptureInfo {
1382 capture_kind_expr_id: expr_id,
1383 path_expr_id: expr_id,
1387 debug!("Capturing new place {:?}, capture_info={:?}", place_with_id, capture_info);
1389 self.capture_information.insert(place_with_id.place.clone(), capture_info);
1391 debug!("Not upvar: {:?}", place_with_id);
1396 impl<'a, 'tcx> euv::Delegate<'tcx> for InferBorrowKind<'a, 'tcx> {
1399 place_with_id: &PlaceWithHirId<'tcx>,
1400 diag_expr_id: hir::HirId,
1401 mode: euv::ConsumeMode,
1404 "consume(place_with_id={:?}, diag_expr_id={:?}, mode={:?})",
1405 place_with_id, diag_expr_id, mode
1407 if !self.capture_information.contains_key(&place_with_id.place) {
1408 self.init_capture_info_for_place(place_with_id, diag_expr_id);
1411 self.adjust_upvar_borrow_kind_for_consume(place_with_id, diag_expr_id, mode);
1416 place_with_id: &PlaceWithHirId<'tcx>,
1417 diag_expr_id: hir::HirId,
1421 "borrow(place_with_id={:?}, diag_expr_id={:?}, bk={:?})",
1422 place_with_id, diag_expr_id, bk
1425 if !self.capture_information.contains_key(&place_with_id.place) {
1426 self.init_capture_info_for_place(place_with_id, diag_expr_id);
1431 ty::UniqueImmBorrow => {
1432 self.adjust_upvar_borrow_kind_for_unique(&place_with_id, diag_expr_id);
1435 self.adjust_upvar_borrow_kind_for_mut(&place_with_id, diag_expr_id);
1440 fn mutate(&mut self, assignee_place: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId) {
1441 debug!("mutate(assignee_place={:?}, diag_expr_id={:?})", assignee_place, diag_expr_id);
1443 if !self.capture_information.contains_key(&assignee_place.place) {
1444 self.init_capture_info_for_place(assignee_place, diag_expr_id);
1447 self.adjust_upvar_borrow_kind_for_mut(assignee_place, diag_expr_id);
1451 /// Truncate projections so that following rules are obeyed by the captured `place`:
1453 /// - No Derefs in move closure, this will result in value behind a reference getting moved.
1454 /// - No projections are applied to raw pointers, since these require unsafe blocks. We capture
1455 /// them completely.
1456 /// - No Index projections are captured, since arrays are captured completely.
1457 fn restrict_capture_precision<'tcx>(
1458 mut place: Place<'tcx>,
1459 capture_kind: ty::UpvarCapture<'tcx>,
1461 if place.projections.is_empty() {
1462 // Nothing to do here
1466 if place.base_ty.is_unsafe_ptr() {
1467 place.projections.truncate(0);
1471 let mut truncated_length = usize::MAX;
1472 let mut first_deref_projection = usize::MAX;
1474 for (i, proj) in place.projections.iter().enumerate() {
1475 if proj.ty.is_unsafe_ptr() {
1476 // Don't apply any projections on top of an unsafe ptr
1477 truncated_length = truncated_length.min(i + 1);
1481 ProjectionKind::Index => {
1482 // Arrays are completely captured, so we drop Index projections
1483 truncated_length = truncated_length.min(i);
1486 ProjectionKind::Deref => {
1487 // We only drop Derefs in case of move closures
1488 // There might be an index projection or raw ptr ahead, so we don't stop here.
1489 first_deref_projection = first_deref_projection.min(i);
1491 ProjectionKind::Field(..) => {} // ignore
1492 ProjectionKind::Subslice => {} // We never capture this
1499 .min(truncated_length)
1500 // In case of capture `ByValue` we want to not capture derefs
1501 .min(match capture_kind {
1502 ty::UpvarCapture::ByValue(..) => first_deref_projection,
1503 ty::UpvarCapture::ByRef(..) => usize::MAX,
1506 place.projections.truncate(length);
1511 fn construct_place_string(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
1512 let variable_name = match place.base {
1513 PlaceBase::Upvar(upvar_id) => var_name(tcx, upvar_id.var_path.hir_id).to_string(),
1514 _ => bug!("Capture_information should only contain upvars"),
1517 let mut projections_str = String::new();
1518 for (i, item) in place.projections.iter().enumerate() {
1519 let proj = match item.kind {
1520 ProjectionKind::Field(a, b) => format!("({:?}, {:?})", a, b),
1521 ProjectionKind::Deref => String::from("Deref"),
1522 ProjectionKind::Index => String::from("Index"),
1523 ProjectionKind::Subslice => String::from("Subslice"),
1526 projections_str.push_str(",");
1528 projections_str.push_str(proj.as_str());
1531 format!("{}[{}]", variable_name, projections_str)
1534 fn construct_capture_kind_reason_string(
1536 place: &Place<'tcx>,
1537 capture_info: &ty::CaptureInfo<'tcx>,
1539 let place_str = construct_place_string(tcx, &place);
1541 let capture_kind_str = match capture_info.capture_kind {
1542 ty::UpvarCapture::ByValue(_) => "ByValue".into(),
1543 ty::UpvarCapture::ByRef(borrow) => format!("{:?}", borrow.kind),
1546 format!("{} captured as {} here", place_str, capture_kind_str)
1549 fn construct_path_string(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
1550 let place_str = construct_place_string(tcx, &place);
1552 format!("{} used here", place_str)
1555 fn construct_capture_info_string(
1557 place: &Place<'tcx>,
1558 capture_info: &ty::CaptureInfo<'tcx>,
1560 let place_str = construct_place_string(tcx, &place);
1562 let capture_kind_str = match capture_info.capture_kind {
1563 ty::UpvarCapture::ByValue(_) => "ByValue".into(),
1564 ty::UpvarCapture::ByRef(borrow) => format!("{:?}", borrow.kind),
1566 format!("{} -> {}", place_str, capture_kind_str)
1569 fn var_name(tcx: TyCtxt<'_>, var_hir_id: hir::HirId) -> Symbol {
1570 tcx.hir().name(var_hir_id)
1573 fn should_do_migration_analysis(tcx: TyCtxt<'_>, closure_id: hir::HirId) -> bool {
1575 tcx.lint_level_at_node(lint::builtin::DISJOINT_CAPTURE_DROP_REORDER, closure_id);
1577 !matches!(level, lint::Level::Allow)
1580 fn migration_suggestion_for_2229(tcx: TyCtxt<'_>, need_migrations: &Vec<hir::HirId>) -> String {
1581 let need_migrations_strings =
1582 need_migrations.iter().map(|v| format!("{}", var_name(tcx, *v))).collect::<Vec<_>>();
1583 let migrations_list_concat = need_migrations_strings.join(", ");
1585 format!("drop(&({}));", migrations_list_concat)
1588 /// Helper function to determine if we need to escalate CaptureKind from
1589 /// CaptureInfo A to B and returns the escalated CaptureInfo.
1590 /// (Note: CaptureInfo contains CaptureKind and an expression that led to capture it in that way)
1592 /// If both `CaptureKind`s are considered equivalent, then the CaptureInfo is selected based
1593 /// on the `CaptureInfo` containing an associated `capture_kind_expr_id`.
1595 /// It is the caller's duty to figure out which path_expr_id to use.
1597 /// If both the CaptureKind and Expression are considered to be equivalent,
1598 /// then `CaptureInfo` A is preferred. This can be useful in cases where we want to priortize
1599 /// expressions reported back to the user as part of diagnostics based on which appears earlier
1600 /// in the closure. This can be acheived simply by calling
1601 /// `determine_capture_info(existing_info, current_info)`. This works out because the
1602 /// expressions that occur earlier in the closure body than the current expression are processed before.
1603 /// Consider the following example
1605 /// struct Point { x: i32, y: i32 }
1606 /// let mut p: Point { x: 10, y: 10 };
1614 /// p.x += 10; // E2
1618 /// `CaptureKind` associated with both `E1` and `E2` will be ByRef(MutBorrow),
1619 /// and both have an expression associated, however for diagnostics we prefer reporting
1620 /// `E1` since it appears earlier in the closure body. When `E2` is being processed we
1621 /// would've already handled `E1`, and have an existing capture_information for it.
1622 /// Calling `determine_capture_info(existing_info_e1, current_info_e2)` will return
1623 /// `existing_info_e1` in this case, allowing us to point to `E1` in case of diagnostics.
1624 fn determine_capture_info(
1625 capture_info_a: ty::CaptureInfo<'tcx>,
1626 capture_info_b: ty::CaptureInfo<'tcx>,
1627 ) -> ty::CaptureInfo<'tcx> {
1628 // If the capture kind is equivalent then, we don't need to escalate and can compare the
1630 let eq_capture_kind = match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
1631 (ty::UpvarCapture::ByValue(_), ty::UpvarCapture::ByValue(_)) => {
1632 // We don't need to worry about the spans being ignored here.
1634 // The expr_id in capture_info corresponds to the span that is stored within
1635 // ByValue(span) and therefore it gets handled with priortizing based on
1636 // expressions below.
1639 (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => {
1640 ref_a.kind == ref_b.kind
1642 (ty::UpvarCapture::ByValue(_), _) | (ty::UpvarCapture::ByRef(_), _) => false,
1645 if eq_capture_kind {
1646 match (capture_info_a.capture_kind_expr_id, capture_info_b.capture_kind_expr_id) {
1647 (Some(_), _) | (None, None) => capture_info_a,
1648 (None, Some(_)) => capture_info_b,
1651 // We select the CaptureKind which ranks higher based the following priority order:
1652 // ByValue > MutBorrow > UniqueImmBorrow > ImmBorrow
1653 match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
1654 (ty::UpvarCapture::ByValue(_), _) => capture_info_a,
1655 (_, ty::UpvarCapture::ByValue(_)) => capture_info_b,
1656 (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => {
1657 match (ref_a.kind, ref_b.kind) {
1659 (ty::UniqueImmBorrow | ty::MutBorrow, ty::ImmBorrow)
1660 | (ty::MutBorrow, ty::UniqueImmBorrow) => capture_info_a,
1663 (ty::ImmBorrow, ty::UniqueImmBorrow | ty::MutBorrow)
1664 | (ty::UniqueImmBorrow, ty::MutBorrow) => capture_info_b,
1666 (ty::ImmBorrow, ty::ImmBorrow)
1667 | (ty::UniqueImmBorrow, ty::UniqueImmBorrow)
1668 | (ty::MutBorrow, ty::MutBorrow) => {
1669 bug!("Expected unequal capture kinds");
1677 /// Determines the Ancestry relationship of Place A relative to Place B
1679 /// `PlaceAncestryRelation::Ancestor` implies Place A is ancestor of Place B
1680 /// `PlaceAncestryRelation::Descendant` implies Place A is descendant of Place B
1681 /// `PlaceAncestryRelation::Divergent` implies neither of them is the ancestor of the other.
1682 fn determine_place_ancestry_relation(
1683 place_a: &Place<'tcx>,
1684 place_b: &Place<'tcx>,
1685 ) -> PlaceAncestryRelation {
1686 // If Place A and Place B, don't start off from the same root variable, they are divergent.
1687 if place_a.base != place_b.base {
1688 return PlaceAncestryRelation::Divergent;
1691 // Assume of length of projections_a = n
1692 let projections_a = &place_a.projections;
1694 // Assume of length of projections_b = m
1695 let projections_b = &place_b.projections;
1697 let mut same_initial_projections = true;
1699 for (proj_a, proj_b) in projections_a.iter().zip(projections_b.iter()) {
1700 if proj_a != proj_b {
1701 same_initial_projections = false;
1706 if same_initial_projections {
1707 // First min(n, m) projections are the same
1708 // Select Ancestor/Descendant
1709 if projections_b.len() >= projections_a.len() {
1710 PlaceAncestryRelation::Ancestor
1712 PlaceAncestryRelation::Descendant
1715 PlaceAncestryRelation::Divergent