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