From 788a716ac57b73b16a42db32d9f0a482cbbf385b Mon Sep 17 00:00:00 2001 From: Altagos Date: Sat, 24 Jan 2026 16:20:55 +0000 Subject: [PATCH] pretty error types --- pretty.zig | 38 ++++++++++++++++++++++++++++++++------ example/main.zig | 11 +++++++++++ 2 file(s) changed, 43 insertion(s)(+), 6 deletion(s)(-) diff --git a/pretty.zig b/pretty.zig --- a/pretty.zig +++ b/pretty.zig @@ -140,7 +140,7 @@ }; const InnerFmtOptions = struct { - dont_skip_type_name: bool = true, + skip_type_name: bool = !default_options.show_type_names, }; fn innerFmt( @@ -152,7 +152,7 @@ ) error{WriteFailed}!void { const info = @typeInfo(T); - if (opts.dont_skip_type_name) try printType(T, ctx, run); + if (!opts.skip_type_name) try printType(T, ctx, run); return switch (info) { .bool => formatBool(ctx, run, value), @@ -173,8 +173,8 @@ .optional => |opt| formatOptional(opt.child, ctx, run, value), .@"struct" => |st| formatStruct(T, st, ctx, run, value), - // TODO: .error_union => |eu| {}, - // TODO: .error_set => |es| {}, + .error_set => formatErrorSet(ctx, run, value), + .error_union => formatErrorUnion(ctx, run, value), // TODO: .array => |arr| {}, // TODO: .pointer => |ptr| {}, @@ -240,7 +240,7 @@ value: ?T, ) !void { return if (value) |val| - innerFmt(T, ctx, run, val, .{ .dont_skip_type_name = false }) + innerFmt(T, ctx, run, val, .{ .skip_type_name = true }) else formatNull(ctx, run); } @@ -265,7 +265,7 @@ run.resetColor(); } - comptime var index: comptime_int = 0; + comptime var index = 0; inline for (st.fields) |field| { indent(next_ctx, run); if (index != 0 and ctx.options.inline_structs) try run.write(", "); @@ -284,6 +284,32 @@ try run.write(" }"); run.resetColor(); } +} + +inline fn formatErrorSet( + comptime ctx: Context, + run: *const Runtime, + value: anyerror, +) !void { + run.setColor(ctx, .@"error"); + try run.write("error."); + try run.write(@errorName(value)); + run.resetColor(); +} + +inline fn formatErrorUnion( + comptime ctx: Context, + run: *Runtime, + value: anytype, +) !void { + const val = value catch |err| return formatErrorSet(ctx, run, err); + return innerFmt( + @TypeOf(val), + ctx, + run, + val, + .{ .skip_type_name = true }, + ); } inline fn formatType( diff --git a/example/main.zig b/example/main.zig --- a/example/main.zig +++ b/example/main.zig @@ -33,6 +33,9 @@ person: Person, }; +const ErrorSet = error{ OutOfMemory, WriteFailed }; +const Result = ErrorSet!Hello; + pub fn main(init: std.process.Init) !void { _ = init; @@ -96,4 +99,12 @@ .{Pretty(Person, .{ .inline_structs = true }).init(person)}, ); print("Pretty nested struct - {f}\n", .{pretty(nested)}); + + const eu_error: Result = error.OutOfMemory; + const eu_ok: Result = .world; + + print("\nError types\n", .{}); + print("Error set - {f}\n", .{pretty(ErrorSet.OutOfMemory)}); + print("Error union error - {f}\n", .{pretty(eu_error)}); + print("Error union ok - {f}\n", .{pretty(eu_ok)}); } -- tangled.sh