reference icon indicating copy to clipboard operation
reference copied to clipboard

"Macros by example" page mixes language and macro_rules input syntax definitions

Open konnorandrews opened this issue 6 months ago • 2 comments

My understanding is the reference's syntax sections should represent what is syntactically valid Rust. However, given the current syntax on the Macros by example page it implies the following code is syntactically invalid.

#[cfg(false)]
macro_rules! name {
  struct Demo;
}

This in fact compiles fine. The macro_rules! acts as a normal macro call where the body is allowed to be any token stream. This means in the reference the MacroRules should actually be Token*.

I propose the reference be changed so that this page splits the syntax for the language vs the syntax inside macro_rules! calls. This way no content is lost, but the distinction is shown.

konnorandrews avatar May 09 '26 21:05 konnorandrews

I looked into this, and I think the example compiles only because of the #[cfg(false)]: the item is removed before the macro body is checked. Without it, the same body is rejected.

$ rustc --edition 2021 --crate-type bin mr.rs
error: expected `=>`, found `Demo`
 --> mr.rs:2:3

Concretely, on nightly-2026-10-15:

source result
#[cfg(false)] macro_rules! name { struct Demo; } compiles (exit 0)
#[cfg(true)] macro_rules! name { struct Demo; } error (exit 1)
macro_rules! name { struct Demo; } error (exit 1)

So macro_rules! does not accept an arbitrary token stream: the body has to be valid macro rules, and the compiler checks that even when the macro is never used. That is what the grammar on the page says, since MacroRulesDef requires MacroRules, so I do not think MacroRules should become Token*.

I may be missing a case where the body really is arbitrary, so if you have a reproduction that does not go through cfg, I would be glad to see it.

isHeSatoshi avatar Oct 19 '26 08:10 isHeSatoshi

#[cfg(false)] doesn't change what syntax is allowed by the language. As example, the following produces the following error.

#[cfg(false)]
fn foo() {
  a b c
}
error: expected one of `!`, `.`, `::`, `;`, `?`, `{`, `}`, or an operator, found `b`
 --> src/main.rs:5:5
  |
5 |   a b c
  |     ^ expected one of 8 possible tokens
  |
help: there is a keyword `as` with a similar name
  |
5 |   as b c
  |    +

macro_rules is unique as it is treated as a macro call by rustc. And macro call bodies are not used unless the call is expanded, which the cfg prevents.

This is important because another way to prevent a macro_rules! from being expanded is to give it to an attribute macro.

#[some_custom_attr_macro]
macro_rules! foo {
  // this body doesn't require any specific syntax 
}

konnorandrews avatar Oct 19 '26 14:10 konnorandrews