motiejus/zig

fork of https://codeberg.org/ziglang/zig
git clone https://git.jakstys.lt/motiejus/zig.git
Log | Tree | Refs | README | LICENSE

commit 4ec299007a6a183edddfcb0505a9c1501da7ad0c (tree)
parent 68c7261e1daf7787dcbf0cd6f9b01e5678d20a93
Author: mlugg <mlugg@mlugg.co.uk>
Date:   Thu, 16 Mar 2023 17:51:31 +0000

Sema: allow dereferencing ill-defined pointers to zero-bit types at comptime

It doesn't matter if a pointer to a zero-bit (i.e. OPV) type is
undefined or runtime-known; we still know the result of the dereference
at comptime. Code may use this, for instance, when allocating zero-bit
types: `@as(*void, undefined)` is entirely reasonable to use at runtime,
since we know the pointer will never be accessed, thus it should be
valid at comptime too.

Diffstat:
Msrc/Sema.zig | 5+++++
Mtest/behavior/comptime_memory.zig | 8++++++++
2 files changed, 13 insertions(+), 0 deletions(-)

diff --git a/src/Sema.zig b/src/Sema.zig @@ -4712,6 +4712,11 @@ fn zirValidateDeref(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErr .Slice => return sema.fail(block, src, "index syntax required for slice type '{}'", .{operand_ty.fmt(sema.mod)}), } + if ((try sema.typeHasOnePossibleValue(operand_ty.childType())) != null) { + // No need to validate the actual pointer value, we don't need it! + return; + } + const elem_ty = operand_ty.elemType2(); if (try sema.resolveMaybeUndefVal(operand)) |val| { if (val.isUndef()) { diff --git a/test/behavior/comptime_memory.zig b/test/behavior/comptime_memory.zig @@ -420,3 +420,11 @@ test "mutate entire slice at comptime" { buf[1..3].* = x; } } + +test "dereference undefined pointer to zero-bit type" { + const p0: *void = undefined; + try testing.expectEqual({}, p0.*); + + const p1: *[0]u32 = undefined; + try testing.expect(p1.*.len == 0); +}