From ba4aa12098a0a9def52582cecd5b0b664ded14d8 Mon Sep 17 00:00:00 2001 From: Veikka Tuominen Date: Mon, 3 Oct 2022 14:12:08 +0300 Subject: [PATCH] Sema: use correct value when `@ptrCast` operand is comptime known Closes #13034 --- src/Sema.zig | 2 +- test/behavior/pointers.zig | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/Sema.zig b/src/Sema.zig index 109b6f2a22ea..eb228c824ede 100644 --- a/src/Sema.zig +++ b/src/Sema.zig @@ -18352,7 +18352,7 @@ fn zirPtrCast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air return sema.failWithOwnedErrorMsg(msg); } - if (try sema.resolveMaybeUndefVal(block, operand_src, operand)) |operand_val| { + if (try sema.resolveMaybeUndefVal(block, operand_src, ptr)) |operand_val| { if (!dest_ty.ptrAllowsZero() and operand_val.isUndef()) { return sema.failWithUseOfUndef(block, operand_src); } diff --git a/test/behavior/pointers.zig b/test/behavior/pointers.zig index 91d398e84dbb..b0fb0f3a4239 100644 --- a/test/behavior/pointers.zig +++ b/test/behavior/pointers.zig @@ -483,3 +483,14 @@ test "pointer to constant decl preserves alignment" { const alignment = @typeInfo(@TypeOf(&S.aligned)).Pointer.alignment; try std.testing.expect(alignment == 8); } + +test "ptrCast comptime known slice to C pointer" { + if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO + if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO + if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO + if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO + + const s: [:0]const u8 = "foo"; + var p = @ptrCast([*c]const u8, s); + try std.testing.expectEqualStrings(s, std.mem.sliceTo(p, 0)); +}