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::{GenericArgKind, SubstsRef};
8 use rustc_middle::ty::{self, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness};
12 /// Returns the set of obligations needed to make `ty` well-formed.
13 /// If `ty` contains unresolved inference variables, this may include
14 /// further WF obligations. However, if `ty` 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>,
24 ) -> Option<Vec<traits::PredicateObligation<'tcx>>> {
25 let mut wf = WfPredicates { infcx, param_env, body_id, span, out: vec![], item: None };
27 debug!("wf::obligations({:?}, body_id={:?}) = {:?}", ty, body_id, wf.out);
29 let result = wf.normalize();
30 debug!("wf::obligations({:?}, body_id={:?}) ~~> {:?}", ty, body_id, result);
33 None // no progress made, return None
37 /// Returns the obligations that make this trait reference
38 /// well-formed. For example, if there is a trait `Set` defined like
39 /// `trait Set<K:Eq>`, then the trait reference `Foo: Set<Bar>` is WF
41 pub fn trait_obligations<'a, 'tcx>(
42 infcx: &InferCtxt<'a, 'tcx>,
43 param_env: ty::ParamEnv<'tcx>,
45 trait_ref: &ty::TraitRef<'tcx>,
47 item: Option<&'tcx hir::Item<'tcx>>,
48 ) -> Vec<traits::PredicateObligation<'tcx>> {
49 let mut wf = WfPredicates { infcx, param_env, body_id, span, out: vec![], item };
50 wf.compute_trait_ref(trait_ref, Elaborate::All);
54 pub fn predicate_obligations<'a, 'tcx>(
55 infcx: &InferCtxt<'a, 'tcx>,
56 param_env: ty::ParamEnv<'tcx>,
58 predicate: &ty::Predicate<'tcx>,
60 ) -> Vec<traits::PredicateObligation<'tcx>> {
61 let mut wf = WfPredicates { infcx, param_env, body_id, span, out: vec![], item: None };
63 // (*) ok to skip binders, because wf code is prepared for it
65 ty::Predicate::Trait(ref t, _) => {
66 wf.compute_trait_ref(&t.skip_binder().trait_ref, Elaborate::None); // (*)
68 ty::Predicate::RegionOutlives(..) => {}
69 ty::Predicate::TypeOutlives(ref t) => {
70 wf.compute(t.skip_binder().0);
72 ty::Predicate::Projection(ref t) => {
73 let t = t.skip_binder(); // (*)
74 wf.compute_projection(t.projection_ty);
77 ty::Predicate::WellFormed(t) => {
80 ty::Predicate::ObjectSafe(_) => {}
81 ty::Predicate::ClosureKind(..) => {}
82 ty::Predicate::Subtype(ref data) => {
83 wf.compute(data.skip_binder().a); // (*)
84 wf.compute(data.skip_binder().b); // (*)
86 ty::Predicate::ConstEvaluatable(def_id, substs) => {
87 let obligations = wf.nominal_obligations(def_id, substs);
88 wf.out.extend(obligations);
90 for ty in substs.types() {
99 struct WfPredicates<'a, 'tcx> {
100 infcx: &'a InferCtxt<'a, 'tcx>,
101 param_env: ty::ParamEnv<'tcx>,
104 out: Vec<traits::PredicateObligation<'tcx>>,
105 item: Option<&'tcx hir::Item<'tcx>>,
108 /// Controls whether we "elaborate" supertraits and so forth on the WF
109 /// predicates. This is a kind of hack to address #43784. The
110 /// underlying problem in that issue was a trait structure like:
113 /// trait Foo: Copy { }
114 /// trait Bar: Foo { }
115 /// impl<T: Bar> Foo for T { }
116 /// impl<T> Bar for T { }
119 /// Here, in the `Foo` impl, we will check that `T: Copy` holds -- but
120 /// we decide that this is true because `T: Bar` is in the
121 /// where-clauses (and we can elaborate that to include `T:
122 /// Copy`). This wouldn't be a problem, except that when we check the
123 /// `Bar` impl, we decide that `T: Foo` must hold because of the `Foo`
124 /// impl. And so nowhere did we check that `T: Copy` holds!
126 /// To resolve this, we elaborate the WF requirements that must be
127 /// proven when checking impls. This means that (e.g.) the `impl Bar
128 /// for T` will be forced to prove not only that `T: Foo` but also `T:
129 /// Copy` (which it won't be able to do, because there is no `Copy`
131 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
137 fn extend_cause_with_original_assoc_item_obligation<'tcx>(
139 trait_ref: &ty::TraitRef<'tcx>,
140 item: Option<&hir::Item<'tcx>>,
141 cause: &mut traits::ObligationCause<'tcx>,
142 pred: &ty::Predicate<'_>,
143 mut trait_assoc_items: impl Iterator<Item = ty::AssocItem>,
146 "extended_cause_with_original_assoc_item_obligation {:?} {:?} {:?} {:?}",
147 trait_ref, item, cause, pred
149 let items = match item {
150 Some(hir::Item { kind: hir::ItemKind::Impl { items, .. }, .. }) => items,
154 |impl_item_ref: &hir::ImplItemRef<'_>| match tcx.hir().impl_item(impl_item_ref.id).kind {
155 hir::ImplItemKind::Const(ty, _) | hir::ImplItemKind::TyAlias(ty) => ty.span,
156 _ => impl_item_ref.span,
159 ty::Predicate::Projection(proj) => {
160 // The obligation comes not from the current `impl` nor the `trait` being
161 // implemented, but rather from a "second order" obligation, like in
162 // `src/test/ui/associated-types/point-at-type-on-obligation-failure.rs`.
163 let trait_assoc_item = tcx.associated_item(proj.projection_def_id());
164 if let Some(impl_item_span) =
165 items.iter().find(|item| item.ident == trait_assoc_item.ident).map(fix_span)
167 cause.span = impl_item_span;
169 let kind = &proj.ty().skip_binder().kind;
170 if let ty::Projection(projection_ty) = kind {
171 // This happens when an associated type has a projection coming from another
172 // associated type. See `traits-assoc-type-in-supertrait-bad.rs`.
173 let trait_assoc_item = tcx.associated_item(projection_ty.item_def_id);
174 if let Some(impl_item_span) =
175 items.iter().find(|item| item.ident == trait_assoc_item.ident).map(fix_span)
177 cause.span = impl_item_span;
182 ty::Predicate::Trait(pred, _) => {
183 // An associated item obligation born out of the `trait` failed to be met. An example
184 // can be seen in `ui/associated-types/point-at-type-on-obligation-failure-2.rs`.
185 debug!("extended_cause_with_original_assoc_item_obligation trait proj {:?}", pred);
186 if let ty::Projection(ty::ProjectionTy { item_def_id, .. }) =
187 &pred.skip_binder().self_ty().kind
189 if let Some(impl_item_span) = trait_assoc_items
190 .find(|i| i.def_id == *item_def_id)
191 .and_then(|trait_assoc_item| {
192 items.iter().find(|i| i.ident == trait_assoc_item.ident).map(fix_span)
195 cause.span = impl_item_span;
203 impl<'a, 'tcx> WfPredicates<'a, 'tcx> {
204 fn cause(&mut self, code: traits::ObligationCauseCode<'tcx>) -> traits::ObligationCause<'tcx> {
205 traits::ObligationCause::new(self.span, self.body_id, code)
208 fn normalize(&mut self) -> Vec<traits::PredicateObligation<'tcx>> {
209 let cause = self.cause(traits::MiscObligation);
210 let infcx = &mut self.infcx;
211 let param_env = self.param_env;
212 let mut obligations = Vec::with_capacity(self.out.len());
213 for pred in &self.out {
214 assert!(!pred.has_escaping_bound_vars());
215 let mut selcx = traits::SelectionContext::new(infcx);
216 let i = obligations.len();
218 traits::normalize_to(&mut selcx, param_env, cause.clone(), pred, &mut obligations);
219 obligations.insert(i, value);
224 /// Pushes the obligations required for `trait_ref` to be WF into `self.out`.
225 fn compute_trait_ref(&mut self, trait_ref: &ty::TraitRef<'tcx>, elaborate: Elaborate) {
226 let tcx = self.infcx.tcx;
227 let obligations = self.nominal_obligations(trait_ref.def_id, trait_ref.substs);
229 debug!("compute_trait_ref obligations {:?}", obligations);
230 let cause = self.cause(traits::MiscObligation);
231 let param_env = self.param_env;
233 let item = self.item;
235 if let Elaborate::All = elaborate {
236 let implied_obligations = traits::util::elaborate_obligations(tcx, obligations.clone());
237 let implied_obligations = implied_obligations.map(|obligation| {
238 debug!("compute_trait_ref implied_obligation {:?}", obligation);
239 debug!("compute_trait_ref implied_obligation cause {:?}", obligation.cause);
240 let mut cause = cause.clone();
241 if let Some(parent_trait_ref) = obligation.predicate.to_opt_poly_trait_ref() {
242 let derived_cause = traits::DerivedObligationCause {
244 parent_code: Rc::new(obligation.cause.code.clone()),
246 cause.code = traits::ObligationCauseCode::ImplDerivedObligation(derived_cause);
248 extend_cause_with_original_assoc_item_obligation(
253 &obligation.predicate,
254 tcx.associated_items(trait_ref.def_id).in_definition_order().copied(),
256 debug!("compute_trait_ref new cause {:?}", cause);
257 traits::Obligation::new(cause, param_env, obligation.predicate)
259 self.out.extend(implied_obligations);
262 self.out.extend(obligations);
264 self.out.extend(trait_ref.substs.types().filter(|ty| !ty.has_escaping_bound_vars()).map(
265 |ty| traits::Obligation::new(cause.clone(), param_env, ty::Predicate::WellFormed(ty)),
269 /// Pushes the obligations required for `trait_ref::Item` to be WF
271 fn compute_projection(&mut self, data: ty::ProjectionTy<'tcx>) {
272 // A projection is well-formed if (a) the trait ref itself is
273 // WF and (b) the trait-ref holds. (It may also be
274 // normalizable and be WF that way.)
275 let trait_ref = data.trait_ref(self.infcx.tcx);
276 self.compute_trait_ref(&trait_ref, Elaborate::None);
278 if !data.has_escaping_bound_vars() {
279 let predicate = trait_ref.without_const().to_predicate();
280 let cause = self.cause(traits::ProjectionWf(data));
281 self.out.push(traits::Obligation::new(cause, self.param_env, predicate));
285 /// Pushes the obligations required for an array length to be WF
287 fn compute_array_len(&mut self, constant: ty::Const<'tcx>) {
288 if let ty::ConstKind::Unevaluated(def_id, substs, promoted) = constant.val {
289 assert!(promoted.is_none());
291 let obligations = self.nominal_obligations(def_id, substs);
292 self.out.extend(obligations);
294 let predicate = ty::Predicate::ConstEvaluatable(def_id, substs);
295 let cause = self.cause(traits::MiscObligation);
296 self.out.push(traits::Obligation::new(cause, self.param_env, predicate));
300 fn require_sized(&mut self, subty: Ty<'tcx>, cause: traits::ObligationCauseCode<'tcx>) {
301 if !subty.has_escaping_bound_vars() {
302 let cause = self.cause(cause);
303 let trait_ref = ty::TraitRef {
304 def_id: self.infcx.tcx.require_lang_item(lang_items::SizedTraitLangItem, None),
305 substs: self.infcx.tcx.mk_substs_trait(subty, &[]),
307 self.out.push(traits::Obligation::new(
310 trait_ref.without_const().to_predicate(),
315 /// Pushes new obligations into `out`. Returns `true` if it was able
316 /// to generate all the predicates needed to validate that `ty0`
317 /// is WF. Returns false if `ty0` is an unresolved type variable,
318 /// in which case we are not able to simplify at all.
319 fn compute(&mut self, ty0: Ty<'tcx>) -> bool {
320 let mut walker = ty0.walk();
321 let param_env = self.param_env;
322 while let Some(arg) = walker.next() {
323 let ty = match arg.unpack() {
324 GenericArgKind::Type(ty) => ty,
326 // No WF constraints for lifetimes being present, any outlives
327 // obligations are handled by the parent (e.g. `ty::Ref`).
328 GenericArgKind::Lifetime(_) => continue,
330 // FIXME(eddyb) this is wrong and needs to be replaced
331 // (see https://github.com/rust-lang/rust/pull/70107).
332 GenericArgKind::Const(_) => continue,
343 | ty::GeneratorWitness(..)
347 | ty::Placeholder(..)
348 | ty::Foreign(..) => {
349 // WfScalar, WfParameter, etc
352 ty::Slice(subty) => {
353 self.require_sized(subty, traits::SliceOrArrayElem);
356 ty::Array(subty, len) => {
357 self.require_sized(subty, traits::SliceOrArrayElem);
358 // FIXME(eddyb) handle `GenericArgKind::Const` above instead.
359 self.compute_array_len(*len);
362 ty::Tuple(ref tys) => {
363 if let Some((_last, rest)) = tys.split_last() {
365 self.require_sized(elem.expect_ty(), traits::TupleElem);
371 // simple cases that are WF if their type args are WF
374 ty::Projection(data) => {
375 walker.skip_current_subtree(); // subtree handled by compute_projection
376 self.compute_projection(data);
379 ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
381 ty::Adt(def, substs) => {
383 let obligations = self.nominal_obligations(def.did, substs);
384 self.out.extend(obligations);
387 ty::FnDef(did, substs) => {
388 let obligations = self.nominal_obligations(did, substs);
389 self.out.extend(obligations);
392 ty::Ref(r, rty, _) => {
394 if !r.has_escaping_bound_vars() && !rty.has_escaping_bound_vars() {
395 let cause = self.cause(traits::ReferenceOutlivesReferent(ty));
396 self.out.push(traits::Obligation::new(
399 ty::Predicate::TypeOutlives(ty::Binder::dummy(ty::OutlivesPredicate(
406 ty::Generator(..) => {
407 // Walk ALL the types in the generator: this will
408 // include the upvar types as well as the yield
409 // type. Note that this is mildly distinct from
410 // the closure case, where we have to be careful
411 // about the signature of the closure. We don't
412 // have the problem of implied bounds here since
413 // generators don't take arguments.
416 ty::Closure(_, substs) => {
417 // Only check the upvar types for WF, not the rest
418 // of the types within. This is needed because we
419 // capture the signature and it may not be WF
420 // without the implied bounds. Consider a closure
421 // like `|x: &'a T|` -- it may be that `T: 'a` is
422 // not known to hold in the creator's context (and
423 // indeed the closure may not be invoked by its
424 // creator, but rather turned to someone who *can*
427 // The special treatment of closures here really
428 // ought not to be necessary either; the problem
429 // is related to #25860 -- there is no way for us
430 // to express a fn type complete with the implied
431 // bounds that it is assuming. I think in reality
432 // the WF rules around fn are a bit messed up, and
433 // that is the rot problem: `fn(&'a T)` should
434 // probably always be WF, because it should be
435 // shorthand for something like `where(T: 'a) {
436 // fn(&'a T) }`, as discussed in #25860.
438 // Note that we are also skipping the generic
439 // types. This is consistent with the `outlives`
440 // code, but anyway doesn't matter: within the fn
441 // body where they are created, the generics will
442 // always be WF, and outside of that fn body we
443 // are not directly inspecting closure types
444 // anyway, except via auto trait matching (which
445 // only inspects the upvar types).
446 walker.skip_current_subtree(); // subtree handled by compute_projection
447 for upvar_ty in substs.as_closure().upvar_tys() {
448 self.compute(upvar_ty);
453 // let the loop iterate into the argument/return
454 // types appearing in the fn signature
457 ty::Opaque(did, substs) => {
458 // all of the requirements on type parameters
459 // should've been checked by the instantiation
460 // of whatever returned this exact `impl Trait`.
462 // for named opaque `impl Trait` types we still need to check them
463 if ty::is_impl_trait_defn(self.infcx.tcx, did).is_none() {
464 let obligations = self.nominal_obligations(did, substs);
465 self.out.extend(obligations);
469 ty::Dynamic(data, r) => {
472 // Here, we defer WF checking due to higher-ranked
473 // regions. This is perhaps not ideal.
474 self.from_object_ty(ty, data, r);
476 // FIXME(#27579) RFC also considers adding trait
477 // obligations that don't refer to Self and
480 let defer_to_coercion = self.infcx.tcx.features().object_safe_for_dispatch;
482 if !defer_to_coercion {
483 let cause = self.cause(traits::MiscObligation);
484 let component_traits = data.auto_traits().chain(data.principal_def_id());
485 self.out.extend(component_traits.map(|did| {
486 traits::Obligation::new(
489 ty::Predicate::ObjectSafe(did),
495 // Inference variables are the complicated case, since we don't
496 // know what type they are. We do two things:
498 // 1. Check if they have been resolved, and if so proceed with
500 // 2. If not, check whether this is the type that we
501 // started with (ty0). In that case, we've made no
502 // progress at all, so return false. Otherwise,
503 // we've at least simplified things (i.e., we went
504 // from `Vec<$0>: WF` to `$0: WF`, so we can
505 // register a pending obligation and keep
506 // moving. (Goal is that an "inductive hypothesis"
507 // is satisfied to ensure termination.)
509 let ty = self.infcx.shallow_resolve(ty);
510 if let ty::Infer(_) = ty.kind {
511 // not yet resolved...
513 // ...this is the type we started from! no progress.
517 let cause = self.cause(traits::MiscObligation);
519 // ...not the type we started from, so we made progress.
520 traits::Obligation::new(
523 ty::Predicate::WellFormed(ty),
527 // Yes, resolved, proceed with the
528 // result. Should never return false because
529 // `ty` is not a Infer.
530 assert!(self.compute(ty));
536 // if we made it through that loop above, we made progress!
540 fn nominal_obligations(
543 substs: SubstsRef<'tcx>,
544 ) -> Vec<traits::PredicateObligation<'tcx>> {
545 let predicates = self.infcx.tcx.predicates_of(def_id).instantiate(self.infcx.tcx, substs);
549 .zip(predicates.spans.into_iter())
550 .map(|(pred, span)| {
551 let cause = self.cause(traits::BindingObligation(def_id, span));
552 traits::Obligation::new(cause, self.param_env, pred)
554 .filter(|pred| !pred.has_escaping_bound_vars())
561 data: ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
562 region: ty::Region<'tcx>,
564 // Imagine a type like this:
567 // trait Bar<'c> : 'c { }
569 // &'b (Foo+'c+Bar<'d>)
572 // In this case, the following relationships must hold:
577 // The first conditions is due to the normal region pointer
578 // rules, which say that a reference cannot outlive its
581 // The final condition may be a bit surprising. In particular,
582 // you may expect that it would have been `'c <= 'd`, since
583 // usually lifetimes of outer things are conservative
584 // approximations for inner things. However, it works somewhat
585 // differently with trait objects: here the idea is that if the
586 // user specifies a region bound (`'c`, in this case) it is the
587 // "master bound" that *implies* that bounds from other traits are
588 // all met. (Remember that *all bounds* in a type like
589 // `Foo+Bar+Zed` must be met, not just one, hence if we write
590 // `Foo<'x>+Bar<'y>`, we know that the type outlives *both* 'x and
593 // Note: in fact we only permit builtin traits, not `Bar<'d>`, I
594 // am looking forward to the future here.
595 if !data.has_escaping_bound_vars() && !region.has_escaping_bound_vars() {
596 let implicit_bounds = object_region_bounds(self.infcx.tcx, data);
598 let explicit_bound = region;
600 self.out.reserve(implicit_bounds.len());
601 for implicit_bound in implicit_bounds {
602 let cause = self.cause(traits::ObjectTypeBound(ty, explicit_bound));
604 ty::Binder::dummy(ty::OutlivesPredicate(explicit_bound, implicit_bound));
605 self.out.push(traits::Obligation::new(
608 outlives.to_predicate(),
615 /// Given an object type like `SomeTrait + Send`, computes the lifetime
616 /// bounds that must hold on the elided self type. These are derived
617 /// from the declarations of `SomeTrait`, `Send`, and friends -- if
618 /// they declare `trait SomeTrait : 'static`, for example, then
619 /// `'static` would appear in the list. The hard work is done by
620 /// `infer::required_region_bounds`, see that for more information.
621 pub fn object_region_bounds<'tcx>(
623 existential_predicates: ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
624 ) -> Vec<ty::Region<'tcx>> {
625 // Since we don't actually *know* the self type for an object,
626 // this "open(err)" serves as a kind of dummy standin -- basically
627 // a placeholder type.
628 let open_ty = tcx.mk_ty_infer(ty::FreshTy(0));
630 let predicates = existential_predicates
632 .filter_map(|predicate| {
633 if let ty::ExistentialPredicate::Projection(_) = *predicate.skip_binder() {
636 Some(predicate.with_self_ty(tcx, open_ty))
641 required_region_bounds(tcx, open_ty, predicates)