Skip to main content

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