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