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