]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/generator_interior.rs
Auto merge of #94105 - 5225225:destabilise-entry-insert, r=Mark-Simulacrum
[rust.git] / compiler / rustc_typeck / src / check / generator_interior.rs
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.
5
6 use self::drop_ranges::DropRanges;
7 use super::FnCtxt;
8 use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
9 use rustc_errors::pluralize;
10 use rustc_hir as hir;
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;
19 use rustc_span::Span;
20 use smallvec::SmallVec;
21 use tracing::debug;
22
23 mod drop_ranges;
24
25 struct InteriorVisitor<'a, 'tcx> {
26     fcx: &'a FnCtxt<'a, 'tcx>,
27     types: FxIndexSet<ty::GeneratorInteriorTypeCause<'tcx>>,
28     region_scope_tree: &'tcx region::ScopeTree,
29     expr_count: usize,
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,
41 }
42
43 impl<'a, 'tcx> InteriorVisitor<'a, 'tcx> {
44     fn record(
45         &mut self,
46         ty: Ty<'tcx>,
47         hir_id: HirId,
48         scope: Option<region::Scope>,
49         expr: Option<&'tcx Expr<'tcx>>,
50         source_span: Span,
51         guard_borrowing_from_pattern: bool,
52     ) {
53         use rustc_span::DUMMY_SP;
54
55         let ty = self.fcx.resolve_vars_if_possible(ty);
56
57         debug!(
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,
60         );
61
62         let live_across_yield = scope
63             .map(|s| {
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.
69                     //
70                     // See the mega-comment at `yield_in_scope` for a proof.
71
72                     yield_data
73                         .iter()
74                         .find(|yield_data| {
75                             debug!(
76                                 "comparing counts yield: {} self: {}, source_span = {:?}",
77                                 yield_data.expr_and_pat_count, self.expr_count, source_span
78                             );
79
80                             if self.fcx.sess().opts.debugging_opts.drop_tracking
81                                 && self
82                                     .drop_ranges
83                                     .is_dropped_at(hir_id, yield_data.expr_and_pat_count)
84                             {
85                                 debug!("value is dropped at yield point; not recording");
86                                 return false;
87                             }
88
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
94                         })
95                         .cloned()
96                 })
97             })
98             .unwrap_or_else(|| {
99                 Some(YieldData { span: DUMMY_SP, expr_and_pat_count: 0, source: self.kind.into() })
100             });
101
102         if let Some(yield_data) = live_across_yield {
103             debug!(
104                 "type in expr = {:?}, scope = {:?}, type = {:?}, count = {}, yield_span = {:?}",
105                 expr, scope, ty, self.expr_count, yield_data.span
106             );
107
108             if let Some((unresolved_type, unresolved_type_span)) =
109                 self.fcx.unresolved_type_vars(&ty)
110             {
111                 // If unresolved type isn't a ty_var then unresolved_type_span is None
112                 let span = self
113                     .prev_unresolved_span
114                     .unwrap_or_else(|| unresolved_type_span.unwrap_or(source_span));
115
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()
120                 {
121                     self.fcx
122                         .tcx
123                         .sess
124                         .delay_span_bug(span, &format!("Encountered var {:?}", unresolved_type));
125                 } else {
126                     let note = format!(
127                         "the type is part of the {} because of this {}",
128                         self.kind, yield_data.source
129                     );
130
131                     self.fcx
132                         .need_type_info_err_in_generator(self.kind, span, unresolved_type)
133                         .span_note(yield_data.span, &*note)
134                         .emit();
135                 }
136             } else {
137                 // Insert the type into the ordered set.
138                 let scope_span = scope.map(|s| s.span(self.fcx.tcx, self.region_scope_tree));
139
140                 if !self.linted_values.contains(&hir_id) {
141                     check_must_not_suspend_ty(
142                         self.fcx,
143                         ty,
144                         hir_id,
145                         SuspendCheckData {
146                             expr,
147                             source_span,
148                             yield_span: yield_data.span,
149                             plural_len: 1,
150                             ..Default::default()
151                         },
152                     );
153                     self.linted_values.insert(hir_id);
154                 }
155
156                 self.types.insert(ty::GeneratorInteriorTypeCause {
157                     span: source_span,
158                     ty,
159                     scope_span,
160                     yield_span: yield_data.span,
161                     expr: expr.map(|e| e.hir_id),
162                 });
163             }
164         } else {
165             debug!(
166                 "no type in expr = {:?}, count = {:?}, span = {:?}",
167                 expr,
168                 self.expr_count,
169                 expr.map(|e| e.span)
170             );
171             if let Some((unresolved_type, unresolved_type_span)) =
172                 self.fcx.unresolved_type_vars(&ty)
173             {
174                 debug!(
175                     "remained unresolved_type = {:?}, unresolved_type_span: {:?}",
176                     unresolved_type, unresolved_type_span
177                 );
178                 self.prev_unresolved_span = unresolved_type_span;
179             }
180         }
181     }
182 }
183
184 pub fn resolve_interior<'a, 'tcx>(
185     fcx: &'a FnCtxt<'a, 'tcx>,
186     def_id: DefId,
187     body_id: hir::BodyId,
188     interior: Ty<'tcx>,
189     kind: hir::GeneratorKind,
190 ) {
191     let body = fcx.tcx.hir().body(body_id);
192     let mut visitor = InteriorVisitor {
193         fcx,
194         types: FxIndexSet::default(),
195         region_scope_tree: fcx.tcx.region_scope_tree(def_id),
196         expr_count: 0,
197         kind,
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),
203     };
204     intravisit::walk_body(&mut visitor, body);
205
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);
209
210     // The types are already kept in insertion order.
211     let types = visitor.types;
212
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.
217     //
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.
221
222     debug!("types in generator {:?}, span = {:?}", types, body.value.span);
223
224     let mut counter = 0;
225     let mut captured_tys = FxHashSet::default();
226     let type_causes: Vec<_> = types
227         .into_iter()
228         .filter_map(|mut cause| {
229             // Erase regions and canonicalize late-bound regions to deduplicate as many types as we
230             // can.
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),
241                     };
242                     let r = fcx.tcx.mk_region(ty::ReLateBound(current_depth, br));
243                     counter += 1;
244                     r
245                 });
246
247                 cause.ty = folded;
248                 Some(cause)
249             } else {
250                 None
251             }
252         })
253         .collect();
254
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))),
259     );
260     let witness =
261         fcx.tcx.mk_generator_witness(ty::Binder::bind_with_vars(type_list, bound_vars.clone()));
262
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);
266
267     debug!(
268         "types in generator after region replacement {:?}, span = {:?}",
269         witness, body.value.span
270     );
271
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),
275         _ => bug!(),
276     }
277 }
278
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
281 // there.
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;
285         self.visit_pat(pat);
286         if let Some(ref g) = guard {
287             self.guard_bindings.push(<_>::default());
288             ArmPatCollector {
289                 guard_bindings_set: &mut self.guard_bindings_set,
290                 guard_bindings: self
291                     .guard_bindings
292                     .last_mut()
293                     .expect("should have pushed at least one earlier"),
294             }
295             .visit_pat(pat);
296
297             match g {
298                 Guard::If(ref e) => {
299                     self.visit_expr(e);
300                 }
301                 Guard::IfLet(ref pat, ref e) => {
302                     self.visit_pat(pat);
303                     self.visit_expr(e);
304                 }
305             }
306
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);
311             }
312         }
313         self.visit_expr(body);
314     }
315
316     fn visit_pat(&mut self, pat: &'tcx Pat<'tcx>) {
317         intravisit::walk_pat(self, pat);
318
319         self.expr_count += 1;
320
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);
325         }
326     }
327
328     fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
329         let mut guard_borrowing_from_pattern = false;
330
331         match &expr.kind {
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);
335                     match res {
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.
339                         Res::Def(
340                             DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn),
341                             _,
342                         ) => {
343                             // NOTE(eddyb) this assumes a path expression has
344                             // no nested expressions to keep track of.
345                             self.expr_count += 1;
346
347                             // Record the rest of the call expression normally.
348                             for arg in *args {
349                                 self.visit_expr(arg);
350                             }
351                         }
352                         _ => intravisit::walk_expr(self, expr),
353                     }
354                 }
355                 _ => intravisit::walk_expr(self, expr),
356             },
357             ExprKind::Path(qpath) => {
358                 intravisit::walk_expr(self, expr);
359                 let res = self.fcx.typeck_results.borrow().qpath_res(qpath, expr.hir_id);
360                 match res {
361                     Res::Local(id) if self.guard_bindings_set.contains(&id) => {
362                         guard_borrowing_from_pattern = true;
363                     }
364                     _ => {}
365                 }
366             }
367             _ => intravisit::walk_expr(self, expr),
368         }
369
370         self.expr_count += 1;
371
372         let scope = self.region_scope_tree.temporary_scope(expr.hir_id.local_id);
373
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) {
377             self.record(
378                 adjusted_ty,
379                 expr.hir_id,
380                 scope,
381                 Some(expr),
382                 expr.span,
383                 guard_borrowing_from_pattern,
384             );
385         }
386
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.
391         //
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)`.
396         //
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.
402         //
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.)
408         //
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 },
421                 );
422                 self.record(
423                     ref_ty,
424                     expr.hir_id,
425                     scope,
426                     Some(expr),
427                     expr.span,
428                     guard_borrowing_from_pattern,
429                 );
430             }
431             self.record(
432                 ty,
433                 expr.hir_id,
434                 scope,
435                 Some(expr),
436                 expr.span,
437                 guard_borrowing_from_pattern,
438             );
439         } else {
440             self.fcx.tcx.sess.delay_span_bug(expr.span, "no type for node");
441         }
442     }
443 }
444
445 struct ArmPatCollector<'a> {
446     guard_bindings_set: &'a mut HirIdSet,
447     guard_bindings: &'a mut SmallVec<[HirId; 4]>,
448 }
449
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);
456         }
457     }
458 }
459
460 #[derive(Default)]
461 pub struct SuspendCheckData<'a, 'tcx> {
462     expr: Option<&'tcx Expr<'tcx>>,
463     source_span: Span,
464     yield_span: Span,
465     descr_pre: &'a str,
466     descr_post: &'a str,
467     plural_len: usize,
468 }
469
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
473 //
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>,
478     ty: Ty<'tcx>,
479     hir_id: HirId,
480     data: SuspendCheckData<'_, 'tcx>,
481 ) -> bool {
482     if ty.is_unit()
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
485     // `must_use`
486     // || fcx.tcx.is_ty_uninhabited_from(fcx.tcx.parent_module(hir_id).to_def_id(), ty, fcx.param_env)
487     {
488         return false;
489     }
490
491     let plural_suffix = pluralize!(data.plural_len);
492
493     match *ty.kind() {
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 })
498         }
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()
507                 {
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(
511                         fcx.tcx,
512                         def_id,
513                         hir_id,
514                         SuspendCheckData { descr_pre, ..data },
515                     ) {
516                         has_emitted = true;
517                         break;
518                     }
519                 }
520             }
521             has_emitted
522         }
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(
530                         fcx.tcx,
531                         def_id,
532                         hir_id,
533                         SuspendCheckData { descr_post, ..data },
534                     ) {
535                         has_emitted = true;
536                         break;
537                     }
538                 }
539             }
540             has_emitted
541         }
542         ty::Tuple(_) => {
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());
547                     Some(comps)
548                 }
549                 _ => None,
550             };
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(
555                     fcx,
556                     ty,
557                     hir_id,
558                     SuspendCheckData {
559                         descr_post,
560                         expr: comps.and_then(|comps| comps.get(i)),
561                         source_span: span,
562                         ..data
563                     },
564                 ) {
565                     has_emitted = true;
566                 }
567             }
568             has_emitted
569         }
570         ty::Array(ty, len) => {
571             let descr_pre = &format!("{}array{} of ", data.descr_pre, plural_suffix);
572             check_must_not_suspend_ty(
573                 fcx,
574                 ty,
575                 hir_id,
576                 SuspendCheckData {
577                     descr_pre,
578                     plural_len: len.try_eval_usize(fcx.tcx, fcx.param_env).unwrap_or(0) as usize
579                         + 1,
580                     ..data
581                 },
582             )
583         }
584         _ => false,
585     }
586 }
587
588 fn check_must_not_suspend_def(
589     tcx: TyCtxt<'_>,
590     def_id: DefId,
591     hir_id: HirId,
592     data: SuspendCheckData<'_, '_>,
593 ) -> bool {
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,
598                 hir_id,
599                 data.source_span,
600                 |lint| {
601                     let msg = format!(
602                         "{}`{}`{} held across a suspend point, but should not be",
603                         data.descr_pre,
604                         tcx.def_path_str(def_id),
605                         data.descr_post,
606                     );
607                     let mut err = lint.build(&msg);
608
609                     // add span pointing to the offending yield/await
610                     err.span_label(data.yield_span, "the value is held across this suspend point");
611
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());
616                     }
617
618                     // Add some quick suggestions on what to do
619                     // FIXME: can `drop` work as a suggestion here as well?
620                     err.span_help(
621                         data.source_span,
622                         "consider using a block (`{ ... }`) \
623                         to shrink the value's scope, ending before the suspend point",
624                     );
625
626                     err.emit();
627                 },
628             );
629
630             return true;
631         }
632     }
633     false
634 }