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