1 use crate::traits::{self, ObligationCause, PredicateObligation};
2 use rustc_data_structures::fx::FxHashMap;
3 use rustc_data_structures::sync::Lrc;
5 use rustc_hir::def_id::{DefId, LocalDefId};
6 use rustc_infer::infer::error_reporting::unexpected_hidden_region_diagnostic;
7 use rustc_infer::infer::free_regions::FreeRegionRelations;
8 use rustc_infer::infer::opaque_types::OpaqueTypeDecl;
9 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
10 use rustc_infer::infer::{self, InferCtxt, InferOk};
11 use rustc_middle::ty::fold::{BottomUpFolder, TypeFoldable, TypeFolder, TypeVisitor};
12 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, Subst};
13 use rustc_middle::ty::{self, OpaqueTypeKey, Ty, TyCtxt};
16 use std::ops::ControlFlow;
18 /// Whether member constraints should be generated for all opaque types
20 pub enum GenerateMemberConstraints {
21 /// The default, used by typeck
23 /// The borrow checker needs member constraints in any case where we don't
24 /// have a `'static` bound. This is because the borrow checker has more
25 /// flexibility in the values of regions. For example, given `f<'a, 'b>`
26 /// the borrow checker can have an inference variable outlive `'a` and `'b`,
27 /// but not be equal to `'static`.
31 pub trait InferCtxtExt<'tcx> {
32 fn instantiate_opaque_types<T: TypeFoldable<'tcx>>(
35 param_env: ty::ParamEnv<'tcx>,
38 ) -> InferOk<'tcx, T>;
40 fn constrain_opaque_types<FRR: FreeRegionRelations<'tcx>>(&self, free_region_relations: &FRR);
42 fn constrain_opaque_type<FRR: FreeRegionRelations<'tcx>>(
44 opaque_type_key: OpaqueTypeKey<'tcx>,
45 opaque_defn: &OpaqueTypeDecl<'tcx>,
46 mode: GenerateMemberConstraints,
47 free_region_relations: &FRR,
51 fn generate_member_constraint(
53 concrete_ty: Ty<'tcx>,
54 opaque_defn: &OpaqueTypeDecl<'tcx>,
55 opaque_type_key: OpaqueTypeKey<'tcx>,
56 first_own_region_index: usize,
59 fn infer_opaque_definition_from_instantiation(
61 opaque_type_key: OpaqueTypeKey<'tcx>,
62 instantiated_ty: Ty<'tcx>,
67 impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
68 /// Replaces all opaque types in `value` with fresh inference variables
69 /// and creates appropriate obligations. For example, given the input:
71 /// impl Iterator<Item = impl Debug>
73 /// this method would create two type variables, `?0` and `?1`. It would
74 /// return the type `?0` but also the obligations:
76 /// ?0: Iterator<Item = ?1>
79 /// Moreover, it returns an `OpaqueTypeMap` that would map `?0` to
80 /// info about the `impl Iterator<..>` type and `?1` to info about
81 /// the `impl Debug` type.
85 /// - `parent_def_id` -- the `DefId` of the function in which the opaque type
87 /// - `body_id` -- the body-id with which the resulting obligations should
89 /// - `param_env` -- the in-scope parameter environment to be used for
91 /// - `value` -- the value within which we are instantiating opaque types
92 /// - `value_span` -- the span where the value came from, used in error reporting
93 fn instantiate_opaque_types<T: TypeFoldable<'tcx>>(
96 param_env: ty::ParamEnv<'tcx>,
99 ) -> InferOk<'tcx, T> {
101 "instantiate_opaque_types(value={:?}, body_id={:?}, \
102 param_env={:?}, value_span={:?})",
103 value, body_id, param_env, value_span,
105 let mut instantiator =
106 Instantiator { infcx: self, body_id, param_env, value_span, obligations: vec![] };
107 let value = instantiator.instantiate_opaque_types_in_map(value);
108 InferOk { value, obligations: instantiator.obligations }
111 /// Given the map `opaque_types` containing the opaque
112 /// `impl Trait` types whose underlying, hidden types are being
113 /// inferred, this method adds constraints to the regions
114 /// appearing in those underlying hidden types to ensure that they
115 /// at least do not refer to random scopes within the current
116 /// function. These constraints are not (quite) sufficient to
117 /// guarantee that the regions are actually legal values; that
118 /// final condition is imposed after region inference is done.
122 /// Let's work through an example to explain how it works. Assume
123 /// the current function is as follows:
126 /// fn foo<'a, 'b>(..) -> (impl Bar<'a>, impl Bar<'b>)
129 /// Here, we have two `impl Trait` types whose values are being
130 /// inferred (the `impl Bar<'a>` and the `impl
131 /// Bar<'b>`). Conceptually, this is sugar for a setup where we
132 /// define underlying opaque types (`Foo1`, `Foo2`) and then, in
133 /// the return type of `foo`, we *reference* those definitions:
136 /// type Foo1<'x> = impl Bar<'x>;
137 /// type Foo2<'x> = impl Bar<'x>;
138 /// fn foo<'a, 'b>(..) -> (Foo1<'a>, Foo2<'b>) { .. }
145 /// As indicating in the comments above, each of those references
146 /// is (in the compiler) basically a substitution (`substs`)
147 /// applied to the type of a suitable `def_id` (which identifies
148 /// `Foo1` or `Foo2`).
150 /// Now, at this point in compilation, what we have done is to
151 /// replace each of the references (`Foo1<'a>`, `Foo2<'b>`) with
152 /// fresh inference variables C1 and C2. We wish to use the values
153 /// of these variables to infer the underlying types of `Foo1` and
154 /// `Foo2`. That is, this gives rise to higher-order (pattern) unification
155 /// constraints like:
158 /// for<'a> (Foo1<'a> = C1)
159 /// for<'b> (Foo1<'b> = C2)
162 /// For these equation to be satisfiable, the types `C1` and `C2`
163 /// can only refer to a limited set of regions. For example, `C1`
164 /// can only refer to `'static` and `'a`, and `C2` can only refer
165 /// to `'static` and `'b`. The job of this function is to impose that
168 /// Up to this point, C1 and C2 are basically just random type
169 /// inference variables, and hence they may contain arbitrary
170 /// regions. In fact, it is fairly likely that they do! Consider
171 /// this possible definition of `foo`:
174 /// fn foo<'a, 'b>(x: &'a i32, y: &'b i32) -> (impl Bar<'a>, impl Bar<'b>) {
179 /// Here, the values for the concrete types of the two impl
180 /// traits will include inference variables:
187 /// Ordinarily, the subtyping rules would ensure that these are
188 /// sufficiently large. But since `impl Bar<'a>` isn't a specific
189 /// type per se, we don't get such constraints by default. This
190 /// is where this function comes into play. It adds extra
191 /// constraints to ensure that all the regions which appear in the
192 /// inferred type are regions that could validly appear.
194 /// This is actually a bit of a tricky constraint in general. We
195 /// want to say that each variable (e.g., `'0`) can only take on
196 /// values that were supplied as arguments to the opaque type
197 /// (e.g., `'a` for `Foo1<'a>`) or `'static`, which is always in
198 /// scope. We don't have a constraint quite of this kind in the current
203 /// We generally prefer to make `<=` constraints, since they
204 /// integrate best into the region solver. To do that, we find the
205 /// "minimum" of all the arguments that appear in the substs: that
206 /// is, some region which is less than all the others. In the case
207 /// of `Foo1<'a>`, that would be `'a` (it's the only choice, after
208 /// all). Then we apply that as a least bound to the variables
209 /// (e.g., `'a <= '0`).
211 /// In some cases, there is no minimum. Consider this example:
214 /// fn baz<'a, 'b>() -> impl Trait<'a, 'b> { ... }
217 /// Here we would report a more complex "in constraint", like `'r
218 /// in ['a, 'b, 'static]` (where `'r` is some region appearing in
219 /// the hidden type).
221 /// # Constrain regions, not the hidden concrete type
223 /// Note that generating constraints on each region `Rc` is *not*
224 /// the same as generating an outlives constraint on `Tc` iself.
225 /// For example, if we had a function like this:
228 /// fn foo<'a, T>(x: &'a u32, y: T) -> impl Foo<'a> {
232 /// // Equivalent to:
233 /// type FooReturn<'a, T> = impl Foo<'a>;
234 /// fn foo<'a, T>(..) -> FooReturn<'a, T> { .. }
237 /// then the hidden type `Tc` would be `(&'0 u32, T)` (where `'0`
238 /// is an inference variable). If we generated a constraint that
239 /// `Tc: 'a`, then this would incorrectly require that `T: 'a` --
240 /// but this is not necessary, because the opaque type we
241 /// create will be allowed to reference `T`. So we only generate a
242 /// constraint that `'0: 'a`.
244 /// # The `free_region_relations` parameter
246 /// The `free_region_relations` argument is used to find the
247 /// "minimum" of the regions supplied to a given opaque type.
248 /// It must be a relation that can answer whether `'a <= 'b`,
249 /// where `'a` and `'b` are regions that appear in the "substs"
250 /// for the opaque type references (the `<'a>` in `Foo1<'a>`).
252 /// Note that we do not impose the constraints based on the
253 /// generic regions from the `Foo1` definition (e.g., `'x`). This
254 /// is because the constraints we are imposing here is basically
255 /// the concern of the one generating the constraining type C1,
256 /// which is the current function. It also means that we can
257 /// take "implied bounds" into account in some cases:
260 /// trait SomeTrait<'a, 'b> { }
261 /// fn foo<'a, 'b>(_: &'a &'b u32) -> impl SomeTrait<'a, 'b> { .. }
264 /// Here, the fact that `'b: 'a` is known only because of the
265 /// implied bounds from the `&'a &'b u32` parameter, and is not
266 /// "inherent" to the opaque type definition.
270 /// - `opaque_types` -- the map produced by `instantiate_opaque_types`
271 /// - `free_region_relations` -- something that can be used to relate
272 /// the free regions (`'a`) that appear in the impl trait.
273 fn constrain_opaque_types<FRR: FreeRegionRelations<'tcx>>(&self, free_region_relations: &FRR) {
274 let opaque_types = self.inner.borrow().opaque_types.clone();
275 for (opaque_type_key, opaque_defn) in opaque_types {
276 self.constrain_opaque_type(
279 GenerateMemberConstraints::WhenRequired,
280 free_region_relations,
285 /// See `constrain_opaque_types` for documentation.
286 #[instrument(level = "debug", skip(self, free_region_relations))]
287 fn constrain_opaque_type<FRR: FreeRegionRelations<'tcx>>(
289 opaque_type_key: OpaqueTypeKey<'tcx>,
290 opaque_defn: &OpaqueTypeDecl<'tcx>,
291 mode: GenerateMemberConstraints,
292 free_region_relations: &FRR,
294 let def_id = opaque_type_key.def_id;
298 let concrete_ty = self.resolve_vars_if_possible(opaque_defn.concrete_ty);
300 debug!(?concrete_ty);
302 let first_own_region = match opaque_defn.origin {
303 hir::OpaqueTyOrigin::FnReturn | hir::OpaqueTyOrigin::AsyncFn => {
306 // fn foo<'l0..'ln>() -> impl Trait<'l0..'lm>
310 // type foo::<'p0..'pn>::Foo<'q0..'qm>
311 // fn foo<l0..'ln>() -> foo::<'static..'static>::Foo<'l0..'lm>.
313 // For these types we only iterate over `'l0..lm` below.
314 tcx.generics_of(def_id).parent_count
316 // These opaque type inherit all lifetime parameters from their
317 // parent, so we have to check them all.
318 hir::OpaqueTyOrigin::TyAlias => 0,
321 let span = tcx.def_span(def_id);
323 // Check if the `impl Trait` bounds include region bounds.
324 // For example, this would be true for:
326 // fn foo<'a, 'b, 'c>() -> impl Trait<'c> + 'a + 'b
330 // fn foo<'c>() -> impl Trait<'c>
332 // unless `Trait` was declared like:
334 // trait Trait<'c>: 'c
336 // in which case it would be true.
338 // This is used during regionck to decide whether we need to
339 // impose any additional constraints to ensure that region
340 // variables in `concrete_ty` wind up being constrained to
341 // something from `substs` (or, at minimum, things that outlive
342 // the fn body). (Ultimately, writeback is responsible for this
344 let bounds = tcx.explicit_item_bounds(def_id);
345 debug!("{:#?}", bounds);
346 let bounds = bounds.iter().map(|(bound, _)| bound.subst(tcx, opaque_type_key.substs));
347 debug!("{:#?}", bounds);
348 let opaque_type = tcx.mk_opaque(def_id, opaque_type_key.substs);
350 let required_region_bounds = required_region_bounds(tcx, opaque_type, bounds);
351 if !required_region_bounds.is_empty() {
352 for required_region in required_region_bounds {
353 concrete_ty.visit_with(&mut ConstrainOpaqueTypeRegionVisitor {
355 op: |r| self.sub_regions(infer::CallReturn(span), required_region, r),
358 if let GenerateMemberConstraints::IfNoStaticBound = mode {
359 self.generate_member_constraint(
369 // There were no `required_region_bounds`,
370 // so we have to search for a `least_region`.
371 // Go through all the regions used as arguments to the
372 // opaque type. These are the parameters to the opaque
373 // type; so in our example above, `substs` would contain
374 // `['a]` for the first impl trait and `'b` for the
376 let mut least_region = None;
378 for subst_arg in &opaque_type_key.substs[first_own_region..] {
379 let subst_region = match subst_arg.unpack() {
380 GenericArgKind::Lifetime(r) => r,
381 GenericArgKind::Type(_) | GenericArgKind::Const(_) => continue,
384 // Compute the least upper bound of it with the other regions.
385 debug!(?least_region);
386 debug!(?subst_region);
388 None => least_region = Some(subst_region),
390 if free_region_relations.sub_free_regions(self.tcx, lr, subst_region) {
391 // keep the current least region
392 } else if free_region_relations.sub_free_regions(self.tcx, subst_region, lr) {
393 // switch to `subst_region`
394 least_region = Some(subst_region);
396 // There are two regions (`lr` and
397 // `subst_region`) which are not relatable. We
398 // can't find a best choice. Therefore,
399 // instead of creating a single bound like
400 // `'r: 'a` (which is our preferred choice),
401 // we will create a "in bound" like `'r in
402 // ['a, 'b, 'c]`, where `'a..'c` are the
403 // regions that appear in the impl trait.
405 return self.generate_member_constraint(
416 let least_region = least_region.unwrap_or(tcx.lifetimes.re_static);
417 debug!(?least_region);
419 if let GenerateMemberConstraints::IfNoStaticBound = mode {
420 if least_region != tcx.lifetimes.re_static {
421 self.generate_member_constraint(
429 concrete_ty.visit_with(&mut ConstrainOpaqueTypeRegionVisitor {
431 op: |r| self.sub_regions(infer::CallReturn(span), least_region, r),
435 /// As a fallback, we sometimes generate an "in constraint". For
436 /// a case like `impl Foo<'a, 'b>`, where `'a` and `'b` cannot be
437 /// related, we would generate a constraint `'r in ['a, 'b,
438 /// 'static]` for each region `'r` that appears in the hidden type
439 /// (i.e., it must be equal to `'a`, `'b`, or `'static`).
441 /// `conflict1` and `conflict2` are the two region bounds that we
442 /// detected which were unrelated. They are used for diagnostics.
443 fn generate_member_constraint(
445 concrete_ty: Ty<'tcx>,
446 opaque_defn: &OpaqueTypeDecl<'tcx>,
447 opaque_type_key: OpaqueTypeKey<'tcx>,
448 first_own_region: usize,
450 // Create the set of choice regions: each region in the hidden
451 // type can be equal to any of the region parameters of the
452 // opaque type definition.
453 let choice_regions: Lrc<Vec<ty::Region<'tcx>>> = Lrc::new(
454 opaque_type_key.substs[first_own_region..]
456 .filter_map(|arg| match arg.unpack() {
457 GenericArgKind::Lifetime(r) => Some(r),
458 GenericArgKind::Type(_) | GenericArgKind::Const(_) => None,
460 .chain(std::iter::once(self.tcx.lifetimes.re_static))
464 concrete_ty.visit_with(&mut ConstrainOpaqueTypeRegionVisitor {
467 self.member_constraint(
468 opaque_type_key.def_id,
469 opaque_defn.definition_span,
478 /// Given the fully resolved, instantiated type for an opaque
479 /// type, i.e., the value of an inference variable like C1 or C2
480 /// (*), computes the "definition type" for an opaque type
481 /// definition -- that is, the inferred value of `Foo1<'x>` or
482 /// `Foo2<'x>` that we would conceptually use in its definition:
484 /// type Foo1<'x> = impl Bar<'x> = AAA; <-- this type AAA
485 /// type Foo2<'x> = impl Bar<'x> = BBB; <-- or this type BBB
486 /// fn foo<'a, 'b>(..) -> (Foo1<'a>, Foo2<'b>) { .. }
488 /// Note that these values are defined in terms of a distinct set of
489 /// generic parameters (`'x` instead of `'a`) from C1 or C2. The main
490 /// purpose of this function is to do that translation.
492 /// (*) C1 and C2 were introduced in the comments on
493 /// `constrain_opaque_types`. Read that comment for more context.
497 /// - `def_id`, the `impl Trait` type
498 /// - `substs`, the substs used to instantiate this opaque type
499 /// - `instantiated_ty`, the inferred type C1 -- fully resolved, lifted version of
500 /// `opaque_defn.concrete_ty`
501 #[instrument(level = "debug", skip(self))]
502 fn infer_opaque_definition_from_instantiation(
504 opaque_type_key: OpaqueTypeKey<'tcx>,
505 instantiated_ty: Ty<'tcx>,
508 let OpaqueTypeKey { def_id, substs } = opaque_type_key;
510 // Use substs to build up a reverse map from regions to their
511 // identity mappings. This is necessary because of `impl
512 // Trait` lifetimes are computed by replacing existing
513 // lifetimes with 'static and remapping only those used in the
514 // `impl Trait` return type, resulting in the parameters
516 let id_substs = InternalSubsts::identity_for_item(self.tcx, def_id);
518 let map: FxHashMap<GenericArg<'tcx>, GenericArg<'tcx>> =
519 substs.iter().enumerate().map(|(index, subst)| (subst, id_substs[index])).collect();
520 debug!("map = {:#?}", map);
522 // Convert the type from the function into a type valid outside
523 // the function, by replacing invalid regions with 'static,
524 // after producing an error for each of them.
525 let definition_ty = instantiated_ty.fold_with(&mut ReverseMapper::new(
527 self.is_tainted_by_errors(),
533 debug!(?definition_ty);
539 // Visitor that requires that (almost) all regions in the type visited outlive
540 // `least_region`. We cannot use `push_outlives_components` because regions in
541 // closure signatures are not included in their outlives components. We need to
542 // ensure all regions outlive the given bound so that we don't end up with,
543 // say, `ReVar` appearing in a return type and causing ICEs when other
544 // functions end up with region constraints involving regions from other
547 // We also cannot use `for_each_free_region` because for closures it includes
548 // the regions parameters from the enclosing item.
550 // We ignore any type parameters because impl trait values are assumed to
551 // capture all the in-scope type parameters.
552 struct ConstrainOpaqueTypeRegionVisitor<'tcx, OP> {
557 impl<'tcx, OP> TypeVisitor<'tcx> for ConstrainOpaqueTypeRegionVisitor<'tcx, OP>
559 OP: FnMut(ty::Region<'tcx>),
561 fn tcx_for_anon_const_substs(&self) -> Option<TyCtxt<'tcx>> {
565 fn visit_binder<T: TypeFoldable<'tcx>>(
567 t: &ty::Binder<'tcx, T>,
568 ) -> ControlFlow<Self::BreakTy> {
569 t.as_ref().skip_binder().visit_with(self);
570 ControlFlow::CONTINUE
573 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
575 // ignore bound regions, keep visiting
576 ty::ReLateBound(_, _) => ControlFlow::CONTINUE,
579 ControlFlow::CONTINUE
584 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
585 // We're only interested in types involving regions
586 if !ty.flags().intersects(ty::TypeFlags::HAS_POTENTIAL_FREE_REGIONS) {
587 return ControlFlow::CONTINUE;
591 ty::Closure(_, ref substs) => {
592 // Skip lifetime parameters of the enclosing item(s)
594 substs.as_closure().tupled_upvars_ty().visit_with(self);
595 substs.as_closure().sig_as_fn_ptr_ty().visit_with(self);
598 ty::Generator(_, ref substs, _) => {
599 // Skip lifetime parameters of the enclosing item(s)
600 // Also skip the witness type, because that has no free regions.
602 substs.as_generator().tupled_upvars_ty().visit_with(self);
603 substs.as_generator().return_ty().visit_with(self);
604 substs.as_generator().yield_ty().visit_with(self);
605 substs.as_generator().resume_ty().visit_with(self);
608 ty.super_visit_with(self);
612 ControlFlow::CONTINUE
616 struct ReverseMapper<'tcx> {
619 /// If errors have already been reported in this fn, we suppress
620 /// our own errors because they are sometimes derivative.
621 tainted_by_errors: bool,
623 opaque_type_def_id: DefId,
624 map: FxHashMap<GenericArg<'tcx>, GenericArg<'tcx>>,
625 map_missing_regions_to_empty: bool,
627 /// initially `Some`, set to `None` once error has been reported
628 hidden_ty: Option<Ty<'tcx>>,
630 /// Span of function being checked.
634 impl ReverseMapper<'tcx> {
637 tainted_by_errors: bool,
638 opaque_type_def_id: DefId,
639 map: FxHashMap<GenericArg<'tcx>, GenericArg<'tcx>>,
648 map_missing_regions_to_empty: false,
649 hidden_ty: Some(hidden_ty),
654 fn fold_kind_mapping_missing_regions_to_empty(
656 kind: GenericArg<'tcx>,
657 ) -> GenericArg<'tcx> {
658 assert!(!self.map_missing_regions_to_empty);
659 self.map_missing_regions_to_empty = true;
660 let kind = kind.fold_with(self);
661 self.map_missing_regions_to_empty = false;
665 fn fold_kind_normally(&mut self, kind: GenericArg<'tcx>) -> GenericArg<'tcx> {
666 assert!(!self.map_missing_regions_to_empty);
671 impl TypeFolder<'tcx> for ReverseMapper<'tcx> {
672 fn tcx(&self) -> TyCtxt<'tcx> {
676 #[instrument(skip(self), level = "debug")]
677 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
679 // Ignore bound regions and `'static` regions that appear in the
680 // type, we only need to remap regions that reference lifetimes
681 // from the function declaraion.
682 // This would ignore `'r` in a type like `for<'r> fn(&'r u32)`.
683 ty::ReLateBound(..) | ty::ReStatic => return r,
685 // If regions have been erased (by writeback), don't try to unerase
687 ty::ReErased => return r,
689 // The regions that we expect from borrow checking.
690 ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReEmpty(ty::UniverseIndex::ROOT) => {}
692 ty::ReEmpty(_) | ty::RePlaceholder(_) | ty::ReVar(_) => {
693 // All of the regions in the type should either have been
694 // erased by writeback, or mapped back to named regions by
696 bug!("unexpected region kind in opaque type: {:?}", r);
700 let generics = self.tcx().generics_of(self.opaque_type_def_id);
701 match self.map.get(&r.into()).map(|k| k.unpack()) {
702 Some(GenericArgKind::Lifetime(r1)) => r1,
703 Some(u) => panic!("region mapped to unexpected kind: {:?}", u),
704 None if self.map_missing_regions_to_empty || self.tainted_by_errors => {
705 self.tcx.lifetimes.re_root_empty
707 None if generics.parent.is_some() => {
708 if let Some(hidden_ty) = self.hidden_ty.take() {
709 unexpected_hidden_region_diagnostic(
711 self.tcx.def_span(self.opaque_type_def_id),
717 self.tcx.lifetimes.re_root_empty
722 .struct_span_err(self.span, "non-defining opaque type use in defining scope")
726 "lifetime `{}` is part of concrete type but not used in \
727 parameter list of the `impl Trait` type alias",
733 self.tcx().lifetimes.re_static
738 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
740 ty::Closure(def_id, substs) => {
741 // I am a horrible monster and I pray for death. When
742 // we encounter a closure here, it is always a closure
743 // from within the function that we are currently
744 // type-checking -- one that is now being encapsulated
745 // in an opaque type. Ideally, we would
746 // go through the types/lifetimes that it references
747 // and treat them just like we would any other type,
748 // which means we would error out if we find any
749 // reference to a type/region that is not in the
752 // **However,** in the case of closures, there is a
753 // somewhat subtle (read: hacky) consideration. The
754 // problem is that our closure types currently include
755 // all the lifetime parameters declared on the
756 // enclosing function, even if they are unused by the
757 // closure itself. We can't readily filter them out,
758 // so here we replace those values with `'empty`. This
759 // can't really make a difference to the rest of the
760 // compiler; those regions are ignored for the
761 // outlives relation, and hence don't affect trait
762 // selection or auto traits, and they are erased
765 let generics = self.tcx.generics_of(def_id);
766 let substs = self.tcx.mk_substs(substs.iter().enumerate().map(|(index, kind)| {
767 if index < generics.parent_count {
768 // Accommodate missing regions in the parent kinds...
769 self.fold_kind_mapping_missing_regions_to_empty(kind)
771 // ...but not elsewhere.
772 self.fold_kind_normally(kind)
776 self.tcx.mk_closure(def_id, substs)
779 ty::Generator(def_id, substs, movability) => {
780 let generics = self.tcx.generics_of(def_id);
781 let substs = self.tcx.mk_substs(substs.iter().enumerate().map(|(index, kind)| {
782 if index < generics.parent_count {
783 // Accommodate missing regions in the parent kinds...
784 self.fold_kind_mapping_missing_regions_to_empty(kind)
786 // ...but not elsewhere.
787 self.fold_kind_normally(kind)
791 self.tcx.mk_generator(def_id, substs, movability)
794 ty::Param(param) => {
795 // Look it up in the substitution list.
796 match self.map.get(&ty.into()).map(|k| k.unpack()) {
797 // Found it in the substitution list; replace with the parameter from the
799 Some(GenericArgKind::Type(t1)) => t1,
800 Some(u) => panic!("type mapped to unexpected kind: {:?}", u),
802 debug!(?param, ?self.map);
808 "type parameter `{}` is part of concrete type but not \
809 used in parameter list for the `impl Trait` type alias",
815 self.tcx().ty_error()
820 _ => ty.super_fold_with(self),
824 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
825 trace!("checking const {:?}", ct);
826 // Find a const parameter
828 ty::ConstKind::Param(..) => {
829 // Look it up in the substitution list.
830 match self.map.get(&ct.into()).map(|k| k.unpack()) {
831 // Found it in the substitution list, replace with the parameter from the
833 Some(GenericArgKind::Const(c1)) => c1,
834 Some(u) => panic!("const mapped to unexpected kind: {:?}", u),
841 "const parameter `{}` is part of concrete type but not \
842 used in parameter list for the `impl Trait` type alias",
848 self.tcx().const_error(ct.ty)
858 struct Instantiator<'a, 'tcx> {
859 infcx: &'a InferCtxt<'a, 'tcx>,
861 param_env: ty::ParamEnv<'tcx>,
863 obligations: Vec<PredicateObligation<'tcx>>,
866 impl<'a, 'tcx> Instantiator<'a, 'tcx> {
867 fn instantiate_opaque_types_in_map<T: TypeFoldable<'tcx>>(&mut self, value: T) -> T {
868 let tcx = self.infcx.tcx;
869 value.fold_with(&mut BottomUpFolder {
872 if ty.references_error() {
873 return tcx.ty_error();
874 } else if let ty::Opaque(def_id, substs) = ty.kind() {
875 // Check that this is `impl Trait` type is
876 // declared by `parent_def_id` -- i.e., one whose
877 // value we are inferring. At present, this is
878 // always true during the first phase of
879 // type-check, but not always true later on during
880 // NLL. Once we support named opaque types more fully,
881 // this same scenario will be able to arise during all phases.
883 // Here is an example using type alias `impl Trait`
884 // that indicates the distinction we are checking for:
888 // pub type Foo = impl Iterator;
889 // pub fn make_foo() -> Foo { .. }
893 // fn foo() -> a::Foo { a::make_foo() }
897 // Here, the return type of `foo` references an
898 // `Opaque` indeed, but not one whose value is
899 // presently being inferred. You can get into a
900 // similar situation with closure return types
904 // fn foo() -> impl Iterator { .. }
906 // let x = || foo(); // returns the Opaque assoc with `foo`
909 if let Some(def_id) = def_id.as_local() {
910 let opaque_hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
911 let parent_def_id = self.infcx.defining_use_anchor;
912 let def_scope_default = || {
913 let opaque_parent_hir_id = tcx.hir().get_parent_item(opaque_hir_id);
914 parent_def_id == tcx.hir().local_def_id(opaque_parent_hir_id)
916 let (in_definition_scope, origin) =
917 match tcx.hir().expect_item(opaque_hir_id).kind {
918 // Anonymous `impl Trait`
919 hir::ItemKind::OpaqueTy(hir::OpaqueTy {
920 impl_trait_fn: Some(parent),
923 }) => (parent == parent_def_id.to_def_id(), origin),
924 // Named `type Foo = impl Bar;`
925 hir::ItemKind::OpaqueTy(hir::OpaqueTy {
930 may_define_opaque_type(tcx, parent_def_id, opaque_hir_id),
933 _ => (def_scope_default(), hir::OpaqueTyOrigin::TyAlias),
935 if in_definition_scope {
936 let opaque_type_key =
937 OpaqueTypeKey { def_id: def_id.to_def_id(), substs };
938 return self.fold_opaque_ty(ty, opaque_type_key, origin);
942 "instantiate_opaque_types_in_map: \
943 encountered opaque outside its definition scope \
957 #[instrument(skip(self), level = "debug")]
961 opaque_type_key: OpaqueTypeKey<'tcx>,
962 origin: hir::OpaqueTyOrigin,
964 let infcx = self.infcx;
966 let OpaqueTypeKey { def_id, substs } = opaque_type_key;
968 // Use the same type variable if the exact same opaque type appears more
969 // than once in the return type (e.g., if it's passed to a type alias).
970 if let Some(opaque_defn) = infcx.inner.borrow().opaque_types.get(&opaque_type_key) {
971 debug!("re-using cached concrete type {:?}", opaque_defn.concrete_ty.kind());
972 return opaque_defn.concrete_ty;
975 let ty_var = infcx.next_ty_var(TypeVariableOrigin {
976 kind: TypeVariableOriginKind::TypeInference,
977 span: self.value_span,
980 // Ideally, we'd get the span where *this specific `ty` came
981 // from*, but right now we just use the span from the overall
982 // value being folded. In simple cases like `-> impl Foo`,
983 // these are the same span, but not in cases like `-> (impl
985 let definition_span = self.value_span;
988 let mut infcx = self.infcx.inner.borrow_mut();
989 infcx.opaque_types.insert(
990 OpaqueTypeKey { def_id, substs },
991 OpaqueTypeDecl { opaque_type: ty, definition_span, concrete_ty: ty_var, origin },
993 infcx.opaque_types_vars.insert(ty_var, ty);
996 debug!("generated new type inference var {:?}", ty_var.kind());
998 let item_bounds = tcx.explicit_item_bounds(def_id);
1000 self.obligations.reserve(item_bounds.len());
1001 for (predicate, _) in item_bounds {
1003 let predicate = predicate.subst(tcx, substs);
1006 // We can't normalize associated types from `rustc_infer`, but we can eagerly register inference variables for them.
1007 let predicate = predicate.fold_with(&mut BottomUpFolder {
1009 ty_op: |ty| match ty.kind() {
1010 ty::Projection(projection_ty) => infcx.infer_projection(
1013 ObligationCause::misc(self.value_span, self.body_id),
1015 &mut self.obligations,
1024 if let ty::PredicateKind::Projection(projection) = predicate.kind().skip_binder() {
1025 if projection.ty.references_error() {
1026 // No point on adding these obligations since there's a type error involved.
1027 return tcx.ty_error();
1030 // Change the predicate to refer to the type variable,
1031 // which will be the concrete type instead of the opaque type.
1032 // This also instantiates nested instances of `impl Trait`.
1033 let predicate = self.instantiate_opaque_types_in_map(predicate);
1036 traits::ObligationCause::new(self.value_span, self.body_id, traits::OpaqueType);
1038 // Require that the predicate holds for the concrete type.
1040 self.obligations.push(traits::Obligation::new(cause, self.param_env, predicate));
1047 /// Returns `true` if `opaque_hir_id` is a sibling or a child of a sibling of `def_id`.
1053 /// pub trait Bar { .. }
1055 /// pub type Baz = impl Bar;
1057 /// fn f1() -> Baz { .. }
1060 /// fn f2() -> bar::Baz { .. }
1064 /// Here, `def_id` is the `LocalDefId` of the defining use of the opaque type (e.g., `f1` or `f2`),
1065 /// and `opaque_hir_id` is the `HirId` of the definition of the opaque type `Baz`.
1066 /// For the above example, this function returns `true` for `f1` and `false` for `f2`.
1067 fn may_define_opaque_type(tcx: TyCtxt<'_>, def_id: LocalDefId, opaque_hir_id: hir::HirId) -> bool {
1068 let mut hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
1070 // Named opaque types can be defined by any siblings or children of siblings.
1071 let scope = tcx.hir().get_defining_scope(opaque_hir_id);
1072 // We walk up the node tree until we hit the root or the scope of the opaque type.
1073 while hir_id != scope && hir_id != hir::CRATE_HIR_ID {
1074 hir_id = tcx.hir().get_parent_item(hir_id);
1076 // Syntactically, we are allowed to define the concrete type if:
1077 let res = hir_id == scope;
1079 "may_define_opaque_type(def={:?}, opaque_node={:?}) = {}",
1080 tcx.hir().find(hir_id),
1081 tcx.hir().get(opaque_hir_id),
1087 /// Given a set of predicates that apply to an object type, returns
1088 /// the region bounds that the (erased) `Self` type must
1089 /// outlive. Precisely *because* the `Self` type is erased, the
1090 /// parameter `erased_self_ty` must be supplied to indicate what type
1091 /// has been used to represent `Self` in the predicates
1092 /// themselves. This should really be a unique type; `FreshTy(0)` is a
1095 /// N.B., in some cases, particularly around higher-ranked bounds,
1096 /// this function returns a kind of conservative approximation.
1097 /// That is, all regions returned by this function are definitely
1098 /// required, but there may be other region bounds that are not
1099 /// returned, as well as requirements like `for<'a> T: 'a`.
1101 /// Requires that trait definitions have been processed so that we can
1102 /// elaborate predicates and walk supertraits.
1103 #[instrument(skip(tcx, predicates), level = "debug")]
1104 crate fn required_region_bounds(
1106 erased_self_ty: Ty<'tcx>,
1107 predicates: impl Iterator<Item = ty::Predicate<'tcx>>,
1108 ) -> Vec<ty::Region<'tcx>> {
1109 assert!(!erased_self_ty.has_escaping_bound_vars());
1111 traits::elaborate_predicates(tcx, predicates)
1112 .filter_map(|obligation| {
1113 debug!(?obligation);
1114 match obligation.predicate.kind().skip_binder() {
1115 ty::PredicateKind::Projection(..)
1116 | ty::PredicateKind::Trait(..)
1117 | ty::PredicateKind::Subtype(..)
1118 | ty::PredicateKind::Coerce(..)
1119 | ty::PredicateKind::WellFormed(..)
1120 | ty::PredicateKind::ObjectSafe(..)
1121 | ty::PredicateKind::ClosureKind(..)
1122 | ty::PredicateKind::RegionOutlives(..)
1123 | ty::PredicateKind::ConstEvaluatable(..)
1124 | ty::PredicateKind::ConstEquate(..)
1125 | ty::PredicateKind::TypeWellFormedFromEnv(..) => None,
1126 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ref t, ref r)) => {
1127 // Search for a bound of the form `erased_self_ty
1128 // : 'a`, but be wary of something like `for<'a>
1129 // erased_self_ty : 'a` (we interpret a
1130 // higher-ranked bound like that as 'static,
1131 // though at present the code in `fulfill.rs`
1132 // considers such bounds to be unsatisfiable, so
1133 // it's kind of a moot point since you could never
1134 // construct such an object, but this seems
1135 // correct even if that code changes).
1136 if t == &erased_self_ty && !r.has_escaping_bound_vars() {