Why is mainstream Rust so macro-heavy?

While going through Luca Palmieri's book Zero to Production in Rust, I realized majority of the heavily used crates in Rust ecosystem are macro-heavy. Procedural macros for initialization and configuration, declaratives for variadic functions and kind-of "one command that rules them all" APIs.
What would writing and reading Rust be like without the convenience of macros?

Remember that just because someone wrote a library that works a certain way, doesn’t mean that that’s the way that Rust is. You can, and should, reject libraries for overusing macros. Or use the non-macro API if there is one.

just embrace and macros.

macros are part of the language, why try to avoid them? like, do you avoid templates in C++? do you avoid monads and do notation in haskell? do you avoid spawning threads in erlang?

to be honest, coming from lisp, I really hope rust macros were more powerful, and they were "first class" constructs like functions. but realistically, macros in their current form are already quite usable. I will not complain.

I avoid C++ precisely because of the unreadable and unreasonable template syntax. Can't say much about others.

I'm not complaining either. Macros are zero-cost abstractions anyway. What I'm curious about is that procedural macros are being used to remedy which shortcoming of the language that they're the first thing I encounter while checking a lib's examples?

I don’t think that there’s really one “shortcoming of the language” behind this phenomenon, or even a finite set. Yes, macros are sometimes written for a specific such shortcoming, but in my experience, lots of macros are motivated by just “I wanted a shorter/prettier syntax to express this specific idea”, where it would be unreasonable for the language to include special support for that idea.

I suppose one could argue that derive macros are being used to address the shortcoming of not yet having reflection. (But also, derive macros are some of the better-justified macros, because they’re largely not introducing gratuitous new syntax, but drawing new conclusions from existing syntax.)

You mean compile-time reflection like C++?

A major reason to avoid both is that error messages are utterly terrible and IDE autocomplete largely useless.

I’m not relevantly familiar with C++ to say, but for purposes of “features Rust doesn’t have yet but might”, “reflection” means functions and structs that provide information about types as the compiler understands them, rather than the pure syntax tree as is currently available to macros.

The current unstable prototype iteration of this idea can be found in std::mem::type_info and the unstable methods of TypeId. This is compile-time reflection, in that the functions to obtain the info can only be called at compile time, not run time (so that the compiler is not obligated to include information about all types in the binary for later lookup).

I would not say I avoid them. But writing macros is hard and I have never had a need to do so in my application code.

Yes. For the same reasons. Until I started to avoid C++ altogether,

Again I would not say avoid. It's just that after trying to understand a hundred times what a monad is I still don't get it :frowning:

No, I love spawning threads in whatever language.

Of course having said that I'm very happy to use existing macros in std or whatever. crate I'm using.

This makes awful lot of sense now! With compile time reflection, the initialization routine would be sufficient to specialize an instance of a library type based on the client type. That's hidden flow too, but hidden in the library code itself. Correct me if I'm wrong.

Thanks.

Pick a file you wish to examine, and run cargo expand which will replace all its macros with the code they generate.

Proc macros in particular have a compile-time cost. Others already mentioned the IDE and worse-errors costs.

(These costs may be considered acceptable.)


As for some of the "why"s I've encountered...

Rust is a very boilerplate heavy language. Macro crates like strum or thiserror can reduce visible boilerplate significantly for some common patterns. Arguably at least some ecosystem derive traits should be uplifted to std.

The limitations of coherence / the orphan rules / the lack of specialization can result in needing to avoid a blanket implementation for your trait, but then you want to implement it for some large number of std types or whatever. Macros can help here. I've also wanted something related for local types only -- i.e. wished for a way to write a pseudo-blanket impl that only applies to local types, as an alternative to macros (or pasting the same implementation 10 times).

Relatedly, implementing something on the 32 combinations of dyn Trait + [AutoTraits] is an exercise in copy-paste without macros. Some impl for dyn Trait + ?Auto1 + ?Auto2 feature could remove that pain.

Implementing something for tuples has a similar problem, which some form of generic variadics could solve. And for related types too, like closures that take some number of arguments.

I kinda disagree to that statement a bit, simply cause macros make life both hard + easy, static compile time safety and performance is the goal of langauge, but the hard part is also writing and maintaining it as well! I wouldn't solely reject any crate just cause it's uses macros too much entirely ! These are my thoughts

If you compare this with C world API you'll however find pretty similar situation as well ! So I don't see any crate using macros as a bad sign it's just how static compilation works at the end of the day !

Ha ha, I remember someone attempting to explain them with snails eating snails, of all things. Honestly I think a large part of the confusion is just because it's actually in practice such a trivial concept (abstracting the sequencing of functions, something relatively useless outside the context of a pure virtual language like Haskell) that people refuse to accept that something often described in such complicated ways can actually be that simple.

I'll refrain from subjecting you to yet another detailed breakdown :face_savoring_food:

That's OK. I like the snail idea :slight_smile:

Some things just can’t be expressed otherwise.

My pet peeve is the str type: Somewhere the compiler knows the length. But it’s not available in the type-system. So it’s impossible to write a compile-time checked function that will take a string of a given length. You can either accept [u8; SIZE] where you loose the fact that it’s well formed UTF-8. Or you accept &str where you loose the length.

For inline strings like Stringlet, this has been overcome by tricks in the stringlet!() constructor macro. (Actually not perfectly, but mostly, for all const expressions including literal strings.)

Yes, that's precisely what C++ templates are based upon. There are an issue with terminology, though.

On one hand “reflection in C++” may mean brand-sparkling new bleediung edge C++26 feature that's only partially implemented in GCC and is not yet supported anywhere else.

On the other hand the whole language is built on top of reflection! You would find discissions about std::iterator_traits, iterator tags and the way these provide an option to do compile-time decisions (using SFINAE, usually) in tutorials that predate C++98, first official C++ standard! Template metaprogramming was discovered in 1994, but it grew quickly, by 1998 it was very much an established cornerstone of the way to define things with a reflection… something that in Rust is usually done with macros, because reflection-capable tools are carefully kept lidded in nightly and are not allowed to escape into stable.

Length in which units?

If bytes: what happens if you want a str of length 1 but have a character Ă© which needs 2 bytes in utf8? And should ee fit in the same a 2-byte str that Ă© would need on its own?

If chars: then you can use a [char; SIZE], then you only need to worry about whether é was created as a single U+00E9 (1 char) or a combination of (´ + e).

The most informative, and hilarious, source for this kind of stuff is any one of Dylan Besties talks on character encoding that you can find on YouTube

Str with length in bytes can be useful if the function is generic over the length,
A unicode character in the str being too long would just instantiate a different version of the function.