]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/upvar.rs
Auto merge of #72562 - RalfJung:rollup-2ngjgwi, r=RalfJung
[rust.git] / src / librustc_typeck / 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 crate::mem_categorization as mc;
37 use crate::mem_categorization::PlaceBase;
38 use rustc_data_structures::fx::FxIndexMap;
39 use rustc_hir as hir;
40 use rustc_hir::def_id::DefId;
41 use rustc_hir::def_id::LocalDefId;
42 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
43 use rustc_infer::infer::UpvarRegion;
44 use rustc_middle::ty::{self, Ty, TyCtxt, UpvarSubsts};
45 use rustc_span::{Span, Symbol};
46
47 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
48     pub fn closure_analyze(&self, body: &'tcx hir::Body<'tcx>) {
49         InferBorrowKindVisitor { fcx: self }.visit_body(body);
50
51         // it's our job to process these.
52         assert!(self.deferred_call_resolutions.borrow().is_empty());
53     }
54 }
55
56 struct InferBorrowKindVisitor<'a, 'tcx> {
57     fcx: &'a FnCtxt<'a, 'tcx>,
58 }
59
60 impl<'a, 'tcx> Visitor<'tcx> for InferBorrowKindVisitor<'a, 'tcx> {
61     type Map = intravisit::ErasedMap<'tcx>;
62
63     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
64         NestedVisitorMap::None
65     }
66
67     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
68         if let hir::ExprKind::Closure(cc, _, body_id, _, _) = expr.kind {
69             let body = self.fcx.tcx.hir().body(body_id);
70             self.visit_body(body);
71             self.fcx.analyze_closure(expr.hir_id, expr.span, body, cc);
72         }
73
74         intravisit::walk_expr(self, expr);
75     }
76 }
77
78 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
79     /// Analysis starting point.
80     fn analyze_closure(
81         &self,
82         closure_hir_id: hir::HirId,
83         span: Span,
84         body: &hir::Body<'_>,
85         capture_clause: hir::CaptureBy,
86     ) {
87         debug!("analyze_closure(id={:?}, body.id={:?})", closure_hir_id, body.id());
88
89         // Extract the type of the closure.
90         let ty = self.node_ty(closure_hir_id);
91         let (closure_def_id, substs) = match ty.kind {
92             ty::Closure(def_id, substs) => (def_id, UpvarSubsts::Closure(substs)),
93             ty::Generator(def_id, substs, _) => (def_id, UpvarSubsts::Generator(substs)),
94             ty::Error => {
95                 // #51714: skip analysis when we have already encountered type errors
96                 return;
97             }
98             _ => {
99                 span_bug!(
100                     span,
101                     "type of closure expr {:?} is not a closure {:?}",
102                     closure_hir_id,
103                     ty
104                 );
105             }
106         };
107
108         let infer_kind = if let UpvarSubsts::Closure(closure_substs) = substs {
109             self.closure_kind(closure_substs).is_none().then_some(closure_substs)
110         } else {
111             None
112         };
113
114         if let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) {
115             let mut upvar_list: FxIndexMap<hir::HirId, ty::UpvarId> =
116                 FxIndexMap::with_capacity_and_hasher(upvars.len(), Default::default());
117             for (&var_hir_id, _) in upvars.iter() {
118                 let upvar_id = ty::UpvarId {
119                     var_path: ty::UpvarPath { hir_id: var_hir_id },
120                     closure_expr_id: closure_def_id.expect_local(),
121                 };
122                 debug!("seed upvar_id {:?}", upvar_id);
123                 // Adding the upvar Id to the list of Upvars, which will be added
124                 // to the map for the closure at the end of the for loop.
125                 upvar_list.insert(var_hir_id, upvar_id);
126
127                 let capture_kind = match capture_clause {
128                     hir::CaptureBy::Value => ty::UpvarCapture::ByValue,
129                     hir::CaptureBy::Ref => {
130                         let origin = UpvarRegion(upvar_id, span);
131                         let upvar_region = self.next_region_var(origin);
132                         let upvar_borrow =
133                             ty::UpvarBorrow { kind: ty::ImmBorrow, region: upvar_region };
134                         ty::UpvarCapture::ByRef(upvar_borrow)
135                     }
136                 };
137
138                 self.tables.borrow_mut().upvar_capture_map.insert(upvar_id, capture_kind);
139             }
140             // Add the vector of upvars to the map keyed with the closure id.
141             // This gives us an easier access to them without having to call
142             // tcx.upvars again..
143             if !upvar_list.is_empty() {
144                 self.tables.borrow_mut().upvar_list.insert(closure_def_id, upvar_list);
145             }
146         }
147
148         let body_owner_def_id = self.tcx.hir().body_owner_def_id(body.id());
149         assert_eq!(body_owner_def_id.to_def_id(), closure_def_id);
150         let mut delegate = InferBorrowKind {
151             fcx: self,
152             closure_def_id,
153             current_closure_kind: ty::ClosureKind::LATTICE_BOTTOM,
154             current_origin: None,
155             adjust_upvar_captures: ty::UpvarCaptureMap::default(),
156         };
157         euv::ExprUseVisitor::new(
158             &mut delegate,
159             &self.infcx,
160             body_owner_def_id,
161             self.param_env,
162             &self.tables.borrow(),
163         )
164         .consume_body(body);
165
166         if let Some(closure_substs) = infer_kind {
167             // Unify the (as yet unbound) type variable in the closure
168             // substs with the kind we inferred.
169             let inferred_kind = delegate.current_closure_kind;
170             let closure_kind_ty = closure_substs.as_closure().kind_ty();
171             self.demand_eqtype(span, inferred_kind.to_ty(self.tcx), closure_kind_ty);
172
173             // If we have an origin, store it.
174             if let Some(origin) = delegate.current_origin {
175                 self.tables.borrow_mut().closure_kind_origins_mut().insert(closure_hir_id, origin);
176             }
177         }
178
179         self.tables.borrow_mut().upvar_capture_map.extend(delegate.adjust_upvar_captures);
180
181         // Now that we've analyzed the closure, we know how each
182         // variable is borrowed, and we know what traits the closure
183         // implements (Fn vs FnMut etc). We now have some updates to do
184         // with that information.
185         //
186         // Note that no closure type C may have an upvar of type C
187         // (though it may reference itself via a trait object). This
188         // results from the desugaring of closures to a struct like
189         // `Foo<..., UV0...UVn>`. If one of those upvars referenced
190         // C, then the type would have infinite size (and the
191         // inference algorithm will reject it).
192
193         // Equate the type variables for the upvars with the actual types.
194         let final_upvar_tys = self.final_upvar_tys(closure_hir_id);
195         debug!(
196             "analyze_closure: id={:?} substs={:?} final_upvar_tys={:?}",
197             closure_hir_id, substs, final_upvar_tys
198         );
199         for (upvar_ty, final_upvar_ty) in substs.upvar_tys().zip(final_upvar_tys) {
200             self.demand_suptype(span, upvar_ty, final_upvar_ty);
201         }
202
203         // If we are also inferred the closure kind here,
204         // process any deferred resolutions.
205         let deferred_call_resolutions = self.remove_deferred_call_resolutions(closure_def_id);
206         for deferred_call_resolution in deferred_call_resolutions {
207             deferred_call_resolution.resolve(self);
208         }
209     }
210
211     // Returns a list of `Ty`s for each upvar.
212     fn final_upvar_tys(&self, closure_id: hir::HirId) -> Vec<Ty<'tcx>> {
213         // Presently an unboxed closure type cannot "escape" out of a
214         // function, so we will only encounter ones that originated in the
215         // local crate or were inlined into it along with some function.
216         // This may change if abstract return types of some sort are
217         // implemented.
218         let tcx = self.tcx;
219         let closure_def_id = tcx.hir().local_def_id(closure_id);
220
221         tcx.upvars_mentioned(closure_def_id)
222             .iter()
223             .flat_map(|upvars| {
224                 upvars.iter().map(|(&var_hir_id, _)| {
225                     let upvar_ty = self.node_ty(var_hir_id);
226                     let upvar_id = ty::UpvarId {
227                         var_path: ty::UpvarPath { hir_id: var_hir_id },
228                         closure_expr_id: closure_def_id,
229                     };
230                     let capture = self.tables.borrow().upvar_capture(upvar_id);
231
232                     debug!("var_id={:?} upvar_ty={:?} capture={:?}", var_hir_id, upvar_ty, capture);
233
234                     match capture {
235                         ty::UpvarCapture::ByValue => upvar_ty,
236                         ty::UpvarCapture::ByRef(borrow) => tcx.mk_ref(
237                             borrow.region,
238                             ty::TypeAndMut { ty: upvar_ty, mutbl: borrow.kind.to_mutbl_lossy() },
239                         ),
240                     }
241                 })
242             })
243             .collect()
244     }
245 }
246
247 struct InferBorrowKind<'a, 'tcx> {
248     fcx: &'a FnCtxt<'a, 'tcx>,
249
250     // The def-id of the closure whose kind and upvar accesses are being inferred.
251     closure_def_id: DefId,
252
253     // The kind that we have inferred that the current closure
254     // requires. Note that we *always* infer a minimal kind, even if
255     // we don't always *use* that in the final result (i.e., sometimes
256     // we've taken the closure kind from the expectations instead, and
257     // for generators we don't even implement the closure traits
258     // really).
259     current_closure_kind: ty::ClosureKind,
260
261     // If we modified `current_closure_kind`, this field contains a `Some()` with the
262     // variable access that caused us to do so.
263     current_origin: Option<(Span, Symbol)>,
264
265     // For each upvar that we access, we track the minimal kind of
266     // access we need (ref, ref mut, move, etc).
267     adjust_upvar_captures: ty::UpvarCaptureMap<'tcx>,
268 }
269
270 impl<'a, 'tcx> InferBorrowKind<'a, 'tcx> {
271     fn adjust_upvar_borrow_kind_for_consume(
272         &mut self,
273         place: &mc::Place<'tcx>,
274         mode: euv::ConsumeMode,
275     ) {
276         debug!("adjust_upvar_borrow_kind_for_consume(place={:?}, mode={:?})", place, mode);
277
278         // we only care about moves
279         match mode {
280             euv::Copy => {
281                 return;
282             }
283             euv::Move => {}
284         }
285
286         let tcx = self.fcx.tcx;
287         let upvar_id = if let PlaceBase::Upvar(upvar_id) = place.base {
288             upvar_id
289         } else {
290             return;
291         };
292
293         debug!("adjust_upvar_borrow_kind_for_consume: upvar={:?}", upvar_id);
294
295         // To move out of an upvar, this must be a FnOnce closure
296         self.adjust_closure_kind(
297             upvar_id.closure_expr_id,
298             ty::ClosureKind::FnOnce,
299             place.span,
300             var_name(tcx, upvar_id.var_path.hir_id),
301         );
302
303         self.adjust_upvar_captures.insert(upvar_id, ty::UpvarCapture::ByValue);
304     }
305
306     /// Indicates that `place` is being directly mutated (e.g., assigned
307     /// to). If the place is based on a by-ref upvar, this implies that
308     /// the upvar must be borrowed using an `&mut` borrow.
309     fn adjust_upvar_borrow_kind_for_mut(&mut self, place: &mc::Place<'tcx>) {
310         debug!("adjust_upvar_borrow_kind_for_mut(place={:?})", place);
311
312         if let PlaceBase::Upvar(upvar_id) = place.base {
313             let mut borrow_kind = ty::MutBorrow;
314             for pointer_ty in place.deref_tys() {
315                 match pointer_ty.kind {
316                     // Raw pointers don't inherit mutability.
317                     ty::RawPtr(_) => return,
318                     // assignment to deref of an `&mut`
319                     // borrowed pointer implies that the
320                     // pointer itself must be unique, but not
321                     // necessarily *mutable*
322                     ty::Ref(.., hir::Mutability::Mut) => borrow_kind = ty::UniqueImmBorrow,
323                     _ => (),
324                 }
325             }
326             self.adjust_upvar_deref(upvar_id, place.span, borrow_kind);
327         }
328     }
329
330     fn adjust_upvar_borrow_kind_for_unique(&mut self, place: &mc::Place<'tcx>) {
331         debug!("adjust_upvar_borrow_kind_for_unique(place={:?})", place);
332
333         if let PlaceBase::Upvar(upvar_id) = place.base {
334             if place.deref_tys().any(ty::TyS::is_unsafe_ptr) {
335                 // Raw pointers don't inherit mutability.
336                 return;
337             }
338             // for a borrowed pointer to be unique, its base must be unique
339             self.adjust_upvar_deref(upvar_id, place.span, ty::UniqueImmBorrow);
340         }
341     }
342
343     fn adjust_upvar_deref(
344         &mut self,
345         upvar_id: ty::UpvarId,
346         place_span: Span,
347         borrow_kind: ty::BorrowKind,
348     ) {
349         assert!(match borrow_kind {
350             ty::MutBorrow => true,
351             ty::UniqueImmBorrow => true,
352
353             // imm borrows never require adjusting any kinds, so we don't wind up here
354             ty::ImmBorrow => false,
355         });
356
357         let tcx = self.fcx.tcx;
358
359         // if this is an implicit deref of an
360         // upvar, then we need to modify the
361         // borrow_kind of the upvar to make sure it
362         // is inferred to mutable if necessary
363         self.adjust_upvar_borrow_kind(upvar_id, borrow_kind);
364
365         // also need to be in an FnMut closure since this is not an ImmBorrow
366         self.adjust_closure_kind(
367             upvar_id.closure_expr_id,
368             ty::ClosureKind::FnMut,
369             place_span,
370             var_name(tcx, upvar_id.var_path.hir_id),
371         );
372     }
373
374     /// We infer the borrow_kind with which to borrow upvars in a stack closure.
375     /// The borrow_kind basically follows a lattice of `imm < unique-imm < mut`,
376     /// moving from left to right as needed (but never right to left).
377     /// Here the argument `mutbl` is the borrow_kind that is required by
378     /// some particular use.
379     fn adjust_upvar_borrow_kind(&mut self, upvar_id: ty::UpvarId, kind: ty::BorrowKind) {
380         let upvar_capture = self
381             .adjust_upvar_captures
382             .get(&upvar_id)
383             .copied()
384             .unwrap_or_else(|| self.fcx.tables.borrow().upvar_capture(upvar_id));
385         debug!(
386             "adjust_upvar_borrow_kind(upvar_id={:?}, upvar_capture={:?}, kind={:?})",
387             upvar_id, upvar_capture, kind
388         );
389
390         match upvar_capture {
391             ty::UpvarCapture::ByValue => {
392                 // Upvar is already by-value, the strongest criteria.
393             }
394             ty::UpvarCapture::ByRef(mut upvar_borrow) => {
395                 match (upvar_borrow.kind, kind) {
396                     // Take RHS:
397                     (ty::ImmBorrow, ty::UniqueImmBorrow | ty::MutBorrow)
398                     | (ty::UniqueImmBorrow, ty::MutBorrow) => {
399                         upvar_borrow.kind = kind;
400                         self.adjust_upvar_captures
401                             .insert(upvar_id, ty::UpvarCapture::ByRef(upvar_borrow));
402                     }
403                     // Take LHS:
404                     (ty::ImmBorrow, ty::ImmBorrow)
405                     | (ty::UniqueImmBorrow, ty::ImmBorrow | ty::UniqueImmBorrow)
406                     | (ty::MutBorrow, _) => {}
407                 }
408             }
409         }
410     }
411
412     fn adjust_closure_kind(
413         &mut self,
414         closure_id: LocalDefId,
415         new_kind: ty::ClosureKind,
416         upvar_span: Span,
417         var_name: Symbol,
418     ) {
419         debug!(
420             "adjust_closure_kind(closure_id={:?}, new_kind={:?}, upvar_span={:?}, var_name={})",
421             closure_id, new_kind, upvar_span, var_name
422         );
423
424         // Is this the closure whose kind is currently being inferred?
425         if closure_id.to_def_id() != self.closure_def_id {
426             debug!("adjust_closure_kind: not current closure");
427             return;
428         }
429
430         // closures start out as `Fn`.
431         let existing_kind = self.current_closure_kind;
432
433         debug!(
434             "adjust_closure_kind: closure_id={:?}, existing_kind={:?}, new_kind={:?}",
435             closure_id, existing_kind, new_kind
436         );
437
438         match (existing_kind, new_kind) {
439             (ty::ClosureKind::Fn, ty::ClosureKind::Fn)
440             | (ty::ClosureKind::FnMut, ty::ClosureKind::Fn | ty::ClosureKind::FnMut)
441             | (ty::ClosureKind::FnOnce, _) => {
442                 // no change needed
443             }
444
445             (ty::ClosureKind::Fn, ty::ClosureKind::FnMut | ty::ClosureKind::FnOnce)
446             | (ty::ClosureKind::FnMut, ty::ClosureKind::FnOnce) => {
447                 // new kind is stronger than the old kind
448                 self.current_closure_kind = new_kind;
449                 self.current_origin = Some((upvar_span, var_name));
450             }
451         }
452     }
453 }
454
455 impl<'a, 'tcx> euv::Delegate<'tcx> for InferBorrowKind<'a, 'tcx> {
456     fn consume(&mut self, place: &mc::Place<'tcx>, mode: euv::ConsumeMode) {
457         debug!("consume(place={:?},mode={:?})", place, mode);
458         self.adjust_upvar_borrow_kind_for_consume(place, mode);
459     }
460
461     fn borrow(&mut self, place: &mc::Place<'tcx>, bk: ty::BorrowKind) {
462         debug!("borrow(place={:?}, bk={:?})", place, bk);
463
464         match bk {
465             ty::ImmBorrow => {}
466             ty::UniqueImmBorrow => {
467                 self.adjust_upvar_borrow_kind_for_unique(place);
468             }
469             ty::MutBorrow => {
470                 self.adjust_upvar_borrow_kind_for_mut(place);
471             }
472         }
473     }
474
475     fn mutate(&mut self, assignee_place: &mc::Place<'tcx>) {
476         debug!("mutate(assignee_place={:?})", assignee_place);
477
478         self.adjust_upvar_borrow_kind_for_mut(assignee_place);
479     }
480 }
481
482 fn var_name(tcx: TyCtxt<'_>, var_hir_id: hir::HirId) -> Symbol {
483     tcx.hir().name(var_hir_id)
484 }