Skip to main content

rustc_hir_analysis/collect/
predicates_of.rs

1use std::assert_matches;
2
3use hir::Node;
4use rustc_data_structures::fx::FxIndexSet;
5use rustc_hir as hir;
6use rustc_hir::def::DefKind;
7use rustc_hir::def_id::{DefId, LocalDefId};
8use rustc_hir::find_attr;
9use rustc_middle::ty::{
10    self, GenericPredicates, ImplTraitInTraitData, Ty, TyCtxt, TypeVisitable, TypeVisitor, Upcast,
11};
12use rustc_middle::{bug, span_bug};
13use rustc_span::{DUMMY_SP, Ident, Span};
14use tracing::{debug, instrument, trace};
15
16use super::item_bounds::explicit_item_bounds_with_filter;
17use crate::collect::ItemCtxt;
18use crate::constrained_generic_params as cgp;
19use crate::delegation::inherit_predicates_for_delegation_item;
20use crate::hir_ty_lowering::{
21    HirTyLowerer, ImpliedBoundsContext, OverlappingAsssocItemConstraints, PredicateFilter,
22    RegionInferReason,
23};
24
25/// Returns a list of all type predicates (explicit and implicit) for the definition with
26/// ID `def_id`. This includes all predicates returned by `explicit_predicates_of`, plus
27/// inferred constraints concerning which regions outlive other regions.
28#[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("predicates_of",
                                    "rustc_hir_analysis::collect::predicates_of",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/collect/predicates_of.rs"),
                                    ::tracing_core::__macro_support::Option::Some(28u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::predicates_of"),
                                    ::tracing_core::field::FieldSet::new(&["def_id"],
                                        ::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))])
                            })
                } 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: ty::GenericPredicates<'_> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let mut result = tcx.explicit_predicates_of(def_id);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/collect/predicates_of.rs:31",
                                    "rustc_hir_analysis::collect::predicates_of",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/collect/predicates_of.rs"),
                                    ::tracing_core::__macro_support::Option::Some(31u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::predicates_of"),
                                    ::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!("predicates_of: explicit_predicates_of({0:?}) = {1:?}",
                                                                def_id, result) as &dyn Value))])
                        });
                } else { ; }
            };
            let inferred_outlives = tcx.inferred_outlives_of(def_id);
            if !inferred_outlives.is_empty() {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/collect/predicates_of.rs:35",
                                        "rustc_hir_analysis::collect::predicates_of",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/collect/predicates_of.rs"),
                                        ::tracing_core::__macro_support::Option::Some(35u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::predicates_of"),
                                        ::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!("predicates_of: inferred_outlives_of({0:?}) = {1:?}",
                                                                    def_id, inferred_outlives) as &dyn Value))])
                            });
                    } else { ; }
                };
                let inferred_outlives_iter =
                    inferred_outlives.iter().map(|(clause, span)|
                            ((*clause).upcast(tcx), *span));
                if result.predicates.is_empty() {
                    result.predicates =
                        tcx.arena.alloc_from_iter(inferred_outlives_iter);
                } else {
                    result.predicates =
                        tcx.arena.alloc_from_iter(result.predicates.into_iter().copied().chain(inferred_outlives_iter));
                }
            }
            if tcx.is_trait(def_id) {
                let span = DUMMY_SP;
                result.predicates =
                    tcx.arena.alloc_from_iter(result.predicates.iter().copied().chain(std::iter::once((ty::TraitRef::identity(tcx,
                                            def_id).upcast(tcx), span))));
            }
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/collect/predicates_of.rs:76",
                                    "rustc_hir_analysis::collect::predicates_of",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/collect/predicates_of.rs"),
                                    ::tracing_core::__macro_support::Option::Some(76u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::predicates_of"),
                                    ::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!("predicates_of({0:?}) = {1:?}",
                                                                def_id, result) as &dyn Value))])
                        });
                } else { ; }
            };
            result
        }
    }
}#[instrument(level = "debug", skip(tcx))]
29pub(super) fn predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
30    let mut result = tcx.explicit_predicates_of(def_id);
31    debug!("predicates_of: explicit_predicates_of({:?}) = {:?}", def_id, result);
32
33    let inferred_outlives = tcx.inferred_outlives_of(def_id);
34    if !inferred_outlives.is_empty() {
35        debug!("predicates_of: inferred_outlives_of({:?}) = {:?}", def_id, inferred_outlives,);
36        let inferred_outlives_iter =
37            inferred_outlives.iter().map(|(clause, span)| ((*clause).upcast(tcx), *span));
38        if result.predicates.is_empty() {
39            result.predicates = tcx.arena.alloc_from_iter(inferred_outlives_iter);
40        } else {
41            result.predicates = tcx.arena.alloc_from_iter(
42                result.predicates.into_iter().copied().chain(inferred_outlives_iter),
43            );
44        }
45    }
46
47    if tcx.is_trait(def_id) {
48        // For traits, add `Self: Trait` predicate. This is
49        // not part of the predicates that a user writes, but it
50        // is something that one must prove in order to invoke a
51        // method or project an associated type.
52        //
53        // In the chalk setup, this predicate is not part of the
54        // "predicates" for a trait item. But it is useful in
55        // rustc because if you directly (e.g.) invoke a trait
56        // method like `Trait::method(...)`, you must naturally
57        // prove that the trait applies to the types that were
58        // used, and adding the predicate into this list ensures
59        // that this is done.
60        //
61        // We use a DUMMY_SP here as a way to signal trait bounds that come
62        // from the trait itself that *shouldn't* be shown as the source of
63        // an obligation and instead be skipped. Otherwise we'd use
64        // `tcx.def_span(def_id);`
65        let span = DUMMY_SP;
66
67        result.predicates = tcx.arena.alloc_from_iter(
68            result
69                .predicates
70                .iter()
71                .copied()
72                .chain(std::iter::once((ty::TraitRef::identity(tcx, def_id).upcast(tcx), span))),
73        );
74    }
75
76    debug!("predicates_of({:?}) = {:?}", def_id, result);
77    result
78}
79
80/// Returns a list of user-specified type predicates for the definition with ID `def_id`.
81/// N.B., this does not include any implied/inferred constraints.
82x;#[instrument(level = "trace", skip(tcx), ret)]
83fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::GenericPredicates<'_> {
84    use rustc_hir::*;
85
86    match tcx.opt_rpitit_info(def_id.to_def_id()) {
87        Some(ImplTraitInTraitData::Trait { fn_def_id, .. }) => {
88            let mut predicates = Vec::new();
89
90            // RPITITs should inherit the predicates of their parent. This is
91            // both to ensure that the RPITITs are only instantiated when the
92            // parent predicates would hold, and also so that the param-env
93            // inherits these predicates as assumptions.
94            let identity_args = ty::GenericArgs::identity_for_item(tcx, def_id);
95            predicates
96                .extend(tcx.explicit_predicates_of(fn_def_id).instantiate_own(tcx, identity_args));
97
98            // We also install bidirectional outlives predicates for the RPITIT
99            // to keep the duplicates lifetimes from opaque lowering in sync.
100            // We only need to compute bidirectional outlives for the duplicated
101            // opaque lifetimes, which explains the slicing below.
102            compute_bidirectional_outlives_predicates(
103                tcx,
104                &tcx.generics_of(def_id.to_def_id()).own_params
105                    [tcx.generics_of(fn_def_id).own_params.len()..],
106                &mut predicates,
107            );
108
109            return ty::GenericPredicates {
110                parent: Some(tcx.parent(def_id.to_def_id())),
111                predicates: tcx.arena.alloc_from_iter(predicates),
112            };
113        }
114
115        Some(ImplTraitInTraitData::Impl { fn_def_id }) => {
116            let trait_item_def_id = tcx.trait_item_of(def_id).unwrap();
117            let trait_assoc_predicates = tcx.explicit_predicates_of(trait_item_def_id);
118
119            let impl_assoc_identity_args = ty::GenericArgs::identity_for_item(tcx, def_id);
120            let impl_def_id = tcx.parent(fn_def_id);
121            let impl_trait_ref_args = tcx.impl_trait_ref(impl_def_id).instantiate_identity().args;
122
123            let impl_assoc_args =
124                impl_assoc_identity_args.rebase_onto(tcx, impl_def_id, impl_trait_ref_args);
125
126            let impl_predicates = trait_assoc_predicates.instantiate_own(tcx, impl_assoc_args);
127
128            return ty::GenericPredicates {
129                parent: Some(impl_def_id),
130                predicates: tcx.arena.alloc_from_iter(impl_predicates),
131            };
132        }
133
134        None => {}
135    }
136
137    let hir_id = tcx.local_def_id_to_hir_id(def_id);
138    let node = tcx.hir_node(hir_id);
139
140    if let Some(sig) = node.fn_sig()
141        && let Some(sig_id) = sig.decl.opt_delegation_sig_id()
142    {
143        return inherit_predicates_for_delegation_item(tcx, def_id, sig_id);
144    }
145
146    let mut is_trait = None;
147    let mut is_default_impl_trait = None;
148
149    let icx = ItemCtxt::new(tcx, def_id);
150
151    const NO_GENERICS: &hir::Generics<'_> = hir::Generics::empty();
152
153    // We use an `IndexSet` to preserve order of insertion.
154    // Preserving the order of insertion is important here so as not to break UI tests.
155    let mut predicates: FxIndexSet<(ty::Clause<'_>, Span)> = FxIndexSet::default();
156
157    let hir_generics = node.generics().unwrap_or(NO_GENERICS);
158    if let Node::Item(item) = node {
159        match item.kind {
160            ItemKind::Impl(impl_) => {
161                if let Some(of_trait) = impl_.of_trait
162                    && of_trait.defaultness.is_default()
163                {
164                    is_default_impl_trait =
165                        Some(ty::Binder::dummy(tcx.impl_trait_ref(def_id).instantiate_identity()));
166                }
167            }
168            ItemKind::Trait(_, _, _, _, _, self_bounds, ..)
169            | ItemKind::TraitAlias(_, _, _, self_bounds) => {
170                is_trait = Some((self_bounds, item.span));
171            }
172            _ => {}
173        }
174    };
175
176    let generics = tcx.generics_of(def_id);
177
178    // Below we'll consider the bounds on the type parameters (including `Self`)
179    // and the explicit where-clauses, but to get the full set of predicates
180    // on a trait we must also consider the bounds that follow the trait's name,
181    // like `trait Foo: A + B + C`.
182    if let Some((self_bounds, span)) = is_trait {
183        let mut bounds = Vec::new();
184        icx.lowerer().lower_bounds(
185            tcx.types.self_param,
186            self_bounds,
187            &mut bounds,
188            ty::List::empty(),
189            PredicateFilter::All,
190            OverlappingAsssocItemConstraints::Allowed,
191        );
192        icx.lowerer().add_implicit_sizedness_bounds(
193            &mut bounds,
194            tcx.types.self_param,
195            self_bounds,
196            ImpliedBoundsContext::TraitDef(def_id),
197            span,
198        );
199        icx.lowerer().add_default_traits(
200            &mut bounds,
201            tcx.types.self_param,
202            self_bounds,
203            ImpliedBoundsContext::TraitDef(def_id),
204            span,
205        );
206        predicates.extend(bounds);
207    }
208
209    // In default impls, we can assume that the self type implements
210    // the trait. So in:
211    //
212    //     default impl Foo for Bar { .. }
213    //
214    // we add a default where clause `Bar: Foo`. We do a similar thing for traits
215    // (see below). Recall that a default impl is not itself an impl, but rather a
216    // set of defaults that can be incorporated into another impl.
217    if let Some(trait_ref) = is_default_impl_trait {
218        predicates.insert((trait_ref.upcast(tcx), tcx.def_span(def_id)));
219    }
220
221    // Add implicit predicates that should be treated as if the user has written them,
222    // including the implicit `T: Sized` for all generic parameters, and `ConstArgHasType`
223    // for const params.
224    for param in hir_generics.params {
225        match param.kind {
226            GenericParamKind::Lifetime { .. } => (),
227            GenericParamKind::Type { .. } => {
228                let param_ty = icx.lowerer().lower_ty_param(param.hir_id);
229                let mut bounds = Vec::new();
230                // Implicit bounds are added to type params unless a `?Trait` bound is found
231                icx.lowerer().add_implicit_sizedness_bounds(
232                    &mut bounds,
233                    param_ty,
234                    &[],
235                    ImpliedBoundsContext::TyParam(param.def_id, hir_generics.predicates),
236                    param.span,
237                );
238                icx.lowerer().add_default_traits(
239                    &mut bounds,
240                    param_ty,
241                    &[],
242                    ImpliedBoundsContext::TyParam(param.def_id, hir_generics.predicates),
243                    param.span,
244                );
245                trace!(?bounds);
246                predicates.extend(bounds);
247                trace!(?predicates);
248            }
249            hir::GenericParamKind::Const { .. } => {
250                let param_def_id = param.def_id.to_def_id();
251                let ct_ty = tcx.type_of(param_def_id).instantiate_identity();
252                let ct = icx.lowerer().lower_const_param(param_def_id, param.hir_id);
253                predicates
254                    .insert((ty::ClauseKind::ConstArgHasType(ct, ct_ty).upcast(tcx), param.span));
255            }
256        }
257    }
258
259    trace!(?predicates);
260    // Add inline `<T: Foo>` bounds and bounds in the where clause.
261    for predicate in hir_generics.predicates {
262        match predicate.kind {
263            hir::WherePredicateKind::BoundPredicate(bound_pred) => {
264                let ty = icx.lowerer().lower_ty_maybe_return_type_notation(bound_pred.bounded_ty);
265                let bound_vars = tcx.late_bound_vars(predicate.hir_id);
266
267                // This is a `where Ty:` (sic!).
268                if bound_pred.bounds.is_empty() {
269                    if let ty::Param(_) = ty.kind() {
270                        // We can skip the predicate because type parameters are trivially WF.
271                    } else {
272                        // Keep the type around in a dummy predicate. That way, it's not a complete
273                        // noop (see #53696) and `Ty` is still checked for WF.
274
275                        let span = bound_pred.bounded_ty.span;
276                        let predicate = ty::Binder::bind_with_vars(
277                            ty::ClauseKind::WellFormed(ty.into()),
278                            bound_vars,
279                        );
280                        predicates.insert((predicate.upcast(tcx), span));
281                    }
282                }
283
284                let mut bounds = Vec::new();
285                icx.lowerer().lower_bounds(
286                    ty,
287                    bound_pred.bounds,
288                    &mut bounds,
289                    bound_vars,
290                    PredicateFilter::All,
291                    OverlappingAsssocItemConstraints::Allowed,
292                );
293                predicates.extend(bounds);
294            }
295
296            hir::WherePredicateKind::RegionPredicate(region_pred) => {
297                let r1 = icx
298                    .lowerer()
299                    .lower_lifetime(region_pred.lifetime, RegionInferReason::RegionPredicate);
300                predicates.extend(region_pred.bounds.iter().map(|bound| {
301                    let (r2, span) = match bound {
302                        hir::GenericBound::Outlives(lt) => (
303                            icx.lowerer().lower_lifetime(lt, RegionInferReason::RegionPredicate),
304                            lt.ident.span,
305                        ),
306                        bound => {
307                            span_bug!(
308                                bound.span(),
309                                "lifetime param bounds must be outlives, but found {bound:?}"
310                            )
311                        }
312                    };
313                    let pred =
314                        ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(r1, r2)).upcast(tcx);
315                    (pred, span)
316                }))
317            }
318
319            hir::WherePredicateKind::EqPredicate(..) => {
320                // FIXME(#20041)
321            }
322        }
323    }
324
325    if tcx.features().generic_const_exprs() {
326        predicates.extend(const_evaluatable_predicates_of(tcx, def_id, &predicates));
327    }
328
329    let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(def_id));
330    // FIXME(staged_api): We might want to look at the normal stability attributes too but
331    // first we would need a way to let std/core use APIs with unstable feature bounds from
332    // within stable APIs.
333    let allow_unstable_feature_attr =
334        find_attr!(attrs, UnstableFeatureBound(i) => i).map(|i| i.as_slice()).unwrap_or_default();
335
336    for (feat_name, span) in allow_unstable_feature_attr {
337        predicates.insert((ty::ClauseKind::UnstableFeature(*feat_name).upcast(tcx), *span));
338    }
339
340    let mut predicates: Vec<_> = predicates.into_iter().collect();
341
342    // Subtle: before we store the predicates into the tcx, we
343    // sort them so that predicates like `T: Foo<Item=U>` come
344    // before uses of `U`. This avoids false ambiguity errors
345    // in trait checking. See `setup_constraining_predicates`
346    // for details.
347    if let Node::Item(&Item { kind: ItemKind::Impl(impl_), .. }) = node {
348        let self_ty = tcx.type_of(def_id).instantiate_identity();
349        let trait_ref =
350            impl_.of_trait.is_some().then(|| tcx.impl_trait_ref(def_id).instantiate_identity());
351        cgp::setup_constraining_predicates(
352            tcx,
353            &mut predicates,
354            trait_ref,
355            &mut cgp::parameters_for_impl(tcx, self_ty, trait_ref),
356        );
357    }
358
359    // Opaque types duplicate some of their generic parameters.
360    // We create bi-directional Outlives predicates between the original
361    // and the duplicated parameter, to ensure that they do not get out of sync.
362    if let Node::OpaqueTy(..) = node {
363        compute_bidirectional_outlives_predicates(tcx, &generics.own_params, &mut predicates);
364        debug!(?predicates);
365    }
366
367    ty::GenericPredicates {
368        parent: generics.parent,
369        predicates: tcx.arena.alloc_from_iter(predicates),
370    }
371}
372
373/// Opaques have duplicated lifetimes and we need to compute bidirectional outlives predicates to
374/// enforce that these lifetimes stay in sync.
375fn compute_bidirectional_outlives_predicates<'tcx>(
376    tcx: TyCtxt<'tcx>,
377    opaque_own_params: &[ty::GenericParamDef],
378    predicates: &mut Vec<(ty::Clause<'tcx>, Span)>,
379) {
380    for param in opaque_own_params {
381        let orig_lifetime = tcx.map_opaque_lifetime_to_parent_lifetime(param.def_id.expect_local());
382        if let ty::ReEarlyParam(..) = orig_lifetime.kind() {
383            let dup_lifetime = ty::Region::new_early_param(
384                tcx,
385                ty::EarlyParamRegion { index: param.index, name: param.name },
386            );
387            let span = tcx.def_span(param.def_id);
388            predicates.push((
389                ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(orig_lifetime, dup_lifetime))
390                    .upcast(tcx),
391                span,
392            ));
393            predicates.push((
394                ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(dup_lifetime, orig_lifetime))
395                    .upcast(tcx),
396                span,
397            ));
398        }
399    }
400}
401
402x;#[instrument(level = "debug", skip(tcx, predicates), ret)]
403fn const_evaluatable_predicates_of<'tcx>(
404    tcx: TyCtxt<'tcx>,
405    def_id: LocalDefId,
406    predicates: &FxIndexSet<(ty::Clause<'tcx>, Span)>,
407) -> FxIndexSet<(ty::Clause<'tcx>, Span)> {
408    struct ConstCollector<'tcx> {
409        tcx: TyCtxt<'tcx>,
410        preds: FxIndexSet<(ty::Clause<'tcx>, Span)>,
411    }
412
413    fn is_const_param_default(tcx: TyCtxt<'_>, def: LocalDefId) -> bool {
414        let hir_id = tcx.local_def_id_to_hir_id(def);
415        let (_, parent_node) = tcx
416            .hir_parent_iter(hir_id)
417            .skip_while(|(_, n)| matches!(n, Node::ConstArg(..)))
418            .next()
419            .unwrap();
420        matches!(
421            parent_node,
422            Node::GenericParam(hir::GenericParam { kind: hir::GenericParamKind::Const { .. }, .. })
423        )
424    }
425
426    impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ConstCollector<'tcx> {
427        fn visit_const(&mut self, c: ty::Const<'tcx>) {
428            if let ty::ConstKind::Unevaluated(uv) = c.kind() {
429                if let Some(local) = uv.def.as_local()
430                    && is_const_param_default(self.tcx, local)
431                {
432                    // Do not look into const param defaults,
433                    // these get checked when they are actually instantiated.
434                    //
435                    // We do not want the following to error:
436                    //
437                    //     struct Foo<const N: usize, const M: usize = { N + 1 }>;
438                    //     struct Bar<const N: usize>(Foo<N, 3>);
439                    return;
440                }
441
442                // Skip type consts as mGCA doesn't support evaluatable clauses.
443                if self.tcx.is_type_const(uv.def) {
444                    return;
445                }
446
447                let span = self.tcx.def_span(uv.def);
448                self.preds.insert((ty::ClauseKind::ConstEvaluatable(c).upcast(self.tcx), span));
449            }
450        }
451    }
452
453    let hir_id = tcx.local_def_id_to_hir_id(def_id);
454    let node = tcx.hir_node(hir_id);
455
456    let mut collector = ConstCollector { tcx, preds: FxIndexSet::default() };
457
458    for (clause, _sp) in predicates {
459        clause.visit_with(&mut collector);
460    }
461
462    if let hir::Node::Item(item) = node
463        && let hir::ItemKind::Impl(impl_) = item.kind
464    {
465        if impl_.of_trait.is_some() {
466            debug!("visit impl trait_ref");
467            let trait_ref = tcx.impl_trait_ref(def_id);
468            trait_ref.instantiate_identity().visit_with(&mut collector);
469        }
470
471        debug!("visit self_ty");
472        let self_ty = tcx.type_of(def_id);
473        self_ty.instantiate_identity().visit_with(&mut collector);
474    }
475
476    if let Some(_) = tcx.hir_fn_sig_by_hir_id(hir_id) {
477        debug!("visit fn sig");
478        let fn_sig = tcx.fn_sig(def_id);
479        let fn_sig = fn_sig.instantiate_identity();
480        debug!(?fn_sig);
481        fn_sig.visit_with(&mut collector);
482    }
483
484    collector.preds
485}
486
487pub(super) fn trait_explicit_predicates_and_bounds(
488    tcx: TyCtxt<'_>,
489    def_id: LocalDefId,
490) -> ty::GenericPredicates<'_> {
491    match (&tcx.def_kind(def_id), &DefKind::Trait) {
    (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);
        }
    }
};assert_eq!(tcx.def_kind(def_id), DefKind::Trait);
492    gather_explicit_predicates_of(tcx, def_id)
493}
494
495pub(super) fn explicit_predicates_of<'tcx>(
496    tcx: TyCtxt<'tcx>,
497    def_id: LocalDefId,
498) -> ty::GenericPredicates<'tcx> {
499    let def_kind = tcx.def_kind(def_id);
500    if let DefKind::Trait = def_kind {
501        // Remove bounds on associated types from the predicates, they will be
502        // returned by `explicit_item_bounds`.
503        let predicates_and_bounds = tcx.trait_explicit_predicates_and_bounds(def_id);
504        let trait_identity_args = ty::GenericArgs::identity_for_item(tcx, def_id);
505
506        let is_assoc_item_ty = |ty: Ty<'tcx>| {
507            // For a predicate from a where clause to become a bound on an
508            // associated type:
509            // * It must use the identity args of the item.
510            //   * We're in the scope of the trait, so we can't name any
511            //     parameters of the GAT. That means that all we need to
512            //     check are that the args of the projection are the
513            //     identity args of the trait.
514            // * It must be an associated type for this trait (*not* a
515            //   supertrait).
516            if let ty::Alias(ty::Projection, projection) = ty.kind() {
517                projection.args == trait_identity_args
518                    // FIXME(return_type_notation): This check should be more robust
519                    && !tcx.is_impl_trait_in_trait(projection.def_id)
520                    && tcx.parent(projection.def_id) == def_id.to_def_id()
521            } else {
522                false
523            }
524        };
525
526        let predicates: Vec<_> = predicates_and_bounds
527            .predicates
528            .iter()
529            .copied()
530            .filter(|(pred, _)| match pred.kind().skip_binder() {
531                ty::ClauseKind::Trait(tr) => !is_assoc_item_ty(tr.self_ty()),
532                ty::ClauseKind::Projection(proj) => {
533                    !is_assoc_item_ty(proj.projection_term.self_ty())
534                }
535                ty::ClauseKind::TypeOutlives(outlives) => !is_assoc_item_ty(outlives.0),
536                _ => true,
537            })
538            .collect();
539        if predicates.len() == predicates_and_bounds.predicates.len() {
540            predicates_and_bounds
541        } else {
542            ty::GenericPredicates {
543                parent: predicates_and_bounds.parent,
544                predicates: tcx.arena.alloc_slice(&predicates),
545            }
546        }
547    } else {
548        if def_kind == DefKind::AnonConst
549            && tcx.features().generic_const_exprs()
550            && let Some(defaulted_param_def_id) =
551                tcx.hir_opt_const_param_default_param_def_id(tcx.local_def_id_to_hir_id(def_id))
552        {
553            // In `generics_of` we set the generics' parent to be our parent's parent which means that
554            // we lose out on the predicates of our actual parent if we dont return those predicates here.
555            // (See comment in `generics_of` for more information on why the parent shenanigans is necessary)
556            //
557            // struct Foo<T, const N: usize = { <T as Trait>::ASSOC }>(T) where T: Trait;
558            //        ^^^                     ^^^^^^^^^^^^^^^^^^^^^^^ the def id we are calling
559            //        ^^^                                             explicit_predicates_of on
560            //        parent item we dont have set as the
561            //        parent of generics returned by `generics_of`
562            //
563            // In the above code we want the anon const to have predicates in its param env for `T: Trait`
564            // and we would be calling `explicit_predicates_of(Foo)` here
565            let parent_def_id = tcx.local_parent(def_id);
566            let parent_preds = tcx.explicit_predicates_of(parent_def_id);
567
568            // If we dont filter out `ConstArgHasType` predicates then every single defaulted const parameter
569            // will ICE because of #106994. FIXME(generic_const_exprs): remove this when a more general solution
570            // to #106994 is implemented.
571            let filtered_predicates = parent_preds
572                .predicates
573                .into_iter()
574                .filter(|(pred, _)| {
575                    if let ty::ClauseKind::ConstArgHasType(ct, _) = pred.kind().skip_binder() {
576                        match ct.kind() {
577                            ty::ConstKind::Param(param_const) => {
578                                let defaulted_param_idx = tcx
579                                    .generics_of(parent_def_id)
580                                    .param_def_id_to_index[&defaulted_param_def_id.to_def_id()];
581                                param_const.index < defaulted_param_idx
582                            }
583                            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("`ConstArgHasType` in `predicates_of`that isn\'t a `Param` const"))bug!(
584                                "`ConstArgHasType` in `predicates_of`\
585                                 that isn't a `Param` const"
586                            ),
587                        }
588                    } else {
589                        true
590                    }
591                })
592                .cloned();
593            return GenericPredicates {
594                parent: parent_preds.parent,
595                predicates: { tcx.arena.alloc_from_iter(filtered_predicates) },
596            };
597        }
598        gather_explicit_predicates_of(tcx, def_id)
599    }
600}
601
602/// Ensures that the super-predicates of the trait with a `DefId`
603/// of `trait_def_id` are lowered and stored. This also ensures that
604/// the transitive super-predicates are lowered.
605pub(super) fn explicit_super_predicates_of<'tcx>(
606    tcx: TyCtxt<'tcx>,
607    trait_def_id: LocalDefId,
608) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]> {
609    implied_predicates_with_filter(tcx, trait_def_id.to_def_id(), PredicateFilter::SelfOnly)
610}
611
612pub(super) fn explicit_supertraits_containing_assoc_item<'tcx>(
613    tcx: TyCtxt<'tcx>,
614    (trait_def_id, assoc_ident): (DefId, Ident),
615) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]> {
616    implied_predicates_with_filter(
617        tcx,
618        trait_def_id,
619        PredicateFilter::SelfTraitThatDefines(assoc_ident),
620    )
621}
622
623pub(super) fn explicit_implied_predicates_of<'tcx>(
624    tcx: TyCtxt<'tcx>,
625    trait_def_id: LocalDefId,
626) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]> {
627    implied_predicates_with_filter(
628        tcx,
629        trait_def_id.to_def_id(),
630        if tcx.is_trait_alias(trait_def_id.to_def_id()) {
631            PredicateFilter::All
632        } else {
633            PredicateFilter::SelfAndAssociatedTypeBounds
634        },
635    )
636}
637
638/// Ensures that the super-predicates of the trait with a `DefId`
639/// of `trait_def_id` are lowered and stored. This also ensures that
640/// the transitive super-predicates are lowered.
641pub(super) fn implied_predicates_with_filter<'tcx>(
642    tcx: TyCtxt<'tcx>,
643    trait_def_id: DefId,
644    filter: PredicateFilter,
645) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]> {
646    let Some(trait_def_id) = trait_def_id.as_local() else {
647        // if `assoc_ident` is None, then the query should've been redirected to an
648        // external provider
649        match filter {
    PredicateFilter::SelfTraitThatDefines(_) => {}
    ref left_val => {
        ::core::panicking::assert_matches_failed(left_val,
            "PredicateFilter::SelfTraitThatDefines(_)",
            ::core::option::Option::None);
    }
};assert_matches!(filter, PredicateFilter::SelfTraitThatDefines(_));
650        return tcx.explicit_super_predicates_of(trait_def_id);
651    };
652
653    let Node::Item(item) = tcx.hir_node_by_def_id(trait_def_id) else {
654        ::rustc_middle::util::bug::bug_fmt(format_args!("trait_def_id {0:?} is not an item",
        trait_def_id));bug!("trait_def_id {trait_def_id:?} is not an item");
655    };
656
657    let (generics, superbounds) = match item.kind {
658        hir::ItemKind::Trait(.., generics, supertraits, _) => (generics, supertraits),
659        hir::ItemKind::TraitAlias(_, _, generics, supertraits) => (generics, supertraits),
660        _ => ::rustc_middle::util::bug::span_bug_fmt(item.span,
    format_args!("super_predicates invoked on non-trait"))span_bug!(item.span, "super_predicates invoked on non-trait"),
661    };
662
663    let icx = ItemCtxt::new(tcx, trait_def_id);
664
665    let self_param_ty = tcx.types.self_param;
666    let mut bounds = Vec::new();
667    icx.lowerer().lower_bounds(
668        self_param_ty,
669        superbounds,
670        &mut bounds,
671        ty::List::empty(),
672        filter,
673        OverlappingAsssocItemConstraints::Allowed,
674    );
675    match filter {
676        PredicateFilter::All
677        | PredicateFilter::SelfOnly
678        | PredicateFilter::SelfTraitThatDefines(_)
679        | PredicateFilter::SelfAndAssociatedTypeBounds => {
680            icx.lowerer().add_implicit_sizedness_bounds(
681                &mut bounds,
682                self_param_ty,
683                superbounds,
684                ImpliedBoundsContext::TraitDef(trait_def_id),
685                item.span,
686            );
687            icx.lowerer().add_default_traits(
688                &mut bounds,
689                self_param_ty,
690                superbounds,
691                ImpliedBoundsContext::TraitDef(trait_def_id),
692                item.span,
693            );
694        }
695        //`ConstIfConst` is only interested in `[const]` bounds.
696        PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {}
697    }
698
699    let where_bounds_that_match =
700        icx.probe_ty_param_bounds_in_generics(generics, item.owner_id.def_id, filter);
701
702    // Combine the two lists to form the complete set of superbounds:
703    let implied_bounds =
704        &*tcx.arena.alloc_from_iter(bounds.into_iter().chain(where_bounds_that_match));
705    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/collect/predicates_of.rs:705",
                        "rustc_hir_analysis::collect::predicates_of",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/collect/predicates_of.rs"),
                        ::tracing_core::__macro_support::Option::Some(705u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::predicates_of"),
                        ::tracing_core::field::FieldSet::new(&["implied_bounds"],
                            ::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(&implied_bounds)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?implied_bounds);
706
707    // Now require that immediate supertraits are lowered, which will, in
708    // turn, reach indirect supertraits, so we detect cycles now instead of
709    // overflowing during elaboration. Same for implied predicates, which
710    // make sure we walk into associated type bounds.
711    match filter {
712        PredicateFilter::SelfOnly => {
713            for &(pred, span) in implied_bounds {
714                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/collect/predicates_of.rs:714",
                        "rustc_hir_analysis::collect::predicates_of",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/collect/predicates_of.rs"),
                        ::tracing_core::__macro_support::Option::Some(714u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::predicates_of"),
                        ::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!("superbound: {0:?}",
                                                    pred) as &dyn Value))])
            });
    } else { ; }
};debug!("superbound: {:?}", pred);
715                if let ty::ClauseKind::Trait(bound) = pred.kind().skip_binder()
716                    && bound.polarity == ty::PredicatePolarity::Positive
717                {
718                    tcx.at(span).explicit_super_predicates_of(bound.def_id());
719                }
720            }
721        }
722        PredicateFilter::All | PredicateFilter::SelfAndAssociatedTypeBounds => {
723            for &(pred, span) in implied_bounds {
724                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/collect/predicates_of.rs:724",
                        "rustc_hir_analysis::collect::predicates_of",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/collect/predicates_of.rs"),
                        ::tracing_core::__macro_support::Option::Some(724u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::predicates_of"),
                        ::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!("superbound: {0:?}",
                                                    pred) as &dyn Value))])
            });
    } else { ; }
};debug!("superbound: {:?}", pred);
725                if let ty::ClauseKind::Trait(bound) = pred.kind().skip_binder()
726                    && bound.polarity == ty::PredicatePolarity::Positive
727                {
728                    tcx.at(span).explicit_implied_predicates_of(bound.def_id());
729                }
730            }
731        }
732        _ => {}
733    }
734
735    assert_only_contains_predicates_from(filter, implied_bounds, tcx.types.self_param);
736
737    ty::EarlyBinder::bind(implied_bounds)
738}
739
740// Make sure when elaborating supertraits, probing for associated types, etc.,
741// we really truly are elaborating clauses that have `ty` as their self type.
742// This is very important since downstream code relies on this being correct.
743pub(super) fn assert_only_contains_predicates_from<'tcx>(
744    filter: PredicateFilter,
745    bounds: &'tcx [(ty::Clause<'tcx>, Span)],
746    ty: Ty<'tcx>,
747) {
748    if !truecfg!(debug_assertions) {
749        return;
750    }
751
752    match filter {
753        PredicateFilter::SelfOnly => {
754            for (clause, _) in bounds {
755                match clause.kind().skip_binder() {
756                    ty::ClauseKind::Trait(trait_predicate) => {
757                        match (&trait_predicate.self_ty(), &ty) {
    (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::Some(format_args!("expected `Self` predicate when computing `{0:?}` implied bounds: {1:?}",
                        filter, clause)));
        }
    }
};assert_eq!(
758                            trait_predicate.self_ty(),
759                            ty,
760                            "expected `Self` predicate when computing \
761                            `{filter:?}` implied bounds: {clause:?}"
762                        );
763                    }
764                    ty::ClauseKind::Projection(projection_predicate) => {
765                        match (&projection_predicate.self_ty(), &ty) {
    (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::Some(format_args!("expected `Self` predicate when computing `{0:?}` implied bounds: {1:?}",
                        filter, clause)));
        }
    }
};assert_eq!(
766                            projection_predicate.self_ty(),
767                            ty,
768                            "expected `Self` predicate when computing \
769                            `{filter:?}` implied bounds: {clause:?}"
770                        );
771                    }
772                    ty::ClauseKind::TypeOutlives(outlives_predicate) => {
773                        match (&outlives_predicate.0, &ty) {
    (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::Some(format_args!("expected `Self` predicate when computing `{0:?}` implied bounds: {1:?}",
                        filter, clause)));
        }
    }
};assert_eq!(
774                            outlives_predicate.0, ty,
775                            "expected `Self` predicate when computing \
776                            `{filter:?}` implied bounds: {clause:?}"
777                        );
778                    }
779                    ty::ClauseKind::HostEffect(host_effect_predicate) => {
780                        match (&host_effect_predicate.self_ty(), &ty) {
    (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::Some(format_args!("expected `Self` predicate when computing `{0:?}` implied bounds: {1:?}",
                        filter, clause)));
        }
    }
};assert_eq!(
781                            host_effect_predicate.self_ty(),
782                            ty,
783                            "expected `Self` predicate when computing \
784                            `{filter:?}` implied bounds: {clause:?}"
785                        );
786                    }
787
788                    ty::ClauseKind::RegionOutlives(_)
789                    | ty::ClauseKind::ConstArgHasType(_, _)
790                    | ty::ClauseKind::WellFormed(_)
791                    | ty::ClauseKind::UnstableFeature(_)
792                    | ty::ClauseKind::ConstEvaluatable(_) => {
793                        ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected non-`Self` predicate when computing `{0:?}` implied bounds: {1:?}",
        filter, clause));bug!(
794                            "unexpected non-`Self` predicate when computing \
795                            `{filter:?}` implied bounds: {clause:?}"
796                        );
797                    }
798                }
799            }
800        }
801        PredicateFilter::SelfTraitThatDefines(_) => {
802            for (clause, _) in bounds {
803                match clause.kind().skip_binder() {
804                    ty::ClauseKind::Trait(trait_predicate) => {
805                        match (&trait_predicate.self_ty(), &ty) {
    (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::Some(format_args!("expected `Self` predicate when computing `{0:?}` implied bounds: {1:?}",
                        filter, clause)));
        }
    }
};assert_eq!(
806                            trait_predicate.self_ty(),
807                            ty,
808                            "expected `Self` predicate when computing \
809                            `{filter:?}` implied bounds: {clause:?}"
810                        );
811                    }
812
813                    ty::ClauseKind::Projection(_)
814                    | ty::ClauseKind::TypeOutlives(_)
815                    | ty::ClauseKind::RegionOutlives(_)
816                    | ty::ClauseKind::ConstArgHasType(_, _)
817                    | ty::ClauseKind::WellFormed(_)
818                    | ty::ClauseKind::ConstEvaluatable(_)
819                    | ty::ClauseKind::UnstableFeature(_)
820                    | ty::ClauseKind::HostEffect(..) => {
821                        ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected non-`Self` predicate when computing `{0:?}` implied bounds: {1:?}",
        filter, clause));bug!(
822                            "unexpected non-`Self` predicate when computing \
823                            `{filter:?}` implied bounds: {clause:?}"
824                        );
825                    }
826                }
827            }
828        }
829        PredicateFilter::ConstIfConst => {
830            for (clause, _) in bounds {
831                match clause.kind().skip_binder() {
832                    ty::ClauseKind::HostEffect(ty::HostEffectPredicate {
833                        trait_ref: _,
834                        constness: ty::BoundConstness::Maybe,
835                    }) => {}
836                    _ => {
837                        ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected non-`HostEffect` predicate when computing `{0:?}` implied bounds: {1:?}",
        filter, clause));bug!(
838                            "unexpected non-`HostEffect` predicate when computing \
839                            `{filter:?}` implied bounds: {clause:?}"
840                        );
841                    }
842                }
843            }
844        }
845        PredicateFilter::SelfConstIfConst => {
846            for (clause, _) in bounds {
847                match clause.kind().skip_binder() {
848                    ty::ClauseKind::HostEffect(pred) => {
849                        match (&pred.constness, &ty::BoundConstness::Maybe) {
    (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::Some(format_args!("expected `[const]` predicate when computing `{0:?}` implied bounds: {1:?}",
                        filter, clause)));
        }
    }
};assert_eq!(
850                            pred.constness,
851                            ty::BoundConstness::Maybe,
852                            "expected `[const]` predicate when computing `{filter:?}` \
853                            implied bounds: {clause:?}",
854                        );
855                        match (&pred.trait_ref.self_ty(), &ty) {
    (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::Some(format_args!("expected `Self` predicate when computing `{0:?}` implied bounds: {1:?}",
                        filter, clause)));
        }
    }
};assert_eq!(
856                            pred.trait_ref.self_ty(),
857                            ty,
858                            "expected `Self` predicate when computing `{filter:?}` \
859                            implied bounds: {clause:?}"
860                        );
861                    }
862                    _ => {
863                        ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected non-`HostEffect` predicate when computing `{0:?}` implied bounds: {1:?}",
        filter, clause));bug!(
864                            "unexpected non-`HostEffect` predicate when computing \
865                            `{filter:?}` implied bounds: {clause:?}"
866                        );
867                    }
868                }
869            }
870        }
871        PredicateFilter::All | PredicateFilter::SelfAndAssociatedTypeBounds => {}
872    }
873}
874
875/// Returns the predicates defined on `item_def_id` of the form
876/// `X: Foo` where `X` is the type parameter `def_id`.
877#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::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("type_param_predicates",
                                    "rustc_hir_analysis::collect::predicates_of",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/collect/predicates_of.rs"),
                                    ::tracing_core::__macro_support::Option::Some(877u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::predicates_of"),
                                    ::tracing_core::field::FieldSet::new(&["item_def_id",
                                                    "def_id", "assoc_ident"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::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(&item_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(&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(&assoc_ident)
                                                            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:
                    ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            match tcx.opt_rpitit_info(item_def_id.to_def_id()) {
                Some(ty::ImplTraitInTraitData::Trait { opaque_def_id, .. }) =>
                    {
                    return tcx.type_param_predicates((opaque_def_id.expect_local(),
                                def_id, assoc_ident));
                }
                Some(ty::ImplTraitInTraitData::Impl { .. }) => {
                    {
                        ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
                                format_args!("should not be lowering bounds on RPITIT in impl")));
                    }
                }
                None => {}
            }
            let param_id = tcx.local_def_id_to_hir_id(def_id);
            let param_owner = tcx.hir_ty_param_owner(def_id);
            let parent =
                if item_def_id == param_owner {
                    None
                } else {
                    tcx.generics_of(item_def_id).parent.map(|def_id|
                            def_id.expect_local())
                };
            let result =
                if let Some(parent) = parent {
                    let icx = ItemCtxt::new(tcx, parent);
                    icx.probe_ty_param_bounds(DUMMY_SP, def_id, assoc_ident)
                } else { ty::EarlyBinder::bind(&[] as &[_]) };
            let mut extend = None;
            let item_hir_id = tcx.local_def_id_to_hir_id(item_def_id);
            let hir_node = tcx.hir_node(item_hir_id);
            let Some(hir_generics) =
                hir_node.generics() else { return result; };
            if let Node::Item(item) = hir_node &&
                        let hir::ItemKind::Trait(..) = item.kind &&
                    param_id == item_hir_id {
                let identity_trait_ref =
                    ty::TraitRef::identity(tcx, item_def_id.to_def_id());
                extend = Some((identity_trait_ref.upcast(tcx), item.span));
            }
            let icx = ItemCtxt::new(tcx, item_def_id);
            let extra_predicates =
                extend.into_iter().chain(icx.probe_ty_param_bounds_in_generics(hir_generics,
                        def_id,
                        PredicateFilter::SelfTraitThatDefines(assoc_ident)));
            let bounds =
                &*tcx.arena.alloc_from_iter(result.skip_binder().iter().copied().chain(extra_predicates));
            let self_ty =
                match tcx.def_kind(def_id) {
                    DefKind::TyParam =>
                        Ty::new_param(tcx,
                            tcx.generics_of(item_def_id).param_def_id_to_index(tcx,
                                    def_id.to_def_id()).expect("expected generic param to be owned by item"),
                            tcx.item_name(def_id.to_def_id())),
                    DefKind::Trait | DefKind::TraitAlias =>
                        tcx.types.self_param,
                    _ =>
                        ::core::panicking::panic("internal error: entered unreachable code"),
                };
            assert_only_contains_predicates_from(PredicateFilter::SelfTraitThatDefines(assoc_ident),
                bounds, self_ty);
            ty::EarlyBinder::bind(bounds)
        }
    }
}#[instrument(level = "trace", skip(tcx))]
878pub(super) fn type_param_predicates<'tcx>(
879    tcx: TyCtxt<'tcx>,
880    (item_def_id, def_id, assoc_ident): (LocalDefId, LocalDefId, Ident),
881) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]> {
882    match tcx.opt_rpitit_info(item_def_id.to_def_id()) {
883        Some(ty::ImplTraitInTraitData::Trait { opaque_def_id, .. }) => {
884            return tcx.type_param_predicates((opaque_def_id.expect_local(), def_id, assoc_ident));
885        }
886        Some(ty::ImplTraitInTraitData::Impl { .. }) => {
887            unreachable!("should not be lowering bounds on RPITIT in impl")
888        }
889        None => {}
890    }
891
892    // In the HIR, bounds can derive from two places. Either
893    // written inline like `<T: Foo>` or in a where-clause like
894    // `where T: Foo`.
895
896    let param_id = tcx.local_def_id_to_hir_id(def_id);
897    let param_owner = tcx.hir_ty_param_owner(def_id);
898
899    // Don't look for bounds where the type parameter isn't in scope.
900    let parent = if item_def_id == param_owner {
901        // FIXME: Shouldn't this be unreachable?
902        None
903    } else {
904        tcx.generics_of(item_def_id).parent.map(|def_id| def_id.expect_local())
905    };
906
907    let result = if let Some(parent) = parent {
908        let icx = ItemCtxt::new(tcx, parent);
909        icx.probe_ty_param_bounds(DUMMY_SP, def_id, assoc_ident)
910    } else {
911        ty::EarlyBinder::bind(&[] as &[_])
912    };
913    let mut extend = None;
914
915    let item_hir_id = tcx.local_def_id_to_hir_id(item_def_id);
916
917    let hir_node = tcx.hir_node(item_hir_id);
918    let Some(hir_generics) = hir_node.generics() else {
919        return result;
920    };
921
922    if let Node::Item(item) = hir_node
923        && let hir::ItemKind::Trait(..) = item.kind
924        // Implied `Self: Trait` and supertrait bounds.
925        && param_id == item_hir_id
926    {
927        let identity_trait_ref = ty::TraitRef::identity(tcx, item_def_id.to_def_id());
928        extend = Some((identity_trait_ref.upcast(tcx), item.span));
929    }
930
931    let icx = ItemCtxt::new(tcx, item_def_id);
932    let extra_predicates = extend.into_iter().chain(icx.probe_ty_param_bounds_in_generics(
933        hir_generics,
934        def_id,
935        PredicateFilter::SelfTraitThatDefines(assoc_ident),
936    ));
937
938    let bounds =
939        &*tcx.arena.alloc_from_iter(result.skip_binder().iter().copied().chain(extra_predicates));
940
941    // Double check that the bounds *only* contain `SelfTy: Trait` preds.
942    let self_ty = match tcx.def_kind(def_id) {
943        DefKind::TyParam => Ty::new_param(
944            tcx,
945            tcx.generics_of(item_def_id)
946                .param_def_id_to_index(tcx, def_id.to_def_id())
947                .expect("expected generic param to be owned by item"),
948            tcx.item_name(def_id.to_def_id()),
949        ),
950        DefKind::Trait | DefKind::TraitAlias => tcx.types.self_param,
951        _ => unreachable!(),
952    };
953    assert_only_contains_predicates_from(
954        PredicateFilter::SelfTraitThatDefines(assoc_ident),
955        bounds,
956        self_ty,
957    );
958
959    ty::EarlyBinder::bind(bounds)
960}
961
962impl<'tcx> ItemCtxt<'tcx> {
963    /// Finds bounds from `hir::Generics`.
964    ///
965    /// This requires scanning through the HIR.
966    /// We do this to avoid having to lower *all* the bounds, which would create artificial cycles.
967    /// Instead, we can only lower the bounds for a type parameter `X` if `X::Foo` is used.
968    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::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("probe_ty_param_bounds_in_generics",
                                    "rustc_hir_analysis::collect::predicates_of",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/collect/predicates_of.rs"),
                                    ::tracing_core::__macro_support::Option::Some(968u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::predicates_of"),
                                    ::tracing_core::field::FieldSet::new(&["param_def_id",
                                                    "filter"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::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(&param_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(&filter)
                                                            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: Vec<(ty::Clause<'tcx>, Span)> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let mut bounds = Vec::new();
            for predicate in hir_generics.predicates {
                let hir_id = predicate.hir_id;
                let hir::WherePredicateKind::BoundPredicate(predicate) =
                    predicate.kind else { continue; };
                match filter {
                    _ if predicate.is_param_bound(param_def_id.to_def_id()) =>
                        {}
                    PredicateFilter::All => {}
                    PredicateFilter::SelfOnly |
                        PredicateFilter::SelfTraitThatDefines(_) |
                        PredicateFilter::SelfConstIfConst |
                        PredicateFilter::SelfAndAssociatedTypeBounds => continue,
                    PredicateFilter::ConstIfConst =>
                        ::core::panicking::panic("internal error: entered unreachable code"),
                }
                let bound_ty =
                    self.lowerer().lower_ty_maybe_return_type_notation(predicate.bounded_ty);
                let bound_vars = self.tcx.late_bound_vars(hir_id);
                self.lowerer().lower_bounds(bound_ty, predicate.bounds,
                    &mut bounds, bound_vars, filter,
                    OverlappingAsssocItemConstraints::Allowed);
            }
            bounds
        }
    }
}#[instrument(level = "trace", skip(self, hir_generics))]
969    fn probe_ty_param_bounds_in_generics(
970        &self,
971        hir_generics: &'tcx hir::Generics<'tcx>,
972        param_def_id: LocalDefId,
973        filter: PredicateFilter,
974    ) -> Vec<(ty::Clause<'tcx>, Span)> {
975        let mut bounds = Vec::new();
976
977        for predicate in hir_generics.predicates {
978            let hir_id = predicate.hir_id;
979            let hir::WherePredicateKind::BoundPredicate(predicate) = predicate.kind else {
980                continue;
981            };
982
983            match filter {
984                _ if predicate.is_param_bound(param_def_id.to_def_id()) => {
985                    // Ok
986                }
987                PredicateFilter::All => {
988                    // Ok
989                }
990                PredicateFilter::SelfOnly
991                | PredicateFilter::SelfTraitThatDefines(_)
992                | PredicateFilter::SelfConstIfConst
993                | PredicateFilter::SelfAndAssociatedTypeBounds => continue,
994                PredicateFilter::ConstIfConst => unreachable!(),
995            }
996
997            let bound_ty = self.lowerer().lower_ty_maybe_return_type_notation(predicate.bounded_ty);
998
999            let bound_vars = self.tcx.late_bound_vars(hir_id);
1000            self.lowerer().lower_bounds(
1001                bound_ty,
1002                predicate.bounds,
1003                &mut bounds,
1004                bound_vars,
1005                filter,
1006                OverlappingAsssocItemConstraints::Allowed,
1007            );
1008        }
1009
1010        bounds
1011    }
1012}
1013
1014pub(super) fn const_conditions<'tcx>(
1015    tcx: TyCtxt<'tcx>,
1016    def_id: LocalDefId,
1017) -> ty::ConstConditions<'tcx> {
1018    if !tcx.is_conditionally_const(def_id) {
1019        ::rustc_middle::util::bug::bug_fmt(format_args!("const_conditions invoked for item that is not conditionally const: {0:?}",
        def_id));bug!("const_conditions invoked for item that is not conditionally const: {def_id:?}");
1020    }
1021
1022    match tcx.opt_rpitit_info(def_id.to_def_id()) {
1023        // RPITITs inherit const conditions of their parent fn
1024        Some(
1025            ty::ImplTraitInTraitData::Impl { fn_def_id }
1026            | ty::ImplTraitInTraitData::Trait { fn_def_id, .. },
1027        ) => return tcx.const_conditions(fn_def_id),
1028        None => {}
1029    }
1030
1031    let (generics, trait_def_id_and_supertraits, has_parent) = match tcx.hir_node_by_def_id(def_id)
1032    {
1033        Node::Item(item) => match item.kind {
1034            hir::ItemKind::Impl(impl_) => (impl_.generics, None, false),
1035            hir::ItemKind::Fn { generics, .. } => (generics, None, false),
1036            hir::ItemKind::Trait(_, _, _, _, generics, supertraits, _) => {
1037                (generics, Some((Some(item.owner_id.def_id), supertraits)), false)
1038            }
1039            hir::ItemKind::TraitAlias(_, _, generics, supertraits) => {
1040                (generics, Some((None, supertraits)), false)
1041            }
1042            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("const_conditions called on wrong item: {0:?}",
        def_id))bug!("const_conditions called on wrong item: {def_id:?}"),
1043        },
1044        // While associated types are not really const, we do allow them to have `[const]`
1045        // bounds and where clauses. `const_conditions` is responsible for gathering
1046        // these up so we can check them in `compare_type_predicate_entailment`, and
1047        // in `HostEffect` goal computation.
1048        Node::TraitItem(item) => match item.kind {
1049            hir::TraitItemKind::Fn(_, _) | hir::TraitItemKind::Type(_, _) => {
1050                (item.generics, None, true)
1051            }
1052            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("const_conditions called on wrong item: {0:?}",
        def_id))bug!("const_conditions called on wrong item: {def_id:?}"),
1053        },
1054        Node::ImplItem(item) => match item.kind {
1055            hir::ImplItemKind::Fn(_, _) | hir::ImplItemKind::Type(_) => {
1056                (item.generics, None, tcx.is_conditionally_const(tcx.local_parent(def_id)))
1057            }
1058            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("const_conditions called on wrong item: {0:?}",
        def_id))bug!("const_conditions called on wrong item: {def_id:?}"),
1059        },
1060        Node::ForeignItem(item) => match item.kind {
1061            hir::ForeignItemKind::Fn(_, _, generics) => (generics, None, false),
1062            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("const_conditions called on wrong item: {0:?}",
        def_id))bug!("const_conditions called on wrong item: {def_id:?}"),
