4 ms·
Not necessarily. The cleanest version of this sort of thing I’ve seen is zig’s comptime. Basically you can annotate loops, conditionals, function parameters, et
by josephg 6y ago
Not necessarily. The cleanest version of this sort of thing I’ve seen is zig’s comptime. Basically you can annotate loops, conditionals, function parameters, etc to be evaluated at compile time instead of runtime. You’re still writing zig - it’s the same language; just some of your code runs in the context of the compiler.
One really nice use of this is printf. In C, printf needs a remarkably large amount of code and it’s quite slow. In zig, printf marks the format string as comptime. Then the compiler runs the code looping over and evaluating the format string, then unrolls the result into the binary. The output ends up being a few terse calls to write / format with no extra machinery at runtime. And you get clean compile errors if the format string doesn’t match your arguments - all with no special casing in the compiler.
More detail, with code: https://ziglang.org/documentation/master/#Case-Study-printf-in-Zig https://ziglang.org/documentation/master/#Case-Study-printf-...
I think nim has something similar.
I’m surprised rust went with macros instead of something like comptime - though I assume there’s some trade offs I’m not aware of.
- akiselev 6y ago> I’m surprised rust went with macros instead of something like comptime - though I assume there’s some trade offs I’m not aware of. Rust has procedural macros which are Rust libraries built and run compile time that can transform raw tokens into valid Rust code (or more raw tokens for nested macros). Procedural macros can annotate any statement or code block - although some specific ones might still be on nightly only.
- _nhynes 6y agocrate-level inner attribute macros are still unsupported [0], so if you want those, you'll need to do the codegen before the compiler takes a pass or from within the compiler itself (using, say an after_parsing [1] hook). They're really helpful for making a deeply embedded DSL. [0] https://github.com/rust-lang/rust/issues/54726 https://github.com/rust-lang/rust/issues/54726 [1] https://doc.rust-lang.org/nightly/nightly-rustc/rustc_driver/trait.Callbacks.html#method.after_parsing https://doc.rust-lang.org/nightly/nightly-rustc/rustc_driver...
- smabie 6y agoWhat's the difference between comptime and macros? they seem pretty much the same at first glance.
- gpderetta 6y agoMacros normally are a separate phase of compilation, separate, for example from type checking.
- renox 6y agoI agree with you that Zig comptime seems really nice. As for the format string at comptime, it's a big improvement over C sure (no missing parameter, yes!) but I still feel that it's still much less readable than Python f-strings.