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(_) => {
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<'a, 'tcx>(
83 infcx: &InferCtxt<'a, '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<'a, 'tcx>(
106 infcx: &InferCtxt<'a, '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(uv) => {
152 let obligations = wf.nominal_obligations(uv.def.did, uv.substs);
153 wf.out.extend(obligations);
155 for arg in uv.substs.iter() {
159 ty::PredicateKind::ConstEquate(c1, c2) => {
160 wf.compute(c1.into());
161 wf.compute(c2.into());
163 ty::PredicateKind::TypeWellFormedFromEnv(..) => {
164 bug!("TypeWellFormedFromEnv is only used for Chalk")
171 struct WfPredicates<'tcx> {
173 param_env: ty::ParamEnv<'tcx>,
176 out: Vec<traits::PredicateObligation<'tcx>>,
177 recursion_depth: usize,
178 item: Option<&'tcx hir::Item<'tcx>>,
181 /// Controls whether we "elaborate" supertraits and so forth on the WF
182 /// predicates. This is a kind of hack to address #43784. The
183 /// underlying problem in that issue was a trait structure like:
185 /// ```ignore (illustrative)
186 /// trait Foo: Copy { }
187 /// trait Bar: Foo { }
188 /// impl<T: Bar> Foo for T { }
189 /// impl<T> Bar for T { }
192 /// Here, in the `Foo` impl, we will check that `T: Copy` holds -- but
193 /// we decide that this is true because `T: Bar` is in the
194 /// where-clauses (and we can elaborate that to include `T:
195 /// Copy`). This wouldn't be a problem, except that when we check the
196 /// `Bar` impl, we decide that `T: Foo` must hold because of the `Foo`
197 /// impl. And so nowhere did we check that `T: Copy` holds!
199 /// To resolve this, we elaborate the WF requirements that must be
200 /// proven when checking impls. This means that (e.g.) the `impl Bar
201 /// for T` will be forced to prove not only that `T: Foo` but also `T:
202 /// Copy` (which it won't be able to do, because there is no `Copy`
204 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
210 fn extend_cause_with_original_assoc_item_obligation<'tcx>(
212 trait_ref: &ty::TraitRef<'tcx>,
213 item: Option<&hir::Item<'tcx>>,
214 cause: &mut traits::ObligationCause<'tcx>,
215 pred: ty::Predicate<'tcx>,
218 "extended_cause_with_original_assoc_item_obligation {:?} {:?} {:?} {:?}",
219 trait_ref, item, cause, pred
221 let (items, impl_def_id) = match item {
222 Some(hir::Item { kind: hir::ItemKind::Impl(impl_), def_id, .. }) => (impl_.items, *def_id),
226 |impl_item_ref: &hir::ImplItemRef| match tcx.hir().impl_item(impl_item_ref.id).kind {
227 hir::ImplItemKind::Const(ty, _) | hir::ImplItemKind::TyAlias(ty) => ty.span,
228 _ => impl_item_ref.span,
231 // It is fine to skip the binder as we don't care about regions here.
232 match pred.kind().skip_binder() {
233 ty::PredicateKind::Projection(proj) => {
234 // The obligation comes not from the current `impl` nor the `trait` being implemented,
235 // but rather from a "second order" obligation, where an associated type has a
236 // projection coming from another associated type. See
237 // `src/test/ui/associated-types/point-at-type-on-obligation-failure.rs` and
238 // `traits-assoc-type-in-supertrait-bad.rs`.
239 if let Some(ty::Projection(projection_ty)) = proj.term.ty().map(|ty| ty.kind())
240 && let Some(&impl_item_id) =
241 tcx.impl_item_implementor_ids(impl_def_id).get(&projection_ty.item_def_id)
242 && let Some(impl_item_span) = items
244 .find(|item| item.id.def_id.to_def_id() == impl_item_id)
247 cause.span = impl_item_span;
250 ty::PredicateKind::Trait(pred) => {
251 // An associated item obligation born out of the `trait` failed to be met. An example
252 // can be seen in `ui/associated-types/point-at-type-on-obligation-failure-2.rs`.
253 debug!("extended_cause_with_original_assoc_item_obligation trait proj {:?}", pred);
254 if let ty::Projection(ty::ProjectionTy { item_def_id, .. }) = *pred.self_ty().kind()
255 && let Some(&impl_item_id) =
256 tcx.impl_item_implementor_ids(impl_def_id).get(&item_def_id)
257 && let Some(impl_item_span) = items
259 .find(|item| item.id.def_id.to_def_id() == impl_item_id)
262 cause.span = impl_item_span;
269 impl<'tcx> WfPredicates<'tcx> {
270 fn tcx(&self) -> TyCtxt<'tcx> {
274 fn cause(&self, code: traits::ObligationCauseCode<'tcx>) -> traits::ObligationCause<'tcx> {
275 traits::ObligationCause::new(self.span, self.body_id, code)
278 fn normalize(self, infcx: &InferCtxt<'_, 'tcx>) -> Vec<traits::PredicateObligation<'tcx>> {
279 let cause = self.cause(traits::WellFormed(None));
280 let param_env = self.param_env;
281 let mut obligations = Vec::with_capacity(self.out.len());
282 for mut obligation in self.out {
283 assert!(!obligation.has_escaping_bound_vars());
284 let mut selcx = traits::SelectionContext::new(infcx);
285 // Don't normalize the whole obligation, the param env is either
286 // already normalized, or we're currently normalizing the
287 // param_env. Either way we should only normalize the predicate.
288 let normalized_predicate = traits::project::normalize_with_depth_to(
292 self.recursion_depth,
293 obligation.predicate,
296 obligation.predicate = normalized_predicate;
297 obligations.push(obligation);
302 /// Pushes the obligations required for `trait_ref` to be WF into `self.out`.
303 fn compute_trait_pred(&mut self, trait_pred: &ty::TraitPredicate<'tcx>, elaborate: Elaborate) {
305 let trait_ref = &trait_pred.trait_ref;
307 // if the trait predicate is not const, the wf obligations should not be const as well.
308 let obligations = if trait_pred.constness == ty::BoundConstness::NotConst {
309 self.nominal_obligations_without_const(trait_ref.def_id, trait_ref.substs)
311 self.nominal_obligations(trait_ref.def_id, trait_ref.substs)
314 debug!("compute_trait_pred obligations {:?}", obligations);
315 let param_env = self.param_env;
316 let depth = self.recursion_depth;
318 let item = self.item;
320 let extend = |traits::PredicateObligation { predicate, mut cause, .. }| {
321 if let Some(parent_trait_pred) = predicate.to_opt_poly_trait_pred() {
322 cause = cause.derived_cause(
324 traits::ObligationCauseCode::DerivedObligation,
327 extend_cause_with_original_assoc_item_obligation(
328 tcx, trait_ref, item, &mut cause, predicate,
330 traits::Obligation::with_depth(cause, depth, param_env, predicate)
333 if let Elaborate::All = elaborate {
334 let implied_obligations = traits::util::elaborate_obligations(tcx, obligations);
335 let implied_obligations = implied_obligations.map(extend);
336 self.out.extend(implied_obligations);
338 self.out.extend(obligations);
341 let tcx = self.tcx();
348 matches!(arg.unpack(), GenericArgKind::Type(..) | GenericArgKind::Const(..))
350 .filter(|(_, arg)| !arg.has_escaping_bound_vars())
352 let mut cause = traits::ObligationCause::misc(self.span, self.body_id);
353 // The first subst is the self ty - use the correct span for it.
355 if let Some(hir::ItemKind::Impl(hir::Impl { self_ty, .. })) =
356 item.map(|i| &i.kind)
358 cause.span = self_ty.span;
361 traits::Obligation::with_depth(
365 ty::Binder::dummy(ty::PredicateKind::WellFormed(arg)).to_predicate(tcx),
371 /// Pushes the obligations required for `trait_ref::Item` to be WF
373 fn compute_projection(&mut self, data: ty::ProjectionTy<'tcx>) {
374 // A projection is well-formed if
376 // (a) its predicates hold (*)
377 // (b) its substs are wf
379 // (*) The predicates of an associated type include the predicates of
380 // the trait that it's contained in. For example, given
382 // trait A<T>: Clone {
383 // type X where T: Copy;
386 // The predicates of `<() as A<i32>>::X` are:
395 // Projection types do not require const predicates.
396 let obligations = self.nominal_obligations_without_const(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 #[instrument(level = "debug", skip(self))]
440 fn compute(&mut self, arg: GenericArg<'tcx>) {
441 let mut walker = arg.walk();
442 let param_env = self.param_env;
443 let depth = self.recursion_depth;
444 while let Some(arg) = walker.next() {
445 debug!(?arg, ?self.out);
446 let ty = match arg.unpack() {
447 GenericArgKind::Type(ty) => ty,
449 // No WF constraints for lifetimes being present, any outlives
450 // obligations are handled by the parent (e.g. `ty::Ref`).
451 GenericArgKind::Lifetime(_) => continue,
453 GenericArgKind::Const(constant) => {
454 match constant.kind() {
455 ty::ConstKind::Unevaluated(uv) => {
456 let obligations = self.nominal_obligations(uv.def.did, uv.substs);
457 self.out.extend(obligations);
460 ty::Binder::dummy(ty::PredicateKind::ConstEvaluatable(uv.shrink()))
461 .to_predicate(self.tcx());
462 let cause = self.cause(traits::WellFormed(None));
463 self.out.push(traits::Obligation::with_depth(
465 self.recursion_depth,
470 ty::ConstKind::Infer(_) => {
471 let cause = self.cause(traits::WellFormed(None));
473 self.out.push(traits::Obligation::with_depth(
475 self.recursion_depth,
477 ty::Binder::dummy(ty::PredicateKind::WellFormed(constant.into()))
478 .to_predicate(self.tcx()),
481 ty::ConstKind::Error(_)
482 | ty::ConstKind::Param(_)
483 | ty::ConstKind::Bound(..)
484 | ty::ConstKind::Placeholder(..) => {
485 // These variants are trivially WF, so nothing to do here.
487 ty::ConstKind::Value(..) => {
488 // FIXME: Enforce that values are structurally-matchable.
495 debug!("wf bounds for ty={:?} ty.kind={:#?}", ty, ty.kind());
505 | ty::GeneratorWitness(..)
509 | ty::Placeholder(..)
510 | ty::Foreign(..) => {
511 // WfScalar, WfParameter, etc
514 // Can only infer to `ty::Int(_) | ty::Uint(_)`.
515 ty::Infer(ty::IntVar(_)) => {}
517 // Can only infer to `ty::Float(_)`.
518 ty::Infer(ty::FloatVar(_)) => {}
520 ty::Slice(subty) => {
521 self.require_sized(subty, traits::SliceOrArrayElem);
524 ty::Array(subty, _) => {
525 self.require_sized(subty, traits::SliceOrArrayElem);
526 // Note that we handle the len is implicitly checked while walking `arg`.
529 ty::Tuple(ref tys) => {
530 if let Some((_last, rest)) = tys.split_last() {
532 self.require_sized(elem, traits::TupleElem);
538 // Simple cases that are WF if their type args are WF.
541 ty::Projection(data) => {
542 walker.skip_current_subtree(); // Subtree handled by compute_projection.
543 self.compute_projection(data);
546 ty::Adt(def, substs) => {
548 let obligations = self.nominal_obligations(def.did(), substs);
549 self.out.extend(obligations);
552 ty::FnDef(did, substs) => {
553 let obligations = self.nominal_obligations(did, substs);
554 self.out.extend(obligations);
557 ty::Ref(r, rty, _) => {
559 if !r.has_escaping_bound_vars() && !rty.has_escaping_bound_vars() {
560 let cause = self.cause(traits::ReferenceOutlivesReferent(ty));
561 self.out.push(traits::Obligation::with_depth(
565 ty::Binder::dummy(ty::PredicateKind::TypeOutlives(
566 ty::OutlivesPredicate(rty, r),
568 .to_predicate(self.tcx()),
573 ty::Generator(did, substs, ..) => {
574 // Walk ALL the types in the generator: this will
575 // include the upvar types as well as the yield
576 // type. Note that this is mildly distinct from
577 // the closure case, where we have to be careful
578 // about the signature of the closure. We don't
579 // have the problem of implied bounds here since
580 // generators don't take arguments.
581 let obligations = self.nominal_obligations(did, substs);
582 self.out.extend(obligations);
585 ty::Closure(did, substs) => {
586 // Only check the upvar types for WF, not the rest
587 // of the types within. This is needed because we
588 // capture the signature and it may not be WF
589 // without the implied bounds. Consider a closure
590 // like `|x: &'a T|` -- it may be that `T: 'a` is
591 // not known to hold in the creator's context (and
592 // indeed the closure may not be invoked by its
593 // creator, but rather turned to someone who *can*
596 // The special treatment of closures here really
597 // ought not to be necessary either; the problem
598 // is related to #25860 -- there is no way for us
599 // to express a fn type complete with the implied
600 // bounds that it is assuming. I think in reality
601 // the WF rules around fn are a bit messed up, and
602 // that is the rot problem: `fn(&'a T)` should
603 // probably always be WF, because it should be
604 // shorthand for something like `where(T: 'a) {
605 // fn(&'a T) }`, as discussed in #25860.
606 walker.skip_current_subtree(); // subtree handled below
607 // FIXME(eddyb) add the type to `walker` instead of recursing.
608 self.compute(substs.as_closure().tupled_upvars_ty().into());
609 // Note that we cannot skip the generic types
610 // types. Normally, within the fn
611 // body where they are created, the generics will
612 // always be WF, and outside of that fn body we
613 // are not directly inspecting closure types
614 // anyway, except via auto trait matching (which
615 // only inspects the upvar types).
616 // But when a closure is part of a type-alias-impl-trait
617 // then the function that created the defining site may
618 // have had more bounds available than the type alias
619 // specifies. This may cause us to have a closure in the
620 // hidden type that is not actually well formed and
621 // can cause compiler crashes when the user abuses unsafe
622 // code to procure such a closure.
623 // See src/test/ui/type-alias-impl-trait/wf_check_closures.rs
624 let obligations = self.nominal_obligations(did, substs);
625 self.out.extend(obligations);
629 // let the loop iterate into the argument/return
630 // types appearing in the fn signature
633 ty::Opaque(did, substs) => {
634 // All of the requirements on type parameters
635 // have already been checked for `impl Trait` in
636 // return position. We do need to check type-alias-impl-trait though.
637 if ty::is_impl_trait_defn(self.tcx, did).is_none() {
638 let obligations = self.nominal_obligations(did, substs);
639 self.out.extend(obligations);
643 ty::Dynamic(data, r, _) => {
646 // Here, we defer WF checking due to higher-ranked
647 // regions. This is perhaps not ideal.
648 self.from_object_ty(ty, data, r);
650 // FIXME(#27579) RFC also considers adding trait
651 // obligations that don't refer to Self and
654 let defer_to_coercion = self.tcx().features().object_safe_for_dispatch;
656 if !defer_to_coercion {
657 let cause = self.cause(traits::WellFormed(None));
658 let component_traits = data.auto_traits().chain(data.principal_def_id());
659 let tcx = self.tcx();
660 self.out.extend(component_traits.map(|did| {
661 traits::Obligation::with_depth(
665 ty::Binder::dummy(ty::PredicateKind::ObjectSafe(did))
672 // Inference variables are the complicated case, since we don't
673 // know what type they are. We do two things:
675 // 1. Check if they have been resolved, and if so proceed with
677 // 2. If not, we've at least simplified things (e.g., we went
678 // from `Vec<$0>: WF` to `$0: WF`), so we can
679 // register a pending obligation and keep
680 // moving. (Goal is that an "inductive hypothesis"
681 // is satisfied to ensure termination.)
682 // See also the comment on `fn obligations`, describing "livelock"
683 // prevention, which happens before this can be reached.
685 let cause = self.cause(traits::WellFormed(None));
686 self.out.push(traits::Obligation::with_depth(
688 self.recursion_depth,
690 ty::Binder::dummy(ty::PredicateKind::WellFormed(ty.into()))
691 .to_predicate(self.tcx()),
700 #[instrument(level = "debug", skip(self))]
701 fn nominal_obligations_inner(
704 substs: SubstsRef<'tcx>,
705 remap_constness: bool,
706 ) -> Vec<traits::PredicateObligation<'tcx>> {
707 let predicates = self.tcx.predicates_of(def_id);
708 let mut origins = vec![def_id; predicates.predicates.len()];
709 let mut head = predicates;
710 while let Some(parent) = head.parent {
711 head = self.tcx.predicates_of(parent);
712 origins.extend(iter::repeat(parent).take(head.predicates.len()));
715 let predicates = predicates.instantiate(self.tcx, substs);
716 trace!("{:#?}", predicates);
717 debug_assert_eq!(predicates.predicates.len(), origins.len());
719 iter::zip(iter::zip(predicates.predicates, predicates.spans), origins.into_iter().rev())
720 .map(|((mut pred, span), origin_def_id)| {
721 let code = if span.is_dummy() {
722 traits::ItemObligation(origin_def_id)
724 traits::BindingObligation(origin_def_id, span)
726 let cause = self.cause(code);
728 pred = pred.without_const(self.tcx);
730 traits::Obligation::with_depth(cause, self.recursion_depth, self.param_env, pred)
732 .filter(|pred| !pred.has_escaping_bound_vars())
736 fn nominal_obligations(
739 substs: SubstsRef<'tcx>,
740 ) -> Vec<traits::PredicateObligation<'tcx>> {
741 self.nominal_obligations_inner(def_id, substs, false)
744 fn nominal_obligations_without_const(
747 substs: SubstsRef<'tcx>,
748 ) -> Vec<traits::PredicateObligation<'tcx>> {
749 self.nominal_obligations_inner(def_id, substs, true)
755 data: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
756 region: ty::Region<'tcx>,
758 // Imagine a type like this:
761 // trait Bar<'c> : 'c { }
763 // &'b (Foo+'c+Bar<'d>)
766 // In this case, the following relationships must hold:
771 // The first conditions is due to the normal region pointer
772 // rules, which say that a reference cannot outlive its
775 // The final condition may be a bit surprising. In particular,
776 // you may expect that it would have been `'c <= 'd`, since
777 // usually lifetimes of outer things are conservative
778 // approximations for inner things. However, it works somewhat
779 // differently with trait objects: here the idea is that if the
780 // user specifies a region bound (`'c`, in this case) it is the
781 // "master bound" that *implies* that bounds from other traits are
782 // all met. (Remember that *all bounds* in a type like
783 // `Foo+Bar+Zed` must be met, not just one, hence if we write
784 // `Foo<'x>+Bar<'y>`, we know that the type outlives *both* 'x and
787 // Note: in fact we only permit builtin traits, not `Bar<'d>`, I
788 // am looking forward to the future here.
789 if !data.has_escaping_bound_vars() && !region.has_escaping_bound_vars() {
790 let implicit_bounds = object_region_bounds(self.tcx, data);
792 let explicit_bound = region;
794 self.out.reserve(implicit_bounds.len());
795 for implicit_bound in implicit_bounds {
796 let cause = self.cause(traits::ObjectTypeBound(ty, explicit_bound));
798 ty::Binder::dummy(ty::OutlivesPredicate(explicit_bound, implicit_bound));
799 self.out.push(traits::Obligation::with_depth(
801 self.recursion_depth,
803 outlives.to_predicate(self.tcx),
810 /// Given an object type like `SomeTrait + Send`, computes the lifetime
811 /// bounds that must hold on the elided self type. These are derived
812 /// from the declarations of `SomeTrait`, `Send`, and friends -- if
813 /// they declare `trait SomeTrait : 'static`, for example, then
814 /// `'static` would appear in the list. The hard work is done by
815 /// `infer::required_region_bounds`, see that for more information.
816 pub fn object_region_bounds<'tcx>(
818 existential_predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
819 ) -> Vec<ty::Region<'tcx>> {
820 // Since we don't actually *know* the self type for an object,
821 // this "open(err)" serves as a kind of dummy standin -- basically
822 // a placeholder type.
823 let open_ty = tcx.mk_ty_infer(ty::FreshTy(0));
825 let predicates = existential_predicates.iter().filter_map(|predicate| {
826 if let ty::ExistentialPredicate::Projection(_) = predicate.skip_binder() {
829 Some(predicate.with_self_ty(tcx, open_ty))
833 required_region_bounds(tcx, open_ty, predicates)
836 /// Given a set of predicates that apply to an object type, returns
837 /// the region bounds that the (erased) `Self` type must
838 /// outlive. Precisely *because* the `Self` type is erased, the
839 /// parameter `erased_self_ty` must be supplied to indicate what type
840 /// has been used to represent `Self` in the predicates
841 /// themselves. This should really be a unique type; `FreshTy(0)` is a
844 /// N.B., in some cases, particularly around higher-ranked bounds,
845 /// this function returns a kind of conservative approximation.
846 /// That is, all regions returned by this function are definitely
847 /// required, but there may be other region bounds that are not
848 /// returned, as well as requirements like `for<'a> T: 'a`.
850 /// Requires that trait definitions have been processed so that we can
851 /// elaborate predicates and walk supertraits.
852 #[instrument(skip(tcx, predicates), level = "debug", ret)]
853 pub(crate) fn required_region_bounds<'tcx>(
855 erased_self_ty: Ty<'tcx>,
856 predicates: impl Iterator<Item = ty::Predicate<'tcx>>,
857 ) -> Vec<ty::Region<'tcx>> {
858 assert!(!erased_self_ty.has_escaping_bound_vars());
860 traits::elaborate_predicates(tcx, predicates)
861 .filter_map(|obligation| {
863 match obligation.predicate.kind().skip_binder() {
864 ty::PredicateKind::Projection(..)
865 | ty::PredicateKind::Trait(..)
866 | ty::PredicateKind::Subtype(..)
867 | ty::PredicateKind::Coerce(..)
868 | ty::PredicateKind::WellFormed(..)
869 | ty::PredicateKind::ObjectSafe(..)
870 | ty::PredicateKind::ClosureKind(..)
871 | ty::PredicateKind::RegionOutlives(..)
872 | ty::PredicateKind::ConstEvaluatable(..)
873 | ty::PredicateKind::ConstEquate(..)
874 | ty::PredicateKind::TypeWellFormedFromEnv(..) => None,
875 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ref t, ref r)) => {
876 // Search for a bound of the form `erased_self_ty
877 // : 'a`, but be wary of something like `for<'a>
878 // erased_self_ty : 'a` (we interpret a
879 // higher-ranked bound like that as 'static,
880 // though at present the code in `fulfill.rs`
881 // considers such bounds to be unsatisfiable, so
882 // it's kind of a moot point since you could never
883 // construct such an object, but this seems
884 // correct even if that code changes).
885 if t == &erased_self_ty && !r.has_escaping_bound_vars() {