unreachable
在 debug 和 safe 模式下,unreachable 会生成对 panic 的调用,并传入消息 reached unreachable code。
在 fast 和 small 模式下,优化器会利用永远不会执行到 unreachable 代码这一假设进行优化。
基础
// unreachable 用于断言控制流永远不会到达
// 某个特定位置:
test "basic math" {
const x = 1;
const y = 2;
if (x + y != 3) {
unreachable;
}
}$ zig test test_unreachable.zig
1/1 test_unreachable.test.basic math...OK
All 1 tests passed.
实际上,std.debug.assert 就是这样实现的:
// std.debug.assert 就是这样实现的
fn assert(ok: bool) void {
if (!ok) unreachable; // 断言失败
}
// 此测试会失败,因为执行到了 unreachable。
test "this will fail" {
assert(false);
}$ zig test test_assertion_failure.zig
1/1 test_assertion_failure.test.this will fail...thread 471146 panic: reached unreachable code
/home/alexrp/Sources/ziglang/zig/doc/langref/test_assertion_failure.zig:3:14: 0x124e989 in assert (test_assertion_failure.zig)
if (!ok) unreachable; // assertion failure
^
/home/alexrp/Sources/ziglang/zig/doc/langref/test_assertion_failure.zig:8:11: 0x124e95e in test.this will fail (test_assertion_failure.zig)
assert(false);
^
/home/alexrp/.cache/zig/p/N-V-__8AALBXTRYsilzupvrmv0afm7ohtj5Mj0paqVfKLmfP/lib/compiler/test_runner.zig:295:25: 0x1202c41 in mainTerminal (test_runner.zig)
if (test_fn.func()) |_| {
^
/home/alexrp/.cache/zig/p/N-V-__8AALBXTRYsilzupvrmv0afm7ohtj5Mj0paqVfKLmfP/lib/compiler/test_runner.zig:74:28: 0x1202422 in main (test_runner.zig)
return mainTerminal(init);
^
/home/alexrp/.cache/zig/p/N-V-__8AALBXTRYsilzupvrmv0afm7ohtj5Mj0paqVfKLmfP/lib/std/start.zig:789:88: 0x11febbf in callMain (std.zig)
if (fn_info.param_types[0].? == std.process.Init.Minimal) return wrapMain(root.main(.{
^
/home/alexrp/.cache/zig/p/N-V-__8AALBXTRYsilzupvrmv0afm7ohtj5Mj0paqVfKLmfP/lib/std/start.zig:248:5: 0x11fe5a1 in _start (std.zig)
asm volatile (switch (native_arch) {
^
error: the following test command terminated with signal ABRT:
/home/alexrp/Sources/ziglang/zig/.zig-cache/o/a13112c1fe2007cebe044e6075fbf8aa/test --seed=0x578a2438
编译时
const assert = @import("std").debug.assert;
test "type of unreachable" {
comptime {
// unreachable 的类型是 noreturn。
// 但这个断言仍然无法编译,因为
// 编译时执行 unreachable 表达式会产生编译错误。
assert(@TypeOf(unreachable) == noreturn);
}
}$ zig test test_comptime_unreachable.zig
/home/alexrp/Sources/ziglang/zig/doc/langref/test_comptime_unreachable.zig:10:16: error: unreachable code
assert(@TypeOf(unreachable) == noreturn);
^~~~~~~~~~~~~~~~~~~~
/home/alexrp/Sources/ziglang/zig/doc/langref/test_comptime_unreachable.zig:10:24: note: control flow is diverted here
assert(@TypeOf(unreachable) == noreturn);
^~~~~~~~~~~
另见: