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_attr_ir::lang_items::LangItem;
9use rustc_hir as hir;
10use rustc_infer::traits::{ObligationCauseCode, PredicateObligation, PredicateObligations};
11use rustc_middle::ty::{
12    self, DelayedSet, GenericArgsRef, PredicateProxy, Term, TermKind, Ty, TyCtxt,
13    TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor,
14};
15use rustc_session::diagnostics::feature_err;
16use rustc_span::def_id::{DefId, LocalDefId};
17use rustc_span::{Span, bug, sym};
18use tracing::{debug, instrument};
19
20use crate::infer::InferCtxt;
21use crate::traits;
22
23/// Returns the set of obligations needed to make `term` well-formed.
24/// If `term` contains unresolved inference variables, this may include
25/// further WF obligations. However, if `term` IS an unresolved
26/// inference variable, returns `None`, because we are not able to
27/// make any progress at all. This is to prevent cycles where we
28/// say "?0 is WF if ?0 is WF".
29pub fn obligations<'tcx>(
30    infcx: &InferCtxt<'tcx>,
31    param_env: ty::ParamEnv<'tcx>,
32    body_def_id: LocalDefId,
33    recursion_depth: usize,
34    term: Term<'tcx>,
35    span: Span,
36) -> Option<PredicateObligations<'tcx>> {
37    // Handle the "cycle" case (see comment above) by bailing out if necessary.
38    let term = match term.kind() {
39        TermKind::Ty(ty) => {
40            match ty.kind() {
41                ty::Infer(ty::TyVar(_)) => {
42                    let resolved_ty = infcx.shallow_resolve(ty);
43                    if resolved_ty == ty {
44                        // No progress, bail out to prevent cycles.
45                        return None;
46                    } else {
47                        resolved_ty
48                    }
49                }
50                _ => ty,
51            }
52            .into()
53        }
54        TermKind::Const(ct) => {
55            match ct.kind() {
56                ty::ConstKind::Infer(_) => {
57                    let resolved = infcx.shallow_resolve_const(ct);
58                    if resolved == ct {
59                        // No progress, bail out to prevent cycles.
60                        return None;
61                    } else {
62                        resolved
63                    }
64                }
65                _ => ct,
66            }
67            .into()
68        }
69    };
70
71    let mut wf = WfPredicates {
72        infcx,
73        param_env,
74        body_def_id,
75        span,
76        out: PredicateObligations::new(),
77        recursion_depth,
78        item: None,
79        visited_tys: Default::default(),
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 /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs:82",
                        "rustc_trait_selection::traits::wf",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("wf::obligations({0:?}, body_def_id={1:?}) = {2:?}",
                                                    term, body_def_id, wf.out) as
                                            &dyn ::tracing::field::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 /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs:85",
                        "rustc_trait_selection::traits::wf",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("wf::obligations({0:?}, body_def_id={1:?}) ~~> {2:?}",
                                                    term, body_def_id, result) as
                                            &dyn ::tracing::field::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.deeply_resolve_ignoring_regions(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.deeply_resolve_ignoring_regions(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        visited_tys: Default::default(),
118    };
119    wf.add_wf_preds_for_term(term);
120    Some(wf.out)
121}
122
123/// Returns the obligations that make this trait reference
124/// well-formed. For example, if there is a trait `Set` defined like
125/// `trait Set<K: Eq>`, then the trait bound `Foo: Set<Bar>` is WF
126/// if `Bar: Eq`.
127pub fn trait_obligations<'tcx>(
128    infcx: &InferCtxt<'tcx>,
129    param_env: ty::ParamEnv<'tcx>,
130    body_def_id: LocalDefId,
131    trait_pred: ty::TraitClause<'tcx>,
132    span: Span,
133    item: &'tcx hir::Item<'tcx>,
134) -> PredicateObligations<'tcx> {
135    let mut wf = WfPredicates {
136        infcx,
137        param_env,
138        body_def_id,
139        span,
140        out: PredicateObligations::new(),
141        recursion_depth: 0,
142        item: Some(item),
143        visited_tys: Default::default(),
144    };
145    wf.add_wf_preds_for_trait_pred(trait_pred, Elaborate::All);
146    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs:146",
                        "rustc_trait_selection::traits::wf",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs"),
                        ::tracing_core::__macro_support::Option::Some(146u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("obligations")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("obligations");
                                            NAME.as_str()
                                        }], ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&wf.out)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(obligations = ?wf.out);
147    wf.normalize(infcx)
148}
149
150/// Returns the requirements for `clause` to be well-formed.
151///
152/// For example, if there is a trait `Set` defined like
153/// `trait Set<K: Eq>`, then the trait bound `Foo: Set<Bar>` is WF
154/// if `Bar: Eq`.
155{}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
            ::tracing::Level::INFO <=
                ::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("clause_obligations",
                                "rustc_trait_selection::traits::wf", ::tracing::Level::INFO,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs"),
                                ::tracing_core::__macro_support::Option::Some(155u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("param_env")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("param_env");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("body_def_id")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("body_def_id");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("clause")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("clause");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("span")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("span");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::INFO <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::INFO <=
                                ::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};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&param_env)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&body_def_id)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&clause)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[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;
                    }
                    {
                        let mut wf =
                            WfPredicates {
                                infcx,
                                param_env,
                                body_def_id,
                                span,
                                out: PredicateObligations::new(),
                                recursion_depth: 0,
                                item: None,
                                visited_tys: Default::default(),
                            };
                        match clause.kind().skip_binder() {
                            ty::ClauseKind::Trait(t) => {
                                wf.add_wf_preds_for_trait_pred(t, Elaborate::None);
                            }
                            ty::ClauseKind::HostEffect(..) => {}
                            ty::ClauseKind::RegionOutlives(..) => {}
                            ty::ClauseKind::TypeOutlives(ty::OutlivesClause(ty, _reg))
                                => {
                                wf.add_wf_preds_for_term(ty.into());
                            }
                            ty::ClauseKind::Projection(t) => {
                                wf.add_wf_preds_for_projection_term(t.projection_term);
                                wf.add_wf_preds_for_term(t.term);
                            }
                            ty::ClauseKind::ConstArgHasType(ct, ty) => {
                                wf.add_wf_preds_for_term(ct.into());
                                wf.add_wf_preds_for_term(ty.into());
                            }
                            ty::ClauseKind::WellFormed(term) => {
                                wf.add_wf_preds_for_term(term);
                            }
                            ty::ClauseKind::ConstEvaluatable(ct) => {
                                wf.add_wf_preds_for_term(ct.into());
                            }
                            ty::ClauseKind::UnstableFeature(_) => {}
                        }
                        wf.normalize(infcx)
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs:155",
                        "rustc_trait_selection::traits::wf", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs"),
                        ::tracing_core::__macro_support::Option::Some(155u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(skip(infcx), ret)]
156pub fn clause_obligations<'tcx>(
157    infcx: &InferCtxt<'tcx>,
158    param_env: ty::ParamEnv<'tcx>,
159    body_def_id: LocalDefId,
160    clause: ty::Clause<'tcx>,
161    span: Span,
162) -> PredicateObligations<'tcx> {
163    let mut wf = WfPredicates {
164        infcx,
165        param_env,
166        body_def_id,
167        span,
168        out: PredicateObligations::new(),
169        recursion_depth: 0,
170        item: None,
171        visited_tys: Default::default(),
172    };
173
174    // It's ok to skip the binder here because wf code is prepared for it
175    match clause.kind().skip_binder() {
176        ty::ClauseKind::Trait(t) => {
177            wf.add_wf_preds_for_trait_pred(t, Elaborate::None);
178        }
179        ty::ClauseKind::HostEffect(..) => {
180            // Technically the well-formedness of this clause is implied by
181            // the corresponding trait clause it should've been generated beside.
182        }
183        ty::ClauseKind::RegionOutlives(..) => {}
184        ty::ClauseKind::TypeOutlives(ty::OutlivesClause(ty, _reg)) => {
185            wf.add_wf_preds_for_term(ty.into());
186        }
187        ty::ClauseKind::Projection(t) => {
188            wf.add_wf_preds_for_projection_term(t.projection_term);
189            wf.add_wf_preds_for_term(t.term);
190        }
191        ty::ClauseKind::ConstArgHasType(ct, ty) => {
192            wf.add_wf_preds_for_term(ct.into());
193            wf.add_wf_preds_for_term(ty.into());
194        }
195        ty::ClauseKind::WellFormed(term) => {
196            wf.add_wf_preds_for_term(term);
197        }
198
199        ty::ClauseKind::ConstEvaluatable(ct) => {
200            wf.add_wf_preds_for_term(ct.into());
201        }
202        ty::ClauseKind::UnstableFeature(_) => {}
203    }
204
205    wf.normalize(infcx)
206}
207
208struct WfPredicates<'a, 'tcx> {
209    infcx: &'a InferCtxt<'tcx>,
210    param_env: ty::ParamEnv<'tcx>,
211    body_def_id: LocalDefId,
212    span: Span,
213    out: PredicateObligations<'tcx>,
214    recursion_depth: usize,
215    item: Option<&'tcx hir::Item<'tcx>>,
216    visited_tys: DelayedSet<Ty<'tcx>>,
217}
218
219/// Controls whether we "elaborate" supertraits and so forth on the WF
220/// predicates. This is a kind of hack to address #43784. The
221/// underlying problem in that issue was a trait structure like:
222///
223/// ```ignore (illustrative)
224/// trait Foo: Copy { }
225/// trait Bar: Foo { }
226/// impl<T: Bar> Foo for T { }
227/// impl<T> Bar for T { }
228/// ```
229///
230/// Here, in the `Foo` impl, we will check that `T: Copy` holds -- but
231/// we decide that this is true because `T: Bar` is in the
232/// where-clauses (and we can elaborate that to include `T:
233/// Copy`). This wouldn't be a problem, except that when we check the
234/// `Bar` impl, we decide that `T: Foo` must hold because of the `Foo`
235/// impl. And so nowhere did we check that `T: Copy` holds!
236///
237/// To resolve this, we elaborate the WF requirements that must be
238/// proven when checking impls. This means that (e.g.) the `impl Bar
239/// for T` will be forced to prove not only that `T: Foo` but also `T:
240/// Copy` (which it won't be able to do, because there is no `Copy`
241/// impl for `T`).
242#[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::marker::StructuralPartialEq for Elaborate { }
#[automatically_derived]
impl ::core::cmp::PartialEq for Elaborate {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Elaborate { }Eq, #[automatically_derived]
impl ::core::marker::Copy for Elaborate { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for Elaborate { }
#[automatically_derived]
impl ::core::clone::Clone for Elaborate {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone)]
243enum Elaborate {
244    All,
245    None,
246}
247
248/// Points the cause span of a super predicate at the relevant associated type.
249///
250/// Given a trait impl item:
251///
252/// ```ignore (incomplete)
253/// impl TargetTrait for TargetType {
254///    type Assoc = SomeType;
255/// }
256/// ```
257///
258/// And a super predicate of `TargetTrait` that has any of the following forms:
259///
260/// 1. `<OtherType as OtherTrait>::Assoc == <TargetType as TargetTrait>::Assoc`
261/// 2. `<<TargetType as TargetTrait>::Assoc as OtherTrait>::Assoc == OtherType`
262/// 3. `<TargetType as TargetTrait>::Assoc: OtherTrait`
263///
264/// Replace the span of the cause with the span of the associated item:
265///
266/// ```ignore (incomplete)
267/// impl TargetTrait for TargetType {
268///     type Assoc = SomeType;
269/// //               ^^^^^^^^ this span
270/// }
271/// ```
272///
273/// Note that bounds that can be expressed as associated item bounds are **not**
274/// super predicates. This means that form 2 and 3 from above are only relevant if
275/// the [`GenericArgsRef`] of the projection type are not its identity arguments.
276fn extend_cause_with_original_assoc_item_obligation<'tcx>(
277    tcx: TyCtxt<'tcx>,
278    item: Option<&hir::Item<'tcx>>,
279    cause: &mut traits::ObligationCause<'tcx>,
280    pred: ty::Predicate<'tcx>,
281) {
282    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs:282",
                        "rustc_trait_selection::traits::wf",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs"),
                        ::tracing_core::__macro_support::Option::Some(282u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("item")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("item");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("cause")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("cause");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("pred")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("pred");
                                            NAME.as_str()
                                        }], ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("extended_cause_with_original_assoc_item_obligation")
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&pred)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?item, ?cause, ?pred, "extended_cause_with_original_assoc_item_obligation");
283    let (items, impl_def_id) = match item {
284        Some(hir::Item { kind: hir::ItemKind::Impl(impl_), owner_id, .. }) => {
285            (impl_.items, *owner_id)
286        }
287        _ => return,
288    };
289
290    let ty_to_impl_span = |ty: Ty<'_>| {
291        if let ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id }, .. }) = ty.kind()
292            && let Some(&impl_item_id) = tcx.impl_item_implementor_ids(impl_def_id).get(def_id)
293            && let Some(impl_item) =
294                items.iter().find(|item| item.owner_id.to_def_id() == impl_item_id)
295        {
296            Some(tcx.hir_impl_item(*impl_item).expect_type().span)
297        } else {
298            None
299        }
300    };
301
302    // It is fine to skip the binder as we don't care about regions here.
303    match pred.kind().skip_binder() {
304        ty::PredicateKind::Clause(ty::ClauseKind::Projection(proj)) => {
305            // Form 1: The obligation comes not from the current `impl` nor the `trait` being
306            // implemented, but rather from a "second order" obligation, where an associated
307            // type has a projection coming from another associated type.
308            // See `tests/ui/traits/assoc-type-in-superbad.rs` for an example.
309            if let Some(term_ty) = proj.term.as_type()
310                && let Some(impl_item_span) = ty_to_impl_span(term_ty)
311            {
312                cause.span = impl_item_span;
313            }
314
315            // Form 2: A projection obligation for an associated item failed to be met.
316            // We overwrite the span from above to ensure that a bound like
317            // `Self::Assoc1: Trait<OtherAssoc = Self::Assoc2>` gets the same
318            // span for both obligations that it is lowered to.
319            if let Some(impl_item_span) = ty_to_impl_span(proj.self_ty()) {
320                cause.span = impl_item_span;
321            }
322        }
323
324        ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => {
325            // Form 3: A trait obligation for an associated item failed to be met.
326            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs:326",
                        "rustc_trait_selection::traits::wf",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs"),
                        ::tracing_core::__macro_support::Option::Some(326u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("extended_cause_with_original_assoc_item_obligation trait proj {0:?}",
                                                    pred) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("extended_cause_with_original_assoc_item_obligation trait proj {:?}", pred);
327            if let Some(impl_item_span) = ty_to_impl_span(pred.self_ty()) {
328                cause.span = impl_item_span;
329            }
330        }
331        _ => {}
332    }
333}
334
335impl<'a, 'tcx> WfPredicates<'a, 'tcx> {
336    fn tcx(&self) -> TyCtxt<'tcx> {
337        self.infcx.tcx
338    }
339
340    fn cause(&self, code: traits::ObligationCauseCode<'tcx>) -> traits::ObligationCause<'tcx> {
341        traits::ObligationCause::new(self.span, self.body_def_id, code)
342    }
343
344    fn normalize(self, infcx: &InferCtxt<'tcx>) -> PredicateObligations<'tcx> {
345        // Do not normalize `wf` obligations with the new solver.
346        //
347        // The current deep normalization routine with the new solver does not
348        // handle ambiguity and the new solver correctly deals with unnnormalized goals.
349        // If the user relies on normalized types, e.g. for `fn implied_outlives_bounds`,
350        // it is their responsibility to normalize while avoiding ambiguity.
351        if infcx.next_trait_solver() {
352            return self.out;
353        }
354
355        let cause = self.cause(ObligationCauseCode::WellFormed(None));
356        let param_env = self.param_env;
357        let mut obligations = PredicateObligations::with_capacity(self.out.len());
358        for mut obligation in self.out {
359            if !!obligation.has_escaping_bound_vars() {
    ::core::panicking::panic("assertion failed: !obligation.has_escaping_bound_vars()")
};assert!(!obligation.has_escaping_bound_vars());
360            let mut selcx = traits::SelectionContext::new(infcx);
361            // Don't normalize the whole obligation, the param env is either
362            // already normalized, or we're currently normalizing the
363            // param_env. Either way we should only normalize the predicate.
364            let normalized_predicate = traits::normalize::normalize_with_depth_to(
365                &mut selcx,
366                param_env,
367                cause.clone(),
368                self.recursion_depth,
369                ty::Unnormalized::new_wip(obligation.predicate),
370                &mut obligations,
371            );
372            obligation.predicate = normalized_predicate;
373            obligations.push(obligation);
374        }
375        obligations
376    }
377
378    /// Pushes the obligations required for `trait_ref` to be WF into `self.out`.
379    fn add_wf_preds_for_trait_pred(
380        &mut self,
381        trait_pred: ty::TraitClause<'tcx>,
382        elaborate: Elaborate,
383    ) {
384        let tcx = self.tcx();
385        let trait_ref = trait_pred.trait_ref;
386
387        // Negative trait predicates don't require supertraits to hold, just
388        // that their args are WF.
389        if trait_pred.polarity == ty::ClausePolarity::Negative {
390            self.add_wf_preds_for_negative_trait_pred(trait_ref);
391            return;
392        }
393
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 the trait predicate is not const, the wf obligations should not be const as well.
411        if let Elaborate::All = elaborate {
412            let mut obligations = PredicateObligations::new();
413            self.nominal_obligations(trait_ref.def_id, trait_ref.args, |_, obligation| {
414                obligations.push(obligation)
415            });
416            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs:416",
                        "rustc_trait_selection::traits::wf",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs"),
                        ::tracing_core::__macro_support::Option::Some(416u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("compute_trait_pred obligations {0:?}",
                                                    obligations) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("compute_trait_pred obligations {:?}", obligations);
417            let implied_obligations = traits::util::elaborate(tcx, obligations);
418            let implied_obligations = implied_obligations.map(extend);
419            self.out.extend(implied_obligations);
420        } else {
421            self.nominal_obligations(trait_ref.def_id, trait_ref.args, |this, obligation| {
422                this.out.push(obligation)
423            });
424        }
425
426        self.out.extend(
427            trait_ref
428                .args
429                .iter()
430                .enumerate()
431                .filter_map(|(i, arg)| arg.as_term().map(|t| (i, t)))
432                .filter(|(_, term)| !term.has_escaping_bound_vars())
433                .map(|(i, term)| {
434                    let mut cause = traits::ObligationCause::misc(self.span, self.body_def_id);
435                    // The first arg is the self ty - use the correct span for it.
436                    if i == 0 {
437                        if let Some(hir::ItemKind::Impl(hir::Impl { self_ty, .. })) =
438                            item.map(|i| &i.kind)
439                        {
440                            cause.span = self_ty.span;
441                        }
442                    }
443                    traits::Obligation::with_depth(
444                        tcx,
445                        cause,
446                        depth,
447                        param_env,
448                        ty::ClauseKind::WellFormed(term),
449                    )
450                }),
451        );
452    }
453
454    // Compute the obligations that are required for `trait_ref` to be WF,
455    // given that it is a *negative* trait predicate.
456    fn add_wf_preds_for_negative_trait_pred(&mut self, trait_ref: ty::TraitRef<'tcx>) {
457        for arg in trait_ref.args {
458            if let Some(term) = arg.as_term() {
459                self.add_wf_preds_for_term(term);
460            }
461        }
462    }
463
464    /// Pushes the obligations required for a projection to be WF into `self.out`.
465    fn add_wf_preds_for_projection_term(&mut self, data: ty::AliasTerm<'tcx>) {
466        // A projection is well-formed if
467        //
468        // (a) its predicates hold (*)
469        // (b) its args are wf
470        //
471        // (*) The predicates of an associated type include the predicates of
472        //     the trait that it's contained in. For example, given
473        //
474        // trait A<T>: Clone {
475        //     type X where T: Copy;
476        // }
477        //
478        // The predicates of `<() as A<i32>>::X` are:
479        // [
480        //     `(): Sized`
481        //     `(): Clone`
482        //     `(): A<i32>`
483        //     `i32: Sized`
484        //     `i32: Clone`
485        //     `i32: Copy`
486        // ]
487        self.nominal_obligations(data.expect_projection_def_id(), data.args, |this, obligation| {
488            this.out.push(obligation)
489        });
490
491        self.add_wf_preds_for_projection_args(data.args);
492    }
493
494    /// Pushes the obligations required for an inherent alias to be WF
495    /// into `self.out`.
496    // FIXME(inherent_associated_types): Merge this function with `fn compute_alias`.
497    fn add_wf_preds_for_inherent_projection(&mut self, data: ty::AliasTerm<'tcx>) {
498        // An inherent projection is well-formed if
499        //
500        // (a) its predicates hold (*)
501        // (b) its args are wf
502        //
503        // (*) The predicates of an inherent associated type include the
504        //     predicates of the impl that it's contained in.
505
506        // In an ideal world, there are no escaping bound vars here. However, WF is jank, and
507        // sometimes there are. We can only `compute_inherent_assoc_term_args` if the Self ty in the
508        // args has no escaping bound vars. If we already have impl format args, though,
509        // `compute_inherent_assoc_term_args` is a no-op (and we have no Self type), so no need to
510        // check for escaping bound vars.
511        let can_compute_impl_args =
512            #[allow(non_exhaustive_omitted_patterns)] match data.kind {
    ty::AliasTermKind::InherentConstImpl { .. } => true,
    _ => false,
}matches!(data.kind, ty::AliasTermKind::InherentConstImpl { .. })
513                || !data.self_ty().has_escaping_bound_vars();
514
515        if can_compute_impl_args {
516            // FIXME(inherent_associated_types): Should this happen inside of a snapshot?
517            // FIXME(inherent_associated_types): This is incompatible with the new solver and lazy norm!
518            let args = traits::project::compute_inherent_assoc_term_args(
519                &mut traits::SelectionContext::new(self.infcx),
520                self.param_env,
521                data,
522                self.cause(ObligationCauseCode::WellFormed(None)),
523                self.recursion_depth,
524                &mut self.out,
525            );
526            let def_id = data.expect_inherent_def_id();
527            self.nominal_obligations(def_id, args, |this, obligation| this.out.push(obligation));
528        }
529
530        data.args.visit_with(self);
531    }
532
533    fn add_wf_preds_for_projection_args(&mut self, args: GenericArgsRef<'tcx>) {
534        let tcx = self.tcx();
535        let cause = self.cause(ObligationCauseCode::WellFormed(None));
536        let param_env = self.param_env;
537        let depth = self.recursion_depth;
538
539        self.out.extend(
540            args.iter()
541                .filter_map(|arg| arg.as_term())
542                .filter(|term| !term.has_escaping_bound_vars())
543                .map(|term| {
544                    traits::Obligation::with_depth(
545                        tcx,
546                        cause.clone(),
547                        depth,
548                        param_env,
549                        ty::ClauseKind::WellFormed(term),
550                    )
551                }),
552        );
553    }
554
555    fn require_sized(&mut self, subty: Ty<'tcx>, cause: traits::ObligationCauseCode<'tcx>) {
556        if !subty.has_escaping_bound_vars() {
557            let cause = self.cause(cause);
558            let trait_ref = ty::TraitRef::new(
559                self.tcx(),
560                self.tcx().require_lang_item(LangItem::Sized, cause.span),
561                [subty],
562            );
563            self.out.push(traits::Obligation::with_depth(
564                self.tcx(),
565                cause,
566                self.recursion_depth,
567                self.param_env,
568                ty::Binder::dummy(trait_ref),
569            ));
570        }
571    }
572
573    /// Pushes all the predicates needed to validate that `term` is WF into `out`.
574    {}
#[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("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs"),
                                    ::tracing_core::__macro_support::Option::Some(574u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("term")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("term");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&term)
                                                            as &dyn ::tracing::field::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 /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs:577",
                                    "rustc_trait_selection::traits::wf",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs"),
                                    ::tracing_core::__macro_support::Option::Some(577u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("self.out")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("self.out");
                                                        NAME.as_str()
                                                    }], ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self.out)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
        }
    }
}#[instrument(level = "debug", skip(self))]
575    fn add_wf_preds_for_term(&mut self, term: Term<'tcx>) {
576        term.visit_with(self);
577        debug!(?self.out);
578    }
579
580    {}
#[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("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs"),
                                    ::tracing_core::__macro_support::Option::Some(580u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("args")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("args");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&args)
                                                            as &dyn ::tracing::field::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;
        }
        {
            if self.tcx().is_lang_item(def_id, LangItem::Sized) { return; }
            if self.tcx().is_lang_item(def_id, LangItem::ConstParamTy) &&
                    self.tcx().features().const_param_ty_unchecked() {
                return;
            }
            let tcx = self.tcx();
            let mut head = (def_id, tcx.clauses_of(def_id));
            let mut inner_levels = Vec::new();
            while let Some(parent) = head.1.parent {
                inner_levels.push(head);
                head = (parent, tcx.clauses_of(parent));
            }
            for &(origin_def_id, clauses) in
                iter::once(&head).chain(inner_levels.iter().rev()) {
                for (clause, span) in clauses.instantiate_own(tcx, args) {
                    if !clause.has_escaping_bound_vars() {
                        let code =
                            ObligationCauseCode::WhereClause(origin_def_id, span);
                        let cause = self.cause(code);
                        let obligation =
                            traits::Obligation::with_depth(tcx, cause,
                                self.recursion_depth, self.param_env,
                                clause.skip_norm_wip());
                        push_obligation(self, obligation);
                    }
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self, push_obligation))]
581    fn nominal_obligations(
582        &mut self,
583        def_id: DefId,
584        args: GenericArgsRef<'tcx>,
585        mut push_obligation: impl FnMut(&mut Self, PredicateObligation<'tcx>),
586    ) {
587        // PERF: `Sized`'s predicates include `MetaSized`, but both are compiler implemented marker
588        // traits, so `MetaSized` will always be WF if `Sized` is WF and vice-versa. Determining
589        // the nominal obligations of `Sized` would in-effect just elaborate `MetaSized` and make
590        // the compiler do a bunch of work needlessly.
591        if self.tcx().is_lang_item(def_id, LangItem::Sized) {
592            return;
593        }
594        if self.tcx().is_lang_item(def_id, LangItem::ConstParamTy)
595            && self.tcx().features().const_param_ty_unchecked()
596        {
597            return;
598        }
599
600        let tcx = self.tcx();
601        let mut head = (def_id, tcx.clauses_of(def_id));
602        let mut inner_levels = Vec::new(); // only allocates if a parent chain exists
603        while let Some(parent) = head.1.parent {
604            inner_levels.push(head);
605            head = (parent, tcx.clauses_of(parent));
606        }
607
608        // Emit outermost first, as diagnostics rely on that order.
609        for &(origin_def_id, clauses) in iter::once(&head).chain(inner_levels.iter().rev()) {
610            for (clause, span) in clauses.instantiate_own(tcx, args) {
611                if !clause.has_escaping_bound_vars() {
612                    let code = ObligationCauseCode::WhereClause(origin_def_id, span);
613                    let cause = self.cause(code);
614                    let obligation = traits::Obligation::with_depth(
615                        tcx,
616                        cause,
617                        self.recursion_depth,
618                        self.param_env,
619                        clause.skip_norm_wip(),
620                    );
621                    push_obligation(self, obligation);
622                }
623            }
624        }
625    }
626
627    fn add_wf_preds_for_dyn_ty(
628        &mut self,
629        ty: Ty<'tcx>,
630        data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
631        region: ty::Region<'tcx>,
632    ) {
633        // Imagine a type like this:
634        //
635        //     trait Foo { }
636        //     trait Bar<'c> : 'c { }
637        //
638        //     &'b (Foo+'c+Bar<'d>)
639        //         ^
640        //
641        // In this case, the following relationships must hold:
642        //
643        //     'b <= 'c
644        //     'd <= 'c
645        //
646        // The first conditions is due to the normal region pointer
647        // rules, which say that a reference cannot outlive its
648        // referent.
649        //
650        // The final condition may be a bit surprising. In particular,
651        // you may expect that it would have been `'c <= 'd`, since
652        // usually lifetimes of outer things are conservative
653        // approximations for inner things. However, it works somewhat
654        // differently with trait objects: here the idea is that if the
655        // user specifies a region bound (`'c`, in this case) it is the
656        // "master bound" that *implies* that bounds from other traits are
657        // all met. (Remember that *all bounds* in a type like
658        // `Foo+Bar+Zed` must be met, not just one, hence if we write
659        // `Foo<'x>+Bar<'y>`, we know that the type outlives *both* 'x and
660        // 'y.)
661        //
662        // Note: in fact we only permit builtin traits, not `Bar<'d>`, I
663        // am looking forward to the future here.
664        if !data.has_escaping_bound_vars() && !region.has_escaping_bound_vars() {
665            let implicit_bounds = object_region_bounds(self.tcx(), data);
666
667            let explicit_bound = region;
668
669            self.out.reserve(implicit_bounds.len());
670            for implicit_bound in implicit_bounds {
671                let cause = self.cause(ObligationCauseCode::ObjectTypeBound(ty, explicit_bound));
672                let outlives =
673                    ty::Binder::dummy(ty::OutlivesClause(explicit_bound, implicit_bound));
674                self.out.push(traits::Obligation::with_depth(
675                    self.tcx(),
676                    cause,
677                    self.recursion_depth,
678                    self.param_env,
679                    outlives,
680                ));
681            }
682
683            // We don't add any wf predicates corresponding to the trait ref's generic arguments
684            // which allows code like this to compile:
685            // ```rust
686            // trait Trait<T: Sized> {}
687            // fn foo(_: &dyn Trait<[u32]>) {}
688            // ```
689        }
690    }
691
692    fn add_wf_preds_for_pat_ty(&mut self, base_ty: Ty<'tcx>, pat: ty::Pattern<'tcx>) {
693        let tcx = self.tcx();
694        match *pat {
695            ty::PatternKind::Range { start, end } => {
696                let mut check = |c| {
697                    let cause = self.cause(ObligationCauseCode::Misc);
698                    self.out.push(traits::Obligation::with_depth(
699                        tcx,
700                        cause.clone(),
701                        self.recursion_depth,
702                        self.param_env,
703                        ty::Binder::dummy(ty::PredicateKind::Clause(
704                            ty::ClauseKind::ConstArgHasType(c, base_ty),
705                        )),
706                    ));
707                    if !tcx.features().generic_pattern_types() {
708                        if c.has_param() {
709                            if self.span.is_dummy() {
710                                self.tcx()
711                                    .dcx()
712                                    .delayed_bug("feature error should be reported elsewhere, too");
713                            } else {
714                                feature_err(
715                                    &self.tcx().sess,
716                                    sym::generic_pattern_types,
717                                    self.span,
718                                    "wraparound pattern type ranges cause monomorphization time errors",
719                                )
720                                .emit();
721                            }
722                        }
723                    }
724                };
725                check(start);
726                check(end);
727            }
728            ty::PatternKind::NotNull => {}
729            ty::PatternKind::Or(patterns) => {
730                for pat in patterns {
731                    self.add_wf_preds_for_pat_ty(base_ty, pat)
732                }
733            }
734        }
735    }
736}
737
738impl<'a, 'tcx> TypeVisitor<TyCtxt<'tcx>> for WfPredicates<'a, 'tcx> {
739    fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
740        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs:740",
                        "rustc_trait_selection::traits::wf",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs"),
                        ::tracing_core::__macro_support::Option::Some(740u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("wf bounds for t={0:?} t.kind={1:#?}",
                                                    t, t.kind()) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("wf bounds for t={:?} t.kind={:#?}", t, t.kind());
741
742        if !self.visited_tys.insert(t) {
743            return;
744        }
745
746        let tcx = self.tcx();
747
748        match *t.kind() {
749            ty::Bool
750            | ty::Char
751            | ty::Int(..)
752            | ty::Uint(..)
753            | ty::Float(..)
754            | ty::Error(_)
755            | ty::Str
756            | ty::CoroutineWitness(..)
757            | ty::Never
758            | ty::Param(_)
759            | ty::Bound(..)
760            | ty::Placeholder(..)
761            | ty::Foreign(..) => {
762                // WfScalar, WfParameter, etc
763            }
764
765            // Can only infer to `ty::Int(_) | ty::Uint(_)`.
766            ty::Infer(ty::IntVar(_)) => {}
767
768            // Can only infer to `ty::Float(_)`.
769            ty::Infer(ty::FloatVar(_)) => {}
770
771            ty::Slice(subty) => {
772                self.require_sized(subty, ObligationCauseCode::SliceOrArrayElem);
773            }
774
775            ty::Array(subty, len) => {
776                self.require_sized(subty, ObligationCauseCode::SliceOrArrayElem);
777                // Note that the len being WF is implicitly checked while visiting.
778                // Here we just check that it's of type usize.
779                let cause = self.cause(ObligationCauseCode::ArrayLen(t));
780                self.out.push(traits::Obligation::with_depth(
781                    tcx,
782                    cause,
783                    self.recursion_depth,
784                    self.param_env,
785                    ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(
786                        len,
787                        tcx.types.usize,
788                    ))),
789                ));
790            }
791
792            ty::Pat(base_ty, pat) => {
793                self.require_sized(base_ty, ObligationCauseCode::Misc);
794                self.add_wf_preds_for_pat_ty(base_ty, pat);
795            }
796
797            ty::Tuple(tys) => {
798                if let Some((last, rest)) = tys.split_last() {
799                    for &elem in rest {
800                        self.require_sized(elem, ObligationCauseCode::TupleElem);
801                        if elem.is_scalable_vector() && !self.span.is_dummy() {
802                            self.tcx()
803                                .dcx()
804                                .struct_span_err(
805                                    self.span,
806                                    "scalable vectors cannot be tuple fields",
807                                )
808                                .emit();
809                        }
810                    }
811
812                    if last.is_scalable_vector() && !self.span.is_dummy() {
813                        self.tcx()
814                            .dcx()
815                            .struct_span_err(self.span, "scalable vectors cannot be tuple fields")
816                            .emit();
817                    }
818                }
819            }
820
821            ty::RawPtr(_, _) => {
822                // Simple cases that are WF if their type args are WF.
823            }
824
825            ty::Alias(
826                _,
827                ty::AliasTy {
828                    kind: ty::Projection { def_id } | ty::Opaque { def_id } | ty::Free { def_id },
829                    args,
830                    ..
831                },
832            ) => {
833                self.nominal_obligations(def_id, args, |this, obligation| {
834                    this.out.push(obligation)
835                });
836            }
837            ty::Alias(_, data @ ty::AliasTy { kind: ty::Inherent { .. }, .. }) => {
838                self.add_wf_preds_for_inherent_projection(data.into());
839                return; // Subtree handled by compute_inherent_projection.
840            }
841
842            ty::Adt(def, args) => {
843                // WfNominalType
844                self.nominal_obligations(def.did(), args, |this, obligation| {
845                    this.out.push(obligation)
846                });
847            }
848
849            ty::FnDef(did, args) => {
850                let args = args.no_bound_vars().unwrap();
851                // HACK: Check the return type of function definitions for
852                // well-formedness to mostly fix #84533. This is still not
853                // perfect and there may be ways to abuse the fact that we
854                // ignore requirements with escaping bound vars. That's a
855                // more general issue however.
856                let fn_sig = tcx.fn_sig(did).instantiate(tcx, args).skip_norm_wip();
857                fn_sig.output().skip_binder().visit_with(self);
858
859                self.nominal_obligations(did, args, |this, obligation| this.out.push(obligation));
860            }
861
862            ty::Ref(r, rty, _) => {
863                // WfReference
864                if !r.has_escaping_bound_vars() && !rty.has_escaping_bound_vars() {
865                    let cause = self.cause(ObligationCauseCode::ReferenceOutlivesReferent(t));
866                    self.out.push(traits::Obligation::with_depth(
867                        tcx,
868                        cause,
869                        self.recursion_depth,
870                        self.param_env,
871                        ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(
872                            ty::OutlivesClause(rty, r),
873                        ))),
874                    ));
875                }
876            }
877
878            ty::Coroutine(did, args, ..) => {
879                // Walk ALL the types in the coroutine: this will
880                // include the upvar types as well as the yield
881                // type. Note that this is mildly distinct from
882                // the closure case, where we have to be careful
883                // about the signature of the closure. We don't
884                // have the problem of implied bounds here since
885                // coroutines don't take arguments.
886                self.nominal_obligations(did, args, |this, obligation| this.out.push(obligation));
887            }
888
889            ty::Closure(did, args) => {
890                // Note that we cannot skip the generic types
891                // types. Normally, within the fn
892                // body where they are created, the generics will
893                // always be WF, and outside of that fn body we
894                // are not directly inspecting closure types
895                // anyway, except via auto trait matching (which
896                // only inspects the upvar types).
897                // But when a closure is part of a type-alias-impl-trait
898                // then the function that created the defining site may
899                // have had more bounds available than the type alias
900                // specifies. This may cause us to have a closure in the
901                // hidden type that is not actually well formed and
902                // can cause compiler crashes when the user abuses unsafe
903                // code to procure such a closure.
904                // See tests/ui/type-alias-impl-trait/wf_check_closures.rs
905                self.nominal_obligations(did, args, |this, obligation| this.out.push(obligation));
906                // Only check the upvar types for WF, not the rest
907                // of the types within. This is needed because we
908                // capture the signature and it may not be WF
909                // without the implied bounds. Consider a closure
910                // like `|x: &'a T|` -- it may be that `T: 'a` is
911                // not known to hold in the creator's context (and
912                // indeed the closure may not be invoked by its
913                // creator, but rather turned to someone who *can*
914                // verify that).
915                //
916                // The special treatment of closures here really
917                // ought not to be necessary either; the problem
918                // is related to #25860 -- there is no way for us
919                // to express a fn type complete with the implied
920                // bounds that it is assuming. I think in reality
921                // the WF rules around fn are a bit messed up, and
922                // that is the rot problem: `fn(&'a T)` should
923                // probably always be WF, because it should be
924                // shorthand for something like `where(T: 'a) {
925                // fn(&'a T) }`, as discussed in #25860.
926                let upvars = args.as_closure().tupled_upvars_ty();
927                return upvars.visit_with(self);
928            }
929
930            ty::CoroutineClosure(did, args) => {
931                // See the above comments. The same apply to coroutine-closures.
932                self.nominal_obligations(did, args, |this, obligation| this.out.push(obligation));
933                let upvars = args.as_coroutine_closure().tupled_upvars_ty();
934                return upvars.visit_with(self);
935            }
936
937            ty::FnPtr(..) => {
938                // Let the visitor iterate into the argument/return
939                // types appearing in the fn signature.
940            }
941            ty::UnsafeBinder(ty) => {
942                // FIXME(unsafe_binders): For now, we have no way to express
943                // that a type must be `ManuallyDrop` OR `Copy` (or a pointer).
944                if !ty.has_escaping_bound_vars() {
945                    self.out.push(traits::Obligation::new(
946                        self.tcx(),
947                        self.cause(ObligationCauseCode::Misc),
948                        self.param_env,
949                        ty.map_bound(|ty| {
950                            ty::TraitRef::new(
951                                self.tcx(),
952                                self.tcx().require_lang_item(
953                                    LangItem::BikeshedGuaranteedNoDrop,
954                                    self.span,
955                                ),
956                                [ty],
957                            )
958                        }),
959                    ));
960                }
961
962                // We recurse into the binder below.
963            }
964
965            ty::Dynamic(data, r) => {
966                // WfObject
967                //
968                // Here, we defer WF checking due to higher-ranked
969                // regions. This is perhaps not ideal.
970                self.add_wf_preds_for_dyn_ty(t, data, r);
971
972                // FIXME(#27579) RFC also considers adding trait
973                // obligations that don't refer to Self and
974                // checking those
975                if let Some(principal) = data.principal() {
976                    let principal_def_id = principal.skip_binder().def_id;
977                    self.out.push(traits::Obligation::with_depth(
978                        tcx,
979                        self.cause(ObligationCauseCode::WellFormed(None)),
980                        self.recursion_depth,
981                        self.param_env,
982                        ty::Binder::dummy(ty::PredicateKind::DynCompatible(principal_def_id)),
983                    ));
984
985                    // For the most part we don't add wf predicates corresponding to
986                    // the trait ref's generic arguments which allows code like this
987                    // to compile:
988                    // ```rust
989                    // trait Trait<T: Sized> {}
990                    // fn foo(_: &dyn Trait<[u32]>) {}
991                    // ```
992                    //
993                    // However, we sometimes incidentally check that const arguments
994                    // have the correct type as a side effect of the anon const
995                    // desugaring. To make this "consistent" for users we explicitly
996                    // check `ConstArgHasType` clauses so that const args that don't
997                    // go through an anon const still have their types checked.
998                    //
999                    // See also: https://rustc-dev-guide.rust-lang.org/const-generics.html
1000                    let args = principal.skip_binder().with_self_ty(self.tcx(), t).args;
1001                    self.nominal_obligations(principal_def_id, args, |this, obligation| {
1002                        let kind = obligation.predicate.kind().skip_binder();
1003                        let keep = match kind {
1004                            ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(ct, _))
1005                                if #[allow(non_exhaustive_omitted_patterns)] match ct.kind() {
    ty::ConstKind::Param(..) | ty::ConstKind::Placeholder(..) => true,
    _ => false,
}matches!(
1006                                    ct.kind(),
1007                                    ty::ConstKind::Param(..) | ty::ConstKind::Placeholder(..)
1008                                ) =>
1009                            {
1010                                // ConstArgHasType clauses are not higher kinded. Assert as
1011                                // such so we can fix this up if that ever changes.
1012                                if !obligation.predicate.kind().bound_vars().is_empty() {
    ::core::panicking::panic("assertion failed: obligation.predicate.kind().bound_vars().is_empty()")
};assert!(obligation.predicate.kind().bound_vars().is_empty());
1013                                // In stable rust, variables from the trait object binder
1014                                // cannot be referenced by a ConstArgHasType clause. However,
1015                                // under `generic_const_parameter_types`, it can. Ignore those
1016                                // predicates for now, to not have HKT-ConstArgHasTypes.
1017                                !kind.has_escaping_bound_vars()
1018                            }
1019                            _ => false,
1020                        };
1021                        if keep {
1022                            this.out.push(obligation);
1023                        }
1024                    });
1025                }
1026
1027                if !t.has_escaping_bound_vars() {
1028                    for projection in data.projection_bounds() {
1029                        let pred_binder = projection
1030                            .with_self_ty(tcx, t)
1031                            .map_bound(|p| {
1032                                p.term.as_const().map(|ct| {
1033                                    let assoc_const_ty = tcx
1034                                        .type_of(p.def_id())
1035                                        .instantiate(tcx, p.projection_term.args)
1036                                        .skip_norm_wip();
1037                                    ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(
1038                                        ct,
1039                                        assoc_const_ty,
1040                                    ))
1041                                })
1042                            })
1043                            .transpose();
1044                        if let Some(pred_binder) = pred_binder {
1045                            self.out.push(traits::Obligation::with_depth(
1046                                tcx,
1047                                self.cause(ObligationCauseCode::WellFormed(None)),
1048                                self.recursion_depth,
1049                                self.param_env,
1050                                pred_binder,
1051                            ));
1052                        }
1053                    }
1054                }
1055            }
1056
1057            // Inference variables are the complicated case, since we don't
1058            // know what type they are. We do two things:
1059            //
1060            // 1. Check if they have been resolved, and if so proceed with
1061            //    THAT type.
1062            // 2. If not, we've at least simplified things (e.g., we went
1063            //    from `Vec?0>: WF` to `?0: WF`), so we can
1064            //    register a pending obligation and keep
1065            //    moving. (Goal is that an "inductive hypothesis"
1066            //    is satisfied to ensure termination.)
1067            // See also the comment on `fn obligations`, describing cycle
1068            // prevention, which happens before this can be reached.
1069            ty::Infer(_) => {
1070                let cause = self.cause(ObligationCauseCode::WellFormed(None));
1071                self.out.push(traits::Obligation::with_depth(
1072                    tcx,
1073                    cause,
1074                    self.recursion_depth,
1075                    self.param_env,
1076                    ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(
1077                        t.into(),
1078                    ))),
1079                ));
1080            }
1081        }
1082
1083        t.super_visit_with(self)
1084    }
1085
1086    fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
1087        let tcx = self.tcx();
1088
1089        match c.kind() {
1090            ty::ConstKind::Alias(_, alias_const) => {
1091                if !c.has_escaping_bound_vars() {
1092                    // Skip type consts as mGCA doesn't support evaluatable clauses
1093                    if !alias_const.kind.is_direct_const(tcx) && !tcx.features().gca_const_items() {
1094                        let predicate = ty::Binder::dummy(ty::PredicateKind::Clause(
1095                            ty::ClauseKind::ConstEvaluatable(c),
1096                        ));
1097                        let cause = self.cause(ObligationCauseCode::WellFormed(None));
1098                        self.out.push(traits::Obligation::with_depth(
1099                            tcx,
1100                            cause,
1101                            self.recursion_depth,
1102                            self.param_env,
1103                            predicate,
1104                        ));
1105                    }
1106
1107                    match alias_const.kind {
1108                        ty::AliasConstKind::InherentSelf { .. } => {
1109                            self.add_wf_preds_for_inherent_projection(alias_const.into());
1110                            return; // Subtree is handled by above function
1111                        }
1112                        // FIXME: This should be unreachable but isn't because we normalize in item
1113                        // wfck before computing wf requirements
1114                        ty::AliasConstKind::InherentImpl { .. } => {
1115                            self.add_wf_preds_for_inherent_projection(alias_const.into());
1116                            return;
1117                        }
1118                        ty::AliasConstKind::Projection { def_id }
1119                        | ty::AliasConstKind::Free { def_id }
1120                        | ty::AliasConstKind::Anon { def_id } => {
1121                            self.nominal_obligations(
1122                                def_id,
1123                                alias_const.args,
1124                                |this, obligation| this.out.push(obligation),
1125                            );
1126                        }
1127                    }
1128                }
1129            }
1130            ty::ConstKind::Infer(_) => {
1131                let cause = self.cause(ObligationCauseCode::WellFormed(None));
1132
1133                self.out.push(traits::Obligation::with_depth(
1134                    tcx,
1135                    cause,
1136                    self.recursion_depth,
1137                    self.param_env,
1138                    ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(
1139                        c.into(),
1140                    ))),
1141                ));
1142            }
1143            ty::ConstKind::Expr(_) => {
1144                // FIXME(generic_const_exprs): this doesn't verify that given `Expr(N + 1)` the
1145                // trait bound `typeof(N): Add<typeof(1)>` holds. This is currently unnecessary
1146                // as `ConstKind::Expr` is only produced via normalization of `ConstKind::Alias`
1147                // which means that the `DefId` would have been typeck'd elsewhere. However in
1148                // the future we may allow directly lowering to `ConstKind::Expr` in which case
1149                // we would not be proving bounds we should.
1150
1151                let predicate = ty::Binder::dummy(ty::PredicateKind::Clause(
1152                    ty::ClauseKind::ConstEvaluatable(c),
1153                ));
1154                let cause = self.cause(ObligationCauseCode::WellFormed(None));
1155                self.out.push(traits::Obligation::with_depth(
1156                    tcx,
1157                    cause,
1158                    self.recursion_depth,
1159                    self.param_env,
1160                    predicate,
1161                ));
1162            }
1163
1164            ty::ConstKind::Error(_)
1165            | ty::ConstKind::Param(_)
1166            | ty::ConstKind::Bound(..)
1167            | ty::ConstKind::Placeholder(..) => {
1168                // These variants are trivially WF, so nothing to do here.
1169            }
1170            ty::ConstKind::Value(val) => {
1171                // FIXME(mgca): no need to feature-gate once valtree lifetimes are not erased
1172                if tcx.features().gca_min_const_items() {
1173                    match val.ty.kind() {
1174                        ty::Adt(adt_def, args) => {
1175                            let adt_val = val.destructure_adt_const();
1176                            let variant_def = adt_def.variant(adt_val.variant);
1177                            let cause = self.cause(ObligationCauseCode::WellFormed(None));
1178                            self.out.extend(variant_def.fields.iter().zip(adt_val.fields).map(
1179                                |(field_def, &field_val)| {
1180                                    let field_ty = tcx
1181                                        .type_of(field_def.did)
1182                                        .instantiate(tcx, args)
1183                                        .skip_norm_wip();
1184                                    let predicate = ty::PredicateKind::Clause(
1185                                        ty::ClauseKind::ConstArgHasType(field_val, field_ty),
1186                                    );
1187                                    traits::Obligation::with_depth(
1188                                        tcx,
1189                                        cause.clone(),
1190                                        self.recursion_depth,
1191                                        self.param_env,
1192                                        predicate,
1193                                    )
1194                                },
1195                            ));
1196                        }
1197                        ty::Tuple(field_tys) => {
1198                            let field_vals = val.to_branch();
1199                            let cause = self.cause(ObligationCauseCode::WellFormed(None));
1200                            self.out.extend(field_tys.iter().zip(field_vals).map(
1201                                |(field_ty, &field_val)| {
1202                                    let predicate = ty::PredicateKind::Clause(
1203                                        ty::ClauseKind::ConstArgHasType(field_val, field_ty),
1204                                    );
1205                                    traits::Obligation::with_depth(
1206                                        tcx,
1207                                        cause.clone(),
1208                                        self.recursion_depth,
1209                                        self.param_env,
1210                                        predicate,
1211                                    )
1212                                },
1213                            ));
1214                        }
1215                        ty::Array(elem_ty, _len) => {
1216                            let elem_vals = val.to_branch();
1217                            let cause = self.cause(ObligationCauseCode::WellFormed(None));
1218
1219                            self.out.extend(elem_vals.iter().map(|&elem_val| {
1220                                let predicate = ty::PredicateKind::Clause(
1221                                    ty::ClauseKind::ConstArgHasType(elem_val, *elem_ty),
1222                                );
1223                                traits::Obligation::with_depth(
1224                                    tcx,
1225                                    cause.clone(),
1226                                    self.recursion_depth,
1227                                    self.param_env,
1228                                    predicate,
1229                                )
1230                            }));
1231                        }
1232                        _ => {}
1233                    }
1234                }
1235
1236                // FIXME: Enforce that values are structurally-matchable.
1237            }
1238        }
1239
1240        c.super_visit_with(self)
1241    }
1242
1243    fn visit_predicate<P: PredicateProxy<TyCtxt<'tcx>>>(&mut self, _p: P) -> Self::Result {
1244        ::rustc_span::macros::bug_impl(None,
    format_args!("predicate should not be checked for well-formedness"),
    Location::caller());bug!("predicate should not be checked for well-formedness");
