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_const_eval::transform::generator` and may be a subset of the
4 //! types computed here.
6 use self::drop_ranges::DropRanges;
8 use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
9 use rustc_errors::pluralize;
11 use rustc_hir::def::{CtorKind, DefKind, Res};
12 use rustc_hir::def_id::DefId;
13 use rustc_hir::hir_id::HirIdSet;
14 use rustc_hir::intravisit::{self, Visitor};
15 use rustc_hir::{Arm, Expr, ExprKind, Guard, HirId, Pat, PatKind};
16 use rustc_middle::middle::region::{self, YieldData};
17 use rustc_middle::ty::{self, Ty, TyCtxt};
18 use rustc_span::symbol::sym;
20 use smallvec::SmallVec;
25 struct InteriorVisitor<'a, 'tcx> {
26 fcx: &'a FnCtxt<'a, 'tcx>,
27 types: FxIndexSet<ty::GeneratorInteriorTypeCause<'tcx>>,
28 region_scope_tree: &'tcx region::ScopeTree,
30 kind: hir::GeneratorKind,
31 prev_unresolved_span: Option<Span>,
32 /// Match arm guards have temporary borrows from the pattern bindings.
33 /// In case there is a yield point in a guard with a reference to such bindings,
34 /// such borrows can span across this yield point.
35 /// As such, we need to track these borrows and record them despite of the fact
36 /// that they may succeed the said yield point in the post-order.
37 guard_bindings: SmallVec<[SmallVec<[HirId; 4]>; 1]>,
38 guard_bindings_set: HirIdSet,
39 linted_values: HirIdSet,
40 drop_ranges: DropRanges,
43 impl<'a, 'tcx> InteriorVisitor<'a, 'tcx> {
48 scope: Option<region::Scope>,
49 expr: Option<&'tcx Expr<'tcx>>,
51 guard_borrowing_from_pattern: bool,
53 use rustc_span::DUMMY_SP;
55 let ty = self.fcx.resolve_vars_if_possible(ty);
58 "attempting to record type ty={:?}; hir_id={:?}; scope={:?}; expr={:?}; source_span={:?}; expr_count={:?}",
59 ty, hir_id, scope, expr, source_span, self.expr_count,
62 let live_across_yield = scope
64 self.region_scope_tree.yield_in_scope(s).and_then(|yield_data| {
65 // If we are recording an expression that is the last yield
66 // in the scope, or that has a postorder CFG index larger
67 // than the one of all of the yields, then its value can't
68 // be storage-live (and therefore live) at any of the yields.
70 // See the mega-comment at `yield_in_scope` for a proof.
76 "comparing counts yield: {} self: {}, source_span = {:?}",
77 yield_data.expr_and_pat_count, self.expr_count, source_span
80 if self.fcx.sess().opts.debugging_opts.drop_tracking
83 .is_dropped_at(hir_id, yield_data.expr_and_pat_count)
85 debug!("value is dropped at yield point; not recording");
89 // If it is a borrowing happening in the guard,
90 // it needs to be recorded regardless because they
91 // do live across this yield point.
92 guard_borrowing_from_pattern
93 || yield_data.expr_and_pat_count >= self.expr_count
99 Some(YieldData { span: DUMMY_SP, expr_and_pat_count: 0, source: self.kind.into() })
102 if let Some(yield_data) = live_across_yield {
104 "type in expr = {:?}, scope = {:?}, type = {:?}, count = {}, yield_span = {:?}",
105 expr, scope, ty, self.expr_count, yield_data.span
108 if let Some((unresolved_type, unresolved_type_span)) =
109 self.fcx.unresolved_type_vars(&ty)
111 // If unresolved type isn't a ty_var then unresolved_type_span is None
113 .prev_unresolved_span
114 .unwrap_or_else(|| unresolved_type_span.unwrap_or(source_span));
116 // If we encounter an int/float variable, then inference fallback didn't
117 // finish due to some other error. Don't emit spurious additional errors.
118 if let ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(_)) =
119 unresolved_type.kind()
124 .delay_span_bug(span, &format!("Encountered var {:?}", unresolved_type));
127 "the type is part of the {} because of this {}",
128 self.kind, yield_data.source
132 .need_type_info_err_in_generator(self.kind, span, unresolved_type)
133 .span_note(yield_data.span, &*note)
137 // Insert the type into the ordered set.
138 let scope_span = scope.map(|s| s.span(self.fcx.tcx, self.region_scope_tree));
140 if !self.linted_values.contains(&hir_id) {
141 check_must_not_suspend_ty(
148 yield_span: yield_data.span,
153 self.linted_values.insert(hir_id);
156 self.types.insert(ty::GeneratorInteriorTypeCause {
160 yield_span: yield_data.span,
161 expr: expr.map(|e| e.hir_id),
166 "no type in expr = {:?}, count = {:?}, span = {:?}",
171 if let Some((unresolved_type, unresolved_type_span)) =
172 self.fcx.unresolved_type_vars(&ty)
175 "remained unresolved_type = {:?}, unresolved_type_span: {:?}",
176 unresolved_type, unresolved_type_span
178 self.prev_unresolved_span = unresolved_type_span;
184 pub fn resolve_interior<'a, 'tcx>(
185 fcx: &'a FnCtxt<'a, 'tcx>,
187 body_id: hir::BodyId,
189 kind: hir::GeneratorKind,
191 let body = fcx.tcx.hir().body(body_id);
192 let mut visitor = InteriorVisitor {
194 types: FxIndexSet::default(),
195 region_scope_tree: fcx.tcx.region_scope_tree(def_id),
198 prev_unresolved_span: None,
199 guard_bindings: <_>::default(),
200 guard_bindings_set: <_>::default(),
201 linted_values: <_>::default(),
202 drop_ranges: drop_ranges::compute_drop_ranges(fcx, def_id, body),
204 intravisit::walk_body(&mut visitor, body);
206 // Check that we visited the same amount of expressions as the RegionResolutionVisitor
207 let region_expr_count = visitor.region_scope_tree.body_expr_count(body_id).unwrap();
208 assert_eq!(region_expr_count, visitor.expr_count);
210 // The types are already kept in insertion order.
211 let types = visitor.types;
213 // The types in the generator interior contain lifetimes local to the generator itself,
214 // which should not be exposed outside of the generator. Therefore, we replace these
215 // lifetimes with existentially-bound lifetimes, which reflect the exact value of the
216 // lifetimes not being known by users.
218 // These lifetimes are used in auto trait impl checking (for example,
219 // if a Sync generator contains an &'α T, we need to check whether &'α T: Sync),
220 // so knowledge of the exact relationships between them isn't particularly important.
222 debug!("types in generator {:?}, span = {:?}", types, body.value.span);
225 let mut captured_tys = FxHashSet::default();
226 let type_causes: Vec<_> = types
228 .filter_map(|mut cause| {
229 // Erase regions and canonicalize late-bound regions to deduplicate as many types as we
231 let erased = fcx.tcx.erase_regions(cause.ty);
232 if captured_tys.insert(erased) {
233 // Replace all regions inside the generator interior with late bound regions.
234 // Note that each region slot in the types gets a new fresh late bound region,
235 // which means that none of the regions inside relate to any other, even if
236 // typeck had previously found constraints that would cause them to be related.
237 let folded = fcx.tcx.fold_regions(erased, &mut false, |_, current_depth| {
238 let br = ty::BoundRegion {
239 var: ty::BoundVar::from_u32(counter),
240 kind: ty::BrAnon(counter),
242 let r = fcx.tcx.mk_region(ty::ReLateBound(current_depth, br));
255 // Extract type components to build the witness type.
256 let type_list = fcx.tcx.mk_type_list(type_causes.iter().map(|cause| cause.ty));
257 let bound_vars = fcx.tcx.mk_bound_variable_kinds(
258 (0..counter).map(|i| ty::BoundVariableKind::Region(ty::BrAnon(i))),
261 fcx.tcx.mk_generator_witness(ty::Binder::bind_with_vars(type_list, bound_vars.clone()));
263 // Store the generator types and spans into the typeck results for this generator.
264 visitor.fcx.inh.typeck_results.borrow_mut().generator_interior_types =
265 ty::Binder::bind_with_vars(type_causes, bound_vars);
268 "types in generator after region replacement {:?}, span = {:?}",
269 witness, body.value.span
272 // Unify the type variable inside the generator with the new witness
273 match fcx.at(&fcx.misc(body.value.span), fcx.param_env).eq(interior, witness) {
274 Ok(ok) => fcx.register_infer_ok_obligations(ok),
279 // This visitor has to have the same visit_expr calls as RegionResolutionVisitor in
280 // librustc_middle/middle/region.rs since `expr_count` is compared against the results
282 impl<'a, 'tcx> Visitor<'tcx> for InteriorVisitor<'a, 'tcx> {
283 fn visit_arm(&mut self, arm: &'tcx Arm<'tcx>) {
284 let Arm { guard, pat, body, .. } = arm;
286 if let Some(ref g) = guard {
287 self.guard_bindings.push(<_>::default());
289 guard_bindings_set: &mut self.guard_bindings_set,
293 .expect("should have pushed at least one earlier"),
298 Guard::If(ref e) => {
301 Guard::IfLet(ref pat, ref e) => {
307 let mut scope_var_ids =
308 self.guard_bindings.pop().expect("should have pushed at least one earlier");
309 for var_id in scope_var_ids.drain(..) {
310 self.guard_bindings_set.remove(&var_id);
313 self.visit_expr(body);
316 fn visit_pat(&mut self, pat: &'tcx Pat<'tcx>) {
317 intravisit::walk_pat(self, pat);
319 self.expr_count += 1;
321 if let PatKind::Binding(..) = pat.kind {
322 let scope = self.region_scope_tree.var_scope(pat.hir_id.local_id);
323 let ty = self.fcx.typeck_results.borrow().pat_ty(pat);
324 self.record(ty, pat.hir_id, Some(scope), None, pat.span, false);
328 fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
329 let mut guard_borrowing_from_pattern = false;
332 ExprKind::Call(callee, args) => match &callee.kind {
333 ExprKind::Path(qpath) => {
334 let res = self.fcx.typeck_results.borrow().qpath_res(qpath, callee.hir_id);
336 // Direct calls never need to keep the callee `ty::FnDef`
337 // ZST in a temporary, so skip its type, just in case it
338 // can significantly complicate the generator type.
340 DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn),
343 // NOTE(eddyb) this assumes a path expression has
344 // no nested expressions to keep track of.
345 self.expr_count += 1;
347 // Record the rest of the call expression normally.
349 self.visit_expr(arg);
352 _ => intravisit::walk_expr(self, expr),
355 _ => intravisit::walk_expr(self, expr),
357 ExprKind::Path(qpath) => {
358 intravisit::walk_expr(self, expr);
359 let res = self.fcx.typeck_results.borrow().qpath_res(qpath, expr.hir_id);
361 Res::Local(id) if self.guard_bindings_set.contains(&id) => {
362 guard_borrowing_from_pattern = true;
367 _ => intravisit::walk_expr(self, expr),
370 self.expr_count += 1;
372 let scope = self.region_scope_tree.temporary_scope(expr.hir_id.local_id);
374 // If there are adjustments, then record the final type --
375 // this is the actual value that is being produced.
376 if let Some(adjusted_ty) = self.fcx.typeck_results.borrow().expr_ty_adjusted_opt(expr) {
383 guard_borrowing_from_pattern,
387 // Also record the unadjusted type (which is the only type if
388 // there are no adjustments). The reason for this is that the
389 // unadjusted value is sometimes a "temporary" that would wind
390 // up in a MIR temporary.
392 // As an example, consider an expression like `vec![].push(x)`.
393 // Here, the `vec![]` would wind up MIR stored into a
394 // temporary variable `t` which we can borrow to invoke
395 // `<Vec<_>>::push(&mut t, x)`.
397 // Note that an expression can have many adjustments, and we
398 // are just ignoring those intermediate types. This is because
399 // those intermediate values are always linearly "consumed" by
400 // the other adjustments, and hence would never be directly
401 // captured in the MIR.
403 // (Note that this partly relies on the fact that the `Deref`
404 // traits always return references, which means their content
405 // can be reborrowed without needing to spill to a temporary.
406 // If this were not the case, then we could conceivably have
407 // to create intermediate temporaries.)
409 // The type table might not have information for this expression
410 // if it is in a malformed scope. (#66387)
411 if let Some(ty) = self.fcx.typeck_results.borrow().expr_ty_opt(expr) {
412 if guard_borrowing_from_pattern {
413 // Match guards create references to all the bindings in the pattern that are used
414 // in the guard, e.g. `y if is_even(y) => ...` becomes `is_even(*r_y)` where `r_y`
415 // is a reference to `y`, so we must record a reference to the type of the binding.
416 let tcx = self.fcx.tcx;
417 let ref_ty = tcx.mk_ref(
418 // Use `ReErased` as `resolve_interior` is going to replace all the regions anyway.
419 tcx.mk_region(ty::ReErased),
420 ty::TypeAndMut { ty, mutbl: hir::Mutability::Not },
428 guard_borrowing_from_pattern,
437 guard_borrowing_from_pattern,
440 self.fcx.tcx.sess.delay_span_bug(expr.span, "no type for node");
445 struct ArmPatCollector<'a> {
446 guard_bindings_set: &'a mut HirIdSet,
447 guard_bindings: &'a mut SmallVec<[HirId; 4]>,
450 impl<'a, 'tcx> Visitor<'tcx> for ArmPatCollector<'a> {
451 fn visit_pat(&mut self, pat: &'tcx Pat<'tcx>) {
452 intravisit::walk_pat(self, pat);
453 if let PatKind::Binding(_, id, ..) = pat.kind {
454 self.guard_bindings.push(id);
455 self.guard_bindings_set.insert(id);
461 pub struct SuspendCheckData<'a, 'tcx> {
462 expr: Option<&'tcx Expr<'tcx>>,
470 // Returns whether it emitted a diagnostic or not
471 // Note that this fn and the proceding one are based on the code
472 // for creating must_use diagnostics
474 // Note that this technique was chosen over things like a `Suspend` marker trait
475 // as it is simpler and has precendent in the compiler
476 pub fn check_must_not_suspend_ty<'tcx>(
477 fcx: &FnCtxt<'_, 'tcx>,
480 data: SuspendCheckData<'_, 'tcx>,
483 // FIXME: should this check `is_ty_uninhabited_from`. This query is not available in this stage
484 // of typeck (before ReVar and RePlaceholder are removed), but may remove noise, like in
486 // || fcx.tcx.is_ty_uninhabited_from(fcx.tcx.parent_module(hir_id).to_def_id(), ty, fcx.param_env)
491 let plural_suffix = pluralize!(data.plural_len);
494 ty::Adt(..) if ty.is_box() => {
495 let boxed_ty = ty.boxed_ty();
496 let descr_pre = &format!("{}boxed ", data.descr_pre);
497 check_must_not_suspend_ty(fcx, boxed_ty, hir_id, SuspendCheckData { descr_pre, ..data })
499 ty::Adt(def, _) => check_must_not_suspend_def(fcx.tcx, def.did, hir_id, data),
500 // FIXME: support adding the attribute to TAITs
501 ty::Opaque(def, _) => {
502 let mut has_emitted = false;
503 for &(predicate, _) in fcx.tcx.explicit_item_bounds(def) {
504 // We only look at the `DefId`, so it is safe to skip the binder here.
505 if let ty::PredicateKind::Trait(ref poly_trait_predicate) =
506 predicate.kind().skip_binder()
508 let def_id = poly_trait_predicate.trait_ref.def_id;
509 let descr_pre = &format!("{}implementer{} of ", data.descr_pre, plural_suffix);
510 if check_must_not_suspend_def(
514 SuspendCheckData { descr_pre, ..data },
523 ty::Dynamic(binder, _) => {
524 let mut has_emitted = false;
525 for predicate in binder.iter() {
526 if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate.skip_binder() {
527 let def_id = trait_ref.def_id;
528 let descr_post = &format!(" trait object{}{}", plural_suffix, data.descr_post);
529 if check_must_not_suspend_def(
533 SuspendCheckData { descr_post, ..data },
543 let mut has_emitted = false;
544 let comps = match data.expr.map(|e| &e.kind) {
545 Some(hir::ExprKind::Tup(comps)) => {
546 debug_assert_eq!(comps.len(), ty.tuple_fields().count());
551 for (i, ty) in ty.tuple_fields().enumerate() {
552 let descr_post = &format!(" in tuple element {}", i);
553 let span = comps.and_then(|c| c.get(i)).map(|e| e.span).unwrap_or(data.source_span);
554 if check_must_not_suspend_ty(
560 expr: comps.and_then(|comps| comps.get(i)),
570 ty::Array(ty, len) => {
571 let descr_pre = &format!("{}array{} of ", data.descr_pre, plural_suffix);
572 check_must_not_suspend_ty(
578 plural_len: len.try_eval_usize(fcx.tcx, fcx.param_env).unwrap_or(0) as usize
588 fn check_must_not_suspend_def(
592 data: SuspendCheckData<'_, '_>,
594 for attr in tcx.get_attrs(def_id).iter() {
595 if attr.has_name(sym::must_not_suspend) {
596 tcx.struct_span_lint_hir(
597 rustc_session::lint::builtin::MUST_NOT_SUSPEND,
602 "{}`{}`{} held across a suspend point, but should not be",
604 tcx.def_path_str(def_id),
607 let mut err = lint.build(&msg);
609 // add span pointing to the offending yield/await
610 err.span_label(data.yield_span, "the value is held across this suspend point");
612 // Add optional reason note
613 if let Some(note) = attr.value_str() {
614 // FIXME(guswynn): consider formatting this better
615 err.span_note(data.source_span, note.as_str());
618 // Add some quick suggestions on what to do
619 // FIXME: can `drop` work as a suggestion here as well?
622 "consider using a block (`{ ... }`) \
623 to shrink the value's scope, ending before the suspend point",