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