Commit 6bba7c702b

Vexu <git@vexu.eu>
2020-08-01 21:46:28
add compile error for alignCasting zero sized types
1 parent 35391f1
Changed files (2)
src/ir.cpp
@@ -29098,6 +29098,19 @@ static IrInstGen *ir_align_cast(IrAnalyze *ira, IrInstGen *target, uint32_t alig
     ZigType *result_type;
     uint32_t old_align_bytes;
 
+    ZigType *actual_ptr = target_type;
+    if (actual_ptr->id == ZigTypeIdOptional) {
+        actual_ptr = actual_ptr->data.maybe.child_type;
+    } else if (is_slice(actual_ptr)) {
+        actual_ptr = actual_ptr->data.structure.fields[slice_ptr_index]->type_entry;
+    }
+
+    if (safety_check_on && !type_has_bits(ira->codegen, actual_ptr)) {
+        ir_add_error(ira, &target->base,
+            buf_sprintf("cannot adjust alignment of zero sized type '%s'", buf_ptr(&target_type->name)));
+        return ira->codegen->invalid_inst_gen;
+    }
+
     if (target_type->id == ZigTypeIdPointer) {
         result_type = adjust_ptr_align(ira->codegen, target_type, align_bytes);
         if ((err = resolve_ptr_align(ira, target_type, &old_align_bytes)))
test/compile_errors.zig
@@ -2,6 +2,32 @@ const tests = @import("tests.zig");
 const std = @import("std");
 
 pub fn addCases(cases: *tests.CompileErrorContext) void {
+    cases.addTest("@alignCast of zero sized types",
+        \\export fn foo() void {
+        \\    const a: *void = undefined;
+        \\    _ = @alignCast(2, a);
+        \\}
+        \\export fn bar() void {
+        \\    const a: ?*void = undefined;
+        \\    _ = @alignCast(2, a);
+        \\}
+        \\export fn baz() void {
+        \\    const a: []void = undefined;
+        \\    _ = @alignCast(2, a);
+        \\}
+        \\export fn qux() void {
+        \\    const a = struct {
+        \\        fn a(comptime b: u32) void {}
+        \\    }.a;
+        \\    _ = @alignCast(2, a);
+        \\}
+    , &[_][]const u8{
+        "tmp.zig:3:23: error: cannot adjust alignment of zero sized type '*void'",
+        "tmp.zig:7:23: error: cannot adjust alignment of zero sized type '?*void'",
+        "tmp.zig:11:23: error: cannot adjust alignment of zero sized type '[]void'",
+        "tmp.zig:17:23: error: cannot adjust alignment of zero sized type 'fn(u32) anytype'",
+    });
+
     cases.addTest("invalid pointer with @Type",
         \\export fn entry() void {
         \\    _ = @Type(.{ .Pointer = .{