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