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