macro_rules: "no syntax variables matched as repeating at this depth" fires before "unknown macro variable"

6f313cb
Opened by Felix S Klock II at 2022-11-11 03:42:03

Consider the following code:

macro_rules! a {
    (begin $ard: ident end) => {
        [$arg]
    }
}

macro_rules! b {
    (begin $($ard: ident),* end) => {
        [$($arg),*]
    }
}

fn main() {
    let (m, n) = (1, 2);
    let x = a![begin m end];
    let y = b![begin n end];
}

This produces the following pair of error messages:

error: unknown macro variable `arg`
  --> src/main.rs:3:10
   |
3  |         [$arg]
   |          ^^^^
...
15 |     let x = a![begin m end];
   |             --------------- in this macro invocation

error: attempted to repeat an expression containing no syntax variables matched as repeating at this depth
 --> src/main.rs:9:11
  |
9 |         [$($arg),*]
  |           ^^^^^^

error: Could not compile `playground`.

While the second error message is correct in principle, it is also misleading. When I get a message like that, my focus is on counting how deeply nested the variable is. I usually don't consider "wait is the syntax variable misspelled?" when I see that error message.

I think we could and should first check if a macro variable occurs at any depth (and report the first error if not) before we report anything about whether a match is found at the current depth (and report the second error if not).

  1. Triage: barely any changes.

    Esteban Kuber at 2022-11-11 03:42:03