Skip to content

Odd behaviour coming from macros #84259

Closed
@InnocentusLime

Description

@InnocentusLime

I tried this code:

struct T(i32);

#[macro_export]
macro_rules! test {
  ($array_type:ty => $($elem:expr),+ $(,)?) => {};
  ($($elem:expr),+) => {};
}

fn main() {
    test!(T(2));
}

I expected it to compile, since T(2) is obviously an expression.

Instead I received the following compiler error:

error: expected type, found 2

The compiler seems to forcefully parse the string with the first rule (although it is clearly inapplicable here), fails and terminates with an error.

What is more surprising is that the following code compiles just fine

struct T;

#[macro_export]
macro_rules! test {
  ($array_type:ty => $($elem:expr),+ $(,)?) => {};
  ($($elem:expr),+) => {};
}

fn main() {
    test!(T);
}

Even the right branch gets picked (the second one)!

Moreover, reordering the branches breaks the following example (which compiles if you swap the test's arms back)

struct T(i32);

#[macro_export]
macro_rules! test {
  ($($elem:expr),+) => {};
  ($array_type:ty => $($elem:expr),+ $(,)?) => {};
}

fn main() {
    test!([&'static T; 2] => T(2));
}

Meta

rustc --version --verbose:

rustc 1.51.0 (2fd73fabe 2021-03-23)
binary: rustc
commit-hash: 2fd73fabe469357a12c2c974c140f67e7cdd76d0
commit-date: 2021-03-23
host: x86_64-unknown-linux-gnu
release: 1.51.0
LLVM version: 11.0.1

Beta and nightly struggle with this code too.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-macrosArea: All kinds of macros (custom derive, macro_rules!, proc macros, ..)C-bugCategory: This is a bug.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions