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