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(..)
554 | ty::GeneratorWitnessMIR(..)
558 | ty::Placeholder(..)
559 | ty::Foreign(..) => {
560 // WfScalar, WfParameter, etc
563 // Can only infer to `ty::Int(_) | ty::Uint(_)`.
564 ty::Infer(ty::IntVar(_)) => {}
566 // Can only infer to `ty::Float(_)`.
567 ty::Infer(ty::FloatVar(_)) => {}
569 ty::Slice(subty) => {
570 self.require_sized(subty, traits::SliceOrArrayElem);
573 ty::Array(subty, _) => {
574 self.require_sized(subty, traits::SliceOrArrayElem);
575 // Note that we handle the len is implicitly checked while walking `arg`.
578 ty::Tuple(ref tys) => {
579 if let Some((_last, rest)) = tys.split_last() {
581 self.require_sized(elem, traits::TupleElem);
587 // Simple cases that are WF if their type args are WF.
590 ty::Alias(ty::Projection, data) => {
591 walker.skip_current_subtree(); // Subtree handled by compute_projection.
592 self.compute_projection(data);
595 ty::Adt(def, substs) => {
597 let obligations = self.nominal_obligations(def.did(), substs);
598 self.out.extend(obligations);
601 ty::FnDef(did, substs) => {
602 let obligations = self.nominal_obligations_without_const(did, substs);
603 self.out.extend(obligations);
606 ty::Ref(r, rty, _) => {
608 if !r.has_escaping_bound_vars() && !rty.has_escaping_bound_vars() {
609 let cause = self.cause(traits::ReferenceOutlivesReferent(ty));
610 self.out.push(traits::Obligation::with_depth(
615 ty::Binder::dummy(ty::PredicateKind::Clause(ty::Clause::TypeOutlives(
616 ty::OutlivesPredicate(rty, r),
622 ty::Generator(did, substs, ..) => {
623 // Walk ALL the types in the generator: this will
624 // include the upvar types as well as the yield
625 // type. Note that this is mildly distinct from
626 // the closure case, where we have to be careful
627 // about the signature of the closure. We don't
628 // have the problem of implied bounds here since
629 // generators don't take arguments.
630 let obligations = self.nominal_obligations(did, substs);
631 self.out.extend(obligations);
634 ty::Closure(did, substs) => {
635 // Only check the upvar types for WF, not the rest
636 // of the types within. This is needed because we
637 // capture the signature and it may not be WF
638 // without the implied bounds. Consider a closure
639 // like `|x: &'a T|` -- it may be that `T: 'a` is
640 // not known to hold in the creator's context (and
641 // indeed the closure may not be invoked by its
642 // creator, but rather turned to someone who *can*
645 // The special treatment of closures here really
646 // ought not to be necessary either; the problem
647 // is related to #25860 -- there is no way for us
648 // to express a fn type complete with the implied
649 // bounds that it is assuming. I think in reality
650 // the WF rules around fn are a bit messed up, and
651 // that is the rot problem: `fn(&'a T)` should
652 // probably always be WF, because it should be
653 // shorthand for something like `where(T: 'a) {
654 // fn(&'a T) }`, as discussed in #25860.
655 walker.skip_current_subtree(); // subtree handled below
656 // FIXME(eddyb) add the type to `walker` instead of recursing.
657 self.compute(substs.as_closure().tupled_upvars_ty().into());
658 // Note that we cannot skip the generic types
659 // types. Normally, within the fn
660 // body where they are created, the generics will
661 // always be WF, and outside of that fn body we
662 // are not directly inspecting closure types
663 // anyway, except via auto trait matching (which
664 // only inspects the upvar types).
665 // But when a closure is part of a type-alias-impl-trait
666 // then the function that created the defining site may
667 // have had more bounds available than the type alias
668 // specifies. This may cause us to have a closure in the
669 // hidden type that is not actually well formed and
670 // can cause compiler crashes when the user abuses unsafe
671 // code to procure such a closure.
672 // See tests/ui/type-alias-impl-trait/wf_check_closures.rs
673 let obligations = self.nominal_obligations(did, substs);
674 self.out.extend(obligations);
678 // let the loop iterate into the argument/return
679 // types appearing in the fn signature
682 ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) => {
683 // All of the requirements on type parameters
684 // have already been checked for `impl Trait` in
685 // return position. We do need to check type-alias-impl-trait though.
686 if self.tcx.is_type_alias_impl_trait(def_id) {
687 let obligations = self.nominal_obligations(def_id, substs);
688 self.out.extend(obligations);
692 ty::Dynamic(data, r, _) => {
695 // Here, we defer WF checking due to higher-ranked
696 // regions. This is perhaps not ideal.
697 self.from_object_ty(ty, data, r);
699 // FIXME(#27579) RFC also considers adding trait
700 // obligations that don't refer to Self and
703 let defer_to_coercion = self.tcx().features().object_safe_for_dispatch;
705 if !defer_to_coercion {
706 let cause = self.cause(traits::WellFormed(None));
707 let component_traits = data.auto_traits().chain(data.principal_def_id());
708 let tcx = self.tcx();
709 self.out.extend(component_traits.map(|did| {
710 traits::Obligation::with_depth(
715 ty::Binder::dummy(ty::PredicateKind::ObjectSafe(did)),
721 // Inference variables are the complicated case, since we don't
722 // know what type they are. We do two things:
724 // 1. Check if they have been resolved, and if so proceed with
726 // 2. If not, we've at least simplified things (e.g., we went
727 // from `Vec<$0>: WF` to `$0: WF`), so we can
728 // register a pending obligation and keep
729 // moving. (Goal is that an "inductive hypothesis"
730 // is satisfied to ensure termination.)
731 // See also the comment on `fn obligations`, describing "livelock"
732 // prevention, which happens before this can be reached.
734 let cause = self.cause(traits::WellFormed(None));
735 self.out.push(traits::Obligation::with_depth(
738 self.recursion_depth,
740 ty::Binder::dummy(ty::PredicateKind::WellFormed(ty.into())),
749 #[instrument(level = "debug", skip(self))]
750 fn nominal_obligations_inner(
753 substs: SubstsRef<'tcx>,
754 remap_constness: bool,
755 ) -> Vec<traits::PredicateObligation<'tcx>> {
756 let predicates = self.tcx.predicates_of(def_id);
757 let mut origins = vec![def_id; predicates.predicates.len()];
758 let mut head = predicates;
759 while let Some(parent) = head.parent {
760 head = self.tcx.predicates_of(parent);
761 origins.extend(iter::repeat(parent).take(head.predicates.len()));
764 let predicates = predicates.instantiate(self.tcx, substs);
765 trace!("{:#?}", predicates);
766 debug_assert_eq!(predicates.predicates.len(), origins.len());
768 iter::zip(predicates, origins.into_iter().rev())
769 .map(|((mut pred, span), origin_def_id)| {
770 let code = if span.is_dummy() {
771 traits::ItemObligation(origin_def_id)
773 traits::BindingObligation(origin_def_id, span)
775 let cause = self.cause(code);
777 pred = pred.without_const(self.tcx);
779 traits::Obligation::with_depth(
782 self.recursion_depth,
787 .filter(|pred| !pred.has_escaping_bound_vars())
791 fn nominal_obligations(
794 substs: SubstsRef<'tcx>,
795 ) -> Vec<traits::PredicateObligation<'tcx>> {
796 self.nominal_obligations_inner(def_id, substs, false)
799 fn nominal_obligations_without_const(
802 substs: SubstsRef<'tcx>,
803 ) -> Vec<traits::PredicateObligation<'tcx>> {
804 self.nominal_obligations_inner(def_id, substs, true)
810 data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
811 region: ty::Region<'tcx>,
813 // Imagine a type like this:
816 // trait Bar<'c> : 'c { }
818 // &'b (Foo+'c+Bar<'d>)
821 // In this case, the following relationships must hold:
826 // The first conditions is due to the normal region pointer
827 // rules, which say that a reference cannot outlive its
830 // The final condition may be a bit surprising. In particular,
831 // you may expect that it would have been `'c <= 'd`, since
832 // usually lifetimes of outer things are conservative
833 // approximations for inner things. However, it works somewhat
834 // differently with trait objects: here the idea is that if the
835 // user specifies a region bound (`'c`, in this case) it is the
836 // "master bound" that *implies* that bounds from other traits are
837 // all met. (Remember that *all bounds* in a type like
838 // `Foo+Bar+Zed` must be met, not just one, hence if we write
839 // `Foo<'x>+Bar<'y>`, we know that the type outlives *both* 'x and
842 // Note: in fact we only permit builtin traits, not `Bar<'d>`, I
843 // am looking forward to the future here.
844 if !data.has_escaping_bound_vars() && !region.has_escaping_bound_vars() {
845 let implicit_bounds = object_region_bounds(self.tcx, data);
847 let explicit_bound = region;
849 self.out.reserve(implicit_bounds.len());
850 for implicit_bound in implicit_bounds {
851 let cause = self.cause(traits::ObjectTypeBound(ty, explicit_bound));
853 ty::Binder::dummy(ty::OutlivesPredicate(explicit_bound, implicit_bound));
854 self.out.push(traits::Obligation::with_depth(
857 self.recursion_depth,
866 /// Given an object type like `SomeTrait + Send`, computes the lifetime
867 /// bounds that must hold on the elided self type. These are derived
868 /// from the declarations of `SomeTrait`, `Send`, and friends -- if
869 /// they declare `trait SomeTrait : 'static`, for example, then
870 /// `'static` would appear in the list. The hard work is done by
871 /// `infer::required_region_bounds`, see that for more information.
872 pub fn object_region_bounds<'tcx>(
874 existential_predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
875 ) -> Vec<ty::Region<'tcx>> {
876 // Since we don't actually *know* the self type for an object,
877 // this "open(err)" serves as a kind of dummy standin -- basically
878 // a placeholder type.
879 let open_ty = tcx.mk_ty_infer(ty::FreshTy(0));
881 let predicates = existential_predicates.iter().filter_map(|predicate| {
882 if let ty::ExistentialPredicate::Projection(_) = predicate.skip_binder() {
885 Some(predicate.with_self_ty(tcx, open_ty))
889 required_region_bounds(tcx, open_ty, predicates)
892 /// Given a set of predicates that apply to an object type, returns
893 /// the region bounds that the (erased) `Self` type must
894 /// outlive. Precisely *because* the `Self` type is erased, the
895 /// parameter `erased_self_ty` must be supplied to indicate what type
896 /// has been used to represent `Self` in the predicates
897 /// themselves. This should really be a unique type; `FreshTy(0)` is a
900 /// N.B., in some cases, particularly around higher-ranked bounds,
901 /// this function returns a kind of conservative approximation.
902 /// That is, all regions returned by this function are definitely
903 /// required, but there may be other region bounds that are not
904 /// returned, as well as requirements like `for<'a> T: 'a`.
906 /// Requires that trait definitions have been processed so that we can
907 /// elaborate predicates and walk supertraits.
908 #[instrument(skip(tcx, predicates), level = "debug", ret)]
909 pub(crate) fn required_region_bounds<'tcx>(
911 erased_self_ty: Ty<'tcx>,
912 predicates: impl Iterator<Item = ty::Predicate<'tcx>>,
913 ) -> Vec<ty::Region<'tcx>> {
914 assert!(!erased_self_ty.has_escaping_bound_vars());
916 traits::elaborate_predicates(tcx, predicates)
917 .filter_map(|obligation| {
919 match obligation.predicate.kind().skip_binder() {
920 ty::PredicateKind::Clause(ty::Clause::Projection(..))
921 | ty::PredicateKind::Clause(ty::Clause::Trait(..))
922 | ty::PredicateKind::Subtype(..)
923 | ty::PredicateKind::Coerce(..)
924 | ty::PredicateKind::WellFormed(..)
925 | ty::PredicateKind::ObjectSafe(..)
926 | ty::PredicateKind::ClosureKind(..)
927 | ty::PredicateKind::Clause(ty::Clause::RegionOutlives(..))
928 | ty::PredicateKind::ConstEvaluatable(..)
929 | ty::PredicateKind::ConstEquate(..)
930 | ty::PredicateKind::Ambiguous
931 | ty::PredicateKind::TypeWellFormedFromEnv(..) => None,
932 ty::PredicateKind::Clause(ty::Clause::TypeOutlives(ty::OutlivesPredicate(
936 // Search for a bound of the form `erased_self_ty
937 // : 'a`, but be wary of something like `for<'a>
938 // erased_self_ty : 'a` (we interpret a
939 // higher-ranked bound like that as 'static,
940 // though at present the code in `fulfill.rs`
941 // considers such bounds to be unsatisfiable, so
942 // it's kind of a moot point since you could never
943 // construct such an object, but this seems
944 // correct even if that code changes).
945 if t == &erased_self_ty && !r.has_escaping_bound_vars() {