Skip to main content

rustc_hir_analysis/hir_ty_lowering/
generics.rs

1use rustc_ast::ast::ParamKindOrd;
2use rustc_errors::codes::*;
3use rustc_errors::{
4    Applicability, Diag, DiagCtxtHandle, Diagnostic, ErrorGuaranteed, Level, MultiSpan,
5    struct_span_code_err,
6};
7use rustc_hir::def::{DefKind, Res};
8use rustc_hir::def_id::DefId;
9use rustc_hir::{self as hir, GenericArg};
10use rustc_lint_defs::builtin::LATE_BOUND_LIFETIME_ARGUMENTS;
11use rustc_middle::ty::{
12    self, GenericArgsRef, GenericParamDef, GenericParamDefKind, IsSuggestable, Ty,
13};
14use rustc_span::kw;
15use rustc_trait_selection::traits;
16use smallvec::SmallVec;
17use tracing::{debug, instrument};
18
19use super::{HirTyLowerer, IsMethodCall};
20use crate::diagnostics::wrong_number_of_generic_args::{GenericArgsInfo, WrongNumberOfGenericArgs};
21use crate::hir_ty_lowering::errors::prohibit_assoc_item_constraint;
22use crate::hir_ty_lowering::{
23    ExplicitLateBound, GenericArgCountMismatch, GenericArgCountResult, GenericArgPosition,
24    GenericArgsLowerer,
25};
26
27/// Report an error that a generic argument did not match the generic parameter that was
28/// expected.
29fn generic_arg_mismatch_err(
30    cx: &dyn HirTyLowerer<'_>,
31    arg: &GenericArg<'_>,
32    param: &GenericParamDef,
33    possible_ordering_error: bool,
34    help: Option<String>,
35) -> ErrorGuaranteed {
36    let tcx = cx.tcx();
37    let sess = tcx.sess;
38    let mut err = {
    cx.dcx().struct_span_err(arg.span(),
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("{0} provided when a {1} was expected",
                            arg.descr(), param.kind.descr()))
                })).with_code(E0747)
}struct_span_code_err!(
39        cx.dcx(),
40        arg.span(),
41        E0747,
42        "{} provided when a {} was expected",
43        arg.descr(),
44        param.kind.descr(),
45    );
46
47    let add_braces_suggestion = |arg: &GenericArg<'_>, err: &mut Diag<'_>| {
48        let suggestions = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(arg.span().shrink_to_lo(), String::from("{ ")),
                (arg.span().shrink_to_hi(), String::from(" }"))]))vec![
49            (arg.span().shrink_to_lo(), String::from("{ ")),
50            (arg.span().shrink_to_hi(), String::from(" }")),
51        ];
52        err.multipart_suggestion(
53            "if this generic argument was intended as a const parameter, \
54                 surround it with braces",
55            suggestions,
56            Applicability::MaybeIncorrect,
57        );
58    };
59
60    // Specific suggestion set for diagnostics
61    match (arg, &param.kind) {
62        (
63            GenericArg::Type(hir::Ty {
64                kind: hir::TyKind::Path(rustc_hir::QPath::Resolved(_, path)),
65                ..
66            }),
67            GenericParamDefKind::Const { .. },
68        ) => match path.res {
69            Res::Err => {
70                add_braces_suggestion(arg, &mut err);
71                return err
72                    .with_primary_message("unresolved item provided when a constant was expected")
73                    .emit_err();
74            }
75            Res::Def(DefKind::TyParam, src_def_id) => {
76                if let Some(param_local_id) = param.def_id.as_local() {
77                    let param_name = tcx.hir_ty_param_name(param_local_id);
78                    let param_type =
79                        tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip();
80                    if param_type.is_suggestable(tcx, false) {
81                        err.span_suggestion_verbose(
82                            tcx.def_span(src_def_id),
83                            "consider changing this type parameter to a const parameter",
84                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("const {0}: {1}", param_name,
                param_type))
    })format!("const {param_name}: {param_type}"),
85                            Applicability::MaybeIncorrect,
86                        );
87                    };
88                }
89            }
90            _ => add_braces_suggestion(arg, &mut err),
91        },
92        (
93            GenericArg::Type(hir::Ty { kind: hir::TyKind::Path(_), .. }),
94            GenericParamDefKind::Const { .. },
95        ) => add_braces_suggestion(arg, &mut err),
96        (
97            GenericArg::Type(hir::Ty { kind: hir::TyKind::Array(_, len), .. }),
98            GenericParamDefKind::Const { .. },
99        ) if tcx.type_of(param.def_id).skip_binder() == tcx.types.usize => {
100            err.span_label(arg.span(), "array type provided where a `usize` was expected");
101            let snippet = sess.source_map().span_to_snippet(tcx.hir_span(len.hir_id));
102            if let Ok(snippet) = snippet {
103                let sugg = if let hir::ConstArgKind::Anon(hir::AnonConst { body, .. }) = len.kind
104                    && let hir::ExprKind::Lit(..) = tcx.hir_body(*body).value.kind
105                {
106                    // We don't need to surround literals in braces when used as consts
107                    snippet
108                } else if let hir::ConstArgKind::Literal { .. } = len.kind {
109                    // We don't need to surround literals in braces when used as consts
110                    snippet
111                } else {
112                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{{ {0} }}", snippet))
    })format!("{{ {snippet} }}")
113                };
114                err.span_suggestion_verbose(
115                    arg.span(),
116                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("you might have meant to use the array\'s length\'s value"))
    })format!("you might have meant to use the array's length's value"),
