Skip to main content

rustc_hir_analysis/collect/
item_bounds.rs

1use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
2use rustc_hir as hir;
3use rustc_infer::traits::util;
4use rustc_middle::ty::{
5    self, GenericArgs, PredicateProxy, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable,
6    TypeVisitableExt, Upcast, shift_vars,
7};
8use rustc_span::def_id::{DefId, LocalDefId};
9use rustc_span::{Span, bug, span_bug};
10use tracing::{debug, instrument};
11
12use super::ItemCtxt;
13use super::clauses_of::assert_only_contains_clauses_from;
14use crate::hir_ty_lowering::{
15    HirTyLowerer, ImpliedBoundsContext, OverlappingAsssocItemConstraints, PredicateFilter,
16};
17
18/// For associated types we include both bounds written on the type
19/// (`type X: Trait`) and predicates from the trait: `where Self::X: Trait`.
20///
21/// Note that this filtering is done with the items identity args to
22/// simplify checking that these bounds are met in impls. This means that
23/// a bound such as `for<'b> <Self as X<'b>>::U: Clone` can't be used, as in
24/// `hr-associated-type-bound-1.rs`.
25fn associated_type_bounds<'tcx>(
26    tcx: TyCtxt<'tcx>,
27    assoc_item_def_id: LocalDefId,
28    hir_bounds: &'tcx [hir::GenericBound<'tcx>],
29    span: Span,
30    filter: PredicateFilter,
31) -> &'tcx [(ty::Clause<'tcx>, Span)] {
32    {
    let _guard = ReducedQueriesGuard::new();
    {
        let item_ty =
            Ty::new_projection_from_args(tcx, ty::IsRigid::No,
                assoc_item_def_id.to_def_id(),
                GenericArgs::identity_for_item(tcx, assoc_item_def_id));
        let icx = ItemCtxt::new(tcx, assoc_item_def_id);
        let mut bounds = Vec::new();
        icx.lowerer().lower_bounds(item_ty, hir_bounds, &mut bounds,
            ty::List::empty(), filter,
            OverlappingAsssocItemConstraints::Allowed);
        match filter {
            PredicateFilter::All | PredicateFilter::SelfOnly |
                PredicateFilter::SelfTraitThatDefines(_) |
                PredicateFilter::SelfAndAssociatedTypeBounds => {
                icx.lowerer().add_implicit_sizedness_bounds(&mut bounds,
                    item_ty, hir_bounds,
                    ImpliedBoundsContext::AssociatedTypeOrImplTrait, span);
                icx.lowerer().add_default_traits(&mut bounds, item_ty,
                    hir_bounds, ImpliedBoundsContext::AssociatedTypeOrImplTrait,
                    span);
                let trait_def_id = tcx.local_parent(assoc_item_def_id);
                let trait_clauses =
                    tcx.trait_explicit_clauses_and_bounds(trait_def_id);
                let item_trait_ref =
                    ty::TraitRef::identity(tcx,
                        tcx.parent(assoc_item_def_id.to_def_id()));
                bounds.extend(trait_clauses.clauses.iter().copied().filter_map(|(clause,
                                span)|
                            {
                                remap_gat_vars_and_recurse_into_nested_projections(tcx,
                                    filter, item_trait_ref, assoc_item_def_id, span, clause)
                            }));
            }
            PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst
                => {}
        }
        let bounds = tcx.arena.alloc_from_iter(bounds);
        {
            use ::tracing::__macro_support::Callsite as _;
            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                {
                    static META: ::tracing::Metadata<'static> =
                        {
                            ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/item_bounds.rs:104",
                                "rustc_hir_analysis::collect::item_bounds",
                                ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/item_bounds.rs"),
                                ::tracing_core::__macro_support::Option::Some(104u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::item_bounds"),
                                ::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!("associated_type_bounds({0}) = {1:?}",
                                                            tcx.def_path_str(assoc_item_def_id.to_def_id()), bounds) as
                                                    &dyn ::tracing::field::Value))])
                    });
            } else { ; }
        };
        assert_only_contains_clauses_from(filter, bounds, item_ty);
        bounds
    }
}ty::print::with_reduced_queries!({
33        let item_ty = Ty::new_projection_from_args(
34            tcx,
35            ty::IsRigid::No,
36            assoc_item_def_id.to_def_id(),
37            GenericArgs::identity_for_item(tcx, assoc_item_def_id),
38        );
39
40        let icx = ItemCtxt::new(tcx, assoc_item_def_id);
41        let mut bounds = Vec::new();
42        icx.lowerer().lower_bounds(
43            item_ty,
44            hir_bounds,
45            &mut bounds,
46            ty::List::empty(),
47            filter,
48            OverlappingAsssocItemConstraints::Allowed,
49        );
50
51        match filter {
52            PredicateFilter::All
53            | PredicateFilter::SelfOnly
54            | PredicateFilter::SelfTraitThatDefines(_)
55            | PredicateFilter::SelfAndAssociatedTypeBounds => {
56                // Implicit bounds are added to associated types unless a `?Trait` bound is found.
57                icx.lowerer().add_implicit_sizedness_bounds(
58                    &mut bounds,
59                    item_ty,
60                    hir_bounds,
61                    ImpliedBoundsContext::AssociatedTypeOrImplTrait,
62                    span,
63                );
64                icx.lowerer().add_default_traits(
65                    &mut bounds,
66                    item_ty,
67                    hir_bounds,
68                    ImpliedBoundsContext::AssociatedTypeOrImplTrait,
69                    span,
70                );
71
72                // Also collect `where Self::Assoc: Trait` from the parent trait's where clauses.
73                let trait_def_id = tcx.local_parent(assoc_item_def_id);
74                let trait_clauses = tcx.trait_explicit_clauses_and_bounds(trait_def_id);
75
76                let item_trait_ref =
77                    ty::TraitRef::identity(tcx, tcx.parent(assoc_item_def_id.to_def_id()));
78                bounds.extend(trait_clauses.clauses.iter().copied().filter_map(
79                    |(clause, span)| {
80                        remap_gat_vars_and_recurse_into_nested_projections(
81                            tcx,
82                            filter,
83                            item_trait_ref,
84                            assoc_item_def_id,
85                            span,
86                            clause,
87                        )
88                    },
89                ));
90            }
91            // `ConstIfConst` is only interested in `[const]` bounds.
92            PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {
93                // FIXME(const_trait_impl): We *could* uplift the
94                // `where Self::Assoc: [const] Trait` bounds from the parent trait
95                // here too, but we'd need to split `const_conditions` into two
96                // queries (like we do for `trait_explicit_clauses_and_bounds`)
97                // since we need to also filter the clauses *out* of the const
98                // conditions or they lead to cycles in the trait solver when
99                // utilizing these bounds. For now, let's do nothing.
100            }
101        }
102
103        let bounds = tcx.arena.alloc_from_iter(bounds);
104        debug!(
105            "associated_type_bounds({}) = {:?}",
106            tcx.def_path_str(assoc_item_def_id.to_def_id()),
107            bounds
108        );
109
110        assert_only_contains_clauses_from(filter, bounds, item_ty);
111
112        bounds
113    })
114}
115
116/// The code below is quite involved, so let me explain.
117///
118/// We loop here, because we also want to collect vars for nested associated items as
119/// well. For example, given a clause like `Self::A::B`, we want to add that to the
120/// item bounds for `A`, so that we may use that bound in the case that `Self::A::B` is
121/// rigid.
122///
123/// Secondly, regarding bound vars, when we see a where clause that mentions a GAT
124/// like `for<'a, ...> Self::Assoc<'a, ...>: Bound<'b, ...>`, we want to turn that into
125/// an item bound on the GAT, where all of the GAT args are substituted with the GAT's
126/// param regions, and then keep all of the other late-bound vars in the bound around.
127/// We need to "compress" the binder so that it doesn't mention any of those vars that
128/// were mapped to params.
129fn remap_gat_vars_and_recurse_into_nested_projections<'tcx>(
130    tcx: TyCtxt<'tcx>,
131    filter: PredicateFilter,
132    item_trait_ref: ty::TraitRef<'tcx>,
133    assoc_item_def_id: LocalDefId,
134    span: Span,
135    clause: ty::Clause<'tcx>,
136) -> Option<(ty::Clause<'tcx>, Span)> {
137    let mut clause_ty = match clause.kind().skip_binder() {
138        ty::ClauseKind::Trait(tr) => tr.self_ty(),
139        ty::ClauseKind::Projection(proj) => proj.projection_term.self_ty(),
140        ty::ClauseKind::TypeOutlives(outlives) => outlives.0,
141        ty::ClauseKind::HostEffect(host) => host.self_ty(),
142        _ => return None,
143    };
144
145    let gat_vars = loop {
146        if let ty::Alias(
147            _,
148            alias_ty @ ty::AliasTy { kind: ty::Projection { def_id: alias_ty_def_id }, .. },
149        ) = *clause_ty.kind()
150        {
151            if alias_ty.trait_ref(tcx) == item_trait_ref
152                && alias_ty_def_id == assoc_item_def_id.to_def_id()
153            {
154                // We have found the GAT in question...
155                // Return the vars, since we may need to remap them.
156                break &alias_ty.args[item_trait_ref.args.len()..];
157            } else {
158                // Only collect *self* type bounds if the filter is for self.
159                match filter {
160                    PredicateFilter::All => {}
161                    PredicateFilter::SelfOnly => {
162                        return None;
163                    }
164                    PredicateFilter::SelfTraitThatDefines(_)
165                    | PredicateFilter::SelfConstIfConst
166                    | PredicateFilter::SelfAndAssociatedTypeBounds
167                    | PredicateFilter::ConstIfConst => {
168                        {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("invalid predicate filter for `remap_gat_vars_and_recurse_into_nested_projections`")));
}unreachable!(
169                            "invalid predicate filter for \
170                            `remap_gat_vars_and_recurse_into_nested_projections`"
171                        )
172                    }
173                }
174
175                clause_ty = alias_ty.self_ty();
176                continue;
177            }
178        }
179
180        return None;
181    };
182
183    // Special-case: No GAT vars, no mapping needed.
184    if gat_vars.is_empty() {
185        return Some((clause, span));
186    }
187
188    // First, check that all of the GAT args are substituted with a unique late-bound arg.
189    // If we find a duplicate, then it can't be mapped to the definition's params.
190    let mut mapping = FxIndexMap::default();
191    let generics = tcx.generics_of(assoc_item_def_id);
192    for (param, var) in std::iter::zip(&generics.own_params, gat_vars) {
193        let existing = match var.kind() {
194            ty::GenericArgKind::Lifetime(re) => {
195                let ty::RegionKind::ReBound(ty::BoundVarIndexKind::Bound(ty::INNERMOST), bv) =
196                    re.kind()
197                else {
198                    return None;
199                };
200                mapping.insert(bv.var, tcx.mk_param_from_def(param))
201            }
202            ty::GenericArgKind::Type(ty) => {
203                let ty::Bound(ty::BoundVarIndexKind::Bound(ty::INNERMOST), bv) = *ty.kind() else {
204                    return None;
205                };
206                mapping.insert(bv.var, tcx.mk_param_from_def(param))
207            }
208            ty::GenericArgKind::Const(ct) => {
209                let ty::ConstKind::Bound(ty::BoundVarIndexKind::Bound(ty::INNERMOST), bv) =
210                    ct.kind()
211                else {
212                    return None;
213                };
214                mapping.insert(bv.var, tcx.mk_param_from_def(param))
215            }
216        };
217
218        if existing.is_some() {
219            return None;
220        }
221    }
222
223    // Finally, map all of the args in the GAT to the params we expect, and compress
224    // the remaining late-bound vars so that they count up from var 0.
225    let mut folder =
226        MapAndCompressBoundVars { tcx, binder: ty::INNERMOST, still_bound_vars: ::alloc::vec::Vec::new()vec![], mapping };
227    let pred = clause.kind().skip_binder().fold_with(&mut folder);
228
229    Some((
230        ty::Binder::bind_with_vars(pred, tcx.mk_bound_variable_kinds(&folder.still_bound_vars))
231            .upcast(tcx),
232        span,
233    ))
234}
235
236/// Given some where clause like `for<'b, 'c> <Self as Trait<'a_identity>>::Gat<'b>: Bound<'c>`,
237/// the mapping will map `'b` back to the GAT's `'b_identity`. Then we need to compress the
238/// remaining bound var `'c` to index 0.
239///
240/// This folder gives us: `for<'c> <Self as Trait<'a_identity>>::Gat<'b_identity>: Bound<'c>`,
241/// which is sufficient for an item bound for `Gat`, since all of the GAT's args are identity.
242struct MapAndCompressBoundVars<'tcx> {
243    tcx: TyCtxt<'tcx>,
244    /// How deep are we? Makes sure we don't touch the vars of nested binders.
245    binder: ty::DebruijnIndex,
246    /// List of bound vars that remain unsubstituted because they were not
247    /// mentioned in the GAT's args.
248    still_bound_vars: Vec<ty::BoundVariableKind<'tcx>>,
249    /// Subtle invariant: If the `GenericArg` is bound, then it should be
250    /// stored with the debruijn index of `INNERMOST` so it can be shifted
251    /// correctly during substitution.
252    mapping: FxIndexMap<ty::BoundVar, ty::GenericArg<'tcx>>,
253}
254
255impl<'tcx> TypeFolder<TyCtxt<'tcx>> for MapAndCompressBoundVars<'tcx> {
256    fn cx(&self) -> TyCtxt<'tcx> {
257        self.tcx
258    }
259
260    fn fold_binder<T>(&mut self, t: ty::Binder<'tcx, T>) -> ty::Binder<'tcx, T>
261    where
262        ty::Binder<'tcx, T>: TypeSuperFoldable<TyCtxt<'tcx>>,
263    {
264        self.binder.shift_in(1);
265        let out = t.super_fold_with(self);
266        self.binder.shift_out(1);
267        out
268    }
269
270    fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
271        if !ty.has_bound_vars() {
272            return ty;
273        }
274
275        if let ty::Bound(ty::BoundVarIndexKind::Bound(binder), old_bound) = *ty.kind()
276            && self.binder == binder
277        {
278            let mapped = if let Some(mapped) = self.mapping.get(&old_bound.var) {
279                mapped.expect_ty()
280            } else {
281                // If we didn't find a mapped generic, then make a new one.
282                // Allocate a new var idx, and insert a new bound ty.
283                let var = ty::BoundVar::from_usize(self.still_bound_vars.len());
284                self.still_bound_vars.push(ty::BoundVariableKind::Ty(old_bound.kind));
285                let mapped = Ty::new_bound(
286                    self.tcx,
287                    ty::INNERMOST,
288                    ty::BoundTy { var, kind: old_bound.kind },
289                );
290                self.mapping.insert(old_bound.var, mapped.into());
291                mapped
292            };
293
294            shift_vars(self.tcx, mapped, self.binder.as_u32())
295        } else {
296            ty.super_fold_with(self)
297        }
298    }
299
300    fn fold_region(&mut self, re: ty::Region<'tcx>) -> ty::Region<'tcx> {
301        if let ty::ReBound(ty::BoundVarIndexKind::Bound(binder), old_bound) = re.kind()
302            && self.binder == binder
303        {
304            let mapped = if let Some(mapped) = self.mapping.get(&old_bound.var) {
305                mapped.expect_region()
306            } else {
307                let var = ty::BoundVar::from_usize(self.still_bound_vars.len());
308                self.still_bound_vars.push(ty::BoundVariableKind::Region(old_bound.kind));
309                let mapped = ty::Region::new_bound(
310                    self.tcx,
311                    ty::INNERMOST,
312                    ty::BoundRegion { var, kind: old_bound.kind },
313                );
314                self.mapping.insert(old_bound.var, mapped.into());
315                mapped
316            };
317
318            shift_vars(self.tcx, mapped, self.binder.as_u32())
319        } else {
320            re
321        }
322    }
323
324    fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
325        if !ct.has_bound_vars() {
326            return ct;
327        }
328
329        if let ty::ConstKind::Bound(ty::BoundVarIndexKind::Bound(binder), old_bound) = ct.kind()
330            && self.binder == binder
331        {
332            let mapped = if let Some(mapped) = self.mapping.get(&old_bound.var) {
333                mapped.expect_const()
334            } else {
335                let var = ty::BoundVar::from_usize(self.still_bound_vars.len());
336                self.still_bound_vars.push(ty::BoundVariableKind::Const);
337                let mapped =
338                    ty::Const::new_bound(self.tcx, ty::INNERMOST, ty::BoundConst::new(var));
339                self.mapping.insert(old_bound.var, mapped.into());
340                mapped
341            };
342
343            shift_vars(self.tcx, mapped, self.binder.as_u32())
344        } else {
345            ct.super_fold_with(self)
346        }
347    }
348
349    fn fold_predicate<P: PredicateProxy<TyCtxt<'tcx>>>(&mut self, p: P) -> P {
350        if !p.has_bound_vars() { p } else { p.super_fold_with(self) }
351    }
352}
353
354/// Opaque types don't inherit bounds from their parent: for return position
355/// impl trait it isn't possible to write a suitable predicate on the
356/// containing function and for type-alias impl trait we don't have a backwards
357/// compatibility issue.
358{}
#[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("opaque_type_bounds",
                                    "rustc_hir_analysis::collect::item_bounds",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/item_bounds.rs"),
                                    ::tracing_core::__macro_support::Option::Some(358u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::item_bounds"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("opaque_def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("opaque_def_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("hir_bounds")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("hir_bounds");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("span");
                                                        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(&opaque_def_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&hir_bounds)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            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: &'tcx [(ty::Clause<'tcx>, Span)] =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            {
                let _guard = ReducedQueriesGuard::new();
                {
                    let icx = ItemCtxt::new(tcx, opaque_def_id);
                    let mut bounds = Vec::new();
                    icx.lowerer().lower_bounds(item_ty, hir_bounds, &mut bounds,
                        ty::List::empty(), filter,
                        OverlappingAsssocItemConstraints::Allowed);
                    match filter {
                        PredicateFilter::All | PredicateFilter::SelfOnly |
                            PredicateFilter::SelfTraitThatDefines(_) |
                            PredicateFilter::SelfAndAssociatedTypeBounds => {
                            icx.lowerer().add_implicit_sizedness_bounds(&mut bounds,
                                item_ty, hir_bounds,
                                ImpliedBoundsContext::AssociatedTypeOrImplTrait, span);
                            icx.lowerer().add_default_traits(&mut bounds, item_ty,
                                hir_bounds, ImpliedBoundsContext::AssociatedTypeOrImplTrait,
                                span);
                        }
                        PredicateFilter::ConstIfConst |
                            PredicateFilter::SelfConstIfConst => {}
                    }
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/item_bounds.rs:402",
                                            "rustc_hir_analysis::collect::item_bounds",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/collect/item_bounds.rs"),
                                            ::tracing_core::__macro_support::Option::Some(402u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect::item_bounds"),
                                            ::tracing_core::field::FieldSet::new(&[{
                                                                const NAME:
                                                                    ::tracing::__macro_support::FieldName<{
                                                                        ::tracing::__macro_support::FieldName::len("bounds")
                                                                    }> =
                                                                    ::tracing::__macro_support::FieldName::new("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(&bounds)
                                                                as &dyn ::tracing::field::Value))])
                                });
                        } else { ; }
                    };
                    tcx.arena.alloc_slice(&bounds)
                }
            }
        }
    }
}#[instrument(level = "trace", skip(tcx, item_ty))]
359fn opaque_type_bounds<'tcx>(
360    tcx: TyCtxt<'tcx>,
361    opaque_def_id: LocalDefId,
362    hir_bounds: &'tcx [hir::GenericBound<'tcx>],
363    item_ty: Ty<'tcx>,
364    span: Span,
365    filter: PredicateFilter,
366) -> &'tcx [(ty::Clause<'tcx>, Span)] {
367    ty::print::with_reduced_queries!({
368        let icx = ItemCtxt::new(tcx, opaque_def_id);
369        let mut bounds = Vec::new();
370        icx.lowerer().lower_bounds(
371            item_ty,
372            hir_bounds,
373            &mut bounds,
374            ty::List::empty(),
375            filter,
376            OverlappingAsssocItemConstraints::Allowed,
377        );
378        // Implicit bounds are added to opaque types unless a `?Trait` bound is found
379        match filter {
380            PredicateFilter::All
381            | PredicateFilter::SelfOnly
382            | PredicateFilter::SelfTraitThatDefines(_)
383            | PredicateFilter::SelfAndAssociatedTypeBounds => {
384                icx.lowerer().add_implicit_sizedness_bounds(
385                    &mut bounds,
386                    item_ty,
387                    hir_bounds,
388                    ImpliedBoundsContext::AssociatedTypeOrImplTrait,
389                    span,
390                );
391                icx.lowerer().add_default_traits(
392                    &mut bounds,
393                    item_ty,
394                    hir_bounds,
395                    ImpliedBoundsContext::AssociatedTypeOrImplTrait,
396                    span,
397                );
398            }
399            //`ConstIfConst` is only interested in `[const]` bounds.
400            PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {}
401        }
402        debug!(?bounds);
403
404        tcx.arena.alloc_slice(&bounds)
405    })
406}
407
408pub(super) fn explicit_item_bounds(
409    tcx: TyCtxt<'_>,
410    def_id: LocalDefId,
411) -> ty::EarlyBinder<'_, &'_ [(ty::Clause<'_>, Span)]> {
412    explicit_item_bounds_with_filter(tcx, def_id, PredicateFilter::All)
413}
414
415pub(super) fn explicit_item_self_bounds(
416    tcx: TyCtxt<'_>,
417    def_id: LocalDefId,
418) -> ty::EarlyBinder<'_, &'_ [(ty::Clause<'_>, Span)]> {
419    explicit_item_bounds_with_filter(tcx, def_id, PredicateFilter::SelfOnly)
420}
421
422pub(super) fn explicit_item_bounds_with_filter(
423    tcx: TyCtxt<'_>,
424    def_id: LocalDefId,
425    filter: PredicateFilter,
426) -> ty::EarlyBinder<'_, &'_ [(ty::Clause<'_>, Span)]> {
427    match tcx.opt_rpitit_info(def_id.to_def_id()) {
428        // RPITIT's bounds are the same as opaque type bounds, but with
429        // a projection self type.
430        Some(ty::ImplTraitInTraitData::Trait { opaque_def_id, .. }) => {
431            let opaque_ty = tcx.hir_node_by_def_id(opaque_def_id.expect_local()).expect_opaque_ty();
432            let bounds =
433                associated_type_bounds(tcx, def_id, opaque_ty.bounds, opaque_ty.span, filter);
434            return ty::EarlyBinder::bind_iter(bounds);
435        }
436        Some(ty::ImplTraitInTraitData::Impl { .. }) => {
437            bug_impl(Some(tcx.def_span(def_id)),
    format_args!("RPITIT in impl should not have item bounds"),
    Location::caller())span_bug!(tcx.def_span(def_id), "RPITIT in impl should not have item bounds")
438        }
439        None => {}
440    }
441
442    let bounds = match tcx.hir_node_by_def_id(def_id) {
443        hir::Node::TraitItem(hir::TraitItem {
444            kind: hir::TraitItemKind::Type(bounds, _),
445            span,
446            ..
447        }) => associated_type_bounds(tcx, def_id, bounds, *span, filter),
448        hir::Node::OpaqueTy(hir::OpaqueTy { bounds, origin, span, .. }) => match origin {
449            // Since RPITITs are lowered as projections in `<dyn HirTyLowerer>::lower_ty`,
450            // when we're asking for the item bounds of the *opaques* in a trait's default
451            // method signature, we need to map these projections back to opaques.
452            rustc_hir::OpaqueTyOrigin::FnReturn {
453                parent,
454                in_trait_or_impl: Some(hir::RpitContext::Trait),
455            }
456            | rustc_hir::OpaqueTyOrigin::AsyncFn {
457                parent,
458                in_trait_or_impl: Some(hir::RpitContext::Trait),
459            } => {
460                let args = GenericArgs::identity_for_item(tcx, def_id);
461                let item_ty = Ty::new_opaque(tcx, ty::IsRigid::No, def_id.to_def_id(), args);
462                let bounds = &*tcx.arena.alloc_slice(
463                    &opaque_type_bounds(tcx, def_id, bounds, item_ty, *span, filter)
464                        .to_vec()
465                        .fold_with(&mut AssocTyToOpaque { tcx, fn_def_id: parent.to_def_id() }),
466                );
467                assert_only_contains_clauses_from(filter, bounds, item_ty);
468                bounds
469            }
470            rustc_hir::OpaqueTyOrigin::FnReturn {
471                parent: _,
472                in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
473            }
474            | rustc_hir::OpaqueTyOrigin::AsyncFn {
475                parent: _,
476                in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
477            }
478            | rustc_hir::OpaqueTyOrigin::TyAlias { parent: _, .. } => {
479                let args = GenericArgs::identity_for_item(tcx, def_id);
480                let item_ty = Ty::new_opaque(tcx, ty::IsRigid::No, def_id.to_def_id(), args);
481                let bounds = opaque_type_bounds(tcx, def_id, bounds, item_ty, *span, filter);
482                assert_only_contains_clauses_from(filter, bounds, item_ty);
483                bounds
484            }
485        },
486        hir::Node::Item(hir::Item { kind: hir::ItemKind::TyAlias(..), .. }) => &[],
487        node => bug_impl(None,
    format_args!("item_bounds called on {0:?} => {1:?}", def_id, node),
    Location::caller())bug!("item_bounds called on {def_id:?} => {node:?}"),
488    };
489
490    ty::EarlyBinder::bind_iter(bounds)
491}
492
493pub(super) fn item_bounds(tcx: TyCtxt<'_>, def_id: DefId) -> ty::EarlyBinder<'_, ty::Clauses<'_>> {
494    tcx.explicit_item_bounds(def_id).map_bound(|bounds| {
495        tcx.mk_clauses_from_iter(util::elaborate(tcx, bounds.iter().map(|&(bound, _span)| bound)))
496    })
497}
498
499pub(super) fn item_self_bounds(
500    tcx: TyCtxt<'_>,
501    def_id: DefId,
502) -> ty::EarlyBinder<'_, ty::Clauses<'_>> {
503    tcx.explicit_item_self_bounds(def_id).map_bound(|bounds| {
504        tcx.mk_clauses_from_iter(
505            util::elaborate(tcx, bounds.iter().map(|&(bound, _span)| bound)).filter_only_self(),
506        )
507    })
508}
509
510/// This exists as an optimization to compute only the item bounds of the item
511/// that are not `Self` bounds.
512pub(super) fn item_non_self_bounds(
513    tcx: TyCtxt<'_>,
514    def_id: DefId,
515) -> ty::EarlyBinder<'_, ty::Clauses<'_>> {
516    let all_bounds: FxIndexSet<_> = tcx.item_bounds(def_id).skip_binder().iter().collect();
517    let own_bounds: FxIndexSet<_> = tcx.item_self_bounds(def_id).skip_binder().iter().collect();
518    if all_bounds.len() == own_bounds.len() {
519        ty::EarlyBinder::bind(tcx, ty::ListWithCachedTypeInfo::empty())
520    } else {
521        ty::EarlyBinder::bind(
522            tcx,
523            tcx.mk_clauses_from_iter(all_bounds.difference(&own_bounds).copied()),
524        )
525    }
526}
527
528/// This exists as an optimization to compute only the supertraits of this impl's
529/// trait that are outlives bounds.
530pub(super) fn impl_super_outlives(
531    tcx: TyCtxt<'_>,
532    def_id: DefId,
533) -> ty::EarlyBinder<'_, ty::Clauses<'_>> {
534    tcx.impl_trait_header(def_id).trait_ref.map_bound(|trait_ref| {
535        let clause: ty::Clause<'_> = trait_ref.upcast(tcx);
536        tcx.mk_clauses_from_iter(util::elaborate(tcx, [clause]).filter(|clause| {
537            #[allow(non_exhaustive_omitted_patterns)] match clause.kind().skip_binder() {
    ty::ClauseKind::TypeOutlives(_) | ty::ClauseKind::RegionOutlives(_) =>
        true,
    _ => false,
}matches!(
538                clause.kind().skip_binder(),
539                ty::ClauseKind::TypeOutlives(_) | ty::ClauseKind::RegionOutlives(_)
540            )
541        }))
542    })
543}
544
545struct AssocTyToOpaque<'tcx> {
546    tcx: TyCtxt<'tcx>,
547    fn_def_id: DefId,
548}
549
550impl<'tcx> TypeFolder<TyCtxt<'tcx>> for AssocTyToOpaque<'tcx> {
551    fn cx(&self) -> TyCtxt<'tcx> {
552        self.tcx
553    }
554
555    fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
556        if let &ty::Alias(
557            _,
558            ty::AliasTy { kind: ty::Projection { def_id: projection_ty_def_id }, args, .. },
559        ) = ty.kind()
560            && let Some(ty::ImplTraitInTraitData::Trait { fn_def_id, .. }) =
561                self.tcx.opt_rpitit_info(projection_ty_def_id)
562            && fn_def_id == self.fn_def_id
563        {
564            self.tcx.type_of(projection_ty_def_id).instantiate(self.tcx, args).skip_norm_wip()
565        } else {
566            ty.super_fold_with(self)
567        }
568    }
569}