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<'a, 'tcx>(
18 infcx: &InferCtxt<'a, '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(infer) => {
45 let resolved = infcx.shallow_resolve(infer);
46 if resolved == infer {
53 .mk_const(ty::ConstS { kind: ty::ConstKind::Infer(resolved), ty: ct.ty() })
59 // There is nothing we have to do for lifetimes.
60 GenericArgKind::Lifetime(..) => return Some(Vec::new()),
63 let mut wf = WfPredicates {
73 debug!("wf::obligations({:?}, body_id={:?}) = {:?}", arg, body_id, wf.out);
75 let result = wf.normalize(infcx);
76 debug!("wf::obligations({:?}, body_id={:?}) ~~> {:?}", arg, body_id, result);
80 /// Returns the obligations that make this trait reference
81 /// well-formed. For example, if there is a trait `Set` defined like
82 /// `trait Set<K:Eq>`, then the trait reference `Foo: Set<Bar>` is WF
84 pub fn trait_obligations<'a, 'tcx>(
85 infcx: &InferCtxt<'a, 'tcx>,
86 param_env: ty::ParamEnv<'tcx>,
88 trait_pred: &ty::TraitPredicate<'tcx>,
90 item: &'tcx hir::Item<'tcx>,
91 ) -> Vec<traits::PredicateObligation<'tcx>> {
92 let mut wf = WfPredicates {
101 wf.compute_trait_pred(trait_pred, Elaborate::All);
102 debug!(obligations = ?wf.out);
106 pub fn predicate_obligations<'a, 'tcx>(
107 infcx: &InferCtxt<'a, 'tcx>,
108 param_env: ty::ParamEnv<'tcx>,
110 predicate: ty::Predicate<'tcx>,
112 ) -> Vec<traits::PredicateObligation<'tcx>> {
113 let mut wf = WfPredicates {
123 // It's ok to skip the binder here because wf code is prepared for it
124 match predicate.kind().skip_binder() {
125 ty::PredicateKind::Trait(t) => {
126 wf.compute_trait_pred(&t, Elaborate::None);
128 ty::PredicateKind::RegionOutlives(..) => {}
129 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
130 wf.compute(ty.into());
132 ty::PredicateKind::Projection(t) => {
133 wf.compute_projection(t.projection_ty);
134 wf.compute(match t.term {
135 ty::Term::Ty(ty) => ty.into(),
136 ty::Term::Const(c) => c.into(),
139 ty::PredicateKind::WellFormed(arg) => {
142 ty::PredicateKind::ObjectSafe(_) => {}
143 ty::PredicateKind::ClosureKind(..) => {}
144 ty::PredicateKind::Subtype(ty::SubtypePredicate { a, b, a_is_expected: _ }) => {
145 wf.compute(a.into());
146 wf.compute(b.into());
148 ty::PredicateKind::Coerce(ty::CoercePredicate { a, b }) => {
149 wf.compute(a.into());
150 wf.compute(b.into());
152 ty::PredicateKind::ConstEvaluatable(uv) => {
153 let obligations = wf.nominal_obligations(uv.def.did, uv.substs);
154 wf.out.extend(obligations);
156 for arg in uv.substs.iter() {
160 ty::PredicateKind::ConstEquate(c1, c2) => {
161 wf.compute(c1.into());
162 wf.compute(c2.into());
164 ty::PredicateKind::TypeWellFormedFromEnv(..) => {
165 bug!("TypeWellFormedFromEnv is only used for Chalk")
172 struct WfPredicates<'tcx> {
174 param_env: ty::ParamEnv<'tcx>,
177 out: Vec<traits::PredicateObligation<'tcx>>,
178 recursion_depth: usize,
179 item: Option<&'tcx hir::Item<'tcx>>,
182 /// Controls whether we "elaborate" supertraits and so forth on the WF
183 /// predicates. This is a kind of hack to address #43784. The
184 /// underlying problem in that issue was a trait structure like:
186 /// ```ignore (illustrative)
187 /// trait Foo: Copy { }
188 /// trait Bar: Foo { }
189 /// impl<T: Bar> Foo for T { }
190 /// impl<T> Bar for T { }
193 /// Here, in the `Foo` impl, we will check that `T: Copy` holds -- but
194 /// we decide that this is true because `T: Bar` is in the
195 /// where-clauses (and we can elaborate that to include `T:
196 /// Copy`). This wouldn't be a problem, except that when we check the
197 /// `Bar` impl, we decide that `T: Foo` must hold because of the `Foo`
198 /// impl. And so nowhere did we check that `T: Copy` holds!
200 /// To resolve this, we elaborate the WF requirements that must be
201 /// proven when checking impls. This means that (e.g.) the `impl Bar
202 /// for T` will be forced to prove not only that `T: Foo` but also `T:
203 /// Copy` (which it won't be able to do, because there is no `Copy`
205 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
211 fn extend_cause_with_original_assoc_item_obligation<'tcx>(
213 trait_ref: &ty::TraitRef<'tcx>,
214 item: Option<&hir::Item<'tcx>>,
215 cause: &mut traits::ObligationCause<'tcx>,
216 pred: ty::Predicate<'tcx>,
219 "extended_cause_with_original_assoc_item_obligation {:?} {:?} {:?} {:?}",
220 trait_ref, item, cause, pred
222 let (items, impl_def_id) = match item {
223 Some(hir::Item { kind: hir::ItemKind::Impl(impl_), def_id, .. }) => (impl_.items, *def_id),
227 |impl_item_ref: &hir::ImplItemRef| match tcx.hir().impl_item(impl_item_ref.id).kind {
228 hir::ImplItemKind::Const(ty, _) | hir::ImplItemKind::TyAlias(ty) => ty.span,
229 _ => impl_item_ref.span,
232 // It is fine to skip the binder as we don't care about regions here.
233 match pred.kind().skip_binder() {
234 ty::PredicateKind::Projection(proj) => {
235 // The obligation comes not from the current `impl` nor the `trait` being implemented,
236 // but rather from a "second order" obligation, where an associated type has a
237 // projection coming from another associated type. See
238 // `src/test/ui/associated-types/point-at-type-on-obligation-failure.rs` and
239 // `traits-assoc-type-in-supertrait-bad.rs`.
240 if let Some(ty::Projection(projection_ty)) = proj.term.ty().map(|ty| ty.kind())
241 && let Some(&impl_item_id) =
242 tcx.impl_item_implementor_ids(impl_def_id).get(&projection_ty.item_def_id)
243 && let Some(impl_item_span) = items
245 .find(|item| item.id.def_id.to_def_id() == impl_item_id)
248 cause.span = impl_item_span;
251 ty::PredicateKind::Trait(pred) => {
252 // An associated item obligation born out of the `trait` failed to be met. An example
253 // can be seen in `ui/associated-types/point-at-type-on-obligation-failure-2.rs`.
254 debug!("extended_cause_with_original_assoc_item_obligation trait proj {:?}", pred);
255 if let ty::Projection(ty::ProjectionTy { item_def_id, .. }) = *pred.self_ty().kind()
256 && let Some(&impl_item_id) =
257 tcx.impl_item_implementor_ids(impl_def_id).get(&item_def_id)
258 && let Some(impl_item_span) = items
260 .find(|item| item.id.def_id.to_def_id() == impl_item_id)
263 cause.span = impl_item_span;
270 impl<'tcx> WfPredicates<'tcx> {
271 fn tcx(&self) -> TyCtxt<'tcx> {
275 fn cause(&self, code: traits::ObligationCauseCode<'tcx>) -> traits::ObligationCause<'tcx> {
276 traits::ObligationCause::new(self.span, self.body_id, code)
279 fn normalize(self, infcx: &InferCtxt<'_, 'tcx>) -> Vec<traits::PredicateObligation<'tcx>> {
280 let cause = self.cause(traits::WellFormed(None));
281 let param_env = self.param_env;
282 let mut obligations = Vec::with_capacity(self.out.len());
283 for mut obligation in self.out {
284 assert!(!obligation.has_escaping_bound_vars());
285 let mut selcx = traits::SelectionContext::new(infcx);
286 // Don't normalize the whole obligation, the param env is either
287 // already normalized, or we're currently normalizing the
288 // param_env. Either way we should only normalize the predicate.
289 let normalized_predicate = traits::project::normalize_with_depth_to(
293 self.recursion_depth,
294 obligation.predicate,
297 obligation.predicate = normalized_predicate;
298 obligations.push(obligation);
303 /// Pushes the obligations required for `trait_ref` to be WF into `self.out`.
304 fn compute_trait_pred(&mut self, trait_pred: &ty::TraitPredicate<'tcx>, elaborate: Elaborate) {
306 let trait_ref = &trait_pred.trait_ref;
308 // if the trait predicate is not const, the wf obligations should not be const as well.
309 let obligations = if trait_pred.constness == ty::BoundConstness::NotConst {
310 self.nominal_obligations_without_const(trait_ref.def_id, trait_ref.substs)
312 self.nominal_obligations(trait_ref.def_id, trait_ref.substs)
315 debug!("compute_trait_pred obligations {:?}", obligations);
316 let param_env = self.param_env;
317 let depth = self.recursion_depth;
319 let item = self.item;
321 let extend = |traits::PredicateObligation { predicate, mut cause, .. }| {
322 if let Some(parent_trait_pred) = predicate.to_opt_poly_trait_pred() {
323 cause = cause.derived_cause(
325 traits::ObligationCauseCode::DerivedObligation,
328 extend_cause_with_original_assoc_item_obligation(
329 tcx, trait_ref, item, &mut cause, predicate,
331 traits::Obligation::with_depth(cause, depth, param_env, predicate)
334 if let Elaborate::All = elaborate {
335 let implied_obligations = traits::util::elaborate_obligations(tcx, obligations);
336 let implied_obligations = implied_obligations.map(extend);
337 self.out.extend(implied_obligations);
339 self.out.extend(obligations);
342 let tcx = self.tcx();
349 matches!(arg.unpack(), GenericArgKind::Type(..) | GenericArgKind::Const(..))
351 .filter(|(_, arg)| !arg.has_escaping_bound_vars())
353 let mut cause = traits::ObligationCause::misc(self.span, self.body_id);
354 // The first subst is the self ty - use the correct span for it.
356 if let Some(hir::ItemKind::Impl(hir::Impl { self_ty, .. })) =
357 item.map(|i| &i.kind)
359 cause.span = self_ty.span;
362 traits::Obligation::with_depth(
366 ty::Binder::dummy(ty::PredicateKind::WellFormed(arg)).to_predicate(tcx),
372 /// Pushes the obligations required for `trait_ref::Item` to be WF
374 fn compute_projection(&mut self, data: ty::ProjectionTy<'tcx>) {
375 // A projection is well-formed if
377 // (a) its predicates hold (*)
378 // (b) its substs are wf
380 // (*) The predicates of an associated type include the predicates of
381 // the trait that it's contained in. For example, given
383 // trait A<T>: Clone {
384 // type X where T: Copy;
387 // The predicates of `<() as A<i32>>::X` are:
396 let obligations = self.nominal_obligations(data.item_def_id, data.substs);
397 self.out.extend(obligations);
399 let tcx = self.tcx();
400 let cause = self.cause(traits::WellFormed(None));
401 let param_env = self.param_env;
402 let depth = self.recursion_depth;
408 matches!(arg.unpack(), GenericArgKind::Type(..) | GenericArgKind::Const(..))
410 .filter(|arg| !arg.has_escaping_bound_vars())
412 traits::Obligation::with_depth(
416 ty::Binder::dummy(ty::PredicateKind::WellFormed(arg)).to_predicate(tcx),
422 fn require_sized(&mut self, subty: Ty<'tcx>, cause: traits::ObligationCauseCode<'tcx>) {
423 if !subty.has_escaping_bound_vars() {
424 let cause = self.cause(cause);
425 let trait_ref = ty::TraitRef {
426 def_id: self.tcx.require_lang_item(LangItem::Sized, None),
427 substs: self.tcx.mk_substs_trait(subty, &[]),
429 self.out.push(traits::Obligation::with_depth(
431 self.recursion_depth,
433 ty::Binder::dummy(trait_ref).without_const().to_predicate(self.tcx),
438 /// Pushes all the predicates needed to validate that `ty` is WF into `out`.
439 fn compute(&mut self, arg: GenericArg<'tcx>) {
440 let mut walker = arg.walk();
441 let param_env = self.param_env;
442 let depth = self.recursion_depth;
443 while let Some(arg) = walker.next() {
444 let ty = match arg.unpack() {
445 GenericArgKind::Type(ty) => ty,
447 // No WF constraints for lifetimes being present, any outlives
448 // obligations are handled by the parent (e.g. `ty::Ref`).
449 GenericArgKind::Lifetime(_) => continue,
451 GenericArgKind::Const(constant) => {
452 match constant.kind() {
453 ty::ConstKind::Unevaluated(uv) => {
454 let obligations = self.nominal_obligations(uv.def.did, uv.substs);
455 self.out.extend(obligations);
458 ty::Binder::dummy(ty::PredicateKind::ConstEvaluatable(uv.shrink()))
459 .to_predicate(self.tcx());
460 let cause = self.cause(traits::WellFormed(None));
461 self.out.push(traits::Obligation::with_depth(
463 self.recursion_depth,
468 ty::ConstKind::Infer(_) => {
469 let cause = self.cause(traits::WellFormed(None));
471 self.out.push(traits::Obligation::with_depth(
473 self.recursion_depth,
475 ty::Binder::dummy(ty::PredicateKind::WellFormed(constant.into()))
476 .to_predicate(self.tcx()),
479 ty::ConstKind::Error(_)
480 | ty::ConstKind::Param(_)
481 | ty::ConstKind::Bound(..)
482 | ty::ConstKind::Placeholder(..) => {
483 // These variants are trivially WF, so nothing to do here.
485 ty::ConstKind::Value(..) => {
486 // FIXME: Enforce that values are structurally-matchable.
501 | ty::GeneratorWitness(..)
505 | ty::Placeholder(..)
506 | ty::Foreign(..) => {
507 // WfScalar, WfParameter, etc
510 // Can only infer to `ty::Int(_) | ty::Uint(_)`.
511 ty::Infer(ty::IntVar(_)) => {}
513 // Can only infer to `ty::Float(_)`.
514 ty::Infer(ty::FloatVar(_)) => {}
516 ty::Slice(subty) => {
517 self.require_sized(subty, traits::SliceOrArrayElem);
520 ty::Array(subty, _) => {
521 self.require_sized(subty, traits::SliceOrArrayElem);
522 // Note that we handle the len is implicitly checked while walking `arg`.
525 ty::Tuple(ref tys) => {
526 if let Some((_last, rest)) = tys.split_last() {
528 self.require_sized(elem, traits::TupleElem);
534 // Simple cases that are WF if their type args are WF.
537 ty::Projection(data) => {
538 walker.skip_current_subtree(); // Subtree handled by compute_projection.
539 self.compute_projection(data);
542 ty::Adt(def, substs) => {
544 let obligations = self.nominal_obligations(def.did(), substs);
545 self.out.extend(obligations);
548 ty::FnDef(did, substs) => {
549 let obligations = self.nominal_obligations(did, substs);
550 self.out.extend(obligations);
553 ty::Ref(r, rty, _) => {
555 if !r.has_escaping_bound_vars() && !rty.has_escaping_bound_vars() {
556 let cause = self.cause(traits::ReferenceOutlivesReferent(ty));
557 self.out.push(traits::Obligation::with_depth(
561 ty::Binder::dummy(ty::PredicateKind::TypeOutlives(
562 ty::OutlivesPredicate(rty, r),
564 .to_predicate(self.tcx()),
569 ty::Generator(did, substs, ..) => {
570 // Walk ALL the types in the generator: this will
571 // include the upvar types as well as the yield
572 // type. Note that this is mildly distinct from
573 // the closure case, where we have to be careful
574 // about the signature of the closure. We don't
575 // have the problem of implied bounds here since
576 // generators don't take arguments.
577 let obligations = self.nominal_obligations(did, substs);
578 self.out.extend(obligations);
581 ty::Closure(did, substs) => {
582 // Only check the upvar types for WF, not the rest
583 // of the types within. This is needed because we
584 // capture the signature and it may not be WF
585 // without the implied bounds. Consider a closure
586 // like `|x: &'a T|` -- it may be that `T: 'a` is
587 // not known to hold in the creator's context (and
588 // indeed the closure may not be invoked by its
589 // creator, but rather turned to someone who *can*
592 // The special treatment of closures here really
593 // ought not to be necessary either; the problem
594 // is related to #25860 -- there is no way for us
595 // to express a fn type complete with the implied
596 // bounds that it is assuming. I think in reality
597 // the WF rules around fn are a bit messed up, and
598 // that is the rot problem: `fn(&'a T)` should
599 // probably always be WF, because it should be
600 // shorthand for something like `where(T: 'a) {
601 // fn(&'a T) }`, as discussed in #25860.
602 walker.skip_current_subtree(); // subtree handled below
603 // FIXME(eddyb) add the type to `walker` instead of recursing.
604 self.compute(substs.as_closure().tupled_upvars_ty().into());
605 // Note that we cannot skip the generic types
606 // types. Normally, within the fn
607 // body where they are created, the generics will
608 // always be WF, and outside of that fn body we
609 // are not directly inspecting closure types
610 // anyway, except via auto trait matching (which
611 // only inspects the upvar types).
612 // But when a closure is part of a type-alias-impl-trait
613 // then the function that created the defining site may
614 // have had more bounds available than the type alias
615 // specifies. This may cause us to have a closure in the
616 // hidden type that is not actually well formed and
617 // can cause compiler crashes when the user abuses unsafe
618 // code to procure such a closure.
619 // See src/test/ui/type-alias-impl-trait/wf_check_closures.rs
620 let obligations = self.nominal_obligations(did, substs);
621 self.out.extend(obligations);
625 // let the loop iterate into the argument/return
626 // types appearing in the fn signature
629 ty::Opaque(did, substs) => {
630 // All of the requirements on type parameters
631 // have already been checked for `impl Trait` in
632 // return position. We do need to check type-alias-impl-trait though.
633 if ty::is_impl_trait_defn(self.tcx, did).is_none() {
634 let obligations = self.nominal_obligations(did, substs);
635 self.out.extend(obligations);
639 ty::Dynamic(data, r) => {
642 // Here, we defer WF checking due to higher-ranked
643 // regions. This is perhaps not ideal.
644 self.from_object_ty(ty, data, r);
646 // FIXME(#27579) RFC also considers adding trait
647 // obligations that don't refer to Self and
650 let defer_to_coercion = self.tcx().features().object_safe_for_dispatch;
652 if !defer_to_coercion {
653 let cause = self.cause(traits::WellFormed(None));
654 let component_traits = data.auto_traits().chain(data.principal_def_id());
655 let tcx = self.tcx();
656 self.out.extend(component_traits.map(|did| {
657 traits::Obligation::with_depth(
661 ty::Binder::dummy(ty::PredicateKind::ObjectSafe(did))
668 // Inference variables are the complicated case, since we don't
669 // know what type they are. We do two things:
671 // 1. Check if they have been resolved, and if so proceed with
673 // 2. If not, we've at least simplified things (e.g., we went
674 // from `Vec<$0>: WF` to `$0: WF`), so we can
675 // register a pending obligation and keep
676 // moving. (Goal is that an "inductive hypothesis"
677 // is satisfied to ensure termination.)
678 // See also the comment on `fn obligations`, describing "livelock"
679 // prevention, which happens before this can be reached.
681 let cause = self.cause(traits::WellFormed(None));
682 self.out.push(traits::Obligation::with_depth(
684 self.recursion_depth,
686 ty::Binder::dummy(ty::PredicateKind::WellFormed(ty.into()))
687 .to_predicate(self.tcx()),
694 #[instrument(level = "debug", skip(self))]
695 fn nominal_obligations_inner(
698 substs: SubstsRef<'tcx>,
699 remap_constness: bool,
700 ) -> Vec<traits::PredicateObligation<'tcx>> {
701 let predicates = self.tcx.predicates_of(def_id);
702 let mut origins = vec![def_id; predicates.predicates.len()];
703 let mut head = predicates;
704 while let Some(parent) = head.parent {
705 head = self.tcx.predicates_of(parent);
706 origins.extend(iter::repeat(parent).take(head.predicates.len()));
709 let predicates = predicates.instantiate(self.tcx, substs);
710 trace!("{:#?}", predicates);
711 debug_assert_eq!(predicates.predicates.len(), origins.len());
713 iter::zip(iter::zip(predicates.predicates, predicates.spans), origins.into_iter().rev())
714 .map(|((mut pred, span), origin_def_id)| {
715 let code = if span.is_dummy() {
716 traits::MiscObligation
718 traits::BindingObligation(origin_def_id, span)
720 let cause = self.cause(code);
722 pred = pred.without_const(self.tcx);
724 traits::Obligation::with_depth(cause, self.recursion_depth, self.param_env, pred)
726 .filter(|pred| !pred.has_escaping_bound_vars())
730 fn nominal_obligations(
733 substs: SubstsRef<'tcx>,
734 ) -> Vec<traits::PredicateObligation<'tcx>> {
735 self.nominal_obligations_inner(def_id, substs, false)
738 fn nominal_obligations_without_const(
741 substs: SubstsRef<'tcx>,
742 ) -> Vec<traits::PredicateObligation<'tcx>> {
743 self.nominal_obligations_inner(def_id, substs, true)
749 data: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
750 region: ty::Region<'tcx>,
752 // Imagine a type like this:
755 // trait Bar<'c> : 'c { }
757 // &'b (Foo+'c+Bar<'d>)
760 // In this case, the following relationships must hold:
765 // The first conditions is due to the normal region pointer
766 // rules, which say that a reference cannot outlive its
769 // The final condition may be a bit surprising. In particular,
770 // you may expect that it would have been `'c <= 'd`, since
771 // usually lifetimes of outer things are conservative
772 // approximations for inner things. However, it works somewhat
773 // differently with trait objects: here the idea is that if the
774 // user specifies a region bound (`'c`, in this case) it is the
775 // "master bound" that *implies* that bounds from other traits are
776 // all met. (Remember that *all bounds* in a type like
777 // `Foo+Bar+Zed` must be met, not just one, hence if we write
778 // `Foo<'x>+Bar<'y>`, we know that the type outlives *both* 'x and
781 // Note: in fact we only permit builtin traits, not `Bar<'d>`, I
782 // am looking forward to the future here.
783 if !data.has_escaping_bound_vars() && !region.has_escaping_bound_vars() {
784 let implicit_bounds = object_region_bounds(self.tcx, data);
786 let explicit_bound = region;
788 self.out.reserve(implicit_bounds.len());
789 for implicit_bound in implicit_bounds {
790 let cause = self.cause(traits::ObjectTypeBound(ty, explicit_bound));
792 ty::Binder::dummy(ty::OutlivesPredicate(explicit_bound, implicit_bound));
793 self.out.push(traits::Obligation::with_depth(
795 self.recursion_depth,
797 outlives.to_predicate(self.tcx),
804 /// Given an object type like `SomeTrait + Send`, computes the lifetime
805 /// bounds that must hold on the elided self type. These are derived
806 /// from the declarations of `SomeTrait`, `Send`, and friends -- if
807 /// they declare `trait SomeTrait : 'static`, for example, then
808 /// `'static` would appear in the list. The hard work is done by
809 /// `infer::required_region_bounds`, see that for more information.
810 pub fn object_region_bounds<'tcx>(
812 existential_predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
813 ) -> Vec<ty::Region<'tcx>> {
814 // Since we don't actually *know* the self type for an object,
815 // this "open(err)" serves as a kind of dummy standin -- basically
816 // a placeholder type.
817 let open_ty = tcx.mk_ty_infer(ty::FreshTy(0));
819 let predicates = existential_predicates.iter().filter_map(|predicate| {
820 if let ty::ExistentialPredicate::Projection(_) = predicate.skip_binder() {
823 Some(predicate.with_self_ty(tcx, open_ty))
827 required_region_bounds(tcx, open_ty, predicates)
830 /// Given a set of predicates that apply to an object type, returns
831 /// the region bounds that the (erased) `Self` type must
832 /// outlive. Precisely *because* the `Self` type is erased, the
833 /// parameter `erased_self_ty` must be supplied to indicate what type
834 /// has been used to represent `Self` in the predicates
835 /// themselves. This should really be a unique type; `FreshTy(0)` is a
838 /// N.B., in some cases, particularly around higher-ranked bounds,
839 /// this function returns a kind of conservative approximation.
840 /// That is, all regions returned by this function are definitely
841 /// required, but there may be other region bounds that are not
842 /// returned, as well as requirements like `for<'a> T: 'a`.
844 /// Requires that trait definitions have been processed so that we can
845 /// elaborate predicates and walk supertraits.
846 #[instrument(skip(tcx, predicates), level = "debug")]
847 pub(crate) fn required_region_bounds<'tcx>(
849 erased_self_ty: Ty<'tcx>,
850 predicates: impl Iterator<Item = ty::Predicate<'tcx>>,
851 ) -> Vec<ty::Region<'tcx>> {
852 assert!(!erased_self_ty.has_escaping_bound_vars());
854 traits::elaborate_predicates(tcx, predicates)
855 .filter_map(|obligation| {
857 match obligation.predicate.kind().skip_binder() {
858 ty::PredicateKind::Projection(..)
859 | ty::PredicateKind::Trait(..)
860 | ty::PredicateKind::Subtype(..)
861 | ty::PredicateKind::Coerce(..)
862 | ty::PredicateKind::WellFormed(..)
863 | ty::PredicateKind::ObjectSafe(..)
864 | ty::PredicateKind::ClosureKind(..)
865 | ty::PredicateKind::RegionOutlives(..)
866 | ty::PredicateKind::ConstEvaluatable(..)
867 | ty::PredicateKind::ConstEquate(..)
868 | ty::PredicateKind::TypeWellFormedFromEnv(..) => None,
869 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ref t, ref r)) => {
870 // Search for a bound of the form `erased_self_ty
871 // : 'a`, but be wary of something like `for<'a>
872 // erased_self_ty : 'a` (we interpret a
873 // higher-ranked bound like that as 'static,
874 // though at present the code in `fulfill.rs`
875 // considers such bounds to be unsatisfiable, so
876 // it's kind of a moot point since you could never
877 // construct such an object, but this seems
878 // correct even if that code changes).
879 if t == &erased_self_ty && !r.has_escaping_bound_vars() {