1 use crate::errors::OpaqueHiddenTypeDiag;
2 use crate::infer::{DefiningAnchor, InferCtxt, InferOk};
5 use hir::def_id::{DefId, LocalDefId};
6 use hir::{HirId, OpaqueTyOrigin};
7 use rustc_data_structures::sync::Lrc;
8 use rustc_data_structures::vec_map::VecMap;
10 use rustc_middle::traits::ObligationCause;
11 use rustc_middle::ty::error::{ExpectedFound, TypeError};
12 use rustc_middle::ty::fold::BottomUpFolder;
13 use rustc_middle::ty::GenericArgKind;
14 use rustc_middle::ty::{
15 self, OpaqueHiddenType, OpaqueTypeKey, Ty, TyCtxt, TypeFoldable, TypeSuperVisitable,
16 TypeVisitable, TypeVisitor,
20 use std::ops::ControlFlow;
22 pub type OpaqueTypeMap<'tcx> = VecMap<OpaqueTypeKey<'tcx>, OpaqueTypeDecl<'tcx>>;
26 pub use table::{OpaqueTypeStorage, OpaqueTypeTable};
28 use super::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
29 use super::InferResult;
31 /// Information about the opaque types whose values we
32 /// are inferring in this function (these are the `impl Trait` that
33 /// appear in the return type).
34 #[derive(Clone, Debug)]
35 pub struct OpaqueTypeDecl<'tcx> {
36 /// The hidden types that have been inferred for this opaque type.
37 /// There can be multiple, but they are all `lub`ed together at the end
38 /// to obtain the canonical hidden type.
39 pub hidden_type: OpaqueHiddenType<'tcx>,
41 /// The origin of the opaque type.
42 pub origin: hir::OpaqueTyOrigin,
45 impl<'tcx> InferCtxt<'tcx> {
46 /// This is a backwards compatibility hack to prevent breaking changes from
47 /// lazy TAIT around RPIT handling.
48 pub fn replace_opaque_types_with_inference_vars<T: TypeFoldable<'tcx>>(
53 param_env: ty::ParamEnv<'tcx>,
54 ) -> InferOk<'tcx, T> {
55 if !value.has_opaque_types() {
56 return InferOk { value, obligations: vec![] };
58 let mut obligations = vec![];
59 let replace_opaque_type = |def_id: DefId| {
62 .map_or(false, |def_id| self.opaque_type_origin(def_id, span).is_some())
64 let value = value.fold_with(&mut BottomUpFolder {
68 ty_op: |ty| match *ty.kind() {
69 ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. })
70 if replace_opaque_type(def_id) =>
72 let def_span = self.tcx.def_span(def_id);
73 let span = if span.contains(def_span) { def_span } else { span };
74 let code = traits::ObligationCauseCode::OpaqueReturnType(None);
75 let cause = ObligationCause::new(span, body_id, code);
76 // FIXME(compiler-errors): We probably should add a new TypeVariableOriginKind
77 // for opaque types, and then use that kind to fix the spans for type errors
78 // that we see later on.
79 let ty_var = self.next_ty_var(TypeVariableOrigin {
80 kind: TypeVariableOriginKind::OpaqueTypeInference(def_id),
84 self.handle_opaque_type(ty, ty_var, true, &cause, param_env)
93 InferOk { value, obligations }
96 pub fn handle_opaque_type(
101 cause: &ObligationCause<'tcx>,
102 param_env: ty::ParamEnv<'tcx>,
103 ) -> InferResult<'tcx, ()> {
104 if a.references_error() || b.references_error() {
105 return Ok(InferOk { value: (), obligations: vec![] });
107 let (a, b) = if a_is_expected { (a, b) } else { (b, a) };
108 let process = |a: Ty<'tcx>, b: Ty<'tcx>, a_is_expected| match *a.kind() {
109 ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) if def_id.is_local() => {
110 let def_id = def_id.expect_local();
111 let origin = match self.defining_use_anchor {
112 DefiningAnchor::Bind(_) => {
113 // Check that this is `impl Trait` type is
114 // declared by `parent_def_id` -- i.e., one whose
115 // value we are inferring. At present, this is
116 // always true during the first phase of
117 // type-check, but not always true later on during
118 // NLL. Once we support named opaque types more fully,
119 // this same scenario will be able to arise during all phases.
121 // Here is an example using type alias `impl Trait`
122 // that indicates the distinction we are checking for:
126 // pub type Foo = impl Iterator;
127 // pub fn make_foo() -> Foo { .. }
131 // fn foo() -> a::Foo { a::make_foo() }
135 // Here, the return type of `foo` references an
136 // `Opaque` indeed, but not one whose value is
137 // presently being inferred. You can get into a
138 // similar situation with closure return types
142 // fn foo() -> impl Iterator { .. }
144 // let x = || foo(); // returns the Opaque assoc with `foo`
147 self.opaque_type_origin(def_id, cause.span)?
149 DefiningAnchor::Bubble => self.opaque_ty_origin_unchecked(def_id, cause.span),
150 DefiningAnchor::Error => return None,
152 if let ty::Alias(ty::Opaque, ty::AliasTy { def_id: b_def_id, .. }) = *b.kind() {
153 // We could accept this, but there are various ways to handle this situation, and we don't
154 // want to make a decision on it right now. Likely this case is so super rare anyway, that
155 // no one encounters it in practice.
156 // It does occur however in `fn fut() -> impl Future<Output = i32> { async { 42 } }`,
157 // where it is of no concern, so we only check for TAITs.
158 if let Some(OpaqueTyOrigin::TyAlias) = b_def_id
160 .and_then(|b_def_id| self.opaque_type_origin(b_def_id, cause.span))
162 self.tcx.sess.emit_err(OpaqueHiddenTypeDiag {
164 hidden_type: self.tcx.def_span(b_def_id),
165 opaque_type: self.tcx.def_span(def_id),
169 Some(self.register_hidden_type(
170 OpaqueTypeKey { def_id, substs },
180 if let Some(res) = process(a, b, true) {
182 } else if let Some(res) = process(b, a, false) {
185 let (a, b) = self.resolve_vars_if_possible((a, b));
186 Err(TypeError::Sorts(ExpectedFound::new(true, a, b)))
190 /// Given the map `opaque_types` containing the opaque
191 /// `impl Trait` types whose underlying, hidden types are being
192 /// inferred, this method adds constraints to the regions
193 /// appearing in those underlying hidden types to ensure that they
194 /// at least do not refer to random scopes within the current
195 /// function. These constraints are not (quite) sufficient to
196 /// guarantee that the regions are actually legal values; that
197 /// final condition is imposed after region inference is done.
201 /// Let's work through an example to explain how it works. Assume
202 /// the current function is as follows:
205 /// fn foo<'a, 'b>(..) -> (impl Bar<'a>, impl Bar<'b>)
208 /// Here, we have two `impl Trait` types whose values are being
209 /// inferred (the `impl Bar<'a>` and the `impl
210 /// Bar<'b>`). Conceptually, this is sugar for a setup where we
211 /// define underlying opaque types (`Foo1`, `Foo2`) and then, in
212 /// the return type of `foo`, we *reference* those definitions:
215 /// type Foo1<'x> = impl Bar<'x>;
216 /// type Foo2<'x> = impl Bar<'x>;
217 /// fn foo<'a, 'b>(..) -> (Foo1<'a>, Foo2<'b>) { .. }
224 /// As indicating in the comments above, each of those references
225 /// is (in the compiler) basically a substitution (`substs`)
226 /// applied to the type of a suitable `def_id` (which identifies
227 /// `Foo1` or `Foo2`).
229 /// Now, at this point in compilation, what we have done is to
230 /// replace each of the references (`Foo1<'a>`, `Foo2<'b>`) with
231 /// fresh inference variables C1 and C2. We wish to use the values
232 /// of these variables to infer the underlying types of `Foo1` and
233 /// `Foo2`. That is, this gives rise to higher-order (pattern) unification
234 /// constraints like:
237 /// for<'a> (Foo1<'a> = C1)
238 /// for<'b> (Foo1<'b> = C2)
241 /// For these equation to be satisfiable, the types `C1` and `C2`
242 /// can only refer to a limited set of regions. For example, `C1`
243 /// can only refer to `'static` and `'a`, and `C2` can only refer
244 /// to `'static` and `'b`. The job of this function is to impose that
247 /// Up to this point, C1 and C2 are basically just random type
248 /// inference variables, and hence they may contain arbitrary
249 /// regions. In fact, it is fairly likely that they do! Consider
250 /// this possible definition of `foo`:
253 /// fn foo<'a, 'b>(x: &'a i32, y: &'b i32) -> (impl Bar<'a>, impl Bar<'b>) {
258 /// Here, the values for the concrete types of the two impl
259 /// traits will include inference variables:
266 /// Ordinarily, the subtyping rules would ensure that these are
267 /// sufficiently large. But since `impl Bar<'a>` isn't a specific
268 /// type per se, we don't get such constraints by default. This
269 /// is where this function comes into play. It adds extra
270 /// constraints to ensure that all the regions which appear in the
271 /// inferred type are regions that could validly appear.
273 /// This is actually a bit of a tricky constraint in general. We
274 /// want to say that each variable (e.g., `'0`) can only take on
275 /// values that were supplied as arguments to the opaque type
276 /// (e.g., `'a` for `Foo1<'a>`) or `'static`, which is always in
277 /// scope. We don't have a constraint quite of this kind in the current
282 /// We generally prefer to make `<=` constraints, since they
283 /// integrate best into the region solver. To do that, we find the
284 /// "minimum" of all the arguments that appear in the substs: that
285 /// is, some region which is less than all the others. In the case
286 /// of `Foo1<'a>`, that would be `'a` (it's the only choice, after
287 /// all). Then we apply that as a least bound to the variables
288 /// (e.g., `'a <= '0`).
290 /// In some cases, there is no minimum. Consider this example:
293 /// fn baz<'a, 'b>() -> impl Trait<'a, 'b> { ... }
296 /// Here we would report a more complex "in constraint", like `'r
297 /// in ['a, 'b, 'static]` (where `'r` is some region appearing in
298 /// the hidden type).
300 /// # Constrain regions, not the hidden concrete type
302 /// Note that generating constraints on each region `Rc` is *not*
303 /// the same as generating an outlives constraint on `Tc` itself.
304 /// For example, if we had a function like this:
307 /// # #![feature(type_alias_impl_trait)]
309 /// # trait Foo<'a> {}
310 /// # impl<'a, T> Foo<'a> for (&'a u32, T) {}
311 /// fn foo<'a, T>(x: &'a u32, y: T) -> impl Foo<'a> {
315 /// // Equivalent to:
316 /// # mod dummy { use super::*;
317 /// type FooReturn<'a, T> = impl Foo<'a>;
318 /// fn foo<'a, T>(x: &'a u32, y: T) -> FooReturn<'a, T> {
324 /// then the hidden type `Tc` would be `(&'0 u32, T)` (where `'0`
325 /// is an inference variable). If we generated a constraint that
326 /// `Tc: 'a`, then this would incorrectly require that `T: 'a` --
327 /// but this is not necessary, because the opaque type we
328 /// create will be allowed to reference `T`. So we only generate a
329 /// constraint that `'0: 'a`.
330 #[instrument(level = "debug", skip(self))]
331 pub fn register_member_constraints(
333 param_env: ty::ParamEnv<'tcx>,
334 opaque_type_key: OpaqueTypeKey<'tcx>,
335 concrete_ty: Ty<'tcx>,
338 let concrete_ty = self.resolve_vars_if_possible(concrete_ty);
339 debug!(?concrete_ty);
341 let variances = self.tcx.variances_of(opaque_type_key.def_id);
344 // For a case like `impl Foo<'a, 'b>`, we would generate a constraint
345 // `'r in ['a, 'b, 'static]` for each region `'r` that appears in the
346 // hidden type (i.e., it must be equal to `'a`, `'b`, or `'static`).
348 // `conflict1` and `conflict2` are the two region bounds that we
349 // detected which were unrelated. They are used for diagnostics.
351 // Create the set of choice regions: each region in the hidden
352 // type can be equal to any of the region parameters of the
353 // opaque type definition.
354 let choice_regions: Lrc<Vec<ty::Region<'tcx>>> = Lrc::new(
359 .filter(|(i, _)| variances[*i] == ty::Variance::Invariant)
360 .filter_map(|(_, arg)| match arg.unpack() {
361 GenericArgKind::Lifetime(r) => Some(r),
362 GenericArgKind::Type(_) | GenericArgKind::Const(_) => None,
364 .chain(std::iter::once(self.tcx.lifetimes.re_static))
368 concrete_ty.visit_with(&mut ConstrainOpaqueTypeRegionVisitor {
370 op: |r| self.member_constraint(opaque_type_key, span, concrete_ty, r, &choice_regions),
374 #[instrument(skip(self), level = "trace", ret)]
375 pub fn opaque_type_origin(&self, def_id: LocalDefId, span: Span) -> Option<OpaqueTyOrigin> {
376 let opaque_hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
377 let parent_def_id = match self.defining_use_anchor {
378 DefiningAnchor::Bubble | DefiningAnchor::Error => return None,
379 DefiningAnchor::Bind(bind) => bind,
381 let item_kind = &self.tcx.hir().expect_item(def_id).kind;
383 let hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) = item_kind else {
386 "weird opaque type: {:#?}, {:#?}",
391 let in_definition_scope = match *origin {
392 // Async `impl Trait`
393 hir::OpaqueTyOrigin::AsyncFn(parent) => parent == parent_def_id,
394 // Anonymous `impl Trait`
395 hir::OpaqueTyOrigin::FnReturn(parent) => parent == parent_def_id,
396 // Named `type Foo = impl Bar;`
397 hir::OpaqueTyOrigin::TyAlias => {
398 may_define_opaque_type(self.tcx, parent_def_id, opaque_hir_id)
402 in_definition_scope.then_some(*origin)
405 #[instrument(skip(self), level = "trace", ret)]
406 fn opaque_ty_origin_unchecked(&self, def_id: LocalDefId, span: Span) -> OpaqueTyOrigin {
407 match self.tcx.hir().expect_item(def_id).kind {
408 hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => origin,
410 span_bug!(span, "weird opaque type: {:?}, {:#?}", def_id, itemkind)
416 /// Visitor that requires that (almost) all regions in the type visited outlive
417 /// `least_region`. We cannot use `push_outlives_components` because regions in
418 /// closure signatures are not included in their outlives components. We need to
419 /// ensure all regions outlive the given bound so that we don't end up with,
420 /// say, `ReVar` appearing in a return type and causing ICEs when other
421 /// functions end up with region constraints involving regions from other
424 /// We also cannot use `for_each_free_region` because for closures it includes
425 /// the regions parameters from the enclosing item.
427 /// We ignore any type parameters because impl trait values are assumed to
428 /// capture all the in-scope type parameters.
429 pub struct ConstrainOpaqueTypeRegionVisitor<'tcx, OP: FnMut(ty::Region<'tcx>)> {
430 pub tcx: TyCtxt<'tcx>,
434 impl<'tcx, OP> TypeVisitor<'tcx> for ConstrainOpaqueTypeRegionVisitor<'tcx, OP>
436 OP: FnMut(ty::Region<'tcx>),
438 fn visit_binder<T: TypeVisitable<'tcx>>(
440 t: &ty::Binder<'tcx, T>,
441 ) -> ControlFlow<Self::BreakTy> {
442 t.super_visit_with(self);
443 ControlFlow::CONTINUE
446 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
448 // ignore bound regions, keep visiting
449 ty::ReLateBound(_, _) => ControlFlow::CONTINUE,
452 ControlFlow::CONTINUE
457 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
458 // We're only interested in types involving regions
459 if !ty.flags().intersects(ty::TypeFlags::HAS_FREE_REGIONS) {
460 return ControlFlow::CONTINUE;
464 ty::Closure(_, ref substs) => {
465 // Skip lifetime parameters of the enclosing item(s)
467 substs.as_closure().tupled_upvars_ty().visit_with(self);
468 substs.as_closure().sig_as_fn_ptr_ty().visit_with(self);
471 ty::Generator(_, ref substs, _) => {
472 // Skip lifetime parameters of the enclosing item(s)
473 // Also skip the witness type, because that has no free regions.
475 substs.as_generator().tupled_upvars_ty().visit_with(self);
476 substs.as_generator().return_ty().visit_with(self);
477 substs.as_generator().yield_ty().visit_with(self);
478 substs.as_generator().resume_ty().visit_with(self);
481 ty::Alias(ty::Opaque, ty::AliasTy { def_id, ref substs, .. }) => {
482 // Skip lifetime paramters that are not captures.
483 let variances = self.tcx.variances_of(*def_id);
485 for (v, s) in std::iter::zip(variances, substs.iter()) {
486 if *v != ty::Variance::Bivariant {
492 ty::Alias(ty::Projection, proj)
493 if self.tcx.def_kind(proj.def_id) == DefKind::ImplTraitPlaceholder =>
495 // Skip lifetime paramters that are not captures.
496 let variances = self.tcx.variances_of(proj.def_id);
498 for (v, s) in std::iter::zip(variances, proj.substs.iter()) {
499 if *v != ty::Variance::Bivariant {
506 ty.super_visit_with(self);
510 ControlFlow::CONTINUE
520 pub fn is_defining(self) -> bool {
522 UseKind::DefiningUse => true,
523 UseKind::OpaqueUse => false,
528 impl<'tcx> InferCtxt<'tcx> {
529 #[instrument(skip(self), level = "debug")]
530 fn register_hidden_type(
532 opaque_type_key: OpaqueTypeKey<'tcx>,
533 cause: ObligationCause<'tcx>,
534 param_env: ty::ParamEnv<'tcx>,
536 origin: hir::OpaqueTyOrigin,
538 ) -> InferResult<'tcx, ()> {
540 let OpaqueTypeKey { def_id, substs } = opaque_type_key;
542 // Ideally, we'd get the span where *this specific `ty` came
543 // from*, but right now we just use the span from the overall
544 // value being folded. In simple cases like `-> impl Foo`,
545 // these are the same span, but not in cases like `-> (impl
547 let span = cause.span;
549 let mut obligations = vec![];
550 let prev = self.inner.borrow_mut().opaque_types().register(
551 OpaqueTypeKey { def_id, substs },
552 OpaqueHiddenType { ty: hidden_ty, span },
555 if let Some(prev) = prev {
557 self.at(&cause, param_env).eq_exp(a_is_expected, prev, hidden_ty)?.obligations;
560 let item_bounds = tcx.bound_explicit_item_bounds(def_id.to_def_id());
562 for (predicate, _) in item_bounds.subst_iter_copied(tcx, substs) {
563 let predicate = predicate.fold_with(&mut BottomUpFolder {
565 ty_op: |ty| match *ty.kind() {
566 // We can't normalize associated types from `rustc_infer`,
567 // but we can eagerly register inference variables for them.
568 // FIXME(RPITIT): Don't replace RPITITs with inference vars.
569 ty::Alias(ty::Projection, projection_ty)
570 if !projection_ty.has_escaping_bound_vars()
571 && tcx.def_kind(projection_ty.def_id)
572 != DefKind::ImplTraitPlaceholder =>
574 self.infer_projection(
582 // Replace all other mentions of the same opaque type with the hidden type,
583 // as the bounds must hold on the hidden type after all.
584 ty::Alias(ty::Opaque, ty::AliasTy { def_id: def_id2, substs: substs2, .. })
585 if def_id.to_def_id() == def_id2 && substs == substs2 =>
589 // FIXME(RPITIT): This can go away when we move to associated types
592 ty::AliasTy { def_id: def_id2, substs: substs2, .. },
593 ) if def_id.to_def_id() == def_id2 && substs == substs2 => hidden_ty,
600 if let ty::PredicateKind::Clause(ty::Clause::Projection(projection)) =
601 predicate.kind().skip_binder()
603 if projection.term.references_error() {
604 // No point on adding these obligations since there's a type error involved.
605 return Ok(InferOk { value: (), obligations: vec![] });
607 trace!("{:#?}", projection.term);
609 // Require that the predicate holds for the concrete type.
611 obligations.push(traits::Obligation::new(
618 Ok(InferOk { value: (), obligations })
622 /// Returns `true` if `opaque_hir_id` is a sibling or a child of a sibling of `def_id`.
625 /// ```ignore UNSOLVED (is this a bug?)
626 /// # #![feature(type_alias_impl_trait)]
629 /// pub trait Bar { /* ... */ }
630 /// pub type Baz = impl Bar;
632 /// # impl Bar for () {}
633 /// fn f1() -> Baz { /* ... */ }
635 /// fn f2() -> bar::Baz { /* ... */ }
639 /// Here, `def_id` is the `LocalDefId` of the defining use of the opaque type (e.g., `f1` or `f2`),
640 /// and `opaque_hir_id` is the `HirId` of the definition of the opaque type `Baz`.
641 /// For the above example, this function returns `true` for `f1` and `false` for `f2`.
642 fn may_define_opaque_type(tcx: TyCtxt<'_>, def_id: LocalDefId, opaque_hir_id: hir::HirId) -> bool {
643 let mut hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
645 // Named opaque types can be defined by any siblings or children of siblings.
646 let scope = tcx.hir().get_defining_scope(opaque_hir_id);
647 // We walk up the node tree until we hit the root or the scope of the opaque type.
648 while hir_id != scope && hir_id != hir::CRATE_HIR_ID {
649 hir_id = tcx.hir().get_parent_item(hir_id).into();
651 // Syntactically, we are allowed to define the concrete type if:
652 let res = hir_id == scope;
654 "may_define_opaque_type(def={:?}, opaque_node={:?}) = {}",
655 tcx.hir().find(hir_id),
656 tcx.hir().get(opaque_hir_id),