1063        },
1064        Node::OpaqueTy(opaque) => match opaque.origin {
1065            hir::OpaqueTyOrigin::FnReturn { parent, .. } => return tcx.const_conditions(parent),
1066            hir::OpaqueTyOrigin::AsyncFn { .. } | hir::OpaqueTyOrigin::TyAlias { .. } => {
1067                ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
1068            }
1069        },
1070        // N.B. Tuple ctors are unconditionally constant.
1071        Node::Ctor(hir::VariantData::Tuple { .. }) => return Default::default(),
1072        _ => ::rustc_middle::util::bug::bug_fmt(format_args!("const_conditions called on wrong item: {0:?}",
        def_id))bug!("const_conditions called on wrong item: {def_id:?}"),
1073    };
1074
1075    let icx = ItemCtxt::new(tcx, def_id);
1076    let mut bounds = Vec::new();
1077
1078    for pred in generics.predicates {
1079        match pred.kind {
1080            hir::WherePredicateKind::BoundPredicate(bound_pred) => {
1081                let ty = icx.lowerer().lower_ty_maybe_return_type_notation(bound_pred.bounded_ty);
1082                let bound_vars = tcx.late_bound_vars(pred.hir_id);
1083                icx.lowerer().lower_bounds(
1084                    ty,
1085                    bound_pred.bounds.iter(),
1086                    &mut bounds,
1087                    bound_vars,
1088                    PredicateFilter::ConstIfConst,
1089                    OverlappingAsssocItemConstraints::Allowed,
1090                );
1091            }
1092            _ => {}
1093        }
1094    }
1095
1096    if let Some((def_id, supertraits)) = trait_def_id_and_supertraits {
1097        if let Some(def_id) = def_id {
1098            // We've checked above that the trait is conditionally const.
1099            bounds.push((
1100                ty::Binder::dummy(ty::TraitRef::identity(tcx, def_id.to_def_id()))
1101                    .to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1102                DUMMY_SP,
1103            ));
1104        }
1105
1106        icx.lowerer().lower_bounds(
1107            tcx.types.self_param,
1108            supertraits,
1109            &mut bounds,
1110            ty::List::empty(),
1111            PredicateFilter::ConstIfConst,
1112            OverlappingAsssocItemConstraints::Allowed,
1113        );
1114    }
1115
1116    ty::ConstConditions {
1117        parent: has_parent.then(|| tcx.local_parent(def_id).to_def_id()),
1118        predicates: tcx.arena.alloc_from_iter(bounds.into_iter().map(|(clause, span)| {
1119            (
1120                clause.kind().map_bound(|clause| match clause {
1121                    ty::ClauseKind::HostEffect(ty::HostEffectPredicate {
1122                        trait_ref,
1123                        constness: ty::BoundConstness::Maybe,
1124                    }) => trait_ref,
1125                    _ => ::rustc_middle::util::bug::bug_fmt(format_args!("converted {0:?}", clause))bug!("converted {clause:?}"),
1126                }),
1127                span,
1128            )
1129        })),
1130    }
1131}
1132
1133pub(super) fn explicit_implied_const_bounds<'tcx>(
1134    tcx: TyCtxt<'tcx>,
1135    def_id: LocalDefId,
1136) -> ty::EarlyBinder<'tcx, &'tcx [(ty::PolyTraitRef<'tcx>, Span)]> {
1137    if !tcx.is_conditionally_const(def_id) {
1138        ::rustc_middle::util::bug::bug_fmt(format_args!("explicit_implied_const_bounds invoked for item that is not conditionally const: {0:?}",
        def_id));bug!(
1139            "explicit_implied_const_bounds invoked for item that is not conditionally const: {def_id:?}"
1140        );
1141    }
1142
1143    let bounds = match tcx.opt_rpitit_info(def_id.to_def_id()) {
1144        // RPITIT's bounds are the same as opaque type bounds, but with
1145        // a projection self type.
1146        Some(ty::ImplTraitInTraitData::Trait { .. }) => {
1147            explicit_item_bounds_with_filter(tcx, def_id, PredicateFilter::ConstIfConst)
1148        }
1149        Some(ty::ImplTraitInTraitData::Impl { .. }) => {
1150            ::rustc_middle::util::bug::span_bug_fmt(tcx.def_span(def_id),
    format_args!("RPITIT in impl should not have item bounds"))span_bug!(tcx.def_span(def_id), "RPITIT in impl should not have item bounds")
1151        }
1152        None => match tcx.hir_node_by_def_id(def_id) {
1153            Node::Item(hir::Item {
1154                kind: hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..),
1155                ..
1156            }) => implied_predicates_with_filter(
1157                tcx,
1158                def_id.to_def_id(),
1159                PredicateFilter::SelfConstIfConst,
1160            ),
1161            Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Type(..), .. })
1162            | Node::OpaqueTy(_) => {
1163                explicit_item_bounds_with_filter(tcx, def_id, PredicateFilter::ConstIfConst)
1164            }
1165            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("explicit_implied_const_bounds called on wrong item: {0:?}",
        def_id))bug!("explicit_implied_const_bounds called on wrong item: {def_id:?}"),
1166        },
1167    };
1168
1169    bounds.map_bound(|bounds| {
1170        &*tcx.arena.alloc_from_iter(bounds.iter().copied().map(|(clause, span)| {
1171            (
1172                clause.kind().map_bound(|clause| match clause {
1173                    ty::ClauseKind::HostEffect(ty::HostEffectPredicate {
1174                        trait_ref,
1175                        constness: ty::BoundConstness::Maybe,
1176                    }) => trait_ref,
1177                    _ => ::rustc_middle::util::bug::bug_fmt(format_args!("converted {0:?}", clause))bug!("converted {clause:?}"),
1178                }),
1179                span,
1180            )
1181        }))
1182    })
1183}