zig

fork of https://codeberg.org/ziglang/zig
Log | Files | Refs | README | LICENSE

commit 09ec720dab6331c8be0300f2943f7d757ad0d7c3 (tree)
parent f7574f44c120dc834ebaf2773dc1ab098a20c232
Author: Andrew Kelley <andrew@ziglang.org>
Date:   Sun, 24 Nov 2019 16:25:26 -0500

fix comptime `@ptrCast` of pointers to arrays

Diffstat:
Msrc/ir.cpp | 25++++++++++++++++++++-----
Mtest/stage1/behavior/pointers.zig | 5++---
2 files changed, 22 insertions(+), 8 deletions(-)

diff --git a/src/ir.cpp b/src/ir.cpp @@ -18585,12 +18585,27 @@ static IrInstruction *ir_analyze_instruction_elem_ptr(IrAnalyze *ira, IrInstruct case ConstPtrSpecialDiscard: zig_unreachable(); case ConstPtrSpecialRef: - mem_size = 1; - old_size = 1; - new_index = index; + if (array_ptr_val->data.x_ptr.data.ref.pointee->type->id == ZigTypeIdArray) { + ConstExprValue *array_val = array_ptr_val->data.x_ptr.data.ref.pointee; + new_index = index; + ZigType *array_type = array_val->type; + mem_size = array_type->data.array.len; + if (array_type->data.array.sentinel != nullptr) { + mem_size += 1; + } + old_size = mem_size; - out_val->data.x_ptr.special = ConstPtrSpecialRef; - out_val->data.x_ptr.data.ref.pointee = array_ptr_val->data.x_ptr.data.ref.pointee; + out_val->data.x_ptr.special = ConstPtrSpecialBaseArray; + out_val->data.x_ptr.data.base_array.array_val = array_val; + out_val->data.x_ptr.data.base_array.elem_index = new_index; + } else { + mem_size = 1; + old_size = 1; + new_index = index; + + out_val->data.x_ptr.special = ConstPtrSpecialRef; + out_val->data.x_ptr.data.ref.pointee = array_ptr_val->data.x_ptr.data.ref.pointee; + } break; case ConstPtrSpecialBaseArray: { diff --git a/test/stage1/behavior/pointers.zig b/test/stage1/behavior/pointers.zig @@ -204,13 +204,12 @@ test "assign null directly to C pointer and test null equality" { test "null terminated pointer" { const S = struct { fn doTheTest() void { - var array_with_zero = [_]u8{'h', 'e', 'l', 'l', 'o', 0}; + var array_with_zero = [_:0]u8{'h', 'e', 'l', 'l', 'o'}; var zero_ptr: [*:0]const u8 = @ptrCast([*:0]const u8, &array_with_zero); var no_zero_ptr: [*]const u8 = zero_ptr; expect(std.mem.eql(u8, std.mem.toSliceConst(u8, no_zero_ptr), "hello")); } }; S.doTheTest(); - // TODO test fails at comptime - //comptime S.doTheTest(); + comptime S.doTheTest(); }