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