Commit fc1a5cd9e7

Andrew Kelley <andrew@ziglang.org>
2021-12-28 02:10:24
Sema: implement `@tagName` for enum literals
1 parent 9dd4fb4
Changed files (3)
src/Sema.zig
@@ -10054,6 +10054,11 @@ fn zirTagName(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
     const operand_ty = sema.typeOf(operand);
 
     const enum_ty = switch (operand_ty.zigTypeTag()) {
+        .EnumLiteral => {
+            const val = try sema.resolveConstValue(block, operand_src, operand);
+            const bytes = val.castTag(.enum_literal).?.data;
+            return sema.addStrLit(block, bytes);
+        },
         .Enum => operand_ty,
         .Union => operand_ty.unionTagType() orelse {
             const decl = operand_ty.getOwnerDecl();
test/behavior/enum_llvm.zig
@@ -39,6 +39,11 @@ test "tag name with assigned enum values" {
     try expect(mem.eql(u8, @tagName(b), "B"));
 }
 
+test "@tagName on enum literals" {
+    try expect(mem.eql(u8, @tagName(.FooBar), "FooBar"));
+    comptime try expect(mem.eql(u8, @tagName(.FooBar), "FooBar"));
+}
+
 const Bar = enum { A, B, C, D };
 
 test "enum literal casting to optional" {
test/behavior/enum_stage1.zig
@@ -43,11 +43,6 @@ test "enum literal casting to error union with payload enum" {
     try expect((try bar) == Bar.B);
 }
 
-test "tagName on enum literals" {
-    try expect(mem.eql(u8, @tagName(.FooBar), "FooBar"));
-    comptime try expect(mem.eql(u8, @tagName(.FooBar), "FooBar"));
-}
-
 test "method call on an enum" {
     const S = struct {
         const E = enum {