From 6bba7c702b4482c33c1de7414fb145d0dfc40fcc Mon Sep 17 00:00:00 2001 From: Vexu Date: Sat, 1 Aug 2020 22:46:28 +0300 Subject: [PATCH] add compile error for alignCasting zero sized types --- src/ir.cpp | 13 +++++++++++++ test/compile_errors.zig | 26 ++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/src/ir.cpp b/src/ir.cpp index 15c4e9ec55..3aadc2557e 100644 --- a/src/ir.cpp +++ b/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))) diff --git a/test/compile_errors.zig b/test/compile_errors.zig index 9b836ac45a..6b231a323d 100644 --- a/test/compile_errors.zig +++ b/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 = .{