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