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