//! Reading and writing state by field path, from the reflected layout alone. //! Shared by the console, the memory overlay, scripts and the probe. const std = @import("std"); const abi = @import("abi"); const Layout = @import("memory.zig").Layout; const Leaf = Layout.Leaf; /// Writes what `path` names: one value for a number, bool or enum leaf, /// or every leaf under it for an array, a vector or a struct, in memory /// order (for a Zig struct not always the declared one): `{ 250, 3 }` /// when they are its elements, otherwise `{ .count = 12, .hz = 60 }` or /// `{ [0].x = 1, [1].x = 2 }`. /// Shows the first `max_values`, then how many more there are. pub fn formatPath(layout: Layout, memory: []const u8, path: []const u8, w: *std.Io.Writer) (std.Io.Writer.Error || error{UnknownField})!void { if (layout.find(path)) |leaf| if (!leaf.whole()) return format(leaf, memory, w); // Names under `path`, found leaf by leaf; sorted by offset afterwards. const Found = struct { offset: usize, leaf: Leaf }; var found: [max_values]Found = undefined; var count: usize = 0; var total: usize = 0; var plain = true; var name_buf: [256]u8 = undefined; for (layout.fields) |leaf| { if (leaf.whole()) continue; var it = leaf.elements(); while (it.next()) |offset| { var nw: std.Io.Writer = .fixed(&name_buf); leaf.name(offset, &nw) catch continue; const name = nw.buffered(); if (!under(name, path)) continue; total += 1; if (!isIndex(name[path.len..])) plain = false; if (count < max_values) { found[count] = .{ .offset = offset, .leaf = leaf }; count += 1; } else { // Keep the lowest offsets. var highest: usize = 0; for (found[1..], 1..) |f, i| if (f.offset > found[highest].offset) { highest = i; }; if (offset < found[highest].offset) found[highest] = .{ .offset = offset, .leaf = leaf }; } } } if (total == 0) return error.UnknownField; std.mem.sortUnstable(Found, found[0..count], {}, struct { fn less(_: void, a: Found, b: Found) bool { return a.offset < b.offset; } }.less); try w.writeAll("{ "); for (found[0..count], 0..) |f, i| { if (i > 0) try w.writeAll(", "); if (!plain) { var nw: std.Io.Writer = .fixed(&name_buf); f.leaf.name(f.offset, &nw) catch {}; try w.print("{s} = ", .{nw.buffered()[path.len..]}); } try format(f.leaf.at(f.offset), memory, w); } if (total > count) try w.print(", ... {d} more", .{total - count}); try w.writeAll(" }"); } pub const max_values = 64; /// `name` is `path` itself or a field or element inside it. fn under(name: []const u8, path: []const u8) bool { if (!std.mem.startsWith(u8, name, path)) return false; if (name.len == path.len) return true; return name[path.len] == '.' or name[path.len] == '['; } /// `[3]`: one index and nothing more. fn isIndex(suffix: []const u8) bool { if (suffix.len < 3 or suffix[0] != '[' or suffix[suffix.len - 1] != ']') return false; for (suffix[1 .. suffix.len - 1]) |ch| if (!std.ascii.isDigit(ch)) return false; return true; } pub fn format(leaf: Leaf, memory: []const u8, w: *std.Io.Writer) std.Io.Writer.Error!void { const bytes = leaf.bytes(memory); switch (leaf.kind) { .int => try w.print("{d}", .{readInt(i64, bytes)}), .uint => try w.print("{d}", .{readInt(u64, bytes)}), .bool => try w.writeAll(if (bytes[0] != 0) "true" else "false"), .float => switch (leaf.size) { 4 => try w.print("{d}", .{@as(f32, @bitCast(bytes[0..4].*))}), 8 => try w.print("{d}", .{@as(f64, @bitCast(bytes[0..8].*))}), else => try w.writeAll("?"), }, .@"enum" => { const value = readInt(i64, bytes); if (tagName(leaf.tags, value)) |name| try w.print(".{s}", .{name}) else try w.print("{d}", .{value}); }, else => try w.print("<{d} bytes>", .{leaf.size}), } } /// Parses `text` as the field's kind (enums by name or number) and stores it. pub fn set(leaf: Leaf, memory: []u8, text: []const u8) !void { const bytes = memory[leaf.offset..][0..leaf.size]; switch (leaf.kind) { .int, .uint, .@"enum" => { const name = std.mem.trimStart(u8, text, "."); const value: i64 = if (leaf.kind == .@"enum" and tagValue(leaf.tags, name) != null) tagValue(leaf.tags, name).? else std.fmt.parseInt(i64, text, 0) catch return error.InvalidValue; writeInt(bytes, value); }, .bool => bytes[0] = if (std.mem.eql(u8, text, "true") or std.mem.eql(u8, text, "1")) 1 else if (std.mem.eql(u8, text, "false") or std.mem.eql(u8, text, "0")) 0 else return error.InvalidValue, .float => { const value = std.fmt.parseFloat(f64, text) catch return error.InvalidValue; switch (leaf.size) { 4 => bytes[0..4].* = @bitCast(@as(f32, @floatCast(value))), 8 => bytes[0..8].* = @bitCast(value), else => return error.UnsupportedField, } }, else => return error.UnsupportedField, } } /// Sets every value of the row of scalars `path` names (an array of /// numbers, a vector, `grid[1]` of a `grid: [3][2]u16`), in memory order, /// from `text`'s words, one each; nothing when one is not a value. pub fn setRow(layout: Layout, memory: []u8, path: []const u8, text: []const u8) !void { for (layout.fields) |leaf| { if (leaf.whole() or !std.mem.endsWith(u8, leaf.path, "[]")) continue; const at = abi.layout.match(leaf.path[0 .. leaf.path.len - 2], leaf.dims[0 .. leaf.dims.len - 1], path) orelse continue; const d = leaf.dims[leaf.dims.len - 1]; var scratch: [16]u8 = undefined; var words = std.mem.tokenizeAny(u8, text, " \t\n"); for (0..d.count) |_| try set(leaf.at(0), &scratch, words.next() orelse return error.TooFewValues); if (words.next() != null) return error.TooManyValues; words.reset(); for (0..d.count) |i| try set(leaf.at(leaf.offset + at + i * d.stride), memory, words.next().?); return; } return error.UnsupportedField; } /// True when the field's formatted value equals `text` (enum names compare /// with or without the leading dot). pub fn matches(leaf: Leaf, memory: []const u8, text: []const u8) bool { var buf: [128]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); format(leaf, memory, &w) catch return false; const shown = w.buffered(); if (std.mem.eql(u8, shown, text)) return true; if (leaf.kind == .@"enum") { if (std.mem.eql(u8, std.mem.trimStart(u8, shown, "."), std.mem.trimStart(u8, text, "."))) return true; const value = std.fmt.parseInt(i64, text, 0) catch return false; return value == readInt(i64, leaf.bytes(memory)); } return false; } /// A number, bool or enum leaf's value as a float; null for other kinds. pub fn number(leaf: Leaf, memory: []const u8) ?f64 { const bytes = leaf.bytes(memory); return switch (leaf.kind) { .int, .@"enum" => @floatFromInt(readInt(i64, bytes)), .uint => @floatFromInt(readInt(u64, bytes)), .bool => if (bytes[0] != 0) 1 else 0, .float => switch (leaf.size) { 4 => @as(f32, @bitCast(bytes[0..4].*)), 8 => @as(f64, @bitCast(bytes[0..8].*)), else => null, }, else => null, }; } pub fn readInt(comptime T: type, bytes: []const u8) T { const n: usize = @min(bytes.len, 8); const value = std.mem.readVarInt(u64, bytes[0..n], .little); if (T == u64) return value; // Sign-extend from the field's own width. const shift: u6 = @intCast(64 - n * 8); return @as(i64, @bitCast(value << shift)) >> shift; } pub fn writeInt(bytes: []u8, value: i64) void { const raw: u64 = @bitCast(value); for (bytes, 0..) |*b, i| b.* = if (i < 8) @truncate(raw >> @intCast(i * 8)) else 0; } pub fn tagName(tags: []const u8, value: i64) ?[]const u8 { var it = std.mem.tokenizeScalar(u8, tags, ','); while (it.next()) |pair| { const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; if ((std.fmt.parseInt(i64, pair[eq + 1 ..], 10) catch continue) == value) return pair[0..eq]; } return null; } pub fn tagValue(tags: []const u8, name: []const u8) ?i64 { var it = std.mem.tokenizeScalar(u8, tags, ','); while (it.next()) |pair| { const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; if (std.mem.eql(u8, pair[0..eq], name)) return std.fmt.parseInt(i64, pair[eq + 1 ..], 10) catch null; } return null; } test "fields format, parse and compare by kind" { const S = extern struct { mood: enum(u32) { calm, angry = 5 } = .calm, x: i16 = -3, speed: f32 = 1.5, on: bool = false }; var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); const layout = try @import("memory.zig").Layout.copy(arena.allocator(), abi.layout.of(S, .state)); var s: S = .{}; const bytes = std.mem.asBytes(&s); try std.testing.expect(matches(layout.find("x").?, bytes, "-3")); try set(layout.find("mood").?, bytes, "angry"); try std.testing.expectEqual(.angry, s.mood); try std.testing.expect(matches(layout.find("mood").?, bytes, ".angry")); try std.testing.expect(matches(layout.find("mood").?, bytes, "5")); try set(layout.find("speed").?, bytes, "0.25"); try std.testing.expectEqual(@as(f32, 0.25), s.speed); try set(layout.find("on").?, bytes, "true"); try std.testing.expect(s.on); try std.testing.expectError(error.InvalidValue, set(layout.find("x").?, bytes, "banana")); } test "a row of scalars is set from its words, all or none" { const S = struct { grid: [3][2]i16 = @splat(@splat(0)), pos: @Vector(2, f32) = .{ 0, 0 } }; var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); const layout = try Layout.copy(arena.allocator(), abi.layout.of(S, .state)); var s: S = .{}; const bytes = std.mem.asBytes(&s); try setRow(layout, bytes, "grid[1]", "4 -5"); try std.testing.expectEqual([2]i16{ 4, -5 }, s.grid[1]); try setRow(layout, bytes, "pos", "1.5\n2"); try std.testing.expectEqual(@as(f32, 2), s.pos[1]); try std.testing.expectError(error.TooFewValues, setRow(layout, bytes, "grid[2]", "7")); try std.testing.expectError(error.TooManyValues, setRow(layout, bytes, "grid[2]", "7 8 9")); try std.testing.expectError(error.InvalidValue, setRow(layout, bytes, "grid[2]", "7 x")); try std.testing.expectEqual([2]i16{ 0, 0 }, s.grid[2]); try std.testing.expectError(error.UnsupportedField, setRow(layout, bytes, "grid", "1 2")); } test "indexed paths reach array elements and vector lanes" { const S = struct { pos: @Vector(2, f32) = .{ 250, 3 }, boids: struct { buffer: [4]struct { pos: [2]f32 = .{ 0, 0 }, mood: enum(u8) { calm = 1, wild = 2 } = .calm } = @splat(.{}), len: u32 = 0 } = .{} }; var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); const layout = try @import("memory.zig").Layout.copy(arena.allocator(), abi.layout.of(S, .state)); var s: S = .{}; const bytes = std.mem.asBytes(&s); try std.testing.expect(matches(layout.find("pos[0]").?, bytes, "250")); try std.testing.expectEqual(@as(?f64, 3), number(layout.find("pos[1]").?, bytes)); try set(layout.find("boids.buffer[3].pos[1]").?, bytes, "20.5"); try std.testing.expectEqual(@as(f32, 20.5), s.boids.buffer[3].pos[1]); try set(layout.find("boids.buffer[2].mood").?, bytes, "wild"); try std.testing.expectEqual(.wild, s.boids.buffer[2].mood); try std.testing.expect(layout.find("boids.buffer[4].mood") == null); try std.testing.expect(layout.find("pos[2]") == null); } test "paths to vectors, arrays and structs print every value under them" { const S = struct { pos: @Vector(2, f32) = .{ 250, 3 }, clock: struct { hz: f32 = 60, count: u64 = 12 } = .{}, list: struct { buffer: [3]struct { x: i32 = 1, on: bool = true } = @splat(.{}), len: u32 = 2 } = .{}, big: [100]u8 = @splat(7) }; var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); const layout = try Layout.copy(arena.allocator(), abi.layout.of(S, .state)); var s: S = .{}; s.list.buffer[1].x = -4; const bytes = std.mem.asBytes(&s); var buf: [1024]u8 = undefined; const cases = [_][2][]const u8{ .{ "pos", "{ 250, 3 }" }, .{ "pos[1]", "3" }, .{ "clock", "{ .count = 12, .hz = 60 }" }, // memory order .{ "list.buffer[1]", "{ .x = -4, .on = true }" }, .{ "list.buffer", "{ [0].x = 1, [0].on = true, [1].x = -4, [1].on = true, [2].x = 1, [2].on = true }" }, }; for (cases) |case| { var w: std.Io.Writer = .fixed(&buf); try formatPath(layout, bytes, case[0], &w); try std.testing.expectEqualStrings(case[1], w.buffered()); } var w: std.Io.Writer = .fixed(&buf); try formatPath(layout, bytes, "big", &w); try std.testing.expect(std.mem.endsWith(u8, w.buffered(), "7, 7, ... 36 more }")); try std.testing.expectError(error.UnknownField, formatPath(layout, bytes, "po", &w)); }