1 use crate::infer::InferCtxt;
4 use rustc_hir::lang_items::LangItem;
5 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, SubstsRef};
6 use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitable};
7 use rustc_span::def_id::{DefId, LocalDefId, CRATE_DEF_ID};
8 use rustc_span::{Span, DUMMY_SP};
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 /// Compute the predicates that are required for a type to be well-formed.
80 /// This is only intended to be used in the new solver, since it does not
81 /// take into account recursion depth or proper error-reporting spans.
82 pub fn unnormalized_obligations<'tcx>(
83 infcx: &InferCtxt<'tcx>,
84 param_env: ty::ParamEnv<'tcx>,
85 arg: GenericArg<'tcx>,
86 ) -> Option<Vec<traits::PredicateObligation<'tcx>>> {
87 if let ty::GenericArgKind::Lifetime(..) = arg.unpack() {
91 debug_assert_eq!(arg, infcx.resolve_vars_if_possible(arg));
93 let mut wf = WfPredicates {
96 body_id: CRATE_DEF_ID,
106 /// Returns the obligations that make this trait reference
107 /// well-formed. For example, if there is a trait `Set` defined like
108 /// `trait Set<K:Eq>`, then the trait reference `Foo: Set<Bar>` is WF
110 pub fn trait_obligations<'tcx>(
111 infcx: &InferCtxt<'tcx>,
112 param_env: ty::ParamEnv<'tcx>,
114 trait_pred: &ty::TraitPredicate<'tcx>,
116 item: &'tcx hir::Item<'tcx>,
117 ) -> Vec<traits::PredicateObligation<'tcx>> {
118 let mut wf = WfPredicates {
127 wf.compute_trait_pred(trait_pred, Elaborate::All);
128 debug!(obligations = ?wf.out);
132 #[instrument(skip(infcx), ret)]
133 pub fn predicate_obligations<'tcx>(
134 infcx: &InferCtxt<'tcx>,
135 param_env: ty::ParamEnv<'tcx>,
137 predicate: ty::Predicate<'tcx>,
139 ) -> Vec<traits::PredicateObligation<'tcx>> {
140 let mut wf = WfPredicates {
150 // It's ok to skip the binder here because wf code is prepared for it
151 match predicate.kind().skip_binder() {
152 ty::PredicateKind::Clause(ty::Clause::Trait(t)) => {
153 wf.compute_trait_pred(&t, Elaborate::None);
155 ty::PredicateKind::Clause(ty::Clause::RegionOutlives(..)) => {}
156 ty::PredicateKind::Clause(ty::Clause::TypeOutlives(ty::OutlivesPredicate(ty, _reg))) => {
157 wf.compute(ty.into());
159 ty::PredicateKind::Clause(ty::Clause::Projection(t)) => {
160 wf.compute_projection(t.projection_ty);
161 wf.compute(match t.term.unpack() {
162 ty::TermKind::Ty(ty) => ty.into(),
163 ty::TermKind::Const(c) => c.into(),
166 ty::PredicateKind::WellFormed(arg) => {
169 ty::PredicateKind::ObjectSafe(_) => {}
170 ty::PredicateKind::ClosureKind(..) => {}
171 ty::PredicateKind::Subtype(ty::SubtypePredicate { a, b, a_is_expected: _ }) => {
172 wf.compute(a.into());
173 wf.compute(b.into());
175 ty::PredicateKind::Coerce(ty::CoercePredicate { a, b }) => {
176 wf.compute(a.into());
177 wf.compute(b.into());
179 ty::PredicateKind::ConstEvaluatable(ct) => {
180 wf.compute(ct.into());
182 ty::PredicateKind::ConstEquate(c1, c2) => {
183 wf.compute(c1.into());
184 wf.compute(c2.into());
186 ty::PredicateKind::Ambiguous => {}
187 ty::PredicateKind::TypeWellFormedFromEnv(..) => {
188 bug!("TypeWellFormedFromEnv is only used for Chalk")
195 struct WfPredicates<'tcx> {
197 param_env: ty::ParamEnv<'tcx>,
200 out: Vec<traits::PredicateObligation<'tcx>>,
201 recursion_depth: usize,
202 item: Option<&'tcx hir::Item<'tcx>>,
205 /// Controls whether we "elaborate" supertraits and so forth on the WF
206 /// predicates. This is a kind of hack to address #43784. The
207 /// underlying problem in that issue was a trait structure like:
209 /// ```ignore (illustrative)
210 /// trait Foo: Copy { }
211 /// trait Bar: Foo { }
212 /// impl<T: Bar> Foo for T { }
213 /// impl<T> Bar for T { }
216 /// Here, in the `Foo` impl, we will check that `T: Copy` holds -- but
217 /// we decide that this is true because `T: Bar` is in the
218 /// where-clauses (and we can elaborate that to include `T:
219 /// Copy`). This wouldn't be a problem, except that when we check the
220 /// `Bar` impl, we decide that `T: Foo` must hold because of the `Foo`
221 /// impl. And so nowhere did we check that `T: Copy` holds!
223 /// To resolve this, we elaborate the WF requirements that must be
224 /// proven when checking impls. This means that (e.g.) the `impl Bar
225 /// for T` will be forced to prove not only that `T: Foo` but also `T:
226 /// Copy` (which it won't be able to do, because there is no `Copy`
228 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
234 fn extend_cause_with_original_assoc_item_obligation<'tcx>(
236 trait_ref: &ty::TraitRef<'tcx>,
237 item: Option<&hir::Item<'tcx>>,
238 cause: &mut traits::ObligationCause<'tcx>,
239 pred: ty::Predicate<'tcx>,
242 "extended_cause_with_original_assoc_item_obligation {:?} {:?} {:?} {:?}",
243 trait_ref, item, cause, pred
245 let (items, impl_def_id) = match item {
246 Some(hir::Item { kind: hir::ItemKind::Impl(impl_), owner_id, .. }) => {
247 (impl_.items, *owner_id)
252 |impl_item_ref: &hir::ImplItemRef| match tcx.hir().impl_item(impl_item_ref.id).kind {
253 hir::ImplItemKind::Const(ty, _) | hir::ImplItemKind::Type(ty) => ty.span,
254 _ => impl_item_ref.span,
257 // It is fine to skip the binder as we don't care about regions here.
258 match pred.kind().skip_binder() {
259 ty::PredicateKind::Clause(ty::Clause::Projection(proj)) => {
260 // The obligation comes not from the current `impl` nor the `trait` being implemented,
261 // but rather from a "second order" obligation, where an associated type has a
262 // projection coming from another associated type. See
263 // `tests/ui/associated-types/point-at-type-on-obligation-failure.rs` and
264 // `traits-assoc-type-in-supertrait-bad.rs`.
265 if let Some(ty::Alias(ty::Projection, projection_ty)) = proj.term.ty().map(|ty| ty.kind())
266 && let Some(&impl_item_id) =
267 tcx.impl_item_implementor_ids(impl_def_id).get(&projection_ty.def_id)
268 && let Some(impl_item_span) = items
270 .find(|item| item.id.owner_id.to_def_id() == impl_item_id)
273 cause.span = impl_item_span;
276 ty::PredicateKind::Clause(ty::Clause::Trait(pred)) => {
277 // An associated item obligation born out of the `trait` failed to be met. An example
278 // can be seen in `ui/associated-types/point-at-type-on-obligation-failure-2.rs`.
279 debug!("extended_cause_with_original_assoc_item_obligation trait proj {:?}", pred);
280 if let ty::Alias(ty::Projection, ty::AliasTy { def_id, .. }) = *pred.self_ty().kind()
281 && let Some(&impl_item_id) =
282 tcx.impl_item_implementor_ids(impl_def_id).get(&def_id)
283 && let Some(impl_item_span) = items
285 .find(|item| item.id.owner_id.to_def_id() == impl_item_id)
288 cause.span = impl_item_span;
295 impl<'tcx> WfPredicates<'tcx> {
296 fn tcx(&self) -> TyCtxt<'tcx> {
300 fn cause(&self, code: traits::ObligationCauseCode<'tcx>) -> traits::ObligationCause<'tcx> {
301 traits::ObligationCause::new(self.span, self.body_id, code)
304 fn normalize(self, infcx: &InferCtxt<'tcx>) -> Vec<traits::PredicateObligation<'tcx>> {
305 let cause = self.cause(traits::WellFormed(None));
306 let param_env = self.param_env;
307 let mut obligations = Vec::with_capacity(self.out.len());
308 for mut obligation in self.out {
309 assert!(!obligation.has_escaping_bound_vars());
310 let mut selcx = traits::SelectionContext::new(infcx);
311 // Don't normalize the whole obligation, the param env is either
312 // already normalized, or we're currently normalizing the
313 // param_env. Either way we should only normalize the predicate.
314 let normalized_predicate = traits::project::normalize_with_depth_to(
318 self.recursion_depth,
319 obligation.predicate,
322 obligation.predicate = normalized_predicate;
323 obligations.push(obligation);
328 /// Pushes the obligations required for `trait_ref` to be WF into `self.out`.
329 fn compute_trait_pred(&mut self, trait_pred: &ty::TraitPredicate<'tcx>, elaborate: Elaborate) {
331 let trait_ref = &trait_pred.trait_ref;
333 // if the trait predicate is not const, the wf obligations should not be const as well.
334 let obligations = if trait_pred.constness == ty::BoundConstness::NotConst {
335 self.nominal_obligations_without_const(trait_ref.def_id, trait_ref.substs)
337 self.nominal_obligations(trait_ref.def_id, trait_ref.substs)
340 debug!("compute_trait_pred obligations {:?}", obligations);
341 let param_env = self.param_env;
342 let depth = self.recursion_depth;
344 let item = self.item;
346 let extend = |traits::PredicateObligation { predicate, mut cause, .. }| {
347 if let Some(parent_trait_pred) = predicate.to_opt_poly_trait_pred() {
348 cause = cause.derived_cause(
350 traits::ObligationCauseCode::DerivedObligation,
353 extend_cause_with_original_assoc_item_obligation(
354 tcx, trait_ref, item, &mut cause, predicate,
356 traits::Obligation::with_depth(tcx, cause, depth, param_env, predicate)
359 if let Elaborate::All = elaborate {
360 let implied_obligations = traits::util::elaborate_obligations(tcx, obligations);
361 let implied_obligations = implied_obligations.map(extend);
362 self.out.extend(implied_obligations);
364 self.out.extend(obligations);
367 let tcx = self.tcx();
374 matches!(arg.unpack(), GenericArgKind::Type(..) | GenericArgKind::Const(..))
376 .filter(|(_, arg)| !arg.has_escaping_bound_vars())
378 let mut cause = traits::ObligationCause::misc(self.span, self.body_id);
379 // The first subst is the self ty - use the correct span for it.
381 if let Some(hir::ItemKind::Impl(hir::Impl { self_ty, .. })) =
382 item.map(|i| &i.kind)
384 cause.span = self_ty.span;
387 traits::Obligation::with_depth(
392 ty::Binder::dummy(ty::PredicateKind::WellFormed(arg)),
398 /// Pushes the obligations required for `trait_ref::Item` to be WF
400 fn compute_projection(&mut self, data: ty::AliasTy<'tcx>) {
401 // A projection is well-formed if
403 // (a) its predicates hold (*)
404 // (b) its substs are wf
406 // (*) The predicates of an associated type include the predicates of
407 // the trait that it's contained in. For example, given
409 // trait A<T>: Clone {
410 // type X where T: Copy;
413 // The predicates of `<() as A<i32>>::X` are:
422 // Projection types do not require const predicates.
423 let obligations = self.nominal_obligations_without_const(data.def_id, data.substs);
424 self.out.extend(obligations);
426 let tcx = self.tcx();
427 let cause = self.cause(traits::WellFormed(None));
428 let param_env = self.param_env;
429 let depth = self.recursion_depth;
435 matches!(arg.unpack(), GenericArgKind::Type(..) | GenericArgKind::Const(..))
437 .filter(|arg| !arg.has_escaping_bound_vars())
439 traits::Obligation::with_depth(
444 ty::Binder::dummy(ty::PredicateKind::WellFormed(arg)),
450 fn require_sized(&mut self, subty: Ty<'tcx>, cause: traits::ObligationCauseCode<'tcx>) {
451 if !subty.has_escaping_bound_vars() {
452 let cause = self.cause(cause);
453 let trait_ref = self.tcx.at(cause.span).mk_trait_ref(LangItem::Sized, [subty]);
454 self.out.push(traits::Obligation::with_depth(
457 self.recursion_depth,
459 ty::Binder::dummy(trait_ref).without_const(),
464 /// Pushes all the predicates needed to validate that `ty` is WF into `out`.
465 #[instrument(level = "debug", skip(self))]
466 fn compute(&mut self, arg: GenericArg<'tcx>) {
467 let mut walker = arg.walk();
468 let param_env = self.param_env;
469 let depth = self.recursion_depth;
470 while let Some(arg) = walker.next() {
471 debug!(?arg, ?self.out);
472 let ty = match arg.unpack() {
473 GenericArgKind::Type(ty) => ty,
475 // No WF constraints for lifetimes being present, any outlives
476 // obligations are handled by the parent (e.g. `ty::Ref`).
477 GenericArgKind::Lifetime(_) => continue,
479 GenericArgKind::Const(ct) => {
481 ty::ConstKind::Unevaluated(uv) => {
482 if !ct.has_escaping_bound_vars() {
483 let obligations = self.nominal_obligations(uv.def.did, uv.substs);
484 self.out.extend(obligations);
487 ty::Binder::dummy(ty::PredicateKind::ConstEvaluatable(ct));
488 let cause = self.cause(traits::WellFormed(None));
489 self.out.push(traits::Obligation::with_depth(
492 self.recursion_depth,
498 ty::ConstKind::Infer(_) => {
499 let cause = self.cause(traits::WellFormed(None));
501 self.out.push(traits::Obligation::with_depth(
504 self.recursion_depth,
506 ty::Binder::dummy(ty::PredicateKind::WellFormed(ct.into())),
509 ty::ConstKind::Expr(_) => {
510 // FIXME(generic_const_exprs): this doesnt verify that given `Expr(N + 1)` the
511 // trait bound `typeof(N): Add<typeof(1)>` holds. This is currently unnecessary
512 // as `ConstKind::Expr` is only produced via normalization of `ConstKind::Unevaluated`
513 // which means that the `DefId` would have been typeck'd elsewhere. However in
514 // the future we may allow directly lowering to `ConstKind::Expr` in which case
515 // we would not be proving bounds we should.
518 ty::Binder::dummy(ty::PredicateKind::ConstEvaluatable(ct));
519 let cause = self.cause(traits::WellFormed(None));
520 self.out.push(traits::Obligation::with_depth(
523 self.recursion_depth,
529 ty::ConstKind::Error(_)
530 | ty::ConstKind::Param(_)
531 | ty::ConstKind::Bound(..)
532 | ty::ConstKind::Placeholder(..) => {
533 // These variants are trivially WF, so nothing to do here.
535 ty::ConstKind::Value(..) => {
536 // FIXME: Enforce that values are structurally-matchable.
543 debug!("wf bounds for ty={:?} ty.kind={:#?}", ty, ty.kind());
553 | ty::GeneratorWitness(..)
557 | ty::Placeholder(..)
558 | ty::Foreign(..) => {
559 // WfScalar, WfParameter, etc
562 // Can only infer to `ty::Int(_) | ty::Uint(_)`.
563 ty::Infer(ty::IntVar(_)) => {}
565 // Can only infer to `ty::Float(_)`.
566 ty::Infer(ty::FloatVar(_)) => {}
568 ty::Slice(subty) => {
569 self.require_sized(subty, traits::SliceOrArrayElem);
572 ty::Array(subty, _) => {
573 self.require_sized(subty, traits::SliceOrArrayElem);
574 // Note that we handle the len is implicitly checked while walking `arg`.
577 ty::Tuple(ref tys) => {
578 if let Some((_last, rest)) = tys.split_last() {
580 self.require_sized(elem, traits::TupleElem);
586 // Simple cases that are WF if their type args are WF.
589 ty::Alias(ty::Projection, data) => {
590 walker.skip_current_subtree(); // Subtree handled by compute_projection.
591 self.compute_projection(data);
594 ty::Adt(def, substs) => {
596 let obligations = self.nominal_obligations(def.did(), substs);
597 self.out.extend(obligations);
600 ty::FnDef(did, substs) => {
601 let obligations = self.nominal_obligations_without_const(did, substs);
602 self.out.extend(obligations);
605 ty::Ref(r, rty, _) => {
607 if !r.has_escaping_bound_vars() && !rty.has_escaping_bound_vars() {
608 let cause = self.cause(traits::ReferenceOutlivesReferent(ty));
609 self.out.push(traits::Obligation::with_depth(
614 ty::Binder::dummy(ty::PredicateKind::Clause(ty::Clause::TypeOutlives(
615 ty::OutlivesPredicate(rty, r),
621 ty::Generator(did, substs, ..) => {
622 // Walk ALL the types in the generator: this will
623 // include the upvar types as well as the yield
624 // type. Note that this is mildly distinct from
625 // the closure case, where we have to be careful
626 // about the signature of the closure. We don't
627 // have the problem of implied bounds here since
628 // generators don't take arguments.
629 let obligations = self.nominal_obligations(did, substs);
630 self.out.extend(obligations);
633 ty::Closure(did, substs) => {
634 // Only check the upvar types for WF, not the rest
635 // of the types within. This is needed because we
636 // capture the signature and it may not be WF
637 // without the implied bounds. Consider a closure
638 // like `|x: &'a T|` -- it may be that `T: 'a` is
639 // not known to hold in the creator's context (and
640 // indeed the closure may not be invoked by its
641 // creator, but rather turned to someone who *can*
644 // The special treatment of closures here really
645 // ought not to be necessary either; the problem
646 // is related to #25860 -- there is no way for us
647 // to express a fn type complete with the implied
648 // bounds that it is assuming. I think in reality
649 // the WF rules around fn are a bit messed up, and
650 // that is the rot problem: `fn(&'a T)` should
651 // probably always be WF, because it should be
652 // shorthand for something like `where(T: 'a) {
653 // fn(&'a T) }`, as discussed in #25860.
654 walker.skip_current_subtree(); // subtree handled below
655 // FIXME(eddyb) add the type to `walker` instead of recursing.
656 self.compute(substs.as_closure().tupled_upvars_ty().into());
657 // Note that we cannot skip the generic types
658 // types. Normally, within the fn
659 // body where they are created, the generics will
660 // always be WF, and outside of that fn body we
661 // are not directly inspecting closure types
662 // anyway, except via auto trait matching (which
663 // only inspects the upvar types).
664 // But when a closure is part of a type-alias-impl-trait
665 // then the function that created the defining site may
666 // have had more bounds available than the type alias
667 // specifies. This may cause us to have a closure in the
668 // hidden type that is not actually well formed and
669 // can cause compiler crashes when the user abuses unsafe
670 // code to procure such a closure.
671 // See tests/ui/type-alias-impl-trait/wf_check_closures.rs
672 let obligations = self.nominal_obligations(did, substs);
673 self.out.extend(obligations);
677 // let the loop iterate into the argument/return
678 // types appearing in the fn signature
681 ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) => {
682 // All of the requirements on type parameters
683 // have already been checked for `impl Trait` in
684 // return position. We do need to check type-alias-impl-trait though.
685 if self.tcx.is_type_alias_impl_trait(def_id) {
686 let obligations = self.nominal_obligations(def_id, substs);
687 self.out.extend(obligations);
691 ty::Dynamic(data, r, _) => {
694 // Here, we defer WF checking due to higher-ranked
695 // regions. This is perhaps not ideal.
696 self.from_object_ty(ty, data, r);
698 // FIXME(#27579) RFC also considers adding trait
699 // obligations that don't refer to Self and
702 let defer_to_coercion = self.tcx().features().object_safe_for_dispatch;
704 if !defer_to_coercion {
705 let cause = self.cause(traits::WellFormed(None));
706 let component_traits = data.auto_traits().chain(data.principal_def_id());
707 let tcx = self.tcx();
708 self.out.extend(component_traits.map(|did| {
709 traits::Obligation::with_depth(
714 ty::Binder::dummy(ty::PredicateKind::ObjectSafe(did)),
720 // Inference variables are the complicated case, since we don't
721 // know what type they are. We do two things:
723 // 1. Check if they have been resolved, and if so proceed with
725 // 2. If not, we've at least simplified things (e.g., we went
726 // from `Vec<$0>: WF` to `$0: WF`), so we can
727 // register a pending obligation and keep
728 // moving. (Goal is that an "inductive hypothesis"
729 // is satisfied to ensure termination.)
730 // See also the comment on `fn obligations`, describing "livelock"
731 // prevention, which happens before this can be reached.
733 let cause = self.cause(traits::WellFormed(None));
734 self.out.push(traits::Obligation::with_depth(
737 self.recursion_depth,
739 ty::Binder::dummy(ty::PredicateKind::WellFormed(ty.into())),
748 #[instrument(level = "debug", skip(self))]
749 fn nominal_obligations_inner(
752 substs: SubstsRef<'tcx>,
753 remap_constness: bool,
754 ) -> Vec<traits::PredicateObligation<'tcx>> {
755 let predicates = self.tcx.predicates_of(def_id);
756 let mut origins = vec![def_id; predicates.predicates.len()];
757 let mut head = predicates;
758 while let Some(parent) = head.parent {
759 head = self.tcx.predicates_of(parent);
760 origins.extend(iter::repeat(parent).take(head.predicates.len()));
763 let predicates = predicates.instantiate(self.tcx, substs);
764 trace!("{:#?}", predicates);
765 debug_assert_eq!(predicates.predicates.len(), origins.len());
767 iter::zip(predicates, origins.into_iter().rev())
768 .map(|((mut pred, span), origin_def_id)| {
769 let code = if span.is_dummy() {
770 traits::ItemObligation(origin_def_id)
772 traits::BindingObligation(origin_def_id, span)
774 let cause = self.cause(code);
776 pred = pred.without_const(self.tcx);
778 traits::Obligation::with_depth(
781 self.recursion_depth,
786 .filter(|pred| !pred.has_escaping_bound_vars())
790 fn nominal_obligations(
793 substs: SubstsRef<'tcx>,
794 ) -> Vec<traits::PredicateObligation<'tcx>> {
795 self.nominal_obligations_inner(def_id, substs, false)
798 fn nominal_obligations_without_const(
801 substs: SubstsRef<'tcx>,
802 ) -> Vec<traits::PredicateObligation<'tcx>> {
803 self.nominal_obligations_inner(def_id, substs, true)
809 data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
810 region: ty::Region<'tcx>,
812 // Imagine a type like this:
815 // trait Bar<'c> : 'c { }
817 // &'b (Foo+'c+Bar<'d>)
820 // In this case, the following relationships must hold:
825 // The first conditions is due to the normal region pointer
826 // rules, which say that a reference cannot outlive its
829 // The final condition may be a bit surprising. In particular,
830 // you may expect that it would have been `'c <= 'd`, since
831 // usually lifetimes of outer things are conservative
832 // approximations for inner things. However, it works somewhat
833 // differently with trait objects: here the idea is that if the
834 // user specifies a region bound (`'c`, in this case) it is the
835 // "master bound" that *implies* that bounds from other traits are
836 // all met. (Remember that *all bounds* in a type like
837 // `Foo+Bar+Zed` must be met, not just one, hence if we write
838 // `Foo<'x>+Bar<'y>`, we know that the type outlives *both* 'x and
841 // Note: in fact we only permit builtin traits, not `Bar<'d>`, I
842 // am looking forward to the future here.
843 if !data.has_escaping_bound_vars() && !region.has_escaping_bound_vars() {
844 let implicit_bounds = object_region_bounds(self.tcx, data);
846 let explicit_bound = region;
848 self.out.reserve(implicit_bounds.len());
849 for implicit_bound in implicit_bounds {
850 let cause = self.cause(traits::ObjectTypeBound(ty, explicit_bound));
852 ty::Binder::dummy(ty::OutlivesPredicate(explicit_bound, implicit_bound));
853 self.out.push(traits::Obligation::with_depth(
856 self.recursion_depth,
865 /// Given an object type like `SomeTrait + Send`, computes the lifetime
866 /// bounds that must hold on the elided self type. These are derived
867 /// from the declarations of `SomeTrait`, `Send`, and friends -- if
868 /// they declare `trait SomeTrait : 'static`, for example, then
869 /// `'static` would appear in the list. The hard work is done by
870 /// `infer::required_region_bounds`, see that for more information.
871 pub fn object_region_bounds<'tcx>(
873 existential_predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
874 ) -> Vec<ty::Region<'tcx>> {
875 // Since we don't actually *know* the self type for an object,
876 // this "open(err)" serves as a kind of dummy standin -- basically
877 // a placeholder type.
878 let open_ty = tcx.mk_ty_infer(ty::FreshTy(0));
880 let predicates = existential_predicates.iter().filter_map(|predicate| {
881 if let ty::ExistentialPredicate::Projection(_) = predicate.skip_binder() {
884 Some(predicate.with_self_ty(tcx, open_ty))
888 required_region_bounds(tcx, open_ty, predicates)
891 /// Given a set of predicates that apply to an object type, returns
892 /// the region bounds that the (erased) `Self` type must
893 /// outlive. Precisely *because* the `Self` type is erased, the
894 /// parameter `erased_self_ty` must be supplied to indicate what type
895 /// has been used to represent `Self` in the predicates
896 /// themselves. This should really be a unique type; `FreshTy(0)` is a
899 /// N.B., in some cases, particularly around higher-ranked bounds,
900 /// this function returns a kind of conservative approximation.
901 /// That is, all regions returned by this function are definitely
902 /// required, but there may be other region bounds that are not
903 /// returned, as well as requirements like `for<'a> T: 'a`.
905 /// Requires that trait definitions have been processed so that we can
906 /// elaborate predicates and walk supertraits.
907 #[instrument(skip(tcx, predicates), level = "debug", ret)]
908 pub(crate) fn required_region_bounds<'tcx>(
910 erased_self_ty: Ty<'tcx>,
911 predicates: impl Iterator<Item = ty::Predicate<'tcx>>,
912 ) -> Vec<ty::Region<'tcx>> {
913 assert!(!erased_self_ty.has_escaping_bound_vars());
915 traits::elaborate_predicates(tcx, predicates)
916 .filter_map(|obligation| {
918 match obligation.predicate.kind().skip_binder() {
919 ty::PredicateKind::Clause(ty::Clause::Projection(..))
920 | ty::PredicateKind::Clause(ty::Clause::Trait(..))
921 | ty::PredicateKind::Subtype(..)
922 | ty::PredicateKind::Coerce(..)
923 | ty::PredicateKind::WellFormed(..)
924 | ty::PredicateKind::ObjectSafe(..)
925 | ty::PredicateKind::ClosureKind(..)
926 | ty::PredicateKind::Clause(ty::Clause::RegionOutlives(..))
927 | ty::PredicateKind::ConstEvaluatable(..)
928 | ty::PredicateKind::ConstEquate(..)
929 | ty::PredicateKind::Ambiguous
930 | ty::PredicateKind::TypeWellFormedFromEnv(..) => None,
931 ty::PredicateKind::Clause(ty::Clause::TypeOutlives(ty::OutlivesPredicate(
935 // Search for a bound of the form `erased_self_ty
936 // : 'a`, but be wary of something like `for<'a>
937 // erased_self_ty : 'a` (we interpret a
938 // higher-ranked bound like that as 'static,
939 // though at present the code in `fulfill.rs`
940 // considers such bounds to be unsatisfiable, so
941 // it's kind of a moot point since you could never
942 // construct such an object, but this seems
943 // correct even if that code changes).
944 if t == &erased_self_ty && !r.has_escaping_bound_vars() {