]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/generator_interior.rs
Auto merge of #76541 - matthiaskrgr:unstable_sort, r=davidtwco
[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::intravisit::{self, NestedVisitorMap, Visitor};
12 use rustc_hir::{Expr, ExprKind, Pat, PatKind};
13 use rustc_middle::middle::region::{self, YieldData};
14 use rustc_middle::ty::{self, Ty};
15 use rustc_span::Span;
16
17 struct InteriorVisitor<'a, 'tcx> {
18     fcx: &'a FnCtxt<'a, 'tcx>,
19     types: FxIndexSet<ty::GeneratorInteriorTypeCause<'tcx>>,
20     region_scope_tree: &'tcx region::ScopeTree,
21     expr_count: usize,
22     kind: hir::GeneratorKind,
23     prev_unresolved_span: Option<Span>,
24 }
25
26 impl<'a, 'tcx> InteriorVisitor<'a, 'tcx> {
27     fn record(
28         &mut self,
29         ty: Ty<'tcx>,
30         scope: Option<region::Scope>,
31         expr: Option<&'tcx Expr<'tcx>>,
32         source_span: Span,
33     ) {
34         use rustc_span::DUMMY_SP;
35
36         debug!(
37             "generator_interior: attempting to record type {:?} {:?} {:?} {:?}",
38             ty, scope, expr, source_span
39         );
40
41         let live_across_yield = scope
42             .map(|s| {
43                 self.region_scope_tree.yield_in_scope(s).and_then(|yield_data| {
44                     // If we are recording an expression that is the last yield
45                     // in the scope, or that has a postorder CFG index larger
46                     // than the one of all of the yields, then its value can't
47                     // be storage-live (and therefore live) at any of the yields.
48                     //
49                     // See the mega-comment at `yield_in_scope` for a proof.
50
51                     debug!(
52                         "comparing counts yield: {} self: {}, source_span = {:?}",
53                         yield_data.expr_and_pat_count, self.expr_count, source_span
54                     );
55
56                     if yield_data.expr_and_pat_count >= self.expr_count {
57                         Some(yield_data)
58                     } else {
59                         None
60                     }
61                 })
62             })
63             .unwrap_or_else(|| {
64                 Some(YieldData { span: DUMMY_SP, expr_and_pat_count: 0, source: self.kind.into() })
65             });
66
67         if let Some(yield_data) = live_across_yield {
68             let ty = self.fcx.resolve_vars_if_possible(&ty);
69             debug!(
70                 "type in expr = {:?}, scope = {:?}, type = {:?}, count = {}, yield_span = {:?}",
71                 expr, scope, ty, self.expr_count, yield_data.span
72             );
73
74             if let Some((unresolved_type, unresolved_type_span)) =
75                 self.fcx.unresolved_type_vars(&ty)
76             {
77                 let note = format!(
78                     "the type is part of the {} because of this {}",
79                     self.kind, yield_data.source
80                 );
81
82                 // If unresolved type isn't a ty_var then unresolved_type_span is None
83                 let span = self
84                     .prev_unresolved_span
85                     .unwrap_or_else(|| unresolved_type_span.unwrap_or(source_span));
86                 self.fcx
87                     .need_type_info_err_in_generator(self.kind, span, unresolved_type)
88                     .span_note(yield_data.span, &*note)
89                     .emit();
90             } else {
91                 // Insert the type into the ordered set.
92                 let scope_span = scope.map(|s| s.span(self.fcx.tcx, self.region_scope_tree));
93                 self.types.insert(ty::GeneratorInteriorTypeCause {
94                     span: source_span,
95                     ty: &ty,
96                     scope_span,
97                     yield_span: yield_data.span,
98                     expr: expr.map(|e| e.hir_id),
99                 });
100             }
101         } else {
102             debug!(
103                 "no type in expr = {:?}, count = {:?}, span = {:?}",
104                 expr,
105                 self.expr_count,
106                 expr.map(|e| e.span)
107             );
108             let ty = self.fcx.resolve_vars_if_possible(&ty);
109             if let Some((unresolved_type, unresolved_type_span)) =
110                 self.fcx.unresolved_type_vars(&ty)
111             {
112                 debug!(
113                     "remained unresolved_type = {:?}, unresolved_type_span: {:?}",
114                     unresolved_type, unresolved_type_span
115                 );
116                 self.prev_unresolved_span = unresolved_type_span;
117             }
118         }
119     }
120 }
121
122 pub fn resolve_interior<'a, 'tcx>(
123     fcx: &'a FnCtxt<'a, 'tcx>,
124     def_id: DefId,
125     body_id: hir::BodyId,
126     interior: Ty<'tcx>,
127     kind: hir::GeneratorKind,
128 ) {
129     let body = fcx.tcx.hir().body(body_id);
130     let mut visitor = InteriorVisitor {
131         fcx,
132         types: FxIndexSet::default(),
133         region_scope_tree: fcx.tcx.region_scope_tree(def_id),
134         expr_count: 0,
135         kind,
136         prev_unresolved_span: None,
137     };
138     intravisit::walk_body(&mut visitor, body);
139
140     // Check that we visited the same amount of expressions and the RegionResolutionVisitor
141     let region_expr_count = visitor.region_scope_tree.body_expr_count(body_id).unwrap();
142     assert_eq!(region_expr_count, visitor.expr_count);
143
144     // The types are already kept in insertion order.
145     let types = visitor.types;
146
147     // The types in the generator interior contain lifetimes local to the generator itself,
148     // which should not be exposed outside of the generator. Therefore, we replace these
149     // lifetimes with existentially-bound lifetimes, which reflect the exact value of the
150     // lifetimes not being known by users.
151     //
152     // These lifetimes are used in auto trait impl checking (for example,
153     // if a Sync generator contains an &'α T, we need to check whether &'α T: Sync),
154     // so knowledge of the exact relationships between them isn't particularly important.
155
156     debug!("types in generator {:?}, span = {:?}", types, body.value.span);
157
158     let mut counter = 0;
159     let mut captured_tys = FxHashSet::default();
160     let type_causes: Vec<_> = types
161         .into_iter()
162         .filter_map(|mut cause| {
163             // Erase regions and canonicalize late-bound regions to deduplicate as many types as we
164             // can.
165             let erased = fcx.tcx.erase_regions(&cause.ty);
166             if captured_tys.insert(erased) {
167                 // Replace all regions inside the generator interior with late bound regions.
168                 // Note that each region slot in the types gets a new fresh late bound region,
169                 // which means that none of the regions inside relate to any other, even if
170                 // typeck had previously found constraints that would cause them to be related.
171                 let folded = fcx.tcx.fold_regions(&erased, &mut false, |_, current_depth| {
172                     counter += 1;
173                     fcx.tcx.mk_region(ty::ReLateBound(current_depth, ty::BrAnon(counter)))
174                 });
175
176                 cause.ty = folded;
177                 Some(cause)
178             } else {
179                 None
180             }
181         })
182         .collect();
183
184     // Extract type components to build the witness type.
185     let type_list = fcx.tcx.mk_type_list(type_causes.iter().map(|cause| cause.ty));
186     let witness = fcx.tcx.mk_generator_witness(ty::Binder::bind(type_list));
187
188     // Store the generator types and spans into the typeck results for this generator.
189     visitor.fcx.inh.typeck_results.borrow_mut().generator_interior_types = type_causes;
190
191     debug!(
192         "types in generator after region replacement {:?}, span = {:?}",
193         witness, body.value.span
194     );
195
196     // Unify the type variable inside the generator with the new witness
197     match fcx.at(&fcx.misc(body.value.span), fcx.param_env).eq(interior, witness) {
198         Ok(ok) => fcx.register_infer_ok_obligations(ok),
199         _ => bug!(),
200     }
201 }
202
203 // This visitor has to have the same visit_expr calls as RegionResolutionVisitor in
204 // librustc_middle/middle/region.rs since `expr_count` is compared against the results
205 // there.
206 impl<'a, 'tcx> Visitor<'tcx> for InteriorVisitor<'a, 'tcx> {
207     type Map = intravisit::ErasedMap<'tcx>;
208
209     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
210         NestedVisitorMap::None
211     }
212
213     fn visit_pat(&mut self, pat: &'tcx Pat<'tcx>) {
214         intravisit::walk_pat(self, pat);
215
216         self.expr_count += 1;
217
218         if let PatKind::Binding(..) = pat.kind {
219             let scope = self.region_scope_tree.var_scope(pat.hir_id.local_id);
220             let ty = self.fcx.typeck_results.borrow().pat_ty(pat);
221             self.record(ty, Some(scope), None, pat.span);
222         }
223     }
224
225     fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
226         match &expr.kind {
227             ExprKind::Call(callee, args) => match &callee.kind {
228                 ExprKind::Path(qpath) => {
229                     let res = self.fcx.typeck_results.borrow().qpath_res(qpath, callee.hir_id);
230                     match res {
231                         // Direct calls never need to keep the callee `ty::FnDef`
232                         // ZST in a temporary, so skip its type, just in case it
233                         // can significantly complicate the generator type.
234                         Res::Def(
235                             DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn),
236                             _,
237                         ) => {
238                             // NOTE(eddyb) this assumes a path expression has
239                             // no nested expressions to keep track of.
240                             self.expr_count += 1;
241
242                             // Record the rest of the call expression normally.
243                             for arg in *args {
244                                 self.visit_expr(arg);
245                             }
246                         }
247                         _ => intravisit::walk_expr(self, expr),
248                     }
249                 }
250                 _ => intravisit::walk_expr(self, expr),
251             },
252             _ => intravisit::walk_expr(self, expr),
253         }
254
255         self.expr_count += 1;
256
257         let scope = self.region_scope_tree.temporary_scope(expr.hir_id.local_id);
258
259         // If there are adjustments, then record the final type --
260         // this is the actual value that is being produced.
261         if let Some(adjusted_ty) = self.fcx.typeck_results.borrow().expr_ty_adjusted_opt(expr) {
262             self.record(adjusted_ty, scope, Some(expr), expr.span);
263         }
264
265         // Also record the unadjusted type (which is the only type if
266         // there are no adjustments). The reason for this is that the
267         // unadjusted value is sometimes a "temporary" that would wind
268         // up in a MIR temporary.
269         //
270         // As an example, consider an expression like `vec![].push()`.
271         // Here, the `vec![]` would wind up MIR stored into a
272         // temporary variable `t` which we can borrow to invoke
273         // `<Vec<_>>::push(&mut t)`.
274         //
275         // Note that an expression can have many adjustments, and we
276         // are just ignoring those intermediate types. This is because
277         // those intermediate values are always linearly "consumed" by
278         // the other adjustments, and hence would never be directly
279         // captured in the MIR.
280         //
281         // (Note that this partly relies on the fact that the `Deref`
282         // traits always return references, which means their content
283         // can be reborrowed without needing to spill to a temporary.
284         // If this were not the case, then we could conceivably have
285         // to create intermediate temporaries.)
286         //
287         // The type table might not have information for this expression
288         // if it is in a malformed scope. (#66387)
289         if let Some(ty) = self.fcx.typeck_results.borrow().expr_ty_opt(expr) {
290             self.record(ty, scope, Some(expr), expr.span);
291         } else {
292             self.fcx.tcx.sess.delay_span_bug(expr.span, "no type for node");
293         }
294     }
295 }