1245    }
1246}
1247
1248/// Given an object type like `SomeTrait + Send`, computes the lifetime
1249/// bounds that must hold on the elided self type. These are derived
1250/// from the declarations of `SomeTrait`, `Send`, and friends -- if
1251/// they declare `trait SomeTrait : 'static`, for example, then
1252/// `'static` would appear in the list.
1253///
1254/// N.B., in some cases, particularly around higher-ranked bounds,
1255/// this function returns a kind of conservative approximation.
1256/// That is, all regions returned by this function are definitely
1257/// required, but there may be other region bounds that are not
1258/// returned, as well as requirements like `for<'a> T: 'a`.
1259///
1260/// Requires that trait definitions have been processed so that we can
1261/// elaborate predicates and walk supertraits.
1262pub fn object_region_bounds<'tcx>(
1263    tcx: TyCtxt<'tcx>,
1264    existential_predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
1265) -> Vec<ty::Region<'tcx>> {
1266    let erased_self_ty = tcx.types.trait_object_dummy_self;
1267
1268    let clauses =
1269        existential_predicates.iter().map(|predicate| predicate.with_self_ty(tcx, erased_self_ty));
1270
1271    traits::elaborate(tcx, clauses)
1272        .filter_map(|clause| {
1273            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs:1273",
                        "rustc_trait_selection::traits::wf",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs"),
                        ::tracing_core::__macro_support::Option::Some(1273u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("clause")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("clause");
                                            NAME.as_str()
                                        }], ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&clause)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?clause);
