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, Ty, TyCtxt, TypeVisitable};
11 /// Returns the set of obligations needed to make `arg` well-formed.
12 /// If `arg` contains unresolved inference variables, this may include
13 /// further WF obligations. However, if `arg` IS an unresolved
14 /// inference variable, returns `None`, because we are not able to
15 /// make any progress at all. This is to prevent "livelock" where we
16 /// say "$0 is WF if $0 is WF".
17 pub fn obligations<'tcx>(
18 infcx: &InferCtxt<'tcx>,
19 param_env: ty::ParamEnv<'tcx>,
21 recursion_depth: usize,
22 arg: GenericArg<'tcx>,
24 ) -> Option<Vec<traits::PredicateObligation<'tcx>>> {
25 // Handle the "livelock" case (see comment above) by bailing out if necessary.
26 let arg = match arg.unpack() {
27 GenericArgKind::Type(ty) => {
29 ty::Infer(ty::TyVar(_)) => {
30 let resolved_ty = infcx.shallow_resolve(ty);
31 if resolved_ty == ty {
32 // No progress, bail out to prevent "livelock".
42 GenericArgKind::Const(ct) => {
44 ty::ConstKind::Infer(_) => {
45 let resolved = infcx.shallow_resolve(ct);
57 // There is nothing we have to do for lifetimes.
58 GenericArgKind::Lifetime(..) => return Some(Vec::new()),
61 let mut wf = WfPredicates {
71 debug!("wf::obligations({:?}, body_id={:?}) = {:?}", arg, body_id, wf.out);
73 let result = wf.normalize(infcx);
74 debug!("wf::obligations({:?}, body_id={:?}) ~~> {:?}", arg, body_id, result);
78 /// Returns the obligations that make this trait reference
79 /// well-formed. For example, if there is a trait `Set` defined like
80 /// `trait Set<K:Eq>`, then the trait reference `Foo: Set<Bar>` is WF
82 pub fn trait_obligations<'tcx>(
83 infcx: &InferCtxt<'tcx>,
84 param_env: ty::ParamEnv<'tcx>,
86 trait_pred: &ty::TraitPredicate<'tcx>,
88 item: &'tcx hir::Item<'tcx>,
89 ) -> Vec<traits::PredicateObligation<'tcx>> {
90 let mut wf = WfPredicates {
99 wf.compute_trait_pred(trait_pred, Elaborate::All);
100 debug!(obligations = ?wf.out);
104 #[instrument(skip(infcx), ret)]
105 pub fn predicate_obligations<'tcx>(
106 infcx: &InferCtxt<'tcx>,
107 param_env: ty::ParamEnv<'tcx>,
109 predicate: ty::Predicate<'tcx>,
111 ) -> Vec<traits::PredicateObligation<'tcx>> {
112 let mut wf = WfPredicates {
122 // It's ok to skip the binder here because wf code is prepared for it
123 match predicate.kind().skip_binder() {
124 ty::PredicateKind::Clause(ty::Clause::Trait(t)) => {
125 wf.compute_trait_pred(&t, Elaborate::None);
127 ty::PredicateKind::Clause(ty::Clause::RegionOutlives(..)) => {}
128 ty::PredicateKind::Clause(ty::Clause::TypeOutlives(ty::OutlivesPredicate(ty, _reg))) => {
129 wf.compute(ty.into());
131 ty::PredicateKind::Clause(ty::Clause::Projection(t)) => {
132 wf.compute_projection(t.projection_ty);
133 wf.compute(match t.term.unpack() {
134 ty::TermKind::Ty(ty) => ty.into(),
135 ty::TermKind::Const(c) => c.into(),
138 ty::PredicateKind::WellFormed(arg) => {
141 ty::PredicateKind::ObjectSafe(_) => {}
142 ty::PredicateKind::ClosureKind(..) => {}
143 ty::PredicateKind::Subtype(ty::SubtypePredicate { a, b, a_is_expected: _ }) => {
144 wf.compute(a.into());
145 wf.compute(b.into());
147 ty::PredicateKind::Coerce(ty::CoercePredicate { a, b }) => {
148 wf.compute(a.into());
149 wf.compute(b.into());
151 ty::PredicateKind::ConstEvaluatable(ct) => {
152 wf.compute(ct.into());
154 ty::PredicateKind::ConstEquate(c1, c2) => {
155 wf.compute(c1.into());
156 wf.compute(c2.into());
158 ty::PredicateKind::Ambiguous => {}
159 ty::PredicateKind::TypeWellFormedFromEnv(..) => {
160 bug!("TypeWellFormedFromEnv is only used for Chalk")
167 struct WfPredicates<'tcx> {
169 param_env: ty::ParamEnv<'tcx>,
172 out: Vec<traits::PredicateObligation<'tcx>>,
173 recursion_depth: usize,
174 item: Option<&'tcx hir::Item<'tcx>>,
177 /// Controls whether we "elaborate" supertraits and so forth on the WF
178 /// predicates. This is a kind of hack to address #43784. The
179 /// underlying problem in that issue was a trait structure like:
181 /// ```ignore (illustrative)
182 /// trait Foo: Copy { }
183 /// trait Bar: Foo { }
184 /// impl<T: Bar> Foo for T { }
185 /// impl<T> Bar for T { }
188 /// Here, in the `Foo` impl, we will check that `T: Copy` holds -- but
189 /// we decide that this is true because `T: Bar` is in the
190 /// where-clauses (and we can elaborate that to include `T:
191 /// Copy`). This wouldn't be a problem, except that when we check the
192 /// `Bar` impl, we decide that `T: Foo` must hold because of the `Foo`
193 /// impl. And so nowhere did we check that `T: Copy` holds!
195 /// To resolve this, we elaborate the WF requirements that must be
196 /// proven when checking impls. This means that (e.g.) the `impl Bar
197 /// for T` will be forced to prove not only that `T: Foo` but also `T:
198 /// Copy` (which it won't be able to do, because there is no `Copy`
200 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
206 fn extend_cause_with_original_assoc_item_obligation<'tcx>(
208 trait_ref: &ty::TraitRef<'tcx>,
209 item: Option<&hir::Item<'tcx>>,
210 cause: &mut traits::ObligationCause<'tcx>,
211 pred: ty::Predicate<'tcx>,
214 "extended_cause_with_original_assoc_item_obligation {:?} {:?} {:?} {:?}",
215 trait_ref, item, cause, pred
217 let (items, impl_def_id) = match item {
218 Some(hir::Item { kind: hir::ItemKind::Impl(impl_), owner_id, .. }) => {
219 (impl_.items, *owner_id)
224 |impl_item_ref: &hir::ImplItemRef| match tcx.hir().impl_item(impl_item_ref.id).kind {
225 hir::ImplItemKind::Const(ty, _) | hir::ImplItemKind::Type(ty) => ty.span,
226 _ => impl_item_ref.span,
229 // It is fine to skip the binder as we don't care about regions here.
230 match pred.kind().skip_binder() {
231 ty::PredicateKind::Clause(ty::Clause::Projection(proj)) => {
232 // The obligation comes not from the current `impl` nor the `trait` being implemented,
233 // but rather from a "second order" obligation, where an associated type has a
234 // projection coming from another associated type. See
235 // `src/test/ui/associated-types/point-at-type-on-obligation-failure.rs` and
236 // `traits-assoc-type-in-supertrait-bad.rs`.
237 if let Some(ty::Alias(ty::Projection, projection_ty)) = proj.term.ty().map(|ty| ty.kind())
238 && let Some(&impl_item_id) =
239 tcx.impl_item_implementor_ids(impl_def_id).get(&projection_ty.def_id)
240 && let Some(impl_item_span) = items
242 .find(|item| item.id.owner_id.to_def_id() == impl_item_id)
245 cause.span = impl_item_span;
248 ty::PredicateKind::Clause(ty::Clause::Trait(pred)) => {
249 // An associated item obligation born out of the `trait` failed to be met. An example
250 // can be seen in `ui/associated-types/point-at-type-on-obligation-failure-2.rs`.
251 debug!("extended_cause_with_original_assoc_item_obligation trait proj {:?}", pred);
252 if let ty::Alias(ty::Projection, ty::AliasTy { def_id, .. }) = *pred.self_ty().kind()
253 && let Some(&impl_item_id) =
254 tcx.impl_item_implementor_ids(impl_def_id).get(&def_id)
255 && let Some(impl_item_span) = items
257 .find(|item| item.id.owner_id.to_def_id() == impl_item_id)
260 cause.span = impl_item_span;
267 impl<'tcx> WfPredicates<'tcx> {
268 fn tcx(&self) -> TyCtxt<'tcx> {
272 fn cause(&self, code: traits::ObligationCauseCode<'tcx>) -> traits::ObligationCause<'tcx> {
273 traits::ObligationCause::new(self.span, self.body_id, code)
276 fn normalize(self, infcx: &InferCtxt<'tcx>) -> Vec<traits::PredicateObligation<'tcx>> {
277 let cause = self.cause(traits::WellFormed(None));
278 let param_env = self.param_env;
279 let mut obligations = Vec::with_capacity(self.out.len());
280 for mut obligation in self.out {
281 assert!(!obligation.has_escaping_bound_vars());
282 let mut selcx = traits::SelectionContext::new(infcx);
283 // Don't normalize the whole obligation, the param env is either
284 // already normalized, or we're currently normalizing the
285 // param_env. Either way we should only normalize the predicate.
286 let normalized_predicate = traits::project::normalize_with_depth_to(
290 self.recursion_depth,
291 obligation.predicate,
294 obligation.predicate = normalized_predicate;
295 obligations.push(obligation);
300 /// Pushes the obligations required for `trait_ref` to be WF into `self.out`.
301 fn compute_trait_pred(&mut self, trait_pred: &ty::TraitPredicate<'tcx>, elaborate: Elaborate) {
303 let trait_ref = &trait_pred.trait_ref;
305 // if the trait predicate is not const, the wf obligations should not be const as well.
306 let obligations = if trait_pred.constness == ty::BoundConstness::NotConst {
307 self.nominal_obligations_without_const(trait_ref.def_id, trait_ref.substs)
309 self.nominal_obligations(trait_ref.def_id, trait_ref.substs)
312 debug!("compute_trait_pred obligations {:?}", obligations);
313 let param_env = self.param_env;
314 let depth = self.recursion_depth;
316 let item = self.item;
318 let extend = |traits::PredicateObligation { predicate, mut cause, .. }| {
319 if let Some(parent_trait_pred) = predicate.to_opt_poly_trait_pred() {
320 cause = cause.derived_cause(
322 traits::ObligationCauseCode::DerivedObligation,
325 extend_cause_with_original_assoc_item_obligation(
326 tcx, trait_ref, item, &mut cause, predicate,
328 traits::Obligation::with_depth(tcx, cause, depth, param_env, predicate)
331 if let Elaborate::All = elaborate {
332 let implied_obligations = traits::util::elaborate_obligations(tcx, obligations);
333 let implied_obligations = implied_obligations.map(extend);
334 self.out.extend(implied_obligations);
336 self.out.extend(obligations);
339 let tcx = self.tcx();
346 matches!(arg.unpack(), GenericArgKind::Type(..) | GenericArgKind::Const(..))
348 .filter(|(_, arg)| !arg.has_escaping_bound_vars())
350 let mut cause = traits::ObligationCause::misc(self.span, self.body_id);
351 // The first subst is the self ty - use the correct span for it.
353 if let Some(hir::ItemKind::Impl(hir::Impl { self_ty, .. })) =
354 item.map(|i| &i.kind)
356 cause.span = self_ty.span;
359 traits::Obligation::with_depth(
364 ty::Binder::dummy(ty::PredicateKind::WellFormed(arg)),
370 /// Pushes the obligations required for `trait_ref::Item` to be WF
372 fn compute_projection(&mut self, data: ty::AliasTy<'tcx>) {
373 // A projection is well-formed if
375 // (a) its predicates hold (*)
376 // (b) its substs are wf
378 // (*) The predicates of an associated type include the predicates of
379 // the trait that it's contained in. For example, given
381 // trait A<T>: Clone {
382 // type X where T: Copy;
385 // The predicates of `<() as A<i32>>::X` are:
394 // Projection types do not require const predicates.
395 let obligations = self.nominal_obligations_without_const(data.def_id, data.substs);
396 self.out.extend(obligations);
398 let tcx = self.tcx();
399 let cause = self.cause(traits::WellFormed(None));
400 let param_env = self.param_env;
401 let depth = self.recursion_depth;
407 matches!(arg.unpack(), GenericArgKind::Type(..) | GenericArgKind::Const(..))
409 .filter(|arg| !arg.has_escaping_bound_vars())
411 traits::Obligation::with_depth(
416 ty::Binder::dummy(ty::PredicateKind::WellFormed(arg)),
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 = self.tcx.at(cause.span).mk_trait_ref(LangItem::Sized, [subty]);
426 self.out.push(traits::Obligation::with_depth(
429 self.recursion_depth,
431 ty::Binder::dummy(trait_ref).without_const(),
436 /// Pushes all the predicates needed to validate that `ty` is WF into `out`.
437 #[instrument(level = "debug", skip(self))]
438 fn compute(&mut self, arg: GenericArg<'tcx>) {
439 let mut walker = arg.walk();
440 let param_env = self.param_env;
441 let depth = self.recursion_depth;
442 while let Some(arg) = walker.next() {
443 debug!(?arg, ?self.out);
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(ct) => {
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(ct));
459 let cause = self.cause(traits::WellFormed(None));
460 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(
474 self.recursion_depth,
476 ty::Binder::dummy(ty::PredicateKind::WellFormed(ct.into())),
479 ty::ConstKind::Expr(_) => {
480 // FIXME(generic_const_exprs): this doesnt verify that given `Expr(N + 1)` the
481 // trait bound `typeof(N): Add<typeof(1)>` holds. This is currently unnecessary
482 // as `ConstKind::Expr` is only produced via normalization of `ConstKind::Unevaluated`
483 // which means that the `DefId` would have been typeck'd elsewhere. However in
484 // the future we may allow directly lowering to `ConstKind::Expr` in which case
485 // we would not be proving bounds we should.
488 ty::Binder::dummy(ty::PredicateKind::ConstEvaluatable(ct));
489 let cause = self.cause(traits::WellFormed(None));
490 self.out.push(traits::Obligation::with_depth(
493 self.recursion_depth,
499 ty::ConstKind::Error(_)
500 | ty::ConstKind::Param(_)
501 | ty::ConstKind::Bound(..)
502 | ty::ConstKind::Placeholder(..) => {
503 // These variants are trivially WF, so nothing to do here.
505 ty::ConstKind::Value(..) => {
506 // FIXME: Enforce that values are structurally-matchable.
513 debug!("wf bounds for ty={:?} ty.kind={:#?}", ty, ty.kind());
523 | ty::GeneratorWitness(..)
527 | ty::Placeholder(..)
528 | ty::Foreign(..) => {
529 // WfScalar, WfParameter, etc
532 // Can only infer to `ty::Int(_) | ty::Uint(_)`.
533 ty::Infer(ty::IntVar(_)) => {}
535 // Can only infer to `ty::Float(_)`.
536 ty::Infer(ty::FloatVar(_)) => {}
538 ty::Slice(subty) => {
539 self.require_sized(subty, traits::SliceOrArrayElem);
542 ty::Array(subty, _) => {
543 self.require_sized(subty, traits::SliceOrArrayElem);
544 // Note that we handle the len is implicitly checked while walking `arg`.
547 ty::Tuple(ref tys) => {
548 if let Some((_last, rest)) = tys.split_last() {
550 self.require_sized(elem, traits::TupleElem);
556 // Simple cases that are WF if their type args are WF.
559 ty::Alias(ty::Projection, data) => {
560 walker.skip_current_subtree(); // Subtree handled by compute_projection.
561 self.compute_projection(data);
564 ty::Adt(def, substs) => {
566 let obligations = self.nominal_obligations(def.did(), substs);
567 self.out.extend(obligations);
570 ty::FnDef(did, substs) => {
571 let obligations = self.nominal_obligations_without_const(did, substs);
572 self.out.extend(obligations);
575 ty::Ref(r, rty, _) => {
577 if !r.has_escaping_bound_vars() && !rty.has_escaping_bound_vars() {
578 let cause = self.cause(traits::ReferenceOutlivesReferent(ty));
579 self.out.push(traits::Obligation::with_depth(
584 ty::Binder::dummy(ty::PredicateKind::Clause(ty::Clause::TypeOutlives(
585 ty::OutlivesPredicate(rty, r),
591 ty::Generator(did, substs, ..) => {
592 // Walk ALL the types in the generator: this will
593 // include the upvar types as well as the yield
594 // type. Note that this is mildly distinct from
595 // the closure case, where we have to be careful
596 // about the signature of the closure. We don't
597 // have the problem of implied bounds here since
598 // generators don't take arguments.
599 let obligations = self.nominal_obligations(did, substs);
600 self.out.extend(obligations);
603 ty::Closure(did, substs) => {
604 // Only check the upvar types for WF, not the rest
605 // of the types within. This is needed because we
606 // capture the signature and it may not be WF
607 // without the implied bounds. Consider a closure
608 // like `|x: &'a T|` -- it may be that `T: 'a` is
609 // not known to hold in the creator's context (and
610 // indeed the closure may not be invoked by its
611 // creator, but rather turned to someone who *can*
614 // The special treatment of closures here really
615 // ought not to be necessary either; the problem
616 // is related to #25860 -- there is no way for us
617 // to express a fn type complete with the implied
618 // bounds that it is assuming. I think in reality
619 // the WF rules around fn are a bit messed up, and
620 // that is the rot problem: `fn(&'a T)` should
621 // probably always be WF, because it should be
622 // shorthand for something like `where(T: 'a) {
623 // fn(&'a T) }`, as discussed in #25860.
624 walker.skip_current_subtree(); // subtree handled below
625 // FIXME(eddyb) add the type to `walker` instead of recursing.
626 self.compute(substs.as_closure().tupled_upvars_ty().into());
627 // Note that we cannot skip the generic types
628 // types. Normally, within the fn
629 // body where they are created, the generics will
630 // always be WF, and outside of that fn body we
631 // are not directly inspecting closure types
632 // anyway, except via auto trait matching (which
633 // only inspects the upvar types).
634 // But when a closure is part of a type-alias-impl-trait
635 // then the function that created the defining site may
636 // have had more bounds available than the type alias
637 // specifies. This may cause us to have a closure in the
638 // hidden type that is not actually well formed and
639 // can cause compiler crashes when the user abuses unsafe
640 // code to procure such a closure.
641 // See src/test/ui/type-alias-impl-trait/wf_check_closures.rs
642 let obligations = self.nominal_obligations(did, substs);
643 self.out.extend(obligations);
647 // let the loop iterate into the argument/return
648 // types appearing in the fn signature
651 ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) => {
652 // All of the requirements on type parameters
653 // have already been checked for `impl Trait` in
654 // return position. We do need to check type-alias-impl-trait though.
655 if ty::is_impl_trait_defn(self.tcx, def_id).is_none() {
656 let obligations = self.nominal_obligations(def_id, substs);
657 self.out.extend(obligations);
661 ty::Dynamic(data, r, _) => {
664 // Here, we defer WF checking due to higher-ranked
665 // regions. This is perhaps not ideal.
666 self.from_object_ty(ty, data, r);
668 // FIXME(#27579) RFC also considers adding trait
669 // obligations that don't refer to Self and
672 let defer_to_coercion = self.tcx().features().object_safe_for_dispatch;
674 if !defer_to_coercion {
675 let cause = self.cause(traits::WellFormed(None));
676 let component_traits = data.auto_traits().chain(data.principal_def_id());
677 let tcx = self.tcx();
678 self.out.extend(component_traits.map(|did| {
679 traits::Obligation::with_depth(
684 ty::Binder::dummy(ty::PredicateKind::ObjectSafe(did)),
690 // Inference variables are the complicated case, since we don't
691 // know what type they are. We do two things:
693 // 1. Check if they have been resolved, and if so proceed with
695 // 2. If not, we've at least simplified things (e.g., we went
696 // from `Vec<$0>: WF` to `$0: WF`), so we can
697 // register a pending obligation and keep
698 // moving. (Goal is that an "inductive hypothesis"
699 // is satisfied to ensure termination.)
700 // See also the comment on `fn obligations`, describing "livelock"
701 // prevention, which happens before this can be reached.
703 let cause = self.cause(traits::WellFormed(None));
704 self.out.push(traits::Obligation::with_depth(
707 self.recursion_depth,
709 ty::Binder::dummy(ty::PredicateKind::WellFormed(ty.into())),
718 #[instrument(level = "debug", skip(self))]
719 fn nominal_obligations_inner(
722 substs: SubstsRef<'tcx>,
723 remap_constness: bool,
724 ) -> Vec<traits::PredicateObligation<'tcx>> {
725 let predicates = self.tcx.predicates_of(def_id);
726 let mut origins = vec![def_id; predicates.predicates.len()];
727 let mut head = predicates;
728 while let Some(parent) = head.parent {
729 head = self.tcx.predicates_of(parent);
730 origins.extend(iter::repeat(parent).take(head.predicates.len()));
733 let predicates = predicates.instantiate(self.tcx, substs);
734 trace!("{:#?}", predicates);
735 debug_assert_eq!(predicates.predicates.len(), origins.len());
737 iter::zip(iter::zip(predicates.predicates, predicates.spans), origins.into_iter().rev())
738 .map(|((mut pred, span), origin_def_id)| {
739 let code = if span.is_dummy() {
740 traits::ItemObligation(origin_def_id)
742 traits::BindingObligation(origin_def_id, span)
744 let cause = self.cause(code);
746 pred = pred.without_const(self.tcx);
748 traits::Obligation::with_depth(
751 self.recursion_depth,
756 .filter(|pred| !pred.has_escaping_bound_vars())
760 fn nominal_obligations(
763 substs: SubstsRef<'tcx>,
764 ) -> Vec<traits::PredicateObligation<'tcx>> {
765 self.nominal_obligations_inner(def_id, substs, false)
768 fn nominal_obligations_without_const(
771 substs: SubstsRef<'tcx>,
772 ) -> Vec<traits::PredicateObligation<'tcx>> {
773 self.nominal_obligations_inner(def_id, substs, true)
779 data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
780 region: ty::Region<'tcx>,
782 // Imagine a type like this:
785 // trait Bar<'c> : 'c { }
787 // &'b (Foo+'c+Bar<'d>)
790 // In this case, the following relationships must hold:
795 // The first conditions is due to the normal region pointer
796 // rules, which say that a reference cannot outlive its
799 // The final condition may be a bit surprising. In particular,
800 // you may expect that it would have been `'c <= 'd`, since
801 // usually lifetimes of outer things are conservative
802 // approximations for inner things. However, it works somewhat
803 // differently with trait objects: here the idea is that if the
804 // user specifies a region bound (`'c`, in this case) it is the
805 // "master bound" that *implies* that bounds from other traits are
806 // all met. (Remember that *all bounds* in a type like
807 // `Foo+Bar+Zed` must be met, not just one, hence if we write
808 // `Foo<'x>+Bar<'y>`, we know that the type outlives *both* 'x and
811 // Note: in fact we only permit builtin traits, not `Bar<'d>`, I
812 // am looking forward to the future here.
813 if !data.has_escaping_bound_vars() && !region.has_escaping_bound_vars() {
814 let implicit_bounds = object_region_bounds(self.tcx, data);
816 let explicit_bound = region;
818 self.out.reserve(implicit_bounds.len());
819 for implicit_bound in implicit_bounds {
820 let cause = self.cause(traits::ObjectTypeBound(ty, explicit_bound));
822 ty::Binder::dummy(ty::OutlivesPredicate(explicit_bound, implicit_bound));
823 self.out.push(traits::Obligation::with_depth(
826 self.recursion_depth,
835 /// Given an object type like `SomeTrait + Send`, computes the lifetime
836 /// bounds that must hold on the elided self type. These are derived
837 /// from the declarations of `SomeTrait`, `Send`, and friends -- if
838 /// they declare `trait SomeTrait : 'static`, for example, then
839 /// `'static` would appear in the list. The hard work is done by
840 /// `infer::required_region_bounds`, see that for more information.
841 pub fn object_region_bounds<'tcx>(
843 existential_predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
844 ) -> Vec<ty::Region<'tcx>> {
845 // Since we don't actually *know* the self type for an object,
846 // this "open(err)" serves as a kind of dummy standin -- basically
847 // a placeholder type.
848 let open_ty = tcx.mk_ty_infer(ty::FreshTy(0));
850 let predicates = existential_predicates.iter().filter_map(|predicate| {
851 if let ty::ExistentialPredicate::Projection(_) = predicate.skip_binder() {
854 Some(predicate.with_self_ty(tcx, open_ty))
858 required_region_bounds(tcx, open_ty, predicates)
861 /// Given a set of predicates that apply to an object type, returns
862 /// the region bounds that the (erased) `Self` type must
863 /// outlive. Precisely *because* the `Self` type is erased, the
864 /// parameter `erased_self_ty` must be supplied to indicate what type
865 /// has been used to represent `Self` in the predicates
866 /// themselves. This should really be a unique type; `FreshTy(0)` is a
869 /// N.B., in some cases, particularly around higher-ranked bounds,
870 /// this function returns a kind of conservative approximation.
871 /// That is, all regions returned by this function are definitely
872 /// required, but there may be other region bounds that are not
873 /// returned, as well as requirements like `for<'a> T: 'a`.
875 /// Requires that trait definitions have been processed so that we can
876 /// elaborate predicates and walk supertraits.
877 #[instrument(skip(tcx, predicates), level = "debug", ret)]
878 pub(crate) fn required_region_bounds<'tcx>(
880 erased_self_ty: Ty<'tcx>,
881 predicates: impl Iterator<Item = ty::Predicate<'tcx>>,
882 ) -> Vec<ty::Region<'tcx>> {
883 assert!(!erased_self_ty.has_escaping_bound_vars());
885 traits::elaborate_predicates(tcx, predicates)
886 .filter_map(|obligation| {
888 match obligation.predicate.kind().skip_binder() {
889 ty::PredicateKind::Clause(ty::Clause::Projection(..))
890 | ty::PredicateKind::Clause(ty::Clause::Trait(..))
891 | ty::PredicateKind::Subtype(..)
892 | ty::PredicateKind::Coerce(..)
893 | ty::PredicateKind::WellFormed(..)
894 | ty::PredicateKind::ObjectSafe(..)
895 | ty::PredicateKind::ClosureKind(..)
896 | ty::PredicateKind::Clause(ty::Clause::RegionOutlives(..))
897 | ty::PredicateKind::ConstEvaluatable(..)
898 | ty::PredicateKind::ConstEquate(..)
899 | ty::PredicateKind::Ambiguous
900 | ty::PredicateKind::TypeWellFormedFromEnv(..) => None,
901 ty::PredicateKind::Clause(ty::Clause::TypeOutlives(ty::OutlivesPredicate(
905 // Search for a bound of the form `erased_self_ty
906 // : 'a`, but be wary of something like `for<'a>
907 // erased_self_ty : 'a` (we interpret a
908 // higher-ranked bound like that as 'static,
909 // though at present the code in `fulfill.rs`
910 // considers such bounds to be unsatisfiable, so
911 // it's kind of a moot point since you could never
912 // construct such an object, but this seems
913 // correct even if that code changes).
914 if t == &erased_self_ty && !r.has_escaping_bound_vars() {