1 use crate::infer::InferCtxtExt as _;
2 use crate::traits::{self, PredicateObligation};
3 use rustc::ty::fold::{BottomUpFolder, TypeFoldable, TypeFolder, TypeVisitor};
4 use rustc::ty::free_region_map::FreeRegionRelations;
5 use rustc::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, SubstsRef};
6 use rustc::ty::{self, GenericParamDefKind, Ty, TyCtxt};
7 use rustc_data_structures::fx::FxHashMap;
8 use rustc_data_structures::sync::Lrc;
10 use rustc_hir::def_id::{DefId, DefIdMap};
12 use rustc_infer::infer::error_reporting::unexpected_hidden_region_diagnostic;
13 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
14 use rustc_infer::infer::{self, InferCtxt, InferOk};
15 use rustc_session::config::nightly_options;
18 pub type OpaqueTypeMap<'tcx> = DefIdMap<OpaqueTypeDecl<'tcx>>;
20 /// Information about the opaque types whose values we
21 /// are inferring in this function (these are the `impl Trait` that
22 /// appear in the return type).
23 #[derive(Copy, Clone, Debug)]
24 pub struct OpaqueTypeDecl<'tcx> {
25 /// The opaque type (`ty::Opaque`) for this declaration.
26 pub opaque_type: Ty<'tcx>,
28 /// The substitutions that we apply to the opaque type that this
29 /// `impl Trait` desugars to. e.g., if:
31 /// fn foo<'a, 'b, T>() -> impl Trait<'a>
33 /// winds up desugared to:
35 /// type Foo<'x, X> = impl Trait<'x>
36 /// fn foo<'a, 'b, T>() -> Foo<'a, T>
38 /// then `substs` would be `['a, T]`.
39 pub substs: SubstsRef<'tcx>,
41 /// The span of this particular definition of the opaque type. So
45 /// type Foo = impl Baz;
47 /// ^^^ This is the span we are looking for!
50 /// In cases where the fn returns `(impl Trait, impl Trait)` or
51 /// other such combinations, the result is currently
52 /// over-approximated, but better than nothing.
53 pub definition_span: Span,
55 /// The type variable that represents the value of the opaque type
56 /// that we require. In other words, after we compile this function,
57 /// we will be created a constraint like:
61 /// where `?C` is the value of this type variable. =) It may
62 /// naturally refer to the type and lifetime parameters in scope
63 /// in this function, though ultimately it should only reference
64 /// those that are arguments to `Foo` in the constraint above. (In
65 /// other words, `?C` should not include `'b`, even though it's a
66 /// lifetime parameter on `foo`.)
67 pub concrete_ty: Ty<'tcx>,
69 /// Returns `true` if the `impl Trait` bounds include region bounds.
70 /// For example, this would be true for:
72 /// fn foo<'a, 'b, 'c>() -> impl Trait<'c> + 'a + 'b
76 /// fn foo<'c>() -> impl Trait<'c>
78 /// unless `Trait` was declared like:
80 /// trait Trait<'c>: 'c
82 /// in which case it would be true.
84 /// This is used during regionck to decide whether we need to
85 /// impose any additional constraints to ensure that region
86 /// variables in `concrete_ty` wind up being constrained to
87 /// something from `substs` (or, at minimum, things that outlive
88 /// the fn body). (Ultimately, writeback is responsible for this
90 pub has_required_region_bounds: bool,
92 /// The origin of the opaque type.
93 pub origin: hir::OpaqueTyOrigin,
96 /// Whether member constraints should be generated for all opaque types
97 pub enum GenerateMemberConstraints {
98 /// The default, used by typeck
100 /// The borrow checker needs member constraints in any case where we don't
101 /// have a `'static` bound. This is because the borrow checker has more
102 /// flexibility in the values of regions. For example, given `f<'a, 'b>`
103 /// the borrow checker can have an inference variable outlive `'a` and `'b`,
104 /// but not be equal to `'static`.
108 pub trait InferCtxtExt<'tcx> {
109 fn instantiate_opaque_types<T: TypeFoldable<'tcx>>(
111 parent_def_id: DefId,
113 param_env: ty::ParamEnv<'tcx>,
116 ) -> InferOk<'tcx, (T, OpaqueTypeMap<'tcx>)>;
118 fn constrain_opaque_types<FRR: FreeRegionRelations<'tcx>>(
120 opaque_types: &OpaqueTypeMap<'tcx>,
121 free_region_relations: &FRR,
124 fn constrain_opaque_type<FRR: FreeRegionRelations<'tcx>>(
127 opaque_defn: &OpaqueTypeDecl<'tcx>,
128 mode: GenerateMemberConstraints,
129 free_region_relations: &FRR,
133 fn generate_member_constraint(
135 concrete_ty: Ty<'tcx>,
136 opaque_type_generics: &ty::Generics,
137 opaque_defn: &OpaqueTypeDecl<'tcx>,
138 opaque_type_def_id: DefId,
142 fn member_constraint_feature_gate(
144 opaque_defn: &OpaqueTypeDecl<'tcx>,
145 opaque_type_def_id: DefId,
146 conflict1: ty::Region<'tcx>,
147 conflict2: ty::Region<'tcx>,
150 fn infer_opaque_definition_from_instantiation(
153 substs: SubstsRef<'tcx>,
154 instantiated_ty: Ty<'tcx>,
159 impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
160 /// Replaces all opaque types in `value` with fresh inference variables
161 /// and creates appropriate obligations. For example, given the input:
163 /// impl Iterator<Item = impl Debug>
165 /// this method would create two type variables, `?0` and `?1`. It would
166 /// return the type `?0` but also the obligations:
168 /// ?0: Iterator<Item = ?1>
171 /// Moreover, it returns a `OpaqueTypeMap` that would map `?0` to
172 /// info about the `impl Iterator<..>` type and `?1` to info about
173 /// the `impl Debug` type.
177 /// - `parent_def_id` -- the `DefId` of the function in which the opaque type
179 /// - `body_id` -- the body-id with which the resulting obligations should
181 /// - `param_env` -- the in-scope parameter environment to be used for
183 /// - `value` -- the value within which we are instantiating opaque types
184 /// - `value_span` -- the span where the value came from, used in error reporting
185 fn instantiate_opaque_types<T: TypeFoldable<'tcx>>(
187 parent_def_id: DefId,
189 param_env: ty::ParamEnv<'tcx>,
192 ) -> InferOk<'tcx, (T, OpaqueTypeMap<'tcx>)> {
194 "instantiate_opaque_types(value={:?}, parent_def_id={:?}, body_id={:?}, \
195 param_env={:?}, value_span={:?})",
196 value, parent_def_id, body_id, param_env, value_span,
198 let mut instantiator = Instantiator {
204 opaque_types: Default::default(),
207 let value = instantiator.instantiate_opaque_types_in_map(value);
208 InferOk { value: (value, instantiator.opaque_types), obligations: instantiator.obligations }
211 /// Given the map `opaque_types` containing the opaque
212 /// `impl Trait` types whose underlying, hidden types are being
213 /// inferred, this method adds constraints to the regions
214 /// appearing in those underlying hidden types to ensure that they
215 /// at least do not refer to random scopes within the current
216 /// function. These constraints are not (quite) sufficient to
217 /// guarantee that the regions are actually legal values; that
218 /// final condition is imposed after region inference is done.
222 /// Let's work through an example to explain how it works. Assume
223 /// the current function is as follows:
226 /// fn foo<'a, 'b>(..) -> (impl Bar<'a>, impl Bar<'b>)
229 /// Here, we have two `impl Trait` types whose values are being
230 /// inferred (the `impl Bar<'a>` and the `impl
231 /// Bar<'b>`). Conceptually, this is sugar for a setup where we
232 /// define underlying opaque types (`Foo1`, `Foo2`) and then, in
233 /// the return type of `foo`, we *reference* those definitions:
236 /// type Foo1<'x> = impl Bar<'x>;
237 /// type Foo2<'x> = impl Bar<'x>;
238 /// fn foo<'a, 'b>(..) -> (Foo1<'a>, Foo2<'b>) { .. }
245 /// As indicating in the comments above, each of those references
246 /// is (in the compiler) basically a substitution (`substs`)
247 /// applied to the type of a suitable `def_id` (which identifies
248 /// `Foo1` or `Foo2`).
250 /// Now, at this point in compilation, what we have done is to
251 /// replace each of the references (`Foo1<'a>`, `Foo2<'b>`) with
252 /// fresh inference variables C1 and C2. We wish to use the values
253 /// of these variables to infer the underlying types of `Foo1` and
254 /// `Foo2`. That is, this gives rise to higher-order (pattern) unification
255 /// constraints like:
258 /// for<'a> (Foo1<'a> = C1)
259 /// for<'b> (Foo1<'b> = C2)
262 /// For these equation to be satisfiable, the types `C1` and `C2`
263 /// can only refer to a limited set of regions. For example, `C1`
264 /// can only refer to `'static` and `'a`, and `C2` can only refer
265 /// to `'static` and `'b`. The job of this function is to impose that
268 /// Up to this point, C1 and C2 are basically just random type
269 /// inference variables, and hence they may contain arbitrary
270 /// regions. In fact, it is fairly likely that they do! Consider
271 /// this possible definition of `foo`:
274 /// fn foo<'a, 'b>(x: &'a i32, y: &'b i32) -> (impl Bar<'a>, impl Bar<'b>) {
279 /// Here, the values for the concrete types of the two impl
280 /// traits will include inference variables:
287 /// Ordinarily, the subtyping rules would ensure that these are
288 /// sufficiently large. But since `impl Bar<'a>` isn't a specific
289 /// type per se, we don't get such constraints by default. This
290 /// is where this function comes into play. It adds extra
291 /// constraints to ensure that all the regions which appear in the
292 /// inferred type are regions that could validly appear.
294 /// This is actually a bit of a tricky constraint in general. We
295 /// want to say that each variable (e.g., `'0`) can only take on
296 /// values that were supplied as arguments to the opaque type
297 /// (e.g., `'a` for `Foo1<'a>`) or `'static`, which is always in
298 /// scope. We don't have a constraint quite of this kind in the current
303 /// We generally prefer to make `<=` constraints, since they
304 /// integrate best into the region solver. To do that, we find the
305 /// "minimum" of all the arguments that appear in the substs: that
306 /// is, some region which is less than all the others. In the case
307 /// of `Foo1<'a>`, that would be `'a` (it's the only choice, after
308 /// all). Then we apply that as a least bound to the variables
309 /// (e.g., `'a <= '0`).
311 /// In some cases, there is no minimum. Consider this example:
314 /// fn baz<'a, 'b>() -> impl Trait<'a, 'b> { ... }
317 /// Here we would report a more complex "in constraint", like `'r
318 /// in ['a, 'b, 'static]` (where `'r` is some region appearing in
319 /// the hidden type).
321 /// # Constrain regions, not the hidden concrete type
323 /// Note that generating constraints on each region `Rc` is *not*
324 /// the same as generating an outlives constraint on `Tc` iself.
325 /// For example, if we had a function like this:
328 /// fn foo<'a, T>(x: &'a u32, y: T) -> impl Foo<'a> {
332 /// // Equivalent to:
333 /// type FooReturn<'a, T> = impl Foo<'a>;
334 /// fn foo<'a, T>(..) -> FooReturn<'a, T> { .. }
337 /// then the hidden type `Tc` would be `(&'0 u32, T)` (where `'0`
338 /// is an inference variable). If we generated a constraint that
339 /// `Tc: 'a`, then this would incorrectly require that `T: 'a` --
340 /// but this is not necessary, because the opaque type we
341 /// create will be allowed to reference `T`. So we only generate a
342 /// constraint that `'0: 'a`.
344 /// # The `free_region_relations` parameter
346 /// The `free_region_relations` argument is used to find the
347 /// "minimum" of the regions supplied to a given opaque type.
348 /// It must be a relation that can answer whether `'a <= 'b`,
349 /// where `'a` and `'b` are regions that appear in the "substs"
350 /// for the opaque type references (the `<'a>` in `Foo1<'a>`).
352 /// Note that we do not impose the constraints based on the
353 /// generic regions from the `Foo1` definition (e.g., `'x`). This
354 /// is because the constraints we are imposing here is basically
355 /// the concern of the one generating the constraining type C1,
356 /// which is the current function. It also means that we can
357 /// take "implied bounds" into account in some cases:
360 /// trait SomeTrait<'a, 'b> { }
361 /// fn foo<'a, 'b>(_: &'a &'b u32) -> impl SomeTrait<'a, 'b> { .. }
364 /// Here, the fact that `'b: 'a` is known only because of the
365 /// implied bounds from the `&'a &'b u32` parameter, and is not
366 /// "inherent" to the opaque type definition.
370 /// - `opaque_types` -- the map produced by `instantiate_opaque_types`
371 /// - `free_region_relations` -- something that can be used to relate
372 /// the free regions (`'a`) that appear in the impl trait.
373 fn constrain_opaque_types<FRR: FreeRegionRelations<'tcx>>(
375 opaque_types: &OpaqueTypeMap<'tcx>,
376 free_region_relations: &FRR,
378 debug!("constrain_opaque_types()");
380 for (&def_id, opaque_defn) in opaque_types {
381 self.constrain_opaque_type(
384 GenerateMemberConstraints::WhenRequired,
385 free_region_relations,
390 /// See `constrain_opaque_types` for documentation.
391 fn constrain_opaque_type<FRR: FreeRegionRelations<'tcx>>(
394 opaque_defn: &OpaqueTypeDecl<'tcx>,
395 mode: GenerateMemberConstraints,
396 free_region_relations: &FRR,
398 debug!("constrain_opaque_type()");
399 debug!("constrain_opaque_type: def_id={:?}", def_id);
400 debug!("constrain_opaque_type: opaque_defn={:#?}", opaque_defn);
404 let concrete_ty = self.resolve_vars_if_possible(&opaque_defn.concrete_ty);
406 debug!("constrain_opaque_type: concrete_ty={:?}", concrete_ty);
408 let opaque_type_generics = tcx.generics_of(def_id);
410 let span = tcx.def_span(def_id);
412 // If there are required region bounds, we can use them.
413 if opaque_defn.has_required_region_bounds {
414 let predicates_of = tcx.predicates_of(def_id);
415 debug!("constrain_opaque_type: predicates: {:#?}", predicates_of,);
416 let bounds = predicates_of.instantiate(tcx, opaque_defn.substs);
417 debug!("constrain_opaque_type: bounds={:#?}", bounds);
418 let opaque_type = tcx.mk_opaque(def_id, opaque_defn.substs);
420 let required_region_bounds =
421 required_region_bounds(tcx, opaque_type, bounds.predicates);
422 debug_assert!(!required_region_bounds.is_empty());
424 for required_region in required_region_bounds {
425 concrete_ty.visit_with(&mut ConstrainOpaqueTypeRegionVisitor {
427 op: |r| self.sub_regions(infer::CallReturn(span), required_region, r),
430 if let GenerateMemberConstraints::IfNoStaticBound = mode {
431 self.generate_member_constraint(
433 opaque_type_generics,
441 // There were no `required_region_bounds`,
442 // so we have to search for a `least_region`.
443 // Go through all the regions used as arguments to the
444 // opaque type. These are the parameters to the opaque
445 // type; so in our example above, `substs` would contain
446 // `['a]` for the first impl trait and `'b` for the
448 let mut least_region = None;
449 for param in &opaque_type_generics.params {
451 GenericParamDefKind::Lifetime => {}
455 // Get the value supplied for this region from the substs.
456 let subst_arg = opaque_defn.substs.region_at(param.index as usize);
458 // Compute the least upper bound of it with the other regions.
459 debug!("constrain_opaque_types: least_region={:?}", least_region);
460 debug!("constrain_opaque_types: subst_arg={:?}", subst_arg);
462 None => least_region = Some(subst_arg),
464 if free_region_relations.sub_free_regions(self.tcx, lr, subst_arg) {
465 // keep the current least region
466 } else if free_region_relations.sub_free_regions(self.tcx, subst_arg, lr) {
467 // switch to `subst_arg`
468 least_region = Some(subst_arg);
470 // There are two regions (`lr` and
471 // `subst_arg`) which are not relatable. We
472 // can't find a best choice. Therefore,
473 // instead of creating a single bound like
474 // `'r: 'a` (which is our preferred choice),
475 // we will create a "in bound" like `'r in
476 // ['a, 'b, 'c]`, where `'a..'c` are the
477 // regions that appear in the impl trait.
479 // For now, enforce a feature gate outside of async functions.
480 self.member_constraint_feature_gate(opaque_defn, def_id, lr, subst_arg);
482 return self.generate_member_constraint(
484 opaque_type_generics,
493 let least_region = least_region.unwrap_or(tcx.lifetimes.re_static);
494 debug!("constrain_opaque_types: least_region={:?}", least_region);
496 if let GenerateMemberConstraints::IfNoStaticBound = mode {
497 if least_region != tcx.lifetimes.re_static {
498 self.generate_member_constraint(
500 opaque_type_generics,
506 concrete_ty.visit_with(&mut ConstrainOpaqueTypeRegionVisitor {
508 op: |r| self.sub_regions(infer::CallReturn(span), least_region, r),
512 /// As a fallback, we sometimes generate an "in constraint". For
513 /// a case like `impl Foo<'a, 'b>`, where `'a` and `'b` cannot be
514 /// related, we would generate a constraint `'r in ['a, 'b,
515 /// 'static]` for each region `'r` that appears in the hidden type
516 /// (i.e., it must be equal to `'a`, `'b`, or `'static`).
518 /// `conflict1` and `conflict2` are the two region bounds that we
519 /// detected which were unrelated. They are used for diagnostics.
520 fn generate_member_constraint(
522 concrete_ty: Ty<'tcx>,
523 opaque_type_generics: &ty::Generics,
524 opaque_defn: &OpaqueTypeDecl<'tcx>,
525 opaque_type_def_id: DefId,
527 // Create the set of choice regions: each region in the hidden
528 // type can be equal to any of the region parameters of the
529 // opaque type definition.
530 let choice_regions: Lrc<Vec<ty::Region<'tcx>>> = Lrc::new(
534 .filter(|param| match param.kind {
535 GenericParamDefKind::Lifetime => true,
536 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => false,
538 .map(|param| opaque_defn.substs.region_at(param.index as usize))
539 .chain(std::iter::once(self.tcx.lifetimes.re_static))
543 concrete_ty.visit_with(&mut ConstrainOpaqueTypeRegionVisitor {
546 self.member_constraint(
548 opaque_defn.definition_span,
557 /// Member constraints are presently feature-gated except for
558 /// async-await. We expect to lift this once we've had a bit more
560 fn member_constraint_feature_gate(
562 opaque_defn: &OpaqueTypeDecl<'tcx>,
563 opaque_type_def_id: DefId,
564 conflict1: ty::Region<'tcx>,
565 conflict2: ty::Region<'tcx>,
567 // If we have `#![feature(member_constraints)]`, no problems.
568 if self.tcx.features().member_constraints {
572 let span = self.tcx.def_span(opaque_type_def_id);
574 // Without a feature-gate, we only generate member-constraints for async-await.
575 let context_name = match opaque_defn.origin {
576 // No feature-gate required for `async fn`.
577 hir::OpaqueTyOrigin::AsyncFn => return false,
579 // Otherwise, generate the label we'll use in the error message.
580 hir::OpaqueTyOrigin::TypeAlias
581 | hir::OpaqueTyOrigin::FnReturn
582 | hir::OpaqueTyOrigin::Misc => "impl Trait",
584 let msg = format!("ambiguous lifetime bound in `{}`", context_name);
585 let mut err = self.tcx.sess.struct_span_err(span, &msg);
587 let conflict1_name = conflict1.to_string();
588 let conflict2_name = conflict2.to_string();
590 let label = match (&*conflict1_name, &*conflict2_name) {
591 ("'_", "'_") => "the elided lifetimes here do not outlive one another",
593 label_owned = format!(
594 "neither `{}` nor `{}` outlives the other",
595 conflict1_name, conflict2_name,
600 err.span_label(span, label);
602 if nightly_options::is_nightly_build() {
603 err.help("add #![feature(member_constraints)] to the crate attributes to enable");
610 /// Given the fully resolved, instantiated type for an opaque
611 /// type, i.e., the value of an inference variable like C1 or C2
612 /// (*), computes the "definition type" for an opaque type
613 /// definition -- that is, the inferred value of `Foo1<'x>` or
614 /// `Foo2<'x>` that we would conceptually use in its definition:
616 /// type Foo1<'x> = impl Bar<'x> = AAA; <-- this type AAA
617 /// type Foo2<'x> = impl Bar<'x> = BBB; <-- or this type BBB
618 /// fn foo<'a, 'b>(..) -> (Foo1<'a>, Foo2<'b>) { .. }
620 /// Note that these values are defined in terms of a distinct set of
621 /// generic parameters (`'x` instead of `'a`) from C1 or C2. The main
622 /// purpose of this function is to do that translation.
624 /// (*) C1 and C2 were introduced in the comments on
625 /// `constrain_opaque_types`. Read that comment for more context.
629 /// - `def_id`, the `impl Trait` type
630 /// - `substs`, the substs used to instantiate this opaque type
631 /// - `instantiated_ty`, the inferred type C1 -- fully resolved, lifted version of
632 /// `opaque_defn.concrete_ty`
633 fn infer_opaque_definition_from_instantiation(
636 substs: SubstsRef<'tcx>,
637 instantiated_ty: Ty<'tcx>,
641 "infer_opaque_definition_from_instantiation(def_id={:?}, instantiated_ty={:?})",
642 def_id, instantiated_ty
645 // Use substs to build up a reverse map from regions to their
646 // identity mappings. This is necessary because of `impl
647 // Trait` lifetimes are computed by replacing existing
648 // lifetimes with 'static and remapping only those used in the
649 // `impl Trait` return type, resulting in the parameters
651 let id_substs = InternalSubsts::identity_for_item(self.tcx, def_id);
652 let map: FxHashMap<GenericArg<'tcx>, GenericArg<'tcx>> =
653 substs.iter().enumerate().map(|(index, subst)| (*subst, id_substs[index])).collect();
655 // Convert the type from the function into a type valid outside
656 // the function, by replacing invalid regions with 'static,
657 // after producing an error for each of them.
658 let definition_ty = instantiated_ty.fold_with(&mut ReverseMapper::new(
660 self.is_tainted_by_errors(),
666 debug!("infer_opaque_definition_from_instantiation: definition_ty={:?}", definition_ty);
672 // Visitor that requires that (almost) all regions in the type visited outlive
673 // `least_region`. We cannot use `push_outlives_components` because regions in
674 // closure signatures are not included in their outlives components. We need to
675 // ensure all regions outlive the given bound so that we don't end up with,
676 // say, `ReScope` appearing in a return type and causing ICEs when other
677 // functions end up with region constraints involving regions from other
680 // We also cannot use `for_each_free_region` because for closures it includes
681 // the regions parameters from the enclosing item.
683 // We ignore any type parameters because impl trait values are assumed to
684 // capture all the in-scope type parameters.
685 struct ConstrainOpaqueTypeRegionVisitor<'tcx, OP>
687 OP: FnMut(ty::Region<'tcx>),
693 impl<'tcx, OP> TypeVisitor<'tcx> for ConstrainOpaqueTypeRegionVisitor<'tcx, OP>
695 OP: FnMut(ty::Region<'tcx>),
697 fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> bool {
698 t.skip_binder().visit_with(self);
699 false // keep visiting
702 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
704 // ignore bound regions, keep visiting
705 ty::ReLateBound(_, _) => false,
713 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
714 // We're only interested in types involving regions
715 if !ty.flags.intersects(ty::TypeFlags::HAS_FREE_REGIONS) {
716 return false; // keep visiting
720 ty::Closure(def_id, ref substs) => {
721 // Skip lifetime parameters of the enclosing item(s)
723 for upvar_ty in substs.as_closure().upvar_tys(def_id, self.tcx) {
724 upvar_ty.visit_with(self);
727 substs.as_closure().sig_ty(def_id, self.tcx).visit_with(self);
730 ty::Generator(def_id, ref substs, _) => {
731 // Skip lifetime parameters of the enclosing item(s)
732 // Also skip the witness type, because that has no free regions.
734 for upvar_ty in substs.as_generator().upvar_tys(def_id, self.tcx) {
735 upvar_ty.visit_with(self);
738 substs.as_generator().return_ty(def_id, self.tcx).visit_with(self);
739 substs.as_generator().yield_ty(def_id, self.tcx).visit_with(self);
740 substs.as_generator().resume_ty(def_id, self.tcx).visit_with(self);
743 ty.super_visit_with(self);
751 struct ReverseMapper<'tcx> {
754 /// If errors have already been reported in this fn, we suppress
755 /// our own errors because they are sometimes derivative.
756 tainted_by_errors: bool,
758 opaque_type_def_id: DefId,
759 map: FxHashMap<GenericArg<'tcx>, GenericArg<'tcx>>,
760 map_missing_regions_to_empty: bool,
762 /// initially `Some`, set to `None` once error has been reported
763 hidden_ty: Option<Ty<'tcx>>,
765 /// Span of function being checked.
769 impl ReverseMapper<'tcx> {
772 tainted_by_errors: bool,
773 opaque_type_def_id: DefId,
774 map: FxHashMap<GenericArg<'tcx>, GenericArg<'tcx>>,
783 map_missing_regions_to_empty: false,
784 hidden_ty: Some(hidden_ty),
789 fn fold_kind_mapping_missing_regions_to_empty(
791 kind: GenericArg<'tcx>,
792 ) -> GenericArg<'tcx> {
793 assert!(!self.map_missing_regions_to_empty);
794 self.map_missing_regions_to_empty = true;
795 let kind = kind.fold_with(self);
796 self.map_missing_regions_to_empty = false;
800 fn fold_kind_normally(&mut self, kind: GenericArg<'tcx>) -> GenericArg<'tcx> {
801 assert!(!self.map_missing_regions_to_empty);
806 impl TypeFolder<'tcx> for ReverseMapper<'tcx> {
807 fn tcx(&self) -> TyCtxt<'tcx> {
811 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
813 // Ignore bound regions and `'static` regions that appear in the
814 // type, we only need to remap regions that reference lifetimes
815 // from the function declaraion.
816 // This would ignore `'r` in a type like `for<'r> fn(&'r u32)`.
817 ty::ReLateBound(..) | ty::ReStatic => return r,
819 // If regions have been erased (by writeback), don't try to unerase
821 ty::ReErased => return r,
823 // The regions that we expect from borrow checking.
824 ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReEmpty(ty::UniverseIndex::ROOT) => {}
827 | ty::RePlaceholder(_)
830 | ty::ReClosureBound(_) => {
831 // All of the regions in the type should either have been
832 // erased by writeback, or mapped back to named regions by
834 bug!("unexpected region kind in opaque type: {:?}", r);
838 let generics = self.tcx().generics_of(self.opaque_type_def_id);
839 match self.map.get(&r.into()).map(|k| k.unpack()) {
840 Some(GenericArgKind::Lifetime(r1)) => r1,
841 Some(u) => panic!("region mapped to unexpected kind: {:?}", u),
842 None if self.map_missing_regions_to_empty || self.tainted_by_errors => {
843 self.tcx.lifetimes.re_root_empty
845 None if generics.parent.is_some() => {
846 if let Some(hidden_ty) = self.hidden_ty.take() {
847 unexpected_hidden_region_diagnostic(
850 self.tcx.def_span(self.opaque_type_def_id),
856 self.tcx.lifetimes.re_root_empty
861 .struct_span_err(self.span, "non-defining opaque type use in defining scope")
865 "lifetime `{}` is part of concrete type but not used in \
866 parameter list of the `impl Trait` type alias",
872 self.tcx().lifetimes.re_static
877 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
879 ty::Closure(def_id, substs) => {
880 // I am a horrible monster and I pray for death. When
881 // we encounter a closure here, it is always a closure
882 // from within the function that we are currently
883 // type-checking -- one that is now being encapsulated
884 // in an opaque type. Ideally, we would
885 // go through the types/lifetimes that it references
886 // and treat them just like we would any other type,
887 // which means we would error out if we find any
888 // reference to a type/region that is not in the
891 // **However,** in the case of closures, there is a
892 // somewhat subtle (read: hacky) consideration. The
893 // problem is that our closure types currently include
894 // all the lifetime parameters declared on the
895 // enclosing function, even if they are unused by the
896 // closure itself. We can't readily filter them out,
897 // so here we replace those values with `'empty`. This
898 // can't really make a difference to the rest of the
899 // compiler; those regions are ignored for the
900 // outlives relation, and hence don't affect trait
901 // selection or auto traits, and they are erased
904 let generics = self.tcx.generics_of(def_id);
905 let substs = self.tcx.mk_substs(substs.iter().enumerate().map(|(index, &kind)| {
906 if index < generics.parent_count {
907 // Accommodate missing regions in the parent kinds...
908 self.fold_kind_mapping_missing_regions_to_empty(kind)
910 // ...but not elsewhere.
911 self.fold_kind_normally(kind)
915 self.tcx.mk_closure(def_id, substs)
918 ty::Generator(def_id, substs, movability) => {
919 let generics = self.tcx.generics_of(def_id);
920 let substs = self.tcx.mk_substs(substs.iter().enumerate().map(|(index, &kind)| {
921 if index < generics.parent_count {
922 // Accommodate missing regions in the parent kinds...
923 self.fold_kind_mapping_missing_regions_to_empty(kind)
925 // ...but not elsewhere.
926 self.fold_kind_normally(kind)
930 self.tcx.mk_generator(def_id, substs, movability)
934 // Look it up in the substitution list.
935 match self.map.get(&ty.into()).map(|k| k.unpack()) {
936 // Found it in the substitution list; replace with the parameter from the
938 Some(GenericArgKind::Type(t1)) => t1,
939 Some(u) => panic!("type mapped to unexpected kind: {:?}", u),
946 "type parameter `{}` is part of concrete type but not \
947 used in parameter list for the `impl Trait` type alias",
958 _ => ty.super_fold_with(self),
962 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
963 trace!("checking const {:?}", ct);
964 // Find a const parameter
966 ty::ConstKind::Param(..) => {
967 // Look it up in the substitution list.
968 match self.map.get(&ct.into()).map(|k| k.unpack()) {
969 // Found it in the substitution list, replace with the parameter from the
971 Some(GenericArgKind::Const(c1)) => c1,
972 Some(u) => panic!("const mapped to unexpected kind: {:?}", u),
979 "const parameter `{}` is part of concrete type but not \
980 used in parameter list for the `impl Trait` type alias",
986 self.tcx().consts.err
996 struct Instantiator<'a, 'tcx> {
997 infcx: &'a InferCtxt<'a, 'tcx>,
998 parent_def_id: DefId,
1000 param_env: ty::ParamEnv<'tcx>,
1002 opaque_types: OpaqueTypeMap<'tcx>,
1003 obligations: Vec<PredicateObligation<'tcx>>,
1006 impl<'a, 'tcx> Instantiator<'a, 'tcx> {
1007 fn instantiate_opaque_types_in_map<T: TypeFoldable<'tcx>>(&mut self, value: &T) -> T {
1008 debug!("instantiate_opaque_types_in_map(value={:?})", value);
1009 let tcx = self.infcx.tcx;
1010 value.fold_with(&mut BottomUpFolder {
1013 if ty.references_error() {
1014 return tcx.types.err;
1015 } else if let ty::Opaque(def_id, substs) = ty.kind {
1016 // Check that this is `impl Trait` type is
1017 // declared by `parent_def_id` -- i.e., one whose
1018 // value we are inferring. At present, this is
1019 // always true during the first phase of
1020 // type-check, but not always true later on during
1021 // NLL. Once we support named opaque types more fully,
1022 // this same scenario will be able to arise during all phases.
1024 // Here is an example using type alias `impl Trait`
1025 // that indicates the distinction we are checking for:
1029 // pub type Foo = impl Iterator;
1030 // pub fn make_foo() -> Foo { .. }
1034 // fn foo() -> a::Foo { a::make_foo() }
1038 // Here, the return type of `foo` references a
1039 // `Opaque` indeed, but not one whose value is
1040 // presently being inferred. You can get into a
1041 // similar situation with closure return types
1045 // fn foo() -> impl Iterator { .. }
1047 // let x = || foo(); // returns the Opaque assoc with `foo`
1050 if let Some(opaque_hir_id) = tcx.hir().as_local_hir_id(def_id) {
1051 let parent_def_id = self.parent_def_id;
1052 let def_scope_default = || {
1053 let opaque_parent_hir_id = tcx.hir().get_parent_item(opaque_hir_id);
1054 parent_def_id == tcx.hir().local_def_id(opaque_parent_hir_id)
1056 let (in_definition_scope, origin) = match tcx.hir().find(opaque_hir_id) {
1057 Some(Node::Item(item)) => match item.kind {
1058 // Anonymous `impl Trait`
1059 hir::ItemKind::OpaqueTy(hir::OpaqueTy {
1060 impl_trait_fn: Some(parent),
1063 }) => (parent == self.parent_def_id, origin),
1064 // Named `type Foo = impl Bar;`
1065 hir::ItemKind::OpaqueTy(hir::OpaqueTy {
1066 impl_trait_fn: None,
1070 may_define_opaque_type(tcx, self.parent_def_id, opaque_hir_id),
1073 _ => (def_scope_default(), hir::OpaqueTyOrigin::TypeAlias),
1075 Some(Node::ImplItem(item)) => match item.kind {
1076 hir::ImplItemKind::OpaqueTy(_) => (
1077 may_define_opaque_type(tcx, self.parent_def_id, opaque_hir_id),
1078 hir::OpaqueTyOrigin::TypeAlias,
1080 _ => (def_scope_default(), hir::OpaqueTyOrigin::TypeAlias),
1083 "expected (impl) item, found {}",
1084 tcx.hir().node_to_string(opaque_hir_id),
1087 if in_definition_scope {
1088 return self.fold_opaque_ty(ty, def_id, substs, origin);
1092 "instantiate_opaque_types_in_map: \
1093 encountered opaque outside its definition scope \
1111 substs: SubstsRef<'tcx>,
1112 origin: hir::OpaqueTyOrigin,
1114 let infcx = self.infcx;
1115 let tcx = infcx.tcx;
1117 debug!("instantiate_opaque_types: Opaque(def_id={:?}, substs={:?})", def_id, substs);
1119 // Use the same type variable if the exact same opaque type appears more
1120 // than once in the return type (e.g., if it's passed to a type alias).
1121 if let Some(opaque_defn) = self.opaque_types.get(&def_id) {
1122 debug!("instantiate_opaque_types: returning concrete ty {:?}", opaque_defn.concrete_ty);
1123 return opaque_defn.concrete_ty;
1125 let span = tcx.def_span(def_id);
1126 debug!("fold_opaque_ty {:?} {:?}", self.value_span, span);
1128 .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span });
1130 let predicates_of = tcx.predicates_of(def_id);
1131 debug!("instantiate_opaque_types: predicates={:#?}", predicates_of,);
1132 let bounds = predicates_of.instantiate(tcx, substs);
1134 let param_env = tcx.param_env(def_id);
1135 let InferOk { value: bounds, obligations } =
1136 infcx.partially_normalize_associated_types_in(span, self.body_id, param_env, &bounds);
1137 self.obligations.extend(obligations);
1139 debug!("instantiate_opaque_types: bounds={:?}", bounds);
1141 let required_region_bounds = required_region_bounds(tcx, ty, bounds.predicates.clone());
1142 debug!("instantiate_opaque_types: required_region_bounds={:?}", required_region_bounds);
1144 // Make sure that we are in fact defining the *entire* type
1145 // (e.g., `type Foo<T: Bound> = impl Bar;` needs to be
1146 // defined by a function like `fn foo<T: Bound>() -> Foo<T>`).
1147 debug!("instantiate_opaque_types: param_env={:#?}", self.param_env,);
1148 debug!("instantiate_opaque_types: generics={:#?}", tcx.generics_of(def_id),);
1150 // Ideally, we'd get the span where *this specific `ty` came
1151 // from*, but right now we just use the span from the overall
1152 // value being folded. In simple cases like `-> impl Foo`,
1153 // these are the same span, but not in cases like `-> (impl
1155 let definition_span = self.value_span;
1157 self.opaque_types.insert(
1163 concrete_ty: ty_var,
1164 has_required_region_bounds: !required_region_bounds.is_empty(),
1168 debug!("instantiate_opaque_types: ty_var={:?}", ty_var);
1170 for predicate in &bounds.predicates {
1171 if let ty::Predicate::Projection(projection) = &predicate {
1172 if projection.skip_binder().ty.references_error() {
1173 // No point on adding these obligations since there's a type error involved.
1179 self.obligations.reserve(bounds.predicates.len());
1180 for predicate in bounds.predicates {
1181 // Change the predicate to refer to the type variable,
1182 // which will be the concrete type instead of the opaque type.
1183 // This also instantiates nested instances of `impl Trait`.
1184 let predicate = self.instantiate_opaque_types_in_map(&predicate);
1186 let cause = traits::ObligationCause::new(span, self.body_id, traits::SizedReturnType);
1188 // Require that the predicate holds for the concrete type.
1189 debug!("instantiate_opaque_types: predicate={:?}", predicate);
1190 self.obligations.push(traits::Obligation::new(cause, self.param_env, predicate));
1197 /// Returns `true` if `opaque_hir_id` is a sibling or a child of a sibling of `def_id`.
1203 /// pub trait Bar { .. }
1205 /// pub type Baz = impl Bar;
1207 /// fn f1() -> Baz { .. }
1210 /// fn f2() -> bar::Baz { .. }
1214 /// Here, `def_id` is the `DefId` of the defining use of the opaque type (e.g., `f1` or `f2`),
1215 /// and `opaque_hir_id` is the `HirId` of the definition of the opaque type `Baz`.
1216 /// For the above example, this function returns `true` for `f1` and `false` for `f2`.
1217 pub fn may_define_opaque_type(tcx: TyCtxt<'_>, def_id: DefId, opaque_hir_id: hir::HirId) -> bool {
1218 let mut hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1220 // Named opaque types can be defined by any siblings or children of siblings.
1221 let scope = tcx.hir().get_defining_scope(opaque_hir_id);
1222 // We walk up the node tree until we hit the root or the scope of the opaque type.
1223 while hir_id != scope && hir_id != hir::CRATE_HIR_ID {
1224 hir_id = tcx.hir().get_parent_item(hir_id);
1226 // Syntactically, we are allowed to define the concrete type if:
1227 let res = hir_id == scope;
1229 "may_define_opaque_type(def={:?}, opaque_node={:?}) = {}",
1230 tcx.hir().find(hir_id),
1231 tcx.hir().get(opaque_hir_id),
1237 /// Given a set of predicates that apply to an object type, returns
1238 /// the region bounds that the (erased) `Self` type must
1239 /// outlive. Precisely *because* the `Self` type is erased, the
1240 /// parameter `erased_self_ty` must be supplied to indicate what type
1241 /// has been used to represent `Self` in the predicates
1242 /// themselves. This should really be a unique type; `FreshTy(0)` is a
1245 /// N.B., in some cases, particularly around higher-ranked bounds,
1246 /// this function returns a kind of conservative approximation.
1247 /// That is, all regions returned by this function are definitely
1248 /// required, but there may be other region bounds that are not
1249 /// returned, as well as requirements like `for<'a> T: 'a`.
1251 /// Requires that trait definitions have been processed so that we can
1252 /// elaborate predicates and walk supertraits.
1254 // FIXME: callers may only have a `&[Predicate]`, not a `Vec`, so that's
1255 // what this code should accept.
1256 crate fn required_region_bounds(
1258 erased_self_ty: Ty<'tcx>,
1259 predicates: Vec<ty::Predicate<'tcx>>,
1260 ) -> Vec<ty::Region<'tcx>> {
1262 "required_region_bounds(erased_self_ty={:?}, predicates={:?})",
1263 erased_self_ty, predicates
1266 assert!(!erased_self_ty.has_escaping_bound_vars());
1268 traits::elaborate_predicates(tcx, predicates)
1269 .filter_map(|predicate| {
1271 ty::Predicate::Projection(..)
1272 | ty::Predicate::Trait(..)
1273 | ty::Predicate::Subtype(..)
1274 | ty::Predicate::WellFormed(..)
1275 | ty::Predicate::ObjectSafe(..)
1276 | ty::Predicate::ClosureKind(..)
1277 | ty::Predicate::RegionOutlives(..)
1278 | ty::Predicate::ConstEvaluatable(..) => None,
1279 ty::Predicate::TypeOutlives(predicate) => {
1280 // Search for a bound of the form `erased_self_ty
1281 // : 'a`, but be wary of something like `for<'a>
1282 // erased_self_ty : 'a` (we interpret a
1283 // higher-ranked bound like that as 'static,
1284 // though at present the code in `fulfill.rs`
1285 // considers such bounds to be unsatisfiable, so
1286 // it's kind of a moot point since you could never
1287 // construct such an object, but this seems
1288 // correct even if that code changes).
1289 let ty::OutlivesPredicate(ref t, ref r) = predicate.skip_binder();
1290 if t == &erased_self_ty && !r.has_escaping_bound_vars() {