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::attrs::AttributeKind;
8use rustc_hir::def::{DefKind, Res};
9use rustc_hir::def_id::{CRATE_DEF_ID, DefId};
10use rustc_hir::{PolyTraitRef, find_attr};
11use rustc_middle::bug;
12use rustc_middle::ty::{
13    self as ty, IsSuggestable, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt,
14    TypeVisitor, Upcast,
15};
16use rustc_span::{ErrorGuaranteed, Ident, Span, kw, sym};
17use rustc_trait_selection::traits;
18use smallvec::SmallVec;
19use tracing::{debug, instrument};
20
21use crate::errors;
22use crate::hir_ty_lowering::{
23    AssocItemQSelf, FeedConstTy, GenericsArgsErrExtend, HirTyLowerer, ImpliedBoundsContext,
24    OverlappingAsssocItemConstraints, PredicateFilter, RegionInferReason,
25};
26
27#[derive(Debug, Default)]
28struct CollectedBound {
29    /// `Trait`
30    positive: bool,
31    /// `?Trait`
32    maybe: bool,
33    /// `!Trait`
34    negative: bool,
35}
36
37impl CollectedBound {
38    /// Returns `true` if any of `Trait`, `?Trait` or `!Trait` were encountered.
39    fn any(&self) -> bool {
40        self.positive || self.maybe || self.negative
41    }
42}
43
44#[derive(Debug)]
45struct CollectedSizednessBounds {
46    // Collected `Sized` bounds
47    sized: CollectedBound,
48    // Collected `MetaSized` bounds
49    meta_sized: CollectedBound,
50    // Collected `PointeeSized` bounds
51    pointee_sized: CollectedBound,
52}
53
54impl CollectedSizednessBounds {
55    /// Returns `true` if any of `Trait`, `?Trait` or `!Trait` were encountered for `Sized`,
56    /// `MetaSized` or `PointeeSized`.
57    fn any(&self) -> bool {
58        self.sized.any() || self.meta_sized.any() || self.pointee_sized.any()
59    }
60}
61
62fn search_bounds_for<'tcx>(
63    hir_bounds: &'tcx [hir::GenericBound<'tcx>],
64    context: ImpliedBoundsContext<'tcx>,
65    mut f: impl FnMut(&'tcx PolyTraitRef<'tcx>),
66) {
67    let mut search_bounds = |hir_bounds: &'tcx [hir::GenericBound<'tcx>]| {
68        for hir_bound in hir_bounds {
69            let hir::GenericBound::Trait(ptr) = hir_bound else {
70                continue;
71            };
72
73            f(ptr)
74        }
75    };
76
77    search_bounds(hir_bounds);
78    if let ImpliedBoundsContext::TyParam(self_ty, where_clause) = context {
79        for clause in where_clause {
80            if let hir::WherePredicateKind::BoundPredicate(pred) = clause.kind
81                && pred.is_param_bound(self_ty.to_def_id())
82            {
83                search_bounds(pred.bounds);
84            }
85        }
86    }
87}
88
89fn collect_relaxed_bounds<'tcx>(
90    hir_bounds: &'tcx [hir::GenericBound<'tcx>],
91    context: ImpliedBoundsContext<'tcx>,
92) -> SmallVec<[&'tcx PolyTraitRef<'tcx>; 1]> {
93    let mut relaxed_bounds: SmallVec<[_; 1]> = SmallVec::new();
94    search_bounds_for(hir_bounds, context, |ptr| {
95        if matches!(ptr.modifiers.polarity, hir::BoundPolarity::Maybe(_)) {
96            relaxed_bounds.push(ptr);
97        }
98    });
99    relaxed_bounds
100}
101
102fn collect_bounds<'a, 'tcx>(
103    hir_bounds: &'a [hir::GenericBound<'tcx>],
104    context: ImpliedBoundsContext<'tcx>,
105    target_did: DefId,
106) -> CollectedBound {
107    let mut collect_into = CollectedBound::default();
108    search_bounds_for(hir_bounds, context, |ptr| {
109        if !matches!(ptr.trait_ref.path.res, Res::Def(DefKind::Trait, did) if did == target_did) {
110            return;
111        }
112
113        match ptr.modifiers.polarity {
114            hir::BoundPolarity::Maybe(_) => collect_into.maybe = true,
115            hir::BoundPolarity::Negative(_) => collect_into.negative = true,
116            hir::BoundPolarity::Positive => collect_into.positive = true,
117        }
118    });
119    collect_into
120}
121
122fn collect_sizedness_bounds<'tcx>(
123    tcx: TyCtxt<'tcx>,
124    hir_bounds: &'tcx [hir::GenericBound<'tcx>],
125    context: ImpliedBoundsContext<'tcx>,
126    span: Span,
127) -> CollectedSizednessBounds {
128    let sized_did = tcx.require_lang_item(hir::LangItem::Sized, span);
129    let sized = collect_bounds(hir_bounds, context, sized_did);
130
131    let meta_sized_did = tcx.require_lang_item(hir::LangItem::MetaSized, span);
132    let meta_sized = collect_bounds(hir_bounds, context, meta_sized_did);
133
134    let pointee_sized_did = tcx.require_lang_item(hir::LangItem::PointeeSized, span);
135    let pointee_sized = collect_bounds(hir_bounds, context, pointee_sized_did);
136
137    CollectedSizednessBounds { sized, meta_sized, pointee_sized }
138}
139
140/// Add a trait bound for `did`.
141fn add_trait_bound<'tcx>(
142    tcx: TyCtxt<'tcx>,
143    bounds: &mut Vec<(ty::Clause<'tcx>, Span)>,
144    self_ty: Ty<'tcx>,
145    did: DefId,
146    span: Span,
147) {
148    let trait_ref = ty::TraitRef::new(tcx, did, [self_ty]);
149    // Preferable to put sizedness obligations first, since we report better errors for `Sized`
150    // ambiguity.
151    bounds.insert(0, (trait_ref.upcast(tcx), span));
152}
153
154impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
155    /// Adds sizedness bounds to a trait, trait alias, parameter, opaque type or associated type.
156    ///
157    /// - On parameters, opaque type and associated types, add default `Sized` bound if no explicit
158    ///   sizedness bounds are present.
159    /// - On traits and trait aliases, add default `MetaSized` supertrait if no explicit sizedness
160    ///   bounds are present.
161    /// - On parameters, opaque type, associated types and trait aliases, add a `MetaSized` bound if
162    ///   a `?Sized` bound is present.
163    pub(crate) fn add_implicit_sizedness_bounds(
164        &self,
165        bounds: &mut Vec<(ty::Clause<'tcx>, Span)>,
166        self_ty: Ty<'tcx>,
167        hir_bounds: &'tcx [hir::GenericBound<'tcx>],
168        context: ImpliedBoundsContext<'tcx>,
169        span: Span,
170    ) {
171        let tcx = self.tcx();
172
173        // Skip adding any default bounds if `#![rustc_no_implicit_bounds]`
174        if tcx.has_attr(CRATE_DEF_ID, sym::rustc_no_implicit_bounds) {
175            return;
176        }
177
178        let meta_sized_did = tcx.require_lang_item(hir::LangItem::MetaSized, span);
179        let pointee_sized_did = tcx.require_lang_item(hir::LangItem::PointeeSized, span);
180
181        // If adding sizedness bounds to a trait, then there are some relevant early exits
182        match context {
183            ImpliedBoundsContext::TraitDef(trait_did) => {
184                let trait_did = trait_did.to_def_id();
185                // Never add a default supertrait to `PointeeSized`.
186                if trait_did == pointee_sized_did {
187                    return;
188                }
189                // Don't add default sizedness supertraits to auto traits because it isn't possible to
190                // relax an automatically added supertrait on the defn itself.
191                if tcx.trait_is_auto(trait_did) {
192                    return;
193                }
194            }
195            ImpliedBoundsContext::TyParam(..) | ImpliedBoundsContext::AssociatedTypeOrImplTrait => {
196                // Report invalid relaxed bounds.
197                // FIXME: Since we only call this validation function here in this function, we only
198                //        fully validate relaxed bounds in contexts where we perform
199                //        "sized elaboration". In most cases that doesn't matter because we *usually*
200                //        reject such relaxed bounds outright during AST lowering.
201                //        However, this can easily get out of sync! Ideally, we would perform this step
202                //        where we are guaranteed to catch *all* bounds like in
203                //        `Self::lower_poly_trait_ref`. List of concrete issues:
204                //        FIXME(more_maybe_bounds): We don't call this for trait object tys, supertrait
205                //                                  bounds, trait alias bounds, assoc type bounds (ATB)!
206                let bounds = collect_relaxed_bounds(hir_bounds, context);
207                self.reject_duplicate_relaxed_bounds(bounds);
208            }
209        }
210
211        let collected = collect_sizedness_bounds(tcx, hir_bounds, context, span);
212        if (collected.sized.maybe || collected.sized.negative)
213            && !collected.sized.positive
214            && !collected.meta_sized.any()
215            && !collected.pointee_sized.any()
216        {
217            // `?Sized` is equivalent to `MetaSized` (but only add the bound if there aren't any
218            // other explicit ones) - this can happen for trait aliases as well as bounds.
219            add_trait_bound(tcx, bounds, self_ty, meta_sized_did, span);
220        } else if !collected.any() {
221            match context {
222                ImpliedBoundsContext::TraitDef(..) => {
223                    // If there are no explicit sizedness bounds on a trait then add a default
224                    // `MetaSized` supertrait.
225                    add_trait_bound(tcx, bounds, self_ty, meta_sized_did, span);
226                }
227                ImpliedBoundsContext::TyParam(..)
228                | ImpliedBoundsContext::AssociatedTypeOrImplTrait => {
229                    // If there are no explicit sizedness bounds on a parameter then add a default
230                    // `Sized` bound.
231                    let sized_did = tcx.require_lang_item(hir::LangItem::Sized, span);
232                    add_trait_bound(tcx, bounds, self_ty, sized_did, span);
233                }
234            }
235        }
236    }
237
238    pub(crate) fn add_default_traits(
239        &self,
240        bounds: &mut Vec<(ty::Clause<'tcx>, Span)>,
241        self_ty: Ty<'tcx>,
242        hir_bounds: &[hir::GenericBound<'tcx>],
243        context: ImpliedBoundsContext<'tcx>,
244        span: Span,
245    ) {
246        self.tcx().default_traits().iter().for_each(|default_trait| {
247            self.add_default_trait(*default_trait, bounds, self_ty, hir_bounds, context, span);
248        });
249    }
250
251    /// Add a `experimental_default_bounds` bound to the `bounds` if appropriate.
252    ///
253    /// Doesn't add the bound if the HIR bounds contain any of `Trait`, `?Trait` or `!Trait`.
254    pub(crate) fn add_default_trait(
255        &self,
256        trait_: hir::LangItem,
257        bounds: &mut Vec<(ty::Clause<'tcx>, Span)>,
258        self_ty: Ty<'tcx>,
259        hir_bounds: &[hir::GenericBound<'tcx>],
260        context: ImpliedBoundsContext<'tcx>,
261        span: Span,
262    ) {
263        let tcx = self.tcx();
264
265        // Supertraits for auto trait are unsound according to the unstable book:
266        // https://doc.rust-lang.org/beta/unstable-book/language-features/auto-traits.html#supertraits
267        if let ImpliedBoundsContext::TraitDef(trait_did) = context
268            && self.tcx().trait_is_auto(trait_did.into())
269        {
270            return;
271        }
272
273        if let Some(trait_did) = tcx.lang_items().get(trait_)
274            && self.should_add_default_traits(trait_did, hir_bounds, context)
275        {
276            add_trait_bound(tcx, bounds, self_ty, trait_did, span);
277        }
278    }
279
280    /// Returns `true` if default trait bound should be added.
281    fn should_add_default_traits<'a>(
282        &self,
283        trait_def_id: DefId,
284        hir_bounds: &'a [hir::GenericBound<'tcx>],
285        context: ImpliedBoundsContext<'tcx>,
286    ) -> bool {
287        let collected = collect_bounds(hir_bounds, context, trait_def_id);
288        !self.tcx().has_attr(CRATE_DEF_ID, sym::rustc_no_implicit_bounds) && !collected.any()
289    }
290
291    fn reject_duplicate_relaxed_bounds(&self, relaxed_bounds: SmallVec<[&PolyTraitRef<'_>; 1]>) {
292        let tcx = self.tcx();
293
294        let mut grouped_bounds = FxIndexMap::<_, Vec<_>>::default();
295
296        for bound in &relaxed_bounds {
297            if let Res::Def(DefKind::Trait, trait_def_id) = bound.trait_ref.path.res {
298                grouped_bounds.entry(trait_def_id).or_default().push(bound.span);
299            }
300        }
301
302        for (trait_def_id, spans) in grouped_bounds {
303            if spans.len() > 1 {
304                let name = tcx.item_name(trait_def_id);
305                self.dcx()
306                    .struct_span_err(spans, format!("duplicate relaxed `{name}` bounds"))
307                    .with_code(E0203)
308                    .emit();
309            }
310        }
311    }
312
313    pub(crate) fn require_bound_to_relax_default_trait(
314        &self,
315        trait_ref: hir::TraitRef<'_>,
316        span: Span,
317    ) {
318        let tcx = self.tcx();
319
320        if let Res::Def(DefKind::Trait, def_id) = trait_ref.path.res
321            && (tcx.is_lang_item(def_id, hir::LangItem::Sized) || tcx.is_default_trait(def_id))
322        {
323            return;
324        }
325
326        self.dcx().span_err(
327            span,
328            if tcx.sess.opts.unstable_opts.experimental_default_bounds
329                || tcx.features().more_maybe_bounds()
330            {
331                "bound modifier `?` can only be applied to default traits"
332            } else {
333                "bound modifier `?` can only be applied to `Sized`"
334            },
335        );
336    }
337
338    /// Lower HIR bounds into `bounds` given the self type `param_ty` and the overarching late-bound vars if any.
339    ///
340    /// ### Examples
341    ///
342    /// ```ignore (illustrative)
343    /// fn foo<T>() where for<'a> T: Trait<'a> + Copy {}
344    /// //                ^^^^^^^ ^  ^^^^^^^^^^^^^^^^ `hir_bounds`, in HIR form
345    /// //                |       |
346    /// //                |       `param_ty`, in ty form
347    /// //                `bound_vars`, in ty form
348    ///
349    /// fn bar<T>() where T: for<'a> Trait<'a> + Copy {} // no overarching `bound_vars` here!
350    /// //                ^  ^^^^^^^^^^^^^^^^^^^^^^^^ `hir_bounds`, in HIR form
351    /// //                |
352    /// //                `param_ty`, in ty form
353    /// ```
354    ///
355    /// ### A Note on Binders
356    ///
357    /// There is an implied binder around `param_ty` and `hir_bounds`.
358    /// See `lower_poly_trait_ref` for more details.
359    #[instrument(level = "debug", skip(self, hir_bounds, bounds))]
360    pub(crate) fn lower_bounds<'hir, I: IntoIterator<Item = &'hir hir::GenericBound<'tcx>>>(
361        &self,
362        param_ty: Ty<'tcx>,
363        hir_bounds: I,
364        bounds: &mut Vec<(ty::Clause<'tcx>, Span)>,
365        bound_vars: &'tcx ty::List<ty::BoundVariableKind>,
366        predicate_filter: PredicateFilter,
367        overlapping_assoc_constraints: OverlappingAsssocItemConstraints,
368    ) where
369        'tcx: 'hir,
370    {
371        for hir_bound in hir_bounds {
372            // In order to avoid cycles, when we're lowering `SelfTraitThatDefines`,
373            // we skip over any traits that don't define the given associated type.
374            if let PredicateFilter::SelfTraitThatDefines(assoc_ident) = predicate_filter {
375                if let Some(trait_ref) = hir_bound.trait_ref()
376                    && let Some(trait_did) = trait_ref.trait_def_id()
377                    && self.tcx().trait_may_define_assoc_item(trait_did, assoc_ident)
378                {
379                    // Okay
380                } else {
381                    continue;
382                }
383            }
384
385            match hir_bound {
386                hir::GenericBound::Trait(poly_trait_ref) => {
387                    let _ = self.lower_poly_trait_ref(
388                        poly_trait_ref,
389                        param_ty,
390                        bounds,
391                        predicate_filter,
392                        overlapping_assoc_constraints,
393                    );
394                }
395                hir::GenericBound::Outlives(lifetime) => {
396                    // `ConstIfConst` is only interested in `[const]` bounds.
397                    if matches!(
398                        predicate_filter,
399                        PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst
400                    ) {
401                        continue;
402                    }
403
404                    let region = self.lower_lifetime(lifetime, RegionInferReason::OutlivesBound);
405                    let bound = ty::Binder::bind_with_vars(
406                        ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(param_ty, region)),
407                        bound_vars,
408                    );
409                    bounds.push((bound.upcast(self.tcx()), lifetime.ident.span));
410                }
411                hir::GenericBound::Use(..) => {
412                    // We don't actually lower `use` into the type layer.
413                }
414            }
415        }
416    }
417
418    /// Lower an associated item constraint from the HIR into `bounds`.
419    ///
420    /// ### A Note on Binders
421    ///
422    /// Given something like `T: for<'a> Iterator<Item = &'a u32>`,
423    /// the `trait_ref` here will be `for<'a> T: Iterator`.
424    /// The `constraint` data however is from *inside* the binder
425    /// (e.g., `&'a u32`) and hence may reference bound regions.
426    #[instrument(level = "debug", skip(self, bounds, duplicates, path_span))]
427    pub(super) fn lower_assoc_item_constraint(
428        &self,
429        hir_ref_id: hir::HirId,
430        trait_ref: ty::PolyTraitRef<'tcx>,
431        constraint: &hir::AssocItemConstraint<'tcx>,
432        bounds: &mut Vec<(ty::Clause<'tcx>, Span)>,
433        duplicates: Option<&mut FxIndexMap<DefId, Span>>,
434        path_span: Span,
435        predicate_filter: PredicateFilter,
436    ) -> Result<(), ErrorGuaranteed> {
437        let tcx = self.tcx();
438
439        let assoc_tag = if constraint.gen_args.parenthesized
440            == hir::GenericArgsParentheses::ReturnTypeNotation
441        {
442            ty::AssocTag::Fn
443        } else if let hir::AssocItemConstraintKind::Equality { term: hir::Term::Const(_) } =
444            constraint.kind
445        {
446            ty::AssocTag::Const
447        } else {
448            ty::AssocTag::Type
449        };
450
451        // Given something like `U: Trait<T = X>`, we want to produce a predicate like
452        // `<U as Trait>::T = X`.
453        // This is somewhat subtle in the event that `T` is defined in a supertrait of `Trait`,
454        // because in that case we need to upcast. I.e., we want to produce
455        // `<B as SuperTrait<i32>>::T == X` for `B: SubTrait<T = X>` where
456        //
457        //     trait SubTrait: SuperTrait<i32> {}
458        //     trait SuperTrait<A> { type T; }
459        let candidate = if self.probe_trait_that_defines_assoc_item(
460            trait_ref.def_id(),
461            assoc_tag,
462            constraint.ident,
463        ) {
464            // Simple case: The assoc item is defined in the current trait.
465            trait_ref
466        } else {
467            // Otherwise, we have to walk through the supertraits to find
468            // one that does define it.
469            self.probe_single_bound_for_assoc_item(
470                || traits::supertraits(tcx, trait_ref),
471                AssocItemQSelf::Trait(trait_ref.def_id()),
472                assoc_tag,
473                constraint.ident,
474                path_span,
475                Some(constraint),
476            )?
477        };
478
479        let assoc_item = self
480            .probe_assoc_item(
481                constraint.ident,
482                assoc_tag,
483                hir_ref_id,
484                constraint.span,
485                candidate.def_id(),
486            )
487            .expect("failed to find associated item");
488
489        if let Some(duplicates) = duplicates {
490            duplicates
491                .entry(assoc_item.def_id)
492                .and_modify(|prev_span| {
493                    self.dcx().emit_err(errors::ValueOfAssociatedStructAlreadySpecified {
494                        span: constraint.span,
495                        prev_span: *prev_span,
496                        item_name: constraint.ident,
497                        def_path: tcx.def_path_str(assoc_item.container_id(tcx)),
498                    });
499                })
500                .or_insert(constraint.span);
501        }
502
503        let projection_term = if let ty::AssocTag::Fn = assoc_tag {
504            let bound_vars = tcx.late_bound_vars(constraint.hir_id);
505            ty::Binder::bind_with_vars(
506                self.lower_return_type_notation_ty(candidate, assoc_item.def_id, path_span)?.into(),
507                bound_vars,
508            )
509        } else {
510            // Create the generic arguments for the associated type or constant by joining the
511            // parent arguments (the arguments of the trait) and the own arguments (the ones of
512            // the associated item itself) and construct an alias type using them.
513            let alias_term = candidate.map_bound(|trait_ref| {
514                let item_segment = hir::PathSegment {
515                    ident: constraint.ident,
516                    hir_id: constraint.hir_id,
517                    res: Res::Err,
518                    args: Some(constraint.gen_args),
519                    infer_args: false,
520                };
521
522                let alias_args = self.lower_generic_args_of_assoc_item(
523                    path_span,
524                    assoc_item.def_id,
525                    &item_segment,
526                    trait_ref.args,
527                );
528                debug!(?alias_args);
529
530                ty::AliasTerm::new_from_args(tcx, assoc_item.def_id, alias_args)
531            });
532
533            // Provide the resolved type of the associated constant to `type_of(AnonConst)`.
534            if let Some(const_arg) = constraint.ct()
535                && let hir::ConstArgKind::Anon(anon_const) = const_arg.kind
536            {
537                let ty = alias_term
538                    .map_bound(|alias| tcx.type_of(alias.def_id).instantiate(tcx, alias.args));
539                let ty =
540                    check_assoc_const_binding_type(self, constraint.ident, ty, constraint.hir_id);
541                tcx.feed_anon_const_type(anon_const.def_id, ty::EarlyBinder::bind(ty));
542            }
543
544            alias_term
545        };
546
547        match constraint.kind {
548            hir::AssocItemConstraintKind::Equality { .. } if let ty::AssocTag::Fn = assoc_tag => {
549                return Err(self.dcx().emit_err(crate::errors::ReturnTypeNotationEqualityBound {
550                    span: constraint.span,
551                }));
552            }
553            // Lower an equality constraint like `Item = u32` as found in HIR bound `T: Iterator<Item = u32>`
554            // to a projection predicate: `<T as Iterator>::Item = u32`.
555            hir::AssocItemConstraintKind::Equality { term } => {
556                let term = match term {
557                    hir::Term::Ty(ty) => self.lower_ty(ty).into(),
558                    hir::Term::Const(ct) => self.lower_const_arg(ct, FeedConstTy::No).into(),
559                };
560
561                // Find any late-bound regions declared in `ty` that are not
562                // declared in the trait-ref or assoc_item. These are not well-formed.
563                //
564                // Example:
565                //
566                //     for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
567                //     for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
568                let late_bound_in_projection_ty =
569                    tcx.collect_constrained_late_bound_regions(projection_term);
570                let late_bound_in_term =
571                    tcx.collect_referenced_late_bound_regions(trait_ref.rebind(term));
572                debug!(?late_bound_in_projection_ty);
573                debug!(?late_bound_in_term);
574
575                // FIXME: point at the type params that don't have appropriate lifetimes:
576                // struct S1<F: for<'a> Fn(&i32, &i32) -> &'a i32>(F);
577                //                         ----  ----     ^^^^^^^
578                // NOTE(mgca): This error should be impossible to trigger with assoc const bindings.
579                self.validate_late_bound_regions(
580                    late_bound_in_projection_ty,
581                    late_bound_in_term,
582                    |br_name| {
583                        struct_span_code_err!(
584                            self.dcx(),
585                            constraint.span,
586                            E0582,
587                            "binding for associated type `{}` references {}, \
588                             which does not appear in the trait input types",
589                            constraint.ident,
590                            br_name
591                        )
592                    },
593                );
594
595                match predicate_filter {
596                    PredicateFilter::All
597                    | PredicateFilter::SelfOnly
598                    | PredicateFilter::SelfAndAssociatedTypeBounds => {
599                        let bound = projection_term.map_bound(|projection_term| {
600                            ty::ClauseKind::Projection(ty::ProjectionPredicate {
601                                projection_term,
602                                term,
603                            })
604                        });
605
606                        if let ty::AssocTag::Const = assoc_tag
607                            && !find_attr!(
608                                self.tcx().get_all_attrs(assoc_item.def_id),
609                                AttributeKind::TypeConst(_)
610                            )
611                        {
612                            if tcx.features().min_generic_const_args() {
613                                let mut err = self.dcx().struct_span_err(
614                                    constraint.span,
615                                    "use of trait associated const without `#[type_const]`",
616                                );
617                                err.note("the declaration in the trait must be marked with `#[type_const]`");
618                                return Err(err.emit());
619                            } else {
620                                let err = self.dcx().span_delayed_bug(
621                                    constraint.span,
622                                    "use of trait associated const without `#[type_const]`",
623                                );
624                                return Err(err);
625                            }
626                        } else {
627                            bounds.push((bound.upcast(tcx), constraint.span));
628                        }
629                    }
630                    // SelfTraitThatDefines is only interested in trait predicates.
631                    PredicateFilter::SelfTraitThatDefines(_) => {}
632                    // `ConstIfConst` is only interested in `[const]` bounds.
633                    PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {}
634                }
635            }
636            // Lower a constraint like `Item: Debug` as found in HIR bound `T: Iterator<Item: Debug>`
637            // to a bound involving a projection: `<T as Iterator>::Item: Debug`.
638            hir::AssocItemConstraintKind::Bound { bounds: hir_bounds } => {
639                match predicate_filter {
640                    PredicateFilter::All
641                    | PredicateFilter::SelfAndAssociatedTypeBounds
642                    | PredicateFilter::ConstIfConst => {
643                        let projection_ty = projection_term
644                            .map_bound(|projection_term| projection_term.expect_ty(self.tcx()));
645                        // Calling `skip_binder` is okay, because `lower_bounds` expects the `param_ty`
646                        // parameter to have a skipped binder.
647                        let param_ty =
648                            Ty::new_alias(tcx, ty::Projection, projection_ty.skip_binder());
649                        self.lower_bounds(
650                            param_ty,
651                            hir_bounds,
652                            bounds,
653                            projection_ty.bound_vars(),
654                            predicate_filter,
655                            OverlappingAsssocItemConstraints::Allowed,
656                        );
657                    }
658                    PredicateFilter::SelfOnly
659                    | PredicateFilter::SelfTraitThatDefines(_)
660                    | PredicateFilter::SelfConstIfConst => {}
661                }
662            }
663        }
664        Ok(())
665    }
666
667    /// Lower a type, possibly specially handling the type if it's a return type notation
668    /// which we otherwise deny in other positions.
669    pub fn lower_ty_maybe_return_type_notation(&self, hir_ty: &hir::Ty<'tcx>) -> Ty<'tcx> {
670        let hir::TyKind::Path(qpath) = hir_ty.kind else {
671            return self.lower_ty(hir_ty);
672        };
673
674        let tcx = self.tcx();
675        match qpath {
676            hir::QPath::Resolved(opt_self_ty, path)
677                if let [mod_segments @ .., trait_segment, item_segment] = &path.segments[..]
678                    && item_segment.args.is_some_and(|args| {
679                        matches!(
680                            args.parenthesized,
681                            hir::GenericArgsParentheses::ReturnTypeNotation
682                        )
683                    }) =>
684            {
685                // We don't allow generics on the module segments.
686                let _ =
687                    self.prohibit_generic_args(mod_segments.iter(), GenericsArgsErrExtend::None);
688
689                let item_def_id = match path.res {
690                    Res::Def(DefKind::AssocFn, item_def_id) => item_def_id,
691                    Res::Err => {
692                        return Ty::new_error_with_message(
693                            tcx,
694                            hir_ty.span,
695                            "failed to resolve RTN",
696                        );
697                    }
698                    _ => bug!("only expected method resolution for fully qualified RTN"),
699                };
700                let trait_def_id = tcx.parent(item_def_id);
701
702                // Good error for `where Trait::method(..): Send`.
703                let Some(self_ty) = opt_self_ty else {
704                    let guar = self.report_missing_self_ty_for_resolved_path(
705                        trait_def_id,
706                        hir_ty.span,
707                        item_segment,
708                        ty::AssocTag::Type,
709                    );
710                    return Ty::new_error(tcx, guar);
711                };
712                let self_ty = self.lower_ty(self_ty);
713
714                let trait_ref = self.lower_mono_trait_ref(
715                    hir_ty.span,
716                    trait_def_id,
717                    self_ty,
718                    trait_segment,
719                    false,
720                );
721
722                // SUBTLE: As noted at the end of `try_append_return_type_notation_params`
723                // in `resolve_bound_vars`, we stash the explicit bound vars of the where
724                // clause onto the item segment of the RTN type. This allows us to know
725                // how many bound vars are *not* coming from the signature of the function
726                // from lowering RTN itself.
727                //
728                // For example, in `where for<'a> <T as Trait<'a>>::method(..): Other`,
729                // the `late_bound_vars` of the where clause predicate (i.e. this HIR ty's
730                // parent) will include `'a` AND all the early- and late-bound vars of the
731                // method. But when lowering the RTN type, we just want the list of vars
732                // we used to resolve the trait ref. We explicitly stored those back onto
733                // the item segment, since there's no other good place to put them.
734                let candidate =
735                    ty::Binder::bind_with_vars(trait_ref, tcx.late_bound_vars(item_segment.hir_id));
736
737                match self.lower_return_type_notation_ty(candidate, item_def_id, hir_ty.span) {
738                    Ok(ty) => Ty::new_alias(tcx, ty::Projection, ty),
739                    Err(guar) => Ty::new_error(tcx, guar),
740                }
741            }
742            hir::QPath::TypeRelative(hir_self_ty, segment)
743                if segment.args.is_some_and(|args| {
744                    matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
745                }) =>
746            {
747                let self_ty = self.lower_ty(hir_self_ty);
748                let (item_def_id, bound) = match self.resolve_type_relative_path(
749                    self_ty,
750                    hir_self_ty,
751                    ty::AssocTag::Fn,
752                    segment,
753                    hir_ty.hir_id,
754                    hir_ty.span,
755                    None,
756                ) {
757                    Ok(result) => result,
758                    Err(guar) => return Ty::new_error(tcx, guar),
759                };
760
761                // Don't let `T::method` resolve to some `for<'a> <T as Tr<'a>>::method`,
762                // which may happen via a higher-ranked where clause or supertrait.
763                // This is the same restrictions as associated types; even though we could
764                // support it, it just makes things a lot more difficult to support in
765                // `resolve_bound_vars`, since we'd need to introduce those as elided
766                // bound vars on the where clause too.
767                if bound.has_bound_vars() {
768                    return Ty::new_error(
769                        tcx,
770                        self.dcx().emit_err(errors::AssociatedItemTraitUninferredGenericParams {
771                            span: hir_ty.span,
772                            inferred_sugg: Some(hir_ty.span.with_hi(segment.ident.span.lo())),
773                            bound: format!("{}::", tcx.anonymize_bound_vars(bound).skip_binder()),
774                            mpart_sugg: None,
775                            what: tcx.def_descr(item_def_id),
776                        }),
777                    );
778                }
779
780                match self.lower_return_type_notation_ty(bound, item_def_id, hir_ty.span) {
781                    Ok(ty) => Ty::new_alias(tcx, ty::Projection, ty),
782                    Err(guar) => Ty::new_error(tcx, guar),
783                }
784            }
785            _ => self.lower_ty(hir_ty),
786        }
787    }
788
789    /// Do the common parts of lowering an RTN type. This involves extending the
790    /// candidate binder to include all of the early- and late-bound vars that are
791    /// defined on the function itself, and constructing a projection to the RPITIT
792    /// return type of that function.
793    fn lower_return_type_notation_ty(
794        &self,
795        candidate: ty::PolyTraitRef<'tcx>,
796        item_def_id: DefId,
797        path_span: Span,
798    ) -> Result<ty::AliasTy<'tcx>, ErrorGuaranteed> {
799        let tcx = self.tcx();
800        let mut emitted_bad_param_err = None;
801        // If we have an method return type bound, then we need to instantiate
802        // the method's early bound params with suitable late-bound params.
803        let mut num_bound_vars = candidate.bound_vars().len();
804        let args = candidate.skip_binder().args.extend_to(tcx, item_def_id, |param, _| {
805            let arg = match param.kind {
806                ty::GenericParamDefKind::Lifetime => ty::Region::new_bound(
807                    tcx,
808                    ty::INNERMOST,
809                    ty::BoundRegion {
810                        var: ty::BoundVar::from_usize(num_bound_vars),
811                        kind: ty::BoundRegionKind::Named(param.def_id),
812                    },
813                )
814                .into(),
815                ty::GenericParamDefKind::Type { .. } => {
816                    let guar = *emitted_bad_param_err.get_or_insert_with(|| {
817                        self.dcx().emit_err(crate::errors::ReturnTypeNotationIllegalParam::Type {
818                            span: path_span,
819                            param_span: tcx.def_span(param.def_id),
820                        })
821                    });
822                    Ty::new_error(tcx, guar).into()
823                }
824                ty::GenericParamDefKind::Const { .. } => {
825                    let guar = *emitted_bad_param_err.get_or_insert_with(|| {
826                        self.dcx().emit_err(crate::errors::ReturnTypeNotationIllegalParam::Const {
827                            span: path_span,
828                            param_span: tcx.def_span(param.def_id),
829                        })
830                    });
831                    ty::Const::new_error(tcx, guar).into()
832                }
833            };
834            num_bound_vars += 1;
835            arg
836        });
837
838        // Next, we need to check that the return-type notation is being used on
839        // an RPITIT (return-position impl trait in trait) or AFIT (async fn in trait).
840        let output = tcx.fn_sig(item_def_id).skip_binder().output();
841        let output = if let ty::Alias(ty::Projection, alias_ty) = *output.skip_binder().kind()
842            && tcx.is_impl_trait_in_trait(alias_ty.def_id)
843        {
844            alias_ty
845        } else {
846            return Err(self.dcx().emit_err(crate::errors::ReturnTypeNotationOnNonRpitit {
847                span: path_span,
848                ty: tcx.liberate_late_bound_regions(item_def_id, output),
849                fn_span: tcx.hir_span_if_local(item_def_id),
850                note: (),
851            }));
852        };
853
854        // Finally, move the fn return type's bound vars over to account for the early bound
855        // params (and trait ref's late bound params). This logic is very similar to
856        // `rustc_middle::ty::predicate::Clause::instantiate_supertrait`
857        // and it's no coincidence why.
858        let shifted_output = tcx.shift_bound_var_indices(num_bound_vars, output);
859        Ok(ty::EarlyBinder::bind(shifted_output).instantiate(tcx, args))
860    }
861}
862
863/// Detect and reject early-bound & escaping late-bound generic params in the type of assoc const bindings.
864///
865/// FIXME(const_generics): This is a temporary and semi-artificial restriction until the
866/// arrival of *generic const generics*[^1].
867///
868/// It might actually be possible that we can already support early-bound generic params
869/// in such types if we just lifted some more checks in other places, too, for example
870/// inside `HirTyLowerer::lower_anon_const`. However, even if that were the case, we should
871/// probably gate this behind another feature flag.
872///
873/// [^1]: <https://github.com/rust-lang/project-const-generics/issues/28>.
874fn check_assoc_const_binding_type<'tcx>(
875    cx: &dyn HirTyLowerer<'tcx>,
876    assoc_const: Ident,
877    ty: ty::Binder<'tcx, Ty<'tcx>>,
878    hir_id: hir::HirId,
879) -> Ty<'tcx> {
880    // We can't perform the checks for early-bound params during name resolution unlike E0770
881    // because this information depends on *type* resolution.
882    // We can't perform these checks in `resolve_bound_vars` either for the same reason.
883    // Consider the trait ref `for<'a> Trait<'a, C = { &0 }>`. We need to know the fully
884    // resolved type of `Trait::C` in order to know if it references `'a` or not.
885
886    let ty = ty.skip_binder();
887    if !ty.has_param() && !ty.has_escaping_bound_vars() {
888        return ty;
889    }
890
891    let mut collector = GenericParamAndBoundVarCollector {
892        cx,
893        params: Default::default(),
894        vars: Default::default(),
895        depth: ty::INNERMOST,
896    };
897    let mut guar = ty.visit_with(&mut collector).break_value();
898
899    let tcx = cx.tcx();
900    let ty_note = ty
901        .make_suggestable(tcx, false, None)
902        .map(|ty| crate::errors::TyOfAssocConstBindingNote { assoc_const, ty });
903
904    let enclosing_item_owner_id = tcx
905        .hir_parent_owner_iter(hir_id)
906        .find_map(|(owner_id, parent)| parent.generics().map(|_| owner_id))
907        .unwrap();
908    let generics = tcx.generics_of(enclosing_item_owner_id);
909    for index in collector.params {
910        let param = generics.param_at(index as _, tcx);
911        let is_self_param = param.name == kw::SelfUpper;
912        guar.get_or_insert(cx.dcx().emit_err(crate::errors::ParamInTyOfAssocConstBinding {
913            span: assoc_const.span,
914            assoc_const,
915            param_name: param.name,
916            param_def_kind: tcx.def_descr(param.def_id),
917            param_category: if is_self_param {
918                "self"
919            } else if param.kind.is_synthetic() {
920                "synthetic"
921            } else {
922                "normal"
923            },
924            param_defined_here_label:
925                (!is_self_param).then(|| tcx.def_ident_span(param.def_id).unwrap()),
926            ty_note,
927        }));
928    }
929    for var_def_id in collector.vars {
930        guar.get_or_insert(cx.dcx().emit_err(
931            crate::errors::EscapingBoundVarInTyOfAssocConstBinding {
932                span: assoc_const.span,
933                assoc_const,
934                var_name: cx.tcx().item_name(var_def_id),
935                var_def_kind: tcx.def_descr(var_def_id),
936                var_defined_here_label: tcx.def_ident_span(var_def_id).unwrap(),
937                ty_note,
938            },
939        ));
940    }
941
942    let guar = guar.unwrap_or_else(|| bug!("failed to find gen params or bound vars in ty"));
943    Ty::new_error(tcx, guar)
944}
945
946struct GenericParamAndBoundVarCollector<'a, 'tcx> {
947    cx: &'a dyn HirTyLowerer<'tcx>,
948    params: FxIndexSet<u32>,
949    vars: FxIndexSet<DefId>,
950    depth: ty::DebruijnIndex,
951}
952
953impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for GenericParamAndBoundVarCollector<'_, 'tcx> {
954    type Result = ControlFlow<ErrorGuaranteed>;
955
956    fn visit_binder<T: TypeVisitable<TyCtxt<'tcx>>>(
957        &mut self,
958        binder: &ty::Binder<'tcx, T>,
959    ) -> Self::Result {
960        self.depth.shift_in(1);
961        let result = binder.super_visit_with(self);
962        self.depth.shift_out(1);
963        result
964    }
965
966    fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
967        match ty.kind() {
968            ty::Param(param) => {
969                self.params.insert(param.index);
970            }
971            ty::Bound(ty::BoundVarIndexKind::Bound(db), bt) if *db >= self.depth => {
972                self.vars.insert(match bt.kind {
973                    ty::BoundTyKind::Param(def_id) => def_id,
974                    ty::BoundTyKind::Anon => {
975                        let reported = self
976                            .cx
977                            .dcx()
978                            .delayed_bug(format!("unexpected anon bound ty: {:?}", bt.var));
979                        return ControlFlow::Break(reported);
980                    }
981                });
982            }
983            _ if ty.has_param() || ty.has_bound_vars() => return ty.super_visit_with(self),
984            _ => {}
985        }
986        ControlFlow::Continue(())
987    }
988
989    fn visit_region(&mut self, re: ty::Region<'tcx>) -> Self::Result {
990        match re.kind() {
991            ty::ReEarlyParam(param) => {
992                self.params.insert(param.index);
993            }
994            ty::ReBound(ty::BoundVarIndexKind::Bound(db), br) if db >= self.depth => {
995                self.vars.insert(match br.kind {
996                    ty::BoundRegionKind::Named(def_id) => def_id,
997                    ty::BoundRegionKind::Anon | ty::BoundRegionKind::ClosureEnv => {
998                        let guar = self
999                            .cx
1000                            .dcx()
1001                            .delayed_bug(format!("unexpected bound region kind: {:?}", br.kind));
1002                        return ControlFlow::Break(guar);
1003                    }
1004                    ty::BoundRegionKind::NamedAnon(_) => bug!("only used for pretty printing"),
1005                });
1006            }
1007            _ => {}
1008        }
1009        ControlFlow::Continue(())
1010    }
1011
1012    fn visit_const(&mut self, ct: ty::Const<'tcx>) -> Self::Result {
1013        match ct.kind() {
1014            ty::ConstKind::Param(param) => {
1015                self.params.insert(param.index);
1016            }
1017            ty::ConstKind::Bound(ty::BoundVarIndexKind::Bound(db), _) if db >= self.depth => {
1018                let guar = self.cx.dcx().delayed_bug("unexpected escaping late-bound const var");
1019                return ControlFlow::Break(guar);
1020            }
1021            _ if ct.has_param() || ct.has_bound_vars() => return ct.super_visit_with(self),
1022            _ => {}
1023        }
1024        ControlFlow::Continue(())
1025    }
1026}