Are macros unreadable just for me?

That's the thing, I'd like to not have to learn this stuff at all. But I fear there may be no real way around it.

But thanks anyway for confirming I'm not crazy for being repulsed by these things. It often feels like I'm alone with these notions.

Yes. Welcome to Rust.

Well, this argument can also justify sticking to C and a sanitizer.

I'm still with @alper: macros are a pain to debug, hard on rust-analyzer, and terribly overused in the Rust ecosystem.

It would have been a nice retort if macros weren't used so heavility by Rust ecosystem and I was only the rare outlier who would have tried to use them to sidestep the limitations of Rust's trait system. But I'm a very good company: a lot of popular libraries use them… it's actually hard to find any that is both popular and doesn't use macros. Starting from std library and then following with serde, axum and bazillion other packages.

Maybe then some other althernative should exist? Templates or other form of compile-time reflection…

C++ declared the war on macros… haven't succeeded but added a lot of things that are supposed to make them less important… Rust continues to exist that world should bent to its ideal, instead… well — macroses would be used heavily as long as Rust would assert that…

Myself, I think that all of the following are true:

  • Macros are often over-used and under-documented.
  • Rust macros (both macro_rules! and procedural macros) are less than ideal in lots of ways and could be greatly improved — full hygiene (when desired, at least); better errors; better options for documenting and checking the usage of the macro. There's lots of ways in which what we have now is nearly minimum-viable level.
  • Rust would be worse off if it had no macros at all.

The available choices aren’t limited to “use the macros we have now” and “don't use macros”; there is also “work on making macros better” and “define macros sparingly and with care for their clarity and usability, and always provide non-macro APIs too”.

But also just added "reflection" in the sense of writing C++ code that emits more C++ code on build... as in "real" macros. There's a bunch of very over-excited talks about it (I can't wait for them to find out about all the tooling issues!)

Turns out, compile time codegen integrated into the language is just too useful, you're shooting yourself in the foot (or maybe cutting your nose to spite your face?) avoiding it in the pursuit of some pure ideal of only "real" code. But equally, if macros are "real" code, they should have the same standards of good design and documentation!

Nope. Reflection in C++26 is still behaves like a template, not like macros. It's just an extension of what C++11 already had. And the only one thing C++ added (but really critical thing, which is hard to substitute in C++98) are variadics.

When you write something like:

auto add_two(auto x, auto y) {
    if constexpr (
            std::is_same_v<decltype(x), const char*> &&
            std::is_same_v<decltype(y), const char*>) {
        return std::string(x) + " " + std::string(y);
    } else {
        return x + y;
    }
}

You are not accepting some random non-C++ input that is, then, transformed into valid C++. The whole things is still C++ with just some “unimportant things” (like types of variables) are not finalized. That's much easier to support in IDE, much easier to process in your head and so. And it was already there in C++11, even, in some sense, in C++98 (only there you couldn't have std::tuple, could only have Lisp-style std::pair<_, std::pair<_, std::pair<_>>>… theoretically the same thing as C++11 tuple, but with such an awful ergonomics that I would say that going below C++11 is not practical if you want to do some metraprogramming… C++17 was are a critical jump in productivity with introduction of if constexpr, but that, too, haven't turned templates into macros.

C++26 simply explaned it from std::tuple (that C++11 processes perfectly fine already) to structs, enums and so on.

You still deal with templates (in normal, human sense: document with some “fill the blanks” fields), not with arbitrary sequences of tokens.

No matter how much work you spend on macros their very nature makes it hard to do “trivial” things with them: show syntax highlighting, format them, offer “go to definition” option and so on.

