1 use crate::infer::InferCtxt;
2 use crate::opaque_types::required_region_bounds;
5 use rustc_hir::def_id::DefId;
6 use rustc_hir::lang_items;
7 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, SubstsRef};
8 use rustc_middle::ty::{self, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness};
12 /// Returns the set of obligations needed to make `arg` well-formed.
13 /// If `arg` contains unresolved inference variables, this may include
14 /// further WF obligations. However, if `arg` IS an unresolved
15 /// inference variable, returns `None`, because we are not able to
16 /// make any progress at all. This is to prevent "livelock" where we
17 /// say "$0 is WF if $0 is WF".
18 pub fn obligations<'a, 'tcx>(
19 infcx: &InferCtxt<'a, 'tcx>,
20 param_env: ty::ParamEnv<'tcx>,
22 arg: GenericArg<'tcx>,
24 ) -> Option<Vec<traits::PredicateObligation<'tcx>>> {
25 // Handle the "livelock" case (see comment above) by bailing out if necessary.
26 let arg = match arg.unpack() {
27 GenericArgKind::Type(ty) => {
29 ty::Infer(ty::TyVar(_)) => {
30 let resolved_ty = infcx.shallow_resolve(ty);
31 if resolved_ty == ty {
32 // No progress, bail out to prevent "livelock".
42 GenericArgKind::Const(ct) => {
44 ty::ConstKind::Infer(infer) => {
45 let resolved = infcx.shallow_resolve(infer);
46 if resolved == infer {
51 infcx.tcx.mk_const(ty::Const { val: ty::ConstKind::Infer(resolved), ty: ct.ty })
57 // There is nothing we have to do for lifetimes.
58 GenericArgKind::Lifetime(..) => return Some(Vec::new()),
61 let mut wf = WfPredicates { infcx, param_env, body_id, span, out: vec![], item: None };
63 debug!("wf::obligations({:?}, body_id={:?}) = {:?}", arg, body_id, wf.out);
65 let result = wf.normalize();
66 debug!("wf::obligations({:?}, body_id={:?}) ~~> {:?}", arg, body_id, result);
70 /// Returns the obligations that make this trait reference
71 /// well-formed. For example, if there is a trait `Set` defined like
72 /// `trait Set<K:Eq>`, then the trait reference `Foo: Set<Bar>` is WF
74 pub fn trait_obligations<'a, 'tcx>(
75 infcx: &InferCtxt<'a, 'tcx>,
76 param_env: ty::ParamEnv<'tcx>,
78 trait_ref: &ty::TraitRef<'tcx>,
80 item: Option<&'tcx hir::Item<'tcx>>,
81 ) -> Vec<traits::PredicateObligation<'tcx>> {
82 let mut wf = WfPredicates { infcx, param_env, body_id, span, out: vec![], item };
83 wf.compute_trait_ref(trait_ref, Elaborate::All);
87 pub fn predicate_obligations<'a, 'tcx>(
88 infcx: &InferCtxt<'a, 'tcx>,
89 param_env: ty::ParamEnv<'tcx>,
91 predicate: ty::Predicate<'tcx>,
93 ) -> Vec<traits::PredicateObligation<'tcx>> {
94 let mut wf = WfPredicates { infcx, param_env, body_id, span, out: vec![], item: None };
96 // It's ok to skip the binder here because wf code is prepared for it
97 match predicate.skip_binders() {
98 ty::PredicateAtom::Trait(t, _) => {
99 wf.compute_trait_ref(&t.trait_ref, Elaborate::None);
101 ty::PredicateAtom::RegionOutlives(..) => {}
102 ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
103 wf.compute(ty.into());
105 ty::PredicateAtom::Projection(t) => {
106 wf.compute_projection(t.projection_ty);
107 wf.compute(t.ty.into());
109 ty::PredicateAtom::WellFormed(arg) => {
112 ty::PredicateAtom::ObjectSafe(_) => {}
113 ty::PredicateAtom::ClosureKind(..) => {}
114 ty::PredicateAtom::Subtype(ty::SubtypePredicate { a, b, a_is_expected: _ }) => {
115 wf.compute(a.into());
116 wf.compute(b.into());
118 ty::PredicateAtom::ConstEvaluatable(def, substs) => {
119 let obligations = wf.nominal_obligations(def.did, substs);
120 wf.out.extend(obligations);
122 for arg in substs.iter() {
126 ty::PredicateAtom::ConstEquate(c1, c2) => {
127 wf.compute(c1.into());
128 wf.compute(c2.into());
135 struct WfPredicates<'a, 'tcx> {
136 infcx: &'a InferCtxt<'a, 'tcx>,
137 param_env: ty::ParamEnv<'tcx>,
140 out: Vec<traits::PredicateObligation<'tcx>>,
141 item: Option<&'tcx hir::Item<'tcx>>,
144 /// Controls whether we "elaborate" supertraits and so forth on the WF
145 /// predicates. This is a kind of hack to address #43784. The
146 /// underlying problem in that issue was a trait structure like:
149 /// trait Foo: Copy { }
150 /// trait Bar: Foo { }
151 /// impl<T: Bar> Foo for T { }
152 /// impl<T> Bar for T { }
155 /// Here, in the `Foo` impl, we will check that `T: Copy` holds -- but
156 /// we decide that this is true because `T: Bar` is in the
157 /// where-clauses (and we can elaborate that to include `T:
158 /// Copy`). This wouldn't be a problem, except that when we check the
159 /// `Bar` impl, we decide that `T: Foo` must hold because of the `Foo`
160 /// impl. And so nowhere did we check that `T: Copy` holds!
162 /// To resolve this, we elaborate the WF requirements that must be
163 /// proven when checking impls. This means that (e.g.) the `impl Bar
164 /// for T` will be forced to prove not only that `T: Foo` but also `T:
165 /// Copy` (which it won't be able to do, because there is no `Copy`
167 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
173 fn extend_cause_with_original_assoc_item_obligation<'tcx>(
175 trait_ref: &ty::TraitRef<'tcx>,
176 item: Option<&hir::Item<'tcx>>,
177 cause: &mut traits::ObligationCause<'tcx>,
178 pred: &ty::Predicate<'tcx>,
179 mut trait_assoc_items: impl Iterator<Item = &'tcx ty::AssocItem>,
182 "extended_cause_with_original_assoc_item_obligation {:?} {:?} {:?} {:?}",
183 trait_ref, item, cause, pred
185 let items = match item {
186 Some(hir::Item { kind: hir::ItemKind::Impl { items, .. }, .. }) => items,
190 |impl_item_ref: &hir::ImplItemRef<'_>| match tcx.hir().impl_item(impl_item_ref.id).kind {
191 hir::ImplItemKind::Const(ty, _) | hir::ImplItemKind::TyAlias(ty) => ty.span,
192 _ => impl_item_ref.span,
195 // It is fine to skip the binder as we don't care about regions here.
196 match pred.skip_binders() {
197 ty::PredicateAtom::Projection(proj) => {
198 // The obligation comes not from the current `impl` nor the `trait` being implemented,
199 // but rather from a "second order" obligation, where an associated type has a
200 // projection coming from another associated type. See
201 // `src/test/ui/associated-types/point-at-type-on-obligation-failure.rs` and
202 // `traits-assoc-type-in-supertrait-bad.rs`.
203 if let ty::Projection(projection_ty) = proj.ty.kind {
204 let trait_assoc_item = tcx.associated_item(projection_ty.item_def_id);
205 if let Some(impl_item_span) =
206 items.iter().find(|item| item.ident == trait_assoc_item.ident).map(fix_span)
208 cause.make_mut().span = impl_item_span;
212 ty::PredicateAtom::Trait(pred, _) => {
213 // An associated item obligation born out of the `trait` failed to be met. An example
214 // can be seen in `ui/associated-types/point-at-type-on-obligation-failure-2.rs`.
215 debug!("extended_cause_with_original_assoc_item_obligation trait proj {:?}", pred);
216 if let ty::Projection(ty::ProjectionTy { item_def_id, .. }) = pred.self_ty().kind {
217 if let Some(impl_item_span) = trait_assoc_items
218 .find(|i| i.def_id == item_def_id)
219 .and_then(|trait_assoc_item| {
220 items.iter().find(|i| i.ident == trait_assoc_item.ident).map(fix_span)
223 cause.make_mut().span = impl_item_span;
231 impl<'a, 'tcx> WfPredicates<'a, 'tcx> {
232 fn tcx(&self) -> TyCtxt<'tcx> {
236 fn cause(&self, code: traits::ObligationCauseCode<'tcx>) -> traits::ObligationCause<'tcx> {
237 traits::ObligationCause::new(self.span, self.body_id, code)
240 fn normalize(&mut self) -> Vec<traits::PredicateObligation<'tcx>> {
241 let cause = self.cause(traits::MiscObligation);
242 let infcx = &mut self.infcx;
243 let param_env = self.param_env;
244 let mut obligations = Vec::with_capacity(self.out.len());
245 for pred in &self.out {
246 assert!(!pred.has_escaping_bound_vars());
247 let mut selcx = traits::SelectionContext::new(infcx);
248 let i = obligations.len();
250 traits::normalize_to(&mut selcx, param_env, cause.clone(), pred, &mut obligations);
251 obligations.insert(i, value);
256 /// Pushes the obligations required for `trait_ref` to be WF into `self.out`.
257 fn compute_trait_ref(&mut self, trait_ref: &ty::TraitRef<'tcx>, elaborate: Elaborate) {
258 let tcx = self.infcx.tcx;
259 let obligations = self.nominal_obligations(trait_ref.def_id, trait_ref.substs);
261 debug!("compute_trait_ref obligations {:?}", obligations);
262 let cause = self.cause(traits::MiscObligation);
263 let param_env = self.param_env;
265 let item = self.item;
267 let extend = |obligation: traits::PredicateObligation<'tcx>| {
268 let mut cause = cause.clone();
269 if let Some(parent_trait_ref) = obligation.predicate.to_opt_poly_trait_ref() {
270 let derived_cause = traits::DerivedObligationCause {
272 parent_code: Rc::new(obligation.cause.code.clone()),
274 cause.make_mut().code =
275 traits::ObligationCauseCode::DerivedObligation(derived_cause);
277 extend_cause_with_original_assoc_item_obligation(
282 &obligation.predicate,
283 tcx.associated_items(trait_ref.def_id).in_definition_order(),
285 traits::Obligation::new(cause, param_env, obligation.predicate)
288 if let Elaborate::All = elaborate {
289 let implied_obligations = traits::util::elaborate_obligations(tcx, obligations);
290 let implied_obligations = implied_obligations.map(extend);
291 self.out.extend(implied_obligations);
293 self.out.extend(obligations);
296 let tcx = self.tcx();
303 matches!(arg.unpack(), GenericArgKind::Type(..) | GenericArgKind::Const(..))
305 .filter(|(_, arg)| !arg.has_escaping_bound_vars())
307 let mut new_cause = cause.clone();
308 // The first subst is the self ty - use the correct span for it.
310 if let Some(hir::ItemKind::Impl { self_ty, .. }) = item.map(|i| &i.kind) {
311 new_cause.make_mut().span = self_ty.span;
314 traits::Obligation::new(
317 ty::PredicateAtom::WellFormed(arg).to_predicate(tcx),
323 /// Pushes the obligations required for `trait_ref::Item` to be WF
325 fn compute_projection(&mut self, data: ty::ProjectionTy<'tcx>) {
326 // A projection is well-formed if (a) the trait ref itself is
327 // WF and (b) the trait-ref holds. (It may also be
328 // normalizable and be WF that way.)
329 let trait_ref = data.trait_ref(self.infcx.tcx);
330 self.compute_trait_ref(&trait_ref, Elaborate::None);
332 if !data.has_escaping_bound_vars() {
333 let predicate = trait_ref.without_const().to_predicate(self.infcx.tcx);
334 let cause = self.cause(traits::ProjectionWf(data));
335 self.out.push(traits::Obligation::new(cause, self.param_env, predicate));
339 fn require_sized(&mut self, subty: Ty<'tcx>, cause: traits::ObligationCauseCode<'tcx>) {
340 if !subty.has_escaping_bound_vars() {
341 let cause = self.cause(cause);
342 let trait_ref = ty::TraitRef {
343 def_id: self.infcx.tcx.require_lang_item(lang_items::SizedTraitLangItem, None),
344 substs: self.infcx.tcx.mk_substs_trait(subty, &[]),
346 self.out.push(traits::Obligation::new(
349 trait_ref.without_const().to_predicate(self.infcx.tcx),
354 /// Pushes all the predicates needed to validate that `ty` is WF into `out`.
355 fn compute(&mut self, arg: GenericArg<'tcx>) {
356 let mut walker = arg.walk();
357 let param_env = self.param_env;
358 while let Some(arg) = walker.next() {
359 let ty = match arg.unpack() {
360 GenericArgKind::Type(ty) => ty,
362 // No WF constraints for lifetimes being present, any outlives
363 // obligations are handled by the parent (e.g. `ty::Ref`).
364 GenericArgKind::Lifetime(_) => continue,
366 GenericArgKind::Const(constant) => {
368 ty::ConstKind::Unevaluated(def, substs, promoted) => {
369 assert!(promoted.is_none());
371 let obligations = self.nominal_obligations(def.did, substs);
372 self.out.extend(obligations);
374 let predicate = ty::PredicateAtom::ConstEvaluatable(def, substs)
375 .to_predicate(self.tcx());
376 let cause = self.cause(traits::MiscObligation);
377 self.out.push(traits::Obligation::new(
383 ty::ConstKind::Infer(infer) => {
384 let resolved = self.infcx.shallow_resolve(infer);
385 // the `InferConst` changed, meaning that we made progress.
386 if resolved != infer {
387 let cause = self.cause(traits::MiscObligation);
389 let resolved_constant = self.infcx.tcx.mk_const(ty::Const {
390 val: ty::ConstKind::Infer(resolved),
393 self.out.push(traits::Obligation::new(
396 ty::PredicateAtom::WellFormed(resolved_constant.into())
397 .to_predicate(self.tcx()),
401 ty::ConstKind::Error(_)
402 | ty::ConstKind::Param(_)
403 | ty::ConstKind::Bound(..)
404 | ty::ConstKind::Placeholder(..) => {
405 // These variants are trivially WF, so nothing to do here.
407 ty::ConstKind::Value(..) => {
408 // FIXME: Enforce that values are structurally-matchable.
423 | ty::GeneratorWitness(..)
427 | ty::Placeholder(..)
428 | ty::Foreign(..) => {
429 // WfScalar, WfParameter, etc
432 // Can only infer to `ty::Int(_) | ty::Uint(_)`.
433 ty::Infer(ty::IntVar(_)) => {}
435 // Can only infer to `ty::Float(_)`.
436 ty::Infer(ty::FloatVar(_)) => {}
438 ty::Slice(subty) => {
439 self.require_sized(subty, traits::SliceOrArrayElem);
442 ty::Array(subty, _) => {
443 self.require_sized(subty, traits::SliceOrArrayElem);
444 // Note that we handle the len is implicitly checked while walking `arg`.
447 ty::Tuple(ref tys) => {
448 if let Some((_last, rest)) = tys.split_last() {
450 self.require_sized(elem.expect_ty(), traits::TupleElem);
456 // Simple cases that are WF if their type args are WF.
459 ty::Projection(data) => {
460 walker.skip_current_subtree(); // Subtree handled by compute_projection.
461 self.compute_projection(data);
464 ty::Adt(def, substs) => {
466 let obligations = self.nominal_obligations(def.did, substs);
467 self.out.extend(obligations);
470 ty::FnDef(did, substs) => {
471 let obligations = self.nominal_obligations(did, substs);
472 self.out.extend(obligations);
475 ty::Ref(r, rty, _) => {
477 if !r.has_escaping_bound_vars() && !rty.has_escaping_bound_vars() {
478 let cause = self.cause(traits::ReferenceOutlivesReferent(ty));
479 self.out.push(traits::Obligation::new(
482 ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(rty, r))
483 .to_predicate(self.tcx()),
488 ty::Generator(..) => {
489 // Walk ALL the types in the generator: this will
490 // include the upvar types as well as the yield
491 // type. Note that this is mildly distinct from
492 // the closure case, where we have to be careful
493 // about the signature of the closure. We don't
494 // have the problem of implied bounds here since
495 // generators don't take arguments.
498 ty::Closure(_, substs) => {
499 // Only check the upvar types for WF, not the rest
500 // of the types within. This is needed because we
501 // capture the signature and it may not be WF
502 // without the implied bounds. Consider a closure
503 // like `|x: &'a T|` -- it may be that `T: 'a` is
504 // not known to hold in the creator's context (and
505 // indeed the closure may not be invoked by its
506 // creator, but rather turned to someone who *can*
509 // The special treatment of closures here really
510 // ought not to be necessary either; the problem
511 // is related to #25860 -- there is no way for us
512 // to express a fn type complete with the implied
513 // bounds that it is assuming. I think in reality
514 // the WF rules around fn are a bit messed up, and
515 // that is the rot problem: `fn(&'a T)` should
516 // probably always be WF, because it should be
517 // shorthand for something like `where(T: 'a) {
518 // fn(&'a T) }`, as discussed in #25860.
520 // Note that we are also skipping the generic
521 // types. This is consistent with the `outlives`
522 // code, but anyway doesn't matter: within the fn
523 // body where they are created, the generics will
524 // always be WF, and outside of that fn body we
525 // are not directly inspecting closure types
526 // anyway, except via auto trait matching (which
527 // only inspects the upvar types).
528 walker.skip_current_subtree(); // subtree handled below
529 for upvar_ty in substs.as_closure().upvar_tys() {
530 // FIXME(eddyb) add the type to `walker` instead of recursing.
531 self.compute(upvar_ty.into());
536 // let the loop iterate into the argument/return
537 // types appearing in the fn signature
540 ty::Opaque(did, substs) => {
541 // all of the requirements on type parameters
542 // should've been checked by the instantiation
543 // of whatever returned this exact `impl Trait`.
545 // for named opaque `impl Trait` types we still need to check them
546 if ty::is_impl_trait_defn(self.infcx.tcx, did).is_none() {
547 let obligations = self.nominal_obligations(did, substs);
548 self.out.extend(obligations);
552 ty::Dynamic(data, r) => {
555 // Here, we defer WF checking due to higher-ranked
556 // regions. This is perhaps not ideal.
557 self.from_object_ty(ty, data, r);
559 // FIXME(#27579) RFC also considers adding trait
560 // obligations that don't refer to Self and
563 let defer_to_coercion = self.tcx().features().object_safe_for_dispatch;
565 if !defer_to_coercion {
566 let cause = self.cause(traits::MiscObligation);
567 let component_traits = data.auto_traits().chain(data.principal_def_id());
568 let tcx = self.tcx();
569 self.out.extend(component_traits.map(|did| {
570 traits::Obligation::new(
573 ty::PredicateAtom::ObjectSafe(did).to_predicate(tcx),
579 // Inference variables are the complicated case, since we don't
580 // know what type they are. We do two things:
582 // 1. Check if they have been resolved, and if so proceed with
584 // 2. If not, we've at least simplified things (e.g., we went
585 // from `Vec<$0>: WF` to `$0: WF`), so we can
586 // register a pending obligation and keep
587 // moving. (Goal is that an "inductive hypothesis"
588 // is satisfied to ensure termination.)
589 // See also the comment on `fn obligations`, describing "livelock"
590 // prevention, which happens before this can be reached.
592 let ty = self.infcx.shallow_resolve(ty);
593 if let ty::Infer(ty::TyVar(_)) = ty.kind {
594 // Not yet resolved, but we've made progress.
595 let cause = self.cause(traits::MiscObligation);
596 self.out.push(traits::Obligation::new(
599 ty::PredicateAtom::WellFormed(ty.into()).to_predicate(self.tcx()),
602 // Yes, resolved, proceed with the result.
603 // FIXME(eddyb) add the type to `walker` instead of recursing.
604 self.compute(ty.into());
611 fn nominal_obligations(
614 substs: SubstsRef<'tcx>,
615 ) -> Vec<traits::PredicateObligation<'tcx>> {
616 let predicates = self.infcx.tcx.predicates_of(def_id).instantiate(self.infcx.tcx, substs);
620 .zip(predicates.spans.into_iter())
621 .map(|(pred, span)| {
622 let cause = self.cause(traits::BindingObligation(def_id, span));
623 traits::Obligation::new(cause, self.param_env, pred)
625 .filter(|pred| !pred.has_escaping_bound_vars())
632 data: ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
633 region: ty::Region<'tcx>,
635 // Imagine a type like this:
638 // trait Bar<'c> : 'c { }
640 // &'b (Foo+'c+Bar<'d>)
643 // In this case, the following relationships must hold:
648 // The first conditions is due to the normal region pointer
649 // rules, which say that a reference cannot outlive its
652 // The final condition may be a bit surprising. In particular,
653 // you may expect that it would have been `'c <= 'd`, since
654 // usually lifetimes of outer things are conservative
655 // approximations for inner things. However, it works somewhat
656 // differently with trait objects: here the idea is that if the
657 // user specifies a region bound (`'c`, in this case) it is the
658 // "master bound" that *implies* that bounds from other traits are
659 // all met. (Remember that *all bounds* in a type like
660 // `Foo+Bar+Zed` must be met, not just one, hence if we write
661 // `Foo<'x>+Bar<'y>`, we know that the type outlives *both* 'x and
664 // Note: in fact we only permit builtin traits, not `Bar<'d>`, I
665 // am looking forward to the future here.
666 if !data.has_escaping_bound_vars() && !region.has_escaping_bound_vars() {
667 let implicit_bounds = object_region_bounds(self.infcx.tcx, data);
669 let explicit_bound = region;
671 self.out.reserve(implicit_bounds.len());
672 for implicit_bound in implicit_bounds {
673 let cause = self.cause(traits::ObjectTypeBound(ty, explicit_bound));
675 ty::Binder::dummy(ty::OutlivesPredicate(explicit_bound, implicit_bound));
676 self.out.push(traits::Obligation::new(
679 outlives.to_predicate(self.infcx.tcx),
686 /// Given an object type like `SomeTrait + Send`, computes the lifetime
687 /// bounds that must hold on the elided self type. These are derived
688 /// from the declarations of `SomeTrait`, `Send`, and friends -- if
689 /// they declare `trait SomeTrait : 'static`, for example, then
690 /// `'static` would appear in the list. The hard work is done by
691 /// `infer::required_region_bounds`, see that for more information.
692 pub fn object_region_bounds<'tcx>(
694 existential_predicates: ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
695 ) -> Vec<ty::Region<'tcx>> {
696 // Since we don't actually *know* the self type for an object,
697 // this "open(err)" serves as a kind of dummy standin -- basically
698 // a placeholder type.
699 let open_ty = tcx.mk_ty_infer(ty::FreshTy(0));
701 let predicates = existential_predicates.iter().filter_map(|predicate| {
702 if let ty::ExistentialPredicate::Projection(_) = predicate.skip_binder() {
705 Some(predicate.with_self_ty(tcx, open_ty))
709 required_region_bounds(tcx, open_ty, predicates)