Skip to main content

rustc_hir_analysis/hir_ty_lowering/
bounds.rs

1use std::ops::ControlFlow;
2
3use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
4use rustc_errors::codes::*;
5use rustc_errors::struct_span_code_err;
6use rustc_hir as hir;
7use rustc_hir::def::{DefKind, Res};
8use rustc_hir::def_id::DefId;
9use rustc_hir::{PolyTraitRef, find_attr};
10use rustc_middle::bug;
11use rustc_middle::ty::{
12    self as ty, IsSuggestable, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt,
13    TypeVisitor, Upcast,
14};
15use rustc_span::{ErrorGuaranteed, Ident, Span, kw};
16use rustc_trait_selection::traits;
17use tracing::{debug, instrument};
18
19use crate::diagnostics;
20use crate::hir_ty_lowering::{
21    AssocItemQSelf, GenericsArgsErrExtend, HirTyLowerer, ImpliedBoundsContext,
22    OverlappingAsssocItemConstraints, PredicateFilter, RegionInferReason,
23};
24
25#[derive(#[automatically_derived]
impl ::core::fmt::Debug for CollectedBound {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "CollectedBound", "positive", &self.positive, "maybe",
            &self.maybe, "negative", &&self.negative)
    }
}Debug, #[automatically_derived]
impl ::core::default::Default for CollectedBound {
    #[inline]
    fn default() -> CollectedBound {
        CollectedBound {
            positive: ::core::default::Default::default(),
            maybe: ::core::default::Default::default(),
            negative: ::core::default::Default::default(),
        }
    }
}Default)]
26struct CollectedBound {
27    /// `Trait`
28    positive: Option<Span>,
29    /// `?Trait`
30    maybe: Option<Span>,
31    /// `!Trait`
32    negative: Option<Span>,
33}
34
35impl CollectedBound {
36    /// Returns `true` if any of `Trait`, `?Trait` or `!Trait` were encountered.
37    fn any(&self) -> bool {
38        self.positive.is_some() || self.maybe.is_some() || self.negative.is_some()
39    }
40}
41
42#[derive(#[automatically_derived]
impl ::core::fmt::Debug for CollectedSizednessBounds {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "CollectedSizednessBounds", "sized", &self.sized, "meta_sized",
            &self.meta_sized, "pointee_sized", &&self.pointee_sized)
    }
}Debug)]
43struct CollectedSizednessBounds {
44    // Collected `Sized` bounds
45    sized: CollectedBound,
46    // Collected `MetaSized` bounds
47    meta_sized: CollectedBound,
48    // Collected `PointeeSized` bounds
49    pointee_sized: CollectedBound,
50}
51
52impl CollectedSizednessBounds {
53    /// Returns `true` if any of `Trait`, `?Trait` or `!Trait` were encountered for `Sized`,
54    /// `MetaSized` or `PointeeSized`.
55    fn any(&self) -> bool {
56        self.sized.any() || self.meta_sized.any() || self.pointee_sized.any()
57    }
58}
59
60fn search_bounds_for<'tcx>(
61    hir_bounds: &'tcx [hir::GenericBound<'tcx>],
62    context: ImpliedBoundsContext<'tcx>,
63    mut f: impl FnMut(&'tcx PolyTraitRef<'tcx>),
64) {
65    let mut search_bounds = |hir_bounds: &'tcx [hir::GenericBound<'tcx>]| {
66        for hir_bound in hir_bounds {
67            let hir::GenericBound::Trait(ptr) = hir_bound else {
68                continue;
69            };
70
71            f(ptr)
72        }
73    };
74
75    search_bounds(hir_bounds);
76    if let ImpliedBoundsContext::TyParam(self_ty, where_clause) = context {
77        for clause in where_clause {
78            if let hir::WherePredicateKind::BoundPredicate(pred) = clause.kind
79                && pred.is_param_bound(self_ty.to_def_id())
80            {
81                search_bounds(pred.bounds);
82            }
83        }
84    }
85}
86
87fn collect_bounds<'a, 'tcx>(
88    hir_bounds: &'a [hir::GenericBound<'tcx>],
89    context: ImpliedBoundsContext<'tcx>,
90    target_did: DefId,
91) -> CollectedBound {
92    let mut collect_into = CollectedBound::default();
93    search_bounds_for(hir_bounds, context, |ptr| {
94        if !#[allow(non_exhaustive_omitted_patterns)] match ptr.trait_ref.path.res {
    Res::Def(DefKind::Trait, did) if did == target_did => true,
    _ => false,
}matches!(ptr.trait_ref.path.res, Res::Def(DefKind::Trait, did) if did == target_did) {
95            return;
96        }
97
98        match ptr.modifiers.polarity {
99            hir::BoundPolarity::Maybe(_) => collect_into.maybe = Some(ptr.span),
100            hir::BoundPolarity::Negative(_) => collect_into.negative = Some(ptr.span),
101            hir::BoundPolarity::Positive => collect_into.positive = Some(ptr.span),
102        }
103    });
104    collect_into
105}
106
107fn collect_sizedness_bounds<'tcx>(
108    tcx: TyCtxt<'tcx>,
109    hir_bounds: &'tcx [hir::GenericBound<'tcx>],
110    context: ImpliedBoundsContext<'tcx>,
111    span: Span,
112) -> CollectedSizednessBounds {
113    let sized_did = tcx.require_lang_item(hir::LangItem::Sized, span);
114    let sized = collect_bounds(hir_bounds, context, sized_did);
115
116    let meta_sized_did = tcx.require_lang_item(hir::LangItem::MetaSized, span);
117    let meta_sized = collect_bounds(hir_bounds, context, meta_sized_did);
118
119    let pointee_sized_did = tcx.require_lang_item(hir::LangItem::PointeeSized, span);
120    let pointee_sized = collect_bounds(hir_bounds, context, pointee_sized_did);
121
122    CollectedSizednessBounds { sized, meta_sized, pointee_sized }
123}
124
125/// Add a trait bound for `did`.
126fn add_trait_bound<'tcx>(
127    tcx: TyCtxt<'tcx>,
128    bounds: &mut Vec<(ty::Clause<'tcx>, Span)>,
129    self_ty: Ty<'tcx>,
130    did: DefId,
131    span: Span,
132) {
133    let trait_ref = ty::TraitRef::new(tcx, did, [self_ty]);
134    // Preferable to put sizedness obligations first, since we report better errors for `Sized`
135    // ambiguity.
136    bounds.insert(0, (trait_ref.upcast(tcx), span));
137}
138
139impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
140    /// Adds sizedness bounds to a trait, trait alias, parameter, opaque type or associated type.
141    ///
142    /// - On parameters, opaque type and associated types, add default `Sized` bound if no explicit
143    ///   sizedness bounds are present.
144    /// - On traits and trait aliases, add default `MetaSized` supertrait if no explicit sizedness
145    ///   bounds are present.
146    /// - On parameters, opaque type, associated types and trait aliases, add a `MetaSized` bound if
147    ///   a `?Sized` bound is present.
148    pub(crate) fn add_implicit_sizedness_bounds(
149        &self,
150        bounds: &mut Vec<(ty::Clause<'tcx>, Span)>,
151        self_ty: Ty<'tcx>,
152        hir_bounds: &'tcx [hir::GenericBound<'tcx>],
153        context: ImpliedBoundsContext<'tcx>,
154        span: Span,
155    ) {
156        let tcx = self.tcx();
157
158        // Skip adding any default bounds if `#![rustc_no_implicit_bounds]`
159        if {
        'done:
            {
            for i in tcx.hir_krate_attrs() {
                #[allow(unused_imports)]
                use rustc_hir::attrs::AttributeKind::*;
                let i: &rustc_hir::Attribute = i;
                match i {
                    rustc_hir::Attribute::Parsed(RustcNoImplicitBounds) => {
                        break 'done Some(());
                    }
                    rustc_hir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }.is_some()find_attr!(tcx, crate, RustcNoImplicitBounds) {
160            return;
161        }
162
163        let meta_sized_did = tcx.require_lang_item(hir::LangItem::MetaSized, span);
164        let pointee_sized_did = tcx.require_lang_item(hir::LangItem::PointeeSized, span);
165
166        // If adding sizedness bounds to a trait, then there are some relevant early exits
167        match context {
168            ImpliedBoundsContext::TraitDef(trait_did) => {
169                let trait_did = trait_did.to_def_id();
170                // Never add a default supertrait to `PointeeSized`.
171                if trait_did == pointee_sized_did {
172                    return;
173                }
174                // Don't add default sizedness supertraits to auto traits because it isn't possible to
175                // relax an automatically added supertrait on the defn itself.
176                if tcx.trait_is_auto(trait_did) {
177                    return;
178                }
179            }
180            ImpliedBoundsContext::TyParam(..) | ImpliedBoundsContext::AssociatedTypeOrImplTrait => {
181            }
182        }
183        let collected = collect_sizedness_bounds(tcx, hir_bounds, context, span);
184        if let Some(span) = collected.sized.maybe.or(collected.sized.negative)
185            && collected.sized.positive.is_none()
186            && !collected.meta_sized.any()
187            && !collected.pointee_sized.any()
188        {
189            // `?Sized` is equivalent to `MetaSized` (but only add the bound if there aren't any
190            // other explicit ones) - this can happen for trait aliases as well as bounds.
191            add_trait_bound(tcx, bounds, self_ty, meta_sized_did, span);
192        } else if !collected.any() {
193            match context {
194                ImpliedBoundsContext::TraitDef(..) => {
195                    // If there are no explicit sizedness bounds on a trait then add a default
196                    // `MetaSized` supertrait.
197                    add_trait_bound(tcx, bounds, self_ty, meta_sized_did, span);
198                }
199                ImpliedBoundsContext::TyParam(..)
200                | ImpliedBoundsContext::AssociatedTypeOrImplTrait => {
201                    // If there are no explicit sizedness bounds on a parameter then add a default
202                    // `Sized` bound.
203                    let sized_did = tcx.require_lang_item(hir::LangItem::Sized, span);
204                    add_trait_bound(tcx, bounds, self_ty, sized_did, span);
205                }
206            }
207        }
208    }
209
210    pub(crate) fn add_default_traits(
211        &self,
212        bounds: &mut Vec<(ty::Clause<'tcx>, Span)>,
213        self_ty: Ty<'tcx>,
214        hir_bounds: &[hir::GenericBound<'tcx>],
215        context: ImpliedBoundsContext<'tcx>,
216        span: Span,
217    ) {
218        self.tcx().default_traits().iter().for_each(|default_trait| {
219            self.add_default_trait(*default_trait, bounds, self_ty, hir_bounds, context, span);
220        });
221    }
222
223    /// Add a `experimental_default_bounds` bound to the `bounds` if appropriate.
224    ///
225    /// Doesn't add the bound if the HIR bounds contain any of `Trait`, `?Trait` or `!Trait`.
226    pub(crate) fn add_default_trait(
227        &self,
228        trait_: hir::LangItem,
229        bounds: &mut Vec<(ty::Clause<'tcx>, Span)>,
230        self_ty: Ty<'tcx>,
231        hir_bounds: &[hir::GenericBound<'tcx>],
232        context: ImpliedBoundsContext<'tcx>,
233        span: Span,
234    ) {
235        let tcx = self.tcx();
236
237        // Supertraits for auto trait are unsound according to the unstable book:
238        // https://doc.rust-lang.org/beta/unstable-book/language-features/auto-traits.html#supertraits
239        if let ImpliedBoundsContext::TraitDef(trait_did) = context
240            && self.tcx().trait_is_auto(trait_did.into())
241        {
242            return;
243        }
244
245        if let Some(trait_did) = tcx.lang_items().get(trait_)
246            && self.should_add_default_traits(trait_did, hir_bounds, context)
247        {
248            add_trait_bound(tcx, bounds, self_ty, trait_did, span);
249        }
250    }
251
252    /// Returns `true` if default trait bound should be added.
253    fn should_add_default_traits<'a>(
254        &self,
255        trait_def_id: DefId,
256        hir_bounds: &'a [hir::GenericBound<'tcx>],
257        context: ImpliedBoundsContext<'tcx>,
258    ) -> bool {
259        let collected = collect_bounds(hir_bounds, context, trait_def_id);
260        !{
        'done:
            {
            for i in self.tcx().hir_krate_attrs() {
                #[allow(unused_imports)]
                use rustc_hir::attrs::AttributeKind::*;
                let i: &rustc_hir::Attribute = i;
                match i {
                    rustc_hir::Attribute::Parsed(RustcNoImplicitBounds) => {
                        break 'done Some(());
                    }
                    rustc_hir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }.is_some()find_attr!(self.tcx(), crate, RustcNoImplicitBounds) && !collected.any()
261    }
262
263    pub(crate) fn require_bound_to_relax_default_trait(
264        &self,
265        trait_ref: hir::TraitRef<'_>,
266        span: Span,
267    ) {
268        let tcx = self.tcx();
269
270        if let Res::Def(DefKind::Trait, def_id) = trait_ref.path.res
271            && (tcx.is_lang_item(def_id, hir::LangItem::Sized) || tcx.is_default_trait(def_id))
272        {
273            return;
274        }
275
276        self.dcx().span_err(
277            span,
278            if tcx.sess.opts.unstable_opts.experimental_default_bounds
279                || tcx.features().more_maybe_bounds()
280            {
281                "bound modifier `?` can only be applied to default traits"
282            } else {
283                "bound modifier `?` can only be applied to `Sized`"
284            },
285        );
286    }
287
288    /// Lower HIR bounds into `bounds` given the self type `param_ty` and the overarching late-bound vars if any.
289    ///
290    /// ### Examples
291    ///
292    /// ```ignore (illustrative)
293    /// fn foo<T>() where for<'a> T: Trait<'a> + Copy {}
294    /// //                ^^^^^^^ ^  ^^^^^^^^^^^^^^^^ `hir_bounds`, in HIR form
295    /// //                |       |
296    /// //                |       `param_ty`, in ty form
297    /// //                `bound_vars`, in ty form
298    ///
299    /// fn bar<T>() where T: for<'a> Trait<'a> + Copy {} // no overarching `bound_vars` here!
300    /// //                ^  ^^^^^^^^^^^^^^^^^^^^^^^^ `hir_bounds`, in HIR form
301    /// //                |
302    /// //                `param_ty`, in ty form
303    /// ```
304    ///
305    /// ### A Note on Binders
306    ///
307    /// There is an implied binder around `param_ty` and `hir_bounds`.
308    /// See `lower_poly_trait_ref` for more details.
309    #[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("lower_bounds",
                                    "rustc_hir_analysis::hir_ty_lowering::bounds",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs"),
                                    ::tracing_core::__macro_support::Option::Some(309u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering::bounds"),
                                    ::tracing_core::field::FieldSet::new(&["param_ty",
                                                    "bound_vars", "predicate_filter",
                                                    "overlapping_assoc_constraints"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&param_ty)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&bound_vars)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&predicate_filter)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&overlapping_assoc_constraints)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            for hir_bound in hir_bounds {
                if let PredicateFilter::SelfTraitThatDefines(assoc_ident) =
                        predicate_filter {
                    if let Some(trait_ref) = hir_bound.trait_ref() &&
                                let Some(trait_did) = trait_ref.trait_def_id() &&
                            self.tcx().trait_may_define_assoc_item(trait_did,
                                assoc_ident) {} else { continue; }
                }
                match hir_bound {
                    hir::GenericBound::Trait(poly_trait_ref) => {
                        let _ =
                            self.lower_poly_trait_ref(poly_trait_ref, param_ty, bounds,
                                predicate_filter, overlapping_assoc_constraints);
                    }
                    hir::GenericBound::Outlives(lifetime) => {
                        if #[allow(non_exhaustive_omitted_patterns)] match predicate_filter
                                {
                                PredicateFilter::ConstIfConst |
                                    PredicateFilter::SelfConstIfConst => true,
                                _ => false,
                            } {
                            continue;
                        }
                        let region =
                            self.lower_lifetime(lifetime,
                                RegionInferReason::OutlivesBound);
                        let bound =
                            ty::Binder::bind_with_vars(ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(param_ty,
                                        region)), bound_vars);
                        bounds.push((bound.upcast(self.tcx()),
                                lifetime.ident.span));
                    }
                    hir::GenericBound::Use(..) => {}
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self, hir_bounds, bounds))]
310    pub(crate) fn lower_bounds<'hir, I: IntoIterator<Item = &'hir hir::GenericBound<'tcx>>>(
311        &self,
312        param_ty: Ty<'tcx>,
313        hir_bounds: I,
314        bounds: &mut Vec<(ty::Clause<'tcx>, Span)>,
315        bound_vars: &'tcx ty::List<ty::BoundVariableKind<'tcx>>,
316        predicate_filter: PredicateFilter,
317        overlapping_assoc_constraints: OverlappingAsssocItemConstraints,
318    ) where
319        'tcx: 'hir,
320    {
321        for hir_bound in hir_bounds {
322            // In order to avoid cycles, when we're lowering `SelfTraitThatDefines`,
323            // we skip over any traits that don't define the given associated type.
324            if let PredicateFilter::SelfTraitThatDefines(assoc_ident) = predicate_filter {
325                if let Some(trait_ref) = hir_bound.trait_ref()
326                    && let Some(trait_did) = trait_ref.trait_def_id()
327                    && self.tcx().trait_may_define_assoc_item(trait_did, assoc_ident)
328                {
329                    // Okay
330                } else {
331                    continue;
332                }
333            }
334
335            match hir_bound {
336                hir::GenericBound::Trait(poly_trait_ref) => {
337                    let _ = self.lower_poly_trait_ref(
338                        poly_trait_ref,
339                        param_ty,
340                        bounds,
341                        predicate_filter,
342                        overlapping_assoc_constraints,
343                    );
344                }
345                hir::GenericBound::Outlives(lifetime) => {
346                    // `ConstIfConst` is only interested in `[const]` bounds.
347                    if matches!(
348                        predicate_filter,
349                        PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst
350                    ) {
351                        continue;
352                    }
353
354                    let region = self.lower_lifetime(lifetime, RegionInferReason::OutlivesBound);
355                    let bound = ty::Binder::bind_with_vars(
356                        ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(param_ty, region)),
357                        bound_vars,
358                    );
359                    bounds.push((bound.upcast(self.tcx()), lifetime.ident.span));
360                }
361                hir::GenericBound::Use(..) => {
362                    // We don't actually lower `use` into the type layer.
363                }
364            }
365        }
366    }
367
368    /// Lower an associated item constraint from the HIR into `bounds`.
369    ///
370    /// ### A Note on Binders
371    ///
372    /// Given something like `T: for<'a> Iterator<Item = &'a u32>`,
373    /// the `trait_ref` here will be `for<'a> T: Iterator`.
374    /// The `constraint` data however is from *inside* the binder
375    /// (e.g., `&'a u32`) and hence may reference bound regions.
376    #[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("lower_assoc_item_constraint",
                                    "rustc_hir_analysis::hir_ty_lowering::bounds",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs"),
                                    ::tracing_core::__macro_support::Option::Some(376u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering::bounds"),
                                    ::tracing_core::field::FieldSet::new(&["hir_ref_id",
                                                    "trait_ref", "constraint", "predicate_filter"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&hir_ref_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ref)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&constraint)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&predicate_filter)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.tcx();
            let assoc_tag =
                if constraint.gen_args.parenthesized ==
                        hir::GenericArgsParentheses::ReturnTypeNotation {
                    ty::AssocTag::Fn
                } else if let hir::AssocItemConstraintKind::Equality {
                        term: hir::Term::Const(_) } = constraint.kind {
                    ty::AssocTag::Const
                } else { ty::AssocTag::Type };
            let candidate =
                if self.probe_trait_that_defines_assoc_item(trait_ref.def_id(),
                        assoc_tag, constraint.ident) {
                    trait_ref
                } else {
                    self.probe_single_bound_for_assoc_item(||
                                traits::supertraits(tcx, trait_ref),
                            AssocItemQSelf::Trait(trait_ref.def_id()), assoc_tag,
                            constraint.ident, path_span, Some(constraint))?
                };
            let assoc_item =
                self.probe_assoc_item(constraint.ident, assoc_tag, hir_ref_id,
                        constraint.span,
                        candidate.def_id()).expect("failed to find associated item");
            if let Some(duplicates) = duplicates {
                duplicates.entry(assoc_item.def_id).and_modify(|prev_span|
                            {
                                self.dcx().emit_err(diagnostics::ValueOfAssociatedStructAlreadySpecified {
                                        span: constraint.span,
                                        prev_span: *prev_span,
                                        item_name: constraint.ident,
                                        def_path: tcx.def_path_str(assoc_item.container_id(tcx)),
                                    });
                            }).or_insert(constraint.span);
            }
            let projection_term =
                if let ty::AssocTag::Fn = assoc_tag {
                    let bound_vars = tcx.late_bound_vars(constraint.hir_id);
                    ty::Binder::bind_with_vars(self.lower_return_type_notation_ty(candidate,
                                    assoc_item.def_id, path_span)?.into(), bound_vars)
                } else {
                    candidate.map_bound(|trait_ref|
                            {
                                let item_segment =
                                    hir::PathSegment {
                                        ident: constraint.ident,
                                        hir_id: constraint.hir_id,
                                        res: Res::Err,
                                        args: Some(constraint.gen_args),
                                        infer_args: false,
                                        delegation_child_segment: false,
                                    };
                                let alias_args =
                                    self.lower_generic_args_of_assoc_item(path_span,
                                        assoc_item.def_id, &item_segment, trait_ref.args);
                                {
                                    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/hir_ty_lowering/bounds.rs:479",
                                                        "rustc_hir_analysis::hir_ty_lowering::bounds",
                                                        ::tracing::Level::DEBUG,
                                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs"),
                                                        ::tracing_core::__macro_support::Option::Some(479u32),
                                                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering::bounds"),
                                                        ::tracing_core::field::FieldSet::new(&["alias_args"],
                                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                        ::tracing::metadata::Kind::EVENT)
                                                };
                                            ::tracing::callsite::DefaultCallsite::new(&META)
                                        };
                                    let enabled =
                                        ::tracing::Level::DEBUG <=
                                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                ::tracing::Level::DEBUG <=
                                                    ::tracing::level_filters::LevelFilter::current() &&
                                            {
                                                let interest = __CALLSITE.interest();
                                                !interest.is_never() &&
                                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                        interest)
                                            };
                                    if enabled {
                                        (|value_set: ::tracing::field::ValueSet|
                                                    {
                                                        let meta = __CALLSITE.metadata();
                                                        ::tracing::Event::dispatch(meta, &value_set);
                                                        ;
                                                    })({
                                                #[allow(unused_imports)]
                                                use ::tracing::field::{debug, display, Value};
                                                let mut iter = __CALLSITE.metadata().fields().iter();
                                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                    ::tracing::__macro_support::Option::Some(&debug(&alias_args)
                                                                            as &dyn Value))])
                                            });
                                    } else { ; }
                                };
                                ty::AliasTerm::new_from_def_id(tcx, assoc_item.def_id,
                                    alias_args)
                            })
                };
            match constraint.kind {
                hir::AssocItemConstraintKind::Equality { .. } if
                    let ty::AssocTag::Fn = assoc_tag => {
                    return Err(self.dcx().emit_err(crate::diagnostics::ReturnTypeNotationEqualityBound {
                                    span: constraint.span,
                                }));
                }
                hir::AssocItemConstraintKind::Equality { term } => {
                    let term =
                        match term {
                            hir::Term::Ty(ty) => self.lower_ty(ty).into(),
                            hir::Term::Const(ct) => {
                                let ty =
                                    projection_term.map_bound(|alias|
                                            alias.expect_ct().type_of(tcx).skip_norm_wip());
                                let ty =
                                    check_assoc_const_binding_type(self, constraint.ident, ty,
                                        constraint.hir_id);
                                self.lower_const_arg(ct, ty).into()
                            }
                        };
                    let late_bound_in_projection_ty =
                        tcx.collect_constrained_late_bound_regions(projection_term);
                    let late_bound_in_term =
                        tcx.collect_referenced_late_bound_regions(trait_ref.rebind(term));
                    {
                        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/hir_ty_lowering/bounds.rs:521",
                                            "rustc_hir_analysis::hir_ty_lowering::bounds",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs"),
                                            ::tracing_core::__macro_support::Option::Some(521u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering::bounds"),
                                            ::tracing_core::field::FieldSet::new(&["late_bound_in_projection_ty"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&debug(&late_bound_in_projection_ty)
                                                                as &dyn Value))])
                                });
                        } else { ; }
                    };
                    {
                        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/hir_ty_lowering/bounds.rs:522",
                                            "rustc_hir_analysis::hir_ty_lowering::bounds",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs"),
                                            ::tracing_core::__macro_support::Option::Some(522u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering::bounds"),
                                            ::tracing_core::field::FieldSet::new(&["late_bound_in_term"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&debug(&late_bound_in_term)
                                                                as &dyn Value))])
                                });
                        } else { ; }
                    };
                    self.validate_late_bound_regions(late_bound_in_projection_ty,
                        late_bound_in_term,
                        |br_name|
                            {
                                {
                                    self.dcx().struct_span_err(constraint.span,
                                            ::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!("binding for associated type `{0}` references {1}, which does not appear in the trait input types",
                                                            constraint.ident, br_name))
                                                })).with_code(E0582)
                                }
                            });
                    match predicate_filter {
                        PredicateFilter::All | PredicateFilter::SelfOnly |
                            PredicateFilter::SelfAndAssociatedTypeBounds => {
                            let bound =
                                projection_term.map_bound(|projection_term|
                                        {
                                            ty::ClauseKind::Projection(ty::ProjectionPredicate {
                                                    projection_term,
                                                    term,
                                                })
                                        });
                            if let ty::AssocTag::Const = assoc_tag &&
                                    !self.tcx().is_type_const(assoc_item.def_id) {
                                if tcx.features().min_generic_const_args() {
                                    let mut err =
                                        self.dcx().struct_span_err(constraint.span,
                                            "use of trait associated const not defined as `type const`");
                                    err.note("the declaration in the trait must begin with `type const` not just `const` alone");
                                    return Err(err.emit());
                                } else {
                                    let err =
                                        self.dcx().span_delayed_bug(constraint.span,
                                            "use of trait associated const defined as `type const`");
                                    return Err(err);
                                }
                            } else {
                                bounds.push((bound.upcast(tcx), constraint.span));
                            }
                        }
                        PredicateFilter::SelfTraitThatDefines(_) => {}
                        PredicateFilter::ConstIfConst |
                            PredicateFilter::SelfConstIfConst => {}
                    }
                }
                hir::AssocItemConstraintKind::Bound { bounds: hir_bounds } =>
                    {
                    match predicate_filter {
                        PredicateFilter::All |
                            PredicateFilter::SelfAndAssociatedTypeBounds |
                            PredicateFilter::ConstIfConst => {
                            let projection_ty =
                                projection_term.map_bound(|projection_term|
                                        projection_term.expect_ty());
                            let param_ty =
                                Ty::new_alias(tcx, ty::IsRigid::No,
                                    projection_ty.skip_binder());
                            self.lower_bounds(param_ty, hir_bounds, bounds,
                                projection_ty.bound_vars(), predicate_filter,
                                OverlappingAsssocItemConstraints::Allowed);
                        }
                        PredicateFilter::SelfOnly |
                            PredicateFilter::SelfTraitThatDefines(_) |
                            PredicateFilter::SelfConstIfConst => {}
                    }
                }
            }
            Ok(())
        }
    }
}#[instrument(level = "debug", skip(self, bounds, duplicates, path_span))]
377    pub(super) fn lower_assoc_item_constraint(
378        &self,
379        hir_ref_id: hir::HirId,
380        trait_ref: ty::PolyTraitRef<'tcx>,
381        constraint: &hir::AssocItemConstraint<'tcx>,
382        bounds: &mut Vec<(ty::Clause<'tcx>, Span)>,
383        duplicates: Option<&mut FxIndexMap<DefId, Span>>,
384        path_span: Span,
385        predicate_filter: PredicateFilter,
386    ) -> Result<(), ErrorGuaranteed> {
387        let tcx = self.tcx();
388
389        let assoc_tag = if constraint.gen_args.parenthesized
390            == hir::GenericArgsParentheses::ReturnTypeNotation
391        {
392            ty::AssocTag::Fn
393        } else if let hir::AssocItemConstraintKind::Equality { term: hir::Term::Const(_) } =
394            constraint.kind
395        {
396            ty::AssocTag::Const
397        } else {
398            ty::AssocTag::Type
399        };
400
401        // Given something like `U: Trait<T = X>`, we want to produce a predicate like
402        // `<U as Trait>::T = X`.
403        // This is somewhat subtle in the event that `T` is defined in a supertrait of `Trait`,
404        // because in that case we need to upcast. I.e., we want to produce
405        // `<B as SuperTrait<i32>>::T == X` for `B: SubTrait<T = X>` where
406        //
407        //     trait SubTrait: SuperTrait<i32> {}
408        //     trait SuperTrait<A> { type T; }
409        let candidate = if self.probe_trait_that_defines_assoc_item(
410            trait_ref.def_id(),
411            assoc_tag,
412            constraint.ident,
413        ) {
414            // Simple case: The assoc item is defined in the current trait.
415            trait_ref
416        } else {
417            // Otherwise, we have to walk through the supertraits to find
418            // one that does define it.
419            self.probe_single_bound_for_assoc_item(
420                || traits::supertraits(tcx, trait_ref),
421                AssocItemQSelf::Trait(trait_ref.def_id()),
422                assoc_tag,
423                constraint.ident,
424                path_span,
425                Some(constraint),
426            )?
427        };
428
429        let assoc_item = self
430            .probe_assoc_item(
431                constraint.ident,
432                assoc_tag,
433                hir_ref_id,
434                constraint.span,
435                candidate.def_id(),
436            )
437            .expect("failed to find associated item");
438
439        if let Some(duplicates) = duplicates {
440            duplicates
441                .entry(assoc_item.def_id)
442                .and_modify(|prev_span| {
443                    self.dcx().emit_err(diagnostics::ValueOfAssociatedStructAlreadySpecified {
444                        span: constraint.span,
445                        prev_span: *prev_span,
446                        item_name: constraint.ident,
447                        def_path: tcx.def_path_str(assoc_item.container_id(tcx)),
448                    });
449                })
450                .or_insert(constraint.span);
451        }
452
453        let projection_term = if let ty::AssocTag::Fn = assoc_tag {
454            let bound_vars = tcx.late_bound_vars(constraint.hir_id);
455            ty::Binder::bind_with_vars(
456                self.lower_return_type_notation_ty(candidate, assoc_item.def_id, path_span)?.into(),
457                bound_vars,
458            )
459        } else {
460            // Create the generic arguments for the associated type or constant by joining the
461            // parent arguments (the arguments of the trait) and the own arguments (the ones of
462            // the associated item itself) and construct an alias type using them.
463            candidate.map_bound(|trait_ref| {
464                let item_segment = hir::PathSegment {
465                    ident: constraint.ident,
466                    hir_id: constraint.hir_id,
467                    res: Res::Err,
468                    args: Some(constraint.gen_args),
469                    infer_args: false,
470                    delegation_child_segment: false,
471                };
472
473                let alias_args = self.lower_generic_args_of_assoc_item(
474                    path_span,
475                    assoc_item.def_id,
476                    &item_segment,
477                    trait_ref.args,
478                );
479                debug!(?alias_args);
480
481                ty::AliasTerm::new_from_def_id(tcx, assoc_item.def_id, alias_args)
482            })
483        };
484
485        match constraint.kind {
486            hir::AssocItemConstraintKind::Equality { .. } if let ty::AssocTag::Fn = assoc_tag => {
487                return Err(self.dcx().emit_err(
488                    crate::diagnostics::ReturnTypeNotationEqualityBound { span: constraint.span },
489                ));
490            }
491            // Lower an equality constraint like `Item = u32` as found in HIR bound `T: Iterator<Item = u32>`
492            // to a projection predicate: `<T as Iterator>::Item = u32`.
493            hir::AssocItemConstraintKind::Equality { term } => {
494                let term = match term {
495                    hir::Term::Ty(ty) => self.lower_ty(ty).into(),
496                    hir::Term::Const(ct) => {
497                        let ty = projection_term
498                            .map_bound(|alias| alias.expect_ct().type_of(tcx).skip_norm_wip());
499                        let ty = check_assoc_const_binding_type(
500                            self,
501                            constraint.ident,
502                            ty,
503                            constraint.hir_id,
504                        );
505
506                        self.lower_const_arg(ct, ty).into()
507                    }
508                };
509
510                // Find any late-bound regions declared in `ty` that are not
511                // declared in the trait-ref or assoc_item. These are not well-formed.
512                //
513                // Example:
514                //
515                //     for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
516                //     for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
517                let late_bound_in_projection_ty =
518                    tcx.collect_constrained_late_bound_regions(projection_term);
519                let late_bound_in_term =
520                    tcx.collect_referenced_late_bound_regions(trait_ref.rebind(term));
521                debug!(?late_bound_in_projection_ty);
522                debug!(?late_bound_in_term);
523
524                // FIXME: point at the type params that don't have appropriate lifetimes:
525                // struct S1<F: for<'a> Fn(&i32, &i32) -> &'a i32>(F);
526                //                         ----  ----     ^^^^^^^
527                // NOTE(mgca): This error should be impossible to trigger with assoc const bindings.
528                self.validate_late_bound_regions(
529                    late_bound_in_projection_ty,
530                    late_bound_in_term,
531                    |br_name| {
532                        struct_span_code_err!(
533                            self.dcx(),
534                            constraint.span,
535                            E0582,
536                            "binding for associated type `{}` references {}, \
537                             which does not appear in the trait input types",
538                            constraint.ident,
539                            br_name
540                        )
541                    },
542                );
543
544                match predicate_filter {
545                    PredicateFilter::All
546                    | PredicateFilter::SelfOnly
547                    | PredicateFilter::SelfAndAssociatedTypeBounds => {
548                        let bound = projection_term.map_bound(|projection_term| {
549                            ty::ClauseKind::Projection(ty::ProjectionPredicate {
550                                projection_term,
551                                term,
552                            })
553                        });
554
555                        if let ty::AssocTag::Const = assoc_tag
556                            && !self.tcx().is_type_const(assoc_item.def_id)
557                        {
558                            if tcx.features().min_generic_const_args() {
559                                let mut err = self.dcx().struct_span_err(
560                                    constraint.span,
561                                    "use of trait associated const not defined as `type const`",
562                                );
563                                err.note("the declaration in the trait must begin with `type const` not just `const` alone");
564                                return Err(err.emit());
565                            } else {
566                                let err = self.dcx().span_delayed_bug(
567                                    constraint.span,
568                                    "use of trait associated const defined as `type const`",
569                                );
570                                return Err(err);
571                            }
572                        } else {
573                            bounds.push((bound.upcast(tcx), constraint.span));
574                        }
575                    }
576                    // SelfTraitThatDefines is only interested in trait predicates.
577                    PredicateFilter::SelfTraitThatDefines(_) => {}
578                    // `ConstIfConst` is only interested in `[const]` bounds.
579                    PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {}
580                }
581            }
582            // Lower a constraint like `Item: Debug` as found in HIR bound `T: Iterator<Item: Debug>`
583            // to a bound involving a projection: `<T as Iterator>::Item: Debug`.
584            hir::AssocItemConstraintKind::Bound { bounds: hir_bounds } => {
585                match predicate_filter {
586                    PredicateFilter::All
587                    | PredicateFilter::SelfAndAssociatedTypeBounds
588                    | PredicateFilter::ConstIfConst => {
589                        let projection_ty = projection_term
590                            .map_bound(|projection_term| projection_term.expect_ty());
591                        // Calling `skip_binder` is okay, because `lower_bounds` expects the `param_ty`
592                        // parameter to have a skipped binder.
593                        let param_ty =
594                            Ty::new_alias(tcx, ty::IsRigid::No, projection_ty.skip_binder());
595                        self.lower_bounds(
596                            param_ty,
597                            hir_bounds,
598                            bounds,
599                            projection_ty.bound_vars(),
600                            predicate_filter,
601                            OverlappingAsssocItemConstraints::Allowed,
602                        );
603                    }
604                    PredicateFilter::SelfOnly
605                    | PredicateFilter::SelfTraitThatDefines(_)
606                    | PredicateFilter::SelfConstIfConst => {}
607                }
608            }
609        }
610        Ok(())
611    }
612
613    /// Lower a type, possibly specially handling the type if it's a return type notation
614    /// which we otherwise deny in other positions.
615    pub fn lower_ty_maybe_return_type_notation(&self, hir_ty: &hir::Ty<'tcx>) -> Ty<'tcx> {
616        let hir::TyKind::Path(qpath) = hir_ty.kind else {
617            return self.lower_ty(hir_ty);
618        };
619
620        let tcx = self.tcx();
621        match qpath {
622            hir::QPath::Resolved(opt_self_ty, path)
623                if let [mod_segments @ .., trait_segment, item_segment] = &path.segments[..]
624                    && item_segment.args.is_some_and(|args| {
625                        #[allow(non_exhaustive_omitted_patterns)] match args.parenthesized {
    hir::GenericArgsParentheses::ReturnTypeNotation => true,
    _ => false,
}matches!(
626                            args.parenthesized,
627                            hir::GenericArgsParentheses::ReturnTypeNotation
628                        )
629                    }) =>
630            {
631                // We don't allow generics on the module segments.
632                let _ =
633                    self.prohibit_generic_args(mod_segments.iter(), GenericsArgsErrExtend::None);
634
635                let item_def_id = match path.res {
636                    Res::Def(DefKind::AssocFn, item_def_id) => item_def_id,
637                    Res::Err => {
638                        return Ty::new_error_with_message(
639                            tcx,
640                            hir_ty.span,
641                            "failed to resolve RTN",
642                        );
643                    }
644                    _ => ::rustc_middle::util::bug::bug_fmt(format_args!("only expected method resolution for fully qualified RTN"))bug!("only expected method resolution for fully qualified RTN"),
645                };
646                let trait_def_id = tcx.parent(item_def_id);
647
648                // Good error for `where Trait::method(..): Send`.
649                let Some(self_ty) = opt_self_ty else {
650                    let guar = self.report_missing_self_ty_for_resolved_path(
651                        trait_def_id,
652                        hir_ty.span,
653                        item_segment,
654                        ty::AssocTag::Type,
655                    );
656                    return Ty::new_error(tcx, guar);
657                };
658                let self_ty = self.lower_ty(self_ty);
659
660                let trait_ref = self.lower_mono_trait_ref(
661                    hir_ty.span,
662                    trait_def_id,
663                    self_ty,
664                    trait_segment,
665                    false,
666                );
667
668                // SUBTLE: As noted at the end of `try_append_return_type_notation_params`
669                // in `resolve_bound_vars`, we stash the explicit bound vars of the where
670                // clause onto the item segment of the RTN type. This allows us to know
671                // how many bound vars are *not* coming from the signature of the function
672                // from lowering RTN itself.
673                //
674                // For example, in `where for<'a> <T as Trait<'a>>::method(..): Other`,
675                // the `late_bound_vars` of the where clause predicate (i.e. this HIR ty's
676                // parent) will include `'a` AND all the early- and late-bound vars of the
677                // method. But when lowering the RTN type, we just want the list of vars
678                // we used to resolve the trait ref. We explicitly stored those back onto
679                // the item segment, since there's no other good place to put them.
680                let candidate =
681                    ty::Binder::bind_with_vars(trait_ref, tcx.late_bound_vars(item_segment.hir_id));
682
683                match self.lower_return_type_notation_ty(candidate, item_def_id, hir_ty.span) {
684                    Ok(ty) => Ty::new_alias(tcx, ty::IsRigid::No, ty),
685                    Err(guar) => Ty::new_error(tcx, guar),
686                }
687            }
688            hir::QPath::TypeRelative(hir_self_ty, segment)
689                if segment.args.is_some_and(|args| {
690                    #[allow(non_exhaustive_omitted_patterns)] match args.parenthesized {
    hir::GenericArgsParentheses::ReturnTypeNotation => true,
    _ => false,
}matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
691                }) =>
692            {
693                let self_ty = self.lower_ty(hir_self_ty);
694                let (item_def_id, bound) = match self.resolve_type_relative_path(
695                    self_ty,
696                    hir_self_ty,
697                    ty::AssocTag::Fn,
698                    segment,
699                    hir_ty.hir_id,
700                    hir_ty.span,
701                    None,
702                ) {
703                    Ok(result) => result,
704                    Err(guar) => return Ty::new_error(tcx, guar),
705                };
706
707                // Don't let `T::method` resolve to some `for<'a> <T as Tr<'a>>::method`,
708                // which may happen via a higher-ranked where clause or supertrait.
709                // This is the same restrictions as associated types; even though we could
710                // support it, it just makes things a lot more difficult to support in
711                // `resolve_bound_vars`, since we'd need to introduce those as elided
712                // bound vars on the where clause too.
713                if bound.has_bound_vars() {
714                    return Ty::new_error(
715                        tcx,
716                        self.dcx().emit_err(
717                            diagnostics::AssociatedItemTraitUninferredGenericParams {
718                                span: hir_ty.span,
719                                inferred_sugg: Some(hir_ty.span.with_hi(segment.ident.span.lo())),
720                                bound: ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}::",
                tcx.anonymize_bound_vars(bound).skip_binder()))
    })format!(
721                                    "{}::",
722                                    tcx.anonymize_bound_vars(bound).skip_binder()
723                                ),
724                                mpart_sugg: None,
725                                what: tcx.def_descr(item_def_id),
726                            },
727                        ),
728                    );
729                }
730
731                match self.lower_return_type_notation_ty(bound, item_def_id, hir_ty.span) {
732                    Ok(ty) => Ty::new_alias(tcx, ty::IsRigid::No, ty),
733                    Err(guar) => Ty::new_error(tcx, guar),
734                }
735            }
736            _ => self.lower_ty(hir_ty),
737        }
738    }
739
740    /// Do the common parts of lowering an RTN type. This involves extending the
741    /// candidate binder to include all of the early- and late-bound vars that are
742    /// defined on the function itself, and constructing a projection to the RPITIT
743    /// return type of that function.
744    fn lower_return_type_notation_ty(
745        &self,
746        candidate: ty::PolyTraitRef<'tcx>,
747        item_def_id: DefId,
748        path_span: Span,
749    ) -> Result<ty::AliasTy<'tcx>, ErrorGuaranteed> {
750        let tcx = self.tcx();
751        let mut emitted_bad_param_err = None;
752        // If we have an method return type bound, then we need to instantiate
753        // the method's early bound params with suitable late-bound params.
754        let mut num_bound_vars = candidate.bound_vars().len();
755        let args = candidate.skip_binder().args.extend_to(tcx, item_def_id, |param, _| {
756            let arg = match param.kind {
757                ty::GenericParamDefKind::Lifetime => ty::Region::new_bound(
758                    tcx,
759                    ty::INNERMOST,
760                    ty::BoundRegion {
761                        var: ty::BoundVar::from_usize(num_bound_vars),
762                        kind: ty::BoundRegionKind::Named(param.def_id),
763                    },
764                )
765                .into(),
766                ty::GenericParamDefKind::Type { .. } => {
767                    let guar = *emitted_bad_param_err.get_or_insert_with(|| {
768                        self.dcx().emit_err(
769                            crate::diagnostics::ReturnTypeNotationIllegalParam::Type {
770                                span: path_span,
771                                param_span: tcx.def_span(param.def_id),
772                            },
773                        )
774                    });
775                    Ty::new_error(tcx, guar).into()
776                }
777                ty::GenericParamDefKind::Const { .. } => {
778                    let guar = *emitted_bad_param_err.get_or_insert_with(|| {
779                        self.dcx().emit_err(
780                            crate::diagnostics::ReturnTypeNotationIllegalParam::Const {
781                                span: path_span,
782                                param_span: tcx.def_span(param.def_id),
783                            },
784                        )
785                    });
786                    ty::Const::new_error(tcx, guar).into()
787                }
788            };
789            num_bound_vars += 1;
790            arg
791        });
792
793        // Next, we need to check that the return-type notation is being used on
794        // an RPITIT (return-position impl trait in trait) or AFIT (async fn in trait).
795        let output = tcx.fn_sig(item_def_id).skip_binder().output();
796        let output = if let ty::Alias(_, alias_ty) = *output.skip_binder().kind()
797            && let ty::AliasTy { kind: ty::Projection { def_id: projection_def_id }, .. } = alias_ty
798            && tcx.is_impl_trait_in_trait(projection_def_id)
799        {
800            alias_ty
801        } else {
802            return Err(self.dcx().emit_err(crate::diagnostics::ReturnTypeNotationOnNonRpitit {
803                span: path_span,
804                ty: tcx.liberate_late_bound_regions(item_def_id, output),
805                fn_span: tcx.hir_span_if_local(item_def_id),
806                note: (),
807            }));
808        };
809
810        // Finally, move the fn return type's bound vars over to account for the early bound
811        // params (and trait ref's late bound params). This logic is very similar to
812        // `rustc_middle::ty::predicate::Clause::instantiate_supertrait`
813        // and it's no coincidence why.
814        let shifted_output = tcx.shift_bound_var_indices(num_bound_vars, output);
815        Ok(ty::EarlyBinder::bind(tcx, shifted_output).instantiate(tcx, args).skip_norm_wip())
816    }
817}
818
819/// Detect and reject early-bound & escaping late-bound generic params in the type of assoc const bindings.
820///
821/// FIXME(const_generics): This is a temporary and semi-artificial restriction until the
822/// arrival of *generic const generics*[^1].
823///
824/// It might actually be possible that we can already support early-bound generic params
825/// in such types if we just lifted some more checks in other places, too, for example
826/// inside `HirTyLowerer::lower_anon_const`. However, even if that were the case, we should
827/// probably gate this behind another feature flag.
828///
829/// [^1]: <https://github.com/rust-lang/project-const-generics/issues/28>.
830pub(crate) fn check_assoc_const_binding_type<'tcx>(
831    cx: &dyn HirTyLowerer<'tcx>,
832    assoc_const: Ident,
833    ty: ty::Binder<'tcx, Ty<'tcx>>,
834    hir_id: hir::HirId,
835) -> Ty<'tcx> {
836    // We can't perform the checks for early-bound params during name resolution unlike E0770
837    // because this information depends on *type* resolution.
838    // We can't perform these checks in `resolve_bound_vars` either for the same reason.
839    // Consider the trait ref `for<'a> Trait<'a, C = { &0 }>`. We need to know the fully
840    // resolved type of `Trait::C` in order to know if it references `'a` or not.
841
842    let ty = ty.skip_binder();
843    if !ty.has_param() && !ty.has_escaping_bound_vars() {
844        return ty;
845    }
846
847    let mut collector = GenericParamAndBoundVarCollector {
848        cx,
849        params: Default::default(),
850        vars: Default::default(),
851        depth: ty::INNERMOST,
852    };
853    let mut guar = ty.visit_with(&mut collector).break_value();
854
855    let tcx = cx.tcx();
856    let ty_note = ty
857        .make_suggestable(tcx, false, None)
858        .map(|ty| crate::diagnostics::TyOfAssocConstBindingNote { assoc_const, ty });
859
860    let enclosing_item_owner_id = tcx
861        .hir_parent_owner_iter(hir_id)
862        .find_map(|(owner_id, parent)| parent.generics().map(|_| owner_id))
863        .unwrap();
864    let generics = tcx.generics_of(enclosing_item_owner_id);
865    for index in collector.params {
866        let param = generics.param_at(index as _, tcx);
867        let is_self_param = param.name == kw::SelfUpper;
868        guar.get_or_insert(cx.dcx().emit_err(crate::diagnostics::ParamInTyOfAssocConstBinding {
869            span: assoc_const.span,
870            assoc_const,
871            param_name: param.name,
872            param_def_kind: tcx.def_descr(param.def_id),
873            param_category: if is_self_param {
874                "self"
875            } else if param.kind.is_synthetic() {
876                "synthetic"
877            } else {
878                "normal"
879            },
880            param_defined_here_label:
881                (!is_self_param).then(|| tcx.def_ident_span(param.def_id).unwrap()),
882            ty_note,
883        }));
884    }
885    for var_def_id in collector.vars {
886        guar.get_or_insert(cx.dcx().emit_err(
887            crate::diagnostics::EscapingBoundVarInTyOfAssocConstBinding {
888                span: assoc_const.span,
889                assoc_const,
890                var_name: cx.tcx().item_name(var_def_id),
891                var_def_kind: tcx.def_descr(var_def_id),
892                var_defined_here_label: tcx.def_ident_span(var_def_id).unwrap(),
893                ty_note,
894            },
895        ));
896    }
897
898    let guar = guar.unwrap_or_else(|| ::rustc_middle::util::bug::bug_fmt(format_args!("failed to find gen params or bound vars in ty"))bug!("failed to find gen params or bound vars in ty"));
899    Ty::new_error(tcx, guar)
900}
901
902struct GenericParamAndBoundVarCollector<'a, 'tcx> {
903    cx: &'a dyn HirTyLowerer<'tcx>,
904    params: FxIndexSet<u32>,
905    vars: FxIndexSet<DefId>,
906    depth: ty::DebruijnIndex,
907}
908
909impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for GenericParamAndBoundVarCollector<'_, 'tcx> {
910    type Result = ControlFlow<ErrorGuaranteed>;
911
912    fn visit_binder<T: TypeVisitable<TyCtxt<'tcx>>>(
913        &mut self,
914        binder: &ty::Binder<'tcx, T>,
915    ) -> Self::Result {
916        self.depth.shift_in(1);
917        let result = binder.super_visit_with(self);
918        self.depth.shift_out(1);
919        result
920    }
921
922    fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
923        match ty.kind() {
924            ty::Param(param) => {
925                self.params.insert(param.index);
926            }
927            ty::Bound(ty::BoundVarIndexKind::Bound(db), bt) if *db >= self.depth => {
928                self.vars.insert(match bt.kind {
929                    ty::BoundTyKind::Param(def_id) => def_id,
930                    ty::BoundTyKind::Anon => {
931                        let reported = self
932                            .cx
933                            .dcx()
934                            .delayed_bug(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unexpected anon bound ty: {0:?}",
                bt.var))
    })format!("unexpected anon bound ty: {:?}", bt.var));
935                        return ControlFlow::Break(reported);
936                    }
937                });
938            }
939            _ if ty.has_param() || ty.has_bound_vars() => return ty.super_visit_with(self),
940            _ => {}
941        }
942        ControlFlow::Continue(())
943    }
944
945    fn visit_region(&mut self, re: ty::Region<'tcx>) -> Self::Result {
946        match re.kind() {
947            ty::ReEarlyParam(param) => {
948                self.params.insert(param.index);
949            }
950            ty::ReBound(ty::BoundVarIndexKind::Bound(db), br) if db >= self.depth => {
951                self.vars.insert(match br.kind {
952                    ty::BoundRegionKind::Named(def_id) => def_id,
953                    ty::BoundRegionKind::Anon | ty::BoundRegionKind::ClosureEnv => {
954                        let guar = self
955                            .cx
956                            .dcx()
957                            .delayed_bug(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unexpected bound region kind: {0:?}",
                br.kind))
    })format!("unexpected bound region kind: {:?}", br.kind));
958                        return ControlFlow::Break(guar);
959                    }
960                    ty::BoundRegionKind::NamedForPrinting(_) => {
961                        ::rustc_middle::util::bug::bug_fmt(format_args!("only used for pretty printing"))bug!("only used for pretty printing")
962                    }
963                });
964            }
965            _ => {}
966        }
967        ControlFlow::Continue(())
968    }
969
970    fn visit_const(&mut self, ct: ty::Const<'tcx>) -> Self::Result {
971        match ct.kind() {
972            ty::ConstKind::Param(param) => {
973                self.params.insert(param.index);
974            }
975            ty::ConstKind::Bound(ty::BoundVarIndexKind::Bound(db), _) if db >= self.depth => {
976                let guar = self.cx.dcx().delayed_bug("unexpected escaping late-bound const var");
977                return ControlFlow::Break(guar);
978            }
979            _ if ct.has_param() || ct.has_bound_vars() => return ct.super_visit_with(self),
980            _ => {}
981        }
982        ControlFlow::Continue(())
983    }
984}