Commit 51ef31a833

Andrew Kelley <andrew@ziglang.org>
2022-04-04 23:28:30
Sema: add empty tuple to mutable slice coercion
1 parent b4bf3bd
Changed files (2)
src
test
behavior
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;
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);
+}