]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/wf.rs
Rollup merge of #90626 - rusticstuff:be-more-accepting, r=jyn514
[rust.git] / compiler / rustc_trait_selection / src / traits / wf.rs
1 use crate::infer::InferCtxt;
2 use crate::opaque_types::required_region_bounds;
3 use crate::traits;
4 use rustc_data_structures::sync::Lrc;
5 use rustc_hir as hir;
6 use rustc_hir::def_id::DefId;
7 use rustc_hir::lang_items::LangItem;
8 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, SubstsRef};
9 use rustc_middle::ty::{self, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness};
10 use rustc_span::Span;
11
12 use std::iter;
13 /// Returns the set of obligations needed to make `arg` well-formed.
14 /// If `arg` contains unresolved inference variables, this may include
15 /// further WF obligations. However, if `arg` IS an unresolved
16 /// inference variable, returns `None`, because we are not able to
17 /// make any progress at all. This is to prevent "livelock" where we
18 /// say "$0 is WF if $0 is WF".
19 pub fn obligations<'a, 'tcx>(
20     infcx: &InferCtxt<'a, 'tcx>,
21     param_env: ty::ParamEnv<'tcx>,
22     body_id: hir::HirId,
23     recursion_depth: usize,
24     arg: GenericArg<'tcx>,
25     span: Span,
26 ) -> Option<Vec<traits::PredicateObligation<'tcx>>> {
27     // Handle the "livelock" case (see comment above) by bailing out if necessary.
28     let arg = match arg.unpack() {
29         GenericArgKind::Type(ty) => {
30             match ty.kind() {
31                 ty::Infer(ty::TyVar(_)) => {
32                     let resolved_ty = infcx.shallow_resolve(ty);
33                     if resolved_ty == ty {
34                         // No progress, bail out to prevent "livelock".
35                         return None;
36                     }
37
38                     resolved_ty
39                 }
40                 _ => ty,
41             }
42             .into()
43         }
44         GenericArgKind::Const(ct) => {
45             match ct.val {
46                 ty::ConstKind::Infer(infer) => {
47                     let resolved = infcx.shallow_resolve(infer);
48                     if resolved == infer {
49                         // No progress.
50                         return None;
51                     }
52
53                     infcx.tcx.mk_const(ty::Const { val: ty::ConstKind::Infer(resolved), ty: ct.ty })
54                 }
55                 _ => ct,
56             }
57             .into()
58         }
59         // There is nothing we have to do for lifetimes.
60         GenericArgKind::Lifetime(..) => return Some(Vec::new()),
61     };
62
63     let mut wf =
64         WfPredicates { infcx, param_env, body_id, span, out: vec![], recursion_depth, item: None };
65     wf.compute(arg);
66     debug!("wf::obligations({:?}, body_id={:?}) = {:?}", arg, body_id, wf.out);
67
68     let result = wf.normalize();
69     debug!("wf::obligations({:?}, body_id={:?}) ~~> {:?}", arg, body_id, result);
70     Some(result)
71 }
72
73 /// Returns the obligations that make this trait reference
74 /// well-formed.  For example, if there is a trait `Set` defined like
75 /// `trait Set<K:Eq>`, then the trait reference `Foo: Set<Bar>` is WF
76 /// if `Bar: Eq`.
77 pub fn trait_obligations<'a, 'tcx>(
78     infcx: &InferCtxt<'a, 'tcx>,
79     param_env: ty::ParamEnv<'tcx>,
80     body_id: hir::HirId,
81     trait_ref: &ty::TraitRef<'tcx>,
82     span: Span,
83     item: Option<&'tcx hir::Item<'tcx>>,
84 ) -> Vec<traits::PredicateObligation<'tcx>> {
85     let mut wf =
86         WfPredicates { infcx, param_env, body_id, span, out: vec![], recursion_depth: 0, item };
87     wf.compute_trait_ref(trait_ref, Elaborate::All);
88     debug!(obligations = ?wf.out);
89     wf.normalize()
90 }
91
92 pub fn predicate_obligations<'a, 'tcx>(
93     infcx: &InferCtxt<'a, 'tcx>,
94     param_env: ty::ParamEnv<'tcx>,
95     body_id: hir::HirId,
96     predicate: ty::Predicate<'tcx>,
97     span: Span,
98 ) -> Vec<traits::PredicateObligation<'tcx>> {
99     let mut wf = WfPredicates {
100         infcx,
101         param_env,
102         body_id,
103         span,
104         out: vec![],
105         recursion_depth: 0,
106         item: None,
107     };
108
109     // It's ok to skip the binder here because wf code is prepared for it
110     match predicate.kind().skip_binder() {
111         ty::PredicateKind::Trait(t) => {
112             wf.compute_trait_ref(&t.trait_ref, Elaborate::None);
113         }
114         ty::PredicateKind::RegionOutlives(..) => {}
115         ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
116             wf.compute(ty.into());
117         }
118         ty::PredicateKind::Projection(t) => {
119             wf.compute_projection(t.projection_ty);
120             wf.compute(t.ty.into());
121         }
122         ty::PredicateKind::WellFormed(arg) => {
123             wf.compute(arg);
124         }
125         ty::PredicateKind::ObjectSafe(_) => {}
126         ty::PredicateKind::ClosureKind(..) => {}
127         ty::PredicateKind::Subtype(ty::SubtypePredicate { a, b, a_is_expected: _ }) => {
128             wf.compute(a.into());
129             wf.compute(b.into());
130         }
131         ty::PredicateKind::Coerce(ty::CoercePredicate { a, b }) => {
132             wf.compute(a.into());
133             wf.compute(b.into());
134         }
135         ty::PredicateKind::ConstEvaluatable(uv) => {
136             let substs = uv.substs(wf.tcx());
137             let obligations = wf.nominal_obligations(uv.def.did, substs);
138             wf.out.extend(obligations);
139
140             for arg in substs.iter() {
141                 wf.compute(arg);
142             }
143         }
144         ty::PredicateKind::ConstEquate(c1, c2) => {
145             wf.compute(c1.into());
146             wf.compute(c2.into());
147         }
148         ty::PredicateKind::TypeWellFormedFromEnv(..) => {
149             bug!("TypeWellFormedFromEnv is only used for Chalk")
150         }
151     }
152
153     wf.normalize()
154 }
155
156 struct WfPredicates<'a, 'tcx> {
157     infcx: &'a InferCtxt<'a, 'tcx>,
158     param_env: ty::ParamEnv<'tcx>,
159     body_id: hir::HirId,
160     span: Span,
161     out: Vec<traits::PredicateObligation<'tcx>>,
162     recursion_depth: usize,
163     item: Option<&'tcx hir::Item<'tcx>>,
164 }
165
166 /// Controls whether we "elaborate" supertraits and so forth on the WF
167 /// predicates. This is a kind of hack to address #43784. The
168 /// underlying problem in that issue was a trait structure like:
169 ///
170 /// ```
171 /// trait Foo: Copy { }
172 /// trait Bar: Foo { }
173 /// impl<T: Bar> Foo for T { }
174 /// impl<T> Bar for T { }
175 /// ```
176 ///
177 /// Here, in the `Foo` impl, we will check that `T: Copy` holds -- but
178 /// we decide that this is true because `T: Bar` is in the
179 /// where-clauses (and we can elaborate that to include `T:
180 /// Copy`). This wouldn't be a problem, except that when we check the
181 /// `Bar` impl, we decide that `T: Foo` must hold because of the `Foo`
182 /// impl. And so nowhere did we check that `T: Copy` holds!
183 ///
184 /// To resolve this, we elaborate the WF requirements that must be
185 /// proven when checking impls. This means that (e.g.) the `impl Bar
186 /// for T` will be forced to prove not only that `T: Foo` but also `T:
187 /// Copy` (which it won't be able to do, because there is no `Copy`
188 /// impl for `T`).
189 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
190 enum Elaborate {
191     All,
192     None,
193 }
194
195 fn extend_cause_with_original_assoc_item_obligation<'tcx>(
196     tcx: TyCtxt<'tcx>,
197     trait_ref: &ty::TraitRef<'tcx>,
198     item: Option<&hir::Item<'tcx>>,
199     cause: &mut traits::ObligationCause<'tcx>,
200     pred: &ty::Predicate<'tcx>,
201     mut trait_assoc_items: impl Iterator<Item = &'tcx ty::AssocItem>,
202 ) {
203     debug!(
204         "extended_cause_with_original_assoc_item_obligation {:?} {:?} {:?} {:?}",
205         trait_ref, item, cause, pred
206     );
207     let items = match item {
208         Some(hir::Item { kind: hir::ItemKind::Impl(impl_), .. }) => impl_.items,
209         _ => return,
210     };
211     let fix_span =
212         |impl_item_ref: &hir::ImplItemRef| match tcx.hir().impl_item(impl_item_ref.id).kind {
213             hir::ImplItemKind::Const(ty, _) | hir::ImplItemKind::TyAlias(ty) => ty.span,
214             _ => impl_item_ref.span,
215         };
216
217     // It is fine to skip the binder as we don't care about regions here.
218     match pred.kind().skip_binder() {
219         ty::PredicateKind::Projection(proj) => {
220             // The obligation comes not from the current `impl` nor the `trait` being implemented,
221             // but rather from a "second order" obligation, where an associated type has a
222             // projection coming from another associated type. See
223             // `src/test/ui/associated-types/point-at-type-on-obligation-failure.rs` and
224             // `traits-assoc-type-in-supertrait-bad.rs`.
225             if let ty::Projection(projection_ty) = proj.ty.kind() {
226                 let trait_assoc_item = tcx.associated_item(projection_ty.item_def_id);
227                 if let Some(impl_item_span) =
228                     items.iter().find(|item| item.ident == trait_assoc_item.ident).map(fix_span)
229                 {
230                     cause.make_mut().span = impl_item_span;
231                 }
232             }
233         }
234         ty::PredicateKind::Trait(pred) => {
235             // An associated item obligation born out of the `trait` failed to be met. An example
236             // can be seen in `ui/associated-types/point-at-type-on-obligation-failure-2.rs`.
237             debug!("extended_cause_with_original_assoc_item_obligation trait proj {:?}", pred);
238             if let ty::Projection(ty::ProjectionTy { item_def_id, .. }) = *pred.self_ty().kind() {
239                 if let Some(impl_item_span) = trait_assoc_items
240                     .find(|i| i.def_id == item_def_id)
241                     .and_then(|trait_assoc_item| {
242                         items.iter().find(|i| i.ident == trait_assoc_item.ident).map(fix_span)
243                     })
244                 {
245                     cause.make_mut().span = impl_item_span;
246                 }
247             }
248         }
249         _ => {}
250     }
251 }
252
253 impl<'a, 'tcx> WfPredicates<'a, 'tcx> {
254     fn tcx(&self) -> TyCtxt<'tcx> {
255         self.infcx.tcx
256     }
257
258     fn cause(&self, code: traits::ObligationCauseCode<'tcx>) -> traits::ObligationCause<'tcx> {
259         traits::ObligationCause::new(self.span, self.body_id, code)
260     }
261
262     fn normalize(mut self) -> Vec<traits::PredicateObligation<'tcx>> {
263         let cause = self.cause(traits::MiscObligation);
264         let infcx = &mut self.infcx;
265         let param_env = self.param_env;
266         let mut obligations = Vec::with_capacity(self.out.len());
267         for mut obligation in self.out {
268             assert!(!obligation.has_escaping_bound_vars());
269             let mut selcx = traits::SelectionContext::new(infcx);
270             // Don't normalize the whole obligation, the param env is either
271             // already normalized, or we're currently normalizing the
272             // param_env. Either way we should only normalize the predicate.
273             let normalized_predicate = traits::project::normalize_with_depth_to(
274                 &mut selcx,
275                 param_env,
276                 cause.clone(),
277                 self.recursion_depth,
278                 obligation.predicate,
279                 &mut obligations,
280             );
281             obligation.predicate = normalized_predicate;
282             obligations.push(obligation);
283         }
284         obligations
285     }
286
287     /// Pushes the obligations required for `trait_ref` to be WF into `self.out`.
288     fn compute_trait_ref(&mut self, trait_ref: &ty::TraitRef<'tcx>, elaborate: Elaborate) {
289         let tcx = self.infcx.tcx;
290         let obligations = self.nominal_obligations(trait_ref.def_id, trait_ref.substs);
291
292         debug!("compute_trait_ref obligations {:?}", obligations);
293         let cause = self.cause(traits::MiscObligation);
294         let param_env = self.param_env;
295         let depth = self.recursion_depth;
296
297         let item = self.item;
298
299         let extend = |obligation: traits::PredicateObligation<'tcx>| {
300             let mut cause = cause.clone();
301             if let Some(parent_trait_ref) = obligation.predicate.to_opt_poly_trait_ref() {
302                 let derived_cause = traits::DerivedObligationCause {
303                     parent_trait_ref: parent_trait_ref.value,
304                     parent_code: Lrc::new(obligation.cause.code.clone()),
305                 };
306                 cause.make_mut().code =
307                     traits::ObligationCauseCode::DerivedObligation(derived_cause);
308             }
309             extend_cause_with_original_assoc_item_obligation(
310                 tcx,
311                 trait_ref,
312                 item,
313                 &mut cause,
314                 &obligation.predicate,
315                 tcx.associated_items(trait_ref.def_id).in_definition_order(),
316             );
317             traits::Obligation::with_depth(cause, depth, param_env, obligation.predicate)
318         };
319
320         if let Elaborate::All = elaborate {
321             let implied_obligations = traits::util::elaborate_obligations(tcx, obligations);
322             let implied_obligations = implied_obligations.map(extend);
323             self.out.extend(implied_obligations);
324         } else {
325             self.out.extend(obligations);
326         }
327
328         let tcx = self.tcx();
329         self.out.extend(
330             trait_ref
331                 .substs
332                 .iter()
333                 .enumerate()
334                 .filter(|(_, arg)| {
335                     matches!(arg.unpack(), GenericArgKind::Type(..) | GenericArgKind::Const(..))
336                 })
337                 .filter(|(_, arg)| !arg.has_escaping_bound_vars())
338                 .map(|(i, arg)| {
339                     let mut new_cause = cause.clone();
340                     // The first subst is the self ty - use the correct span for it.
341                     if i == 0 {
342                         if let Some(hir::ItemKind::Impl(hir::Impl { self_ty, .. })) =
343                             item.map(|i| &i.kind)
344                         {
345                             new_cause.make_mut().span = self_ty.span;
346                         }
347                     }
348                     traits::Obligation::with_depth(
349                         new_cause,
350                         depth,
351                         param_env,
352                         ty::Binder::dummy(ty::PredicateKind::WellFormed(arg)).to_predicate(tcx),
353                     )
354                 }),
355         );
356     }
357
358     /// Pushes the obligations required for `trait_ref::Item` to be WF
359     /// into `self.out`.
360     fn compute_projection(&mut self, data: ty::ProjectionTy<'tcx>) {
361         // A projection is well-formed if
362         //
363         // (a) its predicates hold (*)
364         // (b) its substs are wf
365         //
366         // (*) The predicates of an associated type include the predicates of
367         //     the trait that it's contained in. For example, given
368         //
369         // trait A<T>: Clone {
370         //     type X where T: Copy;
371         // }
372         //
373         // The predicates of `<() as A<i32>>::X` are:
374         // [
375         //     `(): Sized`
376         //     `(): Clone`
377         //     `(): A<i32>`
378         //     `i32: Sized`
379         //     `i32: Clone`
380         //     `i32: Copy`
381         // ]
382         let obligations = self.nominal_obligations(data.item_def_id, data.substs);
383         self.out.extend(obligations);
384
385         let tcx = self.tcx();
386         let cause = self.cause(traits::MiscObligation);
387         let param_env = self.param_env;
388         let depth = self.recursion_depth;
389
390         self.out.extend(
391             data.substs
392                 .iter()
393                 .filter(|arg| {
394                     matches!(arg.unpack(), GenericArgKind::Type(..) | GenericArgKind::Const(..))
395                 })
396                 .filter(|arg| !arg.has_escaping_bound_vars())
397                 .map(|arg| {
398                     traits::Obligation::with_depth(
399                         cause.clone(),
400                         depth,
401                         param_env,
402                         ty::Binder::dummy(ty::PredicateKind::WellFormed(arg)).to_predicate(tcx),
403                     )
404                 }),
405         );
406     }
407
408     fn require_sized(&mut self, subty: Ty<'tcx>, cause: traits::ObligationCauseCode<'tcx>) {
409         if !subty.has_escaping_bound_vars() {
410             let cause = self.cause(cause);
411             let trait_ref = ty::TraitRef {
412                 def_id: self.infcx.tcx.require_lang_item(LangItem::Sized, None),
413                 substs: self.infcx.tcx.mk_substs_trait(subty, &[]),
414             };
415             self.out.push(traits::Obligation::with_depth(
416                 cause,
417                 self.recursion_depth,
418                 self.param_env,
419                 ty::Binder::dummy(trait_ref).without_const().to_predicate(self.infcx.tcx),
420             ));
421         }
422     }
423
424     /// Pushes all the predicates needed to validate that `ty` is WF into `out`.
425     fn compute(&mut self, arg: GenericArg<'tcx>) {
426         let mut walker = arg.walk(self.tcx());
427         let param_env = self.param_env;
428         let depth = self.recursion_depth;
429         while let Some(arg) = walker.next() {
430             let ty = match arg.unpack() {
431                 GenericArgKind::Type(ty) => ty,
432
433                 // No WF constraints for lifetimes being present, any outlives
434                 // obligations are handled by the parent (e.g. `ty::Ref`).
435                 GenericArgKind::Lifetime(_) => continue,
436
437                 GenericArgKind::Const(constant) => {
438                     match constant.val {
439                         ty::ConstKind::Unevaluated(uv) => {
440                             assert!(uv.promoted.is_none());
441                             let substs = uv.substs(self.tcx());
442
443                             let obligations = self.nominal_obligations(uv.def.did, substs);
444                             self.out.extend(obligations);
445
446                             let predicate = ty::Binder::dummy(ty::PredicateKind::ConstEvaluatable(
447                                 ty::Unevaluated::new(uv.def, substs),
448                             ))
449                             .to_predicate(self.tcx());
450                             let cause = self.cause(traits::MiscObligation);
451                             self.out.push(traits::Obligation::with_depth(
452                                 cause,
453                                 self.recursion_depth,
454                                 self.param_env,
455                                 predicate,
456                             ));
457                         }
458                         ty::ConstKind::Infer(infer) => {
459                             let resolved = self.infcx.shallow_resolve(infer);
460                             // the `InferConst` changed, meaning that we made progress.
461                             if resolved != infer {
462                                 let cause = self.cause(traits::MiscObligation);
463
464                                 let resolved_constant = self.infcx.tcx.mk_const(ty::Const {
465                                     val: ty::ConstKind::Infer(resolved),
466                                     ..*constant
467                                 });
468                                 self.out.push(traits::Obligation::with_depth(
469                                     cause,
470                                     self.recursion_depth,
471                                     self.param_env,
472                                     ty::Binder::dummy(ty::PredicateKind::WellFormed(
473                                         resolved_constant.into(),
474                                     ))
475                                     .to_predicate(self.tcx()),
476                                 ));
477                             }
478                         }
479                         ty::ConstKind::Error(_)
480                         | ty::ConstKind::Param(_)
481                         | ty::ConstKind::Bound(..)
482                         | ty::ConstKind::Placeholder(..) => {
483                             // These variants are trivially WF, so nothing to do here.
484                         }
485                         ty::ConstKind::Value(..) => {
486                             // FIXME: Enforce that values are structurally-matchable.
487                         }
488                     }
489                     continue;
490                 }
491             };
492
493             match *ty.kind() {
494                 ty::Bool
495                 | ty::Char
496                 | ty::Int(..)
497                 | ty::Uint(..)
498                 | ty::Float(..)
499                 | ty::Error(_)
500                 | ty::Str
501                 | ty::GeneratorWitness(..)
502                 | ty::Never
503                 | ty::Param(_)
504                 | ty::Bound(..)
505                 | ty::Placeholder(..)
506                 | ty::Foreign(..) => {
507                     // WfScalar, WfParameter, etc
508                 }
509
510                 // Can only infer to `ty::Int(_) | ty::Uint(_)`.
511                 ty::Infer(ty::IntVar(_)) => {}
512
513                 // Can only infer to `ty::Float(_)`.
514                 ty::Infer(ty::FloatVar(_)) => {}
515
516                 ty::Slice(subty) => {
517                     self.require_sized(subty, traits::SliceOrArrayElem);
518                 }
519
520                 ty::Array(subty, _) => {
521                     self.require_sized(subty, traits::SliceOrArrayElem);
522                     // Note that we handle the len is implicitly checked while walking `arg`.
523                 }
524
525                 ty::Tuple(ref tys) => {
526                     if let Some((_last, rest)) = tys.split_last() {
527                         for elem in rest {
528                             self.require_sized(elem.expect_ty(), traits::TupleElem);
529                         }
530                     }
531                 }
532
533                 ty::RawPtr(_) => {
534                     // Simple cases that are WF if their type args are WF.
535                 }
536
537                 ty::Projection(data) => {
538                     walker.skip_current_subtree(); // Subtree handled by compute_projection.
539                     self.compute_projection(data);
540                 }
541
542                 ty::Adt(def, substs) => {
543                     // WfNominalType
544                     let obligations = self.nominal_obligations(def.did, substs);
545                     self.out.extend(obligations);
546                 }
547
548                 ty::FnDef(did, substs) => {
549                     let obligations = self.nominal_obligations(did, substs);
550                     self.out.extend(obligations);
551                 }
552
553                 ty::Ref(r, rty, _) => {
554                     // WfReference
555                     if !r.has_escaping_bound_vars() && !rty.has_escaping_bound_vars() {
556                         let cause = self.cause(traits::ReferenceOutlivesReferent(ty));
557                         self.out.push(traits::Obligation::with_depth(
558                             cause,
559                             depth,
560                             param_env,
561                             ty::Binder::dummy(ty::PredicateKind::TypeOutlives(
562                                 ty::OutlivesPredicate(rty, r),
563                             ))
564                             .to_predicate(self.tcx()),
565                         ));
566                     }
567                 }
568
569                 ty::Generator(..) => {
570                     // Walk ALL the types in the generator: this will
571                     // include the upvar types as well as the yield
572                     // type. Note that this is mildly distinct from
573                     // the closure case, where we have to be careful
574                     // about the signature of the closure. We don't
575                     // have the problem of implied bounds here since
576                     // generators don't take arguments.
577                 }
578
579                 ty::Closure(_, substs) => {
580                     // Only check the upvar types for WF, not the rest
581                     // of the types within. This is needed because we
582                     // capture the signature and it may not be WF
583                     // without the implied bounds. Consider a closure
584                     // like `|x: &'a T|` -- it may be that `T: 'a` is
585                     // not known to hold in the creator's context (and
586                     // indeed the closure may not be invoked by its
587                     // creator, but rather turned to someone who *can*
588                     // verify that).
589                     //
590                     // The special treatment of closures here really
591                     // ought not to be necessary either; the problem
592                     // is related to #25860 -- there is no way for us
593                     // to express a fn type complete with the implied
594                     // bounds that it is assuming. I think in reality
595                     // the WF rules around fn are a bit messed up, and
596                     // that is the rot problem: `fn(&'a T)` should
597                     // probably always be WF, because it should be
598                     // shorthand for something like `where(T: 'a) {
599                     // fn(&'a T) }`, as discussed in #25860.
600                     //
601                     // Note that we are also skipping the generic
602                     // types. This is consistent with the `outlives`
603                     // code, but anyway doesn't matter: within the fn
604                     // body where they are created, the generics will
605                     // always be WF, and outside of that fn body we
606                     // are not directly inspecting closure types
607                     // anyway, except via auto trait matching (which
608                     // only inspects the upvar types).
609                     walker.skip_current_subtree(); // subtree handled below
610                     // FIXME(eddyb) add the type to `walker` instead of recursing.
611                     self.compute(substs.as_closure().tupled_upvars_ty().into());
612                 }
613
614                 ty::FnPtr(_) => {
615                     // let the loop iterate into the argument/return
616                     // types appearing in the fn signature
617                 }
618
619                 ty::Opaque(did, substs) => {
620                     // all of the requirements on type parameters
621                     // should've been checked by the instantiation
622                     // of whatever returned this exact `impl Trait`.
623
624                     // for named opaque `impl Trait` types we still need to check them
625                     if ty::is_impl_trait_defn(self.infcx.tcx, did).is_none() {
626                         let obligations = self.nominal_obligations(did, substs);
627                         self.out.extend(obligations);
628                     }
629                 }
630
631                 ty::Dynamic(data, r) => {
632                     // WfObject
633                     //
634                     // Here, we defer WF checking due to higher-ranked
635                     // regions. This is perhaps not ideal.
636                     self.from_object_ty(ty, data, r);
637
638                     // FIXME(#27579) RFC also considers adding trait
639                     // obligations that don't refer to Self and
640                     // checking those
641
642                     let defer_to_coercion = self.tcx().features().object_safe_for_dispatch;
643
644                     if !defer_to_coercion {
645                         let cause = self.cause(traits::MiscObligation);
646                         let component_traits = data.auto_traits().chain(data.principal_def_id());
647                         let tcx = self.tcx();
648                         self.out.extend(component_traits.map(|did| {
649                             traits::Obligation::with_depth(
650                                 cause.clone(),
651                                 depth,
652                                 param_env,
653                                 ty::Binder::dummy(ty::PredicateKind::ObjectSafe(did))
654                                     .to_predicate(tcx),
655                             )
656                         }));
657                     }
658                 }
659
660                 // Inference variables are the complicated case, since we don't
661                 // know what type they are. We do two things:
662                 //
663                 // 1. Check if they have been resolved, and if so proceed with
664                 //    THAT type.
665                 // 2. If not, we've at least simplified things (e.g., we went
666                 //    from `Vec<$0>: WF` to `$0: WF`), so we can
667                 //    register a pending obligation and keep
668                 //    moving. (Goal is that an "inductive hypothesis"
669                 //    is satisfied to ensure termination.)
670                 // See also the comment on `fn obligations`, describing "livelock"
671                 // prevention, which happens before this can be reached.
672                 ty::Infer(_) => {
673                     let ty = self.infcx.shallow_resolve(ty);
674                     if let ty::Infer(ty::TyVar(_)) = ty.kind() {
675                         // Not yet resolved, but we've made progress.
676                         let cause = self.cause(traits::MiscObligation);
677                         self.out.push(traits::Obligation::with_depth(
678                             cause,
679                             self.recursion_depth,
680                             param_env,
681                             ty::Binder::dummy(ty::PredicateKind::WellFormed(ty.into()))
682                                 .to_predicate(self.tcx()),
683                         ));
684                     } else {
685                         // Yes, resolved, proceed with the result.
686                         // FIXME(eddyb) add the type to `walker` instead of recursing.
687                         self.compute(ty.into());
688                     }
689                 }
690             }
691         }
692     }
693
694     fn nominal_obligations(
695         &mut self,
696         def_id: DefId,
697         substs: SubstsRef<'tcx>,
698     ) -> Vec<traits::PredicateObligation<'tcx>> {
699         let predicates = self.infcx.tcx.predicates_of(def_id);
700         let mut origins = vec![def_id; predicates.predicates.len()];
701         let mut head = predicates;
702         while let Some(parent) = head.parent {
703             head = self.infcx.tcx.predicates_of(parent);
704             origins.extend(iter::repeat(parent).take(head.predicates.len()));
705         }
706
707         let predicates = predicates.instantiate(self.infcx.tcx, substs);
708         debug_assert_eq!(predicates.predicates.len(), origins.len());
709
710         iter::zip(iter::zip(predicates.predicates, predicates.spans), origins.into_iter().rev())
711             .map(|((pred, span), origin_def_id)| {
712                 let cause = self.cause(traits::BindingObligation(origin_def_id, span));
713                 traits::Obligation::with_depth(cause, self.recursion_depth, self.param_env, pred)
714             })
715             .filter(|pred| !pred.has_escaping_bound_vars())
716             .collect()
717     }
718
719     fn from_object_ty(
720         &mut self,
721         ty: Ty<'tcx>,
722         data: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
723         region: ty::Region<'tcx>,
724     ) {
725         // Imagine a type like this:
726         //
727         //     trait Foo { }
728         //     trait Bar<'c> : 'c { }
729         //
730         //     &'b (Foo+'c+Bar<'d>)
731         //         ^
732         //
733         // In this case, the following relationships must hold:
734         //
735         //     'b <= 'c
736         //     'd <= 'c
737         //
738         // The first conditions is due to the normal region pointer
739         // rules, which say that a reference cannot outlive its
740         // referent.
741         //
742         // The final condition may be a bit surprising. In particular,
743         // you may expect that it would have been `'c <= 'd`, since
744         // usually lifetimes of outer things are conservative
745         // approximations for inner things. However, it works somewhat
746         // differently with trait objects: here the idea is that if the
747         // user specifies a region bound (`'c`, in this case) it is the
748         // "master bound" that *implies* that bounds from other traits are
749         // all met. (Remember that *all bounds* in a type like
750         // `Foo+Bar+Zed` must be met, not just one, hence if we write
751         // `Foo<'x>+Bar<'y>`, we know that the type outlives *both* 'x and
752         // 'y.)
753         //
754         // Note: in fact we only permit builtin traits, not `Bar<'d>`, I
755         // am looking forward to the future here.
756         if !data.has_escaping_bound_vars() && !region.has_escaping_bound_vars() {
757             let implicit_bounds = object_region_bounds(self.infcx.tcx, data);
758
759             let explicit_bound = region;
760
761             self.out.reserve(implicit_bounds.len());
762             for implicit_bound in implicit_bounds {
763                 let cause = self.cause(traits::ObjectTypeBound(ty, explicit_bound));
764                 let outlives =
765                     ty::Binder::dummy(ty::OutlivesPredicate(explicit_bound, implicit_bound));
766                 self.out.push(traits::Obligation::with_depth(
767                     cause,
768                     self.recursion_depth,
769                     self.param_env,
770                     outlives.to_predicate(self.infcx.tcx),
771                 ));
772             }
773         }
774     }
775 }
776
777 /// Given an object type like `SomeTrait + Send`, computes the lifetime
778 /// bounds that must hold on the elided self type. These are derived
779 /// from the declarations of `SomeTrait`, `Send`, and friends -- if
780 /// they declare `trait SomeTrait : 'static`, for example, then
781 /// `'static` would appear in the list. The hard work is done by
782 /// `infer::required_region_bounds`, see that for more information.
783 pub fn object_region_bounds<'tcx>(
784     tcx: TyCtxt<'tcx>,
785     existential_predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
786 ) -> Vec<ty::Region<'tcx>> {
787     // Since we don't actually *know* the self type for an object,
788     // this "open(err)" serves as a kind of dummy standin -- basically
789     // a placeholder type.
790     let open_ty = tcx.mk_ty_infer(ty::FreshTy(0));
791
792     let predicates = existential_predicates.iter().filter_map(|predicate| {
793         if let ty::ExistentialPredicate::Projection(_) = predicate.skip_binder() {
794             None
795         } else {
796             Some(predicate.with_self_ty(tcx, open_ty))
797         }
798     });
799
800     required_region_bounds(tcx, open_ty, predicates)
801 }