]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_infer/src/infer/opaque_types.rs
Remove opaque type obligation and just register opaque types as they are encountered.
[rust.git] / compiler / rustc_infer / src / infer / opaque_types.rs
1 use crate::infer::{InferCtxt, InferOk};
2 use crate::traits;
3 use hir::def_id::{DefId, LocalDefId};
4 use hir::OpaqueTyOrigin;
5 use rustc_data_structures::sync::Lrc;
6 use rustc_data_structures::vec_map::VecMap;
7 use rustc_hir as hir;
8 use rustc_middle::traits::ObligationCause;
9 use rustc_middle::ty::fold::BottomUpFolder;
10 use rustc_middle::ty::subst::{GenericArgKind, Subst};
11 use rustc_middle::ty::{
12     self, OpaqueHiddenType, OpaqueTypeKey, Ty, TyCtxt, TypeFoldable, TypeVisitor,
13 };
14 use rustc_span::Span;
15
16 use std::ops::ControlFlow;
17
18 pub type OpaqueTypeMap<'tcx> = VecMap<OpaqueTypeKey<'tcx>, OpaqueTypeDecl<'tcx>>;
19
20 mod table;
21
22 pub use table::{OpaqueTypeStorage, OpaqueTypeTable};
23
24 use super::InferResult;
25
26 /// Information about the opaque types whose values we
27 /// are inferring in this function (these are the `impl Trait` that
28 /// appear in the return type).
29 #[derive(Clone, Debug)]
30 pub struct OpaqueTypeDecl<'tcx> {
31     /// The hidden types that have been inferred for this opaque type.
32     /// There can be multiple, but they are all `lub`ed together at the end
33     /// to obtain the canonical hidden type.
34     pub hidden_type: OpaqueHiddenType<'tcx>,
35
36     /// The origin of the opaque type.
37     pub origin: hir::OpaqueTyOrigin,
38 }
39
40 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
41     pub fn handle_opaque_type(
42         &self,
43         a: Ty<'tcx>,
44         b: Ty<'tcx>,
45         a_is_expected: bool,
46         cause: &ObligationCause<'tcx>,
47         param_env: ty::ParamEnv<'tcx>,
48     ) -> InferResult<'tcx, ()> {
49         if a.references_error() || b.references_error() {
50             return Ok(InferOk { value: (), obligations: vec![] });
51         }
52         let (a, b) = if a_is_expected { (a, b) } else { (b, a) };
53         let process = |a: Ty<'tcx>, b: Ty<'tcx>| match *a.kind() {
54             ty::Opaque(def_id, substs) => {
55                 if let ty::Opaque(did2, _) = *b.kind() {
56                     // We could accept this, but there are various ways to handle this situation, and we don't
57                     // want to make a decision on it right now. Likely this case is so super rare anyway, that
58                     // no one encounters it in practice.
59                     // It does occur however in `fn fut() -> impl Future<Output = i32> { async { 42 } }`,
60                     // where it is of no concern, so we only check for TAITs.
61                     if let Some(OpaqueTyOrigin::TyAlias) = self.opaque_type_origin(did2, cause.span)
62                     {
63                         self.tcx
64                                 .sess
65                                 .struct_span_err(
66                                     cause.span,
67                                     "opaque type's hidden type cannot be another opaque type from the same scope",
68                                 )
69                                 .span_label(cause.span, "one of the two opaque types used here has to be outside its defining scope")
70                                 .span_note(
71                                     self.tcx.def_span(def_id),
72                                     "opaque type whose hidden type is being assigned",
73                                 )
74                                 .span_note(
75                                     self.tcx.def_span(did2),
76                                     "opaque type being used as hidden type",
77                                 )
78                                 .emit();
79                     }
80                 }
81                 Some(self.register_hidden_type(
82                     OpaqueTypeKey { def_id, substs },
83                     cause.clone(),
84                     param_env,
85                     b,
86                     if self.defining_use_anchor.is_some() {
87                         // Check that this is `impl Trait` type is
88                         // declared by `parent_def_id` -- i.e., one whose
89                         // value we are inferring.  At present, this is
90                         // always true during the first phase of
91                         // type-check, but not always true later on during
92                         // NLL. Once we support named opaque types more fully,
93                         // this same scenario will be able to arise during all phases.
94                         //
95                         // Here is an example using type alias `impl Trait`
96                         // that indicates the distinction we are checking for:
97                         //
98                         // ```rust
99                         // mod a {
100                         //   pub type Foo = impl Iterator;
101                         //   pub fn make_foo() -> Foo { .. }
102                         // }
103                         //
104                         // mod b {
105                         //   fn foo() -> a::Foo { a::make_foo() }
106                         // }
107                         // ```
108                         //
109                         // Here, the return type of `foo` references an
110                         // `Opaque` indeed, but not one whose value is
111                         // presently being inferred. You can get into a
112                         // similar situation with closure return types
113                         // today:
114                         //
115                         // ```rust
116                         // fn foo() -> impl Iterator { .. }
117                         // fn bar() {
118                         //     let x = || foo(); // returns the Opaque assoc with `foo`
119                         // }
120                         // ```
121                         self.opaque_type_origin(def_id, cause.span)?
122                     } else {
123                         self.opaque_ty_origin_unchecked(def_id, cause.span)
124                     },
125                 ))
126             }
127             _ => None,
128         };
129         if let Some(res) = process(a, b) {
130             res
131         } else if let Some(res) = process(b, a) {
132             res
133         } else {
134             // Rerun equality check, but this time error out due to
135             // different types.
136             match self.at(cause, param_env).define_opaque_types(false).eq(a, b) {
137                 Ok(_) => span_bug!(
138                     cause.span,
139                     "opaque types are never equal to anything but themselves: {:#?}",
140                     (a.kind(), b.kind())
141                 ),
142                 Err(e) => Err(e),
143             }
144         }
145     }
146
147     /// Given the map `opaque_types` containing the opaque
148     /// `impl Trait` types whose underlying, hidden types are being
149     /// inferred, this method adds constraints to the regions
150     /// appearing in those underlying hidden types to ensure that they
151     /// at least do not refer to random scopes within the current
152     /// function. These constraints are not (quite) sufficient to
153     /// guarantee that the regions are actually legal values; that
154     /// final condition is imposed after region inference is done.
155     ///
156     /// # The Problem
157     ///
158     /// Let's work through an example to explain how it works. Assume
159     /// the current function is as follows:
160     ///
161     /// ```text
162     /// fn foo<'a, 'b>(..) -> (impl Bar<'a>, impl Bar<'b>)
163     /// ```
164     ///
165     /// Here, we have two `impl Trait` types whose values are being
166     /// inferred (the `impl Bar<'a>` and the `impl
167     /// Bar<'b>`). Conceptually, this is sugar for a setup where we
168     /// define underlying opaque types (`Foo1`, `Foo2`) and then, in
169     /// the return type of `foo`, we *reference* those definitions:
170     ///
171     /// ```text
172     /// type Foo1<'x> = impl Bar<'x>;
173     /// type Foo2<'x> = impl Bar<'x>;
174     /// fn foo<'a, 'b>(..) -> (Foo1<'a>, Foo2<'b>) { .. }
175     ///                    //  ^^^^ ^^
176     ///                    //  |    |
177     ///                    //  |    substs
178     ///                    //  def_id
179     /// ```
180     ///
181     /// As indicating in the comments above, each of those references
182     /// is (in the compiler) basically a substitution (`substs`)
183     /// applied to the type of a suitable `def_id` (which identifies
184     /// `Foo1` or `Foo2`).
185     ///
186     /// Now, at this point in compilation, what we have done is to
187     /// replace each of the references (`Foo1<'a>`, `Foo2<'b>`) with
188     /// fresh inference variables C1 and C2. We wish to use the values
189     /// of these variables to infer the underlying types of `Foo1` and
190     /// `Foo2`. That is, this gives rise to higher-order (pattern) unification
191     /// constraints like:
192     ///
193     /// ```text
194     /// for<'a> (Foo1<'a> = C1)
195     /// for<'b> (Foo1<'b> = C2)
196     /// ```
197     ///
198     /// For these equation to be satisfiable, the types `C1` and `C2`
199     /// can only refer to a limited set of regions. For example, `C1`
200     /// can only refer to `'static` and `'a`, and `C2` can only refer
201     /// to `'static` and `'b`. The job of this function is to impose that
202     /// constraint.
203     ///
204     /// Up to this point, C1 and C2 are basically just random type
205     /// inference variables, and hence they may contain arbitrary
206     /// regions. In fact, it is fairly likely that they do! Consider
207     /// this possible definition of `foo`:
208     ///
209     /// ```text
210     /// fn foo<'a, 'b>(x: &'a i32, y: &'b i32) -> (impl Bar<'a>, impl Bar<'b>) {
211     ///         (&*x, &*y)
212     ///     }
213     /// ```
214     ///
215     /// Here, the values for the concrete types of the two impl
216     /// traits will include inference variables:
217     ///
218     /// ```text
219     /// &'0 i32
220     /// &'1 i32
221     /// ```
222     ///
223     /// Ordinarily, the subtyping rules would ensure that these are
224     /// sufficiently large. But since `impl Bar<'a>` isn't a specific
225     /// type per se, we don't get such constraints by default. This
226     /// is where this function comes into play. It adds extra
227     /// constraints to ensure that all the regions which appear in the
228     /// inferred type are regions that could validly appear.
229     ///
230     /// This is actually a bit of a tricky constraint in general. We
231     /// want to say that each variable (e.g., `'0`) can only take on
232     /// values that were supplied as arguments to the opaque type
233     /// (e.g., `'a` for `Foo1<'a>`) or `'static`, which is always in
234     /// scope. We don't have a constraint quite of this kind in the current
235     /// region checker.
236     ///
237     /// # The Solution
238     ///
239     /// We generally prefer to make `<=` constraints, since they
240     /// integrate best into the region solver. To do that, we find the
241     /// "minimum" of all the arguments that appear in the substs: that
242     /// is, some region which is less than all the others. In the case
243     /// of `Foo1<'a>`, that would be `'a` (it's the only choice, after
244     /// all). Then we apply that as a least bound to the variables
245     /// (e.g., `'a <= '0`).
246     ///
247     /// In some cases, there is no minimum. Consider this example:
248     ///
249     /// ```text
250     /// fn baz<'a, 'b>() -> impl Trait<'a, 'b> { ... }
251     /// ```
252     ///
253     /// Here we would report a more complex "in constraint", like `'r
254     /// in ['a, 'b, 'static]` (where `'r` is some region appearing in
255     /// the hidden type).
256     ///
257     /// # Constrain regions, not the hidden concrete type
258     ///
259     /// Note that generating constraints on each region `Rc` is *not*
260     /// the same as generating an outlives constraint on `Tc` iself.
261     /// For example, if we had a function like this:
262     ///
263     /// ```rust
264     /// fn foo<'a, T>(x: &'a u32, y: T) -> impl Foo<'a> {
265     ///   (x, y)
266     /// }
267     ///
268     /// // Equivalent to:
269     /// type FooReturn<'a, T> = impl Foo<'a>;
270     /// fn foo<'a, T>(..) -> FooReturn<'a, T> { .. }
271     /// ```
272     ///
273     /// then the hidden type `Tc` would be `(&'0 u32, T)` (where `'0`
274     /// is an inference variable). If we generated a constraint that
275     /// `Tc: 'a`, then this would incorrectly require that `T: 'a` --
276     /// but this is not necessary, because the opaque type we
277     /// create will be allowed to reference `T`. So we only generate a
278     /// constraint that `'0: 'a`.
279     #[instrument(level = "debug", skip(self))]
280     pub fn register_member_constraints(
281         &self,
282         param_env: ty::ParamEnv<'tcx>,
283         opaque_type_key: OpaqueTypeKey<'tcx>,
284         concrete_ty: Ty<'tcx>,
285         span: Span,
286     ) {
287         let def_id = opaque_type_key.def_id;
288
289         let tcx = self.tcx;
290
291         let concrete_ty = self.resolve_vars_if_possible(concrete_ty);
292
293         debug!(?concrete_ty);
294
295         let first_own_region = match self.opaque_ty_origin_unchecked(def_id, span) {
296             hir::OpaqueTyOrigin::FnReturn(..) | hir::OpaqueTyOrigin::AsyncFn(..) => {
297                 // We lower
298                 //
299                 // fn foo<'l0..'ln>() -> impl Trait<'l0..'lm>
300                 //
301                 // into
302                 //
303                 // type foo::<'p0..'pn>::Foo<'q0..'qm>
304                 // fn foo<l0..'ln>() -> foo::<'static..'static>::Foo<'l0..'lm>.
305                 //
306                 // For these types we only iterate over `'l0..lm` below.
307                 tcx.generics_of(def_id).parent_count
308             }
309             // These opaque type inherit all lifetime parameters from their
310             // parent, so we have to check them all.
311             hir::OpaqueTyOrigin::TyAlias => 0,
312         };
313
314         // For a case like `impl Foo<'a, 'b>`, we would generate a constraint
315         // `'r in ['a, 'b, 'static]` for each region `'r` that appears in the
316         // hidden type (i.e., it must be equal to `'a`, `'b`, or `'static`).
317         //
318         // `conflict1` and `conflict2` are the two region bounds that we
319         // detected which were unrelated. They are used for diagnostics.
320
321         // Create the set of choice regions: each region in the hidden
322         // type can be equal to any of the region parameters of the
323         // opaque type definition.
324         let choice_regions: Lrc<Vec<ty::Region<'tcx>>> = Lrc::new(
325             opaque_type_key.substs[first_own_region..]
326                 .iter()
327                 .filter_map(|arg| match arg.unpack() {
328                     GenericArgKind::Lifetime(r) => Some(r),
329                     GenericArgKind::Type(_) | GenericArgKind::Const(_) => None,
330                 })
331                 .chain(std::iter::once(self.tcx.lifetimes.re_static))
332                 .collect(),
333         );
334
335         concrete_ty.visit_with(&mut ConstrainOpaqueTypeRegionVisitor {
336             op: |r| {
337                 self.member_constraint(
338                     opaque_type_key.def_id,
339                     span,
340                     concrete_ty,
341                     r,
342                     &choice_regions,
343                 )
344             },
345         });
346     }
347
348     #[instrument(skip(self), level = "trace")]
349     pub fn opaque_type_origin(&self, opaque_def_id: DefId, span: Span) -> Option<OpaqueTyOrigin> {
350         let def_id = opaque_def_id.as_local()?;
351         let opaque_hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
352         let parent_def_id = self.defining_use_anchor?;
353         let item_kind = &self.tcx.hir().expect_item(def_id).kind;
354
355         let hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, ..  }) = item_kind else {
356             span_bug!(
357                 span,
358                 "weird opaque type: {:#?}, {:#?}",
359                 opaque_def_id,
360                 item_kind
361             )
362         };
363         let in_definition_scope = match *origin {
364             // Async `impl Trait`
365             hir::OpaqueTyOrigin::AsyncFn(parent) => parent == parent_def_id,
366             // Anonymous `impl Trait`
367             hir::OpaqueTyOrigin::FnReturn(parent) => parent == parent_def_id,
368             // Named `type Foo = impl Bar;`
369             hir::OpaqueTyOrigin::TyAlias => {
370                 may_define_opaque_type(self.tcx, parent_def_id, opaque_hir_id)
371             }
372         };
373         trace!(?origin);
374         in_definition_scope.then_some(*origin)
375     }
376
377     #[instrument(skip(self), level = "trace")]
378     fn opaque_ty_origin_unchecked(&self, opaque_def_id: DefId, span: Span) -> OpaqueTyOrigin {
379         let def_id = opaque_def_id.as_local().unwrap();
380         let origin = match self.tcx.hir().expect_item(def_id).kind {
381             hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => origin,
382             ref itemkind => {
383                 span_bug!(span, "weird opaque type: {:?}, {:#?}", opaque_def_id, itemkind)
384             }
385         };
386         trace!(?origin);
387         origin
388     }
389 }
390
391 // Visitor that requires that (almost) all regions in the type visited outlive
392 // `least_region`. We cannot use `push_outlives_components` because regions in
393 // closure signatures are not included in their outlives components. We need to
394 // ensure all regions outlive the given bound so that we don't end up with,
395 // say, `ReVar` appearing in a return type and causing ICEs when other
396 // functions end up with region constraints involving regions from other
397 // functions.
398 //
399 // We also cannot use `for_each_free_region` because for closures it includes
400 // the regions parameters from the enclosing item.
401 //
402 // We ignore any type parameters because impl trait values are assumed to
403 // capture all the in-scope type parameters.
404 struct ConstrainOpaqueTypeRegionVisitor<OP> {
405     op: OP,
406 }
407
408 impl<'tcx, OP> TypeVisitor<'tcx> for ConstrainOpaqueTypeRegionVisitor<OP>
409 where
410     OP: FnMut(ty::Region<'tcx>),
411 {
412     fn visit_binder<T: TypeFoldable<'tcx>>(
413         &mut self,
414         t: &ty::Binder<'tcx, T>,
415     ) -> ControlFlow<Self::BreakTy> {
416         t.as_ref().skip_binder().visit_with(self);
417         ControlFlow::CONTINUE
418     }
419
420     fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
421         match *r {
422             // ignore bound regions, keep visiting
423             ty::ReLateBound(_, _) => ControlFlow::CONTINUE,
424             _ => {
425                 (self.op)(r);
426                 ControlFlow::CONTINUE
427             }
428         }
429     }
430
431     fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
432         // We're only interested in types involving regions
433         if !ty.flags().intersects(ty::TypeFlags::HAS_FREE_REGIONS) {
434             return ControlFlow::CONTINUE;
435         }
436
437         match ty.kind() {
438             ty::Closure(_, ref substs) => {
439                 // Skip lifetime parameters of the enclosing item(s)
440
441                 substs.as_closure().tupled_upvars_ty().visit_with(self);
442                 substs.as_closure().sig_as_fn_ptr_ty().visit_with(self);
443             }
444
445             ty::Generator(_, ref substs, _) => {
446                 // Skip lifetime parameters of the enclosing item(s)
447                 // Also skip the witness type, because that has no free regions.
448
449                 substs.as_generator().tupled_upvars_ty().visit_with(self);
450                 substs.as_generator().return_ty().visit_with(self);
451                 substs.as_generator().yield_ty().visit_with(self);
452                 substs.as_generator().resume_ty().visit_with(self);
453             }
454             _ => {
455                 ty.super_visit_with(self);
456             }
457         }
458
459         ControlFlow::CONTINUE
460     }
461 }
462
463 pub enum UseKind {
464     DefiningUse,
465     OpaqueUse,
466 }
467
468 impl UseKind {
469     pub fn is_defining(self) -> bool {
470         match self {
471             UseKind::DefiningUse => true,
472             UseKind::OpaqueUse => false,
473         }
474     }
475 }
476
477 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
478     #[instrument(skip(self), level = "debug")]
479     pub fn register_hidden_type(
480         &self,
481         opaque_type_key: OpaqueTypeKey<'tcx>,
482         cause: ObligationCause<'tcx>,
483         param_env: ty::ParamEnv<'tcx>,
484         hidden_ty: Ty<'tcx>,
485         origin: hir::OpaqueTyOrigin,
486     ) -> InferResult<'tcx, ()> {
487         let tcx = self.tcx;
488         let OpaqueTypeKey { def_id, substs } = opaque_type_key;
489
490         // Ideally, we'd get the span where *this specific `ty` came
491         // from*, but right now we just use the span from the overall
492         // value being folded. In simple cases like `-> impl Foo`,
493         // these are the same span, but not in cases like `-> (impl
494         // Foo, impl Bar)`.
495         let span = cause.span;
496
497         let mut obligations = vec![];
498         let prev = self.inner.borrow_mut().opaque_types().register(
499             OpaqueTypeKey { def_id, substs },
500             OpaqueHiddenType { ty: hidden_ty, span },
501             origin,
502         );
503         if let Some(prev) = prev {
504             obligations = self.at(&cause, param_env).eq(prev, hidden_ty)?.obligations;
505         }
506
507         let item_bounds = tcx.explicit_item_bounds(def_id);
508
509         for (predicate, _) in item_bounds {
510             debug!(?predicate);
511             let predicate = predicate.subst(tcx, substs);
512
513             let predicate = predicate.fold_with(&mut BottomUpFolder {
514                 tcx,
515                 ty_op: |ty| match *ty.kind() {
516                     // We can't normalize associated types from `rustc_infer`,
517                     // but we can eagerly register inference variables for them.
518                     ty::Projection(projection_ty) if !projection_ty.has_escaping_bound_vars() => {
519                         self.infer_projection(
520                             param_env,
521                             projection_ty,
522                             cause.clone(),
523                             0,
524                             &mut obligations,
525                         )
526                     }
527                     // Replace all other mentions of the same opaque type with the hidden type,
528                     // as the bounds must hold on the hidden type after all.
529                     ty::Opaque(def_id2, substs2) if def_id == def_id2 && substs == substs2 => {
530                         hidden_ty
531                     }
532                     _ => ty,
533                 },
534                 lt_op: |lt| lt,
535                 ct_op: |ct| ct,
536             });
537
538             if let ty::PredicateKind::Projection(projection) = predicate.kind().skip_binder() {
539                 if projection.term.references_error() {
540                     // No point on adding these obligations since there's a type error involved.
541                     return Ok(InferOk { value: (), obligations: vec![] });
542                 }
543                 trace!("{:#?}", projection.term);
544             }
545             // Require that the predicate holds for the concrete type.
546             debug!(?predicate);
547             obligations.push(traits::Obligation::new(cause.clone(), param_env, predicate));
548         }
549         Ok(InferOk { value: (), obligations })
550     }
551 }
552
553 /// Returns `true` if `opaque_hir_id` is a sibling or a child of a sibling of `def_id`.
554 ///
555 /// Example:
556 /// ```rust
557 /// pub mod foo {
558 ///     pub mod bar {
559 ///         pub trait Bar { .. }
560 ///
561 ///         pub type Baz = impl Bar;
562 ///
563 ///         fn f1() -> Baz { .. }
564 ///     }
565 ///
566 ///     fn f2() -> bar::Baz { .. }
567 /// }
568 /// ```
569 ///
570 /// Here, `def_id` is the `LocalDefId` of the defining use of the opaque type (e.g., `f1` or `f2`),
571 /// and `opaque_hir_id` is the `HirId` of the definition of the opaque type `Baz`.
572 /// For the above example, this function returns `true` for `f1` and `false` for `f2`.
573 fn may_define_opaque_type(tcx: TyCtxt<'_>, def_id: LocalDefId, opaque_hir_id: hir::HirId) -> bool {
574     let mut hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
575
576     // Named opaque types can be defined by any siblings or children of siblings.
577     let scope = tcx.hir().get_defining_scope(opaque_hir_id);
578     // We walk up the node tree until we hit the root or the scope of the opaque type.
579     while hir_id != scope && hir_id != hir::CRATE_HIR_ID {
580         hir_id = tcx.hir().local_def_id_to_hir_id(tcx.hir().get_parent_item(hir_id));
581     }
582     // Syntactically, we are allowed to define the concrete type if:
583     let res = hir_id == scope;
584     trace!(
585         "may_define_opaque_type(def={:?}, opaque_node={:?}) = {}",
586         tcx.hir().find(hir_id),
587         tcx.hir().get(opaque_hir_id),
588         res
589     );
590     res
591 }