]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/upvar.rs
Implement the precise analysis pass for lint `disjoint_capture_drop_reorder`
[rust.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::writeback::Resolver;
34 use super::FnCtxt;
35
36 use crate::expr_use_visitor as euv;
37 use rustc_data_structures::fx::FxIndexMap;
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::ty::fold::TypeFoldable;
45 use rustc_middle::ty::{self, Ty, TyCtxt, TypeckResults, UpvarSubsts};
46 use rustc_session::lint;
47 use rustc_span::sym;
48 use rustc_span::{MultiSpan, Span, Symbol};
49
50 use rustc_index::vec::Idx;
51 use rustc_target::abi::VariantIdx;
52
53 /// Describe the relationship between the paths of two places
54 /// eg:
55 /// - `foo` is ancestor of `foo.bar.baz`
56 /// - `foo.bar.baz` is an descendant of `foo.bar`
57 /// - `foo.bar` and `foo.baz` are divergent
58 enum PlaceAncestryRelation {
59     Ancestor,
60     Descendant,
61     Divergent,
62 }
63
64 /// Intermediate format to store a captured `Place` and associated `ty::CaptureInfo`
65 /// during capture analysis. Information in this map feeds into the minimum capture
66 /// analysis pass.
67 type InferredCaptureInformation<'tcx> = FxIndexMap<Place<'tcx>, ty::CaptureInfo<'tcx>>;
68
69 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
70     pub fn closure_analyze(&self, body: &'tcx hir::Body<'tcx>) {
71         InferBorrowKindVisitor { fcx: self }.visit_body(body);
72
73         // it's our job to process these.
74         assert!(self.deferred_call_resolutions.borrow().is_empty());
75     }
76 }
77
78 struct InferBorrowKindVisitor<'a, 'tcx> {
79     fcx: &'a FnCtxt<'a, 'tcx>,
80 }
81
82 impl<'a, 'tcx> Visitor<'tcx> for InferBorrowKindVisitor<'a, 'tcx> {
83     type Map = intravisit::ErasedMap<'tcx>;
84
85     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
86         NestedVisitorMap::None
87     }
88
89     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
90         if let hir::ExprKind::Closure(cc, _, body_id, _, _) = expr.kind {
91             let body = self.fcx.tcx.hir().body(body_id);
92             self.visit_body(body);
93             self.fcx.analyze_closure(expr.hir_id, expr.span, body, cc);
94         }
95
96         intravisit::walk_expr(self, expr);
97     }
98 }
99
100 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
101     /// Analysis starting point.
102     fn analyze_closure(
103         &self,
104         closure_hir_id: hir::HirId,
105         span: Span,
106         body: &'tcx hir::Body<'tcx>,
107         capture_clause: hir::CaptureBy,
108     ) {
109         debug!("analyze_closure(id={:?}, body.id={:?})", closure_hir_id, body.id());
110
111         // Extract the type of the closure.
112         let ty = self.node_ty(closure_hir_id);
113         let (closure_def_id, substs) = match *ty.kind() {
114             ty::Closure(def_id, substs) => (def_id, UpvarSubsts::Closure(substs)),
115             ty::Generator(def_id, substs, _) => (def_id, UpvarSubsts::Generator(substs)),
116             ty::Error(_) => {
117                 // #51714: skip analysis when we have already encountered type errors
118                 return;
119             }
120             _ => {
121                 span_bug!(
122                     span,
123                     "type of closure expr {:?} is not a closure {:?}",
124                     closure_hir_id,
125                     ty
126                 );
127             }
128         };
129
130         let infer_kind = if let UpvarSubsts::Closure(closure_substs) = substs {
131             self.closure_kind(closure_substs).is_none().then_some(closure_substs)
132         } else {
133             None
134         };
135
136         let local_def_id = closure_def_id.expect_local();
137
138         let body_owner_def_id = self.tcx.hir().body_owner_def_id(body.id());
139         assert_eq!(body_owner_def_id.to_def_id(), closure_def_id);
140         let mut delegate = InferBorrowKind {
141             fcx: self,
142             closure_def_id,
143             closure_span: span,
144             capture_clause,
145             current_closure_kind: ty::ClosureKind::LATTICE_BOTTOM,
146             current_origin: None,
147             capture_information: Default::default(),
148         };
149         euv::ExprUseVisitor::new(
150             &mut delegate,
151             &self.infcx,
152             body_owner_def_id,
153             self.param_env,
154             &self.typeck_results.borrow(),
155         )
156         .consume_body(body);
157
158         debug!(
159             "For closure={:?}, capture_information={:#?}",
160             closure_def_id, delegate.capture_information
161         );
162         self.log_capture_analysis_first_pass(closure_def_id, &delegate.capture_information, span);
163
164         self.compute_min_captures(closure_def_id, delegate.capture_information);
165
166         let closure_hir_id = self.tcx.hir().local_def_id_to_hir_id(local_def_id);
167         if should_do_migration_analysis(self.tcx, closure_hir_id) {
168             self.perform_2229_migration_anaysis(closure_def_id, capture_clause, span, body);
169         }
170
171         // We now fake capture information for all variables that are mentioned within the closure
172         // We do this after handling migrations so that min_captures computes before
173         if !self.tcx.features().capture_disjoint_fields {
174             let mut capture_information: InferredCaptureInformation<'tcx> = Default::default();
175
176             if let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) {
177                 for var_hir_id in upvars.keys() {
178                     let place = self.place_for_root_variable(local_def_id, *var_hir_id);
179
180                     debug!("seed place {:?}", place);
181
182                     let upvar_id = ty::UpvarId::new(*var_hir_id, local_def_id);
183                     let capture_kind = self.init_capture_kind(capture_clause, upvar_id, span);
184                     let fake_info = ty::CaptureInfo {
185                         capture_kind_expr_id: None,
186                         path_expr_id: None,
187                         capture_kind,
188                     };
189
190                     capture_information.insert(place, fake_info);
191                 }
192             }
193
194             // This will update the min captures based on this new fake information.
195             self.compute_min_captures(closure_def_id, capture_information);
196         }
197
198         if let Some(closure_substs) = infer_kind {
199             // Unify the (as yet unbound) type variable in the closure
200             // substs with the kind we inferred.
201             let inferred_kind = delegate.current_closure_kind;
202             let closure_kind_ty = closure_substs.as_closure().kind_ty();
203             self.demand_eqtype(span, inferred_kind.to_ty(self.tcx), closure_kind_ty);
204
205             // If we have an origin, store it.
206             if let Some(origin) = delegate.current_origin.clone() {
207                 let origin = if self.tcx.features().capture_disjoint_fields {
208                     origin
209                 } else {
210                     // FIXME(project-rfc-2229#31): Once the changes to support reborrowing are
211                     //                             made, make sure we are selecting and restricting
212                     //                             the origin correctly.
213                     (origin.0, Place { projections: vec![], ..origin.1 })
214                 };
215
216                 self.typeck_results
217                     .borrow_mut()
218                     .closure_kind_origins_mut()
219                     .insert(closure_hir_id, origin);
220             }
221         }
222
223         self.log_closure_min_capture_info(closure_def_id, span);
224
225         self.min_captures_to_closure_captures_bridge(closure_def_id);
226
227         // Now that we've analyzed the closure, we know how each
228         // variable is borrowed, and we know what traits the closure
229         // implements (Fn vs FnMut etc). We now have some updates to do
230         // with that information.
231         //
232         // Note that no closure type C may have an upvar of type C
233         // (though it may reference itself via a trait object). This
234         // results from the desugaring of closures to a struct like
235         // `Foo<..., UV0...UVn>`. If one of those upvars referenced
236         // C, then the type would have infinite size (and the
237         // inference algorithm will reject it).
238
239         // Equate the type variables for the upvars with the actual types.
240         let final_upvar_tys = self.final_upvar_tys(closure_def_id);
241         debug!(
242             "analyze_closure: id={:?} substs={:?} final_upvar_tys={:?}",
243             closure_hir_id, substs, final_upvar_tys
244         );
245
246         // Build a tuple (U0..Un) of the final upvar types U0..Un
247         // and unify the upvar tupe type in the closure with it:
248         let final_tupled_upvars_type = self.tcx.mk_tup(final_upvar_tys.iter());
249         self.demand_suptype(span, substs.tupled_upvars_ty(), final_tupled_upvars_type);
250
251         // If we are also inferred the closure kind here,
252         // process any deferred resolutions.
253         let deferred_call_resolutions = self.remove_deferred_call_resolutions(closure_def_id);
254         for deferred_call_resolution in deferred_call_resolutions {
255             deferred_call_resolution.resolve(self);
256         }
257     }
258
259     // Returns a list of `Ty`s for each upvar.
260     fn final_upvar_tys(&self, closure_id: DefId) -> Vec<Ty<'tcx>> {
261         // Presently an unboxed closure type cannot "escape" out of a
262         // function, so we will only encounter ones that originated in the
263         // local crate or were inlined into it along with some function.
264         // This may change if abstract return types of some sort are
265         // implemented.
266         let tcx = self.tcx;
267
268         self.typeck_results
269             .borrow()
270             .closure_min_captures_flattened(closure_id)
271             .map(|captured_place| {
272                 let upvar_ty = captured_place.place.ty();
273                 let capture = captured_place.info.capture_kind;
274
275                 debug!(
276                     "final_upvar_tys: place={:?} upvar_ty={:?} capture={:?}, mutability={:?}",
277                     captured_place.place, upvar_ty, capture, captured_place.mutability,
278                 );
279
280                 match capture {
281                     ty::UpvarCapture::ByValue(_) => upvar_ty,
282                     ty::UpvarCapture::ByRef(borrow) => tcx.mk_ref(
283                         borrow.region,
284                         ty::TypeAndMut { ty: upvar_ty, mutbl: borrow.kind.to_mutbl_lossy() },
285                     ),
286                 }
287             })
288             .collect()
289     }
290
291     /// Bridge for closure analysis
292     /// ----------------------------
293     ///
294     /// For closure with DefId `c`, the bridge converts structures required for supporting RFC 2229,
295     /// to structures currently used in the compiler for handling closure captures.
296     ///
297     /// For example the following structure will be converted:
298     ///
299     /// closure_min_captures
300     /// foo -> [ {foo.x, ImmBorrow}, {foo.y, MutBorrow} ]
301     /// bar -> [ {bar.z, ByValue}, {bar.q, MutBorrow} ]
302     ///
303     /// to
304     ///
305     /// 1. closure_captures
306     /// foo -> UpvarId(foo, c), bar -> UpvarId(bar, c)
307     ///
308     /// 2. upvar_capture_map
309     /// UpvarId(foo,c) -> MutBorrow, UpvarId(bar, c) -> ByValue
310     fn min_captures_to_closure_captures_bridge(&self, closure_def_id: DefId) {
311         let mut closure_captures: FxIndexMap<hir::HirId, ty::UpvarId> = Default::default();
312         let mut upvar_capture_map = ty::UpvarCaptureMap::default();
313
314         if let Some(min_captures) =
315             self.typeck_results.borrow().closure_min_captures.get(&closure_def_id)
316         {
317             for (var_hir_id, min_list) in min_captures.iter() {
318                 for captured_place in min_list {
319                     let place = &captured_place.place;
320                     let capture_info = captured_place.info;
321
322                     let upvar_id = match place.base {
323                         PlaceBase::Upvar(upvar_id) => upvar_id,
324                         base => bug!("Expected upvar, found={:?}", base),
325                     };
326
327                     assert_eq!(upvar_id.var_path.hir_id, *var_hir_id);
328                     assert_eq!(upvar_id.closure_expr_id, closure_def_id.expect_local());
329
330                     closure_captures.insert(*var_hir_id, upvar_id);
331
332                     let new_capture_kind =
333                         if let Some(capture_kind) = upvar_capture_map.get(&upvar_id) {
334                             // upvar_capture_map only stores the UpvarCapture (CaptureKind),
335                             // so we create a fake capture info with no expression.
336                             let fake_capture_info = ty::CaptureInfo {
337                                 capture_kind_expr_id: None,
338                                 path_expr_id: None,
339                                 capture_kind: *capture_kind,
340                             };
341                             determine_capture_info(fake_capture_info, capture_info).capture_kind
342                         } else {
343                             capture_info.capture_kind
344                         };
345                     upvar_capture_map.insert(upvar_id, new_capture_kind);
346                 }
347             }
348         }
349         debug!("For closure_def_id={:?}, closure_captures={:#?}", closure_def_id, closure_captures);
350         debug!(
351             "For closure_def_id={:?}, upvar_capture_map={:#?}",
352             closure_def_id, upvar_capture_map
353         );
354
355         if !closure_captures.is_empty() {
356             self.typeck_results
357                 .borrow_mut()
358                 .closure_captures
359                 .insert(closure_def_id, closure_captures);
360
361             self.typeck_results.borrow_mut().upvar_capture_map.extend(upvar_capture_map);
362         }
363     }
364
365     /// Analyzes the information collected by `InferBorrowKind` to compute the min number of
366     /// Places (and corresponding capture kind) that we need to keep track of to support all
367     /// the required captured paths.
368     ///
369     ///
370     /// Note: If this function is called multiple times for the same closure, it will update
371     ///       the existing min_capture map that is stored in TypeckResults.
372     ///
373     /// Eg:
374     /// ```rust,no_run
375     /// struct Point { x: i32, y: i32 }
376     ///
377     /// let s: String;  // hir_id_s
378     /// let mut p: Point; // his_id_p
379     /// let c = || {
380     ///        println!("{}", s);  // L1
381     ///        p.x += 10;  // L2
382     ///        println!("{}" , p.y) // L3
383     ///        println!("{}", p) // L4
384     ///        drop(s);   // L5
385     /// };
386     /// ```
387     /// and let hir_id_L1..5 be the expressions pointing to use of a captured variable on
388     /// the lines L1..5 respectively.
389     ///
390     /// InferBorrowKind results in a structure like this:
391     ///
392     /// ```
393     /// {
394     ///       Place(base: hir_id_s, projections: [], ....) -> {
395     ///                                                            capture_kind_expr: hir_id_L5,
396     ///                                                            path_expr_id: hir_id_L5,
397     ///                                                            capture_kind: ByValue
398     ///                                                       },
399     ///       Place(base: hir_id_p, projections: [Field(0, 0)], ...) -> {
400     ///                                                                     capture_kind_expr: hir_id_L2,
401     ///                                                                     path_expr_id: hir_id_L2,
402     ///                                                                     capture_kind: ByValue
403     ///                                                                 },
404     ///       Place(base: hir_id_p, projections: [Field(1, 0)], ...) -> {
405     ///                                                                     capture_kind_expr: hir_id_L3,
406     ///                                                                     path_expr_id: hir_id_L3,
407     ///                                                                     capture_kind: ByValue
408     ///                                                                 },
409     ///       Place(base: hir_id_p, projections: [], ...) -> {
410     ///                                                          capture_kind_expr: hir_id_L4,
411     ///                                                          path_expr_id: hir_id_L4,
412     ///                                                          capture_kind: ByValue
413     ///                                                      },
414     /// ```
415     ///
416     /// After the min capture analysis, we get:
417     /// ```
418     /// {
419     ///       hir_id_s -> [
420     ///            Place(base: hir_id_s, projections: [], ....) -> {
421     ///                                                                capture_kind_expr: hir_id_L5,
422     ///                                                                path_expr_id: hir_id_L5,
423     ///                                                                capture_kind: ByValue
424     ///                                                            },
425     ///       ],
426     ///       hir_id_p -> [
427     ///            Place(base: hir_id_p, projections: [], ...) -> {
428     ///                                                               capture_kind_expr: hir_id_L2,
429     ///                                                               path_expr_id: hir_id_L4,
430     ///                                                               capture_kind: ByValue
431     ///                                                           },
432     ///       ],
433     /// ```
434     fn compute_min_captures(
435         &self,
436         closure_def_id: DefId,
437         capture_information: InferredCaptureInformation<'tcx>,
438     ) {
439         if capture_information.is_empty() {
440             return;
441         }
442
443         let mut typeck_results = self.typeck_results.borrow_mut();
444
445         let mut root_var_min_capture_list =
446             typeck_results.closure_min_captures.remove(&closure_def_id).unwrap_or_default();
447
448         for (place, capture_info) in capture_information.into_iter() {
449             let var_hir_id = match place.base {
450                 PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
451                 base => bug!("Expected upvar, found={:?}", base),
452             };
453
454             let place = restrict_capture_precision(place, capture_info.capture_kind);
455
456             let min_cap_list = match root_var_min_capture_list.get_mut(&var_hir_id) {
457                 None => {
458                     let mutability = self.determine_capture_mutability(&typeck_results, &place);
459                     let min_cap_list =
460                         vec![ty::CapturedPlace { place, info: capture_info, mutability }];
461                     root_var_min_capture_list.insert(var_hir_id, min_cap_list);
462                     continue;
463                 }
464                 Some(min_cap_list) => min_cap_list,
465             };
466
467             // Go through each entry in the current list of min_captures
468             // - if ancestor is found, update it's capture kind to account for current place's
469             // capture information.
470             //
471             // - if descendant is found, remove it from the list, and update the current place's
472             // capture information to account for the descendants's capture kind.
473             //
474             // We can never be in a case where the list contains both an ancestor and a descendant
475             // Also there can only be ancestor but in case of descendants there might be
476             // multiple.
477
478             let mut descendant_found = false;
479             let mut updated_capture_info = capture_info;
480             min_cap_list.retain(|possible_descendant| {
481                 match determine_place_ancestry_relation(&place, &possible_descendant.place) {
482                     // current place is ancestor of possible_descendant
483                     PlaceAncestryRelation::Ancestor => {
484                         descendant_found = true;
485                         let backup_path_expr_id = updated_capture_info.path_expr_id;
486
487                         updated_capture_info =
488                             determine_capture_info(updated_capture_info, possible_descendant.info);
489
490                         // we need to keep the ancestor's `path_expr_id`
491                         updated_capture_info.path_expr_id = backup_path_expr_id;
492                         false
493                     }
494
495                     _ => true,
496                 }
497             });
498
499             let mut ancestor_found = false;
500             if !descendant_found {
501                 for possible_ancestor in min_cap_list.iter_mut() {
502                     match determine_place_ancestry_relation(&place, &possible_ancestor.place) {
503                         // current place is descendant of possible_ancestor
504                         PlaceAncestryRelation::Descendant => {
505                             ancestor_found = true;
506                             let backup_path_expr_id = possible_ancestor.info.path_expr_id;
507                             possible_ancestor.info =
508                                 determine_capture_info(possible_ancestor.info, capture_info);
509
510                             // we need to keep the ancestor's `path_expr_id`
511                             possible_ancestor.info.path_expr_id = backup_path_expr_id;
512
513                             // Only one ancestor of the current place will be in the list.
514                             break;
515                         }
516                         _ => {}
517                     }
518                 }
519             }
520
521             // Only need to insert when we don't have an ancestor in the existing min capture list
522             if !ancestor_found {
523                 let mutability = self.determine_capture_mutability(&typeck_results, &place);
524                 let captured_place =
525                     ty::CapturedPlace { place, info: updated_capture_info, mutability };
526                 min_cap_list.push(captured_place);
527             }
528         }
529
530         debug!("For closure={:?}, min_captures={:#?}", closure_def_id, root_var_min_capture_list);
531         typeck_results.closure_min_captures.insert(closure_def_id, root_var_min_capture_list);
532     }
533
534     /// Perform the migration analysis for RFC 2229, and emit lint
535     /// `disjoint_capture_drop_reorder` if needed.
536     fn perform_2229_migration_anaysis(
537         &self,
538         closure_def_id: DefId,
539         capture_clause: hir::CaptureBy,
540         span: Span,
541         body: &'tcx hir::Body<'tcx>,
542     ) {
543         let need_migrations_first_pass = self.compute_2229_migrations_first_pass(
544             closure_def_id,
545             span,
546             capture_clause,
547             body,
548             self.typeck_results.borrow().closure_min_captures.get(&closure_def_id),
549         );
550
551         let need_migrations = self.compute_2229_migrations_precise_pass(
552             closure_def_id,
553             span,
554             self.typeck_results.borrow().closure_min_captures.get(&closure_def_id),
555             &need_migrations_first_pass,
556         );
557
558         if !need_migrations.is_empty() {
559             let migrations_text = migration_suggestion_for_2229(self.tcx, &need_migrations);
560
561             let local_def_id = closure_def_id.expect_local();
562             let closure_hir_id = self.tcx.hir().local_def_id_to_hir_id(local_def_id);
563             self.tcx.struct_span_lint_hir(
564                 lint::builtin::DISJOINT_CAPTURE_DROP_REORDER,
565                 closure_hir_id,
566                 span,
567                 |lint| {
568                     let mut diagnostics_builder = lint.build(
569                         "drop order affected for closure because of `capture_disjoint_fields`",
570                     );
571                     diagnostics_builder.note(&migrations_text);
572                     diagnostics_builder.emit();
573                 },
574             );
575         }
576     }
577
578     /// Figures out the list of root variables (and their types) that aren't completely
579     /// captured by the closure when `capture_disjoint_fields` is enabled and drop order of
580     /// some path starting at that root variable **might** be affected.
581     ///
582     /// The output list would include a root variable if:
583     /// - It would have been moved into the closure when `capture_disjoint_fields` wasn't
584     ///   enabled, **and**
585     /// - It wasn't completely captured by the closure, **and**
586     /// - The type of the root variable needs Drop.
587     fn compute_2229_migrations_first_pass(
588         &self,
589         closure_def_id: DefId,
590         closure_span: Span,
591         closure_clause: hir::CaptureBy,
592         body: &'tcx hir::Body<'tcx>,
593         min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
594     ) -> Vec<(hir::HirId, Ty<'tcx>)> {
595         fn resolve_ty<T: TypeFoldable<'tcx>>(
596             fcx: &FnCtxt<'_, 'tcx>,
597             span: Span,
598             body: &'tcx hir::Body<'tcx>,
599             ty: T,
600         ) -> T {
601             let mut resolver = Resolver::new(fcx, &span, body);
602             ty.fold_with(&mut resolver)
603         }
604
605         let upvars = if let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) {
606             upvars
607         } else {
608             return vec![];
609         };
610
611         let mut need_migrations = Vec::new();
612
613         for (&var_hir_id, _) in upvars.iter() {
614             let ty = resolve_ty(self, closure_span, body, self.node_ty(var_hir_id));
615
616             if !ty.needs_drop(self.tcx, self.tcx.param_env(closure_def_id.expect_local())) {
617                 continue;
618             }
619
620             let root_var_min_capture_list = if let Some(root_var_min_capture_list) =
621                 min_captures.and_then(|m| m.get(&var_hir_id))
622             {
623                 root_var_min_capture_list
624             } else {
625                 // The upvar is mentioned within the closure but no path starting from it is
626                 // used.
627
628                 match closure_clause {
629                     // Only migrate if closure is a move closure
630                     hir::CaptureBy::Value => need_migrations.push((var_hir_id, ty)),
631
632                     hir::CaptureBy::Ref => {}
633                 }
634
635                 continue;
636             };
637
638             let is_moved = root_var_min_capture_list
639                 .iter()
640                 .any(|capture| matches!(capture.info.capture_kind, ty::UpvarCapture::ByValue(_)));
641
642             let is_not_completely_captured =
643                 root_var_min_capture_list.iter().any(|capture| capture.place.projections.len() > 0);
644
645             if is_moved && is_not_completely_captured {
646                 need_migrations.push((var_hir_id, ty));
647             }
648         }
649
650         need_migrations
651     }
652
653     fn compute_2229_migrations_precise_pass(
654         &self,
655         closure_def_id: DefId,
656         closure_span: Span,
657         min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
658         need_migrations: &[(hir::HirId, Ty<'tcx>)],
659     ) -> Vec<hir::HirId> {
660         // Need migrations -- second pass
661         let mut need_migrations_2 = Vec::new();
662
663         for (hir_id, ty) in need_migrations {
664             let projections_list = min_captures
665                 .and_then(|m| m.get(hir_id))
666                 .into_iter()
667                 .flatten()
668                 .filter_map(|captured_place| match captured_place.info.capture_kind {
669                     // Only care about captures that are moved into the closure
670                     ty::UpvarCapture::ByValue(..) => {
671                         Some(captured_place.place.projections.as_slice())
672                     }
673                     ty::UpvarCapture::ByRef(..) => None,
674                 })
675                 .collect();
676
677             if self.has_significant_drop_outside_of_captures(
678                 closure_def_id,
679                 closure_span,
680                 ty,
681                 projections_list,
682             ) {
683                 need_migrations_2.push(*hir_id);
684             }
685         }
686
687         need_migrations_2
688     }
689
690     /// This is a helper function to `compute_2229_migrations_precise_pass`. Provided the type
691     /// of a root variable and a list of captured paths starting at this root variable (expressed
692     /// using list of `Projection` slices), it returns true if there is a path that is not
693     /// captured starting at this root variable that implements Drop.
694     ///
695     /// FIXME(project-rfc-2229#35): This should return true only for significant drops.
696     ///                             A drop is significant if it's implemented by the user or does
697     ///                             anything that will have any observable behavior (other than
698     ///                             freeing up memory).
699     ///
700     /// The way this function works is at a given call it looks at type `base_path_ty` of some base
701     /// path say P and then vector of projection slices which represent the different captures
702     /// starting off of P.
703     ///
704     /// This will make more sense with an example:
705     ///
706     /// ```rust
707     /// #![feature(capture_disjoint_fields)]
708     ///
709     /// struct FancyInteger(i32); // This implements Drop
710     ///
711     /// struct Point { x: FancyInteger, y: FancyInteger }
712     /// struct Color;
713     ///
714     /// struct Wrapper { p: Point, c: Color }
715     ///
716     /// fn f(w: Wrapper) {
717     ///   let c = || {
718     ///       // Closure captures w.p.x and w.c by move.
719     ///   };
720     ///
721     ///   c();
722     /// }
723     /// ```
724     ///
725     /// If `capture_disjoint_fields` wasn't enabled the closure would've moved `w` instead of the
726     /// precise paths. If we look closely `w.p.y` isn't captured which implements Drop and
727     /// therefore Drop ordering would change and we want this function to return true.
728     ///
729     /// Call stack to figure out if we need to migrate for `w` would look as follows:
730     ///
731     /// Our initial base path is just `w`, and the paths captured from it are `w[p, x]` and
732     /// `w[c]`.
733     /// Notation:
734     /// - Ty(place): Type of place
735     /// - `(a, b)`: Represents the function parameters `base_path_ty` and `captured_projs`
736     /// respectively.
737     /// ```
738     ///                  (Ty(w), [ &[p, x], &[c] ])
739     ///                                 |
740     ///                    ----------------------------
741     ///                    |                          |
742     ///                    v                          v
743     ///        (Ty(w.p), [ &[x] ])          (Ty(w.c), [ &[] ]) // I(1)
744     ///                    |                          |
745     ///                    v                          v
746     ///        (Ty(w.p), [ &[x] ])                 false
747     ///                    |
748     ///                    |
749     ///          -------------------------------
750     ///          |                             |
751     ///          v                             v
752     ///     (Ty((w.p).x), [ &[] ])     (Ty((w.p).y), []) // IMP 2
753     ///          |                             |
754     ///          v                             v
755     ///        false                     NeedsDrop(Ty(w.p.y))
756     ///                                        |
757     ///                                        v
758     ///                                      true
759     /// ```
760     ///
761     /// IMP 1 `(Ty(w.c), [ &[] ])`: Notice the single empty slice inside `captured_projs`.
762     ///                             This implies that the `w.c` is completely captured by the closure.
763     ///                             Since drop for this path will be called when the closure is
764     ///                             dropped we don't need to migrate for it.
765     ///
766     /// IMP 2 `(Ty((w.p).y), [])`: Notice that `captured_projs` is empty. This implies that this
767     ///                             path wasn't captured by the closure. Also note that even
768     ///                             though we didn't capture this path, the function visits it,
769     ///                             which is kind of the point of this function. We then return
770     ///                             if the type of `w.p.y` implements Drop, which in this case is
771     ///                             true.
772     ///
773     /// Consider another example:
774     ///
775     /// ```rust
776     /// struct X;
777     /// impl Drop for X {}
778     ///
779     /// struct Y(X);
780     /// impl Drop for Y {}
781     ///
782     /// fn foo() {
783     ///     let y = Y(X);
784     ///     let c = || move(y.0);
785     /// }
786     /// ```
787     ///
788     /// Note that `y.0` is captured by the closure. When this function is called for `y`, it will
789     /// return true, because even though all paths starting at `y` are captured, `y` itself
790     /// implements Drop which will be affected since `y` isn't completely captured.
791     fn has_significant_drop_outside_of_captures(
792         &self,
793         closure_def_id: DefId,
794         closure_span: Span,
795         base_path_ty: Ty<'tcx>,
796         captured_projs: Vec<&[Projection<'tcx>]>,
797     ) -> bool {
798         let needs_drop = |ty: Ty<'tcx>| {
799             ty.needs_drop(self.tcx, self.tcx.param_env(closure_def_id.expect_local()))
800         };
801
802         let is_drop_defined_for_ty = |ty: Ty<'tcx>| {
803             let drop_trait = self.tcx.require_lang_item(hir::LangItem::Drop, Some(closure_span));
804             let ty_params = self.tcx.mk_substs_trait(base_path_ty, &[]);
805             self.tcx.type_implements_trait((
806                 drop_trait,
807                 ty,
808                 ty_params,
809                 self.tcx.param_env(closure_def_id.expect_local()),
810             ))
811         };
812
813         let is_drop_defined_for_ty = is_drop_defined_for_ty(base_path_ty);
814
815         // If there is a case where no projection is applied on top of current place
816         // then there must be exactly one capture corresponding to such a case. Note that this
817         // represents the case of the path being completely captured by the variable.
818         //
819         // eg. If `a.b` is captured and we are processing `a.b`, then we can't have the closure also
820         //     capture `a.b.c`, because that voilates min capture.
821         let is_completely_captured = captured_projs.iter().any(|projs| projs.is_empty());
822
823         assert!(!is_completely_captured || (captured_projs.len() == 1));
824
825         if is_drop_defined_for_ty {
826             // If drop is implemented for this type then we need it to be fully captured, or
827             // it will require migration.
828             return !is_completely_captured;
829         }
830
831         if is_completely_captured {
832             // The place is captured entirely, so doesn't matter if needs dtor, it will be drop
833             // when the closure is dropped.
834             return false;
835         }
836
837         match base_path_ty.kind() {
838             _ if captured_projs.is_empty() => needs_drop(base_path_ty),
839
840             // Observations:
841             // - `captured_projs` is not empty. Therefore we can call
842             //   `captured_projs.first().unwrap()` safely.
843             // - All entries in `captured_projs` have atleast one projection.
844             //   Therefore we can call `captured_projs.first().unwrap().first().unwrap()` safely.
845             ty::Adt(def, _) if def.is_box() => {
846                 // We must deref to access paths on top of a Box.
847                 assert!(
848                     captured_projs
849                         .iter()
850                         .all(|projs| matches!(projs.first().unwrap().kind, ProjectionKind::Deref))
851                 );
852
853                 let next_ty = captured_projs.first().unwrap().first().unwrap().ty;
854                 let captured_projs = captured_projs.iter().map(|projs| &projs[1..]).collect();
855                 self.has_significant_drop_outside_of_captures(
856                     closure_def_id,
857                     closure_span,
858                     next_ty,
859                     captured_projs,
860                 )
861             }
862
863             ty::Adt(def, substs) => {
864                 // Multi-varaint enums are captured in entirety,
865                 // which would've been handled in the case of single empty slice in `captured_projs`.
866                 assert_eq!(def.variants.len(), 1);
867
868                 // Only Field projections can be applied to a non-box Adt.
869                 assert!(
870                     captured_projs.iter().all(|projs| matches!(
871                         projs.first().unwrap().kind,
872                         ProjectionKind::Field(..)
873                     ))
874                 );
875                 def.variants.get(VariantIdx::new(0)).unwrap().fields.iter().enumerate().any(
876                     |(i, field)| {
877                         let paths_using_field = captured_projs
878                             .iter()
879                             .filter_map(|projs| {
880                                 if let ProjectionKind::Field(field_idx, _) =
881                                     projs.first().unwrap().kind
882                                 {
883                                     if (field_idx as usize) == i { Some(&projs[1..]) } else { None }
884                                 } else {
885                                     unreachable!();
886                                 }
887                             })
888                             .collect();
889
890                         let after_field_ty = field.ty(self.tcx, substs);
891                         self.has_significant_drop_outside_of_captures(
892                             closure_def_id,
893                             closure_span,
894                             after_field_ty,
895                             paths_using_field,
896                         )
897                     },
898                 )
899             }
900
901             ty::Tuple(..) => {
902                 // Only Field projections can be applied to a tuple.
903                 assert!(
904                     captured_projs.iter().all(|projs| matches!(
905                         projs.first().unwrap().kind,
906                         ProjectionKind::Field(..)
907                     ))
908                 );
909
910                 base_path_ty.tuple_fields().enumerate().any(|(i, element_ty)| {
911                     let paths_using_field = captured_projs
912                         .iter()
913                         .filter_map(|projs| {
914                             if let ProjectionKind::Field(field_idx, _) = projs.first().unwrap().kind
915                             {
916                                 if (field_idx as usize) == i { Some(&projs[1..]) } else { None }
917                             } else {
918                                 unreachable!();
919                             }
920                         })
921                         .collect();
922
923                     self.has_significant_drop_outside_of_captures(
924                         closure_def_id,
925                         closure_span,
926                         element_ty,
927                         paths_using_field,
928                     )
929                 })
930             }
931
932             ty::Ref(_, deref_ty, _) => {
933                 // Only Derefs can be applied to a Ref
934                 assert!(
935                     captured_projs
936                         .iter()
937                         .all(|projs| matches!(projs.first().unwrap().kind, ProjectionKind::Deref))
938                 );
939
940                 let captured_projs = captured_projs.iter().map(|projs| &projs[1..]).collect();
941                 self.has_significant_drop_outside_of_captures(
942                     closure_def_id,
943                     closure_span,
944                     deref_ty,
945                     captured_projs,
946                 )
947             }
948
949             // Unsafe Ptrs are captured in their entirety, which would've have been handled in
950             // the case of single empty slice in `captured_projs`.
951             ty::RawPtr(..) => unreachable!(),
952
953             _ => unreachable!(),
954         }
955     }
956
957     fn init_capture_kind(
958         &self,
959         capture_clause: hir::CaptureBy,
960         upvar_id: ty::UpvarId,
961         closure_span: Span,
962     ) -> ty::UpvarCapture<'tcx> {
963         match capture_clause {
964             hir::CaptureBy::Value => ty::UpvarCapture::ByValue(None),
965             hir::CaptureBy::Ref => {
966                 let origin = UpvarRegion(upvar_id, closure_span);
967                 let upvar_region = self.next_region_var(origin);
968                 let upvar_borrow = ty::UpvarBorrow { kind: ty::ImmBorrow, region: upvar_region };
969                 ty::UpvarCapture::ByRef(upvar_borrow)
970             }
971         }
972     }
973
974     fn place_for_root_variable(
975         &self,
976         closure_def_id: LocalDefId,
977         var_hir_id: hir::HirId,
978     ) -> Place<'tcx> {
979         let upvar_id = ty::UpvarId::new(var_hir_id, closure_def_id);
980
981         Place {
982             base_ty: self.node_ty(var_hir_id),
983             base: PlaceBase::Upvar(upvar_id),
984             projections: Default::default(),
985         }
986     }
987
988     fn should_log_capture_analysis(&self, closure_def_id: DefId) -> bool {
989         self.tcx.has_attr(closure_def_id, sym::rustc_capture_analysis)
990     }
991
992     fn log_capture_analysis_first_pass(
993         &self,
994         closure_def_id: rustc_hir::def_id::DefId,
995         capture_information: &FxIndexMap<Place<'tcx>, ty::CaptureInfo<'tcx>>,
996         closure_span: Span,
997     ) {
998         if self.should_log_capture_analysis(closure_def_id) {
999             let mut diag =
1000                 self.tcx.sess.struct_span_err(closure_span, "First Pass analysis includes:");
1001             for (place, capture_info) in capture_information {
1002                 let capture_str = construct_capture_info_string(self.tcx, place, capture_info);
1003                 let output_str = format!("Capturing {}", capture_str);
1004
1005                 let span =
1006                     capture_info.path_expr_id.map_or(closure_span, |e| self.tcx.hir().span(e));
1007                 diag.span_note(span, &output_str);
1008             }
1009             diag.emit();
1010         }
1011     }
1012
1013     fn log_closure_min_capture_info(&self, closure_def_id: DefId, closure_span: Span) {
1014         if self.should_log_capture_analysis(closure_def_id) {
1015             if let Some(min_captures) =
1016                 self.typeck_results.borrow().closure_min_captures.get(&closure_def_id)
1017             {
1018                 let mut diag =
1019                     self.tcx.sess.struct_span_err(closure_span, "Min Capture analysis includes:");
1020
1021                 for (_, min_captures_for_var) in min_captures {
1022                     for capture in min_captures_for_var {
1023                         let place = &capture.place;
1024                         let capture_info = &capture.info;
1025
1026                         let capture_str =
1027                             construct_capture_info_string(self.tcx, place, capture_info);
1028                         let output_str = format!("Min Capture {}", capture_str);
1029
1030                         if capture.info.path_expr_id != capture.info.capture_kind_expr_id {
1031                             let path_span = capture_info
1032                                 .path_expr_id
1033                                 .map_or(closure_span, |e| self.tcx.hir().span(e));
1034                             let capture_kind_span = capture_info
1035                                 .capture_kind_expr_id
1036                                 .map_or(closure_span, |e| self.tcx.hir().span(e));
1037
1038                             let mut multi_span: MultiSpan =
1039                                 MultiSpan::from_spans(vec![path_span, capture_kind_span]);
1040
1041                             let capture_kind_label =
1042                                 construct_capture_kind_reason_string(self.tcx, place, capture_info);
1043                             let path_label = construct_path_string(self.tcx, place);
1044
1045                             multi_span.push_span_label(path_span, path_label);
1046                             multi_span.push_span_label(capture_kind_span, capture_kind_label);
1047
1048                             diag.span_note(multi_span, &output_str);
1049                         } else {
1050                             let span = capture_info
1051                                 .path_expr_id
1052                                 .map_or(closure_span, |e| self.tcx.hir().span(e));
1053
1054                             diag.span_note(span, &output_str);
1055                         };
1056                     }
1057                 }
1058                 diag.emit();
1059             }
1060         }
1061     }
1062
1063     /// A captured place is mutable if
1064     /// 1. Projections don't include a Deref of an immut-borrow, **and**
1065     /// 2. PlaceBase is mut or projections include a Deref of a mut-borrow.
1066     fn determine_capture_mutability(
1067         &self,
1068         typeck_results: &'a TypeckResults<'tcx>,
1069         place: &Place<'tcx>,
1070     ) -> hir::Mutability {
1071         let var_hir_id = match place.base {
1072             PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
1073             _ => unreachable!(),
1074         };
1075
1076         let bm = *typeck_results.pat_binding_modes().get(var_hir_id).expect("missing binding mode");
1077
1078         let mut is_mutbl = match bm {
1079             ty::BindByValue(mutability) => mutability,
1080             ty::BindByReference(_) => hir::Mutability::Not,
1081         };
1082
1083         for pointer_ty in place.deref_tys() {
1084             match pointer_ty.kind() {
1085                 // We don't capture derefs of raw ptrs
1086                 ty::RawPtr(_) => unreachable!(),
1087
1088                 // Derefencing a mut-ref allows us to mut the Place if we don't deref
1089                 // an immut-ref after on top of this.
1090                 ty::Ref(.., hir::Mutability::Mut) => is_mutbl = hir::Mutability::Mut,
1091
1092                 // The place isn't mutable once we dereference a immutable reference.
1093                 ty::Ref(.., hir::Mutability::Not) => return hir::Mutability::Not,
1094
1095                 // Dereferencing a box doesn't change mutability
1096                 ty::Adt(def, ..) if def.is_box() => {}
1097
1098                 unexpected_ty => bug!("deref of unexpected pointer type {:?}", unexpected_ty),
1099             }
1100         }
1101
1102         is_mutbl
1103     }
1104 }
1105
1106 struct InferBorrowKind<'a, 'tcx> {
1107     fcx: &'a FnCtxt<'a, 'tcx>,
1108
1109     // The def-id of the closure whose kind and upvar accesses are being inferred.
1110     closure_def_id: DefId,
1111
1112     closure_span: Span,
1113
1114     capture_clause: hir::CaptureBy,
1115
1116     // The kind that we have inferred that the current closure
1117     // requires. Note that we *always* infer a minimal kind, even if
1118     // we don't always *use* that in the final result (i.e., sometimes
1119     // we've taken the closure kind from the expectations instead, and
1120     // for generators we don't even implement the closure traits
1121     // really).
1122     current_closure_kind: ty::ClosureKind,
1123
1124     // If we modified `current_closure_kind`, this field contains a `Some()` with the
1125     // variable access that caused us to do so.
1126     current_origin: Option<(Span, Place<'tcx>)>,
1127
1128     /// For each Place that is captured by the closure, we track the minimal kind of
1129     /// access we need (ref, ref mut, move, etc) and the expression that resulted in such access.
1130     ///
1131     /// Consider closure where s.str1 is captured via an ImmutableBorrow and
1132     /// s.str2 via a MutableBorrow
1133     ///
1134     /// ```rust,no_run
1135     /// struct SomeStruct { str1: String, str2: String }
1136     ///
1137     /// // Assume that the HirId for the variable definition is `V1`
1138     /// let mut s = SomeStruct { str1: format!("s1"), str2: format!("s2") }
1139     ///
1140     /// let fix_s = |new_s2| {
1141     ///     // Assume that the HirId for the expression `s.str1` is `E1`
1142     ///     println!("Updating SomeStruct with str1=", s.str1);
1143     ///     // Assume that the HirId for the expression `*s.str2` is `E2`
1144     ///     s.str2 = new_s2;
1145     /// };
1146     /// ```
1147     ///
1148     /// For closure `fix_s`, (at a high level) the map contains
1149     ///
1150     /// ```
1151     /// Place { V1, [ProjectionKind::Field(Index=0, Variant=0)] } : CaptureKind { E1, ImmutableBorrow }
1152     /// Place { V1, [ProjectionKind::Field(Index=1, Variant=0)] } : CaptureKind { E2, MutableBorrow }
1153     /// ```
1154     capture_information: InferredCaptureInformation<'tcx>,
1155 }
1156
1157 impl<'a, 'tcx> InferBorrowKind<'a, 'tcx> {
1158     fn adjust_upvar_borrow_kind_for_consume(
1159         &mut self,
1160         place_with_id: &PlaceWithHirId<'tcx>,
1161         diag_expr_id: hir::HirId,
1162         mode: euv::ConsumeMode,
1163     ) {
1164         debug!(
1165             "adjust_upvar_borrow_kind_for_consume(place_with_id={:?}, diag_expr_id={:?}, mode={:?})",
1166             place_with_id, diag_expr_id, mode
1167         );
1168
1169         // we only care about moves
1170         match mode {
1171             euv::Copy => {
1172                 return;
1173             }
1174             euv::Move => {}
1175         }
1176
1177         let tcx = self.fcx.tcx;
1178         let upvar_id = if let PlaceBase::Upvar(upvar_id) = place_with_id.place.base {
1179             upvar_id
1180         } else {
1181             return;
1182         };
1183
1184         debug!("adjust_upvar_borrow_kind_for_consume: upvar={:?}", upvar_id);
1185
1186         let usage_span = tcx.hir().span(diag_expr_id);
1187
1188         // To move out of an upvar, this must be a FnOnce closure
1189         self.adjust_closure_kind(
1190             upvar_id.closure_expr_id,
1191             ty::ClosureKind::FnOnce,
1192             usage_span,
1193             place_with_id.place.clone(),
1194         );
1195
1196         let capture_info = ty::CaptureInfo {
1197             capture_kind_expr_id: Some(diag_expr_id),
1198             path_expr_id: Some(diag_expr_id),
1199             capture_kind: ty::UpvarCapture::ByValue(Some(usage_span)),
1200         };
1201
1202         let curr_info = self.capture_information[&place_with_id.place];
1203         let updated_info = determine_capture_info(curr_info, capture_info);
1204
1205         self.capture_information[&place_with_id.place] = updated_info;
1206     }
1207
1208     /// Indicates that `place_with_id` is being directly mutated (e.g., assigned
1209     /// to). If the place is based on a by-ref upvar, this implies that
1210     /// the upvar must be borrowed using an `&mut` borrow.
1211     fn adjust_upvar_borrow_kind_for_mut(
1212         &mut self,
1213         place_with_id: &PlaceWithHirId<'tcx>,
1214         diag_expr_id: hir::HirId,
1215     ) {
1216         debug!(
1217             "adjust_upvar_borrow_kind_for_mut(place_with_id={:?}, diag_expr_id={:?})",
1218             place_with_id, diag_expr_id
1219         );
1220
1221         if let PlaceBase::Upvar(_) = place_with_id.place.base {
1222             let mut borrow_kind = ty::MutBorrow;
1223             for pointer_ty in place_with_id.place.deref_tys() {
1224                 match pointer_ty.kind() {
1225                     // Raw pointers don't inherit mutability.
1226                     ty::RawPtr(_) => return,
1227                     // assignment to deref of an `&mut`
1228                     // borrowed pointer implies that the
1229                     // pointer itself must be unique, but not
1230                     // necessarily *mutable*
1231                     ty::Ref(.., hir::Mutability::Mut) => borrow_kind = ty::UniqueImmBorrow,
1232                     _ => (),
1233                 }
1234             }
1235             self.adjust_upvar_deref(place_with_id, diag_expr_id, borrow_kind);
1236         }
1237     }
1238
1239     fn adjust_upvar_borrow_kind_for_unique(
1240         &mut self,
1241         place_with_id: &PlaceWithHirId<'tcx>,
1242         diag_expr_id: hir::HirId,
1243     ) {
1244         debug!(
1245             "adjust_upvar_borrow_kind_for_unique(place_with_id={:?}, diag_expr_id={:?})",
1246             place_with_id, diag_expr_id
1247         );
1248
1249         if let PlaceBase::Upvar(_) = place_with_id.place.base {
1250             if place_with_id.place.deref_tys().any(ty::TyS::is_unsafe_ptr) {
1251                 // Raw pointers don't inherit mutability.
1252                 return;
1253             }
1254             // for a borrowed pointer to be unique, its base must be unique
1255             self.adjust_upvar_deref(place_with_id, diag_expr_id, ty::UniqueImmBorrow);
1256         }
1257     }
1258
1259     fn adjust_upvar_deref(
1260         &mut self,
1261         place_with_id: &PlaceWithHirId<'tcx>,
1262         diag_expr_id: hir::HirId,
1263         borrow_kind: ty::BorrowKind,
1264     ) {
1265         assert!(match borrow_kind {
1266             ty::MutBorrow => true,
1267             ty::UniqueImmBorrow => true,
1268
1269             // imm borrows never require adjusting any kinds, so we don't wind up here
1270             ty::ImmBorrow => false,
1271         });
1272
1273         let tcx = self.fcx.tcx;
1274
1275         // if this is an implicit deref of an
1276         // upvar, then we need to modify the
1277         // borrow_kind of the upvar to make sure it
1278         // is inferred to mutable if necessary
1279         self.adjust_upvar_borrow_kind(place_with_id, diag_expr_id, borrow_kind);
1280
1281         if let PlaceBase::Upvar(upvar_id) = place_with_id.place.base {
1282             self.adjust_closure_kind(
1283                 upvar_id.closure_expr_id,
1284                 ty::ClosureKind::FnMut,
1285                 tcx.hir().span(diag_expr_id),
1286                 place_with_id.place.clone(),
1287             );
1288         }
1289     }
1290
1291     /// We infer the borrow_kind with which to borrow upvars in a stack closure.
1292     /// The borrow_kind basically follows a lattice of `imm < unique-imm < mut`,
1293     /// moving from left to right as needed (but never right to left).
1294     /// Here the argument `mutbl` is the borrow_kind that is required by
1295     /// some particular use.
1296     fn adjust_upvar_borrow_kind(
1297         &mut self,
1298         place_with_id: &PlaceWithHirId<'tcx>,
1299         diag_expr_id: hir::HirId,
1300         kind: ty::BorrowKind,
1301     ) {
1302         let curr_capture_info = self.capture_information[&place_with_id.place];
1303
1304         debug!(
1305             "adjust_upvar_borrow_kind(place={:?}, diag_expr_id={:?}, capture_info={:?}, kind={:?})",
1306             place_with_id, diag_expr_id, curr_capture_info, kind
1307         );
1308
1309         if let ty::UpvarCapture::ByValue(_) = curr_capture_info.capture_kind {
1310             // It's already captured by value, we don't need to do anything here
1311             return;
1312         } else if let ty::UpvarCapture::ByRef(curr_upvar_borrow) = curr_capture_info.capture_kind {
1313             // Use the same region as the current capture information
1314             // Doesn't matter since only one of the UpvarBorrow will be used.
1315             let new_upvar_borrow = ty::UpvarBorrow { kind, region: curr_upvar_borrow.region };
1316
1317             let capture_info = ty::CaptureInfo {
1318                 capture_kind_expr_id: Some(diag_expr_id),
1319                 path_expr_id: Some(diag_expr_id),
1320                 capture_kind: ty::UpvarCapture::ByRef(new_upvar_borrow),
1321             };
1322             let updated_info = determine_capture_info(curr_capture_info, capture_info);
1323             self.capture_information[&place_with_id.place] = updated_info;
1324         };
1325     }
1326
1327     fn adjust_closure_kind(
1328         &mut self,
1329         closure_id: LocalDefId,
1330         new_kind: ty::ClosureKind,
1331         upvar_span: Span,
1332         place: Place<'tcx>,
1333     ) {
1334         debug!(
1335             "adjust_closure_kind(closure_id={:?}, new_kind={:?}, upvar_span={:?}, place={:?})",
1336             closure_id, new_kind, upvar_span, place
1337         );
1338
1339         // Is this the closure whose kind is currently being inferred?
1340         if closure_id.to_def_id() != self.closure_def_id {
1341             debug!("adjust_closure_kind: not current closure");
1342             return;
1343         }
1344
1345         // closures start out as `Fn`.
1346         let existing_kind = self.current_closure_kind;
1347
1348         debug!(
1349             "adjust_closure_kind: closure_id={:?}, existing_kind={:?}, new_kind={:?}",
1350             closure_id, existing_kind, new_kind
1351         );
1352
1353         match (existing_kind, new_kind) {
1354             (ty::ClosureKind::Fn, ty::ClosureKind::Fn)
1355             | (ty::ClosureKind::FnMut, ty::ClosureKind::Fn | ty::ClosureKind::FnMut)
1356             | (ty::ClosureKind::FnOnce, _) => {
1357                 // no change needed
1358             }
1359
1360             (ty::ClosureKind::Fn, ty::ClosureKind::FnMut | ty::ClosureKind::FnOnce)
1361             | (ty::ClosureKind::FnMut, ty::ClosureKind::FnOnce) => {
1362                 // new kind is stronger than the old kind
1363                 self.current_closure_kind = new_kind;
1364                 self.current_origin = Some((upvar_span, place));
1365             }
1366         }
1367     }
1368
1369     fn init_capture_info_for_place(
1370         &mut self,
1371         place_with_id: &PlaceWithHirId<'tcx>,
1372         diag_expr_id: hir::HirId,
1373     ) {
1374         if let PlaceBase::Upvar(upvar_id) = place_with_id.place.base {
1375             assert_eq!(self.closure_def_id.expect_local(), upvar_id.closure_expr_id);
1376
1377             let capture_kind =
1378                 self.fcx.init_capture_kind(self.capture_clause, upvar_id, self.closure_span);
1379
1380             let expr_id = Some(diag_expr_id);
1381             let capture_info = ty::CaptureInfo {
1382                 capture_kind_expr_id: expr_id,
1383                 path_expr_id: expr_id,
1384                 capture_kind,
1385             };
1386
1387             debug!("Capturing new place {:?}, capture_info={:?}", place_with_id, capture_info);
1388
1389             self.capture_information.insert(place_with_id.place.clone(), capture_info);
1390         } else {
1391             debug!("Not upvar: {:?}", place_with_id);
1392         }
1393     }
1394 }
1395
1396 impl<'a, 'tcx> euv::Delegate<'tcx> for InferBorrowKind<'a, 'tcx> {
1397     fn consume(
1398         &mut self,
1399         place_with_id: &PlaceWithHirId<'tcx>,
1400         diag_expr_id: hir::HirId,
1401         mode: euv::ConsumeMode,
1402     ) {
1403         debug!(
1404             "consume(place_with_id={:?}, diag_expr_id={:?}, mode={:?})",
1405             place_with_id, diag_expr_id, mode
1406         );
1407         if !self.capture_information.contains_key(&place_with_id.place) {
1408             self.init_capture_info_for_place(place_with_id, diag_expr_id);
1409         }
1410
1411         self.adjust_upvar_borrow_kind_for_consume(place_with_id, diag_expr_id, mode);
1412     }
1413
1414     fn borrow(
1415         &mut self,
1416         place_with_id: &PlaceWithHirId<'tcx>,
1417         diag_expr_id: hir::HirId,
1418         bk: ty::BorrowKind,
1419     ) {
1420         debug!(
1421             "borrow(place_with_id={:?}, diag_expr_id={:?}, bk={:?})",
1422             place_with_id, diag_expr_id, bk
1423         );
1424
1425         if !self.capture_information.contains_key(&place_with_id.place) {
1426             self.init_capture_info_for_place(place_with_id, diag_expr_id);
1427         }
1428
1429         match bk {
1430             ty::ImmBorrow => {}
1431             ty::UniqueImmBorrow => {
1432                 self.adjust_upvar_borrow_kind_for_unique(&place_with_id, diag_expr_id);
1433             }
1434             ty::MutBorrow => {
1435                 self.adjust_upvar_borrow_kind_for_mut(&place_with_id, diag_expr_id);
1436             }
1437         }
1438     }
1439
1440     fn mutate(&mut self, assignee_place: &PlaceWithHirId<'tcx>, diag_expr_id: hir::HirId) {
1441         debug!("mutate(assignee_place={:?}, diag_expr_id={:?})", assignee_place, diag_expr_id);
1442
1443         if !self.capture_information.contains_key(&assignee_place.place) {
1444             self.init_capture_info_for_place(assignee_place, diag_expr_id);
1445         }
1446
1447         self.adjust_upvar_borrow_kind_for_mut(assignee_place, diag_expr_id);
1448     }
1449 }
1450
1451 /// Truncate projections so that following rules are obeyed by the captured `place`:
1452 ///
1453 /// - No Derefs in move closure, this will result in value behind a reference getting moved.
1454 /// - No projections are applied to raw pointers, since these require unsafe blocks. We capture
1455 ///   them completely.
1456 /// - No Index projections are captured, since arrays are captured completely.
1457 fn restrict_capture_precision<'tcx>(
1458     mut place: Place<'tcx>,
1459     capture_kind: ty::UpvarCapture<'tcx>,
1460 ) -> Place<'tcx> {
1461     if place.projections.is_empty() {
1462         // Nothing to do here
1463         return place;
1464     }
1465
1466     if place.base_ty.is_unsafe_ptr() {
1467         place.projections.truncate(0);
1468         return place;
1469     }
1470
1471     let mut truncated_length = usize::MAX;
1472     let mut first_deref_projection = usize::MAX;
1473
1474     for (i, proj) in place.projections.iter().enumerate() {
1475         if proj.ty.is_unsafe_ptr() {
1476             // Don't apply any projections on top of an unsafe ptr
1477             truncated_length = truncated_length.min(i + 1);
1478             break;
1479         }
1480         match proj.kind {
1481             ProjectionKind::Index => {
1482                 // Arrays are completely captured, so we drop Index projections
1483                 truncated_length = truncated_length.min(i);
1484                 break;
1485             }
1486             ProjectionKind::Deref => {
1487                 // We only drop Derefs in case of move closures
1488                 // There might be an index projection or raw ptr ahead, so we don't stop here.
1489                 first_deref_projection = first_deref_projection.min(i);
1490             }
1491             ProjectionKind::Field(..) => {} // ignore
1492             ProjectionKind::Subslice => {}  // We never capture this
1493         }
1494     }
1495
1496     let length = place
1497         .projections
1498         .len()
1499         .min(truncated_length)
1500         // In case of capture `ByValue` we want to not capture derefs
1501         .min(match capture_kind {
1502             ty::UpvarCapture::ByValue(..) => first_deref_projection,
1503             ty::UpvarCapture::ByRef(..) => usize::MAX,
1504         });
1505
1506     place.projections.truncate(length);
1507
1508     place
1509 }
1510
1511 fn construct_place_string(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
1512     let variable_name = match place.base {
1513         PlaceBase::Upvar(upvar_id) => var_name(tcx, upvar_id.var_path.hir_id).to_string(),
1514         _ => bug!("Capture_information should only contain upvars"),
1515     };
1516
1517     let mut projections_str = String::new();
1518     for (i, item) in place.projections.iter().enumerate() {
1519         let proj = match item.kind {
1520             ProjectionKind::Field(a, b) => format!("({:?}, {:?})", a, b),
1521             ProjectionKind::Deref => String::from("Deref"),
1522             ProjectionKind::Index => String::from("Index"),
1523             ProjectionKind::Subslice => String::from("Subslice"),
1524         };
1525         if i != 0 {
1526             projections_str.push_str(",");
1527         }
1528         projections_str.push_str(proj.as_str());
1529     }
1530
1531     format!("{}[{}]", variable_name, projections_str)
1532 }
1533
1534 fn construct_capture_kind_reason_string(
1535     tcx: TyCtxt<'_>,
1536     place: &Place<'tcx>,
1537     capture_info: &ty::CaptureInfo<'tcx>,
1538 ) -> String {
1539     let place_str = construct_place_string(tcx, &place);
1540
1541     let capture_kind_str = match capture_info.capture_kind {
1542         ty::UpvarCapture::ByValue(_) => "ByValue".into(),
1543         ty::UpvarCapture::ByRef(borrow) => format!("{:?}", borrow.kind),
1544     };
1545
1546     format!("{} captured as {} here", place_str, capture_kind_str)
1547 }
1548
1549 fn construct_path_string(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
1550     let place_str = construct_place_string(tcx, &place);
1551
1552     format!("{} used here", place_str)
1553 }
1554
1555 fn construct_capture_info_string(
1556     tcx: TyCtxt<'_>,
1557     place: &Place<'tcx>,
1558     capture_info: &ty::CaptureInfo<'tcx>,
1559 ) -> String {
1560     let place_str = construct_place_string(tcx, &place);
1561
1562     let capture_kind_str = match capture_info.capture_kind {
1563         ty::UpvarCapture::ByValue(_) => "ByValue".into(),
1564         ty::UpvarCapture::ByRef(borrow) => format!("{:?}", borrow.kind),
1565     };
1566     format!("{} -> {}", place_str, capture_kind_str)
1567 }
1568
1569 fn var_name(tcx: TyCtxt<'_>, var_hir_id: hir::HirId) -> Symbol {
1570     tcx.hir().name(var_hir_id)
1571 }
1572
1573 fn should_do_migration_analysis(tcx: TyCtxt<'_>, closure_id: hir::HirId) -> bool {
1574     let (level, _) =
1575         tcx.lint_level_at_node(lint::builtin::DISJOINT_CAPTURE_DROP_REORDER, closure_id);
1576
1577     !matches!(level, lint::Level::Allow)
1578 }
1579
1580 fn migration_suggestion_for_2229(tcx: TyCtxt<'_>, need_migrations: &Vec<hir::HirId>) -> String {
1581     let need_migrations_strings =
1582         need_migrations.iter().map(|v| format!("{}", var_name(tcx, *v))).collect::<Vec<_>>();
1583     let migrations_list_concat = need_migrations_strings.join(", ");
1584
1585     format!("drop(&({}));", migrations_list_concat)
1586 }
1587
1588 /// Helper function to determine if we need to escalate CaptureKind from
1589 /// CaptureInfo A to B and returns the escalated CaptureInfo.
1590 /// (Note: CaptureInfo contains CaptureKind and an expression that led to capture it in that way)
1591 ///
1592 /// If both `CaptureKind`s are considered equivalent, then the CaptureInfo is selected based
1593 /// on the `CaptureInfo` containing an associated `capture_kind_expr_id`.
1594 ///
1595 /// It is the caller's duty to figure out which path_expr_id to use.
1596 ///
1597 /// If both the CaptureKind and Expression are considered to be equivalent,
1598 /// then `CaptureInfo` A is preferred. This can be useful in cases where we want to priortize
1599 /// expressions reported back to the user as part of diagnostics based on which appears earlier
1600 /// in the closure. This can be acheived simply by calling
1601 /// `determine_capture_info(existing_info, current_info)`. This works out because the
1602 /// expressions that occur earlier in the closure body than the current expression are processed before.
1603 /// Consider the following example
1604 /// ```rust,no_run
1605 /// struct Point { x: i32, y: i32 }
1606 /// let mut p: Point { x: 10, y: 10 };
1607 ///
1608 /// let c = || {
1609 ///     p.x     += 10;
1610 /// // ^ E1 ^
1611 ///     // ...
1612 ///     // More code
1613 ///     // ...
1614 ///     p.x += 10; // E2
1615 /// // ^ E2 ^
1616 /// };
1617 /// ```
1618 /// `CaptureKind` associated with both `E1` and `E2` will be ByRef(MutBorrow),
1619 /// and both have an expression associated, however for diagnostics we prefer reporting
1620 /// `E1` since it appears earlier in the closure body. When `E2` is being processed we
1621 /// would've already handled `E1`, and have an existing capture_information for it.
1622 /// Calling `determine_capture_info(existing_info_e1, current_info_e2)` will return
1623 /// `existing_info_e1` in this case, allowing us to point to `E1` in case of diagnostics.
1624 fn determine_capture_info(
1625     capture_info_a: ty::CaptureInfo<'tcx>,
1626     capture_info_b: ty::CaptureInfo<'tcx>,
1627 ) -> ty::CaptureInfo<'tcx> {
1628     // If the capture kind is equivalent then, we don't need to escalate and can compare the
1629     // expressions.
1630     let eq_capture_kind = match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
1631         (ty::UpvarCapture::ByValue(_), ty::UpvarCapture::ByValue(_)) => {
1632             // We don't need to worry about the spans being ignored here.
1633             //
1634             // The expr_id in capture_info corresponds to the span that is stored within
1635             // ByValue(span) and therefore it gets handled with priortizing based on
1636             // expressions below.
1637             true
1638         }
1639         (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => {
1640             ref_a.kind == ref_b.kind
1641         }
1642         (ty::UpvarCapture::ByValue(_), _) | (ty::UpvarCapture::ByRef(_), _) => false,
1643     };
1644
1645     if eq_capture_kind {
1646         match (capture_info_a.capture_kind_expr_id, capture_info_b.capture_kind_expr_id) {
1647             (Some(_), _) | (None, None) => capture_info_a,
1648             (None, Some(_)) => capture_info_b,
1649         }
1650     } else {
1651         // We select the CaptureKind which ranks higher based the following priority order:
1652         // ByValue > MutBorrow > UniqueImmBorrow > ImmBorrow
1653         match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
1654             (ty::UpvarCapture::ByValue(_), _) => capture_info_a,
1655             (_, ty::UpvarCapture::ByValue(_)) => capture_info_b,
1656             (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => {
1657                 match (ref_a.kind, ref_b.kind) {
1658                     // Take LHS:
1659                     (ty::UniqueImmBorrow | ty::MutBorrow, ty::ImmBorrow)
1660                     | (ty::MutBorrow, ty::UniqueImmBorrow) => capture_info_a,
1661
1662                     // Take RHS:
1663                     (ty::ImmBorrow, ty::UniqueImmBorrow | ty::MutBorrow)
1664                     | (ty::UniqueImmBorrow, ty::MutBorrow) => capture_info_b,
1665
1666                     (ty::ImmBorrow, ty::ImmBorrow)
1667                     | (ty::UniqueImmBorrow, ty::UniqueImmBorrow)
1668                     | (ty::MutBorrow, ty::MutBorrow) => {
1669                         bug!("Expected unequal capture kinds");
1670                     }
1671                 }
1672             }
1673         }
1674     }
1675 }
1676
1677 /// Determines the Ancestry relationship of Place A relative to Place B
1678 ///
1679 /// `PlaceAncestryRelation::Ancestor` implies Place A is ancestor of Place B
1680 /// `PlaceAncestryRelation::Descendant` implies Place A is descendant of Place B
1681 /// `PlaceAncestryRelation::Divergent` implies neither of them is the ancestor of the other.
1682 fn determine_place_ancestry_relation(
1683     place_a: &Place<'tcx>,
1684     place_b: &Place<'tcx>,
1685 ) -> PlaceAncestryRelation {
1686     // If Place A and Place B, don't start off from the same root variable, they are divergent.
1687     if place_a.base != place_b.base {
1688         return PlaceAncestryRelation::Divergent;
1689     }
1690
1691     // Assume of length of projections_a = n
1692     let projections_a = &place_a.projections;
1693
1694     // Assume of length of projections_b = m
1695     let projections_b = &place_b.projections;
1696
1697     let mut same_initial_projections = true;
1698
1699     for (proj_a, proj_b) in projections_a.iter().zip(projections_b.iter()) {
1700         if proj_a != proj_b {
1701             same_initial_projections = false;
1702             break;
1703         }
1704     }
1705
1706     if same_initial_projections {
1707         // First min(n, m) projections are the same
1708         // Select Ancestor/Descendant
1709         if projections_b.len() >= projections_a.len() {
1710             PlaceAncestryRelation::Ancestor
1711         } else {
1712             PlaceAncestryRelation::Descendant
1713         }
1714     } else {
1715         PlaceAncestryRelation::Divergent
1716     }
1717 }