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, sym};
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
23fn 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 match (arg, ¶m.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(
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 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 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
146pub 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 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 let mut args: SmallVec<[ty::GenericArg<'tcx>; 8]> = SmallVec::with_capacity(count);
198 while let Some((def_id, defs)) = stack.pop() {
200 let mut params = defs.own_params.iter().peekable();
201
202 while let Some(¶m) = 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 if has_self {
215 if let Some(¶m) = 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 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 let mut force_infer_lt = None;
241
242 loop {
243 match (args_iter.peek(), params.peek()) {
248 (Some(&arg), Some(¶m)) => {
249 match (arg, ¶m.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 if let GenericParamDefKind::Const { .. } = param.kind
262 && let GenericArg::Infer(inf) = arg
263 && !tcx.features().generic_arg_infer()
264 {
265 rustc_session::parse::feature_err(
266 tcx.sess,
267 sym::generic_arg_infer,
268 inf.span,
269 "const arguments cannot yet be inferred with `_`",
270 )
271 .emit();
272 }
273
274 args.push(ctx.provided_kind(param, arg));
277 args_iter.next();
278 params.next();
279 }
280 (
281 GenericArg::Infer(_) | GenericArg::Type(_) | GenericArg::Const(_),
282 GenericParamDefKind::Lifetime,
283 _,
284 ) => {
285 args.push(ctx.inferred_kind(&args, param, infer_args));
288 force_infer_lt = Some((arg, param));
289 params.next();
290 }
291 (GenericArg::Lifetime(_), _, ExplicitLateBound::Yes) => {
292 args_iter.next();
297 }
298 (_, _, _) => {
299 if arg_count.correct.is_ok() {
304 let mut param_types_present = defs
307 .own_params
308 .iter()
309 .map(|param| (param.kind.to_ord(), param.clone()))
310 .collect::<Vec<(ParamKindOrd, GenericParamDef)>>();
311 param_types_present.sort_by_key(|(ord, _)| *ord);
312 let (mut param_types_present, ordered_params): (
313 Vec<ParamKindOrd>,
314 Vec<GenericParamDef>,
315 ) = param_types_present.into_iter().unzip();
316 param_types_present.dedup();
317
318 generic_arg_mismatch_err(
319 cx,
320 arg,
321 param,
322 !args_iter.clone().is_sorted_by_key(|arg| arg.to_ord()),
323 Some(format!(
324 "reorder the arguments: {}: `<{}>`",
325 param_types_present
326 .into_iter()
327 .map(|ord| format!("{ord}s"))
328 .collect::<Vec<String>>()
329 .join(", then "),
330 ordered_params
331 .into_iter()
332 .filter_map(|param| {
333 if param.name == kw::SelfUpper {
334 None
335 } else {
336 Some(param.name.to_string())
337 }
338 })
339 .collect::<Vec<String>>()
340 .join(", ")
341 )),
342 );
343 }
344
345 while args_iter.next().is_some() {}
351 }
352 }
353 }
354
355 (Some(&arg), None) => {
356 if arg_count.correct.is_ok()
368 && arg_count.explicit_late_bound == ExplicitLateBound::No
369 {
370 let kind = arg.descr();
371 assert_eq!(kind, "lifetime");
372 let (provided_arg, param) =
373 force_infer_lt.expect("lifetimes ought to have been inferred");
374 generic_arg_mismatch_err(cx, provided_arg, param, false, None);
375 }
376
377 break;
378 }
379
380 (None, Some(¶m)) => {
381 args.push(ctx.inferred_kind(&args, param, infer_args));
384 params.next();
385 }
386
387 (None, None) => break,
388 }
389 }
390 }
391
392 tcx.mk_args(&args)
393}
394
395pub fn check_generic_arg_count_for_call(
398 cx: &dyn HirTyLowerer<'_>,
399 def_id: DefId,
400 generics: &ty::Generics,
401 seg: &hir::PathSegment<'_>,
402 is_method_call: IsMethodCall,
403) -> GenericArgCountResult {
404 let gen_pos = match is_method_call {
405 IsMethodCall::Yes => GenericArgPosition::MethodCall,
406 IsMethodCall::No => GenericArgPosition::Value,
407 };
408 let has_self = generics.parent.is_none() && generics.has_self;
409 check_generic_arg_count(cx, def_id, seg, generics, gen_pos, has_self)
410}
411
412#[instrument(skip(cx, gen_pos), level = "debug")]
415pub(crate) fn check_generic_arg_count(
416 cx: &dyn HirTyLowerer<'_>,
417 def_id: DefId,
418 seg: &hir::PathSegment<'_>,
419 gen_params: &ty::Generics,
420 gen_pos: GenericArgPosition,
421 has_self: bool,
422) -> GenericArgCountResult {
423 let gen_args = seg.args();
424 let default_counts = gen_params.own_defaults();
425 let param_counts = gen_params.own_counts();
426
427 let synth_type_param_count = gen_params
430 .own_params
431 .iter()
432 .filter(|param| matches!(param.kind, ty::GenericParamDefKind::Type { synthetic: true, .. }))
433 .count();
434 let named_type_param_count = param_counts.types - has_self as usize - synth_type_param_count;
435 let synth_const_param_count = gen_params
436 .own_params
437 .iter()
438 .filter(|param| {
439 matches!(param.kind, ty::GenericParamDefKind::Const { synthetic: true, .. })
440 })
441 .count();
442 let named_const_param_count = param_counts.consts - synth_const_param_count;
443 let infer_lifetimes =
444 (gen_pos != GenericArgPosition::Type || seg.infer_args) && !gen_args.has_lifetime_params();
445
446 if gen_pos != GenericArgPosition::Type
447 && let Some(c) = gen_args.constraints.first()
448 {
449 prohibit_assoc_item_constraint(cx, c, None);
450 }
451
452 let explicit_late_bound =
453 prohibit_explicit_late_bound_lifetimes(cx, gen_params, gen_args, gen_pos);
454
455 let mut invalid_args = vec![];
456
457 let mut check_lifetime_args = |min_expected_args: usize,
458 max_expected_args: usize,
459 provided_args: usize,
460 late_bounds_ignore: bool| {
461 if (min_expected_args..=max_expected_args).contains(&provided_args) {
462 return Ok(());
463 }
464
465 if late_bounds_ignore {
466 return Ok(());
467 }
468
469 invalid_args.extend(min_expected_args..provided_args);
470
471 let gen_args_info = if provided_args > min_expected_args {
472 let num_redundant_args = provided_args - min_expected_args;
473 GenericArgsInfo::ExcessLifetimes { num_redundant_args }
474 } else {
475 let num_missing_args = min_expected_args - provided_args;
476 GenericArgsInfo::MissingLifetimes { num_missing_args }
477 };
478
479 let reported = cx.dcx().emit_err(WrongNumberOfGenericArgs::new(
480 cx.tcx(),
481 gen_args_info,
482 seg,
483 gen_params,
484 has_self as usize,
485 gen_args,
486 def_id,
487 ));
488
489 Err(reported)
490 };
491
492 let min_expected_lifetime_args = if infer_lifetimes { 0 } else { param_counts.lifetimes };
493 let max_expected_lifetime_args = param_counts.lifetimes;
494 let num_provided_lifetime_args = gen_args.num_lifetime_params();
495
496 let lifetimes_correct = check_lifetime_args(
497 min_expected_lifetime_args,
498 max_expected_lifetime_args,
499 num_provided_lifetime_args,
500 explicit_late_bound == ExplicitLateBound::Yes,
501 );
502
503 let mut check_types_and_consts = |expected_min,
504 expected_max,
505 expected_max_with_synth,
506 provided,
507 params_offset,
508 args_offset| {
509 debug!(
510 ?expected_min,
511 ?expected_max,
512 ?provided,
513 ?params_offset,
514 ?args_offset,
515 "check_types_and_consts"
516 );
517 if (expected_min..=expected_max).contains(&provided) {
518 return Ok(());
519 }
520
521 let num_default_params = expected_max - expected_min;
522
523 let mut all_params_are_binded = false;
524 let gen_args_info = if provided > expected_max {
525 invalid_args.extend((expected_max..provided).map(|i| i + args_offset));
526 let num_redundant_args = provided - expected_max;
527
528 let synth_provided = provided <= expected_max_with_synth;
530
531 GenericArgsInfo::ExcessTypesOrConsts {
532 num_redundant_args,
533 num_default_params,
534 args_offset,
535 synth_provided,
536 }
537 } else {
538 let parent_is_impl_block = cx
544 .tcx()
545 .hir()
546 .parent_owner_iter(seg.hir_id)
547 .next()
548 .is_some_and(|(_, owner_node)| owner_node.is_impl_block());
549 if parent_is_impl_block {
550 let constraint_names: Vec<_> =
551 gen_args.constraints.iter().map(|b| b.ident.name).collect();
552 let param_names: Vec<_> = gen_params
553 .own_params
554 .iter()
555 .filter(|param| !has_self || param.index != 0) .map(|param| param.name)
557 .collect();
558 if constraint_names == param_names {
559 all_params_are_binded = true;
562 };
563 }
564
565 let num_missing_args = expected_max - provided;
566
567 GenericArgsInfo::MissingTypesOrConsts {
568 num_missing_args,
569 num_default_params,
570 args_offset,
571 }
572 };
573
574 debug!(?gen_args_info);
575
576 let reported = gen_args.has_err().unwrap_or_else(|| {
577 cx.dcx()
578 .create_err(WrongNumberOfGenericArgs::new(
579 cx.tcx(),
580 gen_args_info,
581 seg,
582 gen_params,
583 params_offset,
584 gen_args,
585 def_id,
586 ))
587 .emit_unless(all_params_are_binded)
588 });
589
590 Err(reported)
591 };
592
593 let args_correct = {
594 let expected_min = if seg.infer_args {
595 0
596 } else {
597 param_counts.consts + named_type_param_count
598 - default_counts.types
599 - default_counts.consts
600 };
601 debug!(?expected_min);
602 debug!(arg_counts.lifetimes=?gen_args.num_lifetime_params());
603
604 let provided = gen_args.num_generic_params();
605
606 check_types_and_consts(
607 expected_min,
608 named_const_param_count + named_type_param_count,
609 named_const_param_count + named_type_param_count + synth_type_param_count,
610 provided,
611 param_counts.lifetimes + has_self as usize,
612 gen_args.num_lifetime_params(),
613 )
614 };
615
616 GenericArgCountResult {
617 explicit_late_bound,
618 correct: lifetimes_correct
619 .and(args_correct)
620 .map_err(|reported| GenericArgCountMismatch { reported, invalid_args }),
621 }
622}
623
624pub(crate) fn prohibit_explicit_late_bound_lifetimes(
627 cx: &dyn HirTyLowerer<'_>,
628 def: &ty::Generics,
629 args: &hir::GenericArgs<'_>,
630 position: GenericArgPosition,
631) -> ExplicitLateBound {
632 let param_counts = def.own_counts();
633 let infer_lifetimes = position != GenericArgPosition::Type && !args.has_lifetime_params();
634
635 if infer_lifetimes {
636 return ExplicitLateBound::No;
637 }
638
639 if let Some(span_late) = def.has_late_bound_regions {
640 let msg = "cannot specify lifetime arguments explicitly \
641 if late bound lifetime parameters are present";
642 let note = "the late bound lifetime parameter is introduced here";
643 let span = args.args[0].span();
644
645 if position == GenericArgPosition::Value
646 && args.num_lifetime_params() != param_counts.lifetimes
647 {
648 struct_span_code_err!(cx.dcx(), span, E0794, "{}", msg)
649 .with_span_note(span_late, note)
650 .emit();
651 } else {
652 let mut multispan = MultiSpan::from_span(span);
653 multispan.push_span_label(span_late, note);
654 cx.tcx().node_span_lint(
655 LATE_BOUND_LIFETIME_ARGUMENTS,
656 args.args[0].hir_id(),
657 multispan,
658 |lint| {
659 lint.primary_message(msg);
660 },
661 );
662 }
663
664 ExplicitLateBound::Yes
665 } else {
666 ExplicitLateBound::No
667 }
668}