zig icon indicating copy to clipboard operation
zig copied to clipboard

docs: `@shlExact`, `@shrExact` cause illegal behavior on shifted-out bits

Open rohlem opened this issue 1 year ago • 0 comments

Zig Version

0.12.0-dev.3667+77abd3a96, 0.12.0-dev.3182+f3227598e

Steps to Reproduce and Observed Behavior

The langref currently specifies that "the result [of @shlExact may be] undefined". I thought that was unusual for Zig, and indeed the truth seems to be that it's illegal behavior: A compile error at comptime, and a panic with runtime safety at runtime.

We could also explicitly clarify that it's illegal behavior for @shrExact, which currently just states the "[c]aller guarantees" it doesn't happen.

Reproduction:

var a: u2 = 3;
test {
    _ = @shlExact(@as(u2, 3), 1); //comptime-evaluated
    _ = @shlExact(a, 1);
}
test {
    _ = @shrExact(@as(u2, 3), 1); //comptime-evaluated
    _ = @shrExact(a, 1);
}
zig test .\main.zig
main.zig:3:9: error: operation caused overflow
    _ = @shlExact(@as(u2, 3), 1); //comptime-evaluated
        ^~~~~~~~~~~~~~~~~~~~~~~~
main.zig:7:9: error: exact shift shifted out 1 bits
    _ = @shrExact(@as(u2, 3), 1); //comptime-evaluated
        ^~~~~~~~~~~~~~~~~~~~~~~~

(when commented out)

Test [1/2] main.test_0... thread 12736 panic: left shift overflowed bits
C:\data\Development\rohlem\era-5\tmp\shl,rExact\main.zig:4:5: 0x4a1050 in test_0 (test.exe.obj)
    _ = @shlExact(a, 1);
    ^
(...)

Test [2/2] main.test_1... thread 22200 panic: right shift overflowed bits
C:\data\Development\rohlem\era-5\tmp\shl,rExact\main.zig:8:5: 0xc8104c in test_1 (test.exe.obj)
    _ = @shrExact(a, 1);
    ^
(...)

Expected Behavior

Expected langref to match status-quo behavior.

Also we should imo clean up the compile errors: The runtime panics specify the shift direction, whereas comptime @shrExact doesn't, and comptime @shlExact gives a generic overflow message.

rohlem avatar Apr 17 '24 20:04 rohlem