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