unreachable
In Debug
and ReleaseSafe
mode, and when using zig test
, unreachable
emits a call to panic
with the message reached unreachable code
.
In ReleaseFast
mode, the optimizer uses the assumption that unreachable
code will never be hit to perform optimizations. However, zig test
even in ReleaseFast
mode still emits unreachable
as calls to panic
.
Basics
test.zig
// unreachable is used to assert that control flow will never happen upon a
// particular location:
test "basic math" {
const x = 1;
const y = 2;
if (x + y != 3) {
unreachable;
}
}
$ zig test test.zig
Test 1/1 basic math...OK
All tests passed.
In fact, this is how assert is implemented:
test.zig
fn assert(ok: bool) void {
if (!ok) unreachable; // assertion failure
}
// This test will fail because we hit unreachable.
test "this will fail" {
assert(false);
}
$ zig test test.zig
Test 1/1 this will fail...reached unreachable code
/home/andy/dev/zig/docgen_tmp/test.zig:2:14: 0x20424c in ??? (test)
if (!ok) unreachable; // assertion failure
^
/home/andy/dev/zig/docgen_tmp/test.zig:7:11: 0x2040cb in ??? (test)
assert(false);
^
/home/andy/dev/zig/build/lib/zig/std/special/test_runner.zig:13:25: 0x225beb in ??? (test)
if (test_fn.func()) |_| {
^
/home/andy/dev/zig/build/lib/zig/std/special/bootstrap.zig:122:22: 0x225376 in ??? (test)
root.main() catch |err| {
^
/home/andy/dev/zig/build/lib/zig/std/special/bootstrap.zig:43:5: 0x2250e1 in ??? (test)
@noInlineCall(posixCallMainAndExit);
^
Tests failed. Use the following command to reproduce the failure:
/home/andy/dev/zig/docgen_tmp/test
At Compile-Time
test.zig
const assert = @import("std").debug.assert;
test "type of unreachable" {
comptime {
// The type of unreachable is noreturn.
// However this assertion will still fail because
// evaluating unreachable at compile-time is a compile error.
assert(@typeOf(unreachable) == noreturn);
}
}
$ zig test test.zig
/home/andy/dev/zig/docgen_tmp/test.zig:10:16: error: unreachable code
assert(@typeOf(unreachable) == noreturn);
^
See also: