Commit 6a5463951f

mlugg <mlugg@mlugg.co.uk>
2023-08-21 03:07:40
Sema: disallow C pointer to slice coercion
Resolves: #16719
1 parent 82c8e45
Changed files (2)
src
test
cases
src/Sema.zig
@@ -27289,6 +27289,7 @@ fn coerceExtra(
 
             // coercion from C pointer
             if (inst_ty.isCPtr(mod)) src_c_ptr: {
+                if (dest_info.flags.size == .Slice) break :src_c_ptr;
                 if (!sema.checkPtrAttributes(dest_ty, inst_ty, &in_memory_result)) break :src_c_ptr;
                 // In this case we must add a safety check because the C pointer
                 // could be null.
test/cases/compile_errors/ptr_coerced_to_slice.zig
@@ -0,0 +1,20 @@
+export fn foo() void {
+    const ptr: [*]const u8 = "abc";
+    _ = @as([]const u8, ptr);
+}
+export fn bar() void {
+    const ptr: [*c]const u8 = "def";
+    _ = @as([]const u8, ptr);
+}
+export fn baz() void {
+    const ptr: *const u8 = &@as(u8, 123);
+    _ = @as([]const u8, ptr);
+}
+
+// error
+// backend=stage2
+// target=native
+//
+// :3:25: error: expected type '[]const u8', found '[*]const u8'
+// :7:25: error: expected type '[]const u8', found '[*c]const u8'
+// :11:25: error: expected type '[]const u8', found '*const u8'