Skip to content

Weirdness with macros trying to redefine each other #45732

@durka

Description

@durka

On IRC we were trying to make a macro that turns itself into a no-op after the first call. I think it's not actually possible, but I was confused by the compiler's behavior.

A macro that tries to redefine itself (or another already existing macro) is allowed to do so once, but fails with an error the second time.

macro_rules! once {
    () => {
        macro_rules! once { () => {} }
    }
}

once!(); // OK
once!(); // ERROR
error: `once` is already in scope
 --> src/main.rs:3:9
  |
3 |         macro_rules! once { () => {} }
  |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
...
7 | once!();
  | -------- in this macro invocation
  |
  = note: macro-expanded `macro_rules!`s may not shadow existing macros (see RFC 1560)

The error points to the first invocation. However, there is no error if I remove the second invocation!

Also, why can't I do this? :) The error refers us to RFC 1560 which doesn't talk about macros.

cc @jseyfried

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions