]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/generator_interior.rs
Rollup merge of #93568 - willcrichton:scrape-examples-leading-whitespace, r=CraftSpider
[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 // FIXME(eholk): This flag is here to give a quick way to disable drop tracking in case we find
26 // unexpected breakages while it's still new. It should be removed before too long. For example,
27 // see #93161.
28 const ENABLE_DROP_TRACKING: bool = false;
29
30 struct InteriorVisitor<'a, 'tcx> {
31     fcx: &'a FnCtxt<'a, 'tcx>,
32     types: FxIndexSet<ty::GeneratorInteriorTypeCause<'tcx>>,
33     region_scope_tree: &'tcx region::ScopeTree,
34     expr_count: usize,
35     kind: hir::GeneratorKind,
36     prev_unresolved_span: Option<Span>,
37     /// Match arm guards have temporary borrows from the pattern bindings.
38     /// In case there is a yield point in a guard with a reference to such bindings,
39     /// such borrows can span across this yield point.
40     /// As such, we need to track these borrows and record them despite of the fact
41     /// that they may succeed the said yield point in the post-order.
42     guard_bindings: SmallVec<[SmallVec<[HirId; 4]>; 1]>,
43     guard_bindings_set: HirIdSet,
44     linted_values: HirIdSet,
45     drop_ranges: DropRanges,
46 }
47
48 impl<'a, 'tcx> InteriorVisitor<'a, 'tcx> {
49     fn record(
50         &mut self,
51         ty: Ty<'tcx>,
52         hir_id: HirId,
53         scope: Option<region::Scope>,
54         expr: Option<&'tcx Expr<'tcx>>,
55         source_span: Span,
56         guard_borrowing_from_pattern: bool,
57     ) {
58         use rustc_span::DUMMY_SP;
59
60         let ty = self.fcx.resolve_vars_if_possible(ty);
61
62         debug!(
63             "attempting to record type ty={:?}; hir_id={:?}; scope={:?}; expr={:?}; source_span={:?}; expr_count={:?}",
64             ty, hir_id, scope, expr, source_span, self.expr_count,
65         );
66
67         let live_across_yield = scope
68             .map(|s| {
69                 self.region_scope_tree.yield_in_scope(s).and_then(|yield_data| {
70                     // If we are recording an expression that is the last yield
71                     // in the scope, or that has a postorder CFG index larger
72                     // than the one of all of the yields, then its value can't
73                     // be storage-live (and therefore live) at any of the yields.
74                     //
75                     // See the mega-comment at `yield_in_scope` for a proof.
76
77                     yield_data
78                         .iter()
79                         .find(|yield_data| {
80                             debug!(
81                                 "comparing counts yield: {} self: {}, source_span = {:?}",
82                                 yield_data.expr_and_pat_count, self.expr_count, source_span
83                             );
84
85                             if ENABLE_DROP_TRACKING
86                                 && self
87                                     .drop_ranges
88                                     .is_dropped_at(hir_id, yield_data.expr_and_pat_count)
89                             {
90                                 debug!("value is dropped at yield point; not recording");
91                                 return false;
92                             }
93
94                             // If it is a borrowing happening in the guard,
95                             // it needs to be recorded regardless because they
96                             // do live across this yield point.
97                             guard_borrowing_from_pattern
98                                 || yield_data.expr_and_pat_count >= self.expr_count
99                         })
100                         .cloned()
101                 })
102             })
103             .unwrap_or_else(|| {
104                 Some(YieldData { span: DUMMY_SP, expr_and_pat_count: 0, source: self.kind.into() })
105             });
106
107         if let Some(yield_data) = live_across_yield {
108             debug!(
109                 "type in expr = {:?}, scope = {:?}, type = {:?}, count = {}, yield_span = {:?}",
110                 expr, scope, ty, self.expr_count, yield_data.span
111             );
112
113             if let Some((unresolved_type, unresolved_type_span)) =
114                 self.fcx.unresolved_type_vars(&ty)
115             {
116                 // If unresolved type isn't a ty_var then unresolved_type_span is None
117                 let span = self
118                     .prev_unresolved_span
119                     .unwrap_or_else(|| unresolved_type_span.unwrap_or(source_span));
120
121                 // If we encounter an int/float variable, then inference fallback didn't
122                 // finish due to some other error. Don't emit spurious additional errors.
123                 if let ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(_)) =
124                     unresolved_type.kind()
125                 {
126                     self.fcx
127                         .tcx
128                         .sess
129                         .delay_span_bug(span, &format!("Encountered var {:?}", unresolved_type));
130                 } else {
131                     let note = format!(
132                         "the type is part of the {} because of this {}",
133                         self.kind, yield_data.source
134                     );
135
136                     self.fcx
137                         .need_type_info_err_in_generator(self.kind, span, unresolved_type)
138                         .span_note(yield_data.span, &*note)
139                         .emit();
140                 }
141             } else {
142                 // Insert the type into the ordered set.
143                 let scope_span = scope.map(|s| s.span(self.fcx.tcx, self.region_scope_tree));
144
145                 if !self.linted_values.contains(&hir_id) {
146                     check_must_not_suspend_ty(
147                         self.fcx,
148                         ty,
149                         hir_id,
150                         SuspendCheckData {
151                             expr,
152                             source_span,
153                             yield_span: yield_data.span,
154                             plural_len: 1,
155                             ..Default::default()
156                         },
157                     );
158                     self.linted_values.insert(hir_id);
159                 }
160
161                 self.types.insert(ty::GeneratorInteriorTypeCause {
162                     span: source_span,
163                     ty: &ty,
164                     scope_span,
165                     yield_span: yield_data.span,
166                     expr: expr.map(|e| e.hir_id),
167                 });
168             }
169         } else {
170             debug!(
171                 "no type in expr = {:?}, count = {:?}, span = {:?}",
172                 expr,
173                 self.expr_count,
174                 expr.map(|e| e.span)
175             );
176             if let Some((unresolved_type, unresolved_type_span)) =
177                 self.fcx.unresolved_type_vars(&ty)
178             {
179                 debug!(
180                     "remained unresolved_type = {:?}, unresolved_type_span: {:?}",
181                     unresolved_type, unresolved_type_span
182                 );
183                 self.prev_unresolved_span = unresolved_type_span;
184             }
185         }
186     }
187 }
188
189 pub fn resolve_interior<'a, 'tcx>(
190     fcx: &'a FnCtxt<'a, 'tcx>,
191     def_id: DefId,
192     body_id: hir::BodyId,
193     interior: Ty<'tcx>,
194     kind: hir::GeneratorKind,
195 ) {
196     let body = fcx.tcx.hir().body(body_id);
197     let mut visitor = InteriorVisitor {
198         fcx,
199         types: FxIndexSet::default(),
200         region_scope_tree: fcx.tcx.region_scope_tree(def_id),
201         expr_count: 0,
202         kind,
203         prev_unresolved_span: None,
204         guard_bindings: <_>::default(),
205         guard_bindings_set: <_>::default(),
206         linted_values: <_>::default(),
207         drop_ranges: drop_ranges::compute_drop_ranges(fcx, def_id, body),
208     };
209     intravisit::walk_body(&mut visitor, body);
210
211     // Check that we visited the same amount of expressions and the RegionResolutionVisitor
212     let region_expr_count = visitor.region_scope_tree.body_expr_count(body_id).unwrap();
213     assert_eq!(region_expr_count, visitor.expr_count);
214
215     // The types are already kept in insertion order.
216     let types = visitor.types;
217
218     // The types in the generator interior contain lifetimes local to the generator itself,
219     // which should not be exposed outside of the generator. Therefore, we replace these
220     // lifetimes with existentially-bound lifetimes, which reflect the exact value of the
221     // lifetimes not being known by users.
222     //
223     // These lifetimes are used in auto trait impl checking (for example,
224     // if a Sync generator contains an &'α T, we need to check whether &'α T: Sync),
225     // so knowledge of the exact relationships between them isn't particularly important.
226
227     debug!("types in generator {:?}, span = {:?}", types, body.value.span);
228
229     let mut counter = 0;
230     let mut captured_tys = FxHashSet::default();
231     let type_causes: Vec<_> = types
232         .into_iter()
233         .filter_map(|mut cause| {
234             // Erase regions and canonicalize late-bound regions to deduplicate as many types as we
235             // can.
236             let erased = fcx.tcx.erase_regions(cause.ty);
237             if captured_tys.insert(erased) {
238                 // Replace all regions inside the generator interior with late bound regions.
239                 // Note that each region slot in the types gets a new fresh late bound region,
240                 // which means that none of the regions inside relate to any other, even if
241                 // typeck had previously found constraints that would cause them to be related.
242                 let folded = fcx.tcx.fold_regions(erased, &mut false, |_, current_depth| {
243                     let br = ty::BoundRegion {
244                         var: ty::BoundVar::from_u32(counter),
245                         kind: ty::BrAnon(counter),
246                     };
247                     let r = fcx.tcx.mk_region(ty::ReLateBound(current_depth, br));
248                     counter += 1;
249                     r
250                 });
251
252                 cause.ty = folded;
253                 Some(cause)
254             } else {
255                 None
256             }
257         })
258         .collect();
259
260     // Extract type components to build the witness type.
261     let type_list = fcx.tcx.mk_type_list(type_causes.iter().map(|cause| cause.ty));
262     let bound_vars = fcx.tcx.mk_bound_variable_kinds(
263         (0..counter).map(|i| ty::BoundVariableKind::Region(ty::BrAnon(i))),
264     );
265     let witness =
266         fcx.tcx.mk_generator_witness(ty::Binder::bind_with_vars(type_list, bound_vars.clone()));
267
268     // Store the generator types and spans into the typeck results for this generator.
269     visitor.fcx.inh.typeck_results.borrow_mut().generator_interior_types =
270         ty::Binder::bind_with_vars(type_causes, bound_vars);
271
272     debug!(
273         "types in generator after region replacement {:?}, span = {:?}",
274         witness, body.value.span
275     );
276
277     // Unify the type variable inside the generator with the new witness
278     match fcx.at(&fcx.misc(body.value.span), fcx.param_env).eq(interior, witness) {
279         Ok(ok) => fcx.register_infer_ok_obligations(ok),
280         _ => bug!(),
281     }
282 }
283
284 // This visitor has to have the same visit_expr calls as RegionResolutionVisitor in
285 // librustc_middle/middle/region.rs since `expr_count` is compared against the results
286 // there.
287 impl<'a, 'tcx> Visitor<'tcx> for InteriorVisitor<'a, 'tcx> {
288     fn visit_arm(&mut self, arm: &'tcx Arm<'tcx>) {
289         let Arm { guard, pat, body, .. } = arm;
290         self.visit_pat(pat);
291         if let Some(ref g) = guard {
292             self.guard_bindings.push(<_>::default());
293             ArmPatCollector {
294                 guard_bindings_set: &mut self.guard_bindings_set,
295                 guard_bindings: self
296                     .guard_bindings
297                     .last_mut()
298                     .expect("should have pushed at least one earlier"),
299             }
300             .visit_pat(pat);
301
302             match g {
303                 Guard::If(ref e) => {
304                     self.visit_expr(e);
305                 }
306                 Guard::IfLet(ref pat, ref e) => {
307                     self.visit_pat(pat);
308                     self.visit_expr(e);
309                 }
310             }
311
312             let mut scope_var_ids =
313                 self.guard_bindings.pop().expect("should have pushed at least one earlier");
314             for var_id in scope_var_ids.drain(..) {
315                 self.guard_bindings_set.remove(&var_id);
316             }
317         }
318         self.visit_expr(body);
319     }
320
321     fn visit_pat(&mut self, pat: &'tcx Pat<'tcx>) {
322         intravisit::walk_pat(self, pat);
323
324         self.expr_count += 1;
325
326         if let PatKind::Binding(..) = pat.kind {
327             let scope = self.region_scope_tree.var_scope(pat.hir_id.local_id);
328             let ty = self.fcx.typeck_results.borrow().pat_ty(pat);
329             self.record(ty, pat.hir_id, Some(scope), None, pat.span, false);
330         }
331     }
332
333     fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
334         let mut guard_borrowing_from_pattern = false;
335
336         match &expr.kind {
337             ExprKind::Call(callee, args) => match &callee.kind {
338                 ExprKind::Path(qpath) => {
339                     let res = self.fcx.typeck_results.borrow().qpath_res(qpath, callee.hir_id);
340                     match res {
341                         // Direct calls never need to keep the callee `ty::FnDef`
342                         // ZST in a temporary, so skip its type, just in case it
343                         // can significantly complicate the generator type.
344                         Res::Def(
345                             DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn),
346                             _,
347                         ) => {
348                             // NOTE(eddyb) this assumes a path expression has
349                             // no nested expressions to keep track of.
350                             self.expr_count += 1;
351
352                             // Record the rest of the call expression normally.
353                             for arg in *args {
354                                 self.visit_expr(arg);
355                             }
356                         }
357                         _ => intravisit::walk_expr(self, expr),
358                     }
359                 }
360                 _ => intravisit::walk_expr(self, expr),
361             },
362             ExprKind::Path(qpath) => {
363                 intravisit::walk_expr(self, expr);
364                 let res = self.fcx.typeck_results.borrow().qpath_res(qpath, expr.hir_id);
365                 match res {
366                     Res::Local(id) if self.guard_bindings_set.contains(&id) => {
367                         guard_borrowing_from_pattern = true;
368                     }
369                     _ => {}
370                 }
371             }
372             _ => intravisit::walk_expr(self, expr),
373         }
374
375         self.expr_count += 1;
376
377         let scope = self.region_scope_tree.temporary_scope(expr.hir_id.local_id);
378
379         // If there are adjustments, then record the final type --
380         // this is the actual value that is being produced.
381         if let Some(adjusted_ty) = self.fcx.typeck_results.borrow().expr_ty_adjusted_opt(expr) {
382             self.record(
383                 adjusted_ty,
384                 expr.hir_id,
385                 scope,
386                 Some(expr),
387                 expr.span,
388                 guard_borrowing_from_pattern,
389             );
390         }
391
392         // Also record the unadjusted type (which is the only type if
393         // there are no adjustments). The reason for this is that the
394         // unadjusted value is sometimes a "temporary" that would wind
395         // up in a MIR temporary.
396         //
397         // As an example, consider an expression like `vec![].push(x)`.
398         // Here, the `vec![]` would wind up MIR stored into a
399         // temporary variable `t` which we can borrow to invoke
400         // `<Vec<_>>::push(&mut t, x)`.
401         //
402         // Note that an expression can have many adjustments, and we
403         // are just ignoring those intermediate types. This is because
404         // those intermediate values are always linearly "consumed" by
405         // the other adjustments, and hence would never be directly
406         // captured in the MIR.
407         //
408         // (Note that this partly relies on the fact that the `Deref`
409         // traits always return references, which means their content
410         // can be reborrowed without needing to spill to a temporary.
411         // If this were not the case, then we could conceivably have
412         // to create intermediate temporaries.)
413         //
414         // The type table might not have information for this expression
415         // if it is in a malformed scope. (#66387)
416         if let Some(ty) = self.fcx.typeck_results.borrow().expr_ty_opt(expr) {
417             if guard_borrowing_from_pattern {
418                 // Match guards create references to all the bindings in the pattern that are used
419                 // in the guard, e.g. `y if is_even(y) => ...` becomes `is_even(*r_y)` where `r_y`
420                 // is a reference to `y`, so we must record a reference to the type of the binding.
421                 let tcx = self.fcx.tcx;
422                 let ref_ty = tcx.mk_ref(
423                     // Use `ReErased` as `resolve_interior` is going to replace all the regions anyway.
424                     tcx.mk_region(ty::RegionKind::ReErased),
425                     ty::TypeAndMut { ty, mutbl: hir::Mutability::Not },
426                 );
427                 self.record(
428                     ref_ty,
429                     expr.hir_id,
430                     scope,
431                     Some(expr),
432                     expr.span,
433                     guard_borrowing_from_pattern,
434                 );
435             }
436             self.record(
437                 ty,
438                 expr.hir_id,
439                 scope,
440                 Some(expr),
441                 expr.span,
442                 guard_borrowing_from_pattern,
443             );
444         } else {
445             self.fcx.tcx.sess.delay_span_bug(expr.span, "no type for node");
446         }
447     }
448 }
449
450 struct ArmPatCollector<'a> {
451     guard_bindings_set: &'a mut HirIdSet,
452     guard_bindings: &'a mut SmallVec<[HirId; 4]>,
453 }
454
455 impl<'a, 'tcx> Visitor<'tcx> for ArmPatCollector<'a> {
456     fn visit_pat(&mut self, pat: &'tcx Pat<'tcx>) {
457         intravisit::walk_pat(self, pat);
458         if let PatKind::Binding(_, id, ..) = pat.kind {
459             self.guard_bindings.push(id);
460             self.guard_bindings_set.insert(id);
461         }
462     }
463 }
464
465 #[derive(Default)]
466 pub struct SuspendCheckData<'a, 'tcx> {
467     expr: Option<&'tcx Expr<'tcx>>,
468     source_span: Span,
469     yield_span: Span,
470     descr_pre: &'a str,
471     descr_post: &'a str,
472     plural_len: usize,
473 }
474
475 // Returns whether it emitted a diagnostic or not
476 // Note that this fn and the proceding one are based on the code
477 // for creating must_use diagnostics
478 //
479 // Note that this technique was chosen over things like a `Suspend` marker trait
480 // as it is simpler and has precendent in the compiler
481 pub fn check_must_not_suspend_ty<'tcx>(
482     fcx: &FnCtxt<'_, 'tcx>,
483     ty: Ty<'tcx>,
484     hir_id: HirId,
485     data: SuspendCheckData<'_, 'tcx>,
486 ) -> bool {
487     if ty.is_unit()
488     // FIXME: should this check `is_ty_uninhabited_from`. This query is not available in this stage
489     // of typeck (before ReVar and RePlaceholder are removed), but may remove noise, like in
490     // `must_use`
491     // || fcx.tcx.is_ty_uninhabited_from(fcx.tcx.parent_module(hir_id).to_def_id(), ty, fcx.param_env)
492     {
493         return false;
494     }
495
496     let plural_suffix = pluralize!(data.plural_len);
497
498     match *ty.kind() {
499         ty::Adt(..) if ty.is_box() => {
500             let boxed_ty = ty.boxed_ty();
501             let descr_pre = &format!("{}boxed ", data.descr_pre);
502             check_must_not_suspend_ty(fcx, boxed_ty, hir_id, SuspendCheckData { descr_pre, ..data })
503         }
504         ty::Adt(def, _) => check_must_not_suspend_def(fcx.tcx, def.did, hir_id, data),
505         // FIXME: support adding the attribute to TAITs
506         ty::Opaque(def, _) => {
507             let mut has_emitted = false;
508             for &(predicate, _) in fcx.tcx.explicit_item_bounds(def) {
509                 // We only look at the `DefId`, so it is safe to skip the binder here.
510                 if let ty::PredicateKind::Trait(ref poly_trait_predicate) =
511                     predicate.kind().skip_binder()
512                 {
513                     let def_id = poly_trait_predicate.trait_ref.def_id;
514                     let descr_pre = &format!("{}implementer{} of ", data.descr_pre, plural_suffix);
515                     if check_must_not_suspend_def(
516                         fcx.tcx,
517                         def_id,
518                         hir_id,
519                         SuspendCheckData { descr_pre, ..data },
520                     ) {
521                         has_emitted = true;
522                         break;
523                     }
524                 }
525             }
526             has_emitted
527         }
528         ty::Dynamic(binder, _) => {
529             let mut has_emitted = false;
530             for predicate in binder.iter() {
531                 if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate.skip_binder() {
532                     let def_id = trait_ref.def_id;
533                     let descr_post = &format!(" trait object{}{}", plural_suffix, data.descr_post);
534                     if check_must_not_suspend_def(
535                         fcx.tcx,
536                         def_id,
537                         hir_id,
538                         SuspendCheckData { descr_post, ..data },
539                     ) {
540                         has_emitted = true;
541                         break;
542                     }
543                 }
544             }
545             has_emitted
546         }
547         ty::Tuple(_) => {
548             let mut has_emitted = false;
549             let comps = match data.expr.map(|e| &e.kind) {
550                 Some(hir::ExprKind::Tup(comps)) => {
551                     debug_assert_eq!(comps.len(), ty.tuple_fields().count());
552                     Some(comps)
553                 }
554                 _ => None,
555             };
556             for (i, ty) in ty.tuple_fields().enumerate() {
557                 let descr_post = &format!(" in tuple element {}", i);
558                 let span = comps.and_then(|c| c.get(i)).map(|e| e.span).unwrap_or(data.source_span);
559                 if check_must_not_suspend_ty(
560                     fcx,
561                     ty,
562                     hir_id,
563                     SuspendCheckData {
564                         descr_post,
565                         expr: comps.and_then(|comps| comps.get(i)),
566                         source_span: span,
567                         ..data
568                     },
569                 ) {
570                     has_emitted = true;
571                 }
572             }
573             has_emitted
574         }
575         ty::Array(ty, len) => {
576             let descr_pre = &format!("{}array{} of ", data.descr_pre, plural_suffix);
577             check_must_not_suspend_ty(
578                 fcx,
579                 ty,
580                 hir_id,
581                 SuspendCheckData {
582                     descr_pre,
583                     plural_len: len.try_eval_usize(fcx.tcx, fcx.param_env).unwrap_or(0) as usize
584                         + 1,
585                     ..data
586                 },
587             )
588         }
589         _ => false,
590     }
591 }
592
593 fn check_must_not_suspend_def(
594     tcx: TyCtxt<'_>,
595     def_id: DefId,
596     hir_id: HirId,
597     data: SuspendCheckData<'_, '_>,
598 ) -> bool {
599     for attr in tcx.get_attrs(def_id).iter() {
600         if attr.has_name(sym::must_not_suspend) {
601             tcx.struct_span_lint_hir(
602                 rustc_session::lint::builtin::MUST_NOT_SUSPEND,
603                 hir_id,
604                 data.source_span,
605                 |lint| {
606                     let msg = format!(
607                         "{}`{}`{} held across a suspend point, but should not be",
608                         data.descr_pre,
609                         tcx.def_path_str(def_id),
610                         data.descr_post,
611                     );
612                     let mut err = lint.build(&msg);
613
614                     // add span pointing to the offending yield/await
615                     err.span_label(data.yield_span, "the value is held across this suspend point");
616
617                     // Add optional reason note
618                     if let Some(note) = attr.value_str() {
619                         // FIXME(guswynn): consider formatting this better
620                         err.span_note(data.source_span, note.as_str());
621                     }
622
623                     // Add some quick suggestions on what to do
624                     // FIXME: can `drop` work as a suggestion here as well?
625                     err.span_help(
626                         data.source_span,
627                         "consider using a block (`{ ... }`) \
628                         to shrink the value's scope, ending before the suspend point",
629                     );
630
631                     err.emit();
632                 },
633             );
634
635             return true;
636         }
637     }
638     false
639 }