Skip to main content

rustc_trait_selection/traits/
wf.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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