]> git.lizzy.rs Git - rust.git/blobdiff - src/librustc_typeck/astconv.rs
Move generic arg / param validation to `create_substs_for_generic_args`
[rust.git] / src / librustc_typeck / astconv.rs
index 5c9178ff66d155e9cfdaed25d78841a4bdce1473..4ef732a7662a77646b6dda86c74afb70b58493da 100644 (file)
@@ -313,9 +313,10 @@ fn check_generic_arg_count(
         }
 
         // Prohibit explicit lifetime arguments if late-bound lifetime parameters are present.
-        let mut reported_late_bound_region_err = None;
+        let mut reported_late_bound_region_err = false;
         if !infer_lifetimes {
             if let Some(span_late) = def.has_late_bound_regions {
+                reported_late_bound_region_err = true;
                 let msg = "cannot specify lifetime arguments explicitly \
                            if late bound lifetime parameters are present";
                 let note = "the late bound lifetime parameter is introduced here";
@@ -326,7 +327,6 @@ fn check_generic_arg_count(
                     let mut err = tcx.sess.struct_span_err(span, msg);
                     err.span_note(span_late, note);
                     err.emit();
-                    reported_late_bound_region_err = Some(true);
                 } else {
                     let mut multispan = MultiSpan::from_span(span);
                     multispan.push_span_label(span_late, note.to_string());
@@ -336,7 +336,6 @@ fn check_generic_arg_count(
                         multispan,
                         |lint| lint.build(msg).emit(),
                     );
-                    reported_late_bound_region_err = Some(false);
                 }
             }
         }
@@ -405,10 +404,10 @@ fn check_generic_arg_count(
                 true
             };
 
-        let mut arg_count_mismatch = reported_late_bound_region_err.unwrap_or(false);
+        let mut arg_count_mismatch = reported_late_bound_region_err;
         let mut unexpected_spans = vec![];
 
