Devlog ⚡ Zig Programming Language
This page contains a curated list of recent changes to main branch Zig.
This page contains entries for the year 2026. Other years are available in the Devlog archive page.
October 24, 2026
Partial Operator Precedence
Author: Ryan Liptak
As of yesterday, the second oldest open proposal for the Zig language was issue #114: require parentheses sometimes to disambiguate confusing operator precedence, opened February 8, 2016. Ten years later, that proposal has been implemented in the master branch version of Zig thanks to contributor CMDRZero.
This means that some combinations of operators no longer have a defined precedence, and for those that don’t, the compiler will now require parentheses:
``` const a = x orelse y == z; ```
``` test.zig:1:22: error: ambiguous operator precedence with operators ... orelse ... == ...; use parentheses to disambiguate const a = x orelse y == z; ^~ test.zig:1:13: note: previous ambiguous operator here const a = x orelse y == z; ^~~~~~ test.zig:1:22: note: in zig 0.17.x, this was evaluated as (... orelse ...) == ... ```
However, common cases can remain parenthesis-free:
``` const a = x + y * z; ```
The idea behind this is to reduce the number of rules a programmer needs to know when reading and writing Zig code. For example, no matter how experienced you are with Zig, it’s unlikely that you’d be able to explain the evaluation order of the following expression without looking up the precedence rules:
``` a & b + c * d >> e | f orelse g() catch h + i == j or k and l ```
With the now-required parentheses added (while maintaining the same evaluation order as the Zig 0.17.x precedence rules), that expression would look like this:
``` ((((a & ((b + c * d) >> e)) | f) orelse g()) catch (h + i)) == j or (k and l); ```
Still quite hairy, and not something I’d like to see in the wild, but nonetheless it’s understandable without knowing any precedence rules beyond arithmetic and comparison. Outside of this contrived example, though, the expressions that will now require parentheses are relatively rare (353 lines needed changes out of the million+ lines of code in the Zig codebase).
What you need to know
In practice, going forward, you will only need to remember the rules around operator combinations that _still have_ a defined/unambiguous precedence. For example, when reading or writing code involving arithmetic operators, you’ll only need to remember the following precedence table:
```
- / *% *| %
+ - +% -% +| -| == != < > <= >= and or ```
You might notice that there isn’t anything too surprising there, and that lack of surprise was a (subjective) guiding principle for what should and should not require parentheses. As an example, while `%` has unambiguous precedence with regards to addition/subtraction operators, parentheses must be used when mixing `%` with multiplication/division operators, and with itself. However, this, and other ambiguous operator combinations, aren’t something you’ll need to commit to memory. Any (future) code you read will already have parentheses to disambiguate, and for any code you write, the compiler will let you know when you need parentheses.
For the full explanation, and to see the relevant precedence tables pertaining to other operators, see the updated Precedence section of the language reference.
Upgrading existing code
There are two possible approaches here:
1. Manually fix each “ambiguous operator precedence” error as they are surfaced by the compiler (this might be a good opportunity to try out incremental compilation if it’s supported on your platform)
2. Use `zig fmt --upgrade` (the `--upgrade` flag was added for this purpose). This will cause `zig fmt` to add parentheses automatically, maintaining the evaluation order from the previous precedence rules (note: the `--upgrade` flag will be removed after one release cycle)
My personal recommendation would be option 1, as the process of redetermining the intended evaluation order for these uncommon precedence scenarios can occasionally serve to uncover bugs (here’s an example of that).
If you go with option 2, I’d still recommend perusing the diff afterwards to ensure that nothing looks unusual, or is different than you expected/intended. A potentially common example of that is something like `a orelse b() catch c` which previously evaluated to `(a orelse b()) catch c`, but changing that to `a orelse (b() catch c)` likely makes more sense, even if the end result is unaffected. Also worth noting that in some scenarios, redundant parentheses will be added by `zig fmt --upgrade` (e.g. you might see something like `a orelse ((b + c) - d)` where the parentheses around `b + c` are unnecessary), so avoiding that will take a bit of manual cleanup.
That’s about it. I’m hopeful that this change will make bugs stemming from misremembered precedence rules much less likely, and that it will put some attention onto any of those bugs that may currently exist.
Thanks again to CMDRZero for the implementation, and to Isaac Freund for help with the corresponding grammar changes.
October 20, 2026
Naked Package Metadata
Naked packages are ones that do not include a build manifest (build.zig.zon file). This is typically due to them being maintained by third parties outside the Zig ecosystem.
Until now, those package hashes looked like: `N-V-__8AAA7lSAA6p7eRmPGVeA9uHmeiJ2DX-ISiPliRJ8Y7`
This is because, without a build.zig.zon file, there was no `name` and `version` to use in the package hash. Furthermore, those packages have brittle hashes because they included all fetched files without any filter, which may accidentally have included unwanted hidden files that nonetheless cause the package hash to change. Or, the package might have contained symlinks that cannot be created on a particular OS. Without a filter, such files, even if they were unneeded, caused fetching to fail.
Now, Zig supports specifying `version` and `paths` for naked packages next to the URL. The dependency name will also be factored into the package hash, but **only when `version` is provided.** This allows users to opt in, as opposed to having the package hash change suddenly when updating Zig.
Here’s an updated zlib for example:
``` .dependencies = .{ .zlib = .{ .url = "https://github.com/madler/zlib/archive/refs/tags/v1.3.2.tar.gz", .hash = "zlib-1.3.2-__8AANXpEADvBXGMSfhczMTZVAA-TkkE4ecoohAR7s3p", .version = "1.3.2", .paths = .{ "LICENSE", "adler32.c", "compress.c", "crc32.c", "crc32.h", "deflate.c", "deflate.h", "gzclose.c", "gzguts.h", "gzlib.c", "gzread.c", "gzwrite.c", "infback.c", "inffast.c", "inffast.h", "inffixed.h", "inflate.c", "inflate.h", "inftrees.c", "inftrees.h", "trees.c", "trees.h", "uncompr.c", "zconf.h", "zlib.h", "zutil.c", "zutil.h", }, }, }, ```
Before:
``` 4.3M zig-pkg/N-V-__8AAI4ANwDM8MWhHTUFLKfvLE_n2NQk6mh0sFDzhTqO ```
After:
``` 1.2M zig-pkg/zlib-1.3.2-__8AANXpEADvBXGMSfhczMTZVAA-TkkE4ecoohAR7s3p ```
October 14, 2026
Package Hash Consistency Validation
Any time the same package (based on `fingerprint`) appears in the dependency tree, if the semantic version compares equal, the hash must be identical, otherwise one of three things has gone wrong and the maintainer must address it:
- package ownership dispute: somebody forked someone else’s package without changing the name or fingerprint, or
- package maintainer neglected to bump version after making changes, or
- dependency on unreleased changes
When this error occurs, the project maintainer should take care to understand _why_ those two (or more) packages have contradictory hash information before deciding what to do.
Example:
``` andy@bark ~/d/ffmpeg (main)> zig build error: contradictory hash for package with fingerprint 0x7118c1b07efea3d0 and version 0.0.0: libogg-0.0.0+1.3.7-0KP-flwMAACKAIH-iEs4gbg30ll_FQ-cW50JvLZO8VTg error: contradictory hash for package with fingerprint 0x7118c1b07efea3d0 and version 0.0.0: libogg-0.0.0+1.3.7-0KP-foYNAAAaj0YJOwRQs7kTN-ivzRMYTjtKzr6Apelj info: potential cause: package ownership dispute info: potential cause: maintainer neglected to bump version after making changes info: potential cause: dependency on unreleased changes info: hint: use --print-tree to visualize all package versions and hashes ```
October 13, 2026
Printing Package Tree
There is a new `--print-tree` CLI option to `zig build`, that looks like this:
``` andy@bark ~/d/groovebasin (main)> zig build --print-tree ffmpeg ffmpeg-8.1.1-5-zT7QA_AkUgTOx4ZqOUVZsHSk9iv97BInIiubIM6ifr67 ├─ libz zlib-1.3.1-1-ZZQ7ldENAAA7qJjUXP6E6xnRuV-jDL9dyoJFc_eb3zQ6 │ └─ zlib N-V-__8AAB0eQwD-0MdOEBmz7intriBReIsIDNlukNVoNu6o ├─ mbedtls mbedtls-3.6.4-E4NUR2wWAAAUSvVbho9aaU31-e4D8glu9l1VfxKezBkV (not fetched) ├─ openssl openssl-3.3.2-TC9C3Ze3ZABaKR5hc8KRnRPhTClKrKQKqTnXTUYkvmSR (not fetched) ├─ libressl libressl-4.0.0--kqV4KPTAACsSRP8mSIZmqgVa5OZjw6WEgvcftWkLu-c (not fetched) ├─ libmp3lame libmp3lame-3.100.1-7-67wlF2CxEwDWlVOMMLBNPbnDi5kE2OmH0azUHU2Y4DZY ├─ libvorbis libvorbis-0.0.0+1.3.7-1wt9j_QPAADVure94TG4ecBMLD8eIAzWd6ZxVOmBBPCu │ ├─ libvorbis N-V-__8AAA7lSAA6p7eRmPGVeA9uHmeiJ2DX-ISiPliRJ8Y7 │ └─ libogg libogg-0.0.0+1.3.7-0KP-foYNAAAaj0YJOwRQs7kTN-ivzRMYTjtKzr6Apelj │ └─ libogg N-V-__8AAFM3CwD6iAA1kggMPR8NHZ8VTb2zvRZ1Mt4BUfq9 ├─ libogg libogg-0.0.0+1.3.7-0KP-foYNAAAaj0YJOwRQs7kTN-ivzRMYTjtKzr6Apelj │ └─ libogg N-V-__8AAFM3CwD6iAA1kggMPR8NHZ8VTb2zvRZ1Mt4BUfq9 └─ nasm nasm-3.0.1-B_NnpQpTAAA25UxvqONakXtmj-a78PGe3xfgyDFgetb0 ├─ nasm N-V-__8AAEAMKAFrNesgN6ZM9sxj37fq_i7UJe5nKkLmyRJI └─ zlib zlib-1.3.1-1-ZZQ7ldENAAA7qJjUXP6E6xnRuV-jDL9dyoJFc_eb3zQ6 └─ zlib N-V-__8AAB0eQwD-0MdOEBmz7intriBReIsIDNlukNVoNu6o pulseaudio pulseaudio-16.1.1-10-mk_62DNlNwCDcTJ5iGhTxeCoetuAFKE1FrYNw5AErtX- StaticHttpFileServer StaticHttpFileServer-1.0.0-j-0gwes2AAByCgpeLBNR2hOaGVsDz9u8I6o54ft10OxU └─ mime mime-4.0.0-zwmL--0gAACndOVlROQeDnM0chfojNDS8tpohlsBqMNy ```
If a terminal is detected, it prints in color, which is a bit easier to read.
This **early exits before running configurer**, so that problems causing configurer compilation errors can be troubleshooted.
Similarly, `--configure` is added, which is defined to “exit after the configuration phase” which is the exact behavior that `--fetch` used to do. `--fetch` is changed to “Fetch all dependencies including lazy ones; exit without configuration”.
October 12, 2026
More Resilient Help Menu
`zig build --help` now works even when configuration fails, or when there is no build.zig file:
``` info: initialize build.zig template file with "zig init" info: see "zig --help" for more options error: no build.zig file found, in the current directory or any parent directories Usage: zig build [steps] [options]
Steps: (unavailable due to build.zig compilation failure) Project-Specific Options: (unavailable due to build.zig compilation failure)
System Integration Options: --search-prefix [path] Add a path to look for binaries, libraries, headers --sysroot [path] Set the system root directory (usually /) ... Available System Integrations: Enabled:
(unavailable due to build.zig compilation failure)
General Options: -h, --help Print this help to stdout and exit -l, --list-steps Print available steps to stdout and exit ... ```
August 27, 2026
Pointer Stability for ArrayLists
Author: Robbie Lyman
Pointer Stability Locks were added to `std`’s Hash Map containers in 2024. A pull request initially opened by Leo Emar-Kar in 2025 now brings this technique for ensuring memory safety to `std.ArrayList`.
To make use of this in your code, add a call to `lockPointers()` when you first store a pointer to an element or a slice of elements backed by the `ArrayList`, and call `unlockPointers()` when those pointers are no longer needed.
Here’s a somewhat contrived example. Let’s suppose we are managing two `ArrayLists`, say one of which is holding in memory the contents of some input, while the other is storing chunks of interest; maybe each line. Here’s a version of this process which has a bug; see if you can spot it.
``` const std = @import("std");
const Context = struct { history: std.ArrayList(u8), lines: std.ArrayList([]const u8),
fn parse(ctx: *Context, allocator: std.mem.Allocator, input: []const u8) !void { const slice = try ctx.history.addManyAsSlice(allocator, input.len); @memcpy(slice, input); var it = std.mem.tokenizeScalar(u8, slice, '\n'); while (it.next()) |line| { try ctx.lines.append(allocator, line); } } }; ```
Did you spot the bug? The problem is that elements of `Context.lines.items` depend on the _location_ of `Context.history.items`, but this location may _change_ if `Context.history` needs to grow beyond its current capacity. Here’s a reproduction of the bug:
``` test "Context.parse" { const input = "I'm first!\n"; const input_two = \\But this text \\is juuuuuuuuuuuuuuuuuuuuuuuuust long enough that it \\causes a problem! \\And the problem could be that we segfault! \\Which is no fun to run into. ; var ctx: Context = .{ .history = .empty, .lines = .empty, }; const gpa = std.testing.allocator; defer ctx.history.deinit(gpa); defer ctx.lines.deinit(gpa); try ctx.parse(gpa, input); try ctx.parse(gpa, input_two); try std.testing.expectEqualStrings("I'm first!", ctx.lines.items[0]); } ```
If I run this code with `zig test`, I get the following output (plus a little more).
``` ====== expected this output: ========= I'm first!␃
======== instead found this: ========= UUUUUUUUUU␃
====================================== First difference occurs on line 1: expected: I'm first! ^ ('\x49') found: UUUUUUUUUU ^ ('\x55') 1/1 blah.test.Context.parse...FAIL (TestExpectedEqual) ```
Not great, right? This does tell us that we _have_ a bug, but depending on your comfort debugging memory issues (and your choice of allocator, which will change how the bug manifests!), you might be lost for quite a while before you spot the fix.
Since we’ve stored pointers after the first call to `parse` in our test, what happens if we make this change?
``` try ctx.parse(gpa, input); + ctx.history.lockPointers(); + defer ctx.history.unlockPointers(); try ctx.parse(gpa, input_two); try std.testing.expectEqualStrings("I'm first!", ctx.lines.items[0]); ```
We get a panic with a stack trace that shows us where our assumption about pointer stability was violated!
``` thread 3023222 panic: reached unreachable code /Users/robbie/bin/lib/std/debug.zig:442:14: 0x102d2506f in assert (test) if (!ok) unreachable; // assertion failure ^ /Users/robbie/bin/lib/std/debug.zig:1880:15: 0x102d31ef7 in assertUnlocked (test) assert(l.state == .unlocked); ^ /Users/robbie/bin/lib/std/array_list.zig:1348:50: 0x102e3ced7 in ensureTotalCapacityPrecise (test) self.pointer_stability.assertUnlocked(); ^ /Users/robbie/bin/lib/std/array_list.zig:1341:51: 0x102e3cdff in ensureTotalCapacity (test) return self.ensureTotalCapacityPrecise(gpa, growCapacity(new_capacity)); ^ /Users/robbie/bin/lib/std/array_list.zig:1237:41: 0x102e4e5c3 in resize (test) try self.ensureTotalCapacity(gpa, new_len); ^ /Users/robbie/bin/lib/std/array_list.zig:1461:28: 0x102e4e40f in addManyAsSlice (test) try self.resize(gpa, try addOrOom(self.items.len, n)); ^ /Users/robbie/src/advent-of-code/2024/blah.zig:8:51: 0x102e4dc1f in parse (test) const ptr = try ctx.history.addManyAsSlice(allocator, input.len); ^ /Users/robbie/src/advent-of-code/2024/blah.zig:35:18: 0x102e4e167 in test.Context.parse (test) try ctx.parse(gpa, input_two); ```
Nice, that’s already a big help: now I can see that I should consider memory safety issues as a probable cause of my test failure in addition or instead of a logic issue. Obviously this example was somewhat contrived, but I do find myself reaching for `std.ArrayList` as this type of backing storage in real code, so I hope you can see real-world use cases for it yourself.
Before I close, I want to point out something subtle: unlike `HashMap` and its friends, `ArrayList` is _ordered,_ which means that operations on the list may move elements around even without moving, resizing or freeing the backing memory of the list as a whole. For example, the pointer (well, slice) returned by `addManyAsSlice(gpa, n)` may not point to the final `n` elements of the list if you call `orderedRemove()` or `pop()`. For this reason, although `orderedRemove()` and `pop()` never allocate, they _will_ trigger the same assertion above after a call to `lockPointers()`.
June 30, 2026
All Package Management Functionality Moved from Compiler to Build System
Author: Andrew Kelley
Now that there is a separate process for users’ build.zig scripts and the build system itself, it makes sense for that to be the place that package management logic lives.
I moved these subcommands to the maker process:
- `zig build`
- `zig fetch`
- `zig init`
- `zig libc`
This means that large parts of what used to be included in the compiler executable are now shipped in source form instead, including:
- package fetching logic
- HTTP client and networking
- TLS (Transport Layer Security) and associated crypto
- Git protocol
- xz, gzip, zstd, flate, zip
- parsing, validation, and otherwise dealing with `build.zig.zon` files
Consequently, this functionality can now be patched without rebuilding the compiler, making it easier for users and contributors to tinker.
Furthermore, it means that package management in zig now has safety checks enabled when doing networking, since the maker executable is compiled in `ReleaseSafe` mode. Plus, all the crypto used for networking and file hashing can now take advantage of special CPU instructions available on the host, even the ones that are too rare to normally depend on when distributing software. _We can have AOT cake and eat JIT, too!_
My original motivation for doing this was in relation to exposing a build server protocol in order to unblock ZLS after maker/configurer process separation made breaking changes to the `--build-runner` override flag.
Originally, the process tree looked like this:
``` zig build (the zig compiler + package manager) └─ builder (the user's build.zig logic + build system implementation) ```
The process separation changeset made it look like this instead:
``` zig build (the zig compiler + package manager) ├─ configurer (the user's build.zig logic) └─ maker (build system) ```
At this point, consider a long-running `zig build --watch` process, watching files and rebuilding on source code changes. If any changes to `build.zig` are detected, or any files observed during execution of that logic, it means `configurer` needs to be rerun, meaning that `maker` process must exit to give `zig build` a chance to repeat the package management logic.
Now, after the changes described in this devlog entry, it looks like this:
``` zig build (the zig compiler) └─ maker (build system + package manager) └─ configurer (the user's build.zig logic) ```
Thus, when configuration needs to be rerun, `maker` process can continue to live because it is the parent process rather than a sibling. In terms of the upcoming build server, it means avoiding an awkward situation where the server has to exit and the client has to reconnect, rather than simply informing the client of a configuration change.
This is almost entirely a non-breaking change, but there are some observable differences:
- Zig executable binary size: shrinks 4% from 14.1 to 13.5 MiB (no LLVM, ReleaseSmall)
- `--maker-opt` flag is replaced by `ZIG_DEBUG_MAKER` environment variable
- `--zig-lib-dir` flag is replaced by `ZIG_LIB_DIR` environment variable
The follow-up issues to this changeset are the main blockers until we tag Zig 0.17.0:
- build server protocol MVP (needed to unblock ZLS)
- introduce the concept of adding path dependencies of the build script itself
- make `zig build --watch` detect modifications to the build script and rerun itself
- different cwd causes build script cache miss
I have two conferences coming up in July and I need to work on my talks, so being realistic, I don’t think I will have time to wrap these up until early August. Contributions welcome, of course.
Big thanks to Techatrix from the ZLS team for reaching out and working with me on the build server protocol! They are seeking sponsorship, by the way.
June 26, 2026
SPIR-V Backend Progress
Author: Ali Cheraghi
There’s quite a bit to cover. The SPIR-V backend had bitrotted in a number of places after the recent compiler changes, so I spent the past several weeks dragging it into a better state.
@SpirvType
SPIR-V has a handful of types that couldn’t be expressed in Zig’s type system. The new `@SpirvType` builtin has been introduced to address the longest-standing blocker for writing shaders. See #20550, #23326 and #35461 to trace the background.
``` const Sampler = @SpirvType(.sampler); const Image = @SpirvType(.{ .image = .{ .usage = .{ .sampled = u32 }, .format = .unknown, .dim = .@"2d", .depth = .unknown, .arrayed = false, .multisampled = false, .access = .unknown, } }); const SampledImage = @SpirvType(.{ .sampled_image = Image }); const RuntimeArray = @SpirvType(.{ .runtime_array = u32 }); const sampled_image = @extern(*addrspace(.constant) const SampledImage, .{ .name = "sampled_image", .decoration = .{ .descriptor = .{ .set = 0, .binding = 1 } }, }); ```
Execution Mode on the Calling Convention
Execution mode info (workgroup size, fragment origin, etc.) is now carried by the calling convention instead of being emitted via inline assembly `OpExecutionMode`. The old `std.gpu.executionMode()` helper is gone, and the SPIR-V assembler now rejects manual `OpExecutionMode` instructions. Two new calling conventions, `spirv_task` and `spirv_mesh`, were also added for mesh shading pipelines.
``` export fn vert() callconv(.spirv_vertex) void {} export fn frag() callconv(.{ .spirv_fragment = .{ .depth_assumption = .greater } }) void {} export fn comp() callconv(.{ .spirv_kernel = .{ .x = 8, .y = 8, .z = 1 } }) void {} export fn task() callconv(.{ .spirv_task = .{ .x = 1, .y = 1, .z = 1 } }) void {} export fn mesh() callconv(.{ .spirv_mesh = .{ .stage_output = .output_lines, .max_primitives = 1, .max_vertices = 2 } }) void {} ```
Capabilities and Extensions from CPU Features
Capabilities and extensions used to be emitted ad hoc by codegen or via inline assembly. They’re now driven entirely by the CPU feature set like other targets, with dependency chains extracted from SPIRV-Headers (excluding external vendors for now), and the assembler now rejects any attempt to emit `OpCapability` or `OpExtension` directly.
Multi-Threaded Codegen
From day one, the SPIR-V backend ran codegen single-threaded inside the linker thread. Each codegen job now produces an `Mir` value just like every other self-hosted backend, and gets scheduled on the compiler’s thread pool.
The same change brought back two ISel passes that had been removed during earlier refactors: `dedup_types` (which merges equivalent type instructions) and `prune_unused` (which strips dead code from the final module). These had originally been deleted back when codegen was single-threaded.
Object File Linking
`.spv` files are now recognised as object files. You can compile multiple `.zig` files (or external `.spv` objects) and have the SPIR-V linker stitch them into a single module.
Tens of bugs have also been fixed along the way with a nearly 10% increase in total passing behavior tests (49% now) on the `spirv64-vulkan` target, `std.gpu` was renamed to `std.spirv` and the SPIR-V backend is meaningfully more useful than it was a month ago, but there’s still a long way to go. Plenty of behavior tests remain skipped on SPIR-V. That said, if you’ve been on the fence about trying Zig for shaders or compute kernels, this is a good time to give it a shot. Bug reports are very welcome on Codeberg. Happy hacking!
June 25, 2026
New @bitCast Semantics and LLVM Backend Improvements
Author: Matthew Lugg
(Quite long devlog coming up, apologies—I got a little carried away with this one!)
A few weeks ago, I began working on a branch implementing an improvement to the LLVM backend which had been planned for a long time. This ended up snowballing into a bigger change which implemented a few language proposals you might be interested to hear about.
LLVM Backend Integer Lowering
Zig has always lowered arbitrary bit-width integer types (e.g. `u4`, `i13`, `u40`) directly to LLVM IR’s bit-int types (`i4`, `i13`, `i40`). However, we’ve known for a long time that this lowering is not optimal, because LLVM’s documented semantics for representing these types in memory are unnecessarily restrictive to the optimizer. Perhaps more importantly, because Clang never emits LLVM IR like this, these code paths in LLVM have never been properly tested, and so are poorly supported in practice—over the past few years, we have observed many instances of trivial optimizations being missed and even straight-up miscompilations.
So, the original goal of the PR was to only use these bit-int types when manipulating values in SSA form, and to zero- or sign-extend them to ABI-sized types (`i8`, `i16`, `i32`, etc) when storing them in memory. This should be well-supported, not least because it matches how Clang lowers C’s `_BitInt(N)`!
That change was actually fairly straightforward, but I hit one issue which led me down a bit of a rabbit-hole.
The Problem with `@bitCast`
`@bitCast` is an interesting builtin. In the past, it was defined as being equivalent to the following sequence of operations:
- Take a pointer to the operand value
- Cast it to a pointer to the destination type
- Load from that pointer
In other words, it was essentially syntax sugar for reinterpreting bytes of memory. However, over time, we diverged from this definition—for instance, it became allowed to use `@bitCast` to reinterpret a `[3]u8` as a `u24`, even though on most targets `@sizeOf(u24)` is greater than `@sizeOf([3]u8)` so the above definition would invoke Illegal Behavior.
Up to now, the LLVM backend had implemented these underspecified semantics for the `@bitCast` builtin. However, because that definition involved reinterpreting memory, changing how we store integer types in memory ended up impacting the implementation of `@bitCast`, and introducing Illegal Behavior which led to crashes in the compiler test suite.
The easiest solution to this would probably have been to implement logic in the LLVM backend to approximately match the old behavior. I instead opted for a better solution—implement a new definition of `@bitCast`.
Redefining `@bitCast`
In 2024, Jacob Young wrote up language proposal #19755 which aimed to solve the problems with `@bitCast` by precisely specifying a new set of semantics for it. This proposal was accepted shortly after it was submitted, and in fact, the semantics it details are already implemented by the self-hosted x86_64 backend! So to solve the LLVM backend’s problems, I didn’t necessarily need to match the old `@bitCast` semantics—instead, this seemed like a good time to finally get the new semantics implemented _everywhere_.
As an aside, another advantage to doing this is that we could take advantage of the compiler’s `Legalize` pass, which takes difficult-to-lower operations and rewrites them in terms of simpler operations, so that compiler backends only need to support those simple operations. `Legalize` already had functionality, used by the self-hosted x86_64 backend, which converted complex `@bitCast` operations into simpler ones, and it could be easily adapted to aid the other compiler backends too (mainly the LLVM and C backends)—but only if they implemented the new semantics.
Regardless, the point is, I set out on a side quest (which ended up being harder than the _original_ quest) to implement these new semantics throughout the compiler. This includes not only the LLVM and C backends, but also `comptime` execution—after all, Zig allows you to do almost any operation at comptime, `@bitCast` included! Because the new semantics are meaningfully different from the old (more on this later), I also had to audit a lot of uses of `@bitCast` across the standard library, compiler, and supporting libraries (e.g. `compiler_rt`). But after a few mostly-painless fixes for CI failures, I was able to finally get my PR green, and landed it in master yesterday (closing a good few issues in the process!).
The New `@bitCast` Semantics
Now that we’ve gotten through all of the background, it’s finally time for me to actually explain new `@bitCast` behavior. Instead of being based on reinterpreting bytes in memory like before, the builtin is now defined in terms of the bits which _logically_ represent a type.
Every type which supports `@bitCast` has a “logical bit layout”—a representation of that type as an ordered sequence of bits. For instance, `u5` is composed of 5 logical bits, which we order from least-significant to most-significant. `[2]u5` is composed of 10 logical bits—the 5 from the first element, followed by the 5 from the second element. The new definition of `@bitCast` is that it reinterprets the logical bits of one type as the logical bits of a different type.
The simplest example is to take an unsigned integer, say a `u8`, and convert it to a signed integer of the same size, in this case `i8`. This operation does exactly what you’d expect—the bits are unchanged, and we just reinterpret the most-significant bit as a sign bit. Also unchanged are the semantics of `@bitCast` between an integer type and a `packed struct`/`packed union` type.
The place where the new semantics differ from the old is when you get aggregate types (arrays and vectors) involved.
Consider, for instance, bitcasting a `[2]u8` to a `u16`. Under the old semantics, the result of this operation depends on the target endian: on big-endian targets, the first array element became the 8 _most_ significant bits, whereas on little-endian targets, the first array element became the 8 _least_ significant bits. Under the new semantics, because we only care about _logical_ bit representation (which is endian-agnostic), the operation behaves identically on every target: the first array element becomes the 8 _least_ significant bits. As a general rule, the new semantics tend to match the behavior of the old semantics on little-endian targets.
This definition also allows for some weirder operations, such as converting `[2]u3` to `@Vector(3, u2)`:
``` test "bitcast [2]u3 to @Vector(3, u2)" { const arr: [2]u3 = .{ 0b001, 0b011 }; const vec: @Vector(3, u2) = @bitCast(arr);
// Concatenate all bits of `arr` starting with the least-significant bit of `arr[0]` to find the // logical bit sequence, then read off 2-bit chunks from it to get the elements of the resulting // vector value `vec`. // // arr[0] arr[1] // 0b001 0b011 // ------------- ------------- // 1 0 0 1 1 0 // -------- -------- -------- // 0b01 0b10 0b01 // vec[0] vec[1] vec[2]
try expect(vec[0] == 0b01); try expect(vec[1] == 0b10); try expect(vec[2] == 0b01); } const expect = @import("std").testing.expect; ```
This kind of operation isn’t very useful most of the time, but it’s there if you need it! For instance, perhaps you want to deconstruct an integer into a vector of individual bits to operate on—that can now be done by a `@bitCast` to `@Vector(n, u1)`.
While doing all of this stuff, I also implemented a couple of smaller accepted proposals—I won’t detail them here, but you can take a look at the issues if you’re interested:
- Disallow `@bitCast` to/from vectors of pointers (#18936)
- Allow `@bitCast` on enums (part of #35602)
Of course, all of these changed semantics will be explained in the 0.17.0 release notes (hopefully a bit more concisely than what I managed here!), and suggested migration steps outlined.
LLVM Backend Performance
On a final note, I just wanted to mention that the _original_ motivation for this branch—changing how the LLVM backend lowers non-ABI integer types—was demonstrably successful at restoring missed optimizations. In fact, the Zig compiler itself—despite not making heavy use of arbitrary bit width integers internally!—saw around 5% performance improvements from the better optimization. This means you might have some minor runtime performance gains to look forward to in 0.17.0!
Thanks for reading, I hope this was interesting to some of you. Happy hacking!
May 30, 2026
ELF Linker Improvements
Author: Matthew Lugg
I’ve spent the past few weeks working on our new ELF linker which debuted in Zig 0.16.0. At the time of the 0.16.0 release, this linker implementation was in its fairly early stages, and only really supported linking Zig-only code without any external libraries (even libc)—hence why it was (and still is) disabled by default (it can be enabled with `-fnew-linker`). However, quite a lot of progress has been made since that initial release!
Here’s a nice milestone—as of my latest PR, the new ELF linker is capable of building the self-hosted Zig compiler with LLVM and LLD libraries enabled, a task which requires quite a few features under the hood.
``` [mlugg@nebula master]$ # Build the Zig compiler using the new linker: [mlugg@nebula master]$ zig build -Dno-lib -Dnew-linker -Denable-llvm [mlugg@nebula master]$ # Use that compiler to build something with LLVM and LLD: [mlugg@nebula master]$ ./zig-out/bin/zig build-exe ~/hello.zig -fllvm -flld [mlugg@nebula master]$ ./hello Hello, World! [mlugg@nebula master]$ ```
Of course, an ELF linker isn’t necessarily the most exciting thing in the world, which is why the headline feature of this new linker is its support for fast incremental compilation. After the recent enhancements, it is now possible (on x86_64 Linux) to perform incremental rebuilds while linking external libraries, C sources, etc—without any additional performance overhead! Here’s a clip of me trying it out on Andrew’s Tetris clone:
A few silly changes to Andrew’s Tetris clone being built in around 30ms each.
Oh, and fast incremental rebuilds also work nicely on the Zig compiler itself:
``` [mlugg@nebula master]$ zig build -Dno-lib -Denable-llvm -fincremental --watch Build Summary: 4/4 steps succeeded install success └─ install zig success └─ compile exe zig Debug native success 36s
Build Summary: 4/4 steps succeeded install success └─ install zig success └─ compile exe zig Debug native success 244ms
Build Summary: 4/4 steps succeeded install success └─ install zig success └─ compile exe zig Debug native success 228ms
Build Summary: 4/4 steps succeeded install success └─ install zig success └─ compile exe zig Debug native success 288ms
Build Summary: 4/4 steps succeeded install success └─ install zig success └─ compile exe zig Debug native success 283ms ```
The biggest missing feature of this linker implementation right now is that it still does not yet support generating DWARF debug information for Zig code—that’s definitely my next priority. But even without that support, it’s amazing just how useful instant rebuilds can be, for example in any situation where you’re doing a lot of print debugging.
If you’re using the master branch of Zig and you’re on x86_64 Linux, consider trying out incremental compilation with the new ELF linker if it previously wasn’t working with your project! I expect many codebases to already work great with it, unlocking the ability to rebuild your project in milliseconds. Of course, if you come across any bugs, please do open an issue.
And if you’re currently sticking to tagged releases of Zig, don’t worry—as Andrew mentioned in his last devlog, Zig 0.17.0 is just around the corner, so it won’t be long before you can try this too!
May 26, 2026
Build System Reworked
Author: Andrew Kelley
Big branch just landed: separate the maker process from the configurer process
This devlog entry is essentially a preview of the upcoming release notes, but serves as an advanced notice to those who want to help test out the new features and provide feedback that will guide the Zig project moving forward.
Before, `build.zig` files plus the build system implementation were all compiled into one bloated process, in Debug mode. After `build.zig` logic finished constructing a build graph in memory, the “build runner” code executed it.
Now, `build.zig` files are compiled into a small process (the “configurer”) in debug mode. After this logic finishes constructing a build graph in memory, it is serialized to a binary configuration file. The parent `zig build` process is aware of this file and caches it for next time. While waiting for all that, it asynchronously compiles the build graph execution process (the “maker”) in release mode. Once the configuration file is available and the maker process is finished compiling, the maker process is executed, passing it the configuration file. The maker process only needs to be compiled once per `zig version` thanks to the global cache. The maker process then executes the build graph, which is contained within the serialized configuration file.
The primary motivation of this change was to make `zig build` faster, in three ways:
1. Only the user’s `build.zig` logic will be compiled with each change, rather than the entire build system along with it. This is starting to become more valuable now that we have introduced `--watch`, `--fuzz` and `--webui`. The build system can grow more features without making `zig build` take longer.
2. Now the build system can skip rerunning the `build.zig` logic entirely when it knows nothing will change, for example if you add `-freference-trace` to your `zig build` command line, it now avoids re-running your `build.zig` logic redundantly, using the same configuration as last time.
3. Now the process that actually executes the build graph is compiled with optimizations enabled.
To demonstrate points 2 and 3, here is the difference between running `zig build --help` before and after:
``` Benchmark 1 (34 runs): master/zig build -h measurement mean ± σ min … max outliers delta wall_time 150ms ± 5.52ms 145ms … 165ms 4 (12%) 0% peak_rss 84.8MB ± 275KB 84.2MB … 85.1MB 0 ( 0%) 0% cpu_cycles 593M ± 4.01M 588M … 608M 2 ( 6%) 0% instructions 995M ± 52.5K 995M … 995M 0 ( 0%) 0% cache_references 25.8M ± 165K 25.4M … 26.1M 0 ( 0%) 0% cache_misses 651K ± 20.1K 619K … 697K 0 ( 0%) 0% branch_misses 918K ± 7.44K 906K … 935K 0 ( 0%) 0% Benchmark 2 (348 runs): branch/zig build -h measurement mean ± σ min … max outliers delta wall_time 14.3ms ± 744us 13.2ms … 23.3ms 8 ( 2%) ⚡- 90.4% ± 0.4% peak_rss 78.5MB ± 562KB 77.1MB … 81.4MB 7 ( 2%) ⚡- 7.4% ± 0.2% cpu_cycles 24.1M ± 821K 22.8M … 27.1M 3 ( 1%) ⚡- 95.9% ± 0.1% instructions 43.7M ± 23.8K 43.7M … 43.8M 56 (16%) ⚡- 95.6% ± 0.0% cache_references 1.46M ± 14.6K 1.40M … 1.50M 19 ( 5%) ⚡- 94.3% ± 0.1% cache_misses 142K ± 4.87K 127K … 157K 2 ( 1%) ⚡- 78.1% ± 0.4% branch_misses 126K ± 1.37K 120K … 129K 12 ( 3%) ⚡- 86.3% ± 0.1% ```
It’s dramatic because before, `build.zig` logic was being executed with each `zig build` command, but now, the build system uses the cached, serialized configuration instead.
Aside from performance, I expect third-party tooling such as ZLS to benefit from consuming the serialized configuration file rather than maintaining a fork of the build runner.
This changeset heavily reworks the internal mechanism of the zig build system, however, it is mostly non-breaking from an API perspective, with the exceptions noted in the PR linked above.
For most people I’m guessing this is the main breaking change they’ll hit:
``` if (b.args) |args| { run_cmd.addArgs(args); } ```
⬇️
``` run_cmd.addPassthruArgs(); ```
This removes a capability from build scripts since they can no longer observe those arguments. In exchange, it means that when changing those arguments, build scripts no longer must be rebuilt from source.
If you’re someone who wants to influence the direction of Zig, this is a good time to upgrade your projects to the development version and try out these changes. We’ll be releasing 0.17.0 within a couple weeks from now. However, if you don’t have time, and you find out that 0.17.0 broke your build, don’t worry, there will be plenty of opportunity to get fixes in for the 0.17.1 tag as well.
April 08, 2026
Incremental compilation with LLVM
Author: Matthew Lugg
I’ve been spending a bit of time working on personal projects after merging my type resolution changes last month, but I did find the time recently to make some improvements to the LLVM codegen backend. This involved a few different enhancements with various goals, but one nice user-facing change was that I managed to get incremental compilation working with the LLVM backend.
Sadly this can’t do anything to speed up the dreaded LLVM Emit Object: that time is entirely down to LLVM. However, what incremental compilation _does_ help with is minimizing the time spent in the actual Zig compiler code, which means that if your code has compile errors (so “LLVM Emit Object” will be skipped), you’ll usually get those errors very quickly. (Of course, it does still give you a _slight_ speed-up in successful builds too.)
This support is available in master branch builds right now, and will be in the 0.16.0 release (which we’ll be tagging very soon).
For anyone who still hasn’t tried it, especially if you’re using Zig’s master branch, please do try out incremental compilation by passing `-fincremental --watch` to `zig build`! The Zig core team have benefited from incremental compilation in our workflows for a good year now, and we’re also hearing good things from users. The feature is relatively stable at this point, and people are often surprised how much time they can save just by getting up-to-date compile errors in milliseconds rather than seconds.
I haven’t really personally used incremental compilation with the LLVM backend, but all of the incremental test coverage in CI is now enabled for the LLVM backend, and I’ve had positive feedback from users, so it’s definitely worth giving a shot. As always, if you encounter bugs in incremental compilation, please report them if you can!
Thank you, and I hope you find this useful :)
March 10, 2026
Type resolution redesign, with language changes to taste
Author: Matthew Lugg
Today, I merged a 30,000 line PR after two (arguably three) months of work. The goal of this branch was to rework the Zig compiler’s internal type resolution logic to a more logical and straightforward design. It’s a quite exciting change for me personally, because it allowed me to clean up a bunch of the compiler guts, but it also has some nice user-facing changes which you might be interested in!
For one thing, the Zig compiler is now lazier about analyzing the fields of types: if the type is never initialized, then there’s no need for Zig to care what that type “looks like”. This is important when you have a type which doubles as a namespace, a common pattern in modern Zig. For instance, when using `std.Io.Writer`, you don’t want the compiler to also pull in a bunch of code in `std.Io`! Here’s a straightforward example:
``` const Foo = struct { bad_field: @compileError("i am an evil field, muahaha"), const something = 123; }; comptime { _ = Foo.something; // `Foo` only used as a namespace } ```
Previously, this code emitted a compile error. Now, it compiles just fine, because Zig never actually looks at the `@compileError` call.
Another improvement we’ve made is in the “dependency loop” experience. Anyone who has encountered a dependency loop compile error in Zig before knows that the error messages for them are entirely unhelpful—but that’s now changed! If you encounter one (which is also a bit less likely now than it used to be), you’ll get a detailed error message telling you exactly where the dependency loop comes from. Check it out:
``` const Foo = struct { inner: Bar }; const Bar = struct { x: u32 align(@alignOf(Foo)) }; comptime { _ = @as(Foo, undefined); } ```
``` $ zig build-obj repro.zig error: dependency loop with length 2 repro.zig:1:29: note: type 'repro.Foo' depends on type 'repro.Bar' for field declared here const Foo = struct { inner: Bar }; ^~~ repro.zig:2:44: note: type 'repro.Bar' depends on type 'repro.Foo' for alignment query here const Bar = struct { x: u32 align(@alignOf(Foo)) }; ^~~ note: eliminate any one of these dependencies to break the loop ```
Of course, dependency loops can get much more complicated than this, but in every case I’ve tested, the error message has had enough information to easily see what’s going on.
Additionally, this PR made big improvements to the Zig compiler’s “incremental compilation” feature. The short version is that it fixed a huge amount of known bugs, but in particular, “over-analysis” problems (where an incremental update did more work than should be necessary, sometimes by a big margin) should finally be all but eliminated—making incremental compilation significantly faster in many cases! If you’ve not already, consider trying out incremental compilation: it really is a lovely development experience. This is for sure the improvement which excites me the most, and a large part of what motivated this change to begin with.
There are a bunch more changes that come with this PR—dozens of bugfixes, some small language changes (mostly fairly niche), and compiler performance improvements. It’s far too much to list here, but if you’re interested in reading more about it, you can take a look at the PR on Codeberg—and of course, if you encounter any bugs, please do open an issue. Happy hacking!
February 13, 2026
io_uring and Grand Central Dispatch std.Io implementations landed
Author: Andrew Kelley
As we approach the end of the 0.16.0 release cycle, Jacob has been hard at work, bringing `std.Io.Evented` up to speed with all the latest API changes:
- Grand Central Dispatch implementation
Both of these are based on userspace stack switching, sometimes called “fibers”, “stackful coroutines”, or “green threads”.
They are now **available to tinker with**, by constructing one’s application using `std.Io.Evented`. They should be considered **experimental** because there is important followup work to be done before they can be used reliably and robustly:
- remove the logging
- diagnose the unexpected performance degradation when using `IoMode.evented` for the compiler
- a couple functions still unimplemented
- more test coverage is needed
- builtin function to tell you the maximum stack size of a given function to make these implementations practical to use when overcommit is off.
With those caveats in mind, it seems we are indeed reaching the Promised Land, where Zig code can have Io implementations effortlessly swapped out:
``` const std = @import("std");
pub fn main(init: std.process.Init.Minimal) !void { var debug_allocator: std.heap.DebugAllocator(.{}) = .init; const gpa = debug_allocator.allocator();
var threaded: std.Io.Threaded = .init(gpa, .{ .argv0 = .init(init.args), .environ = init.environ, }); defer threaded.deinit(); const io = threaded.io();
return app(io); }
fn app(io: std.Io) !void { try std.Io.File.stdout().writeStreamingAll(io, "Hello, World!\n"); } ```
``` $ strace ./hello_threaded execve("./hello_threaded", ["./hello_threaded"], 0x7ffc1da88b20 /* 98 vars */) = 0 mmap(NULL, 262207, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f583f338000 arch_prctl(ARCH_SET_FS, 0x7f583f378018) = 0 prlimit64(0, RLIMIT_STACK, NULL, {rlim_cur=8192*1024, rlim_max=RLIM64_INFINITY}) = 0 prlimit64(0, RLIMIT_STACK, {rlim_cur=16384*1024, rlim_max=RLIM64_INFINITY}, NULL) = 0 sigaltstack({ss_sp=0x7f583f338000, ss_flags=0, ss_size=262144}, NULL) = 0 sched_getaffinity(0, 128, [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31]) = 8 rt_sigaction(SIGIO, {sa_handler=0x1019d90, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x10328c0}, {sa_handler=SIG_DFL, sa_mask=[], sa_flags=0}, 8) = 0 rt_sigaction(SIGPIPE, {sa_handler=0x1019d90, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x10328c0}, {sa_handler=SIG_DFL, sa_mask=[], sa_flags=0}, 8) = 0 writev(1, [{iov_base="Hello, World!\n", iov_len=14}], 1Hello, World! ) = 14 rt_sigaction(SIGIO, {sa_handler=SIG_DFL, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x10328c0}, NULL, 8) = 0 rt_sigaction(SIGPIPE, {sa_handler=SIG_DFL, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x10328c0}, NULL, 8) = 0 exit_group(0) = ? +++ exited with 0 +++ ```
Swapping out only the I/O implementation:
``` const std = @import("std");
pub fn main(init: std.process.Init.Minimal) !void { var debug_allocator: std.heap.DebugAllocator(.{}) = .init; const gpa = debug_allocator.allocator();
var evented: std.Io.Evented = undefined; try evented.init(gpa, .{ .argv0 = .init(init.args), .environ = init.environ, .backing_allocator_needs_mutex = false, }); defer evented.deinit(); const io = evented.io();
return app(io); }
fn app(io: std.Io) !void { try std.Io.File.stdout().writeStreamingAll(io, "Hello, World!\n"); } ```
``` execve("./hello_evented", ["./hello_evented"], 0x7fff368894f0 /* 98 vars */) = 0 mmap(NULL, 262215, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f70a4c28000 arch_prctl(ARCH_SET_FS, 0x7f70a4c68020) = 0 prlimit64(0, RLIMIT_STACK, NULL, {rlim_cur=8192*1024, rlim_max=RLIM64_INFINITY}) = 0 prlimit64(0, RLIMIT_STACK, {rlim_cur=16384*1024, rlim_max=RLIM64_INFINITY}, NULL) = 0 sigaltstack({ss_sp=0x7f70a4c28008, ss_flags=0, ss_size=262144}, NULL) = 0 sched_getaffinity(0, 128, [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31]) = 8 mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f70a4c27000 mmap(0x7f70a4c28000, 548864, PROT_READ|PROT_WRITE, MAP_PR