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