]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/generator_interior.rs
Auto merge of #67924 - RalfJung:miri, r=RalfJung
[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::intravisit::{self, NestedVisitorMap, Visitor};
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::{Expr, ExprKind, Pat, PatKind};
15 use rustc_span::Span;
16
17 struct InteriorVisitor<'a, 'tcx> {
18     fcx: &'a FnCtxt<'a, 'tcx>,
19     types: FxHashMap<ty::GeneratorInteriorTypeCause<'tcx>, usize>,
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                 // Map the type to the number of types added before it
92                 let entries = self.types.len();
93                 let scope_span = scope.map(|s| s.span(self.fcx.tcx, self.region_scope_tree));
94                 self.types
95                     .entry(ty::GeneratorInteriorTypeCause {
96                         span: source_span,
97                         ty: &ty,
98                         scope_span,
99                     })
100                     .or_insert(entries);
101             }
102         } else {
103             debug!(
104                 "no type in expr = {:?}, count = {:?}, span = {:?}",
105                 expr,
106                 self.expr_count,
107                 expr.map(|e| e.span)
108             );
109             let ty = self.fcx.resolve_vars_if_possible(&ty);
110             if let Some((unresolved_type, unresolved_type_span)) =
111                 self.fcx.unresolved_type_vars(&ty)
112             {
113                 debug!(
114                     "remained unresolved_type = {:?}, unresolved_type_span: {:?}",
115                     unresolved_type, unresolved_type_span
116                 );
117                 self.prev_unresolved_span = unresolved_type_span;
118             }
119         }
120     }
121 }
122
123 pub fn resolve_interior<'a, 'tcx>(
124     fcx: &'a FnCtxt<'a, 'tcx>,
125     def_id: DefId,
126     body_id: hir::BodyId,
127     interior: Ty<'tcx>,
128     kind: hir::GeneratorKind,
129 ) {
130     let body = fcx.tcx.hir().body(body_id);
131     let mut visitor = InteriorVisitor {
132         fcx,
133         types: FxHashMap::default(),
134         region_scope_tree: fcx.tcx.region_scope_tree(def_id),
135         expr_count: 0,
136         kind,
137         prev_unresolved_span: None,
138     };
139     intravisit::walk_body(&mut visitor, body);
140
141     // Check that we visited the same amount of expressions and the RegionResolutionVisitor
142     let region_expr_count = visitor.region_scope_tree.body_expr_count(body_id).unwrap();
143     assert_eq!(region_expr_count, visitor.expr_count);
144
145     let mut types: Vec<_> = visitor.types.drain().collect();
146
147     // Sort types by insertion order
148     types.sort_by_key(|t| t.1);
149
150     // The types in the generator interior contain lifetimes local to the generator itself,
151     // which should not be exposed outside of the generator. Therefore, we replace these
152     // lifetimes with existentially-bound lifetimes, which reflect the exact value of the
153     // lifetimes not being known by users.
154     //
155     // These lifetimes are used in auto trait impl checking (for example,
156     // if a Sync generator contains an &'α T, we need to check whether &'α T: Sync),
157     // so knowledge of the exact relationships between them isn't particularly important.
158
159     debug!("types in generator {:?}, span = {:?}", types, body.value.span);
160
161     // Replace all regions inside the generator interior with late bound regions
162     // Note that each region slot in the types gets a new fresh late bound region,
163     // which means that none of the regions inside relate to any other, even if
164     // typeck had previously found constraints that would cause them to be related.
165     let mut counter = 0;
166     let types = fcx.tcx.fold_regions(&types, &mut false, |_, current_depth| {
167         counter += 1;
168         fcx.tcx.mk_region(ty::ReLateBound(current_depth, ty::BrAnon(counter)))
169     });
170
171     // Store the generator types and spans into the tables for this generator.
172     let interior_types = types.iter().map(|t| t.0.clone()).collect::<Vec<_>>();
173     visitor.fcx.inh.tables.borrow_mut().generator_interior_types = interior_types;
174
175     // Extract type components
176     let type_list = fcx.tcx.mk_type_list(types.into_iter().map(|t| (t.0).ty));
177
178     let witness = fcx.tcx.mk_generator_witness(ty::Binder::bind(type_list));
179
180     debug!(
181         "types in generator after region replacement {:?}, span = {:?}",
182         witness, body.value.span
183     );
184
185     // Unify the type variable inside the generator with the new witness
186     match fcx.at(&fcx.misc(body.value.span), fcx.param_env).eq(interior, witness) {
187         Ok(ok) => fcx.register_infer_ok_obligations(ok),
188         _ => bug!(),
189     }
190 }
191
192 // This visitor has to have the same visit_expr calls as RegionResolutionVisitor in
193 // librustc/middle/region.rs since `expr_count` is compared against the results
194 // there.
195 impl<'a, 'tcx> Visitor<'tcx> for InteriorVisitor<'a, 'tcx> {
196     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
197         NestedVisitorMap::None
198     }
199
200     fn visit_pat(&mut self, pat: &'tcx Pat<'tcx>) {
201         intravisit::walk_pat(self, pat);
202
203         self.expr_count += 1;
204
205         if let PatKind::Binding(..) = pat.kind {
206             let scope = self.region_scope_tree.var_scope(pat.hir_id.local_id);
207             let ty = self.fcx.tables.borrow().pat_ty(pat);
208             self.record(ty, Some(scope), None, pat.span);
209         }
210     }
211
212     fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
213         let scope = self.region_scope_tree.temporary_scope(expr.hir_id.local_id);
214
215         match &expr.kind {
216             ExprKind::Call(callee, args) => match &callee.kind {
217                 ExprKind::Path(qpath) => {
218                     let res = self.fcx.tables.borrow().qpath_res(qpath, callee.hir_id);
219                     match res {
220                         // Direct calls never need to keep the callee `ty::FnDef`
221                         // ZST in a temporary, so skip its type, just in case it
222                         // can significantly complicate the generator type.
223                         Res::Def(DefKind::Fn, _)
224                         | Res::Def(DefKind::Method, _)
225                         | Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) => {
226                             // NOTE(eddyb) this assumes a path expression has
227                             // no nested expressions to keep track of.
228                             self.expr_count += 1;
229
230                             // Record the rest of the call expression normally.
231                             for arg in *args {
232                                 self.visit_expr(arg);
233                             }
234                         }
235                         _ => intravisit::walk_expr(self, expr),
236                     }
237                 }
238                 _ => intravisit::walk_expr(self, expr),
239             },
240             ExprKind::Path(qpath) => {
241                 let res = self.fcx.tables.borrow().qpath_res(qpath, expr.hir_id);
242                 if let Res::Def(DefKind::Static, def_id) = res {
243                     // Statics are lowered to temporary references or
244                     // pointers in MIR, so record that type.
245                     let ptr_ty = self.fcx.tcx.static_ptr_ty(def_id);
246                     self.record(ptr_ty, scope, Some(expr), expr.span);
247                 }
248             }
249             _ => intravisit::walk_expr(self, expr),
250         }
251
252         self.expr_count += 1;
253
254         // If there are adjustments, then record the final type --
255         // this is the actual value that is being produced.
256         if let Some(adjusted_ty) = self.fcx.tables.borrow().expr_ty_adjusted_opt(expr) {
257             self.record(adjusted_ty, scope, Some(expr), expr.span);
258         }
259
260         // Also record the unadjusted type (which is the only type if
261         // there are no adjustments). The reason for this is that the
262         // unadjusted value is sometimes a "temporary" that would wind
263         // up in a MIR temporary.
264         //
265         // As an example, consider an expression like `vec![].push()`.
266         // Here, the `vec![]` would wind up MIR stored into a
267         // temporary variable `t` which we can borrow to invoke
268         // `<Vec<_>>::push(&mut t)`.
269         //
270         // Note that an expression can have many adjustments, and we
271         // are just ignoring those intermediate types. This is because
272         // those intermediate values are always linearly "consumed" by
273         // the other adjustments, and hence would never be directly
274         // captured in the MIR.
275         //
276         // (Note that this partly relies on the fact that the `Deref`
277         // traits always return references, which means their content
278         // can be reborrowed without needing to spill to a temporary.
279         // If this were not the case, then we could conceivably have
280         // to create intermediate temporaries.)
281         //
282         // The type table might not have information for this expression
283         // if it is in a malformed scope. (#66387)
284         if let Some(ty) = self.fcx.tables.borrow().expr_ty_opt(expr) {
285             self.record(ty, scope, Some(expr), expr.span);
286         } else {
287             self.fcx.tcx.sess.delay_span_bug(expr.span, "no type for node");
288         }
289     }
290 }