]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/wf.rs
Rollup merge of #104245 - kubycsolutions:master, r=jyn514
[rust.git] / compiler / rustc_trait_selection / src / traits / wf.rs
1 use crate::infer::InferCtxt;
2 use crate::traits;
3 use rustc_hir as hir;
4 use rustc_hir::def_id::DefId;
5 use rustc_hir::lang_items::LangItem;
6 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, SubstsRef};
7 use rustc_middle::ty::{self, ToPredicate, Ty, TyCtxt, TypeVisitable};
8 use rustc_span::Span;
9
10 use std::iter;
11 /// Returns the set of obligations needed to make `arg` well-formed.
12 /// If `arg` contains unresolved inference variables, this may include
13 /// further WF obligations. However, if `arg` IS an unresolved
14 /// inference variable, returns `None`, because we are not able to
15 /// make any progress at all. This is to prevent "livelock" where we
16 /// say "$0 is WF if $0 is WF".
17 pub fn obligations<'tcx>(
18     infcx: &InferCtxt<'tcx>,
19     param_env: ty::ParamEnv<'tcx>,
20     body_id: hir::HirId,
21     recursion_depth: usize,
22     arg: GenericArg<'tcx>,
23     span: Span,
24 ) -> Option<Vec<traits::PredicateObligation<'tcx>>> {
25     // Handle the "livelock" case (see comment above) by bailing out if necessary.
26     let arg = match arg.unpack() {
27         GenericArgKind::Type(ty) => {
28             match ty.kind() {
29                 ty::Infer(ty::TyVar(_)) => {
30                     let resolved_ty = infcx.shallow_resolve(ty);
31                     if resolved_ty == ty {
32                         // No progress, bail out to prevent "livelock".
33                         return None;
34                     } else {
35                         resolved_ty
36                     }
37                 }
38                 _ => ty,
39             }
40             .into()
41         }
42         GenericArgKind::Const(ct) => {
43             match ct.kind() {
44                 ty::ConstKind::Infer(_) => {
45                     let resolved = infcx.shallow_resolve(ct);
46                     if resolved == ct {
47                         // No progress.
48                         return None;
49                     } else {
50                         resolved
51                     }
52                 }
53                 _ => ct,
54             }
55             .into()
56         }
57         // There is nothing we have to do for lifetimes.
58         GenericArgKind::Lifetime(..) => return Some(Vec::new()),
59     };
60
61     let mut wf = WfPredicates {
62         tcx: infcx.tcx,
63         param_env,
64         body_id,
65         span,
66         out: vec![],
67         recursion_depth,
68         item: None,
69     };
70     wf.compute(arg);
71     debug!("wf::obligations({:?}, body_id={:?}) = {:?}", arg, body_id, wf.out);
72
73     let result = wf.normalize(infcx);
74     debug!("wf::obligations({:?}, body_id={:?}) ~~> {:?}", arg, body_id, result);
75     Some(result)
76 }
77
78 /// Returns the obligations that make this trait reference
79 /// well-formed.  For example, if there is a trait `Set` defined like
80 /// `trait Set<K:Eq>`, then the trait reference `Foo: Set<Bar>` is WF
81 /// if `Bar: Eq`.
82 pub fn trait_obligations<'tcx>(
83     infcx: &InferCtxt<'tcx>,
84     param_env: ty::ParamEnv<'tcx>,
85     body_id: hir::HirId,
86     trait_pred: &ty::TraitPredicate<'tcx>,
87     span: Span,
88     item: &'tcx hir::Item<'tcx>,
89 ) -> Vec<traits::PredicateObligation<'tcx>> {
90     let mut wf = WfPredicates {
91         tcx: infcx.tcx,
92         param_env,
93         body_id,
94         span,
95         out: vec![],
96         recursion_depth: 0,
97         item: Some(item),
98     };
99     wf.compute_trait_pred(trait_pred, Elaborate::All);
100     debug!(obligations = ?wf.out);
101     wf.normalize(infcx)
102 }
103
104 #[instrument(skip(infcx), ret)]
105 pub fn predicate_obligations<'tcx>(
106     infcx: &InferCtxt<'tcx>,
107     param_env: ty::ParamEnv<'tcx>,
108     body_id: hir::HirId,
109     predicate: ty::Predicate<'tcx>,
110     span: Span,
111 ) -> Vec<traits::PredicateObligation<'tcx>> {
112     let mut wf = WfPredicates {
113         tcx: infcx.tcx,
114         param_env,
115         body_id,
116         span,
117         out: vec![],
118         recursion_depth: 0,
119         item: None,
120     };
121
122     // It's ok to skip the binder here because wf code is prepared for it
123     match predicate.kind().skip_binder() {
124         ty::PredicateKind::Trait(t) => {
125             wf.compute_trait_pred(&t, Elaborate::None);
126         }
127         ty::PredicateKind::RegionOutlives(..) => {}
128         ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
129             wf.compute(ty.into());
130         }
131         ty::PredicateKind::Projection(t) => {
132             wf.compute_projection(t.projection_ty);
133             wf.compute(match t.term.unpack() {
134                 ty::TermKind::Ty(ty) => ty.into(),
135                 ty::TermKind::Const(c) => c.into(),
136             })
137         }
138         ty::PredicateKind::WellFormed(arg) => {
139             wf.compute(arg);
140         }
141         ty::PredicateKind::ObjectSafe(_) => {}
142         ty::PredicateKind::ClosureKind(..) => {}
143         ty::PredicateKind::Subtype(ty::SubtypePredicate { a, b, a_is_expected: _ }) => {
144             wf.compute(a.into());
145             wf.compute(b.into());
146         }
147         ty::PredicateKind::Coerce(ty::CoercePredicate { a, b }) => {
148             wf.compute(a.into());
149             wf.compute(b.into());
150         }
151         ty::PredicateKind::ConstEvaluatable(ct) => {
152             wf.compute(ct.into());
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(infcx)
164 }
165
166 struct WfPredicates<'tcx> {
167     tcx: TyCtxt<'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_), owner_id, .. }) => {
218             (impl_.items, *owner_id)
219         }
220         _ => return,
221     };
222     let fix_span =
223         |impl_item_ref: &hir::ImplItemRef| match tcx.hir().impl_item(impl_item_ref.id).kind {
224             hir::ImplItemKind::Const(ty, _) | hir::ImplItemKind::Type(ty) => ty.span,
225             _ => impl_item_ref.span,
226         };
227
228     // It is fine to skip the binder as we don't care about regions here.
229     match pred.kind().skip_binder() {
230         ty::PredicateKind::Projection(proj) => {
231             // The obligation comes not from the current `impl` nor the `trait` being implemented,
232             // but rather from a "second order" obligation, where an associated type has a
233             // projection coming from another associated type. See
234             // `src/test/ui/associated-types/point-at-type-on-obligation-failure.rs` and
235             // `traits-assoc-type-in-supertrait-bad.rs`.
236             if let Some(ty::Projection(projection_ty)) = proj.term.ty().map(|ty| ty.kind())
237                 && let Some(&impl_item_id) =
238                     tcx.impl_item_implementor_ids(impl_def_id).get(&projection_ty.item_def_id)
239                 && let Some(impl_item_span) = items
240                     .iter()
241                     .find(|item| item.id.owner_id.to_def_id() == impl_item_id)
242                     .map(fix_span)
243             {
244                 cause.span = impl_item_span;
245             }
246         }
247         ty::PredicateKind::Trait(pred) => {
248             // An associated item obligation born out of the `trait` failed to be met. An example
249             // can be seen in `ui/associated-types/point-at-type-on-obligation-failure-2.rs`.
250             debug!("extended_cause_with_original_assoc_item_obligation trait proj {:?}", pred);
251             if let ty::Projection(ty::ProjectionTy { item_def_id, .. }) = *pred.self_ty().kind()
252                 && let Some(&impl_item_id) =
253                     tcx.impl_item_implementor_ids(impl_def_id).get(&item_def_id)
254                 && let Some(impl_item_span) = items
255                     .iter()
256                     .find(|item| item.id.owner_id.to_def_id() == impl_item_id)
257                     .map(fix_span)
258             {
259                 cause.span = impl_item_span;
260             }
261         }
262         _ => {}
263     }
264 }
265
266 impl<'tcx> WfPredicates<'tcx> {
267     fn tcx(&self) -> TyCtxt<'tcx> {
268         self.tcx
269     }
270
271     fn cause(&self, code: traits::ObligationCauseCode<'tcx>) -> traits::ObligationCause<'tcx> {
272         traits::ObligationCause::new(self.span, self.body_id, code)
273     }
274
275     fn normalize(self, infcx: &InferCtxt<'tcx>) -> Vec<traits::PredicateObligation<'tcx>> {
276         let cause = self.cause(traits::WellFormed(None));
277         let param_env = self.param_env;
278         let mut obligations = Vec::with_capacity(self.out.len());
279         for mut obligation in self.out {
280             assert!(!obligation.has_escaping_bound_vars());
281             let mut selcx = traits::SelectionContext::new(infcx);
282             // Don't normalize the whole obligation, the param env is either
283             // already normalized, or we're currently normalizing the
284             // param_env. Either way we should only normalize the predicate.
285             let normalized_predicate = traits::project::normalize_with_depth_to(
286                 &mut selcx,
287                 param_env,
288                 cause.clone(),
289                 self.recursion_depth,
290                 obligation.predicate,
291                 &mut obligations,
292             );
293             obligation.predicate = normalized_predicate;
294             obligations.push(obligation);
295         }
296         obligations
297     }
298
299     /// Pushes the obligations required for `trait_ref` to be WF into `self.out`.
300     fn compute_trait_pred(&mut self, trait_pred: &ty::TraitPredicate<'tcx>, elaborate: Elaborate) {
301         let tcx = self.tcx;
302         let trait_ref = &trait_pred.trait_ref;
303
304         // if the trait predicate is not const, the wf obligations should not be const as well.
305         let obligations = if trait_pred.constness == ty::BoundConstness::NotConst {
306             self.nominal_obligations_without_const(trait_ref.def_id, trait_ref.substs)
307         } else {
308             self.nominal_obligations(trait_ref.def_id, trait_ref.substs)
309         };
310
311         debug!("compute_trait_pred obligations {:?}", obligations);
312         let param_env = self.param_env;
313         let depth = self.recursion_depth;
314
315         let item = self.item;
316
317         let extend = |traits::PredicateObligation { predicate, mut cause, .. }| {
318             if let Some(parent_trait_pred) = predicate.to_opt_poly_trait_pred() {
319                 cause = cause.derived_cause(
320                     parent_trait_pred,
321                     traits::ObligationCauseCode::DerivedObligation,
322                 );
323             }
324             extend_cause_with_original_assoc_item_obligation(
325                 tcx, trait_ref, item, &mut cause, predicate,
326             );
327             traits::Obligation::with_depth(cause, depth, param_env, predicate)
328         };
329
330         if let Elaborate::All = elaborate {
331             let implied_obligations = traits::util::elaborate_obligations(tcx, obligations);
332             let implied_obligations = implied_obligations.map(extend);
333             self.out.extend(implied_obligations);
334         } else {
335             self.out.extend(obligations);
336         }
337
338         let tcx = self.tcx();
339         self.out.extend(
340             trait_ref
341                 .substs
342                 .iter()
343                 .enumerate()
344                 .filter(|(_, arg)| {
345                     matches!(arg.unpack(), GenericArgKind::Type(..) | GenericArgKind::Const(..))
346                 })
347                 .filter(|(_, arg)| !arg.has_escaping_bound_vars())
348                 .map(|(i, arg)| {
349                     let mut cause = traits::ObligationCause::misc(self.span, self.body_id);
350                     // The first subst is the self ty - use the correct span for it.
351                     if i == 0 {
352                         if let Some(hir::ItemKind::Impl(hir::Impl { self_ty, .. })) =
353                             item.map(|i| &i.kind)
354                         {
355                             cause.span = self_ty.span;
356                         }
357                     }
358                     traits::Obligation::with_depth(
359                         cause,
360                         depth,
361                         param_env,
362                         ty::Binder::dummy(ty::PredicateKind::WellFormed(arg)).to_predicate(tcx),
363                     )
364                 }),
365         );
366     }
367
368     /// Pushes the obligations required for `trait_ref::Item` to be WF
369     /// into `self.out`.
370     fn compute_projection(&mut self, data: ty::ProjectionTy<'tcx>) {
371         // A projection is well-formed if
372         //
373         // (a) its predicates hold (*)
374         // (b) its substs are wf
375         //
376         // (*) The predicates of an associated type include the predicates of
377         //     the trait that it's contained in. For example, given
378         //
379         // trait A<T>: Clone {
380         //     type X where T: Copy;
381         // }
382         //
383         // The predicates of `<() as A<i32>>::X` are:
384         // [
385         //     `(): Sized`
386         //     `(): Clone`
387         //     `(): A<i32>`
388         //     `i32: Sized`
389         //     `i32: Clone`
390         //     `i32: Copy`
391         // ]
392         // Projection types do not require const predicates.
393         let obligations = self.nominal_obligations_without_const(data.item_def_id, data.substs);
394         self.out.extend(obligations);
395
396         let tcx = self.tcx();
397         let cause = self.cause(traits::WellFormed(None));
398         let param_env = self.param_env;
399         let depth = self.recursion_depth;
400
401         self.out.extend(
402             data.substs
403                 .iter()
404                 .filter(|arg| {
405                     matches!(arg.unpack(), GenericArgKind::Type(..) | GenericArgKind::Const(..))
406                 })
407                 .filter(|arg| !arg.has_escaping_bound_vars())
408                 .map(|arg| {
409                     traits::Obligation::with_depth(
410                         cause.clone(),
411                         depth,
412                         param_env,
413                         ty::Binder::dummy(ty::PredicateKind::WellFormed(arg)).to_predicate(tcx),
414                     )
415                 }),
416         );
417     }
418
419     fn require_sized(&mut self, subty: Ty<'tcx>, cause: traits::ObligationCauseCode<'tcx>) {
420         if !subty.has_escaping_bound_vars() {
421             let cause = self.cause(cause);
422             let trait_ref = ty::TraitRef {
423                 def_id: self.tcx.require_lang_item(LangItem::Sized, None),
424                 substs: self.tcx.mk_substs_trait(subty, &[]),
425             };
426             self.out.push(traits::Obligation::with_depth(
427                 cause,
428                 self.recursion_depth,
429                 self.param_env,
430                 ty::Binder::dummy(trait_ref).without_const().to_predicate(self.tcx),
431             ));
432         }
433     }
434
435     /// Pushes all the predicates needed to validate that `ty` is WF into `out`.
436     #[instrument(level = "debug", skip(self))]
437     fn compute(&mut self, arg: GenericArg<'tcx>) {
438         let mut walker = arg.walk();
439         let param_env = self.param_env;
440         let depth = self.recursion_depth;
441         while let Some(arg) = walker.next() {
442             debug!(?arg, ?self.out);
443             let ty = match arg.unpack() {
444                 GenericArgKind::Type(ty) => ty,
445
446                 // No WF constraints for lifetimes being present, any outlives
447                 // obligations are handled by the parent (e.g. `ty::Ref`).
448                 GenericArgKind::Lifetime(_) => continue,
449
450                 GenericArgKind::Const(ct) => {
451                     match ct.kind() {
452                         ty::ConstKind::Unevaluated(uv) => {
453                             let obligations = self.nominal_obligations(uv.def.did, uv.substs);
454                             self.out.extend(obligations);
455
456                             let predicate =
457                                 ty::Binder::dummy(ty::PredicateKind::ConstEvaluatable(ct))
458                                     .to_predicate(self.tcx());
459                             let cause = self.cause(traits::WellFormed(None));
460                             self.out.push(traits::Obligation::with_depth(
461                                 cause,
462                                 self.recursion_depth,
463                                 self.param_env,
464                                 predicate,
465                             ));
466                         }
467                         ty::ConstKind::Infer(_) => {
468                             let cause = self.cause(traits::WellFormed(None));
469
470                             self.out.push(traits::Obligation::with_depth(
471                                 cause,
472                                 self.recursion_depth,
473                                 self.param_env,
474                                 ty::Binder::dummy(ty::PredicateKind::WellFormed(ct.into()))
475                                     .to_predicate(self.tcx()),
476                             ));
477                         }
478                         ty::ConstKind::Error(_)
479                         | ty::ConstKind::Param(_)
480                         | ty::ConstKind::Bound(..)
481                         | ty::ConstKind::Placeholder(..) => {
482                             // These variants are trivially WF, so nothing to do here.
483                         }
484                         ty::ConstKind::Value(..) => {
485                             // FIXME: Enforce that values are structurally-matchable.
486                         }
487                     }
488                     continue;
489                 }
490             };
491
492             debug!("wf bounds for ty={:?} ty.kind={:#?}", ty, ty.kind());
493
494             match *ty.kind() {
495                 ty::Bool
496                 | ty::Char
497                 | ty::Int(..)
498                 | ty::Uint(..)
499                 | ty::Float(..)
500                 | ty::Error(_)
501                 | ty::Str
502                 | ty::GeneratorWitness(..)
503                 | ty::Never
504                 | ty::Param(_)
505                 | ty::Bound(..)
506                 | ty::Placeholder(..)
507                 | ty::Foreign(..) => {
508                     // WfScalar, WfParameter, etc
509                 }
510
511                 // Can only infer to `ty::Int(_) | ty::Uint(_)`.
512                 ty::Infer(ty::IntVar(_)) => {}
513
514                 // Can only infer to `ty::Float(_)`.
515                 ty::Infer(ty::FloatVar(_)) => {}
516
517                 ty::Slice(subty) => {
518                     self.require_sized(subty, traits::SliceOrArrayElem);
519                 }
520
521                 ty::Array(subty, _) => {
522                     self.require_sized(subty, traits::SliceOrArrayElem);
523                     // Note that we handle the len is implicitly checked while walking `arg`.
524                 }
525
526                 ty::Tuple(ref tys) => {
527                     if let Some((_last, rest)) = tys.split_last() {
528                         for &elem in rest {
529                             self.require_sized(elem, traits::TupleElem);
530                         }
531                     }
532                 }
533
534                 ty::RawPtr(_) => {
535                     // Simple cases that are WF if their type args are WF.
536                 }
537
538                 ty::Projection(data) => {
539                     walker.skip_current_subtree(); // Subtree handled by compute_projection.
540                     self.compute_projection(data);
541                 }
542
543                 ty::Adt(def, substs) => {
544                     // WfNominalType
545                     let obligations = self.nominal_obligations(def.did(), substs);
546                     self.out.extend(obligations);
547                 }
548
549                 ty::FnDef(did, substs) => {
550                     let obligations = self.nominal_obligations_without_const(did, substs);
551                     self.out.extend(obligations);
552                 }
553
554                 ty::Ref(r, rty, _) => {
555                     // WfReference
556                     if !r.has_escaping_bound_vars() && !rty.has_escaping_bound_vars() {
557                         let cause = self.cause(traits::ReferenceOutlivesReferent(ty));
558                         self.out.push(traits::Obligation::with_depth(
559                             cause,
560                             depth,
561                             param_env,
562                             ty::Binder::dummy(ty::PredicateKind::TypeOutlives(
563                                 ty::OutlivesPredicate(rty, r),
564                             ))
565                             .to_predicate(self.tcx()),
566                         ));
567                     }
568                 }
569
570                 ty::Generator(did, substs, ..) => {
571                     // Walk ALL the types in the generator: this will
572                     // include the upvar types as well as the yield
573                     // type. Note that this is mildly distinct from
574                     // the closure case, where we have to be careful
575                     // about the signature of the closure. We don't
576                     // have the problem of implied bounds here since
577                     // generators don't take arguments.
578                     let obligations = self.nominal_obligations(did, substs);
579                     self.out.extend(obligations);
580                 }
581
582                 ty::Closure(did, 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                     walker.skip_current_subtree(); // subtree handled below
604                     // FIXME(eddyb) add the type to `walker` instead of recursing.
605                     self.compute(substs.as_closure().tupled_upvars_ty().into());
606                     // Note that we cannot skip the generic types
607                     // types. Normally, 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                     // But when a closure is part of a type-alias-impl-trait
614                     // then the function that created the defining site may
615                     // have had more bounds available than the type alias
616                     // specifies. This may cause us to have a closure in the
617                     // hidden type that is not actually well formed and
618                     // can cause compiler crashes when the user abuses unsafe
619                     // code to procure such a closure.
620                     // See src/test/ui/type-alias-impl-trait/wf_check_closures.rs
621                     let obligations = self.nominal_obligations(did, substs);
622                     self.out.extend(obligations);
623                 }
624
625                 ty::FnPtr(_) => {
626                     // let the loop iterate into the argument/return
627                     // types appearing in the fn signature
628                 }
629
630                 ty::Opaque(did, substs) => {
631                     // All of the requirements on type parameters
632                     // have already been checked for `impl Trait` in
633                     // return position. We do need to check type-alias-impl-trait though.
634                     if ty::is_impl_trait_defn(self.tcx, did).is_none() {
635                         let obligations = self.nominal_obligations(did, substs);
636                         self.out.extend(obligations);
637                     }
638                 }
639
640                 ty::Dynamic(data, r, _) => {
641                     // WfObject
642                     //
643                     // Here, we defer WF checking due to higher-ranked
644                     // regions. This is perhaps not ideal.
645                     self.from_object_ty(ty, data, r);
646
647                     // FIXME(#27579) RFC also considers adding trait
648                     // obligations that don't refer to Self and
649                     // checking those
650
651                     let defer_to_coercion = self.tcx().features().object_safe_for_dispatch;
652
653                     if !defer_to_coercion {
654                         let cause = self.cause(traits::WellFormed(None));
655                         let component_traits = data.auto_traits().chain(data.principal_def_id());
656                         let tcx = self.tcx();
657                         self.out.extend(component_traits.map(|did| {
658                             traits::Obligation::with_depth(
659                                 cause.clone(),
660                                 depth,
661                                 param_env,
662                                 ty::Binder::dummy(ty::PredicateKind::ObjectSafe(did))
663                                     .to_predicate(tcx),
664                             )
665                         }));
666                     }
667                 }
668
669                 // Inference variables are the complicated case, since we don't
670                 // know what type they are. We do two things:
671                 //
672                 // 1. Check if they have been resolved, and if so proceed with
673                 //    THAT type.
674                 // 2. If not, we've at least simplified things (e.g., we went
675                 //    from `Vec<$0>: WF` to `$0: WF`), so we can
676                 //    register a pending obligation and keep
677                 //    moving. (Goal is that an "inductive hypothesis"
678                 //    is satisfied to ensure termination.)
679                 // See also the comment on `fn obligations`, describing "livelock"
680                 // prevention, which happens before this can be reached.
681                 ty::Infer(_) => {
682                     let cause = self.cause(traits::WellFormed(None));
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                 }
691             }
692
693             debug!(?self.out);
694         }
695     }
696
697     #[instrument(level = "debug", skip(self))]
698     fn nominal_obligations_inner(
699         &mut self,
700         def_id: DefId,
701         substs: SubstsRef<'tcx>,
702         remap_constness: bool,
703     ) -> Vec<traits::PredicateObligation<'tcx>> {
704         let predicates = self.tcx.predicates_of(def_id);
705         let mut origins = vec![def_id; predicates.predicates.len()];
706         let mut head = predicates;
707         while let Some(parent) = head.parent {
708             head = self.tcx.predicates_of(parent);
709             origins.extend(iter::repeat(parent).take(head.predicates.len()));
710         }
711
712         let predicates = predicates.instantiate(self.tcx, substs);
713         trace!("{:#?}", predicates);
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(|((mut pred, span), origin_def_id)| {
718                 let code = if span.is_dummy() {
719                     traits::ItemObligation(origin_def_id)
720                 } else {
721                     traits::BindingObligation(origin_def_id, span)
722                 };
723                 let cause = self.cause(code);
724                 if remap_constness {
725                     pred = pred.without_const(self.tcx);
726                 }
727                 traits::Obligation::with_depth(cause, self.recursion_depth, self.param_env, pred)
728             })
729             .filter(|pred| !pred.has_escaping_bound_vars())
730             .collect()
731     }
732
733     fn nominal_obligations(
734         &mut self,
735         def_id: DefId,
736         substs: SubstsRef<'tcx>,
737     ) -> Vec<traits::PredicateObligation<'tcx>> {
738         self.nominal_obligations_inner(def_id, substs, false)
739     }
740
741     fn nominal_obligations_without_const(
742         &mut self,
743         def_id: DefId,
744         substs: SubstsRef<'tcx>,
745     ) -> Vec<traits::PredicateObligation<'tcx>> {
746         self.nominal_obligations_inner(def_id, substs, true)
747     }
748
749     fn from_object_ty(
750         &mut self,
751         ty: Ty<'tcx>,
752         data: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
753         region: ty::Region<'tcx>,
754     ) {
755         // Imagine a type like this:
756         //
757         //     trait Foo { }
758         //     trait Bar<'c> : 'c { }
759         //
760         //     &'b (Foo+'c+Bar<'d>)
761         //         ^
762         //
763         // In this case, the following relationships must hold:
764         //
765         //     'b <= 'c
766         //     'd <= 'c
767         //
768         // The first conditions is due to the normal region pointer
769         // rules, which say that a reference cannot outlive its
770         // referent.
771         //
772         // The final condition may be a bit surprising. In particular,
773         // you may expect that it would have been `'c <= 'd`, since
774         // usually lifetimes of outer things are conservative
775         // approximations for inner things. However, it works somewhat
776         // differently with trait objects: here the idea is that if the
777         // user specifies a region bound (`'c`, in this case) it is the
778         // "master bound" that *implies* that bounds from other traits are
779         // all met. (Remember that *all bounds* in a type like
780         // `Foo+Bar+Zed` must be met, not just one, hence if we write
781         // `Foo<'x>+Bar<'y>`, we know that the type outlives *both* 'x and
782         // 'y.)
783         //
784         // Note: in fact we only permit builtin traits, not `Bar<'d>`, I
785         // am looking forward to the future here.
786         if !data.has_escaping_bound_vars() && !region.has_escaping_bound_vars() {
787             let implicit_bounds = object_region_bounds(self.tcx, data);
788
789             let explicit_bound = region;
790
791             self.out.reserve(implicit_bounds.len());
792             for implicit_bound in implicit_bounds {
793                 let cause = self.cause(traits::ObjectTypeBound(ty, explicit_bound));
794                 let outlives =
795                     ty::Binder::dummy(ty::OutlivesPredicate(explicit_bound, implicit_bound));
796                 self.out.push(traits::Obligation::with_depth(
797                     cause,
798                     self.recursion_depth,
799                     self.param_env,
800                     outlives.to_predicate(self.tcx),
801                 ));
802             }
803         }
804     }
805 }
806
807 /// Given an object type like `SomeTrait + Send`, computes the lifetime
808 /// bounds that must hold on the elided self type. These are derived
809 /// from the declarations of `SomeTrait`, `Send`, and friends -- if
810 /// they declare `trait SomeTrait : 'static`, for example, then
811 /// `'static` would appear in the list. The hard work is done by
812 /// `infer::required_region_bounds`, see that for more information.
813 pub fn object_region_bounds<'tcx>(
814     tcx: TyCtxt<'tcx>,
815     existential_predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
816 ) -> Vec<ty::Region<'tcx>> {
817     // Since we don't actually *know* the self type for an object,
818     // this "open(err)" serves as a kind of dummy standin -- basically
819     // a placeholder type.
820     let open_ty = tcx.mk_ty_infer(ty::FreshTy(0));
821
822     let predicates = existential_predicates.iter().filter_map(|predicate| {
823         if let ty::ExistentialPredicate::Projection(_) = predicate.skip_binder() {
824             None
825         } else {
826             Some(predicate.with_self_ty(tcx, open_ty))
827         }
828     });
829
830     required_region_bounds(tcx, open_ty, predicates)
831 }
832
833 /// Given a set of predicates that apply to an object type, returns
834 /// the region bounds that the (erased) `Self` type must
835 /// outlive. Precisely *because* the `Self` type is erased, the
836 /// parameter `erased_self_ty` must be supplied to indicate what type
837 /// has been used to represent `Self` in the predicates
838 /// themselves. This should really be a unique type; `FreshTy(0)` is a
839 /// popular choice.
840 ///
841 /// N.B., in some cases, particularly around higher-ranked bounds,
842 /// this function returns a kind of conservative approximation.
843 /// That is, all regions returned by this function are definitely
844 /// required, but there may be other region bounds that are not
845 /// returned, as well as requirements like `for<'a> T: 'a`.
846 ///
847 /// Requires that trait definitions have been processed so that we can
848 /// elaborate predicates and walk supertraits.
849 #[instrument(skip(tcx, predicates), level = "debug", ret)]
850 pub(crate) fn required_region_bounds<'tcx>(
851     tcx: TyCtxt<'tcx>,
852     erased_self_ty: Ty<'tcx>,
853     predicates: impl Iterator<Item = ty::Predicate<'tcx>>,
854 ) -> Vec<ty::Region<'tcx>> {
855     assert!(!erased_self_ty.has_escaping_bound_vars());
856
857     traits::elaborate_predicates(tcx, predicates)
858         .filter_map(|obligation| {
859             debug!(?obligation);
860             match obligation.predicate.kind().skip_binder() {
861                 ty::PredicateKind::Projection(..)
862                 | ty::PredicateKind::Trait(..)
863                 | ty::PredicateKind::Subtype(..)
864                 | ty::PredicateKind::Coerce(..)
865                 | ty::PredicateKind::WellFormed(..)
866                 | ty::PredicateKind::ObjectSafe(..)
867                 | ty::PredicateKind::ClosureKind(..)
868                 | ty::PredicateKind::RegionOutlives(..)
869                 | ty::PredicateKind::ConstEvaluatable(..)
870                 | ty::PredicateKind::ConstEquate(..)
871                 | ty::PredicateKind::TypeWellFormedFromEnv(..) => None,
872                 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ref t, ref r)) => {
873                     // Search for a bound of the form `erased_self_ty
874                     // : 'a`, but be wary of something like `for<'a>
875                     // erased_self_ty : 'a` (we interpret a
876                     // higher-ranked bound like that as 'static,
877                     // though at present the code in `fulfill.rs`
878                     // considers such bounds to be unsatisfiable, so
879                     // it's kind of a moot point since you could never
880                     // construct such an object, but this seems
881                     // correct even if that code changes).
882                     if t == &erased_self_ty && !r.has_escaping_bound_vars() {
883                         Some(*r)
884                     } else {
885                         None
886                     }
887                 }
888             }
889         })
890         .collect()
891 }