Skip to main content

rustc_hir_analysis/collect/
predicates_of.rs

1use hir::Node;
2use rustc_data_structures::assert_matches;
3use rustc_data_structures::fx::FxIndexSet;
4use rustc_hir as hir;
5use rustc_hir::attrs::AttributeKind;
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, AttributeKind::UnstableFeatureBound(i) => i)
335            .map(|i| i.as_slice())
336            .unwrap_or_default();
337
338    for (feat_name, span) in allow_unstable_feature_attr {
339        predicates.insert((ty::ClauseKind::UnstableFeature(*feat_name).upcast(tcx), *span));
340    }
341
342    let mut predicates: Vec<_> = predicates.into_iter().collect();
343
344    // Subtle: before we store the predicates into the tcx, we
345    // sort them so that predicates like `T: Foo<Item=U>` come
346    // before uses of `U`. This avoids false ambiguity errors
347    // in trait checking. See `setup_constraining_predicates`
348    // for details.
349    if let Node::Item(&Item { kind: ItemKind::Impl(impl_), .. }) = node {
350        let self_ty = tcx.type_of(def_id).instantiate_identity();
351        let trait_ref =
352            impl_.of_trait.is_some().then(|| tcx.impl_trait_ref(def_id).instantiate_identity());
353        cgp::setup_constraining_predicates(
354            tcx,
355            &mut predicates,
356            trait_ref,
357            &mut cgp::parameters_for_impl(tcx, self_ty, trait_ref),
358        );
359    }
360
361    // Opaque types duplicate some of their generic parameters.
362    // We create bi-directional Outlives predicates between the original
363    // and the duplicated parameter, to ensure that they do not get out of sync.
364    if let Node::OpaqueTy(..) = node {
365        compute_bidirectional_outlives_predicates(tcx, &generics.own_params, &mut predicates);
366        debug!(?predicates);
367    }
368
369    ty::GenericPredicates {
370        parent: generics.parent,
371        predicates: tcx.arena.alloc_from_iter(predicates),
372    }
373}
374
375/// Opaques have duplicated lifetimes and we need to compute bidirectional outlives predicates to
376/// enforce that these lifetimes stay in sync.
377fn compute_bidirectional_outlives_predicates<'tcx>(
378    tcx: TyCtxt<'tcx>,
379    opaque_own_params: &[ty::GenericParamDef],
380    predicates: &mut Vec<(ty::Clause<'tcx>, Span)>,
381) {
382    for param in opaque_own_params {
383        let orig_lifetime = tcx.map_opaque_lifetime_to_parent_lifetime(param.def_id.expect_local());
384        if let ty::ReEarlyParam(..) = orig_lifetime.kind() {
385            let dup_lifetime = ty::Region::new_early_param(
386                tcx,
387                ty::EarlyParamRegion { index: param.index, name: param.name },
388            );
389            let span = tcx.def_span(param.def_id);
390            predicates.push((
391                ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(orig_lifetime, dup_lifetime))
392                    .upcast(tcx),
393                span,
394            ));
395            predicates.push((
396                ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(dup_lifetime, orig_lifetime))
397                    .upcast(tcx),
398                span,
399            ));
400        }
401    }
402}
403
404x;#[instrument(level = "debug", skip(tcx, predicates), ret)]
405fn const_evaluatable_predicates_of<'tcx>(
406    tcx: TyCtxt<'tcx>,
407    def_id: LocalDefId,
408    predicates: &FxIndexSet<(ty::Clause<'tcx>, Span)>,
409) -> FxIndexSet<(ty::Clause<'tcx>, Span)> {
410    struct ConstCollector<'tcx> {
411        tcx: TyCtxt<'tcx>,
412        preds: FxIndexSet<(ty::Clause<'tcx>, Span)>,
413    }
414
415    fn is_const_param_default(tcx: TyCtxt<'_>, def: LocalDefId) -> bool {
416        let hir_id = tcx.local_def_id_to_hir_id(def);
417        let (_, parent_node) = tcx
418            .hir_parent_iter(hir_id)
419            .skip_while(|(_, n)| matches!(n, Node::ConstArg(..)))
420            .next()
421            .unwrap();
422        matches!(
423            parent_node,
424            Node::GenericParam(hir::GenericParam { kind: hir::GenericParamKind::Const { .. }, .. })
425        )
426    }
427
428    impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ConstCollector<'tcx> {
429        fn visit_const(&mut self, c: ty::Const<'tcx>) {
430            if let ty::ConstKind::Unevaluated(uv) = c.kind() {
431                if let Some(local) = uv.def.as_local()
432                    && is_const_param_default(self.tcx, local)
433                {
434                    // Do not look into const param defaults,
435                    // these get checked when they are actually instantiated.
436                    //
437                    // We do not want the following to error:
438                    //
439                    //     struct Foo<const N: usize, const M: usize = { N + 1 }>;
440                    //     struct Bar<const N: usize>(Foo<N, 3>);
441                    return;
442                }
443
444                let span = self.tcx.def_span(uv.def);
445                self.preds.insert((ty::ClauseKind::ConstEvaluatable(c).upcast(self.tcx), span));
446            }
447        }
448    }
449
450    let hir_id = tcx.local_def_id_to_hir_id(def_id);
451    let node = tcx.hir_node(hir_id);
452
453    let mut collector = ConstCollector { tcx, preds: FxIndexSet::default() };
454
455    for (clause, _sp) in predicates {
456        clause.visit_with(&mut collector);
457    }
458
459    if let hir::Node::Item(item) = node
460        && let hir::ItemKind::Impl(impl_) = item.kind
461    {
462        if impl_.of_trait.is_some() {
463            debug!("visit impl trait_ref");
464            let trait_ref = tcx.impl_trait_ref(def_id);
465            trait_ref.instantiate_identity().visit_with(&mut collector);
466        }
467
468        debug!("visit self_ty");
469        let self_ty = tcx.type_of(def_id);
470        self_ty.instantiate_identity().visit_with(&mut collector);
471    }
472
473    if let Some(_) = tcx.hir_fn_sig_by_hir_id(hir_id) {
474        debug!("visit fn sig");
475        let fn_sig = tcx.fn_sig(def_id);
476        let fn_sig = fn_sig.instantiate_identity();
477        debug!(?fn_sig);
478        fn_sig.visit_with(&mut collector);
479    }
480
481    collector.preds
482}
483
484pub(super) fn trait_explicit_predicates_and_bounds(
485    tcx: TyCtxt<'_>,
486    def_id: LocalDefId,
487) -> ty::GenericPredicates<'_> {
488    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);
489    gather_explicit_predicates_of(tcx, def_id)
490}
491
492pub(super) fn explicit_predicates_of<'tcx>(
493    tcx: TyCtxt<'tcx>,
494    def_id: LocalDefId,
495) -> ty::GenericPredicates<'tcx> {
496    let def_kind = tcx.def_kind(def_id);
497    if let DefKind::Trait = def_kind {
498        // Remove bounds on associated types from the predicates, they will be
499        // returned by `explicit_item_bounds`.
500        let predicates_and_bounds = tcx.trait_explicit_predicates_and_bounds(def_id);
501        let trait_identity_args = ty::GenericArgs::identity_for_item(tcx, def_id);
502
503        let is_assoc_item_ty = |ty: Ty<'tcx>| {
504            // For a predicate from a where clause to become a bound on an
505            // associated type:
506            // * It must use the identity args of the item.
507            //   * We're in the scope of the trait, so we can't name any
508            //     parameters of the GAT. That means that all we need to
509            //     check are that the args of the projection are the
510            //     identity args of the trait.
511            // * It must be an associated type for this trait (*not* a
512            //   supertrait).
513            if let ty::Alias(ty::Projection, projection) = ty.kind() {
514                projection.args == trait_identity_args
515                    // FIXME(return_type_notation): This check should be more robust
516                    && !tcx.is_impl_trait_in_trait(projection.def_id)
517                    && tcx.parent(projection.def_id) == def_id.to_def_id()
518            } else {
519                false
520            }
521        };
522
523        let predicates: Vec<_> = predicates_and_bounds
524            .predicates
525            .iter()
526            .copied()
527            .filter(|(pred, _)| match pred.kind().skip_binder() {
528                ty::ClauseKind::Trait(tr) => !is_assoc_item_ty(tr.self_ty()),
529                ty::ClauseKind::Projection(proj) => {
530                    !is_assoc_item_ty(proj.projection_term.self_ty())
531                }
532                ty::ClauseKind::TypeOutlives(outlives) => !is_assoc_item_ty(outlives.0),
533                _ => true,
534            })
535            .collect();
536        if predicates.len() == predicates_and_bounds.predicates.len() {
537            predicates_and_bounds
538        } else {
539            ty::GenericPredicates {
540                parent: predicates_and_bounds.parent,
541                predicates: tcx.arena.alloc_slice(&predicates),
542            }
543        }
544    } else {
545        if def_kind == DefKind::AnonConst
546            && tcx.features().generic_const_exprs()
547            && let Some(defaulted_param_def_id) =
548                tcx.hir_opt_const_param_default_param_def_id(tcx.local_def_id_to_hir_id(def_id))
549        {
550            // In `generics_of` we set the generics' parent to be our parent's parent which means that
551            // we lose out on the predicates of our actual parent if we dont return those predicates here.
552            // (See comment in `generics_of` for more information on why the parent shenanigans is necessary)
553            //
554            // struct Foo<T, const N: usize = { <T as Trait>::ASSOC }>(T) where T: Trait;
555            //        ^^^                     ^^^^^^^^^^^^^^^^^^^^^^^ the def id we are calling
556            //        ^^^                                             explicit_predicates_of on
557            //        parent item we dont have set as the
558            //        parent of generics returned by `generics_of`
559            //
560            // In the above code we want the anon const to have predicates in its param env for `T: Trait`
561            // and we would be calling `explicit_predicates_of(Foo)` here
562            let parent_def_id = tcx.local_parent(def_id);
563            let parent_preds = tcx.explicit_predicates_of(parent_def_id);
564
565            // If we dont filter out `ConstArgHasType` predicates then every single defaulted const parameter
566            // will ICE because of #106994. FIXME(generic_const_exprs): remove this when a more general solution
567            // to #106994 is implemented.
568            let filtered_predicates = parent_preds
569                .predicates
570                .into_iter()
571                .filter(|(pred, _)| {
572                    if let ty::ClauseKind::ConstArgHasType(ct, _) = pred.kind().skip_binder() {
573                        match ct.kind() {
574                            ty::ConstKind::Param(param_const) => {
575                                let defaulted_param_idx = tcx
576                                    .generics_of(parent_def_id)
577                                    .param_def_id_to_index[&defaulted_param_def_id.to_def_id()];
578                                param_const.index < defaulted_param_idx
579                            }
580                            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("`ConstArgHasType` in `predicates_of`that isn\'t a `Param` const"))bug!(
581                                "`ConstArgHasType` in `predicates_of`\
582                                 that isn't a `Param` const"
583                            ),
584                        }
585                    } else {
586                        true
587                    }
588                })
589                .cloned();
590            return GenericPredicates {
591                parent: parent_preds.parent,
592                predicates: { tcx.arena.alloc_from_iter(filtered_predicates) },
593            };
594        }
595        gather_explicit_predicates_of(tcx, def_id)
596    }
597}
598
599/// Ensures that the super-predicates of the trait with a `DefId`
600/// of `trait_def_id` are lowered and stored. This also ensures that
601/// the transitive super-predicates are lowered.
602pub(super) fn explicit_super_predicates_of<'tcx>(
603    tcx: TyCtxt<'tcx>,
604    trait_def_id: LocalDefId,
605) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]> {
606    implied_predicates_with_filter(tcx, trait_def_id.to_def_id(), PredicateFilter::SelfOnly)
607}
608
609pub(super) fn explicit_supertraits_containing_assoc_item<'tcx>(
610    tcx: TyCtxt<'tcx>,
611    (trait_def_id, assoc_ident): (DefId, Ident),
612) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]> {
613    implied_predicates_with_filter(
614        tcx,
615        trait_def_id,
616        PredicateFilter::SelfTraitThatDefines(assoc_ident),
617    )
618}
619
620pub(super) fn explicit_implied_predicates_of<'tcx>(
621    tcx: TyCtxt<'tcx>,
622    trait_def_id: LocalDefId,
623) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]> {
624    implied_predicates_with_filter(
625        tcx,
626        trait_def_id.to_def_id(),
627        if tcx.is_trait_alias(trait_def_id.to_def_id()) {
628            PredicateFilter::All
629        } else {
630            PredicateFilter::SelfAndAssociatedTypeBounds
631        },
632    )
633}
634
635/// Ensures that the super-predicates of the trait with a `DefId`
636/// of `trait_def_id` are lowered and stored. This also ensures that
637/// the transitive super-predicates are lowered.
638pub(super) fn implied_predicates_with_filter<'tcx>(
639    tcx: TyCtxt<'tcx>,
640    trait_def_id: DefId,
641    filter: PredicateFilter,
642) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]> {
643    let Some(trait_def_id) = trait_def_id.as_local() else {
644        // if `assoc_ident` is None, then the query should've been redirected to an
645        // external provider
646        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(_));
647        return tcx.explicit_super_predicates_of(trait_def_id);
648    };
649
650    let Node::Item(item) = tcx.hir_node_by_def_id(trait_def_id) else {
651        ::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");
652    };
653
654    let (generics, superbounds) = match item.kind {
655        hir::ItemKind::Trait(.., generics, supertraits, _) => (generics, supertraits),
656        hir::ItemKind::TraitAlias(_, _, generics, supertraits) => (generics, supertraits),
657        _ => ::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"),
658    };
659
660    let icx = ItemCtxt::new(tcx, trait_def_id);
661
662    let self_param_ty = tcx.types.self_param;
663    let mut bounds = Vec::new();
664    icx.lowerer().lower_bounds(
665        self_param_ty,
666        superbounds,
667        &mut bounds,
668        ty::List::empty(),
669        filter,
670        OverlappingAsssocItemConstraints::Allowed,
671    );
672    match filter {
673        PredicateFilter::All
674        | PredicateFilter::SelfOnly
675        | PredicateFilter::SelfTraitThatDefines(_)
676        | PredicateFilter::SelfAndAssociatedTypeBounds => {
677            icx.lowerer().add_implicit_sizedness_bounds(
678                &mut bounds,
679                self_param_ty,
680                superbounds,
681                ImpliedBoundsContext::TraitDef(trait_def_id),
682                item.span,
683            );
684            icx.lowerer().add_default_traits(
685                &mut bounds,
686                self_param_ty,
687                superbounds,
688                ImpliedBoundsContext::TraitDef(trait_def_id),
689                item.span,
690            );
691        }
692        //`ConstIfConst` is only interested in `[const]` bounds.
693        PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {}
694    }
695
696    let where_bounds_that_match =
697        icx.probe_ty_param_bounds_in_generics(generics, item.owner_id.def_id, filter);
698
699    // Combine the two lists to form the complete set of superbounds:
700    let implied_bounds =
701        &*tcx.arena.alloc_from_iter(bounds.into_iter().chain(where_bounds_that_match));
702    {
    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:702",
                        "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(702u32),
                        ::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);
