What macro rules treat `()`, `[]` and `{}` all the same?

Wouldn't it be more expressive and less ambiguous to differentiate these three parenthesis/brackets? What's the philosophy behind this?

Technically, it doesn't treat them all exactly the same. When you use {} it becomes "block like" and can either be an expression, statements, or items. When you use the others it becomes "expression-like" and requires a semicolon if you expand to items or statements.

Is it weird that any macro can use any delimiter? ...yeah, kinda. Never made sense to me why this decision was made.

6 Likes

This is, by the way, a reason to always use the braced call syntax (sub_macro! {}) when recursing.

Unfortunately the answer to many macro_rules questions is "because that's what was implemented at the time". The Grand Planā„¢ is to make Macros 2.0 (there's even the macro keyword reserved for it) that are better, but...

5 Likes

Thanks for the information! But what?

There is no underlying philosophy - it happened by accident.

We needed a working macro system for Rust 1.0, and this system worked. It was not as well thought out as other features in Rust.


Specifically, it was designed to be deprecated. This is why macro_rules is called macro_rules! It's so that the "macro" keyword can be used with the better designed future replacement.

I can see there being arguments both for and against this. At the very least, I agree that restricting macros to only one kind of invocation could be useful. The discussion of this should be part of designing macros 2.0 (the macro keyword). The reason macro_rules! doesn't implement it is because we knew explicitly that macros 2.0 would be coming, and designing/implementing differentiating between (), [] and {} is work that didn't need to be done.

For more information, I recommend reading RFC 1548, which is the beginning of the specification for macros 2.0, and mentions a bit how we didn't design everything the best it could be in macro_rules.

3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.