466 points · by klaussilveira · 1y ago · 195 comments
Making Rust's macros easier is laudable. Purely from a user's perspective I find it especially annoying, that proc macros need their own crate, even if I understand the reasons for it. If I read Crabtime correctly it solves that problem, which is nice.
That being said Crabtime looks more like compile time eval on steroids to me than an analogon to Zig's comptime.
One (maybe the) distinguishing feature between comptime in Zig and Rust macros seems to me to be access to type information. In Zig you have it[1] in Rust you don't and that makes a big difference. It doesn't look like we will get that in Rust anytime soon and the projects that need it (e.g. cargo semver check) use dirty tricks (parsing RustDoc from the macro) to accomplish it. I did not see anything like that in Crabtime, but I might have missed it. At any rate, I'd expect compile time reflection for anything that claims to bring comptime to Rust.
[1] I think, but I am not a Zig expert, so please correct me if I am wrong.
There are other differences. First, comptime functions aren't syntactic macros. This makes them much easier to reason about and debug. You could think about them as if they were regular functions running at runtime in a partially-typed language with powerful reflection (their simplicity also means they're weaker than macros, but the point is that you can get very far with that, without taking on the difficulties associated with macros). Second, I think that comptime's uniqueness comes not from what it does in isolation, but that it makes other language features redundant, keeping the entire language simple. This means that with one simple yet just-powerful-enough feature you can do away with several other features.
The end result is that Zig is a very simple language with the expressivity of far more complicated languages. That on its own is not super unusual; in a way, JavaScript is like that, too. But Zig does it in a low-level language, and that's revolutionary. It is because of its simplicity that people compare Zig to C, but it's as expressive as C++ while also being safer than C++, let alone C.
Adding comptime to an already-complex language misses out on its greatest benefit.
I have considered a non backwards compatible JavaScript descendant to clean things up. It would be interesting to hear what you consider to be problems.
Can you give an example of something that's easier to reason about (e.g., an error that's easier to spot) with Zig's comptime than with macros?
> it makes other language features redundant
I'm guessing (so I might be wrong) that IDEs and users still need to be aware of the common idioms, so why does it matter whether or not those common idioms are implemented in the compiler or using comptime? (I'm not saying it doesn't matter, I'm wondering what benefits you have in mind.)
Rust proc_macros takes a stream of tokens and return a stream of tokens. If your macro meant to return an instance of a specific type, it must output the correct tokens which create that instance via existing interfaces. There's some really ugly indirection in trying to understand what's going on.
This is always harder to reason about than Zig's equivalent, because in Zig you just return the thing that you want to return.
You can read their definition, you can expand them, but there's no way to look at a macro call and reason about it, it can do anything at all. In C you don't even know what is and isn't a macro, so Rust has a modest edge in that respect.
Zig just doesn't have this problem to begin with.
The two things it adds on top, is the way nullability is handled at compile time, while the former do runtime null checks, and comptime.
True, but at least there are curly bracket languages heavily influenced by Pascal, such as Go, V (Vlang) (has comptime too and is debatably safer), Odin, etc...
Would you agree with my idea, or would you say I am missing something? Does Zig aleviate some of the problems I mentioned?
``` fn Vec(comptime T: anytype) {
return struct {
// ...
}
}```
IMO having a first class generic type parameter syntax is better but this demonstrates OP's point.
While it started as a hack on how to use templates back in C++98, it has gotten quite usable nowadays in C++23, and the compile time reflection will make it even better.
All without having another language to learn about, as it happens with Rust macros, with its variations, or reliance on 3rd party crates (syn).
They are still not an adequate substitute for Zig's comptime feature. For one and in a sense they are much more limited than comptime functions in Zig but for another (and for better or worse) they also have much higher aspirations than Zig.
const fn must always be able to be run at compile time or run time and always produce bit-identical results. This is much harder than it looks at first glance because it must also uphold in a cross-compiling scenario where the compile time environment can be vastly different from the run time environment.
This requirement also forbids any kind of side effect, so Rust const fn are essentially pure functions and I've heard them called like that.
You raised my hopes and dashed them quite expertly, sir. Bravo!
const std = @import("std");
const myType = struct {
const info = @typeInfo(myType);
const before = info.Struct.decls.len;
pub usingnamespace (if (before == 0) struct { pub fn baz() void {} } else struct {});
const after1 = info.Struct.decls.len;
const after2 = @typeInfo(myType).Struct.decls.len;
};
pub fn main() void {
std.debug.print("Hello, {} {} {}!\n", .{ myType.before, myType.after1, myType.after2 });
}hello: 4, 5, 5
I had previously written a declarative macro to generate benchmark functions [1]. It worked, but I didn't enjoy the process of getting it working. Nor did I feel confident about making changes to it.
When I rewrote it using crabtime I found the experience much better. I was mostly writing Rust code now, something I was familiar with. The code is much more readable and customisable [2]. For example, instead of having to pass in the names of the modules each time I added a new one, I simply read the files from disk at compile time.
To compare the two see what the code looks like in within the braces of paste!{} in the first one and crabtime::output!{} in the second one. The main difference is that I can construct the strings using Rust code and drop them in with a simple {{ str }}. With paste!, I don't know exactly what I did, but I kept messing around until it worked.
Or compare the two loops. In the first one we have `($($year:ident {$($day:ident),+ $(,)?}),+ $(,)?)` while with crabtime we have plain Rust code - `for (year, day) in years_and_days`. I find the latter more readable.
Overall I'm quite pleased with crabtime. Earlier I'd avoid Rust metaprogramming as much as possible, but now I'd be open to writing a macro if the situation called for it.
[1] - https://github.com/nindalf/advent/blob/13ff13/benches/benche...
[2] - https://github.com/nindalf/advent/blob/b72b98/benches/benche...
> We would like to extend our heartfelt gratitude to the following individuals for their valuable contributions to this project:
> timonv – For discovering and suggesting the brilliant name for this crate. Read more about it here (https://www.reddit.com/r/rust/comments/1j42fgi/comment/mg6pw...).
> Polanas – For their invaluable assistance with testing, design, and insightful feedback that greatly improved the project.
> Your support and contributions have played a vital role in making this crate better—thank you!
That said I did replace a declarative macro with it. Supposedly I wrote the declarative macro according to git blame but I only have a vague idea how it works. I replaced it with crabtime and I got something that I can understand and maintain.
Overall I’d say I’m very pleased with crabtime. Previously I would have avoided Rust metaprogramming as much as possible, but now I’d feel confident to use it where appropriate.
Rust can't have Zig's comptime dynamic properties, same way Zig will never have Rust's compile time guarantees*.
You can't simultaneously have your dynamic cake and eat it at compile time.
* Theoretically you can have it, but it would require changing language to such extent it's not recognizable.
This looks worth the playing with and see if they can solve my issue, one thing I avoid as much as possible is to add unnecessary dependencies, didn’t check how many dependencies this will add overall to the project.
[1] https://crates.io/crates/crabtime-internal/1.1.1/dependencie...
I do share the sentiment - and complain about this frequently - but any environment with build scripts can wreck your computer. Encrypt what you can, I guess, but software engineering is an extremely dangerous job wrt security.
I think using something like the pledge syscall from OpenBSD in the compiler could be useful. That way, it's controlled at the process level which things can be accessed on the system.
But thank you for letting me learn something useful.
But go off, king.
So, I'm interested in some metaprogramming right now. I'm setting up Vec3 SIMD types, and it requires a lot of repetition to manage the various variants: f32::Vec3x8, f64::Vec3x16 etc that are all similar internally. This could be handled using traditional macros, procedural macros, or something called "code gen", which I think is string manipulation of code. Could I use crabtime to do this instead? Should I?
> This could be handled using traditional macros, procedural macros, or something called "code gen", which I think is string manipulation of code. Could I use crabtime to do this instead? Should I?
You could, it seems. Crabtime supports both the procedural macros and "code gen" approaches you are talking about.
.user {
&--profile { color: red; }
}
Now, searching for "user--profile" CSS class becomes imposible. Despite this, SASS and similar preprocessor seem to be popular and used almost everywhere. Well, I never had high expectations of front-end developers, so I am not very disappointed.So I think as long as you don't break identifiers, the code should be searchable. But, your IDE will probably not able to help you with auto-complete and navigation.
Yes, that's also a problem. As is MySQLCursorDict Class. Now you have to grep every column name every table your code base accesses.
Does this basically allow us to write normal rust code instead of procmacros, with even fewer constraints?
Learn Haskell, Idris, ATS, etc and you will soon find it baffling how easy it is to impress OOP/Imperative programmers and how little they demand of their languages.