tangled
alpha
login
or
join now
altagos.dev
/
pretty
0
fork
atom
A pretty printer for zig
zig
0
fork
atom
overview
issues
pulls
pipelines
pretty optional
altagos.dev
1 month ago
f0c7fa74
e63c09e3
verified
This commit was signed with the committer's
known signature
.
altagos.dev
SSH Key Fingerprint:
SHA256:UbTjEcCZlc6GzQWLCuDK3D//HESWD2xFPkzue9XMras=
+27
-7
2 changed files
expand all
collapse all
unified
split
example
main.zig
pretty.zig
+7
-1
example/main.zig
···
5
5
const pretty = pretty_mod.pretty;
6
6
const Pretty = pretty_mod.PrettyWithOptions;
7
7
8
8
-
const Hello = enum { world };
8
8
+
const Hello = enum { world, developer };
9
9
10
10
pub fn main(init: std.process.Init) !void {
11
11
_ = init;
···
45
45
print("\nEnums\n", .{});
46
46
print("Pretty enum - {f}\n", .{pretty(Hello.world)});
47
47
print("Pretty enum literal - {f}\n", .{pretty(.hello_world)});
48
48
+
49
49
+
print("\nOptionals\n", .{});
50
50
+
const opt_null: ?Hello = null;
51
51
+
const opt_not_null: ?Hello = .developer;
52
52
+
print("Pretty optional = null - {f}\n", .{pretty(opt_null)});
53
53
+
print("Pretty optional = not null - {f}\n", .{pretty(opt_not_null)});
48
54
}
+20
-6
pretty.zig
···
46
46
.tty = global.tty.?,
47
47
};
48
48
49
49
-
return innerFmt(T, comp_ctx, this.value, run_ctx);
49
49
+
return innerFmt(T, comp_ctx, run_ctx, this.value, .{});
50
50
}
51
51
};
52
52
}
···
90
90
}
91
91
};
92
92
93
93
+
const InnerFmtOptions = struct {
94
94
+
dont_skip_type_name: bool = true,
95
95
+
};
96
96
+
93
97
fn innerFmt(
94
98
comptime T: type,
95
99
comptime cctx: ComptimeContext,
100
100
+
rctx: RuntimeContext,
96
101
value: T,
97
97
-
rctx: RuntimeContext,
102
102
+
opts: InnerFmtOptions,
98
103
) error{WriteFailed}!void {
99
104
const info = @typeInfo(T);
100
100
-
try printType(T, cctx, rctx);
101
105
102
102
-
return switch (info) {
103
103
-
.type => formatType(rctx, value),
104
104
-
.null => formatNull(rctx),
106
106
+
if (opts.dont_skip_type_name) try printType(T, cctx, rctx);
105
107
108
108
+
return switch (info) {
106
109
.bool => formatBool(rctx, value),
110
110
+
.null => formatNull(rctx),
111
111
+
.type => formatType(rctx, value),
107
112
108
113
// comptime types
109
114
.comptime_int,
···
115
120
.@"enum",
116
121
.enum_literal,
117
122
=> formatValue(rctx, value),
123
123
+
124
124
+
.optional => |opt| formatOptional(opt.child, cctx, rctx, value),
118
125
119
126
else => {
120
127
rctx.setColor(.red);
···
157
164
ctx.setColor(.cyan);
158
165
try ctx.write("null");
159
166
ctx.resetColor();
167
167
+
}
168
168
+
169
169
+
inline fn formatOptional(comptime T: type, comptime cctx: ComptimeContext, rctx: RuntimeContext, value: ?T) !void {
170
170
+
return if (value) |val|
171
171
+
innerFmt(T, cctx, rctx, val, .{ .dont_skip_type_name = false })
172
172
+
else
173
173
+
formatNull(rctx);
160
174
}
161
175
162
176
inline fn formatType(ctx: RuntimeContext, value: type) !void {