Commit 2715f6fdb8

Andrew Kelley <superjoe30@gmail.com>
2017-12-06 03:10:47
allow implicit cast from union to its enum tag type
closes #642
1 parent 960914a
Changed files (2)
src
test
cases
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 ||
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);
+}