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