4 ms·
C/C++ macros are particularly horrible as they are essentially text replacement on the source code. Other languages (such as Rust) have macro systems which work
by nicoburns 8y ago
C/C++ macros are particularly horrible as they are essentially text replacement on the source code. Other languages (such as Rust) have macro systems which work with ASTs and can used in isolation without interfering with other stuff.
For example there's a library in Rust which provides a `json` macro with syntax like so:
json!({
"foo": "bar",
"qux": baz
});
where `baz` can be a Rust string or integer. Note: this will typecheck, so if you provide something weird as `baz` then it won't compile, but otherwise the syntax is identical to standard JSON syantax.
- ujal 8y agoWhats the canonical way to deduce the types in Rust from JSON? JSON Schemas?
- pohl 8y agoThis particular crate, serde_json, lets you create any type that implements Serde's Deserialize trait when you're parsing.
- steveklabnik 8y ago... and it also provides a dynamic interface too, if you need to work that way. You probably don’t...
- xfer 8y agoThat still doesn't address the issue of macro syntax being foreign/not easy to refactor. See the nom library for an example.
- monocasa 8y agoRust procedural macros are just regular rust that runs at compile time. You get vector of tokens in, and return a new vector of tokens out.
- xfer 8y agoAnd how does that address this issue?
- steveklabnik 8y agoProcedural macros and macros are different things; nom is the “normal” macros (“macros by example”). The initial procedural macro release is in 6.5 weeks. Nom has worked on stable for years.
- xfer 8y agoI know procedural macros are different in how they work and more flexible, but the problem remains the same: you can't really look at any macro definition and go i know how to use this. A vector of tokens is not the syntax a programmer can parse without the grammar definition that the macro implements. It's still foreign unless it is well-written to match existing language constructs.
- steveklabnik 8y agoSure; to be clear, I'm trying to point out what I think your parent is getting at. I don't necessarily agree.
- monocasa 8y agoOh, I thought you were talking about the issues as a macro writer. Now that I reread it, I think you're talking about as a macro consumer. Is that right?
- nicoburns 8y agoThat's a good point. The nom library definitely does exhibit a lot of the problems described above. There's definitely a ton of macros in the rust ecosystem that don't though.