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