rustc_hir_analysis/errors/
wrong_number_of_generic_args.rs

1use std::iter;
2
3use GenericArgsInfo::*;
4use rustc_errors::codes::*;
5use rustc_errors::{Applicability, Diag, Diagnostic, EmissionGuarantee, MultiSpan, pluralize};
6use rustc_hir as hir;
7use rustc_middle::ty::{self as ty, AssocItems, AssocKind, TyCtxt};
8use rustc_span::def_id::DefId;
9use tracing::debug;
10
11/// Handles the `wrong number of type / lifetime / ... arguments` family of error messages.
12pub(crate) struct WrongNumberOfGenericArgs<'a, 'tcx> {
13    pub(crate) tcx: TyCtxt<'tcx>,
14
15    pub(crate) angle_brackets: AngleBrackets,
16
17    pub(crate) gen_args_info: GenericArgsInfo,
18
19    /// Offending path segment
20    pub(crate) path_segment: &'a hir::PathSegment<'a>,
21
22    /// Generic parameters as expected by type or trait
23    pub(crate) gen_params: &'a ty::Generics,
24
25    /// Index offset into parameters. Depends on whether `Self` is included and on
26    /// number of lifetime parameters in case we're processing missing or redundant
27    /// type or constant arguments.
28    pub(crate) params_offset: usize,
29
30    /// Generic arguments as provided by user
31    pub(crate) gen_args: &'a hir::GenericArgs<'a>,
32
33    /// DefId of the generic type
34    pub(crate) def_id: DefId,
35}
36
37// Provides information about the kind of arguments that were provided for
38// the PathSegment, for which missing generic arguments were detected
39#[derive(Debug)]
40pub(crate) enum AngleBrackets {
41    // No angle brackets were provided, but generic arguments exist in elided form
42    Implied,
43
44    // No angle brackets were provided
45    Missing,
46
47    // Angle brackets are available, but missing some generic arguments
48    Available,
49}
50
51// Information about the kind of arguments that are either missing or are unexpected
52#[derive(Debug)]
53pub(crate) enum GenericArgsInfo {
54    MissingLifetimes {
55        num_missing_args: usize,
56    },
57    ExcessLifetimes {
58        num_redundant_args: usize,
59    },
60    MissingTypesOrConsts {
61        num_missing_args: usize,
62
63        // type or const generic arguments can have default values
64        num_default_params: usize,
65
66        // lifetime arguments precede type and const parameters, this
67        // field gives the number of generic lifetime arguments to let
68        // us infer the position of type and const generic arguments
69        // in the angle brackets
70        args_offset: usize,
71    },
72
73    ExcessTypesOrConsts {
74        num_redundant_args: usize,
75
76        // type or const generic arguments can have default values
77        num_default_params: usize,
78
79        // lifetime arguments precede type and const parameters, this
80        // field gives the number of generic lifetime arguments to let
81        // us infer the position of type and const generic arguments
82        // in the angle brackets
83        args_offset: usize,
84
85        // if synthetic type arguments (e.g. `impl Trait`) are specified
86        synth_provided: bool,
87    },
88}
89
90impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
91    pub(crate) fn new(
92        tcx: TyCtxt<'tcx>,
93        gen_args_info: GenericArgsInfo,
94        path_segment: &'a hir::PathSegment<'_>,
95        gen_params: &'a ty::Generics,
96        params_offset: usize,
97        gen_args: &'a hir::GenericArgs<'a>,
98        def_id: DefId,
99    ) -> Self {
100        let angle_brackets = if gen_args.span_ext().is_none() {
101            if gen_args.is_empty() { AngleBrackets::Missing } else { AngleBrackets::Implied }
102        } else {
103            AngleBrackets::Available
104        };
105
106        Self {
107            tcx,
108            angle_brackets,
109            gen_args_info,
110            path_segment,
111            gen_params,
112            params_offset,
113            gen_args,
114            def_id,
115        }
116    }
117
118    fn missing_lifetimes(&self) -> bool {
119        match self.gen_args_info {
120            MissingLifetimes { .. } | ExcessLifetimes { .. } => true,
121            MissingTypesOrConsts { .. } | ExcessTypesOrConsts { .. } => false,
122        }
123    }
124
125    fn kind(&self) -> &str {
126        if self.missing_lifetimes() { "lifetime" } else { "generic" }
127    }
128
129    /// Returns true if the generic type is a trait
130    /// and is being referred to from one of its trait impls
131    fn is_in_trait_impl(&self) -> bool {
132        if self.tcx.is_trait(self.def_id) {
133            // Here we check if the reference to the generic type
134            // is from the 'of_trait' field of the enclosing impl
135
136            let parent = self.tcx.parent_hir_node(self.path_segment.hir_id);
137            let parent_item = self
138                .tcx
139                .hir_node_by_def_id(self.tcx.hir_get_parent_item(self.path_segment.hir_id).def_id);
140
141            // Get the HIR id of the trait ref
142            let hir::Node::TraitRef(hir::TraitRef { hir_ref_id: trait_ref_id, .. }) = parent else {
143                return false;
144            };
145
146            // Get the HIR id of the 'of_trait' field of the impl
147            let hir::Node::Item(hir::Item {
148                kind:
149                    hir::ItemKind::Impl(hir::Impl {
150                        of_trait: Some(hir::TraitRef { hir_ref_id: id_in_of_trait, .. }),
151                        ..
152                    }),
153                ..
154            }) = parent_item
155            else {
156                return false;
157            };
158
159            // Check that trait is referred to from the of_trait field of impl
160            trait_ref_id == id_in_of_trait
161        } else {
162            false
163        }
164    }
165
166    fn num_provided_args(&self) -> usize {
167        if self.missing_lifetimes() {
168            self.num_provided_lifetime_args()
169        } else {
170            self.num_provided_type_or_const_args()
171        }
172    }
173
174    fn num_provided_lifetime_args(&self) -> usize {
175        match self.angle_brackets {
176            AngleBrackets::Missing => 0,
177            // Only lifetime arguments can be implied
178            AngleBrackets::Implied => self.gen_args.args.len(),
179            AngleBrackets::Available => self.gen_args.num_lifetime_params(),
180        }
181    }
182
183    fn num_provided_type_or_const_args(&self) -> usize {
184        match self.angle_brackets {
185            AngleBrackets::Missing => 0,
186            // Only lifetime arguments can be implied
187            AngleBrackets::Implied => 0,
188            AngleBrackets::Available => self.gen_args.num_generic_params(),
189        }
190    }
191
192    fn num_expected_lifetime_args(&self) -> usize {
193        let num_provided_args = self.num_provided_lifetime_args();
194        match self.gen_args_info {
195            MissingLifetimes { num_missing_args } => num_provided_args + num_missing_args,
196            ExcessLifetimes { num_redundant_args } => num_provided_args - num_redundant_args,
197            _ => 0,
198        }
199    }
200
201    fn num_expected_type_or_const_args(&self) -> usize {
202        let num_provided_args = self.num_provided_type_or_const_args();
203        match self.gen_args_info {
204            MissingTypesOrConsts { num_missing_args, .. } => num_provided_args + num_missing_args,
205            ExcessTypesOrConsts { num_redundant_args, .. } => {
206                num_provided_args - num_redundant_args
207            }
208            _ => 0,
209        }
210    }
211
212    // Gives the number of expected arguments taking into account default arguments
213    fn num_expected_type_or_const_args_including_defaults(&self) -> usize {
214        let provided_args = self.num_provided_type_or_const_args();
215        match self.gen_args_info {
216            MissingTypesOrConsts { num_missing_args, num_default_params, .. } => {
217                provided_args + num_missing_args - num_default_params
218            }
219            ExcessTypesOrConsts { num_redundant_args, num_default_params, .. } => {
220                provided_args - num_redundant_args - num_default_params
221            }
222            _ => 0,
223        }
224    }
225
226    fn num_missing_lifetime_args(&self) -> usize {
227        let missing_args = self.num_expected_lifetime_args() - self.num_provided_lifetime_args();
228        assert!(missing_args > 0);
229        missing_args
230    }
231
232    fn num_missing_type_or_const_args(&self) -> usize {
233        let missing_args = self.num_expected_type_or_const_args_including_defaults()
234            - self.num_provided_type_or_const_args();
235        assert!(missing_args > 0);
236        missing_args
237    }
238
239    fn num_excess_lifetime_args(&self) -> usize {
240        match self.gen_args_info {
241            ExcessLifetimes { num_redundant_args } => num_redundant_args,
242            _ => 0,
243        }
244    }
245
246    fn num_excess_type_or_const_args(&self) -> usize {
247        match self.gen_args_info {
248            ExcessTypesOrConsts { num_redundant_args, .. } => num_redundant_args,
249            _ => 0,
250        }
251    }
252
253    fn too_many_args_provided(&self) -> bool {
254        match self.gen_args_info {
255            MissingLifetimes { .. } | MissingTypesOrConsts { .. } => false,
256            ExcessLifetimes { num_redundant_args }
257            | ExcessTypesOrConsts { num_redundant_args, .. } => {
258                assert!(num_redundant_args > 0);
259                true
260            }
261        }
262    }
263
264    fn not_enough_args_provided(&self) -> bool {
265        match self.gen_args_info {
266            MissingLifetimes { num_missing_args }
267            | MissingTypesOrConsts { num_missing_args, .. } => {
268                assert!(num_missing_args > 0);
269                true
270            }
271            ExcessLifetimes { .. } | ExcessTypesOrConsts { .. } => false,
272        }
273    }
274
275    // Helper method to get the index offset in angle brackets, at which type or const arguments
276    // start appearing
277    fn get_lifetime_args_offset(&self) -> usize {
278        match self.gen_args_info {
279            MissingLifetimes { .. } | ExcessLifetimes { .. } => 0,
280            MissingTypesOrConsts { args_offset, .. } | ExcessTypesOrConsts { args_offset, .. } => {
281                args_offset
282            }
283        }
284    }
285
286    fn get_num_default_params(&self) -> usize {
287        match self.gen_args_info {
288            MissingTypesOrConsts { num_default_params, .. }
289            | ExcessTypesOrConsts { num_default_params, .. } => num_default_params,
290            _ => 0,
291        }
292    }
293
294    fn is_synth_provided(&self) -> bool {
295        match self.gen_args_info {
296            ExcessTypesOrConsts { synth_provided, .. } => synth_provided,
297            _ => false,
298        }
299    }
300
301    // Helper function to choose a quantifier word for the number of expected arguments
302    // and to give a bound for the number of expected arguments
303    fn get_quantifier_and_bound(&self) -> (&'static str, usize) {
304        if self.get_num_default_params() == 0 {
305            match self.gen_args_info {
306                MissingLifetimes { .. } | ExcessLifetimes { .. } => {
307                    ("", self.num_expected_lifetime_args())
308                }
309                MissingTypesOrConsts { .. } | ExcessTypesOrConsts { .. } => {
310                    ("", self.num_expected_type_or_const_args())
311                }
312            }
313        } else {
314            match self.gen_args_info {
315                MissingLifetimes { .. } => ("at least ", self.num_expected_lifetime_args()),
316                MissingTypesOrConsts { .. } => {
317                    ("at least ", self.num_expected_type_or_const_args_including_defaults())
318                }
319                ExcessLifetimes { .. } => ("at most ", self.num_expected_lifetime_args()),
320                ExcessTypesOrConsts { .. } => ("at most ", self.num_expected_type_or_const_args()),
321            }
322        }
323    }
324
325    // Creates lifetime name suggestions from the lifetime parameter names
326    fn get_lifetime_args_suggestions_from_param_names(
327        &self,
328        path_hir_id: hir::HirId,
329        num_params_to_take: usize,
330    ) -> String {
331        debug!(?path_hir_id);
332
333        // If there was already a lifetime among the arguments, just replicate that one.
334        if let Some(lt) = self.gen_args.args.iter().find_map(|arg| match arg {
335            hir::GenericArg::Lifetime(lt) => Some(lt),
336            _ => None,
337        }) {
338            return std::iter::repeat(lt.to_string())
339                .take(num_params_to_take)
340                .collect::<Vec<_>>()
341                .join(", ");
342        }
343
344        let mut ret = Vec::new();
345        let mut ty_id = None;
346        for (id, node) in self.tcx.hir_parent_iter(path_hir_id) {
347            debug!(?id);
348            if let hir::Node::Ty(_) = node {
349                ty_id = Some(id);
350            }
351
352            // Suggest `'_` when in function parameter or elided function return.
353            if let Some(fn_decl) = node.fn_decl()
354                && let Some(ty_id) = ty_id
355            {
356                let in_arg = fn_decl.inputs.iter().any(|t| t.hir_id == ty_id);
357                let in_ret =
358                    matches!(fn_decl.output, hir::FnRetTy::Return(ty) if ty.hir_id == ty_id);
359
360                if in_arg || (in_ret && fn_decl.lifetime_elision_allowed) {
361                    return std::iter::repeat("'_".to_owned())
362                        .take(num_params_to_take)
363                        .collect::<Vec<_>>()
364                        .join(", ");
365                }
366            }
367
368            // Suggest `'static` when in const/static item-like.
369            if let hir::Node::Item(hir::Item {
370                kind: hir::ItemKind::Static { .. } | hir::ItemKind::Const { .. },
371                ..
372            })
373            | hir::Node::TraitItem(hir::TraitItem {
374                kind: hir::TraitItemKind::Const { .. },
375                ..
376            })
377            | hir::Node::ImplItem(hir::ImplItem {
378                kind: hir::ImplItemKind::Const { .. },
379                ..
380            })
381            | hir::Node::ForeignItem(hir::ForeignItem {
382                kind: hir::ForeignItemKind::Static { .. },
383                ..
384            })
385            | hir::Node::AnonConst(..) = node
386            {
387                return std::iter::repeat("'static".to_owned())
388                    .take(num_params_to_take.saturating_sub(ret.len()))
389                    .collect::<Vec<_>>()
390                    .join(", ");
391            }
392
393            let params = if let Some(generics) = node.generics() {
394                generics.params
395            } else if let hir::Node::Ty(ty) = node
396                && let hir::TyKind::BareFn(bare_fn) = ty.kind
397            {
398                bare_fn.generic_params
399            } else {
400                &[]
401            };
402            ret.extend(params.iter().filter_map(|p| {
403                let hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit } =
404                    p.kind
405                else {
406                    return None;
407                };
408                let hir::ParamName::Plain(name) = p.name else { return None };
409                Some(name.to_string())
410            }));
411
412            if ret.len() >= num_params_to_take {
413                return ret[..num_params_to_take].join(", ");
414            }
415            // We cannot refer to lifetimes defined in an outer function.
416            if let hir::Node::Item(_) = node {
417                break;
418            }
419        }
420
421        // We could not gather enough lifetime parameters in the scope.
422        // We use the parameter names from the target type's definition instead.
423        self.gen_params
424            .own_params
425            .iter()
426            .skip(self.params_offset + self.num_provided_lifetime_args())
427            .take(num_params_to_take)
428            .map(|param| param.name.to_string())
429            .collect::<Vec<_>>()
430            .join(", ")
431    }
432
433    // Creates type or constant name suggestions from the provided parameter names
434    fn get_type_or_const_args_suggestions_from_param_names(
435        &self,
436        num_params_to_take: usize,
437    ) -> String {
438        let is_in_a_method_call = self
439            .tcx
440            .hir_parent_iter(self.path_segment.hir_id)
441            .skip(1)
442            .find_map(|(_, node)| match node {
443                hir::Node::Expr(expr) => Some(expr),
444                _ => None,
445            })
446            .is_some_and(|expr| {
447                matches!(
448                    expr.kind,
449                    hir::ExprKind::MethodCall(hir::PathSegment { args: Some(_), .. }, ..)
450                )
451            });
452
453        let fn_sig = self.tcx.hir_get_if_local(self.def_id).and_then(hir::Node::fn_sig);
454        let is_used_in_input = |def_id| {
455            fn_sig.is_some_and(|fn_sig| {
456                fn_sig.decl.inputs.iter().any(|ty| match ty.kind {
457                    hir::TyKind::Path(hir::QPath::Resolved(
458                        None,
459                        hir::Path { res: hir::def::Res::Def(_, id), .. },
460                    )) => *id == def_id,
461                    _ => false,
462                })
463            })
464        };
465        self.gen_params
466            .own_params
467            .iter()
468            .skip(self.params_offset + self.num_provided_type_or_const_args())
469            .take(num_params_to_take)
470            .map(|param| match param.kind {
471                // If it's in method call (turbofish), it might be inferred from the expression (e.g. `.collect::<Vec<_>>()`)
472                // If it is being inferred from the item's inputs, no need to set it.
473                ty::GenericParamDefKind::Type { .. }
474                    if is_in_a_method_call || is_used_in_input(param.def_id) =>
475                {
476                    "_"
477                }
478                _ => param.name.as_str(),
479            })
480            .intersperse(", ")
481            .collect()
482    }
483
484    fn get_unbound_associated_types(&self) -> Vec<String> {
485        if self.tcx.is_trait(self.def_id) {
486            let items: &AssocItems = self.tcx.associated_items(self.def_id);
487            items
488                .in_definition_order()
489                .filter(|item| item.kind == AssocKind::Type)
490                .filter(|item| {
491                    !self
492                        .gen_args
493                        .constraints
494                        .iter()
495                        .any(|constraint| constraint.ident.name == item.name)
496                })
497                .filter(|item| !item.is_impl_trait_in_trait())
498                .map(|item| self.tcx.item_ident(item.def_id).to_string())
499                .collect()
500        } else {
501            Vec::default()
502        }
503    }
504
505    fn create_error_message(&self) -> String {
506        let def_path = self.tcx.def_path_str(self.def_id);
507        let def_kind = self.tcx.def_descr(self.def_id);
508        let (quantifier, bound) = self.get_quantifier_and_bound();
509        let kind = self.kind();
510        let provided_lt_args = self.num_provided_lifetime_args();
511        let provided_type_or_const_args = self.num_provided_type_or_const_args();
512
513        let (provided_args_str, verb) = match self.gen_args_info {
514            MissingLifetimes { .. } | ExcessLifetimes { .. } => (
515                format!("{} lifetime argument{}", provided_lt_args, pluralize!(provided_lt_args)),
516                pluralize!("was", provided_lt_args),
517            ),
518            MissingTypesOrConsts { .. } | ExcessTypesOrConsts { .. } => (
519                format!(
520                    "{} generic argument{}",
521                    provided_type_or_const_args,
522                    pluralize!(provided_type_or_const_args)
523                ),
524                pluralize!("was", provided_type_or_const_args),
525            ),
526        };
527
528        if self.gen_args.span_ext().is_some() {
529            format!(
530                "{} takes {}{} {} argument{} but {} {} supplied",
531                def_kind,
532                quantifier,
533                bound,
534                kind,
535                pluralize!(bound),
536                provided_args_str.as_str(),
537                verb
538            )
539        } else {
540            format!("missing generics for {def_kind} `{def_path}`")
541        }
542    }
543
544    /// Builds the `expected 1 type argument / supplied 2 type arguments` message.
545    fn notify(&self, err: &mut Diag<'_, impl EmissionGuarantee>) {
546        let (quantifier, bound) = self.get_quantifier_and_bound();
547        let provided_args = self.num_provided_args();
548
549        err.span_label(
550            self.path_segment.ident.span,
551            format!(
552                "expected {}{} {} argument{}",
553                quantifier,
554                bound,
555                self.kind(),
556                pluralize!(bound),
557            ),
558        );
559
560        // When too many arguments were provided, we don't highlight each of them, because it
561        // would overlap with the suggestion to remove them:
562        //
563        // ```
564        // type Foo = Bar<usize, usize>;
565        //                -----  ----- supplied 2 type arguments
566        //                     ^^^^^^^ remove this type argument
567        // ```
568        if self.too_many_args_provided() {
569            return;
570        }
571
572        let args = self
573            .gen_args
574            .args
575            .iter()
576            .skip(self.get_lifetime_args_offset())
577            .take(provided_args)
578            .enumerate();
579
580        for (i, arg) in args {
581            err.span_label(
582                arg.span(),
583                if i + 1 == provided_args {
584                    format!(
585                        "supplied {} {} argument{}",
586                        provided_args,
587                        self.kind(),
588                        pluralize!(provided_args)
589                    )
590                } else {
591                    String::new()
592                },
593            );
594        }
595    }
596
597    fn suggest(&self, err: &mut Diag<'_, impl EmissionGuarantee>) {
598        debug!(
599            "suggest(self.provided {:?}, self.gen_args.span(): {:?})",
600            self.num_provided_args(),
601            self.gen_args.span(),
602        );
603
604        match self.angle_brackets {
605            AngleBrackets::Missing | AngleBrackets::Implied => self.suggest_adding_args(err),
606            AngleBrackets::Available => {
607                if self.not_enough_args_provided() {
608                    self.suggest_adding_args(err);
609                } else if self.too_many_args_provided() {
610                    self.suggest_moving_args_from_assoc_fn_to_trait(err);
611                    self.suggest_removing_args_or_generics(err);
612                } else {
613                    unreachable!();
614                }
615            }
616        }
617    }
618
619    /// Suggests to add missing argument(s) when current invocation site already contains some
620    /// generics:
621    ///
622    /// ```text
623    /// type Map = HashMap<String>;
624    /// ```
625    fn suggest_adding_args(&self, err: &mut Diag<'_, impl EmissionGuarantee>) {
626        if self.gen_args.parenthesized != hir::GenericArgsParentheses::No {
627            return;
628        }
629
630        match self.gen_args_info {
631            MissingLifetimes { .. } => {
632                self.suggest_adding_lifetime_args(err);
633            }
634            MissingTypesOrConsts { .. } => {
635                self.suggest_adding_type_and_const_args(err);
636            }
637            ExcessTypesOrConsts { .. } => {
638                // this can happen with `~const T` where T isn't a const_trait.
639            }
640            _ => unreachable!(),
641        }
642    }
643
644    fn suggest_adding_lifetime_args(&self, err: &mut Diag<'_, impl EmissionGuarantee>) {
645        debug!("suggest_adding_lifetime_args(path_segment: {:?})", self.path_segment);
646        let num_missing_args = self.num_missing_lifetime_args();
647        let num_params_to_take = num_missing_args;
648        let msg = format!("add missing {} argument{}", self.kind(), pluralize!(num_missing_args));
649
650        let suggested_args = self.get_lifetime_args_suggestions_from_param_names(
651            self.path_segment.hir_id,
652            num_params_to_take,
653        );
654        debug!("suggested_args: {suggested_args:?}");
655
656        match self.angle_brackets {
657            AngleBrackets::Missing => {
658                let span = self.path_segment.ident.span;
659
660                // insert a suggestion of the form "Y<'a, 'b>"
661                let sugg = format!("<{suggested_args}>");
662                debug!("sugg: {:?}", sugg);
663
664                err.span_suggestion_verbose(
665                    span.shrink_to_hi(),
666                    msg,
667                    sugg,
668                    Applicability::HasPlaceholders,
669                );
670            }
671
672            AngleBrackets::Available => {
673                let (sugg_span, is_first) = if self.num_provided_lifetime_args() == 0 {
674                    (self.gen_args.span().unwrap().shrink_to_lo(), true)
675                } else {
676                    let last_lt = &self.gen_args.args[self.num_provided_lifetime_args() - 1];
677                    (last_lt.span().shrink_to_hi(), false)
678                };
679                let has_non_lt_args = self.num_provided_type_or_const_args() != 0;
680                let has_constraints = !self.gen_args.constraints.is_empty();
681
682                let sugg_prefix = if is_first { "" } else { ", " };
683                let sugg_suffix =
684                    if is_first && (has_non_lt_args || has_constraints) { ", " } else { "" };
685
686                let sugg = format!("{sugg_prefix}{suggested_args}{sugg_suffix}");
687                debug!("sugg: {:?}", sugg);
688
689                err.span_suggestion_verbose(sugg_span, msg, sugg, Applicability::HasPlaceholders);
690            }
691            AngleBrackets::Implied => {
692                // We never encounter missing lifetimes in situations in which lifetimes are elided
693                unreachable!();
694            }
695        }
696    }
697
698    fn suggest_adding_type_and_const_args(&self, err: &mut Diag<'_, impl EmissionGuarantee>) {
699        let num_missing_args = self.num_missing_type_or_const_args();
700        let msg = format!("add missing {} argument{}", self.kind(), pluralize!(num_missing_args));
701
702        let suggested_args =
703            self.get_type_or_const_args_suggestions_from_param_names(num_missing_args);
704        debug!("suggested_args: {:?}", suggested_args);
705
706        match self.angle_brackets {
707            AngleBrackets::Missing | AngleBrackets::Implied => {
708                let span = self.path_segment.ident.span;
709
710                // insert a suggestion of the form "Y<T, U>"
711                let sugg = format!("<{suggested_args}>");
712                debug!("sugg: {:?}", sugg);
713
714                err.span_suggestion_verbose(
715                    span.shrink_to_hi(),
716                    msg,
717                    sugg,
718                    Applicability::HasPlaceholders,
719                );
720            }
721            AngleBrackets::Available => {
722                let gen_args_span = self.gen_args.span().unwrap();
723                let sugg_offset =
724                    self.get_lifetime_args_offset() + self.num_provided_type_or_const_args();
725
726                let (sugg_span, is_first) = if sugg_offset == 0 {
727                    (gen_args_span.shrink_to_lo(), true)
728                } else {
729                    let arg_span = self.gen_args.args[sugg_offset - 1].span();
730                    // If we came here then inferred lifetime's spans can only point
731                    // to either the opening bracket or to the space right after.
732                    // Both of these spans have an `hi` lower than or equal to the span
733                    // of the generics excluding the brackets.
734                    // This allows us to check if `arg_span` is the artificial span of
735                    // an inferred lifetime, in which case the generic we're suggesting to
736                    // add will be the first visible, even if it isn't the actual first generic.
737                    (arg_span.shrink_to_hi(), arg_span.hi() <= gen_args_span.lo())
738                };
739
740                let sugg_prefix = if is_first { "" } else { ", " };
741                let sugg_suffix =
742                    if is_first && !self.gen_args.constraints.is_empty() { ", " } else { "" };
743
744                let sugg = format!("{sugg_prefix}{suggested_args}{sugg_suffix}");
745                debug!("sugg: {:?}", sugg);
746
747                err.span_suggestion_verbose(sugg_span, msg, sugg, Applicability::HasPlaceholders);
748            }
749        }
750    }
751
752    /// Suggests moving redundant argument(s) of an associate function to the
753    /// trait it belongs to.
754    ///
755    /// ```compile_fail
756    /// Into::into::<Option<_>>(42) // suggests considering `Into::<Option<_>>::into(42)`
757    /// ```
758    fn suggest_moving_args_from_assoc_fn_to_trait(
759        &self,
760        err: &mut Diag<'_, impl EmissionGuarantee>,
761    ) {
762        let trait_ = match self.tcx.trait_of_item(self.def_id) {
763            Some(def_id) => def_id,
764            None => return,
765        };
766
767        // Skip suggestion when the associated function is itself generic, it is unclear
768        // how to split the provided parameters between those to suggest to the trait and
769        // those to remain on the associated type.
770        let num_assoc_fn_expected_args =
771            self.num_expected_type_or_const_args() + self.num_expected_lifetime_args();
772        if num_assoc_fn_expected_args > 0 {
773            return;
774        }
775
776        let num_assoc_fn_excess_args =
777            self.num_excess_type_or_const_args() + self.num_excess_lifetime_args();
778
779        let trait_generics = self.tcx.generics_of(trait_);
780        let num_trait_generics_except_self =
781            trait_generics.count() - if trait_generics.has_self { 1 } else { 0 };
782
783        let msg = format!(
784            "consider moving {these} generic argument{s} to the `{name}` trait, which takes up to {num} argument{s}",
785            these = pluralize!("this", num_assoc_fn_excess_args),
786            s = pluralize!(num_assoc_fn_excess_args),
787            name = self.tcx.item_name(trait_),
788            num = num_trait_generics_except_self,
789        );
790
791        if let hir::Node::Expr(expr) = self.tcx.parent_hir_node(self.path_segment.hir_id) {
792            match &expr.kind {
793                hir::ExprKind::Path(qpath) => self
794                    .suggest_moving_args_from_assoc_fn_to_trait_for_qualified_path(
795                        err,
796                        qpath,
797                        msg,
798                        num_assoc_fn_excess_args,
799                        num_trait_generics_except_self,
800                    ),
801                hir::ExprKind::MethodCall(..) => self
802                    .suggest_moving_args_from_assoc_fn_to_trait_for_method_call(
803                        err,
804                        trait_,
805                        expr,
806                        msg,
807                        num_assoc_fn_excess_args,
808                        num_trait_generics_except_self,
809                    ),
810                _ => return,
811            }
812        }
813    }
814
815    fn suggest_moving_args_from_assoc_fn_to_trait_for_qualified_path(
816        &self,
817        err: &mut Diag<'_, impl EmissionGuarantee>,
818        qpath: &'tcx hir::QPath<'tcx>,
819        msg: String,
820        num_assoc_fn_excess_args: usize,
821        num_trait_generics_except_self: usize,
822    ) {
823        if let hir::QPath::Resolved(_, path) = qpath
824            && let Some(trait_path_segment) = path.segments.get(0)
825        {
826            let num_generic_args_supplied_to_trait = trait_path_segment.args().num_generic_params();
827
828            if num_generic_args_supplied_to_trait + num_assoc_fn_excess_args
829                == num_trait_generics_except_self
830                && let Some(span) = self.gen_args.span_ext()
831                && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
832            {
833                let sugg = vec![
834                    (
835                        self.path_segment.ident.span,
836                        format!("{}::{}", snippet, self.path_segment.ident),
837                    ),
838                    (span.with_lo(self.path_segment.ident.span.hi()), "".to_owned()),
839                ];
840
841                err.multipart_suggestion(msg, sugg, Applicability::MaybeIncorrect);
842            }
843        }
844    }
845
846    fn suggest_moving_args_from_assoc_fn_to_trait_for_method_call(
847        &self,
848        err: &mut Diag<'_, impl EmissionGuarantee>,
849        trait_def_id: DefId,
850        expr: &'tcx hir::Expr<'tcx>,
851        msg: String,
852        num_assoc_fn_excess_args: usize,
853        num_trait_generics_except_self: usize,
854    ) {
855        let sm = self.tcx.sess.source_map();
856        let hir::ExprKind::MethodCall(_, rcvr, args, _) = expr.kind else {
857            return;
858        };
859        if num_assoc_fn_excess_args != num_trait_generics_except_self {
860            return;
861        }
862        let Some(gen_args) = self.gen_args.span_ext() else {
863            return;
864        };
865        let Ok(generics) = sm.span_to_snippet(gen_args) else {
866            return;
867        };
868        let Ok(rcvr) =
869            sm.span_to_snippet(rcvr.span.find_ancestor_inside(expr.span).unwrap_or(rcvr.span))
870        else {
871            return;
872        };
873        let Ok(rest) = (match args {
874            [] => Ok(String::new()),
875            [arg] => {
876                sm.span_to_snippet(arg.span.find_ancestor_inside(expr.span).unwrap_or(arg.span))
877            }
878            [first, .., last] => {
879                let first_span = first.span.find_ancestor_inside(expr.span).unwrap_or(first.span);
880                let last_span = last.span.find_ancestor_inside(expr.span).unwrap_or(last.span);
881                sm.span_to_snippet(first_span.to(last_span))
882            }
883        }) else {
884            return;
885        };
886        let comma = if args.len() > 0 { ", " } else { "" };
887        let trait_path = self.tcx.def_path_str(trait_def_id);
888        let method_name = self.tcx.item_name(self.def_id);
889        err.span_suggestion_verbose(
890            expr.span,
891            msg,
892            format!("{trait_path}::{generics}::{method_name}({rcvr}{comma}{rest})"),
893            Applicability::MaybeIncorrect,
894        );
895    }
896
897    /// Suggests to remove redundant argument(s):
898    ///
899    /// ```text
900    /// type Map = HashMap<String, String, String, String>;
901    /// ```
902    fn suggest_removing_args_or_generics(&self, err: &mut Diag<'_, impl EmissionGuarantee>) {
903        let num_provided_lt_args = self.num_provided_lifetime_args();
904        let num_provided_type_const_args = self.num_provided_type_or_const_args();
905        let unbound_types = self.get_unbound_associated_types();
906        let num_provided_args = num_provided_lt_args + num_provided_type_const_args;
907        assert!(num_provided_args > 0);
908
909        let num_redundant_lt_args = self.num_excess_lifetime_args();
910        let num_redundant_type_or_const_args = self.num_excess_type_or_const_args();
911        let num_redundant_args = num_redundant_lt_args + num_redundant_type_or_const_args;
912
913        let redundant_lifetime_args = num_redundant_lt_args > 0;
914        let redundant_type_or_const_args = num_redundant_type_or_const_args > 0;
915
916        let remove_entire_generics = num_redundant_args >= self.gen_args.args.len();
917        let provided_args_matches_unbound_traits =
918            unbound_types.len() == num_redundant_type_or_const_args;
919
920        let remove_lifetime_args = |err: &mut Diag<'_, _>| {
921            let mut lt_arg_spans = Vec::new();
922            let mut found_redundant = false;
923            for arg in self.gen_args.args {
924                if let hir::GenericArg::Lifetime(_) = arg {
925                    lt_arg_spans.push(arg.span());
926                    if lt_arg_spans.len() > self.num_expected_lifetime_args() {
927                        found_redundant = true;
928                    }
929                } else if found_redundant {
930                    // Argument which is redundant and separated like this `'c`
931                    // is not included to avoid including `Bar` in span.
932                    // ```
933                    // type Foo<'a, T> = &'a T;
934                    // let _: Foo<'a, 'b, Bar, 'c>;
935                    // ```
936                    break;
937                }
938            }
939
940            let span_lo_redundant_lt_args = if self.num_expected_lifetime_args() == 0 {
941                lt_arg_spans[0]
942            } else {
943                lt_arg_spans[self.num_expected_lifetime_args() - 1]
944            };
945            let span_hi_redundant_lt_args = lt_arg_spans[lt_arg_spans.len() - 1];
946
947            let span_redundant_lt_args =
948                span_lo_redundant_lt_args.shrink_to_hi().to(span_hi_redundant_lt_args);
949            debug!("span_redundant_lt_args: {:?}", span_redundant_lt_args);
950
951            let num_redundant_lt_args = lt_arg_spans.len() - self.num_expected_lifetime_args();
952            let msg_lifetimes =
953                format!("remove the lifetime argument{s}", s = pluralize!(num_redundant_lt_args));
954
955            err.span_suggestion(
956                span_redundant_lt_args,
957                msg_lifetimes,
958                "",
959                Applicability::MaybeIncorrect,
960            );
961        };
962
963        let remove_type_or_const_args = |err: &mut Diag<'_, _>| {
964            let mut gen_arg_spans = Vec::new();
965            let mut found_redundant = false;
966            for arg in self.gen_args.args {
967                match arg {
968                    hir::GenericArg::Type(_)
969                    | hir::GenericArg::Const(_)
970                    | hir::GenericArg::Infer(_) => {
971                        gen_arg_spans.push(arg.span());
972                        if gen_arg_spans.len() > self.num_expected_type_or_const_args() {
973                            found_redundant = true;
974                        }
975                    }
976                    _ if found_redundant => break,
977                    _ => {}
978                }
979            }
980
981            let span_lo_redundant_type_or_const_args =
982                if self.num_expected_type_or_const_args() == 0 {
983                    gen_arg_spans[0]
984                } else {
985                    gen_arg_spans[self.num_expected_type_or_const_args() - 1]
986                };
987            let span_hi_redundant_type_or_const_args = gen_arg_spans[gen_arg_spans.len() - 1];
988            let span_redundant_type_or_const_args = span_lo_redundant_type_or_const_args
989                .shrink_to_hi()
990                .to(span_hi_redundant_type_or_const_args);
991
992            debug!("span_redundant_type_or_const_args: {:?}", span_redundant_type_or_const_args);
993
994            let num_redundant_gen_args =
995                gen_arg_spans.len() - self.num_expected_type_or_const_args();
996            let msg_types_or_consts = format!(
997                "remove the unnecessary generic argument{s}",
998                s = pluralize!(num_redundant_gen_args),
999            );
1000
1001            err.span_suggestion(
1002                span_redundant_type_or_const_args,
1003                msg_types_or_consts,
1004                "",
1005                Applicability::MaybeIncorrect,
1006            );
1007        };
1008
1009        // If there is a single unbound associated type and a single excess generic param
1010        // suggest replacing the generic param with the associated type bound
1011        if provided_args_matches_unbound_traits && !unbound_types.is_empty() {
1012            // Don't suggest if we're in a trait impl as
1013            // that would result in invalid syntax (fixes #116464)
1014            if !self.is_in_trait_impl() {
1015                let unused_generics = &self.gen_args.args[self.num_expected_type_or_const_args()..];
1016                let suggestions = iter::zip(unused_generics, &unbound_types)
1017                    .map(|(potential, name)| {
1018                        (potential.span().shrink_to_lo(), format!("{name} = "))
1019                    })
1020                    .collect::<Vec<_>>();
1021
1022                if !suggestions.is_empty() {
1023                    err.multipart_suggestion_verbose(
1024                        format!(
1025                            "replace the generic bound{s} with the associated type{s}",
1026                            s = pluralize!(unbound_types.len())
1027                        ),
1028                        suggestions,
1029                        Applicability::MaybeIncorrect,
1030                    );
1031                }
1032            }
1033        } else if remove_entire_generics {
1034            let span = self
1035                .path_segment
1036                .args
1037                .unwrap()
1038                .span_ext()
1039                .unwrap()
1040                .with_lo(self.path_segment.ident.span.hi());
1041
1042            let msg = format!(
1043                "remove the unnecessary {}generics",
1044                if self.gen_args.parenthesized == hir::GenericArgsParentheses::ParenSugar {
1045                    "parenthetical "
1046                } else {
1047                    ""
1048                },
1049            );
1050
1051            if span.is_empty() {
1052                // HACK: Avoid ICE when types with the same name with `derive`s are in the same scope:
1053                //     struct NotSM;
1054                //     #[derive(PartialEq, Eq)]
1055                //     struct NotSM<T>(T);
1056                // With the above code, the suggestion would be to remove the generics of the first
1057                // `NotSM`, which doesn't *have* generics, so we would suggest to remove no code with
1058                // no code, which would trigger an `assert!` later. Ideally, we would do something a
1059                // bit more principled. See closed PR #109082.
1060            } else {
1061                err.span_suggestion(span, msg, "", Applicability::MaybeIncorrect);
1062            }
1063        } else if redundant_lifetime_args && redundant_type_or_const_args {
1064            remove_lifetime_args(err);
1065            remove_type_or_const_args(err);
1066        } else if redundant_lifetime_args {
1067            remove_lifetime_args(err);
1068        } else {
1069            assert!(redundant_type_or_const_args);
1070            remove_type_or_const_args(err);
1071        }
1072    }
1073
1074    /// Builds the `type defined here` message.
1075    fn show_definition(&self, err: &mut Diag<'_, impl EmissionGuarantee>) {
1076        let mut spans: MultiSpan = if let Some(def_span) = self.tcx.def_ident_span(self.def_id) {
1077            if self.tcx.sess.source_map().is_span_accessible(def_span) {
1078                def_span.into()
1079            } else {
1080                return;
1081            }
1082        } else {
1083            return;
1084        };
1085
1086        let msg = {
1087            let def_kind = self.tcx.def_descr(self.def_id);
1088            let (quantifier, bound) = self.get_quantifier_and_bound();
1089
1090            let params = if bound == 0 {
1091                String::new()
1092            } else {
1093                let params = self
1094                    .gen_params
1095                    .own_params
1096                    .iter()
1097                    .skip(self.params_offset)
1098                    .take(bound)
1099                    .map(|param| {
1100                        let span = self.tcx.def_span(param.def_id);
1101                        spans.push_span_label(span, "");
1102                        param
1103                    })
1104                    .map(|param| format!("`{}`", param.name))
1105                    .collect::<Vec<_>>()
1106                    .join(", ");
1107
1108                format!(": {params}")
1109            };
1110
1111            format!(
1112                "{} defined here, with {}{} {} parameter{}{}",
1113                def_kind,
1114                quantifier,
1115                bound,
1116                self.kind(),
1117                pluralize!(bound),
1118                params,
1119            )
1120        };
1121
1122        err.span_note(spans, msg);
1123    }
1124
1125    /// Add note if `impl Trait` is explicitly specified.
1126    fn note_synth_provided(&self, err: &mut Diag<'_, impl EmissionGuarantee>) {
1127        if !self.is_synth_provided() {
1128            return;
1129        }
1130
1131        err.note("`impl Trait` cannot be explicitly specified as a generic argument");
1132    }
1133}
1134
1135impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for WrongNumberOfGenericArgs<'_, '_> {
1136    fn into_diag(
1137        self,
1138        dcx: rustc_errors::DiagCtxtHandle<'a>,
1139        level: rustc_errors::Level,
1140    ) -> Diag<'a, G> {
1141        let msg = self.create_error_message();
1142        let mut err = Diag::new(dcx, level, msg);
1143        err.code(E0107);
1144        err.span(self.path_segment.ident.span);
1145
1146        self.notify(&mut err);
1147        self.suggest(&mut err);
1148        self.show_definition(&mut err);
1149        self.note_synth_provided(&mut err);
1150
1151        err
1152    }
1153}