]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_hir_typeck/src/upvar.rs
New upstream version 1.71.1+dfsg1
[rustc.git] / compiler / rustc_hir_typeck / src / upvar.rs
CommitLineData
1a4d82fc
JJ
1//! ### Inferring borrow kinds for upvars
2//!
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:
04454e1e
FG
8//! ```ignore (not-rust)
9//! ty::ImmBorrow -> ty::UniqueImmBorrow -> ty::MutBorrow
10//! ```
1a4d82fc
JJ
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
18//! from there).
19//!
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.)
32
33use super::FnCtxt;
34
60c5eb7d 35use crate::expr_use_visitor as euv;
04454e1e 36use rustc_errors::{Applicability, MultiSpan};
dfeec247 37use rustc_hir as hir;
dfeec247 38use rustc_hir::def_id::LocalDefId;
5099ac24 39use rustc_hir::intravisit::{self, Visitor};
74b04a01 40use rustc_infer::infer::UpvarRegion;
6a06907d
XL
41use rustc_middle::hir::place::{Place, PlaceBase, PlaceWithHirId, Projection, ProjectionKind};
42use rustc_middle::mir::FakeReadCause;
136023e0
XL
43use rustc_middle::ty::{
44 self, ClosureSizeProfileData, Ty, TyCtxt, TypeckResults, UpvarCapture, UpvarSubsts,
45};
5869c6ff 46use rustc_session::lint;
fc512014 47use rustc_span::sym;
04454e1e 48use rustc_span::{BytePos, Pos, Span, Symbol};
136023e0 49use rustc_trait_selection::infer::InferCtxtExt;
fc512014 50
064997fb 51use rustc_data_structures::fx::{FxHashMap, FxHashSet};
353b0b11 52use rustc_target::abi::FIRST_VARIANT;
6a06907d 53
cdc7bbd5
XL
54use std::iter;
55
fc512014
XL
56/// Describe the relationship between the paths of two places
57/// eg:
58/// - `foo` is ancestor of `foo.bar.baz`
59/// - `foo.bar.baz` is an descendant of `foo.bar`
60/// - `foo.bar` and `foo.baz` are divergent
61enum PlaceAncestryRelation {
62 Ancestor,
63 Descendant,
dc3f5686 64 SamePlace,
fc512014
XL
65 Divergent,
66}
1a4d82fc 67
5869c6ff
XL
68/// Intermediate format to store a captured `Place` and associated `ty::CaptureInfo`
69/// during capture analysis. Information in this map feeds into the minimum capture
70/// analysis pass.
5099ac24 71type InferredCaptureInformation<'tcx> = Vec<(Place<'tcx>, ty::CaptureInfo)>;
5869c6ff 72
dc9dc135 73impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
dfeec247 74 pub fn closure_analyze(&self, body: &'tcx hir::Body<'tcx>) {
041b39d2 75 InferBorrowKindVisitor { fcx: self }.visit_body(body);
e9174d1e 76
a7813a04
XL
77 // it's our job to process these.
78 assert!(self.deferred_call_resolutions.borrow().is_empty());
79 }
e9174d1e
SL
80}
81
136023e0
XL
82/// Intermediate format to store the hir_id pointing to the use that resulted in the
83/// corresponding place being captured and a String which contains the captured value's
84/// name (i.e: a.b.c)
c295e0f8
XL
85#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
86enum UpvarMigrationInfo {
87 /// We previously captured all of `x`, but now we capture some sub-path.
88 CapturingPrecise { source_expr: Option<hir::HirId>, var_name: String },
89 CapturingNothing {
90 // where the variable appears in the closure (but is not captured)
91 use_span: Span,
92 },
93}
94
95/// Reasons that we might issue a migration warning.
96#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
97struct MigrationWarningReason {
98 /// When we used to capture `x` in its entirety, we implemented the auto-trait(s)
99 /// in this vec, but now we don't.
100 auto_traits: Vec<&'static str>,
136023e0 101
c295e0f8
XL
102 /// When we used to capture `x` in its entirety, we would execute some destructors
103 /// at a different time.
104 drop_order: bool,
105}
106
107impl MigrationWarningReason {
108 fn migration_message(&self) -> String {
109 let base = "changes to closure capture in Rust 2021 will affect";
110 if !self.auto_traits.is_empty() && self.drop_order {
111 format!("{} drop order and which traits the closure implements", base)
112 } else if self.drop_order {
113 format!("{} drop order", base)
114 } else {
115 format!("{} which traits the closure implements", base)
116 }
117 }
118}
119
120/// Intermediate format to store information needed to generate a note in the migration lint.
121struct MigrationLintNote {
122 captures_info: UpvarMigrationInfo,
123
124 /// reasons why migration is needed for this capture
125 reason: MigrationWarningReason,
126}
136023e0
XL
127
128/// Intermediate format to store the hir id of the root variable and a HashSet containing
129/// information on why the root variable should be fully captured
c295e0f8
XL
130struct NeededMigration {
131 var_hir_id: hir::HirId,
132 diagnostics_info: Vec<MigrationLintNote>,
133}
136023e0 134
dc9dc135
XL
135struct InferBorrowKindVisitor<'a, 'tcx> {
136 fcx: &'a FnCtxt<'a, 'tcx>,
1a4d82fc
JJ
137}
138
dc9dc135 139impl<'a, 'tcx> Visitor<'tcx> for InferBorrowKindVisitor<'a, 'tcx> {
dfeec247 140 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
3c0e092e 141 match expr.kind {
064997fb 142 hir::ExprKind::Closure(&hir::Closure { capture_clause, body: body_id, .. }) => {
3c0e092e
XL
143 let body = self.fcx.tcx.hir().body(body_id);
144 self.visit_body(body);
923072b8 145 self.fcx.analyze_closure(expr.hir_id, expr.span, body_id, body, capture_clause);
3c0e092e
XL
146 }
147 hir::ExprKind::ConstBlock(anon_const) => {
148 let body = self.fcx.tcx.hir().body(anon_const.body);
149 self.visit_body(body);
150 }
151 _ => {}
1a4d82fc
JJ
152 }
153
92a42be0 154 intravisit::walk_expr(self, expr);
1a4d82fc 155 }
1a4d82fc
JJ
156}
157
dc9dc135 158impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
60c5eb7d 159 /// Analysis starting point.
c295e0f8 160 #[instrument(skip(self, body), level = "debug")]
ff7c6d11
XL
161 fn analyze_closure(
162 &self,
ff7c6d11
XL
163 closure_hir_id: hir::HirId,
164 span: Span,
cdc7bbd5 165 body_id: hir::BodyId,
5869c6ff 166 body: &'tcx hir::Body<'tcx>,
60c5eb7d 167 capture_clause: hir::CaptureBy,
ff7c6d11 168 ) {
ff7c6d11 169 // Extract the type of the closure.
532ac7d7 170 let ty = self.node_ty(closure_hir_id);
1b1a35ee 171 let (closure_def_id, substs) = match *ty.kind() {
dfeec247 172 ty::Closure(def_id, substs) => (def_id, UpvarSubsts::Closure(substs)),
b7449926 173 ty::Generator(def_id, substs, _) => (def_id, UpvarSubsts::Generator(substs)),
f035d41b 174 ty::Error(_) => {
8faf50e0
XL
175 // #51714: skip analysis when we have already encountered type errors
176 return;
177 }
532ac7d7 178 _ => {
ff7c6d11
XL
179 span_bug!(
180 span,
181 "type of closure expr {:?} is not a closure {:?}",
532ac7d7
XL
182 closure_hir_id,
183 ty
ff7c6d11 184 );
041b39d2
XL
185 }
186 };
064997fb 187 let closure_def_id = closure_def_id.expect_local();
041b39d2 188
a1dfa0c6 189 let infer_kind = if let UpvarSubsts::Closure(closure_substs) = substs {
ba9703b0 190 self.closure_kind(closure_substs).is_none().then_some(closure_substs)
ff7c6d11 191 } else {
94b46f34 192 None
ff7c6d11 193 };
3b2f2976 194
064997fb 195 assert_eq!(self.tcx.hir().body_owner_def_id(body.id()), closure_def_id);
ff7c6d11
XL
196 let mut delegate = InferBorrowKind {
197 fcx: self,
064997fb 198 closure_def_id,
5869c6ff 199 capture_information: Default::default(),
6a06907d 200 fake_reads: Default::default(),
ff7c6d11 201 };
60c5eb7d 202 euv::ExprUseVisitor::new(
ff7c6d11
XL
203 &mut delegate,
204 &self.infcx,
064997fb 205 closure_def_id,
ff7c6d11 206 self.param_env,
3dfed10e 207 &self.typeck_results.borrow(),
0731742a
XL
208 )
209 .consume_body(body);
ff7c6d11 210
fc512014
XL
211 debug!(
212 "For closure={:?}, capture_information={:#?}",
213 closure_def_id, delegate.capture_information
214 );
136023e0 215
fc512014
XL
216 self.log_capture_analysis_first_pass(closure_def_id, &delegate.capture_information, span);
217
136023e0
XL
218 let (capture_information, closure_kind, origin) = self
219 .process_collected_capture_information(capture_clause, delegate.capture_information);
220
5099ac24 221 self.compute_min_captures(closure_def_id, capture_information, span);
5869c6ff 222
064997fb 223 let closure_hir_id = self.tcx.hir().local_def_id_to_hir_id(closure_def_id);
17df50a5 224
136023e0 225 if should_do_rust_2021_incompatible_closure_captures_analysis(self.tcx, closure_hir_id) {
49aad941 226 self.perform_2229_migration_analysis(closure_def_id, body_id, capture_clause, span);
5869c6ff
XL
227 }
228
136023e0
XL
229 let after_feature_tys = self.final_upvar_tys(closure_def_id);
230
5869c6ff
XL
231 // We now fake capture information for all variables that are mentioned within the closure
232 // We do this after handling migrations so that min_captures computes before
9ffffee4 233 if !enable_precise_capture(span) {
5869c6ff
XL
234 let mut capture_information: InferredCaptureInformation<'tcx> = Default::default();
235
236 if let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) {
237 for var_hir_id in upvars.keys() {
064997fb 238 let place = self.place_for_root_variable(closure_def_id, *var_hir_id);
5869c6ff
XL
239
240 debug!("seed place {:?}", place);
241
5099ac24 242 let capture_kind = self.init_capture_kind_for_place(&place, capture_clause);
5869c6ff
XL
243 let fake_info = ty::CaptureInfo {
244 capture_kind_expr_id: None,
245 path_expr_id: None,
246 capture_kind,
247 };
248
5099ac24 249 capture_information.push((place, fake_info));
5869c6ff
XL
250 }
251 }
252
253 // This will update the min captures based on this new fake information.
5099ac24 254 self.compute_min_captures(closure_def_id, capture_information, span);
5869c6ff
XL
255 }
256
136023e0
XL
257 let before_feature_tys = self.final_upvar_tys(closure_def_id);
258
94b46f34 259 if let Some(closure_substs) = infer_kind {
ff7c6d11
XL
260 // Unify the (as yet unbound) type variable in the closure
261 // substs with the kind we inferred.
ba9703b0 262 let closure_kind_ty = closure_substs.as_closure().kind_ty();
136023e0 263 self.demand_eqtype(span, closure_kind.to_ty(self.tcx), closure_kind_ty);
ff7c6d11
XL
264
265 // If we have an origin, store it.
136023e0 266 if let Some(origin) = origin {
9ffffee4 267 let origin = if enable_precise_capture(span) {
136023e0 268 (origin.0, origin.1)
5869c6ff 269 } else {
5869c6ff
XL
270 (origin.0, Place { projections: vec![], ..origin.1 })
271 };
272
3dfed10e
XL
273 self.typeck_results
274 .borrow_mut()
275 .closure_kind_origins_mut()
276 .insert(closure_hir_id, origin);
041b39d2 277 }
c1a9b12d 278 }
85aaf69f 279
fc512014
XL
280 self.log_closure_min_capture_info(closure_def_id, span);
281
c1a9b12d
SL
282 // Now that we've analyzed the closure, we know how each
283 // variable is borrowed, and we know what traits the closure
284 // implements (Fn vs FnMut etc). We now have some updates to do
285 // with that information.
85aaf69f 286 //
c1a9b12d
SL
287 // Note that no closure type C may have an upvar of type C
288 // (though it may reference itself via a trait object). This
289 // results from the desugaring of closures to a struct like
290 // `Foo<..., UV0...UVn>`. If one of those upvars referenced
291 // C, then the type would have infinite size (and the
292 // inference algorithm will reject it).
293
ff7c6d11 294 // Equate the type variables for the upvars with the actual types.
fc512014 295 let final_upvar_tys = self.final_upvar_tys(closure_def_id);
ff7c6d11 296 debug!(
94b46f34 297 "analyze_closure: id={:?} substs={:?} final_upvar_tys={:?}",
532ac7d7 298 closure_hir_id, substs, final_upvar_tys
ff7c6d11 299 );
29967ef6
XL
300
301 // Build a tuple (U0..Un) of the final upvar types U0..Un
5e7ed085 302 // and unify the upvar tuple type in the closure with it:
9ffffee4 303 let final_tupled_upvars_type = self.tcx.mk_tup(&final_upvar_tys);
29967ef6 304 self.demand_suptype(span, substs.tupled_upvars_ty(), final_tupled_upvars_type);
c1a9b12d 305
6a06907d
XL
306 let fake_reads = delegate
307 .fake_reads
308 .into_iter()
309 .map(|(place, cause, hir_id)| (place, cause, hir_id))
310 .collect();
311 self.typeck_results.borrow_mut().closure_fake_reads.insert(closure_def_id, fake_reads);
312
064997fb 313 if self.tcx.sess.opts.unstable_opts.profile_closures {
136023e0
XL
314 self.typeck_results.borrow_mut().closure_size_eval.insert(
315 closure_def_id,
316 ClosureSizeProfileData {
9ffffee4
FG
317 before_feature_tys: self.tcx.mk_tup(&before_feature_tys),
318 after_feature_tys: self.tcx.mk_tup(&after_feature_tys),
136023e0
XL
319 },
320 );
321 }
322
041b39d2
XL
323 // If we are also inferred the closure kind here,
324 // process any deferred resolutions.
ff7c6d11
XL
325 let deferred_call_resolutions = self.remove_deferred_call_resolutions(closure_def_id);
326 for deferred_call_resolution in deferred_call_resolutions {
327 deferred_call_resolution.resolve(self);
85aaf69f
SL
328 }
329 }
330
dfeec247 331 // Returns a list of `Ty`s for each upvar.
064997fb 332 fn final_upvar_tys(&self, closure_id: LocalDefId) -> Vec<Ty<'tcx>> {
fc512014
XL
333 self.typeck_results
334 .borrow()
335 .closure_min_captures_flattened(closure_id)
336 .map(|captured_place| {
337 let upvar_ty = captured_place.place.ty();
338 let capture = captured_place.info.capture_kind;
ff7c6d11 339
fc512014 340 debug!(
5869c6ff
XL
341 "final_upvar_tys: place={:?} upvar_ty={:?} capture={:?}, mutability={:?}",
342 captured_place.place, upvar_ty, capture, captured_place.mutability,
fc512014
XL
343 );
344
5099ac24 345 apply_capture_kind_on_capture_ty(self.tcx, upvar_ty, capture, captured_place.region)
dfeec247 346 })
48663c56 347 .collect()
c1a9b12d 348 }
fc512014 349
136023e0
XL
350 /// Adjusts the closure capture information to ensure that the operations aren't unsafe,
351 /// and that the path can be captured with required capture kind (depending on use in closure,
352 /// move closure etc.)
353 ///
2b03887a 354 /// Returns the set of adjusted information along with the inferred closure kind and span
136023e0
XL
355 /// associated with the closure kind inference.
356 ///
357 /// Note that we *always* infer a minimal kind, even if
358 /// we don't always *use* that in the final result (i.e., sometimes
359 /// we've taken the closure kind from the expectations instead, and
360 /// for generators we don't even implement the closure traits
361 /// really).
362 ///
363 /// If we inferred that the closure needs to be FnMut/FnOnce, last element of the returned tuple
364 /// contains a `Some()` with the `Place` that caused us to do so.
365 fn process_collected_capture_information(
366 &self,
367 capture_clause: hir::CaptureBy,
368 capture_information: InferredCaptureInformation<'tcx>,
369 ) -> (InferredCaptureInformation<'tcx>, ty::ClosureKind, Option<(Span, Place<'tcx>)>) {
136023e0
XL
370 let mut closure_kind = ty::ClosureKind::LATTICE_BOTTOM;
371 let mut origin: Option<(Span, Place<'tcx>)> = None;
372
5099ac24
FG
373 let processed = capture_information
374 .into_iter()
375 .map(|(place, mut capture_info)| {
376 // Apply rules for safety before inferring closure kind
377 let (place, capture_kind) =
378 restrict_capture_precision(place, capture_info.capture_kind);
136023e0 379
5099ac24 380 let (place, capture_kind) = truncate_capture_for_optimization(place, capture_kind);
136023e0 381
5099ac24
FG
382 let usage_span = if let Some(usage_expr) = capture_info.path_expr_id {
383 self.tcx.hir().span(usage_expr)
384 } else {
385 unreachable!()
386 };
136023e0 387
5099ac24
FG
388 let updated = match capture_kind {
389 ty::UpvarCapture::ByValue => match closure_kind {
390 ty::ClosureKind::Fn | ty::ClosureKind::FnMut => {
391 (ty::ClosureKind::FnOnce, Some((usage_span, place.clone())))
392 }
393 // If closure is already FnOnce, don't update
394 ty::ClosureKind::FnOnce => (closure_kind, origin.take()),
395 },
136023e0 396
5099ac24
FG
397 ty::UpvarCapture::ByRef(
398 ty::BorrowKind::MutBorrow | ty::BorrowKind::UniqueImmBorrow,
399 ) => {
400 match closure_kind {
401 ty::ClosureKind::Fn => {
402 (ty::ClosureKind::FnMut, Some((usage_span, place.clone())))
403 }
404 // Don't update the origin
405 ty::ClosureKind::FnMut | ty::ClosureKind::FnOnce => {
406 (closure_kind, origin.take())
407 }
136023e0 408 }
136023e0 409 }
136023e0 410
5099ac24
FG
411 _ => (closure_kind, origin.take()),
412 };
136023e0 413
5099ac24
FG
414 closure_kind = updated.0;
415 origin = updated.1;
136023e0 416
5099ac24
FG
417 let (place, capture_kind) = match capture_clause {
418 hir::CaptureBy::Value => adjust_for_move_closure(place, capture_kind),
419 hir::CaptureBy::Ref => adjust_for_non_move_closure(place, capture_kind),
420 };
94222f64 421
5099ac24
FG
422 // This restriction needs to be applied after we have handled adjustments for `move`
423 // closures. We want to make sure any adjustment that might make us move the place into
424 // the closure gets handled.
425 let (place, capture_kind) =
353b0b11 426 restrict_precision_for_drop_types(self, place, capture_kind);
94222f64 427
5099ac24
FG
428 capture_info.capture_kind = capture_kind;
429 (place, capture_info)
430 })
431 .collect();
136023e0
XL
432
433 (processed, closure_kind, origin)
434 }
435
fc512014
XL
436 /// Analyzes the information collected by `InferBorrowKind` to compute the min number of
437 /// Places (and corresponding capture kind) that we need to keep track of to support all
438 /// the required captured paths.
439 ///
5869c6ff
XL
440 ///
441 /// Note: If this function is called multiple times for the same closure, it will update
442 /// the existing min_capture map that is stored in TypeckResults.
443 ///
fc512014 444 /// Eg:
04454e1e
FG
445 /// ```
446 /// #[derive(Debug)]
fc512014
XL
447 /// struct Point { x: i32, y: i32 }
448 ///
04454e1e
FG
449 /// let s = String::from("s"); // hir_id_s
450 /// let mut p = Point { x: 2, y: -2 }; // his_id_p
fc512014 451 /// let c = || {
04454e1e 452 /// println!("{s:?}"); // L1
fc512014 453 /// p.x += 10; // L2
5e7ed085 454 /// println!("{}" , p.y); // L3
04454e1e 455 /// println!("{p:?}"); // L4
fc512014
XL
456 /// drop(s); // L5
457 /// };
458 /// ```
459 /// and let hir_id_L1..5 be the expressions pointing to use of a captured variable on
460 /// the lines L1..5 respectively.
461 ///
462 /// InferBorrowKind results in a structure like this:
463 ///
04454e1e 464 /// ```ignore (illustrative)
fc512014 465 /// {
5869c6ff
XL
466 /// Place(base: hir_id_s, projections: [], ....) -> {
467 /// capture_kind_expr: hir_id_L5,
468 /// path_expr_id: hir_id_L5,
469 /// capture_kind: ByValue
470 /// },
471 /// Place(base: hir_id_p, projections: [Field(0, 0)], ...) -> {
472 /// capture_kind_expr: hir_id_L2,
473 /// path_expr_id: hir_id_L2,
474 /// capture_kind: ByValue
475 /// },
476 /// Place(base: hir_id_p, projections: [Field(1, 0)], ...) -> {
477 /// capture_kind_expr: hir_id_L3,
478 /// path_expr_id: hir_id_L3,
479 /// capture_kind: ByValue
480 /// },
481 /// Place(base: hir_id_p, projections: [], ...) -> {
482 /// capture_kind_expr: hir_id_L4,
483 /// path_expr_id: hir_id_L4,
484 /// capture_kind: ByValue
485 /// },
04454e1e 486 /// }
fc512014
XL
487 /// ```
488 ///
489 /// After the min capture analysis, we get:
04454e1e 490 /// ```ignore (illustrative)
fc512014
XL
491 /// {
492 /// hir_id_s -> [
5869c6ff
XL
493 /// Place(base: hir_id_s, projections: [], ....) -> {
494 /// capture_kind_expr: hir_id_L5,
495 /// path_expr_id: hir_id_L5,
496 /// capture_kind: ByValue
497 /// },
fc512014
XL
498 /// ],
499 /// hir_id_p -> [
5869c6ff
XL
500 /// Place(base: hir_id_p, projections: [], ...) -> {
501 /// capture_kind_expr: hir_id_L2,
502 /// path_expr_id: hir_id_L4,
503 /// capture_kind: ByValue
504 /// },
fc512014 505 /// ],
04454e1e 506 /// }
fc512014
XL
507 /// ```
508 fn compute_min_captures(
509 &self,
064997fb 510 closure_def_id: LocalDefId,
5869c6ff 511 capture_information: InferredCaptureInformation<'tcx>,
5099ac24 512 closure_span: Span,
fc512014 513 ) {
5869c6ff
XL
514 if capture_information.is_empty() {
515 return;
516 }
517
518 let mut typeck_results = self.typeck_results.borrow_mut();
fc512014 519
5869c6ff
XL
520 let mut root_var_min_capture_list =
521 typeck_results.closure_min_captures.remove(&closure_def_id).unwrap_or_default();
522
94222f64 523 for (mut place, capture_info) in capture_information.into_iter() {
fc512014
XL
524 let var_hir_id = match place.base {
525 PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
526 base => bug!("Expected upvar, found={:?}", base),
527 };
9ffffee4 528 let var_ident = self.tcx.hir().ident(var_hir_id);
fc512014 529
5e7ed085
FG
530 let Some(min_cap_list) = root_var_min_capture_list.get_mut(&var_hir_id) else {
531 let mutability = self.determine_capture_mutability(&typeck_results, &place);
532 let min_cap_list = vec![ty::CapturedPlace {
9ffffee4 533 var_ident,
5e7ed085
FG
534 place,
535 info: capture_info,
536 mutability,
537 region: None,
538 }];
539 root_var_min_capture_list.insert(var_hir_id, min_cap_list);
540 continue;
fc512014
XL
541 };
542
543 // Go through each entry in the current list of min_captures
544 // - if ancestor is found, update it's capture kind to account for current place's
545 // capture information.
546 //
547 // - if descendant is found, remove it from the list, and update the current place's
5e7ed085 548 // capture information to account for the descendant's capture kind.
fc512014
XL
549 //
550 // We can never be in a case where the list contains both an ancestor and a descendant
551 // Also there can only be ancestor but in case of descendants there might be
552 // multiple.
553
554 let mut descendant_found = false;
555 let mut updated_capture_info = capture_info;
556 min_cap_list.retain(|possible_descendant| {
557 match determine_place_ancestry_relation(&place, &possible_descendant.place) {
558 // current place is ancestor of possible_descendant
559 PlaceAncestryRelation::Ancestor => {
560 descendant_found = true;
94222f64
XL
561
562 let mut possible_descendant = possible_descendant.clone();
5869c6ff
XL
563 let backup_path_expr_id = updated_capture_info.path_expr_id;
564
94222f64
XL
565 // Truncate the descendant (already in min_captures) to be same as the ancestor to handle any
566 // possible change in capture mode.
567 truncate_place_to_len_and_update_capture_kind(
568 &mut possible_descendant.place,
569 &mut possible_descendant.info.capture_kind,
570 place.projections.len(),
571 );
572
fc512014
XL
573 updated_capture_info =
574 determine_capture_info(updated_capture_info, possible_descendant.info);
5869c6ff
XL
575
576 // we need to keep the ancestor's `path_expr_id`
577 updated_capture_info.path_expr_id = backup_path_expr_id;
fc512014
XL
578 false
579 }
580
581 _ => true,
582 }
583 });
584
585 let mut ancestor_found = false;
586 if !descendant_found {
587 for possible_ancestor in min_cap_list.iter_mut() {
588 match determine_place_ancestry_relation(&place, &possible_ancestor.place) {
5099ac24
FG
589 PlaceAncestryRelation::SamePlace => {
590 ancestor_found = true;
591 possible_ancestor.info = determine_capture_info(
592 possible_ancestor.info,
593 updated_capture_info,
594 );
595
596 // Only one related place will be in the list.
597 break;
598 }
fc512014 599 // current place is descendant of possible_ancestor
5099ac24 600 PlaceAncestryRelation::Descendant => {
fc512014 601 ancestor_found = true;
5869c6ff 602 let backup_path_expr_id = possible_ancestor.info.path_expr_id;
94222f64
XL
603
604 // Truncate the descendant (current place) to be same as the ancestor to handle any
605 // possible change in capture mode.
606 truncate_place_to_len_and_update_capture_kind(
607 &mut place,
608 &mut updated_capture_info.capture_kind,
609 possible_ancestor.place.projections.len(),
610 );
611
612 possible_ancestor.info = determine_capture_info(
613 possible_ancestor.info,
614 updated_capture_info,
615 );
fc512014 616
5869c6ff
XL
617 // we need to keep the ancestor's `path_expr_id`
618 possible_ancestor.info.path_expr_id = backup_path_expr_id;
619
5099ac24 620 // Only one related place will be in the list.
fc512014
XL
621 break;
622 }
623 _ => {}
624 }
625 }
626 }
627
628 // Only need to insert when we don't have an ancestor in the existing min capture list
629 if !ancestor_found {
5869c6ff 630 let mutability = self.determine_capture_mutability(&typeck_results, &place);
5099ac24 631 let captured_place = ty::CapturedPlace {
9ffffee4 632 var_ident,
5099ac24
FG
633 place,
634 info: updated_capture_info,
635 mutability,
636 region: None,
637 };
fc512014
XL
638 min_cap_list.push(captured_place);
639 }
640 }
641
5099ac24
FG
642 // For each capture that is determined to be captured by ref, add region info.
643 for (_, captures) in &mut root_var_min_capture_list {
644 for capture in captures {
645 match capture.info.capture_kind {
646 ty::UpvarCapture::ByRef(_) => {
647 let PlaceBase::Upvar(upvar_id) = capture.place.base else { bug!("expected upvar") };
648 let origin = UpvarRegion(upvar_id, closure_span);
649 let upvar_region = self.next_region_var(origin);
650 capture.region = Some(upvar_region);
651 }
652 _ => (),
653 }
654 }
655 }
656
94222f64
XL
657 debug!(
658 "For closure={:?}, min_captures before sorting={:?}",
659 closure_def_id, root_var_min_capture_list
660 );
661
662 // Now that we have the minimized list of captures, sort the captures by field id.
663 // This causes the closure to capture the upvars in the same order as the fields are
664 // declared which is also the drop order. Thus, in situations where we capture all the
5e7ed085 665 // fields of some type, the observable drop order will remain the same as it previously
94222f64
XL
666 // was even though we're dropping each capture individually.
667 // See https://github.com/rust-lang/project-rfc-2229/issues/42 and
9c376795 668 // `tests/ui/closures/2229_closure_analysis/preserve_field_drop_order.rs`.
94222f64
XL
669 for (_, captures) in &mut root_var_min_capture_list {
670 captures.sort_by(|capture1, capture2| {
671 for (p1, p2) in capture1.place.projections.iter().zip(&capture2.place.projections) {
672 // We do not need to look at the `Projection.ty` fields here because at each
673 // step of the iteration, the projections will either be the same and therefore
674 // the types must be as well or the current projection will be different and
675 // we will return the result of comparing the field indexes.
676 match (p1.kind, p2.kind) {
677 // Paths are the same, continue to next loop.
678 (ProjectionKind::Deref, ProjectionKind::Deref) => {}
679 (ProjectionKind::Field(i1, _), ProjectionKind::Field(i2, _))
680 if i1 == i2 => {}
681
682 // Fields are different, compare them.
683 (ProjectionKind::Field(i1, _), ProjectionKind::Field(i2, _)) => {
684 return i1.cmp(&i2);
685 }
686
687 // We should have either a pair of `Deref`s or a pair of `Field`s.
688 // Anything else is a bug.
689 (
690 l @ (ProjectionKind::Deref | ProjectionKind::Field(..)),
691 r @ (ProjectionKind::Deref | ProjectionKind::Field(..)),
692 ) => bug!(
693 "ProjectionKinds Deref and Field were mismatched: ({:?}, {:?})",
694 l,
695 r
696 ),
697 (
a2a8927a 698 l @ (ProjectionKind::Index
94222f64
XL
699 | ProjectionKind::Subslice
700 | ProjectionKind::Deref
701 | ProjectionKind::Field(..)),
a2a8927a 702 r @ (ProjectionKind::Index
94222f64
XL
703 | ProjectionKind::Subslice
704 | ProjectionKind::Deref
705 | ProjectionKind::Field(..)),
706 ) => bug!(
707 "ProjectionKinds Index or Subslice were unexpected: ({:?}, {:?})",
708 l,
709 r
710 ),
711 }
712 }
713
353b0b11
FG
714 self.tcx.sess.delay_span_bug(
715 closure_span,
49aad941 716 format!(
353b0b11
FG
717 "two identical projections: ({:?}, {:?})",
718 capture1.place.projections, capture2.place.projections
719 ),
94222f64 720 );
353b0b11 721 std::cmp::Ordering::Equal
94222f64
XL
722 });
723 }
724
725 debug!(
726 "For closure={:?}, min_captures after sorting={:#?}",
727 closure_def_id, root_var_min_capture_list
728 );
5869c6ff
XL
729 typeck_results.closure_min_captures.insert(closure_def_id, root_var_min_capture_list);
730 }
fc512014 731
5869c6ff
XL
732 /// Perform the migration analysis for RFC 2229, and emit lint
733 /// `disjoint_capture_drop_reorder` if needed.
49aad941 734 fn perform_2229_migration_analysis(
5869c6ff 735 &self,
064997fb 736 closure_def_id: LocalDefId,
cdc7bbd5 737 body_id: hir::BodyId,
5869c6ff
XL
738 capture_clause: hir::CaptureBy,
739 span: Span,
5869c6ff 740 ) {
17df50a5 741 let (need_migrations, reasons) = self.compute_2229_migrations(
5869c6ff
XL
742 closure_def_id,
743 span,
744 capture_clause,
5869c6ff
XL
745 self.typeck_results.borrow().closure_min_captures.get(&closure_def_id),
746 );
747
748 if !need_migrations.is_empty() {
cdc7bbd5
XL
749 let (migration_string, migrated_variables_concat) =
750 migration_suggestion_for_2229(self.tcx, &need_migrations);
5869c6ff 751
064997fb
FG
752 let closure_hir_id = self.tcx.hir().local_def_id_to_hir_id(closure_def_id);
753 let closure_head_span = self.tcx.def_span(closure_def_id);
5869c6ff 754 self.tcx.struct_span_lint_hir(
136023e0 755 lint::builtin::RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES,
5869c6ff 756 closure_hir_id,
064997fb 757 closure_head_span,
2b03887a 758 reasons.migration_message(),
5869c6ff 759 |lint| {
c295e0f8 760 for NeededMigration { var_hir_id, diagnostics_info } in &need_migrations {
136023e0
XL
761 // Labels all the usage of the captured variable and why they are responsible
762 // for migration being needed
c295e0f8
XL
763 for lint_note in diagnostics_info.iter() {
764 match &lint_note.captures_info {
765 UpvarMigrationInfo::CapturingPrecise { source_expr: Some(capture_expr_id), var_name: captured_name } => {
766 let cause_span = self.tcx.hir().span(*capture_expr_id);
2b03887a 767 lint.span_label(cause_span, format!("in Rust 2018, this closure captures all of `{}`, but in Rust 2021, it will only capture `{}`",
c295e0f8
XL
768 self.tcx.hir().name(*var_hir_id),
769 captured_name,
770 ));
771 }
772 UpvarMigrationInfo::CapturingNothing { use_span } => {
2b03887a 773 lint.span_label(*use_span, format!("in Rust 2018, this causes the closure to capture `{}`, but in Rust 2021, it has no effect",
c295e0f8
XL
774 self.tcx.hir().name(*var_hir_id),
775 ));
776 }
777
778 _ => { }
136023e0
XL
779 }
780
781 // Add a label pointing to where a captured variable affected by drop order
782 // is dropped
c295e0f8 783 if lint_note.reason.drop_order {
5e7ed085 784 let drop_location_span = drop_location_span(self.tcx, closure_hir_id);
136023e0 785
c295e0f8
XL
786 match &lint_note.captures_info {
787 UpvarMigrationInfo::CapturingPrecise { var_name: captured_name, .. } => {
2b03887a 788 lint.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",
c295e0f8
XL
789 self.tcx.hir().name(*var_hir_id),
790 captured_name,
791 ));
792 }
793 UpvarMigrationInfo::CapturingNothing { use_span: _ } => {
2b03887a 794 lint.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",
c295e0f8
XL
795 v = self.tcx.hir().name(*var_hir_id),
796 ));
797 }
798 }
136023e0
XL
799 }
800
801 // Add a label explaining why a closure no longer implements a trait
c295e0f8
XL
802 for &missing_trait in &lint_note.reason.auto_traits {
803 // not capturing something anymore cannot cause a trait to fail to be implemented:
804 match &lint_note.captures_info {
805 UpvarMigrationInfo::CapturingPrecise { var_name: captured_name, .. } => {
806 let var_name = self.tcx.hir().name(*var_hir_id);
2b03887a 807 lint.span_label(closure_head_span, format!("\
c295e0f8
XL
808 in Rust 2018, this closure implements {missing_trait} \
809 as `{var_name}` implements {missing_trait}, but in Rust 2021, \
810 this closure will no longer implement {missing_trait} \
811 because `{var_name}` is not fully captured \
812 and `{captured_name}` does not implement {missing_trait}"));
813 }
814
815 // Cannot happen: if we don't capture a variable, we impl strictly more traits
816 UpvarMigrationInfo::CapturingNothing { use_span } => span_bug!(*use_span, "missing trait from not capturing something"),
817 }
136023e0
XL
818 }
819 }
820 }
2b03887a 821 lint.note("for more information, see <https://doc.rust-lang.org/nightly/edition-guide/rust-2021/disjoint-capture-in-closures.html>");
cdc7bbd5
XL
822
823 let diagnostic_msg = format!(
824 "add a dummy let to cause {} to be fully captured",
825 migrated_variables_concat
826 );
827
064997fb 828 let closure_span = self.tcx.hir().span_with_body(closure_hir_id);
94222f64
XL
829 let mut closure_body_span = {
830 // If the body was entirely expanded from a macro
831 // invocation, i.e. the body is not contained inside the
832 // closure span, then we walk up the expansion until we
833 // find the span before the expansion.
064997fb 834 let s = self.tcx.hir().span_with_body(body_id.hir_id);
94222f64
XL
835 s.find_ancestor_inside(closure_span).unwrap_or(s)
836 };
837
838 if let Ok(mut s) = self.tcx.sess.source_map().span_to_snippet(closure_body_span) {
839 if s.starts_with('$') {
840 // Looks like a macro fragment. Try to find the real block.
841 if let Some(hir::Node::Expr(&hir::Expr {
842 kind: hir::ExprKind::Block(block, ..), ..
843 })) = self.tcx.hir().find(body_id.hir_id) {
844 // If the body is a block (with `{..}`), we use the span of that block.
845 // E.g. with a `|| $body` expanded from a `m!({ .. })`, we use `{ .. }`, and not `$body`.
846 // Since we know it's a block, we know we can insert the `let _ = ..` without
847 // breaking the macro syntax.
848 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(block.span) {
849 closure_body_span = block.span;
850 s = snippet;
851 }
852 }
853 }
854
855 let mut lines = s.lines();
856 let line1 = lines.next().unwrap_or_default();
857
858 if line1.trim_end() == "{" {
859 // This is a multi-line closure with just a `{` on the first line,
860 // so we put the `let` on its own line.
861 // We take the indentation from the next non-empty line.
c295e0f8 862 let line2 = lines.find(|line| !line.is_empty()).unwrap_or_default();
94222f64 863 let indent = line2.split_once(|c: char| !c.is_whitespace()).unwrap_or_default().0;
2b03887a 864 lint.span_suggestion(
94222f64 865 closure_body_span.with_lo(closure_body_span.lo() + BytePos::from_usize(line1.len())).shrink_to_lo(),
49aad941 866 diagnostic_msg,
04454e1e 867 format!("\n{indent}{migration_string};"),
94222f64
XL
868 Applicability::MachineApplicable,
869 );
870 } else if line1.starts_with('{') {
871 // This is a closure with its body wrapped in
872 // braces, but with more than just the opening
873 // brace on the first line. We put the `let`
874 // directly after the `{`.
2b03887a 875 lint.span_suggestion(
94222f64 876 closure_body_span.with_lo(closure_body_span.lo() + BytePos(1)).shrink_to_lo(),
49aad941 877 diagnostic_msg,
04454e1e 878 format!(" {migration_string};"),
94222f64
XL
879 Applicability::MachineApplicable,
880 );
881 } else {
882 // This is a closure without braces around the body.
883 // We add braces to add the `let` before the body.
2b03887a 884 lint.multipart_suggestion(
49aad941 885 diagnostic_msg,
94222f64 886 vec![
04454e1e 887 (closure_body_span.shrink_to_lo(), format!("{{ {migration_string}; ")),
94222f64
XL
888 (closure_body_span.shrink_to_hi(), " }".to_string()),
889 ],
890 Applicability::MachineApplicable
891 );
892 }
893 } else {
2b03887a 894 lint.span_suggestion(
94222f64 895 closure_span,
49aad941 896 diagnostic_msg,
94222f64
XL
897 migration_string,
898 Applicability::HasPlaceholders
899 );
900 }
901
2b03887a 902 lint
5869c6ff
XL
903 },
904 );
905 }
906 }
907
17df50a5
XL
908 /// Combines all the reasons for 2229 migrations
909 fn compute_2229_migrations_reasons(
910 &self,
c295e0f8
XL
911 auto_trait_reasons: FxHashSet<&'static str>,
912 drop_order: bool,
913 ) -> MigrationWarningReason {
914 let mut reasons = MigrationWarningReason::default();
17df50a5 915
a2a8927a 916 reasons.auto_traits.extend(auto_trait_reasons);
c295e0f8 917 reasons.drop_order = drop_order;
17df50a5 918
04454e1e
FG
919 // `auto_trait_reasons` are in hashset order, so sort them to put the
920 // diagnostics we emit later in a cross-platform-consistent order.
921 reasons.auto_traits.sort_unstable();
922
17df50a5
XL
923 reasons
924 }
925
136023e0
XL
926 /// Figures out the list of root variables (and their types) that aren't completely
927 /// captured by the closure when `capture_disjoint_fields` is enabled and auto-traits
928 /// differ between the root variable and the captured paths.
929 ///
930 /// Returns a tuple containing a HashMap of CapturesInfo that maps to a HashSet of trait names
931 /// if migration is needed for traits for the provided var_hir_id, otherwise returns None
932 fn compute_2229_migrations_for_trait(
17df50a5
XL
933 &self,
934 min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
935 var_hir_id: hir::HirId,
136023e0 936 closure_clause: hir::CaptureBy,
c295e0f8 937 ) -> Option<FxHashMap<UpvarMigrationInfo, FxHashSet<&'static str>>> {
136023e0
XL
938 let auto_traits_def_id = vec![
939 self.tcx.lang_items().clone_trait(),
940 self.tcx.lang_items().sync_trait(),
c295e0f8 941 self.tcx.get_diagnostic_item(sym::Send),
136023e0
XL
942 self.tcx.lang_items().unpin_trait(),
943 self.tcx.get_diagnostic_item(sym::unwind_safe_trait),
944 self.tcx.get_diagnostic_item(sym::ref_unwind_safe_trait),
945 ];
3c0e092e
XL
946 const AUTO_TRAITS: [&str; 6] =
947 ["`Clone`", "`Sync`", "`Send`", "`Unpin`", "`UnwindSafe`", "`RefUnwindSafe`"];
136023e0 948
c295e0f8 949 let root_var_min_capture_list = min_captures.and_then(|m| m.get(&var_hir_id))?;
17df50a5 950
064997fb 951 let ty = self.resolve_vars_if_possible(self.node_ty(var_hir_id));
17df50a5 952
136023e0
XL
953 let ty = match closure_clause {
954 hir::CaptureBy::Value => ty, // For move closure the capture kind should be by value
955 hir::CaptureBy::Ref => {
956 // For non move closure the capture kind is the max capture kind of all captures
957 // according to the ordering ImmBorrow < UniqueImmBorrow < MutBorrow < ByValue
958 let mut max_capture_info = root_var_min_capture_list.first().unwrap().info;
959 for capture in root_var_min_capture_list.iter() {
960 max_capture_info = determine_capture_info(max_capture_info, capture.info);
961 }
17df50a5 962
5099ac24
FG
963 apply_capture_kind_on_capture_ty(
964 self.tcx,
965 ty,
966 max_capture_info.capture_kind,
967 Some(self.tcx.lifetimes.re_erased),
968 )
17df50a5 969 }
136023e0 970 };
17df50a5 971
136023e0
XL
972 let mut obligations_should_hold = Vec::new();
973 // Checks if a root variable implements any of the auto traits
974 for check_trait in auto_traits_def_id.iter() {
49aad941
FG
975 obligations_should_hold.push(check_trait.is_some_and(|check_trait| {
976 self.infcx
977 .type_implements_trait(check_trait, [ty], self.param_env)
978 .must_apply_modulo_regions()
979 }));
17df50a5
XL
980 }
981
136023e0
XL
982 let mut problematic_captures = FxHashMap::default();
983 // Check whether captured fields also implement the trait
984 for capture in root_var_min_capture_list.iter() {
985 let ty = apply_capture_kind_on_capture_ty(
986 self.tcx,
987 capture.place.ty(),
988 capture.info.capture_kind,
5099ac24 989 Some(self.tcx.lifetimes.re_erased),
136023e0 990 );
17df50a5 991
136023e0
XL
992 // Checks if a capture implements any of the auto traits
993 let mut obligations_holds_for_capture = Vec::new();
994 for check_trait in auto_traits_def_id.iter() {
49aad941
FG
995 obligations_holds_for_capture.push(check_trait.is_some_and(|check_trait| {
996 self.infcx
997 .type_implements_trait(check_trait, [ty], self.param_env)
998 .must_apply_modulo_regions()
999 }));
136023e0 1000 }
17df50a5 1001
136023e0 1002 let mut capture_problems = FxHashSet::default();
17df50a5 1003
136023e0
XL
1004 // Checks if for any of the auto traits, one or more trait is implemented
1005 // by the root variable but not by the capture
1006 for (idx, _) in obligations_should_hold.iter().enumerate() {
1007 if !obligations_holds_for_capture[idx] && obligations_should_hold[idx] {
3c0e092e 1008 capture_problems.insert(AUTO_TRAITS[idx]);
136023e0
XL
1009 }
1010 }
17df50a5 1011
c295e0f8 1012 if !capture_problems.is_empty() {
136023e0 1013 problematic_captures.insert(
c295e0f8
XL
1014 UpvarMigrationInfo::CapturingPrecise {
1015 source_expr: capture.info.path_expr_id,
1016 var_name: capture.to_string(self.tcx),
1017 },
136023e0
XL
1018 capture_problems,
1019 );
1020 }
17df50a5 1021 }
c295e0f8 1022 if !problematic_captures.is_empty() {
136023e0 1023 return Some(problematic_captures);
17df50a5 1024 }
136023e0 1025 None
17df50a5
XL
1026 }
1027
5869c6ff
XL
1028 /// Figures out the list of root variables (and their types) that aren't completely
1029 /// captured by the closure when `capture_disjoint_fields` is enabled and drop order of
1030 /// some path starting at that root variable **might** be affected.
1031 ///
1032 /// The output list would include a root variable if:
1033 /// - It would have been moved into the closure when `capture_disjoint_fields` wasn't
1034 /// enabled, **and**
1035 /// - It wasn't completely captured by the closure, **and**
6a06907d 1036 /// - One of the paths starting at this root variable, that is not captured needs Drop.
17df50a5 1037 ///
136023e0
XL
1038 /// This function only returns a HashSet of CapturesInfo for significant drops. If there
1039 /// are no significant drops than None is returned
c295e0f8 1040 #[instrument(level = "debug", skip(self))]
17df50a5 1041 fn compute_2229_migrations_for_drop(
5869c6ff 1042 &self,
064997fb 1043 closure_def_id: LocalDefId,
5869c6ff 1044 closure_span: Span,
5869c6ff 1045 min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
17df50a5
XL
1046 closure_clause: hir::CaptureBy,
1047 var_hir_id: hir::HirId,
c295e0f8 1048 ) -> Option<FxHashSet<UpvarMigrationInfo>> {
064997fb 1049 let ty = self.resolve_vars_if_possible(self.node_ty(var_hir_id));
5869c6ff 1050
064997fb 1051 if !ty.has_significant_drop(self.tcx, self.tcx.param_env(closure_def_id)) {
c295e0f8 1052 debug!("does not have significant drop");
136023e0 1053 return None;
17df50a5 1054 }
5869c6ff 1055
3c0e092e 1056 let Some(root_var_min_capture_list) = min_captures.and_then(|m| m.get(&var_hir_id)) else {
17df50a5 1057 // The upvar is mentioned within the closure but no path starting from it is
c295e0f8
XL
1058 // used. This occurs when you have (e.g.)
1059 //
1060 // ```
1061 // let x = move || {
1062 // let _ = y;
1063 // });
1064 // ```
1065 debug!("no path starting from it is used");
1066
5869c6ff 1067
17df50a5
XL
1068 match closure_clause {
1069 // Only migrate if closure is a move closure
c295e0f8
XL
1070 hir::CaptureBy::Value => {
1071 let mut diagnostics_info = FxHashSet::default();
1072 let upvars = self.tcx.upvars_mentioned(closure_def_id).expect("must be an upvar");
1073 let upvar = upvars[&var_hir_id];
1074 diagnostics_info.insert(UpvarMigrationInfo::CapturingNothing { use_span: upvar.span });
1075 return Some(diagnostics_info);
1076 }
17df50a5 1077 hir::CaptureBy::Ref => {}
5869c6ff
XL
1078 }
1079
136023e0 1080 return None;
17df50a5 1081 };
c295e0f8 1082 debug!(?root_var_min_capture_list);
5869c6ff 1083
136023e0
XL
1084 let mut projections_list = Vec::new();
1085 let mut diagnostics_info = FxHashSet::default();
1086
1087 for captured_place in root_var_min_capture_list.iter() {
1088 match captured_place.info.capture_kind {
17df50a5 1089 // Only care about captures that are moved into the closure
5099ac24 1090 ty::UpvarCapture::ByValue => {
136023e0 1091 projections_list.push(captured_place.place.projections.as_slice());
c295e0f8
XL
1092 diagnostics_info.insert(UpvarMigrationInfo::CapturingPrecise {
1093 source_expr: captured_place.info.path_expr_id,
1094 var_name: captured_place.to_string(self.tcx),
1095 });
136023e0
XL
1096 }
1097 ty::UpvarCapture::ByRef(..) => {}
1098 }
1099 }
5869c6ff 1100
c295e0f8
XL
1101 debug!(?projections_list);
1102 debug!(?diagnostics_info);
1103
17df50a5 1104 let is_moved = !projections_list.is_empty();
c295e0f8 1105 debug!(?is_moved);
5869c6ff 1106
17df50a5 1107 let is_not_completely_captured =
c295e0f8
XL
1108 root_var_min_capture_list.iter().any(|capture| !capture.place.projections.is_empty());
1109 debug!(?is_not_completely_captured);
5869c6ff 1110
17df50a5
XL
1111 if is_moved
1112 && is_not_completely_captured
1113 && self.has_significant_drop_outside_of_captures(
1114 closure_def_id,
1115 closure_span,
1116 ty,
1117 projections_list,
1118 )
1119 {
136023e0 1120 return Some(diagnostics_info);
17df50a5 1121 }
6a06907d 1122
c295e0f8 1123 None
17df50a5 1124 }
5869c6ff 1125
17df50a5
XL
1126 /// Figures out the list of root variables (and their types) that aren't completely
1127 /// captured by the closure when `capture_disjoint_fields` is enabled and either drop
1128 /// order of some path starting at that root variable **might** be affected or auto-traits
1129 /// differ between the root variable and the captured paths.
1130 ///
1131 /// The output list would include a root variable if:
1132 /// - It would have been moved into the closure when `capture_disjoint_fields` wasn't
1133 /// enabled, **and**
1134 /// - It wasn't completely captured by the closure, **and**
1135 /// - One of the paths starting at this root variable, that is not captured needs Drop **or**
1136 /// - One of the paths captured does not implement all the auto-traits its root variable
1137 /// implements.
1138 ///
136023e0
XL
1139 /// Returns a tuple containing a vector of MigrationDiagnosticInfo, as well as a String
1140 /// containing the reason why root variables whose HirId is contained in the vector should
1141 /// be captured
c295e0f8 1142 #[instrument(level = "debug", skip(self))]
17df50a5
XL
1143 fn compute_2229_migrations(
1144 &self,
064997fb 1145 closure_def_id: LocalDefId,
17df50a5
XL
1146 closure_span: Span,
1147 closure_clause: hir::CaptureBy,
1148 min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
c295e0f8 1149 ) -> (Vec<NeededMigration>, MigrationWarningReason) {
3c0e092e 1150 let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) else {
c295e0f8 1151 return (Vec::new(), MigrationWarningReason::default());
17df50a5 1152 };
5869c6ff 1153
17df50a5 1154 let mut need_migrations = Vec::new();
136023e0
XL
1155 let mut auto_trait_migration_reasons = FxHashSet::default();
1156 let mut drop_migration_needed = false;
17df50a5
XL
1157
1158 // Perform auto-trait analysis
1159 for (&var_hir_id, _) in upvars.iter() {
c295e0f8 1160 let mut diagnostics_info = Vec::new();
136023e0
XL
1161
1162 let auto_trait_diagnostic = if let Some(diagnostics_info) =
1163 self.compute_2229_migrations_for_trait(min_captures, var_hir_id, closure_clause)
6a06907d 1164 {
136023e0
XL
1165 diagnostics_info
1166 } else {
1167 FxHashMap::default()
1168 };
1169
1170 let drop_reorder_diagnostic = if let Some(diagnostics_info) = self
1171 .compute_2229_migrations_for_drop(
1172 closure_def_id,
1173 closure_span,
1174 min_captures,
1175 closure_clause,
1176 var_hir_id,
1177 ) {
1178 drop_migration_needed = true;
1179 diagnostics_info
1180 } else {
1181 FxHashSet::default()
1182 };
1183
1184 // Combine all the captures responsible for needing migrations into one HashSet
1185 let mut capture_diagnostic = drop_reorder_diagnostic.clone();
1186 for key in auto_trait_diagnostic.keys() {
1187 capture_diagnostic.insert(key.clone());
17df50a5
XL
1188 }
1189
136023e0
XL
1190 let mut capture_diagnostic = capture_diagnostic.into_iter().collect::<Vec<_>>();
1191 capture_diagnostic.sort();
c295e0f8 1192 for captures_info in capture_diagnostic {
136023e0
XL
1193 // Get the auto trait reasons of why migration is needed because of that capture, if there are any
1194 let capture_trait_reasons =
c295e0f8 1195 if let Some(reasons) = auto_trait_diagnostic.get(&captures_info) {
136023e0
XL
1196 reasons.clone()
1197 } else {
1198 FxHashSet::default()
1199 };
1200
1201 // Check if migration is needed because of drop reorder as a result of that capture
c295e0f8 1202 let capture_drop_reorder_reason = drop_reorder_diagnostic.contains(&captures_info);
136023e0
XL
1203
1204 // Combine all the reasons of why the root variable should be captured as a result of
1205 // auto trait implementation issues
f2b60f7d 1206 auto_trait_migration_reasons.extend(capture_trait_reasons.iter().copied());
136023e0 1207
c295e0f8
XL
1208 diagnostics_info.push(MigrationLintNote {
1209 captures_info,
1210 reason: self.compute_2229_migrations_reasons(
136023e0
XL
1211 capture_trait_reasons,
1212 capture_drop_reorder_reason,
1213 ),
c295e0f8 1214 });
17df50a5
XL
1215 }
1216
c295e0f8
XL
1217 if !diagnostics_info.is_empty() {
1218 need_migrations.push(NeededMigration { var_hir_id, diagnostics_info });
5869c6ff 1219 }
fc512014 1220 }
17df50a5
XL
1221 (
1222 need_migrations,
136023e0
XL
1223 self.compute_2229_migrations_reasons(
1224 auto_trait_migration_reasons,
1225 drop_migration_needed,
1226 ),
17df50a5 1227 )
fc512014
XL
1228 }
1229
6a06907d
XL
1230 /// This is a helper function to `compute_2229_migrations_precise_pass`. Provided the type
1231 /// of a root variable and a list of captured paths starting at this root variable (expressed
1232 /// using list of `Projection` slices), it returns true if there is a path that is not
1233 /// captured starting at this root variable that implements Drop.
1234 ///
6a06907d
XL
1235 /// The way this function works is at a given call it looks at type `base_path_ty` of some base
1236 /// path say P and then list of projection slices which represent the different captures moved
1237 /// into the closure starting off of P.
1238 ///
1239 /// This will make more sense with an example:
1240 ///
9ffffee4 1241 /// ```rust,edition2021
6a06907d
XL
1242 ///
1243 /// struct FancyInteger(i32); // This implements Drop
1244 ///
1245 /// struct Point { x: FancyInteger, y: FancyInteger }
1246 /// struct Color;
1247 ///
1248 /// struct Wrapper { p: Point, c: Color }
1249 ///
1250 /// fn f(w: Wrapper) {
1251 /// let c = || {
1252 /// // Closure captures w.p.x and w.c by move.
1253 /// };
1254 ///
1255 /// c();
1256 /// }
1257 /// ```
1258 ///
1259 /// If `capture_disjoint_fields` wasn't enabled the closure would've moved `w` instead of the
1260 /// precise paths. If we look closely `w.p.y` isn't captured which implements Drop and
1261 /// therefore Drop ordering would change and we want this function to return true.
1262 ///
1263 /// Call stack to figure out if we need to migrate for `w` would look as follows:
1264 ///
1265 /// Our initial base path is just `w`, and the paths captured from it are `w[p, x]` and
1266 /// `w[c]`.
1267 /// Notation:
1268 /// - Ty(place): Type of place
cdc7bbd5 1269 /// - `(a, b)`: Represents the function parameters `base_path_ty` and `captured_by_move_projs`
6a06907d 1270 /// respectively.
04454e1e 1271 /// ```ignore (illustrative)
6a06907d 1272 /// (Ty(w), [ &[p, x], &[c] ])
04454e1e
FG
1273 /// // |
1274 /// // ----------------------------
1275 /// // | |
1276 /// // v v
6a06907d 1277 /// (Ty(w.p), [ &[x] ]) (Ty(w.c), [ &[] ]) // I(1)
04454e1e
FG
1278 /// // | |
1279 /// // v v
6a06907d 1280 /// (Ty(w.p), [ &[x] ]) false
04454e1e
FG
1281 /// // |
1282 /// // |
1283 /// // -------------------------------
1284 /// // | |
1285 /// // v v
6a06907d 1286 /// (Ty((w.p).x), [ &[] ]) (Ty((w.p).y), []) // IMP 2
04454e1e
FG
1287 /// // | |
1288 /// // v v
17df50a5 1289 /// false NeedsSignificantDrop(Ty(w.p.y))
04454e1e
FG
1290 /// // |
1291 /// // v
6a06907d
XL
1292 /// true
1293 /// ```
1294 ///
1295 /// IMP 1 `(Ty(w.c), [ &[] ])`: Notice the single empty slice inside `captured_projs`.
1296 /// This implies that the `w.c` is completely captured by the closure.
1297 /// Since drop for this path will be called when the closure is
1298 /// dropped we don't need to migrate for it.
1299 ///
1300 /// IMP 2 `(Ty((w.p).y), [])`: Notice that `captured_projs` is empty. This implies that this
1301 /// path wasn't captured by the closure. Also note that even
1302 /// though we didn't capture this path, the function visits it,
1303 /// which is kind of the point of this function. We then return
1304 /// if the type of `w.p.y` implements Drop, which in this case is
1305 /// true.
1306 ///
1307 /// Consider another example:
1308 ///
04454e1e 1309 /// ```ignore (pseudo-rust)
6a06907d
XL
1310 /// struct X;
1311 /// impl Drop for X {}
1312 ///
1313 /// struct Y(X);
1314 /// impl Drop for Y {}
1315 ///
1316 /// fn foo() {
1317 /// let y = Y(X);
1318 /// let c = || move(y.0);
1319 /// }
1320 /// ```
1321 ///
1322 /// Note that `y.0` is captured by the closure. When this function is called for `y`, it will
1323 /// return true, because even though all paths starting at `y` are captured, `y` itself
1324 /// implements Drop which will be affected since `y` isn't completely captured.
1325 fn has_significant_drop_outside_of_captures(
1326 &self,
064997fb 1327 closure_def_id: LocalDefId,
6a06907d
XL
1328 closure_span: Span,
1329 base_path_ty: Ty<'tcx>,
cdc7bbd5 1330 captured_by_move_projs: Vec<&[Projection<'tcx>]>,
6a06907d 1331 ) -> bool {
064997fb
FG
1332 let needs_drop =
1333 |ty: Ty<'tcx>| ty.has_significant_drop(self.tcx, self.tcx.param_env(closure_def_id));
6a06907d
XL
1334
1335 let is_drop_defined_for_ty = |ty: Ty<'tcx>| {
1336 let drop_trait = self.tcx.require_lang_item(hir::LangItem::Drop, Some(closure_span));
136023e0 1337 self.infcx
487cf647 1338 .type_implements_trait(drop_trait, [ty], self.tcx.param_env(closure_def_id))
136023e0 1339 .must_apply_modulo_regions()
6a06907d
XL
1340 };
1341
1342 let is_drop_defined_for_ty = is_drop_defined_for_ty(base_path_ty);
1343
1344 // If there is a case where no projection is applied on top of current place
1345 // then there must be exactly one capture corresponding to such a case. Note that this
1346 // represents the case of the path being completely captured by the variable.
1347 //
1348 // eg. If `a.b` is captured and we are processing `a.b`, then we can't have the closure also
5e7ed085 1349 // capture `a.b.c`, because that violates min capture.
cdc7bbd5 1350 let is_completely_captured = captured_by_move_projs.iter().any(|projs| projs.is_empty());
6a06907d 1351
cdc7bbd5 1352 assert!(!is_completely_captured || (captured_by_move_projs.len() == 1));
6a06907d
XL
1353
1354 if is_completely_captured {
1355 // The place is captured entirely, so doesn't matter if needs dtor, it will be drop
1356 // when the closure is dropped.
1357 return false;
1358 }
1359
cdc7bbd5
XL
1360 if captured_by_move_projs.is_empty() {
1361 return needs_drop(base_path_ty);
1362 }
1363
6a06907d
XL
1364 if is_drop_defined_for_ty {
1365 // If drop is implemented for this type then we need it to be fully captured,
cdc7bbd5 1366 // and we know it is not completely captured because of the previous checks.
6a06907d 1367
cdc7bbd5
XL
1368 // Note that this is a bug in the user code that will be reported by the
1369 // borrow checker, since we can't move out of drop types.
1370
1371 // The bug exists in the user's code pre-migration, and we don't migrate here.
1372 return false;
6a06907d
XL
1373 }
1374
1375 match base_path_ty.kind() {
1376 // Observations:
cdc7bbd5
XL
1377 // - `captured_by_move_projs` is not empty. Therefore we can call
1378 // `captured_by_move_projs.first().unwrap()` safely.
5e7ed085 1379 // - All entries in `captured_by_move_projs` have at least one projection.
cdc7bbd5 1380 // Therefore we can call `captured_by_move_projs.first().unwrap().first().unwrap()` safely.
6a06907d
XL
1381
1382 // We don't capture derefs in case of move captures, which would have be applied to
1383 // access any further paths.
1384 ty::Adt(def, _) if def.is_box() => unreachable!(),
1385 ty::Ref(..) => unreachable!(),
1386 ty::RawPtr(..) => unreachable!(),
1387
1388 ty::Adt(def, substs) => {
5e7ed085 1389 // Multi-variant enums are captured in entirety,
cdc7bbd5 1390 // which would've been handled in the case of single empty slice in `captured_by_move_projs`.
5e7ed085 1391 assert_eq!(def.variants().len(), 1);
6a06907d
XL
1392
1393 // Only Field projections can be applied to a non-box Adt.
1394 assert!(
cdc7bbd5 1395 captured_by_move_projs.iter().all(|projs| matches!(
6a06907d
XL
1396 projs.first().unwrap().kind,
1397 ProjectionKind::Field(..)
1398 ))
1399 );
353b0b11 1400 def.variants().get(FIRST_VARIANT).unwrap().fields.iter_enumerated().any(
6a06907d 1401 |(i, field)| {
cdc7bbd5 1402 let paths_using_field = captured_by_move_projs
6a06907d
XL
1403 .iter()
1404 .filter_map(|projs| {
1405 if let ProjectionKind::Field(field_idx, _) =
1406 projs.first().unwrap().kind
1407 {
353b0b11 1408 if field_idx == i { Some(&projs[1..]) } else { None }
6a06907d
XL
1409 } else {
1410 unreachable!();
1411 }
1412 })
1413 .collect();
1414
1415 let after_field_ty = field.ty(self.tcx, substs);
1416 self.has_significant_drop_outside_of_captures(
1417 closure_def_id,
1418 closure_span,
1419 after_field_ty,
1420 paths_using_field,
1421 )
1422 },
1423 )
1424 }
1425
5e7ed085 1426 ty::Tuple(fields) => {
6a06907d
XL
1427 // Only Field projections can be applied to a tuple.
1428 assert!(
cdc7bbd5 1429 captured_by_move_projs.iter().all(|projs| matches!(
6a06907d
XL
1430 projs.first().unwrap().kind,
1431 ProjectionKind::Field(..)
1432 ))
1433 );
1434
5e7ed085 1435 fields.iter().enumerate().any(|(i, element_ty)| {
cdc7bbd5 1436 let paths_using_field = captured_by_move_projs
6a06907d
XL
1437 .iter()
1438 .filter_map(|projs| {
1439 if let ProjectionKind::Field(field_idx, _) = projs.first().unwrap().kind
1440 {
353b0b11 1441 if field_idx.index() == i { Some(&projs[1..]) } else { None }
6a06907d
XL
1442 } else {
1443 unreachable!();
1444 }
1445 })
1446 .collect();
1447
1448 self.has_significant_drop_outside_of_captures(
1449 closure_def_id,
1450 closure_span,
1451 element_ty,
1452 paths_using_field,
1453 )
1454 })
1455 }
1456
1457 // Anything else would be completely captured and therefore handled already.
1458 _ => unreachable!(),
1459 }
1460 }
1461
1462 fn init_capture_kind_for_place(
fc512014 1463 &self,
6a06907d 1464 place: &Place<'tcx>,
fc512014 1465 capture_clause: hir::CaptureBy,
5099ac24 1466 ) -> ty::UpvarCapture {
fc512014 1467 match capture_clause {
6a06907d
XL
1468 // In case of a move closure if the data is accessed through a reference we
1469 // want to capture by ref to allow precise capture using reborrows.
1470 //
1471 // If the data will be moved out of this place, then the place will be truncated
1472 // at the first Deref in `adjust_upvar_borrow_kind_for_consume` and then moved into
1473 // the closure.
5099ac24
FG
1474 hir::CaptureBy::Value if !place.deref_tys().any(Ty::is_ref) => {
1475 ty::UpvarCapture::ByValue
fc512014 1476 }
5099ac24 1477 hir::CaptureBy::Value | hir::CaptureBy::Ref => ty::UpvarCapture::ByRef(ty::ImmBorrow),
fc512014
XL
1478 }
1479 }
1480
1481 fn place_for_root_variable(
1482 &self,
1483 closure_def_id: LocalDefId,
1484 var_hir_id: hir::HirId,
1485 ) -> Place<'tcx> {
1486 let upvar_id = ty::UpvarId::new(var_hir_id, closure_def_id);
1487
1488 Place {
1489 base_ty: self.node_ty(var_hir_id),
1490 base: PlaceBase::Upvar(upvar_id),
1491 projections: Default::default(),
1492 }
1493 }
1494
064997fb 1495 fn should_log_capture_analysis(&self, closure_def_id: LocalDefId) -> bool {
353b0b11 1496 self.tcx.has_attr(closure_def_id, sym::rustc_capture_analysis)
fc512014
XL
1497 }
1498
1499 fn log_capture_analysis_first_pass(
1500 &self,
064997fb 1501 closure_def_id: LocalDefId,
5099ac24 1502 capture_information: &InferredCaptureInformation<'tcx>,
fc512014
XL
1503 closure_span: Span,
1504 ) {
1505 if self.should_log_capture_analysis(closure_def_id) {
1506 let mut diag =
1507 self.tcx.sess.struct_span_err(closure_span, "First Pass analysis includes:");
1508 for (place, capture_info) in capture_information {
1509 let capture_str = construct_capture_info_string(self.tcx, place, capture_info);
04454e1e 1510 let output_str = format!("Capturing {capture_str}");
fc512014 1511
5869c6ff
XL
1512 let span =
1513 capture_info.path_expr_id.map_or(closure_span, |e| self.tcx.hir().span(e));
49aad941 1514 diag.span_note(span, output_str);
fc512014
XL
1515 }
1516 diag.emit();
1517 }
1518 }
1519
064997fb 1520 fn log_closure_min_capture_info(&self, closure_def_id: LocalDefId, closure_span: Span) {
fc512014
XL
1521 if self.should_log_capture_analysis(closure_def_id) {
1522 if let Some(min_captures) =
1523 self.typeck_results.borrow().closure_min_captures.get(&closure_def_id)
1524 {
1525 let mut diag =
1526 self.tcx.sess.struct_span_err(closure_span, "Min Capture analysis includes:");
1527
1528 for (_, min_captures_for_var) in min_captures {
1529 for capture in min_captures_for_var {
1530 let place = &capture.place;
1531 let capture_info = &capture.info;
1532
1533 let capture_str =
1534 construct_capture_info_string(self.tcx, place, capture_info);
04454e1e 1535 let output_str = format!("Min Capture {capture_str}");
fc512014 1536
5869c6ff
XL
1537 if capture.info.path_expr_id != capture.info.capture_kind_expr_id {
1538 let path_span = capture_info
1539 .path_expr_id
1540 .map_or(closure_span, |e| self.tcx.hir().span(e));
1541 let capture_kind_span = capture_info
1542 .capture_kind_expr_id
1543 .map_or(closure_span, |e| self.tcx.hir().span(e));
1544
1545 let mut multi_span: MultiSpan =
1546 MultiSpan::from_spans(vec![path_span, capture_kind_span]);
1547
1548 let capture_kind_label =
1549 construct_capture_kind_reason_string(self.tcx, place, capture_info);
1550 let path_label = construct_path_string(self.tcx, place);
1551
1552 multi_span.push_span_label(path_span, path_label);
1553 multi_span.push_span_label(capture_kind_span, capture_kind_label);
1554
49aad941 1555 diag.span_note(multi_span, output_str);
5869c6ff
XL
1556 } else {
1557 let span = capture_info
1558 .path_expr_id
1559 .map_or(closure_span, |e| self.tcx.hir().span(e));
1560
49aad941 1561 diag.span_note(span, output_str);
5869c6ff 1562 };
fc512014
XL
1563 }
1564 }
1565 diag.emit();
1566 }
1567 }
1568 }
5869c6ff
XL
1569
1570 /// A captured place is mutable if
1571 /// 1. Projections don't include a Deref of an immut-borrow, **and**
1572 /// 2. PlaceBase is mut or projections include a Deref of a mut-borrow.
1573 fn determine_capture_mutability(
1574 &self,
1575 typeck_results: &'a TypeckResults<'tcx>,
1576 place: &Place<'tcx>,
1577 ) -> hir::Mutability {
1578 let var_hir_id = match place.base {
1579 PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
1580 _ => unreachable!(),
1581 };
1582
1583 let bm = *typeck_results.pat_binding_modes().get(var_hir_id).expect("missing binding mode");
1584
1585 let mut is_mutbl = match bm {
1586 ty::BindByValue(mutability) => mutability,
1587 ty::BindByReference(_) => hir::Mutability::Not,
1588 };
1589
1590 for pointer_ty in place.deref_tys() {
1591 match pointer_ty.kind() {
1592 // We don't capture derefs of raw ptrs
1593 ty::RawPtr(_) => unreachable!(),
1594
5e7ed085 1595 // Dereferencing a mut-ref allows us to mut the Place if we don't deref
5869c6ff
XL
1596 // an immut-ref after on top of this.
1597 ty::Ref(.., hir::Mutability::Mut) => is_mutbl = hir::Mutability::Mut,
1598
94222f64 1599 // The place isn't mutable once we dereference an immutable reference.
5869c6ff
XL
1600 ty::Ref(.., hir::Mutability::Not) => return hir::Mutability::Not,
1601
1602 // Dereferencing a box doesn't change mutability
1603 ty::Adt(def, ..) if def.is_box() => {}
1604
1605 unexpected_ty => bug!("deref of unexpected pointer type {:?}", unexpected_ty),
1606 }
1607 }
1608
1609 is_mutbl
1610 }
041b39d2 1611}
c1a9b12d 1612
6a06907d
XL
1613/// Truncate the capture so that the place being borrowed is in accordance with RFC 1240,
1614/// which states that it's unsafe to take a reference into a struct marked `repr(packed)`.
1615fn restrict_repr_packed_field_ref_capture<'tcx>(
1616 tcx: TyCtxt<'tcx>,
1617 param_env: ty::ParamEnv<'tcx>,
5099ac24
FG
1618 mut place: Place<'tcx>,
1619 mut curr_borrow_kind: ty::UpvarCapture,
1620) -> (Place<'tcx>, ty::UpvarCapture) {
6a06907d
XL
1621 let pos = place.projections.iter().enumerate().position(|(i, p)| {
1622 let ty = place.ty_before_projection(i);
1623
1624 // Return true for fields of packed structs, unless those fields have alignment 1.
1625 match p.kind {
1626 ProjectionKind::Field(..) => match ty.kind() {
5e7ed085 1627 ty::Adt(def, _) if def.repr().packed() => {
5099ac24
FG
1628 // We erase regions here because they cannot be hashed
1629 match tcx.layout_of(param_env.and(tcx.erase_regions(p.ty))) {
6a06907d
XL
1630 Ok(layout) if layout.align.abi.bytes() == 1 => {
1631 // if the alignment is 1, the type can't be further
1632 // disaligned.
1633 debug!(
1634 "restrict_repr_packed_field_ref_capture: ({:?}) - align = 1",
1635 place
1636 );
1637 false
1638 }
1639 _ => {
1640 debug!("restrict_repr_packed_field_ref_capture: ({:?}) - true", place);
1641 true
1642 }
1643 }
1644 }
1645
1646 _ => false,
1647 },
1648 _ => false,
1649 }
1650 });
1651
6a06907d 1652 if let Some(pos) = pos {
94222f64 1653 truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_borrow_kind, pos);
6a06907d
XL
1654 }
1655
94222f64 1656 (place, curr_borrow_kind)
6a06907d
XL
1657}
1658
136023e0 1659/// Returns a Ty that applies the specified capture kind on the provided capture Ty
a2a8927a 1660fn apply_capture_kind_on_capture_ty<'tcx>(
136023e0
XL
1661 tcx: TyCtxt<'tcx>,
1662 ty: Ty<'tcx>,
5099ac24
FG
1663 capture_kind: UpvarCapture,
1664 region: Option<ty::Region<'tcx>>,
136023e0
XL
1665) -> Ty<'tcx> {
1666 match capture_kind {
5099ac24
FG
1667 ty::UpvarCapture::ByValue => ty,
1668 ty::UpvarCapture::ByRef(kind) => {
1669 tcx.mk_ref(region.unwrap(), ty::TypeAndMut { ty: ty, mutbl: kind.to_mutbl_lossy() })
1670 }
136023e0
XL
1671 }
1672}
1673
1674/// Returns the Span of where the value with the provided HirId would be dropped
9c376795 1675fn drop_location_span(tcx: TyCtxt<'_>, hir_id: hir::HirId) -> Span {
5e7ed085 1676 let owner_id = tcx.hir().get_enclosing_scope(hir_id).unwrap();
136023e0
XL
1677
1678 let owner_node = tcx.hir().get(owner_id);
1679 let owner_span = match owner_node {
1680 hir::Node::Item(item) => match item.kind {
1681 hir::ItemKind::Fn(_, _, owner_id) => tcx.hir().span(owner_id.hir_id),
1682 _ => {
064997fb 1683 bug!("Drop location span error: need to handle more ItemKind '{:?}'", item.kind);
136023e0
XL
1684 }
1685 },
1686 hir::Node::Block(block) => tcx.hir().span(block.hir_id),
064997fb
FG
1687 hir::Node::TraitItem(item) => tcx.hir().span(item.hir_id()),
1688 hir::Node::ImplItem(item) => tcx.hir().span(item.hir_id()),
136023e0 1689 _ => {
064997fb 1690 bug!("Drop location span error: need to handle more Node '{:?}'", owner_node);
136023e0
XL
1691 }
1692 };
1693 tcx.sess.source_map().end_point(owner_span)
1694}
1695
dc9dc135
XL
1696struct InferBorrowKind<'a, 'tcx> {
1697 fcx: &'a FnCtxt<'a, 'tcx>,
ff7c6d11
XL
1698
1699 // The def-id of the closure whose kind and upvar accesses are being inferred.
5099ac24 1700 closure_def_id: LocalDefId,
fc512014 1701
fc512014
XL
1702 /// For each Place that is captured by the closure, we track the minimal kind of
1703 /// access we need (ref, ref mut, move, etc) and the expression that resulted in such access.
1704 ///
1705 /// Consider closure where s.str1 is captured via an ImmutableBorrow and
1706 /// s.str2 via a MutableBorrow
1707 ///
1708 /// ```rust,no_run
04454e1e 1709 /// struct SomeStruct { str1: String, str2: String };
fc512014
XL
1710 ///
1711 /// // Assume that the HirId for the variable definition is `V1`
04454e1e 1712 /// let mut s = SomeStruct { str1: format!("s1"), str2: format!("s2") };
fc512014
XL
1713 ///
1714 /// let fix_s = |new_s2| {
1715 /// // Assume that the HirId for the expression `s.str1` is `E1`
04454e1e 1716 /// println!("Updating SomeStruct with str1={0}", s.str1);
fc512014
XL
1717 /// // Assume that the HirId for the expression `*s.str2` is `E2`
1718 /// s.str2 = new_s2;
1719 /// };
1720 /// ```
1721 ///
1722 /// For closure `fix_s`, (at a high level) the map contains
1723 ///
04454e1e 1724 /// ```ignore (illustrative)
fc512014
XL
1725 /// Place { V1, [ProjectionKind::Field(Index=0, Variant=0)] } : CaptureKind { E1, ImmutableBorrow }
1726 /// Place { V1, [ProjectionKind::Field(Index=1, Variant=0)] } : CaptureKind { E2, MutableBorrow }
5869c6ff
XL
1727 /// ```
1728 capture_information: InferredCaptureInformation<'tcx>,
6a06907d 1729 fake_reads: Vec<(Place<'tcx>, FakeReadCause, hir::HirId)>,
041b39d2
XL
1730}
1731
dc9dc135 1732impl<'a, 'tcx> euv::Delegate<'tcx> for InferBorrowKind<'a, 'tcx> {
923072b8
FG
1733 fn fake_read(
1734 &mut self,
1735 place: &PlaceWithHirId<'tcx>,
1736 cause: FakeReadCause,
1737 diag_expr_id: hir::HirId,
1738 ) {
1739 let PlaceBase::Upvar(_) = place.place.base else { return };
94222f64 1740
5099ac24
FG
1741 // We need to restrict Fake Read precision to avoid fake reading unsafe code,
1742 // such as deref of a raw pointer.
1743 let dummy_capture_kind = ty::UpvarCapture::ByRef(ty::BorrowKind::ImmBorrow);
94222f64 1744
923072b8 1745 let (place, _) = restrict_capture_precision(place.place.clone(), dummy_capture_kind);
5099ac24
FG
1746
1747 let (place, _) = restrict_repr_packed_field_ref_capture(
1748 self.fcx.tcx,
1749 self.fcx.param_env,
1750 place,
1751 dummy_capture_kind,
1752 );
1753 self.fake_reads.push((place, cause, diag_expr_id));
6a06907d
XL
1754 }
1755
c295e0f8 1756 #[instrument(skip(self), level = "debug")]
136023e0 1757 fn consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId) {
5099ac24
FG
1758 let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return };
1759 assert_eq!(self.closure_def_id, upvar_id.closure_expr_id);
fc512014 1760
5099ac24
FG
1761 self.capture_information.push((
1762 place_with_id.place.clone(),
1763 ty::CaptureInfo {
1764 capture_kind_expr_id: Some(diag_expr_id),
1765 path_expr_id: Some(diag_expr_id),
1766 capture_kind: ty::UpvarCapture::ByValue,
1767 },
1768 ));
85aaf69f 1769 }
1a4d82fc 1770
c295e0f8 1771 #[instrument(skip(self), level = "debug")]
29967ef6
XL
1772 fn borrow(
1773 &mut self,
1774 place_with_id: &PlaceWithHirId<'tcx>,
1775 diag_expr_id: hir::HirId,
1776 bk: ty::BorrowKind,
1777 ) {
5099ac24
FG
1778 let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return };
1779 assert_eq!(self.closure_def_id, upvar_id.closure_expr_id);
1780
94222f64 1781 // The region here will get discarded/ignored
5099ac24 1782 let capture_kind = ty::UpvarCapture::ByRef(bk);
94222f64 1783
136023e0
XL
1784 // We only want repr packed restriction to be applied to reading references into a packed
1785 // struct, and not when the data is being moved. Therefore we call this method here instead
1786 // of in `restrict_capture_precision`.
5099ac24 1787 let (place, mut capture_kind) = restrict_repr_packed_field_ref_capture(
6a06907d
XL
1788 self.fcx.tcx,
1789 self.fcx.param_env,
5099ac24
FG
1790 place_with_id.place.clone(),
1791 capture_kind,
6a06907d 1792 );
136023e0 1793
5099ac24
FG
1794 // Raw pointers don't inherit mutability
1795 if place_with_id.place.deref_tys().any(Ty::is_unsafe_ptr) {
1796 capture_kind = ty::UpvarCapture::ByRef(ty::BorrowKind::ImmBorrow);
fc512014
XL
1797 }
1798
5099ac24
FG
1799 self.capture_information.push((
1800 place,
1801 ty::CaptureInfo {
1802 capture_kind_expr_id: Some(diag_expr_id),
1803 path_expr_id: Some(diag_expr_id),
1804 capture_kind,
94222f64 1805 },
5099ac24 1806 ));
1a4d82fc
JJ
1807 }
1808
c295e0f8 1809 #[instrument(skip(self), level = "debug")]
29967ef6 1810 fn mutate(&mut self, assignee_place: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId) {
6a06907d 1811 self.borrow(assignee_place, diag_expr_id, ty::BorrowKind::MutBorrow);
1a4d82fc
JJ
1812 }
1813}
3b2f2976 1814
94222f64
XL
1815/// Rust doesn't permit moving fields out of a type that implements drop
1816fn restrict_precision_for_drop_types<'a, 'tcx>(
1817 fcx: &'a FnCtxt<'a, 'tcx>,
1818 mut place: Place<'tcx>,
5099ac24 1819 mut curr_mode: ty::UpvarCapture,
5099ac24 1820) -> (Place<'tcx>, ty::UpvarCapture) {
353b0b11 1821 let is_copy_type = fcx.infcx.type_is_copy_modulo_regions(fcx.param_env, place.ty());
94222f64 1822
5099ac24 1823 if let (false, UpvarCapture::ByValue) = (is_copy_type, curr_mode) {
94222f64
XL
1824 for i in 0..place.projections.len() {
1825 match place.ty_before_projection(i).kind() {
1826 ty::Adt(def, _) if def.destructor(fcx.tcx).is_some() => {
1827 truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i);
1828 break;
1829 }
1830 _ => {}
1831 }
1832 }
5869c6ff
XL
1833 }
1834
94222f64
XL
1835 (place, curr_mode)
1836}
1837
1838/// Truncate `place` so that an `unsafe` block isn't required to capture it.
1839/// - No projections are applied to raw pointers, since these require unsafe blocks. We capture
1840/// them completely.
1841/// - No projections are applied on top of Union ADTs, since these require unsafe blocks.
9c376795
FG
1842fn restrict_precision_for_unsafe(
1843 mut place: Place<'_>,
5099ac24 1844 mut curr_mode: ty::UpvarCapture,
9c376795 1845) -> (Place<'_>, ty::UpvarCapture) {
5869c6ff 1846 if place.base_ty.is_unsafe_ptr() {
94222f64 1847 truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, 0);
5869c6ff
XL
1848 }
1849
94222f64
XL
1850 if place.base_ty.is_union() {
1851 truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, 0);
1852 }
5869c6ff
XL
1853
1854 for (i, proj) in place.projections.iter().enumerate() {
1855 if proj.ty.is_unsafe_ptr() {
94222f64
XL
1856 // Don't apply any projections on top of an unsafe ptr.
1857 truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i + 1);
1858 break;
1859 }
1860
1861 if proj.ty.is_union() {
5e7ed085 1862 // Don't capture precise fields of a union.
94222f64 1863 truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i + 1);
5869c6ff
XL
1864 break;
1865 }
94222f64
XL
1866 }
1867
1868 (place, curr_mode)
1869}
1870
1871/// Truncate projections so that following rules are obeyed by the captured `place`:
1872/// - No Index projections are captured, since arrays are captured completely.
1873/// - No unsafe block is required to capture `place`
5e7ed085 1874/// Returns the truncated place and updated capture mode.
9c376795
FG
1875fn restrict_capture_precision(
1876 place: Place<'_>,
5099ac24 1877 curr_mode: ty::UpvarCapture,
9c376795 1878) -> (Place<'_>, ty::UpvarCapture) {
94222f64
XL
1879 let (mut place, mut curr_mode) = restrict_precision_for_unsafe(place, curr_mode);
1880
1881 if place.projections.is_empty() {
1882 // Nothing to do here
1883 return (place, curr_mode);
1884 }
1885
1886 for (i, proj) in place.projections.iter().enumerate() {
5869c6ff 1887 match proj.kind {
353b0b11
FG
1888 ProjectionKind::Index | ProjectionKind::Subslice => {
1889 // Arrays are completely captured, so we drop Index and Subslice projections
94222f64
XL
1890 truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i);
1891 return (place, curr_mode);
5869c6ff 1892 }
6a06907d 1893 ProjectionKind::Deref => {}
5869c6ff 1894 ProjectionKind::Field(..) => {} // ignore
5869c6ff
XL
1895 }
1896 }
1897
c295e0f8 1898 (place, curr_mode)
5869c6ff
XL
1899}
1900
94222f64 1901/// Truncate deref of any reference.
9c376795
FG
1902fn adjust_for_move_closure(
1903 mut place: Place<'_>,
5099ac24 1904 mut kind: ty::UpvarCapture,
9c376795 1905) -> (Place<'_>, ty::UpvarCapture) {
136023e0
XL
1906 let first_deref = place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
1907
94222f64
XL
1908 if let Some(idx) = first_deref {
1909 truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
6a06907d 1910 }
94222f64 1911
5099ac24 1912 (place, ty::UpvarCapture::ByValue)
136023e0 1913}
6a06907d 1914
136023e0
XL
1915/// Adjust closure capture just that if taking ownership of data, only move data
1916/// from enclosing stack frame.
9c376795
FG
1917fn adjust_for_non_move_closure(
1918 mut place: Place<'_>,
5099ac24 1919 mut kind: ty::UpvarCapture,
9c376795 1920) -> (Place<'_>, ty::UpvarCapture) {
136023e0
XL
1921 let contains_deref =
1922 place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
1923
1924 match kind {
5099ac24 1925 ty::UpvarCapture::ByValue => {
94222f64
XL
1926 if let Some(idx) = contains_deref {
1927 truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
1928 }
136023e0
XL
1929 }
1930
94222f64 1931 ty::UpvarCapture::ByRef(..) => {}
136023e0 1932 }
94222f64
XL
1933
1934 (place, kind)
6a06907d
XL
1935}
1936
a2a8927a 1937fn construct_place_string<'tcx>(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
fc512014
XL
1938 let variable_name = match place.base {
1939 PlaceBase::Upvar(upvar_id) => var_name(tcx, upvar_id.var_path.hir_id).to_string(),
1940 _ => bug!("Capture_information should only contain upvars"),
1941 };
1942
1943 let mut projections_str = String::new();
1944 for (i, item) in place.projections.iter().enumerate() {
1945 let proj = match item.kind {
1946 ProjectionKind::Field(a, b) => format!("({:?}, {:?})", a, b),
1947 ProjectionKind::Deref => String::from("Deref"),
1948 ProjectionKind::Index => String::from("Index"),
1949 ProjectionKind::Subslice => String::from("Subslice"),
1950 };
1951 if i != 0 {
6a06907d 1952 projections_str.push(',');
fc512014
XL
1953 }
1954 projections_str.push_str(proj.as_str());
1955 }
1956
04454e1e 1957 format!("{variable_name}[{projections_str}]")
5869c6ff
XL
1958}
1959
a2a8927a 1960fn construct_capture_kind_reason_string<'tcx>(
5869c6ff
XL
1961 tcx: TyCtxt<'_>,
1962 place: &Place<'tcx>,
5099ac24 1963 capture_info: &ty::CaptureInfo,
5869c6ff 1964) -> String {
c295e0f8 1965 let place_str = construct_place_string(tcx, place);
5869c6ff 1966
fc512014 1967 let capture_kind_str = match capture_info.capture_kind {
5099ac24
FG
1968 ty::UpvarCapture::ByValue => "ByValue".into(),
1969 ty::UpvarCapture::ByRef(kind) => format!("{:?}", kind),
fc512014 1970 };
5869c6ff 1971
04454e1e 1972 format!("{place_str} captured as {capture_kind_str} here")
5869c6ff
XL
1973}
1974
a2a8927a 1975fn construct_path_string<'tcx>(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
c295e0f8 1976 let place_str = construct_place_string(tcx, place);
5869c6ff 1977
04454e1e 1978 format!("{place_str} used here")
5869c6ff
XL
1979}
1980
a2a8927a 1981fn construct_capture_info_string<'tcx>(
5869c6ff
XL
1982 tcx: TyCtxt<'_>,
1983 place: &Place<'tcx>,
5099ac24 1984 capture_info: &ty::CaptureInfo,
5869c6ff 1985) -> String {
c295e0f8 1986 let place_str = construct_place_string(tcx, place);
5869c6ff
XL
1987
1988 let capture_kind_str = match capture_info.capture_kind {
5099ac24
FG
1989 ty::UpvarCapture::ByValue => "ByValue".into(),
1990 ty::UpvarCapture::ByRef(kind) => format!("{:?}", kind),
5869c6ff 1991 };
04454e1e 1992 format!("{place_str} -> {capture_kind_str}")
fc512014
XL
1993}
1994
f9f354fc 1995fn var_name(tcx: TyCtxt<'_>, var_hir_id: hir::HirId) -> Symbol {
dc9dc135 1996 tcx.hir().name(var_hir_id)
3b2f2976 1997}
fc512014 1998
c295e0f8 1999#[instrument(level = "debug", skip(tcx))]
136023e0
XL
2000fn should_do_rust_2021_incompatible_closure_captures_analysis(
2001 tcx: TyCtxt<'_>,
2002 closure_id: hir::HirId,
2003) -> bool {
f2b60f7d
FG
2004 if tcx.sess.rust_2021() {
2005 return false;
2006 }
2007
136023e0
XL
2008 let (level, _) =
2009 tcx.lint_level_at_node(lint::builtin::RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES, closure_id);
5869c6ff
XL
2010
2011 !matches!(level, lint::Level::Allow)
2012}
2013
cdc7bbd5
XL
2014/// Return a two string tuple (s1, s2)
2015/// - s1: Line of code that is needed for the migration: eg: `let _ = (&x, ...)`.
2016/// - s2: Comma separated names of the variables being migrated.
2017fn migration_suggestion_for_2229(
2018 tcx: TyCtxt<'_>,
923072b8 2019 need_migrations: &[NeededMigration],
cdc7bbd5 2020) -> (String, String) {
c295e0f8
XL
2021 let need_migrations_variables = need_migrations
2022 .iter()
2023 .map(|NeededMigration { var_hir_id: v, .. }| var_name(tcx, *v))
2024 .collect::<Vec<_>>();
cdc7bbd5
XL
2025
2026 let migration_ref_concat =
04454e1e 2027 need_migrations_variables.iter().map(|v| format!("&{v}")).collect::<Vec<_>>().join(", ");
cdc7bbd5
XL
2028
2029 let migration_string = if 1 == need_migrations.len() {
04454e1e 2030 format!("let _ = {migration_ref_concat}")
cdc7bbd5 2031 } else {
04454e1e 2032 format!("let _ = ({migration_ref_concat})")
cdc7bbd5
XL
2033 };
2034
2035 let migrated_variables_concat =
04454e1e 2036 need_migrations_variables.iter().map(|v| format!("`{v}`")).collect::<Vec<_>>().join(", ");
5869c6ff 2037
cdc7bbd5 2038 (migration_string, migrated_variables_concat)
5869c6ff
XL
2039}
2040
fc512014
XL
2041/// Helper function to determine if we need to escalate CaptureKind from
2042/// CaptureInfo A to B and returns the escalated CaptureInfo.
2043/// (Note: CaptureInfo contains CaptureKind and an expression that led to capture it in that way)
2044///
2045/// If both `CaptureKind`s are considered equivalent, then the CaptureInfo is selected based
5869c6ff
XL
2046/// on the `CaptureInfo` containing an associated `capture_kind_expr_id`.
2047///
2048/// It is the caller's duty to figure out which path_expr_id to use.
fc512014
XL
2049///
2050/// If both the CaptureKind and Expression are considered to be equivalent,
5e7ed085 2051/// then `CaptureInfo` A is preferred. This can be useful in cases where we want to prioritize
fc512014 2052/// expressions reported back to the user as part of diagnostics based on which appears earlier
cdc7bbd5 2053/// in the closure. This can be achieved simply by calling
fc512014
XL
2054/// `determine_capture_info(existing_info, current_info)`. This works out because the
2055/// expressions that occur earlier in the closure body than the current expression are processed before.
2056/// Consider the following example
2057/// ```rust,no_run
2058/// struct Point { x: i32, y: i32 }
04454e1e 2059/// let mut p = Point { x: 10, y: 10 };
fc512014
XL
2060///
2061/// let c = || {
2062/// p.x += 10;
2063/// // ^ E1 ^
2064/// // ...
2065/// // More code
2066/// // ...
2067/// p.x += 10; // E2
2068/// // ^ E2 ^
2069/// };
2070/// ```
2071/// `CaptureKind` associated with both `E1` and `E2` will be ByRef(MutBorrow),
2072/// and both have an expression associated, however for diagnostics we prefer reporting
2073/// `E1` since it appears earlier in the closure body. When `E2` is being processed we
2074/// would've already handled `E1`, and have an existing capture_information for it.
2075/// Calling `determine_capture_info(existing_info_e1, current_info_e2)` will return
2076/// `existing_info_e1` in this case, allowing us to point to `E1` in case of diagnostics.
5099ac24
FG
2077fn determine_capture_info(
2078 capture_info_a: ty::CaptureInfo,
2079 capture_info_b: ty::CaptureInfo,
2080) -> ty::CaptureInfo {
fc512014
XL
2081 // If the capture kind is equivalent then, we don't need to escalate and can compare the
2082 // expressions.
2083 let eq_capture_kind = match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
5099ac24
FG
2084 (ty::UpvarCapture::ByValue, ty::UpvarCapture::ByValue) => true,
2085 (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => ref_a == ref_b,
2086 (ty::UpvarCapture::ByValue, _) | (ty::UpvarCapture::ByRef(_), _) => false,
fc512014
XL
2087 };
2088
2089 if eq_capture_kind {
5869c6ff 2090 match (capture_info_a.capture_kind_expr_id, capture_info_b.capture_kind_expr_id) {
fc512014
XL
2091 (Some(_), _) | (None, None) => capture_info_a,
2092 (None, Some(_)) => capture_info_b,
2093 }
2094 } else {
2095 // We select the CaptureKind which ranks higher based the following priority order:
2096 // ByValue > MutBorrow > UniqueImmBorrow > ImmBorrow
2097 match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
5099ac24
FG
2098 (ty::UpvarCapture::ByValue, _) => capture_info_a,
2099 (_, ty::UpvarCapture::ByValue) => capture_info_b,
fc512014 2100 (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => {
5099ac24 2101 match (ref_a, ref_b) {
fc512014
XL
2102 // Take LHS:
2103 (ty::UniqueImmBorrow | ty::MutBorrow, ty::ImmBorrow)
2104 | (ty::MutBorrow, ty::UniqueImmBorrow) => capture_info_a,
2105
2106 // Take RHS:
2107 (ty::ImmBorrow, ty::UniqueImmBorrow | ty::MutBorrow)
2108 | (ty::UniqueImmBorrow, ty::MutBorrow) => capture_info_b,
2109
2110 (ty::ImmBorrow, ty::ImmBorrow)
2111 | (ty::UniqueImmBorrow, ty::UniqueImmBorrow)
2112 | (ty::MutBorrow, ty::MutBorrow) => {
2113 bug!("Expected unequal capture kinds");
2114 }
2115 }
2116 }
2117 }
2118 }
2119}
2120
94222f64
XL
2121/// Truncates `place` to have up to `len` projections.
2122/// `curr_mode` is the current required capture kind for the place.
2123/// Returns the truncated `place` and the updated required capture kind.
2124///
2125/// Note: Capture kind changes from `MutBorrow` to `UniqueImmBorrow` if the truncated part of the `place`
2126/// contained `Deref` of `&mut`.
a2a8927a 2127fn truncate_place_to_len_and_update_capture_kind<'tcx>(
94222f64 2128 place: &mut Place<'tcx>,
5099ac24 2129 curr_mode: &mut ty::UpvarCapture,
94222f64
XL
2130 len: usize,
2131) {
2132 let is_mut_ref = |ty: Ty<'_>| matches!(ty.kind(), ty::Ref(.., hir::Mutability::Mut));
2133
2134 // If the truncated part of the place contains `Deref` of a `&mut` then convert MutBorrow ->
2135 // UniqueImmBorrow
2136 // Note that if the place contained Deref of a raw pointer it would've not been MutBorrow, so
2137 // we don't need to worry about that case here.
2138 match curr_mode {
5099ac24 2139 ty::UpvarCapture::ByRef(ty::BorrowKind::MutBorrow) => {
94222f64
XL
2140 for i in len..place.projections.len() {
2141 if place.projections[i].kind == ProjectionKind::Deref
2142 && is_mut_ref(place.ty_before_projection(i))
2143 {
5099ac24 2144 *curr_mode = ty::UpvarCapture::ByRef(ty::BorrowKind::UniqueImmBorrow);
94222f64
XL
2145 break;
2146 }
2147 }
2148 }
2149
2150 ty::UpvarCapture::ByRef(..) => {}
5099ac24 2151 ty::UpvarCapture::ByValue => {}
94222f64
XL
2152 }
2153
2154 place.projections.truncate(len);
2155}
2156
fc512014
XL
2157/// Determines the Ancestry relationship of Place A relative to Place B
2158///
2159/// `PlaceAncestryRelation::Ancestor` implies Place A is ancestor of Place B
2160/// `PlaceAncestryRelation::Descendant` implies Place A is descendant of Place B
2161/// `PlaceAncestryRelation::Divergent` implies neither of them is the ancestor of the other.
a2a8927a 2162fn determine_place_ancestry_relation<'tcx>(
fc512014
XL
2163 place_a: &Place<'tcx>,
2164 place_b: &Place<'tcx>,
2165) -> PlaceAncestryRelation {
487cf647 2166 // If Place A and Place B don't start off from the same root variable, they are divergent.
fc512014
XL
2167 if place_a.base != place_b.base {
2168 return PlaceAncestryRelation::Divergent;
2169 }
2170
2171 // Assume of length of projections_a = n
2172 let projections_a = &place_a.projections;
2173
2174 // Assume of length of projections_b = m
2175 let projections_b = &place_b.projections;
2176
6a06907d 2177 let same_initial_projections =
dc3f5686 2178 iter::zip(projections_a, projections_b).all(|(proj_a, proj_b)| proj_a.kind == proj_b.kind);
fc512014
XL
2179
2180 if same_initial_projections {
dc3f5686
XL
2181 use std::cmp::Ordering;
2182
fc512014
XL
2183 // First min(n, m) projections are the same
2184 // Select Ancestor/Descendant
dc3f5686
XL
2185 match projections_b.len().cmp(&projections_a.len()) {
2186 Ordering::Greater => PlaceAncestryRelation::Ancestor,
2187 Ordering::Equal => PlaceAncestryRelation::SamePlace,
2188 Ordering::Less => PlaceAncestryRelation::Descendant,
fc512014
XL
2189 }
2190 } else {
2191 PlaceAncestryRelation::Divergent
2192 }
2193}
136023e0 2194
5e7ed085
FG
2195/// Reduces the precision of the captured place when the precision doesn't yield any benefit from
2196/// borrow checking perspective, allowing us to save us on the size of the capture.
136023e0
XL
2197///
2198///
2199/// Fields that are read through a shared reference will always be read via a shared ref or a copy,
2200/// and therefore capturing precise paths yields no benefit. This optimization truncates the
2201/// rightmost deref of the capture if the deref is applied to a shared ref.
2202///
2203/// Reason we only drop the last deref is because of the following edge case:
2204///
04454e1e
FG
2205/// ```
2206/// # struct A { field_of_a: Box<i32> }
2207/// # struct B {}
2208/// # struct C<'a>(&'a i32);
136023e0
XL
2209/// struct MyStruct<'a> {
2210/// a: &'static A,
2211/// b: B,
2212/// c: C<'a>,
2213/// }
2214///
2215/// fn foo<'a, 'b>(m: &'a MyStruct<'b>) -> impl FnMut() + 'static {
04454e1e 2216/// || drop(&*m.a.field_of_a)
136023e0
XL
2217/// // Here we really do want to capture `*m.a` because that outlives `'static`
2218///
9ffffee4 2219/// // If we capture `m`, then the closure no longer outlives `'static`
136023e0
XL
2220/// // it is constrained to `'a`
2221/// }
2222/// ```
9c376795
FG
2223fn truncate_capture_for_optimization(
2224 mut place: Place<'_>,
5099ac24 2225 mut curr_mode: ty::UpvarCapture,
9c376795 2226) -> (Place<'_>, ty::UpvarCapture) {
136023e0
XL
2227 let is_shared_ref = |ty: Ty<'_>| matches!(ty.kind(), ty::Ref(.., hir::Mutability::Not));
2228
2229 // Find the right-most deref (if any). All the projections that come after this
2230 // are fields or other "in-place pointer adjustments"; these refer therefore to
2231 // data owned by whatever pointer is being dereferenced here.
2232 let idx = place.projections.iter().rposition(|proj| ProjectionKind::Deref == proj.kind);
2233
2234 match idx {
2235 // If that pointer is a shared reference, then we don't need those fields.
2236 Some(idx) if is_shared_ref(place.ty_before_projection(idx)) => {
94222f64 2237 truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, idx + 1)
136023e0 2238 }
94222f64 2239 None | Some(_) => {}
136023e0 2240 }
94222f64
XL
2241
2242 (place, curr_mode)
136023e0
XL
2243}
2244
9ffffee4 2245/// Precise capture is enabled if user is using Rust Edition 2021 or higher.
136023e0 2246/// `span` is the span of the closure.
9ffffee4 2247fn enable_precise_capture(span: Span) -> bool {
136023e0
XL
2248 // We use span here to ensure that if the closure was generated by a macro with a different
2249 // edition.
9ffffee4 2250 span.rust_2021()
136023e0 2251}