Skip to content

Commit a736dfe

Browse files
committed
implement implicit cast from enum literal to enum
See #683
1 parent d0551db commit a736dfe

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

src/ir.cpp

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11579,6 +11579,22 @@ static IrInstruction *ir_analyze_cast(IrAnalyze *ira, IrInstruction *source_inst
1157911579
return ir_analyze_number_to_literal(ira, source_instr, value, wanted_type);
1158011580
}
1158111581

11582+
// cast from enum literal to enum with matching field name
11583+
if (actual_type->id == ZigTypeIdEnumLiteral && wanted_type->id == ZigTypeIdEnum) {
11584+
if ((err = type_resolve(ira->codegen, wanted_type, ResolveStatusZeroBitsKnown)))
11585+
return ira->codegen->invalid_instruction;
11586+
11587+
TypeEnumField *field = find_enum_type_field(wanted_type, value->value.data.x_enum_literal);
11588+
if (field == nullptr) {
11589+
ir_add_error(ira, source_instr, buf_sprintf("enum '%s' has no field named '%s'",
11590+
buf_ptr(&wanted_type->name), buf_ptr(value->value.data.x_enum_literal)));
11591+
return ira->codegen->invalid_instruction;
11592+
}
11593+
IrInstruction *result = ir_const(ira, source_instr, wanted_type);
11594+
bigint_init_bigint(&result->value.data.x_enum_tag, &field->value);
11595+
return result;
11596+
}
11597+
1158211598
// cast from union to the enum type of the union
1158311599
if (actual_type->id == ZigTypeIdUnion && wanted_type->id == ZigTypeIdEnum) {
1158411600
if ((err = type_resolve(ira->codegen, actual_type, ResolveStatusZeroBitsKnown)))

test/stage1/behavior/enum.zig

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -901,3 +901,15 @@ test "enum literal equality" {
901901
expect(x != y);
902902
expect(x == z);
903903
}
904+
905+
test "enum literal cast to enum" {
906+
const Color = enum {
907+
Auto,
908+
Off,
909+
On,
910+
};
911+
912+
var color1: Color = .Auto;
913+
var color2 = Color.Auto;
914+
expect(color1 == color2);
915+
}

0 commit comments

Comments
 (0)