From 51ef31a8331e92103253a37ddfdacbd263cee81d Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Mon, 4 Apr 2022 14:28:30 -0700 Subject: [PATCH] Sema: add empty tuple to mutable slice coercion --- src/Sema.zig | 13 +++++++++++++ test/behavior/cast.zig | 5 +++++ 2 files changed, 18 insertions(+) diff --git a/src/Sema.zig b/src/Sema.zig index 65550bec00dd944b6de26741a7362ac21a8cc24c..1430e80ac046c00d8e72fdfe61f6fd0d31ac7b83 100644 --- a/src/Sema.zig +++ b/src/Sema.zig @@ -18166,6 +18166,19 @@ fn coerce( { return sema.coerceTupleToSlicePtrs(block, dest_ty, dest_ty_src, inst, inst_src); } + + // empty tuple to zero-length slice + // note that this allows coercing to a mutable slice. + if (inst_ty.isSinglePointer() and + inst_ty.childType().tag() == .empty_struct_literal and + dest_info.size == .Slice) + { + const slice_val = try Value.Tag.slice.create(sema.arena, .{ + .ptr = Value.undef, + .len = Value.zero, + }); + return sema.addConstant(dest_ty, slice_val); + } }, .Many => p: { if (!inst_ty.isSlice()) break :p; diff --git a/test/behavior/cast.zig b/test/behavior/cast.zig index 4e952828c58d9fad598de500210fdd32a2d05318..0473a3603388b9e96b5d6184b2a00a8804b9dbf6 100644 --- a/test/behavior/cast.zig +++ b/test/behavior/cast.zig @@ -1386,3 +1386,8 @@ test "coerce undefined single-item pointer of array to error union of slice" { const s = try b; try expect(s.len == 0); } + +test "pointer to empty struct literal to mutable slice" { + var x: []i32 = &.{}; + try expect(x.len == 0); +} -- 2.54.0