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