-
Notifications
You must be signed in to change notification settings - Fork 4
/
reflect.zig
57 lines (47 loc) · 1.84 KB
/
reflect.zig
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
const std = @import("std");
pub fn reflect(comptime T: type) void {
typeInfo(T, 0);
std.debug.print("\n", .{});
}
fn typeInfo(comptime T: type, indent: usize) void {
if (indent == 0) std.debug.print("\x1b[31m{any}\x1b[m\n", .{T});
const info = @typeInfo(T);
switch (info) {
.Struct => printStruct(info.Struct, indent + 1),
else => return,
}
}
fn printStruct(comptime S: std.builtin.Type.Struct, indent: usize) void {
var buf: [256]u8 = undefined;
const spc = repeat(&buf, " ", indent);
const spc2 = repeat(buf[spc.len..], " ", indent + 1);
// Fields
if (S.fields.len > 0) std.debug.print("{s}\x1b[36mfields\x1b[m:\n", .{spc});
inline for (S.fields) |field| {
// name and type
std.debug.print("{s}.{s} \x1b[34m{any}\x1b[m, ", .{ spc2, field.name, field.type });
// less important field meta
std.debug.print("\x1b[2malignment: {any}, ", .{field.alignment});
std.debug.print("is_comptime: {any}, ", .{field.is_comptime});
std.debug.print("default_value: {any}\x1b[m", .{field.default_value});
std.debug.print("\n", .{});
typeInfo(field.type, indent + 1);
}
// Declarations
if (S.decls.len > 0) std.debug.print("{s}\x1b[36mdecls\x1b[m:\n", .{spc});
inline for (S.decls) |decl| {
std.debug.print("{s}\x1b[35m{s}\x1b[m\n", .{ spc2, decl.name });
}
// less important struct meta
std.debug.print("{s}\x1b[2mlayout: {any}, ", .{ spc, S.layout });
std.debug.print("is_tuple: {any}, ", .{S.is_tuple});
std.debug.print("backing_integer: {any}\x1b[m\n", .{S.backing_integer});
}
fn repeat(buf: []u8, str: []const u8, reps: usize) []u8 {
for (0..reps) |i| {
const s = i * str.len;
const e = (i + 1) * str.len;
@memcpy(buf[s..e], str);
}
return buf[0 .. str.len * reps];
}