703
704    // Now require that immediate supertraits are lowered, which will, in
705    // turn, reach indirect supertraits, so we detect cycles now instead of
706    // overflowing during elaboration. Same for implied predicates, which
707    // make sure we walk into associated type bounds.
708    match filter {
709        PredicateFilter::SelfOnly => {
710            for &(pred, span) in implied_bounds {
711                {
    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:711",
                        "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(711u32),
                        ::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);
712                if let ty::ClauseKind::Trait(bound) = pred.kind().skip_binder()
713                    && bound.polarity == ty::PredicatePolarity::Positive
714                {
715                    tcx.at(span).explicit_super_predicates_of(bound.def_id());
716                }
717            }
718        }
719        PredicateFilter::All | PredicateFilter::SelfAndAssociatedTypeBounds => {
720            for &(pred, span) in implied_bounds {
721                {
    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:721",
                        "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(721u32),
                        ::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);
722                if let ty::ClauseKind::Trait(bound) = pred.kind().skip_binder()
723                    && bound.polarity == ty::PredicatePolarity::Positive
724                {
725                    tcx.at(span).explicit_implied_predicates_of(bound.def_id());
726                }
727            }
728        }
729        _ => {}
730    }
731
732    assert_only_contains_predicates_from(filter, implied_bounds, tcx.types.self_param);
733
734    ty::EarlyBinder::bind(implied_bounds)
735}
736
737// Make sure when elaborating supertraits, probing for associated types, etc.,
738// we really truly are elaborating clauses that have `ty` as their self type.
739// This is very important since downstream code relies on this being correct.
740pub(super) fn assert_only_contains_predicates_from<'tcx>(
741    filter: PredicateFilter,
742    bounds: &'tcx [(ty::Clause<'tcx>, Span)],
743    ty: Ty<'tcx>,
744) {
745    if !truecfg!(debug_assertions) {
746        return;
747    }
748
749    match filter {
750        PredicateFilter::SelfOnly => {
751            for (clause, _) in bounds {
752                match clause.kind().skip_binder() {
753                    ty::ClauseKind::Trait(trait_predicate) => {
754                        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!(
755                            trait_predicate.self_ty(),
756                            ty,
757                            "expected `Self` predicate when computing \
758                            `{filter:?}` implied bounds: {clause:?}"
759                        );
760                    }
761                    ty::ClauseKind::Projection(projection_predicate) => {
762                        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!(
763                            projection_predicate.self_ty(),
764                            ty,
765                            "expected `Self` predicate when computing \
766                            `{filter:?}` implied bounds: {clause:?}"
767                        );
768                    }
769                    ty::ClauseKind::TypeOutlives(outlives_predicate) => {
770                        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!(
771                            outlives_predicate.0, ty,
772                            "expected `Self` predicate when computing \
773                            `{filter:?}` implied bounds: {clause:?}"
774                        );
775                    }
776                    ty::ClauseKind::HostEffect(host_effect_predicate) => {
777                        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!(
778                            host_effect_predicate.self_ty(),
779                            ty,
780                            "expected `Self` predicate when computing \
781                            `{filter:?}` implied bounds: {clause:?}"
782                        );
783                    }
784
785                    ty::ClauseKind::RegionOutlives(_)
786                    | ty::ClauseKind::ConstArgHasType(_, _)
787                    | ty::ClauseKind::WellFormed(_)
788                    | ty::ClauseKind::UnstableFeature(_)
789                    | ty::ClauseKind::ConstEvaluatable(_) => {
790                        ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected non-`Self` predicate when computing `{0:?}` implied bounds: {1:?}",
        filter, clause));bug!(
791                            "unexpected non-`Self` predicate when computing \
792                            `{filter:?}` implied bounds: {clause:?}"
793                        );
794                    }
795                }
796            }
797        }
798        PredicateFilter::SelfTraitThatDefines(_) => {
799            for (clause, _) in bounds {
800                match clause.kind().skip_binder() {
801                    ty::ClauseKind::Trait(trait_predicate) => {
802                        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!(
803                            trait_predicate.self_ty(),
804                            ty,
805                            "expected `Self` predicate when computing \
806                            `{filter:?}` implied bounds: {clause:?}"
807                        );
808                    }
809
810                    ty::ClauseKind::Projection(_)
811                    | ty::ClauseKind::TypeOutlives(_)
812                    | ty::ClauseKind::RegionOutlives(_)
813                    | ty::ClauseKind::ConstArgHasType(_, _)
814                    | ty::ClauseKind::WellFormed(_)
815                    | ty::ClauseKind::ConstEvaluatable(_)
816                    | ty::ClauseKind::UnstableFeature(_)
817                    | ty::ClauseKind::HostEffect(..) => {
818                        ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected non-`Self` predicate when computing `{0:?}` implied bounds: {1:?}",
        filter, clause));bug!(
819                            "unexpected non-`Self` predicate when computing \
820                            `{filter:?}` implied bounds: {clause:?}"
821                        );
822                    }
823                }
824            }
825        }
826        PredicateFilter::ConstIfConst => {
827            for (clause, _) in bounds {
828                match clause.kind().skip_binder() {
829                    ty::ClauseKind::HostEffect(ty::HostEffectPredicate {
830                        trait_ref: _,
831                        constness: ty::BoundConstness::Maybe,
832                    }) => {}
833                    _ => {
834                        ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected non-`HostEffect` predicate when computing `{0:?}` implied bounds: {1:?}",
        filter, clause));bug!(
835                            "unexpected non-`HostEffect` predicate when computing \
836                            `{filter:?}` implied bounds: {clause:?}"
837                        );
838                    }
839                }
840            }
841        }
842        PredicateFilter::SelfConstIfConst => {
843            for (clause, _) in bounds {
844                match clause.kind().skip_binder() {
845                    ty::ClauseKind::HostEffect(pred) => {
846                        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!(
847                            pred.constness,
848                            ty::BoundConstness::Maybe,
849                            "expected `[const]` predicate when computing `{filter:?}` \
850                            implied bounds: {clause:?}",
851                        );
852                        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!(
853                            pred.trait_ref.self_ty(),
854                            ty,
855                            "expected `Self` predicate when computing `{filter:?}` \
856                            implied bounds: {clause:?}"
857                        );
858                    }
859                    _ => {
860                        ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected non-`HostEffect` predicate when computing `{0:?}` implied bounds: {1:?}",
        filter, clause));bug!(
861                            "unexpected non-`HostEffect` predicate when computing \
862                            `{filter:?}` implied bounds: {clause:?}"
863                        );
864                    }
865                }
866            }
867        }
868        PredicateFilter::All | PredicateFilter::SelfAndAssociatedTypeBounds => {}
869    }
870}
871
872/// Returns the predicates defined on `item_def_id` of the form
873/// `X: Foo` where `X` is the type parameter `def_id`.
874#[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(874u32),
                                    ::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))]
