]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/generator_interior.rs
Auto merge of #82127 - tgnottingham:tune-ahead-of-time-codegen, r=varkor
[rust.git] / compiler / rustc_typeck / src / check / generator_interior.rs
1 //! This calculates the types which has storage which lives across a suspension point in a
2 //! generator from the perspective of typeck. The actual types used at runtime
3 //! is calculated in `rustc_mir::transform::generator` and may be a subset of the
4 //! types computed here.
5
6 use super::FnCtxt;
7 use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
8 use rustc_hir as hir;
9 use rustc_hir::def::{CtorKind, DefKind, Res};
10 use rustc_hir::def_id::DefId;
11 use rustc_hir::hir_id::HirIdSet;
12 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
13 use rustc_hir::{Arm, Expr, ExprKind, Guard, HirId, Pat, PatKind};
14 use rustc_middle::middle::region::{self, YieldData};
15 use rustc_middle::ty::{self, Ty};
16 use rustc_span::Span;
17 use smallvec::SmallVec;
18
19 struct InteriorVisitor<'a, 'tcx> {
20     fcx: &'a FnCtxt<'a, 'tcx>,
21     types: FxIndexSet<ty::GeneratorInteriorTypeCause<'tcx>>,
22     region_scope_tree: &'tcx region::ScopeTree,
23     expr_count: usize,
24     kind: hir::GeneratorKind,
25     prev_unresolved_span: Option<Span>,
26     /// Match arm guards have temporary borrows from the pattern bindings.
27     /// In case there is a yield point in a guard with a reference to such bindings,
28     /// such borrows can span across this yield point.
29     /// As such, we need to track these borrows and record them despite of the fact
30     /// that they may succeed the said yield point in the post-order.
31     guard_bindings: SmallVec<[SmallVec<[HirId; 4]>; 1]>,
32     guard_bindings_set: HirIdSet,
33 }
34
35 impl<'a, 'tcx> InteriorVisitor<'a, 'tcx> {
36     fn record(
37         &mut self,
38         ty: Ty<'tcx>,
39         scope: Option<region::Scope>,
40         expr: Option<&'tcx Expr<'tcx>>,
41         source_span: Span,
42         guard_borrowing_from_pattern: bool,
43     ) {
44         use rustc_span::DUMMY_SP;
45
46         debug!(
47             "generator_interior: attempting to record type {:?} {:?} {:?} {:?}",
48             ty, scope, expr, source_span
49         );
50
51         let live_across_yield = scope
52             .map(|s| {
53                 self.region_scope_tree.yield_in_scope(s).and_then(|yield_data| {
54                     // If we are recording an expression that is the last yield
55                     // in the scope, or that has a postorder CFG index larger
56                     // than the one of all of the yields, then its value can't
57                     // be storage-live (and therefore live) at any of the yields.
58                     //
59                     // See the mega-comment at `yield_in_scope` for a proof.
60
61                     debug!(
62                         "comparing counts yield: {} self: {}, source_span = {:?}",
63                         yield_data.expr_and_pat_count, self.expr_count, source_span
64                     );
65
66                     // If it is a borrowing happening in the guard,
67                     // it needs to be recorded regardless because they
68                     // do live across this yield point.
69                     if guard_borrowing_from_pattern
70                         || yield_data.expr_and_pat_count >= self.expr_count
71                     {
72                         Some(yield_data)
73                     } else {
74                         None
75                     }
76                 })
77             })
78             .unwrap_or_else(|| {
79                 Some(YieldData { span: DUMMY_SP, expr_and_pat_count: 0, source: self.kind.into() })
80             });
81
82         if let Some(yield_data) = live_across_yield {
83             let ty = self.fcx.resolve_vars_if_possible(ty);
84             debug!(
85                 "type in expr = {:?}, scope = {:?}, type = {:?}, count = {}, yield_span = {:?}",
86                 expr, scope, ty, self.expr_count, yield_data.span
87             );
88
89             if let Some((unresolved_type, unresolved_type_span)) =
90                 self.fcx.unresolved_type_vars(&ty)
91             {
92                 let note = format!(
93                     "the type is part of the {} because of this {}",
94                     self.kind, yield_data.source
95                 );
96
97                 // If unresolved type isn't a ty_var then unresolved_type_span is None
98                 let span = self
99                     .prev_unresolved_span
100                     .unwrap_or_else(|| unresolved_type_span.unwrap_or(source_span));
101                 self.fcx
102                     .need_type_info_err_in_generator(self.kind, span, unresolved_type)
103                     .span_note(yield_data.span, &*note)
104                     .emit();
105             } else {
106                 // Insert the type into the ordered set.
107                 let scope_span = scope.map(|s| s.span(self.fcx.tcx, self.region_scope_tree));
108                 self.types.insert(ty::GeneratorInteriorTypeCause {
109                     span: source_span,
110                     ty: &ty,
111                     scope_span,
112                     yield_span: yield_data.span,
113                     expr: expr.map(|e| e.hir_id),
114                 });
115             }
116         } else {
117             debug!(
118                 "no type in expr = {:?}, count = {:?}, span = {:?}",
119                 expr,
120                 self.expr_count,
121                 expr.map(|e| e.span)
122             );
123             let ty = self.fcx.resolve_vars_if_possible(ty);
124             if let Some((unresolved_type, unresolved_type_span)) =
125                 self.fcx.unresolved_type_vars(&ty)
126             {
127                 debug!(
128                     "remained unresolved_type = {:?}, unresolved_type_span: {:?}",
129                     unresolved_type, unresolved_type_span
130                 );
131                 self.prev_unresolved_span = unresolved_type_span;
132             }
133         }
134     }
135 }
136
137 pub fn resolve_interior<'a, 'tcx>(
138     fcx: &'a FnCtxt<'a, 'tcx>,
139     def_id: DefId,
140     body_id: hir::BodyId,
141     interior: Ty<'tcx>,
142     kind: hir::GeneratorKind,
143 ) {
144     let body = fcx.tcx.hir().body(body_id);
145     let mut visitor = InteriorVisitor {
146         fcx,
147         types: FxIndexSet::default(),
148         region_scope_tree: fcx.tcx.region_scope_tree(def_id),
149         expr_count: 0,
150         kind,
151         prev_unresolved_span: None,
152         guard_bindings: <_>::default(),
153         guard_bindings_set: <_>::default(),
154     };
155     intravisit::walk_body(&mut visitor, body);
156
157     // Check that we visited the same amount of expressions and the RegionResolutionVisitor
158     let region_expr_count = visitor.region_scope_tree.body_expr_count(body_id).unwrap();
159     assert_eq!(region_expr_count, visitor.expr_count);
160
161     // The types are already kept in insertion order.
162     let types = visitor.types;
163
164     // The types in the generator interior contain lifetimes local to the generator itself,
165     // which should not be exposed outside of the generator. Therefore, we replace these
166     // lifetimes with existentially-bound lifetimes, which reflect the exact value of the
167     // lifetimes not being known by users.
168     //
169     // These lifetimes are used in auto trait impl checking (for example,
170     // if a Sync generator contains an &'α T, we need to check whether &'α T: Sync),
171     // so knowledge of the exact relationships between them isn't particularly important.
172
173     debug!("types in generator {:?}, span = {:?}", types, body.value.span);
174
175     let mut counter = 0;
176     let mut captured_tys = FxHashSet::default();
177     let type_causes: Vec<_> = types
178         .into_iter()
179         .filter_map(|mut cause| {
180             // Erase regions and canonicalize late-bound regions to deduplicate as many types as we
181             // can.
182             let erased = fcx.tcx.erase_regions(cause.ty);
183             if captured_tys.insert(erased) {
184                 // Replace all regions inside the generator interior with late bound regions.
185                 // Note that each region slot in the types gets a new fresh late bound region,
186                 // which means that none of the regions inside relate to any other, even if
187                 // typeck had previously found constraints that would cause them to be related.
188                 let folded = fcx.tcx.fold_regions(erased, &mut false, |_, current_depth| {
189                     let br = ty::BoundRegion { kind: ty::BrAnon(counter) };
190                     let r = fcx.tcx.mk_region(ty::ReLateBound(current_depth, br));
191                     counter += 1;
192                     r
193                 });
194
195                 cause.ty = folded;
196                 Some(cause)
197             } else {
198                 None
199             }
200         })
201         .collect();
202
203     // Extract type components to build the witness type.
204     let type_list = fcx.tcx.mk_type_list(type_causes.iter().map(|cause| cause.ty));
205     let witness = fcx.tcx.mk_generator_witness(ty::Binder::bind(type_list));
206
207     // Store the generator types and spans into the typeck results for this generator.
208     visitor.fcx.inh.typeck_results.borrow_mut().generator_interior_types =
209         ty::Binder::bind(type_causes);
210
211     debug!(
212         "types in generator after region replacement {:?}, span = {:?}",
213         witness, body.value.span
214     );
215
216     // Unify the type variable inside the generator with the new witness
217     match fcx.at(&fcx.misc(body.value.span), fcx.param_env).eq(interior, witness) {
218         Ok(ok) => fcx.register_infer_ok_obligations(ok),
219         _ => bug!(),
220     }
221 }
222
223 // This visitor has to have the same visit_expr calls as RegionResolutionVisitor in
224 // librustc_middle/middle/region.rs since `expr_count` is compared against the results
225 // there.
226 impl<'a, 'tcx> Visitor<'tcx> for InteriorVisitor<'a, 'tcx> {
227     type Map = intravisit::ErasedMap<'tcx>;
228
229     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
230         NestedVisitorMap::None
231     }
232
233     fn visit_arm(&mut self, arm: &'tcx Arm<'tcx>) {
234         let Arm { guard, pat, body, .. } = arm;
235         self.visit_pat(pat);
236         if let Some(ref g) = guard {
237             self.guard_bindings.push(<_>::default());
238             ArmPatCollector {
239                 guard_bindings_set: &mut self.guard_bindings_set,
240                 guard_bindings: self
241                     .guard_bindings
242                     .last_mut()
243                     .expect("should have pushed at least one earlier"),
244             }
245             .visit_pat(pat);
246
247             match g {
248                 Guard::If(ref e) => {
249                     self.visit_expr(e);
250                 }
251                 Guard::IfLet(ref pat, ref e) => {
252                     self.visit_pat(pat);
253                     self.visit_expr(e);
254                 }
255             }
256
257             let mut scope_var_ids =
258                 self.guard_bindings.pop().expect("should have pushed at least one earlier");
259             for var_id in scope_var_ids.drain(..) {
260                 self.guard_bindings_set.remove(&var_id);
261             }
262         }
263         self.visit_expr(body);
264     }
265
266     fn visit_pat(&mut self, pat: &'tcx Pat<'tcx>) {
267         intravisit::walk_pat(self, pat);
268
269         self.expr_count += 1;
270
271         if let PatKind::Binding(..) = pat.kind {
272             let scope = self.region_scope_tree.var_scope(pat.hir_id.local_id);
273             let ty = self.fcx.typeck_results.borrow().pat_ty(pat);
274             self.record(ty, Some(scope), None, pat.span, false);
275         }
276     }
277
278     fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
279         let mut guard_borrowing_from_pattern = false;
280         match &expr.kind {
281             ExprKind::Call(callee, args) => match &callee.kind {
282                 ExprKind::Path(qpath) => {
283                     let res = self.fcx.typeck_results.borrow().qpath_res(qpath, callee.hir_id);
284                     match res {
285                         // Direct calls never need to keep the callee `ty::FnDef`
286                         // ZST in a temporary, so skip its type, just in case it
287                         // can significantly complicate the generator type.
288                         Res::Def(
289                             DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn),
290                             _,
291                         ) => {
292                             // NOTE(eddyb) this assumes a path expression has
293                             // no nested expressions to keep track of.
294                             self.expr_count += 1;
295
296                             // Record the rest of the call expression normally.
297                             for arg in *args {
298                                 self.visit_expr(arg);
299                             }
300                         }
301                         _ => intravisit::walk_expr(self, expr),
302                     }
303                 }
304                 _ => intravisit::walk_expr(self, expr),
305             },
306             ExprKind::Path(qpath) => {
307                 intravisit::walk_expr(self, expr);
308                 let res = self.fcx.typeck_results.borrow().qpath_res(qpath, expr.hir_id);
309                 match res {
310                     Res::Local(id) if self.guard_bindings_set.contains(&id) => {
311                         guard_borrowing_from_pattern = true;
312                     }
313                     _ => {}
314                 }
315             }
316             _ => intravisit::walk_expr(self, expr),
317         }
318
319         self.expr_count += 1;
320
321         let scope = self.region_scope_tree.temporary_scope(expr.hir_id.local_id);
322
323         // If there are adjustments, then record the final type --
324         // this is the actual value that is being produced.
325         if let Some(adjusted_ty) = self.fcx.typeck_results.borrow().expr_ty_adjusted_opt(expr) {
326             self.record(adjusted_ty, scope, Some(expr), expr.span, guard_borrowing_from_pattern);
327         }
328
329         // Also record the unadjusted type (which is the only type if
330         // there are no adjustments). The reason for this is that the
331         // unadjusted value is sometimes a "temporary" that would wind
332         // up in a MIR temporary.
333         //
334         // As an example, consider an expression like `vec![].push(x)`.
335         // Here, the `vec![]` would wind up MIR stored into a
336         // temporary variable `t` which we can borrow to invoke
337         // `<Vec<_>>::push(&mut t, x)`.
338         //
339         // Note that an expression can have many adjustments, and we
340         // are just ignoring those intermediate types. This is because
341         // those intermediate values are always linearly "consumed" by
342         // the other adjustments, and hence would never be directly
343         // captured in the MIR.
344         //
345         // (Note that this partly relies on the fact that the `Deref`
346         // traits always return references, which means their content
347         // can be reborrowed without needing to spill to a temporary.
348         // If this were not the case, then we could conceivably have
349         // to create intermediate temporaries.)
350         //
351         // The type table might not have information for this expression
352         // if it is in a malformed scope. (#66387)
353         if let Some(ty) = self.fcx.typeck_results.borrow().expr_ty_opt(expr) {
354             if guard_borrowing_from_pattern {
355                 // Match guards create references to all the bindings in the pattern that are used
356                 // in the guard, e.g. `y if is_even(y) => ...` becomes `is_even(*r_y)` where `r_y`
357                 // is a reference to `y`, so we must record a reference to the type of the binding.
358                 let tcx = self.fcx.tcx;
359                 let ref_ty = tcx.mk_ref(
360                     // Use `ReErased` as `resolve_interior` is going to replace all the regions anyway.
361                     tcx.mk_region(ty::RegionKind::ReErased),
362                     ty::TypeAndMut { ty, mutbl: hir::Mutability::Not },
363                 );
364                 self.record(ref_ty, scope, Some(expr), expr.span, guard_borrowing_from_pattern);
365             }
366             self.record(ty, scope, Some(expr), expr.span, guard_borrowing_from_pattern);
367         } else {
368             self.fcx.tcx.sess.delay_span_bug(expr.span, "no type for node");
369         }
370     }
371 }
372
373 struct ArmPatCollector<'a> {
374     guard_bindings_set: &'a mut HirIdSet,
375     guard_bindings: &'a mut SmallVec<[HirId; 4]>,
376 }
377
378 impl<'a, 'tcx> Visitor<'tcx> for ArmPatCollector<'a> {
379     type Map = intravisit::ErasedMap<'tcx>;
380
381     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
382         NestedVisitorMap::None
383     }
384
385     fn visit_pat(&mut self, pat: &'tcx Pat<'tcx>) {
386         intravisit::walk_pat(self, pat);
387         if let PatKind::Binding(_, id, ..) = pat.kind {
388             self.guard_bindings.push(id);
389             self.guard_bindings_set.insert(id);
390         }
391     }
392 }