Skip to main content

rustc_trait_selection/traits/
wf.rs

1//! Core logic responsible for determining what it means for various type system
2//! primitives to be "well formed". Actually checking whether these primitives are
3//! well formed is performed elsewhere (e.g. during type checking or item well formedness
4//! checking).
5
6use std::iter;
7
8use rustc_hir as hir;
9use rustc_hir::lang_items::LangItem;
10use rustc_infer::traits::{ObligationCauseCode, PredicateObligations};
11use rustc_middle::bug;
12use rustc_middle::ty::{
13    self, GenericArgsRef, Term, TermKind, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable,
14    TypeVisitableExt, TypeVisitor,
15};
16use rustc_session::diagnostics::feature_err;
17use rustc_span::def_id::{DefId, LocalDefId};
18use rustc_span::{Span, sym};
19use tracing::{debug, instrument, trace};
20
21use crate::infer::InferCtxt;
22use crate::traits;
23
24/// Returns the set of obligations needed to make `term` well-formed.
25/// If `term` contains unresolved inference variables, this may include
26/// further WF obligations. However, if `term` IS an unresolved
27/// inference variable, returns `None`, because we are not able to
28/// make any progress at all. This is to prevent cycles where we
29/// say "?0 is WF if ?0 is WF".
30pub fn obligations<'tcx>(
31    infcx: &InferCtxt<'tcx>,
32    param_env: ty::ParamEnv<'tcx>,
33    body_def_id: LocalDefId,
34    recursion_depth: usize,
35    term: Term<'tcx>,
36    span: Span,
37) -> Option<PredicateObligations<'tcx>> {
38    // Handle the "cycle" case (see comment above) by bailing out if necessary.
39    let term = match term.kind() {
40        TermKind::Ty(ty) => {
41            match ty.kind() {
42                ty::Infer(ty::TyVar(_)) => {
43                    let resolved_ty = infcx.shallow_resolve(ty);
44                    if resolved_ty == ty {
45                        // No progress, bail out to prevent cycles.
46                        return None;
47                    } else {
48                        resolved_ty
49                    }
50                }
51                _ => ty,
52            }
53            .into()
54        }
55        TermKind::Const(ct) => {
56            match ct.kind() {
57                ty::ConstKind::Infer(_) => {
58                    let resolved = infcx.shallow_resolve_const(ct);
59                    if resolved == ct {
60                        // No progress, bail out to prevent cycles.
61                        return None;
62                    } else {
63                        resolved
64                    }
65                }
66                _ => ct,
67            }
68            .into()
69        }
70    };
71
72    let mut wf = WfPredicates {
73        infcx,
74        param_env,
75        body_def_id,
76        span,
77        out: PredicateObligations::new(),
78        recursion_depth,
79        item: None,
80    };
81    wf.add_wf_preds_for_term(term);
82    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/wf.rs:82",
                        "rustc_trait_selection::traits::wf",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/wf.rs"),
                        ::tracing_core::__macro_support::Option::Some(82u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("wf::obligations({0:?}, body_def_id={1:?}) = {2:?}",
                                                    term, body_def_id, wf.out) as &dyn Value))])
            });
    } else { ; }
};debug!("wf::obligations({:?}, body_def_id={:?}) = {:?}", term, body_def_id, wf.out);
83
84    let result = wf.normalize(infcx);
85    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/wf.rs:85",
                        "rustc_trait_selection::traits::wf",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/wf.rs"),
                        ::tracing_core::__macro_support::Option::Some(85u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("wf::obligations({0:?}, body_def_id={1:?}) ~~> {2:?}",
                                                    term, body_def_id, result) as &dyn Value))])
            });
    } else { ; }
};debug!("wf::obligations({:?}, body_def_id={:?}) ~~> {:?}", term, body_def_id, result);
86    Some(result)
87}
88
89/// Compute the predicates that are required for a type to be well-formed.
90///
91/// This is only intended to be used in the new solver, since it does not
92/// take into account recursion depth or proper error-reporting spans.
93pub fn unnormalized_obligations<'tcx>(
94    infcx: &InferCtxt<'tcx>,
95    param_env: ty::ParamEnv<'tcx>,
96    term: Term<'tcx>,
97    span: Span,
98    body_def_id: LocalDefId,
99) -> Option<PredicateObligations<'tcx>> {
100    if true {
    {
        match (&term, &infcx.resolve_vars_if_possible(term)) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(term, infcx.resolve_vars_if_possible(term));
101
102    // However, if `term` IS an unresolved inference variable, returns `None`,
103    // because we are not able to make any progress at all. This is to prevent
104    // cycles where we say "?0 is WF if ?0 is WF".
105    if term.is_infer() {
106        return None;
107    }
108
109    let mut wf = WfPredicates {
110        infcx,
111        param_env,
112        body_def_id,
113        span,
114        out: PredicateObligations::new(),
115        recursion_depth: 0,
116        item: None,
117    };
118    wf.add_wf_preds_for_term(term);
119    Some(wf.out)
120}
121
122/// Returns the obligations that make this trait reference
123/// well-formed. For example, if there is a trait `Set` defined like
124/// `trait Set<K: Eq>`, then the trait bound `Foo: Set<Bar>` is WF
125/// if `Bar: Eq`.
126pub fn trait_obligations<'tcx>(
127    infcx: &InferCtxt<'tcx>,
128    param_env: ty::ParamEnv<'tcx>,
129    body_def_id: LocalDefId,
130    trait_pred: ty::TraitPredicate<'tcx>,
131    span: Span,
132    item: &'tcx hir::Item<'tcx>,
133) -> PredicateObligations<'tcx> {
134    let mut wf = WfPredicates {
135        infcx,
136        param_env,
137        body_def_id,
138        span,
139        out: PredicateObligations::new(),
140        recursion_depth: 0,
141        item: Some(item),
142    };
143    wf.add_wf_preds_for_trait_pred(trait_pred, Elaborate::All);
144    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/wf.rs:144",
                        "rustc_trait_selection::traits::wf",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/wf.rs"),
                        ::tracing_core::__macro_support::Option::Some(144u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
                        ::tracing_core::field::FieldSet::new(&["obligations"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&wf.out) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(obligations = ?wf.out);
145    wf.normalize(infcx)
146}
147
148/// Returns the requirements for `clause` to be well-formed.
149///
150/// For example, if there is a trait `Set` defined like
151/// `trait Set<K: Eq>`, then the trait bound `Foo: Set<Bar>` is WF
152/// if `Bar: Eq`.
153x;#[instrument(skip(infcx), ret)]
154pub fn clause_obligations<'tcx>(
155    infcx: &InferCtxt<'tcx>,
156    param_env: ty::ParamEnv<'tcx>,
157    body_def_id: LocalDefId,
158    clause: ty::Clause<'tcx>,
159    span: Span,
160) -> PredicateObligations<'tcx> {
161    let mut wf = WfPredicates {
162        infcx,
163        param_env,
164        body_def_id,
165        span,
166        out: PredicateObligations::new(),
167        recursion_depth: 0,
168        item: None,
169    };
170
171    // It's ok to skip the binder here because wf code is prepared for it
172    match clause.kind().skip_binder() {
173        ty::ClauseKind::Trait(t) => {
174            wf.add_wf_preds_for_trait_pred(t, Elaborate::None);
175        }
176        ty::ClauseKind::HostEffect(..) => {
177            // Technically the well-formedness of this predicate is implied by
178            // the corresponding trait predicate it should've been generated beside.
179        }
180        ty::ClauseKind::RegionOutlives(..) => {}
181        ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
182            wf.add_wf_preds_for_term(ty.into());
183        }
184        ty::ClauseKind::Projection(t) => {
185            wf.add_wf_preds_for_projection_term(t.projection_term);
186            wf.add_wf_preds_for_term(t.term);
187        }
188        ty::ClauseKind::ConstArgHasType(ct, ty) => {
189            wf.add_wf_preds_for_term(ct.into());
190            wf.add_wf_preds_for_term(ty.into());
191        }
192        ty::ClauseKind::WellFormed(term) => {
193            wf.add_wf_preds_for_term(term);
194        }
195
196        ty::ClauseKind::ConstEvaluatable(ct) => {
197            wf.add_wf_preds_for_term(ct.into());
198        }
199        ty::ClauseKind::UnstableFeature(_) => {}
200    }
201
202    wf.normalize(infcx)
203}
204
205struct WfPredicates<'a, 'tcx> {
206    infcx: &'a InferCtxt<'tcx>,
207    param_env: ty::ParamEnv<'tcx>,
208    body_def_id: LocalDefId,
209    span: Span,
210    out: PredicateObligations<'tcx>,
211    recursion_depth: usize,
212    item: Option<&'tcx hir::Item<'tcx>>,
213}
214
215/// Controls whether we "elaborate" supertraits and so forth on the WF
216/// predicates. This is a kind of hack to address #43784. The
217/// underlying problem in that issue was a trait structure like:
218///
219/// ```ignore (illustrative)
220/// trait Foo: Copy { }
221/// trait Bar: Foo { }
222/// impl<T: Bar> Foo for T { }
223/// impl<T> Bar for T { }
224/// ```
225///
226/// Here, in the `Foo` impl, we will check that `T: Copy` holds -- but
227/// we decide that this is true because `T: Bar` is in the
228/// where-clauses (and we can elaborate that to include `T:
229/// Copy`). This wouldn't be a problem, except that when we check the
230/// `Bar` impl, we decide that `T: Foo` must hold because of the `Foo`
231/// impl. And so nowhere did we check that `T: Copy` holds!
232///
233/// To resolve this, we elaborate the WF requirements that must be
234/// proven when checking impls. This means that (e.g.) the `impl Bar
235/// for T` will be forced to prove not only that `T: Foo` but also `T:
236/// Copy` (which it won't be able to do, because there is no `Copy`
237/// impl for `T`).
238#[derive(#[automatically_derived]
impl ::core::fmt::Debug for Elaborate {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                Elaborate::All => "All",
                Elaborate::None => "None",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for Elaborate {
    #[inline]
    fn eq(&self, other: &Elaborate) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Elaborate {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::marker::Copy for Elaborate { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Elaborate {
    #[inline]
    fn clone(&self) -> Elaborate { *self }
}Clone)]
239enum Elaborate {
240    All,
241    None,
242}
243
244/// Points the cause span of a super predicate at the relevant associated type.
245///
246/// Given a trait impl item:
247///
248/// ```ignore (incomplete)
249/// impl TargetTrait for TargetType {
250///    type Assoc = SomeType;
251/// }
252/// ```
253///
254/// And a super predicate of `TargetTrait` that has any of the following forms:
255///
256/// 1. `<OtherType as OtherTrait>::Assoc == <TargetType as TargetTrait>::Assoc`
257/// 2. `<<TargetType as TargetTrait>::Assoc as OtherTrait>::Assoc == OtherType`
258/// 3. `<TargetType as TargetTrait>::Assoc: OtherTrait`
259///
260/// Replace the span of the cause with the span of the associated item:
261///
262/// ```ignore (incomplete)
263/// impl TargetTrait for TargetType {
264///     type Assoc = SomeType;
265/// //               ^^^^^^^^ this span
266/// }
267/// ```
268///
269/// Note that bounds that can be expressed as associated item bounds are **not**
270/// super predicates. This means that form 2 and 3 from above are only relevant if
271/// the [`GenericArgsRef`] of the projection type are not its identity arguments.
272fn extend_cause_with_original_assoc_item_obligation<'tcx>(
273    tcx: TyCtxt<'tcx>,
274    item: Option<&hir::Item<'tcx>>,
275    cause: &mut traits::ObligationCause<'tcx>,
276    pred: ty::Predicate<'tcx>,
277) {
278    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/wf.rs:278",
                        "rustc_trait_selection::traits::wf",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/wf.rs"),
                        ::tracing_core::__macro_support::Option::Some(278u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
                        ::tracing_core::field::FieldSet::new(&["message", "item",
                                        "cause", "pred"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("extended_cause_with_original_assoc_item_obligation")
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&item) as
                                            &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&cause) as
                                            &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&pred) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?item, ?cause, ?pred, "extended_cause_with_original_assoc_item_obligation");
279    let (items, impl_def_id) = match item {
280        Some(hir::Item { kind: hir::ItemKind::Impl(impl_), owner_id, .. }) => {
281            (impl_.items, *owner_id)
282        }
283        _ => return,
284    };
285
286    let ty_to_impl_span = |ty: Ty<'_>| {
287        if let ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id }, .. }) = ty.kind()
288            && let Some(&impl_item_id) = tcx.impl_item_implementor_ids(impl_def_id).get(def_id)
289            && let Some(impl_item) =
290                items.iter().find(|item| item.owner_id.to_def_id() == impl_item_id)
291        {
292            Some(tcx.hir_impl_item(*impl_item).expect_type().span)
293        } else {
294            None
295        }
296    };
297
298    // It is fine to skip the binder as we don't care about regions here.
299    match pred.kind().skip_binder() {
300        ty::PredicateKind::Clause(ty::ClauseKind::Projection(proj)) => {
301            // Form 1: The obligation comes not from the current `impl` nor the `trait` being
302            // implemented, but rather from a "second order" obligation, where an associated
303            // type has a projection coming from another associated type.
304            // See `tests/ui/traits/assoc-type-in-superbad.rs` for an example.
305            if let Some(term_ty) = proj.term.as_type()
306                && let Some(impl_item_span) = ty_to_impl_span(term_ty)
307            {
308                cause.span = impl_item_span;
309            }
310
311            // Form 2: A projection obligation for an associated item failed to be met.
312            // We overwrite the span from above to ensure that a bound like
313            // `Self::Assoc1: Trait<OtherAssoc = Self::Assoc2>` gets the same
314            // span for both obligations that it is lowered to.
315            if let Some(impl_item_span) = ty_to_impl_span(proj.self_ty()) {
316                cause.span = impl_item_span;
317            }
318        }
319
320        ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => {
321            // Form 3: A trait obligation for an associated item failed to be met.
322            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/wf.rs:322",
                        "rustc_trait_selection::traits::wf",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/wf.rs"),
                        ::tracing_core::__macro_support::Option::Some(322u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("extended_cause_with_original_assoc_item_obligation trait proj {0:?}",
                                                    pred) as &dyn Value))])
            });
    } else { ; }
};debug!("extended_cause_with_original_assoc_item_obligation trait proj {:?}", pred);
323            if let Some(impl_item_span) = ty_to_impl_span(pred.self_ty()) {
324                cause.span = impl_item_span;
325            }
326        }
327        _ => {}
328    }
329}
330
331impl<'a, 'tcx> WfPredicates<'a, 'tcx> {
332    fn tcx(&self) -> TyCtxt<'tcx> {
333        self.infcx.tcx
334    }
335
336    fn cause(&self, code: traits::ObligationCauseCode<'tcx>) -> traits::ObligationCause<'tcx> {
337        traits::ObligationCause::new(self.span, self.body_def_id, code)
338    }
339
340    fn normalize(self, infcx: &InferCtxt<'tcx>) -> PredicateObligations<'tcx> {
341        // Do not normalize `wf` obligations with the new solver.
342        //
343        // The current deep normalization routine with the new solver does not
344        // handle ambiguity and the new solver correctly deals with unnnormalized goals.
345        // If the user relies on normalized types, e.g. for `fn implied_outlives_bounds`,
346        // it is their responsibility to normalize while avoiding ambiguity.
347        if infcx.next_trait_solver() {
348            return self.out;
349        }
350
351        let cause = self.cause(ObligationCauseCode::WellFormed(None));
352        let param_env = self.param_env;
353        let mut obligations = PredicateObligations::with_capacity(self.out.len());
354        for mut obligation in self.out {
355            if !!obligation.has_escaping_bound_vars() {
    ::core::panicking::panic("assertion failed: !obligation.has_escaping_bound_vars()")
};assert!(!obligation.has_escaping_bound_vars());
356            let mut selcx = traits::SelectionContext::new(infcx);
357            // Don't normalize the whole obligation, the param env is either
358            // already normalized, or we're currently normalizing the
359            // param_env. Either way we should only normalize the predicate.
360            let normalized_predicate = traits::normalize::normalize_with_depth_to(
361                &mut selcx,
362                param_env,
363                cause.clone(),
364                self.recursion_depth,
365                obligation.predicate,
366                &mut obligations,
367            );
368            obligation.predicate = normalized_predicate;
369            obligations.push(obligation);
370        }
371        obligations
372    }
373
374    /// Pushes the obligations required for `trait_ref` to be WF into `self.out`.
375    fn add_wf_preds_for_trait_pred(
376        &mut self,
377        trait_pred: ty::TraitPredicate<'tcx>,
378        elaborate: Elaborate,
379    ) {
380        let tcx = self.tcx();
381        let trait_ref = trait_pred.trait_ref;
382
383        // Negative trait predicates don't require supertraits to hold, just
384        // that their args are WF.
385        if trait_pred.polarity == ty::PredicatePolarity::Negative {
386            self.add_wf_preds_for_negative_trait_pred(trait_ref);
387            return;
388        }
389
390        // if the trait predicate is not const, the wf obligations should not be const as well.
391        let obligations = self.nominal_obligations(trait_ref.def_id, trait_ref.args);
392
393        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/wf.rs:393",
                        "rustc_trait_selection::traits::wf",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/wf.rs"),
                        ::tracing_core::__macro_support::Option::Some(393u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("compute_trait_pred obligations {0:?}",
                                                    obligations) as &dyn Value))])
            });
    } else { ; }
};debug!("compute_trait_pred obligations {:?}", obligations);
394        let param_env = self.param_env;
395        let depth = self.recursion_depth;
396
397        let item = self.item;
398
399        let extend = |traits::PredicateObligation { predicate, mut cause, .. }| {
400            if let Some(parent_trait_pred) = predicate.as_trait_clause() {
401                cause = cause.derived_cause(
402                    parent_trait_pred,
403                    traits::ObligationCauseCode::WellFormedDerived,
404                );
405            }
406            extend_cause_with_original_assoc_item_obligation(tcx, item, &mut cause, predicate);
407            traits::Obligation::with_depth(tcx, cause, depth, param_env, predicate)
408        };
409
410        if let Elaborate::All = elaborate {
411            let implied_obligations = traits::util::elaborate(tcx, obligations);
412            let implied_obligations = implied_obligations.map(extend);
413            self.out.extend(implied_obligations);
414        } else {
415            self.out.extend(obligations);
416        }
417
418        self.out.extend(
419            trait_ref
420                .args
421                .iter()
422                .enumerate()
423                .filter_map(|(i, arg)| arg.as_term().map(|t| (i, t)))
424                .filter(|(_, term)| !term.has_escaping_bound_vars())
425                .map(|(i, term)| {
426                    let mut cause = traits::ObligationCause::misc(self.span, self.body_def_id);
427                    // The first arg is the self ty - use the correct span for it.
428                    if i == 0 {
429                        if let Some(hir::ItemKind::Impl(hir::Impl { self_ty, .. })) =
430                            item.map(|i| &i.kind)
431                        {
432                            cause.span = self_ty.span;
433                        }
434                    }
435                    traits::Obligation::with_depth(
436                        tcx,
437                        cause,
438                        depth,
439                        param_env,
440                        ty::ClauseKind::WellFormed(term),
441                    )
442                }),
443        );
444    }
445
446    // Compute the obligations that are required for `trait_ref` to be WF,
447    // given that it is a *negative* trait predicate.
448    fn add_wf_preds_for_negative_trait_pred(&mut self, trait_ref: ty::TraitRef<'tcx>) {
449        for arg in trait_ref.args {
450            if let Some(term) = arg.as_term() {
451                self.add_wf_preds_for_term(term);
452            }
453        }
454    }
455
456    /// Pushes the obligations required for a projection to be WF into `self.out`.
457    fn add_wf_preds_for_projection_term(&mut self, data: ty::AliasTerm<'tcx>) {
458        // A projection is well-formed if
459        //
460        // (a) its predicates hold (*)
461        // (b) its args are wf
462        //
463        // (*) The predicates of an associated type include the predicates of
464        //     the trait that it's contained in. For example, given
465        //
466        // trait A<T>: Clone {
467        //     type X where T: Copy;
468        // }
469        //
470        // The predicates of `<() as A<i32>>::X` are:
471        // [
472        //     `(): Sized`
473        //     `(): Clone`
474        //     `(): A<i32>`
475        //     `i32: Sized`
476        //     `i32: Clone`
477        //     `i32: Copy`
478        // ]
479        let obligations = self.nominal_obligations(data.expect_projection_def_id(), data.args);
480        self.out.extend(obligations);
481
482        self.add_wf_preds_for_projection_args(data.args);
483    }
484
485    /// Pushes the obligations required for an inherent alias to be WF
486    /// into `self.out`.
487    // FIXME(inherent_associated_types): Merge this function with `fn compute_alias`.
488    fn add_wf_preds_for_inherent_projection(&mut self, data: ty::AliasTerm<'tcx>) {
489        // An inherent projection is well-formed if
490        //
491        // (a) its predicates hold (*)
492        // (b) its args are wf
493        //
494        // (*) The predicates of an inherent associated type include the
495        //     predicates of the impl that it's contained in.
496
497        if !data.self_ty().has_escaping_bound_vars() {
498            // FIXME(inherent_associated_types): Should this happen inside of a snapshot?
499            // FIXME(inherent_associated_types): This is incompatible with the new solver and lazy norm!
500            let args = traits::project::compute_inherent_assoc_term_args(
501                &mut traits::SelectionContext::new(self.infcx),
502                self.param_env,
503                data,
504                self.cause(ObligationCauseCode::WellFormed(None)),
505                self.recursion_depth,
506                &mut self.out,
507            );
508            let def_id = data.expect_inherent_def_id();
509            let obligations = self.nominal_obligations(def_id, args);
510            self.out.extend(obligations);
511        }
512
513        data.args.visit_with(self);
514    }
515
516    fn add_wf_preds_for_projection_args(&mut self, args: GenericArgsRef<'tcx>) {
517        let tcx = self.tcx();
518        let cause = self.cause(ObligationCauseCode::WellFormed(None));
519        let param_env = self.param_env;
520        let depth = self.recursion_depth;
521
522        self.out.extend(
523            args.iter()
524                .filter_map(|arg| arg.as_term())
525                .filter(|term| !term.has_escaping_bound_vars())
526                .map(|term| {
527                    traits::Obligation::with_depth(
528                        tcx,
529                        cause.clone(),
530                        depth,
531                        param_env,
532                        ty::ClauseKind::WellFormed(term),
533                    )
534                }),
535        );
536    }
537
538    fn require_sized(&mut self, subty: Ty<'tcx>, cause: traits::ObligationCauseCode<'tcx>) {
539        if !subty.has_escaping_bound_vars() {
540            let cause = self.cause(cause);
541            let trait_ref = ty::TraitRef::new(
542                self.tcx(),
543                self.tcx().require_lang_item(LangItem::Sized, cause.span),
544                [subty],
545            );
546            self.out.push(traits::Obligation::with_depth(
547                self.tcx(),
548                cause,
549                self.recursion_depth,
550                self.param_env,
551                ty::Binder::dummy(trait_ref),
552            ));
553        }
554    }
555
556    /// Pushes all the predicates needed to validate that `term` is WF into `out`.
557    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("add_wf_preds_for_term",
                                    "rustc_trait_selection::traits::wf",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/wf.rs"),
                                    ::tracing_core::__macro_support::Option::Some(557u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
                                    ::tracing_core::field::FieldSet::new(&["term"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&term)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            term.visit_with(self);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/wf.rs:560",
                                    "rustc_trait_selection::traits::wf",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/wf.rs"),
                                    ::tracing_core::__macro_support::Option::Some(560u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
                                    ::tracing_core::field::FieldSet::new(&["self.out"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&self.out)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
        }
    }
}#[instrument(level = "debug", skip(self))]
558    fn add_wf_preds_for_term(&mut self, term: Term<'tcx>) {
559        term.visit_with(self);
560        debug!(?self.out);
561    }
562
563    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("nominal_obligations",
                                    "rustc_trait_selection::traits::wf",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/wf.rs"),
                                    ::tracing_core::__macro_support::Option::Some(563u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
                                    ::tracing_core::field::FieldSet::new(&["def_id", "args"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&args)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: PredicateObligations<'tcx> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            if self.tcx().is_lang_item(def_id, LangItem::Sized) {
                return Default::default();
            }
            if self.tcx().is_lang_item(def_id, LangItem::ConstParamTy) &&
                    self.tcx().features().const_param_ty_unchecked() {
                return Default::default();
            }
            let predicates = self.tcx().predicates_of(def_id);
            let mut origins =
                ::alloc::vec::from_elem(def_id, predicates.predicates.len());
            let mut head = predicates;
            while let Some(parent) = head.parent {
                head = self.tcx().predicates_of(parent);
                origins.extend(iter::repeat(parent).take(head.predicates.len()));
            }
            let predicates = predicates.instantiate(self.tcx(), args);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/wf.rs:591",
                                    "rustc_trait_selection::traits::wf",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/wf.rs"),
                                    ::tracing_core::__macro_support::Option::Some(591u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::TRACE <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::TRACE <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("{0:#?}",
                                                                predicates) as &dyn Value))])
                        });
                } else { ; }
            };
            if true {
                {
                    match (&predicates.predicates.len(), &origins.len()) {
                        (left_val, right_val) => {
                            if !(*left_val == *right_val) {
                                let kind = ::core::panicking::AssertKind::Eq;
                                ::core::panicking::assert_failed(kind, &*left_val,
                                    &*right_val, ::core::option::Option::None);
                            }
                        }
                    }
                };
            };
            iter::zip(predicates,
                            origins.into_iter().rev()).map(|((pred, span),
                                origin_def_id)|
                            {
                                let code =
                                    ObligationCauseCode::WhereClause(origin_def_id, span);
                                let cause = self.cause(code);
                                traits::Obligation::with_depth(self.tcx(), cause,
                                    self.recursion_depth, self.param_env, pred.skip_norm_wip())
                            }).filter(|pred| !pred.has_escaping_bound_vars()).collect()
        }
    }
}#[instrument(level = "debug", skip(self))]
564    fn nominal_obligations(
565        &mut self,
566        def_id: DefId,
567        args: GenericArgsRef<'tcx>,
568    ) -> PredicateObligations<'tcx> {
569        // PERF: `Sized`'s predicates include `MetaSized`, but both are compiler implemented marker
570        // traits, so `MetaSized` will always be WF if `Sized` is WF and vice-versa. Determining
571        // the nominal obligations of `Sized` would in-effect just elaborate `MetaSized` and make
572        // the compiler do a bunch of work needlessly.
573        if self.tcx().is_lang_item(def_id, LangItem::Sized) {
574            return Default::default();
575        }
576        if self.tcx().is_lang_item(def_id, LangItem::ConstParamTy)
577            && self.tcx().features().const_param_ty_unchecked()
578        {
579            return Default::default();
580        }
581
582        let predicates = self.tcx().predicates_of(def_id);
583        let mut origins = vec![def_id; predicates.predicates.len()];
584        let mut head = predicates;
585        while let Some(parent) = head.parent {
586            head = self.tcx().predicates_of(parent);
587            origins.extend(iter::repeat(parent).take(head.predicates.len()));
588        }
589
590        let predicates = predicates.instantiate(self.tcx(), args);
591        trace!("{:#?}", predicates);
592        debug_assert_eq!(predicates.predicates.len(), origins.len());
593
594        iter::zip(predicates, origins.into_iter().rev())
595            .map(|((pred, span), origin_def_id)| {
596                let code = ObligationCauseCode::WhereClause(origin_def_id, span);
597                let cause = self.cause(code);
598                traits::Obligation::with_depth(
599                    self.tcx(),
600                    cause,
601                    self.recursion_depth,
602                    self.param_env,
603                    pred.skip_norm_wip(),
604                )
605            })
606            .filter(|pred| !pred.has_escaping_bound_vars())
607            .collect()
608    }
609
610    fn add_wf_preds_for_dyn_ty(
611        &mut self,
612        ty: Ty<'tcx>,
613        data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
614        region: ty::Region<'tcx>,
615    ) {
616        // Imagine a type like this:
617        //
618        //     trait Foo { }
619        //     trait Bar<'c> : 'c { }
620        //
621        //     &'b (Foo+'c+Bar<'d>)
622        //         ^
623        //
624        // In this case, the following relationships must hold:
625        //
626        //     'b <= 'c
627        //     'd <= 'c
628        //
629        // The first conditions is due to the normal region pointer
630        // rules, which say that a reference cannot outlive its
631        // referent.
632        //
633        // The final condition may be a bit surprising. In particular,
634        // you may expect that it would have been `'c <= 'd`, since
635        // usually lifetimes of outer things are conservative
636        // approximations for inner things. However, it works somewhat
637        // differently with trait objects: here the idea is that if the
638        // user specifies a region bound (`'c`, in this case) it is the
639        // "master bound" that *implies* that bounds from other traits are
640        // all met. (Remember that *all bounds* in a type like
641        // `Foo+Bar+Zed` must be met, not just one, hence if we write
642        // `Foo<'x>+Bar<'y>`, we know that the type outlives *both* 'x and
643        // 'y.)
644        //
645        // Note: in fact we only permit builtin traits, not `Bar<'d>`, I
646        // am looking forward to the future here.
647        if !data.has_escaping_bound_vars() && !region.has_escaping_bound_vars() {
648            let implicit_bounds = object_region_bounds(self.tcx(), data);
649
650            let explicit_bound = region;
651
652            self.out.reserve(implicit_bounds.len());
653            for implicit_bound in implicit_bounds {
654                let cause = self.cause(ObligationCauseCode::ObjectTypeBound(ty, explicit_bound));
655                let outlives =
656                    ty::Binder::dummy(ty::OutlivesPredicate(explicit_bound, implicit_bound));
657                self.out.push(traits::Obligation::with_depth(
658                    self.tcx(),
659                    cause,
660                    self.recursion_depth,
661                    self.param_env,
662                    outlives,
663                ));
664            }
665
666            // We don't add any wf predicates corresponding to the trait ref's generic arguments
667            // which allows code like this to compile:
668            // ```rust
669            // trait Trait<T: Sized> {}
670            // fn foo(_: &dyn Trait<[u32]>) {}
671            // ```
672        }
673    }
674
675    fn add_wf_preds_for_pat_ty(&mut self, base_ty: Ty<'tcx>, pat: ty::Pattern<'tcx>) {
676        let tcx = self.tcx();
677        match *pat {
678            ty::PatternKind::Range { start, end } => {
679                let mut check = |c| {
680                    let cause = self.cause(ObligationCauseCode::Misc);
681                    self.out.push(traits::Obligation::with_depth(
682                        tcx,
683                        cause.clone(),
684                        self.recursion_depth,
685                        self.param_env,
686                        ty::Binder::dummy(ty::PredicateKind::Clause(
687                            ty::ClauseKind::ConstArgHasType(c, base_ty),
688                        )),
689                    ));
690                    if !tcx.features().generic_pattern_types() {
691                        if c.has_param() {
692                            if self.span.is_dummy() {
693                                self.tcx()
694                                    .dcx()
695                                    .delayed_bug("feature error should be reported elsewhere, too");
696                            } else {
697                                feature_err(
698                                    &self.tcx().sess,
699                                    sym::generic_pattern_types,
700                                    self.span,
701                                    "wraparound pattern type ranges cause monomorphization time errors",
702                                )
703                                .emit();
704                            }
705                        }
706                    }
707                };
708                check(start);
709                check(end);
710            }
711            ty::PatternKind::NotNull => {}
712            ty::PatternKind::Or(patterns) => {
713                for pat in patterns {
714                    self.add_wf_preds_for_pat_ty(base_ty, pat)
715                }
716            }
717        }
718    }
719}
720
721impl<'a, 'tcx> TypeVisitor<TyCtxt<'tcx>> for WfPredicates<'a, 'tcx> {
722    fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
723        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/wf.rs:723",
                        "rustc_trait_selection::traits::wf",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/wf.rs"),
                        ::tracing_core::__macro_support::Option::Some(723u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("wf bounds for t={0:?} t.kind={1:#?}",
                                                    t, t.kind()) as &dyn Value))])
            });
    } else { ; }
};debug!("wf bounds for t={:?} t.kind={:#?}", t, t.kind());
724
725        let tcx = self.tcx();
726
727        match *t.kind() {
728            ty::Bool
729            | ty::Char
730            | ty::Int(..)
731            | ty::Uint(..)
732            | ty::Float(..)
733            | ty::Error(_)
734            | ty::Str
735            | ty::CoroutineWitness(..)
736            | ty::Never
737            | ty::Param(_)
738            | ty::Bound(..)
739            | ty::Placeholder(..)
740            | ty::Foreign(..) => {
741                // WfScalar, WfParameter, etc
742            }
743
744            // Can only infer to `ty::Int(_) | ty::Uint(_)`.
745            ty::Infer(ty::IntVar(_)) => {}
746
747            // Can only infer to `ty::Float(_)`.
748            ty::Infer(ty::FloatVar(_)) => {}
749
750            ty::Slice(subty) => {
751                self.require_sized(subty, ObligationCauseCode::SliceOrArrayElem);
752            }
753
754            ty::Array(subty, len) => {
755                self.require_sized(subty, ObligationCauseCode::SliceOrArrayElem);
756                // Note that the len being WF is implicitly checked while visiting.
757                // Here we just check that it's of type usize.
758                let cause = self.cause(ObligationCauseCode::ArrayLen(t));
759                self.out.push(traits::Obligation::with_depth(
760                    tcx,
761                    cause,
762                    self.recursion_depth,
763                    self.param_env,
764                    ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(
765                        len,
766                        tcx.types.usize,
767                    ))),
768                ));
769            }
770
771            ty::Pat(base_ty, pat) => {
772                self.require_sized(base_ty, ObligationCauseCode::Misc);
773                self.add_wf_preds_for_pat_ty(base_ty, pat);
774            }
775
776            ty::Tuple(tys) => {
777                if let Some((last, rest)) = tys.split_last() {
778                    for &elem in rest {
779                        self.require_sized(elem, ObligationCauseCode::TupleElem);
780                        if elem.is_scalable_vector() && !self.span.is_dummy() {
781                            self.tcx()
782                                .dcx()
783                                .struct_span_err(
784                                    self.span,
785                                    "scalable vectors cannot be tuple fields",
786                                )
787                                .emit();
788                        }
789                    }
790
791                    if last.is_scalable_vector() && !self.span.is_dummy() {
792                        self.tcx()
793                            .dcx()
794                            .struct_span_err(self.span, "scalable vectors cannot be tuple fields")
795                            .emit();
796                    }
797                }
798            }
799
800            ty::RawPtr(_, _) => {
801                // Simple cases that are WF if their type args are WF.
802            }
803
804            ty::Alias(
805                _,
806                ty::AliasTy {
807                    kind: ty::Projection { def_id } | ty::Opaque { def_id } | ty::Free { def_id },
808                    args,
809                    ..
810                },
811            ) => {
812                let obligations = self.nominal_obligations(def_id, args);
813                self.out.extend(obligations);
814            }
815            ty::Alias(_, data @ ty::AliasTy { kind: ty::Inherent { .. }, .. }) => {
816                self.add_wf_preds_for_inherent_projection(data.into());
817                return; // Subtree handled by compute_inherent_projection.
818            }
819
820            ty::Adt(def, args) => {
821                // WfNominalType
822                let obligations = self.nominal_obligations(def.did(), args);
823                self.out.extend(obligations);
824            }
825
826            ty::FnDef(did, args) => {
827                let args = args.no_bound_vars().unwrap();
828                // HACK: Check the return type of function definitions for
829                // well-formedness to mostly fix #84533. This is still not
830                // perfect and there may be ways to abuse the fact that we
831                // ignore requirements with escaping bound vars. That's a
832                // more general issue however.
833                let fn_sig = tcx.fn_sig(did).instantiate(tcx, args).skip_norm_wip();
834                fn_sig.output().skip_binder().visit_with(self);
835
836                let obligations = self.nominal_obligations(did, args);
837                self.out.extend(obligations);
838            }
839
840            ty::Ref(r, rty, _) => {
841                // WfReference
842                if !r.has_escaping_bound_vars() && !rty.has_escaping_bound_vars() {
843                    let cause = self.cause(ObligationCauseCode::ReferenceOutlivesReferent(t));
844                    self.out.push(traits::Obligation::with_depth(
845                        tcx,
846                        cause,
847                        self.recursion_depth,
848                        self.param_env,
849                        ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(
850                            ty::OutlivesPredicate(rty, r),
851                        ))),
852                    ));
853                }
854            }
855
856            ty::Coroutine(did, args, ..) => {
857                // Walk ALL the types in the coroutine: this will
858                // include the upvar types as well as the yield
859                // type. Note that this is mildly distinct from
860                // the closure case, where we have to be careful
861                // about the signature of the closure. We don't
862                // have the problem of implied bounds here since
863                // coroutines don't take arguments.
864                let obligations = self.nominal_obligations(did, args);
865                self.out.extend(obligations);
866            }
867
868            ty::Closure(did, args) => {
869                // Note that we cannot skip the generic types
870                // types. Normally, within the fn
871                // body where they are created, the generics will
872                // always be WF, and outside of that fn body we
873                // are not directly inspecting closure types
874                // anyway, except via auto trait matching (which
875                // only inspects the upvar types).
876                // But when a closure is part of a type-alias-impl-trait
877                // then the function that created the defining site may
878                // have had more bounds available than the type alias
879                // specifies. This may cause us to have a closure in the
880                // hidden type that is not actually well formed and
881                // can cause compiler crashes when the user abuses unsafe
882                // code to procure such a closure.
883                // See tests/ui/type-alias-impl-trait/wf_check_closures.rs
884                let obligations = self.nominal_obligations(did, args);
885                self.out.extend(obligations);
886                // Only check the upvar types for WF, not the rest
887                // of the types within. This is needed because we
888                // capture the signature and it may not be WF
889                // without the implied bounds. Consider a closure
890                // like `|x: &'a T|` -- it may be that `T: 'a` is
891                // not known to hold in the creator's context (and
892                // indeed the closure may not be invoked by its
893                // creator, but rather turned to someone who *can*
894                // verify that).
895                //
896                // The special treatment of closures here really
897                // ought not to be necessary either; the problem
898                // is related to #25860 -- there is no way for us
899                // to express a fn type complete with the implied
900                // bounds that it is assuming. I think in reality
901                // the WF rules around fn are a bit messed up, and
902                // that is the rot problem: `fn(&'a T)` should
903                // probably always be WF, because it should be
904                // shorthand for something like `where(T: 'a) {
905                // fn(&'a T) }`, as discussed in #25860.
906                let upvars = args.as_closure().tupled_upvars_ty();
907                return upvars.visit_with(self);
908            }
909
910            ty::CoroutineClosure(did, args) => {
911                // See the above comments. The same apply to coroutine-closures.
912                let obligations = self.nominal_obligations(did, args);
913                self.out.extend(obligations);
914                let upvars = args.as_coroutine_closure().tupled_upvars_ty();
915                return upvars.visit_with(self);
916            }
917
918            ty::FnPtr(..) => {
919                // Let the visitor iterate into the argument/return
920                // types appearing in the fn signature.
921            }
922            ty::UnsafeBinder(ty) => {
923                // FIXME(unsafe_binders): For now, we have no way to express
924                // that a type must be `ManuallyDrop` OR `Copy` (or a pointer).
925                if !ty.has_escaping_bound_vars() {
926                    self.out.push(traits::Obligation::new(
927                        self.tcx(),
928                        self.cause(ObligationCauseCode::Misc),
929                        self.param_env,
930                        ty.map_bound(|ty| {
931                            ty::TraitRef::new(
932                                self.tcx(),
933                                self.tcx().require_lang_item(
934                                    LangItem::BikeshedGuaranteedNoDrop,
935                                    self.span,
936                                ),
937                                [ty],
938                            )
939                        }),
940                    ));
941                }
942
943                // We recurse into the binder below.
944            }
945
946            ty::Dynamic(data, r) => {
947                // WfObject
948                //
949                // Here, we defer WF checking due to higher-ranked
950                // regions. This is perhaps not ideal.
951                self.add_wf_preds_for_dyn_ty(t, data, r);
952
953                // FIXME(#27579) RFC also considers adding trait
954                // obligations that don't refer to Self and
955                // checking those
956                if let Some(principal) = data.principal() {
957                    let principal_def_id = principal.skip_binder().def_id;
958                    self.out.push(traits::Obligation::with_depth(
959                        tcx,
960                        self.cause(ObligationCauseCode::WellFormed(None)),
961                        self.recursion_depth,
962                        self.param_env,
963                        ty::Binder::dummy(ty::PredicateKind::DynCompatible(principal_def_id)),
964                    ));
965
966                    // For the most part we don't add wf predicates corresponding to
967                    // the trait ref's generic arguments which allows code like this
968                    // to compile:
969                    // ```rust
970                    // trait Trait<T: Sized> {}
971                    // fn foo(_: &dyn Trait<[u32]>) {}
972                    // ```
973                    //
974                    // However, we sometimes incidentally check that const arguments
975                    // have the correct type as a side effect of the anon const
976                    // desugaring. To make this "consistent" for users we explicitly
977                    // check `ConstArgHasType` clauses so that const args that don't
978                    // go through an anon const still have their types checked.
979                    //
980                    // See also: https://rustc-dev-guide.rust-lang.org/const-generics.html
981                    let args = principal.skip_binder().with_self_ty(self.tcx(), t).args;
982                    let obligations =
983                        self.nominal_obligations(principal_def_id, args).into_iter().filter(|o| {
984                            let kind = o.predicate.kind().skip_binder();
985                            match kind {
986                                ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(
987                                    ct,
988                                    _,
989                                )) if #[allow(non_exhaustive_omitted_patterns)] match ct.kind() {
    ty::ConstKind::Param(..) => true,
    _ => false,
}matches!(ct.kind(), ty::ConstKind::Param(..)) => {
990                                    // ConstArgHasType clauses are not higher kinded. Assert as
991                                    // such so we can fix this up if that ever changes.
992                                    if !o.predicate.kind().bound_vars().is_empty() {
    ::core::panicking::panic("assertion failed: o.predicate.kind().bound_vars().is_empty()")
};assert!(o.predicate.kind().bound_vars().is_empty());
993                                    // In stable rust, variables from the trait object binder
994                                    // cannot be referenced by a ConstArgHasType clause. However,
995                                    // under `generic_const_parameter_types`, it can. Ignore those
996                                    // predicates for now, to not have HKT-ConstArgHasTypes.
997                                    !kind.has_escaping_bound_vars()
998                                }
999                                _ => false,
1000                            }
1001                        });
1002                    self.out.extend(obligations);
1003                }
1004
1005                if !t.has_escaping_bound_vars() {
1006                    for projection in data.projection_bounds() {
1007                        let pred_binder = projection
1008                            .with_self_ty(tcx, t)
1009                            .map_bound(|p| {
1010                                p.term.as_const().map(|ct| {
1011                                    let assoc_const_ty = tcx
1012                                        .type_of(p.def_id())
1013                                        .instantiate(tcx, p.projection_term.args)
1014                                        .skip_norm_wip();
1015                                    ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(
1016                                        ct,
1017                                        assoc_const_ty,
1018                                    ))
1019                                })
1020                            })
1021                            .transpose();
1022                        if let Some(pred_binder) = pred_binder {
1023                            self.out.push(traits::Obligation::with_depth(
1024                                tcx,
1025                                self.cause(ObligationCauseCode::WellFormed(None)),
1026                                self.recursion_depth,
1027                                self.param_env,
1028                                pred_binder,
1029                            ));
1030                        }
1031                    }
1032                }
1033            }
1034
1035            // Inference variables are the complicated case, since we don't
1036            // know what type they are. We do two things:
1037            //
1038            // 1. Check if they have been resolved, and if so proceed with
1039            //    THAT type.
1040            // 2. If not, we've at least simplified things (e.g., we went
1041            //    from `Vec?0>: WF` to `?0: WF`), so we can
1042            //    register a pending obligation and keep
1043            //    moving. (Goal is that an "inductive hypothesis"
1044            //    is satisfied to ensure termination.)
1045            // See also the comment on `fn obligations`, describing cycle
1046            // prevention, which happens before this can be reached.
1047            ty::Infer(_) => {
1048                let cause = self.cause(ObligationCauseCode::WellFormed(None));
1049                self.out.push(traits::Obligation::with_depth(
1050                    tcx,
1051                    cause,
1052                    self.recursion_depth,
1053                    self.param_env,
1054                    ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(
1055                        t.into(),
1056                    ))),
1057                ));
1058            }
1059        }
1060
1061        t.super_visit_with(self)
1062    }
1063
1064    fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
1065        let tcx = self.tcx();
1066
1067        match c.kind() {
1068            ty::ConstKind::Alias(_, alias_const) => {
1069                if !c.has_escaping_bound_vars() {
1070                    // Skip type consts as mGCA doesn't support evaluatable clauses
1071                    if !alias_const.kind.is_type_const(tcx) && !tcx.features().generic_const_args()
1072                    {
1073                        let predicate = ty::Binder::dummy(ty::PredicateKind::Clause(
1074                            ty::ClauseKind::ConstEvaluatable(c),
1075                        ));
1076                        let cause = self.cause(ObligationCauseCode::WellFormed(None));
1077                        self.out.push(traits::Obligation::with_depth(
1078                            tcx,
1079                            cause,
1080                            self.recursion_depth,
1081                            self.param_env,
1082                            predicate,
1083                        ));
1084                    }
1085
1086                    match alias_const.kind {
1087                        ty::AliasConstKind::Inherent { .. } => {
1088                            self.add_wf_preds_for_inherent_projection(alias_const.into());
1089                            return; // Subtree is handled by above function
1090                        }
1091                        ty::AliasConstKind::Projection { def_id }
1092                        | ty::AliasConstKind::Free { def_id }
1093                        | ty::AliasConstKind::Anon { def_id } => {
1094                            let obligations = self.nominal_obligations(def_id, alias_const.args);
1095                            self.out.extend(obligations);
1096                        }
1097                    }
1098                }
1099            }
1100            ty::ConstKind::Infer(_) => {
1101                let cause = self.cause(ObligationCauseCode::WellFormed(None));
1102
1103                self.out.push(traits::Obligation::with_depth(
1104                    tcx,
1105                    cause,
1106                    self.recursion_depth,
1107                    self.param_env,
1108                    ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(
1109                        c.into(),
1110                    ))),
1111                ));
1112            }
1113            ty::ConstKind::Expr(_) => {
1114                // FIXME(generic_const_exprs): this doesn't verify that given `Expr(N + 1)` the
1115                // trait bound `typeof(N): Add<typeof(1)>` holds. This is currently unnecessary
1116                // as `ConstKind::Expr` is only produced via normalization of `ConstKind::Alias`
1117                // which means that the `DefId` would have been typeck'd elsewhere. However in
1118                // the future we may allow directly lowering to `ConstKind::Expr` in which case
1119                // we would not be proving bounds we should.
1120
1121                let predicate = ty::Binder::dummy(ty::PredicateKind::Clause(
1122                    ty::ClauseKind::ConstEvaluatable(c),
1123                ));
1124                let cause = self.cause(ObligationCauseCode::WellFormed(None));
1125                self.out.push(traits::Obligation::with_depth(
1126                    tcx,
1127                    cause,
1128                    self.recursion_depth,
1129                    self.param_env,
1130                    predicate,
1131                ));
1132            }
1133
1134            ty::ConstKind::Error(_)
1135            | ty::ConstKind::Param(_)
1136            | ty::ConstKind::Bound(..)
1137            | ty::ConstKind::Placeholder(..) => {
1138                // These variants are trivially WF, so nothing to do here.
1139            }
1140            ty::ConstKind::Value(val) => {
1141                // FIXME(mgca): no need to feature-gate once valtree lifetimes are not erased
1142                if tcx.features().min_generic_const_args() {
1143                    match val.ty.kind() {
1144                        ty::Adt(adt_def, args) => {
1145                            let adt_val = val.destructure_adt_const();
1146                            let variant_def = adt_def.variant(adt_val.variant);
1147                            let cause = self.cause(ObligationCauseCode::WellFormed(None));
1148                            self.out.extend(variant_def.fields.iter().zip(adt_val.fields).map(
1149                                |(field_def, &field_val)| {
1150                                    let field_ty = tcx
1151                                        .type_of(field_def.did)
1152                                        .instantiate(tcx, args)
1153                                        .skip_norm_wip();
1154                                    let predicate = ty::PredicateKind::Clause(
1155                                        ty::ClauseKind::ConstArgHasType(field_val, field_ty),
1156                                    );
1157                                    traits::Obligation::with_depth(
1158                                        tcx,
1159                                        cause.clone(),
1160                                        self.recursion_depth,
1161                                        self.param_env,
1162                                        predicate,
1163                                    )
1164                                },
1165                            ));
1166                        }
1167                        ty::Tuple(field_tys) => {
1168                            let field_vals = val.to_branch();
1169                            let cause = self.cause(ObligationCauseCode::WellFormed(None));
1170                            self.out.extend(field_tys.iter().zip(field_vals).map(
1171                                |(field_ty, &field_val)| {
1172                                    let predicate = ty::PredicateKind::Clause(
1173                                        ty::ClauseKind::ConstArgHasType(field_val, field_ty),
1174                                    );
1175                                    traits::Obligation::with_depth(
1176                                        tcx,
1177                                        cause.clone(),
1178                                        self.recursion_depth,
1179                                        self.param_env,
1180                                        predicate,
1181                                    )
1182                                },
1183                            ));
1184                        }
1185                        ty::Array(elem_ty, _len) => {
1186                            let elem_vals = val.to_branch();
1187                            let cause = self.cause(ObligationCauseCode::WellFormed(None));
1188
1189                            self.out.extend(elem_vals.iter().map(|&elem_val| {
1190                                let predicate = ty::PredicateKind::Clause(
1191                                    ty::ClauseKind::ConstArgHasType(elem_val, *elem_ty),
1192                                );
1193                                traits::Obligation::with_depth(
1194                                    tcx,
1195                                    cause.clone(),
1196                                    self.recursion_depth,
1197                                    self.param_env,
1198                                    predicate,
1199                                )
1200                            }));
1201                        }
1202                        _ => {}
1203                    }
1204                }
1205
1206                // FIXME: Enforce that values are structurally-matchable.
1207            }
1208        }
1209
1210        c.super_visit_with(self)
1211    }
1212
1213    fn visit_predicate(&mut self, _p: ty::Predicate<'tcx>) -> Self::Result {
1214        ::rustc_middle::util::bug::bug_fmt(format_args!("predicate should not be checked for well-formedness"));bug!("predicate should not be checked for well-formedness");
1215    }
1216}
1217
1218/// Given an object type like `SomeTrait + Send`, computes the lifetime
1219/// bounds that must hold on the elided self type. These are derived
1220/// from the declarations of `SomeTrait`, `Send`, and friends -- if
1221/// they declare `trait SomeTrait : 'static`, for example, then
1222/// `'static` would appear in the list.
1223///
1224/// N.B., in some cases, particularly around higher-ranked bounds,
1225/// this function returns a kind of conservative approximation.
1226/// That is, all regions returned by this function are definitely
1227/// required, but there may be other region bounds that are not
1228/// returned, as well as requirements like `for<'a> T: 'a`.
1229///
1230/// Requires that trait definitions have been processed so that we can
1231/// elaborate predicates and walk supertraits.
1232pub fn object_region_bounds<'tcx>(
1233    tcx: TyCtxt<'tcx>,
1234    existential_predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
1235) -> Vec<ty::Region<'tcx>> {
1236    let erased_self_ty = tcx.types.trait_object_dummy_self;
1237
1238    let predicates =
1239        existential_predicates.iter().map(|predicate| predicate.with_self_ty(tcx, erased_self_ty));
1240
1241    traits::elaborate(tcx, predicates)
1242        .filter_map(|pred| {
1243            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/wf.rs:1243",
                        "rustc_trait_selection::traits::wf",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/wf.rs"),
                        ::tracing_core::__macro_support::Option::Some(1243u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
                        ::tracing_core::field::FieldSet::new(&["pred"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&pred) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?pred);
1244            match pred.kind().skip_binder() {
1245                ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ref t, ref r)) => {
1246                    // Search for a bound of the form `erased_self_ty
1247                    // : 'a`, but be wary of something like `for<'a>
1248                    // erased_self_ty : 'a` (we interpret a
1249                    // higher-ranked bound like that as 'static,
1250                    // though at present the code in `fulfill.rs`
1251                    // considers such bounds to be unsatisfiable, so
1252                    // it's kind of a moot point since you could never
1253                    // construct such an object, but this seems
1254                    // correct even if that code changes).
1255                    if t == &erased_self_ty && !r.has_escaping_bound_vars() {
1256                        Some(*r)
1257                    } else {
1258                        None
1259                    }
1260                }
1261                ty::ClauseKind::Trait(_)
1262                | ty::ClauseKind::HostEffect(..)
1263                | ty::ClauseKind::RegionOutlives(_)
1264                | ty::ClauseKind::Projection(_)
1265                | ty::ClauseKind::ConstArgHasType(_, _)
1266                | ty::ClauseKind::WellFormed(_)
1267                | ty::ClauseKind::UnstableFeature(_)
1268                | ty::ClauseKind::ConstEvaluatable(_) => None,
1269            }
1270        })
1271        .collect()
1272}