Skip to content

Commit 490cafe

Browse files
LemonBoyandrewrk
authored andcommitted
stage1: Error out when trying to execute unreachable
Closes #6802
1 parent f4bb8be commit 490cafe

File tree

3 files changed

+22
-2
lines changed

3 files changed

+22
-2
lines changed

doc/langref.html.in

+1-1
Original file line numberDiff line numberDiff line change
@@ -8675,7 +8675,7 @@ test "safety check" {
86758675
{#code_end#}
86768676
{#header_open|Reaching Unreachable Code#}
86778677
<p>At compile-time:</p>
8678-
{#code_begin|test_err|unable to evaluate constant expression#}
8678+
{#code_begin|test_err|reached unreachable code#}
86798679
comptime {
86808680
assert(false);
86818681
}

src/stage1/ir.cpp

+5
Original file line numberDiff line numberDiff line change
@@ -21592,6 +21592,11 @@ static IrInstGen *ir_analyze_instruction_cond_br(IrAnalyze *ira, IrInstSrcCondBr
2159221592
static IrInstGen *ir_analyze_instruction_unreachable(IrAnalyze *ira,
2159321593
IrInstSrcUnreachable *unreachable_instruction)
2159421594
{
21595+
if (ir_should_inline(ira->old_irb.exec, unreachable_instruction->base.base.scope)) {
21596+
ir_add_error(ira, &unreachable_instruction->base.base, buf_sprintf("reached unreachable code"));
21597+
return ir_unreach_error(ira);
21598+
}
21599+
2159521600
IrInstGen *result = ir_build_unreachable_gen(ira, &unreachable_instruction->base.base);
2159621601
return ir_finish_anal(ira, result);
2159721602
}

test/compile_errors.zig

+16-1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,21 @@ const tests = @import("tests.zig");
22
const std = @import("std");
33

44
pub fn addCases(cases: *tests.CompileErrorContext) void {
5+
cases.add("unreachable executed at comptime",
6+
\\fn foo(comptime x: i32) i32 {
7+
\\ comptime {
8+
\\ if (x >= 0) return -x;
9+
\\ unreachable;
10+
\\ }
11+
\\}
12+
\\export fn entry() void {
13+
\\ _ = foo(-42);
14+
\\}
15+
, &[_][]const u8{
16+
"tmp.zig:4:9: error: reached unreachable code",
17+
"tmp.zig:8:12: note: called from here",
18+
});
19+
520
cases.add("indexing a undefined slice at comptime",
621
\\comptime {
722
\\ var slice: []u8 = undefined;
@@ -6208,7 +6223,7 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {
62086223
\\ if (!ok) unreachable;
62096224
\\}
62106225
, &[_][]const u8{
6211-
"tmp.zig:10:14: error: unable to evaluate constant expression",
6226+
"tmp.zig:10:14: error: reached unreachable code",
62126227
"tmp.zig:6:20: note: referenced here",
62136228
});
62146229

0 commit comments

Comments
 (0)