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