From b46efcde82436e73c73dab132f73aeff98673894 Mon Sep 17 00:00:00 2001 From: LemonBoy Date: Tue, 25 Feb 2020 12:22:21 +0100 Subject: [PATCH] ir: Fix sizeOf comparison with ptr to zst Closes #4536 --- src/analyze.cpp | 5 ++-- test/stage1/behavior/sizeof_and_typeof.zig | 34 ++++++++++++++++++++-- 2 files changed, 34 insertions(+), 5 deletions(-) diff --git a/src/analyze.cpp b/src/analyze.cpp index 95b2c7712..5ee5f4464 100644 --- a/src/analyze.cpp +++ b/src/analyze.cpp @@ -1132,10 +1132,9 @@ Error type_val_resolve_zero_bits(CodeGen *g, ZigValue *type_val, ZigType *parent if (type_val->special != ConstValSpecialLazy) { assert(type_val->special == ConstValSpecialStatic); if ((type_val->data.x_type->id == ZigTypeIdStruct && - type_val->data.x_type->data.structure.resolve_loop_flag_zero_bits) || + type_val->data.x_type->data.structure.resolve_loop_flag_zero_bits) || (type_val->data.x_type->id == ZigTypeIdUnion && - type_val->data.x_type->data.unionation.resolve_loop_flag_zero_bits) || - type_val->data.x_type->id == ZigTypeIdPointer) + type_val->data.x_type->data.unionation.resolve_loop_flag_zero_bits)) { // Does a struct/union which contains a pointer field to itself have bits? Yes. *is_zero_bits = false; diff --git a/test/stage1/behavior/sizeof_and_typeof.zig b/test/stage1/behavior/sizeof_and_typeof.zig index a738dbbbf..e3b62b15c 100644 --- a/test/stage1/behavior/sizeof_and_typeof.zig +++ b/test/stage1/behavior/sizeof_and_typeof.zig @@ -1,5 +1,7 @@ -const builtin = @import("builtin"); -const expect = @import("std").testing.expect; +const std = @import("std"); +const builtin = std.builtin; +const expect = std.testing.expect; +const expectEqual = std.testing.expectEqual; test "@sizeOf and @TypeOf" { const y: @TypeOf(x) = 120; @@ -135,3 +137,31 @@ test "@bitSizeOf" { a: u2 }) == 2); } + +test "@sizeOf comparison against zero" { + const S0 = struct { + f: *@This(), + }; + const U0 = union { + f: *@This(), + }; + const S = struct { + fn doTheTest(comptime T: type, comptime result: bool) void { + expectEqual(result, @sizeOf(T) > 0); + } + }; + // Zero-sized type + S.doTheTest(u0, false); + S.doTheTest(*u0, false); + // Non byte-sized type + S.doTheTest(u1, true); + S.doTheTest(*u1, true); + // Regular type + S.doTheTest(u8, true); + S.doTheTest(*u8, true); + S.doTheTest(f32, true); + S.doTheTest(*f32, true); + // Container with ptr pointing to themselves + S.doTheTest(S0, true); + S.doTheTest(U0, true); +}