875pub(super) fn type_param_predicates<'tcx>(
876    tcx: TyCtxt<'tcx>,
877    (item_def_id, def_id, assoc_ident): (LocalDefId, LocalDefId, Ident),
878) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]> {
879    match tcx.opt_rpitit_info(item_def_id.to_def_id()) {
880        Some(ty::ImplTraitInTraitData::Trait { opaque_def_id, .. }) => {
881            return tcx.type_param_predicates((opaque_def_id.expect_local(), def_id, assoc_ident));
882        }
883        Some(ty::ImplTraitInTraitData::Impl { .. }) => {
884            unreachable!("should not be lowering bounds on RPITIT in impl")
885        }
886        None => {}
887    }
888
889    // In the HIR, bounds can derive from two places. Either
890    // written inline like `<T: Foo>` or in a where-clause like
891    // `where T: Foo`.
892
893    let param_id = tcx.local_def_id_to_hir_id(def_id);
894    let param_owner = tcx.hir_ty_param_owner(def_id);
895
896    // Don't look for bounds where the type parameter isn't in scope.
897    let parent = if item_def_id == param_owner {
898        // FIXME: Shouldn't this be unreachable?
899        None
900    } else {
901        tcx.generics_of(item_def_id).parent.map(|def_id| def_id.expect_local())
902    };
903
904    let result = if let Some(parent) = parent {
905        let icx = ItemCtxt::new(tcx, parent);
906        icx.probe_ty_param_bounds(DUMMY_SP, def_id, assoc_ident)
907    } else {
908        ty::EarlyBinder::bind(&[] as &[_])
909    };
910    let mut extend = None;
911
912    let item_hir_id = tcx.local_def_id_to_hir_id(item_def_id);
913
914    let hir_node = tcx.hir_node(item_hir_id);
915    let Some(hir_generics) = hir_node.generics() else {
916        return result;
917    };
918
919    if let Node::Item(item) = hir_node
920        && let hir::ItemKind::Trait(..) = item.kind
921        // Implied `Self: Trait` and supertrait bounds.
922        && param_id == item_hir_id
923    {
924        let identity_trait_ref = ty::TraitRef::identity(tcx, item_def_id.to_def_id());
925        extend = Some((identity_trait_ref.upcast(tcx), item.span));
926    }
927
928    let icx = ItemCtxt::new(tcx, item_def_id);
929    let extra_predicates = extend.into_iter().chain(icx.probe_ty_param_bounds_in_generics(
930        hir_generics,
931        def_id,
932        PredicateFilter::SelfTraitThatDefines(assoc_ident),
933    ));
934
935    let bounds =
936        &*tcx.arena.alloc_from_iter(result.skip_binder().iter().copied().chain(extra_predicates));
937
938    // Double check that the bounds *only* contain `SelfTy: Trait` preds.
939    let self_ty = match tcx.def_kind(def_id) {
940        DefKind::TyParam => Ty::new_param(
941            tcx,
942            tcx.generics_of(item_def_id)
943                .param_def_id_to_index(tcx, def_id.to_def_id())
944                .expect("expected generic param to be owned by item"),
945            tcx.item_name(def_id.to_def_id()),
946        ),
947        DefKind::Trait | DefKind::TraitAlias => tcx.types.self_param,
948        _ => unreachable!(),
949    };
950    assert_only_contains_predicates_from(
951        PredicateFilter::SelfTraitThatDefines(assoc_ident),
952        bounds,
953        self_ty,
954    );
955
956    ty::EarlyBinder::bind(bounds)
957}
958
959impl<'tcx> ItemCtxt<'tcx> {
960    /// Finds bounds from `hir::Generics`.
961    ///
962    /// This requires scanning through the HIR.
963    /// We do this to avoid having to lower *all* the bounds, which would create artificial cycles.
964    /// Instead, we can only lower the bounds for a type parameter `X` if `X::Foo` is used.
965    #[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(965u32),
                                    ::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))]
