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_errors::Applicability;
38 use rustc_hir::def_id::DefId;
39 use rustc_hir::def_id::LocalDefId;
40 use rustc_hir::intravisit::{self, Visitor};
41 use rustc_infer::infer::UpvarRegion;
42 use rustc_middle::hir::place::{Place, PlaceBase, PlaceWithHirId, Projection, ProjectionKind};
43 use rustc_middle::mir::FakeReadCause;
44 use rustc_middle::ty::{
45 self, ClosureSizeProfileData, Ty, TyCtxt, TypeckResults, UpvarCapture, UpvarSubsts,
47 use rustc_session::lint;
49 use rustc_span::{BytePos, MultiSpan, Pos, Span, Symbol};
50 use rustc_trait_selection::infer::InferCtxtExt;
52 use rustc_data_structures::stable_map::FxHashMap;
53 use rustc_data_structures::stable_set::FxHashSet;
54 use rustc_index::vec::Idx;
55 use rustc_target::abi::VariantIdx;
59 /// Describe the relationship between the paths of two places
61 /// - `foo` is ancestor of `foo.bar.baz`
62 /// - `foo.bar.baz` is an descendant of `foo.bar`
63 /// - `foo.bar` and `foo.baz` are divergent
64 enum PlaceAncestryRelation {
71 /// Intermediate format to store a captured `Place` and associated `ty::CaptureInfo`
72 /// during capture analysis. Information in this map feeds into the minimum capture
74 type InferredCaptureInformation<'tcx> = Vec<(Place<'tcx>, ty::CaptureInfo)>;
76 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
77 pub fn closure_analyze(&self, body: &'tcx hir::Body<'tcx>) {
78 InferBorrowKindVisitor { fcx: self }.visit_body(body);
80 // it's our job to process these.
81 assert!(self.deferred_call_resolutions.borrow().is_empty());
85 /// Intermediate format to store the hir_id pointing to the use that resulted in the
86 /// corresponding place being captured and a String which contains the captured value's
88 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
89 enum UpvarMigrationInfo {
90 /// We previously captured all of `x`, but now we capture some sub-path.
91 CapturingPrecise { source_expr: Option<hir::HirId>, var_name: String },
93 // where the variable appears in the closure (but is not captured)
98 /// Reasons that we might issue a migration warning.
99 #[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
100 struct MigrationWarningReason {
101 /// When we used to capture `x` in its entirety, we implemented the auto-trait(s)
102 /// in this vec, but now we don't.
103 auto_traits: Vec<&'static str>,
105 /// When we used to capture `x` in its entirety, we would execute some destructors
106 /// at a different time.
110 impl MigrationWarningReason {
111 fn migration_message(&self) -> String {
112 let base = "changes to closure capture in Rust 2021 will affect";
113 if !self.auto_traits.is_empty() && self.drop_order {
114 format!("{} drop order and which traits the closure implements", base)
115 } else if self.drop_order {
116 format!("{} drop order", base)
118 format!("{} which traits the closure implements", base)
123 /// Intermediate format to store information needed to generate a note in the migration lint.
124 struct MigrationLintNote {
125 captures_info: UpvarMigrationInfo,
127 /// reasons why migration is needed for this capture
128 reason: MigrationWarningReason,
131 /// Intermediate format to store the hir id of the root variable and a HashSet containing
132 /// information on why the root variable should be fully captured
133 struct NeededMigration {
134 var_hir_id: hir::HirId,
135 diagnostics_info: Vec<MigrationLintNote>,
138 struct InferBorrowKindVisitor<'a, 'tcx> {
139 fcx: &'a FnCtxt<'a, 'tcx>,
142 impl<'a, 'tcx> Visitor<'tcx> for InferBorrowKindVisitor<'a, 'tcx> {
143 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
145 hir::ExprKind::Closure(cc, _, body_id, _, _) => {
146 let body = self.fcx.tcx.hir().body(body_id);
147 self.visit_body(body);
148 self.fcx.analyze_closure(expr.hir_id, expr.span, body_id, body, cc);
150 hir::ExprKind::ConstBlock(anon_const) => {
151 let body = self.fcx.tcx.hir().body(anon_const.body);
152 self.visit_body(body);
157 intravisit::walk_expr(self, expr);
161 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
162 /// Analysis starting point.
163 #[instrument(skip(self, body), level = "debug")]
166 closure_hir_id: hir::HirId,
168 body_id: hir::BodyId,
169 body: &'tcx hir::Body<'tcx>,
170 capture_clause: hir::CaptureBy,
172 // Extract the type of the closure.
173 let ty = self.node_ty(closure_hir_id);
174 let (closure_def_id, substs) = match *ty.kind() {
175 ty::Closure(def_id, substs) => (def_id, UpvarSubsts::Closure(substs)),
176 ty::Generator(def_id, substs, _) => (def_id, UpvarSubsts::Generator(substs)),
178 // #51714: skip analysis when we have already encountered type errors
184 "type of closure expr {:?} is not a closure {:?}",
191 let infer_kind = if let UpvarSubsts::Closure(closure_substs) = substs {
192 self.closure_kind(closure_substs).is_none().then_some(closure_substs)
197 let local_def_id = closure_def_id.expect_local();
199 let body_owner_def_id = self.tcx.hir().body_owner_def_id(body.id());
200 assert_eq!(body_owner_def_id.to_def_id(), closure_def_id);
201 let mut delegate = InferBorrowKind {
203 closure_def_id: local_def_id,
204 capture_information: Default::default(),
205 fake_reads: Default::default(),
207 euv::ExprUseVisitor::new(
212 &self.typeck_results.borrow(),
217 "For closure={:?}, capture_information={:#?}",
218 closure_def_id, delegate.capture_information
221 self.log_capture_analysis_first_pass(closure_def_id, &delegate.capture_information, span);
223 let (capture_information, closure_kind, origin) = self
224 .process_collected_capture_information(capture_clause, delegate.capture_information);
226 self.compute_min_captures(closure_def_id, capture_information, span);
228 let closure_hir_id = self.tcx.hir().local_def_id_to_hir_id(local_def_id);
230 if should_do_rust_2021_incompatible_closure_captures_analysis(self.tcx, closure_hir_id) {
231 self.perform_2229_migration_anaysis(closure_def_id, body_id, capture_clause, span);
234 let after_feature_tys = self.final_upvar_tys(closure_def_id);
236 // We now fake capture information for all variables that are mentioned within the closure
237 // We do this after handling migrations so that min_captures computes before
238 if !enable_precise_capture(self.tcx, span) {
239 let mut capture_information: InferredCaptureInformation<'tcx> = Default::default();
241 if let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) {
242 for var_hir_id in upvars.keys() {
243 let place = self.place_for_root_variable(local_def_id, *var_hir_id);
245 debug!("seed place {:?}", place);
247 let capture_kind = self.init_capture_kind_for_place(&place, capture_clause);
248 let fake_info = ty::CaptureInfo {
249 capture_kind_expr_id: None,
254 capture_information.push((place, fake_info));
258 // This will update the min captures based on this new fake information.
259 self.compute_min_captures(closure_def_id, capture_information, span);
262 let before_feature_tys = self.final_upvar_tys(closure_def_id);
264 if let Some(closure_substs) = infer_kind {
265 // Unify the (as yet unbound) type variable in the closure
266 // substs with the kind we inferred.
267 let closure_kind_ty = closure_substs.as_closure().kind_ty();
268 self.demand_eqtype(span, closure_kind.to_ty(self.tcx), closure_kind_ty);
270 // If we have an origin, store it.
271 if let Some(origin) = origin {
272 let origin = if enable_precise_capture(self.tcx, span) {
275 (origin.0, Place { projections: vec![], ..origin.1 })
280 .closure_kind_origins_mut()
281 .insert(closure_hir_id, origin);
285 self.log_closure_min_capture_info(closure_def_id, span);
287 // Now that we've analyzed the closure, we know how each
288 // variable is borrowed, and we know what traits the closure
289 // implements (Fn vs FnMut etc). We now have some updates to do
290 // with that information.
292 // Note that no closure type C may have an upvar of type C
293 // (though it may reference itself via a trait object). This
294 // results from the desugaring of closures to a struct like
295 // `Foo<..., UV0...UVn>`. If one of those upvars referenced
296 // C, then the type would have infinite size (and the
297 // inference algorithm will reject it).
299 // Equate the type variables for the upvars with the actual types.
300 let final_upvar_tys = self.final_upvar_tys(closure_def_id);
302 "analyze_closure: id={:?} substs={:?} final_upvar_tys={:?}",
303 closure_hir_id, substs, final_upvar_tys
306 // Build a tuple (U0..Un) of the final upvar types U0..Un
307 // and unify the upvar tupe type in the closure with it:
308 let final_tupled_upvars_type = self.tcx.mk_tup(final_upvar_tys.iter());
309 self.demand_suptype(span, substs.tupled_upvars_ty(), final_tupled_upvars_type);
311 let fake_reads = delegate
314 .map(|(place, cause, hir_id)| (place, cause, hir_id))
316 self.typeck_results.borrow_mut().closure_fake_reads.insert(closure_def_id, fake_reads);
318 if self.tcx.sess.opts.debugging_opts.profile_closures {
319 self.typeck_results.borrow_mut().closure_size_eval.insert(
321 ClosureSizeProfileData {
322 before_feature_tys: self.tcx.mk_tup(before_feature_tys.into_iter()),
323 after_feature_tys: self.tcx.mk_tup(after_feature_tys.into_iter()),
328 // If we are also inferred the closure kind here,
329 // process any deferred resolutions.
330 let deferred_call_resolutions = self.remove_deferred_call_resolutions(closure_def_id);
331 for deferred_call_resolution in deferred_call_resolutions {
332 deferred_call_resolution.resolve(self);
336 // Returns a list of `Ty`s for each upvar.
337 fn final_upvar_tys(&self, closure_id: DefId) -> Vec<Ty<'tcx>> {
338 // Presently an unboxed closure type cannot "escape" out of a
339 // function, so we will only encounter ones that originated in the
340 // local crate or were inlined into it along with some function.
341 // This may change if abstract return types of some sort are
345 .closure_min_captures_flattened(closure_id)
346 .map(|captured_place| {
347 let upvar_ty = captured_place.place.ty();
348 let capture = captured_place.info.capture_kind;
351 "final_upvar_tys: place={:?} upvar_ty={:?} capture={:?}, mutability={:?}",
352 captured_place.place, upvar_ty, capture, captured_place.mutability,
355 apply_capture_kind_on_capture_ty(self.tcx, upvar_ty, capture, captured_place.region)
360 /// Adjusts the closure capture information to ensure that the operations aren't unsafe,
361 /// and that the path can be captured with required capture kind (depending on use in closure,
362 /// move closure etc.)
364 /// Returns the set of of adjusted information along with the inferred closure kind and span
365 /// associated with the closure kind inference.
367 /// Note that we *always* infer a minimal kind, even if
368 /// we don't always *use* that in the final result (i.e., sometimes
369 /// we've taken the closure kind from the expectations instead, and
370 /// for generators we don't even implement the closure traits
373 /// If we inferred that the closure needs to be FnMut/FnOnce, last element of the returned tuple
374 /// contains a `Some()` with the `Place` that caused us to do so.
375 fn process_collected_capture_information(
377 capture_clause: hir::CaptureBy,
378 capture_information: InferredCaptureInformation<'tcx>,
379 ) -> (InferredCaptureInformation<'tcx>, ty::ClosureKind, Option<(Span, Place<'tcx>)>) {
380 let mut closure_kind = ty::ClosureKind::LATTICE_BOTTOM;
381 let mut origin: Option<(Span, Place<'tcx>)> = None;
383 let processed = capture_information
385 .map(|(place, mut capture_info)| {
386 // Apply rules for safety before inferring closure kind
387 let (place, capture_kind) =
388 restrict_capture_precision(place, capture_info.capture_kind);
390 let (place, capture_kind) = truncate_capture_for_optimization(place, capture_kind);
392 let usage_span = if let Some(usage_expr) = capture_info.path_expr_id {
393 self.tcx.hir().span(usage_expr)
398 let updated = match capture_kind {
399 ty::UpvarCapture::ByValue => match closure_kind {
400 ty::ClosureKind::Fn | ty::ClosureKind::FnMut => {
401 (ty::ClosureKind::FnOnce, Some((usage_span, place.clone())))
403 // If closure is already FnOnce, don't update
404 ty::ClosureKind::FnOnce => (closure_kind, origin.take()),
407 ty::UpvarCapture::ByRef(
408 ty::BorrowKind::MutBorrow | ty::BorrowKind::UniqueImmBorrow,
411 ty::ClosureKind::Fn => {
412 (ty::ClosureKind::FnMut, Some((usage_span, place.clone())))
414 // Don't update the origin
415 ty::ClosureKind::FnMut | ty::ClosureKind::FnOnce => {
416 (closure_kind, origin.take())
421 _ => (closure_kind, origin.take()),
424 closure_kind = updated.0;
427 let (place, capture_kind) = match capture_clause {
428 hir::CaptureBy::Value => adjust_for_move_closure(place, capture_kind),
429 hir::CaptureBy::Ref => adjust_for_non_move_closure(place, capture_kind),
432 // This restriction needs to be applied after we have handled adjustments for `move`
433 // closures. We want to make sure any adjustment that might make us move the place into
434 // the closure gets handled.
435 let (place, capture_kind) =
436 restrict_precision_for_drop_types(self, place, capture_kind, usage_span);
438 capture_info.capture_kind = capture_kind;
439 (place, capture_info)
443 (processed, closure_kind, origin)
446 /// Analyzes the information collected by `InferBorrowKind` to compute the min number of
447 /// Places (and corresponding capture kind) that we need to keep track of to support all
448 /// the required captured paths.
451 /// Note: If this function is called multiple times for the same closure, it will update
452 /// the existing min_capture map that is stored in TypeckResults.
456 /// struct Point { x: i32, y: i32 }
458 /// let s: String; // hir_id_s
459 /// let mut p: Point; // his_id_p
461 /// println!("{s}"); // L1
463 /// println!("{}" , p.y); // L3
464 /// println!("{p}"); // L4
468 /// and let hir_id_L1..5 be the expressions pointing to use of a captured variable on
469 /// the lines L1..5 respectively.
471 /// InferBorrowKind results in a structure like this:
475 /// Place(base: hir_id_s, projections: [], ....) -> {
476 /// capture_kind_expr: hir_id_L5,
477 /// path_expr_id: hir_id_L5,
478 /// capture_kind: ByValue
480 /// Place(base: hir_id_p, projections: [Field(0, 0)], ...) -> {
481 /// capture_kind_expr: hir_id_L2,
482 /// path_expr_id: hir_id_L2,
483 /// capture_kind: ByValue
485 /// Place(base: hir_id_p, projections: [Field(1, 0)], ...) -> {
486 /// capture_kind_expr: hir_id_L3,
487 /// path_expr_id: hir_id_L3,
488 /// capture_kind: ByValue
490 /// Place(base: hir_id_p, projections: [], ...) -> {
491 /// capture_kind_expr: hir_id_L4,
492 /// path_expr_id: hir_id_L4,
493 /// capture_kind: ByValue
497 /// After the min capture analysis, we get:
501 /// Place(base: hir_id_s, projections: [], ....) -> {
502 /// capture_kind_expr: hir_id_L5,
503 /// path_expr_id: hir_id_L5,
504 /// capture_kind: ByValue
508 /// Place(base: hir_id_p, projections: [], ...) -> {
509 /// capture_kind_expr: hir_id_L2,
510 /// path_expr_id: hir_id_L4,
511 /// capture_kind: ByValue
515 fn compute_min_captures(
517 closure_def_id: DefId,
518 capture_information: InferredCaptureInformation<'tcx>,
521 if capture_information.is_empty() {
525 let mut typeck_results = self.typeck_results.borrow_mut();
527 let mut root_var_min_capture_list =
528 typeck_results.closure_min_captures.remove(&closure_def_id).unwrap_or_default();
530 for (mut place, capture_info) in capture_information.into_iter() {
531 let var_hir_id = match place.base {
532 PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
533 base => bug!("Expected upvar, found={:?}", base),
536 let Some(min_cap_list) = root_var_min_capture_list.get_mut(&var_hir_id) else {
537 let mutability = self.determine_capture_mutability(&typeck_results, &place);
538 let min_cap_list = vec![ty::CapturedPlace {
544 root_var_min_capture_list.insert(var_hir_id, min_cap_list);
548 // Go through each entry in the current list of min_captures
549 // - if ancestor is found, update it's capture kind to account for current place's
550 // capture information.
552 // - if descendant is found, remove it from the list, and update the current place's
553 // capture information to account for the descendants's capture kind.
555 // We can never be in a case where the list contains both an ancestor and a descendant
556 // Also there can only be ancestor but in case of descendants there might be
559 let mut descendant_found = false;
560 let mut updated_capture_info = capture_info;
561 min_cap_list.retain(|possible_descendant| {
562 match determine_place_ancestry_relation(&place, &possible_descendant.place) {
563 // current place is ancestor of possible_descendant
564 PlaceAncestryRelation::Ancestor => {
565 descendant_found = true;
567 let mut possible_descendant = possible_descendant.clone();
568 let backup_path_expr_id = updated_capture_info.path_expr_id;
570 // Truncate the descendant (already in min_captures) to be same as the ancestor to handle any
571 // possible change in capture mode.
572 truncate_place_to_len_and_update_capture_kind(
573 &mut possible_descendant.place,
574 &mut possible_descendant.info.capture_kind,
575 place.projections.len(),
578 updated_capture_info =
579 determine_capture_info(updated_capture_info, possible_descendant.info);
581 // we need to keep the ancestor's `path_expr_id`
582 updated_capture_info.path_expr_id = backup_path_expr_id;
590 let mut ancestor_found = false;
591 if !descendant_found {
592 for possible_ancestor in min_cap_list.iter_mut() {
593 match determine_place_ancestry_relation(&place, &possible_ancestor.place) {
594 PlaceAncestryRelation::SamePlace => {
595 ancestor_found = true;
596 possible_ancestor.info = determine_capture_info(
597 possible_ancestor.info,
598 updated_capture_info,
601 // Only one related place will be in the list.
604 // current place is descendant of possible_ancestor
605 PlaceAncestryRelation::Descendant => {
606 ancestor_found = true;
607 let backup_path_expr_id = possible_ancestor.info.path_expr_id;
609 // Truncate the descendant (current place) to be same as the ancestor to handle any
610 // possible change in capture mode.
611 truncate_place_to_len_and_update_capture_kind(
613 &mut updated_capture_info.capture_kind,
614 possible_ancestor.place.projections.len(),
617 possible_ancestor.info = determine_capture_info(
618 possible_ancestor.info,
619 updated_capture_info,
622 // we need to keep the ancestor's `path_expr_id`
623 possible_ancestor.info.path_expr_id = backup_path_expr_id;
625 // Only one related place will be in the list.
633 // Only need to insert when we don't have an ancestor in the existing min capture list
635 let mutability = self.determine_capture_mutability(&typeck_results, &place);
636 let captured_place = ty::CapturedPlace {
638 info: updated_capture_info,
642 min_cap_list.push(captured_place);
646 // For each capture that is determined to be captured by ref, add region info.
647 for (_, captures) in &mut root_var_min_capture_list {
648 for capture in captures {
649 match capture.info.capture_kind {
650 ty::UpvarCapture::ByRef(_) => {
651 let PlaceBase::Upvar(upvar_id) = capture.place.base else { bug!("expected upvar") };
652 let origin = UpvarRegion(upvar_id, closure_span);
653 let upvar_region = self.next_region_var(origin);
654 capture.region = Some(upvar_region);
662 "For closure={:?}, min_captures before sorting={:?}",
663 closure_def_id, root_var_min_capture_list
666 // Now that we have the minimized list of captures, sort the captures by field id.
667 // This causes the closure to capture the upvars in the same order as the fields are
668 // declared which is also the drop order. Thus, in situations where we capture all the
669 // fields of some type, the obserable drop order will remain the same as it previously
670 // was even though we're dropping each capture individually.
671 // See https://github.com/rust-lang/project-rfc-2229/issues/42 and
672 // `src/test/ui/closures/2229_closure_analysis/preserve_field_drop_order.rs`.
673 for (_, captures) in &mut root_var_min_capture_list {
674 captures.sort_by(|capture1, capture2| {
675 for (p1, p2) in capture1.place.projections.iter().zip(&capture2.place.projections) {
676 // We do not need to look at the `Projection.ty` fields here because at each
677 // step of the iteration, the projections will either be the same and therefore
678 // the types must be as well or the current projection will be different and
679 // we will return the result of comparing the field indexes.
680 match (p1.kind, p2.kind) {
681 // Paths are the same, continue to next loop.
682 (ProjectionKind::Deref, ProjectionKind::Deref) => {}
683 (ProjectionKind::Field(i1, _), ProjectionKind::Field(i2, _))
686 // Fields are different, compare them.
687 (ProjectionKind::Field(i1, _), ProjectionKind::Field(i2, _)) => {
691 // We should have either a pair of `Deref`s or a pair of `Field`s.
692 // Anything else is a bug.
694 l @ (ProjectionKind::Deref | ProjectionKind::Field(..)),
695 r @ (ProjectionKind::Deref | ProjectionKind::Field(..)),
697 "ProjectionKinds Deref and Field were mismatched: ({:?}, {:?})",
702 l @ (ProjectionKind::Index
703 | ProjectionKind::Subslice
704 | ProjectionKind::Deref
705 | ProjectionKind::Field(..)),
706 r @ (ProjectionKind::Index
707 | ProjectionKind::Subslice
708 | ProjectionKind::Deref
709 | ProjectionKind::Field(..)),
711 "ProjectionKinds Index or Subslice were unexpected: ({:?}, {:?})",
719 "we captured two identical projections: capture1 = {:?}, capture2 = {:?}",
726 "For closure={:?}, min_captures after sorting={:#?}",
727 closure_def_id, root_var_min_capture_list
729 typeck_results.closure_min_captures.insert(closure_def_id, root_var_min_capture_list);
732 /// Perform the migration analysis for RFC 2229, and emit lint
733 /// `disjoint_capture_drop_reorder` if needed.
734 fn perform_2229_migration_anaysis(
736 closure_def_id: DefId,
737 body_id: hir::BodyId,
738 capture_clause: hir::CaptureBy,
741 let (need_migrations, reasons) = self.compute_2229_migrations(
745 self.typeck_results.borrow().closure_min_captures.get(&closure_def_id),
748 if !need_migrations.is_empty() {
749 let (migration_string, migrated_variables_concat) =
750 migration_suggestion_for_2229(self.tcx, &need_migrations);
752 let local_def_id = closure_def_id.expect_local();
753 let closure_hir_id = self.tcx.hir().local_def_id_to_hir_id(local_def_id);
754 let closure_span = self.tcx.hir().span(closure_hir_id);
755 let closure_head_span = self.tcx.sess.source_map().guess_head_span(closure_span);
756 self.tcx.struct_span_lint_hir(
757 lint::builtin::RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES,
761 let mut diagnostics_builder = lint.build(
762 &reasons.migration_message(),
764 for NeededMigration { var_hir_id, diagnostics_info } in &need_migrations {
765 // Labels all the usage of the captured variable and why they are responsible
766 // for migration being needed
767 for lint_note in diagnostics_info.iter() {
768 match &lint_note.captures_info {
769 UpvarMigrationInfo::CapturingPrecise { source_expr: Some(capture_expr_id), var_name: captured_name } => {
770 let cause_span = self.tcx.hir().span(*capture_expr_id);
771 diagnostics_builder.span_label(cause_span, format!("in Rust 2018, this closure captures all of `{}`, but in Rust 2021, it will only capture `{}`",
772 self.tcx.hir().name(*var_hir_id),
776 UpvarMigrationInfo::CapturingNothing { use_span } => {
777 diagnostics_builder.span_label(*use_span, format!("in Rust 2018, this causes the closure to capture `{}`, but in Rust 2021, it has no effect",
778 self.tcx.hir().name(*var_hir_id),
785 // Add a label pointing to where a captured variable affected by drop order
787 if lint_note.reason.drop_order {
788 let drop_location_span = drop_location_span(self.tcx, closure_hir_id);
790 match &lint_note.captures_info {
791 UpvarMigrationInfo::CapturingPrecise { var_name: captured_name, .. } => {
792 diagnostics_builder.span_label(drop_location_span, format!("in Rust 2018, `{}` is dropped here, but in Rust 2021, only `{}` will be dropped here as part of the closure",
793 self.tcx.hir().name(*var_hir_id),
797 UpvarMigrationInfo::CapturingNothing { use_span: _ } => {
798 diagnostics_builder.span_label(drop_location_span, format!("in Rust 2018, `{v}` is dropped here along with the closure, but in Rust 2021 `{v}` is not part of the closure",
799 v = self.tcx.hir().name(*var_hir_id),
805 // Add a label explaining why a closure no longer implements a trait
806 for &missing_trait in &lint_note.reason.auto_traits {
807 // not capturing something anymore cannot cause a trait to fail to be implemented:
808 match &lint_note.captures_info {
809 UpvarMigrationInfo::CapturingPrecise { var_name: captured_name, .. } => {
810 let var_name = self.tcx.hir().name(*var_hir_id);
811 diagnostics_builder.span_label(closure_head_span, format!("\
812 in Rust 2018, this closure implements {missing_trait} \
813 as `{var_name}` implements {missing_trait}, but in Rust 2021, \
814 this closure will no longer implement {missing_trait} \
815 because `{var_name}` is not fully captured \
816 and `{captured_name}` does not implement {missing_trait}"));
819 // Cannot happen: if we don't capture a variable, we impl strictly more traits
820 UpvarMigrationInfo::CapturingNothing { use_span } => span_bug!(*use_span, "missing trait from not capturing something"),
825 diagnostics_builder.note("for more information, see <https://doc.rust-lang.org/nightly/edition-guide/rust-2021/disjoint-capture-in-closures.html>");
827 let diagnostic_msg = format!(
828 "add a dummy let to cause {} to be fully captured",
829 migrated_variables_concat
832 let mut closure_body_span = {
833 // If the body was entirely expanded from a macro
834 // invocation, i.e. the body is not contained inside the
835 // closure span, then we walk up the expansion until we
836 // find the span before the expansion.
837 let s = self.tcx.hir().span(body_id.hir_id);
838 s.find_ancestor_inside(closure_span).unwrap_or(s)
841 if let Ok(mut s) = self.tcx.sess.source_map().span_to_snippet(closure_body_span) {
842 if s.starts_with('$') {
843 // Looks like a macro fragment. Try to find the real block.
844 if let Some(hir::Node::Expr(&hir::Expr {
845 kind: hir::ExprKind::Block(block, ..), ..
846 })) = self.tcx.hir().find(body_id.hir_id) {
847 // If the body is a block (with `{..}`), we use the span of that block.
848 // E.g. with a `|| $body` expanded from a `m!({ .. })`, we use `{ .. }`, and not `$body`.
849 // Since we know it's a block, we know we can insert the `let _ = ..` without
850 // breaking the macro syntax.
851 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(block.span) {
852 closure_body_span = block.span;
858 let mut lines = s.lines();
859 let line1 = lines.next().unwrap_or_default();
861 if line1.trim_end() == "{" {
862 // This is a multi-line closure with just a `{` on the first line,
863 // so we put the `let` on its own line.
864 // We take the indentation from the next non-empty line.
865 let line2 = lines.find(|line| !line.is_empty()).unwrap_or_default();
866 let indent = line2.split_once(|c: char| !c.is_whitespace()).unwrap_or_default().0;
867 diagnostics_builder.span_suggestion(
868 closure_body_span.with_lo(closure_body_span.lo() + BytePos::from_usize(line1.len())).shrink_to_lo(),
870 format!("\n{}{};", indent, migration_string),
871 Applicability::MachineApplicable,
873 } else if line1.starts_with('{') {
874 // This is a closure with its body wrapped in
875 // braces, but with more than just the opening
876 // brace on the first line. We put the `let`
877 // directly after the `{`.
878 diagnostics_builder.span_suggestion(
879 closure_body_span.with_lo(closure_body_span.lo() + BytePos(1)).shrink_to_lo(),
881 format!(" {};", migration_string),
882 Applicability::MachineApplicable,
885 // This is a closure without braces around the body.
886 // We add braces to add the `let` before the body.
887 diagnostics_builder.multipart_suggestion(
890 (closure_body_span.shrink_to_lo(), format!("{{ {}; ", migration_string)),
891 (closure_body_span.shrink_to_hi(), " }".to_string()),
893 Applicability::MachineApplicable
897 diagnostics_builder.span_suggestion(
901 Applicability::HasPlaceholders
905 diagnostics_builder.emit();
911 /// Combines all the reasons for 2229 migrations
912 fn compute_2229_migrations_reasons(
914 auto_trait_reasons: FxHashSet<&'static str>,
916 ) -> MigrationWarningReason {
917 let mut reasons = MigrationWarningReason::default();
919 reasons.auto_traits.extend(auto_trait_reasons);
920 reasons.drop_order = drop_order;
925 /// Figures out the list of root variables (and their types) that aren't completely
926 /// captured by the closure when `capture_disjoint_fields` is enabled and auto-traits
927 /// differ between the root variable and the captured paths.
929 /// Returns a tuple containing a HashMap of CapturesInfo that maps to a HashSet of trait names
930 /// if migration is needed for traits for the provided var_hir_id, otherwise returns None
931 fn compute_2229_migrations_for_trait(
933 min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
934 var_hir_id: hir::HirId,
935 closure_clause: hir::CaptureBy,
936 ) -> Option<FxHashMap<UpvarMigrationInfo, FxHashSet<&'static str>>> {
937 let auto_traits_def_id = vec![
938 self.tcx.lang_items().clone_trait(),
939 self.tcx.lang_items().sync_trait(),
940 self.tcx.get_diagnostic_item(sym::Send),
941 self.tcx.lang_items().unpin_trait(),
942 self.tcx.get_diagnostic_item(sym::unwind_safe_trait),
943 self.tcx.get_diagnostic_item(sym::ref_unwind_safe_trait),
945 const AUTO_TRAITS: [&str; 6] =
946 ["`Clone`", "`Sync`", "`Send`", "`Unpin`", "`UnwindSafe`", "`RefUnwindSafe`"];
948 let root_var_min_capture_list = min_captures.and_then(|m| m.get(&var_hir_id))?;
950 let ty = self.infcx.resolve_vars_if_possible(self.node_ty(var_hir_id));
952 let ty = match closure_clause {
953 hir::CaptureBy::Value => ty, // For move closure the capture kind should be by value
954 hir::CaptureBy::Ref => {
955 // For non move closure the capture kind is the max capture kind of all captures
956 // according to the ordering ImmBorrow < UniqueImmBorrow < MutBorrow < ByValue
957 let mut max_capture_info = root_var_min_capture_list.first().unwrap().info;
958 for capture in root_var_min_capture_list.iter() {
959 max_capture_info = determine_capture_info(max_capture_info, capture.info);
962 apply_capture_kind_on_capture_ty(
965 max_capture_info.capture_kind,
966 Some(self.tcx.lifetimes.re_erased),
971 let mut obligations_should_hold = Vec::new();
972 // Checks if a root variable implements any of the auto traits
973 for check_trait in auto_traits_def_id.iter() {
974 obligations_should_hold.push(
978 .type_implements_trait(
981 self.tcx.mk_substs_trait(ty, &[]),
984 .must_apply_modulo_regions()
990 let mut problematic_captures = FxHashMap::default();
991 // Check whether captured fields also implement the trait
992 for capture in root_var_min_capture_list.iter() {
993 let ty = apply_capture_kind_on_capture_ty(
996 capture.info.capture_kind,
997 Some(self.tcx.lifetimes.re_erased),
1000 // Checks if a capture implements any of the auto traits
1001 let mut obligations_holds_for_capture = Vec::new();
1002 for check_trait in auto_traits_def_id.iter() {
1003 obligations_holds_for_capture.push(
1005 .map(|check_trait| {
1007 .type_implements_trait(
1010 self.tcx.mk_substs_trait(ty, &[]),
1013 .must_apply_modulo_regions()
1019 let mut capture_problems = FxHashSet::default();
1021 // Checks if for any of the auto traits, one or more trait is implemented
1022 // by the root variable but not by the capture
1023 for (idx, _) in obligations_should_hold.iter().enumerate() {
1024 if !obligations_holds_for_capture[idx] && obligations_should_hold[idx] {
1025 capture_problems.insert(AUTO_TRAITS[idx]);
1029 if !capture_problems.is_empty() {
1030 problematic_captures.insert(
1031 UpvarMigrationInfo::CapturingPrecise {
1032 source_expr: capture.info.path_expr_id,
1033 var_name: capture.to_string(self.tcx),
1039 if !problematic_captures.is_empty() {
1040 return Some(problematic_captures);
1045 /// Figures out the list of root variables (and their types) that aren't completely
1046 /// captured by the closure when `capture_disjoint_fields` is enabled and drop order of
1047 /// some path starting at that root variable **might** be affected.
1049 /// The output list would include a root variable if:
1050 /// - It would have been moved into the closure when `capture_disjoint_fields` wasn't
1051 /// enabled, **and**
1052 /// - It wasn't completely captured by the closure, **and**
1053 /// - One of the paths starting at this root variable, that is not captured needs Drop.
1055 /// This function only returns a HashSet of CapturesInfo for significant drops. If there
1056 /// are no significant drops than None is returned
1057 #[instrument(level = "debug", skip(self))]
1058 fn compute_2229_migrations_for_drop(
1060 closure_def_id: DefId,
1062 min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
1063 closure_clause: hir::CaptureBy,
1064 var_hir_id: hir::HirId,
1065 ) -> Option<FxHashSet<UpvarMigrationInfo>> {
1066 let ty = self.infcx.resolve_vars_if_possible(self.node_ty(var_hir_id));
1068 if !ty.has_significant_drop(self.tcx, self.tcx.param_env(closure_def_id.expect_local())) {
1069 debug!("does not have significant drop");
1073 let Some(root_var_min_capture_list) = min_captures.and_then(|m| m.get(&var_hir_id)) else {
1074 // The upvar is mentioned within the closure but no path starting from it is
1075 // used. This occurs when you have (e.g.)
1078 // let x = move || {
1082 debug!("no path starting from it is used");
1085 match closure_clause {
1086 // Only migrate if closure is a move closure
1087 hir::CaptureBy::Value => {
1088 let mut diagnostics_info = FxHashSet::default();
1089 let upvars = self.tcx.upvars_mentioned(closure_def_id).expect("must be an upvar");
1090 let upvar = upvars[&var_hir_id];
1091 diagnostics_info.insert(UpvarMigrationInfo::CapturingNothing { use_span: upvar.span });
1092 return Some(diagnostics_info);
1094 hir::CaptureBy::Ref => {}
1099 debug!(?root_var_min_capture_list);
1101 let mut projections_list = Vec::new();
1102 let mut diagnostics_info = FxHashSet::default();
1104 for captured_place in root_var_min_capture_list.iter() {
1105 match captured_place.info.capture_kind {
1106 // Only care about captures that are moved into the closure
1107 ty::UpvarCapture::ByValue => {
1108 projections_list.push(captured_place.place.projections.as_slice());
1109 diagnostics_info.insert(UpvarMigrationInfo::CapturingPrecise {
1110 source_expr: captured_place.info.path_expr_id,
1111 var_name: captured_place.to_string(self.tcx),
1114 ty::UpvarCapture::ByRef(..) => {}
1118 debug!(?projections_list);
1119 debug!(?diagnostics_info);
1121 let is_moved = !projections_list.is_empty();
1124 let is_not_completely_captured =
1125 root_var_min_capture_list.iter().any(|capture| !capture.place.projections.is_empty());
1126 debug!(?is_not_completely_captured);
1129 && is_not_completely_captured
1130 && self.has_significant_drop_outside_of_captures(
1137 return Some(diagnostics_info);
1143 /// Figures out the list of root variables (and their types) that aren't completely
1144 /// captured by the closure when `capture_disjoint_fields` is enabled and either drop
1145 /// order of some path starting at that root variable **might** be affected or auto-traits
1146 /// differ between the root variable and the captured paths.
1148 /// The output list would include a root variable if:
1149 /// - It would have been moved into the closure when `capture_disjoint_fields` wasn't
1150 /// enabled, **and**
1151 /// - It wasn't completely captured by the closure, **and**
1152 /// - One of the paths starting at this root variable, that is not captured needs Drop **or**
1153 /// - One of the paths captured does not implement all the auto-traits its root variable
1156 /// Returns a tuple containing a vector of MigrationDiagnosticInfo, as well as a String
1157 /// containing the reason why root variables whose HirId is contained in the vector should
1159 #[instrument(level = "debug", skip(self))]
1160 fn compute_2229_migrations(
1162 closure_def_id: DefId,
1164 closure_clause: hir::CaptureBy,
1165 min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
1166 ) -> (Vec<NeededMigration>, MigrationWarningReason) {
1167 let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) else {
1168 return (Vec::new(), MigrationWarningReason::default());
1171 let mut need_migrations = Vec::new();
1172 let mut auto_trait_migration_reasons = FxHashSet::default();
1173 let mut drop_migration_needed = false;
1175 // Perform auto-trait analysis
1176 for (&var_hir_id, _) in upvars.iter() {
1177 let mut diagnostics_info = Vec::new();
1179 let auto_trait_diagnostic = if let Some(diagnostics_info) =
1180 self.compute_2229_migrations_for_trait(min_captures, var_hir_id, closure_clause)
1184 FxHashMap::default()
1187 let drop_reorder_diagnostic = if let Some(diagnostics_info) = self
1188 .compute_2229_migrations_for_drop(
1195 drop_migration_needed = true;
1198 FxHashSet::default()
1201 // Combine all the captures responsible for needing migrations into one HashSet
1202 let mut capture_diagnostic = drop_reorder_diagnostic.clone();
1203 for key in auto_trait_diagnostic.keys() {
1204 capture_diagnostic.insert(key.clone());
1207 let mut capture_diagnostic = capture_diagnostic.into_iter().collect::<Vec<_>>();
1208 capture_diagnostic.sort();
1209 for captures_info in capture_diagnostic {
1210 // Get the auto trait reasons of why migration is needed because of that capture, if there are any
1211 let capture_trait_reasons =
1212 if let Some(reasons) = auto_trait_diagnostic.get(&captures_info) {
1215 FxHashSet::default()
1218 // Check if migration is needed because of drop reorder as a result of that capture
1219 let capture_drop_reorder_reason = drop_reorder_diagnostic.contains(&captures_info);
1221 // Combine all the reasons of why the root variable should be captured as a result of
1222 // auto trait implementation issues
1223 auto_trait_migration_reasons.extend(capture_trait_reasons.clone());
1225 diagnostics_info.push(MigrationLintNote {
1227 reason: self.compute_2229_migrations_reasons(
1228 capture_trait_reasons,
1229 capture_drop_reorder_reason,
1234 if !diagnostics_info.is_empty() {
1235 need_migrations.push(NeededMigration { var_hir_id, diagnostics_info });
1240 self.compute_2229_migrations_reasons(
1241 auto_trait_migration_reasons,
1242 drop_migration_needed,
1247 /// This is a helper function to `compute_2229_migrations_precise_pass`. Provided the type
1248 /// of a root variable and a list of captured paths starting at this root variable (expressed
1249 /// using list of `Projection` slices), it returns true if there is a path that is not
1250 /// captured starting at this root variable that implements Drop.
1252 /// The way this function works is at a given call it looks at type `base_path_ty` of some base
1253 /// path say P and then list of projection slices which represent the different captures moved
1254 /// into the closure starting off of P.
1256 /// This will make more sense with an example:
1259 /// #![feature(capture_disjoint_fields)]
1261 /// struct FancyInteger(i32); // This implements Drop
1263 /// struct Point { x: FancyInteger, y: FancyInteger }
1266 /// struct Wrapper { p: Point, c: Color }
1268 /// fn f(w: Wrapper) {
1270 /// // Closure captures w.p.x and w.c by move.
1277 /// If `capture_disjoint_fields` wasn't enabled the closure would've moved `w` instead of the
1278 /// precise paths. If we look closely `w.p.y` isn't captured which implements Drop and
1279 /// therefore Drop ordering would change and we want this function to return true.
1281 /// Call stack to figure out if we need to migrate for `w` would look as follows:
1283 /// Our initial base path is just `w`, and the paths captured from it are `w[p, x]` and
1286 /// - Ty(place): Type of place
1287 /// - `(a, b)`: Represents the function parameters `base_path_ty` and `captured_by_move_projs`
1290 /// (Ty(w), [ &[p, x], &[c] ])
1292 /// ----------------------------
1295 /// (Ty(w.p), [ &[x] ]) (Ty(w.c), [ &[] ]) // I(1)
1298 /// (Ty(w.p), [ &[x] ]) false
1301 /// -------------------------------
1304 /// (Ty((w.p).x), [ &[] ]) (Ty((w.p).y), []) // IMP 2
1307 /// false NeedsSignificantDrop(Ty(w.p.y))
1313 /// IMP 1 `(Ty(w.c), [ &[] ])`: Notice the single empty slice inside `captured_projs`.
1314 /// This implies that the `w.c` is completely captured by the closure.
1315 /// Since drop for this path will be called when the closure is
1316 /// dropped we don't need to migrate for it.
1318 /// IMP 2 `(Ty((w.p).y), [])`: Notice that `captured_projs` is empty. This implies that this
1319 /// path wasn't captured by the closure. Also note that even
1320 /// though we didn't capture this path, the function visits it,
1321 /// which is kind of the point of this function. We then return
1322 /// if the type of `w.p.y` implements Drop, which in this case is
1325 /// Consider another example:
1329 /// impl Drop for X {}
1332 /// impl Drop for Y {}
1336 /// let c = || move(y.0);
1340 /// Note that `y.0` is captured by the closure. When this function is called for `y`, it will
1341 /// return true, because even though all paths starting at `y` are captured, `y` itself
1342 /// implements Drop which will be affected since `y` isn't completely captured.
1343 fn has_significant_drop_outside_of_captures(
1345 closure_def_id: DefId,
1347 base_path_ty: Ty<'tcx>,
1348 captured_by_move_projs: Vec<&[Projection<'tcx>]>,
1350 let needs_drop = |ty: Ty<'tcx>| {
1351 ty.has_significant_drop(self.tcx, self.tcx.param_env(closure_def_id.expect_local()))
1354 let is_drop_defined_for_ty = |ty: Ty<'tcx>| {
1355 let drop_trait = self.tcx.require_lang_item(hir::LangItem::Drop, Some(closure_span));
1356 let ty_params = self.tcx.mk_substs_trait(base_path_ty, &[]);
1358 .type_implements_trait(
1362 self.tcx.param_env(closure_def_id.expect_local()),
1364 .must_apply_modulo_regions()
1367 let is_drop_defined_for_ty = is_drop_defined_for_ty(base_path_ty);
1369 // If there is a case where no projection is applied on top of current place
1370 // then there must be exactly one capture corresponding to such a case. Note that this
1371 // represents the case of the path being completely captured by the variable.
1373 // eg. If `a.b` is captured and we are processing `a.b`, then we can't have the closure also
1374 // capture `a.b.c`, because that violates min capture.
1375 let is_completely_captured = captured_by_move_projs.iter().any(|projs| projs.is_empty());
1377 assert!(!is_completely_captured || (captured_by_move_projs.len() == 1));
1379 if is_completely_captured {
1380 // The place is captured entirely, so doesn't matter if needs dtor, it will be drop
1381 // when the closure is dropped.
1385 if captured_by_move_projs.is_empty() {
1386 return needs_drop(base_path_ty);
1389 if is_drop_defined_for_ty {
1390 // If drop is implemented for this type then we need it to be fully captured,
1391 // and we know it is not completely captured because of the previous checks.
1393 // Note that this is a bug in the user code that will be reported by the
1394 // borrow checker, since we can't move out of drop types.
1396 // The bug exists in the user's code pre-migration, and we don't migrate here.
1400 match base_path_ty.kind() {
1402 // - `captured_by_move_projs` is not empty. Therefore we can call
1403 // `captured_by_move_projs.first().unwrap()` safely.
1404 // - All entries in `captured_by_move_projs` have atleast one projection.
1405 // Therefore we can call `captured_by_move_projs.first().unwrap().first().unwrap()` safely.
1407 // We don't capture derefs in case of move captures, which would have be applied to
1408 // access any further paths.
1409 ty::Adt(def, _) if def.is_box() => unreachable!(),
1410 ty::Ref(..) => unreachable!(),
1411 ty::RawPtr(..) => unreachable!(),
1413 ty::Adt(def, substs) => {
1414 // Multi-variant enums are captured in entirety,
1415 // which would've been handled in the case of single empty slice in `captured_by_move_projs`.
1416 assert_eq!(def.variants().len(), 1);
1418 // Only Field projections can be applied to a non-box Adt.
1420 captured_by_move_projs.iter().all(|projs| matches!(
1421 projs.first().unwrap().kind,
1422 ProjectionKind::Field(..)
1425 def.variants().get(VariantIdx::new(0)).unwrap().fields.iter().enumerate().any(
1427 let paths_using_field = captured_by_move_projs
1429 .filter_map(|projs| {
1430 if let ProjectionKind::Field(field_idx, _) =
1431 projs.first().unwrap().kind
1433 if (field_idx as usize) == i { Some(&projs[1..]) } else { None }
1440 let after_field_ty = field.ty(self.tcx, substs);
1441 self.has_significant_drop_outside_of_captures(
1451 ty::Tuple(fields) => {
1452 // Only Field projections can be applied to a tuple.
1454 captured_by_move_projs.iter().all(|projs| matches!(
1455 projs.first().unwrap().kind,
1456 ProjectionKind::Field(..)
1460 fields.iter().enumerate().any(|(i, element_ty)| {
1461 let paths_using_field = captured_by_move_projs
1463 .filter_map(|projs| {
1464 if let ProjectionKind::Field(field_idx, _) = projs.first().unwrap().kind
1466 if (field_idx as usize) == i { Some(&projs[1..]) } else { None }
1473 self.has_significant_drop_outside_of_captures(
1482 // Anything else would be completely captured and therefore handled already.
1483 _ => unreachable!(),
1487 fn init_capture_kind_for_place(
1489 place: &Place<'tcx>,
1490 capture_clause: hir::CaptureBy,
1491 ) -> ty::UpvarCapture {
1492 match capture_clause {
1493 // In case of a move closure if the data is accessed through a reference we
1494 // want to capture by ref to allow precise capture using reborrows.
1496 // If the data will be moved out of this place, then the place will be truncated
1497 // at the first Deref in `adjust_upvar_borrow_kind_for_consume` and then moved into
1499 hir::CaptureBy::Value if !place.deref_tys().any(Ty::is_ref) => {
1500 ty::UpvarCapture::ByValue
1502 hir::CaptureBy::Value | hir::CaptureBy::Ref => ty::UpvarCapture::ByRef(ty::ImmBorrow),
1506 fn place_for_root_variable(
1508 closure_def_id: LocalDefId,
1509 var_hir_id: hir::HirId,
1511 let upvar_id = ty::UpvarId::new(var_hir_id, closure_def_id);
1514 base_ty: self.node_ty(var_hir_id),
1515 base: PlaceBase::Upvar(upvar_id),
1516 projections: Default::default(),
1520 fn should_log_capture_analysis(&self, closure_def_id: DefId) -> bool {
1521 self.tcx.has_attr(closure_def_id, sym::rustc_capture_analysis)
1524 fn log_capture_analysis_first_pass(
1526 closure_def_id: rustc_hir::def_id::DefId,
1527 capture_information: &InferredCaptureInformation<'tcx>,
1530 if self.should_log_capture_analysis(closure_def_id) {
1532 self.tcx.sess.struct_span_err(closure_span, "First Pass analysis includes:");
1533 for (place, capture_info) in capture_information {
1534 let capture_str = construct_capture_info_string(self.tcx, place, capture_info);
1535 let output_str = format!("Capturing {}", capture_str);
1538 capture_info.path_expr_id.map_or(closure_span, |e| self.tcx.hir().span(e));
1539 diag.span_note(span, &output_str);
1545 fn log_closure_min_capture_info(&self, closure_def_id: DefId, closure_span: Span) {
1546 if self.should_log_capture_analysis(closure_def_id) {
1547 if let Some(min_captures) =
1548 self.typeck_results.borrow().closure_min_captures.get(&closure_def_id)
1551 self.tcx.sess.struct_span_err(closure_span, "Min Capture analysis includes:");
1553 for (_, min_captures_for_var) in min_captures {
1554 for capture in min_captures_for_var {
1555 let place = &capture.place;
1556 let capture_info = &capture.info;
1559 construct_capture_info_string(self.tcx, place, capture_info);
1560 let output_str = format!("Min Capture {}", capture_str);
1562 if capture.info.path_expr_id != capture.info.capture_kind_expr_id {
1563 let path_span = capture_info
1565 .map_or(closure_span, |e| self.tcx.hir().span(e));
1566 let capture_kind_span = capture_info
1567 .capture_kind_expr_id
1568 .map_or(closure_span, |e| self.tcx.hir().span(e));
1570 let mut multi_span: MultiSpan =
1571 MultiSpan::from_spans(vec![path_span, capture_kind_span]);
1573 let capture_kind_label =
1574 construct_capture_kind_reason_string(self.tcx, place, capture_info);
1575 let path_label = construct_path_string(self.tcx, place);
1577 multi_span.push_span_label(path_span, path_label);
1578 multi_span.push_span_label(capture_kind_span, capture_kind_label);
1580 diag.span_note(multi_span, &output_str);
1582 let span = capture_info
1584 .map_or(closure_span, |e| self.tcx.hir().span(e));
1586 diag.span_note(span, &output_str);
1595 /// A captured place is mutable if
1596 /// 1. Projections don't include a Deref of an immut-borrow, **and**
1597 /// 2. PlaceBase is mut or projections include a Deref of a mut-borrow.
1598 fn determine_capture_mutability(
1600 typeck_results: &'a TypeckResults<'tcx>,
1601 place: &Place<'tcx>,
1602 ) -> hir::Mutability {
1603 let var_hir_id = match place.base {
1604 PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
1605 _ => unreachable!(),
1608 let bm = *typeck_results.pat_binding_modes().get(var_hir_id).expect("missing binding mode");
1610 let mut is_mutbl = match bm {
1611 ty::BindByValue(mutability) => mutability,
1612 ty::BindByReference(_) => hir::Mutability::Not,
1615 for pointer_ty in place.deref_tys() {
1616 match pointer_ty.kind() {
1617 // We don't capture derefs of raw ptrs
1618 ty::RawPtr(_) => unreachable!(),
1620 // Derefencing a mut-ref allows us to mut the Place if we don't deref
1621 // an immut-ref after on top of this.
1622 ty::Ref(.., hir::Mutability::Mut) => is_mutbl = hir::Mutability::Mut,
1624 // The place isn't mutable once we dereference an immutable reference.
1625 ty::Ref(.., hir::Mutability::Not) => return hir::Mutability::Not,
1627 // Dereferencing a box doesn't change mutability
1628 ty::Adt(def, ..) if def.is_box() => {}
1630 unexpected_ty => bug!("deref of unexpected pointer type {:?}", unexpected_ty),
1638 /// Truncate the capture so that the place being borrowed is in accordance with RFC 1240,
1639 /// which states that it's unsafe to take a reference into a struct marked `repr(packed)`.
1640 fn restrict_repr_packed_field_ref_capture<'tcx>(
1642 param_env: ty::ParamEnv<'tcx>,
1643 mut place: Place<'tcx>,
1644 mut curr_borrow_kind: ty::UpvarCapture,
1645 ) -> (Place<'tcx>, ty::UpvarCapture) {
1646 let pos = place.projections.iter().enumerate().position(|(i, p)| {
1647 let ty = place.ty_before_projection(i);
1649 // Return true for fields of packed structs, unless those fields have alignment 1.
1651 ProjectionKind::Field(..) => match ty.kind() {
1652 ty::Adt(def, _) if def.repr().packed() => {
1653 // We erase regions here because they cannot be hashed
1654 match tcx.layout_of(param_env.and(tcx.erase_regions(p.ty))) {
1655 Ok(layout) if layout.align.abi.bytes() == 1 => {
1656 // if the alignment is 1, the type can't be further
1659 "restrict_repr_packed_field_ref_capture: ({:?}) - align = 1",
1665 debug!("restrict_repr_packed_field_ref_capture: ({:?}) - true", place);
1677 if let Some(pos) = pos {
1678 truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_borrow_kind, pos);
1681 (place, curr_borrow_kind)
1684 /// Returns a Ty that applies the specified capture kind on the provided capture Ty
1685 fn apply_capture_kind_on_capture_ty<'tcx>(
1688 capture_kind: UpvarCapture,
1689 region: Option<ty::Region<'tcx>>,
1691 match capture_kind {
1692 ty::UpvarCapture::ByValue => ty,
1693 ty::UpvarCapture::ByRef(kind) => {
1694 tcx.mk_ref(region.unwrap(), ty::TypeAndMut { ty: ty, mutbl: kind.to_mutbl_lossy() })
1699 /// Returns the Span of where the value with the provided HirId would be dropped
1700 fn drop_location_span<'tcx>(tcx: TyCtxt<'tcx>, hir_id: hir::HirId) -> Span {
1701 let owner_id = tcx.hir().get_enclosing_scope(hir_id).unwrap();
1703 let owner_node = tcx.hir().get(owner_id);
1704 let owner_span = match owner_node {
1705 hir::Node::Item(item) => match item.kind {
1706 hir::ItemKind::Fn(_, _, owner_id) => tcx.hir().span(owner_id.hir_id),
1708 bug!("Drop location span error: need to handle more ItemKind {:?}", item.kind);
1711 hir::Node::Block(block) => tcx.hir().span(block.hir_id),
1713 bug!("Drop location span error: need to handle more Node {:?}", owner_node);
1716 tcx.sess.source_map().end_point(owner_span)
1719 struct InferBorrowKind<'a, 'tcx> {
1720 fcx: &'a FnCtxt<'a, 'tcx>,
1722 // The def-id of the closure whose kind and upvar accesses are being inferred.
1723 closure_def_id: LocalDefId,
1725 /// For each Place that is captured by the closure, we track the minimal kind of
1726 /// access we need (ref, ref mut, move, etc) and the expression that resulted in such access.
1728 /// Consider closure where s.str1 is captured via an ImmutableBorrow and
1729 /// s.str2 via a MutableBorrow
1732 /// struct SomeStruct { str1: String, str2: String }
1734 /// // Assume that the HirId for the variable definition is `V1`
1735 /// let mut s = SomeStruct { str1: format!("s1"), str2: format!("s2") }
1737 /// let fix_s = |new_s2| {
1738 /// // Assume that the HirId for the expression `s.str1` is `E1`
1739 /// println!("Updating SomeStruct with str1=", s.str1);
1740 /// // Assume that the HirId for the expression `*s.str2` is `E2`
1741 /// s.str2 = new_s2;
1745 /// For closure `fix_s`, (at a high level) the map contains
1748 /// Place { V1, [ProjectionKind::Field(Index=0, Variant=0)] } : CaptureKind { E1, ImmutableBorrow }
1749 /// Place { V1, [ProjectionKind::Field(Index=1, Variant=0)] } : CaptureKind { E2, MutableBorrow }
1751 capture_information: InferredCaptureInformation<'tcx>,
1752 fake_reads: Vec<(Place<'tcx>, FakeReadCause, hir::HirId)>,
1755 impl<'a, 'tcx> euv::Delegate<'tcx> for InferBorrowKind<'a, 'tcx> {
1756 fn fake_read(&mut self, place: Place<'tcx>, cause: FakeReadCause, diag_expr_id: hir::HirId) {
1757 let PlaceBase::Upvar(_) = place.base else { return };
1759 // We need to restrict Fake Read precision to avoid fake reading unsafe code,
1760 // such as deref of a raw pointer.
1761 let dummy_capture_kind = ty::UpvarCapture::ByRef(ty::BorrowKind::ImmBorrow);
1763 let (place, _) = restrict_capture_precision(place, dummy_capture_kind);
1765 let (place, _) = restrict_repr_packed_field_ref_capture(
1771 self.fake_reads.push((place, cause, diag_expr_id));
1774 #[instrument(skip(self), level = "debug")]
1775 fn consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId) {
1776 let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return };
1777 assert_eq!(self.closure_def_id, upvar_id.closure_expr_id);
1779 self.capture_information.push((
1780 place_with_id.place.clone(),
1782 capture_kind_expr_id: Some(diag_expr_id),
1783 path_expr_id: Some(diag_expr_id),
1784 capture_kind: ty::UpvarCapture::ByValue,
1789 #[instrument(skip(self), level = "debug")]
1792 place_with_id: &PlaceWithHirId<'tcx>,
1793 diag_expr_id: hir::HirId,
1796 let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return };
1797 assert_eq!(self.closure_def_id, upvar_id.closure_expr_id);
1799 // The region here will get discarded/ignored
1800 let capture_kind = ty::UpvarCapture::ByRef(bk);
1802 // We only want repr packed restriction to be applied to reading references into a packed
1803 // struct, and not when the data is being moved. Therefore we call this method here instead
1804 // of in `restrict_capture_precision`.
1805 let (place, mut capture_kind) = restrict_repr_packed_field_ref_capture(
1808 place_with_id.place.clone(),
1812 // Raw pointers don't inherit mutability
1813 if place_with_id.place.deref_tys().any(Ty::is_unsafe_ptr) {
1814 capture_kind = ty::UpvarCapture::ByRef(ty::BorrowKind::ImmBorrow);
1817 self.capture_information.push((
1820 capture_kind_expr_id: Some(diag_expr_id),
1821 path_expr_id: Some(diag_expr_id),
1827 #[instrument(skip(self), level = "debug")]
1828 fn mutate(&mut self, assignee_place: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId) {
1829 self.borrow(assignee_place, diag_expr_id, ty::BorrowKind::MutBorrow);
1833 /// Rust doesn't permit moving fields out of a type that implements drop
1834 fn restrict_precision_for_drop_types<'a, 'tcx>(
1835 fcx: &'a FnCtxt<'a, 'tcx>,
1836 mut place: Place<'tcx>,
1837 mut curr_mode: ty::UpvarCapture,
1839 ) -> (Place<'tcx>, ty::UpvarCapture) {
1840 let is_copy_type = fcx.infcx.type_is_copy_modulo_regions(fcx.param_env, place.ty(), span);
1842 if let (false, UpvarCapture::ByValue) = (is_copy_type, curr_mode) {
1843 for i in 0..place.projections.len() {
1844 match place.ty_before_projection(i).kind() {
1845 ty::Adt(def, _) if def.destructor(fcx.tcx).is_some() => {
1846 truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i);
1857 /// Truncate `place` so that an `unsafe` block isn't required to capture it.
1858 /// - No projections are applied to raw pointers, since these require unsafe blocks. We capture
1859 /// them completely.
1860 /// - No projections are applied on top of Union ADTs, since these require unsafe blocks.
1861 fn restrict_precision_for_unsafe<'tcx>(
1862 mut place: Place<'tcx>,
1863 mut curr_mode: ty::UpvarCapture,
1864 ) -> (Place<'tcx>, ty::UpvarCapture) {
1865 if place.base_ty.is_unsafe_ptr() {
1866 truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, 0);
1869 if place.base_ty.is_union() {
1870 truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, 0);
1873 for (i, proj) in place.projections.iter().enumerate() {
1874 if proj.ty.is_unsafe_ptr() {
1875 // Don't apply any projections on top of an unsafe ptr.
1876 truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i + 1);
1880 if proj.ty.is_union() {
1881 // Don't capture preicse fields of a union.
1882 truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i + 1);
1890 /// Truncate projections so that following rules are obeyed by the captured `place`:
1891 /// - No Index projections are captured, since arrays are captured completely.
1892 /// - No unsafe block is required to capture `place`
1893 /// Returns the truncated place and updated cature mode.
1894 fn restrict_capture_precision<'tcx>(
1896 curr_mode: ty::UpvarCapture,
1897 ) -> (Place<'tcx>, ty::UpvarCapture) {
1898 let (mut place, mut curr_mode) = restrict_precision_for_unsafe(place, curr_mode);
1900 if place.projections.is_empty() {
1901 // Nothing to do here
1902 return (place, curr_mode);
1905 for (i, proj) in place.projections.iter().enumerate() {
1907 ProjectionKind::Index => {
1908 // Arrays are completely captured, so we drop Index projections
1909 truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i);
1910 return (place, curr_mode);
1912 ProjectionKind::Deref => {}
1913 ProjectionKind::Field(..) => {} // ignore
1914 ProjectionKind::Subslice => {} // We never capture this
1921 /// Truncate deref of any reference.
1922 fn adjust_for_move_closure<'tcx>(
1923 mut place: Place<'tcx>,
1924 mut kind: ty::UpvarCapture,
1925 ) -> (Place<'tcx>, ty::UpvarCapture) {
1926 let first_deref = place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
1928 if let Some(idx) = first_deref {
1929 truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
1932 (place, ty::UpvarCapture::ByValue)
1935 /// Adjust closure capture just that if taking ownership of data, only move data
1936 /// from enclosing stack frame.
1937 fn adjust_for_non_move_closure<'tcx>(
1938 mut place: Place<'tcx>,
1939 mut kind: ty::UpvarCapture,
1940 ) -> (Place<'tcx>, ty::UpvarCapture) {
1941 let contains_deref =
1942 place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
1945 ty::UpvarCapture::ByValue => {
1946 if let Some(idx) = contains_deref {
1947 truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
1951 ty::UpvarCapture::ByRef(..) => {}
1957 fn construct_place_string<'tcx>(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
1958 let variable_name = match place.base {
1959 PlaceBase::Upvar(upvar_id) => var_name(tcx, upvar_id.var_path.hir_id).to_string(),
1960 _ => bug!("Capture_information should only contain upvars"),
1963 let mut projections_str = String::new();
1964 for (i, item) in place.projections.iter().enumerate() {
1965 let proj = match item.kind {
1966 ProjectionKind::Field(a, b) => format!("({:?}, {:?})", a, b),
1967 ProjectionKind::Deref => String::from("Deref"),
1968 ProjectionKind::Index => String::from("Index"),
1969 ProjectionKind::Subslice => String::from("Subslice"),
1972 projections_str.push(',');
1974 projections_str.push_str(proj.as_str());
1977 format!("{}[{}]", variable_name, projections_str)
1980 fn construct_capture_kind_reason_string<'tcx>(
1982 place: &Place<'tcx>,
1983 capture_info: &ty::CaptureInfo,
1985 let place_str = construct_place_string(tcx, place);
1987 let capture_kind_str = match capture_info.capture_kind {
1988 ty::UpvarCapture::ByValue => "ByValue".into(),
1989 ty::UpvarCapture::ByRef(kind) => format!("{:?}", kind),
1992 format!("{} captured as {} here", place_str, capture_kind_str)
1995 fn construct_path_string<'tcx>(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
1996 let place_str = construct_place_string(tcx, place);
1998 format!("{} used here", place_str)
2001 fn construct_capture_info_string<'tcx>(
2003 place: &Place<'tcx>,
2004 capture_info: &ty::CaptureInfo,
2006 let place_str = construct_place_string(tcx, place);
2008 let capture_kind_str = match capture_info.capture_kind {
2009 ty::UpvarCapture::ByValue => "ByValue".into(),
2010 ty::UpvarCapture::ByRef(kind) => format!("{:?}", kind),
2012 format!("{} -> {}", place_str, capture_kind_str)
2015 fn var_name(tcx: TyCtxt<'_>, var_hir_id: hir::HirId) -> Symbol {
2016 tcx.hir().name(var_hir_id)
2019 #[instrument(level = "debug", skip(tcx))]
2020 fn should_do_rust_2021_incompatible_closure_captures_analysis(
2022 closure_id: hir::HirId,
2025 tcx.lint_level_at_node(lint::builtin::RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES, closure_id);
2027 !matches!(level, lint::Level::Allow)
2030 /// Return a two string tuple (s1, s2)
2031 /// - s1: Line of code that is needed for the migration: eg: `let _ = (&x, ...)`.
2032 /// - s2: Comma separated names of the variables being migrated.
2033 fn migration_suggestion_for_2229(
2035 need_migrations: &Vec<NeededMigration>,
2036 ) -> (String, String) {
2037 let need_migrations_variables = need_migrations
2039 .map(|NeededMigration { var_hir_id: v, .. }| var_name(tcx, *v))
2040 .collect::<Vec<_>>();
2042 let migration_ref_concat =
2043 need_migrations_variables.iter().map(|v| format!("&{}", v)).collect::<Vec<_>>().join(", ");
2045 let migration_string = if 1 == need_migrations.len() {
2046 format!("let _ = {}", migration_ref_concat)
2048 format!("let _ = ({})", migration_ref_concat)
2051 let migrated_variables_concat =
2052 need_migrations_variables.iter().map(|v| format!("`{}`", v)).collect::<Vec<_>>().join(", ");
2054 (migration_string, migrated_variables_concat)
2057 /// Helper function to determine if we need to escalate CaptureKind from
2058 /// CaptureInfo A to B and returns the escalated CaptureInfo.
2059 /// (Note: CaptureInfo contains CaptureKind and an expression that led to capture it in that way)
2061 /// If both `CaptureKind`s are considered equivalent, then the CaptureInfo is selected based
2062 /// on the `CaptureInfo` containing an associated `capture_kind_expr_id`.
2064 /// It is the caller's duty to figure out which path_expr_id to use.
2066 /// If both the CaptureKind and Expression are considered to be equivalent,
2067 /// then `CaptureInfo` A is preferred. This can be useful in cases where we want to priortize
2068 /// expressions reported back to the user as part of diagnostics based on which appears earlier
2069 /// in the closure. This can be achieved simply by calling
2070 /// `determine_capture_info(existing_info, current_info)`. This works out because the
2071 /// expressions that occur earlier in the closure body than the current expression are processed before.
2072 /// Consider the following example
2074 /// struct Point { x: i32, y: i32 }
2075 /// let mut p: Point { x: 10, y: 10 };
2083 /// p.x += 10; // E2
2087 /// `CaptureKind` associated with both `E1` and `E2` will be ByRef(MutBorrow),
2088 /// and both have an expression associated, however for diagnostics we prefer reporting
2089 /// `E1` since it appears earlier in the closure body. When `E2` is being processed we
2090 /// would've already handled `E1`, and have an existing capture_information for it.
2091 /// Calling `determine_capture_info(existing_info_e1, current_info_e2)` will return
2092 /// `existing_info_e1` in this case, allowing us to point to `E1` in case of diagnostics.
2093 fn determine_capture_info(
2094 capture_info_a: ty::CaptureInfo,
2095 capture_info_b: ty::CaptureInfo,
2096 ) -> ty::CaptureInfo {
2097 // If the capture kind is equivalent then, we don't need to escalate and can compare the
2099 let eq_capture_kind = match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
2100 (ty::UpvarCapture::ByValue, ty::UpvarCapture::ByValue) => true,
2101 (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => ref_a == ref_b,
2102 (ty::UpvarCapture::ByValue, _) | (ty::UpvarCapture::ByRef(_), _) => false,
2105 if eq_capture_kind {
2106 match (capture_info_a.capture_kind_expr_id, capture_info_b.capture_kind_expr_id) {
2107 (Some(_), _) | (None, None) => capture_info_a,
2108 (None, Some(_)) => capture_info_b,
2111 // We select the CaptureKind which ranks higher based the following priority order:
2112 // ByValue > MutBorrow > UniqueImmBorrow > ImmBorrow
2113 match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
2114 (ty::UpvarCapture::ByValue, _) => capture_info_a,
2115 (_, ty::UpvarCapture::ByValue) => capture_info_b,
2116 (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => {
2117 match (ref_a, ref_b) {
2119 (ty::UniqueImmBorrow | ty::MutBorrow, ty::ImmBorrow)
2120 | (ty::MutBorrow, ty::UniqueImmBorrow) => capture_info_a,
2123 (ty::ImmBorrow, ty::UniqueImmBorrow | ty::MutBorrow)
2124 | (ty::UniqueImmBorrow, ty::MutBorrow) => capture_info_b,
2126 (ty::ImmBorrow, ty::ImmBorrow)
2127 | (ty::UniqueImmBorrow, ty::UniqueImmBorrow)
2128 | (ty::MutBorrow, ty::MutBorrow) => {
2129 bug!("Expected unequal capture kinds");
2137 /// Truncates `place` to have up to `len` projections.
2138 /// `curr_mode` is the current required capture kind for the place.
2139 /// Returns the truncated `place` and the updated required capture kind.
2141 /// Note: Capture kind changes from `MutBorrow` to `UniqueImmBorrow` if the truncated part of the `place`
2142 /// contained `Deref` of `&mut`.
2143 fn truncate_place_to_len_and_update_capture_kind<'tcx>(
2144 place: &mut Place<'tcx>,
2145 curr_mode: &mut ty::UpvarCapture,
2148 let is_mut_ref = |ty: Ty<'_>| matches!(ty.kind(), ty::Ref(.., hir::Mutability::Mut));
2150 // If the truncated part of the place contains `Deref` of a `&mut` then convert MutBorrow ->
2152 // Note that if the place contained Deref of a raw pointer it would've not been MutBorrow, so
2153 // we don't need to worry about that case here.
2155 ty::UpvarCapture::ByRef(ty::BorrowKind::MutBorrow) => {
2156 for i in len..place.projections.len() {
2157 if place.projections[i].kind == ProjectionKind::Deref
2158 && is_mut_ref(place.ty_before_projection(i))
2160 *curr_mode = ty::UpvarCapture::ByRef(ty::BorrowKind::UniqueImmBorrow);
2166 ty::UpvarCapture::ByRef(..) => {}
2167 ty::UpvarCapture::ByValue => {}
2170 place.projections.truncate(len);
2173 /// Determines the Ancestry relationship of Place A relative to Place B
2175 /// `PlaceAncestryRelation::Ancestor` implies Place A is ancestor of Place B
2176 /// `PlaceAncestryRelation::Descendant` implies Place A is descendant of Place B
2177 /// `PlaceAncestryRelation::Divergent` implies neither of them is the ancestor of the other.
2178 fn determine_place_ancestry_relation<'tcx>(
2179 place_a: &Place<'tcx>,
2180 place_b: &Place<'tcx>,
2181 ) -> PlaceAncestryRelation {
2182 // If Place A and Place B, don't start off from the same root variable, they are divergent.
2183 if place_a.base != place_b.base {
2184 return PlaceAncestryRelation::Divergent;
2187 // Assume of length of projections_a = n
2188 let projections_a = &place_a.projections;
2190 // Assume of length of projections_b = m
2191 let projections_b = &place_b.projections;
2193 let same_initial_projections =
2194 iter::zip(projections_a, projections_b).all(|(proj_a, proj_b)| proj_a.kind == proj_b.kind);
2196 if same_initial_projections {
2197 use std::cmp::Ordering;
2199 // First min(n, m) projections are the same
2200 // Select Ancestor/Descendant
2201 match projections_b.len().cmp(&projections_a.len()) {
2202 Ordering::Greater => PlaceAncestryRelation::Ancestor,
2203 Ordering::Equal => PlaceAncestryRelation::SamePlace,
2204 Ordering::Less => PlaceAncestryRelation::Descendant,
2207 PlaceAncestryRelation::Divergent
2211 /// Reduces the precision of the captured place when the precision doesn't yield any benefit from
2212 /// borrow checking perspective, allowing us to save us on the size of the capture.
2215 /// Fields that are read through a shared reference will always be read via a shared ref or a copy,
2216 /// and therefore capturing precise paths yields no benefit. This optimization truncates the
2217 /// rightmost deref of the capture if the deref is applied to a shared ref.
2219 /// Reason we only drop the last deref is because of the following edge case:
2222 /// struct MyStruct<'a> {
2228 /// fn foo<'a, 'b>(m: &'a MyStruct<'b>) -> impl FnMut() + 'static {
2229 /// let c = || drop(&*m.a.field_of_a);
2230 /// // Here we really do want to capture `*m.a` because that outlives `'static`
2232 /// // If we capture `m`, then the closure no longer outlives `'static'
2233 /// // it is constrained to `'a`
2236 fn truncate_capture_for_optimization<'tcx>(
2237 mut place: Place<'tcx>,
2238 mut curr_mode: ty::UpvarCapture,
2239 ) -> (Place<'tcx>, ty::UpvarCapture) {
2240 let is_shared_ref = |ty: Ty<'_>| matches!(ty.kind(), ty::Ref(.., hir::Mutability::Not));
2242 // Find the right-most deref (if any). All the projections that come after this
2243 // are fields or other "in-place pointer adjustments"; these refer therefore to
2244 // data owned by whatever pointer is being dereferenced here.
2245 let idx = place.projections.iter().rposition(|proj| ProjectionKind::Deref == proj.kind);
2248 // If that pointer is a shared reference, then we don't need those fields.
2249 Some(idx) if is_shared_ref(place.ty_before_projection(idx)) => {
2250 truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, idx + 1)
2252 None | Some(_) => {}
2258 /// Precise capture is enabled if the feature gate `capture_disjoint_fields` is enabled or if
2259 /// user is using Rust Edition 2021 or higher.
2261 /// `span` is the span of the closure.
2262 fn enable_precise_capture(tcx: TyCtxt<'_>, span: Span) -> bool {
2263 // We use span here to ensure that if the closure was generated by a macro with a different
2265 tcx.features().capture_disjoint_fields || span.rust_2021()