Rust Declarative Macros: A Simple and Practical Introduction


Hey everyone!

I'm back with another article focused on Rust fundamentals. I think existing material covers the basics of using Rust pretty well, but one thing that I found kind of lacking back when I learned Rust was description of macros.

It's possible it has improved nowadays, but I want to eventually write about proc-macros. So I'm going to start with an article introducing the concept of macros, and explaining the differences between Rust and C-style macros, as well as the basics of declarative macros.

Future articles will eventually get into procedural macro territory. But I want to move through this slowly and carefully.


Anyways, I hope this helps if you are new to Rust and struggling to understand the macro_rules! syntax (or just anything about Rust macros, really).

If you have questions or feedback for future articles, please let me know. :slight_smile:

Interesting. Actually I intend to learn something about Rust macros (and async as well) in the next few years. When I read the official book 3 years ago, I skipped the macro chapter--not because I consider macros as too complicated, but I had that time no real use for it. Below are some of my bookmarks about declarative macros. Can you recommend some of those articles as useful references as well?

Declarative Macros - The Little Book of Rust Macros
Introduction - Rust Macros Tutorial
A guide through rust declarative macros - DEV Community
Macros in Rust: A tutorial with examples - LogRocket Blog
Declarative macros in Rust - a way of writing your own syntax
https://medium.com/@altaaar/a-guide-to-declarative-macros-in-rust-6f006fdaeebf
https://medium.com/@nmpiash/rust-declarative-macros-a-practical-guide-to-macro-rules-3ece2e0e064e

The last link is actually quite fresh, but the other links might be a bit old.

I'm unfamiliar with most of those posts, so I'll have to take a bit of time to scan through and read them to say what I think.

However, I am familiar with the Little Book of Rust Macros. I think it's an excellent in-depth, book-style introduction to declarative macros, and delves into some advanced topic that I personally do not plan on delving into (like incremental TT munchers).

I haven't read it in a while, so I'm not sure if my feelings have changed, but I believe from what I recall I would still recommend it to someone who really wants to dig into the topic.

The big issue with that reference (and many like it), is that it gets up-to procedural macros, and then stops.

I don't blame them, it's such an involved topic. I'm going to try my best to say at least something interesting about proc-macros. But a lot of time it's like - you learn what you need to learn and then, you can apply it, but teaching it is a whole other matter...

I'm rambling though. To answer your question, yes I believe the Little Book of Rust Macros is a great read, and I recommend it. It's very probably even better than what I have posted here today. But, you know - different perspectives, and different framing might help folks who are still struggling. So I hope my article is still of some value (and I want to build up to talking about some other things, perhaps not covered in that book).

The other ones, I'm not so sure - I'd have to read them in more detail to find out. I'll take a look over the weekend, if that's okay with you. :slight_smile:

It's obvious that next chapter will be : Procedural Macros.

We'll get there - I actually have more to say about declarative macros.

This post covers the basics of how to make them, but it doesn't talk about more subjective things like good practices for writing them, how to integrate them into your project, where to use them, where not to use them, etc.

I decided to save that for another post, less my article verge on 1 hour worth of reading material... :frowning:

I just had a short look at your tutorial.

While the text starts quite fine, there might be one serious issue: You give no real introduction near to the start of the text, e.g. why some languages like Rust, Zig, Nim have macros at all, and what the difference to functions or procedures is. I assume that people coming more from languages like Python, Java, JavaScript, Ruby, are not very familiar with the term macro, or might know the term from editors or text processors for recording keyboard input. And C programmers might know macros more as a form of text substitution. I assume you will explain all that later in your text, but it should be close to the top, otherwise you will lose readers.

Thanks for the feedback!

Indeed, I may have made a large assumption that the reader even knows what a macro is. It hadn't even crossed my mind that others could be coming from a language that doesn't have them in the first place. :sweat_smile:

I'll try to add something early on. It's a bit late for me here now, but I'll take a look and see what I can do first thing in the morning.

It took me a bit longer than I had anticipated, but I have added the suggested change to give a brief introduction to what macros are.

If you have time, feel free to take a look and let me know what you think!

New Sections Added:

As I wrote in my first message, I know unfortunately not much about Rust macros -- I used them in Nim, but that was many years ago, and I forgot most of it already.

For my esthetic feeling, the first paragraph is a bit too short:

Macros are a language feature commonly used to process some inputs during compile-time, and produce some Rust code to be compiled into the invoking code.

We might expand it e.g. by "Rust macros can be used as a more powerful and versatile form of (generic) functions and methods, e.g. when a function should accept a variable length sequence of parameters with different data types, as Rust println! macro does, up to building sophisticated Domain Specific Languages (DSL), e.g. for a GUI toolkit or other purposes requiring functionality that the Rust core language does not provides.

Before the section " Benefits and Downsides of Macros" I would add a list of typical use cases, e.g. introspection. I guess the serde crate will use them?

For the list of advantages, one could say that it can improve performance, when macros can do parts of processing work already at compile time, instead whenever the binary is executed.

For the list of disadvantage, I would add compile time, e.g. the Xilem GUI toolkit struggled with that, and I think a few other crates as well.

Generally, I am not sure if it is a good idea to present the list with advantages and disadvantages that early -- an option would be to present it late, as a form of conclusion. But I think it is OK to use this early form.

Note, that all these remarks are pure spontaneous draft ideas, and the wording is quite bad, as I am not a native English speaker.

Hmm, that duplicates the things listed currently in the "Benefits" section, really.

I think I'll reword it slightly to merge the list of benefits into the description of what they are, maybe renaming the list to instead be "Common Uses for Macros" or something, as I don't want to restate what is in the bulleted list in the prior paragraph.

I can add that benefit and disadvantage as well (if I do in fact keep the list of disadvantages in the end; it might not be a bad idea to drop those as you suggest, opting to go into those in the next article, when covering real-world usage).

Thanks, I'll play around with it and see if I can reformat it to flow better. :slight_smile:

Unfortunately, I am not any longer really happy with the start of your text:

In C, macros are pretty easy to learn because you can abstract them as simple “text substitution”.

Yesterday I considered it fine -- but that is because I have some tiny C background. But many Rust people do not. And, C and Rust are not the only languages with macros, I know at least of Zig and Nim.

Also, it might be a good idea to mention, why statically typed compiled languages like Rust benefit (and need) macros, while dynamic languages like Python, Ruby, and JavaScript can live without them.

Yes, I know it is a bit hard to create a perfect text. Perhaps you should just continue with the part about proc macros, and later you can come back to fine tune all.

Note, in my online Rust book that I wrote two years ago, the chapters about macros and async are totally missing -- I was too lazy after spending around 800 hours for the other chapters -- and the number of interested readers was just too low.

[EDIT]

I really like your sentence "But the simplicity of their implementation can often lead to surprising and counter-intuitive results. As such, they are difficult to master.". But it comes a bit too early.

[EDIT 2]

I am not sure if

They are recognized as a part of the compiler’s parsing process.

is fully fine. In my feeling it should be better

They are processed during the compiler’s parsing process.

[EDIT 3]

Sorry, your sentence is mostly fine, I would use

They are recognized DURING the compiler’s parsing process.

[EDIT 4]

Maybe replace

Macros add a level of indirection that can

with

Macros can add levels of abstraction and indirection that can

Thanks again for all the great feedback, I do feel the article is becoming better because of it!

I think what I'm feeling from this feedback is that the opening should distance itself from assuming the reader has an understanding of C-style macros. So I tuned the intro to assume a bit less about the reader. I believe at least the intro flows a bit nicer here, now.

I also squashed the big "What Are Macros?" section into one section, just focusing on what they are used to accomplish. Very probably it is still not perfect, but thank you for the feedback, and if I get other feedback I will continue to massage the article into shape as time permits! :slight_smile:

You know, I'm reminded of a common thing I tell people about data analytics - which is that one of the hardest things to do, counter-intuitively is count properly (especially in the presence of large, complex datasets).

I often feel that way about explaining things; it can be easy to learn things sometimes, and it seems like it should be easy to explain what you've learned - but then I try teaching and am humbled pretty quickly. :sweat_smile:

I just saw that you tried to improve your text. Unfortunately I get the feeling that my comments just made it worse, sorry. As a non native English speaker I am now unable to make sense of the two first sentences:

Macros are commonly abstracted to be understood as simple “text substitution” language features.

Depending on how they are implemented can change your experience interacting with them.

Perhaps that is correct English, but I really doubt it. At least it is very hard to understand and make any sense of it. So perhaps you should just revert to the original version, and continue with the second part about proc macros. Again, sorry for my comments, I think I just confused you. I know myself that attempts to improve a text can make it worse, the happens to me sometimes, so I often just revert my changes.

That's okay!

I think it's correct English, but maybe I'm using too many words unnecessarily.

I'll just try to use simpler words:

Macros are commonly presented as simple "text substitution" language features. The way they're implemented can affect your experience using them.

Is a bit easier to understand. I'll update it in a few minutes.

And never fear giving such advice, I'm totally okay hearing if something is or isn't working. And if you do not wish to continue giving your thoughts, that's totally fine too - I appreciate the feedback you've given me thus far, and I personally do feel it's in a better state now than it was.

I tend to use too many words when I talk or write, so maybe a bit of that is coming out in my articles, that's still good feedback. :grinning_cat:

thanks for info

Thanks for reading! :blush:

I will try to read your full text this weekend -- I think after 3 years playing with Rust it is actually time to learn the macro stuff, and learning from fresh material is generally most fun.

Do you think that your phrase

Some common uses of macro are to…

is correct grammar? I would have used the most common singular form "of a macro" or plural "of macros". But I am not really sure.

Ah, I had intended "some common uses of macros are to...", so that is in fact a mistake. Thanks!

However, it might be simpler as you suggest to simply use singular form; "Some common uses of a macro are to...". I will update it soon here, as I'm about to publish an update on the website anyway for one of my projects.


I'm glad to hear you're going to take a look, if you find any issues don't hesitate to reach out about them!

I have edited and revised this article many times, so there might be some places where I have made some grammar mistakes like this.

One more problem I have with your grammar:

There’s more phases to compilation after this,

Sounds a bit grammatically incorrect, at least difficult to read. Could we say instead:

There are more steps in the compilation process after this,

And one question concerning Rust macros in general, which might be hard to answer:

On the Nim homepage, we had the statement below, with which I struggled all the years a bit:

Elegant

  • Macros cannot change Nim's syntax because there is no need for it — the syntax is flexible enough.

I recommended to them to just remove this statement from the frontpage, as it is a bit hard to understand, and not really important to mention.

So what could we say about Rust macros -- can they change the syntax?