]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_analysis/src/astconv/generics.rs
:arrow_up: rust-analyzer
[rust.git] / compiler / rustc_hir_analysis / src / astconv / generics.rs
1 use super::IsMethodCall;
2 use crate::astconv::{
3     AstConv, CreateSubstsForGenericArgsCtxt, ExplicitLateBound, GenericArgCountMismatch,
4     GenericArgCountResult, GenericArgPosition,
5 };
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};
10 use rustc_hir as hir;
11 use rustc_hir::def::{DefKind, Res};
12 use rustc_hir::def_id::DefId;
13 use rustc_hir::GenericArg;
14 use rustc_middle::ty::{
15     self, subst, subst::SubstsRef, GenericParamDef, GenericParamDefKind, IsSuggestable, Ty, TyCtxt,
16 };
17 use rustc_session::lint::builtin::LATE_BOUND_LIFETIME_ARGUMENTS;
18 use rustc_span::{symbol::kw, Span};
19 use smallvec::SmallVec;
20
21 impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
22     /// Report an error that a generic argument did not match the generic parameter that was
23     /// expected.
24     fn generic_arg_mismatch_err(
25         tcx: TyCtxt<'_>,
26         arg: &GenericArg<'_>,
27         param: &GenericParamDef,
28         possible_ordering_error: bool,
29         help: Option<&str>,
30     ) {
31         let sess = tcx.sess;
32         let mut err = struct_span_err!(
33             sess,
34             arg.span(),
35             E0747,
36             "{} provided when a {} was expected",
37             arg.descr(),
38             param.kind.descr(),
39         );
40
41         if let GenericParamDefKind::Const { .. } = param.kind {
42             if matches!(arg, GenericArg::Type(hir::Ty { kind: hir::TyKind::Infer, .. })) {
43                 err.help("const arguments cannot yet be inferred with `_`");
44                 if sess.is_nightly_build() {
45                     err.help(
46                         "add `#![feature(generic_arg_infer)]` to the crate attributes to enable",
47                     );
48                 }
49             }
50         }
51
52         let add_braces_suggestion = |arg: &GenericArg<'_>, err: &mut Diagnostic| {
53             let suggestions = vec![
54                 (arg.span().shrink_to_lo(), String::from("{ ")),
55                 (arg.span().shrink_to_hi(), String::from(" }")),
56             ];
57             err.multipart_suggestion(
58                 "if this generic argument was intended as a const parameter, \
59                  surround it with braces",
60                 suggestions,
61                 Applicability::MaybeIncorrect,
62             );
63         };
64
65         // Specific suggestion set for diagnostics
66         match (arg, &param.kind) {
67             (
68                 GenericArg::Type(hir::Ty {
69                     kind: hir::TyKind::Path(rustc_hir::QPath::Resolved(_, path)),
70                     ..
71                 }),
72                 GenericParamDefKind::Const { .. },
73             ) => match path.res {
74                 Res::Err => {
75                     add_braces_suggestion(arg, &mut err);
76                     err.set_primary_message(
77                         "unresolved item provided when a constant was expected",
78                     )
79                     .emit();
80                     return;
81                 }
82                 Res::Def(DefKind::TyParam, src_def_id) => {
83                     if let Some(param_local_id) = param.def_id.as_local() {
84                         let param_name = tcx.hir().ty_param_name(param_local_id);
85                         let param_type = tcx.type_of(param.def_id);
86                         if param_type.is_suggestable(tcx, false) {
87                             err.span_suggestion(
88                                 tcx.def_span(src_def_id),
89                                 "consider changing this type parameter to be a `const` generic",
90                                 format!("const {}: {}", param_name, param_type),
91                                 Applicability::MaybeIncorrect,
92                             );
93                         };
94                     }
95                 }
96                 _ => add_braces_suggestion(arg, &mut err),
97             },
98             (
99                 GenericArg::Type(hir::Ty { kind: hir::TyKind::Path(_), .. }),
100                 GenericParamDefKind::Const { .. },
101             ) => add_braces_suggestion(arg, &mut err),
102             (
103                 GenericArg::Type(hir::Ty { kind: hir::TyKind::Array(_, len), .. }),
104                 GenericParamDefKind::Const { .. },
105             ) if tcx.type_of(param.def_id) == tcx.types.usize => {
106                 let snippet = sess.source_map().span_to_snippet(tcx.hir().span(len.hir_id()));
107                 if let Ok(snippet) = snippet {
108                     err.span_suggestion(
109                         arg.span(),
110                         "array type provided where a `usize` was expected, try",
111                         format!("{{ {} }}", snippet),
112                         Applicability::MaybeIncorrect,
113                     );
114                 }
115             }
116             (GenericArg::Const(cnst), GenericParamDefKind::Type { .. }) => {
117                 let body = tcx.hir().body(cnst.value.body);
118                 if let rustc_hir::ExprKind::Path(rustc_hir::QPath::Resolved(_, path)) =
119                     body.value.kind
120                 {
121                     if let Res::Def(DefKind::Fn { .. }, id) = path.res {
122                         err.help(&format!(
123                             "`{}` is a function item, not a type",
124                             tcx.item_name(id)
125                         ));
126                         err.help("function item types cannot be named directly");
127                     }
128                 }
129             }
130             _ => {}
131         }
132
133         let kind_ord = param.kind.to_ord();
134         let arg_ord = arg.to_ord();
135
136         // This note is only true when generic parameters are strictly ordered by their kind.
137         if possible_ordering_error && kind_ord.cmp(&arg_ord) != core::cmp::Ordering::Equal {
138             let (first, last) = if kind_ord < arg_ord {
139                 (param.kind.descr(), arg.descr())
140             } else {
141                 (arg.descr(), param.kind.descr())
142             };
143             err.note(&format!("{} arguments must be provided before {} arguments", first, last));
144             if let Some(help) = help {
145                 err.help(help);
146             }
147         }
148
149         err.emit();
150     }
151
152     /// Creates the relevant generic argument substitutions
153     /// corresponding to a set of generic parameters. This is a
154     /// rather complex function. Let us try to explain the role
155     /// of each of its parameters:
156     ///
157     /// To start, we are given the `def_id` of the thing we are
158     /// creating the substitutions for, and a partial set of
159     /// substitutions `parent_substs`. In general, the substitutions
160     /// for an item begin with substitutions for all the "parents" of
161     /// that item -- e.g., for a method it might include the
162     /// parameters from the impl.
163     ///
164     /// Therefore, the method begins by walking down these parents,
165     /// starting with the outermost parent and proceed inwards until
166     /// it reaches `def_id`. For each parent `P`, it will check `parent_substs`
167     /// first to see if the parent's substitutions are listed in there. If so,
168     /// we can append those and move on. Otherwise, it invokes the
169     /// three callback functions:
170     ///
171     /// - `args_for_def_id`: given the `DefId` `P`, supplies back the
172     ///   generic arguments that were given to that parent from within
173     ///   the path; so e.g., if you have `<T as Foo>::Bar`, the `DefId`
174     ///   might refer to the trait `Foo`, and the arguments might be
175     ///   `[T]`. The boolean value indicates whether to infer values
176     ///   for arguments whose values were not explicitly provided.
177     /// - `provided_kind`: given the generic parameter and the value from `args_for_def_id`,
178     ///   instantiate a `GenericArg`.
179     /// - `inferred_kind`: if no parameter was provided, and inference is enabled, then
180     ///   creates a suitable inference variable.
181     pub fn create_substs_for_generic_args<'a>(
182         tcx: TyCtxt<'tcx>,
183         def_id: DefId,
184         parent_substs: &[subst::GenericArg<'tcx>],
185         has_self: bool,
186         self_ty: Option<Ty<'tcx>>,
187         arg_count: &GenericArgCountResult,
188         ctx: &mut impl CreateSubstsForGenericArgsCtxt<'a, 'tcx>,
189     ) -> SubstsRef<'tcx> {
190         // Collect the segments of the path; we need to substitute arguments
191         // for parameters throughout the entire path (wherever there are
192         // generic parameters).
193         let mut parent_defs = tcx.generics_of(def_id);
194         let count = parent_defs.count();
195         let mut stack = vec![(def_id, parent_defs)];
196         while let Some(def_id) = parent_defs.parent {
197             parent_defs = tcx.generics_of(def_id);
198             stack.push((def_id, parent_defs));
199         }
200
201         // We manually build up the substitution, rather than using convenience
202         // methods in `subst.rs`, so that we can iterate over the arguments and
203         // parameters in lock-step linearly, instead of trying to match each pair.
204         let mut substs: SmallVec<[subst::GenericArg<'tcx>; 8]> = SmallVec::with_capacity(count);
205         // Iterate over each segment of the path.
206         while let Some((def_id, defs)) = stack.pop() {
207             let mut params = defs.params.iter().peekable();
208
209             // If we have already computed substitutions for parents, we can use those directly.
210             while let Some(&param) = params.peek() {
211                 if let Some(&kind) = parent_substs.get(param.index as usize) {
212                     substs.push(kind);
213                     params.next();
214                 } else {
215                     break;
216                 }
217             }
218
219             // `Self` is handled first, unless it's been handled in `parent_substs`.
220             if has_self {
221                 if let Some(&param) = params.peek() {
222                     if param.index == 0 {
223                         if let GenericParamDefKind::Type { .. } = param.kind {
224                             substs.push(
225                                 self_ty
226                                     .map(|ty| ty.into())
227                                     .unwrap_or_else(|| ctx.inferred_kind(None, param, true)),
228                             );
229                             params.next();
230                         }
231                     }
232                 }
233             }
234
235             // Check whether this segment takes generic arguments and the user has provided any.
236             let (generic_args, infer_args) = ctx.args_for_def_id(def_id);
237
238             let args_iter = generic_args.iter().flat_map(|generic_args| generic_args.args.iter());
239             let mut args = args_iter.clone().peekable();
240
241             // If we encounter a type or const when we expect a lifetime, we infer the lifetimes.
242             // If we later encounter a lifetime, we know that the arguments were provided in the
243             // wrong order. `force_infer_lt` records the type or const that forced lifetimes to be
244             // inferred, so we can use it for diagnostics later.
245             let mut force_infer_lt = None;
246
247             loop {
248                 // We're going to iterate through the generic arguments that the user
249                 // provided, matching them with the generic parameters we expect.
250                 // Mismatches can occur as a result of elided lifetimes, or for malformed
251                 // input. We try to handle both sensibly.
252                 match (args.peek(), params.peek()) {
253                     (Some(&arg), Some(&param)) => {
254                         match (arg, &param.kind, arg_count.explicit_late_bound) {
255                             (GenericArg::Lifetime(_), GenericParamDefKind::Lifetime, _)
256                             | (
257                                 GenericArg::Type(_) | GenericArg::Infer(_),
258                                 GenericParamDefKind::Type { .. },
259                                 _,
260                             )
261                             | (
262                                 GenericArg::Const(_) | GenericArg::Infer(_),
263                                 GenericParamDefKind::Const { .. },
264                                 _,
265                             ) => {
266                                 substs.push(ctx.provided_kind(param, arg));
267                                 args.next();
268                                 params.next();
269                             }
270                             (
271                                 GenericArg::Infer(_) | GenericArg::Type(_) | GenericArg::Const(_),
272                                 GenericParamDefKind::Lifetime,
273                                 _,
274                             ) => {
275                                 // We expected a lifetime argument, but got a type or const
276                                 // argument. That means we're inferring the lifetimes.
277                                 substs.push(ctx.inferred_kind(None, param, infer_args));
278                                 force_infer_lt = Some((arg, param));
279                                 params.next();
280                             }
281                             (GenericArg::Lifetime(_), _, ExplicitLateBound::Yes) => {
282                                 // We've come across a lifetime when we expected something else in
283                                 // the presence of explicit late bounds. This is most likely
284                                 // due to the presence of the explicit bound so we're just going to
285                                 // ignore it.
286                                 args.next();
287                             }
288                             (_, _, _) => {
289                                 // We expected one kind of parameter, but the user provided
290                                 // another. This is an error. However, if we already know that
291                                 // the arguments don't match up with the parameters, we won't issue
292                                 // an additional error, as the user already knows what's wrong.
293                                 if arg_count.correct.is_ok() {
294                                     // We're going to iterate over the parameters to sort them out, and
295                                     // show that order to the user as a possible order for the parameters
296                                     let mut param_types_present = defs
297                                         .params
298                                         .iter()
299                                         .map(|param| (param.kind.to_ord(), param.clone()))
300                                         .collect::<Vec<(ParamKindOrd, GenericParamDef)>>();
301                                     param_types_present.sort_by_key(|(ord, _)| *ord);
302                                     let (mut param_types_present, ordered_params): (
303                                         Vec<ParamKindOrd>,
304                                         Vec<GenericParamDef>,
305                                     ) = param_types_present.into_iter().unzip();
306                                     param_types_present.dedup();
307
308                                     Self::generic_arg_mismatch_err(
309                                         tcx,
310                                         arg,
311                                         param,
312                                         !args_iter.clone().is_sorted_by_key(|arg| arg.to_ord()),
313                                         Some(&format!(
314                                             "reorder the arguments: {}: `<{}>`",
315                                             param_types_present
316                                                 .into_iter()
317                                                 .map(|ord| format!("{}s", ord))
318                                                 .collect::<Vec<String>>()
319                                                 .join(", then "),
320                                             ordered_params
321                                                 .into_iter()
322                                                 .filter_map(|param| {
323                                                     if param.name == kw::SelfUpper {
324                                                         None
325                                                     } else {
326                                                         Some(param.name.to_string())
327                                                     }
328                                                 })
329                                                 .collect::<Vec<String>>()
330                                                 .join(", ")
331                                         )),
332                                     );
333                                 }
334
335                                 // We've reported the error, but we want to make sure that this
336                                 // problem doesn't bubble down and create additional, irrelevant
337                                 // errors. In this case, we're simply going to ignore the argument
338                                 // and any following arguments. The rest of the parameters will be
339                                 // inferred.
340                                 while args.next().is_some() {}
341                             }
342                         }
343                     }
344
345                     (Some(&arg), None) => {
346                         // We should never be able to reach this point with well-formed input.
347                         // There are three situations in which we can encounter this issue.
348                         //
349                         //  1.  The number of arguments is incorrect. In this case, an error
350                         //      will already have been emitted, and we can ignore it.
351                         //  2.  There are late-bound lifetime parameters present, yet the
352                         //      lifetime arguments have also been explicitly specified by the
353                         //      user.
354                         //  3.  We've inferred some lifetimes, which have been provided later (i.e.
355                         //      after a type or const). We want to throw an error in this case.
356
357                         if arg_count.correct.is_ok()
358                             && arg_count.explicit_late_bound == ExplicitLateBound::No
359                         {
360                             let kind = arg.descr();
361                             assert_eq!(kind, "lifetime");
362                             let (provided_arg, param) =
363                                 force_infer_lt.expect("lifetimes ought to have been inferred");
364                             Self::generic_arg_mismatch_err(tcx, provided_arg, param, false, None);
365                         }
366
367                         break;
368                     }
369
370                     (None, Some(&param)) => {
371                         // If there are fewer arguments than parameters, it means
372                         // we're inferring the remaining arguments.
373                         substs.push(ctx.inferred_kind(Some(&substs), param, infer_args));
374                         params.next();
375                     }
376
377                     (None, None) => break,
378                 }
379             }
380         }
381
382         tcx.intern_substs(&substs)
383     }
384
385     /// Checks that the correct number of generic arguments have been provided.
386     /// Used specifically for function calls.
387     pub fn check_generic_arg_count_for_call(
388         tcx: TyCtxt<'_>,
389         span: Span,
390         def_id: DefId,
391         generics: &ty::Generics,
392         seg: &hir::PathSegment<'_>,
393         is_method_call: IsMethodCall,
394     ) -> GenericArgCountResult {
395         let empty_args = hir::GenericArgs::none();
396         let gen_args = seg.args.unwrap_or(&empty_args);
397         let gen_pos = if is_method_call == IsMethodCall::Yes {
398             GenericArgPosition::MethodCall
399         } else {
400             GenericArgPosition::Value
401         };
402         let has_self = generics.parent.is_none() && generics.has_self;
403
404         Self::check_generic_arg_count(
405             tcx,
406             span,
407             def_id,
408             seg,
409             generics,
410             gen_args,
411             gen_pos,
412             has_self,
413             seg.infer_args,
414         )
415     }
416
417     /// Checks that the correct number of generic arguments have been provided.
418     /// This is used both for datatypes and function calls.
419     #[instrument(skip(tcx, gen_pos), level = "debug")]
420     pub(crate) fn check_generic_arg_count(
421         tcx: TyCtxt<'_>,
422         span: Span,
423         def_id: DefId,
424         seg: &hir::PathSegment<'_>,
425         gen_params: &ty::Generics,
426         gen_args: &hir::GenericArgs<'_>,
427         gen_pos: GenericArgPosition,
428         has_self: bool,
429         infer_args: bool,
430     ) -> GenericArgCountResult {
431         let default_counts = gen_params.own_defaults();
432         let param_counts = gen_params.own_counts();
433
434         // Subtracting from param count to ensure type params synthesized from `impl Trait`
435         // cannot be explicitly specified.
436         let synth_type_param_count = gen_params
437             .params
438             .iter()
439             .filter(|param| {
440                 matches!(param.kind, ty::GenericParamDefKind::Type { synthetic: true, .. })
441             })
442             .count();
443         let named_type_param_count =
444             param_counts.types - has_self as usize - synth_type_param_count;
445         let infer_lifetimes =
446             (gen_pos != GenericArgPosition::Type || infer_args) && !gen_args.has_lifetime_params();
447
448         if gen_pos != GenericArgPosition::Type && let Some(b) = gen_args.bindings.first() {
449             Self::prohibit_assoc_ty_binding(tcx, b.span);
450         }
451
452         let explicit_late_bound =
453             Self::prohibit_explicit_late_bound_lifetimes(tcx, gen_params, gen_args, gen_pos);
454
455         let mut invalid_args = vec![];
456
457         let mut check_lifetime_args =
458             |min_expected_args: usize,
459              max_expected_args: usize,
460              provided_args: usize,
461              late_bounds_ignore: bool| {
462                 if (min_expected_args..=max_expected_args).contains(&provided_args) {
463                     return Ok(());
464                 }
465
466                 if late_bounds_ignore {
467                     return Ok(());
468                 }
469
470                 if provided_args > max_expected_args {
471                     invalid_args.extend(
472                         gen_args.args[max_expected_args..provided_args]
473                             .iter()
474                             .map(|arg| arg.span()),
475                     );
476                 };
477
478                 let gen_args_info = if provided_args > min_expected_args {
479                     invalid_args.extend(
480                         gen_args.args[min_expected_args..provided_args]
481                             .iter()
482                             .map(|arg| arg.span()),
483                     );
484                     let num_redundant_args = provided_args - min_expected_args;
485                     GenericArgsInfo::ExcessLifetimes { num_redundant_args }
486                 } else {
487                     let num_missing_args = min_expected_args - provided_args;
488                     GenericArgsInfo::MissingLifetimes { num_missing_args }
489                 };
490
491                 let reported = WrongNumberOfGenericArgs::new(
492                     tcx,
493                     gen_args_info,
494                     seg,
495                     gen_params,
496                     has_self as usize,
497                     gen_args,
498                     def_id,
499                 )
500                 .diagnostic()
501                 .emit();
502
503                 Err(reported)
504             };
505
506         let min_expected_lifetime_args = if infer_lifetimes { 0 } else { param_counts.lifetimes };
507         let max_expected_lifetime_args = param_counts.lifetimes;
508         let num_provided_lifetime_args = gen_args.num_lifetime_params();
509
510         let lifetimes_correct = check_lifetime_args(
511             min_expected_lifetime_args,
512             max_expected_lifetime_args,
513             num_provided_lifetime_args,
514             explicit_late_bound == ExplicitLateBound::Yes,
515         );
516
517         let mut check_types_and_consts = |expected_min,
518                                           expected_max,
519                                           expected_max_with_synth,
520                                           provided,
521                                           params_offset,
522                                           args_offset| {
523             debug!(
524                 ?expected_min,
525                 ?expected_max,
526                 ?provided,
527                 ?params_offset,
528                 ?args_offset,
529                 "check_types_and_consts"
530             );
531             if (expected_min..=expected_max).contains(&provided) {
532                 return Ok(());
533             }
534
535             let num_default_params = expected_max - expected_min;
536
537             let gen_args_info = if provided > expected_max {
538                 invalid_args.extend(
539                     gen_args.args[args_offset + expected_max..args_offset + provided]
540                         .iter()
541                         .map(|arg| arg.span()),
542                 );
543                 let num_redundant_args = provided - expected_max;
544
545                 // Provide extra note if synthetic arguments like `impl Trait` are specified.
546                 let synth_provided = provided <= expected_max_with_synth;
547
548                 GenericArgsInfo::ExcessTypesOrConsts {
549                     num_redundant_args,
550                     num_default_params,
551                     args_offset,
552                     synth_provided,
553                 }
554             } else {
555                 let num_missing_args = expected_max - provided;
556
557                 GenericArgsInfo::MissingTypesOrConsts {
558                     num_missing_args,
559                     num_default_params,
560                     args_offset,
561                 }
562             };
563
564             debug!(?gen_args_info);
565
566             let reported = WrongNumberOfGenericArgs::new(
567                 tcx,
568                 gen_args_info,
569                 seg,
570                 gen_params,
571                 params_offset,
572                 gen_args,
573                 def_id,
574             )
575             .diagnostic()
576             .emit_unless(gen_args.has_err());
577
578             Err(reported)
579         };
580
581         let args_correct = {
582             let expected_min = if infer_args {
583                 0
584             } else {
585                 param_counts.consts + named_type_param_count
586                     - default_counts.types
587                     - default_counts.consts
588             };
589             debug!(?expected_min);
590             debug!(arg_counts.lifetimes=?gen_args.num_lifetime_params());
591
592             check_types_and_consts(
593                 expected_min,
594                 param_counts.consts + named_type_param_count,
595                 param_counts.consts + named_type_param_count + synth_type_param_count,
596                 gen_args.num_generic_params(),
597                 param_counts.lifetimes + has_self as usize,
598                 gen_args.num_lifetime_params(),
599             )
600         };
601
602         GenericArgCountResult {
603             explicit_late_bound,
604             correct: lifetimes_correct.and(args_correct).map_err(|reported| {
605                 GenericArgCountMismatch { reported: Some(reported), invalid_args }
606             }),
607         }
608     }
609
610     /// Emits an error regarding forbidden type binding associations
611     pub fn prohibit_assoc_ty_binding(tcx: TyCtxt<'_>, span: Span) {
612         tcx.sess.emit_err(AssocTypeBindingNotAllowed { span });
613     }
614
615     /// Prohibits explicit lifetime arguments if late-bound lifetime parameters
616     /// are present. This is used both for datatypes and function calls.
617     pub(crate) fn prohibit_explicit_late_bound_lifetimes(
618         tcx: TyCtxt<'_>,
619         def: &ty::Generics,
620         args: &hir::GenericArgs<'_>,
621         position: GenericArgPosition,
622     ) -> ExplicitLateBound {
623         let param_counts = def.own_counts();
624         let infer_lifetimes = position != GenericArgPosition::Type && !args.has_lifetime_params();
625
626         if infer_lifetimes {
627             return ExplicitLateBound::No;
628         }
629
630         if let Some(span_late) = def.has_late_bound_regions {
631             let msg = "cannot specify lifetime arguments explicitly \
632                        if late bound lifetime parameters are present";
633             let note = "the late bound lifetime parameter is introduced here";
634             let span = args.args[0].span();
635
636             if position == GenericArgPosition::Value
637                 && args.num_lifetime_params() != param_counts.lifetimes
638             {
639                 let mut err = tcx.sess.struct_span_err(span, msg);
640                 err.span_note(span_late, note);
641                 err.emit();
642             } else {
643                 let mut multispan = MultiSpan::from_span(span);
644                 multispan.push_span_label(span_late, note);
645                 tcx.struct_span_lint_hir(
646                     LATE_BOUND_LIFETIME_ARGUMENTS,
647                     args.args[0].hir_id(),
648                     multispan,
649                     msg,
650                     |lint| lint,
651                 );
652             }
653
654             ExplicitLateBound::Yes
655         } else {
656             ExplicitLateBound::No
657         }
658     }
659 }