rustc_hir_analysis/hir_ty_lowering/
generics.rs1use 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
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_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 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 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 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 args_iter.next();
284 }
285 (_, _, _) => {
286 if arg_count.correct.is_ok() {
291 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 while args_iter.next().is_some() {}
338 }
339 }
340 }
341
342 (Some(&arg), None) => {
343 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(¶m)) => {
368 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
382pub 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#[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 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 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 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) .map(|param| param.name)
536 .collect();
537 if constraint_names == param_names {
538 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
603pub(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}