3 ms·
Rust has three main forms of metaprogramming: generics, which are kind of like templates, but more like concepts (in C++ terms), macros, and compiler plugins.
by steveklabnik 10y ago
Rust has three main forms of metaprogramming: generics, which are kind of like templates, but more like concepts (in C++ terms), macros, and compiler plugins.
- baq 10y agoworth noting that Rust generics aren't (by design!) as powerful as C++ templates. macros and compiler plugins OTOH...
- cesarb 10y agoI don't think compiler plugins count yet, since they're currently not stable.
- steveklabnik 10y agoThat's an important point, yes, thank you. Their RFC was accepted two weeks ago. We'll see how long they take to make it into stable.
- nurettin 10y agoWait, Rust has macros that expand to code and mess up debugging, confuse tooling and everything else just like C++? Isn't that exactly what the language should have avoided?
- carry_bit 10y agoMacros in Rust are very different than macros in C++. They're similar to syntax-rules in Scheme: https://doc.rust-lang.org/book/macros.html https://doc.rust-lang.org/book/macros.html
- steveklabnik 10y agoThey do expand to code. They shouldn't mess up debugging or confuse tooling. They're much more similar to Lisp-style macros than the C preprocessor.
- nurettin 10y agoOh, ok, the word macro is heavily overloaded and it seems I misinterpreted the Rust use of macros. But oh boy it costs lots of rep to ask a question.
- kibwen 10y agoTrust me, every C and Lisp programmer in the world is upset that both languages use "macro" to mean such wildly different things. :)
- white-flame 10y agoC++ macros don't expand to actual semantic "code", in terms of an AST or even lexed terms. It blindly expand spans of textual characters, which I agree no post-C language should ever do again. Languages as old as Lisp do AST-level macro expansion, with the actual programming language itself computing the expansion. Any code template blocks in the macro body are processed and validated in the native syntax of the language so that nesting and such aren't mungable.
- kazinator 10y agoC and C++ macros are worse than textual. They work with abstract token sequences. This, per se, is not inherently worse, except that, oops: undefined behavior is worked into the spec. For instance, if you have a macro argument X which holds the ( token and another one Y which holds 123, and you paste these together using X ## Y, you get undefined behavior: two tokens are pasted to form something which is not a single, valid token. A purely textual preprocessor wouldn't have an UB issue of this type.