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