How Our Rust-to-Zig Rewrite Is Going
5 hours ago
- #Roc
- #Zig
- #Compiler
- The Roc compiler team has rewritten 300,000 lines of Rust code into Zig, recently achieving feature parity with the original compiler.
- Key new features in the Zig-based compiler include hot code loading during development, cross-compiled binaries, and type-safe string interpolation in pattern matching with zero heap allocations.
- The rewrite was motivated by architectural challenges, especially in implementing polymorphic defunctionalization, which required a scratch rewrite rather than incremental changes.
- Zig was chosen over Rust due to faster build times, better memory control with granular allocators, ecosystem relevance for compiler needs, and more assistance with memory-unsafe code.
- Memory safety comparison shows fewer memory corruption bug reports in the Zig compiler (10) vs. Rust (21), though most were miscompilations, not compiler itself issues.
- Build times are significantly faster with Zig's incremental builds (35ms) compared to Rust's (3.4s), despite a current stable release bug delaying full benefits.
- The compiler uses zero-parse deserialization for caching, leveraging array-based data structures for I/O-bound performance, enabled by Zig's memory control.
- Zig's ecosystem, including its compiler code, provided reusable components like an LLVM bitcode serializer, aligning with Roc's unusual needs.
- Missing aspects from Rust include automatic allocation in tests, private struct fields, and better dead code detection, but Zig offers benefits like control over data layouts and error handling.
- Next steps include releasing Roc version 0.1.0 later this year, with ongoing work on documentation and bug fixes, supported by the nonprofit Roc Programming Language Foundation.