1 // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! This calculates the types which has storage which lives across a suspension point in a
12 //! generator from the perspective of typeck. The actual types used at runtime
13 //! is calculated in `rustc_mir::transform::generator` and may be a subset of the
14 //! types computed here.
16 use rustc::hir::def_id::DefId;
17 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
18 use rustc::hir::{self, Pat, PatKind, Expr};
19 use rustc::middle::region;
20 use rustc::ty::{self, Ty, GeneratorInterior};
24 use util::nodemap::FxHashMap;
26 struct InteriorVisitor<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
27 fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
28 types: FxHashMap<Ty<'tcx>, usize>,
29 region_scope_tree: Rc<region::ScopeTree>,
33 impl<'a, 'gcx, 'tcx> InteriorVisitor<'a, 'gcx, 'tcx> {
36 scope: Option<region::Scope>,
37 expr: Option<&'tcx Expr>,
39 use syntax_pos::DUMMY_SP;
41 let live_across_yield = scope.map_or(Some(DUMMY_SP), |s| {
42 self.region_scope_tree.yield_in_scope(s).and_then(|(yield_span, expr_count)| {
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.
48 // See the mega-comment at `yield_in_scope` for a proof.
50 debug!("comparing counts yield: {} self: {}, source_span = {:?}",
51 expr_count, self.expr_count, source_span);
53 if expr_count >= self.expr_count {
61 if let Some(yield_span) = live_across_yield {
62 let ty = self.fcx.resolve_type_vars_if_possible(&ty);
64 debug!("type in expr = {:?}, scope = {:?}, type = {:?}, count = {}, yield_span = {:?}",
65 expr, scope, ty, self.expr_count, yield_span);
67 if self.fcx.any_unresolved_type_vars(&ty) {
68 let mut err = struct_span_err!(self.fcx.tcx.sess, source_span, E0907,
69 "type inside generator must be known in this context");
70 err.span_note(yield_span,
71 "the type is part of the generator because of this `yield`");
74 // Map the type to the number of types added before it
75 let entries = self.types.len();
76 self.types.entry(&ty).or_insert(entries);
79 debug!("no type in expr = {:?}, count = {:?}, span = {:?}",
80 expr, self.expr_count, expr.map(|e| e.span));
85 pub fn resolve_interior<'a, 'gcx, 'tcx>(fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
88 interior: GeneratorInterior<'tcx>) {
89 let body = fcx.tcx.hir.body(body_id);
90 let mut visitor = InteriorVisitor {
93 region_scope_tree: fcx.tcx.region_scope_tree(def_id),
96 intravisit::walk_body(&mut visitor, body);
98 // Check that we visited the same amount of expressions and the RegionResolutionVisitor
99 let region_expr_count = visitor.region_scope_tree.body_expr_count(body_id).unwrap();
100 assert_eq!(region_expr_count, visitor.expr_count);
102 let mut types: Vec<_> = visitor.types.drain().collect();
104 // Sort types by insertion order
105 types.sort_by_key(|t| t.1);
107 // Extract type components
108 let type_list = fcx.tcx.mk_type_list(types.into_iter().map(|t| t.0));
110 // The types in the generator interior contain lifetimes local to the generator itself,
111 // which should not be exposed outside of the generator. Therefore, we replace these
112 // lifetimes with existentially-bound lifetimes, which reflect the exact value of the
113 // lifetimes not being known by users.
115 // These lifetimes are used in auto trait impl checking (for example,
116 // if a Sync generator contains an &'α T, we need to check whether &'α T: Sync),
117 // so knowledge of the exact relationships between them isn't particularly important.
119 debug!("Types in generator {:?}, span = {:?}", type_list, body.value.span);
121 // Replace all regions inside the generator interior with late bound regions
122 // Note that each region slot in the types gets a new fresh late bound region,
123 // which means that none of the regions inside relate to any other, even if
124 // typeck had previously found contraints that would cause them to be related.
126 let type_list = fcx.tcx.fold_regions(&type_list, &mut false, |_, current_depth| {
128 fcx.tcx.mk_region(ty::ReLateBound(ty::DebruijnIndex::new(current_depth),
129 ty::BrAnon(counter)))
132 let witness = fcx.tcx.mk_generator_witness(ty::Binder(type_list));
134 debug!("Types in generator after region replacement {:?}, span = {:?}",
135 witness, body.value.span);
137 // Unify the type variable inside the generator with the new witness
138 match fcx.at(&fcx.misc(body.value.span), fcx.param_env).eq(interior.witness, witness) {
139 Ok(ok) => fcx.register_infer_ok_obligations(ok),
144 // This visitor has to have the same visit_expr calls as RegionResolutionVisitor in
145 // librustc/middle/region.rs since `expr_count` is compared against the results
147 impl<'a, 'gcx, 'tcx> Visitor<'tcx> for InteriorVisitor<'a, 'gcx, 'tcx> {
148 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
149 NestedVisitorMap::None
152 fn visit_pat(&mut self, pat: &'tcx Pat) {
153 if let PatKind::Binding(..) = pat.node {
154 let scope = self.region_scope_tree.var_scope(pat.hir_id.local_id);
155 let ty = self.fcx.tables.borrow().pat_ty(pat);
156 self.record(ty, Some(scope), None, pat.span);
159 self.expr_count += 1;
161 intravisit::walk_pat(self, pat);
164 fn visit_expr(&mut self, expr: &'tcx Expr) {
165 intravisit::walk_expr(self, expr);
167 self.expr_count += 1;
169 let scope = self.region_scope_tree.temporary_scope(expr.hir_id.local_id);
171 let ty = self.fcx.tables.borrow().expr_ty_adjusted(expr);
172 self.record(ty, scope, Some(expr), expr.span);