2 use crate::hir::def_id::DefId;
3 use crate::infer::InferCtxt;
4 use crate::middle::lang_items;
5 use crate::traits::{self, AssocTypeBoundData};
6 use crate::ty::subst::SubstsRef;
7 use crate::ty::{self, ToPredicate, Ty, TyCtxt, TypeFoldable};
9 use syntax::symbol::{kw, Ident};
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);
28 let result = wf.normalize();
29 debug!("wf::obligations({:?}, body_id={:?}) ~~> {:?}", ty, body_id, result);
32 None // no progress made, return None
36 /// Returns the obligations that make this trait reference
37 /// well-formed. For example, if there is a trait `Set` defined like
38 /// `trait Set<K:Eq>`, then the trait reference `Foo: Set<Bar>` is WF
40 pub fn trait_obligations<'a, 'tcx>(
41 infcx: &InferCtxt<'a, 'tcx>,
42 param_env: ty::ParamEnv<'tcx>,
44 trait_ref: &ty::TraitRef<'tcx>,
46 item: Option<&'tcx hir::Item<'tcx>>,
47 ) -> Vec<traits::PredicateObligation<'tcx>> {
48 let mut wf = WfPredicates { infcx, param_env, body_id, span, out: vec![], item };
49 wf.compute_trait_ref(trait_ref, Elaborate::All);
53 pub fn predicate_obligations<'a, 'tcx>(
54 infcx: &InferCtxt<'a, 'tcx>,
55 param_env: ty::ParamEnv<'tcx>,
57 predicate: &ty::Predicate<'tcx>,
59 ) -> Vec<traits::PredicateObligation<'tcx>> {
60 let mut wf = WfPredicates { infcx, param_env, body_id, span, out: vec![], item: None };
62 // (*) ok to skip binders, because wf code is prepared for it
64 ty::Predicate::Trait(ref t) => {
65 wf.compute_trait_ref(&t.skip_binder().trait_ref, Elaborate::None); // (*)
67 ty::Predicate::RegionOutlives(..) => {}
68 ty::Predicate::TypeOutlives(ref t) => {
69 wf.compute(t.skip_binder().0);
71 ty::Predicate::Projection(ref t) => {
72 let t = t.skip_binder(); // (*)
73 wf.compute_projection(t.projection_ty);
76 ty::Predicate::WellFormed(t) => {
79 ty::Predicate::ObjectSafe(_) => {}
80 ty::Predicate::ClosureKind(..) => {}
81 ty::Predicate::Subtype(ref data) => {
82 wf.compute(data.skip_binder().a); // (*)
83 wf.compute(data.skip_binder().b); // (*)
85 ty::Predicate::ConstEvaluatable(def_id, substs) => {
86 let obligations = wf.nominal_obligations(def_id, substs);
87 wf.out.extend(obligations);
89 for ty in substs.types() {
98 struct WfPredicates<'a, 'tcx> {
99 infcx: &'a InferCtxt<'a, 'tcx>,
100 param_env: ty::ParamEnv<'tcx>,
103 out: Vec<traits::PredicateObligation<'tcx>>,
104 item: Option<&'tcx hir::Item<'tcx>>,
107 /// Controls whether we "elaborate" supertraits and so forth on the WF
108 /// predicates. This is a kind of hack to address #43784. The
109 /// underlying problem in that issue was a trait structure like:
112 /// trait Foo: Copy { }
113 /// trait Bar: Foo { }
114 /// impl<T: Bar> Foo for T { }
115 /// impl<T> Bar for T { }
118 /// Here, in the `Foo` impl, we will check that `T: Copy` holds -- but
119 /// we decide that this is true because `T: Bar` is in the
120 /// where-clauses (and we can elaborate that to include `T:
121 /// Copy`). This wouldn't be a problem, except that when we check the
122 /// `Bar` impl, we decide that `T: Foo` must hold because of the `Foo`
123 /// impl. And so nowhere did we check that `T: Copy` holds!
125 /// To resolve this, we elaborate the WF requirements that must be
126 /// proven when checking impls. This means that (e.g.) the `impl Bar
127 /// for T` will be forced to prove not only that `T: Foo` but also `T:
128 /// Copy` (which it won't be able to do, because there is no `Copy`
130 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
136 impl<'a, 'tcx> WfPredicates<'a, 'tcx> {
137 fn cause(&mut self, code: traits::ObligationCauseCode<'tcx>) -> traits::ObligationCause<'tcx> {
138 traits::ObligationCause::new(self.span, self.body_id, code)
141 fn normalize(&mut self) -> Vec<traits::PredicateObligation<'tcx>> {
142 let cause = self.cause(traits::MiscObligation);
143 let infcx = &mut self.infcx;
144 let param_env = self.param_env;
147 .inspect(|pred| assert!(!pred.has_escaping_bound_vars()))
149 let mut selcx = traits::SelectionContext::new(infcx);
150 let pred = traits::normalize(&mut selcx, param_env, cause.clone(), pred);
151 once(pred.value).chain(pred.obligations)
156 /// Pushes the obligations required for `trait_ref` to be WF into `self.out`.
157 fn compute_trait_ref(&mut self, trait_ref: &ty::TraitRef<'tcx>, elaborate: Elaborate) {
158 let tcx = self.infcx.tcx;
159 let obligations = self.nominal_obligations(trait_ref.def_id, trait_ref.substs);
161 let cause = self.cause(traits::MiscObligation);
162 let param_env = self.param_env;
164 let item = &self.item;
165 let extend_cause_with_original_assoc_item_obligation =
166 |cause: &mut traits::ObligationCause<'_>,
167 pred: &ty::Predicate<'_>,
168 trait_assoc_items: ty::AssocItemsIterator<'_>| {
171 .as_local_hir_id(trait_ref.def_id)
172 .and_then(|trait_id| tcx.hir().find(trait_id));
173 let (trait_name, trait_generics) = match trait_item {
174 Some(hir::Node::Item(hir::Item {
176 kind: hir::ItemKind::Trait(.., generics, _, _),
179 | Some(hir::Node::Item(hir::Item {
181 kind: hir::ItemKind::TraitAlias(generics, _),
183 })) => (Some(ident), Some(generics)),
187 let item_span = item.map(|i| tcx.sess.source_map().def_span(i.span));
189 ty::Predicate::Projection(proj) => {
190 // The obligation comes not from the current `impl` nor the `trait` being
191 // implemented, but rather from a "second order" obligation, like in
192 // `src/test/ui/associated-types/point-at-type-on-obligation-failure.rs`:
194 // error[E0271]: type mismatch resolving `<Foo2 as Bar2>::Ok == ()`
195 // --> $DIR/point-at-type-on-obligation-failure.rs:13:5
198 // | -- associated type defined here
200 // LL | impl Bar for Foo {
201 // | ---------------- in this `impl` item
202 // LL | type Ok = ();
203 // | ^^^^^^^^^^^^^ expected `u32`, found `()`
205 // = note: expected type `u32`
208 // FIXME: we would want to point a span to all places that contributed to this
209 // obligation. In the case above, it should be closer to:
211 // error[E0271]: type mismatch resolving `<Foo2 as Bar2>::Ok == ()`
212 // --> $DIR/point-at-type-on-obligation-failure.rs:13:5
215 // | -- associated type defined here
216 // LL | type Sibling: Bar2<Ok=Self::Ok>;
217 // | -------------------------------- obligation set here
219 // LL | impl Bar for Foo {
220 // | ---------------- in this `impl` item
221 // LL | type Ok = ();
222 // | ^^^^^^^^^^^^^ expected `u32`, found `()`
224 // LL | impl Bar2 for Foo2 {
225 // | ---------------- in this `impl` item
226 // LL | type Ok = u32;
227 // | -------------- obligation set here
229 // = note: expected type `u32`
231 if let Some(hir::ItemKind::Impl(.., impl_items)) = item.map(|i| &i.kind) {
232 let trait_assoc_item = tcx.associated_item(proj.projection_def_id());
233 if let Some(impl_item) = impl_items
235 .filter(|item| item.ident == trait_assoc_item.ident)
238 cause.span = impl_item.span;
239 cause.code = traits::AssocTypeBound(Box::new(AssocTypeBoundData {
240 impl_span: item_span,
241 original: trait_assoc_item.ident.span,
247 ty::Predicate::Trait(proj) => {
248 // An associated item obligation born out of the `trait` failed to be met.
249 // Point at the `impl` that failed the obligation, the associated item that
250 // needed to meet the obligation, and the definition of that associated item,
251 // which should hold the obligation in most cases. An example can be seen in
252 // `src/test/ui/associated-types/point-at-type-on-obligation-failure-2.rs`:
254 // error[E0277]: the trait bound `bool: Bar` is not satisfied
255 // --> $DIR/point-at-type-on-obligation-failure-2.rs:8:5
257 // LL | type Assoc: Bar;
258 // | ----- associated type defined here
260 // LL | impl Foo for () {
261 // | --------------- in this `impl` item
262 // LL | type Assoc = bool;
263 // | ^^^^^^^^^^^^^^^^^^ the trait `Bar` is not implemented for `bool`
265 // If the obligation comes from the where clause in the `trait`, we point at it:
267 // error[E0277]: the trait bound `bool: Bar` is not satisfied
268 // --> $DIR/point-at-type-on-obligation-failure-2.rs:8:5
270 // | trait Foo where <Self as Foo>>::Assoc: Bar {
271 // | -------------------------- restricted in this bound
273 // | ----- associated type defined here
275 // LL | impl Foo for () {
276 // | --------------- in this `impl` item
277 // LL | type Assoc = bool;
278 // | ^^^^^^^^^^^^^^^^^^ the trait `Bar` is not implemented for `bool`
280 ty::Projection(ty::ProjectionTy { item_def_id, .. }),
281 Some(hir::ItemKind::Impl(.., impl_items)),
282 ) = (&proj.skip_binder().self_ty().kind, item.map(|i| &i.kind))
284 if let Some((impl_item, trait_assoc_item)) = trait_assoc_items
285 .filter(|i| i.def_id == *item_def_id)
287 .and_then(|trait_assoc_item| {
290 .filter(|i| i.ident == trait_assoc_item.ident)
292 .map(|impl_item| (impl_item, trait_assoc_item))
295 let bounds = trait_generics
297 get_generic_bound_spans(
300 trait_assoc_item.ident,
303 .unwrap_or_else(Vec::new);
304 cause.span = impl_item.span;
305 cause.code = traits::AssocTypeBound(Box::new(AssocTypeBoundData {
306 impl_span: item_span,
307 original: trait_assoc_item.ident.span,
317 if let Elaborate::All = elaborate {
318 let trait_assoc_items = tcx.associated_items(trait_ref.def_id);
321 obligations.iter().map(|obligation| obligation.predicate.clone()).collect();
322 let implied_obligations = traits::elaborate_predicates(tcx, predicates);
323 let implied_obligations = implied_obligations.map(|pred| {
324 let mut cause = cause.clone();
325 extend_cause_with_original_assoc_item_obligation(
328 trait_assoc_items.clone(),
330 traits::Obligation::new(cause, param_env, pred)
332 self.out.extend(implied_obligations);
335 self.out.extend(obligations);
337 self.out.extend(trait_ref.substs.types().filter(|ty| !ty.has_escaping_bound_vars()).map(
338 |ty| traits::Obligation::new(cause.clone(), param_env, ty::Predicate::WellFormed(ty)),
342 /// Pushes the obligations required for `trait_ref::Item` to be WF
344 fn compute_projection(&mut self, data: ty::ProjectionTy<'tcx>) {
345 // A projection is well-formed if (a) the trait ref itself is
346 // WF and (b) the trait-ref holds. (It may also be
347 // normalizable and be WF that way.)
348 let trait_ref = data.trait_ref(self.infcx.tcx);
349 self.compute_trait_ref(&trait_ref, Elaborate::None);
351 if !data.has_escaping_bound_vars() {
352 let predicate = trait_ref.to_predicate();
353 let cause = self.cause(traits::ProjectionWf(data));
354 self.out.push(traits::Obligation::new(cause, self.param_env, predicate));
358 /// Pushes the obligations required for an array length to be WF
360 fn compute_array_len(&mut self, constant: ty::Const<'tcx>) {
361 if let ty::ConstKind::Unevaluated(def_id, substs) = constant.val {
362 let obligations = self.nominal_obligations(def_id, substs);
363 self.out.extend(obligations);
365 let predicate = ty::Predicate::ConstEvaluatable(def_id, substs);
366 let cause = self.cause(traits::MiscObligation);
367 self.out.push(traits::Obligation::new(cause, self.param_env, predicate));
371 fn require_sized(&mut self, subty: Ty<'tcx>, cause: traits::ObligationCauseCode<'tcx>) {
372 if !subty.has_escaping_bound_vars() {
373 let cause = self.cause(cause);
374 let trait_ref = ty::TraitRef {
375 def_id: self.infcx.tcx.require_lang_item(lang_items::SizedTraitLangItem, None),
376 substs: self.infcx.tcx.mk_substs_trait(subty, &[]),
378 self.out.push(traits::Obligation::new(cause, self.param_env, trait_ref.to_predicate()));
382 /// Pushes new obligations into `out`. Returns `true` if it was able
383 /// to generate all the predicates needed to validate that `ty0`
384 /// is WF. Returns false if `ty0` is an unresolved type variable,
385 /// in which case we are not able to simplify at all.
386 fn compute(&mut self, ty0: Ty<'tcx>) -> bool {
387 let mut subtys = ty0.walk();
388 let param_env = self.param_env;
389 while let Some(ty) = subtys.next() {
398 | ty::GeneratorWitness(..)
402 | ty::Placeholder(..)
403 | ty::Foreign(..) => {
404 // WfScalar, WfParameter, etc
407 ty::Slice(subty) => {
408 self.require_sized(subty, traits::SliceOrArrayElem);
411 ty::Array(subty, len) => {
412 self.require_sized(subty, traits::SliceOrArrayElem);
413 self.compute_array_len(*len);
416 ty::Tuple(ref tys) => {
417 if let Some((_last, rest)) = tys.split_last() {
419 self.require_sized(elem.expect_ty(), traits::TupleElem);
425 // simple cases that are WF if their type args are WF
428 ty::Projection(data) => {
429 subtys.skip_current_subtree(); // subtree handled by compute_projection
430 self.compute_projection(data);
433 ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
435 ty::Adt(def, substs) => {
437 let obligations = self.nominal_obligations(def.did, substs);
438 self.out.extend(obligations);
441 ty::FnDef(did, substs) => {
442 let obligations = self.nominal_obligations(did, substs);
443 self.out.extend(obligations);
446 ty::Ref(r, rty, _) => {
448 if !r.has_escaping_bound_vars() && !rty.has_escaping_bound_vars() {
449 let cause = self.cause(traits::ReferenceOutlivesReferent(ty));
450 self.out.push(traits::Obligation::new(
453 ty::Predicate::TypeOutlives(ty::Binder::dummy(ty::OutlivesPredicate(
460 ty::Generator(..) => {
461 // Walk ALL the types in the generator: this will
462 // include the upvar types as well as the yield
463 // type. Note that this is mildly distinct from
464 // the closure case, where we have to be careful
465 // about the signature of the closure. We don't
466 // have the problem of implied bounds here since
467 // generators don't take arguments.
470 ty::Closure(def_id, substs) => {
471 // Only check the upvar types for WF, not the rest
472 // of the types within. This is needed because we
473 // capture the signature and it may not be WF
474 // without the implied bounds. Consider a closure
475 // like `|x: &'a T|` -- it may be that `T: 'a` is
476 // not known to hold in the creator's context (and
477 // indeed the closure may not be invoked by its
478 // creator, but rather turned to someone who *can*
481 // The special treatment of closures here really
482 // ought not to be necessary either; the problem
483 // is related to #25860 -- there is no way for us
484 // to express a fn type complete with the implied
485 // bounds that it is assuming. I think in reality
486 // the WF rules around fn are a bit messed up, and
487 // that is the rot problem: `fn(&'a T)` should
488 // probably always be WF, because it should be
489 // shorthand for something like `where(T: 'a) {
490 // fn(&'a T) }`, as discussed in #25860.
492 // Note that we are also skipping the generic
493 // types. This is consistent with the `outlives`
494 // code, but anyway doesn't matter: within the fn
495 // body where they are created, the generics will
496 // always be WF, and outside of that fn body we
497 // are not directly inspecting closure types
498 // anyway, except via auto trait matching (which
499 // only inspects the upvar types).
500 subtys.skip_current_subtree(); // subtree handled by compute_projection
501 for upvar_ty in substs.as_closure().upvar_tys(def_id, self.infcx.tcx) {
502 self.compute(upvar_ty);
507 // let the loop iterate into the argument/return
508 // types appearing in the fn signature
511 ty::Opaque(did, substs) => {
512 // all of the requirements on type parameters
513 // should've been checked by the instantiation
514 // of whatever returned this exact `impl Trait`.
516 // for named opaque `impl Trait` types we still need to check them
517 if super::is_impl_trait_defn(self.infcx.tcx, did).is_none() {
518 let obligations = self.nominal_obligations(did, substs);
519 self.out.extend(obligations);
523 ty::Dynamic(data, r) => {
526 // Here, we defer WF checking due to higher-ranked
527 // regions. This is perhaps not ideal.
528 self.from_object_ty(ty, data, r);
530 // FIXME(#27579) RFC also considers adding trait
531 // obligations that don't refer to Self and
534 let defer_to_coercion = self.infcx.tcx.features().object_safe_for_dispatch;
536 if !defer_to_coercion {
537 let cause = self.cause(traits::MiscObligation);
538 let component_traits = data.auto_traits().chain(data.principal_def_id());
539 self.out.extend(component_traits.map(|did| {
540 traits::Obligation::new(
543 ty::Predicate::ObjectSafe(did),
549 // Inference variables are the complicated case, since we don't
550 // know what type they are. We do two things:
552 // 1. Check if they have been resolved, and if so proceed with
554 // 2. If not, check whether this is the type that we
555 // started with (ty0). In that case, we've made no
556 // progress at all, so return false. Otherwise,
557 // we've at least simplified things (i.e., we went
558 // from `Vec<$0>: WF` to `$0: WF`, so we can
559 // register a pending obligation and keep
560 // moving. (Goal is that an "inductive hypothesis"
561 // is satisfied to ensure termination.)
563 let ty = self.infcx.shallow_resolve(ty);
564 if let ty::Infer(_) = ty.kind {
565 // not yet resolved...
567 // ...this is the type we started from! no progress.
571 let cause = self.cause(traits::MiscObligation);
573 // ...not the type we started from, so we made progress.
574 traits::Obligation::new(
577 ty::Predicate::WellFormed(ty),
581 // Yes, resolved, proceed with the
582 // result. Should never return false because
583 // `ty` is not a Infer.
584 assert!(self.compute(ty));
590 // if we made it through that loop above, we made progress!
594 fn nominal_obligations(
597 substs: SubstsRef<'tcx>,
598 ) -> Vec<traits::PredicateObligation<'tcx>> {
599 let predicates = self.infcx.tcx.predicates_of(def_id).instantiate(self.infcx.tcx, substs);
600 let cause = self.cause(traits::ItemObligation(def_id));
604 .map(|pred| traits::Obligation::new(cause.clone(), self.param_env, pred))
605 .filter(|pred| !pred.has_escaping_bound_vars())
612 data: ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
613 region: ty::Region<'tcx>,
615 // Imagine a type like this:
618 // trait Bar<'c> : 'c { }
620 // &'b (Foo+'c+Bar<'d>)
623 // In this case, the following relationships must hold:
628 // The first conditions is due to the normal region pointer
629 // rules, which say that a reference cannot outlive its
632 // The final condition may be a bit surprising. In particular,
633 // you may expect that it would have been `'c <= 'd`, since
634 // usually lifetimes of outer things are conservative
635 // approximations for inner things. However, it works somewhat
636 // differently with trait objects: here the idea is that if the
637 // user specifies a region bound (`'c`, in this case) it is the
638 // "master bound" that *implies* that bounds from other traits are
639 // all met. (Remember that *all bounds* in a type like
640 // `Foo+Bar+Zed` must be met, not just one, hence if we write
641 // `Foo<'x>+Bar<'y>`, we know that the type outlives *both* 'x and
644 // Note: in fact we only permit builtin traits, not `Bar<'d>`, I
645 // am looking forward to the future here.
646 if !data.has_escaping_bound_vars() && !region.has_escaping_bound_vars() {
647 let implicit_bounds = object_region_bounds(self.infcx.tcx, data);
649 let explicit_bound = region;
651 self.out.reserve(implicit_bounds.len());
652 for implicit_bound in implicit_bounds {
653 let cause = self.cause(traits::ObjectTypeBound(ty, explicit_bound));
655 ty::Binder::dummy(ty::OutlivesPredicate(explicit_bound, implicit_bound));
656 self.out.push(traits::Obligation::new(
659 outlives.to_predicate(),
666 /// Given an object type like `SomeTrait + Send`, computes the lifetime
667 /// bounds that must hold on the elided self type. These are derived
668 /// from the declarations of `SomeTrait`, `Send`, and friends -- if
669 /// they declare `trait SomeTrait : 'static`, for example, then
670 /// `'static` would appear in the list. The hard work is done by
671 /// `ty::required_region_bounds`, see that for more information.
672 pub fn object_region_bounds<'tcx>(
674 existential_predicates: ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
675 ) -> Vec<ty::Region<'tcx>> {
676 // Since we don't actually *know* the self type for an object,
677 // this "open(err)" serves as a kind of dummy standin -- basically
678 // a placeholder type.
679 let open_ty = tcx.mk_ty_infer(ty::FreshTy(0));
681 let predicates = existential_predicates
683 .filter_map(|predicate| {
684 if let ty::ExistentialPredicate::Projection(_) = *predicate.skip_binder() {
687 Some(predicate.with_self_ty(tcx, open_ty))
692 tcx.required_region_bounds(open_ty, predicates)
695 /// Find the span of a generic bound affecting an associated type.
696 fn get_generic_bound_spans(
697 generics: &hir::Generics<'_>,
698 trait_name: Option<&Ident>,
699 assoc_item_name: Ident,
701 let mut bounds = vec![];
702 for clause in generics.where_clause.predicates.iter() {
703 if let hir::WherePredicate::BoundPredicate(pred) = clause {
704 match &pred.bounded_ty.kind {
705 hir::TyKind::Path(hir::QPath::Resolved(Some(ty), path)) => {
706 let mut s = path.segments.iter();
707 if let (a, Some(b), None) = (s.next(), s.next(), s.next()) {
708 if a.map(|s| &s.ident) == trait_name
709 && b.ident == assoc_item_name
710 && is_self_path(&ty.kind)
712 // `<Self as Foo>::Bar`
713 bounds.push(pred.span);
717 hir::TyKind::Path(hir::QPath::TypeRelative(ty, segment)) => {
718 if segment.ident == assoc_item_name {
719 if is_self_path(&ty.kind) {
721 bounds.push(pred.span);
732 fn is_self_path(kind: &hir::TyKind<'_>) -> bool {
734 hir::TyKind::Path(hir::QPath::Resolved(None, path)) => {
735 let mut s = path.segments.iter();
736 if let (Some(segment), None) = (s.next(), s.next()) {
737 if segment.ident.name == kw::SelfUpper {