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::{
46 self, ClosureSizeProfileData, Ty, TyCtxt, TypeckResults, UpvarCapture, UpvarSubsts,
48 use rustc_session::lint;
50 use rustc_span::{MultiSpan, Span, Symbol};
51 use rustc_trait_selection::infer::InferCtxtExt;
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 {
70 /// Intermediate format to store a captured `Place` and associated `ty::CaptureInfo`
71 /// during capture analysis. Information in this map feeds into the minimum capture
73 type InferredCaptureInformation<'tcx> = FxIndexMap<Place<'tcx>, ty::CaptureInfo<'tcx>>;
75 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
76 pub fn closure_analyze(&self, body: &'tcx hir::Body<'tcx>) {
77 InferBorrowKindVisitor { fcx: self }.visit_body(body);
79 // it's our job to process these.
80 assert!(self.deferred_call_resolutions.borrow().is_empty());
84 struct InferBorrowKindVisitor<'a, 'tcx> {
85 fcx: &'a FnCtxt<'a, 'tcx>,
88 impl<'a, 'tcx> Visitor<'tcx> for InferBorrowKindVisitor<'a, 'tcx> {
89 type Map = intravisit::ErasedMap<'tcx>;
91 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
92 NestedVisitorMap::None
95 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
96 if let hir::ExprKind::Closure(cc, _, body_id, _, _) = expr.kind {
97 let body = self.fcx.tcx.hir().body(body_id);
98 self.visit_body(body);
99 self.fcx.analyze_closure(expr.hir_id, expr.span, body_id, body, cc);
102 intravisit::walk_expr(self, expr);
106 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
107 /// Analysis starting point.
110 closure_hir_id: hir::HirId,
112 body_id: hir::BodyId,
113 body: &'tcx hir::Body<'tcx>,
114 capture_clause: hir::CaptureBy,
116 debug!("analyze_closure(id={:?}, body.id={:?})", closure_hir_id, body.id());
118 // Extract the type of the closure.
119 let ty = self.node_ty(closure_hir_id);
120 let (closure_def_id, substs) = match *ty.kind() {
121 ty::Closure(def_id, substs) => (def_id, UpvarSubsts::Closure(substs)),
122 ty::Generator(def_id, substs, _) => (def_id, UpvarSubsts::Generator(substs)),
124 // #51714: skip analysis when we have already encountered type errors
130 "type of closure expr {:?} is not a closure {:?}",
137 let infer_kind = if let UpvarSubsts::Closure(closure_substs) = substs {
138 self.closure_kind(closure_substs).is_none().then_some(closure_substs)
143 let local_def_id = closure_def_id.expect_local();
145 let body_owner_def_id = self.tcx.hir().body_owner_def_id(body.id());
146 assert_eq!(body_owner_def_id.to_def_id(), closure_def_id);
147 let mut delegate = InferBorrowKind {
151 capture_information: Default::default(),
152 fake_reads: Default::default(),
154 euv::ExprUseVisitor::new(
159 &self.typeck_results.borrow(),
164 "For closure={:?}, capture_information={:#?}",
165 closure_def_id, delegate.capture_information
168 self.log_capture_analysis_first_pass(closure_def_id, &delegate.capture_information, span);
170 let (capture_information, closure_kind, origin) = self
171 .process_collected_capture_information(capture_clause, delegate.capture_information);
173 self.compute_min_captures(closure_def_id, capture_information);
175 let closure_hir_id = self.tcx.hir().local_def_id_to_hir_id(local_def_id);
177 if should_do_rust_2021_incompatible_closure_captures_analysis(self.tcx, closure_hir_id) {
178 self.perform_2229_migration_anaysis(closure_def_id, body_id, capture_clause, span);
181 let after_feature_tys = self.final_upvar_tys(closure_def_id);
183 // We now fake capture information for all variables that are mentioned within the closure
184 // We do this after handling migrations so that min_captures computes before
185 if !enable_precise_capture(self.tcx, span) {
186 let mut capture_information: InferredCaptureInformation<'tcx> = Default::default();
188 if let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) {
189 for var_hir_id in upvars.keys() {
190 let place = self.place_for_root_variable(local_def_id, *var_hir_id);
192 debug!("seed place {:?}", place);
194 let upvar_id = ty::UpvarId::new(*var_hir_id, local_def_id);
196 self.init_capture_kind_for_place(&place, capture_clause, upvar_id, span);
197 let fake_info = ty::CaptureInfo {
198 capture_kind_expr_id: None,
203 capture_information.insert(place, fake_info);
207 // This will update the min captures based on this new fake information.
208 self.compute_min_captures(closure_def_id, capture_information);
211 let before_feature_tys = self.final_upvar_tys(closure_def_id);
213 if let Some(closure_substs) = infer_kind {
214 // Unify the (as yet unbound) type variable in the closure
215 // substs with the kind we inferred.
216 let closure_kind_ty = closure_substs.as_closure().kind_ty();
217 self.demand_eqtype(span, closure_kind.to_ty(self.tcx), closure_kind_ty);
219 // If we have an origin, store it.
220 if let Some(origin) = origin {
221 let origin = if enable_precise_capture(self.tcx, span) {
224 (origin.0, Place { projections: vec![], ..origin.1 })
229 .closure_kind_origins_mut()
230 .insert(closure_hir_id, origin);
234 self.log_closure_min_capture_info(closure_def_id, span);
236 // Now that we've analyzed the closure, we know how each
237 // variable is borrowed, and we know what traits the closure
238 // implements (Fn vs FnMut etc). We now have some updates to do
239 // with that information.
241 // Note that no closure type C may have an upvar of type C
242 // (though it may reference itself via a trait object). This
243 // results from the desugaring of closures to a struct like
244 // `Foo<..., UV0...UVn>`. If one of those upvars referenced
245 // C, then the type would have infinite size (and the
246 // inference algorithm will reject it).
248 // Equate the type variables for the upvars with the actual types.
249 let final_upvar_tys = self.final_upvar_tys(closure_def_id);
251 "analyze_closure: id={:?} substs={:?} final_upvar_tys={:?}",
252 closure_hir_id, substs, final_upvar_tys
255 // Build a tuple (U0..Un) of the final upvar types U0..Un
256 // and unify the upvar tupe type in the closure with it:
257 let final_tupled_upvars_type = self.tcx.mk_tup(final_upvar_tys.iter());
258 self.demand_suptype(span, substs.tupled_upvars_ty(), final_tupled_upvars_type);
260 let fake_reads = delegate
263 .map(|(place, cause, hir_id)| (place, cause, hir_id))
265 self.typeck_results.borrow_mut().closure_fake_reads.insert(closure_def_id, fake_reads);
267 if self.tcx.sess.opts.debugging_opts.profile_closures {
268 self.typeck_results.borrow_mut().closure_size_eval.insert(
270 ClosureSizeProfileData {
271 before_feature_tys: self.tcx.mk_tup(before_feature_tys.into_iter()),
272 after_feature_tys: self.tcx.mk_tup(after_feature_tys.into_iter()),
277 // If we are also inferred the closure kind here,
278 // process any deferred resolutions.
279 let deferred_call_resolutions = self.remove_deferred_call_resolutions(closure_def_id);
280 for deferred_call_resolution in deferred_call_resolutions {
281 deferred_call_resolution.resolve(self);
285 // Returns a list of `Ty`s for each upvar.
286 fn final_upvar_tys(&self, closure_id: DefId) -> Vec<Ty<'tcx>> {
287 // Presently an unboxed closure type cannot "escape" out of a
288 // function, so we will only encounter ones that originated in the
289 // local crate or were inlined into it along with some function.
290 // This may change if abstract return types of some sort are
294 .closure_min_captures_flattened(closure_id)
295 .map(|captured_place| {
296 let upvar_ty = captured_place.place.ty();
297 let capture = captured_place.info.capture_kind;
300 "final_upvar_tys: place={:?} upvar_ty={:?} capture={:?}, mutability={:?}",
301 captured_place.place, upvar_ty, capture, captured_place.mutability,
304 apply_capture_kind_on_capture_ty(self.tcx, upvar_ty, capture)
309 /// Adjusts the closure capture information to ensure that the operations aren't unsafe,
310 /// and that the path can be captured with required capture kind (depending on use in closure,
311 /// move closure etc.)
313 /// Returns the set of of adjusted information along with the inferred closure kind and span
314 /// associated with the closure kind inference.
316 /// Note that we *always* infer a minimal kind, even if
317 /// we don't always *use* that in the final result (i.e., sometimes
318 /// we've taken the closure kind from the expectations instead, and
319 /// for generators we don't even implement the closure traits
322 /// If we inferred that the closure needs to be FnMut/FnOnce, last element of the returned tuple
323 /// contains a `Some()` with the `Place` that caused us to do so.
324 fn process_collected_capture_information(
326 capture_clause: hir::CaptureBy,
327 capture_information: InferredCaptureInformation<'tcx>,
328 ) -> (InferredCaptureInformation<'tcx>, ty::ClosureKind, Option<(Span, Place<'tcx>)>) {
329 let mut processed: InferredCaptureInformation<'tcx> = Default::default();
331 let mut closure_kind = ty::ClosureKind::LATTICE_BOTTOM;
332 let mut origin: Option<(Span, Place<'tcx>)> = None;
334 for (place, mut capture_info) in capture_information {
335 // Apply rules for safety before inferring closure kind
336 let place = restrict_capture_precision(place);
338 let place = truncate_capture_for_optimization(&place);
340 let usage_span = if let Some(usage_expr) = capture_info.path_expr_id {
341 self.tcx.hir().span(usage_expr)
346 let updated = match capture_info.capture_kind {
347 ty::UpvarCapture::ByValue(..) => match closure_kind {
348 ty::ClosureKind::Fn | ty::ClosureKind::FnMut => {
349 (ty::ClosureKind::FnOnce, Some((usage_span, place.clone())))
351 // If closure is already FnOnce, don't update
352 ty::ClosureKind::FnOnce => (closure_kind, origin),
355 ty::UpvarCapture::ByRef(ty::UpvarBorrow {
356 kind: ty::BorrowKind::MutBorrow | ty::BorrowKind::UniqueImmBorrow,
360 ty::ClosureKind::Fn => {
361 (ty::ClosureKind::FnMut, Some((usage_span, place.clone())))
363 // Don't update the origin
364 ty::ClosureKind::FnMut | ty::ClosureKind::FnOnce => (closure_kind, origin),
368 _ => (closure_kind, origin),
371 closure_kind = updated.0;
374 let (place, capture_kind) = match capture_clause {
375 hir::CaptureBy::Value => adjust_for_move_closure(place, capture_info.capture_kind),
376 hir::CaptureBy::Ref => {
377 adjust_for_non_move_closure(place, capture_info.capture_kind)
381 capture_info.capture_kind = capture_kind;
382 processed.insert(place, capture_info);
385 (processed, closure_kind, origin)
388 /// Analyzes the information collected by `InferBorrowKind` to compute the min number of
389 /// Places (and corresponding capture kind) that we need to keep track of to support all
390 /// the required captured paths.
393 /// Note: If this function is called multiple times for the same closure, it will update
394 /// the existing min_capture map that is stored in TypeckResults.
398 /// struct Point { x: i32, y: i32 }
400 /// let s: String; // hir_id_s
401 /// let mut p: Point; // his_id_p
403 /// println!("{}", s); // L1
405 /// println!("{}" , p.y) // L3
406 /// println!("{}", p) // L4
410 /// and let hir_id_L1..5 be the expressions pointing to use of a captured variable on
411 /// the lines L1..5 respectively.
413 /// InferBorrowKind results in a structure like this:
417 /// Place(base: hir_id_s, projections: [], ....) -> {
418 /// capture_kind_expr: hir_id_L5,
419 /// path_expr_id: hir_id_L5,
420 /// capture_kind: ByValue
422 /// Place(base: hir_id_p, projections: [Field(0, 0)], ...) -> {
423 /// capture_kind_expr: hir_id_L2,
424 /// path_expr_id: hir_id_L2,
425 /// capture_kind: ByValue
427 /// Place(base: hir_id_p, projections: [Field(1, 0)], ...) -> {
428 /// capture_kind_expr: hir_id_L3,
429 /// path_expr_id: hir_id_L3,
430 /// capture_kind: ByValue
432 /// Place(base: hir_id_p, projections: [], ...) -> {
433 /// capture_kind_expr: hir_id_L4,
434 /// path_expr_id: hir_id_L4,
435 /// capture_kind: ByValue
439 /// After the min capture analysis, we get:
443 /// Place(base: hir_id_s, projections: [], ....) -> {
444 /// capture_kind_expr: hir_id_L5,
445 /// path_expr_id: hir_id_L5,
446 /// capture_kind: ByValue
450 /// Place(base: hir_id_p, projections: [], ...) -> {
451 /// capture_kind_expr: hir_id_L2,
452 /// path_expr_id: hir_id_L4,
453 /// capture_kind: ByValue
457 fn compute_min_captures(
459 closure_def_id: DefId,
460 capture_information: InferredCaptureInformation<'tcx>,
462 if capture_information.is_empty() {
466 let mut typeck_results = self.typeck_results.borrow_mut();
468 let mut root_var_min_capture_list =
469 typeck_results.closure_min_captures.remove(&closure_def_id).unwrap_or_default();
471 for (place, capture_info) in capture_information.into_iter() {
472 let var_hir_id = match place.base {
473 PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
474 base => bug!("Expected upvar, found={:?}", base),
477 let min_cap_list = match root_var_min_capture_list.get_mut(&var_hir_id) {
479 let mutability = self.determine_capture_mutability(&typeck_results, &place);
481 vec![ty::CapturedPlace { place, info: capture_info, mutability }];
482 root_var_min_capture_list.insert(var_hir_id, min_cap_list);
485 Some(min_cap_list) => min_cap_list,
488 // Go through each entry in the current list of min_captures
489 // - if ancestor is found, update it's capture kind to account for current place's
490 // capture information.
492 // - if descendant is found, remove it from the list, and update the current place's
493 // capture information to account for the descendants's capture kind.
495 // We can never be in a case where the list contains both an ancestor and a descendant
496 // Also there can only be ancestor but in case of descendants there might be
499 let mut descendant_found = false;
500 let mut updated_capture_info = capture_info;
501 min_cap_list.retain(|possible_descendant| {
502 match determine_place_ancestry_relation(&place, &possible_descendant.place) {
503 // current place is ancestor of possible_descendant
504 PlaceAncestryRelation::Ancestor => {
505 descendant_found = true;
506 let backup_path_expr_id = updated_capture_info.path_expr_id;
508 updated_capture_info =
509 determine_capture_info(updated_capture_info, possible_descendant.info);
511 // we need to keep the ancestor's `path_expr_id`
512 updated_capture_info.path_expr_id = backup_path_expr_id;
520 let mut ancestor_found = false;
521 if !descendant_found {
522 for possible_ancestor in min_cap_list.iter_mut() {
523 match determine_place_ancestry_relation(&place, &possible_ancestor.place) {
524 // current place is descendant of possible_ancestor
525 PlaceAncestryRelation::Descendant => {
526 ancestor_found = true;
527 let backup_path_expr_id = possible_ancestor.info.path_expr_id;
528 possible_ancestor.info =
529 determine_capture_info(possible_ancestor.info, capture_info);
531 // we need to keep the ancestor's `path_expr_id`
532 possible_ancestor.info.path_expr_id = backup_path_expr_id;
534 // Only one ancestor of the current place will be in the list.
542 // Only need to insert when we don't have an ancestor in the existing min capture list
544 let mutability = self.determine_capture_mutability(&typeck_results, &place);
546 ty::CapturedPlace { place, info: updated_capture_info, mutability };
547 min_cap_list.push(captured_place);
551 debug!("For closure={:?}, min_captures={:#?}", closure_def_id, root_var_min_capture_list);
552 typeck_results.closure_min_captures.insert(closure_def_id, root_var_min_capture_list);
555 /// Perform the migration analysis for RFC 2229, and emit lint
556 /// `disjoint_capture_drop_reorder` if needed.
557 fn perform_2229_migration_anaysis(
559 closure_def_id: DefId,
560 body_id: hir::BodyId,
561 capture_clause: hir::CaptureBy,
564 let (need_migrations, reasons) = self.compute_2229_migrations(
568 self.typeck_results.borrow().closure_min_captures.get(&closure_def_id),
571 if !need_migrations.is_empty() {
572 let (migration_string, migrated_variables_concat) =
573 migration_suggestion_for_2229(self.tcx, &need_migrations);
575 let local_def_id = closure_def_id.expect_local();
576 let closure_hir_id = self.tcx.hir().local_def_id_to_hir_id(local_def_id);
577 self.tcx.struct_span_lint_hir(
578 lint::builtin::RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES,
582 let mut diagnostics_builder = lint.build(
584 "{} will change in Rust 2021",
589 diagnostics_builder.note("for more information, see <https://doc.rust-lang.org/nightly/edition-guide/rust-2021/disjoint-capture-in-closures.html>");
590 let closure_body_span = self.tcx.hir().span(body_id.hir_id);
592 match self.tcx.sess.source_map().span_to_snippet(closure_body_span) {
594 let trimmed = s.trim_start();
596 // If the closure contains a block then replace the opening brace
597 // with "{ let _ = (..); "
598 let sugg = if let Some('{') = trimmed.chars().next() {
599 format!("{{ {}; {}", migration_string, &trimmed[1..])
601 format!("{{ {}; {} }}", migration_string, s)
603 (sugg, Applicability::MachineApplicable)
605 Err(_) => (migration_string.clone(), Applicability::HasPlaceholders),
608 let diagnostic_msg = format!(
609 "add a dummy let to cause {} to be fully captured",
610 migrated_variables_concat
613 diagnostics_builder.span_suggestion(
619 diagnostics_builder.emit();
625 /// Combines all the reasons for 2229 migrations
626 fn compute_2229_migrations_reasons(
628 auto_trait_reasons: FxHashSet<&str>,
631 let mut reasons = String::new();
633 if auto_trait_reasons.len() > 0 {
635 "{} trait implementation",
636 auto_trait_reasons.clone().into_iter().collect::<Vec<&str>>().join(", ")
640 if auto_trait_reasons.len() > 0 && drop_reason {
641 reasons = format!("{}, and ", reasons);
645 reasons = format!("{}drop order", reasons);
651 /// Returns true if migration is needed for trait for the provided var_hir_id
652 fn need_2229_migrations_for_trait(
654 min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
655 var_hir_id: hir::HirId,
656 check_trait: Option<DefId>,
657 closure_clause: hir::CaptureBy,
659 let root_var_min_capture_list = if let Some(root_var_min_capture_list) =
660 min_captures.and_then(|m| m.get(&var_hir_id))
662 root_var_min_capture_list
667 let ty = self.infcx.resolve_vars_if_possible(self.node_ty(var_hir_id));
669 let ty = match closure_clause {
670 hir::CaptureBy::Value => ty, // For move closure the capture kind should be by value
671 hir::CaptureBy::Ref => {
672 // For non move closure the capture kind is the max capture kind of all captures
673 // according to the ordering ImmBorrow < UniqueImmBorrow < MutBorrow < ByValue
674 let mut max_capture_info = root_var_min_capture_list.first().unwrap().info;
675 for capture in root_var_min_capture_list.iter() {
676 max_capture_info = determine_capture_info(max_capture_info, capture.info);
679 apply_capture_kind_on_capture_ty(self.tcx, ty, max_capture_info.capture_kind)
683 let obligation_should_hold = check_trait
686 .type_implements_trait(
689 self.tcx.mk_substs_trait(ty, &[]),
692 .must_apply_modulo_regions()
696 // Check whether captured fields also implement the trait
697 for capture in root_var_min_capture_list.iter() {
698 let ty = apply_capture_kind_on_capture_ty(
701 capture.info.capture_kind,
704 let obligation_holds_for_capture = check_trait
707 .type_implements_trait(
710 self.tcx.mk_substs_trait(ty, &[]),
713 .must_apply_modulo_regions()
717 if !obligation_holds_for_capture && obligation_should_hold {
724 /// Figures out the list of root variables (and their types) that aren't completely
725 /// captured by the closure when `capture_disjoint_fields` is enabled and auto-traits
726 /// differ between the root variable and the captured paths.
728 /// The output list would include a root variable if:
729 /// - It would have been captured into the closure when `capture_disjoint_fields` wasn't
731 /// - It wasn't completely captured by the closure, **and**
732 /// - One of the paths captured does not implement all the auto-traits its root variable
734 fn compute_2229_migrations_for_trait(
736 min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
737 var_hir_id: hir::HirId,
738 closure_clause: hir::CaptureBy,
739 ) -> Option<FxHashSet<&str>> {
740 let tcx = self.infcx.tcx;
742 // Check whether catpured fields also implement the trait
743 let mut auto_trait_reasons = FxHashSet::default();
745 if self.need_2229_migrations_for_trait(
748 tcx.lang_items().clone_trait(),
751 auto_trait_reasons.insert("`Clone`");
754 if self.need_2229_migrations_for_trait(
757 tcx.lang_items().sync_trait(),
760 auto_trait_reasons.insert("`Sync`");
763 if self.need_2229_migrations_for_trait(
766 tcx.get_diagnostic_item(sym::send_trait),
769 auto_trait_reasons.insert("`Send`");
772 if self.need_2229_migrations_for_trait(
775 tcx.lang_items().unpin_trait(),
778 auto_trait_reasons.insert("`Unpin`");
781 if self.need_2229_migrations_for_trait(
784 tcx.get_diagnostic_item(sym::unwind_safe_trait),
787 auto_trait_reasons.insert("`UnwindSafe`");
790 if self.need_2229_migrations_for_trait(
793 tcx.get_diagnostic_item(sym::ref_unwind_safe_trait),
796 auto_trait_reasons.insert("`RefUnwindSafe`");
799 if auto_trait_reasons.len() > 0 {
800 return Some(auto_trait_reasons);
806 /// Figures out the list of root variables (and their types) that aren't completely
807 /// captured by the closure when `capture_disjoint_fields` is enabled and drop order of
808 /// some path starting at that root variable **might** be affected.
810 /// The output list would include a root variable if:
811 /// - It would have been moved into the closure when `capture_disjoint_fields` wasn't
813 /// - It wasn't completely captured by the closure, **and**
814 /// - One of the paths starting at this root variable, that is not captured needs Drop.
816 /// This function only returns true for significant drops. A type is considerent to have a
817 /// significant drop if it's Drop implementation is not annotated by `rustc_insignificant_dtor`.
818 fn compute_2229_migrations_for_drop(
820 closure_def_id: DefId,
822 min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
823 closure_clause: hir::CaptureBy,
824 var_hir_id: hir::HirId,
826 let ty = self.infcx.resolve_vars_if_possible(self.node_ty(var_hir_id));
828 if !ty.has_significant_drop(self.tcx, self.tcx.param_env(closure_def_id.expect_local())) {
832 let root_var_min_capture_list = if let Some(root_var_min_capture_list) =
833 min_captures.and_then(|m| m.get(&var_hir_id))
835 root_var_min_capture_list
837 // The upvar is mentioned within the closure but no path starting from it is
840 match closure_clause {
841 // Only migrate if closure is a move closure
842 hir::CaptureBy::Value => return true,
843 hir::CaptureBy::Ref => {}
849 let projections_list = root_var_min_capture_list
851 .filter_map(|captured_place| match captured_place.info.capture_kind {
852 // Only care about captures that are moved into the closure
853 ty::UpvarCapture::ByValue(..) => Some(captured_place.place.projections.as_slice()),
854 ty::UpvarCapture::ByRef(..) => None,
856 .collect::<Vec<_>>();
858 let is_moved = !projections_list.is_empty();
860 let is_not_completely_captured =
861 root_var_min_capture_list.iter().any(|capture| capture.place.projections.len() > 0);
864 && is_not_completely_captured
865 && self.has_significant_drop_outside_of_captures(
878 /// Figures out the list of root variables (and their types) that aren't completely
879 /// captured by the closure when `capture_disjoint_fields` is enabled and either drop
880 /// order of some path starting at that root variable **might** be affected or auto-traits
881 /// differ between the root variable and the captured paths.
883 /// The output list would include a root variable if:
884 /// - It would have been moved into the closure when `capture_disjoint_fields` wasn't
886 /// - It wasn't completely captured by the closure, **and**
887 /// - One of the paths starting at this root variable, that is not captured needs Drop **or**
888 /// - One of the paths captured does not implement all the auto-traits its root variable
891 /// Returns a tuple containing a vector of HirIds as well as a String containing the reason
892 /// why root variables whose HirId is contained in the vector should be fully captured.
893 fn compute_2229_migrations(
895 closure_def_id: DefId,
897 closure_clause: hir::CaptureBy,
898 min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
899 ) -> (Vec<hir::HirId>, String) {
900 let upvars = if let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) {
903 return (Vec::new(), format!(""));
906 let mut need_migrations = Vec::new();
907 let mut auto_trait_reasons = FxHashSet::default();
908 let mut drop_reorder_reason = false;
910 // Perform auto-trait analysis
911 for (&var_hir_id, _) in upvars.iter() {
912 let mut need_migration = false;
913 if let Some(trait_migration_cause) =
914 self.compute_2229_migrations_for_trait(min_captures, var_hir_id, closure_clause)
916 need_migration = true;
917 auto_trait_reasons.extend(trait_migration_cause);
920 if self.compute_2229_migrations_for_drop(
927 need_migration = true;
928 drop_reorder_reason = true;
932 need_migrations.push(var_hir_id);
938 self.compute_2229_migrations_reasons(auto_trait_reasons, drop_reorder_reason),
942 /// This is a helper function to `compute_2229_migrations_precise_pass`. Provided the type
943 /// of a root variable and a list of captured paths starting at this root variable (expressed
944 /// using list of `Projection` slices), it returns true if there is a path that is not
945 /// captured starting at this root variable that implements Drop.
947 /// The way this function works is at a given call it looks at type `base_path_ty` of some base
948 /// path say P and then list of projection slices which represent the different captures moved
949 /// into the closure starting off of P.
951 /// This will make more sense with an example:
954 /// #![feature(capture_disjoint_fields)]
956 /// struct FancyInteger(i32); // This implements Drop
958 /// struct Point { x: FancyInteger, y: FancyInteger }
961 /// struct Wrapper { p: Point, c: Color }
963 /// fn f(w: Wrapper) {
965 /// // Closure captures w.p.x and w.c by move.
972 /// If `capture_disjoint_fields` wasn't enabled the closure would've moved `w` instead of the
973 /// precise paths. If we look closely `w.p.y` isn't captured which implements Drop and
974 /// therefore Drop ordering would change and we want this function to return true.
976 /// Call stack to figure out if we need to migrate for `w` would look as follows:
978 /// Our initial base path is just `w`, and the paths captured from it are `w[p, x]` and
981 /// - Ty(place): Type of place
982 /// - `(a, b)`: Represents the function parameters `base_path_ty` and `captured_by_move_projs`
985 /// (Ty(w), [ &[p, x], &[c] ])
987 /// ----------------------------
990 /// (Ty(w.p), [ &[x] ]) (Ty(w.c), [ &[] ]) // I(1)
993 /// (Ty(w.p), [ &[x] ]) false
996 /// -------------------------------
999 /// (Ty((w.p).x), [ &[] ]) (Ty((w.p).y), []) // IMP 2
1002 /// false NeedsSignificantDrop(Ty(w.p.y))
1008 /// IMP 1 `(Ty(w.c), [ &[] ])`: Notice the single empty slice inside `captured_projs`.
1009 /// This implies that the `w.c` is completely captured by the closure.
1010 /// Since drop for this path will be called when the closure is
1011 /// dropped we don't need to migrate for it.
1013 /// IMP 2 `(Ty((w.p).y), [])`: Notice that `captured_projs` is empty. This implies that this
1014 /// path wasn't captured by the closure. Also note that even
1015 /// though we didn't capture this path, the function visits it,
1016 /// which is kind of the point of this function. We then return
1017 /// if the type of `w.p.y` implements Drop, which in this case is
1020 /// Consider another example:
1024 /// impl Drop for X {}
1027 /// impl Drop for Y {}
1031 /// let c = || move(y.0);
1035 /// Note that `y.0` is captured by the closure. When this function is called for `y`, it will
1036 /// return true, because even though all paths starting at `y` are captured, `y` itself
1037 /// implements Drop which will be affected since `y` isn't completely captured.
1038 fn has_significant_drop_outside_of_captures(
1040 closure_def_id: DefId,
1042 base_path_ty: Ty<'tcx>,
1043 captured_by_move_projs: Vec<&[Projection<'tcx>]>,
1045 let needs_drop = |ty: Ty<'tcx>| {
1046 ty.has_significant_drop(self.tcx, self.tcx.param_env(closure_def_id.expect_local()))
1049 let is_drop_defined_for_ty = |ty: Ty<'tcx>| {
1050 let drop_trait = self.tcx.require_lang_item(hir::LangItem::Drop, Some(closure_span));
1051 let ty_params = self.tcx.mk_substs_trait(base_path_ty, &[]);
1053 .type_implements_trait(
1057 self.tcx.param_env(closure_def_id.expect_local()),
1059 .must_apply_modulo_regions()
1062 let is_drop_defined_for_ty = is_drop_defined_for_ty(base_path_ty);
1064 // If there is a case where no projection is applied on top of current place
1065 // then there must be exactly one capture corresponding to such a case. Note that this
1066 // represents the case of the path being completely captured by the variable.
1068 // eg. If `a.b` is captured and we are processing `a.b`, then we can't have the closure also
1069 // capture `a.b.c`, because that voilates min capture.
1070 let is_completely_captured = captured_by_move_projs.iter().any(|projs| projs.is_empty());
1072 assert!(!is_completely_captured || (captured_by_move_projs.len() == 1));
1074 if is_completely_captured {
1075 // The place is captured entirely, so doesn't matter if needs dtor, it will be drop
1076 // when the closure is dropped.
1080 if captured_by_move_projs.is_empty() {
1081 return needs_drop(base_path_ty);
1084 if is_drop_defined_for_ty {
1085 // If drop is implemented for this type then we need it to be fully captured,
1086 // and we know it is not completely captured because of the previous checks.
1088 // Note that this is a bug in the user code that will be reported by the
1089 // borrow checker, since we can't move out of drop types.
1091 // The bug exists in the user's code pre-migration, and we don't migrate here.
1095 match base_path_ty.kind() {
1097 // - `captured_by_move_projs` is not empty. Therefore we can call
1098 // `captured_by_move_projs.first().unwrap()` safely.
1099 // - All entries in `captured_by_move_projs` have atleast one projection.
1100 // Therefore we can call `captured_by_move_projs.first().unwrap().first().unwrap()` safely.
1102 // We don't capture derefs in case of move captures, which would have be applied to
1103 // access any further paths.
1104 ty::Adt(def, _) if def.is_box() => unreachable!(),
1105 ty::Ref(..) => unreachable!(),
1106 ty::RawPtr(..) => unreachable!(),
1108 ty::Adt(def, substs) => {
1109 // Multi-varaint enums are captured in entirety,
1110 // which would've been handled in the case of single empty slice in `captured_by_move_projs`.
1111 assert_eq!(def.variants.len(), 1);
1113 // Only Field projections can be applied to a non-box Adt.
1115 captured_by_move_projs.iter().all(|projs| matches!(
1116 projs.first().unwrap().kind,
1117 ProjectionKind::Field(..)
1120 def.variants.get(VariantIdx::new(0)).unwrap().fields.iter().enumerate().any(
1122 let paths_using_field = captured_by_move_projs
1124 .filter_map(|projs| {
1125 if let ProjectionKind::Field(field_idx, _) =
1126 projs.first().unwrap().kind
1128 if (field_idx as usize) == i { Some(&projs[1..]) } else { None }
1135 let after_field_ty = field.ty(self.tcx, substs);
1136 self.has_significant_drop_outside_of_captures(
1147 // Only Field projections can be applied to a tuple.
1149 captured_by_move_projs.iter().all(|projs| matches!(
1150 projs.first().unwrap().kind,
1151 ProjectionKind::Field(..)
1155 base_path_ty.tuple_fields().enumerate().any(|(i, element_ty)| {
1156 let paths_using_field = captured_by_move_projs
1158 .filter_map(|projs| {
1159 if let ProjectionKind::Field(field_idx, _) = projs.first().unwrap().kind
1161 if (field_idx as usize) == i { Some(&projs[1..]) } else { None }
1168 self.has_significant_drop_outside_of_captures(
1177 // Anything else would be completely captured and therefore handled already.
1178 _ => unreachable!(),
1182 fn init_capture_kind_for_place(
1184 place: &Place<'tcx>,
1185 capture_clause: hir::CaptureBy,
1186 upvar_id: ty::UpvarId,
1188 ) -> ty::UpvarCapture<'tcx> {
1189 match capture_clause {
1190 // In case of a move closure if the data is accessed through a reference we
1191 // want to capture by ref to allow precise capture using reborrows.
1193 // If the data will be moved out of this place, then the place will be truncated
1194 // at the first Deref in `adjust_upvar_borrow_kind_for_consume` and then moved into
1196 hir::CaptureBy::Value if !place.deref_tys().any(ty::TyS::is_ref) => {
1197 ty::UpvarCapture::ByValue(None)
1199 hir::CaptureBy::Value | hir::CaptureBy::Ref => {
1200 let origin = UpvarRegion(upvar_id, closure_span);
1201 let upvar_region = self.next_region_var(origin);
1202 let upvar_borrow = ty::UpvarBorrow { kind: ty::ImmBorrow, region: upvar_region };
1203 ty::UpvarCapture::ByRef(upvar_borrow)
1208 fn place_for_root_variable(
1210 closure_def_id: LocalDefId,
1211 var_hir_id: hir::HirId,
1213 let upvar_id = ty::UpvarId::new(var_hir_id, closure_def_id);
1216 base_ty: self.node_ty(var_hir_id),
1217 base: PlaceBase::Upvar(upvar_id),
1218 projections: Default::default(),
1222 fn should_log_capture_analysis(&self, closure_def_id: DefId) -> bool {
1223 self.tcx.has_attr(closure_def_id, sym::rustc_capture_analysis)
1226 fn log_capture_analysis_first_pass(
1228 closure_def_id: rustc_hir::def_id::DefId,
1229 capture_information: &FxIndexMap<Place<'tcx>, ty::CaptureInfo<'tcx>>,
1232 if self.should_log_capture_analysis(closure_def_id) {
1234 self.tcx.sess.struct_span_err(closure_span, "First Pass analysis includes:");
1235 for (place, capture_info) in capture_information {
1236 let capture_str = construct_capture_info_string(self.tcx, place, capture_info);
1237 let output_str = format!("Capturing {}", capture_str);
1240 capture_info.path_expr_id.map_or(closure_span, |e| self.tcx.hir().span(e));
1241 diag.span_note(span, &output_str);
1247 fn log_closure_min_capture_info(&self, closure_def_id: DefId, closure_span: Span) {
1248 if self.should_log_capture_analysis(closure_def_id) {
1249 if let Some(min_captures) =
1250 self.typeck_results.borrow().closure_min_captures.get(&closure_def_id)
1253 self.tcx.sess.struct_span_err(closure_span, "Min Capture analysis includes:");
1255 for (_, min_captures_for_var) in min_captures {
1256 for capture in min_captures_for_var {
1257 let place = &capture.place;
1258 let capture_info = &capture.info;
1261 construct_capture_info_string(self.tcx, place, capture_info);
1262 let output_str = format!("Min Capture {}", capture_str);
1264 if capture.info.path_expr_id != capture.info.capture_kind_expr_id {
1265 let path_span = capture_info
1267 .map_or(closure_span, |e| self.tcx.hir().span(e));
1268 let capture_kind_span = capture_info
1269 .capture_kind_expr_id
1270 .map_or(closure_span, |e| self.tcx.hir().span(e));
1272 let mut multi_span: MultiSpan =
1273 MultiSpan::from_spans(vec![path_span, capture_kind_span]);
1275 let capture_kind_label =
1276 construct_capture_kind_reason_string(self.tcx, place, capture_info);
1277 let path_label = construct_path_string(self.tcx, place);
1279 multi_span.push_span_label(path_span, path_label);
1280 multi_span.push_span_label(capture_kind_span, capture_kind_label);
1282 diag.span_note(multi_span, &output_str);
1284 let span = capture_info
1286 .map_or(closure_span, |e| self.tcx.hir().span(e));
1288 diag.span_note(span, &output_str);
1297 /// A captured place is mutable if
1298 /// 1. Projections don't include a Deref of an immut-borrow, **and**
1299 /// 2. PlaceBase is mut or projections include a Deref of a mut-borrow.
1300 fn determine_capture_mutability(
1302 typeck_results: &'a TypeckResults<'tcx>,
1303 place: &Place<'tcx>,
1304 ) -> hir::Mutability {
1305 let var_hir_id = match place.base {
1306 PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
1307 _ => unreachable!(),
1310 let bm = *typeck_results.pat_binding_modes().get(var_hir_id).expect("missing binding mode");
1312 let mut is_mutbl = match bm {
1313 ty::BindByValue(mutability) => mutability,
1314 ty::BindByReference(_) => hir::Mutability::Not,
1317 for pointer_ty in place.deref_tys() {
1318 match pointer_ty.kind() {
1319 // We don't capture derefs of raw ptrs
1320 ty::RawPtr(_) => unreachable!(),
1322 // Derefencing a mut-ref allows us to mut the Place if we don't deref
1323 // an immut-ref after on top of this.
1324 ty::Ref(.., hir::Mutability::Mut) => is_mutbl = hir::Mutability::Mut,
1326 // The place isn't mutable once we dereference a immutable reference.
1327 ty::Ref(.., hir::Mutability::Not) => return hir::Mutability::Not,
1329 // Dereferencing a box doesn't change mutability
1330 ty::Adt(def, ..) if def.is_box() => {}
1332 unexpected_ty => bug!("deref of unexpected pointer type {:?}", unexpected_ty),
1340 /// Truncate the capture so that the place being borrowed is in accordance with RFC 1240,
1341 /// which states that it's unsafe to take a reference into a struct marked `repr(packed)`.
1342 fn restrict_repr_packed_field_ref_capture<'tcx>(
1344 param_env: ty::ParamEnv<'tcx>,
1345 place: &Place<'tcx>,
1347 let pos = place.projections.iter().enumerate().position(|(i, p)| {
1348 let ty = place.ty_before_projection(i);
1350 // Return true for fields of packed structs, unless those fields have alignment 1.
1352 ProjectionKind::Field(..) => match ty.kind() {
1353 ty::Adt(def, _) if def.repr.packed() => {
1354 match tcx.layout_raw(param_env.and(p.ty)) {
1355 Ok(layout) if layout.align.abi.bytes() == 1 => {
1356 // if the alignment is 1, the type can't be further
1359 "restrict_repr_packed_field_ref_capture: ({:?}) - align = 1",
1365 debug!("restrict_repr_packed_field_ref_capture: ({:?}) - true", place);
1377 let mut place = place.clone();
1379 if let Some(pos) = pos {
1380 place.projections.truncate(pos);
1386 /// Returns a Ty that applies the specified capture kind on the provided capture Ty
1387 fn apply_capture_kind_on_capture_ty(
1390 capture_kind: UpvarCapture<'tcx>,
1392 match capture_kind {
1393 ty::UpvarCapture::ByValue(_) => ty,
1394 ty::UpvarCapture::ByRef(borrow) => tcx
1395 .mk_ref(borrow.region, ty::TypeAndMut { ty: ty, mutbl: borrow.kind.to_mutbl_lossy() }),
1399 struct InferBorrowKind<'a, 'tcx> {
1400 fcx: &'a FnCtxt<'a, 'tcx>,
1402 // The def-id of the closure whose kind and upvar accesses are being inferred.
1403 closure_def_id: DefId,
1407 /// For each Place that is captured by the closure, we track the minimal kind of
1408 /// access we need (ref, ref mut, move, etc) and the expression that resulted in such access.
1410 /// Consider closure where s.str1 is captured via an ImmutableBorrow and
1411 /// s.str2 via a MutableBorrow
1414 /// struct SomeStruct { str1: String, str2: String }
1416 /// // Assume that the HirId for the variable definition is `V1`
1417 /// let mut s = SomeStruct { str1: format!("s1"), str2: format!("s2") }
1419 /// let fix_s = |new_s2| {
1420 /// // Assume that the HirId for the expression `s.str1` is `E1`
1421 /// println!("Updating SomeStruct with str1=", s.str1);
1422 /// // Assume that the HirId for the expression `*s.str2` is `E2`
1423 /// s.str2 = new_s2;
1427 /// For closure `fix_s`, (at a high level) the map contains
1430 /// Place { V1, [ProjectionKind::Field(Index=0, Variant=0)] } : CaptureKind { E1, ImmutableBorrow }
1431 /// Place { V1, [ProjectionKind::Field(Index=1, Variant=0)] } : CaptureKind { E2, MutableBorrow }
1433 capture_information: InferredCaptureInformation<'tcx>,
1434 fake_reads: Vec<(Place<'tcx>, FakeReadCause, hir::HirId)>,
1437 impl<'a, 'tcx> InferBorrowKind<'a, 'tcx> {
1438 fn adjust_upvar_borrow_kind_for_consume(
1440 place_with_id: &PlaceWithHirId<'tcx>,
1441 diag_expr_id: hir::HirId,
1442 mode: euv::ConsumeMode,
1445 "adjust_upvar_borrow_kind_for_consume(place_with_id={:?}, diag_expr_id={:?}, mode={:?})",
1446 place_with_id, diag_expr_id, mode
1449 // Copy type being used as ByValue are equivalent to ImmBorrow and don't require any
1452 euv::ConsumeMode::Copy => return,
1453 euv::ConsumeMode::Move => {}
1456 let tcx = self.fcx.tcx;
1457 let upvar_id = if let PlaceBase::Upvar(upvar_id) = place_with_id.place.base {
1463 debug!("adjust_upvar_borrow_kind_for_consume: upvar={:?}", upvar_id);
1465 let usage_span = tcx.hir().span(diag_expr_id);
1467 let capture_info = ty::CaptureInfo {
1468 capture_kind_expr_id: Some(diag_expr_id),
1469 path_expr_id: Some(diag_expr_id),
1470 capture_kind: ty::UpvarCapture::ByValue(Some(usage_span)),
1473 let curr_info = self.capture_information[&place_with_id.place];
1474 let updated_info = determine_capture_info(curr_info, capture_info);
1476 self.capture_information[&place_with_id.place] = updated_info;
1479 /// Indicates that `place_with_id` is being directly mutated (e.g., assigned
1480 /// to). If the place is based on a by-ref upvar, this implies that
1481 /// the upvar must be borrowed using an `&mut` borrow.
1482 fn adjust_upvar_borrow_kind_for_mut(
1484 place_with_id: &PlaceWithHirId<'tcx>,
1485 diag_expr_id: hir::HirId,
1488 "adjust_upvar_borrow_kind_for_mut(place_with_id={:?}, diag_expr_id={:?})",
1489 place_with_id, diag_expr_id
1492 if let PlaceBase::Upvar(_) = place_with_id.place.base {
1493 let mut borrow_kind = ty::MutBorrow;
1494 for pointer_ty in place_with_id.place.deref_tys() {
1495 match pointer_ty.kind() {
1496 // Raw pointers don't inherit mutability.
1497 ty::RawPtr(_) => return,
1498 // assignment to deref of an `&mut`
1499 // borrowed pointer implies that the
1500 // pointer itself must be unique, but not
1501 // necessarily *mutable*
1502 ty::Ref(.., hir::Mutability::Mut) => borrow_kind = ty::UniqueImmBorrow,
1506 self.adjust_upvar_deref(place_with_id, diag_expr_id, borrow_kind);
1510 fn adjust_upvar_borrow_kind_for_unique(
1512 place_with_id: &PlaceWithHirId<'tcx>,
1513 diag_expr_id: hir::HirId,
1516 "adjust_upvar_borrow_kind_for_unique(place_with_id={:?}, diag_expr_id={:?})",
1517 place_with_id, diag_expr_id
1520 if let PlaceBase::Upvar(_) = place_with_id.place.base {
1521 if place_with_id.place.deref_tys().any(ty::TyS::is_unsafe_ptr) {
1522 // Raw pointers don't inherit mutability.
1525 // for a borrowed pointer to be unique, its base must be unique
1526 self.adjust_upvar_deref(place_with_id, diag_expr_id, ty::UniqueImmBorrow);
1530 fn adjust_upvar_deref(
1532 place_with_id: &PlaceWithHirId<'tcx>,
1533 diag_expr_id: hir::HirId,
1534 borrow_kind: ty::BorrowKind,
1536 assert!(match borrow_kind {
1537 ty::MutBorrow => true,
1538 ty::UniqueImmBorrow => true,
1540 // imm borrows never require adjusting any kinds, so we don't wind up here
1541 ty::ImmBorrow => false,
1544 // if this is an implicit deref of an
1545 // upvar, then we need to modify the
1546 // borrow_kind of the upvar to make sure it
1547 // is inferred to mutable if necessary
1548 self.adjust_upvar_borrow_kind(place_with_id, diag_expr_id, borrow_kind);
1551 /// We infer the borrow_kind with which to borrow upvars in a stack closure.
1552 /// The borrow_kind basically follows a lattice of `imm < unique-imm < mut`,
1553 /// moving from left to right as needed (but never right to left).
1554 /// Here the argument `mutbl` is the borrow_kind that is required by
1555 /// some particular use.
1556 fn adjust_upvar_borrow_kind(
1558 place_with_id: &PlaceWithHirId<'tcx>,
1559 diag_expr_id: hir::HirId,
1560 kind: ty::BorrowKind,
1562 let curr_capture_info = self.capture_information[&place_with_id.place];
1565 "adjust_upvar_borrow_kind(place={:?}, diag_expr_id={:?}, capture_info={:?}, kind={:?})",
1566 place_with_id, diag_expr_id, curr_capture_info, kind
1569 if let ty::UpvarCapture::ByValue(_) = curr_capture_info.capture_kind {
1570 // It's already captured by value, we don't need to do anything here
1572 } else if let ty::UpvarCapture::ByRef(curr_upvar_borrow) = curr_capture_info.capture_kind {
1573 // Use the same region as the current capture information
1574 // Doesn't matter since only one of the UpvarBorrow will be used.
1575 let new_upvar_borrow = ty::UpvarBorrow { kind, region: curr_upvar_borrow.region };
1577 let capture_info = ty::CaptureInfo {
1578 capture_kind_expr_id: Some(diag_expr_id),
1579 path_expr_id: Some(diag_expr_id),
1580 capture_kind: ty::UpvarCapture::ByRef(new_upvar_borrow),
1582 let updated_info = determine_capture_info(curr_capture_info, capture_info);
1583 self.capture_information[&place_with_id.place] = updated_info;
1587 fn init_capture_info_for_place(
1589 place_with_id: &PlaceWithHirId<'tcx>,
1590 diag_expr_id: hir::HirId,
1592 if let PlaceBase::Upvar(upvar_id) = place_with_id.place.base {
1593 assert_eq!(self.closure_def_id.expect_local(), upvar_id.closure_expr_id);
1595 // Initialize to ImmBorrow
1596 // We will escalate the CaptureKind based on any uses we see or in `process_collected_capture_information`.
1597 let origin = UpvarRegion(upvar_id, self.closure_span);
1598 let upvar_region = self.fcx.next_region_var(origin);
1599 let upvar_borrow = ty::UpvarBorrow { kind: ty::ImmBorrow, region: upvar_region };
1600 let capture_kind = ty::UpvarCapture::ByRef(upvar_borrow);
1602 let expr_id = Some(diag_expr_id);
1603 let capture_info = ty::CaptureInfo {
1604 capture_kind_expr_id: expr_id,
1605 path_expr_id: expr_id,
1609 debug!("Capturing new place {:?}, capture_info={:?}", place_with_id, capture_info);
1611 self.capture_information.insert(place_with_id.place.clone(), capture_info);
1613 debug!("Not upvar: {:?}", place_with_id);
1618 impl<'a, 'tcx> euv::Delegate<'tcx> for InferBorrowKind<'a, 'tcx> {
1619 fn fake_read(&mut self, place: Place<'tcx>, cause: FakeReadCause, diag_expr_id: hir::HirId) {
1620 if let PlaceBase::Upvar(_) = place.base {
1621 // We need to restrict Fake Read precision to avoid fake reading unsafe code,
1622 // such as deref of a raw pointer.
1623 let place = restrict_capture_precision(place);
1625 restrict_repr_packed_field_ref_capture(self.fcx.tcx, self.fcx.param_env, &place);
1626 self.fake_reads.push((place, cause, diag_expr_id));
1632 place_with_id: &PlaceWithHirId<'tcx>,
1633 diag_expr_id: hir::HirId,
1634 mode: euv::ConsumeMode,
1637 "consume(place_with_id={:?}, diag_expr_id={:?}, mode={:?})",
1638 place_with_id, diag_expr_id, mode
1641 if !self.capture_information.contains_key(&place_with_id.place) {
1642 self.init_capture_info_for_place(&place_with_id, diag_expr_id);
1645 self.adjust_upvar_borrow_kind_for_consume(&place_with_id, diag_expr_id, mode);
1650 place_with_id: &PlaceWithHirId<'tcx>,
1651 diag_expr_id: hir::HirId,
1655 "borrow(place_with_id={:?}, diag_expr_id={:?}, bk={:?})",
1656 place_with_id, diag_expr_id, bk
1659 // We only want repr packed restriction to be applied to reading references into a packed
1660 // struct, and not when the data is being moved. Therefore we call this method here instead
1661 // of in `restrict_capture_precision`.
1662 let place = restrict_repr_packed_field_ref_capture(
1665 &place_with_id.place,
1668 let place_with_id = PlaceWithHirId { place, ..*place_with_id };
1670 if !self.capture_information.contains_key(&place_with_id.place) {
1671 self.init_capture_info_for_place(&place_with_id, diag_expr_id);
1676 ty::UniqueImmBorrow => {
1677 self.adjust_upvar_borrow_kind_for_unique(&place_with_id, diag_expr_id);
1680 self.adjust_upvar_borrow_kind_for_mut(&place_with_id, diag_expr_id);
1685 fn mutate(&mut self, assignee_place: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId) {
1686 debug!("mutate(assignee_place={:?}, diag_expr_id={:?})", assignee_place, diag_expr_id);
1688 self.borrow(assignee_place, diag_expr_id, ty::BorrowKind::MutBorrow);
1692 /// Truncate projections so that following rules are obeyed by the captured `place`:
1693 /// - No projections are applied to raw pointers, since these require unsafe blocks. We capture
1694 /// them completely.
1695 /// - No Index projections are captured, since arrays are captured completely.
1696 fn restrict_capture_precision<'tcx>(mut place: Place<'tcx>) -> Place<'tcx> {
1697 if place.projections.is_empty() {
1698 // Nothing to do here
1702 if place.base_ty.is_unsafe_ptr() {
1703 place.projections.truncate(0);
1707 let mut truncated_length = usize::MAX;
1709 for (i, proj) in place.projections.iter().enumerate() {
1710 if proj.ty.is_unsafe_ptr() {
1711 // Don't apply any projections on top of an unsafe ptr
1712 truncated_length = truncated_length.min(i + 1);
1716 ProjectionKind::Index => {
1717 // Arrays are completely captured, so we drop Index projections
1718 truncated_length = truncated_length.min(i);
1721 ProjectionKind::Deref => {}
1722 ProjectionKind::Field(..) => {} // ignore
1723 ProjectionKind::Subslice => {} // We never capture this
1727 let length = place.projections.len().min(truncated_length);
1729 place.projections.truncate(length);
1734 /// Take ownership if data being accessed is owned by the variable used to access it
1735 /// (or if closure attempts to move data that it doesn’t own).
1736 /// Note: When taking ownership, only capture data found on the stack.
1737 fn adjust_for_move_closure<'tcx>(
1738 mut place: Place<'tcx>,
1739 kind: ty::UpvarCapture<'tcx>,
1740 ) -> (Place<'tcx>, ty::UpvarCapture<'tcx>) {
1741 let contains_deref_of_ref = place.deref_tys().any(|ty| ty.is_ref());
1742 let first_deref = place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
1745 ty::UpvarCapture::ByRef(..) if contains_deref_of_ref => (place, kind),
1747 // If there's any Deref and the data needs to be moved into the closure body,
1748 // or it's a Deref of a Box, truncate the path to the first deref
1749 _ if first_deref.is_some() => {
1750 let place = match first_deref {
1752 place.projections.truncate(idx);
1758 // AMAN: I think we don't need the span inside the ByValue anymore
1759 // we have more detailed span in CaptureInfo
1760 (place, ty::UpvarCapture::ByValue(None))
1763 _ => (place, ty::UpvarCapture::ByValue(None)),
1767 /// Adjust closure capture just that if taking ownership of data, only move data
1768 /// from enclosing stack frame.
1769 fn adjust_for_non_move_closure<'tcx>(
1770 mut place: Place<'tcx>,
1771 kind: ty::UpvarCapture<'tcx>,
1772 ) -> (Place<'tcx>, ty::UpvarCapture<'tcx>) {
1773 let contains_deref =
1774 place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
1777 ty::UpvarCapture::ByValue(..) if contains_deref.is_some() => {
1778 let place = match contains_deref {
1780 place.projections.truncate(idx);
1783 // Because of the if guard on the match on `kind`, we should never get here.
1784 None => unreachable!(),
1790 ty::UpvarCapture::ByValue(..) => (place, kind),
1791 ty::UpvarCapture::ByRef(..) => (place, kind),
1795 fn construct_place_string(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
1796 let variable_name = match place.base {
1797 PlaceBase::Upvar(upvar_id) => var_name(tcx, upvar_id.var_path.hir_id).to_string(),
1798 _ => bug!("Capture_information should only contain upvars"),
1801 let mut projections_str = String::new();
1802 for (i, item) in place.projections.iter().enumerate() {
1803 let proj = match item.kind {
1804 ProjectionKind::Field(a, b) => format!("({:?}, {:?})", a, b),
1805 ProjectionKind::Deref => String::from("Deref"),
1806 ProjectionKind::Index => String::from("Index"),
1807 ProjectionKind::Subslice => String::from("Subslice"),
1810 projections_str.push(',');
1812 projections_str.push_str(proj.as_str());
1815 format!("{}[{}]", variable_name, projections_str)
1818 fn construct_capture_kind_reason_string(
1820 place: &Place<'tcx>,
1821 capture_info: &ty::CaptureInfo<'tcx>,
1823 let place_str = construct_place_string(tcx, &place);
1825 let capture_kind_str = match capture_info.capture_kind {
1826 ty::UpvarCapture::ByValue(_) => "ByValue".into(),
1827 ty::UpvarCapture::ByRef(borrow) => format!("{:?}", borrow.kind),
1830 format!("{} captured as {} here", place_str, capture_kind_str)
1833 fn construct_path_string(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
1834 let place_str = construct_place_string(tcx, &place);
1836 format!("{} used here", place_str)
1839 fn construct_capture_info_string(
1841 place: &Place<'tcx>,
1842 capture_info: &ty::CaptureInfo<'tcx>,
1844 let place_str = construct_place_string(tcx, &place);
1846 let capture_kind_str = match capture_info.capture_kind {
1847 ty::UpvarCapture::ByValue(_) => "ByValue".into(),
1848 ty::UpvarCapture::ByRef(borrow) => format!("{:?}", borrow.kind),
1850 format!("{} -> {}", place_str, capture_kind_str)
1853 fn var_name(tcx: TyCtxt<'_>, var_hir_id: hir::HirId) -> Symbol {
1854 tcx.hir().name(var_hir_id)
1857 fn should_do_rust_2021_incompatible_closure_captures_analysis(
1859 closure_id: hir::HirId,
1862 tcx.lint_level_at_node(lint::builtin::RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES, closure_id);
1864 !matches!(level, lint::Level::Allow)
1867 /// Return a two string tuple (s1, s2)
1868 /// - s1: Line of code that is needed for the migration: eg: `let _ = (&x, ...)`.
1869 /// - s2: Comma separated names of the variables being migrated.
1870 fn migration_suggestion_for_2229(
1872 need_migrations: &Vec<hir::HirId>,
1873 ) -> (String, String) {
1874 let need_migrations_variables =
1875 need_migrations.iter().map(|v| var_name(tcx, *v)).collect::<Vec<_>>();
1877 let migration_ref_concat =
1878 need_migrations_variables.iter().map(|v| format!("&{}", v)).collect::<Vec<_>>().join(", ");
1880 let migration_string = if 1 == need_migrations.len() {
1881 format!("let _ = {}", migration_ref_concat)
1883 format!("let _ = ({})", migration_ref_concat)
1886 let migrated_variables_concat =
1887 need_migrations_variables.iter().map(|v| format!("`{}`", v)).collect::<Vec<_>>().join(", ");
1889 (migration_string, migrated_variables_concat)
1892 /// Helper function to determine if we need to escalate CaptureKind from
1893 /// CaptureInfo A to B and returns the escalated CaptureInfo.
1894 /// (Note: CaptureInfo contains CaptureKind and an expression that led to capture it in that way)
1896 /// If both `CaptureKind`s are considered equivalent, then the CaptureInfo is selected based
1897 /// on the `CaptureInfo` containing an associated `capture_kind_expr_id`.
1899 /// It is the caller's duty to figure out which path_expr_id to use.
1901 /// If both the CaptureKind and Expression are considered to be equivalent,
1902 /// then `CaptureInfo` A is preferred. This can be useful in cases where we want to priortize
1903 /// expressions reported back to the user as part of diagnostics based on which appears earlier
1904 /// in the closure. This can be achieved simply by calling
1905 /// `determine_capture_info(existing_info, current_info)`. This works out because the
1906 /// expressions that occur earlier in the closure body than the current expression are processed before.
1907 /// Consider the following example
1909 /// struct Point { x: i32, y: i32 }
1910 /// let mut p: Point { x: 10, y: 10 };
1918 /// p.x += 10; // E2
1922 /// `CaptureKind` associated with both `E1` and `E2` will be ByRef(MutBorrow),
1923 /// and both have an expression associated, however for diagnostics we prefer reporting
1924 /// `E1` since it appears earlier in the closure body. When `E2` is being processed we
1925 /// would've already handled `E1`, and have an existing capture_information for it.
1926 /// Calling `determine_capture_info(existing_info_e1, current_info_e2)` will return
1927 /// `existing_info_e1` in this case, allowing us to point to `E1` in case of diagnostics.
1928 fn determine_capture_info(
1929 capture_info_a: ty::CaptureInfo<'tcx>,
1930 capture_info_b: ty::CaptureInfo<'tcx>,
1931 ) -> ty::CaptureInfo<'tcx> {
1932 // If the capture kind is equivalent then, we don't need to escalate and can compare the
1934 let eq_capture_kind = match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
1935 (ty::UpvarCapture::ByValue(_), ty::UpvarCapture::ByValue(_)) => {
1936 // We don't need to worry about the spans being ignored here.
1938 // The expr_id in capture_info corresponds to the span that is stored within
1939 // ByValue(span) and therefore it gets handled with priortizing based on
1940 // expressions below.
1943 (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => {
1944 ref_a.kind == ref_b.kind
1946 (ty::UpvarCapture::ByValue(_), _) | (ty::UpvarCapture::ByRef(_), _) => false,
1949 if eq_capture_kind {
1950 match (capture_info_a.capture_kind_expr_id, capture_info_b.capture_kind_expr_id) {
1951 (Some(_), _) | (None, None) => capture_info_a,
1952 (None, Some(_)) => capture_info_b,
1955 // We select the CaptureKind which ranks higher based the following priority order:
1956 // ByValue > MutBorrow > UniqueImmBorrow > ImmBorrow
1957 match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
1958 (ty::UpvarCapture::ByValue(_), _) => capture_info_a,
1959 (_, ty::UpvarCapture::ByValue(_)) => capture_info_b,
1960 (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => {
1961 match (ref_a.kind, ref_b.kind) {
1963 (ty::UniqueImmBorrow | ty::MutBorrow, ty::ImmBorrow)
1964 | (ty::MutBorrow, ty::UniqueImmBorrow) => capture_info_a,
1967 (ty::ImmBorrow, ty::UniqueImmBorrow | ty::MutBorrow)
1968 | (ty::UniqueImmBorrow, ty::MutBorrow) => capture_info_b,
1970 (ty::ImmBorrow, ty::ImmBorrow)
1971 | (ty::UniqueImmBorrow, ty::UniqueImmBorrow)
1972 | (ty::MutBorrow, ty::MutBorrow) => {
1973 bug!("Expected unequal capture kinds");
1981 /// Determines the Ancestry relationship of Place A relative to Place B
1983 /// `PlaceAncestryRelation::Ancestor` implies Place A is ancestor of Place B
1984 /// `PlaceAncestryRelation::Descendant` implies Place A is descendant of Place B
1985 /// `PlaceAncestryRelation::Divergent` implies neither of them is the ancestor of the other.
1986 fn determine_place_ancestry_relation(
1987 place_a: &Place<'tcx>,
1988 place_b: &Place<'tcx>,
1989 ) -> PlaceAncestryRelation {
1990 // If Place A and Place B, don't start off from the same root variable, they are divergent.
1991 if place_a.base != place_b.base {
1992 return PlaceAncestryRelation::Divergent;
1995 // Assume of length of projections_a = n
1996 let projections_a = &place_a.projections;
1998 // Assume of length of projections_b = m
1999 let projections_b = &place_b.projections;
2001 let same_initial_projections =
2002 iter::zip(projections_a, projections_b).all(|(proj_a, proj_b)| proj_a == proj_b);
2004 if same_initial_projections {
2005 // First min(n, m) projections are the same
2006 // Select Ancestor/Descendant
2007 if projections_b.len() >= projections_a.len() {
2008 PlaceAncestryRelation::Ancestor
2010 PlaceAncestryRelation::Descendant
2013 PlaceAncestryRelation::Divergent
2017 /// Reduces the precision of the captured place when the precision doesn't yeild any benefit from
2018 /// borrow checking prespective, allowing us to save us on the size of the capture.
2021 /// Fields that are read through a shared reference will always be read via a shared ref or a copy,
2022 /// and therefore capturing precise paths yields no benefit. This optimization truncates the
2023 /// rightmost deref of the capture if the deref is applied to a shared ref.
2025 /// Reason we only drop the last deref is because of the following edge case:
2028 /// struct MyStruct<'a> {
2034 /// fn foo<'a, 'b>(m: &'a MyStruct<'b>) -> impl FnMut() + 'static {
2035 /// let c = || drop(&*m.a.field_of_a);
2036 /// // Here we really do want to capture `*m.a` because that outlives `'static`
2038 /// // If we capture `m`, then the closure no longer outlives `'static'
2039 /// // it is constrained to `'a`
2042 fn truncate_capture_for_optimization<'tcx>(place: &Place<'tcx>) -> Place<'tcx> {
2043 let is_shared_ref = |ty: Ty<'_>| matches!(ty.kind(), ty::Ref(.., hir::Mutability::Not));
2045 // Find the right-most deref (if any). All the projections that come after this
2046 // are fields or other "in-place pointer adjustments"; these refer therefore to
2047 // data owned by whatever pointer is being dereferenced here.
2048 let idx = place.projections.iter().rposition(|proj| ProjectionKind::Deref == proj.kind);
2051 // If that pointer is a shared reference, then we don't need those fields.
2052 Some(idx) if is_shared_ref(place.ty_before_projection(idx)) => {
2053 Place { projections: place.projections[0..=idx].to_vec(), ..place.clone() }
2055 None | Some(_) => place.clone(),
2059 /// Precise capture is enabled if the feature gate `capture_disjoint_fields` is enabled or if
2060 /// user is using Rust Edition 2021 or higher.
2062 /// `span` is the span of the closure.
2063 fn enable_precise_capture(tcx: TyCtxt<'_>, span: Span) -> bool {
2064 // We use span here to ensure that if the closure was generated by a macro with a different
2066 tcx.features().capture_disjoint_fields || span.rust_2021()