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.
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};
13 use crate::util::nodemap::FxHashMap;
15 struct InteriorVisitor<'a, 'tcx> {
16 fcx: &'a FnCtxt<'a, 'tcx>,
17 types: FxHashMap<Ty<'tcx>, usize>,
18 region_scope_tree: &'tcx region::ScopeTree,
20 kind: hir::GeneratorKind,
23 impl<'a, 'tcx> InteriorVisitor<'a, 'tcx> {
26 scope: Option<region::Scope>,
27 expr: Option<&'tcx Expr>,
29 use syntax_pos::DUMMY_SP;
31 debug!("generator_interior: attempting to record type {:?} {:?} {:?} {:?}",
32 ty, scope, expr, source_span);
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.
42 // See the mega-comment at `yield_in_scope` for a proof.
44 debug!("comparing counts yield: {} self: {}, source_span = {:?}",
45 yield_data.expr_and_pat_count, self.expr_count, source_span);
47 if yield_data.expr_and_pat_count >= self.expr_count {
53 }).unwrap_or_else(|| Some(YieldData {
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,
62 if let Some(yield_data) = live_across_yield {
63 let ty = self.fcx.resolve_vars_if_possible(&ty);
65 debug!("type in expr = {:?}, scope = {:?}, type = {:?}, count = {}, yield_span = {:?}",
66 expr, scope, ty, self.expr_count, yield_data.span);
68 if let Some((unresolved_type, unresolved_type_span)) =
69 self.fcx.unresolved_type_vars(&ty)
71 let note = format!("the type is part of the {} because of this {}",
75 // If unresolved type isn't a ty_var then unresolved_type_span is None
76 self.fcx.need_type_info_err_in_generator(
78 unresolved_type_span.unwrap_or(source_span),
81 .span_note(yield_data.span, &*note)
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);
89 debug!("no type in expr = {:?}, count = {:?}, span = {:?}",
90 expr, self.expr_count, expr.map(|e| e.span));
95 pub fn resolve_interior<'a, 'tcx>(
96 fcx: &'a FnCtxt<'a, 'tcx>,
100 kind: hir::GeneratorKind,
102 let body = fcx.tcx.hir().body(body_id);
103 let mut visitor = InteriorVisitor {
105 types: FxHashMap::default(),
106 region_scope_tree: fcx.tcx.region_scope_tree(def_id),
110 intravisit::walk_body(&mut visitor, body);
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);
116 let mut types: Vec<_> = visitor.types.drain().collect();
118 // Sort types by insertion order
119 types.sort_by_key(|t| t.1);
121 // Extract type components
122 let type_list = fcx.tcx.mk_type_list(types.into_iter().map(|t| t.0));
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.
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.
133 debug!("types in generator {:?}, span = {:?}", type_list, body.value.span);
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.
140 let type_list = fcx.tcx.fold_regions(&type_list, &mut false, |_, current_depth| {
142 fcx.tcx.mk_region(ty::ReLateBound(current_depth, ty::BrAnon(counter)))
145 let witness = fcx.tcx.mk_generator_witness(ty::Binder::bind(type_list));
147 debug!("types in generator after region replacement {:?}, span = {:?}",
148 witness, body.value.span);
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),
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
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
165 fn visit_pat(&mut self, pat: &'tcx Pat) {
166 intravisit::walk_pat(self, pat);
168 self.expr_count += 1;
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);
177 fn visit_expr(&mut self, expr: &'tcx Expr) {
178 intravisit::walk_expr(self, expr);
180 self.expr_count += 1;
182 let scope = self.region_scope_tree.temporary_scope(expr.hir_id.local_id);
184 // Record the unadjusted type
185 let ty = self.fcx.tables.borrow().expr_ty(expr);
186 self.record(ty, scope, Some(expr), expr.span);
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);