1274            match clause.kind().skip_binder() {
1275                ty::ClauseKind::TypeOutlives(ty::OutlivesClause(ref t, ref r)) => {
1276                    // Search for a bound of the form `erased_self_ty
1277                    // : 'a`, but be wary of something like `for<'a>
1278                    // erased_self_ty : 'a` (we interpret a
1279                    // higher-ranked bound like that as 'static,
1280                    // though at present the code in `fulfill.rs`
1281                    // considers such bounds to be unsatisfiable, so
1282                    // it's kind of a moot point since you could never
1283                    // construct such an object, but this seems
1284                    // correct even if that code changes).
1285                    if t == &erased_self_ty && !r.has_escaping_bound_vars() {
1286                        Some(*r)
1287                    } else {
1288                        None
1289                    }
1290                }
1291                ty::ClauseKind::Trait(_)
1292                | ty::ClauseKind::HostEffect(..)
1293                | ty::ClauseKind::RegionOutlives(_)
1294                | ty::ClauseKind::Projection(_)
1295                | ty::ClauseKind::ConstArgHasType(_, _)
1296                | ty::ClauseKind::WellFormed(_)
1297                | ty::ClauseKind::UnstableFeature(_)
1298                | ty::ClauseKind::ConstEvaluatable(_) => None,
1299            }
1300        })
1301        .collect()
1302}