diff --git a/example/main.zig b/example/main.zig index 48f61b0..d76b3dd 100644 --- a/example/main.zig +++ b/example/main.zig @@ -33,6 +33,9 @@ const ChildC = struct { person: Person, }; +const ErrorSet = error{ OutOfMemory, WriteFailed }; +const Result = ErrorSet!Hello; + pub fn main(init: std.process.Init) !void { _ = init; @@ -96,4 +99,12 @@ pub fn main(init: std.process.Init) !void { .{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)}); } diff --git a/pretty.zig b/pretty.zig index 499834d..8bbdac7 100644 --- a/pretty.zig +++ b/pretty.zig @@ -140,7 +140,7 @@ const Context = struct { }; const InnerFmtOptions = struct { - dont_skip_type_name: bool = true, + skip_type_name: bool = !default_options.show_type_names, }; fn innerFmt( @@ -152,7 +152,7 @@ fn innerFmt( ) 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 @@ fn innerFmt( .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 @@ inline fn formatOptional( 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 @@ inline fn formatStruct( 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(", "); @@ -286,6 +286,32 @@ inline fn formatStruct( } } +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( comptime ctx: Context, run: *const Runtime,