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