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