]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/wf.rs
Rollup merge of #101501 - Jarcho:tcx_lint_passes, r=davidtwco
[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.unpack() {
133                 ty::TermKind::Ty(ty) => ty.into(),
134                 ty::TermKind::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     #[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             let ty = match arg.unpack() {
444                 GenericArgKind::Type(ty) => ty,
445
446                 // No WF constraints for lifetimes being present, any outlives
447                 // obligations are handled by the parent (e.g. `ty::Ref`).
448                 GenericArgKind::Lifetime(_) => continue,
449
450                 GenericArgKind::Const(constant) => {
451                     match constant.kind() {
452                         ty::ConstKind::Unevaluated(uv) => {
453                             let obligations = self.nominal_obligations(uv.def.did, uv.substs);
454                             self.out.extend(obligations);
455
456                             let predicate =
457                                 ty::Binder::dummy(ty::PredicateKind::ConstEvaluatable(uv.shrink()))
458                                     .to_predicate(self.tcx());
459                             let cause = self.cause(traits::WellFormed(None));
460                             self.out.push(traits::Obligation::with_depth(
461                                 cause,
462                                 self.recursion_depth,
463                                 self.param_env,
464                                 predicate,
465                             ));
466                         }
467                         ty::ConstKind::Infer(_) => {
468                             let cause = self.cause(traits::WellFormed(None));
469
470                             self.out.push(traits::Obligation::with_depth(
471                                 cause,
472                                 self.recursion_depth,
473                                 self.param_env,
474                                 ty::Binder::dummy(ty::PredicateKind::WellFormed(constant.into()))
475                                     .to_predicate(self.tcx()),
476                             ));
477                         }
478                         ty::ConstKind::Error(_)
479                         | ty::ConstKind::Param(_)
480                         | ty::ConstKind::Bound(..)
481                         | ty::ConstKind::Placeholder(..) => {
482                             // These variants are trivially WF, so nothing to do here.
483                         }
484                         ty::ConstKind::Value(..) => {
485                             // FIXME: Enforce that values are structurally-matchable.
486                         }
487                     }
488                     continue;
489                 }
490             };
491
492             debug!("wf bounds for ty={:?} ty.kind={:#?}", ty, ty.kind());
493
494             match *ty.kind() {
495                 ty::Bool
496                 | ty::Char
497                 | ty::Int(..)
498                 | ty::Uint(..)
499                 | ty::Float(..)
500                 | ty::Error(_)
501                 | ty::Str
502                 | ty::GeneratorWitness(..)
503                 | ty::Never
504                 | ty::Param(_)
505                 | ty::Bound(..)
506                 | ty::Placeholder(..)
507                 | ty::Foreign(..) => {
508                     // WfScalar, WfParameter, etc
509                 }
510
511                 // Can only infer to `ty::Int(_) | ty::Uint(_)`.
512                 ty::Infer(ty::IntVar(_)) => {}
513
514                 // Can only infer to `ty::Float(_)`.
515                 ty::Infer(ty::FloatVar(_)) => {}
516
517                 ty::Slice(subty) => {
518                     self.require_sized(subty, traits::SliceOrArrayElem);
519                 }
520
521                 ty::Array(subty, _) => {
522                     self.require_sized(subty, traits::SliceOrArrayElem);
523                     // Note that we handle the len is implicitly checked while walking `arg`.
524                 }
525
526                 ty::Tuple(ref tys) => {
527                     if let Some((_last, rest)) = tys.split_last() {
528                         for &elem in rest {
529                             self.require_sized(elem, traits::TupleElem);
530                         }
531                     }
532                 }
533
534                 ty::RawPtr(_) => {
535                     // Simple cases that are WF if their type args are WF.
536                 }
537
538                 ty::Projection(data) => {
539                     walker.skip_current_subtree(); // Subtree handled by compute_projection.
540                     self.compute_projection(data);
541                 }
542
543                 ty::Adt(def, substs) => {
544                     // WfNominalType
545                     let obligations = self.nominal_obligations(def.did(), substs);
546                     self.out.extend(obligations);
547                 }
548
549                 ty::FnDef(did, substs) => {
550                     let obligations = self.nominal_obligations(did, substs);
551                     self.out.extend(obligations);
552                 }
553
554                 ty::Ref(r, rty, _) => {
555                     // WfReference
556                     if !r.has_escaping_bound_vars() && !rty.has_escaping_bound_vars() {
557                         let cause = self.cause(traits::ReferenceOutlivesReferent(ty));
558                         self.out.push(traits::Obligation::with_depth(
559                             cause,
560                             depth,
561                             param_env,
562                             ty::Binder::dummy(ty::PredicateKind::TypeOutlives(
563                                 ty::OutlivesPredicate(rty, r),
564                             ))
565                             .to_predicate(self.tcx()),
566                         ));
567                     }
568                 }
569
570                 ty::Generator(did, substs, ..) => {
571                     // Walk ALL the types in the generator: this will
572                     // include the upvar types as well as the yield
573                     // type. Note that this is mildly distinct from
574                     // the closure case, where we have to be careful
575                     // about the signature of the closure. We don't
576                     // have the problem of implied bounds here since
577                     // generators don't take arguments.
578                     let obligations = self.nominal_obligations(did, substs);
579                     self.out.extend(obligations);
580                 }
581
582                 ty::Closure(did, substs) => {
583                     // Only check the upvar types for WF, not the rest
584                     // of the types within. This is needed because we
585                     // capture the signature and it may not be WF
586                     // without the implied bounds. Consider a closure
587                     // like `|x: &'a T|` -- it may be that `T: 'a` is
588                     // not known to hold in the creator's context (and
589                     // indeed the closure may not be invoked by its
590                     // creator, but rather turned to someone who *can*
591                     // verify that).
592                     //
593                     // The special treatment of closures here really
594                     // ought not to be necessary either; the problem
595                     // is related to #25860 -- there is no way for us
596                     // to express a fn type complete with the implied
597                     // bounds that it is assuming. I think in reality
598                     // the WF rules around fn are a bit messed up, and
599                     // that is the rot problem: `fn(&'a T)` should
600                     // probably always be WF, because it should be
601                     // shorthand for something like `where(T: 'a) {
602                     // fn(&'a T) }`, as discussed in #25860.
603                     walker.skip_current_subtree(); // subtree handled below
604                     // FIXME(eddyb) add the type to `walker` instead of recursing.
605                     self.compute(substs.as_closure().tupled_upvars_ty().into());
606                     // Note that we cannot skip the generic types
607                     // types. Normally, within the fn
608                     // body where they are created, the generics will
609                     // always be WF, and outside of that fn body we
610                     // are not directly inspecting closure types
611                     // anyway, except via auto trait matching (which
612                     // only inspects the upvar types).
613                     // But when a closure is part of a type-alias-impl-trait
614                     // then the function that created the defining site may
615                     // have had more bounds available than the type alias
616                     // specifies. This may cause us to have a closure in the
617                     // hidden type that is not actually well formed and
618                     // can cause compiler crashes when the user abuses unsafe
619                     // code to procure such a closure.
620                     // See src/test/ui/type-alias-impl-trait/wf_check_closures.rs
621                     let obligations = self.nominal_obligations(did, substs);
622                     self.out.extend(obligations);
623                 }
624
625                 ty::FnPtr(_) => {
626                     // let the loop iterate into the argument/return
627                     // types appearing in the fn signature
628                 }
629
630                 ty::Opaque(did, substs) => {
631                     // All of the requirements on type parameters
632                     // have already been checked for `impl Trait` in
633                     // return position. We do need to check type-alias-impl-trait though.
634                     if ty::is_impl_trait_defn(self.tcx, did).is_none() {
635                         let obligations = self.nominal_obligations(did, substs);
636                         self.out.extend(obligations);
637                     }
638                 }
639
640                 ty::Dynamic(data, r) => {
641                     // WfObject
642                     //
643                     // Here, we defer WF checking due to higher-ranked
644                     // regions. This is perhaps not ideal.
645                     self.from_object_ty(ty, data, r);
646
647                     // FIXME(#27579) RFC also considers adding trait
648                     // obligations that don't refer to Self and
649                     // checking those
650
651                     let defer_to_coercion = self.tcx().features().object_safe_for_dispatch;
652
653                     if !defer_to_coercion {
654                         let cause = self.cause(traits::WellFormed(None));
655                         let component_traits = data.auto_traits().chain(data.principal_def_id());
656                         let tcx = self.tcx();
657                         self.out.extend(component_traits.map(|did| {
658                             traits::Obligation::with_depth(
659                                 cause.clone(),
660                                 depth,
661                                 param_env,
662                                 ty::Binder::dummy(ty::PredicateKind::ObjectSafe(did))
663                                     .to_predicate(tcx),
664                             )
665                         }));
666                     }
667                 }
668
669                 // Inference variables are the complicated case, since we don't
670                 // know what type they are. We do two things:
671                 //
672                 // 1. Check if they have been resolved, and if so proceed with
673                 //    THAT type.
674                 // 2. If not, we've at least simplified things (e.g., we went
675                 //    from `Vec<$0>: WF` to `$0: WF`), so we can
676                 //    register a pending obligation and keep
677                 //    moving. (Goal is that an "inductive hypothesis"
678                 //    is satisfied to ensure termination.)
679                 // See also the comment on `fn obligations`, describing "livelock"
680                 // prevention, which happens before this can be reached.
681                 ty::Infer(_) => {
682                     let cause = self.cause(traits::WellFormed(None));
683                     self.out.push(traits::Obligation::with_depth(
684                         cause,
685                         self.recursion_depth,
686                         param_env,
687                         ty::Binder::dummy(ty::PredicateKind::WellFormed(ty.into()))
688                             .to_predicate(self.tcx()),
689                     ));
690                 }
691             }
692         }
693     }
694
695     #[instrument(level = "debug", skip(self))]
696     fn nominal_obligations_inner(
697         &mut self,
698         def_id: DefId,
699         substs: SubstsRef<'tcx>,
700         remap_constness: bool,
701     ) -> Vec<traits::PredicateObligation<'tcx>> {
702         let predicates = self.tcx.predicates_of(def_id);
703         let mut origins = vec![def_id; predicates.predicates.len()];
704         let mut head = predicates;
705         while let Some(parent) = head.parent {
706             head = self.tcx.predicates_of(parent);
707             origins.extend(iter::repeat(parent).take(head.predicates.len()));
708         }
709
710         let predicates = predicates.instantiate(self.tcx, substs);
711         trace!("{:#?}", predicates);
712         debug_assert_eq!(predicates.predicates.len(), origins.len());
713
714         iter::zip(iter::zip(predicates.predicates, predicates.spans), origins.into_iter().rev())
715             .map(|((mut pred, span), origin_def_id)| {
716                 let code = if span.is_dummy() {
717                     traits::ItemObligation(origin_def_id)
718                 } else {
719                     traits::BindingObligation(origin_def_id, span)
720                 };
721                 let cause = self.cause(code);
722                 if remap_constness {
723                     pred = pred.without_const(self.tcx);
724                 }
725                 traits::Obligation::with_depth(cause, self.recursion_depth, self.param_env, pred)
726             })
727             .filter(|pred| !pred.has_escaping_bound_vars())
728             .collect()
729     }
730
731     fn nominal_obligations(
732         &mut self,
733         def_id: DefId,
734         substs: SubstsRef<'tcx>,
735     ) -> Vec<traits::PredicateObligation<'tcx>> {
736         self.nominal_obligations_inner(def_id, substs, false)
737     }
738
739     fn nominal_obligations_without_const(
740         &mut self,
741         def_id: DefId,
742         substs: SubstsRef<'tcx>,
743     ) -> Vec<traits::PredicateObligation<'tcx>> {
744         self.nominal_obligations_inner(def_id, substs, true)
745     }
746
747     fn from_object_ty(
748         &mut self,
749         ty: Ty<'tcx>,
750         data: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
751         region: ty::Region<'tcx>,
752     ) {
753         // Imagine a type like this:
754         //
755         //     trait Foo { }
756         //     trait Bar<'c> : 'c { }
757         //
758         //     &'b (Foo+'c+Bar<'d>)
759         //         ^
760         //
761         // In this case, the following relationships must hold:
762         //
763         //     'b <= 'c
764         //     'd <= 'c
765         //
766         // The first conditions is due to the normal region pointer
767         // rules, which say that a reference cannot outlive its
768         // referent.
769         //
770         // The final condition may be a bit surprising. In particular,
771         // you may expect that it would have been `'c <= 'd`, since
772         // usually lifetimes of outer things are conservative
773         // approximations for inner things. However, it works somewhat
774         // differently with trait objects: here the idea is that if the
775         // user specifies a region bound (`'c`, in this case) it is the
776         // "master bound" that *implies* that bounds from other traits are
777         // all met. (Remember that *all bounds* in a type like
778         // `Foo+Bar+Zed` must be met, not just one, hence if we write
779         // `Foo<'x>+Bar<'y>`, we know that the type outlives *both* 'x and
780         // 'y.)
781         //
782         // Note: in fact we only permit builtin traits, not `Bar<'d>`, I
783         // am looking forward to the future here.
784         if !data.has_escaping_bound_vars() && !region.has_escaping_bound_vars() {
785             let implicit_bounds = object_region_bounds(self.tcx, data);
786
787             let explicit_bound = region;
788
789             self.out.reserve(implicit_bounds.len());
790             for implicit_bound in implicit_bounds {
791                 let cause = self.cause(traits::ObjectTypeBound(ty, explicit_bound));
792                 let outlives =
793                     ty::Binder::dummy(ty::OutlivesPredicate(explicit_bound, implicit_bound));
794                 self.out.push(traits::Obligation::with_depth(
795                     cause,
796                     self.recursion_depth,
797                     self.param_env,
798                     outlives.to_predicate(self.tcx),
799                 ));
800             }
801         }
802     }
803 }
804
805 /// Given an object type like `SomeTrait + Send`, computes the lifetime
806 /// bounds that must hold on the elided self type. These are derived
807 /// from the declarations of `SomeTrait`, `Send`, and friends -- if
808 /// they declare `trait SomeTrait : 'static`, for example, then
809 /// `'static` would appear in the list. The hard work is done by
810 /// `infer::required_region_bounds`, see that for more information.
811 pub fn object_region_bounds<'tcx>(
812     tcx: TyCtxt<'tcx>,
813     existential_predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
814 ) -> Vec<ty::Region<'tcx>> {
815     // Since we don't actually *know* the self type for an object,
816     // this "open(err)" serves as a kind of dummy standin -- basically
817     // a placeholder type.
818     let open_ty = tcx.mk_ty_infer(ty::FreshTy(0));
819
820     let predicates = existential_predicates.iter().filter_map(|predicate| {
821         if let ty::ExistentialPredicate::Projection(_) = predicate.skip_binder() {
822             None
823         } else {
824             Some(predicate.with_self_ty(tcx, open_ty))
825         }
826     });
827
828     required_region_bounds(tcx, open_ty, predicates)
829 }
830
831 /// Given a set of predicates that apply to an object type, returns
832 /// the region bounds that the (erased) `Self` type must
833 /// outlive. Precisely *because* the `Self` type is erased, the
834 /// parameter `erased_self_ty` must be supplied to indicate what type
835 /// has been used to represent `Self` in the predicates
836 /// themselves. This should really be a unique type; `FreshTy(0)` is a
837 /// popular choice.
838 ///
839 /// N.B., in some cases, particularly around higher-ranked bounds,
840 /// this function returns a kind of conservative approximation.
841 /// That is, all regions returned by this function are definitely
842 /// required, but there may be other region bounds that are not
843 /// returned, as well as requirements like `for<'a> T: 'a`.
844 ///
845 /// Requires that trait definitions have been processed so that we can
846 /// elaborate predicates and walk supertraits.
847 #[instrument(skip(tcx, predicates), level = "debug", ret)]
848 pub(crate) fn required_region_bounds<'tcx>(
849     tcx: TyCtxt<'tcx>,
850     erased_self_ty: Ty<'tcx>,
851     predicates: impl Iterator<Item = ty::Predicate<'tcx>>,
852 ) -> Vec<ty::Region<'tcx>> {
853     assert!(!erased_self_ty.has_escaping_bound_vars());
854
855     traits::elaborate_predicates(tcx, predicates)
856         .filter_map(|obligation| {
857             debug!(?obligation);
858             match obligation.predicate.kind().skip_binder() {
859                 ty::PredicateKind::Projection(..)
860                 | ty::PredicateKind::Trait(..)
861                 | ty::PredicateKind::Subtype(..)
862                 | ty::PredicateKind::Coerce(..)
863                 | ty::PredicateKind::WellFormed(..)
864                 | ty::PredicateKind::ObjectSafe(..)
865                 | ty::PredicateKind::ClosureKind(..)
866                 | ty::PredicateKind::RegionOutlives(..)
867                 | ty::PredicateKind::ConstEvaluatable(..)
868                 | ty::PredicateKind::ConstEquate(..)
869                 | ty::PredicateKind::TypeWellFormedFromEnv(..) => None,
870                 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ref t, ref r)) => {
871                     // Search for a bound of the form `erased_self_ty
872                     // : 'a`, but be wary of something like `for<'a>
873                     // erased_self_ty : 'a` (we interpret a
874                     // higher-ranked bound like that as 'static,
875                     // though at present the code in `fulfill.rs`
876                     // considers such bounds to be unsatisfiable, so
877                     // it's kind of a moot point since you could never
878                     // construct such an object, but this seems
879                     // correct even if that code changes).
880                     if t == &erased_self_ty && !r.has_escaping_bound_vars() {
881                         Some(*r)
882                     } else {
883                         None
884                     }
885                 }
886             }
887         })
888         .collect()
889 }