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;
37 use rustc_errors::Applicability;
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::mir::FakeReadCause;
45 use rustc_middle::ty::{self, TraitRef, Ty, TyCtxt, TypeckResults, UpvarSubsts};
46 use rustc_session::lint;
48 use rustc_span::{MultiSpan, Span, Symbol};
49 use rustc_trait_selection::traits::{Obligation, ObligationCause};
51 use rustc_data_structures::stable_set::FxHashSet;
52 use rustc_index::vec::Idx;
53 use rustc_target::abi::VariantIdx;
57 /// Describe the relationship between the paths of two places
59 /// - `foo` is ancestor of `foo.bar.baz`
60 /// - `foo.bar.baz` is an descendant of `foo.bar`
61 /// - `foo.bar` and `foo.baz` are divergent
62 enum PlaceAncestryRelation {
68 /// Intermediate format to store a captured `Place` and associated `ty::CaptureInfo`
69 /// during capture analysis. Information in this map feeds into the minimum capture
71 type InferredCaptureInformation<'tcx> = FxIndexMap<Place<'tcx>, ty::CaptureInfo<'tcx>>;
73 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
74 pub fn closure_analyze(&self, body: &'tcx hir::Body<'tcx>) {
75 InferBorrowKindVisitor { fcx: self }.visit_body(body);
77 // it's our job to process these.
78 assert!(self.deferred_call_resolutions.borrow().is_empty());
82 struct InferBorrowKindVisitor<'a, 'tcx> {
83 fcx: &'a FnCtxt<'a, 'tcx>,
86 impl<'a, 'tcx> Visitor<'tcx> for InferBorrowKindVisitor<'a, 'tcx> {
87 type Map = intravisit::ErasedMap<'tcx>;
89 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
90 NestedVisitorMap::None
93 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
94 if let hir::ExprKind::Closure(cc, _, body_id, _, _) = expr.kind {
95 let body = self.fcx.tcx.hir().body(body_id);
96 self.visit_body(body);
97 self.fcx.analyze_closure(expr.hir_id, expr.span, body_id, body, cc);
100 intravisit::walk_expr(self, expr);
104 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
105 /// Analysis starting point.
108 closure_hir_id: hir::HirId,
110 body_id: hir::BodyId,
111 body: &'tcx hir::Body<'tcx>,
112 capture_clause: hir::CaptureBy,
114 debug!("analyze_closure(id={:?}, body.id={:?})", closure_hir_id, body.id());
116 // Extract the type of the closure.
117 let ty = self.node_ty(closure_hir_id);
118 let (closure_def_id, substs) = match *ty.kind() {
119 ty::Closure(def_id, substs) => (def_id, UpvarSubsts::Closure(substs)),
120 ty::Generator(def_id, substs, _) => (def_id, UpvarSubsts::Generator(substs)),
122 // #51714: skip analysis when we have already encountered type errors
128 "type of closure expr {:?} is not a closure {:?}",
135 let infer_kind = if let UpvarSubsts::Closure(closure_substs) = substs {
136 self.closure_kind(closure_substs).is_none().then_some(closure_substs)
141 let local_def_id = closure_def_id.expect_local();
143 let body_owner_def_id = self.tcx.hir().body_owner_def_id(body.id());
144 assert_eq!(body_owner_def_id.to_def_id(), closure_def_id);
145 let mut delegate = InferBorrowKind {
150 current_closure_kind: ty::ClosureKind::LATTICE_BOTTOM,
151 current_origin: None,
152 capture_information: Default::default(),
153 fake_reads: Default::default(),
155 euv::ExprUseVisitor::new(
160 &self.typeck_results.borrow(),
165 "For closure={:?}, capture_information={:#?}",
166 closure_def_id, delegate.capture_information
168 self.log_capture_analysis_first_pass(closure_def_id, &delegate.capture_information, span);
170 self.compute_min_captures(closure_def_id, delegate.capture_information);
172 let closure_hir_id = self.tcx.hir().local_def_id_to_hir_id(local_def_id);
174 if should_do_disjoint_capture_migration_analysis(self.tcx, closure_hir_id) {
175 self.perform_2229_migration_anaysis(closure_def_id, body_id, capture_clause, span);
178 // We now fake capture information for all variables that are mentioned within the closure
179 // We do this after handling migrations so that min_captures computes before
180 if !self.tcx.features().capture_disjoint_fields {
181 let mut capture_information: InferredCaptureInformation<'tcx> = Default::default();
183 if let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) {
184 for var_hir_id in upvars.keys() {
185 let place = self.place_for_root_variable(local_def_id, *var_hir_id);
187 debug!("seed place {:?}", place);
189 let upvar_id = ty::UpvarId::new(*var_hir_id, local_def_id);
191 self.init_capture_kind_for_place(&place, capture_clause, upvar_id, span);
192 let fake_info = ty::CaptureInfo {
193 capture_kind_expr_id: None,
198 capture_information.insert(place, fake_info);
202 // This will update the min captures based on this new fake information.
203 self.compute_min_captures(closure_def_id, capture_information);
206 if let Some(closure_substs) = infer_kind {
207 // Unify the (as yet unbound) type variable in the closure
208 // substs with the kind we inferred.
209 let inferred_kind = delegate.current_closure_kind;
210 let closure_kind_ty = closure_substs.as_closure().kind_ty();
211 self.demand_eqtype(span, inferred_kind.to_ty(self.tcx), closure_kind_ty);
213 // If we have an origin, store it.
214 if let Some(origin) = delegate.current_origin.clone() {
215 let origin = if self.tcx.features().capture_disjoint_fields {
216 (origin.0, restrict_capture_precision(origin.1))
218 (origin.0, Place { projections: vec![], ..origin.1 })
223 .closure_kind_origins_mut()
224 .insert(closure_hir_id, origin);
228 self.log_closure_min_capture_info(closure_def_id, span);
230 // Now that we've analyzed the closure, we know how each
231 // variable is borrowed, and we know what traits the closure
232 // implements (Fn vs FnMut etc). We now have some updates to do
233 // with that information.
235 // Note that no closure type C may have an upvar of type C
236 // (though it may reference itself via a trait object). This
237 // results from the desugaring of closures to a struct like
238 // `Foo<..., UV0...UVn>`. If one of those upvars referenced
239 // C, then the type would have infinite size (and the
240 // inference algorithm will reject it).
242 // Equate the type variables for the upvars with the actual types.
243 let final_upvar_tys = self.final_upvar_tys(closure_def_id);
245 "analyze_closure: id={:?} substs={:?} final_upvar_tys={:?}",
246 closure_hir_id, substs, final_upvar_tys
249 // Build a tuple (U0..Un) of the final upvar types U0..Un
250 // and unify the upvar tupe type in the closure with it:
251 let final_tupled_upvars_type = self.tcx.mk_tup(final_upvar_tys.iter());
252 self.demand_suptype(span, substs.tupled_upvars_ty(), final_tupled_upvars_type);
254 let fake_reads = delegate
257 .map(|(place, cause, hir_id)| (place, cause, hir_id))
259 self.typeck_results.borrow_mut().closure_fake_reads.insert(closure_def_id, fake_reads);
261 // If we are also inferred the closure kind here,
262 // process any deferred resolutions.
263 let deferred_call_resolutions = self.remove_deferred_call_resolutions(closure_def_id);
264 for deferred_call_resolution in deferred_call_resolutions {
265 deferred_call_resolution.resolve(self);
269 // Returns a list of `Ty`s for each upvar.
270 fn final_upvar_tys(&self, closure_id: DefId) -> Vec<Ty<'tcx>> {
271 // Presently an unboxed closure type cannot "escape" out of a
272 // function, so we will only encounter ones that originated in the
273 // local crate or were inlined into it along with some function.
274 // This may change if abstract return types of some sort are
278 .closure_min_captures_flattened(closure_id)
279 .map(|captured_place| {
280 let upvar_ty = captured_place.place.ty();
281 let capture = captured_place.info.capture_kind;
284 "final_upvar_tys: place={:?} upvar_ty={:?} capture={:?}, mutability={:?}",
285 captured_place.place, upvar_ty, capture, captured_place.mutability,
289 ty::UpvarCapture::ByValue(_) => upvar_ty,
290 ty::UpvarCapture::ByRef(borrow) => self.tcx.mk_ref(
292 ty::TypeAndMut { ty: upvar_ty, mutbl: borrow.kind.to_mutbl_lossy() },
299 /// Analyzes the information collected by `InferBorrowKind` to compute the min number of
300 /// Places (and corresponding capture kind) that we need to keep track of to support all
301 /// the required captured paths.
304 /// Note: If this function is called multiple times for the same closure, it will update
305 /// the existing min_capture map that is stored in TypeckResults.
309 /// struct Point { x: i32, y: i32 }
311 /// let s: String; // hir_id_s
312 /// let mut p: Point; // his_id_p
314 /// println!("{}", s); // L1
316 /// println!("{}" , p.y) // L3
317 /// println!("{}", p) // L4
321 /// and let hir_id_L1..5 be the expressions pointing to use of a captured variable on
322 /// the lines L1..5 respectively.
324 /// InferBorrowKind results in a structure like this:
328 /// Place(base: hir_id_s, projections: [], ....) -> {
329 /// capture_kind_expr: hir_id_L5,
330 /// path_expr_id: hir_id_L5,
331 /// capture_kind: ByValue
333 /// Place(base: hir_id_p, projections: [Field(0, 0)], ...) -> {
334 /// capture_kind_expr: hir_id_L2,
335 /// path_expr_id: hir_id_L2,
336 /// capture_kind: ByValue
338 /// Place(base: hir_id_p, projections: [Field(1, 0)], ...) -> {
339 /// capture_kind_expr: hir_id_L3,
340 /// path_expr_id: hir_id_L3,
341 /// capture_kind: ByValue
343 /// Place(base: hir_id_p, projections: [], ...) -> {
344 /// capture_kind_expr: hir_id_L4,
345 /// path_expr_id: hir_id_L4,
346 /// capture_kind: ByValue
350 /// After the min capture analysis, we get:
354 /// Place(base: hir_id_s, projections: [], ....) -> {
355 /// capture_kind_expr: hir_id_L5,
356 /// path_expr_id: hir_id_L5,
357 /// capture_kind: ByValue
361 /// Place(base: hir_id_p, projections: [], ...) -> {
362 /// capture_kind_expr: hir_id_L2,
363 /// path_expr_id: hir_id_L4,
364 /// capture_kind: ByValue
368 fn compute_min_captures(
370 closure_def_id: DefId,
371 capture_information: InferredCaptureInformation<'tcx>,
373 if capture_information.is_empty() {
377 let mut typeck_results = self.typeck_results.borrow_mut();
379 let mut root_var_min_capture_list =
380 typeck_results.closure_min_captures.remove(&closure_def_id).unwrap_or_default();
382 for (place, capture_info) in capture_information.into_iter() {
383 let var_hir_id = match place.base {
384 PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
385 base => bug!("Expected upvar, found={:?}", base),
388 let place = restrict_capture_precision(place);
390 let min_cap_list = match root_var_min_capture_list.get_mut(&var_hir_id) {
392 let mutability = self.determine_capture_mutability(&typeck_results, &place);
394 vec![ty::CapturedPlace { place, info: capture_info, mutability }];
395 root_var_min_capture_list.insert(var_hir_id, min_cap_list);
398 Some(min_cap_list) => min_cap_list,
401 // Go through each entry in the current list of min_captures
402 // - if ancestor is found, update it's capture kind to account for current place's
403 // capture information.
405 // - if descendant is found, remove it from the list, and update the current place's
406 // capture information to account for the descendants's capture kind.
408 // We can never be in a case where the list contains both an ancestor and a descendant
409 // Also there can only be ancestor but in case of descendants there might be
412 let mut descendant_found = false;
413 let mut updated_capture_info = capture_info;
414 min_cap_list.retain(|possible_descendant| {
415 match determine_place_ancestry_relation(&place, &possible_descendant.place) {
416 // current place is ancestor of possible_descendant
417 PlaceAncestryRelation::Ancestor => {
418 descendant_found = true;
419 let backup_path_expr_id = updated_capture_info.path_expr_id;
421 updated_capture_info =
422 determine_capture_info(updated_capture_info, possible_descendant.info);
424 // we need to keep the ancestor's `path_expr_id`
425 updated_capture_info.path_expr_id = backup_path_expr_id;
433 let mut ancestor_found = false;
434 if !descendant_found {
435 for possible_ancestor in min_cap_list.iter_mut() {
436 match determine_place_ancestry_relation(&place, &possible_ancestor.place) {
437 // current place is descendant of possible_ancestor
438 PlaceAncestryRelation::Descendant => {
439 ancestor_found = true;
440 let backup_path_expr_id = possible_ancestor.info.path_expr_id;
441 possible_ancestor.info =
442 determine_capture_info(possible_ancestor.info, capture_info);
444 // we need to keep the ancestor's `path_expr_id`
445 possible_ancestor.info.path_expr_id = backup_path_expr_id;
447 // Only one ancestor of the current place will be in the list.
455 // Only need to insert when we don't have an ancestor in the existing min capture list
457 let mutability = self.determine_capture_mutability(&typeck_results, &place);
459 ty::CapturedPlace { place, info: updated_capture_info, mutability };
460 min_cap_list.push(captured_place);
464 debug!("For closure={:?}, min_captures={:#?}", closure_def_id, root_var_min_capture_list);
465 typeck_results.closure_min_captures.insert(closure_def_id, root_var_min_capture_list);
468 /// Perform the migration analysis for RFC 2229, and emit lint
469 /// `disjoint_capture_drop_reorder` if needed.
470 fn perform_2229_migration_anaysis(
472 closure_def_id: DefId,
473 body_id: hir::BodyId,
474 capture_clause: hir::CaptureBy,
477 let (need_migrations, reasons) = self.compute_2229_migrations(
481 self.typeck_results.borrow().closure_min_captures.get(&closure_def_id),
484 if !need_migrations.is_empty() {
485 let (migration_string, migrated_variables_concat) =
486 migration_suggestion_for_2229(self.tcx, &need_migrations);
488 let local_def_id = closure_def_id.expect_local();
489 let closure_hir_id = self.tcx.hir().local_def_id_to_hir_id(local_def_id);
490 self.tcx.struct_span_lint_hir(
491 lint::builtin::DISJOINT_CAPTURE_MIGRATION,
495 let mut diagnostics_builder = lint.build(
497 "{} affected for closure because of `capture_disjoint_fields`",
502 let closure_body_span = self.tcx.hir().span(body_id.hir_id);
504 match self.tcx.sess.source_map().span_to_snippet(closure_body_span) {
506 let trimmed = s.trim_start();
508 // If the closure contains a block then replace the opening brace
509 // with "{ let _ = (..); "
510 let sugg = if let Some('{') = trimmed.chars().next() {
511 format!("{{ {}; {}", migration_string, &trimmed[1..])
513 format!("{{ {}; {} }}", migration_string, s)
515 (sugg, Applicability::MachineApplicable)
517 Err(_) => (migration_string.clone(), Applicability::HasPlaceholders),
520 let diagnostic_msg = format!(
521 "add a dummy let to cause {} to be fully captured",
522 migrated_variables_concat
525 diagnostics_builder.span_suggestion(
531 diagnostics_builder.emit();
537 /// Combines all the reasons for 2229 migrations
538 fn compute_2229_migrations_reasons(
540 auto_trait_reasons: FxHashSet<&str>,
543 let mut reasons = String::new();
545 if auto_trait_reasons.len() > 0 {
547 "{} trait implementation",
548 auto_trait_reasons.clone().into_iter().collect::<Vec<&str>>().join(", ")
552 if auto_trait_reasons.len() > 0 && drop_reason {
553 reasons = format!("{}, and ", reasons);
557 reasons = format!("{}drop order", reasons);
563 /// Returns true if `ty` may implement `trait_def_id`
567 cause: &ObligationCause<'tcx>,
570 use crate::rustc_middle::ty::ToPredicate;
571 use crate::rustc_middle::ty::WithConstness;
572 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
573 let tcx = self.infcx.tcx;
575 let trait_ref = TraitRef { def_id: trait_def_id, substs: tcx.mk_substs_trait(ty, &[]) };
577 let obligation = Obligation::new(
580 trait_ref.without_const().to_predicate(tcx),
583 self.infcx.predicate_may_hold(&obligation)
586 /// Returns true if migration is needed for trait for the provided var_hir_id
587 fn need_2229_migrations_for_trait(
589 min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
590 var_hir_id: hir::HirId,
591 check_trait: Option<DefId>,
593 let root_var_min_capture_list = if let Some(root_var_min_capture_list) =
594 min_captures.and_then(|m| m.get(&var_hir_id))
596 root_var_min_capture_list
601 let ty = self.infcx.resolve_vars_if_possible(self.node_ty(var_hir_id));
603 let cause = ObligationCause::misc(self.tcx.hir().span(var_hir_id), self.body_id);
605 let obligation_should_hold = check_trait
606 .map(|check_trait| self.ty_impls_trait(ty, &cause, check_trait))
609 // Check whether catpured fields also implement the trait
611 for capture in root_var_min_capture_list.iter() {
612 let ty = capture.place.ty();
614 let obligation_holds_for_capture = check_trait
615 .map(|check_trait| self.ty_impls_trait(ty, &cause, check_trait))
618 if !obligation_holds_for_capture && obligation_should_hold {
625 /// Figures out the list of root variables (and their types) that aren't completely
626 /// captured by the closure when `capture_disjoint_fields` is enabled and auto-traits
627 /// differ between the root variable and the captured paths.
629 /// The output list would include a root variable if:
630 /// - It would have been captured into the closure when `capture_disjoint_fields` wasn't
632 /// - It wasn't completely captured by the closure, **and**
633 /// - One of the paths captured does not implement all the auto-traits its root variable
635 fn compute_2229_migrations_for_trait(
637 min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
638 var_hir_id: hir::HirId,
639 ) -> Option<FxHashSet<&str>> {
640 let tcx = self.infcx.tcx;
642 // Check whether catpured fields also implement the trait
643 let mut auto_trait_reasons = FxHashSet::default();
645 if self.need_2229_migrations_for_trait(
648 tcx.lang_items().clone_trait(),
650 auto_trait_reasons.insert("`Clone`");
653 if self.need_2229_migrations_for_trait(
656 tcx.lang_items().sync_trait(),
658 auto_trait_reasons.insert("`Sync`");
661 if self.need_2229_migrations_for_trait(
664 tcx.lang_items().send_trait(),
666 auto_trait_reasons.insert("`Send`");
669 if self.need_2229_migrations_for_trait(
672 tcx.lang_items().unpin_trait(),
674 auto_trait_reasons.insert("`Unpin`");
677 if self.need_2229_migrations_for_trait(
680 tcx.lang_items().unwind_safe_trait(),
682 auto_trait_reasons.insert("`UnwindSafe`");
685 if self.need_2229_migrations_for_trait(
688 tcx.lang_items().ref_unwind_safe_trait(),
690 auto_trait_reasons.insert("`RefUnwindSafe`");
693 if auto_trait_reasons.len() > 0 {
694 return Some(auto_trait_reasons);
700 /// Figures out the list of root variables (and their types) that aren't completely
701 /// captured by the closure when `capture_disjoint_fields` is enabled and drop order of
702 /// some path starting at that root variable **might** be affected.
704 /// The output list would include a root variable if:
705 /// - It would have been moved into the closure when `capture_disjoint_fields` wasn't
707 /// - It wasn't completely captured by the closure, **and**
708 /// - One of the paths starting at this root variable, that is not captured needs Drop.
710 /// This function only returns true for significant drops. A type is considerent to have a
711 /// significant drop if it's Drop implementation is not annotated by `rustc_insignificant_dtor`.
712 fn compute_2229_migrations_for_drop(
714 closure_def_id: DefId,
716 min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
717 closure_clause: hir::CaptureBy,
718 var_hir_id: hir::HirId,
720 let ty = self.infcx.resolve_vars_if_possible(self.node_ty(var_hir_id));
722 if !ty.has_significant_drop(self.tcx, self.tcx.param_env(closure_def_id.expect_local())) {
726 let root_var_min_capture_list = if let Some(root_var_min_capture_list) =
727 min_captures.and_then(|m| m.get(&var_hir_id))
729 root_var_min_capture_list
731 // The upvar is mentioned within the closure but no path starting from it is
734 match closure_clause {
735 // Only migrate if closure is a move closure
736 hir::CaptureBy::Value => return true,
737 hir::CaptureBy::Ref => {}
743 let projections_list = root_var_min_capture_list
745 .filter_map(|captured_place| match captured_place.info.capture_kind {
746 // Only care about captures that are moved into the closure
747 ty::UpvarCapture::ByValue(..) => Some(captured_place.place.projections.as_slice()),
748 ty::UpvarCapture::ByRef(..) => None,
750 .collect::<Vec<_>>();
752 let is_moved = !projections_list.is_empty();
754 let is_not_completely_captured =
755 root_var_min_capture_list.iter().any(|capture| capture.place.projections.len() > 0);
758 && is_not_completely_captured
759 && self.has_significant_drop_outside_of_captures(
772 /// Figures out the list of root variables (and their types) that aren't completely
773 /// captured by the closure when `capture_disjoint_fields` is enabled and either drop
774 /// order of some path starting at that root variable **might** be affected or auto-traits
775 /// differ between the root variable and the captured paths.
777 /// The output list would include a root variable if:
778 /// - It would have been moved into the closure when `capture_disjoint_fields` wasn't
780 /// - It wasn't completely captured by the closure, **and**
781 /// - One of the paths starting at this root variable, that is not captured needs Drop **or**
782 /// - One of the paths captured does not implement all the auto-traits its root variable
785 /// Returns a tuple containing a vector of HirIds as well as a String containing the reason
786 /// why root variables whose HirId is contained in the vector should be fully captured.
787 fn compute_2229_migrations(
789 closure_def_id: DefId,
791 closure_clause: hir::CaptureBy,
792 min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
793 ) -> (Vec<hir::HirId>, String) {
794 let upvars = if let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) {
797 return (Vec::new(), format!(""));
800 let mut need_migrations = Vec::new();
801 let mut auto_trait_reasons = FxHashSet::default();
802 let mut drop_reorder_reason = false;
804 // Perform auto-trait analysis
805 for (&var_hir_id, _) in upvars.iter() {
806 let mut need_migration = false;
807 if let Some(trait_migration_cause) =
808 self.compute_2229_migrations_for_trait(min_captures, var_hir_id)
810 need_migration = true;
811 auto_trait_reasons.extend(trait_migration_cause);
814 if self.compute_2229_migrations_for_drop(
821 need_migration = true;
822 drop_reorder_reason = true;
826 need_migrations.push(var_hir_id);
832 self.compute_2229_migrations_reasons(auto_trait_reasons, drop_reorder_reason),
836 /// This is a helper function to `compute_2229_migrations_precise_pass`. Provided the type
837 /// of a root variable and a list of captured paths starting at this root variable (expressed
838 /// using list of `Projection` slices), it returns true if there is a path that is not
839 /// captured starting at this root variable that implements Drop.
841 /// The way this function works is at a given call it looks at type `base_path_ty` of some base
842 /// path say P and then list of projection slices which represent the different captures moved
843 /// into the closure starting off of P.
845 /// This will make more sense with an example:
848 /// #![feature(capture_disjoint_fields)]
850 /// struct FancyInteger(i32); // This implements Drop
852 /// struct Point { x: FancyInteger, y: FancyInteger }
855 /// struct Wrapper { p: Point, c: Color }
857 /// fn f(w: Wrapper) {
859 /// // Closure captures w.p.x and w.c by move.
866 /// If `capture_disjoint_fields` wasn't enabled the closure would've moved `w` instead of the
867 /// precise paths. If we look closely `w.p.y` isn't captured which implements Drop and
868 /// therefore Drop ordering would change and we want this function to return true.
870 /// Call stack to figure out if we need to migrate for `w` would look as follows:
872 /// Our initial base path is just `w`, and the paths captured from it are `w[p, x]` and
875 /// - Ty(place): Type of place
876 /// - `(a, b)`: Represents the function parameters `base_path_ty` and `captured_by_move_projs`
879 /// (Ty(w), [ &[p, x], &[c] ])
881 /// ----------------------------
884 /// (Ty(w.p), [ &[x] ]) (Ty(w.c), [ &[] ]) // I(1)
887 /// (Ty(w.p), [ &[x] ]) false
890 /// -------------------------------
893 /// (Ty((w.p).x), [ &[] ]) (Ty((w.p).y), []) // IMP 2
896 /// false NeedsSignificantDrop(Ty(w.p.y))
902 /// IMP 1 `(Ty(w.c), [ &[] ])`: Notice the single empty slice inside `captured_projs`.
903 /// This implies that the `w.c` is completely captured by the closure.
904 /// Since drop for this path will be called when the closure is
905 /// dropped we don't need to migrate for it.
907 /// IMP 2 `(Ty((w.p).y), [])`: Notice that `captured_projs` is empty. This implies that this
908 /// path wasn't captured by the closure. Also note that even
909 /// though we didn't capture this path, the function visits it,
910 /// which is kind of the point of this function. We then return
911 /// if the type of `w.p.y` implements Drop, which in this case is
914 /// Consider another example:
918 /// impl Drop for X {}
921 /// impl Drop for Y {}
925 /// let c = || move(y.0);
929 /// Note that `y.0` is captured by the closure. When this function is called for `y`, it will
930 /// return true, because even though all paths starting at `y` are captured, `y` itself
931 /// implements Drop which will be affected since `y` isn't completely captured.
932 fn has_significant_drop_outside_of_captures(
934 closure_def_id: DefId,
936 base_path_ty: Ty<'tcx>,
937 captured_by_move_projs: Vec<&[Projection<'tcx>]>,
939 let needs_drop = |ty: Ty<'tcx>| {
940 ty.has_significant_drop(self.tcx, self.tcx.param_env(closure_def_id.expect_local()))
943 let is_drop_defined_for_ty = |ty: Ty<'tcx>| {
944 let drop_trait = self.tcx.require_lang_item(hir::LangItem::Drop, Some(closure_span));
945 let ty_params = self.tcx.mk_substs_trait(base_path_ty, &[]);
946 self.tcx.type_implements_trait((
950 self.tcx.param_env(closure_def_id.expect_local()),
954 let is_drop_defined_for_ty = is_drop_defined_for_ty(base_path_ty);
956 // If there is a case where no projection is applied on top of current place
957 // then there must be exactly one capture corresponding to such a case. Note that this
958 // represents the case of the path being completely captured by the variable.
960 // eg. If `a.b` is captured and we are processing `a.b`, then we can't have the closure also
961 // capture `a.b.c`, because that voilates min capture.
962 let is_completely_captured = captured_by_move_projs.iter().any(|projs| projs.is_empty());
964 assert!(!is_completely_captured || (captured_by_move_projs.len() == 1));
966 if is_completely_captured {
967 // The place is captured entirely, so doesn't matter if needs dtor, it will be drop
968 // when the closure is dropped.
972 if captured_by_move_projs.is_empty() {
973 return needs_drop(base_path_ty);
976 if is_drop_defined_for_ty {
977 // If drop is implemented for this type then we need it to be fully captured,
978 // and we know it is not completely captured because of the previous checks.
980 // Note that this is a bug in the user code that will be reported by the
981 // borrow checker, since we can't move out of drop types.
983 // The bug exists in the user's code pre-migration, and we don't migrate here.
987 match base_path_ty.kind() {
989 // - `captured_by_move_projs` is not empty. Therefore we can call
990 // `captured_by_move_projs.first().unwrap()` safely.
991 // - All entries in `captured_by_move_projs` have atleast one projection.
992 // Therefore we can call `captured_by_move_projs.first().unwrap().first().unwrap()` safely.
994 // We don't capture derefs in case of move captures, which would have be applied to
995 // access any further paths.
996 ty::Adt(def, _) if def.is_box() => unreachable!(),
997 ty::Ref(..) => unreachable!(),
998 ty::RawPtr(..) => unreachable!(),
1000 ty::Adt(def, substs) => {
1001 // Multi-varaint enums are captured in entirety,
1002 // which would've been handled in the case of single empty slice in `captured_by_move_projs`.
1003 assert_eq!(def.variants.len(), 1);
1005 // Only Field projections can be applied to a non-box Adt.
1007 captured_by_move_projs.iter().all(|projs| matches!(
1008 projs.first().unwrap().kind,
1009 ProjectionKind::Field(..)
1012 def.variants.get(VariantIdx::new(0)).unwrap().fields.iter().enumerate().any(
1014 let paths_using_field = captured_by_move_projs
1016 .filter_map(|projs| {
1017 if let ProjectionKind::Field(field_idx, _) =
1018 projs.first().unwrap().kind
1020 if (field_idx as usize) == i { Some(&projs[1..]) } else { None }
1027 let after_field_ty = field.ty(self.tcx, substs);
1028 self.has_significant_drop_outside_of_captures(
1039 // Only Field projections can be applied to a tuple.
1041 captured_by_move_projs.iter().all(|projs| matches!(
1042 projs.first().unwrap().kind,
1043 ProjectionKind::Field(..)
1047 base_path_ty.tuple_fields().enumerate().any(|(i, element_ty)| {
1048 let paths_using_field = captured_by_move_projs
1050 .filter_map(|projs| {
1051 if let ProjectionKind::Field(field_idx, _) = projs.first().unwrap().kind
1053 if (field_idx as usize) == i { Some(&projs[1..]) } else { None }
1060 self.has_significant_drop_outside_of_captures(
1069 // Anything else would be completely captured and therefore handled already.
1070 _ => unreachable!(),
1074 fn init_capture_kind_for_place(
1076 place: &Place<'tcx>,
1077 capture_clause: hir::CaptureBy,
1078 upvar_id: ty::UpvarId,
1080 ) -> ty::UpvarCapture<'tcx> {
1081 match capture_clause {
1082 // In case of a move closure if the data is accessed through a reference we
1083 // want to capture by ref to allow precise capture using reborrows.
1085 // If the data will be moved out of this place, then the place will be truncated
1086 // at the first Deref in `adjust_upvar_borrow_kind_for_consume` and then moved into
1088 hir::CaptureBy::Value if !place.deref_tys().any(ty::TyS::is_ref) => {
1089 ty::UpvarCapture::ByValue(None)
1091 hir::CaptureBy::Value | hir::CaptureBy::Ref => {
1092 let origin = UpvarRegion(upvar_id, closure_span);
1093 let upvar_region = self.next_region_var(origin);
1094 let upvar_borrow = ty::UpvarBorrow { kind: ty::ImmBorrow, region: upvar_region };
1095 ty::UpvarCapture::ByRef(upvar_borrow)
1100 fn place_for_root_variable(
1102 closure_def_id: LocalDefId,
1103 var_hir_id: hir::HirId,
1105 let upvar_id = ty::UpvarId::new(var_hir_id, closure_def_id);
1108 base_ty: self.node_ty(var_hir_id),
1109 base: PlaceBase::Upvar(upvar_id),
1110 projections: Default::default(),
1114 fn should_log_capture_analysis(&self, closure_def_id: DefId) -> bool {
1115 self.tcx.has_attr(closure_def_id, sym::rustc_capture_analysis)
1118 fn log_capture_analysis_first_pass(
1120 closure_def_id: rustc_hir::def_id::DefId,
1121 capture_information: &FxIndexMap<Place<'tcx>, ty::CaptureInfo<'tcx>>,
1124 if self.should_log_capture_analysis(closure_def_id) {
1126 self.tcx.sess.struct_span_err(closure_span, "First Pass analysis includes:");
1127 for (place, capture_info) in capture_information {
1128 let capture_str = construct_capture_info_string(self.tcx, place, capture_info);
1129 let output_str = format!("Capturing {}", capture_str);
1132 capture_info.path_expr_id.map_or(closure_span, |e| self.tcx.hir().span(e));
1133 diag.span_note(span, &output_str);
1139 fn log_closure_min_capture_info(&self, closure_def_id: DefId, closure_span: Span) {
1140 if self.should_log_capture_analysis(closure_def_id) {
1141 if let Some(min_captures) =
1142 self.typeck_results.borrow().closure_min_captures.get(&closure_def_id)
1145 self.tcx.sess.struct_span_err(closure_span, "Min Capture analysis includes:");
1147 for (_, min_captures_for_var) in min_captures {
1148 for capture in min_captures_for_var {
1149 let place = &capture.place;
1150 let capture_info = &capture.info;
1153 construct_capture_info_string(self.tcx, place, capture_info);
1154 let output_str = format!("Min Capture {}", capture_str);
1156 if capture.info.path_expr_id != capture.info.capture_kind_expr_id {
1157 let path_span = capture_info
1159 .map_or(closure_span, |e| self.tcx.hir().span(e));
1160 let capture_kind_span = capture_info
1161 .capture_kind_expr_id
1162 .map_or(closure_span, |e| self.tcx.hir().span(e));
1164 let mut multi_span: MultiSpan =
1165 MultiSpan::from_spans(vec![path_span, capture_kind_span]);
1167 let capture_kind_label =
1168 construct_capture_kind_reason_string(self.tcx, place, capture_info);
1169 let path_label = construct_path_string(self.tcx, place);
1171 multi_span.push_span_label(path_span, path_label);
1172 multi_span.push_span_label(capture_kind_span, capture_kind_label);
1174 diag.span_note(multi_span, &output_str);
1176 let span = capture_info
1178 .map_or(closure_span, |e| self.tcx.hir().span(e));
1180 diag.span_note(span, &output_str);
1189 /// A captured place is mutable if
1190 /// 1. Projections don't include a Deref of an immut-borrow, **and**
1191 /// 2. PlaceBase is mut or projections include a Deref of a mut-borrow.
1192 fn determine_capture_mutability(
1194 typeck_results: &'a TypeckResults<'tcx>,
1195 place: &Place<'tcx>,
1196 ) -> hir::Mutability {
1197 let var_hir_id = match place.base {
1198 PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
1199 _ => unreachable!(),
1202 let bm = *typeck_results.pat_binding_modes().get(var_hir_id).expect("missing binding mode");
1204 let mut is_mutbl = match bm {
1205 ty::BindByValue(mutability) => mutability,
1206 ty::BindByReference(_) => hir::Mutability::Not,
1209 for pointer_ty in place.deref_tys() {
1210 match pointer_ty.kind() {
1211 // We don't capture derefs of raw ptrs
1212 ty::RawPtr(_) => unreachable!(),
1214 // Derefencing a mut-ref allows us to mut the Place if we don't deref
1215 // an immut-ref after on top of this.
1216 ty::Ref(.., hir::Mutability::Mut) => is_mutbl = hir::Mutability::Mut,
1218 // The place isn't mutable once we dereference a immutable reference.
1219 ty::Ref(.., hir::Mutability::Not) => return hir::Mutability::Not,
1221 // Dereferencing a box doesn't change mutability
1222 ty::Adt(def, ..) if def.is_box() => {}
1224 unexpected_ty => bug!("deref of unexpected pointer type {:?}", unexpected_ty),
1232 /// Truncate the capture so that the place being borrowed is in accordance with RFC 1240,
1233 /// which states that it's unsafe to take a reference into a struct marked `repr(packed)`.
1234 fn restrict_repr_packed_field_ref_capture<'tcx>(
1236 param_env: ty::ParamEnv<'tcx>,
1237 place: &Place<'tcx>,
1239 let pos = place.projections.iter().enumerate().position(|(i, p)| {
1240 let ty = place.ty_before_projection(i);
1242 // Return true for fields of packed structs, unless those fields have alignment 1.
1244 ProjectionKind::Field(..) => match ty.kind() {
1245 ty::Adt(def, _) if def.repr.packed() => {
1246 match tcx.layout_raw(param_env.and(p.ty)) {
1247 Ok(layout) if layout.align.abi.bytes() == 1 => {
1248 // if the alignment is 1, the type can't be further
1251 "restrict_repr_packed_field_ref_capture: ({:?}) - align = 1",
1257 debug!("restrict_repr_packed_field_ref_capture: ({:?}) - true", place);
1269 let mut place = place.clone();
1271 if let Some(pos) = pos {
1272 place.projections.truncate(pos);
1278 struct InferBorrowKind<'a, 'tcx> {
1279 fcx: &'a FnCtxt<'a, 'tcx>,
1281 // The def-id of the closure whose kind and upvar accesses are being inferred.
1282 closure_def_id: DefId,
1286 capture_clause: hir::CaptureBy,
1288 // The kind that we have inferred that the current closure
1289 // requires. Note that we *always* infer a minimal kind, even if
1290 // we don't always *use* that in the final result (i.e., sometimes
1291 // we've taken the closure kind from the expectations instead, and
1292 // for generators we don't even implement the closure traits
1294 current_closure_kind: ty::ClosureKind,
1296 // If we modified `current_closure_kind`, this field contains a `Some()` with the
1297 // variable access that caused us to do so.
1298 current_origin: Option<(Span, Place<'tcx>)>,
1300 /// For each Place that is captured by the closure, we track the minimal kind of
1301 /// access we need (ref, ref mut, move, etc) and the expression that resulted in such access.
1303 /// Consider closure where s.str1 is captured via an ImmutableBorrow and
1304 /// s.str2 via a MutableBorrow
1307 /// struct SomeStruct { str1: String, str2: String }
1309 /// // Assume that the HirId for the variable definition is `V1`
1310 /// let mut s = SomeStruct { str1: format!("s1"), str2: format!("s2") }
1312 /// let fix_s = |new_s2| {
1313 /// // Assume that the HirId for the expression `s.str1` is `E1`
1314 /// println!("Updating SomeStruct with str1=", s.str1);
1315 /// // Assume that the HirId for the expression `*s.str2` is `E2`
1316 /// s.str2 = new_s2;
1320 /// For closure `fix_s`, (at a high level) the map contains
1323 /// Place { V1, [ProjectionKind::Field(Index=0, Variant=0)] } : CaptureKind { E1, ImmutableBorrow }
1324 /// Place { V1, [ProjectionKind::Field(Index=1, Variant=0)] } : CaptureKind { E2, MutableBorrow }
1326 capture_information: InferredCaptureInformation<'tcx>,
1327 fake_reads: Vec<(Place<'tcx>, FakeReadCause, hir::HirId)>,
1330 impl<'a, 'tcx> InferBorrowKind<'a, 'tcx> {
1331 fn adjust_upvar_borrow_kind_for_consume(
1333 place_with_id: &PlaceWithHirId<'tcx>,
1334 diag_expr_id: hir::HirId,
1335 mode: euv::ConsumeMode,
1338 "adjust_upvar_borrow_kind_for_consume(place_with_id={:?}, diag_expr_id={:?}, mode={:?})",
1339 place_with_id, diag_expr_id, mode
1342 match (self.capture_clause, mode) {
1343 // In non-move closures, we only care about moves
1344 (hir::CaptureBy::Ref, euv::Copy) => return,
1346 // We want to capture Copy types that read through a ref via a reborrow
1347 (hir::CaptureBy::Value, euv::Copy)
1348 if place_with_id.place.deref_tys().any(ty::TyS::is_ref) =>
1353 (hir::CaptureBy::Ref, euv::Move) | (hir::CaptureBy::Value, euv::Move | euv::Copy) => {}
1356 let place = truncate_capture_for_move(place_with_id.place.clone());
1357 let place_with_id = PlaceWithHirId { place: place.clone(), hir_id: place_with_id.hir_id };
1359 if !self.capture_information.contains_key(&place) {
1360 self.init_capture_info_for_place(&place_with_id, diag_expr_id);
1363 let tcx = self.fcx.tcx;
1364 let upvar_id = if let PlaceBase::Upvar(upvar_id) = place_with_id.place.base {
1370 debug!("adjust_upvar_borrow_kind_for_consume: upvar={:?}", upvar_id);
1372 let usage_span = tcx.hir().span(diag_expr_id);
1374 if matches!(mode, euv::Move) {
1375 // To move out of an upvar, this must be a FnOnce closure
1376 self.adjust_closure_kind(
1377 upvar_id.closure_expr_id,
1378 ty::ClosureKind::FnOnce,
1384 let capture_info = ty::CaptureInfo {
1385 capture_kind_expr_id: Some(diag_expr_id),
1386 path_expr_id: Some(diag_expr_id),
1387 capture_kind: ty::UpvarCapture::ByValue(Some(usage_span)),
1390 let curr_info = self.capture_information[&place_with_id.place];
1391 let updated_info = determine_capture_info(curr_info, capture_info);
1393 self.capture_information[&place_with_id.place] = updated_info;
1396 /// Indicates that `place_with_id` is being directly mutated (e.g., assigned
1397 /// to). If the place is based on a by-ref upvar, this implies that
1398 /// the upvar must be borrowed using an `&mut` borrow.
1399 fn adjust_upvar_borrow_kind_for_mut(
1401 place_with_id: &PlaceWithHirId<'tcx>,
1402 diag_expr_id: hir::HirId,
1405 "adjust_upvar_borrow_kind_for_mut(place_with_id={:?}, diag_expr_id={:?})",
1406 place_with_id, diag_expr_id
1409 if let PlaceBase::Upvar(_) = place_with_id.place.base {
1410 let mut borrow_kind = ty::MutBorrow;
1411 for pointer_ty in place_with_id.place.deref_tys() {
1412 match pointer_ty.kind() {
1413 // Raw pointers don't inherit mutability.
1414 ty::RawPtr(_) => return,
1415 // assignment to deref of an `&mut`
1416 // borrowed pointer implies that the
1417 // pointer itself must be unique, but not
1418 // necessarily *mutable*
1419 ty::Ref(.., hir::Mutability::Mut) => borrow_kind = ty::UniqueImmBorrow,
1423 self.adjust_upvar_deref(place_with_id, diag_expr_id, borrow_kind);
1427 fn adjust_upvar_borrow_kind_for_unique(
1429 place_with_id: &PlaceWithHirId<'tcx>,
1430 diag_expr_id: hir::HirId,
1433 "adjust_upvar_borrow_kind_for_unique(place_with_id={:?}, diag_expr_id={:?})",
1434 place_with_id, diag_expr_id
1437 if let PlaceBase::Upvar(_) = place_with_id.place.base {
1438 if place_with_id.place.deref_tys().any(ty::TyS::is_unsafe_ptr) {
1439 // Raw pointers don't inherit mutability.
1442 // for a borrowed pointer to be unique, its base must be unique
1443 self.adjust_upvar_deref(place_with_id, diag_expr_id, ty::UniqueImmBorrow);
1447 fn adjust_upvar_deref(
1449 place_with_id: &PlaceWithHirId<'tcx>,
1450 diag_expr_id: hir::HirId,
1451 borrow_kind: ty::BorrowKind,
1453 assert!(match borrow_kind {
1454 ty::MutBorrow => true,
1455 ty::UniqueImmBorrow => true,
1457 // imm borrows never require adjusting any kinds, so we don't wind up here
1458 ty::ImmBorrow => false,
1461 let tcx = self.fcx.tcx;
1463 // if this is an implicit deref of an
1464 // upvar, then we need to modify the
1465 // borrow_kind of the upvar to make sure it
1466 // is inferred to mutable if necessary
1467 self.adjust_upvar_borrow_kind(place_with_id, diag_expr_id, borrow_kind);
1469 if let PlaceBase::Upvar(upvar_id) = place_with_id.place.base {
1470 self.adjust_closure_kind(
1471 upvar_id.closure_expr_id,
1472 ty::ClosureKind::FnMut,
1473 tcx.hir().span(diag_expr_id),
1474 place_with_id.place.clone(),
1479 /// We infer the borrow_kind with which to borrow upvars in a stack closure.
1480 /// The borrow_kind basically follows a lattice of `imm < unique-imm < mut`,
1481 /// moving from left to right as needed (but never right to left).
1482 /// Here the argument `mutbl` is the borrow_kind that is required by
1483 /// some particular use.
1484 fn adjust_upvar_borrow_kind(
1486 place_with_id: &PlaceWithHirId<'tcx>,
1487 diag_expr_id: hir::HirId,
1488 kind: ty::BorrowKind,
1490 let curr_capture_info = self.capture_information[&place_with_id.place];
1493 "adjust_upvar_borrow_kind(place={:?}, diag_expr_id={:?}, capture_info={:?}, kind={:?})",
1494 place_with_id, diag_expr_id, curr_capture_info, kind
1497 if let ty::UpvarCapture::ByValue(_) = curr_capture_info.capture_kind {
1498 // It's already captured by value, we don't need to do anything here
1500 } else if let ty::UpvarCapture::ByRef(curr_upvar_borrow) = curr_capture_info.capture_kind {
1501 // Use the same region as the current capture information
1502 // Doesn't matter since only one of the UpvarBorrow will be used.
1503 let new_upvar_borrow = ty::UpvarBorrow { kind, region: curr_upvar_borrow.region };
1505 let capture_info = ty::CaptureInfo {
1506 capture_kind_expr_id: Some(diag_expr_id),
1507 path_expr_id: Some(diag_expr_id),
1508 capture_kind: ty::UpvarCapture::ByRef(new_upvar_borrow),
1510 let updated_info = determine_capture_info(curr_capture_info, capture_info);
1511 self.capture_information[&place_with_id.place] = updated_info;
1515 fn adjust_closure_kind(
1517 closure_id: LocalDefId,
1518 new_kind: ty::ClosureKind,
1523 "adjust_closure_kind(closure_id={:?}, new_kind={:?}, upvar_span={:?}, place={:?})",
1524 closure_id, new_kind, upvar_span, place
1527 // Is this the closure whose kind is currently being inferred?
1528 if closure_id.to_def_id() != self.closure_def_id {
1529 debug!("adjust_closure_kind: not current closure");
1533 // closures start out as `Fn`.
1534 let existing_kind = self.current_closure_kind;
1537 "adjust_closure_kind: closure_id={:?}, existing_kind={:?}, new_kind={:?}",
1538 closure_id, existing_kind, new_kind
1541 match (existing_kind, new_kind) {
1542 (ty::ClosureKind::Fn, ty::ClosureKind::Fn)
1543 | (ty::ClosureKind::FnMut, ty::ClosureKind::Fn | ty::ClosureKind::FnMut)
1544 | (ty::ClosureKind::FnOnce, _) => {
1548 (ty::ClosureKind::Fn, ty::ClosureKind::FnMut | ty::ClosureKind::FnOnce)
1549 | (ty::ClosureKind::FnMut, ty::ClosureKind::FnOnce) => {
1550 // new kind is stronger than the old kind
1551 self.current_closure_kind = new_kind;
1552 self.current_origin = Some((upvar_span, place));
1557 fn init_capture_info_for_place(
1559 place_with_id: &PlaceWithHirId<'tcx>,
1560 diag_expr_id: hir::HirId,
1562 if let PlaceBase::Upvar(upvar_id) = place_with_id.place.base {
1563 assert_eq!(self.closure_def_id.expect_local(), upvar_id.closure_expr_id);
1565 let capture_kind = self.fcx.init_capture_kind_for_place(
1566 &place_with_id.place,
1567 self.capture_clause,
1572 let expr_id = Some(diag_expr_id);
1573 let capture_info = ty::CaptureInfo {
1574 capture_kind_expr_id: expr_id,
1575 path_expr_id: expr_id,
1579 debug!("Capturing new place {:?}, capture_info={:?}", place_with_id, capture_info);
1581 self.capture_information.insert(place_with_id.place.clone(), capture_info);
1583 debug!("Not upvar: {:?}", place_with_id);
1588 impl<'a, 'tcx> euv::Delegate<'tcx> for InferBorrowKind<'a, 'tcx> {
1589 fn fake_read(&mut self, place: Place<'tcx>, cause: FakeReadCause, diag_expr_id: hir::HirId) {
1590 if let PlaceBase::Upvar(_) = place.base {
1591 self.fake_reads.push((place, cause, diag_expr_id));
1597 place_with_id: &PlaceWithHirId<'tcx>,
1598 diag_expr_id: hir::HirId,
1599 mode: euv::ConsumeMode,
1602 "consume(place_with_id={:?}, diag_expr_id={:?}, mode={:?})",
1603 place_with_id, diag_expr_id, mode
1605 if !self.capture_information.contains_key(&place_with_id.place) {
1606 self.init_capture_info_for_place(place_with_id, diag_expr_id);
1609 self.adjust_upvar_borrow_kind_for_consume(place_with_id, diag_expr_id, mode);
1614 place_with_id: &PlaceWithHirId<'tcx>,
1615 diag_expr_id: hir::HirId,
1619 "borrow(place_with_id={:?}, diag_expr_id={:?}, bk={:?})",
1620 place_with_id, diag_expr_id, bk
1623 let place = restrict_repr_packed_field_ref_capture(
1626 &place_with_id.place,
1628 let place_with_id = PlaceWithHirId { place, ..*place_with_id };
1630 if !self.capture_information.contains_key(&place_with_id.place) {
1631 self.init_capture_info_for_place(&place_with_id, diag_expr_id);
1636 ty::UniqueImmBorrow => {
1637 self.adjust_upvar_borrow_kind_for_unique(&place_with_id, diag_expr_id);
1640 self.adjust_upvar_borrow_kind_for_mut(&place_with_id, diag_expr_id);
1645 fn mutate(&mut self, assignee_place: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId) {
1646 debug!("mutate(assignee_place={:?}, diag_expr_id={:?})", assignee_place, diag_expr_id);
1648 self.borrow(assignee_place, diag_expr_id, ty::BorrowKind::MutBorrow);
1652 /// Truncate projections so that following rules are obeyed by the captured `place`:
1653 /// - No projections are applied to raw pointers, since these require unsafe blocks. We capture
1654 /// them completely.
1655 /// - No Index projections are captured, since arrays are captured completely.
1656 fn restrict_capture_precision<'tcx>(mut place: Place<'tcx>) -> Place<'tcx> {
1657 if place.projections.is_empty() {
1658 // Nothing to do here
1662 if place.base_ty.is_unsafe_ptr() {
1663 place.projections.truncate(0);
1667 let mut truncated_length = usize::MAX;
1669 for (i, proj) in place.projections.iter().enumerate() {
1670 if proj.ty.is_unsafe_ptr() {
1671 // Don't apply any projections on top of an unsafe ptr
1672 truncated_length = truncated_length.min(i + 1);
1676 ProjectionKind::Index => {
1677 // Arrays are completely captured, so we drop Index projections
1678 truncated_length = truncated_length.min(i);
1681 ProjectionKind::Deref => {}
1682 ProjectionKind::Field(..) => {} // ignore
1683 ProjectionKind::Subslice => {} // We never capture this
1687 let length = place.projections.len().min(truncated_length);
1689 place.projections.truncate(length);
1694 /// Truncates a place so that the resultant capture doesn't move data out of a reference
1695 fn truncate_capture_for_move(mut place: Place<'tcx>) -> Place<'tcx> {
1696 if let Some(i) = place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref) {
1697 // We only drop Derefs in case of move closures
1698 // There might be an index projection or raw ptr ahead, so we don't stop here.
1699 place.projections.truncate(i);
1705 fn construct_place_string(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
1706 let variable_name = match place.base {
1707 PlaceBase::Upvar(upvar_id) => var_name(tcx, upvar_id.var_path.hir_id).to_string(),
1708 _ => bug!("Capture_information should only contain upvars"),
1711 let mut projections_str = String::new();
1712 for (i, item) in place.projections.iter().enumerate() {
1713 let proj = match item.kind {
1714 ProjectionKind::Field(a, b) => format!("({:?}, {:?})", a, b),
1715 ProjectionKind::Deref => String::from("Deref"),
1716 ProjectionKind::Index => String::from("Index"),
1717 ProjectionKind::Subslice => String::from("Subslice"),
1720 projections_str.push(',');
1722 projections_str.push_str(proj.as_str());
1725 format!("{}[{}]", variable_name, projections_str)
1728 fn construct_capture_kind_reason_string(
1730 place: &Place<'tcx>,
1731 capture_info: &ty::CaptureInfo<'tcx>,
1733 let place_str = construct_place_string(tcx, &place);
1735 let capture_kind_str = match capture_info.capture_kind {
1736 ty::UpvarCapture::ByValue(_) => "ByValue".into(),
1737 ty::UpvarCapture::ByRef(borrow) => format!("{:?}", borrow.kind),
1740 format!("{} captured as {} here", place_str, capture_kind_str)
1743 fn construct_path_string(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
1744 let place_str = construct_place_string(tcx, &place);
1746 format!("{} used here", place_str)
1749 fn construct_capture_info_string(
1751 place: &Place<'tcx>,
1752 capture_info: &ty::CaptureInfo<'tcx>,
1754 let place_str = construct_place_string(tcx, &place);
1756 let capture_kind_str = match capture_info.capture_kind {
1757 ty::UpvarCapture::ByValue(_) => "ByValue".into(),
1758 ty::UpvarCapture::ByRef(borrow) => format!("{:?}", borrow.kind),
1760 format!("{} -> {}", place_str, capture_kind_str)
1763 fn var_name(tcx: TyCtxt<'_>, var_hir_id: hir::HirId) -> Symbol {
1764 tcx.hir().name(var_hir_id)
1767 fn should_do_disjoint_capture_migration_analysis(tcx: TyCtxt<'_>, closure_id: hir::HirId) -> bool {
1768 let (level, _) = tcx.lint_level_at_node(lint::builtin::DISJOINT_CAPTURE_MIGRATION, closure_id);
1770 !matches!(level, lint::Level::Allow)
1773 /// Return a two string tuple (s1, s2)
1774 /// - s1: Line of code that is needed for the migration: eg: `let _ = (&x, ...)`.
1775 /// - s2: Comma separated names of the variables being migrated.
1776 fn migration_suggestion_for_2229(
1778 need_migrations: &Vec<hir::HirId>,
1779 ) -> (String, String) {
1780 let need_migrations_variables =
1781 need_migrations.iter().map(|v| var_name(tcx, *v)).collect::<Vec<_>>();
1783 let migration_ref_concat =
1784 need_migrations_variables.iter().map(|v| format!("&{}", v)).collect::<Vec<_>>().join(", ");
1786 let migration_string = if 1 == need_migrations.len() {
1787 format!("let _ = {}", migration_ref_concat)
1789 format!("let _ = ({})", migration_ref_concat)
1792 let migrated_variables_concat =
1793 need_migrations_variables.iter().map(|v| format!("`{}`", v)).collect::<Vec<_>>().join(", ");
1795 (migration_string, migrated_variables_concat)
1798 /// Helper function to determine if we need to escalate CaptureKind from
1799 /// CaptureInfo A to B and returns the escalated CaptureInfo.
1800 /// (Note: CaptureInfo contains CaptureKind and an expression that led to capture it in that way)
1802 /// If both `CaptureKind`s are considered equivalent, then the CaptureInfo is selected based
1803 /// on the `CaptureInfo` containing an associated `capture_kind_expr_id`.
1805 /// It is the caller's duty to figure out which path_expr_id to use.
1807 /// If both the CaptureKind and Expression are considered to be equivalent,
1808 /// then `CaptureInfo` A is preferred. This can be useful in cases where we want to priortize
1809 /// expressions reported back to the user as part of diagnostics based on which appears earlier
1810 /// in the closure. This can be achieved simply by calling
1811 /// `determine_capture_info(existing_info, current_info)`. This works out because the
1812 /// expressions that occur earlier in the closure body than the current expression are processed before.
1813 /// Consider the following example
1815 /// struct Point { x: i32, y: i32 }
1816 /// let mut p: Point { x: 10, y: 10 };
1824 /// p.x += 10; // E2
1828 /// `CaptureKind` associated with both `E1` and `E2` will be ByRef(MutBorrow),
1829 /// and both have an expression associated, however for diagnostics we prefer reporting
1830 /// `E1` since it appears earlier in the closure body. When `E2` is being processed we
1831 /// would've already handled `E1`, and have an existing capture_information for it.
1832 /// Calling `determine_capture_info(existing_info_e1, current_info_e2)` will return
1833 /// `existing_info_e1` in this case, allowing us to point to `E1` in case of diagnostics.
1834 fn determine_capture_info(
1835 capture_info_a: ty::CaptureInfo<'tcx>,
1836 capture_info_b: ty::CaptureInfo<'tcx>,
1837 ) -> ty::CaptureInfo<'tcx> {
1838 // If the capture kind is equivalent then, we don't need to escalate and can compare the
1840 let eq_capture_kind = match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
1841 (ty::UpvarCapture::ByValue(_), ty::UpvarCapture::ByValue(_)) => {
1842 // We don't need to worry about the spans being ignored here.
1844 // The expr_id in capture_info corresponds to the span that is stored within
1845 // ByValue(span) and therefore it gets handled with priortizing based on
1846 // expressions below.
1849 (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => {
1850 ref_a.kind == ref_b.kind
1852 (ty::UpvarCapture::ByValue(_), _) | (ty::UpvarCapture::ByRef(_), _) => false,
1855 if eq_capture_kind {
1856 match (capture_info_a.capture_kind_expr_id, capture_info_b.capture_kind_expr_id) {
1857 (Some(_), _) | (None, None) => capture_info_a,
1858 (None, Some(_)) => capture_info_b,
1861 // We select the CaptureKind which ranks higher based the following priority order:
1862 // ByValue > MutBorrow > UniqueImmBorrow > ImmBorrow
1863 match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
1864 (ty::UpvarCapture::ByValue(_), _) => capture_info_a,
1865 (_, ty::UpvarCapture::ByValue(_)) => capture_info_b,
1866 (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => {
1867 match (ref_a.kind, ref_b.kind) {
1869 (ty::UniqueImmBorrow | ty::MutBorrow, ty::ImmBorrow)
1870 | (ty::MutBorrow, ty::UniqueImmBorrow) => capture_info_a,
1873 (ty::ImmBorrow, ty::UniqueImmBorrow | ty::MutBorrow)
1874 | (ty::UniqueImmBorrow, ty::MutBorrow) => capture_info_b,
1876 (ty::ImmBorrow, ty::ImmBorrow)
1877 | (ty::UniqueImmBorrow, ty::UniqueImmBorrow)
1878 | (ty::MutBorrow, ty::MutBorrow) => {
1879 bug!("Expected unequal capture kinds");
1887 /// Determines the Ancestry relationship of Place A relative to Place B
1889 /// `PlaceAncestryRelation::Ancestor` implies Place A is ancestor of Place B
1890 /// `PlaceAncestryRelation::Descendant` implies Place A is descendant of Place B
1891 /// `PlaceAncestryRelation::Divergent` implies neither of them is the ancestor of the other.
1892 fn determine_place_ancestry_relation(
1893 place_a: &Place<'tcx>,
1894 place_b: &Place<'tcx>,
1895 ) -> PlaceAncestryRelation {
1896 // If Place A and Place B, don't start off from the same root variable, they are divergent.
1897 if place_a.base != place_b.base {
1898 return PlaceAncestryRelation::Divergent;
1901 // Assume of length of projections_a = n
1902 let projections_a = &place_a.projections;
1904 // Assume of length of projections_b = m
1905 let projections_b = &place_b.projections;
1907 let same_initial_projections =
1908 iter::zip(projections_a, projections_b).all(|(proj_a, proj_b)| proj_a == proj_b);
1910 if same_initial_projections {
1911 // First min(n, m) projections are the same
1912 // Select Ancestor/Descendant
1913 if projections_b.len() >= projections_a.len() {
1914 PlaceAncestryRelation::Ancestor
1916 PlaceAncestryRelation::Descendant
1919 PlaceAncestryRelation::Divergent