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