1 use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
2 use crate::infer::{InferCtxt, InferOk};
4 use rustc_data_structures::sync::Lrc;
5 use rustc_data_structures::vec_map::VecMap;
7 use rustc_hir::def_id::LocalDefId;
8 use rustc_middle::ty::fold::BottomUpFolder;
9 use rustc_middle::ty::subst::{GenericArgKind, Subst};
10 use rustc_middle::ty::{self, OpaqueTypeKey, Ty, TyCtxt, TypeFoldable, TypeVisitor};
13 use std::ops::ControlFlow;
15 pub type OpaqueTypeMap<'tcx> = VecMap<OpaqueTypeKey<'tcx>, OpaqueTypeDecl<'tcx>>;
17 /// Information about the opaque types whose values we
18 /// are inferring in this function (these are the `impl Trait` that
19 /// appear in the return type).
20 #[derive(Copy, Clone, Debug)]
21 pub struct OpaqueTypeDecl<'tcx> {
22 /// The opaque type (`ty::Opaque`) for this declaration.
23 pub opaque_type: Ty<'tcx>,
25 /// The span of this particular definition of the opaque type. So
28 /// ```ignore (incomplete snippet)
29 /// type Foo = impl Baz;
31 /// // ^^^ This is the span we are looking for!
35 /// In cases where the fn returns `(impl Trait, impl Trait)` or
36 /// other such combinations, the result is currently
37 /// over-approximated, but better than nothing.
38 pub definition_span: Span,
40 /// The type variable that represents the value of the opaque type
41 /// that we require. In other words, after we compile this function,
42 /// we will be created a constraint like:
46 /// where `?C` is the value of this type variable. =) It may
47 /// naturally refer to the type and lifetime parameters in scope
48 /// in this function, though ultimately it should only reference
49 /// those that are arguments to `Foo` in the constraint above. (In
50 /// other words, `?C` should not include `'b`, even though it's a
51 /// lifetime parameter on `foo`.)
52 pub concrete_ty: Ty<'tcx>,
54 /// The origin of the opaque type.
55 pub origin: hir::OpaqueTyOrigin,
58 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
59 /// Replaces all opaque types in `value` with fresh inference variables
60 /// and creates appropriate obligations. For example, given the input:
62 /// impl Iterator<Item = impl Debug>
64 /// this method would create two type variables, `?0` and `?1`. It would
65 /// return the type `?0` but also the obligations:
67 /// ?0: Iterator<Item = ?1>
70 /// Moreover, it returns an `OpaqueTypeMap` that would map `?0` to
71 /// info about the `impl Iterator<..>` type and `?1` to info about
72 /// the `impl Debug` type.
76 /// - `parent_def_id` -- the `DefId` of the function in which the opaque type
78 /// - `body_id` -- the body-id with which the resulting obligations should
80 /// - `param_env` -- the in-scope parameter environment to be used for
82 /// - `value` -- the value within which we are instantiating opaque types
83 /// - `value_span` -- the span where the value came from, used in error reporting
84 pub fn instantiate_opaque_types<T: TypeFoldable<'tcx>>(
87 param_env: ty::ParamEnv<'tcx>,
90 ) -> InferOk<'tcx, T> {
92 "instantiate_opaque_types(value={:?}, body_id={:?}, \
93 param_env={:?}, value_span={:?})",
94 value, body_id, param_env, value_span,
96 let mut instantiator =
97 Instantiator { infcx: self, body_id, param_env, value_span, obligations: vec![] };
98 let value = instantiator.instantiate_opaque_types_in_map(value);
99 InferOk { value, obligations: instantiator.obligations }
102 /// Given the map `opaque_types` containing the opaque
103 /// `impl Trait` types whose underlying, hidden types are being
104 /// inferred, this method adds constraints to the regions
105 /// appearing in those underlying hidden types to ensure that they
106 /// at least do not refer to random scopes within the current
107 /// function. These constraints are not (quite) sufficient to
108 /// guarantee that the regions are actually legal values; that
109 /// final condition is imposed after region inference is done.
113 /// Let's work through an example to explain how it works. Assume
114 /// the current function is as follows:
117 /// fn foo<'a, 'b>(..) -> (impl Bar<'a>, impl Bar<'b>)
120 /// Here, we have two `impl Trait` types whose values are being
121 /// inferred (the `impl Bar<'a>` and the `impl
122 /// Bar<'b>`). Conceptually, this is sugar for a setup where we
123 /// define underlying opaque types (`Foo1`, `Foo2`) and then, in
124 /// the return type of `foo`, we *reference* those definitions:
127 /// type Foo1<'x> = impl Bar<'x>;
128 /// type Foo2<'x> = impl Bar<'x>;
129 /// fn foo<'a, 'b>(..) -> (Foo1<'a>, Foo2<'b>) { .. }
136 /// As indicating in the comments above, each of those references
137 /// is (in the compiler) basically a substitution (`substs`)
138 /// applied to the type of a suitable `def_id` (which identifies
139 /// `Foo1` or `Foo2`).
141 /// Now, at this point in compilation, what we have done is to
142 /// replace each of the references (`Foo1<'a>`, `Foo2<'b>`) with
143 /// fresh inference variables C1 and C2. We wish to use the values
144 /// of these variables to infer the underlying types of `Foo1` and
145 /// `Foo2`. That is, this gives rise to higher-order (pattern) unification
146 /// constraints like:
149 /// for<'a> (Foo1<'a> = C1)
150 /// for<'b> (Foo1<'b> = C2)
153 /// For these equation to be satisfiable, the types `C1` and `C2`
154 /// can only refer to a limited set of regions. For example, `C1`
155 /// can only refer to `'static` and `'a`, and `C2` can only refer
156 /// to `'static` and `'b`. The job of this function is to impose that
159 /// Up to this point, C1 and C2 are basically just random type
160 /// inference variables, and hence they may contain arbitrary
161 /// regions. In fact, it is fairly likely that they do! Consider
162 /// this possible definition of `foo`:
165 /// fn foo<'a, 'b>(x: &'a i32, y: &'b i32) -> (impl Bar<'a>, impl Bar<'b>) {
170 /// Here, the values for the concrete types of the two impl
171 /// traits will include inference variables:
178 /// Ordinarily, the subtyping rules would ensure that these are
179 /// sufficiently large. But since `impl Bar<'a>` isn't a specific
180 /// type per se, we don't get such constraints by default. This
181 /// is where this function comes into play. It adds extra
182 /// constraints to ensure that all the regions which appear in the
183 /// inferred type are regions that could validly appear.
185 /// This is actually a bit of a tricky constraint in general. We
186 /// want to say that each variable (e.g., `'0`) can only take on
187 /// values that were supplied as arguments to the opaque type
188 /// (e.g., `'a` for `Foo1<'a>`) or `'static`, which is always in
189 /// scope. We don't have a constraint quite of this kind in the current
194 /// We generally prefer to make `<=` constraints, since they
195 /// integrate best into the region solver. To do that, we find the
196 /// "minimum" of all the arguments that appear in the substs: that
197 /// is, some region which is less than all the others. In the case
198 /// of `Foo1<'a>`, that would be `'a` (it's the only choice, after
199 /// all). Then we apply that as a least bound to the variables
200 /// (e.g., `'a <= '0`).
202 /// In some cases, there is no minimum. Consider this example:
205 /// fn baz<'a, 'b>() -> impl Trait<'a, 'b> { ... }
208 /// Here we would report a more complex "in constraint", like `'r
209 /// in ['a, 'b, 'static]` (where `'r` is some region appearing in
210 /// the hidden type).
212 /// # Constrain regions, not the hidden concrete type
214 /// Note that generating constraints on each region `Rc` is *not*
215 /// the same as generating an outlives constraint on `Tc` iself.
216 /// For example, if we had a function like this:
219 /// fn foo<'a, T>(x: &'a u32, y: T) -> impl Foo<'a> {
223 /// // Equivalent to:
224 /// type FooReturn<'a, T> = impl Foo<'a>;
225 /// fn foo<'a, T>(..) -> FooReturn<'a, T> { .. }
228 /// then the hidden type `Tc` would be `(&'0 u32, T)` (where `'0`
229 /// is an inference variable). If we generated a constraint that
230 /// `Tc: 'a`, then this would incorrectly require that `T: 'a` --
231 /// but this is not necessary, because the opaque type we
232 /// create will be allowed to reference `T`. So we only generate a
233 /// constraint that `'0: 'a`.
235 /// # The `free_region_relations` parameter
237 /// The `free_region_relations` argument is used to find the
238 /// "minimum" of the regions supplied to a given opaque type.
239 /// It must be a relation that can answer whether `'a <= 'b`,
240 /// where `'a` and `'b` are regions that appear in the "substs"
241 /// for the opaque type references (the `<'a>` in `Foo1<'a>`).
243 /// Note that we do not impose the constraints based on the
244 /// generic regions from the `Foo1` definition (e.g., `'x`). This
245 /// is because the constraints we are imposing here is basically
246 /// the concern of the one generating the constraining type C1,
247 /// which is the current function. It also means that we can
248 /// take "implied bounds" into account in some cases:
251 /// trait SomeTrait<'a, 'b> { }
252 /// fn foo<'a, 'b>(_: &'a &'b u32) -> impl SomeTrait<'a, 'b> { .. }
255 /// Here, the fact that `'b: 'a` is known only because of the
256 /// implied bounds from the `&'a &'b u32` parameter, and is not
257 /// "inherent" to the opaque type definition.
261 /// - `opaque_types` -- the map produced by `instantiate_opaque_types`
262 /// - `free_region_relations` -- something that can be used to relate
263 /// the free regions (`'a`) that appear in the impl trait.
264 #[instrument(level = "debug", skip(self))]
265 pub fn constrain_opaque_type(
267 opaque_type_key: OpaqueTypeKey<'tcx>,
268 opaque_defn: &OpaqueTypeDecl<'tcx>,
270 let def_id = opaque_type_key.def_id;
274 let concrete_ty = self.resolve_vars_if_possible(opaque_defn.concrete_ty);
276 debug!(?concrete_ty);
278 let first_own_region = match opaque_defn.origin {
279 hir::OpaqueTyOrigin::FnReturn | hir::OpaqueTyOrigin::AsyncFn => {
282 // fn foo<'l0..'ln>() -> impl Trait<'l0..'lm>
286 // type foo::<'p0..'pn>::Foo<'q0..'qm>
287 // fn foo<l0..'ln>() -> foo::<'static..'static>::Foo<'l0..'lm>.
289 // For these types we only iterate over `'l0..lm` below.
290 tcx.generics_of(def_id).parent_count
292 // These opaque type inherit all lifetime parameters from their
293 // parent, so we have to check them all.
294 hir::OpaqueTyOrigin::TyAlias => 0,
297 // For a case like `impl Foo<'a, 'b>`, we would generate a constraint
298 // `'r in ['a, 'b, 'static]` for each region `'r` that appears in the
299 // hidden type (i.e., it must be equal to `'a`, `'b`, or `'static`).
301 // `conflict1` and `conflict2` are the two region bounds that we
302 // detected which were unrelated. They are used for diagnostics.
304 // Create the set of choice regions: each region in the hidden
305 // type can be equal to any of the region parameters of the
306 // opaque type definition.
307 let choice_regions: Lrc<Vec<ty::Region<'tcx>>> = Lrc::new(
308 opaque_type_key.substs[first_own_region..]
310 .filter_map(|arg| match arg.unpack() {
311 GenericArgKind::Lifetime(r) => Some(r),
312 GenericArgKind::Type(_) | GenericArgKind::Const(_) => None,
314 .chain(std::iter::once(self.tcx.lifetimes.re_static))
318 concrete_ty.visit_with(&mut ConstrainOpaqueTypeRegionVisitor {
321 self.member_constraint(
322 opaque_type_key.def_id,
323 opaque_defn.definition_span,
333 // Visitor that requires that (almost) all regions in the type visited outlive
334 // `least_region`. We cannot use `push_outlives_components` because regions in
335 // closure signatures are not included in their outlives components. We need to
336 // ensure all regions outlive the given bound so that we don't end up with,
337 // say, `ReVar` appearing in a return type and causing ICEs when other
338 // functions end up with region constraints involving regions from other
341 // We also cannot use `for_each_free_region` because for closures it includes
342 // the regions parameters from the enclosing item.
344 // We ignore any type parameters because impl trait values are assumed to
345 // capture all the in-scope type parameters.
346 struct ConstrainOpaqueTypeRegionVisitor<'tcx, OP> {
351 impl<'tcx, OP> TypeVisitor<'tcx> for ConstrainOpaqueTypeRegionVisitor<'tcx, OP>
353 OP: FnMut(ty::Region<'tcx>),
355 fn tcx_for_anon_const_substs(&self) -> Option<TyCtxt<'tcx>> {
359 fn visit_binder<T: TypeFoldable<'tcx>>(
361 t: &ty::Binder<'tcx, T>,
362 ) -> ControlFlow<Self::BreakTy> {
363 t.as_ref().skip_binder().visit_with(self);
364 ControlFlow::CONTINUE
367 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
369 // ignore bound regions, keep visiting
370 ty::ReLateBound(_, _) => ControlFlow::CONTINUE,
373 ControlFlow::CONTINUE
378 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
379 // We're only interested in types involving regions
380 if !ty.flags().intersects(ty::TypeFlags::HAS_POTENTIAL_FREE_REGIONS) {
381 return ControlFlow::CONTINUE;
385 ty::Closure(_, ref substs) => {
386 // Skip lifetime parameters of the enclosing item(s)
388 substs.as_closure().tupled_upvars_ty().visit_with(self);
389 substs.as_closure().sig_as_fn_ptr_ty().visit_with(self);
392 ty::Generator(_, ref substs, _) => {
393 // Skip lifetime parameters of the enclosing item(s)
394 // Also skip the witness type, because that has no free regions.
396 substs.as_generator().tupled_upvars_ty().visit_with(self);
397 substs.as_generator().return_ty().visit_with(self);
398 substs.as_generator().yield_ty().visit_with(self);
399 substs.as_generator().resume_ty().visit_with(self);
402 ty.super_visit_with(self);
406 ControlFlow::CONTINUE
410 struct Instantiator<'a, 'tcx> {
411 infcx: &'a InferCtxt<'a, 'tcx>,
413 param_env: ty::ParamEnv<'tcx>,
415 obligations: Vec<traits::PredicateObligation<'tcx>>,
418 impl<'a, 'tcx> Instantiator<'a, 'tcx> {
419 fn instantiate_opaque_types_in_map<T: TypeFoldable<'tcx>>(&mut self, value: T) -> T {
420 let tcx = self.infcx.tcx;
421 value.fold_with(&mut BottomUpFolder {
424 if ty.references_error() {
425 return tcx.ty_error();
426 } else if let ty::Opaque(def_id, substs) = ty.kind() {
427 // Check that this is `impl Trait` type is
428 // declared by `parent_def_id` -- i.e., one whose
429 // value we are inferring. At present, this is
430 // always true during the first phase of
431 // type-check, but not always true later on during
432 // NLL. Once we support named opaque types more fully,
433 // this same scenario will be able to arise during all phases.
435 // Here is an example using type alias `impl Trait`
436 // that indicates the distinction we are checking for:
440 // pub type Foo = impl Iterator;
441 // pub fn make_foo() -> Foo { .. }
445 // fn foo() -> a::Foo { a::make_foo() }
449 // Here, the return type of `foo` references an
450 // `Opaque` indeed, but not one whose value is
451 // presently being inferred. You can get into a
452 // similar situation with closure return types
456 // fn foo() -> impl Iterator { .. }
458 // let x = || foo(); // returns the Opaque assoc with `foo`
461 if let Some(def_id) = def_id.as_local() {
462 let opaque_hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
463 let parent_def_id = self.infcx.defining_use_anchor;
464 let def_scope_default = || {
465 let opaque_parent_hir_id = tcx.hir().get_parent_item(opaque_hir_id);
466 parent_def_id == tcx.hir().local_def_id(opaque_parent_hir_id)
468 let (in_definition_scope, origin) =
469 match tcx.hir().expect_item(opaque_hir_id).kind {
470 // Anonymous `impl Trait`
471 hir::ItemKind::OpaqueTy(hir::OpaqueTy {
472 impl_trait_fn: Some(parent),
475 }) => (parent == parent_def_id.to_def_id(), origin),
476 // Named `type Foo = impl Bar;`
477 hir::ItemKind::OpaqueTy(hir::OpaqueTy {
482 may_define_opaque_type(tcx, parent_def_id, opaque_hir_id),
485 _ => (def_scope_default(), hir::OpaqueTyOrigin::TyAlias),
487 if in_definition_scope {
488 let opaque_type_key =
489 OpaqueTypeKey { def_id: def_id.to_def_id(), substs };
490 return self.fold_opaque_ty(ty, opaque_type_key, origin);
494 "instantiate_opaque_types_in_map: \
495 encountered opaque outside its definition scope \
509 #[instrument(skip(self), level = "debug")]
513 opaque_type_key: OpaqueTypeKey<'tcx>,
514 origin: hir::OpaqueTyOrigin,
516 let infcx = self.infcx;
518 let OpaqueTypeKey { def_id, substs } = opaque_type_key;
520 // Use the same type variable if the exact same opaque type appears more
521 // than once in the return type (e.g., if it's passed to a type alias).
522 if let Some(opaque_defn) = infcx.inner.borrow().opaque_types.get(&opaque_type_key) {
523 debug!("re-using cached concrete type {:?}", opaque_defn.concrete_ty.kind());
524 return opaque_defn.concrete_ty;
527 let ty_var = infcx.next_ty_var(TypeVariableOrigin {
528 kind: TypeVariableOriginKind::TypeInference,
529 span: self.value_span,
532 // Ideally, we'd get the span where *this specific `ty` came
533 // from*, but right now we just use the span from the overall
534 // value being folded. In simple cases like `-> impl Foo`,
535 // these are the same span, but not in cases like `-> (impl
537 let definition_span = self.value_span;
540 let mut infcx = self.infcx.inner.borrow_mut();
541 infcx.opaque_types.insert(
542 OpaqueTypeKey { def_id, substs },
543 OpaqueTypeDecl { opaque_type: ty, definition_span, concrete_ty: ty_var, origin },
545 infcx.opaque_types_vars.insert(ty_var, ty);
548 debug!("generated new type inference var {:?}", ty_var.kind());
550 let item_bounds = tcx.explicit_item_bounds(def_id);
552 self.obligations.reserve(item_bounds.len());
553 for (predicate, _) in item_bounds {
555 let predicate = predicate.subst(tcx, substs);
558 // We can't normalize associated types from `rustc_infer`, but we can eagerly register inference variables for them.
559 let predicate = predicate.fold_with(&mut BottomUpFolder {
561 ty_op: |ty| match ty.kind() {
562 ty::Projection(projection_ty) => infcx.infer_projection(
565 traits::ObligationCause::misc(self.value_span, self.body_id),
567 &mut self.obligations,
576 if let ty::PredicateKind::Projection(projection) = predicate.kind().skip_binder() {
577 if projection.ty.references_error() {
578 // No point on adding these obligations since there's a type error involved.
579 return tcx.ty_error();
582 // Change the predicate to refer to the type variable,
583 // which will be the concrete type instead of the opaque type.
584 // This also instantiates nested instances of `impl Trait`.
585 let predicate = self.instantiate_opaque_types_in_map(predicate);
588 traits::ObligationCause::new(self.value_span, self.body_id, traits::OpaqueType);
590 // Require that the predicate holds for the concrete type.
592 self.obligations.push(traits::Obligation::new(cause, self.param_env, predicate));
599 /// Returns `true` if `opaque_hir_id` is a sibling or a child of a sibling of `def_id`.
605 /// pub trait Bar { .. }
607 /// pub type Baz = impl Bar;
609 /// fn f1() -> Baz { .. }
612 /// fn f2() -> bar::Baz { .. }
616 /// Here, `def_id` is the `LocalDefId` of the defining use of the opaque type (e.g., `f1` or `f2`),
617 /// and `opaque_hir_id` is the `HirId` of the definition of the opaque type `Baz`.
618 /// For the above example, this function returns `true` for `f1` and `false` for `f2`.
619 fn may_define_opaque_type(tcx: TyCtxt<'_>, def_id: LocalDefId, opaque_hir_id: hir::HirId) -> bool {
620 let mut hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
622 // Named opaque types can be defined by any siblings or children of siblings.
623 let scope = tcx.hir().get_defining_scope(opaque_hir_id);
624 // We walk up the node tree until we hit the root or the scope of the opaque type.
625 while hir_id != scope && hir_id != hir::CRATE_HIR_ID {
626 hir_id = tcx.hir().get_parent_item(hir_id);
628 // Syntactically, we are allowed to define the concrete type if:
629 let res = hir_id == scope;
631 "may_define_opaque_type(def={:?}, opaque_node={:?}) = {}",
632 tcx.hir().find(hir_id),
633 tcx.hir().get(opaque_hir_id),