And idea of having Zig-style comptime templates (that's what C++26 added, more or less) was rejected thus we are stuck with macros.

There are bazillion crates that try to emulate what C++ have with Any, but they, too, need to rely, very heavility, on macros… and need to hope that dead code elimination would remove all the unused code that may or may not actually happen.

Ofthen the whole thing of generating gigabytes of code and then throwing away gigabytes of code becomes so slow that macros are picked up instead of all that complexity.

It's not exactly rust macros, but it's pretty close: you can't accept arbitrary tokens (at least technically), but you can emit arbitrary syntax (at least as I understand it, I could be wrong!).

It seems pretty close to derive macros, maybe?

What do you mean by that? The fact that you can attach arbitrary string in quotes and then, later, process it? Technically you can do that in C++11 already (even processing is limited), but you couldn't just produce arbitrary sequence of tokens to be interpreted neither in C++11 nor in C++26.

It's slightly similar, yet very different: derive macros, essentially, accept “anything with balanced braces” and may have arbitrary syntax inside. C++ reflection clearly separates these “arbitrary pieces” — they may contain their own micro-language (like C++20 std::format does already) but putting everything in one sting is not how reflection is supposed to be used and it's not like it's used.

It's like in real world: you may say that a sheet of paper with just a string “letter” on top and large cut out rectangle where you may write your own text is still, technically, a template… but that's not how how templates are supposed to be used and that's not how they are used.

I'm not invested in this particular topic,[1] but as a drive-by note, there's a project goal to explore reflection/comptime in Rust. Though something that is useful for all that macros do is surely quite a long way off.

This proposal is solely for producing const eval values, not for putting types back into the type system.
That will be a follow-up once this proposal has a merged MVP.


  1. don't expect any replies ↩︎

At least some of those are solving problems that require macros, saving the user of the library from having to write the macros. So that may explain, in part, why so many libraries have macros.

Note that Zig comptime code defeats tooling just like macros do.

If this is going to defeat tooling as well, I'd rather the effort is spent improving the language instead. If it doesn't defeat tooling, that would really be something.

Sorry, just that it does have to be valid C++ syntax, but you don't have to interpret it as C++ would, so I'm assuming it's going to get abused in all sorts of "fun" ways.

Well… I prefer Java tricks to C/C++ macros, any day… even if some of these are, indeed, go too far, sure.

Most Java packages don't abuse reflection, though. Hopefully the same would be true for C++.

I have to admit, I love declarative macros for the wrong reason: they're a very fun puzzle to solve. All their quirks and shortcomings make for an intriguing challenge when trying to get it just right.

However, I realize those are bad things when it comes to writing code for production. Still, I think macros are indispensible to Rust, even if in need of a lot of love.

Those links are mostly if you want to write macros, but it's not mandatory.

Even if it's part of the language, you shouldn't have to deal with macros too often, and unless you're curious about how something works, you shouldn't have to reverse-engineer them. More often, they'll be macros of the standard library, which are well documented.

In the case you exposed, it's more a problem of documentation and maturity of the crate; you could have the same problem with any obscure method, trait, or type in "pure" Rust. So it's more a matter of finding the information or considering another approach. I see there's a Q&A, so that could be a way to ask how it exactly works (and maybe hint that something isn't entirely clear).

Macros should normally make the life of their users easier, not complicate it. :slight_smile:

Crystal's macros are pretty interesting in that they mostly look like normal functions operating on normal values. You can just do something like this, without the "code tetris" of TT munching and weird sigils.

for bits in [8, 16, 32, 64] {
    define_method("Foo::from_i{bits}“, ...)
}

Aren't those procedural macros? They're a little annoying to write since they need a separate crate and you need to bring your own parser, but it's not a particularly heavy burden.

That looks like the little procedural macro I did to implement a trait (or any generic implementation) for several types. :smiley:

#[trait_gen(T -> u8, u16, u32, u64, u128)]
impl MyLog for T {
    fn my_log2(self) -> u32 {
        T::BITS - 1 - self.leading_zeros()
    }
}

Thankfully, I did that more to learn and as a proof of concept than anything else, seeing how much it's used. :wink: But I think something like that implemented in the Rust language itself would make some of the standard library's code more understandable, rather than using declarative macros.

From what I see, the definition isn't clearer in Crystal than in Rust. It's still like a template language, where the variables are between {{ ... }} rather than being after a $. It looks actually very close to template languages used for building web pages, like Django and so on, so it's a little more powerful in some ways (e.g. you can create loops without the need to have it in the pattern) and less in other ways (no pattern matching).

It also look like a literal replacement rather than a token-based replacement, though I think each has its strong points and weaknesses.

macro define_constants(count)
  {% for i in (1..count) %}
    PI_{{i.id}} = Math::PI * {{i}}
  {% end %}
end

The instantiation doesn't look distinguishable enough, so there I prefer Rust's way to clearly indicate it's a macro, either procedural or declarative. The only ambiguity is between a declarative macro and a procedural "function-like" macro, which both look the same when instantiated, but there's no mistaking it's a macro, which is the important part.

how many times have I been lost when I was trying to find the definition of a method, only to find several layers of macros used to define methods on several types?

There is that. But it's also a severe shortcoming of "view source:" nothing is hyperlinked. If one could just click through to the macro (and function) definitions, it would become an order of magnitude more useful!

Btw. no need for any cargo tricks: at least in VS code there's a hidden "Rust macro expand" command. I've bound it to Ctrl-M and it's a life saver. But it only works on correct code. If the macro's input can't be matched, tough luck.

I'm not using VSCode. In RustRover, you can jump to the definition in a hyperlink way, but it's limited: sometimes, declarative macros within other declarative macros won't get contextual awareness, so you have to do a search. You can also expand it fully, so that might help, and it's handled by the IDE, so it's lighter and handier than expanding it through Cargo.

The support gets better with time, of course, but it's asking a lot of the IDE and the user who must understand how things like shl are actually implemented[1].


  1. You need to go through a few levels, which are in the same file. But you're ultimately stuck because of forward_ref_binop, which is defined elsewhere, and to find it, you need to check the top crate... good luck with that! ↩︎