Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 29 additions & 3 deletions lib/std/fmt.zig
Original file line number Diff line number Diff line change
Expand Up @@ -359,11 +359,34 @@ pub fn formatType(
},
.Enum => |enumInfo| {
try out_stream.writeAll(@typeName(T));

var has_name: bool = undefined;
if (enumInfo.is_exhaustive) {
has_name = true;
} else {
has_name = false;
// Use @tagName only if value is one of known fields
inline for (enumInfo.fields) |enumField| {
if (@enumToInt(value) == enumField.value) {
has_name = true;
break;
}
}
}

var use_name = has_name;
if (comptime std.mem.eql(u8, fmt, "x") or
comptime std.mem.eql(u8, fmt, "X") or
comptime std.mem.eql(u8, fmt, "d") or
comptime std.mem.eql(u8, fmt, "b"))
{
use_name = false;
}

if (use_name) {
try out_stream.writeAll(".");
try out_stream.writeAll(@tagName(value));
} else {
// TODO: when @tagName works on exhaustive enums print known enum strings
try out_stream.writeAll("(");
try formatType(@enumToInt(value), fmt, options, out_stream, max_depth);
try out_stream.writeAll(")");
Expand Down Expand Up @@ -1293,6 +1316,8 @@ test "enum" {
const value = Enum.Two;
try testFmt("enum: Enum.Two\n", "enum: {}\n", .{value});
try testFmt("enum: Enum.Two\n", "enum: {}\n", .{&value});
try testFmt("enum: Enum(0)\n", "enum: {x}\n", .{Enum.One});
try testFmt("enum: Enum(1)\n", "enum: {X}\n", .{Enum.Two});
}

test "non-exhaustive enum" {
Expand All @@ -1301,11 +1326,12 @@ test "non-exhaustive enum" {
Two = 0xbeef,
_,
};
try testFmt("enum: Enum(15)\n", "enum: {}\n", .{Enum.One});
try testFmt("enum: Enum(48879)\n", "enum: {}\n", .{Enum.Two});
try testFmt("enum: Enum.One\n", "enum: {}\n", .{Enum.One});
try testFmt("enum: Enum.Two\n", "enum: {}\n", .{Enum.Two});
try testFmt("enum: Enum(4660)\n", "enum: {}\n", .{@intToEnum(Enum, 0x1234)});
try testFmt("enum: Enum(f)\n", "enum: {x}\n", .{Enum.One});
try testFmt("enum: Enum(beef)\n", "enum: {x}\n", .{Enum.Two});
try testFmt("enum: Enum(BEEF)\n", "enum: {X}\n", .{Enum.Two});
try testFmt("enum: Enum(1234)\n", "enum: {x}\n", .{@intToEnum(Enum, 0x1234)});
}

Expand Down