1 use crate::infer::InferCtxt;
4 use rustc_hir::def_id::DefId;
5 use rustc_hir::lang_items::LangItem;
6 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, SubstsRef};
7 use rustc_middle::ty::{self, ToPredicate, Ty, TyCtxt, TypeVisitable};
11 /// Returns the set of obligations needed to make `arg` well-formed.
12 /// If `arg` contains unresolved inference variables, this may include
13 /// further WF obligations. However, if `arg` IS an unresolved
14 /// inference variable, returns `None`, because we are not able to
15 /// make any progress at all. This is to prevent "livelock" where we
16 /// say "$0 is WF if $0 is WF".
17 pub fn obligations<'tcx>(
18 infcx: &InferCtxt<'tcx>,
19 param_env: ty::ParamEnv<'tcx>,
21 recursion_depth: usize,
22 arg: GenericArg<'tcx>,
24 ) -> Option<Vec<traits::PredicateObligation<'tcx>>> {
25 // Handle the "livelock" case (see comment above) by bailing out if necessary.
26 let arg = match arg.unpack() {
27 GenericArgKind::Type(ty) => {
29 ty::Infer(ty::TyVar(_)) => {
30 let resolved_ty = infcx.shallow_resolve(ty);
31 if resolved_ty == ty {
32 // No progress, bail out to prevent "livelock".
42 GenericArgKind::Const(ct) => {
44 ty::ConstKind::Infer(_) => {
45 let resolved = infcx.shallow_resolve(ct);
57 // There is nothing we have to do for lifetimes.
58 GenericArgKind::Lifetime(..) => return Some(Vec::new()),
61 let mut wf = WfPredicates {
71 debug!("wf::obligations({:?}, body_id={:?}) = {:?}", arg, body_id, wf.out);
73 let result = wf.normalize(infcx);
74 debug!("wf::obligations({:?}, body_id={:?}) ~~> {:?}", arg, body_id, result);
78 /// Returns the obligations that make this trait reference
79 /// well-formed. For example, if there is a trait `Set` defined like
80 /// `trait Set<K:Eq>`, then the trait reference `Foo: Set<Bar>` is WF
82 pub fn trait_obligations<'tcx>(
83 infcx: &InferCtxt<'tcx>,
84 param_env: ty::ParamEnv<'tcx>,
86 trait_pred: &ty::TraitPredicate<'tcx>,
88 item: &'tcx hir::Item<'tcx>,
89 ) -> Vec<traits::PredicateObligation<'tcx>> {
90 let mut wf = WfPredicates {
99 wf.compute_trait_pred(trait_pred, Elaborate::All);
100 debug!(obligations = ?wf.out);
104 #[instrument(skip(infcx), ret)]
105 pub fn predicate_obligations<'tcx>(
106 infcx: &InferCtxt<'tcx>,
107 param_env: ty::ParamEnv<'tcx>,
109 predicate: ty::Predicate<'tcx>,
111 ) -> Vec<traits::PredicateObligation<'tcx>> {
112 let mut wf = WfPredicates {
122 // It's ok to skip the binder here because wf code is prepared for it
123 match predicate.kind().skip_binder() {
124 ty::PredicateKind::Trait(t) => {
125 wf.compute_trait_pred(&t, Elaborate::None);
127 ty::PredicateKind::RegionOutlives(..) => {}
128 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
129 wf.compute(ty.into());
131 ty::PredicateKind::Projection(t) => {
132 wf.compute_projection(t.projection_ty);
133 wf.compute(match t.term.unpack() {
134 ty::TermKind::Ty(ty) => ty.into(),
135 ty::TermKind::Const(c) => c.into(),
138 ty::PredicateKind::WellFormed(arg) => {
141 ty::PredicateKind::ObjectSafe(_) => {}
142 ty::PredicateKind::ClosureKind(..) => {}
143 ty::PredicateKind::Subtype(ty::SubtypePredicate { a, b, a_is_expected: _ }) => {
144 wf.compute(a.into());
145 wf.compute(b.into());
147 ty::PredicateKind::Coerce(ty::CoercePredicate { a, b }) => {
148 wf.compute(a.into());
149 wf.compute(b.into());
151 ty::PredicateKind::ConstEvaluatable(ct) => {
152 wf.compute(ct.into());
154 ty::PredicateKind::ConstEquate(c1, c2) => {
155 wf.compute(c1.into());
156 wf.compute(c2.into());
158 ty::PredicateKind::TypeWellFormedFromEnv(..) => {
159 bug!("TypeWellFormedFromEnv is only used for Chalk")
166 struct WfPredicates<'tcx> {
168 param_env: ty::ParamEnv<'tcx>,
171 out: Vec<traits::PredicateObligation<'tcx>>,
172 recursion_depth: usize,
173 item: Option<&'tcx hir::Item<'tcx>>,
176 /// Controls whether we "elaborate" supertraits and so forth on the WF
177 /// predicates. This is a kind of hack to address #43784. The
178 /// underlying problem in that issue was a trait structure like:
180 /// ```ignore (illustrative)
181 /// trait Foo: Copy { }
182 /// trait Bar: Foo { }
183 /// impl<T: Bar> Foo for T { }
184 /// impl<T> Bar for T { }
187 /// Here, in the `Foo` impl, we will check that `T: Copy` holds -- but
188 /// we decide that this is true because `T: Bar` is in the
189 /// where-clauses (and we can elaborate that to include `T:
190 /// Copy`). This wouldn't be a problem, except that when we check the
191 /// `Bar` impl, we decide that `T: Foo` must hold because of the `Foo`
192 /// impl. And so nowhere did we check that `T: Copy` holds!
194 /// To resolve this, we elaborate the WF requirements that must be
195 /// proven when checking impls. This means that (e.g.) the `impl Bar
196 /// for T` will be forced to prove not only that `T: Foo` but also `T:
197 /// Copy` (which it won't be able to do, because there is no `Copy`
199 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
205 fn extend_cause_with_original_assoc_item_obligation<'tcx>(
207 trait_ref: &ty::TraitRef<'tcx>,
208 item: Option<&hir::Item<'tcx>>,
209 cause: &mut traits::ObligationCause<'tcx>,
210 pred: ty::Predicate<'tcx>,
213 "extended_cause_with_original_assoc_item_obligation {:?} {:?} {:?} {:?}",
214 trait_ref, item, cause, pred
216 let (items, impl_def_id) = match item {
217 Some(hir::Item { kind: hir::ItemKind::Impl(impl_), owner_id, .. }) => {
218 (impl_.items, *owner_id)
223 |impl_item_ref: &hir::ImplItemRef| match tcx.hir().impl_item(impl_item_ref.id).kind {
224 hir::ImplItemKind::Const(ty, _) | hir::ImplItemKind::Type(ty) => ty.span,
225 _ => impl_item_ref.span,
228 // It is fine to skip the binder as we don't care about regions here.
229 match pred.kind().skip_binder() {
230 ty::PredicateKind::Projection(proj) => {
231 // The obligation comes not from the current `impl` nor the `trait` being implemented,
232 // but rather from a "second order" obligation, where an associated type has a
233 // projection coming from another associated type. See
234 // `src/test/ui/associated-types/point-at-type-on-obligation-failure.rs` and
235 // `traits-assoc-type-in-supertrait-bad.rs`.
236 if let Some(ty::Projection(projection_ty)) = proj.term.ty().map(|ty| ty.kind())
237 && let Some(&impl_item_id) =
238 tcx.impl_item_implementor_ids(impl_def_id).get(&projection_ty.item_def_id)
239 && let Some(impl_item_span) = items
241 .find(|item| item.id.owner_id.to_def_id() == impl_item_id)
244 cause.span = impl_item_span;
247 ty::PredicateKind::Trait(pred) => {
248 // An associated item obligation born out of the `trait` failed to be met. An example
249 // can be seen in `ui/associated-types/point-at-type-on-obligation-failure-2.rs`.
250 debug!("extended_cause_with_original_assoc_item_obligation trait proj {:?}", pred);
251 if let ty::Projection(ty::ProjectionTy { item_def_id, .. }) = *pred.self_ty().kind()
252 && let Some(&impl_item_id) =
253 tcx.impl_item_implementor_ids(impl_def_id).get(&item_def_id)
254 && let Some(impl_item_span) = items
256 .find(|item| item.id.owner_id.to_def_id() == impl_item_id)
259 cause.span = impl_item_span;
266 impl<'tcx> WfPredicates<'tcx> {
267 fn tcx(&self) -> TyCtxt<'tcx> {
271 fn cause(&self, code: traits::ObligationCauseCode<'tcx>) -> traits::ObligationCause<'tcx> {
272 traits::ObligationCause::new(self.span, self.body_id, code)
275 fn normalize(self, infcx: &InferCtxt<'tcx>) -> Vec<traits::PredicateObligation<'tcx>> {
276 let cause = self.cause(traits::WellFormed(None));
277 let param_env = self.param_env;
278 let mut obligations = Vec::with_capacity(self.out.len());
279 for mut obligation in self.out {
280 assert!(!obligation.has_escaping_bound_vars());
281 let mut selcx = traits::SelectionContext::new(infcx);
282 // Don't normalize the whole obligation, the param env is either
283 // already normalized, or we're currently normalizing the
284 // param_env. Either way we should only normalize the predicate.
285 let normalized_predicate = traits::project::normalize_with_depth_to(
289 self.recursion_depth,
290 obligation.predicate,
293 obligation.predicate = normalized_predicate;
294 obligations.push(obligation);
299 /// Pushes the obligations required for `trait_ref` to be WF into `self.out`.
300 fn compute_trait_pred(&mut self, trait_pred: &ty::TraitPredicate<'tcx>, elaborate: Elaborate) {
302 let trait_ref = &trait_pred.trait_ref;
304 // if the trait predicate is not const, the wf obligations should not be const as well.
305 let obligations = if trait_pred.constness == ty::BoundConstness::NotConst {
306 self.nominal_obligations_without_const(trait_ref.def_id, trait_ref.substs)
308 self.nominal_obligations(trait_ref.def_id, trait_ref.substs)
311 debug!("compute_trait_pred obligations {:?}", obligations);
312 let param_env = self.param_env;
313 let depth = self.recursion_depth;
315 let item = self.item;
317 let extend = |traits::PredicateObligation { predicate, mut cause, .. }| {
318 if let Some(parent_trait_pred) = predicate.to_opt_poly_trait_pred() {
319 cause = cause.derived_cause(
321 traits::ObligationCauseCode::DerivedObligation,
324 extend_cause_with_original_assoc_item_obligation(
325 tcx, trait_ref, item, &mut cause, predicate,
327 traits::Obligation::with_depth(cause, depth, param_env, predicate)
330 if let Elaborate::All = elaborate {
331 let implied_obligations = traits::util::elaborate_obligations(tcx, obligations);
332 let implied_obligations = implied_obligations.map(extend);
333 self.out.extend(implied_obligations);
335 self.out.extend(obligations);
338 let tcx = self.tcx();
345 matches!(arg.unpack(), GenericArgKind::Type(..) | GenericArgKind::Const(..))
347 .filter(|(_, arg)| !arg.has_escaping_bound_vars())
349 let mut cause = traits::ObligationCause::misc(self.span, self.body_id);
350 // The first subst is the self ty - use the correct span for it.
352 if let Some(hir::ItemKind::Impl(hir::Impl { self_ty, .. })) =
353 item.map(|i| &i.kind)
355 cause.span = self_ty.span;
358 traits::Obligation::with_depth(
362 ty::Binder::dummy(ty::PredicateKind::WellFormed(arg)).to_predicate(tcx),
368 /// Pushes the obligations required for `trait_ref::Item` to be WF
370 fn compute_projection(&mut self, data: ty::ProjectionTy<'tcx>) {
371 // A projection is well-formed if
373 // (a) its predicates hold (*)
374 // (b) its substs are wf
376 // (*) The predicates of an associated type include the predicates of
377 // the trait that it's contained in. For example, given
379 // trait A<T>: Clone {
380 // type X where T: Copy;
383 // The predicates of `<() as A<i32>>::X` are:
392 // Projection types do not require const predicates.
393 let obligations = self.nominal_obligations_without_const(data.item_def_id, data.substs);
394 self.out.extend(obligations);
396 let tcx = self.tcx();
397 let cause = self.cause(traits::WellFormed(None));
398 let param_env = self.param_env;
399 let depth = self.recursion_depth;
405 matches!(arg.unpack(), GenericArgKind::Type(..) | GenericArgKind::Const(..))
407 .filter(|arg| !arg.has_escaping_bound_vars())
409 traits::Obligation::with_depth(
413 ty::Binder::dummy(ty::PredicateKind::WellFormed(arg)).to_predicate(tcx),
419 fn require_sized(&mut self, subty: Ty<'tcx>, cause: traits::ObligationCauseCode<'tcx>) {
420 if !subty.has_escaping_bound_vars() {
421 let cause = self.cause(cause);
422 let trait_ref = ty::TraitRef {
423 def_id: self.tcx.require_lang_item(LangItem::Sized, None),
424 substs: self.tcx.mk_substs_trait(subty, &[]),
426 self.out.push(traits::Obligation::with_depth(
428 self.recursion_depth,
430 ty::Binder::dummy(trait_ref).without_const().to_predicate(self.tcx),
435 /// Pushes all the predicates needed to validate that `ty` is WF into `out`.
436 #[instrument(level = "debug", skip(self))]
437 fn compute(&mut self, arg: GenericArg<'tcx>) {
438 let mut walker = arg.walk();
439 let param_env = self.param_env;
440 let depth = self.recursion_depth;
441 while let Some(arg) = walker.next() {
442 debug!(?arg, ?self.out);
443 let ty = match arg.unpack() {
444 GenericArgKind::Type(ty) => ty,
446 // No WF constraints for lifetimes being present, any outlives
447 // obligations are handled by the parent (e.g. `ty::Ref`).
448 GenericArgKind::Lifetime(_) => continue,
450 GenericArgKind::Const(ct) => {
452 ty::ConstKind::Unevaluated(uv) => {
453 let obligations = self.nominal_obligations(uv.def.did, uv.substs);
454 self.out.extend(obligations);
457 ty::Binder::dummy(ty::PredicateKind::ConstEvaluatable(ct))
458 .to_predicate(self.tcx());
459 let cause = self.cause(traits::WellFormed(None));
460 self.out.push(traits::Obligation::with_depth(
462 self.recursion_depth,
467 ty::ConstKind::Infer(_) => {
468 let cause = self.cause(traits::WellFormed(None));
470 self.out.push(traits::Obligation::with_depth(
472 self.recursion_depth,
474 ty::Binder::dummy(ty::PredicateKind::WellFormed(ct.into()))
475 .to_predicate(self.tcx()),
478 ty::ConstKind::Error(_)
479 | ty::ConstKind::Param(_)
480 | ty::ConstKind::Bound(..)
481 | ty::ConstKind::Placeholder(..) => {
482 // These variants are trivially WF, so nothing to do here.
484 ty::ConstKind::Value(..) => {
485 // FIXME: Enforce that values are structurally-matchable.
492 debug!("wf bounds for ty={:?} ty.kind={:#?}", ty, ty.kind());
502 | ty::GeneratorWitness(..)
506 | ty::Placeholder(..)
507 | ty::Foreign(..) => {
508 // WfScalar, WfParameter, etc
511 // Can only infer to `ty::Int(_) | ty::Uint(_)`.
512 ty::Infer(ty::IntVar(_)) => {}
514 // Can only infer to `ty::Float(_)`.
515 ty::Infer(ty::FloatVar(_)) => {}
517 ty::Slice(subty) => {
518 self.require_sized(subty, traits::SliceOrArrayElem);
521 ty::Array(subty, _) => {
522 self.require_sized(subty, traits::SliceOrArrayElem);
523 // Note that we handle the len is implicitly checked while walking `arg`.
526 ty::Tuple(ref tys) => {
527 if let Some((_last, rest)) = tys.split_last() {
529 self.require_sized(elem, traits::TupleElem);
535 // Simple cases that are WF if their type args are WF.
538 ty::Projection(data) => {
539 walker.skip_current_subtree(); // Subtree handled by compute_projection.
540 self.compute_projection(data);
543 ty::Adt(def, substs) => {
545 let obligations = self.nominal_obligations(def.did(), substs);
546 self.out.extend(obligations);
549 ty::FnDef(did, substs) => {
550 let obligations = self.nominal_obligations_without_const(did, substs);
551 self.out.extend(obligations);
554 ty::Ref(r, rty, _) => {
556 if !r.has_escaping_bound_vars() && !rty.has_escaping_bound_vars() {
557 let cause = self.cause(traits::ReferenceOutlivesReferent(ty));
558 self.out.push(traits::Obligation::with_depth(
562 ty::Binder::dummy(ty::PredicateKind::TypeOutlives(
563 ty::OutlivesPredicate(rty, r),
565 .to_predicate(self.tcx()),
570 ty::Generator(did, substs, ..) => {
571 // Walk ALL the types in the generator: this will
572 // include the upvar types as well as the yield
573 // type. Note that this is mildly distinct from
574 // the closure case, where we have to be careful
575 // about the signature of the closure. We don't
576 // have the problem of implied bounds here since
577 // generators don't take arguments.
578 let obligations = self.nominal_obligations(did, substs);
579 self.out.extend(obligations);
582 ty::Closure(did, substs) => {
583 // Only check the upvar types for WF, not the rest
584 // of the types within. This is needed because we
585 // capture the signature and it may not be WF
586 // without the implied bounds. Consider a closure
587 // like `|x: &'a T|` -- it may be that `T: 'a` is
588 // not known to hold in the creator's context (and
589 // indeed the closure may not be invoked by its
590 // creator, but rather turned to someone who *can*
593 // The special treatment of closures here really
594 // ought not to be necessary either; the problem
595 // is related to #25860 -- there is no way for us
596 // to express a fn type complete with the implied
597 // bounds that it is assuming. I think in reality
598 // the WF rules around fn are a bit messed up, and
599 // that is the rot problem: `fn(&'a T)` should
600 // probably always be WF, because it should be
601 // shorthand for something like `where(T: 'a) {
602 // fn(&'a T) }`, as discussed in #25860.
603 walker.skip_current_subtree(); // subtree handled below
604 // FIXME(eddyb) add the type to `walker` instead of recursing.
605 self.compute(substs.as_closure().tupled_upvars_ty().into());
606 // Note that we cannot skip the generic types
607 // types. Normally, within the fn
608 // body where they are created, the generics will
609 // always be WF, and outside of that fn body we
610 // are not directly inspecting closure types
611 // anyway, except via auto trait matching (which
612 // only inspects the upvar types).
613 // But when a closure is part of a type-alias-impl-trait
614 // then the function that created the defining site may
615 // have had more bounds available than the type alias
616 // specifies. This may cause us to have a closure in the
617 // hidden type that is not actually well formed and
618 // can cause compiler crashes when the user abuses unsafe
619 // code to procure such a closure.
620 // See src/test/ui/type-alias-impl-trait/wf_check_closures.rs
621 let obligations = self.nominal_obligations(did, substs);
622 self.out.extend(obligations);
626 // let the loop iterate into the argument/return
627 // types appearing in the fn signature
630 ty::Opaque(did, substs) => {
631 // All of the requirements on type parameters
632 // have already been checked for `impl Trait` in
633 // return position. We do need to check type-alias-impl-trait though.
634 if ty::is_impl_trait_defn(self.tcx, did).is_none() {
635 let obligations = self.nominal_obligations(did, substs);
636 self.out.extend(obligations);
640 ty::Dynamic(data, r, _) => {
643 // Here, we defer WF checking due to higher-ranked
644 // regions. This is perhaps not ideal.
645 self.from_object_ty(ty, data, r);
647 // FIXME(#27579) RFC also considers adding trait
648 // obligations that don't refer to Self and
651 let defer_to_coercion = self.tcx().features().object_safe_for_dispatch;
653 if !defer_to_coercion {
654 let cause = self.cause(traits::WellFormed(None));
655 let component_traits = data.auto_traits().chain(data.principal_def_id());
656 let tcx = self.tcx();
657 self.out.extend(component_traits.map(|did| {
658 traits::Obligation::with_depth(
662 ty::Binder::dummy(ty::PredicateKind::ObjectSafe(did))
669 // Inference variables are the complicated case, since we don't
670 // know what type they are. We do two things:
672 // 1. Check if they have been resolved, and if so proceed with
674 // 2. If not, we've at least simplified things (e.g., we went
675 // from `Vec<$0>: WF` to `$0: WF`), so we can
676 // register a pending obligation and keep
677 // moving. (Goal is that an "inductive hypothesis"
678 // is satisfied to ensure termination.)
679 // See also the comment on `fn obligations`, describing "livelock"
680 // prevention, which happens before this can be reached.
682 let cause = self.cause(traits::WellFormed(None));
683 self.out.push(traits::Obligation::with_depth(
685 self.recursion_depth,
687 ty::Binder::dummy(ty::PredicateKind::WellFormed(ty.into()))
688 .to_predicate(self.tcx()),
697 #[instrument(level = "debug", skip(self))]
698 fn nominal_obligations_inner(
701 substs: SubstsRef<'tcx>,
702 remap_constness: bool,
703 ) -> Vec<traits::PredicateObligation<'tcx>> {
704 let predicates = self.tcx.predicates_of(def_id);
705 let mut origins = vec![def_id; predicates.predicates.len()];
706 let mut head = predicates;
707 while let Some(parent) = head.parent {
708 head = self.tcx.predicates_of(parent);
709 origins.extend(iter::repeat(parent).take(head.predicates.len()));
712 let predicates = predicates.instantiate(self.tcx, substs);
713 trace!("{:#?}", predicates);
714 debug_assert_eq!(predicates.predicates.len(), origins.len());
716 iter::zip(iter::zip(predicates.predicates, predicates.spans), origins.into_iter().rev())
717 .map(|((mut pred, span), origin_def_id)| {
718 let code = if span.is_dummy() {
719 traits::ItemObligation(origin_def_id)
721 traits::BindingObligation(origin_def_id, span)
723 let cause = self.cause(code);
725 pred = pred.without_const(self.tcx);
727 traits::Obligation::with_depth(cause, self.recursion_depth, self.param_env, pred)
729 .filter(|pred| !pred.has_escaping_bound_vars())
733 fn nominal_obligations(
736 substs: SubstsRef<'tcx>,
737 ) -> Vec<traits::PredicateObligation<'tcx>> {
738 self.nominal_obligations_inner(def_id, substs, false)
741 fn nominal_obligations_without_const(
744 substs: SubstsRef<'tcx>,
745 ) -> Vec<traits::PredicateObligation<'tcx>> {
746 self.nominal_obligations_inner(def_id, substs, true)
752 data: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
753 region: ty::Region<'tcx>,
755 // Imagine a type like this:
758 // trait Bar<'c> : 'c { }
760 // &'b (Foo+'c+Bar<'d>)
763 // In this case, the following relationships must hold:
768 // The first conditions is due to the normal region pointer
769 // rules, which say that a reference cannot outlive its
772 // The final condition may be a bit surprising. In particular,
773 // you may expect that it would have been `'c <= 'd`, since
774 // usually lifetimes of outer things are conservative
775 // approximations for inner things. However, it works somewhat
776 // differently with trait objects: here the idea is that if the
777 // user specifies a region bound (`'c`, in this case) it is the
778 // "master bound" that *implies* that bounds from other traits are
779 // all met. (Remember that *all bounds* in a type like
780 // `Foo+Bar+Zed` must be met, not just one, hence if we write
781 // `Foo<'x>+Bar<'y>`, we know that the type outlives *both* 'x and
784 // Note: in fact we only permit builtin traits, not `Bar<'d>`, I
785 // am looking forward to the future here.
786 if !data.has_escaping_bound_vars() && !region.has_escaping_bound_vars() {
787 let implicit_bounds = object_region_bounds(self.tcx, data);
789 let explicit_bound = region;
791 self.out.reserve(implicit_bounds.len());
792 for implicit_bound in implicit_bounds {
793 let cause = self.cause(traits::ObjectTypeBound(ty, explicit_bound));
795 ty::Binder::dummy(ty::OutlivesPredicate(explicit_bound, implicit_bound));
796 self.out.push(traits::Obligation::with_depth(
798 self.recursion_depth,
800 outlives.to_predicate(self.tcx),
807 /// Given an object type like `SomeTrait + Send`, computes the lifetime
808 /// bounds that must hold on the elided self type. These are derived
809 /// from the declarations of `SomeTrait`, `Send`, and friends -- if
810 /// they declare `trait SomeTrait : 'static`, for example, then
811 /// `'static` would appear in the list. The hard work is done by
812 /// `infer::required_region_bounds`, see that for more information.
813 pub fn object_region_bounds<'tcx>(
815 existential_predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
816 ) -> Vec<ty::Region<'tcx>> {
817 // Since we don't actually *know* the self type for an object,
818 // this "open(err)" serves as a kind of dummy standin -- basically
819 // a placeholder type.
820 let open_ty = tcx.mk_ty_infer(ty::FreshTy(0));
822 let predicates = existential_predicates.iter().filter_map(|predicate| {
823 if let ty::ExistentialPredicate::Projection(_) = predicate.skip_binder() {
826 Some(predicate.with_self_ty(tcx, open_ty))
830 required_region_bounds(tcx, open_ty, predicates)
833 /// Given a set of predicates that apply to an object type, returns
834 /// the region bounds that the (erased) `Self` type must
835 /// outlive. Precisely *because* the `Self` type is erased, the
836 /// parameter `erased_self_ty` must be supplied to indicate what type
837 /// has been used to represent `Self` in the predicates
838 /// themselves. This should really be a unique type; `FreshTy(0)` is a
841 /// N.B., in some cases, particularly around higher-ranked bounds,
842 /// this function returns a kind of conservative approximation.
843 /// That is, all regions returned by this function are definitely
844 /// required, but there may be other region bounds that are not
845 /// returned, as well as requirements like `for<'a> T: 'a`.
847 /// Requires that trait definitions have been processed so that we can
848 /// elaborate predicates and walk supertraits.
849 #[instrument(skip(tcx, predicates), level = "debug", ret)]
850 pub(crate) fn required_region_bounds<'tcx>(
852 erased_self_ty: Ty<'tcx>,
853 predicates: impl Iterator<Item = ty::Predicate<'tcx>>,
854 ) -> Vec<ty::Region<'tcx>> {
855 assert!(!erased_self_ty.has_escaping_bound_vars());
857 traits::elaborate_predicates(tcx, predicates)
858 .filter_map(|obligation| {
860 match obligation.predicate.kind().skip_binder() {
861 ty::PredicateKind::Projection(..)
862 | ty::PredicateKind::Trait(..)
863 | ty::PredicateKind::Subtype(..)
864 | ty::PredicateKind::Coerce(..)
865 | ty::PredicateKind::WellFormed(..)
866 | ty::PredicateKind::ObjectSafe(..)
867 | ty::PredicateKind::ClosureKind(..)
868 | ty::PredicateKind::RegionOutlives(..)
869 | ty::PredicateKind::ConstEvaluatable(..)
870 | ty::PredicateKind::ConstEquate(..)
871 | ty::PredicateKind::TypeWellFormedFromEnv(..) => None,
872 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ref t, ref r)) => {
873 // Search for a bound of the form `erased_self_ty
874 // : 'a`, but be wary of something like `for<'a>
875 // erased_self_ty : 'a` (we interpret a
876 // higher-ranked bound like that as 'static,
877 // though at present the code in `fulfill.rs`
878 // considers such bounds to be unsatisfiable, so
879 // it's kind of a moot point since you could never
880 // construct such an object, but this seems
881 // correct even if that code changes).
882 if t == &erased_self_ty && !r.has_escaping_bound_vars() {