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