117                    sugg,
118                    Applicability::MaybeIncorrect,
119                );
120            }
121        }
122        (GenericArg::Const(cnst), GenericParamDefKind::Type { .. }) => {
123            if let hir::ConstArgKind::Path(qpath) = cnst.kind
124                && let rustc_hir::QPath::Resolved(_, path) = qpath
125                && let Res::Def(DefKind::Fn { .. }, id) = path.res
126            {
127                err.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is a function item, not a type",
                tcx.item_name(id)))
    })format!("`{}` is a function item, not a type", tcx.item_name(id)));
128                err.help("function item types cannot be named directly");
129            } else if let hir::ConstArgKind::Anon(anon) = cnst.kind
130                && let body = tcx.hir_body(anon.body)
131                && let rustc_hir::ExprKind::Path(rustc_hir::QPath::Resolved(_, path)) =
132                    body.value.kind
133                && let Res::Def(DefKind::Fn { .. }, id) = path.res
134            {
135                // FIXME(mgca): this branch is dead once new const path lowering
136                // (for single-segment paths) is no longer gated
137                err.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is a function item, not a type",
                tcx.item_name(id)))
    })format!("`{}` is a function item, not a type", tcx.item_name(id)));
138                err.help("function item types cannot be named directly");
139            }
140        }
141        _ => {}
142    }
143
144    let kind_ord = param.kind.to_ord();
145    let arg_ord = arg.to_ord();
146
147    // This note is only true when generic parameters are strictly ordered by their kind.
148    if possible_ordering_error && kind_ord.cmp(&arg_ord) != core::cmp::Ordering::Equal {
149        let (first, last) = if kind_ord < arg_ord {
150            (param.kind.descr(), arg.descr())
151        } else {
152            (arg.descr(), param.kind.descr())
153        };
154        err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} arguments must be provided before {1} arguments",
                first, last))
    })format!("{first} arguments must be provided before {last} arguments"));
