
Zig is a general-purpose programming language and toolchain for maintaining robust, optimal, and reusable software.
Zig development is funded via Zig Software Foundation, a 501(c)(3) non-profit organization. Please consider a recurring donation so that we can offer more billable hours to our core team members. This is the most straightforward way to accelerate the project along the Roadmap to 1.0. If you need donation receipts or are looking to migrate away from GitHub Sponsors, we recommend donating via Every.org.
This release features 5 months of work: changes from 206 different contributors, spread among 925 commits.
Originally predicted to be shorter, this release cycle ended up substantial, with the Build System reworked, including the introduction of the Build Server Protocol, and the ELF Linker enhanced to the point where we expect Incremental Compilation to work for everyone on x86_64-linux.
Target Support

Zig supports a wide range of architectures and operating systems. The Support Table and Additional Platforms sections cover the targets that Zig can build programs for, while the zig-bootstrap README covers the targets that the Zig Compiler itself can be easily cross-compiled to run on.
Notable changes:
aarch64-openbsd is now tested natively in Zig's CI, ensuring high-quality support going forward.
aarch64-freebsd and aarch64-netbsd CI jobs now run on pull requests too, in addition to master pushes.
- An LLVM bug that broke most
aarch64-windows binaries, including the Zig Compiler, has been worked around.
- The Zig Compiler now applies mandatory code hardening techniques when targeting
aarch64-openbsd so that the resulting binaries actually work.
- Zig now provides stack traces on crashes and failed assertions on 32-bit ARM. Some work still remains for Thumb-only targets.
- Zig now provides stack traces on crashes and failed assertions on SPARC.
- Zig now handles pointer authentication opcodes when doing stack unwinding on AArch64.
- Support for the
loongarch32-linux-gnu[sf] targets has been added.
- Zig now has generally usable support for 64-bit SPARC, and especially
sparc64-linux. This is largely thanks to Zig's new ELF linker which now has better support for this target than LLD.
- The Zig Standard Library has been ported to the x32 and N32 ABIs on x86-64 and 64-bit MIPS, respectively. These are niche ILP32 ABIs that allow using the 64-bit instruction set while only having 32-bit pointers - the idea being to trade available address space for lower memory usage and better cache utilization.
- Target information has been added for some game consoles:
aarch64-switch, arm-gba, mipsel-psx, and powerpc-wiiu
- Very early
xtensa-linux support has been added to Zig. Note that, for now, this support can only be exercised via the C backend or the experimental LLVM backend.
- The Zig Standard Library now has support for
arc[eb]-linux, csky-linux, and m88k-openbsd when using the C backend.
- The Zig Standard Library now has support for no-libc
microblaze[el]-linux, sh[eb]-linux, and sparc-linux.
- Zig now enforces
-mabi=ieeelongdouble for all PowerPC targets. This is just a formalization of what was already reality; Zig has never supported the IBM "double-double" format for long double and likely never will. As a result, this release drops support for powerpc-linux-gnueabi[hf] because glibc only supports the "double-double" format on these targets. The powerpc-linux-musleabi[hf] targets remain supported as they use the IEEE format.
- This release drops support for
powerpc64-linux-gnu. Zig has only ever supported linking ELFv2 binaries for 64-bit PowerPC, and glibc does not officially support ELFv2 on big endian - nor IEEE long double, as above.
- Zig's ability to detect the native CPU model and features has been greatly enhanced across the board; this affects almost every architecture on every supported OS.
- The baseline CPU model has been changed for some targets:
aarch64-haiku: cortex_a55
m68k-*: M68030
mips64-openbsd: octeon
powerpc-netbsd: 750
powerpc64-freebsd: pwr8
powerpc64-linux: pwr8
powerpc64-openbsd: pwr9
s390x-*: arch11
sparc-*: generic
sparc-linux: v9
sparc64-*: ultrasparc
xtensa-*: esp32
- In Zig's target query syntax, native libc version detection now only happens if the triple actually uses native libc (i.e. the ABI component is omitted). We expect this new behavior to better match people's mental model for how target queries work, particularly when considering how the OS component works.
Tier System
Zig's level of support for various targets is broadly categorized into four tiers with Tier 1 being the highest. The goal is for Tier 1 targets to have zero disabled tests - this will become a requirement for post-1.0.0 Zig releases.
Tier 1
- All non-experimental language features are known to work correctly.
- The Compiler can generate machine code for this target without relying on LLVM.
- The integrated fuzzer works on this target (if applicable).
Tier 2
- The Standard Library cross-platform abstractions have implementations for this target.
- Failed assertions and crashes produce stack traces on this target.
- libc is available for this target even when cross-compiling (if applicable).
- Continuous integration machines build the module tests for this target on every push.
Tier 3
- The Compiler can generate machine code for this target by relying on an external backend such as LLVM.
- The Linker can produce object files, libraries, and executables for this target.
Tier 4
- The Compiler can generate assembly or C source code for this target.
Support Table
In the following table, ✅ indicates full support, ❌ indicates no support, and ⚠️ indicates that there is partial support, e.g. only for some sub-targets, or with some notable known issues. ❔ indicates that the status is largely unknown, typically because the target is rarely exercised. Hover over other icons for details.
Targets marked with 🪦 are obsolescent; the Zig compiler and standard library maintain best-effort support for them, but that support is expected to be removed eventually.
OS Version Requirements
The Zig standard library has minimum version requirements for some supported operating systems, which in turn affect the Zig compiler itself:
| OS |
Version |
| Darwin |
15.0+ |
| DragonFly BSD |
6.4+ |
| FreeBSD |
14.0+ |
| Linux |
5.10+ |
| NetBSD |
10.1+ |
| OpenBSD |
7.8+ |
| Windows |
10+ |
Additional Platforms
Zig also has varying levels of support for these targets, for which the tier system does not quite apply:
aarch64-driverkit
aarch64[_be]-freestanding
aarch64-fuchsia
aarch64-hurd
aarch64-switch
aarch64-uefi
alpha-freestanding
amdgcn-amdhsa
amdgcn-amdpal
amdgcn-mesa3d
arc[eb]-freestanding
arm[eb]-freestanding
arm-3ds
arm-fuchsia
arm-gba
arm-uefi
arm-vita
avr-freestanding
bpf(eb,el)-freestanding
csky-freestanding
ez80-freestanding
ez80-tios
hexagon-freestanding
hppa[64]-freestanding
kalimba-freestanding
kvx-freestanding
lanai-freestanding
loongarch(32,64)-freestanding
loongarch(32,64)-uefi
m68k-freestanding
m88k-freestanding
microblaze[el]-freestanding
mips[64][el]-freestanding
mipsel-psx
mipsel-psp
msp430-freestanding
nvptx[64]-cuda
nvptx[64]-nvcl
or1k-freestanding
powerpc-wiiu
powerpc[64][le]-freestanding
powerpc64-ps3
propeller-freestanding
riscv(32,64)[be]-freestanding
riscv(32,64)-uefi
riscv64-fuchsia
riscv64-hurd
s390x-freestanding
sh[eb]-freestanding
sparc[64]-freestanding
spirv(32,64)-opencl
spirv(32,64)-opengl
spirv(32,64)-vulkan
spork8-freestanding
thumb[eb]-freestanding
thumb-fuchsia
thumb-gba
thumb-vita
ve-freestanding
wasm(32,64)-emscripten
wasm(32,64)-freestanding
x86[_16,_64]-freestanding
x86[_64]-hurd
x86[_64]-uefi
x86_64-driverkit
x86_64-fuchsia
x86_64-plan9
x86_64-ps4
x86_64-ps5
xcore-freestanding
xtensa[eb]-freestanding
Language Changes
Language Stability Progress
Since the release of Zig 0.16.0, a lot of progress has been made towards stabilizing the language. This is a key step in our roadmap, and a requirement before tagging Zig 1.0.
In particular, since the last release, we have discussed and made decisions on many language proposals—accepting around 25 and rejecting around 125. At the time of writing, 23 undecided language proposals remain open on the Codeberg issue tracker, and 61 undecided language proposals remain open on the legacy GitHub issue tracker. Therefore, this effort represents a significant step towards finalizing the language design (although some major decisions remain).
@bitCast changes
Zig 0.17.0 changes the definition of the @bitCast builtin.
In many cases, the new behavior is equivalent to the old: in particular, casting between an integer type and another integer type is unaffected, as is casting between an integer type and a packed struct or packed union.
However, the semantics of @bitCast calls involving array or vector types have changed. Unfortunately, this change has the potential to break existing code without triggering a compile error.. Therefore, it may be useful when upgrading to audit any @bitCast uses which involve array or vector types.
The new definition of @bitCast is that it reinterprets the logical bit representation of a value as a different type. The following types are considered to have logical bit representations:
void
bool
- integer types, except for
comptime_int
- floating-point types, except for
comptime_float
- integer-backed types
enum(T), packed struct(T), and packed union(T)
- arrays or vectors of any of these types
For integer and floating-point types, the logical bit representation starts with the least-significant bit and ends with the most-significant bit. For array and vector types, all elements' logical bit representations are concatenated in order starting with the first element.
In practice, this means that the new @bitCast definition largely aligns with the old behavior on little-endian targets. Unlike the old behavior, the new behavior is fully endian-agnostic, i.e. the operation behaves the same regardless of the target endian.
The new @bitCast definition disallows casts between some types which were previously allowed. In particular, casts involving extern struct or extern union types are no longer permitted. In most cases, code which was using such casts is aiming to reinterpret the value's in-memory representation (sometimes called "type punning")—to achieve this, use @ptrCast or an extern union.
bitcast_extern_struct.zig
const TwoBytes = extern struct {
b0: u8,
b1: u8,
};
test "type pun extern struct" {
const bytes: TwoBytes = .{ .b0 = 0x12, .b1 = 0xAB };
const int: u16 = @bitCast(bytes);
switch (std.lang.Endian.native) {
.little => try expectEqual(0xAB_12, int),
.big => try expectEqual(0x12_AB, int),
}
}
const std = @import("std");
const expectEqual = std.testing.expectEqual;
$ zig test bitcast_extern_struct.zig
/home/ci/.cache/act/4d2db5a0202099f4/hostexecutor/src/download/0.17.0/release-notes/bitcast_extern_struct.zig:7:31: error: cannot @bitCast from 'bitcast_extern_struct.TwoBytes'
const int: u16 = @bitCast(bytes);
^~~~~
/home/ci/.cache/act/4d2db5a0202099f4/hostexecutor/src/download/0.17.0/release-notes/bitcast_extern_struct.zig:1:25: note: struct declared here
const TwoBytes = extern struct {
~~~~~~~^~~~~~
ptrcast_extern_struct.zig
const TwoBytes = extern struct {
b0: u8,
b1: u8,
};
test "type pun extern struct" {
const bytes: TwoBytes = .{ .b0 = 0x12, .b1 = 0xAB };
const int_ptr: *align(1) const u16 = @ptrCast(&bytes);
switch (std.lang.Endian.native) {
.little => try expectEqual(0xAB_12, int_ptr.*),
.big => try expectEqual(0x12_AB, int_ptr.*),
}
}
const std = @import("std");
const expectEqual = std.testing.expectEqual;
$ zig test ptrcast_extern_struct.zig
1/1 ptrcast_extern_struct.test.type pun extern struct...OK
All 1 tests passed.
Formally Specified and Fuzzed Grammar
Zig's formal grammar.peg and the actual language implementation did not agree in many places. Probably, the formal grammar has never actually 100% matched the actual handwritten tokenizer and parser.
This problem is now fixed and unblocks future grammar changes and language specification work.
At a high level, the approach was to write a tool that accepts Zig's grammar.peg as input and outputs a simple recursive descent parser. This generated parser is then used as an oracle for fuzz testing and the handwritten std.zig.Ast.parse() is compared against it. This approach ensures a single source of truth and allows for easy iteration as the grammar changes.
More details: #36094
C Translation Moving to External Package
@cImport was deprecated in Zig 0.16.0 and is now removed. Furthermore, in this release std.Build.Step.TranslateC is deprecated in favor of an explicit package dependency on official ZSF translate-c package, which is the same implementation the build step provides, but offers more configuration options for the translated code, and has an independent release cadence from the main Zig toolchain.
Upgrade guide:
zig fetch --save git+https://codeberg.org/ziglang/translate-c
--- a/build.zig
+++ b/build.zig
@@ -1,16 +1,19 @@
const std = @import("std");
+const Translator = @import("translate_c").Translator;
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
- const translate_c = b.addTranslateC(.{
- .root_source_file = b.path("src/c.h"),
+ const translate_c = b.dependency("translate_c", .{});
+
+ const translator: Translator = .init(translate_c, .{
+ .c_source_file = b.path("src/c.h"),
.target = target,
.optimize = optimize,
+ // additional options now available that go here:
+ // https://codeberg.org/ziglang/translate-c#options
});
- translate_c.linkSystemLibrary("glfw", .{});
- translate_c.linkSystemLibrary("epoxy", .{});
+ translator.linkSystemLibrary("glfw3", .{});
+ translator.linkSystemLibrary("epoxy", .{});
const exe = b.addExecutable(.{
.name = "tetris",
@@ -21,7 +24,7 @@ pub fn build(b: *std.Build) void {
.imports = &.{
.{
.name = "c",
- .module = translate_c.createModule(),
+ .module = translator.mod,
},
},
}),
Added @backingInt and @fromBackingInt
The @backingInt and @fromBackingInt builtins are new. These builtins replace the now-deprecated @intFromEnum and @enumFromInt builtins (#35966).
@backingInt works with all enums and with bitpacks with explicit backing integer types only. It also works with tagged unions, returning the backing integer of the active tag value. An undefined enum or bitpack yields an undefined backing integer.
@fromBackingInt infers its result type, which may be any enum or a bitpack with an explicit backing integer type. It takes a parameter of exactly that backing integer type. For enums, passing a backing integer that is either undefined or would yield an invalid tag value results in safety-checked Illegal Behavior. For bitpacks, passing an undefined backing integer yields an undefined bitpack.
@bitCast now also performs a safety check for invalid tag values if its destination type is an enum.
Also adds a std.meta.BackingInt function to get the result type of @backingInt.
Zig now requires empty enums to have noreturn as their backing integer because they are uninstantiable.
Upgrade example:
--- a/lib/std/Build.zig
+++ b/lib/std/Build.zig
@@ -145,7 +145,7 @@ pub const Graph = struct {
pub fn addGeneratedFile(graph: *Graph, owner: *Step) Configuration.GeneratedFileIndex {
graph.generated_files.append(graph.arena, owner) catch @panic("OOM");
- return @enumFromInt(graph.generated_files.items.len - 1);
+ return @fromBackingInt(@intCast(graph.generated_files.items.len - 1));
}
pub fn dupeString(graph: *const Graph, bytes: []const u8) []const u8 {
@@ -2607,7 +2607,7 @@ pub const LazyPath = union(enum) {
.src_path, .cwd_relative, .relative, .dependency => {},
.generated => |gen| {
const graph = other_step.owner.graph;
- const generated_owner_step = graph.generated_files.items[@intFromEnum(gen.index)];
+ const generated_owner_step = graph.generated_files.items[@backingInt(gen.index)];
other_step.dependOn(generated_owner_step);
},
}
zig fmt automatically performs this upgrade.
Added @SpirvType
SPIR-V has a number of types, such as images and samplers, that have no equivalent in Zig's type system. Previously, the only way to refer to one of them was through inline assembly, which made it impossible to declare a texture or a storage buffer as an ordinary global variable. Zig 0.17.0 implements accepted proposal #35240, adding the @SpirvType builtin alongside the other type-creating builtins:
@SpirvType(comptime options: std.lang.Type.Spirv) type
.sampler creates an OpTypeSampler.
.image creates an OpTypeImage.
.sampled_image creates an OpTypeSampledImage from an image type whose usage is .sampled.
.runtime_array creates an OpTypeRuntimeArray. It supports indexing and exposes a len field just like the array type.
Using this builtin when not targeting SPIR-V is a compile error. The options are also validated against the target OS.
spirv_type.zig
const std = @import("std");
const Image = @SpirvType(.{ .image = .{
.usage = .{ .sampled = f32 },
.format = .unknown,
.dim = .@"2d",
.depth = .not_depth,
.arrayed = false,
.multisampled = false,
.access = .unknown,
} });
const SampledImage = @SpirvType(.{ .sampled_image = Image });
const texture = @extern(*addrspace(.constant) const SampledImage, .{
.name = "texture",
.decoration = .{ .descriptor = .{ .set = 0, .binding = 0 } },
});
const uv_in = @extern(*addrspace(.input) const @Vector(2, f32), .{
.name = "uv",
.decoration = .{ .location = 0 },
});
const color_out = @extern(*addrspace(.output) @Vector(4, f32), .{
.name = "color",
.decoration = .{ .location = 0 },
});
export fn main() callconv(.{ .spirv_fragment = .{} }) void {
color_out.* = std.spirv.imageSampleImplicitLod(texture, uv_in.*);
}
$ zig build-obj spirv_type.zig -target spirv32-vulkan
Array Multiplication Syntax Removed
Array multiplication syntax (a ** b) has been removed in favor of @splat.
Migration:
--- a/player/chromaprint.zig
+++ b/player/chromaprint.zig
@@ -35,7 +35,7 @@ pub const Chroma = struct {
const max_index = @min(window_size / 2, freqToIndex(max_freq));
const notes: [window_size]u8 = n: {
@setEvalBranchQuota(window_size);
- var result = [1]u8{0} ** window_size;
+ var result: [window_size]u8 = @splat(0);
for (min_index..max_index) |i| {
const freq = indexToFreq(i);
const octave = freqToOctave(freq);
@@ -123,7 +123,7 @@ const RollingIntegralImage = struct {
num_rows: u32,
pub const init: RollingIntegralImage = .{
- .data = [1]Float{0} ** data_size,
+ .data = @splat(0),
.num_rows = 0,
};
Added @divCeil
The new @divCeil builtin performs integer division rounded toward positive infinity, complementing the existing @divTrunc, @divFloor, and @divExact builtins.
@divCeil(5, 3) == 2
@divCeil(-5, 3) == -1
As with the other division builtins, caller guarantees that denominator != 0 and that result does not overflow.
No more std.math.divCeil(a, b) catch unreachable!
@hasDecl Returns true Only for Public Declarations
Previously, @hasDecl returned true for public declarations and declarations in the same file. Now, the behavior is the same independently of which file @hasDecl is in.
hasdecl.zig
const std = @import("std");
const Foo = struct {
bar: i32,
const baz = 1;
pub var quux = "xxx";
};
test "@hasDecl example" {
try std.testing.expect(!@hasDecl(Foo, "bar"));
try std.testing.expect(!@hasDecl(Foo, "baz")); // different in 0.17.0
try std.testing.expect(@hasDecl(Foo, "quux"));
}
$ zig test hasdecl.zig
1/1 hasdecl.test.@hasDecl example...OK
All 1 tests passed.
Allow Dereference and Coercion to Array Pointer of comptime Length Slices
Now allowed:
const slice: []const u16 = &.{ 1, 2, 3 };
const array: [3]u16 = slice.*;
const array_ptr: *const [3]u16 = slice;
void{} Syntax Removed
void{} is no longer valid syntax. Use {} instead (#15213).
errdefer Capture Removed
errdefer |err| {
// `err` was the error being returned; you could do stuff with it!
// Like a normal `defer/`errdefer`, you can't `return` or `try` in this block, so you can't change
// which error is returned; but you can e.g. log it
}
The capture (|err|) is no longer allowed (#23734).
To migrate, split the function into two:
fn processOneTarget(job: Job) void {
- errdefer |err| std.debug.panic("panic: {s}", .{@errorName(err)});
+ processOneTargetInner(job) catch |err| std.debug.panic("panic: {s}", .{@errorName(err)});
+}
+fn processOneTargetInner(job: Job) !void {
const target = job.target;
i0 Removed
i0 is no longer an allowed primitive integer type.
This type was nonsensical, so does not have a direct alternative. However, any uses of it can almost certainly be transparently replaced with u0.
internal and link_once Global Linkage Removed
The internal and link_once tags of std.lang.GlobalLinkage have been removed as they had unclear semantics and incomplete support in codegen and linking (#36956). Any use of link_once is likely served by weak, while the replacement for internal is to simply not @export the symbol in the first place.
Standard Library
- Added
f128 support for @exp and @exp2 based on "Table-Driven Implementation of the Exponential Function in IEEE Floating-Point Arithmetic" by Ping Tak Peter Tang, adapted to work with 128-bit numbers (#31846).
- Added
std.Io.Semaphore.waitTimeout (#31924).
- Added
std.spirv helpers for sampling, querying, and writing images (#36187).
ArrayHashMap.setKey no longer recomputes the entire index (#32136).
std.Target.parseCpuModel now returns optional rather than error.
std.debug.Pdb: deduplicate inline source locations (#35438).
hash.crc full namespace audit (#35952).
std.fs.path add appending variants for relative and resolve (#36784).
Deprecations
std.heap.memory_pool.AlignedManaged removed in favor of std.heap.memory_pool.Aligned.
std.heap.memory_pool.ExtraManaged removed in favor of std.heap.memory_pool.Extra.
- Deprecated
std.builtin in favor of std.lang.
- Deprecated
std.meta.fieldInfo in favor of @typeInfo.
- Deprecated
std.meta.fieldNames in favor of @typeInfo.
- Deprecated
std.meta.fieldTypes in favor of @typeInfo.
- Deprecated
std.DoublyLinkedList.pop in favor of std.DoublyLinkedList.popLast.
- Renamed
std.gpu to std.spirv.
- Removed
std.ascii.indexOfIgnoreCase in favor of std.ascii.findIgnoreCase.
- Removed
std.ascii.indexOfIgnoreCasePos in favor of std.ascii.findIgnoreCasePos.
- Removed
std.ascii.indexOfIgnoreCasePosLinear in favor of std.ascii.findIgnoreCasePosLinear.
- Removed
std.bit_set.Integer.initEmpty in favor of std.bit_set.Integer.empty.
- Removed
std.bit_set.Integer.initFull in favor of std.bit_set.Integer.full.
- Removed
std.bit_set.Array.initEmpty in favor of std.bit_set.Array.empty.
- Removed
std.bit_set.Array.initFull in favor of std.bit_set.Array.full.
- Removed
std.enums.EnumSet.initEmpty in favor of std.enums.EnumSet.empty.
- Removed
std.enums.EnumSet.initFull in favor of std.enums.EnumSet.full.
- Removed
std.mem.containsAtLeastScalar2 in favor of std.mem.containsAtLeastScalar.
- Removed
std.mem.readPackedIntNative in favor of std.mem.readPackedInt.
- Removed
std.mem.readPackedIntForeign in favor of std.mem.readPackedInt.
- Removed
std.mem.writePackedIntNative in favor of std.mem.writePackedInt.
- Removed
std.mem.writePackedIntForeign in favor of std.mem.writePackedInt.
StackFallbackAllocator Reworked
StackFallbackAllocator is an abstraction that is useful for the "small vec" optimization, in which common cases can fit on a pre-allocated stack buffer, but rare cases need dynamic heap allocation. The previous design had a few problems:
- There was no way to specify the alignment of the buffer.
- It was generic over the size of the buffer.
- Calling
.allocator().get() mutated the type, unlike all other allocators, requiring a runtime safety check.
Now, the buffer is provided as an argument, like most other std APIs that need a buffer.
var stack align(@max(
@alignOf(std.heap.StackFallbackAllocator(0)),
@alignOf(Item)),
) = std.heap.stackFallback(@sizeOf(Item), self.gpa);
const allocator = stack.get();
⬇️
var stack_buf: [1]Item = undefined;
var stack: std.heap.StackFallbackAllocator = .init(@ptrCast(&stack_buf), gpa);
const allocator = stack.allocator();
SafeAllocator Introduced
std.heap.DebugAllocator is replaced by a thread-safe allocator with the following guarantees:
deinit reports all leaks and frees all backing memory.
- All allocation mismatches result in either a panic or segmentation fault.
- Allocations from other
SafeAllocator instances cause a panic (if Options.canary differ).
- Double frees and operation (resize, remap, and free) races panic or segmentation fault.
Given the backing allocator does not reuse memory, it does not reuse memory either and most writes after free will segmentation fault or are eventually detected and panic.
std.heap.DebugAllocator and std.heap.Check are deprecated.
Every allocation is trailed by an AllocFooter which contains metadata for the allocation and stack traces. It is protected by a checksum to catch corruption from allocation overwrites and report canary mismatches. An allocation's memory has a minimum alignment of AllocFooter so that the footer is at a fixed offset determined from the allocation size. An allocation's memory is stored either:
- Inside linearly-filled buckets for small allocations.
- Inside an allocation directly from the backing allocator.
To track allocations, each thread maintains a table of backing allocations. The table may be modified by other threads in the case of a producer-consumer operation, so the table is a linked list only expanded by creating new segments. Each thread maintains a linked list of free entries, which may contain entries from other threads' tables.
In the case of producer-consumer operations, acquire/release ordering is assumed to be provided externally. This is also assumed by all other thread-safe allocators that reuse memory as otherwise there would be data races on reuse of allocated memory.
Two fuzz tests have also been added for the allocator. They check that there is no memory reuse, that returned memory is writable, and that it is not overwritten. The multi-threaded fuzz test spawns a number of worker threads which are used for all the test runs. I have run these tests extensively under TSAN.
ArrayList
getLastOrNull has been deprecated and renamed to last
getLast has been deprecated in favor of last combined with .?
lastPtr has been added which returns ?*T
Upgrade guide:
if (list.getLastOrNull()) |foo| {
// ...
}
const foo = list.getLast();
⬇️
if (list.last()) |foo| {
// ...
}
const foo = list.last().?;
ArrayList Pointer Stability
This is an enhancement that can help track down ArrayList usage bugs faster (#36239).
Devlog Entry
debug.SafetyLock Gains Support for Shared Locking
The existing lock and unlock methods continue to act exclusively. They should be used when data may be mutated. New methods, lockShared and unlockShared, may be used for shared locking in situations where multiple independent users are reading but not mutating data.
fmt.allocPrint moved to mem.Allocator
try std.fmt.allocPrint(arena, "{s}={d}", .{ x, y });
⬇️
try arena.print("{s}={d}", .{ x, y });
Formatted Printing Enhancements
The "{q}" specifier which escapes strings so that they can appear in double-quoted string literals has relaxed escaping rules such that UTF-8 encoded data can pass through unmangled.
"{qf}" is introduced for double-quote escaping the output of a format().
std.zon.parse Reworked
std.zon.parse now takes struct args and allocates its result from an arena.
Migration guide:
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
const result = std.zon.fromSlice(
MyZonType,
gpa,
source,
&diag,
.{},
) catch |err| switch (err) {
error.ParseZon => std.process.fatal("input.zon: {f}", .{diag}),
error.OutOfMemory => |e| return e,
};
defer std.zon.parse.free(result);
⬇️
var diag: Diagnostics = undefined;
const result = std.zon.fromSlice(MyZonType, .{
.gpa = gpa,
.arena = arena,
.source = source,
.diagnostics = &diag,
}) catch |err| switch (err) {
error.ParseZon => diag.fatal("input.zon"),
error.OutOfMemory => |e| return e,
}
Some methods were renamed:
fromSliceAlloc ➡️ fromSlice
fromSlice ➡️ fromSliceNoAlloc
- The other "from" methods were renamed following this same scheme.
"updateFrom" variants such as updateFromSlice were added. These update an in memory value, overwriting the value's fields with fields specified in the ZON source. This can be useful when using ZON to load configuration files with varying precedence, for example a text editor that has a global config file and a per-project config file.
Rename bit_set Variants and Deprecate the Managed One
Renames the types for consistency, deprecating the previous names and the managed variant.
std.bit_set.IntegerBitSet ➡️ std.bit_set.Integer
std.bit_set.ArrayBitSet ➡️ std.bit_set.Array
std.StaticBitset, std.bit_set.StaticBitSet ➡️ std.bit_set.Static
std.DynamicBitSetUnmanaged, std.bit_set.DynamicBitSetUnmanaged ➡️ std.bit_set.Dynamic
std.DynamicBitSet, std.bit_set.DynamicBitSet ➡️ std.bit_set.DynamicManaged (deprecated)
Struct-Of-Arrays Style for std.lang.Type
When doing type reflection, structs and unions return their information in struct-of-arrays style (#35234).
--- a/lib/compiler/Maker/ScannedConfig.zig
+++ b/lib/compiler/Maker/ScannedConfig.zig
@@ -49,9 +49,10 @@ pub fn print(sc: *const ScannedConfig, w: *Writer) Writer.Error!void {
}
fn printStruct(sc: *const ScannedConfig, s: *Serializer.Struct, comptime S: type, v: S) !void {
- inline for (@typeInfo(S).@"struct".fields) |field| {
- try s.fieldPrefix(field.name);
- try printValue(sc, s.container.serializer, field.type, @field(v, field.name));
+ const info = @typeInfo(S).@"struct";
+ inline for (info.field_names, info.field_types) |field_name, field_type| {
+ try s.fieldPrefix(field_name);
+ try printValue(sc, s.container.serializer, field_type, @field(v, field_name));
}
}
Rename lang.OptimizeMode to lang.Optimize
And remove "release" from the enum tag names.
No functional change, however, despite the addition of backwards-compatibile declarations in this patch, it is breaking because expressions that use == or != operators will not able to use the deprecated names.
std.lang: OptimizeMode ➡️ Optimize
Debug ➡️ debug
ReleaseSafe ➡️ safe
ReleaseFast ➡️ fast
ReleaseSmall ➡️ small
lang.Optimize.runtimeSafety
std.lang.Optimize.runtimeSafety is preferred as an alternative to std.debug.runtime_safety since it will offer callsites knowledge about their own module rather than standard library module.
@import("builtin") Deprecations
The redundant constants cpu, os, abi, and object_format in @import("builtin") have been deprecated and will be removed in 0.18.0. Please replace any usage with the corresponding fields on the target constant:
@import("builtin").cpu ➡️ @import("builtin").target.cpu
@import("builtin").os ➡️ @import("builtin").target.os
@import("builtin").abi ➡️ @import("builtin").target.abi
@import("builtin").object_format ➡️ @import("builtin").target.ofmt
Handle Floats Correctly in mem.eql and mem.findDiff
The functions std.mem.eql and std.mem.findDiff short-circuit when their two inputs are slices to the same memory. This short-circuiting is only correct when the == operator, for the given type, is reflexive. This isn't the case for floats, as for example std.math.nan(f64) != std.math.nan(f64). The change in this PR disables that optimisation when working on float slices.
Previously-failing, now-succeeding tests:
const x: [3]f64 = .{ 42.0, std.math.nan(f64), 3.1415 };
try std.testing.expect(!std.mem.eql(f64, &x, &x));
try std.testing.expectEqual(1, std.mem.findDiff(f64, &x, &x));
Decouple Uri and net.HostName
Uri was sometimes using HostName.validate for host (in resolveInPlace) and sometimes not (in parseAfterScheme). On its own, this was a problem, but the bigger problem is that RFC3986 (Uri) has a much different idea of what a valid host name is than RFC1123 (HostName), and so just making Uri consistently use HostName.validate would make Uri less useful overall.
Instead, all HostName-related stuff has been removed from Uri. Uri.getHost has been moved to HostName.fromUri (without a graceful deprecation, since the semantics are different enough for users to need to evaluate usage sites), while Uri.getHostAlloc has been removed entirely.
Migration guide:
var host_buf: [HostName.max_len]u8 = undefined;
const host = try uri.getHost(&host_buf);
⬇️
var host_buf: [HostName.max_len]u8 = undefined;
// note: the error set is different than it was before since fromUri does validation
const host = try HostName.fromUri(uri, &host_buf);
#36036
Build System
b.build_root (Directory) ➡️ b.root (Path)
ConfigHeader.Options: include_guard_override ➡️ include_guard
LazyPath: getDisplayName ➡️ format ("{f}")
LazyPath.basename: removed since the value is not known until make phase
b.findProgram divided into findProgram and findProgramLazy and API future-proofed.
ConfigHeader fixed; now reports unused values for all styles
addArtifactArg, addPrefixedArtifactArg ➡️ addArtifactArg2
addOutputFileArg, addPrefixedOutputFileArg ➡️ addOutputFileArg2
addFileContentArg, addPrefixedFileContentArg ➡️ addFileContentArg2
addOutputDirectoryArg, addPrefixedOutputDirectoryArg ➡️ addOutputDirectoryArg2
addDirectoryArg, addPrefixedDirectoryArg, addDecoratedDirectoryArg ➡️ addDirectoryArg2
addDepFileOutputArg, addPrefixedDepFileOutputArg ➡️ addDepFileOutputArg2
addFileArg, addPrefixedFileArg ➡️ addFileArg2
Separate the Maker Process from the Configurer Process
zig build now runs projects' build.zig code in a separate executable than the one that performs Package Management and executes the build graph, making zig build faster for several reasons (#35428):
- The
maker executable remains unmodified when build.zig script is edited, and therefore only needs to be built exactly once ("first time setup") after installing Zig.
- The
maker executable is built with optimizations enabled, which is starting to become more valuable now that we have introduced --watch and --fuzz.
build.zig logic can be skipped sometimes depending on what CLI flags are used with zig build.
Furthermore, configuration is now serialized into a compact binary format that can be consumed by third party tooling and is part of the new Build Server Protocol. The prior way of satisfying this use case by forking the build runner is no longer supported.
To render configuration as .zon to stdout, pass --print-configuration.
Cache System Reworked
New features:
- Directory support. Ability for entries added, removed, or renamed in directories to cause a cache miss.
- Metadata mode. Normally, only changed contents causes a cache miss. In metadata mode, when size, inode, or mtime changes, it always causes a cache miss independent of contents.
All four combinations are possible (is_directory=true/false, metadata_mode=true/false). These features are exposed as new API in the Build System.
Since the Zig toolchain is heavily reliant on the caching system, this release also switches to a binary format, saving roughly 25% on file size, which eases a bit of pressure on the file system cache while also simplifying the work the computer needs to do - directly copy bytes from disk rather than parsing text files. The new zig cache-cat subcommand is available for troubleshooting or tinkering with files inside a zig-cache directory.
The cache system also now has the capability to explain why a "miss" happened. The public-facing API of std.Build.Cache has many breaking changes, but outside of compiler tooling, this is an uncommon API to be used, and all the changes make it harder to misuse.
This change has been observed to speed up cache hits by 5-10% (#36822).
Introduce the Concept of Configure Cache Poisoning
If the cache is poisoned means that the configure logic had side effects, or otherwise did something that could not be tracked by the cache system.
This is not to be confused with whether individual steps may have side effects when being evaluated; it has to do with the logic inside build.zig itself. For example, a Run step that prints "hello world" has side effects at make time and therefore does not warrant setting this flag, while checking for the existence of scdoc at configure time in order to choose the default value for a configuration option does.
Keeping the cache pure will make zig build faster, bypassing the configurer process when identical configuration would be generated.
When the cache is poisoned, the maker process will delete the build configuration file upon ingesting it since it cannot be reused.
Ways to poison the cache include calling findProgram, or more directly std.Build.Graph.poisonCache. A better alternative than cache poisoning is to explicitly declare the configuration dependencies with these new functions:
std.Build.dependOnFileContents - indicates that the build.zig logic depends on a particular file's contents.
std.Build.dependOnFileMetadata - indicates that the build.zig logic depends on a particular file's size, inode, mtime, and contents.
std.Build.dependOnDirectoryContents - indicates that the build.zig logic depends on a particular directory's entries.
std.Build.dependOnDirectoryMetadata - indicates that the build.zig logic depends on a particular directory's last modification date.
Advanced users can override the cache poisoning behavior with a new CLI option:
--cache-poison[=mode] Override configuration caching behavior
pure (default) Avoid false positive cache hits
poisoned Don't cache the configuration
disallowed Panics when cache would be poisoned
ignored A little poison never hurt anybody
findProgram
Immediately (in the configure phase), searches for an executable on the host that has more than one possible name.
Names are searched in order, observing search prefixes first and then PATH environment variable.
Calling this function poisons the configuration cache, so it is only appropriate when the existence of the program or its output needs to be observed by configuration logic. That's why there is also findProgramLazy now.
findProgramLazy
Creates an anonymous Step that searches for an executable on the host that has more than one possible name.
Unlike findProgram, this function does not poison the configuration cache, however the result cannot be used in the configuration phase, hence the return type being LazyPath.
Returns the LazyPath of the found executable. The search only takes place if the LazyPath will be used by a depending Step.
This API is useful in the following cases:
- The binary is not named the same across all systems (for example "python" vs "python3").
- The binary may be produced by building from source rather than being globally installed and will therefore be possibly found in one of the search prefix paths.
Run Step: Passthru Args
In the Run step, passthru args are all together now, not observable in configure phase whether run args are provided.
--- build.zig
+++ build.zig
@@
-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.
Fmt Step: Options
paths and exclude_paths are now LazyPath lists. There is a convenience method to create them: b.pathList.
--- build.zig
+++ build.zig
@@
- const fmt_include_paths = &.{ "lib", "src", "test", "tools", "build.zig", "build.zig.zon" };
- const fmt_exclude_paths = &.{ "test/cases", "test/behavior/zon" };
+ const fmt_include_paths = b.pathList(&.{ "lib", "src", "test", "tools", "build.zig", "build.zig.zon" });
+ const fmt_exclude_paths = b.pathList(&.{ "test/cases", "test/behavior/zon" });
Step.Options: add addOptionPathDirectory
Now, when adding an option that is a file path, one must explicitly choose between (#36876):
addOptionPath (must be a file)
addOptionPathDirectory (must be a directory)
addOptionPathUntracked (opt out of dependency tracking)
Lazy Dependency Ergonomic Enhancements
- Log when lazy dependencies are fetched.
std.Build.dependency: support lazy dependencies
- Introduce
std.Build.dependencyLazy which possibly returns error.LazyDependencyNeeded instead of null, so that you can use try
- When user
build functions return error.LazyDependencyNeeded, build system proceeds to fetch them rather than failing configuration.
Removed Ability to Override Build Runner
There is no concept of a "build runner" any more; it has been split into: configurer and maker
This use case is now handled by the Build Server Protocol.
Package Management
All package management functionality has been moved out of the Compiler and into the Build System. This includes the following sub-commands:
zig build
zig fetch
zig init
zig libc
zig cache-cat
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
All of this functionality is now compiled in -Osafe optimization mode rather than -Ofast due to being in the compiler. When hacking on the build system itself, the environment variable ZIG_DEBUG_CMD=1 may be used to compile the build system in debug mode instead.
Miscellaneous changes:
- Bug fix: reject path deps that escape the parent package root.
Ability to Override Package Path
--pkg-path CLI arg and ZIG_LOCAL_PKG_DIR env var are now observed for both fetch and build commands.
Global vs Local Fetching
Now zig fetch only fetches into the global cache, just like it used to. However, if --save (or any variant) is used, then it also fetches into the local package path. When fetching globally, does not require build.zig to be present. zig build always fetches locally (in addition to globally).
Notably, this fixes the regressed use case zig fetch .
When fetching by path, the hash is always computed, recompressed tarball is always created, always overwrites any existing global cache entry.
Slight Difference in PATH for DLL Arguments
It used to be the case that, when targeting Windows or Wine, artifact args added to Run steps modified PATH based on the set of directories containing the recursive set of DLL dependencies. Now this is only done for argv[0]. The motivation for also doing this for the other command line arguments is unclear, since those DLLs don't need to be loaded in order to execute argv[0].
Build Server Protocol
Now, when --listen=- is passed, the build system serves a protocol that allows connected clients to monitor and control the build graph as it executes. This is intended to be consumed by third-party tooling such as IDEs.
Current things you can do:
- Get full access to the entire build graph's static, post-configuration information, such as which build steps are available, which options are set, dependencies, etc. There are a couple things yet to be included, such as the exposed set of module names.
- Get notified when a build step starts and completes, including information about errors and which files were generated.
- Request specific steps to build.
In particular, the separation of maker process and configurer process is a breaking change that prevents the ZLS project from working with 0.17.0. Although some progress was made to restore functionality in this release cycle, Zig team and ZLS team are still working together to enhance the build server protocol further to the point that ZLS can not only restore functionality, but surpass the power and capabilities compared to before.
In the future it is expected for much of Zig's own first-party build system tooling to become a client of the build server protocol, dogfooding it to ensure that third-party tooling enjoys equivalent capabilities (#36497).
It is also planned for the build server to multiplex compiler server protocol for the compilation steps, providing type-system information, refactoring, and other advanced editing capabilities (#615).
Compiler
Incremental Compilation
The Zig compiler's implementation of incremental compilation—a feature allowing near-instant rebuilds of projects after changing the code—has been significantly improved in Zig 0.17.0. Many bugs have been fixed, and the new ELF Linker introduced in the previous release has gained good support for the feature.
Thanks to these enhancements, it is now possible for most projects targeting x86_64-linux to take advantage of incremental compilation. To do so, add the arguments -fincremental --watch to your zig build command (e.g. zig build -fincremental --watch)—this will cause the Zig build system to listen for changes to source files, and react to them by performing an incremental rebuild.
For more information on ways to use incremental compilation in your own projects, or to learn more about how this feature works under the hood, consider checking out this blog post by a Zig core team member.
Future releases will continue to focus on improving this feature, including introducing a new Mach-O linker and self-hosted aarch64 Backend with good support for incremental compilation; adding support for using incremental compilation without --watch; and fixing any remaining bugs.
SPIR-V Backend
The self-hosted SPIR-V backend is now multi-threaded like the other backends.
Execution modes such as LocalSize and OriginUpperLeft are now derived from the function's calling convention instead of being set through inline assembly, and the new spirv_task and spirv_mesh calling conventions add support for task and mesh shaders (#35676).
Declaring capabilities and extensions in inline assembly with OpCapability and OpExtension is no longer allowed. They are enabled through target CPU features instead, i.e. the -mcpu option.
22 bugs were fixed in the SPIR-V backend during this release cycle.
aarch64 Backend
Progress towards this is blocked on Linker enhancements, many of which were completed during this release cycle.
loongarch Backend
Initial implementation of self-hosted backend for loongarch64 has been contributed (#36418). It is still experimental and not yet usable. There are two ways to contribute to this backend: working on it directly, and contributing to AIR Legalization Features, which helps all unfinished backends reach the finish line quicker.
WebAssembly Backend
Zig's WebAssembly backend is now passing 2060/2054 (100%) behavior tests compared to the LLVM backend. However, it is not yet the default when compiling in debug optimization mode due to lack of debug info support (#37032).
Linker
ELF
This release makes significant progress towards replacing Zig's legacy self-hosted ELF linker with its new implementation introduced in the previous release. Specific enhancements include:
- Full x86_64 support
- Full SPARC64 support
- Partial Loongarch support
- Static library generation
- Shared library generation
- Errors for undefined symbols in executables
- GOT generation
- Copy relocations
- GNU symbol versioning
- DWARF debug information
- Symbol hash table generation
- Mostly-reproducible binaries
- Arbitrary section alignment
- Support for small host file system block sizes
While this linker has not quite reached feature parity with our old self-hosted ELF linker yet—and so remains disabled by default—it is already capable in practice of building the vast majority of Zig projects targeting x86_64-linux. This unlocks the ability to use Incremental Compilation for these projects—like in Zig 0.16.0, the new linker is enabled by default in this case.
In the next release of Zig, we hope to fully eliminate the legacy ELF linker in favour of this implementation.
COFF
COFF support in