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};
8 use rustc_errors::pluralize;
10 use rustc_hir::def::{CtorKind, DefKind, Res};
11 use rustc_hir::def_id::DefId;
12 use rustc_hir::hir_id::HirIdSet;
13 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
14 use rustc_hir::{Arm, Expr, ExprKind, Guard, HirId, Pat, PatKind};
15 use rustc_middle::middle::region::{self, YieldData};
16 use rustc_middle::ty::{self, Ty, TyCtxt};
17 use rustc_span::symbol::sym;
19 use smallvec::SmallVec;
22 struct InteriorVisitor<'a, 'tcx> {
23 fcx: &'a FnCtxt<'a, 'tcx>,
24 types: FxIndexSet<ty::GeneratorInteriorTypeCause<'tcx>>,
25 region_scope_tree: &'tcx region::ScopeTree,
27 kind: hir::GeneratorKind,
28 prev_unresolved_span: Option<Span>,
29 /// Match arm guards have temporary borrows from the pattern bindings.
30 /// In case there is a yield point in a guard with a reference to such bindings,
31 /// such borrows can span across this yield point.
32 /// As such, we need to track these borrows and record them despite of the fact
33 /// that they may succeed the said yield point in the post-order.
34 guard_bindings: SmallVec<[SmallVec<[HirId; 4]>; 1]>,
35 guard_bindings_set: HirIdSet,
38 impl<'a, 'tcx> InteriorVisitor<'a, 'tcx> {
43 scope: Option<region::Scope>,
44 expr: Option<&'tcx Expr<'tcx>>,
46 guard_borrowing_from_pattern: bool,
48 use rustc_span::DUMMY_SP;
51 "generator_interior: attempting to record type {:?} {:?} {:?} {:?}",
52 ty, scope, expr, source_span
55 let live_across_yield = scope
57 self.region_scope_tree.yield_in_scope(s).and_then(|yield_data| {
58 // If we are recording an expression that is the last yield
59 // in the scope, or that has a postorder CFG index larger
60 // than the one of all of the yields, then its value can't
61 // be storage-live (and therefore live) at any of the yields.
63 // See the mega-comment at `yield_in_scope` for a proof.
66 "comparing counts yield: {} self: {}, source_span = {:?}",
67 yield_data.expr_and_pat_count, self.expr_count, source_span
70 // If it is a borrowing happening in the guard,
71 // it needs to be recorded regardless because they
72 // do live across this yield point.
73 if guard_borrowing_from_pattern
74 || yield_data.expr_and_pat_count >= self.expr_count
83 Some(YieldData { span: DUMMY_SP, expr_and_pat_count: 0, source: self.kind.into() })
86 if let Some(yield_data) = live_across_yield {
87 let ty = self.fcx.resolve_vars_if_possible(ty);
89 "type in expr = {:?}, scope = {:?}, type = {:?}, count = {}, yield_span = {:?}",
90 expr, scope, ty, self.expr_count, yield_data.span
93 if let Some((unresolved_type, unresolved_type_span)) =
94 self.fcx.unresolved_type_vars(&ty)
96 // If unresolved type isn't a ty_var then unresolved_type_span is None
99 .unwrap_or_else(|| unresolved_type_span.unwrap_or(source_span));
101 // If we encounter an int/float variable, then inference fallback didn't
102 // finish due to some other error. Don't emit spurious additional errors.
103 if let ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(_)) =
104 unresolved_type.kind()
109 .delay_span_bug(span, &format!("Encountered var {:?}", unresolved_type));
112 "the type is part of the {} because of this {}",
113 self.kind, yield_data.source
117 .need_type_info_err_in_generator(self.kind, span, unresolved_type)
118 .span_note(yield_data.span, &*note)
122 // Insert the type into the ordered set.
123 let scope_span = scope.map(|s| s.span(self.fcx.tcx, self.region_scope_tree));
125 check_must_not_suspend_ty(
137 self.types.insert(ty::GeneratorInteriorTypeCause {
141 yield_span: yield_data.span,
142 expr: expr.map(|e| e.hir_id),
147 "no type in expr = {:?}, count = {:?}, span = {:?}",
152 let ty = self.fcx.resolve_vars_if_possible(ty);
153 if let Some((unresolved_type, unresolved_type_span)) =
154 self.fcx.unresolved_type_vars(&ty)
157 "remained unresolved_type = {:?}, unresolved_type_span: {:?}",
158 unresolved_type, unresolved_type_span
160 self.prev_unresolved_span = unresolved_type_span;
166 pub fn resolve_interior<'a, 'tcx>(
167 fcx: &'a FnCtxt<'a, 'tcx>,
169 body_id: hir::BodyId,
171 kind: hir::GeneratorKind,
173 let body = fcx.tcx.hir().body(body_id);
174 let mut visitor = InteriorVisitor {
176 types: FxIndexSet::default(),
177 region_scope_tree: fcx.tcx.region_scope_tree(def_id),
180 prev_unresolved_span: None,
181 guard_bindings: <_>::default(),
182 guard_bindings_set: <_>::default(),
184 intravisit::walk_body(&mut visitor, body);
186 // Check that we visited the same amount of expressions and the RegionResolutionVisitor
187 let region_expr_count = visitor.region_scope_tree.body_expr_count(body_id).unwrap();
188 assert_eq!(region_expr_count, visitor.expr_count);
190 // The types are already kept in insertion order.
191 let types = visitor.types;
193 // The types in the generator interior contain lifetimes local to the generator itself,
194 // which should not be exposed outside of the generator. Therefore, we replace these
195 // lifetimes with existentially-bound lifetimes, which reflect the exact value of the
196 // lifetimes not being known by users.
198 // These lifetimes are used in auto trait impl checking (for example,
199 // if a Sync generator contains an &'α T, we need to check whether &'α T: Sync),
200 // so knowledge of the exact relationships between them isn't particularly important.
202 debug!("types in generator {:?}, span = {:?}", types, body.value.span);
205 let mut captured_tys = FxHashSet::default();
206 let type_causes: Vec<_> = types
208 .filter_map(|mut cause| {
209 // Erase regions and canonicalize late-bound regions to deduplicate as many types as we
211 let erased = fcx.tcx.erase_regions(cause.ty);
212 if captured_tys.insert(erased) {
213 // Replace all regions inside the generator interior with late bound regions.
214 // Note that each region slot in the types gets a new fresh late bound region,
215 // which means that none of the regions inside relate to any other, even if
216 // typeck had previously found constraints that would cause them to be related.
217 let folded = fcx.tcx.fold_regions(erased, &mut false, |_, current_depth| {
218 let br = ty::BoundRegion {
219 var: ty::BoundVar::from_u32(counter),
220 kind: ty::BrAnon(counter),
222 let r = fcx.tcx.mk_region(ty::ReLateBound(current_depth, br));
235 // Extract type components to build the witness type.
236 let type_list = fcx.tcx.mk_type_list(type_causes.iter().map(|cause| cause.ty));
237 let bound_vars = fcx.tcx.mk_bound_variable_kinds(
238 (0..counter).map(|i| ty::BoundVariableKind::Region(ty::BrAnon(i))),
241 fcx.tcx.mk_generator_witness(ty::Binder::bind_with_vars(type_list, bound_vars.clone()));
243 // Store the generator types and spans into the typeck results for this generator.
244 visitor.fcx.inh.typeck_results.borrow_mut().generator_interior_types =
245 ty::Binder::bind_with_vars(type_causes, bound_vars);
248 "types in generator after region replacement {:?}, span = {:?}",
249 witness, body.value.span
252 // Unify the type variable inside the generator with the new witness
253 match fcx.at(&fcx.misc(body.value.span), fcx.param_env).eq(interior, witness) {
254 Ok(ok) => fcx.register_infer_ok_obligations(ok),
259 // This visitor has to have the same visit_expr calls as RegionResolutionVisitor in
260 // librustc_middle/middle/region.rs since `expr_count` is compared against the results
262 impl<'a, 'tcx> Visitor<'tcx> for InteriorVisitor<'a, 'tcx> {
263 type Map = intravisit::ErasedMap<'tcx>;
265 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
266 NestedVisitorMap::None
269 fn visit_arm(&mut self, arm: &'tcx Arm<'tcx>) {
270 let Arm { guard, pat, body, .. } = arm;
272 if let Some(ref g) = guard {
273 self.guard_bindings.push(<_>::default());
275 guard_bindings_set: &mut self.guard_bindings_set,
279 .expect("should have pushed at least one earlier"),
284 Guard::If(ref e) => {
287 Guard::IfLet(ref pat, ref e) => {
293 let mut scope_var_ids =
294 self.guard_bindings.pop().expect("should have pushed at least one earlier");
295 for var_id in scope_var_ids.drain(..) {
296 self.guard_bindings_set.remove(&var_id);
299 self.visit_expr(body);
302 fn visit_pat(&mut self, pat: &'tcx Pat<'tcx>) {
303 intravisit::walk_pat(self, pat);
305 self.expr_count += 1;
307 if let PatKind::Binding(..) = pat.kind {
308 let scope = self.region_scope_tree.var_scope(pat.hir_id.local_id);
309 let ty = self.fcx.typeck_results.borrow().pat_ty(pat);
310 self.record(ty, pat.hir_id, Some(scope), None, pat.span, false);
314 fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
315 let mut guard_borrowing_from_pattern = false;
317 ExprKind::Call(callee, args) => match &callee.kind {
318 ExprKind::Path(qpath) => {
319 let res = self.fcx.typeck_results.borrow().qpath_res(qpath, callee.hir_id);
321 // Direct calls never need to keep the callee `ty::FnDef`
322 // ZST in a temporary, so skip its type, just in case it
323 // can significantly complicate the generator type.
325 DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn),
328 // NOTE(eddyb) this assumes a path expression has
329 // no nested expressions to keep track of.
330 self.expr_count += 1;
332 // Record the rest of the call expression normally.
334 self.visit_expr(arg);
337 _ => intravisit::walk_expr(self, expr),
340 _ => intravisit::walk_expr(self, expr),
342 ExprKind::Path(qpath) => {
343 intravisit::walk_expr(self, expr);
344 let res = self.fcx.typeck_results.borrow().qpath_res(qpath, expr.hir_id);
346 Res::Local(id) if self.guard_bindings_set.contains(&id) => {
347 guard_borrowing_from_pattern = true;
352 _ => intravisit::walk_expr(self, expr),
355 self.expr_count += 1;
357 let scope = self.region_scope_tree.temporary_scope(expr.hir_id.local_id);
359 // If there are adjustments, then record the final type --
360 // this is the actual value that is being produced.
361 if let Some(adjusted_ty) = self.fcx.typeck_results.borrow().expr_ty_adjusted_opt(expr) {
368 guard_borrowing_from_pattern,
372 // Also record the unadjusted type (which is the only type if
373 // there are no adjustments). The reason for this is that the
374 // unadjusted value is sometimes a "temporary" that would wind
375 // up in a MIR temporary.
377 // As an example, consider an expression like `vec![].push(x)`.
378 // Here, the `vec![]` would wind up MIR stored into a
379 // temporary variable `t` which we can borrow to invoke
380 // `<Vec<_>>::push(&mut t, x)`.
382 // Note that an expression can have many adjustments, and we
383 // are just ignoring those intermediate types. This is because
384 // those intermediate values are always linearly "consumed" by
385 // the other adjustments, and hence would never be directly
386 // captured in the MIR.
388 // (Note that this partly relies on the fact that the `Deref`
389 // traits always return references, which means their content
390 // can be reborrowed without needing to spill to a temporary.
391 // If this were not the case, then we could conceivably have
392 // to create intermediate temporaries.)
394 // The type table might not have information for this expression
395 // if it is in a malformed scope. (#66387)
396 if let Some(ty) = self.fcx.typeck_results.borrow().expr_ty_opt(expr) {
397 if guard_borrowing_from_pattern {
398 // Match guards create references to all the bindings in the pattern that are used
399 // in the guard, e.g. `y if is_even(y) => ...` becomes `is_even(*r_y)` where `r_y`
400 // is a reference to `y`, so we must record a reference to the type of the binding.
401 let tcx = self.fcx.tcx;
402 let ref_ty = tcx.mk_ref(
403 // Use `ReErased` as `resolve_interior` is going to replace all the regions anyway.
404 tcx.mk_region(ty::RegionKind::ReErased),
405 ty::TypeAndMut { ty, mutbl: hir::Mutability::Not },
413 guard_borrowing_from_pattern,
422 guard_borrowing_from_pattern,
425 self.fcx.tcx.sess.delay_span_bug(expr.span, "no type for node");
430 struct ArmPatCollector<'a> {
431 guard_bindings_set: &'a mut HirIdSet,
432 guard_bindings: &'a mut SmallVec<[HirId; 4]>,
435 impl<'a, 'tcx> Visitor<'tcx> for ArmPatCollector<'a> {
436 type Map = intravisit::ErasedMap<'tcx>;
438 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
439 NestedVisitorMap::None
442 fn visit_pat(&mut self, pat: &'tcx Pat<'tcx>) {
443 intravisit::walk_pat(self, pat);
444 if let PatKind::Binding(_, id, ..) = pat.kind {
445 self.guard_bindings.push(id);
446 self.guard_bindings_set.insert(id);
451 // Returns whether it emitted a diagnostic or not
452 // Note that this fn and the proceding one are based on the code
453 // for creating must_use diagnostics
454 pub fn check_must_not_suspend_ty<'tcx>(
455 fcx: &FnCtxt<'_, 'tcx>,
458 expr: Option<&'tcx Expr<'tcx>>,
466 // || fcx.tcx.is_ty_uninhabited_from(fcx.tcx.parent_module(hir_id).to_def_id(), ty, fcx.param_env)
467 // FIXME: should this check is_ty_uninhabited_from
472 let plural_suffix = pluralize!(plural_len);
475 ty::Adt(..) if ty.is_box() => {
476 let boxed_ty = ty.boxed_ty();
477 let descr_pre = &format!("{}boxed ", descr_pre);
478 check_must_not_suspend_ty(
490 ty::Adt(def, _) => check_must_not_suspend_def(
499 ty::Opaque(def, _) => {
500 let mut has_emitted = false;
501 for &(predicate, _) in fcx.tcx.explicit_item_bounds(def) {
502 // We only look at the `DefId`, so it is safe to skip the binder here.
503 if let ty::PredicateKind::Trait(ref poly_trait_predicate) =
504 predicate.kind().skip_binder()
506 let def_id = poly_trait_predicate.trait_ref.def_id;
507 let descr_pre = &format!("{}implementer{} of ", descr_pre, plural_suffix,);
508 if check_must_not_suspend_def(
524 ty::Dynamic(binder, _) => {
525 let mut has_emitted = false;
526 for predicate in binder.iter() {
527 if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate.skip_binder() {
528 let def_id = trait_ref.def_id;
529 let descr_post = &format!(" trait object{}{}", plural_suffix, descr_post,);
530 if check_must_not_suspend_def(
546 ty::Tuple(ref tys) => {
547 let mut has_emitted = false;
548 let spans = if let Some(hir::ExprKind::Tup(comps)) = expr.map(|e| &e.kind) {
549 debug_assert_eq!(comps.len(), tys.len());
550 comps.iter().map(|e| e.span).collect()
554 for (i, ty) in tys.iter().map(|k| k.expect_ty()).enumerate() {
555 let descr_post = &format!(" in tuple element {}", i);
556 let span = *spans.get(i).unwrap_or(&source_span);
557 if check_must_not_suspend_ty(
558 fcx, ty, hir_id, expr, span, yield_span, descr_pre, descr_post, plural_len,
565 ty::Array(ty, len) => {
566 let descr_pre = &format!("{}array{} of ", descr_pre, plural_suffix,);
567 check_must_not_suspend_ty(
576 len.try_eval_usize(fcx.tcx, fcx.param_env).unwrap_or(0) as usize + 1,
583 fn check_must_not_suspend_def(
589 descr_pre_path: &str,
590 descr_post_path: &str,
592 for attr in tcx.get_attrs(def_id).iter() {
593 if attr.has_name(sym::must_not_suspend) {
594 tcx.struct_span_lint_hir(
595 rustc_session::lint::builtin::MUST_NOT_SUSPEND,
600 "{}`{}`{} held across a yield point, but should not be",
602 tcx.def_path_str(def_id),
605 let mut err = lint.build(&msg);
607 // Add optional reason note
608 if let Some(note) = attr.value_str() {
609 err.note(¬e.as_str());
612 // add span pointing to the offending yield/await)
613 err.span_label(yield_span, "The value is held across this yield point");
615 // Add some quick suggestions on what to do
618 "`drop` this value before the yield point, or use a block (`{ ... }`) \"
619 to shrink its scope",