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_def_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_def_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_def_id={1:?}) = {2:?}",
                                                    term, body_def_id, wf.out) as &dyn Value))])
            });
    } else { ; }
};debug!("wf::obligations({:?}, body_def_id={:?}) = {:?}", term, body_def_id, wf.out);
83
84    let result = wf.normalize(infcx);
85    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event 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_def_id={1:?}) ~~> {2:?}",
                                                    term, body_def_id, result) as &dyn Value))])
            });
    } else { ; }
};debug!("wf::obligations({:?}, body_def_id={:?}) ~~> {:?}", term, body_def_id, result);
86    Some(result)
87}
88
89/// Compute the predicates that are required for a type to be well-formed.
90///
91/// This is only intended to be used in the new solver, since it does not
92/// take into account recursion depth or proper error-reporting spans.
93pub fn unnormalized_obligations<'tcx>(
94    infcx: &InferCtxt<'tcx>,
95    param_env: ty::ParamEnv<'tcx>,
96    term: Term<'tcx>,
97    span: Span,
98    body_def_id: LocalDefId,
99) -> Option<PredicateObligations<'tcx>> {
100    if true {
    {
        match (&term, &infcx.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_def_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_def_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_def_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_def_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_def_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_def_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_def_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_def_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(
805                _,
806                ty::AliasTy {
807                    kind: ty::Projection { def_id } | ty::Opaque { def_id } | ty::Free { def_id },
808                    args,
809                    ..
810                },
811            ) => {
812                let obligations = self.nominal_obligations(def_id, args);
813                self.out.extend(obligations);
814            }
815            ty::Alias(_, data @ ty::AliasTy { kind: ty::Inherent { .. }, .. }) => {
816                self.add_wf_preds_for_inherent_projection(data.into());
817                return; // Subtree handled by compute_inherent_projection.
818            }
819
820            ty::Adt(def, args) => {
821                // WfNominalType
822                let obligations = self.nominal_obligations(def.did(), args);
823                self.out.extend(obligations);
824            }
825
826            ty::FnDef(did, args) => {
827                // HACK: Check the return type of function definitions for
828                // well-formedness to mostly fix #84533. This is still not
829                // perfect and there may be ways to abuse the fact that we
830                // ignore requirements with escaping bound vars. That's a
831                // more general issue however.
832                let fn_sig = tcx.fn_sig(did).instantiate(tcx, args).skip_norm_wip();
833                fn_sig.output().skip_binder().visit_with(self);
834
835                let obligations = self.nominal_obligations(did, args);
836                self.out.extend(obligations);
837            }
838
839            ty::Ref(r, rty, _) => {
840                // WfReference
841                if !r.has_escaping_bound_vars() && !rty.has_escaping_bound_vars() {
842                    let cause = self.cause(ObligationCauseCode::ReferenceOutlivesReferent(t));
843                    self.out.push(traits::Obligation::with_depth(
844                        tcx,
845                        cause,
846                        self.recursion_depth,
847                        self.param_env,
848                        ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(
849                            ty::OutlivesPredicate(rty, r),
850                        ))),
851                    ));
852                }
853            }
854
855            ty::Coroutine(did, args, ..) => {
856                // Walk ALL the types in the coroutine: this will
857                // include the upvar types as well as the yield
858                // type. Note that this is mildly distinct from
859                // the closure case, where we have to be careful
860                // about the signature of the closure. We don't
861                // have the problem of implied bounds here since
862                // coroutines don't take arguments.
863                let obligations = self.nominal_obligations(did, args);
864                self.out.extend(obligations);
865            }
866
867            ty::Closure(did, args) => {
868                // Note that we cannot skip the generic types
869                // types. Normally, within the fn
870                // body where they are created, the generics will
871                // always be WF, and outside of that fn body we
872                // are not directly inspecting closure types
873                // anyway, except via auto trait matching (which
874                // only inspects the upvar types).
875                // But when a closure is part of a type-alias-impl-trait
876                // then the function that created the defining site may
877                // have had more bounds available than the type alias
878                // specifies. This may cause us to have a closure in the
879                // hidden type that is not actually well formed and
880                // can cause compiler crashes when the user abuses unsafe
881                // code to procure such a closure.
882                // See tests/ui/type-alias-impl-trait/wf_check_closures.rs
883                let obligations = self.nominal_obligations(did, args);
884                self.out.extend(obligations);
885                // Only check the upvar types for WF, not the rest
886                // of the types within. This is needed because we
887                // capture the signature and it may not be WF
888                // without the implied bounds. Consider a closure
889                // like `|x: &'a T|` -- it may be that `T: 'a` is
890                // not known to hold in the creator's context (and
891                // indeed the closure may not be invoked by its
892                // creator, but rather turned to someone who *can*
893                // verify that).
894                //
895                // The special treatment of closures here really
896                // ought not to be necessary either; the problem
897                // is related to #25860 -- there is no way for us
898                // to express a fn type complete with the implied
899                // bounds that it is assuming. I think in reality
900                // the WF rules around fn are a bit messed up, and
901                // that is the rot problem: `fn(&'a T)` should
902                // probably always be WF, because it should be
903                // shorthand for something like `where(T: 'a) {
904                // fn(&'a T) }`, as discussed in #25860.
905                let upvars = args.as_closure().tupled_upvars_ty();
906                return upvars.visit_with(self);
907            }
908
909            ty::CoroutineClosure(did, args) => {
910                // See the above comments. The same apply to coroutine-closures.
911                let obligations = self.nominal_obligations(did, args);
912                self.out.extend(obligations);
913                let upvars = args.as_coroutine_closure().tupled_upvars_ty();
914                return upvars.visit_with(self);
915            }
916
917            ty::FnPtr(..) => {
918                // Let the visitor iterate into the argument/return
919                // types appearing in the fn signature.
920            }
921            ty::UnsafeBinder(ty) => {
922                // FIXME(unsafe_binders): For now, we have no way to express
923                // that a type must be `ManuallyDrop` OR `Copy` (or a pointer).
924                if !ty.has_escaping_bound_vars() {
925                    self.out.push(traits::Obligation::new(
926                        self.tcx(),
927                        self.cause(ObligationCauseCode::Misc),
928                        self.param_env,
929                        ty.map_bound(|ty| {
930                            ty::TraitRef::new(
931                                self.tcx(),
932                                self.tcx().require_lang_item(
933                                    LangItem::BikeshedGuaranteedNoDrop,
934                                    self.span,
935                                ),
936                                [ty],
937                            )
938                        }),
939                    ));
940                }
941
942                // We recurse into the binder below.
943            }
944
945            ty::Dynamic(data, r) => {
946                // WfObject
947                //
948                // Here, we defer WF checking due to higher-ranked
949                // regions. This is perhaps not ideal.
950                self.add_wf_preds_for_dyn_ty(t, data, r);
951
952                // FIXME(#27579) RFC also considers adding trait
953                // obligations that don't refer to Self and
954                // checking those
955                if let Some(principal) = data.principal() {
956                    let principal_def_id = principal.skip_binder().def_id;
957                    self.out.push(traits::Obligation::with_depth(
958                        tcx,
959                        self.cause(ObligationCauseCode::WellFormed(None)),
960                        self.recursion_depth,
961                        self.param_env,
962                        ty::Binder::dummy(ty::PredicateKind::DynCompatible(principal_def_id)),
963                    ));
964
965                    // For the most part we don't add wf predicates corresponding to
966                    // the trait ref's generic arguments which allows code like this
967                    // to compile:
968                    // ```rust
969                    // trait Trait<T: Sized> {}
970                    // fn foo(_: &dyn Trait<[u32]>) {}
971                    // ```
972                    //
973                    // However, we sometimes incidentally check that const arguments
974                    // have the correct type as a side effect of the anon const
975                    // desugaring. To make this "consistent" for users we explicitly
976                    // check `ConstArgHasType` clauses so that const args that don't
977                    // go through an anon const still have their types checked.
978                    //
979                    // See also: https://rustc-dev-guide.rust-lang.org/const-generics.html
980                    let args = principal.skip_binder().with_self_ty(self.tcx(), t).args;
981                    let obligations =
982                        self.nominal_obligations(principal_def_id, args).into_iter().filter(|o| {
983                            let kind = o.predicate.kind().skip_binder();
984                            match kind {
985                                ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(
986                                    ct,
987                                    _,
988                                )) if #[allow(non_exhaustive_omitted_patterns)] match ct.kind() {
    ty::ConstKind::Param(..) => true,
    _ => false,
}matches!(ct.kind(), ty::ConstKind::Param(..)) => {
989                                    // ConstArgHasType clauses are not higher kinded. Assert as
990                                    // such so we can fix this up if that ever changes.
991                                    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());
992                                    // In stable rust, variables from the trait object binder
993                                    // cannot be referenced by a ConstArgHasType clause. However,
994                                    // under `generic_const_parameter_types`, it can. Ignore those
995                                    // predicates for now, to not have HKT-ConstArgHasTypes.
996                                    !kind.has_escaping_bound_vars()
997                                }
998                                _ => false,
999                            }
1000                        });
1001                    self.out.extend(obligations);
1002                }
1003
1004                if !t.has_escaping_bound_vars() {
1005                    for projection in data.projection_bounds() {
1006                        let pred_binder = projection
1007                            .with_self_ty(tcx, t)
1008                            .map_bound(|p| {
1009                                p.term.as_const().map(|ct| {
1010                                    let assoc_const_ty = tcx
1011                                        .type_of(p.def_id())
1012                                        .instantiate(tcx, p.projection_term.args)
1013                                        .skip_norm_wip();
1014                                    ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(
1015                                        ct,
1016                                        assoc_const_ty,
1017                                    ))
1018                                })
1019                            })
1020                            .transpose();
1021                        if let Some(pred_binder) = pred_binder {
1022                            self.out.push(traits::Obligation::with_depth(
1023                                tcx,
1024                                self.cause(ObligationCauseCode::WellFormed(None)),
1025                                self.recursion_depth,
1026                                self.param_env,
1027                                pred_binder,
1028                            ));
1029                        }
1030                    }
1031                }
1032            }
1033
1034            // Inference variables are the complicated case, since we don't
1035            // know what type they are. We do two things:
1036            //
1037            // 1. Check if they have been resolved, and if so proceed with
1038            //    THAT type.
1039            // 2. If not, we've at least simplified things (e.g., we went
1040            //    from `Vec?0>: WF` to `?0: WF`), so we can
1041            //    register a pending obligation and keep
1042            //    moving. (Goal is that an "inductive hypothesis"
1043            //    is satisfied to ensure termination.)
1044            // See also the comment on `fn obligations`, describing cycle
1045            // prevention, which happens before this can be reached.
1046            ty::Infer(_) => {
1047                let cause = self.cause(ObligationCauseCode::WellFormed(None));
1048                self.out.push(traits::Obligation::with_depth(
1049                    tcx,
1050                    cause,
1051                    self.recursion_depth,
1052                    self.param_env,
1053                    ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(
1054                        t.into(),
1055                    ))),
1056                ));
1057            }
1058        }
1059
1060        t.super_visit_with(self)
1061    }
1062
1063    fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
1064        let tcx = self.tcx();
1065
1066        match c.kind() {
1067            ty::ConstKind::Alias(_, alias_const) => {
1068                if !c.has_escaping_bound_vars() {
1069                    // Skip type consts as mGCA doesn't support evaluatable clauses
1070                    if !alias_const.kind.is_type_const(tcx) && !tcx.features().generic_const_args()
1071                    {
1072                        let predicate = ty::Binder::dummy(ty::PredicateKind::Clause(
1073                            ty::ClauseKind::ConstEvaluatable(c),
1074                        ));
1075                        let cause = self.cause(ObligationCauseCode::WellFormed(None));
1076                        self.out.push(traits::Obligation::with_depth(
1077                            tcx,
1078                            cause,
1079                            self.recursion_depth,
1080                            self.param_env,
1081                            predicate,
1082                        ));
1083                    }
1084
1085                    match alias_const.kind {
1086                        ty::AliasConstKind::Inherent { .. } => {
1087                            self.add_wf_preds_for_inherent_projection(alias_const.into());
1088                            return; // Subtree is handled by above function
1089                        }
1090                        ty::AliasConstKind::Projection { def_id }
1091                        | ty::AliasConstKind::Free { def_id }
1092                        | ty::AliasConstKind::Anon { def_id } => {
1093                            let obligations = self.nominal_obligations(def_id, alias_const.args);
1094                            self.out.extend(obligations);
1095                        }
1096                    }
1097                }
1098            }
1099            ty::ConstKind::Infer(_) => {
1100                let cause = self.cause(ObligationCauseCode::WellFormed(None));
1101
1102                self.out.push(traits::Obligation::with_depth(
1103                    tcx,
1104                    cause,
1105                    self.recursion_depth,
1106                    self.param_env,
1107                    ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(
1108                        c.into(),
1109                    ))),
1110                ));
1111            }
1112            ty::ConstKind::Expr(_) => {
1113                // FIXME(generic_const_exprs): this doesn't verify that given `Expr(N + 1)` the
1114                // trait bound `typeof(N): Add<typeof(1)>` holds. This is currently unnecessary
1115                // as `ConstKind::Expr` is only produced via normalization of `ConstKind::Alias`
1116                // which means that the `DefId` would have been typeck'd elsewhere. However in
1117                // the future we may allow directly lowering to `ConstKind::Expr` in which case
1118                // we would not be proving bounds we should.
1119
1120                let predicate = ty::Binder::dummy(ty::PredicateKind::Clause(
1121                    ty::ClauseKind::ConstEvaluatable(c),
1122                ));
1123                let cause = self.cause(ObligationCauseCode::WellFormed(None));
1124                self.out.push(traits::Obligation::with_depth(
1125                    tcx,
1126                    cause,
1127                    self.recursion_depth,
1128                    self.param_env,
1129                    predicate,
1130                ));
1131            }
1132
1133            ty::ConstKind::Error(_)
1134            | ty::ConstKind::Param(_)
1135            | ty::ConstKind::Bound(..)
1136            | ty::ConstKind::Placeholder(..) => {
1137                // These variants are trivially WF, so nothing to do here.
1138            }
1139            ty::ConstKind::Value(val) => {
1140                // FIXME(mgca): no need to feature-gate once valtree lifetimes are not erased
1141                if tcx.features().min_generic_const_args() {
1142                    match val.ty.kind() {
1143                        ty::Adt(adt_def, args) => {
1144                            let adt_val = val.destructure_adt_const();
1145                            let variant_def = adt_def.variant(adt_val.variant);
1146                            let cause = self.cause(ObligationCauseCode::WellFormed(None));
1147                            self.out.extend(variant_def.fields.iter().zip(adt_val.fields).map(
1148                                |(field_def, &field_val)| {
1149                                    let field_ty = tcx
1150                                        .type_of(field_def.did)
1151                                        .instantiate(tcx, args)
1152                                        .skip_norm_wip();
1153                                    let predicate = ty::PredicateKind::Clause(
1154                                        ty::ClauseKind::ConstArgHasType(field_val, field_ty),
1155                                    );
1156                                    traits::Obligation::with_depth(
1157                                        tcx,
1158                                        cause.clone(),
1159                                        self.recursion_depth,
1160                                        self.param_env,
1161                                        predicate,
1162                                    )
1163                                },
1164                            ));
1165                        }
1166                        ty::Tuple(field_tys) => {
1167                            let field_vals = val.to_branch();
1168                            let cause = self.cause(ObligationCauseCode::WellFormed(None));
1169                            self.out.extend(field_tys.iter().zip(field_vals).map(
1170                                |(field_ty, &field_val)| {
1171                                    let predicate = ty::PredicateKind::Clause(
1172                                        ty::ClauseKind::ConstArgHasType(field_val, field_ty),
1173                                    );
1174                                    traits::Obligation::with_depth(
1175                                        tcx,
1176                                        cause.clone(),
1177                                        self.recursion_depth,
1178                                        self.param_env,
1179                                        predicate,
1180                                    )
1181                                },
1182                            ));
1183                        }
1184                        ty::Array(elem_ty, _len) => {
1185                            let elem_vals = val.to_branch();
1186                            let cause = self.cause(ObligationCauseCode::WellFormed(None));
1187
1188                            self.out.extend(elem_vals.iter().map(|&elem_val| {
1189                                let predicate = ty::PredicateKind::Clause(
1190                                    ty::ClauseKind::ConstArgHasType(elem_val, *elem_ty),
1191                                );
1192                                traits::Obligation::with_depth(
1193                                    tcx,
1194                                    cause.clone(),
1195                                    self.recursion_depth,
1196                                    self.param_env,
1197                                    predicate,
1198                                )
1199                            }));
1200                        }
1201                        _ => {}
1202                    }
1203                }
1204
1205                // FIXME: Enforce that values are structurally-matchable.
1206            }
1207        }
1208
1209        c.super_visit_with(self)
1210    }
1211
1212    fn visit_predicate(&mut self, _p: ty::Predicate<'tcx>) -> Self::Result {
1213        ::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");
1214    }
1215}
1216
1217/// Given an object type like `SomeTrait + Send`, computes the lifetime
1218/// bounds that must hold on the elided self type. These are derived
1219/// from the declarations of `SomeTrait`, `Send`, and friends -- if
1220/// they declare `trait SomeTrait : 'static`, for example, then
1221/// `'static` would appear in the list.
1222///
1223/// N.B., in some cases, particularly around higher-ranked bounds,
1224/// this function returns a kind of conservative approximation.
1225/// That is, all regions returned by this function are definitely
1226/// required, but there may be other region bounds that are not
1227/// returned, as well as requirements like `for<'a> T: 'a`.
1228///
1229/// Requires that trait definitions have been processed so that we can
1230/// elaborate predicates and walk supertraits.
1231pub fn object_region_bounds<'tcx>(
1232    tcx: TyCtxt<'tcx>,
1233    existential_predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
1234) -> Vec<ty::Region<'tcx>> {
1235    let erased_self_ty = tcx.types.trait_object_dummy_self;
1236
1237    let predicates =
1238        existential_predicates.iter().map(|predicate| predicate.with_self_ty(tcx, erased_self_ty));
1239
1240    traits::elaborate(tcx, predicates)
1241        .filter_map(|pred| {
1242            {
    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:1242",
                        "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(1242u32),
                        ::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);
1243            match pred.kind().skip_binder() {
1244                ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ref t, ref r)) => {
1245                    // Search for a bound of the form `erased_self_ty
1246                    // : 'a`, but be wary of something like `for<'a>
1247                    // erased_self_ty : 'a` (we interpret a
1248                    // higher-ranked bound like that as 'static,
1249                    // though at present the code in `fulfill.rs`
1250                    // considers such bounds to be unsatisfiable, so
1251                    // it's kind of a moot point since you could never
1252                    // construct such an object, but this seems
1253                    // correct even if that code changes).
1254                    if t == &erased_self_ty && !r.has_escaping_bound_vars() {
1255                        Some(*r)
1256                    } else {
1257                        None
1258                    }
1259                }
1260                ty::ClauseKind::Trait(_)
1261                | ty::ClauseKind::HostEffect(..)
1262                | ty::ClauseKind::RegionOutlives(_)
1263                | ty::ClauseKind::Projection(_)
1264                | ty::ClauseKind::ConstArgHasType(_, _)
1265                | ty::ClauseKind::WellFormed(_)
1266                | ty::ClauseKind::UnstableFeature(_)
1267                | ty::ClauseKind::ConstEvaluatable(_) => None,
1268            }
1269        })
1270        .collect()
1271}