rustc_hir_analysis/hir_ty_lowering/
generics.rs

1use rustc_ast::ast::ParamKindOrd;
2use rustc_errors::codes::*;
3use rustc_errors::{Applicability, Diag, ErrorGuaranteed, MultiSpan, struct_span_code_err};
4use rustc_hir::def::{DefKind, Res};
5use rustc_hir::def_id::DefId;
6use rustc_hir::{self as hir, GenericArg};
7use rustc_middle::ty::{
8    self, GenericArgsRef, GenericParamDef, GenericParamDefKind, IsSuggestable, Ty,
9};
10use rustc_session::lint::builtin::LATE_BOUND_LIFETIME_ARGUMENTS;
11use rustc_span::kw;
12use smallvec::SmallVec;
13use tracing::{debug, instrument};
14
15use super::{HirTyLowerer, IsMethodCall};
16use crate::errors::wrong_number_of_generic_args::{GenericArgsInfo, WrongNumberOfGenericArgs};
17use crate::hir_ty_lowering::errors::prohibit_assoc_item_constraint;
18use crate::hir_ty_lowering::{
19    ExplicitLateBound, GenericArgCountMismatch, GenericArgCountResult, GenericArgPosition,
20    GenericArgsLowerer,
21};
22
23/// Report an error that a generic argument did not match the generic parameter that was
24/// expected.
25fn generic_arg_mismatch_err(
26    cx: &dyn HirTyLowerer<'_>,
27    arg: &GenericArg<'_>,
28    param: &GenericParamDef,
29    possible_ordering_error: bool,
30    help: Option<String>,
31) -> ErrorGuaranteed {
32    let tcx = cx.tcx();
33    let sess = tcx.sess;
34    let mut err = struct_span_code_err!(
35        cx.dcx(),
36        arg.span(),
37        E0747,
38        "{} provided when a {} was expected",
39        arg.descr(),
40        param.kind.descr(),
41    );
42
43    let add_braces_suggestion = |arg: &GenericArg<'_>, err: &mut Diag<'_>| {
44        let suggestions = vec![
45            (arg.span().shrink_to_lo(), String::from("{ ")),
46            (arg.span().shrink_to_hi(), String::from(" }")),
47        ];
48        err.multipart_suggestion(
49            "if this generic argument was intended as a const parameter, \
50                 surround it with braces",
51            suggestions,
52            Applicability::MaybeIncorrect,
53        );
54    };
55
56    // Specific suggestion set for diagnostics
57    match (arg, &param.kind) {
58        (
59            GenericArg::Type(hir::Ty {
60                kind: hir::TyKind::Path(rustc_hir::QPath::Resolved(_, path)),
61                ..
62            }),
63            GenericParamDefKind::Const { .. },
64        ) => match path.res {
65            Res::Err => {
66                add_braces_suggestion(arg, &mut err);
67                return err
68                    .with_primary_message("unresolved item provided when a constant was expected")
69                    .emit();
70            }
71            Res::Def(DefKind::TyParam, src_def_id) => {
72                if let Some(param_local_id) = param.def_id.as_local() {
73                    let param_name = tcx.hir_ty_param_name(param_local_id);
74                    let param_type = tcx.type_of(param.def_id).instantiate_identity();
75                    if param_type.is_suggestable(tcx, false) {
76                        err.span_suggestion_verbose(
77                            tcx.def_span(src_def_id),
78                            "consider changing this type parameter to a const parameter",
79                            format!("const {param_name}: {param_type}"),
80                            Applicability::MaybeIncorrect,
81                        );
82                    };
83                }
84            }
85            _ => add_braces_suggestion(arg, &mut err),
86        },
87        (
88            GenericArg::Type(hir::Ty { kind: hir::TyKind::Path(_), .. }),
89            GenericParamDefKind::Const { .. },
90        ) => add_braces_suggestion(arg, &mut err),
91        (
92            GenericArg::Type(hir::Ty { kind: hir::TyKind::Array(_, len), .. }),
93            GenericParamDefKind::Const { .. },
94        ) if tcx.type_of(param.def_id).skip_binder() == tcx.types.usize => {
95            let snippet = sess.source_map().span_to_snippet(tcx.hir_span(len.hir_id));
96            if let Ok(snippet) = snippet {
97                err.span_suggestion(
98                    arg.span(),
99                    "array type provided where a `usize` was expected, try",
100                    format!("{{ {snippet} }}"),
101                    Applicability::MaybeIncorrect,
102                );
103            }
104        }
105        (GenericArg::Const(cnst), GenericParamDefKind::Type { .. }) => {
106            if let hir::ConstArgKind::Path(qpath) = cnst.kind
107                && let rustc_hir::QPath::Resolved(_, path) = qpath
108                && let Res::Def(DefKind::Fn { .. }, id) = path.res
109            {
110                err.help(format!("`{}` is a function item, not a type", tcx.item_name(id)));
111                err.help("function item types cannot be named directly");
112            } else if let hir::ConstArgKind::Anon(anon) = cnst.kind
113                && let body = tcx.hir_body(anon.body)
114                && let rustc_hir::ExprKind::Path(rustc_hir::QPath::Resolved(_, path)) =
115                    body.value.kind
116                && let Res::Def(DefKind::Fn { .. }, id) = path.res
117            {
118                // FIXME(mgca): this branch is dead once new const path lowering
119                // (for single-segment paths) is no longer gated
120                err.help(format!("`{}` is a function item, not a type", tcx.item_name(id)));
121                err.help("function item types cannot be named directly");
122            }
123        }
124        _ => {}
125    }
126
127    let kind_ord = param.kind.to_ord();
128    let arg_ord = arg.to_ord();
129
130    // This note is only true when generic parameters are strictly ordered by their kind.
131    if possible_ordering_error && kind_ord.cmp(&arg_ord) != core::cmp::Ordering::Equal {
132        let (first, last) = if kind_ord < arg_ord {
133            (param.kind.descr(), arg.descr())
134        } else {
135            (arg.descr(), param.kind.descr())
136        };
137        err.note(format!("{first} arguments must be provided before {last} arguments"));
138        if let Some(help) = help {
139            err.help(help);
140        }
141    }
142
143    err.emit()
144}
145
146/// Lower generic arguments from the HIR to the [`rustc_middle::ty`] representation.
147///
148/// This is a rather complex function. Let us try to explain the role
149/// of each of its parameters:
150///
151/// To start, we are given the `def_id` of the thing whose generic parameters we
152/// are creating, and a partial set of arguments `parent_args`. In general,
153/// the generic arguments for an item begin with arguments for all the "parents"
154/// of that item -- e.g., for a method it might include the parameters from the impl.
155///
156/// Therefore, the method begins by walking down these parents,
157/// starting with the outermost parent and proceed inwards until
158/// it reaches `def_id`. For each parent `P`, it will check `parent_args`
159/// first to see if the parent's arguments are listed in there. If so,
160/// we can append those and move on. Otherwise, it uses the provided
161/// [`GenericArgsLowerer`] `ctx` which has the following methods:
162///
163/// - `args_for_def_id`: given the `DefId` `P`, supplies back the
164///   generic arguments that were given to that parent from within
165///   the path; so e.g., if you have `<T as Foo>::Bar`, the `DefId`
166///   might refer to the trait `Foo`, and the arguments might be
167///   `[T]`. The boolean value indicates whether to infer values
168///   for arguments whose values were not explicitly provided.
169/// - `provided_kind`: given the generic parameter and the value
170///   from `args_for_def_id`, creating a `GenericArg`.
171/// - `inferred_kind`: if no parameter was provided, and inference
172///   is enabled, then creates a suitable inference variable.
173pub fn lower_generic_args<'tcx: 'a, 'a>(
174    cx: &dyn HirTyLowerer<'tcx>,
175    def_id: DefId,
176    parent_args: &[ty::GenericArg<'tcx>],
177    has_self: bool,
178    self_ty: Option<Ty<'tcx>>,
179    arg_count: &GenericArgCountResult,
180    ctx: &mut impl GenericArgsLowerer<'a, 'tcx>,
181) -> GenericArgsRef<'tcx> {
182    let tcx = cx.tcx();
183    // Collect the segments of the path; we need to instantiate arguments
184    // for parameters throughout the entire path (wherever there are
185    // generic parameters).
186    let mut parent_defs = tcx.generics_of(def_id);
187    let count = parent_defs.count();
188    let mut stack = vec![(def_id, parent_defs)];
189    while let Some(def_id) = parent_defs.parent {
190        parent_defs = tcx.generics_of(def_id);
191        stack.push((def_id, parent_defs));
192    }
193
194    // We manually build up the generic arguments, rather than using convenience
195    // methods in `rustc_middle/src/ty/generic_args.rs`, so that we can iterate over the arguments and
196    // parameters in lock-step linearly, instead of trying to match each pair.
197    let mut args: SmallVec<[ty::GenericArg<'tcx>; 8]> = SmallVec::with_capacity(count);
198    // Iterate over each segment of the path.
199    while let Some((def_id, defs)) = stack.pop() {
200        let mut params = defs.own_params.iter().peekable();
201
202        // If we have already computed the generic arguments for parents,
203        // we can use those directly.
204        while let Some(&param) = params.peek() {
205            if let Some(&kind) = parent_args.get(param.index as usize) {
206                args.push(kind);
207                params.next();
208            } else {
209                break;
210            }
211        }
212
213        // `Self` is handled first, unless it's been handled in `parent_args`.
214        if has_self {
215            if let Some(&param) = params.peek() {
216                if param.index == 0 {
217                    if let GenericParamDefKind::Type { .. } = param.kind {
218                        assert_eq!(&args[..], &[]);
219                        args.push(
220                            self_ty
221                                .map(|ty| ty.into())
222                                .unwrap_or_else(|| ctx.inferred_kind(&args, param, true)),
223                        );
224                        params.next();
225                    }
226                }
227            }
228        }
229
230        // Check whether this segment takes generic arguments and the user has provided any.
231        let (generic_args, infer_args) = ctx.args_for_def_id(def_id);
232
233        let mut args_iter =
234            generic_args.iter().flat_map(|generic_args| generic_args.args.iter()).peekable();
235
236        // If we encounter a type or const when we expect a lifetime, we infer the lifetimes.
237        // If we later encounter a lifetime, we know that the arguments were provided in the
238        // wrong order. `force_infer_lt` records the type or const that forced lifetimes to be
239        // inferred, so we can use it for diagnostics later.
240        let mut force_infer_lt = None;
241
242        loop {
243            // We're going to iterate through the generic arguments that the user
244            // provided, matching them with the generic parameters we expect.
245            // Mismatches can occur as a result of elided lifetimes, or for malformed
246            // input. We try to handle both sensibly.
247            match (args_iter.peek(), params.peek()) {
248                (Some(&arg), Some(&param)) => {
249                    match (arg, &param.kind, arg_count.explicit_late_bound) {
250                        (GenericArg::Lifetime(_), GenericParamDefKind::Lifetime, _)
251                        | (
252                            GenericArg::Type(_) | GenericArg::Infer(_),
253                            GenericParamDefKind::Type { .. },
254                            _,
255                        )
256                        | (
257                            GenericArg::Const(_) | GenericArg::Infer(_),
258                            GenericParamDefKind::Const { .. },
259                            _,
260                        ) => {
261                            // We lower to an infer even when the feature gate is not enabled
262                            // as it is useful for diagnostics to be able to see a `ConstKind::Infer`
263                            args.push(ctx.provided_kind(&args, param, arg));
264                            args_iter.next();
265                            params.next();
266                        }
267                        (
268                            GenericArg::Infer(_) | GenericArg::Type(_) | GenericArg::Const(_),
269                            GenericParamDefKind::Lifetime,
270                            _,
271                        ) => {
272                            // We expected a lifetime argument, but got a type or const
273                            // argument. That means we're inferring the lifetimes.
274                            args.push(ctx.inferred_kind(&args, param, infer_args));
275                            force_infer_lt = Some((arg, param));
276                            params.next();
277                        }
278                        (GenericArg::Lifetime(_), _, ExplicitLateBound::Yes) => {
279                            // We've come across a lifetime when we expected something else in
280                            // the presence of explicit late bounds. This is most likely
281                            // due to the presence of the explicit bound so we're just going to
282                            // ignore it.
283                            args_iter.next();
284                        }
285                        (_, _, _) => {
286                            // We expected one kind of parameter, but the user provided
287                            // another. This is an error. However, if we already know that
288                            // the arguments don't match up with the parameters, we won't issue
289                            // an additional error, as the user already knows what's wrong.
290                            if arg_count.correct.is_ok() {
291                                // We're going to iterate over the parameters to sort them out, and
292                                // show that order to the user as a possible order for the parameters
293                                let mut param_types_present = defs
294                                    .own_params
295                                    .iter()
296                                    .map(|param| (param.kind.to_ord(), param.clone()))
297                                    .collect::<Vec<(ParamKindOrd, GenericParamDef)>>();
298                                param_types_present.sort_by_key(|(ord, _)| *ord);
299                                let (mut param_types_present, ordered_params): (
300                                    Vec<ParamKindOrd>,
301                                    Vec<GenericParamDef>,
302                                ) = param_types_present.into_iter().unzip();
303                                param_types_present.dedup();
304
305                                generic_arg_mismatch_err(
306                                    cx,
307                                    arg,
308                                    param,
309                                    !args_iter.clone().is_sorted_by_key(|arg| arg.to_ord()),
310                                    Some(format!(
311                                        "reorder the arguments: {}: `<{}>`",
312                                        param_types_present
313                                            .into_iter()
314                                            .map(|ord| format!("{ord}s"))
315                                            .collect::<Vec<String>>()
316                                            .join(", then "),
317                                        ordered_params
318                                            .into_iter()
319                                            .filter_map(|param| {
320                                                if param.name == kw::SelfUpper {
321                                                    None
322                                                } else {
323                                                    Some(param.name.to_string())
324                                                }
325                                            })
326                                            .collect::<Vec<String>>()
327                                            .join(", ")
328                                    )),
329                                );
330                            }
331
332                            // We've reported the error, but we want to make sure that this
333                            // problem doesn't bubble down and create additional, irrelevant
334                            // errors. In this case, we're simply going to ignore the argument
335                            // and any following arguments. The rest of the parameters will be
336                            // inferred.
337                            while args_iter.next().is_some() {}
338                        }
339                    }
340                }
341
342                (Some(&arg), None) => {
343                    // We should never be able to reach this point with well-formed input.
344                    // There are three situations in which we can encounter this issue.
345                    //
346                    //  1. The number of arguments is incorrect. In this case, an error
347                    //     will already have been emitted, and we can ignore it.
348                    //  2. There are late-bound lifetime parameters present, yet the
349                    //     lifetime arguments have also been explicitly specified by the
350                    //     user.
351                    //  3. We've inferred some lifetimes, which have been provided later (i.e.
352                    //     after a type or const). We want to throw an error in this case.
353
354                    if arg_count.correct.is_ok()
355                        && arg_count.explicit_late_bound == ExplicitLateBound::No
356                    {
357                        let kind = arg.descr();
358                        assert_eq!(kind, "lifetime");
359                        let (provided_arg, param) =
360                            force_infer_lt.expect("lifetimes ought to have been inferred");
361                        generic_arg_mismatch_err(cx, provided_arg, param, false, None);
362                    }
363
364                    break;
365                }
366
367                (None, Some(&param)) => {
368                    // If there are fewer arguments than parameters, it means
369                    // we're inferring the remaining arguments.
370                    args.push(ctx.inferred_kind(&args, param, infer_args));
371                    params.next();
372                }
373
374                (None, None) => break,
375            }
376        }
377    }
378
379    tcx.mk_args(&args)
380}
381
382/// Checks that the correct number of generic arguments have been provided.
383/// Used specifically for function calls.
384pub fn check_generic_arg_count_for_call(
385    cx: &dyn HirTyLowerer<'_>,
386    def_id: DefId,
387    generics: &ty::Generics,
388    seg: &hir::PathSegment<'_>,
389    is_method_call: IsMethodCall,
390) -> GenericArgCountResult {
391    let gen_pos = match is_method_call {
392        IsMethodCall::Yes => GenericArgPosition::MethodCall,
393        IsMethodCall::No => GenericArgPosition::Value,
394    };
395    let has_self = generics.parent.is_none() && generics.has_self;
396    check_generic_arg_count(cx, def_id, seg, generics, gen_pos, has_self)
397}
398
399/// Checks that the correct number of generic arguments have been provided.
400/// This is used both for datatypes and function calls.
401#[instrument(skip(cx, gen_pos), level = "debug")]
402pub(crate) fn check_generic_arg_count(
403    cx: &dyn HirTyLowerer<'_>,
404    def_id: DefId,
405    seg: &hir::PathSegment<'_>,
406    gen_params: &ty::Generics,
407    gen_pos: GenericArgPosition,
408    has_self: bool,
409) -> GenericArgCountResult {
410    let gen_args = seg.args();
411    let default_counts = gen_params.own_defaults();
412    let param_counts = gen_params.own_counts();
413
414    // Subtracting from param count to ensure type params synthesized from `impl Trait`
415    // cannot be explicitly specified.
416    let synth_type_param_count = gen_params
417        .own_params
418        .iter()
419        .filter(|param| matches!(param.kind, ty::GenericParamDefKind::Type { synthetic: true, .. }))
420        .count();
421    let named_type_param_count = param_counts.types - has_self as usize - synth_type_param_count;
422    let named_const_param_count = param_counts.consts;
423    let infer_lifetimes =
424        (gen_pos != GenericArgPosition::Type || seg.infer_args) && !gen_args.has_lifetime_params();
425
426    if gen_pos != GenericArgPosition::Type
427        && let Some(c) = gen_args.constraints.first()
428    {
429        prohibit_assoc_item_constraint(cx, c, None);
430    }
431
432    let explicit_late_bound =
433        prohibit_explicit_late_bound_lifetimes(cx, gen_params, gen_args, gen_pos);
434
435    let mut invalid_args = vec![];
436
437    let mut check_lifetime_args = |min_expected_args: usize,
438                                   max_expected_args: usize,
439                                   provided_args: usize,
440                                   late_bounds_ignore: bool| {
441        if (min_expected_args..=max_expected_args).contains(&provided_args) {
442            return Ok(());
443        }
444
445        if late_bounds_ignore {
446            return Ok(());
447        }
448
449        invalid_args.extend(min_expected_args..provided_args);
450
451        let gen_args_info = if provided_args > min_expected_args {
452            let num_redundant_args = provided_args - min_expected_args;
453            GenericArgsInfo::ExcessLifetimes { num_redundant_args }
454        } else {
455            let num_missing_args = min_expected_args - provided_args;
456            GenericArgsInfo::MissingLifetimes { num_missing_args }
457        };
458
459        let reported = cx.dcx().emit_err(WrongNumberOfGenericArgs::new(
460            cx.tcx(),
461            gen_args_info,
462            seg,
463            gen_params,
464            has_self as usize,
465            gen_args,
466            def_id,
467        ));
468
469        Err(reported)
470    };
471
472    let min_expected_lifetime_args = if infer_lifetimes { 0 } else { param_counts.lifetimes };
473    let max_expected_lifetime_args = param_counts.lifetimes;
474    let num_provided_lifetime_args = gen_args.num_lifetime_params();
475
476    let lifetimes_correct = check_lifetime_args(
477        min_expected_lifetime_args,
478        max_expected_lifetime_args,
479        num_provided_lifetime_args,
480        explicit_late_bound == ExplicitLateBound::Yes,
481    );
482
483    let mut check_types_and_consts = |expected_min,
484                                      expected_max,
485                                      expected_max_with_synth,
486                                      provided,
487                                      params_offset,
488                                      args_offset| {
489        debug!(
490            ?expected_min,
491            ?expected_max,
492            ?provided,
493            ?params_offset,
494            ?args_offset,
495            "check_types_and_consts"
496        );
497        if (expected_min..=expected_max).contains(&provided) {
498            return Ok(());
499        }
500
501        let num_default_params = expected_max - expected_min;
502
503        let mut all_params_are_binded = false;
504        let gen_args_info = if provided > expected_max {
505            invalid_args.extend((expected_max..provided).map(|i| i + args_offset));
506            let num_redundant_args = provided - expected_max;
507
508            // Provide extra note if synthetic arguments like `impl Trait` are specified.
509            let synth_provided = provided <= expected_max_with_synth;
510
511            GenericArgsInfo::ExcessTypesOrConsts {
512                num_redundant_args,
513                num_default_params,
514                args_offset,
515                synth_provided,
516            }
517        } else {
518            // Check if associated type bounds are incorrectly written in impl block header like:
519            // ```
520            // trait Foo<T> {}
521            // impl Foo<T: Default> for u8 {}
522            // ```
523            let parent_is_impl_block = cx
524                .tcx()
525                .hir_parent_owner_iter(seg.hir_id)
526                .next()
527                .is_some_and(|(_, owner_node)| owner_node.is_impl_block());
528            if parent_is_impl_block {
529                let constraint_names: Vec<_> =
530                    gen_args.constraints.iter().map(|b| b.ident.name).collect();
531                let param_names: Vec<_> = gen_params
532                    .own_params
533                    .iter()
534                    .filter(|param| !has_self || param.index != 0) // Assumes `Self` will always be the first parameter
535                    .map(|param| param.name)
536                    .collect();
537                if constraint_names == param_names {
538                    // We set this to true and delay emitting `WrongNumberOfGenericArgs`
539                    // to provide a succinct error for cases like issue #113073
540                    all_params_are_binded = true;
541                };
542            }
543
544            let num_missing_args = expected_max - provided;
545
546            GenericArgsInfo::MissingTypesOrConsts {
547                num_missing_args,
548                num_default_params,
549                args_offset,
550            }
551        };
552
553        debug!(?gen_args_info);
554
555        let reported = gen_args.has_err().unwrap_or_else(|| {
556            cx.dcx()
557                .create_err(WrongNumberOfGenericArgs::new(
558                    cx.tcx(),
559                    gen_args_info,
560                    seg,
561                    gen_params,
562                    params_offset,
563                    gen_args,
564                    def_id,
565                ))
566                .emit_unless_delay(all_params_are_binded)
567        });
568
569        Err(reported)
570    };
571
572    let args_correct = {
573        let expected_min = if seg.infer_args {
574            0
575        } else {
576            param_counts.consts + named_type_param_count
577                - default_counts.types
578                - default_counts.consts
579        };
580        debug!(?expected_min);
581        debug!(arg_counts.lifetimes=?gen_args.num_lifetime_params());
582
583        let provided = gen_args.num_generic_params();
584
585        check_types_and_consts(
586            expected_min,
587            named_const_param_count + named_type_param_count,
588            named_const_param_count + named_type_param_count + synth_type_param_count,
589            provided,
590            param_counts.lifetimes + has_self as usize,
591            gen_args.num_lifetime_params(),
592        )
593    };
594
595    GenericArgCountResult {
596        explicit_late_bound,
597        correct: lifetimes_correct
598            .and(args_correct)
599            .map_err(|reported| GenericArgCountMismatch { reported, invalid_args }),
600    }
601}
602
603/// Prohibits explicit lifetime arguments if late-bound lifetime parameters
604/// are present. This is used both for datatypes and function calls.
605pub(crate) fn prohibit_explicit_late_bound_lifetimes(
606    cx: &dyn HirTyLowerer<'_>,
607    def: &ty::Generics,
608    args: &hir::GenericArgs<'_>,
609    position: GenericArgPosition,
610) -> ExplicitLateBound {
611    let param_counts = def.own_counts();
612    let infer_lifetimes = position != GenericArgPosition::Type && !args.has_lifetime_params();
613
614    if infer_lifetimes {
615        return ExplicitLateBound::No;
616    }
617
618    if let Some(span_late) = def.has_late_bound_regions {
619        let msg = "cannot specify lifetime arguments explicitly \
620                       if late bound lifetime parameters are present";
621        let note = "the late bound lifetime parameter is introduced here";
622        let span = args.args[0].span();
623
624        if position == GenericArgPosition::Value
625            && args.num_lifetime_params() != param_counts.lifetimes
626        {
627            struct_span_code_err!(cx.dcx(), span, E0794, "{}", msg)
628                .with_span_note(span_late, note)
629                .emit();
630        } else {
631            let mut multispan = MultiSpan::from_span(span);
632            multispan.push_span_label(span_late, note);
633            cx.tcx().node_span_lint(
634                LATE_BOUND_LIFETIME_ARGUMENTS,
635                args.args[0].hir_id(),
636                multispan,
637                |lint| {
638                    lint.primary_message(msg);
639                },
640            );
641        }
642
643        ExplicitLateBound::Yes
644    } else {
645        ExplicitLateBound::No
646    }
647}