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