authorgravatar for mlugg@mlugg.co.ukMatthew Lugg <mlugg@mlugg.co.uk> 2025-01-22 04:16:16+00:00
committergravatar for mlugg@mlugg.co.ukMatthew Lugg <mlugg@mlugg.co.uk> 2025-01-22 04:18:43+00:00
loge864c38cc38095a1496229803465fdd0d079f9c3
tree1912a3efcf6a8fe67c36d960a980d7ad87ecd6c4
parent8470b6ea37a82330be2c5ab41460fe58b8cfd4f6
signaturelock-open Commit is signed but in an unrecognized format.

Sema: fix crash when `inline` loop condition is not comptime-known


3 files changed, 26 insertions(+), 1 deletions(-)

lib/std/zig.zig+2
......@@ -788,6 +788,7 @@ pub const SimpleComptimeReason = enum(u32) {
788788 // Miscellaneous reasons.
789789 comptime_keyword,
790790 comptime_call_modifier,
791 inline_loop_operand,
791792 switch_item,
792793 tuple_field_default_value,
793794 struct_field_default_value,
......@@ -863,6 +864,7 @@ pub const SimpleComptimeReason = enum(u32) {
863864
864865 .comptime_keyword => "'comptime' keyword forces comptime evaluation",
865866 .comptime_call_modifier => "'.compile_time' call modifier forces comptime evaluation",
867 .inline_loop_operand => "inline loop condition must be comptime-known",
866868 .switch_item => "switch prong values must be comptime-known",
867869 .tuple_field_default_value => "tuple field default value must be comptime-known",
868870 .struct_field_default_value => "struct field default value must be comptime-known",
src/Sema.zig+8-1
......@@ -1824,7 +1824,14 @@ fn analyzeBodyInner(
18241824 );
18251825 const uncasted_cond = try sema.resolveInst(extra.data.condition);
18261826 const cond = try sema.coerce(block, Type.bool, uncasted_cond, cond_src);
1827 const cond_val = try sema.resolveConstDefinedValue(block, cond_src, cond, null);
1827 const cond_val = try sema.resolveConstDefinedValue(
1828 block,
1829 cond_src,
1830 cond,
1831 // If this block is comptime, it's more helpful to just give the outer message.
1832 // This is particularly true if this came from a comptime `condbr` above.
1833 if (block.isComptime()) null else .{ .simple = .inline_loop_operand },
1834 );
18281835 const inline_body = if (cond_val.toBool()) then_body else else_body;
18291836
18301837 try sema.maybeErrorUnwrapCondbr(block, inline_body, extra.data.condition, cond_src);
test/cases/compile_errors/runtime_condition_in_inline_loop.zig created+16
......@@ -0,0 +1,16 @@
1var rt_slice: []const u8 = &.{ 1, 2, 3 };
2
3export fn foo() void {
4 inline for (rt_slice) |_| {}
5}
6
7export fn bar() void {
8 inline while (rt_slice.len == 0) {}
9}
10
11// error
12//
13// :4:17: error: unable to resolve comptime value
14// :4:17: note: inline loop condition must be comptime-known
15// :8:32: error: unable to resolve comptime value
16// :8:32: note: inline loop condition must be comptime-known