-        if reported_late_bound_region_err.is_none()
+        if !reported_late_bound_region_err
             && (!infer_lifetimes || arg_counts.lifetimes > param_counts.lifetimes)
         {
             arg_count_mismatch |= check_kind_count(
@@ -482,6 +481,7 @@ pub fn create_substs_for_generic_args<'b>(
         parent_substs: &[subst::GenericArg<'tcx>],
         has_self: bool,
         self_ty: Option<Ty<'tcx>>,
+        arg_count_mismatch: bool,
         args_for_def_id: impl Fn(DefId) -> (Option<&'b GenericArgs<'b>>, bool),
         provided_kind: impl Fn(&GenericParamDef, &GenericArg<'_>) -> subst::GenericArg<'tcx>,
         mut inferred_kind: impl FnMut(
@@ -505,7 +505,6 @@ pub fn create_substs_for_generic_args<'b>(
         // methods in `subst.rs`, so that we can iterate over the arguments and
         // parameters in lock-step linearly, instead of trying to match each pair.
         let mut substs: SmallVec<[subst::GenericArg<'tcx>; 8]> = SmallVec::with_capacity(count);
-
         // Iterate over each segment of the path.
         while let Some((def_id, defs)) = stack.pop() {
             let mut params = defs.params.iter().peekable();
@@ -542,6 +541,18 @@ pub fn create_substs_for_generic_args<'b>(
             let mut args =
                 generic_args.iter().flat_map(|generic_args| generic_args.args.iter()).peekable();
 
+            let arg_kind = |arg| match arg {
+                &GenericArg::Lifetime(_) => "lifetime",
+                &GenericArg::Type(_) => "type",
+                &GenericArg::Const(_) => "constant",
+            };
+
+            // If we encounter a type or const when we expect a lifetime, we infer the lifetimes.
+            // If we later encounter a lifetime, we know that the arguments were provided in the
+            // wrong order. `force_infer_lt` records the type or const that forced lifetimes to be
+            // inferred, so we can use it for diagnostics later.
+            let mut force_infer_lt = None;
+
             loop {
                 // We're going to iterate through the generic arguments that the user
                 // provided, matching them with the generic parameters we expect.
@@ -562,28 +573,74 @@ pub fn create_substs_for_generic_args<'b>(
                                 // We expected a lifetime argument, but got a type or const
                                 // argument. That means we're inferring the lifetimes.
                                 substs.push(inferred_kind(None, param, infer_args));
+                                force_infer_lt = Some(arg);
                                 params.next();
                             }
-                            (_, _) => {
+                            (_, kind) => {
                                 // We expected one kind of parameter, but the user provided
-                                // another. This is an error, but we need to handle it
-                                // gracefully so we can report sensible errors.
-                                // In this case, we're simply going to infer this argument.
-                                args.next();
+                                // another. This is an error. However, if we already know that
+                                // the arguments don't match up with the parameters, we won't issue
+                                // an additional error, as the user already knows what's wrong.
+                                if !arg_count_mismatch {
+                                    let param_kind = match kind {
+                                        GenericParamDefKind::Lifetime => "lifetime",
+                                        GenericParamDefKind::Type { .. } => "type",
+                                        GenericParamDefKind::Const => "constant",
+                                    };
+                                    struct_span_err!(
+                                        tcx.sess,
+                                        arg.span(),
+                                        E0747,
+                                        "{} provided when a {} was expected",
+                                        arg_kind(arg),
+                                        param_kind,
+                                    )
+                                    .emit();
+                                }
+
+                                // We've reported the error, but we want to make sure that this
+                                // problem doesn't bubble down and create additional, irrelevant
+                                // errors. In this case, we're simply going to ignore the argument
+                                // and any following arguments. The rest of the parameters will be
+                                // inferred.
+                                while args.next().is_some() {}
                             }
                         }
                     }
-                    (Some(_), None) => {
+                    (Some(&arg), None) => {
                         // We should never be able to reach this point with well-formed input.
-                        // Getting to this point means the user supplied more arguments than
-                        // there are parameters.
-                        args.next();
+                        // There are two situations in which we can encounter this issue.
+                        //
+                        //  1.  The number of arguments is incorrect. In this case, an error
+                        //      will already have been emitted, and we can ignore it. This case
+                        //      also occurs when late-bound lifetime parameters are present, yet
+                        //      the lifetime arguments have also been explicitly specified by the
+                        //      user.
+                        //  2.  We've inferred some lifetimes, which have been provided later (i.e.
+                        //      after a type or const). We want to throw an error in this case.
+
+                        if !arg_count_mismatch {
+                            let kind = arg_kind(arg);
+                            assert_eq!(kind, "lifetime");
+                            let provided =
+                                force_infer_lt.expect("lifetimes ought to have been inferred");
+                            struct_span_err!(
+                                tcx.sess,
+                                provided.span(),
+                                E0747,
+                                "{} provided when a {} was expected",
+                                arg_kind(provided),
+                                kind,
+                            )
+                            .emit();
+                        }
+
+                        break;
                     }
                     (None, Some(&param)) => {
                         // If there are fewer arguments than parameters, it means
                         // we're inferring the remaining arguments.
                         substs.push(inferred_kind(Some(&substs), param, infer_args));
-                        args.next();
                         params.next();
                     }
                     (None, None) => break,
@@ -659,7 +716,7 @@ fn create_substs_for_ast_path<'a>(
             assert!(self_ty.is_none() && parent_substs.is_empty());
         }
 
-        let (_, potential_assoc_types) = Self::check_generic_arg_count(
+        let (arg_count_mismatch, potential_assoc_types) = Self::check_generic_arg_count(
             tcx,
             span,
             &generic_params,
@@ -692,8 +749,16 @@ fn create_substs_for_ast_path<'a>(
             parent_substs,
             self_ty.is_some(),
             self_ty,
+            arg_count_mismatch,
             // Provide the generic args, and whether types should be inferred.
-            |_| (Some(generic_args), infer_args),
+            |did| {
+                if did == def_id {
+                    (Some(generic_args), infer_args)
+                } else {
+                    // The last component of this tuple is unimportant.
+                    (None, false)
+                }
+            },
             // Provide substitutions for parameters for which (valid) arguments have been provided.
             |param, arg| match (&param.kind, arg) {
                 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {