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