Skip to content

in declarative macros, "literal" matching arm can throw compiler error rather than matching or failing to match #106504

@edwardpeters

Description

@edwardpeters

(I'm not confident enough to call this a bug but I think it qualifies as unexpected behavior)

I tried this code:

macro_rules! show_me{
    ($l : literal $($tail : tt)*) => {
        println!("{} is a literal followed by {}", stringify!($l), stringify!($($tail)*));
        show_me!($($tail)*)
    };
    ($token : tt $($tail : tt)*) => {
        println!("{} is something else followed by {}", stringify!($token), stringify!($($tail)*));
        show_me!($($tail)*)
    };
    () => {}
}

fn main() {
    show_me!(-x);
}

I expected that this code would see no literals in the passed expression, and then fall through to the next branch, outputing:

- is something else followed by x
x is something else followed by 

(note that it does this for show_me!(+x))

Instead, the compiler fails with:

error: unexpected token: `x`
  --> src/main.rs:20:15
   |
8  |     ($l : literal $($tail : tt)*) => {
   |      ------------ while parsing argument for this `literal` macro fragment
...
20 |     show_me!(-x);
   |               ^

rustc --version --verbose

rustc 1.66.0 (69f9c33d7 2022-12-12)
binary: rustc
commit-hash: 69f9c33d71c871fc16ac445211281c6e7a340943
commit-date: 2022-12-12
host: x86_64-unknown-linux-gnu
release: 1.66.0
LLVM version: 15.0.2

The behavior is the same in nightly build:
rustc --version --verbose

rustc 1.68.0-nightly (659e169d3 2023-01-04)
binary: rustc
commit-hash: 659e169d37990b9c730a59a96081f2ef7afbe8f1
commit-date: 2023-01-04
host: x86_64-unknown-linux-gnu
release: 1.68.0-nightly
LLVM version: 15.0.6

And beta:
rustc --version --verbose

rustc 1.67.0-beta.6 (51b03459a 2022-12-31)
binary: rustc
commit-hash: 51b03459a49d03dbad7d120fb8575fc4580c057b
commit-date: 2022-12-31
host: x86_64-unknown-linux-gnu
release: 1.67.0-beta.6
LLVM version: 15.0.6

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-macrosArea: All kinds of macros (custom derive, macro_rules!, proc macros, ..)

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions