]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/generator_interior.rs
Rollup merge of #62557 - taiki-e:typo, r=Centril
[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_id::DefId;
7 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
8 use rustc::hir::{self, Pat, PatKind, Expr};
9 use rustc::middle::region::{self, YieldData};
10 use rustc::ty::{self, Ty};
11 use syntax_pos::Span;
12 use super::FnCtxt;
13 use crate::util::nodemap::FxHashMap;
14
15 struct InteriorVisitor<'a, 'tcx> {
16     fcx: &'a FnCtxt<'a, 'tcx>,
17     types: FxHashMap<Ty<'tcx>, usize>,
18     region_scope_tree: &'tcx region::ScopeTree,
19     expr_count: usize,
20     kind: hir::GeneratorKind,
21 }
22
23 impl<'a, 'tcx> InteriorVisitor<'a, 'tcx> {
24     fn record(&mut self,
25               ty: Ty<'tcx>,
26               scope: Option<region::Scope>,
27               expr: Option<&'tcx Expr>,
28               source_span: Span) {
29         use syntax_pos::DUMMY_SP;
30
31         debug!("generator_interior: attempting to record type {:?} {:?} {:?} {:?}",
32                ty, scope, expr, source_span);
33
34
35         let live_across_yield = scope.map(|s| {
36             self.region_scope_tree.yield_in_scope(s).and_then(|yield_data| {
37                 // If we are recording an expression that is the last yield
38                 // in the scope, or that has a postorder CFG index larger
39                 // than the one of all of the yields, then its value can't
40                 // be storage-live (and therefore live) at any of the yields.
41                 //
42                 // See the mega-comment at `yield_in_scope` for a proof.
43
44                 debug!("comparing counts yield: {} self: {}, source_span = {:?}",
45                        yield_data.expr_and_pat_count, self.expr_count, source_span);
46
47                 if yield_data.expr_and_pat_count >= self.expr_count {
48                     Some(yield_data)
49                 } else {
50                     None
51                 }
52             })
53         }).unwrap_or_else(|| Some(YieldData {
54             span: DUMMY_SP,
55             expr_and_pat_count: 0,
56             source: match self.kind { // Guess based on the kind of the current generator.
57                 hir::GeneratorKind::Gen => hir::YieldSource::Yield,
58                 hir::GeneratorKind::Async => hir::YieldSource::Await,
59             },
60         }));
61
62         if let Some(yield_data) = live_across_yield {
63             let ty = self.fcx.resolve_vars_if_possible(&ty);
64
65             debug!("type in expr = {:?}, scope = {:?}, type = {:?}, count = {}, yield_span = {:?}",
66                    expr, scope, ty, self.expr_count, yield_data.span);
67
68             if let Some((unresolved_type, unresolved_type_span)) =
69                 self.fcx.unresolved_type_vars(&ty)
70             {
71                 let note = format!("the type is part of the {} because of this {}",
72                                    self.kind,
73                                    yield_data.source);
74
75                 // If unresolved type isn't a ty_var then unresolved_type_span is None
76                 self.fcx.need_type_info_err_in_generator(
77                     self.kind,
78                     unresolved_type_span.unwrap_or(source_span),
79                     unresolved_type,
80                 )
81                     .span_note(yield_data.span, &*note)
82                     .emit();
83             } else {
84                 // Map the type to the number of types added before it
85                 let entries = self.types.len();
86                 self.types.entry(&ty).or_insert(entries);
87             }
88         } else {
89             debug!("no type in expr = {:?}, count = {:?}, span = {:?}",
90                    expr, self.expr_count, expr.map(|e| e.span));
91         }
92     }
93 }
94
95 pub fn resolve_interior<'a, 'tcx>(
96     fcx: &'a FnCtxt<'a, 'tcx>,
97     def_id: DefId,
98     body_id: hir::BodyId,
99     interior: Ty<'tcx>,
100     kind: hir::GeneratorKind,
101 ) {
102     let body = fcx.tcx.hir().body(body_id);
103     let mut visitor = InteriorVisitor {
104         fcx,
105         types: FxHashMap::default(),
106         region_scope_tree: fcx.tcx.region_scope_tree(def_id),
107         expr_count: 0,
108         kind,
109     };
110     intravisit::walk_body(&mut visitor, body);
111
112     // Check that we visited the same amount of expressions and the RegionResolutionVisitor
113     let region_expr_count = visitor.region_scope_tree.body_expr_count(body_id).unwrap();
114     assert_eq!(region_expr_count, visitor.expr_count);
115
116     let mut types: Vec<_> = visitor.types.drain().collect();
117
118     // Sort types by insertion order
119     types.sort_by_key(|t| t.1);
120
121     // Extract type components
122     let type_list = fcx.tcx.mk_type_list(types.into_iter().map(|t| t.0));
123
124     // The types in the generator interior contain lifetimes local to the generator itself,
125     // which should not be exposed outside of the generator. Therefore, we replace these
126     // lifetimes with existentially-bound lifetimes, which reflect the exact value of the
127     // lifetimes not being known by users.
128     //
129     // These lifetimes are used in auto trait impl checking (for example,
130     // if a Sync generator contains an &'α T, we need to check whether &'α T: Sync),
131     // so knowledge of the exact relationships between them isn't particularly important.
132
133     debug!("types in generator {:?}, span = {:?}", type_list, body.value.span);
134
135     // Replace all regions inside the generator interior with late bound regions
136     // Note that each region slot in the types gets a new fresh late bound region,
137     // which means that none of the regions inside relate to any other, even if
138     // typeck had previously found constraints that would cause them to be related.
139     let mut counter = 0;
140     let type_list = fcx.tcx.fold_regions(&type_list, &mut false, |_, current_depth| {
141         counter += 1;
142         fcx.tcx.mk_region(ty::ReLateBound(current_depth, ty::BrAnon(counter)))
143     });
144
145     let witness = fcx.tcx.mk_generator_witness(ty::Binder::bind(type_list));
146
147     debug!("types in generator after region replacement {:?}, span = {:?}",
148             witness, body.value.span);
149
150     // Unify the type variable inside the generator with the new witness
151     match fcx.at(&fcx.misc(body.value.span), fcx.param_env).eq(interior, witness) {
152         Ok(ok) => fcx.register_infer_ok_obligations(ok),
153         _ => bug!(),
154     }
155 }
156
157 // This visitor has to have the same visit_expr calls as RegionResolutionVisitor in
158 // librustc/middle/region.rs since `expr_count` is compared against the results
159 // there.
160 impl<'a, 'tcx> Visitor<'tcx> for InteriorVisitor<'a, 'tcx> {
161     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
162         NestedVisitorMap::None
163     }
164
165     fn visit_pat(&mut self, pat: &'tcx Pat) {
166         intravisit::walk_pat(self, pat);
167
168         self.expr_count += 1;
169
170         if let PatKind::Binding(..) = pat.node {
171             let scope = self.region_scope_tree.var_scope(pat.hir_id.local_id);
172             let ty = self.fcx.tables.borrow().pat_ty(pat);
173             self.record(ty, Some(scope), None, pat.span);
174         }
175     }
176
177     fn visit_expr(&mut self, expr: &'tcx Expr) {
178         intravisit::walk_expr(self, expr);
179
180         self.expr_count += 1;
181
182         let scope = self.region_scope_tree.temporary_scope(expr.hir_id.local_id);
183
184         // Record the unadjusted type
185         let ty = self.fcx.tables.borrow().expr_ty(expr);
186         self.record(ty, scope, Some(expr), expr.span);
187
188         // Also include the adjusted types, since these can result in MIR locals
189         for adjustment in self.fcx.tables.borrow().expr_adjustments(expr) {
190             self.record(adjustment.target, scope, Some(expr), expr.span);
191         }
192     }
193 }