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