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, 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;
55 /// Describe the relationship between the paths of two places
57 /// - `foo` is ancestor of `foo.bar.baz`
58 /// - `foo.bar.baz` is an descendant of `foo.bar`
59 /// - `foo.bar` and `foo.baz` are divergent
60 enum PlaceAncestryRelation {
66 /// Intermediate format to store a captured `Place` and associated `ty::CaptureInfo`
67 /// during capture analysis. Information in this map feeds into the minimum capture
69 type InferredCaptureInformation<'tcx> = FxIndexMap<Place<'tcx>, ty::CaptureInfo<'tcx>>;
71 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
72 pub fn closure_analyze(&self, body: &'tcx hir::Body<'tcx>) {
73 InferBorrowKindVisitor { fcx: self }.visit_body(body);
75 // it's our job to process these.
76 assert!(self.deferred_call_resolutions.borrow().is_empty());
80 struct InferBorrowKindVisitor<'a, 'tcx> {
81 fcx: &'a FnCtxt<'a, 'tcx>,
84 impl<'a, 'tcx> Visitor<'tcx> for InferBorrowKindVisitor<'a, 'tcx> {
85 type Map = intravisit::ErasedMap<'tcx>;
87 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
88 NestedVisitorMap::None
91 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
92 if let hir::ExprKind::Closure(cc, _, body_id, _, _) = expr.kind {
93 let body = self.fcx.tcx.hir().body(body_id);
94 self.visit_body(body);
95 self.fcx.analyze_closure(expr.hir_id, expr.span, body_id, body, cc);
98 intravisit::walk_expr(self, expr);
102 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
103 /// Analysis starting point.
106 closure_hir_id: hir::HirId,
108 body_id: hir::BodyId,
109 body: &'tcx hir::Body<'tcx>,
110 capture_clause: hir::CaptureBy,
112 debug!("analyze_closure(id={:?}, body.id={:?})", closure_hir_id, body.id());
114 // Extract the type of the closure.
115 let ty = self.node_ty(closure_hir_id);
116 let (closure_def_id, substs) = match *ty.kind() {
117 ty::Closure(def_id, substs) => (def_id, UpvarSubsts::Closure(substs)),
118 ty::Generator(def_id, substs, _) => (def_id, UpvarSubsts::Generator(substs)),
120 // #51714: skip analysis when we have already encountered type errors
126 "type of closure expr {:?} is not a closure {:?}",
133 let infer_kind = if let UpvarSubsts::Closure(closure_substs) = substs {
134 self.closure_kind(closure_substs).is_none().then_some(closure_substs)
139 let local_def_id = closure_def_id.expect_local();
141 let body_owner_def_id = self.tcx.hir().body_owner_def_id(body.id());
142 assert_eq!(body_owner_def_id.to_def_id(), closure_def_id);
143 let mut delegate = InferBorrowKind {
148 current_closure_kind: ty::ClosureKind::LATTICE_BOTTOM,
149 current_origin: None,
150 capture_information: Default::default(),
151 fake_reads: Default::default(),
153 euv::ExprUseVisitor::new(
158 &self.typeck_results.borrow(),
163 "For closure={:?}, capture_information={:#?}",
164 closure_def_id, delegate.capture_information
166 self.log_capture_analysis_first_pass(closure_def_id, &delegate.capture_information, span);
168 self.compute_min_captures(closure_def_id, delegate.capture_information);
170 let closure_hir_id = self.tcx.hir().local_def_id_to_hir_id(local_def_id);
171 if should_do_migration_analysis(self.tcx, closure_hir_id) {
172 self.perform_2229_migration_anaysis(closure_def_id, body_id, capture_clause, span);
175 // We now fake capture information for all variables that are mentioned within the closure
176 // We do this after handling migrations so that min_captures computes before
177 if !self.tcx.features().capture_disjoint_fields {
178 let mut capture_information: InferredCaptureInformation<'tcx> = Default::default();
180 if let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) {
181 for var_hir_id in upvars.keys() {
182 let place = self.place_for_root_variable(local_def_id, *var_hir_id);
184 debug!("seed place {:?}", place);
186 let upvar_id = ty::UpvarId::new(*var_hir_id, local_def_id);
188 self.init_capture_kind_for_place(&place, capture_clause, upvar_id, span);
189 let fake_info = ty::CaptureInfo {
190 capture_kind_expr_id: None,
195 capture_information.insert(place, fake_info);
199 // This will update the min captures based on this new fake information.
200 self.compute_min_captures(closure_def_id, capture_information);
203 if let Some(closure_substs) = infer_kind {
204 // Unify the (as yet unbound) type variable in the closure
205 // substs with the kind we inferred.
206 let inferred_kind = delegate.current_closure_kind;
207 let closure_kind_ty = closure_substs.as_closure().kind_ty();
208 self.demand_eqtype(span, inferred_kind.to_ty(self.tcx), closure_kind_ty);
210 // If we have an origin, store it.
211 if let Some(origin) = delegate.current_origin.clone() {
212 let origin = if self.tcx.features().capture_disjoint_fields {
213 (origin.0, restrict_capture_precision(origin.1))
215 (origin.0, Place { projections: vec![], ..origin.1 })
220 .closure_kind_origins_mut()
221 .insert(closure_hir_id, origin);
225 self.log_closure_min_capture_info(closure_def_id, span);
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 let fake_reads = delegate
254 .map(|(place, cause, hir_id)| (place, cause, hir_id))
256 self.typeck_results.borrow_mut().closure_fake_reads.insert(closure_def_id, fake_reads);
258 // If we are also inferred the closure kind here,
259 // process any deferred resolutions.
260 let deferred_call_resolutions = self.remove_deferred_call_resolutions(closure_def_id);
261 for deferred_call_resolution in deferred_call_resolutions {
262 deferred_call_resolution.resolve(self);
266 // Returns a list of `Ty`s for each upvar.
267 fn final_upvar_tys(&self, closure_id: DefId) -> Vec<Ty<'tcx>> {
268 // Presently an unboxed closure type cannot "escape" out of a
269 // function, so we will only encounter ones that originated in the
270 // local crate or were inlined into it along with some function.
271 // This may change if abstract return types of some sort are
275 .closure_min_captures_flattened(closure_id)
276 .map(|captured_place| {
277 let upvar_ty = captured_place.place.ty();
278 let capture = captured_place.info.capture_kind;
281 "final_upvar_tys: place={:?} upvar_ty={:?} capture={:?}, mutability={:?}",
282 captured_place.place, upvar_ty, capture, captured_place.mutability,
286 ty::UpvarCapture::ByValue(_) => upvar_ty,
287 ty::UpvarCapture::ByRef(borrow) => self.tcx.mk_ref(
289 ty::TypeAndMut { ty: upvar_ty, mutbl: borrow.kind.to_mutbl_lossy() },
296 /// Analyzes the information collected by `InferBorrowKind` to compute the min number of
297 /// Places (and corresponding capture kind) that we need to keep track of to support all
298 /// the required captured paths.
301 /// Note: If this function is called multiple times for the same closure, it will update
302 /// the existing min_capture map that is stored in TypeckResults.
306 /// struct Point { x: i32, y: i32 }
308 /// let s: String; // hir_id_s
309 /// let mut p: Point; // his_id_p
311 /// println!("{}", s); // L1
313 /// println!("{}" , p.y) // L3
314 /// println!("{}", p) // L4
318 /// and let hir_id_L1..5 be the expressions pointing to use of a captured variable on
319 /// the lines L1..5 respectively.
321 /// InferBorrowKind results in a structure like this:
325 /// Place(base: hir_id_s, projections: [], ....) -> {
326 /// capture_kind_expr: hir_id_L5,
327 /// path_expr_id: hir_id_L5,
328 /// capture_kind: ByValue
330 /// Place(base: hir_id_p, projections: [Field(0, 0)], ...) -> {
331 /// capture_kind_expr: hir_id_L2,
332 /// path_expr_id: hir_id_L2,
333 /// capture_kind: ByValue
335 /// Place(base: hir_id_p, projections: [Field(1, 0)], ...) -> {
336 /// capture_kind_expr: hir_id_L3,
337 /// path_expr_id: hir_id_L3,
338 /// capture_kind: ByValue
340 /// Place(base: hir_id_p, projections: [], ...) -> {
341 /// capture_kind_expr: hir_id_L4,
342 /// path_expr_id: hir_id_L4,
343 /// capture_kind: ByValue
347 /// After the min capture analysis, we get:
351 /// Place(base: hir_id_s, projections: [], ....) -> {
352 /// capture_kind_expr: hir_id_L5,
353 /// path_expr_id: hir_id_L5,
354 /// capture_kind: ByValue
358 /// Place(base: hir_id_p, projections: [], ...) -> {
359 /// capture_kind_expr: hir_id_L2,
360 /// path_expr_id: hir_id_L4,
361 /// capture_kind: ByValue
365 fn compute_min_captures(
367 closure_def_id: DefId,
368 capture_information: InferredCaptureInformation<'tcx>,
370 if capture_information.is_empty() {
374 let mut typeck_results = self.typeck_results.borrow_mut();
376 let mut root_var_min_capture_list =
377 typeck_results.closure_min_captures.remove(&closure_def_id).unwrap_or_default();
379 for (place, capture_info) in capture_information.into_iter() {
380 let var_hir_id = match place.base {
381 PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
382 base => bug!("Expected upvar, found={:?}", base),
385 let place = restrict_capture_precision(place);
387 let min_cap_list = match root_var_min_capture_list.get_mut(&var_hir_id) {
389 let mutability = self.determine_capture_mutability(&typeck_results, &place);
391 vec![ty::CapturedPlace { place, info: capture_info, mutability }];
392 root_var_min_capture_list.insert(var_hir_id, min_cap_list);
395 Some(min_cap_list) => min_cap_list,
398 // Go through each entry in the current list of min_captures
399 // - if ancestor is found, update it's capture kind to account for current place's
400 // capture information.
402 // - if descendant is found, remove it from the list, and update the current place's
403 // capture information to account for the descendants's capture kind.
405 // We can never be in a case where the list contains both an ancestor and a descendant
406 // Also there can only be ancestor but in case of descendants there might be
409 let mut descendant_found = false;
410 let mut updated_capture_info = capture_info;
411 min_cap_list.retain(|possible_descendant| {
412 match determine_place_ancestry_relation(&place, &possible_descendant.place) {
413 // current place is ancestor of possible_descendant
414 PlaceAncestryRelation::Ancestor => {
415 descendant_found = true;
416 let backup_path_expr_id = updated_capture_info.path_expr_id;
418 updated_capture_info =
419 determine_capture_info(updated_capture_info, possible_descendant.info);
421 // we need to keep the ancestor's `path_expr_id`
422 updated_capture_info.path_expr_id = backup_path_expr_id;
430 let mut ancestor_found = false;
431 if !descendant_found {
432 for possible_ancestor in min_cap_list.iter_mut() {
433 match determine_place_ancestry_relation(&place, &possible_ancestor.place) {
434 // current place is descendant of possible_ancestor
435 PlaceAncestryRelation::Descendant => {
436 ancestor_found = true;
437 let backup_path_expr_id = possible_ancestor.info.path_expr_id;
438 possible_ancestor.info =
439 determine_capture_info(possible_ancestor.info, capture_info);
441 // we need to keep the ancestor's `path_expr_id`
442 possible_ancestor.info.path_expr_id = backup_path_expr_id;
444 // Only one ancestor of the current place will be in the list.
452 // Only need to insert when we don't have an ancestor in the existing min capture list
454 let mutability = self.determine_capture_mutability(&typeck_results, &place);
456 ty::CapturedPlace { place, info: updated_capture_info, mutability };
457 min_cap_list.push(captured_place);
461 debug!("For closure={:?}, min_captures={:#?}", closure_def_id, root_var_min_capture_list);
462 typeck_results.closure_min_captures.insert(closure_def_id, root_var_min_capture_list);
465 /// Perform the migration analysis for RFC 2229, and emit lint
466 /// `disjoint_capture_drop_reorder` if needed.
467 fn perform_2229_migration_anaysis(
469 closure_def_id: DefId,
470 body_id: hir::BodyId,
471 capture_clause: hir::CaptureBy,
474 let need_migrations = self.compute_2229_migrations(
478 self.typeck_results.borrow().closure_min_captures.get(&closure_def_id),
481 if !need_migrations.is_empty() {
482 let (migration_string, migrated_variables_concat) =
483 migration_suggestion_for_2229(self.tcx, &need_migrations);
485 let local_def_id = closure_def_id.expect_local();
486 let closure_hir_id = self.tcx.hir().local_def_id_to_hir_id(local_def_id);
487 self.tcx.struct_span_lint_hir(
488 lint::builtin::DISJOINT_CAPTURE_DROP_REORDER,
492 let mut diagnostics_builder = lint.build(
493 "drop order affected for closure because of `capture_disjoint_fields`",
495 let closure_body_span = self.tcx.hir().span(body_id.hir_id);
497 match self.tcx.sess.source_map().span_to_snippet(closure_body_span) {
499 let trimmed = s.trim_start();
501 // If the closure contains a block then replace the opening brace
502 // with "{ let _ = (..); "
503 let sugg = if let Some('{') = trimmed.chars().next() {
504 format!("{{ {}; {}", migration_string, &trimmed[1..])
506 format!("{{ {}; {} }}", migration_string, s)
508 (sugg, Applicability::MachineApplicable)
510 Err(_) => (migration_string.clone(), Applicability::HasPlaceholders),
513 let diagnostic_msg = format!(
514 "add a dummy let to cause {} to be fully captured",
515 migrated_variables_concat
518 diagnostics_builder.span_suggestion(
524 diagnostics_builder.emit();
530 /// Figures out the list of root variables (and their types) that aren't completely
531 /// captured by the closure when `capture_disjoint_fields` is enabled and drop order of
532 /// some path starting at that root variable **might** be affected.
534 /// The output list would include a root variable if:
535 /// - It would have been moved into the closure when `capture_disjoint_fields` wasn't
537 /// - It wasn't completely captured by the closure, **and**
538 /// - One of the paths starting at this root variable, that is not captured needs Drop.
539 fn compute_2229_migrations(
541 closure_def_id: DefId,
543 closure_clause: hir::CaptureBy,
544 min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
545 ) -> Vec<hir::HirId> {
546 let upvars = if let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) {
552 let mut need_migrations = Vec::new();
554 for (&var_hir_id, _) in upvars.iter() {
555 let ty = self.infcx.resolve_vars_if_possible(self.node_ty(var_hir_id));
557 if !ty.needs_drop(self.tcx, self.tcx.param_env(closure_def_id.expect_local())) {
561 let root_var_min_capture_list = if let Some(root_var_min_capture_list) =
562 min_captures.and_then(|m| m.get(&var_hir_id))
564 root_var_min_capture_list
566 // The upvar is mentioned within the closure but no path starting from it is
569 match closure_clause {
570 // Only migrate if closure is a move closure
571 hir::CaptureBy::Value => need_migrations.push(var_hir_id),
573 hir::CaptureBy::Ref => {}
579 let projections_list = root_var_min_capture_list
581 .filter_map(|captured_place| match captured_place.info.capture_kind {
582 // Only care about captures that are moved into the closure
583 ty::UpvarCapture::ByValue(..) => {
584 Some(captured_place.place.projections.as_slice())
586 ty::UpvarCapture::ByRef(..) => None,
588 .collect::<Vec<_>>();
590 let is_moved = !projections_list.is_empty();
592 let is_not_completely_captured =
593 root_var_min_capture_list.iter().any(|capture| capture.place.projections.len() > 0);
596 && is_not_completely_captured
597 && self.has_significant_drop_outside_of_captures(
604 need_migrations.push(var_hir_id);
611 /// This is a helper function to `compute_2229_migrations_precise_pass`. Provided the type
612 /// of a root variable and a list of captured paths starting at this root variable (expressed
613 /// using list of `Projection` slices), it returns true if there is a path that is not
614 /// captured starting at this root variable that implements Drop.
616 /// FIXME(project-rfc-2229#35): This should return true only for significant drops.
617 /// A drop is significant if it's implemented by the user or does
618 /// anything that will have any observable behavior (other than
619 /// freeing up memory).
621 /// The way this function works is at a given call it looks at type `base_path_ty` of some base
622 /// path say P and then list of projection slices which represent the different captures moved
623 /// into the closure starting off of P.
625 /// This will make more sense with an example:
628 /// #![feature(capture_disjoint_fields)]
630 /// struct FancyInteger(i32); // This implements Drop
632 /// struct Point { x: FancyInteger, y: FancyInteger }
635 /// struct Wrapper { p: Point, c: Color }
637 /// fn f(w: Wrapper) {
639 /// // Closure captures w.p.x and w.c by move.
646 /// If `capture_disjoint_fields` wasn't enabled the closure would've moved `w` instead of the
647 /// precise paths. If we look closely `w.p.y` isn't captured which implements Drop and
648 /// therefore Drop ordering would change and we want this function to return true.
650 /// Call stack to figure out if we need to migrate for `w` would look as follows:
652 /// Our initial base path is just `w`, and the paths captured from it are `w[p, x]` and
655 /// - Ty(place): Type of place
656 /// - `(a, b)`: Represents the function parameters `base_path_ty` and `captured_by_move_projs`
659 /// (Ty(w), [ &[p, x], &[c] ])
661 /// ----------------------------
664 /// (Ty(w.p), [ &[x] ]) (Ty(w.c), [ &[] ]) // I(1)
667 /// (Ty(w.p), [ &[x] ]) false
670 /// -------------------------------
673 /// (Ty((w.p).x), [ &[] ]) (Ty((w.p).y), []) // IMP 2
676 /// false NeedsDrop(Ty(w.p.y))
682 /// IMP 1 `(Ty(w.c), [ &[] ])`: Notice the single empty slice inside `captured_projs`.
683 /// This implies that the `w.c` is completely captured by the closure.
684 /// Since drop for this path will be called when the closure is
685 /// dropped we don't need to migrate for it.
687 /// IMP 2 `(Ty((w.p).y), [])`: Notice that `captured_projs` is empty. This implies that this
688 /// path wasn't captured by the closure. Also note that even
689 /// though we didn't capture this path, the function visits it,
690 /// which is kind of the point of this function. We then return
691 /// if the type of `w.p.y` implements Drop, which in this case is
694 /// Consider another example:
698 /// impl Drop for X {}
701 /// impl Drop for Y {}
705 /// let c = || move(y.0);
709 /// Note that `y.0` is captured by the closure. When this function is called for `y`, it will
710 /// return true, because even though all paths starting at `y` are captured, `y` itself
711 /// implements Drop which will be affected since `y` isn't completely captured.
712 fn has_significant_drop_outside_of_captures(
714 closure_def_id: DefId,
716 base_path_ty: Ty<'tcx>,
717 captured_by_move_projs: Vec<&[Projection<'tcx>]>,
719 let needs_drop = |ty: Ty<'tcx>| {
720 ty.needs_drop(self.tcx, self.tcx.param_env(closure_def_id.expect_local()))
723 let is_drop_defined_for_ty = |ty: Ty<'tcx>| {
724 let drop_trait = self.tcx.require_lang_item(hir::LangItem::Drop, Some(closure_span));
725 let ty_params = self.tcx.mk_substs_trait(base_path_ty, &[]);
726 self.tcx.type_implements_trait((
730 self.tcx.param_env(closure_def_id.expect_local()),
734 let is_drop_defined_for_ty = is_drop_defined_for_ty(base_path_ty);
736 // If there is a case where no projection is applied on top of current place
737 // then there must be exactly one capture corresponding to such a case. Note that this
738 // represents the case of the path being completely captured by the variable.
740 // eg. If `a.b` is captured and we are processing `a.b`, then we can't have the closure also
741 // capture `a.b.c`, because that voilates min capture.
742 let is_completely_captured = captured_by_move_projs.iter().any(|projs| projs.is_empty());
744 assert!(!is_completely_captured || (captured_by_move_projs.len() == 1));
746 if is_completely_captured {
747 // The place is captured entirely, so doesn't matter if needs dtor, it will be drop
748 // when the closure is dropped.
752 if captured_by_move_projs.is_empty() {
753 return needs_drop(base_path_ty);
756 if is_drop_defined_for_ty {
757 // If drop is implemented for this type then we need it to be fully captured,
758 // and we know it is not completely captured because of the previous checks.
760 // Note that this is a bug in the user code that will be reported by the
761 // borrow checker, since we can't move out of drop types.
763 // The bug exists in the user's code pre-migration, and we don't migrate here.
767 match base_path_ty.kind() {
769 // - `captured_by_move_projs` is not empty. Therefore we can call
770 // `captured_by_move_projs.first().unwrap()` safely.
771 // - All entries in `captured_by_move_projs` have atleast one projection.
772 // Therefore we can call `captured_by_move_projs.first().unwrap().first().unwrap()` safely.
774 // We don't capture derefs in case of move captures, which would have be applied to
775 // access any further paths.
776 ty::Adt(def, _) if def.is_box() => unreachable!(),
777 ty::Ref(..) => unreachable!(),
778 ty::RawPtr(..) => unreachable!(),
780 ty::Adt(def, substs) => {
781 // Multi-varaint enums are captured in entirety,
782 // which would've been handled in the case of single empty slice in `captured_by_move_projs`.
783 assert_eq!(def.variants.len(), 1);
785 // Only Field projections can be applied to a non-box Adt.
787 captured_by_move_projs.iter().all(|projs| matches!(
788 projs.first().unwrap().kind,
789 ProjectionKind::Field(..)
792 def.variants.get(VariantIdx::new(0)).unwrap().fields.iter().enumerate().any(
794 let paths_using_field = captured_by_move_projs
796 .filter_map(|projs| {
797 if let ProjectionKind::Field(field_idx, _) =
798 projs.first().unwrap().kind
800 if (field_idx as usize) == i { Some(&projs[1..]) } else { None }
807 let after_field_ty = field.ty(self.tcx, substs);
808 self.has_significant_drop_outside_of_captures(
819 // Only Field projections can be applied to a tuple.
821 captured_by_move_projs.iter().all(|projs| matches!(
822 projs.first().unwrap().kind,
823 ProjectionKind::Field(..)
827 base_path_ty.tuple_fields().enumerate().any(|(i, element_ty)| {
828 let paths_using_field = captured_by_move_projs
830 .filter_map(|projs| {
831 if let ProjectionKind::Field(field_idx, _) = projs.first().unwrap().kind
833 if (field_idx as usize) == i { Some(&projs[1..]) } else { None }
840 self.has_significant_drop_outside_of_captures(
849 // Anything else would be completely captured and therefore handled already.
854 fn init_capture_kind_for_place(
857 capture_clause: hir::CaptureBy,
858 upvar_id: ty::UpvarId,
860 ) -> ty::UpvarCapture<'tcx> {
861 match capture_clause {
862 // In case of a move closure if the data is accessed through a reference we
863 // want to capture by ref to allow precise capture using reborrows.
865 // If the data will be moved out of this place, then the place will be truncated
866 // at the first Deref in `adjust_upvar_borrow_kind_for_consume` and then moved into
868 hir::CaptureBy::Value if !place.deref_tys().any(ty::TyS::is_ref) => {
869 ty::UpvarCapture::ByValue(None)
871 hir::CaptureBy::Value | hir::CaptureBy::Ref => {
872 let origin = UpvarRegion(upvar_id, closure_span);
873 let upvar_region = self.next_region_var(origin);
874 let upvar_borrow = ty::UpvarBorrow { kind: ty::ImmBorrow, region: upvar_region };
875 ty::UpvarCapture::ByRef(upvar_borrow)
880 fn place_for_root_variable(
882 closure_def_id: LocalDefId,
883 var_hir_id: hir::HirId,
885 let upvar_id = ty::UpvarId::new(var_hir_id, closure_def_id);
888 base_ty: self.node_ty(var_hir_id),
889 base: PlaceBase::Upvar(upvar_id),
890 projections: Default::default(),
894 fn should_log_capture_analysis(&self, closure_def_id: DefId) -> bool {
895 self.tcx.has_attr(closure_def_id, sym::rustc_capture_analysis)
898 fn log_capture_analysis_first_pass(
900 closure_def_id: rustc_hir::def_id::DefId,
901 capture_information: &FxIndexMap<Place<'tcx>, ty::CaptureInfo<'tcx>>,
904 if self.should_log_capture_analysis(closure_def_id) {
906 self.tcx.sess.struct_span_err(closure_span, "First Pass analysis includes:");
907 for (place, capture_info) in capture_information {
908 let capture_str = construct_capture_info_string(self.tcx, place, capture_info);
909 let output_str = format!("Capturing {}", capture_str);
912 capture_info.path_expr_id.map_or(closure_span, |e| self.tcx.hir().span(e));
913 diag.span_note(span, &output_str);
919 fn log_closure_min_capture_info(&self, closure_def_id: DefId, closure_span: Span) {
920 if self.should_log_capture_analysis(closure_def_id) {
921 if let Some(min_captures) =
922 self.typeck_results.borrow().closure_min_captures.get(&closure_def_id)
925 self.tcx.sess.struct_span_err(closure_span, "Min Capture analysis includes:");
927 for (_, min_captures_for_var) in min_captures {
928 for capture in min_captures_for_var {
929 let place = &capture.place;
930 let capture_info = &capture.info;
933 construct_capture_info_string(self.tcx, place, capture_info);
934 let output_str = format!("Min Capture {}", capture_str);
936 if capture.info.path_expr_id != capture.info.capture_kind_expr_id {
937 let path_span = capture_info
939 .map_or(closure_span, |e| self.tcx.hir().span(e));
940 let capture_kind_span = capture_info
941 .capture_kind_expr_id
942 .map_or(closure_span, |e| self.tcx.hir().span(e));
944 let mut multi_span: MultiSpan =
945 MultiSpan::from_spans(vec![path_span, capture_kind_span]);
947 let capture_kind_label =
948 construct_capture_kind_reason_string(self.tcx, place, capture_info);
949 let path_label = construct_path_string(self.tcx, place);
951 multi_span.push_span_label(path_span, path_label);
952 multi_span.push_span_label(capture_kind_span, capture_kind_label);
954 diag.span_note(multi_span, &output_str);
956 let span = capture_info
958 .map_or(closure_span, |e| self.tcx.hir().span(e));
960 diag.span_note(span, &output_str);
969 /// A captured place is mutable if
970 /// 1. Projections don't include a Deref of an immut-borrow, **and**
971 /// 2. PlaceBase is mut or projections include a Deref of a mut-borrow.
972 fn determine_capture_mutability(
974 typeck_results: &'a TypeckResults<'tcx>,
976 ) -> hir::Mutability {
977 let var_hir_id = match place.base {
978 PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
982 let bm = *typeck_results.pat_binding_modes().get(var_hir_id).expect("missing binding mode");
984 let mut is_mutbl = match bm {
985 ty::BindByValue(mutability) => mutability,
986 ty::BindByReference(_) => hir::Mutability::Not,
989 for pointer_ty in place.deref_tys() {
990 match pointer_ty.kind() {
991 // We don't capture derefs of raw ptrs
992 ty::RawPtr(_) => unreachable!(),
994 // Derefencing a mut-ref allows us to mut the Place if we don't deref
995 // an immut-ref after on top of this.
996 ty::Ref(.., hir::Mutability::Mut) => is_mutbl = hir::Mutability::Mut,
998 // The place isn't mutable once we dereference a immutable reference.
999 ty::Ref(.., hir::Mutability::Not) => return hir::Mutability::Not,
1001 // Dereferencing a box doesn't change mutability
1002 ty::Adt(def, ..) if def.is_box() => {}
1004 unexpected_ty => bug!("deref of unexpected pointer type {:?}", unexpected_ty),
1012 /// Truncate the capture so that the place being borrowed is in accordance with RFC 1240,
1013 /// which states that it's unsafe to take a reference into a struct marked `repr(packed)`.
1014 fn restrict_repr_packed_field_ref_capture<'tcx>(
1016 param_env: ty::ParamEnv<'tcx>,
1017 place: &Place<'tcx>,
1019 let pos = place.projections.iter().enumerate().position(|(i, p)| {
1020 let ty = place.ty_before_projection(i);
1022 // Return true for fields of packed structs, unless those fields have alignment 1.
1024 ProjectionKind::Field(..) => match ty.kind() {
1025 ty::Adt(def, _) if def.repr.packed() => {
1026 match tcx.layout_raw(param_env.and(p.ty)) {
1027 Ok(layout) if layout.align.abi.bytes() == 1 => {
1028 // if the alignment is 1, the type can't be further
1031 "restrict_repr_packed_field_ref_capture: ({:?}) - align = 1",
1037 debug!("restrict_repr_packed_field_ref_capture: ({:?}) - true", place);
1049 let mut place = place.clone();
1051 if let Some(pos) = pos {
1052 place.projections.truncate(pos);
1058 struct InferBorrowKind<'a, 'tcx> {
1059 fcx: &'a FnCtxt<'a, 'tcx>,
1061 // The def-id of the closure whose kind and upvar accesses are being inferred.
1062 closure_def_id: DefId,
1066 capture_clause: hir::CaptureBy,
1068 // The kind that we have inferred that the current closure
1069 // requires. Note that we *always* infer a minimal kind, even if
1070 // we don't always *use* that in the final result (i.e., sometimes
1071 // we've taken the closure kind from the expectations instead, and
1072 // for generators we don't even implement the closure traits
1074 current_closure_kind: ty::ClosureKind,
1076 // If we modified `current_closure_kind`, this field contains a `Some()` with the
1077 // variable access that caused us to do so.
1078 current_origin: Option<(Span, Place<'tcx>)>,
1080 /// For each Place that is captured by the closure, we track the minimal kind of
1081 /// access we need (ref, ref mut, move, etc) and the expression that resulted in such access.
1083 /// Consider closure where s.str1 is captured via an ImmutableBorrow and
1084 /// s.str2 via a MutableBorrow
1087 /// struct SomeStruct { str1: String, str2: String }
1089 /// // Assume that the HirId for the variable definition is `V1`
1090 /// let mut s = SomeStruct { str1: format!("s1"), str2: format!("s2") }
1092 /// let fix_s = |new_s2| {
1093 /// // Assume that the HirId for the expression `s.str1` is `E1`
1094 /// println!("Updating SomeStruct with str1=", s.str1);
1095 /// // Assume that the HirId for the expression `*s.str2` is `E2`
1096 /// s.str2 = new_s2;
1100 /// For closure `fix_s`, (at a high level) the map contains
1103 /// Place { V1, [ProjectionKind::Field(Index=0, Variant=0)] } : CaptureKind { E1, ImmutableBorrow }
1104 /// Place { V1, [ProjectionKind::Field(Index=1, Variant=0)] } : CaptureKind { E2, MutableBorrow }
1106 capture_information: InferredCaptureInformation<'tcx>,
1107 fake_reads: Vec<(Place<'tcx>, FakeReadCause, hir::HirId)>,
1110 impl<'a, 'tcx> InferBorrowKind<'a, 'tcx> {
1111 fn adjust_upvar_borrow_kind_for_consume(
1113 place_with_id: &PlaceWithHirId<'tcx>,
1114 diag_expr_id: hir::HirId,
1115 mode: euv::ConsumeMode,
1118 "adjust_upvar_borrow_kind_for_consume(place_with_id={:?}, diag_expr_id={:?}, mode={:?})",
1119 place_with_id, diag_expr_id, mode
1122 match (self.capture_clause, mode) {
1123 // In non-move closures, we only care about moves
1124 (hir::CaptureBy::Ref, euv::Copy) => return,
1126 // We want to capture Copy types that read through a ref via a reborrow
1127 (hir::CaptureBy::Value, euv::Copy)
1128 if place_with_id.place.deref_tys().any(ty::TyS::is_ref) =>
1133 (hir::CaptureBy::Ref, euv::Move) | (hir::CaptureBy::Value, euv::Move | euv::Copy) => {}
1136 let place = truncate_capture_for_move(place_with_id.place.clone());
1137 let place_with_id = PlaceWithHirId { place: place.clone(), hir_id: place_with_id.hir_id };
1139 if !self.capture_information.contains_key(&place) {
1140 self.init_capture_info_for_place(&place_with_id, diag_expr_id);
1143 let tcx = self.fcx.tcx;
1144 let upvar_id = if let PlaceBase::Upvar(upvar_id) = place_with_id.place.base {
1150 debug!("adjust_upvar_borrow_kind_for_consume: upvar={:?}", upvar_id);
1152 let usage_span = tcx.hir().span(diag_expr_id);
1154 if matches!(mode, euv::Move) {
1155 // To move out of an upvar, this must be a FnOnce closure
1156 self.adjust_closure_kind(
1157 upvar_id.closure_expr_id,
1158 ty::ClosureKind::FnOnce,
1164 let capture_info = ty::CaptureInfo {
1165 capture_kind_expr_id: Some(diag_expr_id),
1166 path_expr_id: Some(diag_expr_id),
1167 capture_kind: ty::UpvarCapture::ByValue(Some(usage_span)),
1170 let curr_info = self.capture_information[&place_with_id.place];
1171 let updated_info = determine_capture_info(curr_info, capture_info);
1173 self.capture_information[&place_with_id.place] = updated_info;
1176 /// Indicates that `place_with_id` is being directly mutated (e.g., assigned
1177 /// to). If the place is based on a by-ref upvar, this implies that
1178 /// the upvar must be borrowed using an `&mut` borrow.
1179 fn adjust_upvar_borrow_kind_for_mut(
1181 place_with_id: &PlaceWithHirId<'tcx>,
1182 diag_expr_id: hir::HirId,
1185 "adjust_upvar_borrow_kind_for_mut(place_with_id={:?}, diag_expr_id={:?})",
1186 place_with_id, diag_expr_id
1189 if let PlaceBase::Upvar(_) = place_with_id.place.base {
1190 let mut borrow_kind = ty::MutBorrow;
1191 for pointer_ty in place_with_id.place.deref_tys() {
1192 match pointer_ty.kind() {
1193 // Raw pointers don't inherit mutability.
1194 ty::RawPtr(_) => return,
1195 // assignment to deref of an `&mut`
1196 // borrowed pointer implies that the
1197 // pointer itself must be unique, but not
1198 // necessarily *mutable*
1199 ty::Ref(.., hir::Mutability::Mut) => borrow_kind = ty::UniqueImmBorrow,
1203 self.adjust_upvar_deref(place_with_id, diag_expr_id, borrow_kind);
1207 fn adjust_upvar_borrow_kind_for_unique(
1209 place_with_id: &PlaceWithHirId<'tcx>,
1210 diag_expr_id: hir::HirId,
1213 "adjust_upvar_borrow_kind_for_unique(place_with_id={:?}, diag_expr_id={:?})",
1214 place_with_id, diag_expr_id
1217 if let PlaceBase::Upvar(_) = place_with_id.place.base {
1218 if place_with_id.place.deref_tys().any(ty::TyS::is_unsafe_ptr) {
1219 // Raw pointers don't inherit mutability.
1222 // for a borrowed pointer to be unique, its base must be unique
1223 self.adjust_upvar_deref(place_with_id, diag_expr_id, ty::UniqueImmBorrow);
1227 fn adjust_upvar_deref(
1229 place_with_id: &PlaceWithHirId<'tcx>,
1230 diag_expr_id: hir::HirId,
1231 borrow_kind: ty::BorrowKind,
1233 assert!(match borrow_kind {
1234 ty::MutBorrow => true,
1235 ty::UniqueImmBorrow => true,
1237 // imm borrows never require adjusting any kinds, so we don't wind up here
1238 ty::ImmBorrow => false,
1241 let tcx = self.fcx.tcx;
1243 // if this is an implicit deref of an
1244 // upvar, then we need to modify the
1245 // borrow_kind of the upvar to make sure it
1246 // is inferred to mutable if necessary
1247 self.adjust_upvar_borrow_kind(place_with_id, diag_expr_id, borrow_kind);
1249 if let PlaceBase::Upvar(upvar_id) = place_with_id.place.base {
1250 self.adjust_closure_kind(
1251 upvar_id.closure_expr_id,
1252 ty::ClosureKind::FnMut,
1253 tcx.hir().span(diag_expr_id),
1254 place_with_id.place.clone(),
1259 /// We infer the borrow_kind with which to borrow upvars in a stack closure.
1260 /// The borrow_kind basically follows a lattice of `imm < unique-imm < mut`,
1261 /// moving from left to right as needed (but never right to left).
1262 /// Here the argument `mutbl` is the borrow_kind that is required by
1263 /// some particular use.
1264 fn adjust_upvar_borrow_kind(
1266 place_with_id: &PlaceWithHirId<'tcx>,
1267 diag_expr_id: hir::HirId,
1268 kind: ty::BorrowKind,
1270 let curr_capture_info = self.capture_information[&place_with_id.place];
1273 "adjust_upvar_borrow_kind(place={:?}, diag_expr_id={:?}, capture_info={:?}, kind={:?})",
1274 place_with_id, diag_expr_id, curr_capture_info, kind
1277 if let ty::UpvarCapture::ByValue(_) = curr_capture_info.capture_kind {
1278 // It's already captured by value, we don't need to do anything here
1280 } else if let ty::UpvarCapture::ByRef(curr_upvar_borrow) = curr_capture_info.capture_kind {
1281 // Use the same region as the current capture information
1282 // Doesn't matter since only one of the UpvarBorrow will be used.
1283 let new_upvar_borrow = ty::UpvarBorrow { kind, region: curr_upvar_borrow.region };
1285 let capture_info = ty::CaptureInfo {
1286 capture_kind_expr_id: Some(diag_expr_id),
1287 path_expr_id: Some(diag_expr_id),
1288 capture_kind: ty::UpvarCapture::ByRef(new_upvar_borrow),
1290 let updated_info = determine_capture_info(curr_capture_info, capture_info);
1291 self.capture_information[&place_with_id.place] = updated_info;
1295 fn adjust_closure_kind(
1297 closure_id: LocalDefId,
1298 new_kind: ty::ClosureKind,
1303 "adjust_closure_kind(closure_id={:?}, new_kind={:?}, upvar_span={:?}, place={:?})",
1304 closure_id, new_kind, upvar_span, place
1307 // Is this the closure whose kind is currently being inferred?
1308 if closure_id.to_def_id() != self.closure_def_id {
1309 debug!("adjust_closure_kind: not current closure");
1313 // closures start out as `Fn`.
1314 let existing_kind = self.current_closure_kind;
1317 "adjust_closure_kind: closure_id={:?}, existing_kind={:?}, new_kind={:?}",
1318 closure_id, existing_kind, new_kind
1321 match (existing_kind, new_kind) {
1322 (ty::ClosureKind::Fn, ty::ClosureKind::Fn)
1323 | (ty::ClosureKind::FnMut, ty::ClosureKind::Fn | ty::ClosureKind::FnMut)
1324 | (ty::ClosureKind::FnOnce, _) => {
1328 (ty::ClosureKind::Fn, ty::ClosureKind::FnMut | ty::ClosureKind::FnOnce)
1329 | (ty::ClosureKind::FnMut, ty::ClosureKind::FnOnce) => {
1330 // new kind is stronger than the old kind
1331 self.current_closure_kind = new_kind;
1332 self.current_origin = Some((upvar_span, place));
1337 fn init_capture_info_for_place(
1339 place_with_id: &PlaceWithHirId<'tcx>,
1340 diag_expr_id: hir::HirId,
1342 if let PlaceBase::Upvar(upvar_id) = place_with_id.place.base {
1343 assert_eq!(self.closure_def_id.expect_local(), upvar_id.closure_expr_id);
1345 let capture_kind = self.fcx.init_capture_kind_for_place(
1346 &place_with_id.place,
1347 self.capture_clause,
1352 let expr_id = Some(diag_expr_id);
1353 let capture_info = ty::CaptureInfo {
1354 capture_kind_expr_id: expr_id,
1355 path_expr_id: expr_id,
1359 debug!("Capturing new place {:?}, capture_info={:?}", place_with_id, capture_info);
1361 self.capture_information.insert(place_with_id.place.clone(), capture_info);
1363 debug!("Not upvar: {:?}", place_with_id);
1368 impl<'a, 'tcx> euv::Delegate<'tcx> for InferBorrowKind<'a, 'tcx> {
1369 fn fake_read(&mut self, place: Place<'tcx>, cause: FakeReadCause, diag_expr_id: hir::HirId) {
1370 if let PlaceBase::Upvar(_) = place.base {
1371 self.fake_reads.push((place, cause, diag_expr_id));
1377 place_with_id: &PlaceWithHirId<'tcx>,
1378 diag_expr_id: hir::HirId,
1379 mode: euv::ConsumeMode,
1382 "consume(place_with_id={:?}, diag_expr_id={:?}, mode={:?})",
1383 place_with_id, diag_expr_id, mode
1385 if !self.capture_information.contains_key(&place_with_id.place) {
1386 self.init_capture_info_for_place(place_with_id, diag_expr_id);
1389 self.adjust_upvar_borrow_kind_for_consume(place_with_id, diag_expr_id, mode);
1394 place_with_id: &PlaceWithHirId<'tcx>,
1395 diag_expr_id: hir::HirId,
1399 "borrow(place_with_id={:?}, diag_expr_id={:?}, bk={:?})",
1400 place_with_id, diag_expr_id, bk
1403 let place = restrict_repr_packed_field_ref_capture(
1406 &place_with_id.place,
1408 let place_with_id = PlaceWithHirId { place, ..*place_with_id };
1410 if !self.capture_information.contains_key(&place_with_id.place) {
1411 self.init_capture_info_for_place(&place_with_id, diag_expr_id);
1416 ty::UniqueImmBorrow => {
1417 self.adjust_upvar_borrow_kind_for_unique(&place_with_id, diag_expr_id);
1420 self.adjust_upvar_borrow_kind_for_mut(&place_with_id, diag_expr_id);
1425 fn mutate(&mut self, assignee_place: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId) {
1426 debug!("mutate(assignee_place={:?}, diag_expr_id={:?})", assignee_place, diag_expr_id);
1428 self.borrow(assignee_place, diag_expr_id, ty::BorrowKind::MutBorrow);
1432 /// Truncate projections so that following rules are obeyed by the captured `place`:
1433 /// - No projections are applied to raw pointers, since these require unsafe blocks. We capture
1434 /// them completely.
1435 /// - No Index projections are captured, since arrays are captured completely.
1436 fn restrict_capture_precision<'tcx>(mut place: Place<'tcx>) -> Place<'tcx> {
1437 if place.projections.is_empty() {
1438 // Nothing to do here
1442 if place.base_ty.is_unsafe_ptr() {
1443 place.projections.truncate(0);
1447 let mut truncated_length = usize::MAX;
1449 for (i, proj) in place.projections.iter().enumerate() {
1450 if proj.ty.is_unsafe_ptr() {
1451 // Don't apply any projections on top of an unsafe ptr
1452 truncated_length = truncated_length.min(i + 1);
1456 ProjectionKind::Index => {
1457 // Arrays are completely captured, so we drop Index projections
1458 truncated_length = truncated_length.min(i);
1461 ProjectionKind::Deref => {}
1462 ProjectionKind::Field(..) => {} // ignore
1463 ProjectionKind::Subslice => {} // We never capture this
1467 let length = place.projections.len().min(truncated_length);
1469 place.projections.truncate(length);
1474 /// Truncates a place so that the resultant capture doesn't move data out of a reference
1475 fn truncate_capture_for_move(mut place: Place<'tcx>) -> Place<'tcx> {
1476 if let Some(i) = place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref) {
1477 // We only drop Derefs in case of move closures
1478 // There might be an index projection or raw ptr ahead, so we don't stop here.
1479 place.projections.truncate(i);
1485 fn construct_place_string(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
1486 let variable_name = match place.base {
1487 PlaceBase::Upvar(upvar_id) => var_name(tcx, upvar_id.var_path.hir_id).to_string(),
1488 _ => bug!("Capture_information should only contain upvars"),
1491 let mut projections_str = String::new();
1492 for (i, item) in place.projections.iter().enumerate() {
1493 let proj = match item.kind {
1494 ProjectionKind::Field(a, b) => format!("({:?}, {:?})", a, b),
1495 ProjectionKind::Deref => String::from("Deref"),
1496 ProjectionKind::Index => String::from("Index"),
1497 ProjectionKind::Subslice => String::from("Subslice"),
1500 projections_str.push(',');
1502 projections_str.push_str(proj.as_str());
1505 format!("{}[{}]", variable_name, projections_str)
1508 fn construct_capture_kind_reason_string(
1510 place: &Place<'tcx>,
1511 capture_info: &ty::CaptureInfo<'tcx>,
1513 let place_str = construct_place_string(tcx, &place);
1515 let capture_kind_str = match capture_info.capture_kind {
1516 ty::UpvarCapture::ByValue(_) => "ByValue".into(),
1517 ty::UpvarCapture::ByRef(borrow) => format!("{:?}", borrow.kind),
1520 format!("{} captured as {} here", place_str, capture_kind_str)
1523 fn construct_path_string(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
1524 let place_str = construct_place_string(tcx, &place);
1526 format!("{} used here", place_str)
1529 fn construct_capture_info_string(
1531 place: &Place<'tcx>,
1532 capture_info: &ty::CaptureInfo<'tcx>,
1534 let place_str = construct_place_string(tcx, &place);
1536 let capture_kind_str = match capture_info.capture_kind {
1537 ty::UpvarCapture::ByValue(_) => "ByValue".into(),
1538 ty::UpvarCapture::ByRef(borrow) => format!("{:?}", borrow.kind),
1540 format!("{} -> {}", place_str, capture_kind_str)
1543 fn var_name(tcx: TyCtxt<'_>, var_hir_id: hir::HirId) -> Symbol {
1544 tcx.hir().name(var_hir_id)
1547 fn should_do_migration_analysis(tcx: TyCtxt<'_>, closure_id: hir::HirId) -> bool {
1549 tcx.lint_level_at_node(lint::builtin::DISJOINT_CAPTURE_DROP_REORDER, closure_id);
1551 !matches!(level, lint::Level::Allow)
1554 /// Return a two string tuple (s1, s2)
1555 /// - s1: Line of code that is needed for the migration: eg: `let _ = (&x, ...)`.
1556 /// - s2: Comma separated names of the variables being migrated.
1557 fn migration_suggestion_for_2229(
1559 need_migrations: &Vec<hir::HirId>,
1560 ) -> (String, String) {
1561 let need_migrations_variables =
1562 need_migrations.iter().map(|v| var_name(tcx, *v)).collect::<Vec<_>>();
1564 let migration_ref_concat =
1565 need_migrations_variables.iter().map(|v| format!("&{}", v)).collect::<Vec<_>>().join(", ");
1567 let migration_string = if 1 == need_migrations.len() {
1568 format!("let _ = {}", migration_ref_concat)
1570 format!("let _ = ({})", migration_ref_concat)
1573 let migrated_variables_concat =
1574 need_migrations_variables.iter().map(|v| format!("`{}`", v)).collect::<Vec<_>>().join(", ");
1576 (migration_string, migrated_variables_concat)
1579 /// Helper function to determine if we need to escalate CaptureKind from
1580 /// CaptureInfo A to B and returns the escalated CaptureInfo.
1581 /// (Note: CaptureInfo contains CaptureKind and an expression that led to capture it in that way)
1583 /// If both `CaptureKind`s are considered equivalent, then the CaptureInfo is selected based
1584 /// on the `CaptureInfo` containing an associated `capture_kind_expr_id`.
1586 /// It is the caller's duty to figure out which path_expr_id to use.
1588 /// If both the CaptureKind and Expression are considered to be equivalent,
1589 /// then `CaptureInfo` A is preferred. This can be useful in cases where we want to priortize
1590 /// expressions reported back to the user as part of diagnostics based on which appears earlier
1591 /// in the closure. This can be achieved simply by calling
1592 /// `determine_capture_info(existing_info, current_info)`. This works out because the
1593 /// expressions that occur earlier in the closure body than the current expression are processed before.
1594 /// Consider the following example
1596 /// struct Point { x: i32, y: i32 }
1597 /// let mut p: Point { x: 10, y: 10 };
1605 /// p.x += 10; // E2
1609 /// `CaptureKind` associated with both `E1` and `E2` will be ByRef(MutBorrow),
1610 /// and both have an expression associated, however for diagnostics we prefer reporting
1611 /// `E1` since it appears earlier in the closure body. When `E2` is being processed we
1612 /// would've already handled `E1`, and have an existing capture_information for it.
1613 /// Calling `determine_capture_info(existing_info_e1, current_info_e2)` will return
1614 /// `existing_info_e1` in this case, allowing us to point to `E1` in case of diagnostics.
1615 fn determine_capture_info(
1616 capture_info_a: ty::CaptureInfo<'tcx>,
1617 capture_info_b: ty::CaptureInfo<'tcx>,
1618 ) -> ty::CaptureInfo<'tcx> {
1619 // If the capture kind is equivalent then, we don't need to escalate and can compare the
1621 let eq_capture_kind = match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
1622 (ty::UpvarCapture::ByValue(_), ty::UpvarCapture::ByValue(_)) => {
1623 // We don't need to worry about the spans being ignored here.
1625 // The expr_id in capture_info corresponds to the span that is stored within
1626 // ByValue(span) and therefore it gets handled with priortizing based on
1627 // expressions below.
1630 (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => {
1631 ref_a.kind == ref_b.kind
1633 (ty::UpvarCapture::ByValue(_), _) | (ty::UpvarCapture::ByRef(_), _) => false,
1636 if eq_capture_kind {
1637 match (capture_info_a.capture_kind_expr_id, capture_info_b.capture_kind_expr_id) {
1638 (Some(_), _) | (None, None) => capture_info_a,
1639 (None, Some(_)) => capture_info_b,
1642 // We select the CaptureKind which ranks higher based the following priority order:
1643 // ByValue > MutBorrow > UniqueImmBorrow > ImmBorrow
1644 match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
1645 (ty::UpvarCapture::ByValue(_), _) => capture_info_a,
1646 (_, ty::UpvarCapture::ByValue(_)) => capture_info_b,
1647 (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => {
1648 match (ref_a.kind, ref_b.kind) {
1650 (ty::UniqueImmBorrow | ty::MutBorrow, ty::ImmBorrow)
1651 | (ty::MutBorrow, ty::UniqueImmBorrow) => capture_info_a,
1654 (ty::ImmBorrow, ty::UniqueImmBorrow | ty::MutBorrow)
1655 | (ty::UniqueImmBorrow, ty::MutBorrow) => capture_info_b,
1657 (ty::ImmBorrow, ty::ImmBorrow)
1658 | (ty::UniqueImmBorrow, ty::UniqueImmBorrow)
1659 | (ty::MutBorrow, ty::MutBorrow) => {
1660 bug!("Expected unequal capture kinds");
1668 /// Determines the Ancestry relationship of Place A relative to Place B
1670 /// `PlaceAncestryRelation::Ancestor` implies Place A is ancestor of Place B
1671 /// `PlaceAncestryRelation::Descendant` implies Place A is descendant of Place B
1672 /// `PlaceAncestryRelation::Divergent` implies neither of them is the ancestor of the other.
1673 fn determine_place_ancestry_relation(
1674 place_a: &Place<'tcx>,
1675 place_b: &Place<'tcx>,
1676 ) -> PlaceAncestryRelation {
1677 // If Place A and Place B, don't start off from the same root variable, they are divergent.
1678 if place_a.base != place_b.base {
1679 return PlaceAncestryRelation::Divergent;
1682 // Assume of length of projections_a = n
1683 let projections_a = &place_a.projections;
1685 // Assume of length of projections_b = m
1686 let projections_b = &place_b.projections;
1688 let same_initial_projections =
1689 iter::zip(projections_a, projections_b).all(|(proj_a, proj_b)| proj_a == proj_b);
1691 if same_initial_projections {
1692 // First min(n, m) projections are the same
1693 // Select Ancestor/Descendant
1694 if projections_b.len() >= projections_a.len() {
1695 PlaceAncestryRelation::Ancestor
1697 PlaceAncestryRelation::Descendant
1700 PlaceAncestryRelation::Divergent