966    fn probe_ty_param_bounds_in_generics(
967        &self,
968        hir_generics: &'tcx hir::Generics<'tcx>,
969        param_def_id: LocalDefId,
970        filter: PredicateFilter,
971    ) -> Vec<(ty::Clause<'tcx>, Span)> {
972        let mut bounds = Vec::new();
973
974        for predicate in hir_generics.predicates {
975            let hir_id = predicate.hir_id;
976            let hir::WherePredicateKind::BoundPredicate(predicate) = predicate.kind else {
977                continue;
978            };
979
980            match filter {
981                _ if predicate.is_param_bound(param_def_id.to_def_id()) => {
982                    // Ok
983                }
984                PredicateFilter::All => {
985                    // Ok
986                }
987                PredicateFilter::SelfOnly
988                | PredicateFilter::SelfTraitThatDefines(_)
989                | PredicateFilter::SelfConstIfConst
990                | PredicateFilter::SelfAndAssociatedTypeBounds => continue,
991                PredicateFilter::ConstIfConst => unreachable!(),
992            }
993
994            let bound_ty = self.lowerer().lower_ty_maybe_return_type_notation(predicate.bounded_ty);
995
996            let bound_vars = self.tcx.late_bound_vars(hir_id);
997            self.lowerer().lower_bounds(
998                bound_ty,
999                predicate.bounds,
1000                &mut bounds,
1001                bound_vars,
1002                filter,
1003                OverlappingAsssocItemConstraints::Allowed,
1004            );
1005        }
1006
1007        bounds
1008    }
1009}
1010
1011pub(super) fn const_conditions<'tcx>(
1012    tcx: TyCtxt<'tcx>,
1013    def_id: LocalDefId,
1014) -> ty::ConstConditions<'tcx> {
1015    if !tcx.is_conditionally_const(def_id) {
1016        ::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:?}");
1017    }
1018
1019    match tcx.opt_rpitit_info(def_id.to_def_id()) {
1020        // RPITITs inherit const conditions of their parent fn
1021        Some(
1022            ty::ImplTraitInTraitData::Impl { fn_def_id }
1023            | ty::ImplTraitInTraitData::Trait { fn_def_id, .. },
1024        ) => return tcx.const_conditions(fn_def_id),
1025        None => {}
1026    }
1027
1028    let (generics, trait_def_id_and_supertraits, has_parent) = match tcx.hir_node_by_def_id(def_id)
1029    {
1030        Node::Item(item) => match item.kind {
1031            hir::ItemKind::Impl(impl_) => (impl_.generics, None, false),
1032            hir::ItemKind::Fn { generics, .. } => (generics, None, false),
1033            hir::ItemKind::Trait(_, _, _, _, generics, supertraits, _) => {
1034                (generics, Some((Some(item.owner_id.def_id), supertraits)), false)
1035            }
1036            hir::ItemKind::TraitAlias(_, _, generics, supertraits) => {
1037                (generics, Some((None, supertraits)), false)
1038            }
1039            _ => ::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:?}"),
1040        },
1041        // While associated types are not really const, we do allow them to have `[const]`
1042        // bounds and where clauses. `const_conditions` is responsible for gathering
1043        // these up so we can check them in `compare_type_predicate_entailment`, and
1044        // in `HostEffect` goal computation.
1045        Node::TraitItem(item) => match item.kind {
1046            hir::TraitItemKind::Fn(_, _) | hir::TraitItemKind::Type(_, _) => {
1047                (item.generics, None, true)
1048            }
1049            _ => ::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:?}"),
1050        },
1051        Node::ImplItem(item) => match item.kind {
1052            hir::ImplItemKind::Fn(_, _) | hir::ImplItemKind::Type(_) => {
1053                (item.generics, None, tcx.is_conditionally_const(tcx.local_parent(def_id)))
1054            }
1055            _ => ::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:?}"),
1056        },
1057        Node::ForeignItem(item) => match item.kind {
1058            hir::ForeignItemKind::Fn(_, _, generics) => (generics, None, false),
1059            _ => ::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:?}"),
1060        },
1061        Node::OpaqueTy(opaque) => match opaque.origin {
1062            hir::OpaqueTyOrigin::FnReturn { parent, .. } => return tcx.const_conditions(parent),
1063            hir::OpaqueTyOrigin::AsyncFn { .. } | hir::OpaqueTyOrigin::TyAlias { .. } => {
1064                ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
1065            }
1066        },
1067        // N.B. Tuple ctors are unconditionally constant.
1068        Node::Ctor(hir::VariantData::Tuple { .. }) => return Default::default(),
1069        _ => ::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:?}"),
1070    };
1071
1072    let icx = ItemCtxt::new(tcx, def_id);
1073    let mut bounds = Vec::new();
1074
1075    for pred in generics.predicates {
1076        match pred.kind {
1077            hir::WherePredicateKind::BoundPredicate(bound_pred) => {
1078                let ty = icx.lowerer().lower_ty_maybe_return_type_notation(bound_pred.bounded_ty);
1079                let bound_vars = tcx.late_bound_vars(pred.hir_id);
1080                icx.lowerer().lower_bounds(
1081                    ty,
1082                    bound_pred.bounds.iter(),
1083                    &mut bounds,
1084                    bound_vars,
1085                    PredicateFilter::ConstIfConst,
1086                    OverlappingAsssocItemConstraints::Allowed,
1087                );
1088            }
1089            _ => {}
1090        }
1091    }
1092
1093    if let Some((def_id, supertraits)) = trait_def_id_and_supertraits {
1094        if let Some(def_id) = def_id {
1095            // We've checked above that the trait is conditionally const.
1096            bounds.push((
1097                ty::Binder::dummy(ty::TraitRef::identity(tcx, def_id.to_def_id()))
1098                    .to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1099                DUMMY_SP,
1100            ));
1101        }
1102
1103        icx.lowerer().lower_bounds(
1104            tcx.types.self_param,
1105            supertraits,
1106            &mut bounds,
1107            ty::List::empty(),
1108            PredicateFilter::ConstIfConst,
1109            OverlappingAsssocItemConstraints::Allowed,
1110        );
1111    }
1112
1113    ty::ConstConditions {
1114        parent: has_parent.then(|| tcx.local_parent(def_id).to_def_id()),
1115        predicates: tcx.arena.alloc_from_iter(bounds.into_iter().map(|(clause, span)| {
1116            (
1117                clause.kind().map_bound(|clause| match clause {
1118                    ty::ClauseKind::HostEffect(ty::HostEffectPredicate {
1119                        trait_ref,
1120                        constness: ty::BoundConstness::Maybe,
1121                    }) => trait_ref,
1122                    _ => ::rustc_middle::util::bug::bug_fmt(format_args!("converted {0:?}", clause))bug!("converted {clause:?}"),
1123                }),
1124                span,
1125            )
1126        })),
1127    }
1128}
1129
1130pub(super) fn explicit_implied_const_bounds<'tcx>(
1131    tcx: TyCtxt<'tcx>,
1132    def_id: LocalDefId,
1133) -> ty::EarlyBinder<'tcx, &'tcx [(ty::PolyTraitRef<'tcx>, Span)]> {
1134    if !tcx.is_conditionally_const(def_id) {
1135        ::rustc_middle::util::bug::bug_fmt(format_args!("explicit_implied_const_bounds invoked for item that is not conditionally const: {0:?}",
        def_id));bug!(
1136            "explicit_implied_const_bounds invoked for item that is not conditionally const: {def_id:?}"
1137        );
1138    }
1139
1140    let bounds = match tcx.opt_rpitit_info(def_id.to_def_id()) {
1141        // RPITIT's bounds are the same as opaque type bounds, but with
1142        // a projection self type.
1143        Some(ty::ImplTraitInTraitData::Trait { .. }) => {
1144            explicit_item_bounds_with_filter(tcx, def_id, PredicateFilter::ConstIfConst)
1145        }
1146        Some(ty::ImplTraitInTraitData::Impl { .. }) => {
1147            ::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")
1148        }
1149        None => match tcx.hir_node_by_def_id(def_id) {
1150            Node::Item(hir::Item {
1151                kind: hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..),
1152                ..
1153            }) => implied_predicates_with_filter(
1154                tcx,
1155                def_id.to_def_id(),
1156                PredicateFilter::SelfConstIfConst,
1157            ),
1158            Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Type(..), .. })
1159            | Node::OpaqueTy(_) => {
1160                explicit_item_bounds_with_filter(tcx, def_id, PredicateFilter::ConstIfConst)
1161            }
1162            _ => ::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:?}"),
1163        },
1164    };
1165
1166    bounds.map_bound(|bounds| {
1167        &*tcx.arena.alloc_from_iter(bounds.iter().copied().map(|(clause, span)| {
1168            (
1169                clause.kind().map_bound(|clause| match clause {
1170                    ty::ClauseKind::HostEffect(ty::HostEffectPredicate {
1171                        trait_ref,
1172                        constness: ty::BoundConstness::Maybe,
1173                    }) => trait_ref,
1174                    _ => ::rustc_middle::util::bug::bug_fmt(format_args!("converted {0:?}", clause))bug!("converted {clause:?}"),
1175                }),
1176                span,
1177            )
1178        }))
1179    })
1180}