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