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 synth_const_param_count = gen_params
423        .own_params
424        .iter()
425        .filter(|param| {
426            matches!(param.kind, ty::GenericParamDefKind::Const { synthetic: true, .. })
427        })
428        .count();
429    let named_const_param_count = param_counts.consts - synth_const_param_count;
430    let infer_lifetimes =
431        (gen_pos != GenericArgPosition::Type || seg.infer_args) && !gen_args.has_lifetime_params();
432
433    if gen_pos != GenericArgPosition::Type
434        && let Some(c) = gen_args.constraints.first()
435    {
436        prohibit_assoc_item_constraint(cx, c, None);
437    }
438
439    let explicit_late_bound =
440        prohibit_explicit_late_bound_lifetimes(cx, gen_params, gen_args, gen_pos);
441
442    let mut invalid_args = vec![];
443
444    let mut check_lifetime_args = |min_expected_args: usize,
445                                   max_expected_args: usize,
446                                   provided_args: usize,
447                                   late_bounds_ignore: bool| {
448        if (min_expected_args..=max_expected_args).contains(&provided_args) {
449            return Ok(());
450        }
451
452        if late_bounds_ignore {
453            return Ok(());
454        }
455
456        invalid_args.extend(min_expected_args..provided_args);
457
458        let gen_args_info = if provided_args > min_expected_args {
459            let num_redundant_args = provided_args - min_expected_args;
460            GenericArgsInfo::ExcessLifetimes { num_redundant_args }
461        } else {
462            let num_missing_args = min_expected_args - provided_args;
463            GenericArgsInfo::MissingLifetimes { num_missing_args }
464        };
465
466        let reported = cx.dcx().emit_err(WrongNumberOfGenericArgs::new(
467            cx.tcx(),
468            gen_args_info,
469            seg,
470            gen_params,
471            has_self as usize,
472            gen_args,
473            def_id,
474        ));
475
476        Err(reported)
477    };
478
479    let min_expected_lifetime_args = if infer_lifetimes { 0 } else { param_counts.lifetimes };
480    let max_expected_lifetime_args = param_counts.lifetimes;
481    let num_provided_lifetime_args = gen_args.num_lifetime_params();
482
483    let lifetimes_correct = check_lifetime_args(
484        min_expected_lifetime_args,
485        max_expected_lifetime_args,
486        num_provided_lifetime_args,
487        explicit_late_bound == ExplicitLateBound::Yes,
488    );
489
490    let mut check_types_and_consts = |expected_min,
491                                      expected_max,
492                                      expected_max_with_synth,
493                                      provided,
494                                      params_offset,
495                                      args_offset| {
496        debug!(
497            ?expected_min,
498            ?expected_max,
499            ?provided,
500            ?params_offset,
501            ?args_offset,
502            "check_types_and_consts"
503        );
504        if (expected_min..=expected_max).contains(&provided) {
505            return Ok(());
506        }
507
508        let num_default_params = expected_max - expected_min;
509
510        let mut all_params_are_binded = false;
511        let gen_args_info = if provided > expected_max {
512            invalid_args.extend((expected_max..provided).map(|i| i + args_offset));
513            let num_redundant_args = provided - expected_max;
514
515            // Provide extra note if synthetic arguments like `impl Trait` are specified.
516            let synth_provided = provided <= expected_max_with_synth;
517
518            GenericArgsInfo::ExcessTypesOrConsts {
519                num_redundant_args,
520                num_default_params,
521                args_offset,
522                synth_provided,
523            }
524        } else {
525            // Check if associated type bounds are incorrectly written in impl block header like:
526            // ```
527            // trait Foo<T> {}
528            // impl Foo<T: Default> for u8 {}
529            // ```
530            let parent_is_impl_block = cx
531                .tcx()
532                .hir_parent_owner_iter(seg.hir_id)
533                .next()
534                .is_some_and(|(_, owner_node)| owner_node.is_impl_block());
535            if parent_is_impl_block {
536                let constraint_names: Vec<_> =
537                    gen_args.constraints.iter().map(|b| b.ident.name).collect();
538                let param_names: Vec<_> = gen_params
539                    .own_params
540                    .iter()
541                    .filter(|param| !has_self || param.index != 0) // Assumes `Self` will always be the first parameter
542                    .map(|param| param.name)
543                    .collect();
544                if constraint_names == param_names {
545                    // We set this to true and delay emitting `WrongNumberOfGenericArgs`
546                    // to provide a succinct error for cases like issue #113073
547                    all_params_are_binded = true;
548                };
549            }
550
551            let num_missing_args = expected_max - provided;
552
553            GenericArgsInfo::MissingTypesOrConsts {
554                num_missing_args,
555                num_default_params,
556                args_offset,
557            }
558        };
559
560        debug!(?gen_args_info);
561
562        let reported = gen_args.has_err().unwrap_or_else(|| {
563            cx.dcx()
564                .create_err(WrongNumberOfGenericArgs::new(
565                    cx.tcx(),
566                    gen_args_info,
567                    seg,
568                    gen_params,
569                    params_offset,
570                    gen_args,
571                    def_id,
572                ))
573                .emit_unless(all_params_are_binded)
574        });
575
576        Err(reported)
577    };
578
579    let args_correct = {
580        let expected_min = if seg.infer_args {
581            0
582        } else {
583            param_counts.consts + named_type_param_count
584                - default_counts.types
585                - default_counts.consts
586        };
587        debug!(?expected_min);
588        debug!(arg_counts.lifetimes=?gen_args.num_lifetime_params());
589
590        let provided = gen_args.num_generic_params();
591
592        check_types_and_consts(
593            expected_min,
594            named_const_param_count + named_type_param_count,
595            named_const_param_count + named_type_param_count + synth_type_param_count,
596            provided,
597            param_counts.lifetimes + has_self as usize,
598            gen_args.num_lifetime_params(),
599        )
600    };
601
602    GenericArgCountResult {
603        explicit_late_bound,
604        correct: lifetimes_correct
605            .and(args_correct)
606            .map_err(|reported| GenericArgCountMismatch { reported, invalid_args }),
607    }
608}
609
610/// Prohibits explicit lifetime arguments if late-bound lifetime parameters
611/// are present. This is used both for datatypes and function calls.
612pub(crate) fn prohibit_explicit_late_bound_lifetimes(
613    cx: &dyn HirTyLowerer<'_>,
614    def: &ty::Generics,
615    args: &hir::GenericArgs<'_>,
616    position: GenericArgPosition,
617) -> ExplicitLateBound {
618    let param_counts = def.own_counts();
619    let infer_lifetimes = position != GenericArgPosition::Type && !args.has_lifetime_params();
620
621    if infer_lifetimes {
622        return ExplicitLateBound::No;
623    }
624
625    if let Some(span_late) = def.has_late_bound_regions {
626        let msg = "cannot specify lifetime arguments explicitly \
627                       if late bound lifetime parameters are present";
628        let note = "the late bound lifetime parameter is introduced here";
629        let span = args.args[0].span();
630
631        if position == GenericArgPosition::Value
632            && args.num_lifetime_params() != param_counts.lifetimes
633        {
634            struct_span_code_err!(cx.dcx(), span, E0794, "{}", msg)
635                .with_span_note(span_late, note)
636                .emit();
637        } else {
638            let mut multispan = MultiSpan::from_span(span);
639            multispan.push_span_label(span_late, note);
640            cx.tcx().node_span_lint(
641                LATE_BOUND_LIFETIME_ARGUMENTS,
642                args.args[0].hir_id(),
643                multispan,
644                |lint| {
645                    lint.primary_message(msg);
646                },
647            );
648        }
649
650        ExplicitLateBound::Yes
651    } else {
652        ExplicitLateBound::No
653    }
654}