1 use super::IsMethodCall;
3 AstConv, CreateSubstsForGenericArgsCtxt, ExplicitLateBound, GenericArgCountMismatch,
4 GenericArgCountResult, GenericArgPosition,
6 use crate::errors::AssocTypeBindingNotAllowed;
7 use crate::structured_errors::{GenericArgsInfo, StructuredDiagnostic, WrongNumberOfGenericArgs};
8 use rustc_ast::ast::ParamKindOrd;
9 use rustc_errors::{struct_span_err, Applicability, Diagnostic, MultiSpan};
11 use rustc_hir::def::{DefKind, Res};
12 use rustc_hir::def_id::DefId;
13 use rustc_hir::GenericArg;
14 use rustc_infer::infer::TyCtxtInferExt;
15 use rustc_middle::ty::{
16 self, subst, subst::SubstsRef, GenericParamDef, GenericParamDefKind, IsSuggestable, Ty, TyCtxt,
18 use rustc_session::lint::builtin::LATE_BOUND_LIFETIME_ARGUMENTS;
19 use rustc_span::{symbol::kw, Span};
20 use smallvec::SmallVec;
22 impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
23 /// Report an error that a generic argument did not match the generic parameter that was
25 fn generic_arg_mismatch_err(
28 param: &GenericParamDef,
29 possible_ordering_error: bool,
33 let mut err = struct_span_err!(
37 "{} provided when a {} was expected",
42 if let GenericParamDefKind::Const { .. } = param.kind {
43 if matches!(arg, GenericArg::Type(hir::Ty { kind: hir::TyKind::Infer, .. })) {
44 err.help("const arguments cannot yet be inferred with `_`");
45 if sess.is_nightly_build() {
47 "add `#![feature(generic_arg_infer)]` to the crate attributes to enable",
53 let add_braces_suggestion = |arg: &GenericArg<'_>, err: &mut Diagnostic| {
54 let suggestions = vec![
55 (arg.span().shrink_to_lo(), String::from("{ ")),
56 (arg.span().shrink_to_hi(), String::from(" }")),
58 err.multipart_suggestion(
59 "if this generic argument was intended as a const parameter, \
60 surround it with braces",
62 Applicability::MaybeIncorrect,
66 // Specific suggestion set for diagnostics
67 match (arg, ¶m.kind) {
69 GenericArg::Type(hir::Ty {
70 kind: hir::TyKind::Path(rustc_hir::QPath::Resolved(_, path)),
73 GenericParamDefKind::Const { .. },
76 add_braces_suggestion(arg, &mut err);
77 err.set_primary_message(
78 "unresolved item provided when a constant was expected",
83 Res::Def(DefKind::TyParam, src_def_id) => {
84 if let Some(param_local_id) = param.def_id.as_local() {
85 let param_name = tcx.hir().ty_param_name(param_local_id);
86 let param_type = tcx.infer_ctxt().enter(|infcx| {
87 infcx.resolve_numeric_literals_with_default(tcx.type_of(param.def_id))
89 if param_type.is_suggestable(tcx, false) {
91 tcx.def_span(src_def_id),
92 "consider changing this type parameter to be a `const` generic",
93 format!("const {}: {}", param_name, param_type),
94 Applicability::MaybeIncorrect,
99 _ => add_braces_suggestion(arg, &mut err),
102 GenericArg::Type(hir::Ty { kind: hir::TyKind::Path(_), .. }),
103 GenericParamDefKind::Const { .. },
104 ) => add_braces_suggestion(arg, &mut err),
106 GenericArg::Type(hir::Ty { kind: hir::TyKind::Array(_, len), .. }),
107 GenericParamDefKind::Const { .. },
108 ) if tcx.type_of(param.def_id) == tcx.types.usize => {
109 let snippet = sess.source_map().span_to_snippet(tcx.hir().span(len.hir_id()));
110 if let Ok(snippet) = snippet {
113 "array type provided where a `usize` was expected, try",
114 format!("{{ {} }}", snippet),
115 Applicability::MaybeIncorrect,
119 (GenericArg::Const(cnst), GenericParamDefKind::Type { .. }) => {
120 let body = tcx.hir().body(cnst.value.body);
121 if let rustc_hir::ExprKind::Path(rustc_hir::QPath::Resolved(_, path)) =
124 if let Res::Def(DefKind::Fn { .. }, id) = path.res {
126 "`{}` is a function item, not a type",
129 err.help("function item types cannot be named directly");
136 let kind_ord = param.kind.to_ord();
137 let arg_ord = arg.to_ord();
139 // This note is only true when generic parameters are strictly ordered by their kind.
140 if possible_ordering_error && kind_ord.cmp(&arg_ord) != core::cmp::Ordering::Equal {
141 let (first, last) = if kind_ord < arg_ord {
142 (param.kind.descr(), arg.descr())
144 (arg.descr(), param.kind.descr())
146 err.note(&format!("{} arguments must be provided before {} arguments", first, last));
147 if let Some(help) = help {
155 /// Creates the relevant generic argument substitutions
156 /// corresponding to a set of generic parameters. This is a
157 /// rather complex function. Let us try to explain the role
158 /// of each of its parameters:
160 /// To start, we are given the `def_id` of the thing we are
161 /// creating the substitutions for, and a partial set of
162 /// substitutions `parent_substs`. In general, the substitutions
163 /// for an item begin with substitutions for all the "parents" of
164 /// that item -- e.g., for a method it might include the
165 /// parameters from the impl.
167 /// Therefore, the method begins by walking down these parents,
168 /// starting with the outermost parent and proceed inwards until
169 /// it reaches `def_id`. For each parent `P`, it will check `parent_substs`
170 /// first to see if the parent's substitutions are listed in there. If so,
171 /// we can append those and move on. Otherwise, it invokes the
172 /// three callback functions:
174 /// - `args_for_def_id`: given the `DefId` `P`, supplies back the
175 /// generic arguments that were given to that parent from within
176 /// the path; so e.g., if you have `<T as Foo>::Bar`, the `DefId`
177 /// might refer to the trait `Foo`, and the arguments might be
178 /// `[T]`. The boolean value indicates whether to infer values
179 /// for arguments whose values were not explicitly provided.
180 /// - `provided_kind`: given the generic parameter and the value from `args_for_def_id`,
181 /// instantiate a `GenericArg`.
182 /// - `inferred_kind`: if no parameter was provided, and inference is enabled, then
183 /// creates a suitable inference variable.
184 pub fn create_substs_for_generic_args<'a>(
187 parent_substs: &[subst::GenericArg<'tcx>],
189 self_ty: Option<Ty<'tcx>>,
190 arg_count: &GenericArgCountResult,
191 ctx: &mut impl CreateSubstsForGenericArgsCtxt<'a, 'tcx>,
192 ) -> SubstsRef<'tcx> {
193 // Collect the segments of the path; we need to substitute arguments
194 // for parameters throughout the entire path (wherever there are
195 // generic parameters).
196 let mut parent_defs = tcx.generics_of(def_id);
197 let count = parent_defs.count();
198 let mut stack = vec![(def_id, parent_defs)];
199 while let Some(def_id) = parent_defs.parent {
200 parent_defs = tcx.generics_of(def_id);
201 stack.push((def_id, parent_defs));
204 // We manually build up the substitution, rather than using convenience
205 // methods in `subst.rs`, so that we can iterate over the arguments and
206 // parameters in lock-step linearly, instead of trying to match each pair.
207 let mut substs: SmallVec<[subst::GenericArg<'tcx>; 8]> = SmallVec::with_capacity(count);
208 // Iterate over each segment of the path.
209 while let Some((def_id, defs)) = stack.pop() {
210 let mut params = defs.params.iter().peekable();
212 // If we have already computed substitutions for parents, we can use those directly.
213 while let Some(¶m) = params.peek() {
214 if let Some(&kind) = parent_substs.get(param.index as usize) {
222 // `Self` is handled first, unless it's been handled in `parent_substs`.
224 if let Some(¶m) = params.peek() {
225 if param.index == 0 {
226 if let GenericParamDefKind::Type { .. } = param.kind {
230 .unwrap_or_else(|| ctx.inferred_kind(None, param, true)),
238 // Check whether this segment takes generic arguments and the user has provided any.
239 let (generic_args, infer_args) = ctx.args_for_def_id(def_id);
241 let args_iter = generic_args.iter().flat_map(|generic_args| generic_args.args.iter());
242 let mut args = args_iter.clone().peekable();
244 // If we encounter a type or const when we expect a lifetime, we infer the lifetimes.
245 // If we later encounter a lifetime, we know that the arguments were provided in the
246 // wrong order. `force_infer_lt` records the type or const that forced lifetimes to be
247 // inferred, so we can use it for diagnostics later.
248 let mut force_infer_lt = None;
251 // We're going to iterate through the generic arguments that the user
252 // provided, matching them with the generic parameters we expect.
253 // Mismatches can occur as a result of elided lifetimes, or for malformed
254 // input. We try to handle both sensibly.
255 match (args.peek(), params.peek()) {
256 (Some(&arg), Some(¶m)) => {
257 match (arg, ¶m.kind, arg_count.explicit_late_bound) {
258 (GenericArg::Lifetime(_), GenericParamDefKind::Lifetime, _)
260 GenericArg::Type(_) | GenericArg::Infer(_),
261 GenericParamDefKind::Type { .. },
265 GenericArg::Const(_) | GenericArg::Infer(_),
266 GenericParamDefKind::Const { .. },
269 substs.push(ctx.provided_kind(param, arg));
274 GenericArg::Infer(_) | GenericArg::Type(_) | GenericArg::Const(_),
275 GenericParamDefKind::Lifetime,
278 // We expected a lifetime argument, but got a type or const
279 // argument. That means we're inferring the lifetimes.
280 substs.push(ctx.inferred_kind(None, param, infer_args));
281 force_infer_lt = Some((arg, param));
284 (GenericArg::Lifetime(_), _, ExplicitLateBound::Yes) => {
285 // We've come across a lifetime when we expected something else in
286 // the presence of explicit late bounds. This is most likely
287 // due to the presence of the explicit bound so we're just going to
292 // We expected one kind of parameter, but the user provided
293 // another. This is an error. However, if we already know that
294 // the arguments don't match up with the parameters, we won't issue
295 // an additional error, as the user already knows what's wrong.
296 if arg_count.correct.is_ok() {
297 // We're going to iterate over the parameters to sort them out, and
298 // show that order to the user as a possible order for the parameters
299 let mut param_types_present = defs
302 .map(|param| (param.kind.to_ord(), param.clone()))
303 .collect::<Vec<(ParamKindOrd, GenericParamDef)>>();
304 param_types_present.sort_by_key(|(ord, _)| *ord);
305 let (mut param_types_present, ordered_params): (
307 Vec<GenericParamDef>,
308 ) = param_types_present.into_iter().unzip();
309 param_types_present.dedup();
311 Self::generic_arg_mismatch_err(
315 !args_iter.clone().is_sorted_by_key(|arg| arg.to_ord()),
317 "reorder the arguments: {}: `<{}>`",
320 .map(|ord| format!("{}s", ord))
321 .collect::<Vec<String>>()
325 .filter_map(|param| {
326 if param.name == kw::SelfUpper {
329 Some(param.name.to_string())
332 .collect::<Vec<String>>()
338 // We've reported the error, but we want to make sure that this
339 // problem doesn't bubble down and create additional, irrelevant
340 // errors. In this case, we're simply going to ignore the argument
341 // and any following arguments. The rest of the parameters will be
343 while args.next().is_some() {}
348 (Some(&arg), None) => {
349 // We should never be able to reach this point with well-formed input.
350 // There are three situations in which we can encounter this issue.
352 // 1. The number of arguments is incorrect. In this case, an error
353 // will already have been emitted, and we can ignore it.
354 // 2. There are late-bound lifetime parameters present, yet the
355 // lifetime arguments have also been explicitly specified by the
357 // 3. We've inferred some lifetimes, which have been provided later (i.e.
358 // after a type or const). We want to throw an error in this case.
360 if arg_count.correct.is_ok()
361 && arg_count.explicit_late_bound == ExplicitLateBound::No
363 let kind = arg.descr();
364 assert_eq!(kind, "lifetime");
365 let (provided_arg, param) =
366 force_infer_lt.expect("lifetimes ought to have been inferred");
367 Self::generic_arg_mismatch_err(tcx, provided_arg, param, false, None);
373 (None, Some(¶m)) => {
374 // If there are fewer arguments than parameters, it means
375 // we're inferring the remaining arguments.
376 substs.push(ctx.inferred_kind(Some(&substs), param, infer_args));
380 (None, None) => break,
385 tcx.intern_substs(&substs)
388 /// Checks that the correct number of generic arguments have been provided.
389 /// Used specifically for function calls.
390 pub fn check_generic_arg_count_for_call(
394 generics: &ty::Generics,
395 seg: &hir::PathSegment<'_>,
396 is_method_call: IsMethodCall,
397 ) -> GenericArgCountResult {
398 let empty_args = hir::GenericArgs::none();
399 let gen_args = seg.args.unwrap_or(&empty_args);
400 let gen_pos = if is_method_call == IsMethodCall::Yes {
401 GenericArgPosition::MethodCall
403 GenericArgPosition::Value
405 let has_self = generics.parent.is_none() && generics.has_self;
407 Self::check_generic_arg_count(
420 /// Checks that the correct number of generic arguments have been provided.
421 /// This is used both for datatypes and function calls.
422 #[instrument(skip(tcx, gen_pos), level = "debug")]
423 pub(crate) fn check_generic_arg_count(
427 seg: &hir::PathSegment<'_>,
428 gen_params: &ty::Generics,
429 gen_args: &hir::GenericArgs<'_>,
430 gen_pos: GenericArgPosition,
433 ) -> GenericArgCountResult {
434 let default_counts = gen_params.own_defaults();
435 let param_counts = gen_params.own_counts();
437 // Subtracting from param count to ensure type params synthesized from `impl Trait`
438 // cannot be explicitly specified.
439 let synth_type_param_count = gen_params
443 matches!(param.kind, ty::GenericParamDefKind::Type { synthetic: true, .. })
446 let named_type_param_count =
447 param_counts.types - has_self as usize - synth_type_param_count;
448 let infer_lifetimes =
449 (gen_pos != GenericArgPosition::Type || infer_args) && !gen_args.has_lifetime_params();
451 if gen_pos != GenericArgPosition::Type && !gen_args.bindings.is_empty() {
452 Self::prohibit_assoc_ty_binding(tcx, gen_args.bindings[0].span);
455 let explicit_late_bound =
456 Self::prohibit_explicit_late_bound_lifetimes(tcx, gen_params, gen_args, gen_pos);
458 let mut invalid_args = vec![];
460 let mut check_lifetime_args =
461 |min_expected_args: usize,
462 max_expected_args: usize,
463 provided_args: usize,
464 late_bounds_ignore: bool| {
465 if (min_expected_args..=max_expected_args).contains(&provided_args) {
469 if late_bounds_ignore {
473 if provided_args > max_expected_args {
475 gen_args.args[max_expected_args..provided_args]
477 .map(|arg| arg.span()),
481 let gen_args_info = if provided_args > min_expected_args {
483 gen_args.args[min_expected_args..provided_args]
485 .map(|arg| arg.span()),
487 let num_redundant_args = provided_args - min_expected_args;
488 GenericArgsInfo::ExcessLifetimes { num_redundant_args }
490 let num_missing_args = min_expected_args - provided_args;
491 GenericArgsInfo::MissingLifetimes { num_missing_args }
494 let reported = WrongNumberOfGenericArgs::new(
509 let min_expected_lifetime_args = if infer_lifetimes { 0 } else { param_counts.lifetimes };
510 let max_expected_lifetime_args = param_counts.lifetimes;
511 let num_provided_lifetime_args = gen_args.num_lifetime_params();
513 let lifetimes_correct = check_lifetime_args(
514 min_expected_lifetime_args,
515 max_expected_lifetime_args,
516 num_provided_lifetime_args,
517 explicit_late_bound == ExplicitLateBound::Yes,
520 let mut check_types_and_consts = |expected_min,
522 expected_max_with_synth,
532 "check_types_and_consts"
534 if (expected_min..=expected_max).contains(&provided) {
538 let num_default_params = expected_max - expected_min;
540 let gen_args_info = if provided > expected_max {
542 gen_args.args[args_offset + expected_max..args_offset + provided]
544 .map(|arg| arg.span()),
546 let num_redundant_args = provided - expected_max;
548 // Provide extra note if synthetic arguments like `impl Trait` are specified.
549 let synth_provided = provided <= expected_max_with_synth;
551 GenericArgsInfo::ExcessTypesOrConsts {
558 let num_missing_args = expected_max - provided;
560 GenericArgsInfo::MissingTypesOrConsts {
567 debug!(?gen_args_info);
569 let reported = WrongNumberOfGenericArgs::new(
579 .emit_unless(gen_args.has_err());
585 let expected_min = if infer_args {
588 param_counts.consts + named_type_param_count
589 - default_counts.types
590 - default_counts.consts
592 debug!(?expected_min);
593 debug!(arg_counts.lifetimes=?gen_args.num_lifetime_params());
595 check_types_and_consts(
597 param_counts.consts + named_type_param_count,
598 param_counts.consts + named_type_param_count + synth_type_param_count,
599 gen_args.num_generic_params(),
600 param_counts.lifetimes + has_self as usize,
601 gen_args.num_lifetime_params(),
605 GenericArgCountResult {
607 correct: lifetimes_correct.and(args_correct).map_err(|reported| {
608 GenericArgCountMismatch { reported: Some(reported), invalid_args }
613 /// Emits an error regarding forbidden type binding associations
614 pub fn prohibit_assoc_ty_binding(tcx: TyCtxt<'_>, span: Span) {
615 tcx.sess.emit_err(AssocTypeBindingNotAllowed { span });
618 /// Prohibits explicit lifetime arguments if late-bound lifetime parameters
619 /// are present. This is used both for datatypes and function calls.
620 pub(crate) fn prohibit_explicit_late_bound_lifetimes(
623 args: &hir::GenericArgs<'_>,
624 position: GenericArgPosition,
625 ) -> ExplicitLateBound {
626 let param_counts = def.own_counts();
627 let infer_lifetimes = position != GenericArgPosition::Type && !args.has_lifetime_params();
630 return ExplicitLateBound::No;
633 if let Some(span_late) = def.has_late_bound_regions {
634 let msg = "cannot specify lifetime arguments explicitly \
635 if late bound lifetime parameters are present";
636 let note = "the late bound lifetime parameter is introduced here";
637 let span = args.args[0].span();
639 if position == GenericArgPosition::Value
640 && args.num_lifetime_params() != param_counts.lifetimes
642 let mut err = tcx.sess.struct_span_err(span, msg);
643 err.span_note(span_late, note);
646 let mut multispan = MultiSpan::from_span(span);
647 multispan.push_span_label(span_late, note);
648 tcx.struct_span_lint_hir(
649 LATE_BOUND_LIFETIME_ARGUMENTS,
650 args.args[0].hir_id(),
653 lint.build(msg).emit();
658 ExplicitLateBound::Yes
660 ExplicitLateBound::No