A pretty printer for zig
zig

pretty error types

altagos.dev 788a716a 00906425

verified
+43 -6
+11
example/main.zig
··· 33 33 person: Person, 34 34 }; 35 35 36 + const ErrorSet = error{ OutOfMemory, WriteFailed }; 37 + const Result = ErrorSet!Hello; 38 + 36 39 pub fn main(init: std.process.Init) !void { 37 40 _ = init; 38 41 ··· 96 99 .{Pretty(Person, .{ .inline_structs = true }).init(person)}, 97 100 ); 98 101 print("Pretty nested struct - {f}\n", .{pretty(nested)}); 102 + 103 + const eu_error: Result = error.OutOfMemory; 104 + const eu_ok: Result = .world; 105 + 106 + print("\nError types\n", .{}); 107 + print("Error set - {f}\n", .{pretty(ErrorSet.OutOfMemory)}); 108 + print("Error union error - {f}\n", .{pretty(eu_error)}); 109 + print("Error union ok - {f}\n", .{pretty(eu_ok)}); 99 110 }
+32 -6
pretty.zig
··· 140 140 }; 141 141 142 142 const InnerFmtOptions = struct { 143 - dont_skip_type_name: bool = true, 143 + skip_type_name: bool = !default_options.show_type_names, 144 144 }; 145 145 146 146 fn innerFmt( ··· 152 152 ) error{WriteFailed}!void { 153 153 const info = @typeInfo(T); 154 154 155 - if (opts.dont_skip_type_name) try printType(T, ctx, run); 155 + if (!opts.skip_type_name) try printType(T, ctx, run); 156 156 157 157 return switch (info) { 158 158 .bool => formatBool(ctx, run, value), ··· 173 173 .optional => |opt| formatOptional(opt.child, ctx, run, value), 174 174 .@"struct" => |st| formatStruct(T, st, ctx, run, value), 175 175 176 - // TODO: .error_union => |eu| {}, 177 - // TODO: .error_set => |es| {}, 176 + .error_set => formatErrorSet(ctx, run, value), 177 + .error_union => formatErrorUnion(ctx, run, value), 178 178 179 179 // TODO: .array => |arr| {}, 180 180 // TODO: .pointer => |ptr| {}, ··· 240 240 value: ?T, 241 241 ) !void { 242 242 return if (value) |val| 243 - innerFmt(T, ctx, run, val, .{ .dont_skip_type_name = false }) 243 + innerFmt(T, ctx, run, val, .{ .skip_type_name = true }) 244 244 else 245 245 formatNull(ctx, run); 246 246 } ··· 265 265 run.resetColor(); 266 266 } 267 267 268 - comptime var index: comptime_int = 0; 268 + comptime var index = 0; 269 269 inline for (st.fields) |field| { 270 270 indent(next_ctx, run); 271 271 if (index != 0 and ctx.options.inline_structs) try run.write(", "); ··· 284 284 try run.write(" }"); 285 285 run.resetColor(); 286 286 } 287 + } 288 + 289 + inline fn formatErrorSet( 290 + comptime ctx: Context, 291 + run: *const Runtime, 292 + value: anyerror, 293 + ) !void { 294 + run.setColor(ctx, .@"error"); 295 + try run.write("error."); 296 + try run.write(@errorName(value)); 297 + run.resetColor(); 298 + } 299 + 300 + inline fn formatErrorUnion( 301 + comptime ctx: Context, 302 + run: *Runtime, 303 + value: anytype, 304 + ) !void { 305 + const val = value catch |err| return formatErrorSet(ctx, run, err); 306 + return innerFmt( 307 + @TypeOf(val), 308 + ctx, 309 + run, 310 + val, 311 + .{ .skip_type_name = true }, 312 + ); 287 313 } 288 314 289 315 inline fn formatType(