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