From 611d4bc6a1a99f4364b690dea688e81dd599daae Mon Sep 17 00:00:00 2001 From: Michael Dusan Date: Sun, 14 Apr 2019 22:47:53 -0400 Subject: [PATCH] stage1: const_values_equal support tagged union --- src/analyze.cpp | 7 +++---- test/stage1/behavior/union.zig | 37 ++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 4 deletions(-) diff --git a/src/analyze.cpp b/src/analyze.cpp index 730c52c927..2775c05b79 100644 --- a/src/analyze.cpp +++ b/src/analyze.cpp @@ -5158,11 +5158,10 @@ bool const_values_equal(CodeGen *g, ConstExprValue *a, ConstExprValue *b) { if (bigint_cmp(&union1->tag, &union2->tag) == CmpEQ) { TypeUnionField *field = find_union_field_by_tag(a->type, &union1->tag); assert(field != nullptr); - if (type_has_bits(field->type_entry)) { - zig_panic("TODO const expr analyze union field value for equality"); - } else { + if (!type_has_bits(field->type_entry)) return true; - } + assert(find_union_field_by_tag(a->type, &union2->tag) != nullptr); + return const_values_equal(g, union1->payload, union2->payload); } return false; } diff --git a/test/stage1/behavior/union.zig b/test/stage1/behavior/union.zig index bbba867667..b8bb9a51b8 100644 --- a/test/stage1/behavior/union.zig +++ b/test/stage1/behavior/union.zig @@ -365,3 +365,40 @@ test "@enumToInt works on unions" { expect(@enumToInt(b) == 1); expect(@enumToInt(c) == 2); } + +const Attribute = union(enum) { + A: bool, + B: u8, +}; + +fn setAttribute(attr: Attribute) void {} + +fn Setter(attr: Attribute) type { + return struct{ + fn set() void { + setAttribute(attr); + } + }; +} + +test "comptime union field value equality" { + const a0 = Setter(Attribute{ .A = false }); + const a1 = Setter(Attribute{ .A = true }); + const a2 = Setter(Attribute{ .A = false }); + + const b0 = Setter(Attribute{ .B = 5 }); + const b1 = Setter(Attribute{ .B = 9 }); + const b2 = Setter(Attribute{ .B = 5 }); + + expect(a0 == a0); + expect(a1 == a1); + expect(a0 == a2); + + expect(b0 == b0); + expect(b1 == b1); + expect(b0 == b2); + + expect(a0 != b0); + expect(a0 != a1); + expect(b0 != b1); +}