155        if let Some(help) = help {
156            err.help(help);
157        }
158    }
159
160    err.emit_err()
161}
162
163/// Lower generic arguments from the HIR to the [`rustc_middle::ty`] representation.
164///
165/// This is a rather complex function. Let us try to explain the role
166/// of each of its parameters:
167///
168/// To start, we are given the `def_id` of the thing whose generic parameters we
169/// are creating, and a partial set of arguments `parent_args`. In general,
170/// the generic arguments for an item begin with arguments for all the "parents"
171/// of that item -- e.g., for a method it might include the parameters from the impl.
172///
173/// Therefore, the method begins by walking down these parents,
174/// starting with the outermost parent and proceed inwards until
175/// it reaches `def_id`. For each parent `P`, it will check `parent_args`
176/// first to see if the parent's arguments are listed in there. If so,
177/// we can append those and move on. Otherwise, it uses the provided
178/// [`GenericArgsLowerer`] `ctx` which has the following methods:
179///
180/// - `args_for_def_id`: given the `DefId` `P`, supplies back the
181///   generic arguments that were given to that parent from within
182///   the path; so e.g., if you have `<T as Foo>::Bar`, the `DefId`
183///   might refer to the trait `Foo`, and the arguments might be
184///   `[T]`. The boolean value indicates whether to infer values
185///   for arguments whose values were not explicitly provided.
186/// - `provided_kind`: given the generic parameter and the value
187///   from `args_for_def_id`, creating a `GenericArg`.
188/// - `inferred_kind`: if no parameter was provided, and inference
189///   is enabled, then creates a suitable inference variable.
190pub fn lower_generic_args<'tcx: 'a, 'a>(
191    cx: &dyn HirTyLowerer<'tcx>,
192    def_id: DefId,
193    parent_args: &[ty::GenericArg<'tcx>],
194    has_self: bool,
195    self_ty: Option<Ty<'tcx>>,
196    arg_count: &GenericArgCountResult,
197    ctx: &mut impl GenericArgsLowerer<'a, 'tcx>,
198) -> GenericArgsRef<'tcx> {
199    let tcx = cx.tcx();
200    // Collect the segments of the path; we need to instantiate arguments
201    // for parameters throughout the entire path (wherever there are
202    // generic parameters).
203    let mut parent_defs = tcx.generics_of(def_id);
204    let count = parent_defs.count();
205    let mut stack = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(def_id, parent_defs)]))vec![(def_id, parent_defs)];
206    while let Some(def_id) = parent_defs.parent {
207        parent_defs = tcx.generics_of(def_id);
208        stack.push((def_id, parent_defs));
209    }
210
211    // We manually build up the generic arguments, rather than using convenience
212    // methods in `rustc_middle/src/ty/generic_args.rs`, so that we can iterate over the arguments and
213    // parameters in lock-step linearly, instead of trying to match each pair.
214    let mut args: SmallVec<[ty::GenericArg<'tcx>; 8]> = SmallVec::with_capacity(count);
215    // Iterate over each segment of the path.
216    while let Some((def_id, defs)) = stack.pop() {
217        let mut params = defs.own_params.iter().peekable();
218
219        // If we have already computed the generic arguments for parents,
220        // we can use those directly.
221        while let Some(&param) = params.peek() {
222            if let Some(&kind) = parent_args.get(param.index as usize) {
223                args.push(kind);
224                params.next();
225            } else {
226                break;
227            }
228        }
229
230        // `Self` is handled first, unless it's been handled in `parent_args`.
231        if has_self {
232            if let Some(&param) = params.peek() {
233                if param.index == 0 {
234                    if let GenericParamDefKind::Type { .. } = param.kind {
235                        {
    match (&&args[..], &&[]) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(&args[..], &[]);
236                        args.push(
237                            self_ty
238                                .map(|ty| ty.into())
239                                .unwrap_or_else(|| ctx.inferred_kind(&args, param, true)),
240                        );
241                        params.next();
242                    }
243                }
244            }
245        }
246
247        // Check whether this segment takes generic arguments and the user has provided any.
248        let (generic_args, infer_args) = ctx.args_for_def_id(def_id);
249
250        let mut args_iter =
251            generic_args.iter().flat_map(|generic_args| generic_args.args.iter()).peekable();
252
253        // If we encounter a type or const when we expect a lifetime, we infer the lifetimes.
254        // If we later encounter a lifetime, we know that the arguments were provided in the
255        // wrong order. `force_infer_lt` records the type or const that forced lifetimes to be
256        // inferred, so we can use it for diagnostics later.
257        let mut force_infer_lt = None;
258
259        loop {
260            // We're going to iterate through the generic arguments that the user
261            // provided, matching them with the generic parameters we expect.
262            // Mismatches can occur as a result of elided lifetimes, or for malformed
263            // input. We try to handle both sensibly.
264            match (args_iter.peek(), params.peek()) {
265                (Some(&arg), Some(&param)) => {
266                    match (arg, &param.kind, arg_count.explicit_late_bound) {
267                        (GenericArg::Lifetime(_), GenericParamDefKind::Lifetime, _)
268                        | (
269                            GenericArg::Type(_)
270                            | GenericArg::Infer(hir::InferArg {
271                                kind: hir::InferArgKind::TypeOrConst,
272                                ..
273                            }),
274                            GenericParamDefKind::Type { .. },
275                            _,
276                        )
277                        | (
278                            GenericArg::Const(_) | GenericArg::Infer(_),
279                            GenericParamDefKind::Const { .. },
280                            _,
281                        ) => {
282                            // We lower to an infer even when the feature gate is not enabled
283                            // as it is useful for diagnostics to be able to see a `ConstKind::Infer`
284                            args.push(ctx.provided_kind(&args, param, arg));
285                            args_iter.next();
286                            params.next();
287                        }
288                        (
289                            GenericArg::Infer(_) | GenericArg::Type(_) | GenericArg::Const(_),
290                            GenericParamDefKind::Lifetime,
291                            _,
292                        ) => {
293                            // We expected a lifetime argument, but got a type or const
294                            // argument. That means we're inferring the lifetimes.
295                            args.push(ctx.inferred_kind(&args, param, infer_args));
296                            force_infer_lt = Some((arg, param));
297                            params.next();
298                        }
299                        (GenericArg::Lifetime(_), _, ExplicitLateBound::Yes) => {
300                            // We've come across a lifetime when we expected something else in
301                            // the presence of explicit late bounds. This is most likely
302                            // due to the presence of the explicit bound so we're just going to
303                            // ignore it.
304                            args_iter.next();
305                        }
306                        (_, _, _) => {
307                            // We expected one kind of parameter, but the user provided
308                            // another. This is an error. However, if we already know that
309                            // the arguments don't match up with the parameters, we won't issue
310                            // an additional error, as the user already knows what's wrong.
311                            if arg_count.correct.is_ok() {
312                                // We're going to iterate over the parameters to sort them out, and
313                                // show that order to the user as a possible order for the parameters
314                                let mut param_types_present = defs
315                                    .own_params
316                                    .iter()
317                                    .map(|param| (param.kind.to_ord(), param.clone()))
318                                    .collect::<Vec<(ParamKindOrd, GenericParamDef)>>();
319                                param_types_present.sort_by_key(|(ord, _)| *ord);
320                                let (mut param_types_present, ordered_params): (
321                                    Vec<ParamKindOrd>,
322                                    Vec<GenericParamDef>,
323                                ) = param_types_present.into_iter().unzip();
324                                param_types_present.dedup();
325
326                                generic_arg_mismatch_err(
327                                    cx,
328                                    arg,
329                                    param,
330                                    !args_iter.clone().is_sorted_by_key(|arg| arg.to_ord()),
331                                    Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("reorder the arguments: {0}: `<{1}>`",
                param_types_present.into_iter().map(|ord|
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("{0}s", ord))
                                    })).collect::<Vec<String>>().join(", then "),
                ordered_params.into_iter().filter_map(|param|
                                {
                                    if param.name == kw::SelfUpper {
                                        None
                                    } else { Some(param.name.to_string()) }
                                }).collect::<Vec<String>>().join(", ")))
    })format!(
332                                        "reorder the arguments: {}: `<{}>`",
333                                        param_types_present
334                                            .into_iter()
335                                            .map(|ord| format!("{ord}s"))
336                                            .collect::<Vec<String>>()
337                                            .join(", then "),
338                                        ordered_params
339                                            .into_iter()
340                                            .filter_map(|param| {
341                                                if param.name == kw::SelfUpper {
342                                                    None
343                                                } else {
344                                                    Some(param.name.to_string())
345                                                }
346                                            })
347                                            .collect::<Vec<String>>()
348                                            .join(", ")
349                                    )),
350                                );
351                            }
352
353                            // We've reported the error, but we want to make sure that this
354                            // problem doesn't bubble down and create additional, irrelevant
355                            // errors. In this case, we're simply going to ignore the argument
356                            // and any following arguments. The rest of the parameters will be
357                            // inferred.
358                            while args_iter.next().is_some() {}
359                        }
360                    }
361                }
362
363                (Some(&arg), None) => {
364                    // We should never be able to reach this point with well-formed input.
365                    // There are three situations in which we can encounter this issue.
366                    //
367                    //  1. The number of arguments is incorrect. In this case, an error
368                    //     will already have been emitted, and we can ignore it.
369                    //  2. There are late-bound lifetime parameters present, yet the
370                    //     lifetime arguments have also been explicitly specified by the
371                    //     user.
372                    //  3. We've inferred some lifetimes, which have been provided later (i.e.
373                    //     after a type or const). We want to throw an error in this case.
374
375                    if arg_count.correct.is_ok()
376                        && arg_count.explicit_late_bound == ExplicitLateBound::No
377                    {
378                        let kind = arg.descr();
379                        {
    match (&kind, &"lifetime") {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(kind, "lifetime");
380                        let (provided_arg, param) =
381                            force_infer_lt.expect("lifetimes ought to have been inferred");
382                        generic_arg_mismatch_err(cx, provided_arg, param, false, None);
383                    }
384
385                    break;
386                }
387
388                (None, Some(&param)) => {
389                    // If there are fewer arguments than parameters, it means
390                    // we're inferring the remaining arguments.
391                    args.push(ctx.inferred_kind(&args, param, infer_args));
392                    params.next();
393                }
394
395                (None, None) => break,
396            }
397        }
398    }
399
400    tcx.mk_args(&args)
401}
402
403/// Checks that the correct number of generic arguments have been provided.
404/// Used specifically for function calls.
405pub fn check_generic_arg_count_for_value_path(
406    cx: &dyn HirTyLowerer<'_>,
407    def_id: DefId,
408    generics: &ty::Generics,
409    seg: &hir::PathSegment<'_>,
410    is_method_call: IsMethodCall,
411) -> GenericArgCountResult {
412    let gen_pos = GenericArgPosition::Value(is_method_call);
413    check_generic_arg_count(cx, def_id, seg, generics, gen_pos, generics.has_own_self())
414}
415
416/// Checks that the correct number of generic arguments have been provided.
417/// This is used both for datatypes and function calls.
418{}
#[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("check_generic_arg_count",
                                    "rustc_hir_analysis::hir_ty_lowering::generics",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_hir_analysis/src/hir_ty_lowering/generics.rs"),
                                    ::tracing_core::__macro_support::Option::Some(418u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering::generics"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("seg")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("seg");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("gen_params")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("gen_params");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("has_self")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("has_self");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&seg)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&gen_params)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&has_self as
                                                            &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: GenericArgCountResult = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let gen_args = seg.args();
            let default_counts = gen_params.own_defaults();
            let param_counts = gen_params.own_counts();
            let has_invalid_bound =
                match seg.args {
                    Some(args) =>
                        args.constraints.iter().any(|c|
                                {
                                    if let hir::AssocItemConstraintKind::Bound {
                                                bounds: [hir::GenericBound::Trait(poly_trait_ref)] } =
                                                c.kind && let Res::Err = poly_trait_ref.trait_ref.path.res {
                                        true
                                    } else { false }
                                }),
                    None => false,
                };
            let synth_type_param_count =
                gen_params.own_params.iter().filter(|param|
                            #[allow(non_exhaustive_omitted_patterns)] match param.kind {
                                ty::GenericParamDefKind::Type { synthetic: true, .. } =>
                                    true,
                                _ => false,
                            }).count();
            let named_type_param_count =
                param_counts.types - has_self as usize -
                    synth_type_param_count;
            let named_const_param_count = param_counts.consts;
            let infer_lifetimes =
                (gen_pos != GenericArgPosition::Type || seg.infer_args) &&
                    !gen_args.has_lifetime_args();
            if gen_pos != GenericArgPosition::Type &&
                    let Some(c) = gen_args.constraints.first() {
                prohibit_assoc_item_constraint(cx, c, None);
            }
            let tcx = cx.tcx();
            let explicit_late_bound =
                match seg.delegation_child_segment {
                    true => ExplicitLateBound::No,
                    false =>
                        prohibit_explicit_late_bound_lifetimes(cx, gen_params,
                            gen_args, gen_pos),
                };
            let mut invalid_args = ::alloc::vec::Vec::new();
            let mut check_lifetime_args =
                |min_expected_args: usize, max_expected_args: usize,
                    provided_args: usize, late_bounds_ignore: bool|
                    {
                        if (min_expected_args..=max_expected_args).contains(&provided_args)
                            {
                            return Ok(());
                        }
                        if late_bounds_ignore { return Ok(()); }
                        invalid_args.extend(min_expected_args..provided_args);
                        let gen_args_info =
                            if provided_args > min_expected_args {
                                let num_redundant_args = provided_args - min_expected_args;
                                GenericArgsInfo::ExcessLifetimes { num_redundant_args }
                            } else {
                                let num_missing_args = min_expected_args - provided_args;
                                GenericArgsInfo::MissingLifetimes { num_missing_args }
                            };
                        let reported =
                            cx.dcx().emit_err(WrongNumberOfGenericArgs::new(tcx,
                                    gen_args_info, seg, gen_params, has_self as usize, gen_args,
                                    def_id, cx.item_def_id()));
                        Err(reported)
                    };
            let min_expected_lifetime_args =
                if infer_lifetimes { 0 } else { param_counts.lifetimes };
            let max_expected_lifetime_args = param_counts.lifetimes;
            let num_provided_lifetime_args = gen_args.num_lifetime_args();
            let lifetimes_correct =
                check_lifetime_args(min_expected_lifetime_args,
                    max_expected_lifetime_args, num_provided_lifetime_args,
                    explicit_late_bound == ExplicitLateBound::Yes);
            let mut check_types_and_consts =
                |expected_min, expected_max, expected_max_with_synth,
                    provided, params_offset, args_offset|
                    {
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event /rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_hir_analysis/src/hir_ty_lowering/generics.rs:529",
                                                "rustc_hir_analysis::hir_ty_lowering::generics",
                                                ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_hir_analysis/src/hir_ty_lowering/generics.rs"),
                                                ::tracing_core::__macro_support::Option::Some(529u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering::generics"),
                                                ::tracing_core::field::FieldSet::new(&["message",
                                                                {
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("expected_min")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("expected_min");
                                                                    NAME.as_str()
                                                                },
                                                                {
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("expected_max")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("expected_max");
                                                                    NAME.as_str()
                                                                },
                                                                {
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("provided")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("provided");
                                                                    NAME.as_str()
                                                                },
                                                                {
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("params_offset")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("params_offset");
                                                                    NAME.as_str()
                                                                },
                                                                {
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("args_offset")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("args_offset");
                                                                    NAME.as_str()
                                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("check_types_and_consts")
                                                                    as &dyn ::tracing::field::Value)),
                                                        (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected_min)
                                                                    as &dyn ::tracing::field::Value)),
                                                        (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected_max)
                                                                    as &dyn ::tracing::field::Value)),
                                                        (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&provided)
                                                                    as &dyn ::tracing::field::Value)),
                                                        (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&params_offset)
                                                                    as &dyn ::tracing::field::Value)),
                                                        (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&args_offset)
                                                                    as &dyn ::tracing::field::Value))])
                                    });
                            } else { ; }
                        };
                        if (expected_min..=expected_max).contains(&provided) {
                            return Ok(());
                        }
                        let num_default_params = expected_max - expected_min;
                        let mut all_params_are_binded = false;
                        let gen_args_info =
                            if provided > expected_max {
                                invalid_args.extend((expected_max..provided).map(|i|
                                            i + args_offset));
                                let num_redundant_args = provided - expected_max;
                                let synth_provided = provided <= expected_max_with_synth;
                                GenericArgsInfo::ExcessTypesOrConsts {
                                    num_redundant_args,
                                    num_default_params,
                                    args_offset,
                                    synth_provided,
                                }
                            } else {
                                let parent_is_impl_block =
                                    cx.tcx().hir_parent_owner_iter(seg.hir_id).next().is_some_and(|(_,
                                                owner_node)| owner_node.is_impl_block());
                                if parent_is_impl_block {
                                    let constraint_names: Vec<_> =
                                        gen_args.constraints.iter().map(|b| b.ident.name).collect();
                                    let param_names: Vec<_> =
                                        gen_params.own_params.iter().filter(|param|
                                                        !has_self ||
                                                            param.index != 0).map(|param| param.name).collect();
                                    if constraint_names == param_names {
                                        let has_assoc_ty_with_same_name =
                                            if let DefKind::Trait = tcx.def_kind(def_id) {
                                                gen_args.constraints.iter().any(|constraint|
                                                        {
                                                            traits::supertrait_def_ids(tcx,
                                                                    def_id).any(|trait_did|
                                                                    {
                                                                        cx.probe_trait_that_defines_assoc_item(trait_did,
                                                                            ty::AssocTag::Type, constraint.ident)
                                                                    })
                                                        })
                                            } else { false };
                                        all_params_are_binded = !has_assoc_ty_with_same_name;
                                    };
                                }
                                let num_missing_args = expected_max - provided;
                                GenericArgsInfo::MissingTypesOrConsts {
                                    num_missing_args,
                                    num_default_params,
                                    args_offset,
                                }
                            };
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event /rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_hir_analysis/src/hir_ty_lowering/generics.rs:609",
                                                "rustc_hir_analysis::hir_ty_lowering::generics",
                                                ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_hir_analysis/src/hir_ty_lowering/generics.rs"),
                                                ::tracing_core::__macro_support::Option::Some(609u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering::generics"),
                                                ::tracing_core::field::FieldSet::new(&[{
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("gen_args_info")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("gen_args_info");
                                                                    NAME.as_str()
                                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&gen_args_info)
                                                                    as &dyn ::tracing::field::Value))])
                                    });
                            } else { ; }
                        };
                        let reported =
                            gen_args.has_err().unwrap_or_else(||
                                    {
                                        cx.dcx().create_err(WrongNumberOfGenericArgs::new(tcx,
                                                    gen_args_info, seg, gen_params, params_offset, gen_args,
                                                    def_id,
                                                    cx.item_def_id())).emit_err_unless_delay(all_params_are_binded
                                                || has_invalid_bound)
                                    });
                        Err(reported)
                    };
            let args_correct =
                {
                    let expected_min =
                        if seg.infer_args {
                            0
                        } else {
                            param_counts.consts + named_type_param_count -
                                    default_counts.types - default_counts.consts
                        };
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event /rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_hir_analysis/src/hir_ty_lowering/generics.rs:637",
                                            "rustc_hir_analysis::hir_ty_lowering::generics",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("/rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_hir_analysis/src/hir_ty_lowering/generics.rs"),
                                            ::tracing_core::__macro_support::Option::Some(637u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering::generics"),
                                            ::tracing_core::field::FieldSet::new(&[{
                                                                const NAME:
                                                                    ::tracing::__macro_support::FieldName<{
                                                                        ::tracing::__macro_support::FieldName::len("expected_min")
                                                                    }> =
                                                                    ::tracing::__macro_support::FieldName::new("expected_min");
                                                                NAME.as_str()
                                                            }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected_min)
                                                                as &dyn ::tracing::field::Value))])
                                });
                        } else { ; }
                    };
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event /rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_hir_analysis/src/hir_ty_lowering/generics.rs:638",
                                            "rustc_hir_analysis::hir_ty_lowering::generics",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("/rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_hir_analysis/src/hir_ty_lowering/generics.rs"),
                                            ::tracing_core::__macro_support::Option::Some(638u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering::generics"),
                                            ::tracing_core::field::FieldSet::new(&[{
                                                                const NAME:
                                                                    ::tracing::__macro_support::FieldName<{
                                                                        ::tracing::__macro_support::FieldName::len("arg_counts.lifetimes")
                                                                    }> =
                                                                    ::tracing::__macro_support::FieldName::new("arg_counts.lifetimes");
                                                                NAME.as_str()
                                                            }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&gen_args.num_lifetime_args())
                                                                as &dyn ::tracing::field::Value))])
                                });
                        } else { ; }
                    };
                    let provided = gen_args.num_generic_params();
                    check_types_and_consts(expected_min,
                        named_const_param_count + named_type_param_count,
                        named_const_param_count + named_type_param_count +
                            synth_type_param_count, provided,
                        param_counts.lifetimes + has_self as usize,
                        gen_args.num_lifetime_args())
                };
            GenericArgCountResult {
                explicit_late_bound,
                correct: lifetimes_correct.and(args_correct).map_err(|reported|
                        GenericArgCountMismatch { reported, invalid_args }),
            }
        }
    }
}#[instrument(skip(cx, gen_pos), level = "debug")]
419pub(crate) fn check_generic_arg_count(
420    cx: &dyn HirTyLowerer<'_>,
421    def_id: DefId,
422    seg: &hir::PathSegment<'_>,
423    gen_params: &ty::Generics,
424    gen_pos: GenericArgPosition,
425    has_self: bool,
426) -> GenericArgCountResult {
427    let gen_args = seg.args();
428    let default_counts = gen_params.own_defaults();
429    let param_counts = gen_params.own_counts();
430    // If we have any `Vec<foo: Bar>` constraint, where `Bar` is unresolved, the user likely meant
431    // to write `Vec<foo::Bar>`, so we silence the incorrect number of generics error.
432    let has_invalid_bound = match seg.args {
433        Some(args) => args.constraints.iter().any(|c| {
434            if let hir::AssocItemConstraintKind::Bound {
435                bounds: [hir::GenericBound::Trait(poly_trait_ref)],
436            } = c.kind
437                && let Res::Err = poly_trait_ref.trait_ref.path.res
438            {
439                true
440            } else {
441                false
442            }
443        }),
444        None => false,
445    };
446
447    // Subtracting from param count to ensure type params synthesized from `impl Trait`
448    // cannot be explicitly specified.
449    let synth_type_param_count = gen_params
450        .own_params
451        .iter()
452        .filter(|param| matches!(param.kind, ty::GenericParamDefKind::Type { synthetic: true, .. }))
453        .count();
454    let named_type_param_count = param_counts.types - has_self as usize - synth_type_param_count;
455    let named_const_param_count = param_counts.consts;
456    let infer_lifetimes =
457        (gen_pos != GenericArgPosition::Type || seg.infer_args) && !gen_args.has_lifetime_args();
458
459    if gen_pos != GenericArgPosition::Type
460        && let Some(c) = gen_args.constraints.first()
461    {
462        prohibit_assoc_item_constraint(cx, c, None);
463    }
464
465    let tcx = cx.tcx();
466
467    // Suppress this warning for delegations as it is compiler generated and lifetimes are
468    // propagated while late-bound lifetimes may be present.
469    let explicit_late_bound = match seg.delegation_child_segment {
470        true => ExplicitLateBound::No,
471        false => prohibit_explicit_late_bound_lifetimes(cx, gen_params, gen_args, gen_pos),
472    };
473
474    let mut invalid_args = vec![];
475
476    let mut check_lifetime_args = |min_expected_args: usize,
477                                   max_expected_args: usize,
478                                   provided_args: usize,
479                                   late_bounds_ignore: bool| {
480        if (min_expected_args..=max_expected_args).contains(&provided_args) {
481            return Ok(());
482        }
483
484        if late_bounds_ignore {
485            return Ok(());
486        }
487
488        invalid_args.extend(min_expected_args..provided_args);
489
490        let gen_args_info = if provided_args > min_expected_args {
491            let num_redundant_args = provided_args - min_expected_args;
492            GenericArgsInfo::ExcessLifetimes { num_redundant_args }
493        } else {
494            let num_missing_args = min_expected_args - provided_args;
495            GenericArgsInfo::MissingLifetimes { num_missing_args }
496        };
497
498        let reported = cx.dcx().emit_err(WrongNumberOfGenericArgs::new(
499            tcx,
500            gen_args_info,
501            seg,
502            gen_params,
503            has_self as usize,
504            gen_args,
505            def_id,
506            cx.item_def_id(),
507        ));
508
509        Err(reported)
510    };
511
512    let min_expected_lifetime_args = if infer_lifetimes { 0 } else { param_counts.lifetimes };
513    let max_expected_lifetime_args = param_counts.lifetimes;
514    let num_provided_lifetime_args = gen_args.num_lifetime_args();
515
516    let lifetimes_correct = check_lifetime_args(
517        min_expected_lifetime_args,
518        max_expected_lifetime_args,
519        num_provided_lifetime_args,
520        explicit_late_bound == ExplicitLateBound::Yes,
521    );
522
523    let mut check_types_and_consts = |expected_min,
524                                      expected_max,
525                                      expected_max_with_synth,
526                                      provided,
527                                      params_offset,
528                                      args_offset| {
529        debug!(
530            ?expected_min,
531            ?expected_max,
532            ?provided,
533            ?params_offset,
534            ?args_offset,
535            "check_types_and_consts"
536        );
537        if (expected_min..=expected_max).contains(&provided) {
538            return Ok(());
539        }
540
541        let num_default_params = expected_max - expected_min;
542
543        let mut all_params_are_binded = false;
544        let gen_args_info = if provided > expected_max {
545            invalid_args.extend((expected_max..provided).map(|i| i + args_offset));
546            let num_redundant_args = provided - expected_max;
547
548            // Provide extra note if synthetic arguments like `impl Trait` are specified.
549            let synth_provided = provided <= expected_max_with_synth;
550
551            GenericArgsInfo::ExcessTypesOrConsts {
552                num_redundant_args,
553                num_default_params,
554                args_offset,
555                synth_provided,
556            }
557        } else {
558            // Check if associated type bounds are incorrectly written in impl block header like:
559            // ```
560            // trait Foo<T> {}
561            // impl Foo<T: Default> for u8 {}
562            // ```
563            let parent_is_impl_block = cx
564                .tcx()
565                .hir_parent_owner_iter(seg.hir_id)
566                .next()
567                .is_some_and(|(_, owner_node)| owner_node.is_impl_block());
568            if parent_is_impl_block {
569                let constraint_names: Vec<_> =
570                    gen_args.constraints.iter().map(|b| b.ident.name).collect();
571                let param_names: Vec<_> = gen_params
572                    .own_params
573                    .iter()
574                    .filter(|param| !has_self || param.index != 0) // Assumes `Self` will always be the first parameter
575                    .map(|param| param.name)
576                    .collect();
577                if constraint_names == param_names {
578                    let has_assoc_ty_with_same_name = if let DefKind::Trait = tcx.def_kind(def_id) {
579                        gen_args.constraints.iter().any(|constraint| {
580                            traits::supertrait_def_ids(tcx, def_id).any(|trait_did| {
581                                cx.probe_trait_that_defines_assoc_item(
582                                    trait_did,
583                                    ty::AssocTag::Type,
584                                    constraint.ident,
585                                )
586                            })
587                        })
588                    } else {
589                        false
590                    };
591                    // We set this to true and delay emitting `WrongNumberOfGenericArgs`
592                    // to provide a succinct error for cases like issue #113073,
593                    // but only if when we don't have any assoc type with the same name with a
594                    // generic arg. Otherwise it will cause an ICE due to a delayed error because we
595                    // don't have any error other than `WrongNumberOfGenericArgs`.
596                    all_params_are_binded = !has_assoc_ty_with_same_name;
597                };
598            }
599
600            let num_missing_args = expected_max - provided;
601
602            GenericArgsInfo::MissingTypesOrConsts {
603                num_missing_args,
604                num_default_params,
605                args_offset,
606            }
607        };
608
609        debug!(?gen_args_info);
610
611        let reported = gen_args.has_err().unwrap_or_else(|| {
612            cx.dcx()
613                .create_err(WrongNumberOfGenericArgs::new(
614                    tcx,
615                    gen_args_info,
616                    seg,
617                    gen_params,
618                    params_offset,
619                    gen_args,
620                    def_id,
621                    cx.item_def_id(),
622                ))
623                .emit_err_unless_delay(all_params_are_binded || has_invalid_bound)
624        });
625
626        Err(reported)
627    };
628
629    let args_correct = {
630        let expected_min = if seg.infer_args {
631            0
632        } else {
633            param_counts.consts + named_type_param_count
634                - default_counts.types
635                - default_counts.consts
636        };
637        debug!(?expected_min);
638        debug!(arg_counts.lifetimes=?gen_args.num_lifetime_args());
639
640        let provided = gen_args.num_generic_params();
641
642        check_types_and_consts(
643            expected_min,
644            named_const_param_count + named_type_param_count,
645            named_const_param_count + named_type_param_count + synth_type_param_count,
646            provided,
647            param_counts.lifetimes + has_self as usize,
648            gen_args.num_lifetime_args(),
649        )
650    };
651
652    GenericArgCountResult {
653        explicit_late_bound,
654        correct: lifetimes_correct
655            .and(args_correct)
656            .map_err(|reported| GenericArgCountMismatch { reported, invalid_args }),
657    }
658}
659
660/// Prohibits explicit lifetime arguments if late-bound lifetime parameters
661/// are present. This is used both for datatypes and function calls.
662pub(crate) fn prohibit_explicit_late_bound_lifetimes(
663    cx: &dyn HirTyLowerer<'_>,
664    def: &ty::Generics,
665    args: &hir::GenericArgs<'_>,
666    position: GenericArgPosition,
667) -> ExplicitLateBound {
668    struct LifetimeArgsIssue {
669        msg: &'static str,
670    }
671
672    impl<'a> Diagnostic<'a> for LifetimeArgsIssue {
673        fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a> {
674            let Self { msg } = self;
675            Diag::new(dcx, level, msg)
676        }
677    }
678
679    let param_counts = def.own_counts();
680
681    if let Some(span_late) = def.has_late_bound_regions
682        && args.has_lifetime_args()
683    {
684        let msg = "cannot specify lifetime arguments explicitly \
685                       if late bound lifetime parameters are present";
686        let note = "the late bound lifetime parameter is introduced here";
687        let span = args.args[0].span();
688
689        if position == GenericArgPosition::Value(IsMethodCall::No)
690            && args.num_lifetime_args() != param_counts.lifetimes
691        {
692            {
    cx.dcx().struct_span_err(span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("{0}", msg))
                })).with_code(E0794)
}struct_span_code_err!(cx.dcx(), span, E0794, "{}", msg)
693                .with_span_note(span_late, note)
694                .emit();
695        } else {
696            let mut multispan = MultiSpan::from_span(span);
697            multispan.push_span_label(span_late, note);
698            cx.tcx().emit_node_span_lint(
699                LATE_BOUND_LIFETIME_ARGUMENTS,
700                args.args[0].hir_id(),
701                multispan,
702                LifetimeArgsIssue { msg },
703            );
704        }
705
706        ExplicitLateBound::Yes
707    } else {
708        ExplicitLateBound::No
709    }
710}