From 2715f6fdb8bca1c88c58dac047889711359e193b Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Tue, 5 Dec 2017 21:10:47 -0500 Subject: [PATCH] allow implicit cast from union to its enum tag type closes #642 --- src/ir.cpp | 11 +++++++++++ test/cases/union.zig | 8 ++++++++ 2 files changed, 19 insertions(+) diff --git a/src/ir.cpp b/src/ir.cpp index 86fa8c3566..0ab63a02fe 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -7468,6 +7468,17 @@ static ImplicitCastMatchResult ir_types_match_with_implicit_cast(IrAnalyze *ira, } } + // implicit union to its enum tag type + if (expected_type->id == TypeTableEntryIdEnum && actual_type->id == TypeTableEntryIdUnion && + (actual_type->data.unionation.decl_node->data.container_decl.auto_enum || + actual_type->data.unionation.decl_node->data.container_decl.init_arg_expr != nullptr)) + { + type_ensure_zero_bits_known(ira->codegen, actual_type); + if (actual_type->data.unionation.tag_type == expected_type) { + return ImplicitCastMatchResultYes; + } + } + // implicit enum to union which has the enum as the tag type if (expected_type->id == TypeTableEntryIdUnion && actual_type->id == TypeTableEntryIdEnum && (expected_type->data.unionation.decl_node->data.container_decl.auto_enum || diff --git a/test/cases/union.zig b/test/cases/union.zig index cd7fad4c88..5657767dce 100644 --- a/test/cases/union.zig +++ b/test/cases/union.zig @@ -197,3 +197,11 @@ test "cast tag type of union to union" { } const Letter2 = enum { A, B, C }; const Value2 = union(Letter2) { A: i32, B, C, }; + +test "implicit cast union to its tag type" { + var x: Value2 = Letter2.B; + giveMeLetterB(x); +} +fn giveMeLetterB(x: Letter2) { + assert(x == Value2.B); +}