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.
7 use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
9 use rustc_hir::def::{CtorKind, DefKind, Res};
10 use rustc_hir::def_id::DefId;
11 use rustc_hir::hir_id::HirIdSet;
12 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
13 use rustc_hir::{Arm, Expr, ExprKind, Guard, HirId, Pat, PatKind};
14 use rustc_middle::middle::region::{self, YieldData};
15 use rustc_middle::ty::{self, Ty};
17 use smallvec::SmallVec;
19 struct InteriorVisitor<'a, 'tcx> {
20 fcx: &'a FnCtxt<'a, 'tcx>,
21 types: FxIndexSet<ty::GeneratorInteriorTypeCause<'tcx>>,
22 region_scope_tree: &'tcx region::ScopeTree,
24 kind: hir::GeneratorKind,
25 prev_unresolved_span: Option<Span>,
26 /// Match arm guards have temporary borrows from the pattern bindings.
27 /// In case there is a yield point in a guard with a reference to such bindings,
28 /// such borrows can span across this yield point.
29 /// As such, we need to track these borrows and record them despite of the fact
30 /// that they may succeed the said yield point in the post-order.
31 guard_bindings: SmallVec<[SmallVec<[HirId; 4]>; 1]>,
32 guard_bindings_set: HirIdSet,
35 impl<'a, 'tcx> InteriorVisitor<'a, 'tcx> {
39 scope: Option<region::Scope>,
40 expr: Option<&'tcx Expr<'tcx>>,
42 guard_borrowing_from_pattern: bool,
44 use rustc_span::DUMMY_SP;
47 "generator_interior: attempting to record type {:?} {:?} {:?} {:?}",
48 ty, scope, expr, source_span
51 let live_across_yield = scope
53 self.region_scope_tree.yield_in_scope(s).and_then(|yield_data| {
54 // If we are recording an expression that is the last yield
55 // in the scope, or that has a postorder CFG index larger
56 // than the one of all of the yields, then its value can't
57 // be storage-live (and therefore live) at any of the yields.
59 // See the mega-comment at `yield_in_scope` for a proof.
62 "comparing counts yield: {} self: {}, source_span = {:?}",
63 yield_data.expr_and_pat_count, self.expr_count, source_span
66 // If it is a borrowing happening in the guard,
67 // it needs to be recorded regardless because they
68 // do live across this yield point.
69 if guard_borrowing_from_pattern
70 || yield_data.expr_and_pat_count >= self.expr_count
79 Some(YieldData { span: DUMMY_SP, expr_and_pat_count: 0, source: self.kind.into() })
82 if let Some(yield_data) = live_across_yield {
83 let ty = self.fcx.resolve_vars_if_possible(ty);
85 "type in expr = {:?}, scope = {:?}, type = {:?}, count = {}, yield_span = {:?}",
86 expr, scope, ty, self.expr_count, yield_data.span
89 if let Some((unresolved_type, unresolved_type_span)) =
90 self.fcx.unresolved_type_vars(&ty)
92 // If unresolved type isn't a ty_var then unresolved_type_span is None
95 .unwrap_or_else(|| unresolved_type_span.unwrap_or(source_span));
97 // If we encounter an int/float variable, then inference fallback didn't
98 // finish due to some other error. Don't emit spurious additional errors.
99 if let ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(_)) =
100 unresolved_type.kind()
105 .delay_span_bug(span, &format!("Encountered var {:?}", unresolved_type));
108 "the type is part of the {} because of this {}",
109 self.kind, yield_data.source
113 .need_type_info_err_in_generator(self.kind, span, unresolved_type)
114 .span_note(yield_data.span, &*note)
118 // Insert the type into the ordered set.
119 let scope_span = scope.map(|s| s.span(self.fcx.tcx, self.region_scope_tree));
120 self.types.insert(ty::GeneratorInteriorTypeCause {
124 yield_span: yield_data.span,
125 expr: expr.map(|e| e.hir_id),
130 "no type in expr = {:?}, count = {:?}, span = {:?}",
135 let ty = self.fcx.resolve_vars_if_possible(ty);
136 if let Some((unresolved_type, unresolved_type_span)) =
137 self.fcx.unresolved_type_vars(&ty)
140 "remained unresolved_type = {:?}, unresolved_type_span: {:?}",
141 unresolved_type, unresolved_type_span
143 self.prev_unresolved_span = unresolved_type_span;
149 pub fn resolve_interior<'a, 'tcx>(
150 fcx: &'a FnCtxt<'a, 'tcx>,
152 body_id: hir::BodyId,
154 kind: hir::GeneratorKind,
156 let body = fcx.tcx.hir().body(body_id);
157 let mut visitor = InteriorVisitor {
159 types: FxIndexSet::default(),
160 region_scope_tree: fcx.tcx.region_scope_tree(def_id),
163 prev_unresolved_span: None,
164 guard_bindings: <_>::default(),
165 guard_bindings_set: <_>::default(),
167 intravisit::walk_body(&mut visitor, body);
169 // Check that we visited the same amount of expressions and the RegionResolutionVisitor
170 let region_expr_count = visitor.region_scope_tree.body_expr_count(body_id).unwrap();
171 assert_eq!(region_expr_count, visitor.expr_count);
173 // The types are already kept in insertion order.
174 let types = visitor.types;
176 // The types in the generator interior contain lifetimes local to the generator itself,
177 // which should not be exposed outside of the generator. Therefore, we replace these
178 // lifetimes with existentially-bound lifetimes, which reflect the exact value of the
179 // lifetimes not being known by users.
181 // These lifetimes are used in auto trait impl checking (for example,
182 // if a Sync generator contains an &'α T, we need to check whether &'α T: Sync),
183 // so knowledge of the exact relationships between them isn't particularly important.
185 debug!("types in generator {:?}, span = {:?}", types, body.value.span);
188 let mut captured_tys = FxHashSet::default();
189 let type_causes: Vec<_> = types
191 .filter_map(|mut cause| {
192 // Erase regions and canonicalize late-bound regions to deduplicate as many types as we
194 let erased = fcx.tcx.erase_regions(cause.ty);
195 if captured_tys.insert(erased) {
196 // Replace all regions inside the generator interior with late bound regions.
197 // Note that each region slot in the types gets a new fresh late bound region,
198 // which means that none of the regions inside relate to any other, even if
199 // typeck had previously found constraints that would cause them to be related.
200 let folded = fcx.tcx.fold_regions(erased, &mut false, |_, current_depth| {
201 let br = ty::BoundRegion {
202 var: ty::BoundVar::from_u32(counter),
203 kind: ty::BrAnon(counter),
205 let r = fcx.tcx.mk_region(ty::ReLateBound(current_depth, br));
218 // Extract type components to build the witness type.
219 let type_list = fcx.tcx.mk_type_list(type_causes.iter().map(|cause| cause.ty));
220 let bound_vars = fcx.tcx.mk_bound_variable_kinds(
221 (0..counter).map(|i| ty::BoundVariableKind::Region(ty::BrAnon(i))),
224 fcx.tcx.mk_generator_witness(ty::Binder::bind_with_vars(type_list, bound_vars.clone()));
226 // Store the generator types and spans into the typeck results for this generator.
227 visitor.fcx.inh.typeck_results.borrow_mut().generator_interior_types =
228 ty::Binder::bind_with_vars(type_causes, bound_vars);
231 "types in generator after region replacement {:?}, span = {:?}",
232 witness, body.value.span
235 // Unify the type variable inside the generator with the new witness
236 match fcx.at(&fcx.misc(body.value.span), fcx.param_env).eq(interior, witness) {
237 Ok(ok) => fcx.register_infer_ok_obligations(ok),
242 // This visitor has to have the same visit_expr calls as RegionResolutionVisitor in
243 // librustc_middle/middle/region.rs since `expr_count` is compared against the results
245 impl<'a, 'tcx> Visitor<'tcx> for InteriorVisitor<'a, 'tcx> {
246 type Map = intravisit::ErasedMap<'tcx>;
248 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
249 NestedVisitorMap::None
252 fn visit_arm(&mut self, arm: &'tcx Arm<'tcx>) {
253 let Arm { guard, pat, body, .. } = arm;
255 if let Some(ref g) = guard {
256 self.guard_bindings.push(<_>::default());
258 guard_bindings_set: &mut self.guard_bindings_set,
262 .expect("should have pushed at least one earlier"),
267 Guard::If(ref e) => {
270 Guard::IfLet(ref pat, ref e) => {
276 let mut scope_var_ids =
277 self.guard_bindings.pop().expect("should have pushed at least one earlier");
278 for var_id in scope_var_ids.drain(..) {
279 self.guard_bindings_set.remove(&var_id);
282 self.visit_expr(body);
285 fn visit_pat(&mut self, pat: &'tcx Pat<'tcx>) {
286 intravisit::walk_pat(self, pat);
288 self.expr_count += 1;
290 if let PatKind::Binding(..) = pat.kind {
291 let scope = self.region_scope_tree.var_scope(pat.hir_id.local_id);
292 let ty = self.fcx.typeck_results.borrow().pat_ty(pat);
293 self.record(ty, Some(scope), None, pat.span, false);
297 fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
298 let mut guard_borrowing_from_pattern = false;
300 ExprKind::Call(callee, args) => match &callee.kind {
301 ExprKind::Path(qpath) => {
302 let res = self.fcx.typeck_results.borrow().qpath_res(qpath, callee.hir_id);
304 // Direct calls never need to keep the callee `ty::FnDef`
305 // ZST in a temporary, so skip its type, just in case it
306 // can significantly complicate the generator type.
308 DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn),
311 // NOTE(eddyb) this assumes a path expression has
312 // no nested expressions to keep track of.
313 self.expr_count += 1;
315 // Record the rest of the call expression normally.
317 self.visit_expr(arg);
320 _ => intravisit::walk_expr(self, expr),
323 _ => intravisit::walk_expr(self, expr),
325 ExprKind::Path(qpath) => {
326 intravisit::walk_expr(self, expr);
327 let res = self.fcx.typeck_results.borrow().qpath_res(qpath, expr.hir_id);
329 Res::Local(id) if self.guard_bindings_set.contains(&id) => {
330 guard_borrowing_from_pattern = true;
335 _ => intravisit::walk_expr(self, expr),
338 self.expr_count += 1;
340 let scope = self.region_scope_tree.temporary_scope(expr.hir_id.local_id);
342 // If there are adjustments, then record the final type --
343 // this is the actual value that is being produced.
344 if let Some(adjusted_ty) = self.fcx.typeck_results.borrow().expr_ty_adjusted_opt(expr) {
345 self.record(adjusted_ty, scope, Some(expr), expr.span, guard_borrowing_from_pattern);
348 // Also record the unadjusted type (which is the only type if
349 // there are no adjustments). The reason for this is that the
350 // unadjusted value is sometimes a "temporary" that would wind
351 // up in a MIR temporary.
353 // As an example, consider an expression like `vec![].push(x)`.
354 // Here, the `vec![]` would wind up MIR stored into a
355 // temporary variable `t` which we can borrow to invoke
356 // `<Vec<_>>::push(&mut t, x)`.
358 // Note that an expression can have many adjustments, and we
359 // are just ignoring those intermediate types. This is because
360 // those intermediate values are always linearly "consumed" by
361 // the other adjustments, and hence would never be directly
362 // captured in the MIR.
364 // (Note that this partly relies on the fact that the `Deref`
365 // traits always return references, which means their content
366 // can be reborrowed without needing to spill to a temporary.
367 // If this were not the case, then we could conceivably have
368 // to create intermediate temporaries.)
370 // The type table might not have information for this expression
371 // if it is in a malformed scope. (#66387)
372 if let Some(ty) = self.fcx.typeck_results.borrow().expr_ty_opt(expr) {
373 if guard_borrowing_from_pattern {
374 // Match guards create references to all the bindings in the pattern that are used
375 // in the guard, e.g. `y if is_even(y) => ...` becomes `is_even(*r_y)` where `r_y`
376 // is a reference to `y`, so we must record a reference to the type of the binding.
377 let tcx = self.fcx.tcx;
378 let ref_ty = tcx.mk_ref(
379 // Use `ReErased` as `resolve_interior` is going to replace all the regions anyway.
380 tcx.mk_region(ty::RegionKind::ReErased),
381 ty::TypeAndMut { ty, mutbl: hir::Mutability::Not },
383 self.record(ref_ty, scope, Some(expr), expr.span, guard_borrowing_from_pattern);
385 self.record(ty, scope, Some(expr), expr.span, guard_borrowing_from_pattern);
387 self.fcx.tcx.sess.delay_span_bug(expr.span, "no type for node");
392 struct ArmPatCollector<'a> {
393 guard_bindings_set: &'a mut HirIdSet,
394 guard_bindings: &'a mut SmallVec<[HirId; 4]>,
397 impl<'a, 'tcx> Visitor<'tcx> for ArmPatCollector<'a> {
398 type Map = intravisit::ErasedMap<'tcx>;
400 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
401 NestedVisitorMap::None
404 fn visit_pat(&mut self, pat: &'tcx Pat<'tcx>) {
405 intravisit::walk_pat(self, pat);
406 if let PatKind::Binding(_, id, ..) = pat.kind {
407 self.guard_bindings.push(id);
408 self.guard_bindings_set.insert(id);