diff options
Diffstat (limited to 'core')
| -rw-r--r-- | core/Output.zig | 171 | ||||
| -rw-r--r-- | core/Query.zig | 35 | ||||
| -rw-r--r-- | core/builtins.zig | 729 | ||||
| -rw-r--r-- | core/builtins_json.zig | 28 | ||||
| -rw-r--r-- | core/config.zig | 8 | ||||
| -rw-r--r-- | core/draw.zig | 6 | ||||
| -rw-r--r-- | core/fuzz.zig | 773 | ||||
| -rw-r--r-- | core/locations.zig | 9 | ||||
| -rw-r--r-- | core/ninep/ctl.zig | 115 | ||||
| -rw-r--r-- | core/root.zig | 2 | ||||
| -rw-r--r-- | core/tape.zig | 77 | ||||
| -rw-r--r-- | core/walk.zig | 58 | ||||
| -rw-r--r-- | core/walk.zig.orig | 2618 |
13 files changed, 4267 insertions, 362 deletions
diff --git a/core/Output.zig b/core/Output.zig index 09ec2a51..a1e5865e 100644 --- a/core/Output.zig +++ b/core/Output.zig @@ -757,13 +757,16 @@ fn openStepped(p: *Pardes, id: usize, from: Origin, content: []u8) !void { look.armLookWalk(p, free); } +/// The +Help's text: a builtin a row (its keys, its name, its other +/// shortcuts) with its documentation under it, a line a paragraph, and a +/// blank line; bare (`prefix` empty) every builtin of this view, then the +/// addons' words, the language keys and how a query pane is driven; with +/// `prefix`, the builtins under SPC and those keys. fn helpContent(p: *const Pardes, gpa: std.mem.Allocator, prefix: []const u8) ![]u8 { - const full_header = "pardes builtins, and how to run each:\nSPC and its keys, a chord, a button, the\ntopbar - or the name, executed anywhere.\n\n"; + const full_header = "pardes builtins: each one's keys and its name, then what it does. Run one by its keys, or by its name anywhere: B2 on the word, Exec <name>, a line of a ctl file, or `pardes do <name>` from a shell. `Help <name>` shows one builtin alone; `Help <keys>` (or SPC, those keys, then ?) the builtins under SPC and those keys.\n\n"; const group_header = "pardes builtins under SPC"; - const calls_help = "\nCallstack: static caller chains,\nwith signatures and clickable call sites.\nCallers / Callees: one direction at a time.\n"; - const show_calls_help = prefix.len == 0 or std.mem.eql(u8, prefix, "l"); const language_footer = - "\nlanguage keys (motions, not words):\n" ++ + "language keys (motions, not words):\n" ++ "gd gD gy gi gr goto: definition,\n" ++ " declaration, type-def,\n" ++ " implementation, refs\n" ++ @@ -775,7 +778,7 @@ fn helpContent(p: *const Pardes, gpa: std.mem.Allocator, prefix: []const u8) ![] "Tab after a . completion, in insert\n" ++ "C-left-click definition, by mouse\n" ++ "SPC l ... hover, rename, symbols,\n" ++ - " calls, types: above\n"; + " calls, types: above\n\n"; var out: std.Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); const w = &out.writer; @@ -790,26 +793,15 @@ fn helpContent(p: *const Pardes, gpa: std.mem.Allocator, prefix: []const u8) ![] // word is none in a terminal's view if (!std.mem.startsWith(u8, row.path orelse "", prefix)) continue; if (!builtins.registry.here(p, row.cmd)) continue; - try w.print("{s}\n", .{row.line}); + try w.print("{s}\n{s}\n\n", .{ row.line, builtins.registry.doc(row.cmd).text }); } // An addon's words, after the core's, each saying whose it is. for (p.kinds.words[0..p.kinds.nwords]) |*kw| { const path = kw.leader.slice(); if (!std.mem.startsWith(u8, path, prefix) or (prefix.len > 0 and path.len == 0)) continue; - var keys: [64]u8 = undefined; - var n: usize = 0; - if (path.len > 0) for ("SPC") |ch| { - keys[n] = ch; - n += 1; - }; - for (path) |ch| if (n + 2 <= keys.len) { - keys[n] = ' '; - keys[n + 1] = ch; - n += 2; - }; - try w.print("{s: <12}{s} {s} (addon {s})\n", .{ keys[0..n], kw.name.slice(), kw.doc.slice(), p.kinds.kinds[kw.kind].nameOf() }); + try addonRow(w, p, kw); + try w.print("{s}\n\n", .{kw.doc.slice()}); } - if (show_calls_help) try w.writeAll(calls_help); if (prefix.len == 0) try w.writeAll(language_footer); // The paths that run a builtin with a word (config.leader_args), and how // a query pane is driven: under SPC f, b, s and in the whole listing. @@ -817,7 +809,7 @@ fn helpContent(p: *const Pardes, gpa: std.mem.Allocator, prefix: []const u8) ![] if (std.mem.startsWith(u8, la.path, prefix)) break true; } else std.mem.eql(u8, prefix, "f"); if (prefix.len == 0 or search_group) { - try w.writeAll("\nsearch: a query pane under the text,\nits line 1 the query, its first word\nthe source (/ Find Grep Recent Panes\nSymbols All Refs Def Impl Diagnostics)\n"); + try w.writeAll("search: a query pane under the text,\nits line 1 the query, its first word\nthe source (/ Find Grep Recent Panes\nSymbols All Refs Def Impl Diagnostics)\n"); for (config.leader_args) |la| { if (!std.mem.startsWith(u8, la.path, prefix)) continue; var keys: [16]u8 = @splat(' '); @@ -836,6 +828,91 @@ fn helpContent(p: *const Pardes, gpa: std.mem.Allocator, prefix: []const u8) ![] return out.toOwnedSlice(); } +/// The column a builtin's name stands at in its row (pardes.builtin_rows): +/// an addon's word's row puts its name there too. +const name_column = std.mem.indexOf(u8, pardes.builtin_rows[0].line, @tagName(pardes.builtin_rows[0].cmd)).?; + +/// An addon's word's row: its keys, its name, whose it is. +fn addonRow(w: *std.Io.Writer, p: *const Pardes, kw: *const pardes.Kind.Word) std.Io.Writer.Error!void { + var key_buf: [32]u8 = undefined; + var keys: std.Io.Writer = .fixed(&key_buf); + const path = kw.leader.slice(); + if (path.len > 0) keys.writeAll("SPC") catch {}; + for (path) |ch| keys.print(" {c}", .{ch}) catch {}; + try w.print("{s}", .{keys.buffered()}); + try w.splatByteAll(' ', name_column -| keys.buffered().len); + try w.print("{s} (addon {s})\n", .{ kw.name.slice(), p.kinds.kinds[kw.kind].nameOf() }); +} + +/// Builtin `b` alone (`Help <name>`, `pardes help <name>`): its row, its +/// documentation, and what the list does not say, a line each: its keys +/// spelled out, its argument, what it acts on, and the same word from a +/// shell. +pub fn writeWordHelp(w: *std.Io.Writer, b: Builtin) std.Io.Writer.Error!void { + const row = for (pardes.builtin_rows) |r| { + if (r.cmd == b) break r; + } else unreachable; // a row a builtin + const name = @tagName(b); + try w.print("{s}\n\n{s}\n\n", .{ row.line, builtins.registry.doc(b).text }); + try w.writeAll("keys: "); + const shortcuts = std.mem.trim(u8, row.line[std.mem.indexOf(u8, row.line, name).? + name.len ..], " "); + var first = true; + if (row.path) |path| { + try w.writeAll("SPC"); + for (path) |c| try w.print(" {c}", .{c}); + try w.writeAll(" in normal mode"); + first = false; + } + var parts = std.mem.splitSequence(u8, shortcuts, ", "); + while (parts.next()) |part| if (part.len > 0) { + if (!first) try w.writeAll("; "); + first = false; + try w.writeAll(if (std.mem.eql(u8, part, "topbar")) "its word in the workspace tag" else part); + }; + if (row.path == null and shortcuts.len == 0) try w.print("none: run its name (B2 on it, Exec {s})", .{name}); + try w.writeAll("\nargument: "); + if (config.Settings.find(name)) |setting| { + try w.writeAll(config.Settings.takes(setting.action) orelse "a value"); + if (!builtins.registry.requiresArg(b)) try w.writeAll(", or none"); + } else try w.writeAll(if (!builtins.registry.takesArg(b)) "none" else if (builtins.registry.requiresArg(b)) "required" else "optional"); + try w.writeAll("\nacts on: "); + if (builtins.registry.needs(b)) |kind| try w.print("{s}, ", .{kind.noun()}); + try w.writeAll(if (b == .Edit) + "the pane it runs from (over 9P, a pane's ctl, or the root's for the pane with the keyboard)" + else if (builtins.registry.scope(b) == .session) + "the session (over 9P, the root ctl)" + else + "the pane it runs from (over 9P, that pane's ctl)"); + if (!builtins.registry.hereFor(b, builtins.capabilities, false)) try w.writeAll("; a window's word: none in a terminal"); + try w.print("\nfrom a shell: pardes do {s}{s}\n", .{ name, if (!builtins.registry.takesArg(b)) "" else if (builtins.registry.requiresArg(b)) " ARG" else " [ARG]" }); +} + +/// An addon's word alone, as `writeWordHelp` writes a builtin. +fn writeAddonWordHelp(w: *std.Io.Writer, p: *const Pardes, kw: *const pardes.Kind.Word) std.Io.Writer.Error!void { + try addonRow(w, p, kw); + try w.print("\n{s}\n\nkeys: ", .{kw.doc.slice()}); + const path = kw.leader.slice(); + if (path.len == 0) try w.print("none: run its name (B2 on it, Exec {s})", .{kw.name.slice()}) else { + try w.writeAll("SPC"); + for (path) |c| try w.print(" {c}", .{c}); + try w.writeAll(" in normal mode"); + } + const arg = switch (kw.arg) { + pardes.Kind.c.PA_ARG_NONE => "none", + pardes.Kind.c.PA_ARG_REQUIRED => "required", + else => "optional", + }; + try w.print("\nargument: {s}\nacts on: {s} pane, the one it runs from (over 9P, that pane's ctl)\nfrom a shell: pardes do {s}{s}\n", .{ + arg, + p.kinds.kinds[kw.kind].nameOf(), + kw.name.slice(), + if (kw.arg == pardes.Kind.c.PA_ARG_NONE) "" else if (kw.arg == pardes.Kind.c.PA_ARG_REQUIRED) " ARG" else " [ARG]", + }); +} + +/// The +Help (keys.zig's `SPC ... ?`, the `Help` word): bare, every +/// builtin; `prefix`, those under SPC and those keys. One +Help: a second +/// fills it again. pub fn openHelp(p: *Pardes, id: usize, prefix: []const u8) !void { const content = try helpContent(p, p.gpa, prefix); // content is handed off unfreed on purpose: openRead adopts it or frees @@ -843,6 +920,35 @@ pub fn openHelp(p: *Pardes, id: usize, prefix: []const u8) !void { return openRead(p, id, .{ .cmd = .Help }, prefix, content); } +/// `Help <what>`: a builtin's name or an addon's word, as the registry +/// takes them, that one alone in the +Help; SPC keys, the builtins under +/// them. False for a word that is neither, the +Help left as it was. +pub fn openHelpOn(p: *Pardes, id: usize, what: []const u8) !bool { + const b = std.meta.stringToEnum(Builtin, what); + const word = for (p.kinds.words[0..p.kinds.nwords]) |*kw| { + if (std.mem.eql(u8, kw.name.slice(), what)) break kw; + } else null; + if (b == null and word == null) { + if (!underKeys(p, what)) return false; + try openHelp(p, id, what); + return true; + } + var out: std.Io.Writer.Allocating = .init(p.gpa); + errdefer out.deinit(); + if (b) |one| try writeWordHelp(&out.writer, one) else try writeAddonWordHelp(&out.writer, p, word.?); + try openRead(p, id, .{ .cmd = .Help }, what, try out.toOwnedSlice()); + return true; +} + +/// Whether some builtin of this view, or an addon's word, is under SPC and +/// `keys`. +fn underKeys(p: *const Pardes, keys: []const u8) bool { + for (pardes.builtin_rows) |row| if (row.path) |path| if (std.mem.startsWith(u8, path, keys) and builtins.registry.here(p, row.cmd)) return true; + for (config.leader_args) |la| if (std.mem.startsWith(u8, la.path, keys)) return true; + for (p.kinds.words[0..p.kinds.nwords]) |*kw| if (kw.leader.slice().len > 0 and std.mem.startsWith(u8, kw.leader.slice(), keys)) return true; + return false; +} + /// Where a dump goes by default, as the session's environment says (the /// authority's, `tape.authority`): in `buf`. fn dumpDirectory(buf: []u8) []const u8 { @@ -1078,33 +1184,30 @@ test "plain output does not opt into location decoration" { try std.testing.expect(traits(.{ .query = .completion }).locations); } -test "full Help renders builtin rows, a call hierarchy guide, then language keys" { +test "full Help renders each builtin's row with its documentation under it, then language keys" { const core = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer core.deinit(); const content = try helpContent(core, std.testing.allocator, ""); defer std.testing.allocator.free(content); - // FIRST blank line: the end of the header (the footer opens with one too) + // FIRST blank line: the end of the header const body = content[(std.mem.indexOf(u8, content, "\n\n") orelse return error.MissingHelpHeader) + 2 ..]; var lines = std.mem.splitScalar(u8, body, '\n'); - for (pardes.builtin_rows) |row| if (builtins.registry.here(core, row.cmd)) - try std.testing.expectEqualStrings(row.line, lines.next() orelse - return error.MissingBuiltinHelpRow); - // The short call guide disambiguates the three related commands. - try std.testing.expectEqualStrings("", lines.next() orelse return error.MissingCallHelp); - try std.testing.expectEqualStrings("Callstack: static caller chains,", lines.next() orelse return error.MissingCallHelp); - try std.testing.expectEqualStrings("with signatures and clickable call sites.", lines.next() orelse return error.MissingCallHelp); - try std.testing.expectEqualStrings("Callers / Callees: one direction at a time.", lines.next() orelse return error.MissingCallHelp); + for (pardes.builtin_rows) |row| if (builtins.registry.here(core, row.cmd)) { + try std.testing.expectEqualStrings(row.line, lines.next() orelse return error.MissingBuiltinHelpRow); + // A line a paragraph, then a blank line. + var paragraphs = std.mem.splitScalar(u8, builtins.registry.doc(row.cmd).text, '\n'); + while (paragraphs.next()) |paragraph| try std.testing.expectEqualStrings(paragraph, lines.next() orelse return error.MissingDocumentation); + try std.testing.expectEqualStrings("", lines.next() orelse return error.MissingBlank); + }; // The language keys close the page. - try std.testing.expectEqualStrings("", lines.next() orelse - return error.MissingLanguageKeys); try std.testing.expectEqualStrings("language keys (motions, not words):", lines.next() orelse return error.MissingLanguageKeys); try std.testing.expect(std.mem.indexOf(u8, body, "\ngd gD gy gi gr goto: definition,\n") != null); - // The language group also explains call commands, without the motion footer. + // The language group: its words' documentation, without the motion footer. const group = try helpContent(core, std.testing.allocator, "l"); defer std.testing.allocator.free(group); try std.testing.expect(std.mem.indexOf(u8, group, "language keys") == null); - try std.testing.expect(std.mem.indexOf(u8, group, "Callstack: static caller chains") != null); + try std.testing.expect(std.mem.indexOf(u8, group, builtins.registry.doc(.Callstack).text) != null); } diff --git a/core/Query.zig b/core/Query.zig index f91339ca..228cdd0e 100644 --- a/core/Query.zig +++ b/core/Query.zig @@ -1259,19 +1259,21 @@ pub fn take(p: *Pardes, q: *Query, kind: Stream.Kind, rows: []const u8) void { const t = look.parsePathLine(ln); if (t.at.line == 0 or t.path.len == 0) continue; const code = if (t.end < ln.len) ln[t.end + 1 ..] else ""; - const path_at: u32 = @intCast(q.found_bytes.items.len); + // A row is a line's text, a file's name in it unescaped (one + // named `a:5000000000:b` reads as `a` at line 5000000000): one + // whose numbers a Found cannot hold is passed over. + const found: Found = .{ + .path = std.math.cast(u32, q.found_bytes.items.len) orelse return, + .path_len = std.math.cast(u16, t.path.len) orelse continue, + .line = std.math.cast(u32, t.at.line) orelse continue, + .col = std.math.cast(u32, t.at.col -| 1) orelse continue, + .end = std.math.cast(u32, if (t.at.end_col > 0) t.at.end_col else t.at.col) orelse continue, + .code = std.math.cast(u32, q.found_bytes.items.len + t.path.len) orelse return, + .code_len = std.math.cast(u32, code.len) orelse continue, + }; q.found_bytes.appendSlice(p.gpa, t.path) catch return; - const code_at: u32 = @intCast(q.found_bytes.items.len); q.found_bytes.appendSlice(p.gpa, code) catch return; - q.found.append(p.gpa, .{ - .path = path_at, - .path_len = @intCast(t.path.len), - .line = @intCast(t.at.line), - .col = @intCast(t.at.col -| 1), - .end = @intCast(if (t.at.end_col > 0) t.at.end_col else t.at.col), - .code = code_at, - .code_len = @intCast(code.len), - }) catch return; + q.found.append(p.gpa, found) catch return; }, } } @@ -2749,3 +2751,14 @@ test "a query row's address reaches every way a look arrives: an empty look writ try std.testing.expectEqual(tree.Status.ok, @import("ninep/harness.zig").wr(p, tree.Node.of(qp.serial, .look), line).reply.status); try std.testing.expectEqual(@as(i32, 3), a.body.cur_row); } + +test "Grep: a row whose numbers a Found cannot hold (a column past u32) is passed over, never cast" { + const gpa = std.testing.allocator; + const p = try @import("ninep/harness.zig").withFile(gpa, "x\n"); + defer p.deinit(); + var q: Query = .{ .owner = 0 }; + defer q.deinit(p.gpa); + take(p, &q, .grep, "a:5000000000:b:3:1-4 hit\nok.txt:2:3-5 hit\nb:7:4294967297 hit\n"); + // Taken or passed over, each: never cast (main: Query.zig:1267). + try std.testing.expect(q.found.items.len <= 3); +} diff --git a/core/builtins.zig b/core/builtins.zig index 9649d7b8..a236b0d6 100644 --- a/core/builtins.zig +++ b/core/builtins.zig @@ -1,4 +1,15 @@ //! Command structs and runtime settings form the builtin registry; bindings live in config.zig. +//! +//! THE CONVENTION: the `///` block right above a builtin's `pub const +//! <Word> = struct` is what a USER reads, in Help, `pardes help`, /commands, +//! `pardes words` and the manual's glossary (`registry.doc`): what the word +//! does, its argument's forms as typed, what it does bare, where its answer +//! goes, an example where the forms are not obvious. No file names, no +//! "registration", no history: notes for whoever reads the code are `//` +//! lines inside the struct. Its first sentence (to the first `. `) is the +//! summary, at most `summary_max` bytes; a blank `///` starts a paragraph. +//! The compiler holds it: a builtin with no `///`, a summary past the bound +//! or a `///` naming a .zig file fails the build, naming the builtin. const std = @import("std"); const pardes = @import("root.zig"); const tagline = @import("tagline.zig"); @@ -152,6 +163,46 @@ pub fn word(comptime T: type) []const u8 { return n[dot + 1 ..]; } +/// A builtin's documentation (THE CONVENTION, at the top of this file). +pub const Doc = struct { + /// Its first sentence: a line of /commands and of `pardes words`. + summary: []const u8, + /// All of it, a line a paragraph, the summary first. + text: []const u8, +}; + +/// The longest summary, in bytes: a line's worth after its word. +pub const summary_max = 100; + +/// `text`'s first sentence: to the first `.` a blank or a line's end +/// follows (`a.zig@main` and `from..to` go on). +fn docOf(comptime text: []const u8) Doc { + for (text, 0..) |c, i| { + if (c == '\n') return .{ .summary = text[0..i], .text = text }; + if (c == '.' and (i + 1 == text.len or text[i + 1] == ' ' or text[i + 1] == '\n')) return .{ .summary = text[0 .. i + 1], .text = text }; + } + return .{ .summary = text, .text = text }; +} + +/// The `///` lines from `from` to `to` in `source` as paragraphs: each +/// line's text after `///` joined to the next by a blank, a blank `///` a +/// line break. +fn paragraphs(comptime source: []const u8, comptime from: usize, comptime to: usize) []const u8 { + var text: []const u8 = ""; + var lines = std.mem.splitScalar(u8, source[from..to], '\n'); + var gap: []const u8 = ""; + while (lines.next()) |line| { + const said = std.mem.trim(u8, line["///".len..], " "); + if (said.len == 0) { + if (text.len > 0) gap = "\n"; + continue; + } + text = text ++ (if (text.len == 0) "" else if (gap.len > 0) gap else " ") ++ said; + gap = ""; + } + return text; +} + pub const OutputTraits = struct { name: []const u8, steps: bool = false, @@ -204,6 +255,63 @@ pub const registry = struct { return setting; } + /// What a user reads of builtin `b` (THE CONVENTION, at the top). + pub fn doc(b: Builtin()) Doc { + return docs[@backingInt(b)]; + } + + /// Each builtin's documentation, by its number: a hand-written one's + /// the `///` block above it, read off this file at compile time; a + /// setting's its `doc`. + const docs = docs: { + const manual = manualBuiltinList(); + const generated = settingList(); + var table: [manual.len + generated.len]Doc = undefined; + var found: [manual.len]bool = @splat(false); + // a few branches a byte of the source, once + @setEvalBranchQuota(4_000_000); + const source = @embedFile("builtins.zig"); + var block: ?usize = null; // where the `///` lines above this one start + var block_end: usize = 0; + var at: usize = 0; + while (at < source.len) { + const end = std.mem.indexOfScalarPos(u8, source, at, '\n') orelse source.len; + const line = source[at..end]; + if (std.mem.startsWith(u8, line, "///")) { + if (block == null) block = at; + block_end = end; + } else { + if (block) |from| if (std.mem.startsWith(u8, line, "pub const ")) { + const rest = line["pub const ".len..]; + if (std.mem.indexOf(u8, rest, " = struct")) |name_end| for (manual, 0..) |T, i| { + if (!std.mem.eql(u8, word(T), rest[0..name_end])) continue; + table[i] = docOf(paragraphs(source, from, block_end)); + found[i] = true; + }; + }; + block = null; + } + at = end + 1; + } + for (manual, 0..) |T, i| { + if (!found[i]) @compileError("builtin " ++ word(T) ++ " has no documentation: a `///` block right above `pub const " ++ word(T) ++ " = struct`"); + held(word(T), table[i]); + } + for (generated, manual.len..) |setting, i| { + table[i] = docOf(setting.doc); + held(setting.word, table[i]); + } + break :docs table; + }; + + /// THE CONVENTION's two rules the compiler can read. + fn held(comptime name: []const u8, comptime d: Doc) void { + if (d.summary.len > summary_max) + @compileError(std.fmt.comptimePrint("builtin {s}: its first sentence is {d} bytes, over {d}: \"{s}\"", .{ name, d.summary.len, summary_max, d.summary })); + if (std.mem.indexOf(u8, d.text, ".zig") != null) + @compileError("builtin " ++ name ++ ": its documentation names a source file; a note for the code's reader is a `//` line inside the struct"); + } + pub fn takesArg(b: Builtin()) bool { // Every setting takes its value, and a switch flips when bare. return declOr(b, "takes_arg", false, true); @@ -267,7 +375,14 @@ pub const registry = struct { // ---- the two acme verbs ---- -/// Look at its argument: open the file or address it names, else find the word, as a right click does. +/// Look at its argument as B3 does: open the file or address it names, else +/// find the word. +/// +/// `Look notes.txt:12` opens the file at line 12, or goes to the pane already +/// showing it; an address may be a line, `:12:5`, `/re/`, a directory (a pane +/// listing it) or a URL (the browser, by a plumbing rule). A relative path is +/// found in the directory of the pane looked from, then of each pane on the +/// jump list. Bare (Enter): the selection, else what is under the cursor. pub const Look = struct { pub const takes_arg = true; pub const requires_arg = true; @@ -282,7 +397,13 @@ pub const Look = struct { } }; -/// Execute its argument as a middle click on it would, a builtin or a shell command. +/// Run its argument as B2 on it would: a builtin, else a shell command. +/// +/// `Exec Newcol` runs the builtin. `Exec make test` runs the line: from a +/// terminal at an idle, empty prompt, typed into its shell; from anywhere +/// else, in a command pane (a terminal running `$SHELL -c` the line, which +/// shows its output and `exit N` when it ends; Kill stops it). Run by name, a +/// line is never a REPL's. pub const Exec = struct { pub const takes_arg = true; pub const requires_arg = true; @@ -394,10 +515,14 @@ pub fn warnModifiedIn(c: Ctx, asking: Pane.Discarding, which: Asked) bool { return count > 0; } -/// Quit the editor, refusing once while a pane holds unsaved text: an Exit -/// with nothing edited since discards it (acme's Exit, editors/acme/exec.c:892, -/// asking warnModified first). +/// Quit the editor; refused once while a pane holds unsaved text. +/// +/// Each pane with unsaved text is listed in +Unsaved and the notice counts +/// them; Exit again, nothing edited since, quits and discards it. On the way +/// out the session's panes are kept in the state file, for History and +/// Restore. pub const Exit = struct { + // acme's Exit (editors/acme/exec.c:892), asking warnModifiedIn first. pub const scope: Scope = .session; pub fn run(c: Ctx) void { if (warnModifiedIn(c, .Exit, .all)) return; @@ -406,14 +531,16 @@ pub const Exit = struct { } }; -/// acme's Kill (exec.c, `kill`; acme.c's WKill): stop the commands pardes -/// started -- the lines it typed into a terminal, from an exec, a middle -/// click or a pty/run, while their shell says they run (C mark to D). -/// Bare, every one; `Kill make ls`, those whose line starts with one of -/// the words. acme posts the "kill" note, which ends a process; here that -/// is SIGTERM to the terminal's foreground job, and never to the shell, -/// which is its own job and stays. +/// Stop the commands pardes started that are still running. +/// +/// They are the lines pardes typed into a terminal (from an exec, a middle +/// click, a pty/run) and its command panes. Bare, every one; `Kill make ls`, +/// those whose line starts with one of the words. Each gets SIGTERM: a +/// command pane's whole command, a terminal's foreground job, never its +/// shell, which stays. pub const Kill = struct { + // acme's Kill (exec.c, `kill`; acme.c's WKill) posts the "kill" note, + // which ends a process; here a terminal's job between its C and D marks. pub const scope: Scope = .session; pub const takes_arg = true; pub fn run(c: Ctx) void { @@ -462,8 +589,11 @@ pub const Kill = struct { } }; -/// Write the session's panes and layout to the state file, for Restore; -/// `Dump export <path>` writes them to a file of their own instead. +/// Write the session's panes and layout to the state file, for Restore. +/// +/// `Dump export <path>` writes them to a file of their own instead (`~` the +/// home directory). The workspace tag then holds a `Restore <path>` word that +/// brings them back. pub const Dump = struct { pub const scope: Scope = .session; pub const takes_arg = true; @@ -481,8 +611,13 @@ pub const Dump = struct { } }; -/// Replace every pane with those of a dump: the state file's of that label, -/// or a file's; bare, the last one this session made, else the newest. +/// Replace every pane with those of a dump. +/// +/// `Restore <label>`: the state file's dump of that label (History lists +/// them); `Restore <file>`: a dump file's, a path, or the name of a file in +/// the DumpDir or the directory pardes runs in. Bare: the last one this +/// session made, else the newest. A file that is not a dump is said first; +/// then, as Exit, it is refused once while a pane holds unsaved text. pub const Restore = struct { pub const scope: Scope = .session; pub const takes_arg = true; @@ -532,7 +667,9 @@ pub const Restore = struct { }; /// Detach this pardes from its terminal or window, leaving the session -/// running: `pardes attach` (or `pardes-gui attach`) shows it as a client. +/// running. +/// +/// `pardes attach` (or `pardes-gui attach`) shows it again, as a client. pub const Detach = struct { pub const scope: Scope = .session; pub const enabled = pardes.can_attach; @@ -541,8 +678,11 @@ pub const Detach = struct { } }; -/// Take in the shells of a session that died holding them, each as a -/// terminal pane here: the pardes daemon kept their terminals open. +/// Take in the shells of a session that died holding them, each as a terminal +/// here. +/// +/// The pardes daemon kept their terminals open; with none kept for this +/// session, it says so. pub const Adopt = struct { pub const scope: Scope = .session; pub const enabled = pardes.can_attach; @@ -551,9 +691,11 @@ pub const Adopt = struct { } }; -/// Move this session onto the pardes installed since it started, in place: -/// its text, undo, views, terminals with their running shells, and its -/// terminals and windows come along. The pardes daemon moves too. +/// Move this session onto the pardes installed since it started, in place. +/// +/// Its text, undo, views, terminals with their running shells, and its +/// terminals and windows come along; the pardes daemon moves too. A pardes +/// that cannot move to another build in place says so. pub const Upgrade = struct { pub const scope: Scope = .session; pub const enabled = pardes.can_attach; @@ -563,6 +705,10 @@ pub const Upgrade = struct { }; /// Mount another pardes's 9P tree under /n/<name>, given its dial address. +/// +/// `Mount <name> <dial>`, the dial `unix!/path`, a socket's path, +/// `tcp!<numeric-ip>!<port>` or a session's name. One that cannot be reached +/// is said at once, and not kept. pub const Mount = struct { pub const scope: Scope = .session; pub const takes_arg = true; @@ -603,7 +749,7 @@ pub const Mount = struct { } }; -/// Unmount the 9P tree mounted under /n/<name>. +/// Unmount the 9P tree mounted under /n/<name>: `Unmount <name>`. pub const Unmount = struct { pub const scope: Scope = .session; pub const takes_arg = true; @@ -625,7 +771,7 @@ pub const Unmount = struct { // ---- the message row ---- -/// Show its argument on this pane's message row. +/// Show its argument on this pane's message row: `Msg built`. pub const Msg = struct { pub const takes_arg = true; pub const requires_arg = true; @@ -646,7 +792,7 @@ pub const NextColor = struct { } }; -/// List the themes in a pane, each a word to click. +/// List the bundled themes in a +Themes, each a `Theme <name>` line to run. pub const Themes = struct { pub const scope: Scope = .session; pub const output: OutputTraits = .{ .name = config.themes_buffer, .steps = true, .commands = true }; @@ -655,7 +801,9 @@ pub const Themes = struct { } }; -/// Load a theme from a file. +/// Load a theme from a .zon file: `ThemeFile ~/themes/mine.zon`. +/// +/// DumpThemes writes the bundled ones out to start from. pub const ThemeFile = struct { pub const scope: Scope = .session; pub const takes_arg = true; @@ -672,7 +820,10 @@ pub const ThemeFile = struct { } }; -/// Write the bundled themes into the config directory's themes, to edit. +/// Write the bundled themes into the configuration directory's themes, to +/// edit. +/// +/// ThemeFile loads one back. pub const DumpThemes = struct { pub const scope: Scope = .session; pub fn run(c: Ctx) void { @@ -684,7 +835,7 @@ pub const DumpThemes = struct { } }; -/// List the fonts in a pane, each a word to click. +/// List this machine's fonts in a +Fonts, each a `Font <name>` line to run. pub const Fonts = struct { pub const scope: Scope = .session; pub const output: OutputTraits = .{ .name = config.fonts_buffer, .steps = true, .commands = true }; @@ -696,7 +847,10 @@ pub const Fonts = struct { } }; -/// Show the declarations enclosing the top row at the pane's head, on or off. +/// Show, at the pane's head, the declarations its top row is in. +/// +/// `TreeContext on` or `off` sets it; bare, it flips. Only a source file the +/// parser knows has them. pub const TreeContext = struct { pub const takes_arg = true; @@ -728,8 +882,10 @@ fn stateArg(c: Ctx, comptime T: type, comptime builtin_word: []const u8, comptim const OnOff = enum { on, off }; -/// Addons, the libraries that bring kinds of pane: `Addon load <path>`, -/// `Addon unload <name>`, `Addon reload <name>`; bare, the kinds here. +/// Load, unload or reload an addon, a library that brings a kind of pane. +/// +/// `Addon load <path>`, `Addon unload <name>`, `Addon reload <name>`; bare, +/// the kinds here. pub const Addon = struct { pub const scope: Scope = .session; pub const takes_arg = true; @@ -738,8 +894,11 @@ pub const Addon = struct { } }; -/// glyph art over the host's pixels: an image pane's picture, or the -/// kitty graphics a terminal's program placed (yazi's previews) +/// Draw an image pane's picture, or a terminal's kitty graphics, as glyph +/// art. +/// +/// `Petscii on` or `Petscii off` sets it; bare, it flips. A terminal's kitty +/// graphics are the pictures its program placed (yazi's previews). pub const Petscii = struct { pub const needs: PaneKind = .picture; pub const takes_arg = true; @@ -755,7 +914,10 @@ pub const Petscii = struct { } }; -/// the C64 palette or the terminal's own 16 +/// Draw an image pane's glyph art in the C64 palette, or in the terminal's +/// own 16 colours. +/// +/// `Palette commodore` or `Palette terminal` sets it; bare, it flips. pub const Palette = struct { pub const needs: PaneKind = .image; pub const takes_arg = true; @@ -769,7 +931,10 @@ pub const Palette = struct { } }; -/// add the printable ASCII bitmaps to the matcher's glyph set +/// Add the printable ASCII glyphs to those an image pane's glyph art is made +/// of, or take them out. +/// +/// `Ascii on` or `off` sets it; bare, it flips. pub const Ascii = struct { pub const needs: PaneKind = .image; pub const takes_arg = true; @@ -786,14 +951,19 @@ pub const Ascii = struct { // ---- the system clipboard ---- /// Copy the selection to the system clipboard. +/// +/// Every cursor's selection, joined; in an image or a PDF's pane, what it has +/// selected. pub const ClipYank = struct { pub fn run(c: Ctx) void { edit.clipYank(c.p, c.pane, false); } }; -/// helix `<space>Y`: the PRIMARY selection alone, where `SPC y` joins every -/// cursor's. One cursor makes them the same word. +/// Copy the primary selection alone to the system clipboard. +/// +/// ClipYank (`SPC y`) copies every cursor's selection, joined; with one +/// cursor the two are the same. pub const ClipYankMain = struct { pub fn run(c: Ctx) void { edit.clipYank(c.p, c.pane, true); @@ -823,9 +993,11 @@ pub const ClipReplace = struct { // ---- panes and columns ---- -/// acme's Get: the pane's file read again, its unsaved edits refused once -/// as Del refuses them. `Get file` loads that file into the pane instead, -/// the pane taking its name. +/// Read this pane's file again from disk; refused once over unsaved edits, as +/// Del is. +/// +/// `Get <file>` loads that file into the pane instead, the pane taking its +/// name. In a directory's pane, it reads the directory again. pub const Get = struct { pub const takes_arg = true; pub fn run(c: Ctx) void { @@ -861,10 +1033,12 @@ pub const Get = struct { } }; -/// acme's Putall: every pane holding unsaved edits to a file is saved, each -/// as its own Save; one that is refused (changed on disk since, a write -/// that fails) says so and the rest are saved all the same. +/// Save every pane holding unsaved edits to a file, each as its own Save. +/// +/// One that is refused (changed on disk since, a write that fails) says so, +/// and the rest are saved all the same. pub const Putall = struct { + // acme's Putall. pub const scope: Scope = .session; pub fn run(c: Ctx) void { for (c.p.panes, 0..) |slot, id| { @@ -880,10 +1054,13 @@ pub const Putall = struct { } }; -/// acme's Incl, for the session: `Incl dir ...` adds directories a look at a -/// name found nowhere else is tried in (`stdio.h`, `<foo.h>`), bare lists -/// them, `Incl -` empties the list. +/// Add directories where a Look tries a name it finds nowhere else +/// (`stdio.h`, `<foo.h>`). +/// +/// `Incl <dir> ...` adds them, each absolute or from `~`; bare, it lists +/// them; `Incl -` empties the list. The list is the session's. pub const Incl = struct { + // acme's Incl, for the session. pub const scope: Scope = .session; pub const takes_arg = true; pub fn run(c: Ctx) void { @@ -935,9 +1112,11 @@ pub const Incl = struct { } }; -/// Open the plumbing file, the plumber's rules (plumb(6)'s rule sets) in -/// the configuration directory beside `init`: saved, they are the rules in -/// force. Not there yet, it holds `include basic`, the default rules. +/// Open the plumbing file, the plumber's rules, in the configuration +/// directory beside `init`. +/// +/// Saved, they are the rules in force (plumb(6)'s rule sets). Not there yet, +/// it holds `include basic`, the default rules. pub const Plumb = struct { pub const scope: Scope = .session; pub const takes_arg = true; @@ -950,9 +1129,13 @@ pub const Plumb = struct { } }; -/// acme's Zerox: a second pane on this pane's file, the same text, undo and -/// unsaved state, with a scroll and a cursor of its own (File.zerox). +/// Open a second pane on this pane's file: the same text, undo and unsaved +/// state. +/// +/// Each pane keeps a scroll and a cursor of its own. Only a file's pane takes +/// it. pub const Zerox = struct { + // acme's Zerox (File.zerox). pub fn run(c: Ctx) void { if (@import("edit_cmd.zig").busyOn(c.p, c.id)) return c.p.reportFailure(c.id, "Zerox: " ++ @import("edit_cmd.zig").e_busy); const f = c.pane.file orelse return c.p.reportFailure(c.id, "Zerox: only a file pane takes it"); @@ -964,6 +1147,11 @@ pub const Zerox = struct { }; /// Write the pane's text to its file, or to the file its argument names. +/// +/// `Save <path>` writes it there. Bare, a pane with no file of its own (a +/// +New, a list, a terminal) asks for a path; a file at a revision is +/// read-only, written only to a path. Over a file changed on disk since it +/// was read, it warns once. pub const Save = struct { pub const takes_arg = true; pub fn run(c: Ctx) void { @@ -995,7 +1183,10 @@ pub const Save = struct { } }; -/// Open an empty scratch pane, <dir>/+New, in this pane's directory. +/// Open an empty scratch pane, +New, in this pane's directory. +/// +/// It takes the keyboard. Save asks it for a path to write to; past 100 +/// bytes, Exit, Del and Restore ask about its text as about a file's. pub const New = struct { pub const output: OutputTraits = .{ .name = config.scratch_buffer, .doc = true, .saves = true }; pub fn run(c: Ctx) void { @@ -1003,7 +1194,10 @@ pub const New = struct { } }; -/// An empty column right of the keyboard's, its tag taking the keyboard. +/// Make an empty column right of the keyboard's, its tag taking the keyboard. +/// +/// The next pane made from there goes in it. Refused, saying why, when no +/// column fits. pub const Newcol = struct { pub const scope: Scope = .session; pub fn run(c: Ctx) void { @@ -1011,9 +1205,13 @@ pub const Newcol = struct { } }; -/// Close the pane. `Del k` gives its rows to the open pane above it and -/// `Del j` to the one below, each falling back to the other side. Focus on -/// it goes with its rows. +/// Close the pane. +/// +/// `Del k` gives its rows to the pane above it, `Del j` to the one below, +/// each falling back to the other side; bare, from the keyboard between two +/// panes, it asks k or j on the pane's notice band. A docked pane's rows go +/// back to the pane it answers for. Refused once while the pane holds unsaved +/// text (listed in +Unsaved); Del again, nothing edited since, closes it. pub const Del = struct { pub const takes_arg = true; pub fn run(c: Ctx) void { @@ -1057,7 +1255,10 @@ pub const Del = struct { } }; -/// Recolour a terminal's or a +Pager's program colours to the theme, or show them as sent, flipping between them. +/// Recolour a terminal's or a +Pager's program colours to the theme, or show +/// them as sent. +/// +/// Each Filter flips between the two. pub const Filter = struct { pub const needs: PaneKind = .program_colors; pub fn run(c: Ctx) void { @@ -1065,49 +1266,103 @@ pub const Filter = struct { } }; -/// Turn a text's syntax colours off in this view, or on again. -/// The ink layer (File.Layers). +/// Turn this text's syntax colours off in this view, or on again. pub const Syntax = struct { + // The ink layer (File.Layers). pub fn run(c: Ctx) void { if (c.pane.file == null) return c.p.reportFailure(c.id, "Syntax: only a text pane has it"); c.pane.layers.ink = !c.pane.layers.ink; } }; -/// Show a file as it was at revision `rev` (jj), read-only, beside its pane; in such a pane, that file at another revision in its place, or bare, the file. +/// Show this file as it was at a jj revision, read-only, beside its pane. +/// +/// `At <rev>` (`At main`, `At @-`) opens `path@rev`, as a Look at that name +/// does. In such a pane, `At <rev>` turns it to that revision, the cursor's +/// line kept, and bare `At` opens the file itself. What jj refuses is said in +/// jj's words. pub const At = struct { pub const takes_arg = true; pub const run = @import("jj.zig").word; }; -/// Pin the changes `revset` names (jj) on a file's pane and show them in every view of it: a lane each after the line number, a line one added whole green, what the file no longer has as lines of its text where it stood, read-only (a line taken away whole red, each change's description after its last line); bare, shown or not (none pinned yet: `@`). +/// Draw jj's changes to this file on its own pane: a lane each, and what they +/// took away. +/// +/// `Changes <revset>` pins the revset's changes that touched the file on its +/// pane, or a revision's (`notes.md@main`), and shows them in every view of +/// it: `Changes @-::@`, `Changes trunk()..@`. One set a pane: a later Changes +/// or Compare replaces it. Bare: hidden, or shown again; with none pinned +/// yet, `@`. +/// +/// Each change gets a lane after the line number. What the file no longer has +/// stands where it stood as lines of the pane's text with no number, +/// read-only: the cursor, a selection, a search, B2 and B3 work there, and an +/// edit that touches one is refused. After a change's last line comes its +/// description, `id title author age`, its lane ending in an arrow at it; a +/// long one wraps. `] g` and `[ g` step through the changes; B3 on a +/// description's id opens that change's patch at that line +/// (`Diff <id> <path>:<line>`). pub const Changes = struct { pub const takes_arg = true; pub const run = @import("jj.zig").changesWord; }; -/// Pin on a file's pane the file's whole difference between each two of `points` (jj revisions, a blank between, two or more) as one change, however many changes lie between them, and show them in every view of it as `Changes` shows a change: a lane each, the lines it wrote and took away, its row `from..to N changes dates` after its last line; bare, as bare `Changes`. +/// Draw the file's difference between each two jj revisions as one change, as +/// Changes draws one. +/// +/// `Compare <rev> <rev> [<rev> ...]`: two points or more in their order, each +/// one revision (a commit or change id, a bookmark, `master@origin`, `@`): +/// `Compare 9ef6312813 ea63317630 master@origin`. A pair is drawn as one +/// change however many lie between its points; after its last line, its row: +/// the two points, how many changes lie between them, their first and last +/// days. One set a pane: a later Changes or Compare replaces it. Bare: as +/// bare Changes. pub const Compare = struct { pub const takes_arg = true; pub const run = @import("jj.zig").compareWord; }; -/// Count, for each declaration of a file's pane, the changes in `window` (jj) that touched it, and show it in this view: a heat lane after the line number and a strip by the scroll thumb, the line numbers' grey to the theme's red on a log scale; `window` a revset or a span of time (`3d`, `2w`, `6m`, `1y`); bare, shown here or not (none counted yet: the file's whole history). +/// Show how many changes touched each declaration of this file, as a heat +/// lane. +/// +/// `Churn <window>`: a revset, or a span of time back from now (`3d`, `2w`, +/// `6m`, `1y`). In this view a cell after the line number, from the line +/// numbers' grey to the theme's red on a log scale, and a strip by the scroll +/// thumb. Bare: hidden in this view or shown again; with none counted yet, +/// the file's whole history. pub const Churn = struct { pub const takes_arg = true; pub const run = @import("jj.zig").churnWord; }; -/// Stack a diff's hunks as a diff viewer shows them, each under its place and the declarations around it, in a +Diff; on a +Diff, show the diff itself as text. `Diff <file>` stacks that diff's, `Diff <revision>` git show's. -/// The diff viewer's one registration: its word and traits here, all else -/// its own (hunks.zig). +/// Show a diff's hunks stacked in a +Diff, each under its place, as a diff +/// viewer shows them. +/// +/// Bare, on a diff (a .diff, a .patch, a +Pager holding one): its hunks +/// stacked; on a +Diff: the diff itself, as text. `Diff <file>`: that .diff's +/// or .patch's hunks. `Diff <hash>` (7 to 40 hex digits): `git show` of that +/// commit, in its own `+Diff-<hash>`. `Diff <change> [path[:line]]` (a jj +/// change id): its patch, its header and whole message on top, the cursor at +/// that place. `Diff <from>..<to> [path[:line]]`: the difference between two +/// points, the changes between them on top. +/// +/// Each hunk stands under its `path:line` and the declarations around it, a + +/// or - before each line, the words a changed line changed tinted. `SPC j n` +/// and `SPC j p` step through the hunks; B3 on a place opens it. pub const Diff = struct { + // The diff viewer's one registration: its word and traits here, all else + // its own (hunks.zig). pub const takes_arg = true; pub const output: OutputTraits = .{ .name = config.diff_buffer, .steps = true, .locations = true }; pub const run = @import("hunks.zig").word; }; -/// Cycle the pane's input modes: terminals add raw tty mode to normal/insert. +/// Step this pane to its next input mode: normal, insert, and in a terminal +/// raw. +/// +/// From the last it goes back to normal. The keyboard goes to the pane's +/// text. pub const Mode = struct { pub fn run(c: Ctx) void { if (c.pane.file == null and !c.pane.isTerminal()) return c.p.reportFailure(c.id, "Mode: only a text or terminal pane has modes"); @@ -1115,7 +1370,8 @@ pub const Mode = struct { } }; -/// Switch this terminal between raw program input and normal editor mode. +/// Switch this terminal between raw mode, its keys the program's, and normal +/// mode. pub const Togglettymode = struct { pub const needs: PaneKind = .terminal; pub fn run(c: Ctx) void { @@ -1123,12 +1379,16 @@ pub const Togglettymode = struct { } }; -/// acme's Edit (exec.c `edit`, edit.c): sam's command language over the -/// open text panes, from a tag, a pane ctl or exec, starting in the pane's -/// body. One undo step in each file it changes; a failure changes nothing -/// and says why. core/edit_cmd.zig runs it; core/sam_edit.zig has what is -/// left out. +/// Run a command of sam's language over the open text panes, starting in this +/// pane's body. +/// +/// `Edit ,s/old/new/g` changes every old to new in this pane's text. As +/// acme's Edit: from a tag, a pane's ctl or an exec; one undo step in each +/// file it changes; a failure changes nothing and says why. Left out of +/// sam's: the `'` address, `B <cmd` and `D <cmd`, and `\1` to `\9` in `s`. pub const Edit = struct { + // acme's Edit (exec.c `edit`, edit.c). core/edit_cmd.zig runs it; + // core/sam_edit.zig has what is left out. pub const takes_arg = true; pub const requires_arg = true; pub fn run(c: Ctx) void { @@ -1136,12 +1396,12 @@ pub const Edit = struct { } }; -/// acme's Undo and Redo (exec.c `undo`): step the pane's body back or -/// forward through its edits, from a tag, a pane ctl or exec. -/// With no step left, Undo and Redo say so and change nothing; a ctl write -/// of them still succeeds, as acme's Undo is silent there. A file keeps -/// limits.undo_max steps (256). +/// Step the pane's text back one edit. +/// +/// With no step left, it says so and changes nothing (a ctl write of it still +/// succeeds, as acme's Undo is silent there). A file keeps 256 steps. pub const Undo = struct { + // acme's Undo and Redo (exec.c `undo`); limits.undo_max steps. pub fn run(c: Ctx) void { if (@import("edit_cmd.zig").busyOn(c.p, c.id)) return c.p.reportFailure(c.id, "Undo: " ++ @import("edit_cmd.zig").e_busy); if (c.pane.file) |f| if (f.history.journal.done == 0) return c.p.setMessage(.at(c.id), "Undo: nothing to undo"); @@ -1149,7 +1409,9 @@ pub const Undo = struct { } }; -/// Redo the last undone edit. +/// Step the pane's text forward again, one edit Undo took back. +/// +/// With none left, it says so and changes nothing. pub const Redo = struct { pub fn run(c: Ctx) void { if (@import("edit_cmd.zig").busyOn(c.p, c.id)) return c.p.reportFailure(c.id, "Redo: " ++ @import("edit_cmd.zig").e_busy); @@ -1158,16 +1420,17 @@ pub const Redo = struct { } }; -/// Fold a pane to its tag, or restore its share of the column. +/// Fold this pane to its tag, or give it its share of the column again. pub const Collapse = struct { pub fn run(c: Ctx) void { layout.toggleCollapse(c.p, c.id); } }; -/// Undock a pane from the pane it answers for: it stays where it is, a -/// pane of its own, and the next search from that pane opens another -/// under it. +/// Undock a pane from the pane it answers for: it stays where it is, a pane +/// of its own. +/// +/// The next search from that pane opens another under it. pub const Undock = struct { pub fn run(c: Ctx) void { if (c.pane.docked_to == null) return c.p.reportFailure(c.id, "Undock: not docked to a pane"); @@ -1175,7 +1438,11 @@ pub const Undock = struct { } }; -/// Close this column and its panes, refusing once over unsaved text. +/// Close this column and its panes. +/// +/// The column is the one whose tag it ran from, else the pane's. Refused once +/// while a pane in it holds unsaved text, the notice saying how many; Delcol +/// again, nothing edited since, closes them. pub const Delcol = struct { pub fn run(c: Ctx) void { // The column of the tag it came from, else the pane's: a pane ctl's @@ -1188,24 +1455,26 @@ pub const Delcol = struct { } }; -/// Close the pane, giving its rows to the pane above it. +/// Close the pane, giving its rows to the pane above it, as `Del k` does. pub const DelAbove = struct { pub fn run(c: Ctx) void { Del.run(.{ .p = c.p, .pane = c.pane, .id = c.id, .txt = c.txt, .arg = "k" }); } }; -/// Close the pane, giving its rows to the pane below it. +/// Close the pane, giving its rows to the pane below it, as `Del j` does. pub const DelBelow = struct { pub fn run(c: Ctx) void { Del.run(.{ .p = c.p, .pane = c.pane, .id = c.id, .txt = c.txt, .arg = "j" }); } }; -/// A shell in the calling pane's directory, raw from the first frame. On every -/// pane's tagline: the fast path from wherever you are to a prompt there. -/// A terminal below the caller in its directory: the configured shell, or -/// the one named, `Term fish`, as a terminal's own tag word `Term+fish` says. +/// Open a terminal below this pane, in its directory, raw: its keys the +/// shell's at once. +/// +/// `Term fish` runs that shell instead of the Shell setting's, as a +/// terminal's own tag word `Term+fish` says; a shell that is not there is +/// said. A directory that is not there makes no terminal. pub const Term = struct { pub const takes_arg = true; pub const plus_arg = true; @@ -1226,18 +1495,19 @@ pub const Term = struct { } }; -/// Binds this terminal as a language's REPL, so an exec on that language's -/// files is typed into it instead of run. The language is named as the -/// syntax table has it: an exec made on the body of a file in that -/// language -- a middle click, the execute key, a single word like `ls` -/// as much as a selection -- and one made on this terminal's own body, is -/// typed into it (bracketed paste if its program asked for that, else line -/// by line, then Enter) instead of run. `Repl python` binds (again, it is -/// already); `Repl -` unbinds; `Repl` bare says what it is bound as. With -/// several bound for a language, the exec asks which. -/// Still commands, whatever is bound: a word in a tag, `Exec <text>` run by -/// name (typed, a 2-1 chord onto Exec, a ctl line), and a command word -/// @`cmd` in the text, looked at or clicked. +/// Bind this terminal as a language's REPL: an exec on that language's files +/// is typed into it. +/// +/// `Repl python` binds it (the language named as a code fence names it: `py`, +/// `Python`, `sh`); `Repl -` unbinds it; bare, it says what it is bound as. +/// An exec made on the body of a file in that language (a middle click, the +/// execute key, a single word like `ls` as much as a selection), and one made +/// on this terminal's own body, is typed into it (bracketed paste if its +/// program asked for that, else line by line, then Enter) instead of run. +/// With several bound for a language, the exec asks which. +/// +/// Still commands, whatever is bound: a word in a tag, `Exec <text>`, a ctl +/// line, and a command word @`cmd` in the text, looked at or clicked. pub const Repl = struct { pub const takes_arg = true; pub fn run(c: Ctx) void { @@ -1304,8 +1574,10 @@ pub const Repl = struct { } }; -/// Fold the active pane's column into the one on its right, keeping its panes. -/// The horizontal mirror of the vertical stacking `New` does. +/// Fold the keyboard's column into the one on its right, keeping its panes. +/// +/// Refused for the last column, and where the joined column could not give +/// each pane its tag and 2 rows. pub const Joincol = struct { pub const scope: Scope = .session; pub fn run(c: Ctx) void { @@ -1329,17 +1601,31 @@ pub const Tutor = struct { } }; -/// Open the help: every key and every builtin. +/// Show every builtin with its keys and documentation, or one builtin's alone. +/// +/// `Help <name>`: that builtin alone, its keys spelled out, what it acts on +/// and its line for a shell (`Help Diff`); a setting or an addon's word the +/// same. `Help <keys>`: the builtins under SPC and those keys (`Help l`, as +/// `SPC l ?` shows them). Each fills the one +Help: a second Help replaces +/// its text. pub const Help = struct { pub const scope: Scope = .session; + pub const takes_arg = true; pub const output: OutputTraits = .{ .name = config.help_buffer }; pub fn run(c: Ctx) void { - panes.Output.openHelp(c.p, c.id, "") catch |err| c.p.reportError(.at(c.id), "help", err); + const what = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); + if (what.len == 0) return panes.Output.openHelp(c.p, c.id, "") catch |err| c.p.reportError(.at(c.id), "help", err); + const found = panes.Output.openHelpOn(c.p, c.id, what) catch |err| return c.p.reportError(.at(c.id), "help", err); + if (found) return; + var said: pardes.Kind.Buf(128) = .{}; + c.p.reportFailure(c.id, said.print("Help: {s}: no such builtin, nor SPC keys", .{what[0..@min(what.len, 64)]})); } }; -/// Open the startup file, `init`, in a pane: its pane when it is open, else -/// the file, else a pane of that name for Save to make it and its directory. +/// Open the startup file, `init` in the configuration directory, in a pane. +/// +/// Its pane when it is open, else the file; not there yet, a pane of that +/// name, which Save makes, its directory too. pub const Config = struct { pub const scope: Scope = .session; pub fn run(c: Ctx) void { @@ -1375,8 +1661,10 @@ fn openConfigFile(c: Ctx, name: []const u8, path: []const u8, initial: []const u c.p.view().active = free; } -/// Open the settings in effect, each a word to click, and the startup -/// file's path. +/// Show the settings in effect in a +DumpConfig, as lines the startup file +/// takes. +/// +/// The startup file's path with them; a line run there is that setting. pub const DumpConfig = struct { pub const scope: Scope = .session; pub const output: OutputTraits = .{ .name = config.dump_config_buffer }; @@ -1385,7 +1673,12 @@ pub const DumpConfig = struct { } }; -/// Set how location rows are drawn, or show how they are when bare. +/// Set how a list's location rows are drawn: `LocationsConfig layout:inline +/// context:2`. +/// +/// Its fields: `context:<lines>` around each, `tscontext:on|off`, +/// `tslocations:on|off`, `layout:inline|stacked`; those not given stay. Bare, +/// it shows them in a +LocationsConfig. pub const LocationsConfig = struct { pub const scope: Scope = .session; pub const takes_arg = true; @@ -1416,7 +1709,7 @@ pub const LocationsConfig = struct { } }; -/// Open the messages shown so far. +/// Show the messages said so far in a +Messages. pub const Messages = struct { pub const scope: Scope = .session; pub const output: OutputTraits = .{ .name = config.messages_buffer }; @@ -1425,10 +1718,12 @@ pub const Messages = struct { } }; -/// This build: its version, commit, jj change and build time (a stamped -/// build's: a release or the ~/.local install), the zig that built it, its -/// optimize mode, target, platform, grammars, whether the addons are compiled -/// in, and its dependencies, printed into an output buffer. +/// Show this build in a +Build: its version, compiler, optimize mode, target +/// and dependencies. +/// +/// A stamped build's (a release, or the ~/.local install) commit, jj change +/// and build time too, its platform, its grammars, and whether the addons are +/// compiled in. pub const Build = struct { pub const scope: Scope = .session; pub const output: OutputTraits = .{ .name = config.build_buffer }; @@ -1437,8 +1732,7 @@ pub const Build = struct { } }; -/// This build's version and what changed to reach it, printed into an output -/// buffer the same way Config prints the live settings. +/// Show this build's version and what changed to reach it, in a +Changelog. pub const Changelog = struct { pub const scope: Scope = .session; pub const output: OutputTraits = .{ .name = config.changelog_buffer }; @@ -1447,7 +1741,10 @@ pub const Changelog = struct { } }; -/// Open a minimap of the file in braille dots. +/// Map a file of this pane's directory in braille dots: `Mini notes.txt`. +/// +/// A pane of its own, drawn once: a Mini of the same file again draws it +/// anew. pub const Mini = struct { pub const takes_arg = true; pub const requires_arg = true; // a file to map: bare, wrong #args (EINVAL) @@ -1466,7 +1763,12 @@ pub const Mini = struct { const e_search_miss_find = "Find: name not found"; const e_search_miss_grep = "Grep: text not found"; -/// List the files below this pane's directory whose names hold its argument, in a +Search. +/// List the files below this pane's directory whose names match its argument. +/// +/// A query pane under this pane, its line 1 `Find <name>`, the files under it +/// by a fuzzy match of their names: with a word, listed, the keyboard left +/// where it was; bare (`SPC f f`), typed into. Enter or B3 on a row opens +/// that file. A script's Find that finds nothing fails, `not found`. pub const Find = struct { pub const takes_arg = true; // A script's Find names what to find (bare, it is a key's prompt). @@ -1476,8 +1778,13 @@ pub const Find = struct { } }; -/// Find's sibling: Find matches file NAMES under this pane's directory, Grep -/// matches the LINES of those files, on the disk engine's worker. +/// List the lines of the files below this pane's directory that hold its +/// argument. +/// +/// The text is matched as it is, not as a pattern, in a query pane under this +/// pane, its line 1 `Grep <text>`: with a word, listed, the keyboard left +/// where it was; bare (`SPC f g`), typed into. Past 2000 lines it stops, and +/// More goes on. A script's Grep that finds nothing fails, `not found`. pub const Grep = struct { pub const takes_arg = true; pub const requires_arg = true; @@ -1503,8 +1810,13 @@ fn search(c: Ctx, source: panes.Query.Source, miss: []const u8) void { c.p.reportFailure(c.id, miss); } -/// Search in a query pane under this pane, line 1 the argument (`Panes`, -/// `Symbols lay`, `All needle`, `/re`, any of its words); bare, `/`. +/// Search in a query pane under this pane, its line 1 the argument. +/// +/// Line 1's first word names what it searches: `/re` this pane's text, +/// `Find`, `Grep`, `Recent`, `Panes`, `Symbols`, `All` (every open pane's +/// text), `Refs`, `Def`, `Impl`, `Diagnostics`; a line with none of them is a +/// `/`: `Search lay` is `/lay`. Bare, `/`, typed into. `SPC b b`, `SPC s s` +/// and `SPC /` open it with Panes, Symbols and All. pub const Search = struct { pub const takes_arg = true; pub const quiet = true; @@ -1515,7 +1827,7 @@ pub const Search = struct { } }; -/// A query pane's Grep stopped at its 2000 lines goes on for 2000 more. +/// Let a query pane's Grep stopped at its 2000 lines go on for 2000 more. pub const More = struct { pub const quiet = true; pub fn run(c: Ctx) void { @@ -1523,7 +1835,11 @@ pub const More = struct { } }; -/// Pick an open pane by its name in a query pane under this one (SPC b b). +/// Pick a pane by its name, in a query pane under this one. +/// +/// The open panes, then those closed this session, `(closed)`: Enter on one +/// goes to it, or brings a closed one back where it was, its text with it. +/// `Panes <name>` narrows them; `SPC b b` opens the same query. pub const Panes = struct { pub const takes_arg = true; pub const quiet = true; @@ -1549,7 +1865,7 @@ pub const Left = struct { } }; -/// Move the keyboard to the pane below, off a tag onto the pane under it. +/// Move the keyboard to the pane below, or off a tag onto the pane under it. pub const Down = struct { pub fn run(c: Ctx) void { if (c.p.view().header != null) { @@ -1568,7 +1884,8 @@ pub const Down = struct { } }; -/// Move the keyboard to the pane above, and from a column's top pane to its tag. +/// Move the keyboard to the pane above, and from a column's top pane to its +/// tag. pub const Up = struct { pub fn run(c: Ctx) void { if (c.p.view().header != null) { @@ -1593,10 +1910,12 @@ pub const Right = struct { } }; -/// Emacs's follow-mode: one text across a chain of panes as consecutive -/// pages, each going on where the one before ends, scrolled as one. Adds a -/// page, a Zerox twin, at the end of the column right of the chain's last, -/// or in a new column there; its tag has Unfollow. +/// Show one text across a chain of panes as consecutive pages, scrolled as +/// one. +/// +/// As Emacs's follow-mode: each page goes on where the one before ends. Each +/// Follow adds a page, a Zerox of the text, at the end of the column right of +/// the chain's last, or in a new column there; its tag has Unfollow. pub const Follow = struct { pub fn run(c: Ctx) void { if (@import("edit_cmd.zig").busyOn(c.p, c.id)) return c.p.reportFailure(c.id, "Follow: " ++ @import("edit_cmd.zig").e_busy); @@ -1634,8 +1953,10 @@ pub const Follow = struct { } }; -/// Take this pane out of its Follow chain: it stays, a Zerox twin with the -/// scroll it has, and the chain closes up behind it. +/// Take this pane out of its Follow chain. +/// +/// It stays, a Zerox twin with the scroll it has, and the chain closes up +/// behind it. pub const Unfollow = struct { pub fn run(c: Ctx) void { const f = if (c.pane.file) |*file| file else return c.p.reportFailure(c.id, "Unfollow: this pane is in no Follow chain"); @@ -1644,8 +1965,12 @@ pub const Unfollow = struct { } }; -/// Window mode: h/j/k/l move an outline between the panes; Enter or Esc -/// focuses the outlined pane, `:` its tag, the letter shown on a pane that one; d is Del on it (then k or j between two), c Collapse. +/// Window mode: move an outline between the panes and act on the one +/// outlined. +/// +/// h/j/k/l move the outline; Enter or Esc focuses the outlined pane, `:` its +/// tag, the letter shown on a pane that one; d is Del on it (then k or j +/// between two), c Collapse. pub const Window = struct { pub fn run(c: Ctx) void { tagline.exitHeader(c.p); @@ -1655,7 +1980,9 @@ pub const Window = struct { // ---- the jump group ---- -/// Ctrl-o: one step back into the history. +/// Go one step back in the jump history. +/// +/// A place in a file closed since opens the file again. pub const Back = struct { pub const scope: Scope = .session; pub fn run(c: Ctx) void { @@ -1663,7 +1990,7 @@ pub const Back = struct { } }; -/// Ctrl-i: one step forward again, up to wherever Back started. +/// Go one step forward again in the jump history, up to where Back started. pub const Forward = struct { pub const scope: Scope = .session; pub fn run(c: Ctx) void { @@ -1671,7 +1998,11 @@ pub const Forward = struct { } }; -/// Select the next Look location across panes; Enter opens it. +/// Select the next thing a Look would open: a place in a list, a word that +/// names a file. +/// +/// The walk goes on through the panes in order, the keyboard with it; Enter +/// opens what it selected. pub const LookNext = struct { pub const quiet = true; pub fn run(c: Ctx) void { @@ -1679,7 +2010,9 @@ pub const LookNext = struct { } }; -/// Select the previous Look location across panes; Enter opens it. +/// Select the previous thing a Look would open, as LookNext walks forward. +/// +/// Enter opens what it selected. pub const LookPrev = struct { pub const quiet = true; pub fn run(c: Ctx) void { @@ -1688,6 +2021,8 @@ pub const LookPrev = struct { }; /// Go back to the last place jumped from in another pane. +/// +/// With none, to the pane beside this one. pub const Last = struct { pub fn run(c: Ctx) void { var i = c.p.view().jumps.n; @@ -1704,7 +2039,11 @@ pub const Last = struct { } }; -/// List the files opened lately, closed ones too, each a place to open again. +/// List the files opened lately, closed ones too, in a query pane under this +/// one. +/// +/// `Recent <name>` narrows them by name; bare (`SPC f r`), typed into. Enter +/// opens the current one; B3 on a row, that one. pub const Recent = struct { pub const scope: Scope = .session; pub const takes_arg = true; @@ -1716,12 +2055,15 @@ pub const Recent = struct { } }; -/// List the state file's dumps, those Dump made and those every session's -/// end left (dump.dumpExit), the newest first, each as the command that -/// brings it back, `Restore <label>` on a line of its own, its date, size, -/// pane count and the panes' names indented under it; a click on the -/// Restore (an exec, or a look at the line) is that Restore. +/// List the state file's dumps, newest first, each with the Restore that +/// brings it back. +/// +/// Those Dump made and those every session's end left, in a +History: each a +/// `Restore <label>` line, its date, size and pane count, the panes' names +/// indented under it. B2 on the Restore, or a Look at its line, is that +/// Restore. pub const History = struct { + // A session's end dumps it (dump.dumpExit). pub const scope: Scope = .session; pub const output: OutputTraits = .{ .name = config.history_buffer }; pub fn run(c: Ctx) void { @@ -1733,7 +2075,7 @@ pub const History = struct { } }; -/// List the places jumped from, each a place to go. +/// List the places jumped from in a +Jumps, each a place to go. pub const Jumplist = struct { pub const scope: Scope = .session; pub const output: OutputTraits = .{ .name = config.jumps_buffer, .steps = true, .locations = true }; @@ -1744,8 +2086,11 @@ pub const Jumplist = struct { // ---- the language group ---- -/// Go to the definition of the symbol under the cursor; with an argument -/// (a 2-1 chord's selection), of that symbol, where it is nearest. +/// Go to the definition of the symbol under the cursor. +/// +/// With an argument (a 2-1 chord's selection), of that symbol, asked at its +/// occurrence nearest the cursor. One answer is a jump; several open a list, +/// the keyboard on its current row; none says so. `g d` does the same. pub const Def = struct { pub const takes_arg = true; /// Its answer says what it found, a jump or a list or why not; its @@ -1756,8 +2101,11 @@ pub const Def = struct { } }; -/// List the references to the symbol under the cursor; with an argument -/// (a 2-1 chord's selection), to that symbol, where it is nearest. +/// List the references to the symbol under the cursor. +/// +/// With an argument (a 2-1 chord's selection), to that symbol, asked at its +/// occurrence nearest the cursor; a single reference is a jump. `g r` does +/// the same. pub const Refs = struct { pub const takes_arg = true; pub const quiet = true; // as Def @@ -1766,14 +2114,15 @@ pub const Refs = struct { } }; -/// Ask the language server about the symbol under the cursor. +/// Ask the language server about the symbol under the cursor, its answer in a +/// +Hover. pub const Hover = struct { pub fn run(c: Ctx) void { c.p.lspRequest(c.id, .hover, ""); } }; -/// List the language server's code actions for the cursor. +/// List the language server's code actions for the cursor, in a +Lsp. pub const CodeAction = struct { pub fn run(c: Ctx) void { c.p.lspRequest(c.id, .code_action, ""); @@ -1787,70 +2136,93 @@ pub const SelectRefs = struct { } }; -/// List the file's symbols from the language server. +/// List this file's symbols in a +Search. pub const Symbols = struct { pub fn run(c: Ctx) void { c.p.lspRequest(c.id, .document_symbols, ""); } }; -/// List the file's diagnostics from the language server. +/// List this file's diagnostics in a +Search. +/// +/// `] d` and `[ d` step through them in the text, `] D` and `[ D` to the last +/// and the first. pub const Diagnostics = struct { pub fn run(c: Ctx) void { c.p.lspRequest(c.id, .diagnostics, ""); } }; -/// List the workspace's diagnostics from the language server. +/// List the diagnostics of the whole workspace in a +Search. pub const WsDiagnostics = struct { pub fn run(c: Ctx) void { c.p.lspRequest(c.id, .workspace_diagnostics, ""); } }; -/// Run the file's language indexer at its project root, writing the index.scip the language words ask first. +/// Run the file's language indexer at its project root, writing its +/// index.scip. +/// +/// The language words ask the nearest index.scip above a file first, and its +/// language server only when the index has nothing to say; an index older +/// than the file still answers, and says so once. pub const Index = struct { pub fn run(c: Ctx) void { c.p.lspRequest(c.id, .index, ""); } }; -/// Show outermost callers first, with signatures and call sites (gc). +/// Show the callers of the function under the cursor as a tree, outermost +/// first, in a +Callstack. +/// +/// Each caller with its place to open and its signature, the line of each +/// call under it; callers named for tests after the rest, a recursion marked +/// `↻`. CallstackDepth sets how many levels (8 by default); a deeper tree +/// says where to go on from. `g c` does the same. pub const Callstack = struct { pub fn run(c: Ctx) void { c.p.lspRequest(c.id, .callstack, ""); } }; -/// List the callers of the function under the cursor. +/// List the functions that call the one under the cursor, one level up; a +/// single one is a jump. pub const Callers = struct { pub fn run(c: Ctx) void { c.p.lspRequest(c.id, .incoming_calls, ""); } }; -/// List the functions the function under the cursor calls. +/// List the functions the one under the cursor calls, one level down; a +/// single one is a jump. pub const Callees = struct { pub fn run(c: Ctx) void { c.p.lspRequest(c.id, .outgoing_calls, ""); } }; -/// List the supertypes of the type under the cursor. +/// List the supertypes of the type under the cursor in a +Search; a single +/// one is a jump. pub const Supertypes = struct { pub fn run(c: Ctx) void { c.p.lspRequest(c.id, .supertypes, ""); } }; -/// List the subtypes of the type under the cursor. +/// List the subtypes of the type under the cursor in a +Search; a single one +/// is a jump. pub const Subtypes = struct { pub fn run(c: Ctx) void { c.p.lspRequest(c.id, .subtypes, ""); } }; -/// Rename the symbol under the cursor everywhere, to its argument. +/// Rename the symbol under the cursor to its argument, wherever the language +/// server finds it. +/// +/// Bare, it asks for the new name. Within this file it is done at once, +/// saying how many places changed; one that reaches other files changes +/// nothing and lists its edits in a +Search to look over. pub const Rename = struct { pub const takes_arg = true; pub const requires_arg = true; @@ -1861,7 +2233,8 @@ pub const Rename = struct { } }; -/// Search the workspace's symbols for its argument. +/// Search the workspace's symbols for its argument, in a +Search; bare, it +/// asks for the name. pub const WsSymbols = struct { pub const takes_arg = true; pub const requires_arg = true; @@ -1872,14 +2245,20 @@ pub const WsSymbols = struct { } }; -/// Show which language servers serve this file and their state. +/// Show which index and language server serve this file, and their state, in +/// a +Lsp. +/// +/// The index.scip it asks (or the Index that would write one), its server and +/// the server's state (not started yet, failed and waiting to retry), and +/// what answered each query lately. pub const Lspinfo = struct { pub fn run(c: Ctx) void { c.p.lspRequest(c.id, .status, ""); } }; -/// Explain how the last language server request was answered, step by step. +/// Explain, step by step in a +Lsp, how the last language server request was +/// answered. pub const Lspwhy = struct { pub fn run(c: Ctx) void { c.p.lspRequest(c.id, .explain, ""); @@ -1905,6 +2284,24 @@ fn testDump(buf: []u8) ![]const u8 { return std.fmt.bufPrint(buf, "Restore {s}/d.zon", .{at}); } +test "a builtin's documentation is the whole `///` block above it, a line a paragraph, its summary first" { + const Builtin = registry.Builtin(); + const diff = registry.doc(Builtin.Diff); + try std.testing.expect(std.mem.startsWith(u8, diff.text, diff.summary)); + try std.testing.expect(std.mem.endsWith(u8, diff.summary, ".")); + // Its paragraphs, each its `///` lines joined: the forms in the second. + var paras = std.mem.splitScalar(u8, diff.text, '\n'); + _ = paras.next(); + try std.testing.expect(std.mem.indexOf(u8, paras.next().?, "`Diff <hash>` (7 to 40 hex digits)") != null); + try std.testing.expect(paras.next() != null); + // No note for the code's reader: those are `//` lines in the struct. + try std.testing.expect(std.mem.indexOf(u8, diff.text, "registration") == null); + // A setting's is its own doc. + try std.testing.expectEqualStrings(config.Settings.find("Wrap").?.doc, registry.doc(Builtin.Wrap).text); + // Every builtin has one, its summary a line (the compiler holds both). + for (std.enums.values(Builtin)) |b| try std.testing.expect(registry.doc(b).summary.len > 0); +} + test "capabilities exactly gate setting builtins" { const Builtin = registry.Builtin(); for (config.Settings.settings) |setting| { diff --git a/core/builtins_json.zig b/core/builtins_json.zig index 23e15098..c66775db 100644 --- a/core/builtins_json.zig +++ b/core/builtins_json.zig @@ -1,17 +1,17 @@ //! Every builtin as JSON, for the docs' glossary (docs/typ/builtins-tui.json //! and builtins-gui.json, a build's list each; style.typ merges them): //! the rows the `Help` builtin draws (pardes.builtin_rows: the leader path -//! and the other shortcuts) with what /commands says of each word (its doc -//! comment's first sentence, or a setting's doc), then the shipped addons' -//! words, read off their kinds' `Word` lines (`"addon"` first, so a search -//! for a builtin's `{"name": ` never meets one). One source, so the -//! glossary and Help cannot drift; the test below fails when the committed -//! copy is stale, and `zig build builtins-json` rewrites it. +//! and the other shortcuts) with each word's documentation (registry.doc: +//! `doc` its summary, what /commands says, and `text` all of it), then the +//! shipped addons' words, read off their kinds' `Word` lines (`"addon"` +//! first, so a search for a builtin's `{"name": ` never meets one; `text` +//! their one sentence). One source, so the glossary and Help cannot drift; +//! the test below fails when the committed copy is stale, and `zig build +//! builtins-json` rewrites it. const std = @import("std"); const pardes = @import("root.zig"); const builtins = @import("builtins.zig"); const config = @import("config.zig"); -const ctl = @import("ninep/ctl.zig"); const str = std.json.Stringify.encodeJsonString; @@ -70,10 +70,11 @@ pub fn write(w: *std.Io.Writer, addon_sources: []const []const u8) std.Io.Writer try w.writeAll(if (setting != null) "true" else "false"); try w.writeAll(", \"choices\": "); if (setting) |s| if (config.Settings.choices(s.action)) |v| try str(v, .{}, w) else try w.writeAll("null") else try w.writeAll("null"); - var buf: [2048]u8 = undefined; - const doc = if (setting) |s| s.doc else ctl.summaryOf(name, &buf); + const doc = builtins.registry.doc(b); try w.writeAll(", \"doc\": "); - try str(doc, .{}, w); + try str(doc.summary, .{}, w); + try w.writeAll(", \"text\": "); + try str(doc.text, .{}, w); try w.writeByte('}'); } // A kind's word is a line of its own: `.{ .name = "PdfFit", .leader = @@ -91,8 +92,11 @@ pub fn write(w: *std.Io.Writer, addon_sources: []const []const u8) std.Io.Writer for (l) |c| try w.print(" {c}", .{c}); try w.writeByte('"'); } else try w.writeAll("null"); - try w.print(", \"also\": [], \"arg\": {}, \"scope\": \"pane\", \"setting\": false, \"choices\": null, \"doc\": ", .{std.mem.indexOf(u8, line, ".arg = .") != null}); - try str(quoted(line, ".doc = ") orelse "", .{}, w); + try w.print(", \"also\": [], \"arg\": {}, \"scope\": \"pane\", \"setting\": false, \"choices\": null", .{std.mem.indexOf(u8, line, ".arg = .") != null}); + for ([_][]const u8{ "doc", "text" }) |field| { + try w.print(", \"{s}\": ", .{field}); + try str(quoted(line, ".doc = ") orelse "", .{}, w); + } try w.writeByte('}'); } } diff --git a/core/config.zig b/core/config.zig index a2911dad..e9225c53 100644 --- a/core/config.zig +++ b/core/config.zig @@ -799,10 +799,10 @@ pub const Settings = struct { .{ .word = "InactiveDim", .action = .inactive_dim, .doc = "Fade the unfocused panes' text by a percentage, 0 through 100, 0 off." }, .{ .word = "Pet", .action = .{ .choice = .pet }, .doc = "The window's companion in the workspace tag's blank space: off, cat or frog." }, .{ .word = "MessageLinger", .action = .message_linger, .doc = "How long, in milliseconds, a message stays after what dismisses it." }, - .{ .word = "DumpDir", .action = .dump_dir, .doc = "The directory of the state file Dump writes to and Recent is kept in, where a relative Restore name is looked for too; bare, the default." }, - .{ .word = "Theme", .action = .theme, .doc = "Switch to the named theme." }, - .{ .word = "Shell", .action = .shell, .doc = "The shell new terminals run; bare, $SHELL if it is executable, else /bin/sh." }, - .{ .word = "Font", .action = .font, .doc = "The body font, by name or path, and its size." }, + .{ .word = "DumpDir", .action = .dump_dir, .doc = "The directory of the state file, where Dump writes and Recent is kept. A relative Restore name is looked for there too; bare, the default." }, + .{ .word = "Theme", .action = .theme, .doc = "Switch to the theme named: `Theme atelier`. Themes lists them, NextColor steps through them." }, + .{ .word = "Shell", .action = .shell, .doc = "The shell new terminals run: `Shell /bin/zsh`; bare, $SHELL if it is executable, else /bin/sh." }, + .{ .word = "Font", .action = .font, .doc = "The body font, by name or path, and its size after a colon: `Font Mono:14`. Fonts lists them." }, .{ .word = "TaglineSize", .action = .tagline_size, .doc = "Scale the tag font, a percentage." }, .{ .word = "WindowOpacity", .action = .window_opacity, .doc = "The window's opacity, a percentage." }, .{ .word = "CallstackDepth", .action = .callstack_depth, .doc = "Caller levels collected by Callstack, 1 through 64; default 8. Bare, it says the current limit." }, diff --git a/core/draw.zig b/core/draw.zig index 8198e2ff..5263f7bf 100644 --- a/core/draw.zig +++ b/core/draw.zig @@ -279,7 +279,11 @@ fn joinNotice(p: *Pardes, s: *Surface, arena: std.mem.Allocator, region: Region) // A notice wider than its band has less padding than the band hides. for (skip..@max(skip, @min(pad, skip + chip))) |col| s.at(region.rect.x + @as(u16, @intCast(col - skip)), region.rect.y).style.fg = .default; if (layer.cursor) |caret| { - if (caret.x >= skip) s.cursor = .{ .x = region.rect.x + caret.x - @as(u16, @intCast(skip)), .y = region.rect.y, .bar = caret.bar }; + // Counted wide: a band of 65535 glyphs (Layer.capacity's bound, which + // a frontend's row metrics reach) puts its caret past u16, and past + // the grid, where it is not drawn. + const x = @as(u32, region.rect.x) + caret.x; + if (caret.x >= skip and x - skip < s.cols) s.cursor = .{ .x = @intCast(x - skip), .y = region.rect.y, .bar = caret.bar }; } } diff --git a/core/fuzz.zig b/core/fuzz.zig new file mode 100644 index 00000000..f324a48e --- /dev/null +++ b/core/fuzz.zig @@ -0,0 +1,773 @@ +//! The boundaries' fuzzes: bytes the core did not make, garbage and +//! mutated-valid, into the reader that takes them, on a fixed list of +//! seeds and a bound of seconds. Each holds one rule: an error, never a +//! panic, never a hang, memory bounded (`Capped`, and the testing +//! allocator's leak check at the end). A seed that fails is a run of its +//! own again: `-Dtest-filter` and the seed alone in `seeds`. +const std = @import("std"); +const pardes = @import("root.zig"); +const ninep = @import("runtime").ninep; +const th = @import("ninep/harness.zig"); +const Pardes = pardes.Pardes; +const Random = std.Random; +const testing = std.testing; + +const seeds = [_]u64{ 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597 }; + +/// An allocator over `child` that refuses one allocation past `one` and a +/// total past `all`, and counts what it refused: a reader that sizes an +/// allocation by a count the outside gave shows here, not as a machine +/// out of memory. +const Capped = struct { + child: std.mem.Allocator, + one: usize, + all: usize, + live: usize = 0, + refused: usize = 0, + + fn allocator(c: *Capped) std.mem.Allocator { + return .{ .ptr = c, .vtable = &.{ .alloc = alloc, .resize = resize, .remap = remap, .free = free } }; + } + fn room(c: *Capped, more: usize) bool { + if (more <= c.one and c.live + more <= c.all) return true; + c.refused += 1; + return false; + } + fn alloc(ctx: *anyopaque, len: usize, a: std.mem.Alignment, ret: usize) ?[*]u8 { + const c: *Capped = @ptrCast(@alignCast(ctx)); + if (!c.room(len)) return null; + const got = c.child.rawAlloc(len, a, ret) orelse return null; + c.live += len; + return got; + } + fn resize(ctx: *anyopaque, m: []u8, a: std.mem.Alignment, len: usize, ret: usize) bool { + const c: *Capped = @ptrCast(@alignCast(ctx)); + if (len > m.len and !c.room(len - m.len)) return false; + if (!c.child.rawResize(m, a, len, ret)) return false; + c.live = c.live - m.len + len; + return true; + } + fn remap(ctx: *anyopaque, m: []u8, a: std.mem.Alignment, len: usize, ret: usize) ?[*]u8 { + const c: *Capped = @ptrCast(@alignCast(ctx)); + if (len > m.len and !c.room(len - m.len)) return null; + const got = c.child.rawRemap(m, a, len, ret) orelse return null; + c.live = c.live - m.len + len; + return got; + } + fn free(ctx: *anyopaque, m: []u8, a: std.mem.Alignment, ret: usize) void { + const c: *Capped = @ptrCast(@alignCast(ctx)); + c.child.rawFree(m, a, ret); + c.live -= m.len; + } +}; + +fn chance(r: Random, p: f32) bool { + return r.float(f32) < p; +} + +fn pick(r: Random, xs: anytype) @TypeOf(xs[0]) { + return xs[r.uintLessThan(usize, xs.len)]; +} + +/// Random bytes with no byte that starts a shell or a prompt (`!|<>;&$` and +/// the backquote, `:`) and no capital (a builtin's first letter): what the +/// fuzz writes may be run (an exec file, a click, a key) and the core's +/// effects are dropped here, but a word that does its own I/O must never be +/// spelled by chance. +fn tame(r: Random, out: []u8) []u8 { + for (out) |*b| b.* = while (true) { + const c = r.int(u8); + if (std.mem.indexOfScalar(u8, "!|<>;&$`:", c) == null and !(c >= 'A' and c <= 'Z')) break c; + }; + return out; +} + +// --------------------------------------------------------------------------- +// (ii) 9P: frames through the engine pardes runs into its tree. + +const Engine = ninep.Server(pardes.ctlfs, ninep.editor); +const msize = ninep.msize; + +/// The names a walk takes: the tree's own, and the odd ones. Never `os` (the +/// host's files: read and WRITTEN through the tree) nor `n` (other servers). +const odd_names = [_][]const u8{ "", ".", "..", "...", "\x00", "a\x00b", "body\x00", "/", "a/b", "\xff\xfe", "na\xc3\xafve", "0", "1", "2", "3", "4", "9", "64", "99", "-1", "4294967295", "18446744073709551616", "pty", "ctl", "status", "data", "run", "new", "event" }; +const forbidden = [_][]const u8{ "os", "n" }; + +fn walkName(r: Random, buf: []u8) []const u8 { + const top = std.meta.fieldNames(pardes.ctlfs.TopFile); + const pane = std.meta.fieldNames(pardes.ctlfs.PaneFile); + return switch (r.uintLessThan(u8, 10)) { + 0...3 => pick(r, top), + 4...6 => pick(r, pane), + 7, 8 => pick(r, &odd_names), + else => tame(r, buf[0..r.uintAtMost(usize, @min(buf.len, @as(usize, if (chance(r, 0.5)) 300 else 8)))]), + }; +} + +const offsets = [_]u64{ 0, 0, 0, 1, 3, 7, 100, 4095, 4096, 65536, 1 << 31, 1 << 32, (1 << 63) - 1, 1 << 63, std.math.maxInt(u64) }; +const counts = [_]u32{ 0, 1, 7, 64, 4096, 8192, msize - 11, msize, msize + 1, 1 << 31, std.math.maxInt(u32) }; +const words = [_][]const u8{ "", "\n", "\x00", "\xff", "\xc0\x80", "\xe6\x97", "clean\n", "dirty\n", "show\n", "addr=dot\n", "dot=addr\n", "mark\n", "nomark\n", "limit=addr\n", "0\n", "1\n", "#3\n", ",\n", "/alpha/\n", "$\n", "0,$\n", "+\n", "-\n", "m 5 5 0\n", "m 99999 99999 7\n", "m -1 -1 1\n", "m a b c\n", "follow\n", "follow new\n", "lock\n", "unlock\n", "c 2 0\n", "99999999999\n", "-1\n", "\t\t\n", + // A pane's rows (core/locations.zig formatRows): kind, seven numbers, styles, path. + "m 1 0 0 0 0 0 0 5:0+5=7 a.txt\n", "c 3 0 0 0 0 0 0 3:1+2=15 y\n", "m 1 0 0 0 0 9999 9999 4:0+4=keyword.add x\n", "p 18446744073709551615 0 0 0 0 0 0 - x\n", "m 1 4294967296 1 1 1 1 1 2:0+2=string a.txt\nc 2 0 0 0 0 0 0 - b\n" }; + +fn data(r: Random, buf: []u8) []const u8 { + if (chance(r, 0.5)) return pick(r, &words); + const n = switch (r.uintLessThan(u8, 4)) { + 0 => r.uintAtMost(usize, 16), + 1 => r.uintAtMost(usize, 512), + 2 => r.uintAtMost(usize, 8192), + else => r.uintAtMost(usize, msize - 23), + }; + return tame(r, buf[0..@min(n, buf.len)]); +} + +/// The fids a connection walked last: most requests are about them. +const Fids = struct { + recent: [4]u32 = @splat(0), + at: usize = 0, + + fn any(f: *const Fids, r: Random) u32 { + if (chance(r, 0.6)) return pick(r, &f.recent); + return if (chance(r, 0.9)) r.uintLessThan(u32, 12) else pick(r, &[_]u32{ 255, 256, 4096, ninep.nofid, std.math.maxInt(u32) - 1 }); + } + fn fresh(f: *Fids, r: Random) u32 { + const n = if (chance(r, 0.9)) 1 + r.uintLessThan(u32, 11) else f.any(r); + f.recent[f.at % f.recent.len] = n; + f.at += 1; + return n; + } +}; + +/// A path of the tree from its root, mostly; its names in `out`. +fn realPath(r: Random, out: *[16][]const u8) u16 { + const top = std.meta.fieldNames(pardes.ctlfs.TopFile); + const pane = std.meta.fieldNames(pardes.ctlfs.PaneFile); + if (chance(r, 0.4)) { + out[0] = pick(r, top); + return 1; + } + out[0] = "pane"; + out[1] = pick(r, &[_][]const u8{ "1", "2", "3", "4", "new" }); + if (std.mem.eql(u8, out[1], "new")) return 2; + if (chance(r, 0.15)) { + out[2] = "pty"; + out[3] = pick(r, &[_][]const u8{ "ctl", "status", "data", "run" }); + return 4; + } + out[2] = if (chance(r, 0.3)) pick(r, &[_][]const u8{ "rows", "body", "addr", "data", "ctl", "event", "tag" }) else pick(r, pane); + return 3; +} + +/// One request, valid in its encoding, hostile in its values. +fn request(r: Random, f: *Fids, names: *[16][300]u8, buf: []u8) ninep.Msg { + return switch (r.uintLessThan(u8, 22)) { + 0 => .{ .tversion = .{ .msize = pick(r, &[_]u32{ msize, msize, 0, 1, 7, 24, 4096, msize + 24, std.math.maxInt(u32) }), .version = pick(r, &[_][]const u8{ "9P2000", "9P2000", "9P2000.u", "", "9P", "\x00" }) } }, + 1 => .{ .tattach = .{ .fid = f.any(r), .afid = if (chance(r, 0.9)) ninep.nofid else f.any(r), .uname = pick(r, &[_][]const u8{ "user", "", "\x00" }), .aname = pick(r, &[_][]const u8{ "", "pardes", "x" }) } }, + 2 => .{ .tauth = .{ .afid = f.any(r), .uname = "u", .aname = "" } }, + 3 => .{ .tflush = .{ .oldtag = r.int(u16) } }, + 4...7 => walk: { + var m: ninep.Msg = .{ .twalk = .{ .fid = 0, .newfid = 0, .nwname = 0 } }; + if (chance(r, 0.7)) { + m.twalk.nwname = realPath(r, &m.twalk.wname); + // One name of it odd, now and then. + if (chance(r, 0.15)) m.twalk.wname[r.uintLessThan(u16, m.twalk.nwname)] = walkName(r, &names[0]); + } else { + m.twalk.fid = f.any(r); + m.twalk.nwname = if (chance(r, 0.95)) r.uintAtMost(u16, 4) else r.uintAtMost(u16, 16); + for (m.twalk.wname[0..m.twalk.nwname], names[0..m.twalk.nwname]) |*w, *nb| w.* = walkName(r, nb); + } + m.twalk.newfid = f.fresh(r); + break :walk m; + }, + 8, 9 => .{ .topen = .{ .fid = f.any(r), .mode = if (chance(r, 0.7)) pick(r, &[_]u8{ 0, 1, 2, 3, 0x10, 0x11, 0x40, 0x12 }) else r.int(u8) } }, + 10 => .{ .tcreate = .{ .fid = f.any(r), .name = walkName(r, &names[0]), .perm = if (chance(r, 0.5)) pick(r, &[_]u32{ 0o644, 0x80000755, 0 }) else r.int(u32), .mode = r.int(u8) } }, + 11...13 => .{ .tread = .{ .fid = f.any(r), .offset = pick(r, &offsets), .count = pick(r, &counts) } }, + 14...17 => .{ .twrite = .{ .fid = f.any(r), .offset = pick(r, &offsets), .data = data(r, buf) } }, + 18 => .{ .tclunk = .{ .fid = f.any(r) } }, + 19 => .{ .tremove = .{ .fid = f.any(r) } }, + 20 => .{ .tstat = .{ .fid = f.any(r) } }, + else => .{ .twstat = .{ .fid = f.any(r), .stat = .{ + .type = if (chance(r, 0.8)) 0xffff else r.int(u16), + .dev = if (chance(r, 0.8)) 0xffffffff else r.int(u32), + .qid = .{ .type = 0xff, .version = 0xffffffff, .path = if (chance(r, 0.8)) std.math.maxInt(u64) else r.int(u64) }, + .mode = if (chance(r, 0.7)) 0xffffffff else r.int(u32), + .atime = 0xffffffff, + .mtime = if (chance(r, 0.8)) 0xffffffff else r.int(u32), + .length = if (chance(r, 0.5)) std.math.maxInt(u64) else pick(r, &offsets), + .name = if (chance(r, 0.7)) "" else walkName(r, &names[1]), + .uid = "", + .gid = "", + .muid = "", + } } }, + }; +} + +/// A frame the engine will take as one: whether it may be pushed. The +/// stream is framed here as the engine frames it (cloud9 Server.receive), so +/// a mutation that moves a frame's length cannot glue a walk into /os. +fn allowed(frame: []const u8) bool { + const got = ninep.decode(frame) catch return true; // the engine refuses it + switch (got.msg) { + .twalk => |w| for (w.wname[0..@min(w.nwname, w.wname.len)]) |name| { + for (forbidden) |f| if (std.mem.eql(u8, name, f)) return false; + }, + .tattach => |a| for ([_][]const u8{ "", "pardes", "x" }) |ok| { + if (std.mem.eql(u8, a.aname, ok)) break; + } else return false, + else => {}, + } + return true; +} + +fn mutate(r: Random, frame: []u8, len: usize) usize { + switch (r.uintLessThan(u8, 6)) { + 0 => frame[r.uintLessThan(usize, len)] ^= @as(u8, 1) << r.int(u3), + 1 => frame[r.uintLessThan(usize, len)] = r.int(u8), + 2 => return r.uintLessThan(usize, len), // cut, its length left saying more + 3 => { + const n = @min(r.uintAtMost(usize, 64), frame.len - len); + r.bytes(frame[len..][0..n]); + return len + n; // more than it says + }, + 4 => std.mem.writeInt(u32, frame[0..4], pick(r, &[_]u32{ 0, 6, 7, @intCast(len + 1), msize + 1, std.math.maxInt(u32), r.int(u32) }), .little), + else => frame[4] = r.int(u8), // another type + } + return len; +} + +/// Serves what the engine has whole, as runtime/9p_io.zig's `onServe` does +/// with the turn its own: the core's effects are dropped (no save, no +/// shell, no file). +fn serve(p: *Pardes, e: *Engine) void { + while (true) { + const req = e.next() orelse e.retry() orelse break; + const reply = pardes.filesystem.EditHold.retried(&p.fs, req) orelse p.serveFs(req); + p.fs.edit_started = false; + e.reply(&reply, p.fsPayload(reply)); + if (req.op == .release) pardes.ctlfs.runClosedLines(p); + while (p.nextEffect()) |_| {} + e.wrote(e.output().len); + } + // What the pump does between requests (Core.settle), its effects dropped. + pardes.ctlfs.pane.flushPausedBatch(p); + pardes.ctlfs.ctl.fillClosedPagers(p); + pardes.ctlfs.runClosedLines(p); + while (p.nextEffect()) |_| {} + e.wrote(e.output().len); +} + +fn connect(e: *Engine, in: []u8, out: []u8, seed: u64) void { + e.initIn(.{ .in = in, .out = out, .root = pardes.ctlfs.root, .seed = @truncate(seed) }); +} + +fn hangUp(p: *Pardes, e: *Engine) void { + e.hangup(); + serve(p, e); +} + +/// One seed: a connection or more, each greeted (mostly), then requests, +/// some mutated, some garbage. +fn ninepSeed(seed: u64, steps: usize) !void { + var prng: Random.DefaultPrng = .init(seed); + const r = prng.random(); + var cap: Capped = .{ .child = testing.allocator, .one = 64 << 20, .all = 512 << 20 }; + const gpa = cap.allocator(); + const p = try th.withFile(gpa, "alpha beta\ngamma\n\tdelta \xe6\x97\xa5\n"); + defer p.deinit(); + p.fs.write_room = msize - 24; + const e = try testing.allocator.create(Engine); + defer testing.allocator.destroy(e); + e.seq = 0; + const in = try testing.allocator.alloc(u8, msize); + defer testing.allocator.free(in); + const out = try testing.allocator.alloc(u8, 2 * msize); + defer testing.allocator.free(out); + const buf = try testing.allocator.alloc(u8, msize + 128); + defer testing.allocator.free(buf); + const scratch = try testing.allocator.alloc(u8, msize); + defer testing.allocator.free(scratch); + var names: [16][300]u8 = undefined; + var fids: Fids = .{}; + + var c: Conn = .{ .p = p, .e = e, .buf = buf }; + connect(e, in, out, seed); + var greet = true; + // A dirty connection's frames are mutated and garbage comes on it (the + // decoder's); a clean one's are whole, and go deep (the tree's). + var dirty = false; + for (0..steps) |_| { + if (e.protocol.dead or chance(r, 0.004)) { + hangUp(p, e); + connect(e, in, out, r.int(u64)); + greet = true; + dirty = chance(r, 0.25); + fids = .{}; + } + if (greet) { + greet = false; + try c.send(.{ .tversion = .{ .msize = msize, .version = "9P2000" } }, ninep.notag); + try c.send(.{ .tattach = .{ .fid = 0, .afid = ninep.nofid, .uname = "user", .aname = "" } }, c.next()); + } else if (dirty and chance(r, 0.05)) { + const len = r.uintAtMost(usize, 96); + r.bytes(buf[0..len]); // garbage + try push(p, e, buf[0..len]); + } else if (!dirty and chance(r, 0.4)) { + // A file's round: walked, opened, read and written at hostile + // offsets and counts, clunked (or left open). + var w: ninep.Msg = .{ .twalk = .{ .fid = 0, .newfid = fids.fresh(r), .nwname = 0 } }; + w.twalk.nwname = realPath(r, &w.twalk.wname); + const k = w.twalk.newfid; + try c.send(w, c.next()); + try c.send(.{ .topen = .{ .fid = k, .mode = pick(r, &[_]u8{ 0, 1, 2, 2, 0x11, 0x12, 0x40 }) } }, c.next()); + for (0..1 + r.uintLessThan(usize, 4)) |_| try c.send(if (chance(r, 0.6)) + .{ .twrite = .{ .fid = k, .offset = pick(r, &offsets), .data = data(r, scratch) } } + else + .{ .tread = .{ .fid = k, .offset = pick(r, &offsets), .count = pick(r, &counts) } }, c.next()); + if (chance(r, 0.7)) try c.send(.{ .tclunk = .{ .fid = k } }, c.next()); + } else { + const msg = request(r, &fids, &names, scratch); + if (!dirty and (msg == .tversion or msg == .tauth)) continue; + const t: u16 = if (msg == .tversion) ninep.notag else if (!dirty or chance(r, 0.97)) c.next() else pick(r, &[_]u16{ 0, c.tag, ninep.notag }); + const f = ninep.encode(msg, t, buf) catch continue; + const len = if (dirty and chance(r, 0.1)) mutate(r, buf, f.len) else f.len; + try push(p, e, buf[0..len]); + } + // Drawn, as the session draws after a request (and every client). + _ = p.frame_arena.reset(.retain_capacity); + _ = p.render(p.frame_arena.allocator()) catch {}; + } + hangUp(p, e); + try testing.expectEqual(@as(usize, 0), cap.refused); +} + +/// One connection's sending side: each request encoded whole and pushed. +const Conn = struct { + p: *Pardes, + e: *Engine, + buf: []u8, + tag: u16 = 0, + + fn next(c: *Conn) u16 { + c.tag +%= 1; + if (c.tag == ninep.notag) c.tag = 1; + return c.tag; + } + fn send(c: *Conn, msg: ninep.Msg, tag: u16) !void { + const f = ninep.encode(msg, tag, c.buf) catch return; + try push(c.p, c.e, f); + } +}; + +/// Pushes `bytes` a frame at a time, as the engine will frame them, each +/// checked by `allowed`; one that is not ends the connection there. +fn push(p: *Pardes, e: *Engine, bytes: []const u8) !void { + var at: usize = 0; + while (at < bytes.len and !e.protocol.dead) { + const held = e.protocol.in_len; + // The length the engine will read: its own first bytes, or these. + var head: [4]u8 = undefined; + const have = @min(held, 4); + @memcpy(head[0..have], e.protocol.in[0..have]); + const more = @min(4 - have, bytes.len - at); + @memcpy(head[have..][0..more], bytes[at..][0..more]); + if (have + more < 4) { + at += e.push(bytes[at..]); + break; + } + const len = std.mem.readInt(u32, &head, .little); + if (held >= len) break; // a whole frame the engine has not taken yet: the rest goes + if (len < ninep.header_len or len > msize) { + _ = e.push(bytes[at..]); // the engine refuses it and ends the link + serve(p, e); + break; + } + const want = len - held; + if (bytes.len - at < want) { + at += e.push(bytes[at..]); + break; + } + var frame: [msize]u8 = undefined; + @memcpy(frame[0..held], e.protocol.in[0..held]); + @memcpy(frame[held..len], bytes[at..][0..want]); + if (!allowed(frame[0..len])) { + hangUp(p, e); + break; + } + const n = e.push(bytes[at..][0..want]); + at += n; + serve(p, e); + if (n < want) break; + } + serve(p, e); +} + +test "9P: hostile and mutated frames through the engine into the tree: a refusal, never a panic" { + for (seeds) |seed| try ninepSeed(seed, 400); +} + +// --------------------------------------------------------------------------- +// (iii) the wire: a client's messages into the session's reader and core; +// the session's units into a client's. + +const wire = @import("wire"); +const replica = pardes.replica; + +/// Bytes laid out as abi/wire.zig's decoders read them. +const Out = struct { + buf: []u8, + n: usize = 0, + + fn byte(o: *Out, v: u8) void { + if (o.n == o.buf.len) return; + o.buf[o.n] = v; + o.n += 1; + } + fn int(o: *Out, comptime T: type, v: T) void { + var b: [@sizeOf(T)]u8 = undefined; + std.mem.writeInt(T, &b, v, .little); + for (b) |x| o.byte(x); + } + fn bytes(o: *Out, v: []const u8) void { + for (v) |x| o.byte(x); + } +}; + +fn flag(r: Random) u8 { + return if (chance(r, 0.97)) @intFromBool(r.boolean()) else r.int(u8); +} + +fn small(r: Random) u16 { + return if (chance(r, 0.8)) pick(r, &[_]u16{ 0, 1, 2, 5, 23, 24, 79, 80, 81, 127, 128, 511, 512, 513, 4096, 65535 }) else r.int(u16); +} + +fn real(r: Random) u32 { + return if (chance(r, 0.9)) @bitCast(pick(r, &[_]f32{ 0, 1, -1, 0.5, 7.5, -0.0, 1e30, -1e30, 3.4e38, 1e-40, 65535.5 })) else r.int(u32); +} + +fn metrics(o: *Out, r: Random) void { + const some = chance(r, 0.5); + o.byte(if (some) 1 else flag(r)); + if (some) for (0..4) |_| o.int(u16, if (chance(r, 0.9)) 1 + r.uintLessThan(u16, 40) else small(r)); +} + +fn place(o: *Out, r: Random) void { + const rows = small(r); + for ([_]u16{ small(r), small(r), small(r), small(r), small(r), rows, if (chance(r, 0.9)) r.uintAtMost(u16, rows) else small(r) }) |n| o.int(u16, n); +} + +/// A key's code: letters, digits, the specials' plane, and the odd ones. +fn codepoint(r: Random) u32 { + return switch (r.uintLessThan(u8, 6)) { + 0, 1 => pick(r, "abcdefghijklmnopqrstuvwxyz0123456789 .,-_/\t\r"), + 2 => pick(r, &[_]u32{ 0, 0x08, 0x1b, 0x7f, 0x0d, 0xD800, 0xDFFF, 0xFFFD, 0x10FFFF, 0x110000, 0xFFFFFFFF }), + 3 => 0xE000 + r.uintLessThan(u32, 0x1900), + 4 => 0xF0000 + r.uintLessThan(u32, 0x20000), + else => r.uintAtMost(u32, 0x10FFFF), + }; +} + +/// One client message: a frame (tag, length, payload) as the decoder reads +/// it, its shape mostly whole and its values hostile. +fn clientFrame(r: Random, out: []u8, text: []u8) []u8 { + const tags = std.enums.values(wire.ClientTag); + const tag: u8 = if (chance(r, 0.98)) @backingInt(pick(r, tags)) else r.int(u8); + var o: Out = .{ .buf = out }; + o.byte(tag); + o.int(u32, 0); + switch (std.enums.fromInt(wire.ClientTag, tag) orelse .ping) { + .key => { + o.int(u32, codepoint(r)); + const t = tame(r, text[0..if (chance(r, 0.9)) r.uintAtMost(usize, 8) else r.uintAtMost(usize, 300)]); + o.int(u16, @intCast(t.len)); + o.bytes(t); + for (0..3) |_| o.byte(if (chance(r, 0.8)) 0 else flag(r)); + }, + .mouse => { + o.byte(if (chance(r, 0.95)) r.uintLessThan(u8, 10) else r.int(u8)); + o.byte(if (chance(r, 0.95)) r.uintLessThan(u8, 4) else r.int(u8)); + o.int(u16, small(r)); + o.int(u16, small(r)); + for (0..3) |_| o.byte(if (chance(r, 0.8)) 0 else flag(r)); + o.int(u32, real(r)); + // A body hit, then a tag hit. + for (0..2) |which| { + const some = chance(r, 0.4); + o.byte(if (some) 1 else flag(r)); + if (!some) continue; + if (which == 1) { + o.byte(r.uintLessThan(u8, 8)); + o.int(u16, small(r)); + } + o.int(u32, if (chance(r, 0.8)) r.uintLessThan(u32, 6) else r.int(u32)); + o.int(u16, small(r)); + o.int(u16, small(r)); + o.int(u32, real(r)); + o.int(u32, real(r)); + metrics(&o, r); + place(&o, r); + } + }, + .resize => { + o.int(u16, if (chance(r, 0.9)) 1 + r.uintLessThan(u16, wire.max_cols) else small(r)); + o.int(u16, if (chance(r, 0.9)) 1 + r.uintLessThan(u16, wire.max_rows) else small(r)); + o.int(u16, small(r)); + o.int(u16, small(r)); + metrics(&o, r); + }, + .paste => { + const t = tame(r, text[0..r.uintAtMost(usize, 300)]); + o.int(u32, @intCast(t.len)); + o.bytes(t); + }, + .command => { + const t = tame(r, text[0..r.uintAtMost(usize, 64)]); + o.int(u16, @intCast(t.len)); + o.bytes(t); + }, + .focus => o.byte(flag(r)), + .frontend => for (0..3) |_| o.byte(flag(r)), + .pointer_leave => {}, + else => { + const n = r.uintAtMost(usize, 40); + r.bytes(text[0..n]); + o.bytes(text[0..n]); + }, + } + std.mem.writeInt(u32, out[1..5], @intCast(o.n - wire.header_len), .little); + return out[0..o.n]; +} + +/// A client's input as the session's reader takes it (`Peer.take`): its +/// head, a stamp now and then, its event's frame; mutated, or garbage. +fn clientInput(r: Random, out: []u8, text: []u8) []u8 { + if (chance(r, 0.02)) { + const n = r.uintAtMost(usize, 64); + r.bytes(out[0..n]); + return out[0..n]; + } + var o: Out = .{ .buf = out }; + o.int(u16, r.uintLessThan(u16, 4)); + o.int(u32, r.int(u32)); + if (chance(r, 0.1)) { + o.byte(@backingInt(wire.ClientTag.stamp)); + o.int(u32, 16); + o.int(i64, r.int(i64)); + o.int(i64, r.int(i64)); + } + const f = clientFrame(r, out[o.n..], text); + var n = o.n + f.len; + if (chance(r, 0.05)) n = mutate(r, out, n); + return out[0..n]; +} + +fn wireSessionSeed(seed: u64, steps: usize) !void { + var prng: Random.DefaultPrng = .init(seed); + const r = prng.random(); + var cap: Capped = .{ .child = testing.allocator, .one = 64 << 20, .all = 512 << 20 }; + const p = try th.withFile(cap.allocator(), "alpha beta\ngamma\n\tdelta \xe6\x97\xa5\n"); + defer p.deinit(); + const out = try testing.allocator.alloc(u8, 1 << 16); + defer testing.allocator.free(out); + const text = try testing.allocator.alloc(u8, 1 << 15); + defer testing.allocator.free(text); + for (0..steps) |_| { + const msg = clientInput(r, out, text); + // Every tag's decoder, as `Peer.take` and the daemon's hello read them. + if (msg.len > 6) if (wire.framed(msg[6..]) catch null) |f| { + _ = wire.decodeClient(f.tag, f.payload) catch {}; + }; + const in = replica.parseInput(msg) orelse continue; + p.update(in.event); + while (p.nextEffect()) |_| {} + _ = p.frame_arena.reset(.retain_capacity); + _ = p.render(p.frame_arena.allocator()) catch {}; + } + try testing.expectEqual(@as(usize, 0), cap.refused); +} + +test "the wire, a session's side: a client's hostile and mutated inputs are refused or applied, never a panic" { + for (seeds) |seed| try wireSessionSeed(seed, 300); +} + +fn never(_: ?*anyopaque) bool { + return false; +} +const quiet_host: pardes.Host.VTable = .{ .watched = never }; + +/// A session's units from its boot, of inputs a client could send (typing, +/// a paste, sizes, focus, a pointer's motion: nothing that saves or runs). +fn recordedUnits(gpa: std.mem.Allocator, units: *std.ArrayList([]u8)) !void { + const a = try replica.Authority.init(gpa, .{ .cols = 80, .rows = 24 }, .{ .vtable = &quiet_host }); + defer a.deinit(); + try units.append(gpa, try gpa.dupe(u8, try a.unit(0, 0))); + var buf: [256]u8 = undefined; + // Each a tag and its payload, as abi/wire.zig's decodeClient reads it. + const script = [_]struct { wire.ClientTag, []const u8 }{ + .{ .key, "i\x00\x00\x00\x01\x00i\x00\x00\x00" }, + .{ .key, "h\x00\x00\x00\x01\x00h\x00\x00\x00" }, + .{ .paste, "\x0f\x00\x00\x00hello\nworld\n\xe6\x97\xa5" }, + .{ .resize, "\x64\x00\x1e\x00\x0a\x00\x14\x00\x00" }, // 100x30 + .{ .focus, "\x00" }, + .{ .focus, "\x01" }, + .{ .mouse, "\x07\x02\x0a\x00\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" }, // motion at 10,5 + .{ .key, "\x1b\x00\x00\x00\x00\x00\x00\x00\x00" }, // escape + .{ .resize, "\x3c\x00\x14\x00\x0a\x00\x14\x00\x00" }, // 60x20 + .{ .key, "x\x00\x00\x00\x01\x00x\x00\x00\x00" }, + }; + for (0..3) |_| for (script) |s| { + var o: Out = .{ .buf = &buf }; + o.bytes(&@as([6]u8, @splat(0))); + o.byte(@backingInt(s[0])); + o.int(u32, @intCast(s[1].len)); + o.bytes(s[1]); + const in = replica.parseInput(buf[0..o.n]) orelse return error.BadScript; + a.apply(in.event); + a.seq += 1; + try units.append(gpa, try gpa.dupe(u8, try a.unit(0, a.seq))); + }; +} + +fn wireClientSeed(gpa: std.mem.Allocator, units: []const []const u8, seed: u64) !void { + var prng: Random.DefaultPrng = .init(seed); + const r = prng.random(); + var cap: Capped = .{ .child = gpa, .one = 64 << 20, .all = 512 << 20 }; + const copies = try gpa.alloc([]u8, units.len); + defer gpa.free(copies); + for (copies, units) |*c, u| c.* = try gpa.alloc(u8, u.len + 64); + defer for (copies) |c| gpa.free(c); + var lens = try gpa.alloc(usize, units.len); + defer gpa.free(lens); + for (copies, units, lens) |c, u, *n| { + @memcpy(c[0..u.len], u); + n.* = u.len; + // Seed 0 is the units as sent: a replica of them is the session. + if (seed != 0 and chance(r, 0.3)) n.* = switch (r.uintLessThan(u8, 4)) { + 0 => flips: { + for (0..1 + r.uintLessThan(usize, 4)) |_| c[r.uintLessThan(usize, u.len)] ^= @as(u8, 1) << r.int(u3); + break :flips u.len; + }, + 1 => cut: { + break :cut r.uintLessThan(usize, u.len); + }, + 2 => grown: { + r.bytes(c[u.len..][0..64]); + break :grown u.len + r.uintAtMost(usize, 64); + }, + else => set: { + c[r.uintLessThan(usize, u.len)] = r.int(u8); + break :set u.len; + }, + }; + } + const rep = replica.Replica.init(cap.allocator(), 1, copies[0][0..lens[0]]) catch return; + defer rep.deinit(); + for (copies[1..], lens[1..]) |c, n| rep.confirm(c[0..n]); + rep.settle(); + if (seed == 0) try testing.expect(rep.diverged == null); + try testing.expectEqual(@as(usize, 0), cap.refused); +} + +test "the wire, a client's side: a session's units cut, flipped and grown diverge the client, never a panic" { + const gpa = testing.allocator; + var units: std.ArrayList([]u8) = .empty; + defer { + for (units.items) |u| gpa.free(u); + units.deinit(gpa); + } + try recordedUnits(gpa, &units); + try wireClientSeed(gpa, units.items, 0); + for (seeds) |seed| for (0..8) |k| try wireClientSeed(gpa, units.items, seed *% 31 +% k); +} + +// --------------------------------------------------------------------------- +// (iv) a dump and an image read back: a join's (a client loads it before its +// digest is checked: replica.made), a Restore's and an Upgrade's (Db.zig's +// image, the state file's). + +/// `n` bytes of `b` changed as a disk or a peer could: bits flipped, a +/// byte set, a run zeroed, cut, grown (`b` has room past `n`). +fn damage(r: Random, b: []u8, n: usize) usize { + if (n == 0) return n; + switch (r.uintLessThan(u8, 6)) { + 0 => for (0..1 + r.uintLessThan(usize, 4)) |_| { + b[r.uintLessThan(usize, n)] ^= @as(u8, 1) << r.int(u3); + }, + 1 => b[r.uintLessThan(usize, n)] = r.int(u8), + 2 => { + const at = r.uintLessThan(usize, n); + @memset(b[at..][0..@min(n - at, 1 + r.uintLessThan(usize, 16))], 0); + }, + 3 => return r.uintLessThan(usize, n), + 4 => { + const more = @min(b.len - n, r.uintAtMost(usize, 64)); + r.bytes(b[n..][0..more]); + return n + more; + }, + else => { + const at = r.uintLessThan(usize, n); + @memset(b[at..][0..@min(n - at, 8)], 0xff); + }, + } + return n; +} + +fn loadSeed(whole: []const u8, seed: u64) !void { + var prng: Random.DefaultPrng = .init(seed); + const r = prng.random(); + var cap: Capped = .{ .child = testing.allocator, .one = 64 << 20, .all = 512 << 20 }; + const gpa = cap.allocator(); + const b = try testing.allocator.alloc(u8, whole.len + 64); + defer testing.allocator.free(b); + @memcpy(b[0..whole.len], whole); + var n = whole.len; + if (seed != 0) for (0..1 + r.uintLessThan(usize, 3)) |_| { + n = damage(r, b, n); + }; + var why: [256]u8 = undefined; + pardes.dump.check(gpa, b[0..n], &why) catch {}; + var notes: std.ArrayList(u8) = .empty; + defer notes.deinit(gpa); + if (pardes.dump.load(gpa, .{ .cols = 80, .rows = 24 }, b[0..n], ¬es)) |q| { + _ = q.frame_arena.reset(.retain_capacity); + _ = q.render(q.frame_arena.allocator()) catch {}; + q.deinit(); + } else |err| if (seed == 0) return err; + try testing.expectEqual(@as(usize, 0), cap.refused); +} + +test "a dump and an image cut, flipped and grown: refused or loaded, never a panic" { + const gpa = testing.allocator; + const p = try th.withFile(gpa, "alpha beta\ngamma\n\tdelta \xe6\x97\xa5\n"); + defer p.deinit(); + const bytes = try pardes.dump.dumpBytes(p); + defer gpa.free(bytes); + const image = try pardes.dump.image(p, "fuzz"); + defer gpa.free(image); + for ([_][]const u8{ bytes, image }) |whole| { + try loadSeed(whole, 0); + for (seeds) |seed| for (0..8) |k| try loadSeed(whole, seed *% 31 +% k); + } +} + +test "9P: a rows style past the syntax's kinds is refused, never drawn" { + const p = try th.withFile(testing.allocator, "x\n"); + defer p.deinit(); + // A results pane: its rows' styles are what it is painted with. + try pardes.panes.Output.fillResults(p, 0, "/tmp", .search, "foo", try p.gpa.dupe(u8, "a.txt:1:1 foo\nb.txt:2:3 foo\n"), null); + const serial = for (p.panes) |slot| { + const pane = slot orelse continue; + const f = pane.file orelse continue; + if (f.output != null and f.location_rows.len > 0) break pane.serial; + } else return error.NoSearch; + const rows = pardes.ctlfs.Node.of(serial, .rows); + // 1..4 are Syn's kinds (keyword, string, number, comment); 5..15 none. + for ([_][]const u8{ "7", "5", "15", "4" }) |n| { + _ = th.call(p, .{ .tag = 1, .op = .setattr, .node = rows, .truncate = true }); + var line: [64]u8 = undefined; + const text = try std.fmt.bufPrint(&line, "m 1 1 0 0 0 0 0 3:0+3={s} a.txt\n", .{n}); + const want: pardes.ctlfs.Status = if (std.mem.eql(u8, n, "4")) .ok else .err; + try testing.expectEqual(want, th.wr(p, rows, text).reply.status); + _ = p.frame_arena.reset(.retain_capacity); + _ = try p.render(p.frame_arena.allocator()); + } +} diff --git a/core/locations.zig b/core/locations.zig index 10704912..041e9692 100644 --- a/core/locations.zig +++ b/core/locations.zig @@ -224,9 +224,12 @@ pub fn parseRows(arena: std.mem.Allocator, text: []const u8) error{ OutOfMemory, continue :names; }; if (style & syntax.syn_bits != 0) return error.BadRows; - const syn: u8 = if (std.meta.stringToEnum(syntax.Syn, name)) |known| @backingInt(known) else std.fmt.parseInt(u4, name, 10) catch return error.BadRows; - if (syn == 0) return error.BadRows; - style |= syn; + // A kind by its name or its number, one Syn has: the + // render takes the style's syntax bits as a Syn. + const syn = std.meta.stringToEnum(syntax.Syn, name) orelse + std.enums.fromInt(syntax.Syn, std.fmt.parseInt(u8, name, 10) catch return error.BadRows) orelse return error.BadRows; + if (syn == .none) return error.BadRows; + style |= @backingInt(syn); } @memset(row.colors[start..][0..n], style); } diff --git a/core/ninep/ctl.zig b/core/ninep/ctl.zig index 2090f17e..84f3ba6b 100644 --- a/core/ninep/ctl.zig +++ b/core/ninep/ctl.zig @@ -809,63 +809,8 @@ fn sizeOf(line: []const u8) ?[2]u16 { // ---- /commands ---- /// Every builtin the registry holds, one a line: its word, `arg` when it -/// takes one, and which ctl takes it, `root` or `pane` -- the registry -/// itself, so a new builtin is listed the moment it exists. -/// A builtin's doc comment, its first sentence, from the source itself: a -/// line of /commands says what each word does without a second copy of it. -pub fn summaryOf(word: []const u8, buf: []u8) []const u8 { - const source = @embedFile("../builtins.zig"); - var needle_buf: [64]u8 = undefined; - const needle = std.fmt.bufPrint(&needle_buf, "\npub const {s} = struct", .{word}) catch return ""; - const at = std.mem.indexOf(u8, source, needle) orelse return ""; - // Back over the `///` lines just above it. - var start = at + 1; - while (start > 0) { - const prev_end = start - 1; - const prev_start = if (std.mem.lastIndexOfScalar(u8, source[0..prev_end], '\n')) |nl| nl + 1 else 0; - if (!std.mem.startsWith(u8, std.mem.trimStart(u8, source[prev_start..prev_end], " "), "///")) break; - start = prev_start; - } - var w = std.Io.Writer.fixed(buf); - var lines = std.mem.splitScalar(u8, source[start .. at + 1], '\n'); - while (lines.next()) |line| { - const text = std.mem.trim(u8, std.mem.trimStart(u8, std.mem.trimStart(u8, line, " "), "/"), " "); - if (text.len == 0) continue; - if (w.buffered().len > 0) w.writeByte(' ') catch break; - w.writeAll(text) catch break; - } - const all = stripCitations(w.buffered()); - // The first sentence, whole: to a `.` that ends one. - var i: usize = 0; - while (std.mem.indexOfScalarPos(u8, all, i, '.')) |dot| : (i = dot + 1) { - if (dot + 1 == all.len or all[dot + 1] == ' ') return all[0 .. dot + 1]; - } - return all; -} - -/// Drops a parenthesis that cites source (`(editors/acme/exec.c:892)`, -/// `(exec.c, \`kill\`; acme.c's WKill)`): a reader of /commands wants what -/// the word does, not where acme has it. In place; answers the rest. -fn stripCitations(text: []u8) []u8 { - var out: usize = 0; - var i: usize = 0; - while (i < text.len) { - if (text[i] == '(') if (std.mem.indexOfScalarPos(u8, text, i, ')')) |close| { - const inside = text[i + 1 .. close]; - if (std.mem.indexOf(u8, inside, ".c") != null or std.mem.indexOf(u8, inside, ".zig") != null) { - // With the space before it, and a colon after it kept. - if (out > 0 and text[out - 1] == ' ') out -= 1; - i = close + 1; - continue; - } - }; - text[out] = text[i]; - out += 1; - i += 1; - } - return text[0..out]; -} - +/// takes one, which ctl takes it, `root` or `pane`, and its summary -- the +/// registry itself, so a new builtin is listed the moment it exists. fn writeCommands(p: *const Pardes, w: *std.Io.Writer) !void { for (std.enums.values(Builtin)) |b| { // A window's own word is none in a terminal's view. @@ -885,15 +830,8 @@ fn writeCommands(p: *const Pardes, w: *std.Io.Writer) !void { var first = true; while (parts.next()) |v| : (first = false) try w.print("{s}{s}", .{ if (first) "" else ",", v }); }; - // Then ` -- ` and what it does: a setting's doc, else its source's. - var summary_buf: [2048]u8 = undefined; - const summary = if (config.Settings.find(@tagName(b))) |setting| setting.doc else summaryOf(@tagName(b), &summary_buf); - if (summary.len > 0) { - // The sentence whole unless it is long, then cut between words. - const kept = @import("../Messages.zig").clip(summary, 240); - try w.print(" -- {s}{s}", .{ kept, if (kept.len < summary.len) "…" else "" }); - } - try w.writeByte('\n'); + // Then ` -- ` and what it does, in a line (builtins.summary_max). + try w.print(" -- {s}\n", .{builtins.registry.doc(b).summary}); } // The addons' words, after the core's: `(addon <name>)` says whose. for (p.kinds.words[0..p.kinds.nwords]) |*kw| try w.print("{s}{s} {s} -- {s} (addon {s})\n", .{ @@ -1383,7 +1321,7 @@ test "commands lists every builtin with its argument and the ctl that takes it" var here: usize = 0; for (std.enums.values(Builtin)) |b| here += @intFromBool(builtins.registry.here(p, b)); try testing.expectEqual(here, lines); - for ([_][]const u8{ "\nDel arg pane -- ", "\nNewcol root -- ", "\nSave arg pane", "\nVerbose arg root on,off", "\nUndo pane -- ", "\nEdit arg both -- acme's Edit" }) |row| + for ([_][]const u8{ "\nDel arg pane -- ", "\nNewcol root -- ", "\nSave arg pane", "\nVerbose arg root on,off", "\nUndo pane -- ", "\nEdit arg both -- " }) |row| try testing.expect(std.mem.indexOf(u8, listed.bytes, row) != null); } @@ -2463,48 +2401,19 @@ test "a file changed on disk under unsaved edits is not reloaded: it says so, ge try testing.expect(wr(p, Node.of(serial, .ctl), "Save\n").saved); } -test "every word's /commands description is its own doc comment's first sentence, no citation" { +test "every word's /commands description is its documentation's summary, a line" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); const listed = rd(p, @backingInt(tree.TopFile.commands), 0, 1 << 16).bytes; - for ([_][]const u8{ - "\nRepl arg pane -- Binds this terminal as a language's REPL, so an exec on that language's files is typed into it instead of run.\n", - "\nJoincol root -- Fold the active pane's column into the one on its right, keeping its panes.\n", - "\nExit root -- Quit the editor, refusing once while a pane holds unsaved text: an Exit with nothing edited since discards it.\n", - "\nWrap arg root on,off -- Long lines wrap onto the next row, on or off.\n", - // the reference's examples, as they read. - "\nNewcol root -- An empty column right of the keyboard's, its tag taking the keyboard.\n", - "\nSave arg pane -- Write the pane's text to its file, or to the file its argument names.\n", - "\nVerbose arg root on,off -- A builtin says its own name on the message row as it runs, on or off.\n", - "\nKill arg root -- acme's Kill: stop the commands pardes started", - }) |row| try testing.expect(std.mem.indexOf(u8, listed, row) != null); - try testing.expect(std.mem.indexOf(u8, listed, ".c:") == null); - // Every description is the first sentence of the doc comment just - // above its word's declaration in builtins.zig. - const source = @embedFile("../builtins.zig"); var it = std.mem.tokenizeScalar(u8, listed, '\n'); - var undescribed: usize = 0; while (it.next()) |line| { - // Every builtin has one: a word nobody can look up is no use. - const dashes = std.mem.indexOf(u8, line, " -- ") orelse { - std.debug.print("no doc comment: {s}\n", .{line}); - undescribed += 1; - continue; - }; - const word = line[0..std.mem.indexOfScalar(u8, line, ' ').?]; - if (config.Settings.find(word)) |setting| { - try testing.expect(std.mem.endsWith(u8, line, setting.doc)); - continue; - } - var needle: [64]u8 = undefined; - const at = std.mem.indexOf(u8, source, try std.fmt.bufPrint(&needle, "\npub const {s} = struct", .{word})).?; - const said = std.mem.trimEnd(u8, line[dashes + 4 ..], "…"); - // Its opening words are in the comment block right above. - const head = said[0..@min(said.len, 10)]; - const block_start = std.mem.lastIndexOf(u8, source[0..at], "\n\n") orelse 0; - try testing.expect(std.mem.indexOf(u8, source[block_start..at], head) != null); + const b = std.meta.stringToEnum(Builtin, line[0..std.mem.indexOfScalar(u8, line, ' ').?]).?; + var want: [builtins.summary_max + 8]u8 = undefined; + try testing.expect(std.mem.endsWith(u8, line, try std.fmt.bufPrint(&want, " -- {s}", .{builtins.registry.doc(b).summary}))); } - try testing.expectEqual(0, undescribed); + // A setting's is its own doc's first sentence; a sentence names no source. + try testing.expect(std.mem.indexOf(u8, listed, "\nWrap arg root on,off -- Long lines wrap onto the next row, on or off.\n") != null); + try testing.expect(std.mem.indexOf(u8, listed, ".c:") == null); } test "Newcol at the column cap fails the write and says the cap" { diff --git a/core/root.zig b/core/root.zig index a9abee95..773c7588 100644 --- a/core/root.zig +++ b/core/root.zig @@ -396,6 +396,7 @@ test "a compact tagline anchors at its own pane, and both shells step from the s } test { + _ = @import("fuzz.zig"); _ = @import("Addon.zig"); _ = @import("rollback.zig"); _ = @import("Core.zig"); @@ -648,6 +649,7 @@ const machine_lines = [_]struct { []const u8, usize, []const u8 }{ .{ "ninep/pty.zig", 1, "a 9P exec's shell check (tape.site(.shell))" }, .{ "ninep/screen.zig", 1, "a 9P address's text type" }, .{ "ninep/tree.zig", 1, "the daemon's registry (/sessions, tape.site(.sessions))" }, + .{ "fuzz.zig", 1, "the 9P fuzz's engine, the session's (runtime.ninep): a test's, no step's" }, .{ "term/terminal.zig", 2, "the emulator's image files (TMPDIR) and its Io: each side's emulator, a medium's read taped (Term.media)" }, }; diff --git a/core/tape.zig b/core/tape.zig index 5f98238d..1552d65c 100644 --- a/core/tape.zig +++ b/core/tape.zig @@ -271,7 +271,9 @@ pub const Tape = struct { replica: bool = false, skips_render: bool = false, digests: u64 = 0, + /// What `diverge` said first, in `diverged_buf`: nothing to free. diverged: ?[]const u8 = null, + diverged_buf: [1024]u8 = undefined, /// The input being applied, for a divergence's report. applying: []const u8 = "", /// PARDES_RECORD_EVERY: a digest after every input, a nested one's too @@ -436,30 +438,50 @@ pub const Tape = struct { const Record = struct { kind: Kind, payload: walk.Reader }; + /// The next record, or null at the tape's end; a record the tape cannot + /// read (cut short, of no kind, by a hash not here) diverges it. fn next(t: *Tape) ?Record { const head = t.in.take(5) catch return null; const len = std.mem.bytesToValue(u32, head[1..5]); - const payload = t.in.take(len) catch return null; - const kind: Kind = @fromBackingInt(@intCast(head[0])); + const payload = t.in.take(len) catch { + t.diverge("the tape ends inside a record", .{}); + return null; + }; + const kind = std.enums.fromInt(Kind, head[0]) orelse { + t.diverge("a record of no kind ({d})", .{head[0]}); + return null; + }; if (kind != .blob) return .{ .kind = kind, .payload = .{ .bytes = payload } }; if (payload.len != 34) { t.diverge("a record by hash is short", .{}); return null; } + const of = std.enums.fromInt(Kind, payload[0]) orelse { + t.diverge("a record by hash of no kind ({d})", .{payload[0]}); + return null; + }; const bytes = t.byHash(payload[1..33], payload[33] != 0) orelse { t.diverge("a record by hash {x} is not here", .{payload[1..9]}); return null; }; - return .{ .kind = @fromBackingInt(@intCast(payload[0])), .payload = .{ .bytes = bytes } }; + return .{ .kind = of, .payload = .{ .bytes = bytes } }; } + /// The next record's kind, or null at the tape's end and for a byte of + /// no kind (which `next` diverges on). fn peek(t: *const Tape) ?Kind { if (t.in.bytes.len - t.in.at < 5) return null; - const kind: Kind = @fromBackingInt(@intCast(t.in.bytes[t.in.at])); - if (kind == .blob and t.in.bytes.len - t.in.at > 5) return @fromBackingInt(@intCast(t.in.bytes[t.in.at + 5])); + const kind = std.enums.fromInt(Kind, t.in.bytes[t.in.at]) orelse return null; + if (kind == .blob and t.in.bytes.len - t.in.at > 5) return std.enums.fromInt(Kind, t.in.bytes[t.in.at + 5]); return kind; } + /// A host record's call (its first two bytes), 0 for one too short to + /// name it: what a divergence says. + fn hostId(payload: []const u8) u16 { + return if (payload.len < 2) 0 else std.mem.bytesToValue(u16, payload[0..2]); + } + /// The bytes of a record by hash: sent, or read here (a file read's /// answer, on the session's machine), each checked against its hash. fn byHash(t: *Tape, hash: *const [32]u8, is_path: bool) ?[]const u8 { @@ -485,7 +507,7 @@ pub const Tape = struct { /// first said): its replica joins again. pub fn diverge(t: *Tape, comptime why: []const u8, args: anytype) void { if (t.diverged != null) return; - t.diverged = std.fmt.allocPrint(t.gpa, why ++ " (tape byte {d}, in {s})", args ++ .{ t.in.at, t.applying }) catch why; + t.diverged = std.fmt.bufPrint(&t.diverged_buf, why ++ " (tape byte {d}, in {s})", args ++ .{ t.in.at, t.applying }) catch why; } /// A host call a replica that skips render does not make (it draws no frame, @@ -526,11 +548,11 @@ pub const Tape = struct { fn finishInput(t: *Tape) void { while (t.diverged == null) { const kind = t.peek() orelse return t.diverge("the tape ends inside an input", .{}); - var rec = t.next().?; + var rec = t.next() orelse return t.diverge("the tape ends inside an input", .{}); switch (kind) { .done => return, .set => t.applySet(&rec.payload), - .host => if (t.skips_render) t.skipHost() else return t.diverge("the core did not make the host call {d} the tape has", .{std.mem.bytesToValue(u16, rec.payload.bytes[0..2])}), + .host => if (t.skips_render) t.skipHost() else return t.diverge("the core did not make the host call {d} the tape has", .{hostId(rec.payload.bytes)}), .input => t.apply(&rec.payload), .digest => t.check(rec.payload.bytes), .ret, .blob => return t.diverge("the core's input ended before the recorded one", .{}), @@ -569,8 +591,8 @@ pub const Tape = struct { t.diverge("the core called " ++ what ++ " past the tape's end", .{}); return false; }; - if (rec.kind != .host or std.mem.bytesToValue(u16, rec.payload.bytes[0..2]) != id) { - const other: u16 = if (rec.kind == .host) std.mem.bytesToValue(u16, rec.payload.bytes[0..2]) else 0; + if (rec.kind != .host or rec.payload.bytes.len < 2 or hostId(rec.payload.bytes) != id) { + const other: u16 = if (rec.kind == .host) hostId(rec.payload.bytes) else 0; t.diverge("the core called " ++ what ++ " where the tape has a {t} ({d})", .{ rec.kind, other }); return false; } @@ -644,7 +666,7 @@ pub const Tape = struct { fn apply(t: *Tape, r: *walk.Reader) void { // A session's options are kept by its core (`opts`): theirs for good. const Tag = std.meta.Tag(Input); - const tag = std.mem.bytesToValue(Tag, (r.take(@sizeOf(Tag)) catch return t.diverge("a short input", .{}))); + const tag = walk.enumFrom(Tag, (r.take(@sizeOf(Tag)) catch return t.diverge("a short input", .{}))[0..@sizeOf(Tag)]) orelse return t.diverge("an input of no kind", .{}); r.at -= @sizeOf(Tag); const kept = tag == .init or tag == .init_from_dump or tag == .restore; const keep = if (t.kept_arena) |*k| k.allocator() else t.gpa; @@ -1392,8 +1414,12 @@ pub fn replayUnit(t: *Tape, bytes: []const u8) ?[]const u8 { defer t.replay = false; t.in = .{ .bytes = bytes }; while (t.diverged == null) { - const kind = t.peek() orelse break; - var rec = t.next().?; + const kind = t.peek() orelse { + // Bytes left that are no record's head: cut, or of no kind. + if (t.in.at < t.in.bytes.len and t.next() == null and t.diverged == null) t.diverge("the tape ends inside a record's head", .{}); + break; + }; + var rec = t.next() orelse break; switch (kind) { .input => { t.apply(&rec.payload); @@ -1450,7 +1476,7 @@ fn nextRecord(r: *walk.Reader) ?struct { kind: Kind, payload: []const u8 } { while (true) { const head = r.take(5) catch return null; const payload = r.take(std.mem.bytesToValue(u32, head[1..5])) catch return null; - const kind: Kind = @fromBackingInt(@intCast(head[0])); + const kind = std.enums.fromInt(Kind, head[0]) orelse return null; if (kind != .digest) return .{ .kind = kind, .payload = payload }; } } @@ -1463,9 +1489,9 @@ pub fn describe(bytes: []const u8, w: *std.Io.Writer) void { while (true) { const head = r.take(5) catch return; const payload = r.take(std.mem.bytesToValue(u32, head[1..5])) catch return; - const raw: Kind = @fromBackingInt(@intCast(head[0])); + const raw = std.enums.fromInt(Kind, head[0]) orelse return w.print("a record of no kind ({d})\n", .{head[0]}) catch {}; // A record by hash, as the kind it stands for (its bytes are not here). - const kind: Kind = if (raw == .blob and payload.len > 0) @fromBackingInt(@intCast(payload[0])) else raw; + const kind: Kind = if (raw == .blob and payload.len > 0) std.enums.fromInt(Kind, payload[0]) orelse .blob else raw; if (raw == .blob) { w.splatByteAll(' ', depth * 2) catch {}; w.print("{t} by hash\n", .{kind}) catch {}; @@ -1477,9 +1503,15 @@ pub fn describe(bytes: []const u8, w: *std.Io.Writer) void { w.splatByteAll(' ', depth * 2) catch {}; switch (kind) { .input => { - const tag = std.mem.bytesToValue(std.meta.Tag(Input), payload[0..@sizeOf(std.meta.Tag(Input))]); - w.print("input {t}", .{tag}) catch {}; - if (tag == .update) w.print(" {t}", .{std.mem.bytesToValue(std.meta.Tag(pardes.Event), payload[@sizeOf(std.meta.Tag(Input))..][0..@sizeOf(std.meta.Tag(pardes.Event))])}) catch {}; + // Its tags read as the replay reads them: one of no kind is said, not cast. + const Tag = std.meta.Tag(Input); + const EventTag = std.meta.Tag(pardes.Event); + const tag: ?Tag = if (payload.len < @sizeOf(Tag)) null else walk.enumFrom(Tag, payload[0..@sizeOf(Tag)]); + w.print("input {s}", .{if (tag) |g| @tagName(g) else "of no kind"}) catch {}; + if (tag == .update and payload.len >= @sizeOf(Tag) + @sizeOf(EventTag)) { + const ev = walk.enumFrom(EventTag, payload[@sizeOf(Tag)..][0..@sizeOf(EventTag)]); + w.print(" {s}", .{if (ev) |e| @tagName(e) else "of no kind"}) catch {}; + } // A key's or a pointer's own words: which one a divergence // starts at. var room: [4096]u8 = undefined; @@ -1492,8 +1524,9 @@ pub fn describe(bytes: []const u8, w: *std.Io.Writer) void { } else |_| {}; }, .host => { - const id = std.mem.bytesToValue(u16, payload[0..2]); - w.print("host {s}", .{if (id < host_fns.len) host_fns[id] else @tagName(@as(Site, @fromBackingInt(@intCast(id - host_fns.len))))}) catch {}; + const id = Tape.hostId(payload); + const of = if (id < host_fns.len) null else std.enums.fromInt(Site, id - host_fns.len); + w.print("host {s}", .{if (id < host_fns.len) host_fns[id] else if (of) |s| @tagName(s) else "of no kind"}) catch {}; }, // Its bytes when traced: which field of equal length differs. .ret => if (payload.len <= 8 or libc.getenv("PARDES_REPLICA_TRACE") != null) w.print("ret {x}", .{payload}) catch {} else w.print("ret ({d} bytes)", .{payload.len}) catch {}, @@ -1579,7 +1612,6 @@ test "a syscall that is no site, made replaying, diverges the replay and poisons var t: Tape = .{ .gpa = gpa, .replay = true, .scratch = .init(gpa), .arena = .init(gpa) }; defer t.scratch.deinit(); defer t.arena.deinit(); - defer if (t.diverged) |why| gpa.free(why); const since = pardes.turn.yields; t.stray(since); try std.testing.expect(t.diverged == null); @@ -1600,7 +1632,6 @@ test "a replay that finds no answer where its core reads one diverges, and the r var t: Tape = .{ .gpa = gpa, .replay = true, .scratch = .init(gpa), .arena = .init(gpa) }; defer t.scratch.deinit(); defer t.arena.deinit(); - defer if (t.diverged) |why| gpa.free(why); // The input's end where the core reads a value of the host's (a // window client's step that took a turn the session's had not, H9 of // 2026-10-30: it aborted the client). diff --git a/core/walk.zig b/core/walk.zig index d870052d..46bfadc5 100644 --- a/core/walk.zig +++ b/core/walk.zig @@ -457,8 +457,52 @@ pub const Reader = struct { }; /// What an error read back is when this build has none of that name (an -/// OS's own, a newer build's): the tape is another build's, and diverges. -const TapeError = error{ EndOfTape, OutOfMemory, NoSuchError }; +/// OS's own, a newer build's): the tape is another build's, and diverges; +/// BadTape, a value none of its type's (an enum's number of no name). +const TapeError = error{ EndOfTape, OutOfMemory, NoSuchError, BadTape }; + +/// An enum's bytes as `encode` writes them (`@sizeOf(E)` of them), read +/// checked: null for a number none of `E`'s names has, which a tape or a +/// dump read back may hold (cut, flipped, a hostile peer's), never cast. +pub fn enumFrom(comptime E: type, bytes: *const [@sizeOf(E)]u8) ?E { + const info = @typeInfo(E).@"enum"; + const wide = std.mem.bytesToValue(@Int(.unsigned, @sizeOf(E) * 8), bytes); + const tag: info.tag_type = @bitCast(@as(@Int(.unsigned, @bitSizeOf(info.tag_type)), @truncate(wide))); + if (info.mode == .nonexhaustive) return @fromBackingInt(tag); + return std.enums.fromInt(E, tag); +} + +/// `bytes`, a run of `E`s copied whole, when each is one of `E`'s names (an +/// enum's run is checked as one read alone is; another flat type's is bytes). +fn named(comptime E: type, bytes: []const u8) error{BadTape}![]const u8 { + if (comptime @typeInfo(E) != .@"enum" or @typeInfo(E).@"enum".mode == .nonexhaustive) return bytes; + var at: usize = 0; + while (at < bytes.len) : (at += @sizeOf(E)) if (enumFrom(E, bytes[at..][0..@sizeOf(E)]) == null) return error.BadTape; + return bytes; +} + +/// The fewest bytes `encode` writes for a `T`: a count read back is held to +/// the bytes left before anything is made for it (0: no such bound). +fn least(comptime T: type) usize { + return switch (@typeInfo(T)) { + .bool, .int, .float, .@"enum" => @sizeOf(T), + .optional, .error_union => 1, + .array => |a| a.len * least(a.child), + .pointer => |p| if (p.size == .slice) @sizeOf(usize) else 0, + .@"union" => |u| @sizeOf(u.tag_type.?), + .@"struct" => |s| sum: { + if (s.layout == .@"packed") break :sum @sizeOf(T); + if (machinery(T)) break :sum 0; + var n: usize = 0; + for (s.field_names, s.field_types, s.field_attrs) |name, F, attr| { + if (attr.@"comptime" or excluded(T, name)) continue; + n += least(F); + } + break :sum n; + }, + else => 0, + }; +} /// The inverse of `encode`; slices (and what a pointer points at) are made /// in `a`. A field `encode` left out is its default. @@ -466,7 +510,8 @@ pub fn decode(comptime T: type, r: *Reader, a: std.mem.Allocator) TapeError!T { switch (@typeInfo(T)) { .void, .null, .undefined => return {}, .bool => return (try r.take(1))[0] != 0, - .int, .float, .@"enum" => return r.scalar(T), + .int, .float => return r.scalar(T), + .@"enum" => return enumFrom(T, (try r.take(@sizeOf(T)))[0..@sizeOf(T)]) orelse error.BadTape, .optional => |o| { if ((try r.take(1))[0] == 0) return null; if (comptime machinery(o.child)) unreachable; @@ -475,7 +520,7 @@ pub fn decode(comptime T: type, r: *Reader, a: std.mem.Allocator) TapeError!T { .array => |a_info| { var out: T = undefined; if (comptime flat(a_info.child)) { - @memcpy(std.mem.sliceAsBytes(&out), try r.take(@sizeOf(T))); + @memcpy(std.mem.sliceAsBytes(&out), try named(a_info.child, try r.take(@sizeOf(T)))); } else for (&out) |*e| { e.* = try decode(a_info.child, r, a); } @@ -489,9 +534,12 @@ pub fn decode(comptime T: type, r: *Reader, a: std.mem.Allocator) TapeError!T { }, .slice => { const n = try r.scalar(usize); + // More than the bytes left could hold: refused before it is made. + const min = comptime least(p.child); + if (min > 0 and n > (r.bytes.len - r.at) / min) return error.EndOfTape; const out = try a.alloc(p.child, n); if (comptime flat(p.child)) { - @memcpy(std.mem.sliceAsBytes(out), try r.take(n * @sizeOf(p.child))); + @memcpy(std.mem.sliceAsBytes(out), try named(p.child, try r.take(n * @sizeOf(p.child)))); } else for (out) |*e| { e.* = try decode(p.child, r, a); } diff --git a/core/walk.zig.orig b/core/walk.zig.orig new file mode 100644 index 00000000..d870052d --- /dev/null +++ b/core/walk.zig.orig @@ -0,0 +1,2618 @@ +//! The reflective walk over the core's state: one comptime `@typeInfo` walk +//! that hashes a session into a digest (the replay harness compares two), +//! encodes values for the tape, and dumps a session for another build to +//! load by name: into a xitdb database's maps (`Put`, `Get`: a Dump, +//! Restore, -l, an Upgrade, a handover; Db.zig), or as bytes with a table +//! of its types (`Dump`, `Load`: a closed pane, the join of phase 5, and +//! for one release the `.dump` files before). The rollback copy is to walk +//! the same way (docs/next-daemon.md). +//! +//! Values, never addresses: a pointer is followed to what it points at, a +//! slice is its elements, an ArrayList its items, a hash map its entries in +//! no order. A type the walk cannot see into (an opaque handle, a function, +//! an untagged union, a many-pointer) is a compile error naming it, until +//! the struct that holds it says what the field is: +//! +//! pub const replica = .{ +//! // This process's own: presentation, timing, the host's handles +//! // and caches. A replica has its own and never compares them. +//! .local = .{ "frames", "surface" }, +//! // Recomputed from the rest whenever it is wanted. +//! .derived = .{ "wrap_line" }, +//! // Held by the session that performs effects alone. +//! .authority = .{ "host" }, +//! // A field written only as far as another says: hashed that far. +//! .len = .{ .{ "jumps", "njumps" } }, +//! // What a field holds is made with another allocator on a load. +//! .alloc = .{ .{ "image", "image" } }, +//! // Immutable blobs: replaced whole, never written, freed raw +//! // (memory.freeRaw). A digest hashes each once and +//! // folds that word in; a replica's rollback copy pins them. +//! .blob = .{ "content" }, +//! }; +//! +//! None of the three kinds is in a digest or a dump. A type (a struct or a +//! tagged union) with a `pub fn digest(*const T, *Hasher) void` of its own +//! hashes itself; one with +//! `dumpWrite`, `dumpRead` (and `dumpFree`) dumps itself as bytes. +const std = @import("std"); +const xitdb = @import("xitdb"); + +pub const Hasher = std.hash.Wyhash; +const builtin = @import("builtin"); + +/// Whether `T.name` holds blobs (`.blob`): a file's text, an undo entry's +/// bytes, a register's text, a file's location rows. +pub fn blob(comptime T: type, comptime name: []const u8) bool { + @setEvalBranchQuota(100_000); + if (!@hasDecl(T, "replica") or !@hasField(@TypeOf(T.replica), "blob")) return false; + inline for (T.replica.blob) |n| if (comptime std.mem.eql(u8, n, name)) return true; + return false; +} + +// ---- a blob in a digest: its length ---- +// +// A digest walks the whole core at every unit a replica is sent (and every +// unit a replica replays): a 100 MB file was hashed in full each time, then +// once and kept as a word by its address while texts were never written in +// place. A blob of `blob_min` bytes or more is digested as its length now, +// never its bytes: a file's text says what it holds by its revision +// (File.State.revision, in the digest), and the other blobs are replaced +// whole, never written. A smaller one is hashed as any slice is. + +const blob_min = 4096; +threadlocal var in_blob: bool = false; + +/// A blob as a digest takes it: its length. +fn hashBlob(comptime E: type, items: []const E, h: *Hasher) void { + // The list is the C heap's (a replica client's), which a build with no + // libc has none of. + if (comptime builtin.link_libc) if (blobs_out) |list| list.append(std.heap.c_allocator, std.mem.sliceAsBytes(items)) catch {}; + h.update(std.mem.asBytes(&items.len)); +} + +/// Where `blobs` notes every blob. +threadlocal var blobs_out: ?*std.ArrayListUnmanaged([]const u8) = null; + +/// Every blob of `v` a digest takes as one (`blob_min` bytes and up), as +/// its bytes, onto `out` (the C heap's): a replica client's, which knows +/// its blobs by content (core/replica.zig `Have`). +pub fn blobs(comptime T: type, v: *const T, out: *std.ArrayListUnmanaged([]const u8)) void { + blobs_out = out; + defer blobs_out = null; + _ = digest(T, v); +} + +pub fn digest(comptime T: type, v: *const T) u64 { + var h = Hasher.init(0); + hash(T, v, &h); + return h.final(); +} + +/// A digest of each field `hash` would walk, in order (what a divergence +/// is narrowed down by); `names` are theirs. +pub fn fieldDigests(comptime T: type, v: *const T, out: []u64) []u64 { + var n: usize = 0; + const s = @typeInfo(T).@"struct"; + inline for (s.field_names, s.field_types, s.field_attrs) |name, F, attr| { + if (attr.@"comptime" or comptime excluded(T, name)) continue; + var h = Hasher.init(0); + const was = in_blob; + in_blob = comptime blob(T, name); + defer in_blob = was; + if (comptime lengthOf(T, name)) |len| { + hashSlice(Element(F), @field(v, name)[0..lengthIn(v, len)], &h); + } else hash(F, &@field(v, name), &h); + out[n] = h.final(); + n += 1; + } + return out[0..n]; +} + +pub fn fieldNames(comptime T: type) []const []const u8 { + comptime { + var names: []const []const u8 = &.{}; + const s = @typeInfo(T).@"struct"; + for (s.field_names, s.field_attrs) |name, attr| { + if (attr.@"comptime" or excluded(T, name)) continue; + names = names ++ .{name}; + } + return names; + } +} + +/// Types that are machinery, never state: an allocator, the Io, a lock. +pub fn machinery(comptime T: type) bool { + inline for (.{ std.mem.Allocator, std.Io, std.Io.Mutex, std.Io.Condition, std.Thread, std.heap.ArenaAllocator }) |M| if (T == M) return true; + return false; +} + +/// Bytes that are the value whole: no padding, no pointer. +fn flat(comptime T: type) bool { + return switch (@typeInfo(T)) { + .int => @sizeOf(T) * 8 == @bitSizeOf(T), + .bool => true, + .@"enum" => |e| @sizeOf(T) * 8 == @bitSizeOf(e.tag_type), + else => false, + }; +} + +/// A field the walk cannot follow: a pointer to an opaque thing or a +/// function, or a many-pointer, bare or optional (the struct holding it is +/// named in the error, not the walk's depth). +fn opaqueTo(comptime F: type) bool { + return switch (@typeInfo(F)) { + .optional => |o| opaqueTo(o.child), + .pointer => |p| p.size == .many or p.size == .c or switch (@typeInfo(p.child)) { + .@"opaque", .@"fn" => true, + else => false, + }, + else => false, + }; +} + +fn excluded(comptime T: type, comptime name: []const u8) bool { + @setEvalBranchQuota(100_000); + if (!@hasDecl(T, "replica")) return false; + inline for (.{ "local", "derived", "authority" }) |kind| { + if (@hasField(@TypeOf(T.replica), kind)) inline for (@field(T.replica, kind)) |n| { + if (comptime std.mem.eql(u8, n, name)) return true; + }; + } + return false; +} + +/// What a `len`-cut field holds: a fixed array's, or a slice's room (a +/// selection's ranges, made once and used `nsel` deep). +fn Element(comptime F: type) type { + return switch (@typeInfo(F)) { + .array => |a| a.child, + .pointer => |p| p.child, + else => @compileError("walk: a `len` cuts an array or a slice, not " ++ @typeName(F)), + }; +} + +pub fn lengthIn(v: anytype, comptime len: []const u8) usize { + const n = @field(v, len); + return if (@typeInfo(@TypeOf(n)) == .optional) (if (n) |k| k else 0) else n; +} + +/// How far the field `len` names says its array is written (null: none). +pub fn lengthOf(comptime T: type, comptime name: []const u8) ?[]const u8 { + @setEvalBranchQuota(100_000); + if (!@hasDecl(T, "replica") or !@hasField(@TypeOf(T.replica), "len")) return null; + inline for (T.replica.len) |pair| if (comptime std.mem.eql(u8, pair[0], name)) return pair[1]; + return null; +} + +/// Every name an annotation gives is a field: a rename cannot quietly put +/// a field back in the digest. +fn checkAnnotations(comptime T: type) void { + if (!@hasDecl(T, "replica")) return; + inline for (@typeInfo(@TypeOf(T.replica)).@"struct".field_names) |kind| { + inline for (@field(T.replica, kind)) |entry| { + const name = if (comptime std.mem.eql(u8, kind, "len") or std.mem.eql(u8, kind, "alloc")) entry[0] else entry; + if (!@hasField(T, name)) @compileError("walk: " ++ @typeName(T) ++ " annotates no field " ++ name); + } + } +} + +pub fn hash(comptime T: type, v: *const T, h: *Hasher) void { + switch (@typeInfo(T)) { + .void, .null, .undefined => {}, + .bool => h.update(&.{@intFromBool(v.*)}), + .int => hashInt(T, v.*, h), + .float => h.update(std.mem.asBytes(v)), + .@"enum" => hashEnum(T, v.*, h), + .optional => |o| if (v.*) |*payload| { + h.update(&.{1}); + hash(o.child, payload, h); + } else h.update(&.{0}), + .array => |a| if (comptime flatHash(a.child)) h.update(std.mem.sliceAsBytes(v)) else for (v) |*e| hash(a.child, e, h), + .pointer => |p| switch (p.size) { + .one => hash(p.child, v.*, h), + .slice => hashSlice(p.child, v.*, h), + else => @compileError("walk: a many-pointer has no length: " ++ @typeName(T)), + }, + .@"struct" => |s| { + if (comptime machinery(T)) return; + if (comptime @hasDecl(T, "digest") and @TypeOf(T.digest) == fn (*const T, *Hasher) void) return v.digest(h); + if (s.layout == .@"packed") return hashInt(s.backing_integer.?, @bitCast(v.*), h); + if (comptime isList(T)) + return hashSlice(@typeInfo(@FieldType(T, "items")).pointer.child, v.items, h); + // std.atomic.Value: what it holds. + if (comptime isAtomic(T)) return hash(@FieldType(T, "raw"), &v.raw, h); + // A worker's future is a handle of the host's, never state. + if (comptime @hasField(T, "any_future")) return; + // std.DynamicBitSetUnmanaged: its bits. + if (comptime isBitset(T)) { + h.update(std.mem.asBytes(&v.bit_length)); + return h.update(std.mem.sliceAsBytes(v.masks[0 .. (v.bit_length + @bitSizeOf(usize) - 1) / @bitSizeOf(usize)])); + } + comptime checkAnnotations(T); + inline for (s.field_names, s.field_types, s.field_attrs) |name, F, attr| { + if (attr.@"comptime" or comptime excluded(T, name)) continue; + if (comptime opaqueTo(F)) @compileError("walk: " ++ @typeName(T) ++ "." ++ name ++ " is " ++ @typeName(F) ++ ", which no walk sees into: say what it is (`replica`)"); + const was = in_blob; + in_blob = comptime blob(T, name); + defer in_blob = was; + if (comptime lengthOf(T, name)) |len| { + hashSlice(Element(F), @field(v, name)[0..lengthIn(v, len)], h); + } else hash(F, &@field(v, name), h); + } + }, + .@"union" => |u| { + if (u.tag_type == null) @compileError("walk: an untagged union: " ++ @typeName(T)); + if (comptime @hasDecl(T, "digest") and @TypeOf(T.digest) == fn (*const T, *Hasher) void) return v.digest(h); + const tag: u.tag_type.? = v.*; + hash(u.tag_type.?, &tag, h); + switch (v.*) { + inline else => |*payload| hash(@TypeOf(payload.*), payload, h), + } + }, + .error_set => h.update(@errorName(v.*)), + .error_union => |e| if (v.*) |*payload| { + h.update(&.{1}); + hash(e.payload, payload, h); + } else |err| { + h.update(&.{0}); + h.update(@errorName(err)); + }, + else => @compileError("walk: cannot hash " ++ @typeName(T)), + } +} + +/// Bytes a digest takes whole: an enum's are its build's number, not it. +fn flatHash(comptime T: type) bool { + return flat(T) and @typeInfo(T) != .@"enum"; +} + +/// An enum by its name, as a dump reads it, not by its number: an enum +/// made at compile time numbers its words as its build has them +/// (`registry.Builtin` has fewer in a FreeBSD build than a Linux one, which +/// has Tty9p), so a window client here of a session on the box loaded a +/// +LocationsConfig to another digest. A name's word (its hash, fixed +/// width, so that two names in a row are not one), looked up by number +/// where the words are numbered 0 up; one numbered by hand, or a value no +/// word has, by its number. +fn hashEnum(comptime T: type, v: T, h: *Hasher) void { + const e = @typeInfo(T).@"enum"; + const words: ?[e.field_names.len]u64 = comptime words: { + @setEvalBranchQuota(100_000); + var out: [e.field_names.len]u64 = undefined; + for (e.field_names, e.field_values, 0..) |name, n, i| { + if (n != i) break :words null; + out[i] = std.hash.Wyhash.hash(0, name); + } + break :words out; + }; + const n = @backingInt(v); + if (words) |table| if (n >= 0 and n < table.len) return h.update(std.mem.asBytes(&table[@intCast(n)])); + hashInt(e.tag_type, n, h); +} + +/// An integer by its value: one narrower than its bytes (a u21, an i2) has +/// bits in memory that are no part of it. +fn hashInt(comptime I: type, n: I, h: *Hasher) void { + const W = @Int(@typeInfo(I).int.signedness, @sizeOf(I) * 8); + const wide: W = n; + h.update(std.mem.asBytes(&wide)); +} + +fn hashSlice(comptime E: type, items: []const E, h: *Hasher) void { + if (in_blob and items.len * @sizeOf(E) >= blob_min) return hashBlob(E, items, h); + h.update(std.mem.asBytes(&items.len)); + if (comptime flatHash(E)) return h.update(std.mem.sliceAsBytes(items)); + for (items) |*e| hash(E, e, h); +} + +/// The value as bytes, the same walk: what the tape carries (core/tape.zig), +/// to a replica of another build too (a window of a terminal's session, a +/// Linux client of a FreeBSD one). Native byte order, which every machine +/// pardes runs on shares, and an error by its name: its number is its +/// build's own (a Linux terminal's FileNotFound is a window's +/// NoDefaultValue). What a field is laid out as (a std.Io.File.Stat's +/// `nlink` is another width on FreeBSD) is the tape's shape, which +/// wire.semantics hashes (`shape`). +pub fn encode(comptime T: type, v: *const T, w: *std.Io.Writer) std.Io.Writer.Error!void { + switch (@typeInfo(T)) { + .void, .null, .undefined => {}, + .bool, .int, .float, .@"enum" => try w.writeAll(std.mem.asBytes(v)), + .optional => |o| if (comptime machinery(o.child)) try w.writeByte(0) else if (v.*) |*payload| { + try w.writeByte(1); + try encode(o.child, payload, w); + } else try w.writeByte(0), + .array => |a| if (comptime flat(a.child)) try w.writeAll(std.mem.sliceAsBytes(v)) else for (v) |*e| try encode(a.child, e, w), + .pointer => |p| switch (p.size) { + .one => try encode(p.child, v.*, w), + .slice => { + try w.writeAll(std.mem.asBytes(&v.len)); + if (comptime flat(p.child)) try w.writeAll(std.mem.sliceAsBytes(v.*)) else for (v.*) |*e| try encode(p.child, e, w); + }, + else => @compileError("walk: a many-pointer has no length: " ++ @typeName(T)), + }, + .@"struct" => |s| { + if (comptime machinery(T)) return; + if (s.layout == .@"packed") return w.writeAll(std.mem.asBytes(v)); + inline for (s.field_names, s.field_types, s.field_attrs) |name, F, attr| { + if (attr.@"comptime" or comptime excluded(T, name)) continue; + try encode(F, &@field(v, name), w); + } + }, + .@"union" => |u| { + if (u.tag_type == null) @compileError("walk: an untagged union: " ++ @typeName(T)); + const tag: u.tag_type.? = v.*; + try encode(u.tag_type.?, &tag, w); + switch (v.*) { + inline else => |*payload| try encode(@TypeOf(payload.*), payload, w), + } + }, + .error_set => try encodeError(T, v.*, w), + .error_union => |e| if (v.*) |*payload| { + try w.writeByte(1); + try encode(e.payload, payload, w); + } else |err| { + try w.writeByte(0); + try encodeError(e.error_set, err, w); + }, + else => @compileError("walk: cannot encode " ++ @typeName(T)), + } +} + +/// What `encode` lays each of `types` out as, in words: each field, element +/// and tag where it goes, an enum's names and numbers, an error as an +/// error (it goes by its name). wire.semantics hashes the tape's: builds +/// whose tapes differ in shape, as a FreeBSD std.Io.File.Stat differs from +/// a Linux one, refuse each other's replicas in words, not read each other +/// out of step. +pub fn shape(comptime types: []const type) []const u8 { + comptime { + @setEvalBranchQuota(10_000_000); + var out: []const u8 = ""; + for (types) |T| out = out ++ (shapeOf(T, 0) ++ "\n"); + return out; + } +} + +fn shapeOf(comptime T: type, comptime depth: u8) []const u8 { + comptime { + if (depth > 32) @compileError("walk: the tape's shape nests past 32 deep at " ++ @typeName(T) ++ ": a type that holds itself?"); + return switch (@typeInfo(T)) { + .void, .null, .undefined => "v", + .bool => "b", + .int => |i| @tagName(i.signedness) ++ decimal(i.bits), + .float => |f| "f" ++ decimal(f.bits), + .@"enum" => |e| blk: { + var out: []const u8 = shapeOf(e.tag_type, depth + 1) ++ "{"; + for (e.field_names, e.field_values) |n, v| out = out ++ (n ++ "=" ++ decimal(v) ++ ","); + break :blk out ++ "}"; + }, + .optional => |o| if (machinery(o.child)) "0" else "?" ++ shapeOf(o.child, depth + 1), + .array => |a| "[" ++ decimal(a.len) ++ "]" ++ shapeOf(a.child, depth + 1), + .pointer => |p| switch (p.size) { + .one => shapeOf(p.child, depth + 1), + .slice => "[]" ++ shapeOf(p.child, depth + 1), + else => @compileError("walk: a many-pointer has no length: " ++ @typeName(T)), + }, + .@"struct" => |s| blk: { + if (machinery(T)) break :blk ""; + var out: []const u8 = if (s.layout == .@"packed") "p{" else "{"; + for (s.field_names, s.field_types, s.field_attrs) |name, F, attr| { + if (attr.@"comptime" or excluded(T, name)) continue; + out = out ++ (name ++ ":" ++ shapeOf(F, depth + 1) ++ ","); + } + break :blk out ++ "}"; + }, + .@"union" => |u| blk: { + var out: []const u8 = shapeOf(u.tag_type.?, depth + 1) ++ "("; + for (u.field_names, u.field_types) |name, F| out = out ++ (name ++ ":" ++ shapeOf(F, depth + 1) ++ ","); + break :blk out ++ ")"; + }, + .error_set => "error", + .error_union => |e| "!" ++ shapeOf(e.payload, depth + 1), + else => @compileError("walk: cannot encode " ++ @typeName(T)), + }; + } +} + +/// `n` in decimal, as `{d}` writes it: memoized, where comptimePrint (an +/// inline function) formats again at every call, 5e6 of the compiler's +/// instructions each. +fn decimal(comptime n: comptime_int) []const u8 { + if (n < 0) return "-" ++ decimal(-n); + if (n < 10) return &.{'0' + n}; + return decimal(n / 10) ++ &[_]u8{'0' + n % 10}; +} + +/// An error by its name. An `anyerror` must be one `decode` can read back +/// (`errorNamed`): a Debug build stops at one that is not, as it is taped. +fn encodeError(comptime E: type, err: E, w: *std.Io.Writer) std.Io.Writer.Error!void { + if (comptime E == anyerror and builtin.mode == .debug) if (errorNamed(E, @errorName(err)) == null) + std.debug.panic("walk: error.{s} is taped as an anyerror, which a replica reads back only as one of tape.Failure's: add the set it comes from", .{@errorName(err)}); + try writeName(w, @errorName(err)); +} + +/// The error of `E` called `name`. `anyerror` keeps no list of its names +/// to look one up in: one is read back as one of tape.Failure's, what a +/// host reports as failed (the tape's only anyerrors). +fn errorNamed(comptime E: type, name: []const u8) ?E { + const Named = if (E == anyerror) @import("tape.zig").Failure else E; + inline for (@typeInfo(Named).error_set.error_names.?) |n| if (std.mem.eql(u8, name, n)) return @field(Named, n); + return null; +} + +pub const Reader = struct { + bytes: []const u8, + at: usize = 0, + + pub fn take(r: *Reader, n: usize) error{EndOfTape}![]const u8 { + if (r.bytes.len - r.at < n) return error.EndOfTape; + defer r.at += n; + return r.bytes[r.at..][0..n]; + } + + fn scalar(r: *Reader, comptime T: type) error{EndOfTape}!T { + return std.mem.bytesToValue(T, try r.take(@sizeOf(T))); + } +}; + +/// What an error read back is when this build has none of that name (an +/// OS's own, a newer build's): the tape is another build's, and diverges. +const TapeError = error{ EndOfTape, OutOfMemory, NoSuchError }; + +/// The inverse of `encode`; slices (and what a pointer points at) are made +/// in `a`. A field `encode` left out is its default. +pub fn decode(comptime T: type, r: *Reader, a: std.mem.Allocator) TapeError!T { + switch (@typeInfo(T)) { + .void, .null, .undefined => return {}, + .bool => return (try r.take(1))[0] != 0, + .int, .float, .@"enum" => return r.scalar(T), + .optional => |o| { + if ((try r.take(1))[0] == 0) return null; + if (comptime machinery(o.child)) unreachable; + return try decode(o.child, r, a); + }, + .array => |a_info| { + var out: T = undefined; + if (comptime flat(a_info.child)) { + @memcpy(std.mem.sliceAsBytes(&out), try r.take(@sizeOf(T))); + } else for (&out) |*e| { + e.* = try decode(a_info.child, r, a); + } + return out; + }, + .pointer => |p| switch (p.size) { + .one => { + const out = try a.create(p.child); + out.* = try decode(p.child, r, a); + return out; + }, + .slice => { + const n = try r.scalar(usize); + const out = try a.alloc(p.child, n); + if (comptime flat(p.child)) { + @memcpy(std.mem.sliceAsBytes(out), try r.take(n * @sizeOf(p.child))); + } else for (out) |*e| { + e.* = try decode(p.child, r, a); + } + return out; + }, + else => @compileError("walk: a many-pointer has no length: " ++ @typeName(T)), + }, + .@"struct" => |s| { + if (s.layout == .@"packed") return r.scalar(T); + var out: T = undefined; + inline for (s.field_names, s.field_types, s.field_attrs) |name, F, attr| { + if (attr.@"comptime") continue; + if (comptime excluded(T, name)) { + const default = attr.default_value_ptr orelse @compileError("walk: " ++ name ++ " has no default to decode to"); + @field(out, name) = @as(*const F, @ptrCast(@alignCast(default))).*; + } else if (comptime @typeInfo(F) == .error_set) { + // No `!anyerror` to return it through: read in place. + try decodeError(F, r, &@field(out, name)); + } else @field(out, name) = try decode(F, r, a); + } + return out; + }, + .@"union" => |u| { + const tag = try decode(u.tag_type.?, r, a); + inline for (u.field_names, u.field_types) |name, F| if (tag == @field(u.tag_type.?, name)) { + return @unionInit(T, name, try decode(F, r, a)); + }; + unreachable; + }, + .error_union => |e| { + if ((try r.take(1))[0] != 0) return try decode(e.payload, r, a); + // The value's error, not decode's own. + var err: e.error_set = undefined; + try decodeError(e.error_set, r, &err); + return @as(T, err); + }, + else => @compileError("walk: cannot decode " ++ @typeName(T)), + } +} + +/// An error by its name, as `encode` wrote it, into `out`: no error union +/// holds an error set. +fn decodeError(comptime E: type, r: *Reader, out: *E) TapeError!void { + const len = try r.scalar(u16); + out.* = errorNamed(E, try r.take(len)) orelse return error.NoSuchError; +} + +// ---- the dump: the same walk, by name, for another build ---- +// +// A dump (docs/next-daemon.md, phase 2) is `dump_magic`, then a table of +// every type its roots' walk reaches -- each struct's and union's fields by +// name, each enum's names, each number's width -- then each root's value, +// laid out as `encode` lays it out but for three things: an enum or a +// union's tag is its place among the table's names, a pointer or a slice met +// again is a reference to the first (what two fields share is shared again), +// and a type with a `dumpWrite` of its own is its bytes, counted. +// +// A build that is not the writer's matches by name: a field added since +// takes its default, one removed is passed over, one whose kind changed +// takes its default and says so (`Decoder.notes`). With no default to take, +// the value it is part of is refused (`error.Incompatible`), and an element +// of an array of optional pointers (a session's panes) is then left out, +// nothing above it. A dump whose table is this build's own is read field +// after field, no name asked. +// +// Native byte order: the machines pardes runs on are all little-endian. + +const dump_magic = "pardes-dump\x00\x02\n"; + +const Kind = enum(u8) { skip, void, bool, int, float, @"enum", optional, one, slice, array, prefix, @"struct", @"union", err, error_union, custom, bitset }; + +/// std's lists: their items, not the capacity behind them (nor, in a safe +/// build, the lock that checks no pointer into them moves). +pub fn isList(comptime T: type) bool { + if (@typeInfo(T) != .@"struct" or !@hasField(T, "items") or !@hasField(T, "capacity")) return false; + const n = @typeInfo(T).@"struct".field_names.len; + return n == 2 or (n == 3 and @hasField(T, "pointer_stability")); +} +fn isAtomic(comptime T: type) bool { + return @typeInfo(T) == .@"struct" and @hasField(T, "raw") and @typeInfo(T).@"struct".field_names.len == 1 and @hasDecl(T, "load"); +} +fn isBitset(comptime T: type) bool { + return @typeInfo(T) == .@"struct" and @hasField(T, "bit_length") and @hasField(T, "masks") and @typeInfo(T).@"struct".field_names.len == 2; +} + +/// A field written only as far as its `len` says: a count, then that many. +fn Prefix(comptime E: type) type { + return struct { + pub const element = E; + }; +} + +/// What the dump walks `T` as: an atomic as what it holds, a list as its +/// items. +fn Canon(comptime T: type) type { + if (comptime isAtomic(T)) return Canon(@FieldType(T, "raw")); + if (comptime isList(T)) return []@typeInfo(@FieldType(T, "items")).pointer.child; + return T; +} + +fn kindOf(comptime T: type) Kind { + return switch (@typeInfo(T)) { + .void, .null, .undefined => .void, + .bool => .bool, + .int => .int, + .float => .float, + .@"enum" => .@"enum", + .optional => .optional, + .array => .array, + .pointer => |p| switch (p.size) { + .one => .one, + .slice => .slice, + else => @compileError("walk: a many-pointer has no length: " ++ @typeName(T)), + }, + .@"struct" => if (machinery(T) or @hasField(T, "any_future")) + .skip + else if (@hasDecl(T, "dumpWrite")) + .custom + else if (@hasDecl(T, "element") and T == Prefix(T.element)) + .prefix + else if (isBitset(T)) + .bitset + else + .@"struct", + .@"union" => |u| if (u.tag_type == null) @compileError("walk: an untagged union: " ++ @typeName(T)) else .@"union", + else => @compileError("walk: cannot dump " ++ @typeName(T)), + }; +} + +/// The fields of struct `T` a dump holds, in order. +fn dumpFields(comptime T: type) []const [:0]const u8 { + comptime { + @setEvalBranchQuota(1_000_000); + var names: []const [:0]const u8 = &.{}; + const s = @typeInfo(T).@"struct"; + for (s.field_names, s.field_types, s.field_attrs) |name, F, attr| { + if (attr.@"comptime" or excluded(T, name) or kindOf(Canon(F)) == .skip) continue; + if (opaqueTo(F)) @compileError("walk: " ++ @typeName(T) ++ "." ++ name ++ " is " ++ @typeName(F) ++ ", which no walk sees into: say what it is (`replica`)"); + names = names ++ .{name}; + } + return names; + } +} + +/// The type a dump walks field `name` of `T` as. +fn FieldDump(comptime T: type, comptime name: []const u8) type { + const F = @FieldType(T, name); + if (comptime cutArray(T, name)) return Prefix(Canon(@typeInfo(F).array.child)); + return Canon(F); +} + +/// A fixed array a `len` cuts, which a dump writes as far as it says. A +/// slice it cuts (a text's room for its ranges, made whole) is written +/// whole, room and all, which only plain numbers may be: a load gives it +/// the room it had. +fn cutArray(comptime T: type, comptime name: []const u8) bool { + const F = @FieldType(T, name); + if (comptime lengthOf(T, name) == null) return false; + if (@typeInfo(F) == .array) return true; + if (!plain(Element(F))) @compileError("walk: " ++ @typeName(T) ++ "." ++ name ++ " is a slice a `len` cuts, of what a dump cannot write past the cut"); + return false; +} + +/// Every bit pattern one of its values: what a dump may write where +/// nothing was ever written. +fn plain(comptime T: type) bool { + return switch (@typeInfo(T)) { + .int, .float => true, + .array => |a| plain(a.child), + .@"struct" => |st| st.layout != .@"packed" and blk: { + for (st.field_types) |F| if (!plain(F)) break :blk false; + break :blk true; + }, + else => false, + }; +} + +fn children(comptime T: type) []const type { + comptime { + return switch (kindOf(T)) { + .optional => &.{Canon(@typeInfo(T).optional.child)}, + .one, .slice => &.{Canon(@typeInfo(T).pointer.child)}, + .array => &.{Canon(@typeInfo(T).array.child)}, + .prefix => &.{T.element}, + .@"struct" => blk: { + var out: []const type = &.{}; + for (dumpFields(T)) |name| out = out ++ .{FieldDump(T, name)}; + break :blk out; + }, + .@"union" => blk: { + var out: []const type = &.{}; + for (@typeInfo(T).@"union".field_types) |F| out = out ++ .{Canon(F)}; + break :blk out; + }, + else => &.{}, + }; + } +} + +fn collect(comptime T: type, comptime list: []const type) []const type { + comptime { + for (list) |U| if (U == T) return list; + var out: []const type = list ++ .{T}; + if (kindOf(T) == .@"struct") checkAnnotations(T); + for (children(T)) |C| out = collect(C, out); + return out; + } +} + +/// Every type the walk of `roots` reaches, each once. +fn graph(comptime roots: []const type) []const type { + comptime { + @setEvalBranchQuota(100_000_000); + var list: []const type = &.{}; + for (roots) |R| list = collect(Canon(R), list); + return list; + } +} + +/// The types the walk of `roots` reaches that walk themselves by hand (a +/// `digest` or a `dumpWrite` of their own): the ones whose digest can take +/// what their dump does not carry, which the one walk holds for the rest. +pub fn handWalked(comptime roots: []const type) []const type { + comptime { + var out: []const type = &.{}; + for (graph(roots)) |T| switch (@typeInfo(T)) { + .@"struct", .@"union" => if (@hasDecl(T, "dumpWrite") or (@hasDecl(T, "digest") and @TypeOf(T.digest) == fn (*const T, *Hasher) void)) { + out = out ++ .{T}; + }, + else => {}, + }; + return out; + } +} + +fn indexIn(comptime types: []const type, comptime T: type) u32 { + comptime { + @setEvalBranchQuota(100_000_000); + for (types, 0..) |U, i| if (U == T) return i; + @compileError("walk: not in the dump's table: " ++ @typeName(T)); + } +} + +/// How many bytes an integer of `bits` is written in: its own size. +fn intBytes(bits: u16) usize { + return if (bits == 0) 0 else if (bits <= 8) 1 else if (bits <= 16) 2 else if (bits <= 32) 4 else if (bits <= 64) 8 else 16; +} + +fn writeName(w: *std.Io.Writer, name: []const u8) !void { + try w.writeAll(std.mem.asBytes(&@as(u16, @intCast(name.len)))); + try w.writeAll(name); +} + +fn writeU32(w: *std.Io.Writer, n: u32) !void { + try w.writeAll(std.mem.asBytes(&n)); +} + +fn writeTable(comptime types: []const type, w: *std.Io.Writer) !void { + try writeU32(w, types.len); + inline for (types) |T| { + const k = comptime kindOf(T); + try w.writeByte(@backingInt(k)); + switch (k) { + .int => { + try w.writeByte(@intFromBool(@typeInfo(T).int.signedness == .signed)); + try w.writeAll(std.mem.asBytes(&@as(u16, @typeInfo(T).int.bits))); + }, + .float => try w.writeAll(std.mem.asBytes(&@as(u16, @typeInfo(T).float.bits))), + .@"enum" => { + const e = @typeInfo(T).@"enum"; + const tag = @typeInfo(e.tag_type).int; + try w.writeByte(@intFromBool(tag.signedness == .signed)); + try w.writeAll(std.mem.asBytes(&@as(u16, tag.bits))); + try writeU32(w, e.field_names.len); + inline for (e.field_names, e.field_values) |name, value| { + try writeName(w, name); + try w.writeAll(std.mem.asBytes(&@as(i128, value))); + } + }, + .array => { + try w.writeAll(std.mem.asBytes(&@as(u64, @typeInfo(T).array.len))); + try writeU32(w, comptime indexIn(types, children(T)[0])); + }, + .optional, .one, .slice, .prefix, .error_union => try writeU32(w, comptime indexIn(types, children(T)[0])), + .@"struct" => { + const names = comptime dumpFields(T); + try writeU32(w, names.len); + inline for (names) |name| { + try writeName(w, name); + try writeU32(w, comptime indexIn(types, FieldDump(T, name))); + } + }, + .@"union" => { + const u = @typeInfo(T).@"union"; + try writeU32(w, u.field_names.len); + inline for (u.field_names, u.field_types) |name, F| { + try writeName(w, name); + try writeU32(w, comptime indexIn(types, Canon(F))); + } + }, + .custom => try writeName(w, @typeName(T)), + .skip, .void, .bool, .err, .bitset => {}, + } + } +} + +/// Integers by value, in the bytes `intBytes` gives them: a `u21`'s +/// padding is no part of it. +fn putInt(comptime I: type, n: I, w: *std.Io.Writer) !void { + const info = @typeInfo(I).int; + const W = @Int(info.signedness, intBytes(info.bits) * 8); + const wide: W = n; + try w.writeAll(std.mem.asBytes(&wide)); +} + +/// The table of `types` as bytes, made once a process (it is the build's): +/// a store record or a dump writes it, a load compares it. +fn tableOf(comptime types: []const type) []const u8 { + const Once = struct { + // Of these types alone: a container that named none of its + // function's parameters would be one for every table. + const of = types; + /// 0 none, 1 being made, 2 made. + var state: std.atomic.Value(u8) = .init(0); + var bytes: []const u8 = &.{}; + }; + if (Once.state.load(.acquire) == 2) return Once.bytes; + if (Once.state.cmpxchgStrong(0, 1, .acquire, .monotonic) == null) { + var out: std.Io.Writer.Allocating = .init(std.heap.page_allocator); + writeTable(types, &out.writer) catch @panic("walk: out of memory for a dump's table"); + Once.bytes = out.toOwnedSlice() catch @panic("walk: out of memory for a dump's table"); + Once.state.store(2, .release); + } else while (Once.state.load(.acquire) != 2) std.atomic.spinLoopHint(); + return Once.bytes; +} + +/// A blob's bytes a dump left out (`Dump.deferred`): they go at `at`. +pub const Deferred = struct { at: usize, bytes: []const u8 }; + +/// Writes a dump of `roots`' values, one `put` each in order. +pub fn Dump(comptime roots: []const type) type { + return struct { + const Self = @This(); + pub const types = graph(roots); + + gpa: std.mem.Allocator, + out: std.Io.Writer.Allocating, + memo: std.AutoHashMapUnmanaged(Key, u32) = .empty, + /// Set: a `.blob`'s bytes (of `blob_min` and up) are not written but + /// noted, where they go and what they are; the dump with them put + /// back in place is the dump. A replica's join streams them from + /// its writer thread (core/replica.zig), the session's step paying + /// for the rest alone. + deferred: ?*std.ArrayListUnmanaged(Deferred) = null, + in_blob: bool = false, + + const Key = struct { addr: usize, len: usize, ty: u32 }; + + pub fn init(gpa: std.mem.Allocator) !Self { + var d: Self = .{ .gpa = gpa, .out = .init(gpa) }; + errdefer d.out.deinit(); + try d.out.writer.writeAll(dump_magic); + try d.out.writer.writeAll(tableOf(types)); + return d; + } + + pub fn deinit(d: *Self) void { + d.memo.deinit(d.gpa); + d.out.deinit(); + } + + /// The dump, the caller's (gpa). + pub fn finish(d: *Self) ![]u8 { + d.memo.deinit(d.gpa); + d.memo = .empty; + return d.out.toOwnedSlice(); + } + + pub fn put(d: *Self, comptime T: type, v: *const T) !void { + try writeU32(&d.out.writer, comptime indexIn(types, Canon(T))); + try d.value(T, v); + } + + /// Whether the pointer or slice at `addr` was met before: its + /// reference written if so, else 0 and it is noted. + fn seen(d: *Self, comptime T: type, addr: usize, len: usize) Error!bool { + const w = &d.out.writer; + if (len == 0) { + try writeU32(w, 0); + return false; + } + const got = try d.memo.getOrPut(d.gpa, .{ .addr = addr, .len = len, .ty = comptime indexIn(types, Canon(T)) }); + if (got.found_existing) { + try writeU32(w, got.value_ptr.*); + return true; + } + got.value_ptr.* = @intCast(d.memo.count()); + try writeU32(w, 0); + return false; + } + + const Error = std.Io.Writer.Error || std.mem.Allocator.Error; + + fn items(d: *Self, comptime E: type, slice: []const E) Error!void { + const w = &d.out.writer; + try w.writeAll(std.mem.asBytes(&@as(u64, slice.len))); + if (comptime flat(E)) return w.writeAll(std.mem.sliceAsBytes(slice)); + for (slice) |*e| try d.value(E, e); + } + + fn value(d: *Self, comptime T: type, v: *const T) Error!void { + if (comptime isAtomic(T)) return d.value(@FieldType(T, "raw"), &v.raw); + const w = &d.out.writer; + if (comptime isList(T)) { + const E = @typeInfo(@FieldType(T, "items")).pointer.child; + if (try d.seen([]E, @intFromPtr(v.items.ptr), v.items.len)) return; + return d.items(E, v.items); + } + switch (comptime kindOf(T)) { + .skip, .void => {}, + .bool => try w.writeByte(@intFromBool(v.*)), + .int => try putInt(T, v.*, w), + .float => try w.writeAll(std.mem.asBytes(v)), + .@"enum" => try putInt(@typeInfo(T).@"enum".tag_type, @backingInt(v.*), w), + .optional => if (v.*) |*payload| { + try w.writeByte(1); + try d.value(@typeInfo(T).optional.child, payload); + } else try w.writeByte(0), + .one => { + const C = @typeInfo(T).pointer.child; + if (try d.seen(T, @intFromPtr(v.*), @max(1, @sizeOf(C)))) return; + try d.value(C, v.*); + }, + .slice => { + const E = @typeInfo(T).pointer.child; + if (try d.seen(T, @intFromPtr(v.ptr), v.len)) return; + if (comptime flat(E)) if (d.in_blob) if (d.deferred) |later| { + const bytes = std.mem.sliceAsBytes(v.*); + if (bytes.len >= blob_min) { + try w.writeAll(std.mem.asBytes(&@as(u64, v.len))); + return later.append(d.gpa, .{ .at = d.out.writer.end, .bytes = bytes }); + } + }; + try d.items(E, v.*); + }, + .array => { + const E = @typeInfo(T).array.child; + if (comptime flat(E)) return w.writeAll(std.mem.sliceAsBytes(v)); + for (v) |*e| try d.value(E, e); + }, + .prefix => unreachable, + .@"struct" => { + const packed_struct = comptime @typeInfo(T).@"struct".layout == .@"packed"; + inline for (comptime dumpFields(T)) |name| { + const F = @FieldType(T, name); + const was = d.in_blob; + d.in_blob = was or comptime blob(T, name); + defer d.in_blob = was; + if (comptime cutArray(T, name)) { + const all = &@field(v, name); + try d.items(@typeInfo(F).array.child, all[0..@min(all.len, lengthIn(v, comptime lengthOf(T, name).?))]); + } else if (packed_struct) { + const copy: F = @field(v, name); + try d.value(F, ©); + } else try d.value(F, &@field(v, name)); + } + }, + .@"union" => { + const tag = std.meta.activeTag(v.*); + const ordinal: u16 = inline for (@typeInfo(T).@"union".field_names, 0..) |name, i| { + if (tag == @field(std.meta.Tag(T), name)) break i; + } else unreachable; + try w.writeAll(std.mem.asBytes(&ordinal)); + switch (v.*) { + inline else => |*payload| try d.value(@TypeOf(payload.*), payload), + } + }, + // Kinds an old dump's table may name (`skip`); no type walked here has them. + .err, .error_union => unreachable, + .custom => { + const at = d.out.writer.end; + try w.writeAll(&std.mem.toBytes(@as(u64, 0))); + T.dumpWrite(v, d.gpa, w) catch return error.WriteFailed; + const n: u64 = d.out.writer.end - at - 8; + @memcpy(d.out.writer.buffer[at..][0..8], std.mem.asBytes(&n)); + }, + .bitset => { + try w.writeAll(std.mem.asBytes(&@as(u64, v.bit_length))); + const words = (v.bit_length + @bitSizeOf(usize) - 1) / @bitSizeOf(usize); + if (words > 0) try w.writeAll(std.mem.sliceAsBytes(v.masks[0..words])); + }, + } + } + }; +} + +/// One value `T` as a dump of its own (gpa): a closed pane, a terminal's +/// parts that are not its emulator. +pub fn save(comptime T: type, gpa: std.mem.Allocator, v: *const T) ![]u8 { + var d = try Dump(&.{T}).init(gpa); + errdefer d.deinit(); + try d.put(T, v); + return d.finish(); +} + +const DecodeError = error{ EndOfDump, BadDump, Incompatible, OutOfMemory }; + +/// The allocators a `replica.alloc` annotation may name, beside the +/// loader's own: `.alloc = .{ .{ "image", "image" } }` makes what field +/// `image` holds with `allocs.image`. +const Allocators = struct { + image: ?std.mem.Allocator = null, + terminal: ?std.mem.Allocator = null, +}; + +fn allocOf(comptime T: type, comptime name: []const u8) ?[]const u8 { + if (!@hasDecl(T, "replica") or !@hasField(@TypeOf(T.replica), "alloc")) return null; + inline for (T.replica.alloc) |pair| if (comptime std.mem.eql(u8, pair[0], name)) return pair[1]; + return null; +} + +fn countOf(n: u64) DecodeError!usize { + return std.math.cast(usize, n) orelse error.BadDump; +} + +/// An allocation a load made: what a reference to it finds, and what a +/// failed load frees. +const Made = struct { bytes: []u8, alignment: std.mem.Alignment, gpa: std.mem.Allocator, dead: bool = false }; + +/// A type as the dump's writer had it. +const SrcType = struct { + kind: Kind, + signed: bool = false, + bits: u16 = 0, + child: u32 = 0, + len: u64 = 0, + /// A struct's or union's fields, an enum's names (and `value`s). + fields: []const SrcField = &.{}, +}; +const SrcField = struct { name: []const u8, ty: u32 = 0, value: i128 = 0 }; + +/// Reads a dump of `roots`, one `into` or `get` each in order: a `Loader` +/// told this build's table of them. +pub fn Load(comptime roots: []const type) type { + return struct { + pub fn init(gpa: std.mem.Allocator, bytes: []const u8) DecodeError!Loader { + return Loader.init(gpa, bytes, tableOf(graph(roots))); + } + }; +} + +/// `Load`'s reader, one for every root set: it reads by the dump's own +/// table, and this build's (`table`) only says whether the two are one. +pub const Loader = struct { + const Self = @This(); + + /// Where what is read is made (a `replica.alloc` field's own + /// allocator while it is read). + gpa: std.mem.Allocator, + /// The loader's own lists'. + own: std.mem.Allocator, + bytes: []const u8, + at: usize = 0, + arena: std.heap.ArenaAllocator, + src: []SrcType = &.{}, + /// Its table is this build's: no name is asked. + same: bool = false, + /// Each pointer and slice made so far: what a reference finds, and + /// what `rollback` frees. + shared: std.ArrayList(Made) = .empty, + /// What a type's `dumpRead` made, freed by its `dumpFree` too. + customs: std.ArrayList(struct { ptr: *anyopaque, gpa: std.mem.Allocator, free: *const fn (*anyopaque, std.mem.Allocator) void }) = .empty, + /// What was let go, for the person whose session it is. + notes: std.ArrayList(u8) = .empty, + /// The field being read, for a note. + field: []const u8 = "", + /// Where a field's annotation (`replica.alloc`) says its values are + /// made instead of `gpa`. + allocs: Allocators = .{}, + + pub fn init(gpa: std.mem.Allocator, bytes: []const u8, table: []const u8) DecodeError!Self { + var l: Self = .{ .gpa = gpa, .own = gpa, .bytes = bytes, .arena = .init(gpa) }; + errdefer l.arena.deinit(); + if (!std.mem.startsWith(u8, bytes, dump_magic)) return error.BadDump; + l.at = dump_magic.len; + const table_at = l.at; + try l.readTable(); + l.same = std.mem.eql(u8, table, bytes[table_at..l.at]); + return l; + } + + pub fn deinit(l: *Self) void { + l.shared.deinit(l.own); + l.customs.deinit(l.own); + l.notes.deinit(l.own); + l.arena.deinit(); + } + + /// Everything read so far freed: a load that fails leaves nothing. + /// What it was read into must not be used after (nor freed). + pub fn rollback(l: *Self) void { + for (l.customs.items) |c| c.free(c.ptr, c.gpa); + for (l.shared.items) |m| if (m.bytes.len > 0) m.gpa.rawFree(m.bytes, m.alignment, @returnAddress()); + l.customs.clearRetainingCapacity(); + l.shared.clearRetainingCapacity(); + } + + fn made(l: *Self, bytes: []u8, alignment: std.mem.Alignment) DecodeError!usize { + try l.shared.append(l.own, .{ .bytes = bytes, .alignment = alignment, .gpa = l.gpa }); + return l.shared.items.len - 1; + } + + fn take(l: *Self, n: usize) DecodeError![]const u8 { + if (l.bytes.len - l.at < n) return error.EndOfDump; + defer l.at += n; + return l.bytes[l.at..][0..n]; + } + + fn scalar(l: *Self, comptime T: type) DecodeError!T { + return std.mem.bytesToValue(T, try l.take(@sizeOf(T))); + } + + /// A count, as this machine counts (a wasm32 one has 32 bits). + fn count(l: *Self) DecodeError!usize { + return countOf(try l.scalar(u64)); + } + + fn name(l: *Self) DecodeError![]const u8 { + return l.take(try l.scalar(u16)); + } + + fn readTable(l: *Self) DecodeError!void { + const a = l.arena.allocator(); + const n = try l.scalar(u32); + if (n > l.bytes.len) return error.BadDump; + l.src = try a.alloc(SrcType, n); + for (l.src) |*t| { + const k = std.enums.fromInt(Kind, (try l.take(1))[0]) orelse return error.BadDump; + t.* = .{ .kind = k }; + switch (k) { + .int => { + t.signed = (try l.take(1))[0] != 0; + t.bits = try l.scalar(u16); + }, + .float => t.bits = try l.scalar(u16), + .@"enum" => { + t.signed = (try l.take(1))[0] != 0; + t.bits = try l.scalar(u16); + const list = try a.alloc(SrcField, try l.scalar(u32)); + for (list) |*f| f.* = .{ .name = try l.name(), .value = try l.scalar(i128) }; + t.fields = list; + }, + .array => { + t.len = try l.scalar(u64); + t.child = try l.scalar(u32); + }, + .optional, .one, .slice, .prefix, .error_union => t.child = try l.scalar(u32), + .@"struct", .@"union" => { + const nfields = try l.scalar(u32); + if (nfields > l.bytes.len) return error.BadDump; + const list = try a.alloc(SrcField, nfields); + for (list) |*f| f.* = .{ .name = try l.name(), .ty = try l.scalar(u32) }; + t.fields = list; + }, + .custom => _ = try l.name(), + .skip, .void, .bool, .err, .bitset => {}, + } + } + for (l.src) |t| { + if (t.child >= n) return error.BadDump; + for (t.fields) |f| if (f.ty >= n) return error.BadDump; + } + } + + pub fn note(l: *Self, comptime fmt: []const u8, args: anytype) void { + if (l.notes.items.len > 4096) return; + l.notes.print(l.own, fmt ++ "\n", args) catch {}; + } + + /// A note on a type's field, its names given as run-time strings: + /// one instance of `note` (and of std's `print`) a message, where + /// a tuple of the comptime names made one a type, field and message. + fn noteField(l: *Self, comptime what: []const u8, type_name: []const u8, field: []const u8) void { + l.note("{s}.{s}: " ++ what, .{ type_name, field }); + } + + fn root(l: *Self) DecodeError!u32 { + const ty = try l.scalar(u32); + if (ty >= l.src.len) return error.BadDump; + return ty; + } + + /// The next root, made: what it points at is `gpa`'s. + pub fn get(l: *Self, comptime T: type) DecodeError!T { + var out: T = undefined; + try l.fresh(T, &out); + try l.value(T, try l.root(), &out); + return out; + } + + /// The next root read into `out` as it stands: a field the dump + /// holds is replaced (what it held is not freed), every other one + /// is left as it is. A field another build cannot give is left too, + /// and noted. + pub fn into(l: *Self, comptime T: type, out: *T) DecodeError!void { + const ty = try l.root(); + const s = l.src[ty]; + if (s.kind != .@"struct") return error.BadDump; + try l.fields(T, s, out, true); + } + + fn fresh(l: *Self, comptime T: type, out: *T) DecodeError!void { + freshOf(T, out, l.gpa); + } + + /// Whether the source's `ty` and `T` are of one kind, else the + /// source's value passed over. + fn kindMatches(l: *Self, comptime T: type, ty: u32) DecodeError!bool { + if (l.same) return true; + const want = comptime kindOf(Canon(T)); + const got = l.src[ty].kind; + if (got == want) return true; + // A field that came to hold a count and so many, or stopped. + if ((want == .array and got == .prefix) or (want == .prefix and got == .array)) return true; + try l.skip(ty); + return false; + } + + fn readInt(l: *Self, comptime I: type, s: SrcType) DecodeError!I { + if (l.same) { + const info = @typeInfo(I).int; + const W = @Int(info.signedness, intBytes(info.bits) * 8); + return @intCast(try l.scalar(W)); + } + const n = intBytes(s.bits); + const raw = try l.take(n); + var wide: u128 = 0; + for (raw, 0..) |b, i| wide |= @as(u128, b) << @intCast(i * 8); + if (s.signed and n > 0) { + const shift: u7 = @intCast(128 - n * 8); + const signed: i128 = @as(i128, @bitCast(wide << shift)) >> shift; + return std.math.cast(I, signed) orelse error.Incompatible; + } + return std.math.cast(I, wide) orelse error.Incompatible; + } + + /// `T` read from the source's type `ty` into `out`, which `fresh` + /// has made ready. + fn value(l: *Self, comptime T: type, ty: u32, out: *T) DecodeError!void { + if (comptime isAtomic(T)) { + const R = @FieldType(T, "raw"); + var raw: R = undefined; + try l.fresh(R, &raw); + try l.value(R, ty, &raw); + out.* = .{ .raw = raw }; + return; + } + // A field this build compiles out (a void field): passed over, + // said only when it held something. + if (comptime kindOf(Canon(T)) == .void) if (!l.same and l.src[ty].kind != .void) { + const held = l.src[ty].kind != .optional or (l.at < l.bytes.len and l.bytes[l.at] != 0); + try l.skip(ty); + if (held) l.note("{s}: not in this build", .{l.field}); + return; + }; + if (!try l.kindMatches(T, ty)) return error.Incompatible; + const s = l.src[ty]; + if (comptime isList(T)) { + const E = @typeInfo(@FieldType(T, "items")).pointer.child; + const got = try l.slice(E, s); + out.* = .empty; + out.items = got; + out.capacity = got.len; + return; + } + switch (comptime kindOf(T)) { + .skip, .void => {}, + .bool => out.* = (try l.take(1))[0] != 0, + .int => out.* = try l.readInt(T, s), + .float => out.* = if (l.same or s.bits == @typeInfo(T).float.bits) try l.scalar(T) else return error.Incompatible, + .@"enum" => { + const e = @typeInfo(T).@"enum"; + if (l.same) { + out.* = @fromBackingInt(@intCast(try l.readInt(e.tag_type, s))); + return; + } + const n = try l.readInt(i128, s); + const was = for (s.fields) |f| { + if (f.value == n) break f.name; + } else null; + if (was) |w| inline for (e.field_names) |field| if (std.mem.eql(u8, w, field)) { + out.* = @field(T, field); + return; + }; + if (e.mode == .nonexhaustive and was == null) + if (std.math.cast(e.tag_type, n)) |tag| { + out.* = @fromBackingInt(@intCast(tag)); + return; + }; + l.note("{s}: no {s} here", .{ l.field, was orelse "such value" }); + return error.Incompatible; + }, + .optional => { + const C = @typeInfo(T).optional.child; + if ((try l.take(1))[0] == 0) { + out.* = null; + return; + } + if (comptime kindOf(Canon(C)) == .skip) { + out.* = if (comptime C == std.mem.Allocator) l.gpa else null; + return; + } + // A slice's or a pointer's null is its address: set to + // an undefined payload, the optional itself is undefined, + // and ReleaseSafe's optimizer read it as null (a pane's + // `?[]u8` command one byte long, every field after it out + // of step). Read through a local and set it from that. + if (comptime @typeInfo(C) == .pointer) { + var payload: C = undefined; + try l.value(C, s.child, &payload); + out.* = payload; + return; + } + out.* = @as(C, undefined); + try l.fresh(C, &out.*.?); + l.value(C, s.child, &out.*.?) catch |err| { + out.* = null; + return err; + }; + }, + .one => { + const C = @typeInfo(T).pointer.child; + if (try l.ref()) |again| { + out.* = @ptrCast(@alignCast(again.ptr)); + return; + } + const one = try l.gpa.create(C); + const at = l.made(std.mem.asBytes(one), .of(C)) catch |err| { + l.gpa.destroy(one); + return err; + }; + try l.fresh(C, one); + l.value(C, s.child, one) catch |err| { + // Left half made: no later reference may find it. + l.shared.items[at].dead = true; + return err; + }; + out.* = one; + }, + .slice => { + const E = @typeInfo(T).pointer.child; + const got = try l.slice(E, s); + if (comptime @typeInfo(T).pointer.sentinel_ptr != null) @compileError("walk: a sentinel slice: " ++ @typeName(T)); + out.* = got; + }, + .array => { + const E = @typeInfo(T).array.child; + const n: u64 = if (s.kind == .prefix) try l.scalar(u64) else s.len; + try l.elements(E, s.child, n, out); + }, + .prefix => unreachable, + .@"struct" => try l.fields(T, s, out, false), + .@"union" => { + const u = @typeInfo(T).@"union"; + const ordinal = try l.scalar(u16); + if (ordinal >= s.fields.len) return error.BadDump; + const was = s.fields[ordinal]; + inline for (u.field_names, u.field_types, 0..) |field, F, i| { + if (if (l.same) ordinal == i else std.mem.eql(u8, was.name, field)) { + out.* = @unionInit(T, field, undefined); + try l.fresh(F, &@field(out.*, field)); + return l.value(F, was.ty, &@field(out.*, field)); + } + } + try l.skip(was.ty); + l.note("{s}: no {s} here", .{ l.field, was.name }); + return error.Incompatible; + }, + .err, .error_union => unreachable, + .custom => { + const bytes = try l.take(try l.count()); + T.dumpRead(out, l.gpa, bytes) catch |err| { + if (err == error.OutOfMemory) return error.OutOfMemory; + l.note("{s}: {t}", .{ l.field, err }); + return error.Incompatible; + }; + if (comptime @hasDecl(T, "dumpFree")) try l.customs.append(l.own, .{ .ptr = out, .gpa = l.gpa, .free = @ptrCast(&T.dumpFree) }); + }, + .bitset => { + const bits = try l.count(); + out.* = try .initEmpty(l.gpa, bits); + const words = (bits + @bitSizeOf(usize) - 1) / @bitSizeOf(usize); + if (words > 0) @memcpy(std.mem.sliceAsBytes(out.masks[0..words]), try l.take(words * @sizeOf(usize))); + }, + } + } + + /// A reference to a pointer or slice made before, or null for a + /// new one (its length then read). + fn ref(l: *Self) DecodeError!?[]u8 { + const n = try l.scalar(u32); + if (n == 0) return null; + if (n > l.shared.items.len) return error.BadDump; + const got = l.shared.items[n - 1]; + if (got.dead) return error.Incompatible; + return got.bytes; + } + + fn slice(l: *Self, comptime E: type, s: SrcType) DecodeError![]E { + if (try l.ref()) |again| return @as([*]E, @ptrCast(@alignCast(again.ptr)))[0 .. again.len / @max(1, @sizeOf(E))]; + const n = try l.count(); + if (n == 0) return &.{}; + if (n > l.bytes.len) return error.BadDump; + const many = try l.gpa.alloc(E, n); + const at = l.made(std.mem.sliceAsBytes(many), .of(E)) catch |err| { + l.gpa.free(many); + return err; + }; + l.elements(E, s.child, n, many) catch |err| { + l.shared.items[at].dead = true; + return err; + }; + return many; + } + + /// `n` elements of the source's type `ty` into `out` (an array or + /// a slice), as many as it holds, the rest passed over. + fn elements(l: *Self, comptime E: type, ty: u32, n: u64, out: []E) DecodeError!void { + const keep: usize = @intCast(@min(n, out.len)); + const s = l.src[ty]; + // Bytes copied whole between builds when both sides agree on + // them: integers and bools (an enum's numbers may not be the other's). + const bulk = if (comptime flat(E)) l.same or (comptime flatHash(E)) and s.kind == (comptime kindOf(E)) and + (s.kind == .bool or (s.bits == @bitSizeOf(E) and s.signed == (@typeInfo(E) == .int and @typeInfo(E).int.signedness == .signed))) else false; + if (bulk) { + if (n > l.bytes.len) return error.EndOfDump; + @memcpy(std.mem.sliceAsBytes(out[0..keep]), try l.take(keep * @sizeOf(E))); + _ = try l.take(@intCast((n - keep) * @sizeOf(E))); + return; + } + // An array of optional pointers (a session's panes): one that + // cannot be read is left out, not the array. + const droppable = comptime @typeInfo(E) == .optional and @typeInfo(@typeInfo(E).optional.child) == .pointer; + var failed = false; + for (0..try countOf(n)) |i| { + if (i >= keep) { + try l.skip(ty); + continue; + } + try l.fresh(E, &out[i]); + l.value(E, ty, &out[i]) catch |err| { + if (err != error.Incompatible) return err; + if (droppable) { + out[i] = null; + l.note("{s}[{d}] left out", .{ l.field, i }); + } else failed = true; + }; + } + if (failed) return error.Incompatible; + } + + fn fields(l: *Self, comptime T: type, s: SrcType, out: *T, existing: bool) DecodeError!void { + const names = comptime dumpFields(T); + const packed_struct = comptime @typeInfo(T).@"struct".layout == .@"packed"; + const outer = l.field; + defer l.field = outer; + if (l.same) { + if (s.fields.len != names.len) return error.BadDump; + inline for (names, 0..) |field, k| { + l.field = field; + try l.oneField(T, field, s.fields[k].ty, out, packed_struct, existing); + } + return; + } + var found: std.StaticBitSet(@max(1, names.len)) = .empty; + var failed = false; + for (s.fields) |f| { + const k: ?usize = inline for (names, 0..) |field, k| { + if (std.mem.eql(u8, f.name, field)) break k; + } else null; + const at = k orelse { + try l.skip(f.ty); + continue; + }; + found.set(at); + inline for (names, 0..) |field, i| if (i == at) { + l.field = field; + l.oneField(T, field, f.ty, out, packed_struct, existing) catch |err| { + if (err != error.Incompatible) return err; + const attr = comptime @typeInfo(T).@"struct".field_attrs[std.meta.fieldIndex(T, field).?]; + if (comptime attr.default_value_ptr) |dp| { + @field(out, field) = @as(*const @FieldType(T, field), @ptrCast(@alignCast(dp))).*; + l.noteField("its kind changed; its default taken", @typeName(T), field); + } else if (existing) { + l.noteField("its kind changed; left as it was", @typeName(T), field); + } else failed = true; + }; + }; + } + // A field the writer did not have: its default (`fresh`), or + // the value cannot be made. + inline for (names, 0..) |field, i| if (!found.isSet(i)) { + const attr = comptime @typeInfo(T).@"struct".field_attrs[std.meta.fieldIndex(T, field).?]; + if (comptime attr.default_value_ptr == null) { + if (!existing) { + l.noteField("not in the dump", @typeName(T), field); + failed = true; + } + } + }; + if (failed) return error.Incompatible; + } + + fn oneField(l: *Self, comptime T: type, comptime field: []const u8, ty: u32, out: *T, comptime packed_struct: bool, existing: bool) DecodeError!void { + const F = @FieldType(T, field); + const gpa = l.gpa; + defer l.gpa = gpa; + if (comptime allocOf(T, field)) |which| if (@field(l.allocs, which)) |a| { + l.gpa = a; + }; + if (comptime cutArray(T, field)) { + return l.value(F, ty, &@field(out, field)); + } + // A struct held in place in one read as it stands (the root's): + // what it does not hold stays as it is too. + if (comptime kindOf(Canon(F)) == .@"struct" and Canon(F) == F and @typeInfo(F).@"struct".layout != .@"packed") if (existing) { + if (!try l.kindMatches(F, ty)) return error.Incompatible; + return l.fields(F, l.src[ty], &@field(out, field), true); + }; + if (packed_struct) { + var copy: F = undefined; + try l.fresh(F, ©); + try l.value(F, ty, ©); + @field(out, field) = copy; + return; + } + try l.fresh(F, &@field(out, field)); + try l.value(F, ty, &@field(out, field)); + } + + /// The source's value of type `ty` passed over. + fn skip(l: *Self, ty: u32) DecodeError!void { + const s = l.src[ty]; + switch (s.kind) { + .skip, .void => {}, + .bool => _ = try l.take(1), + .int, .@"enum" => _ = try l.take(intBytes(s.bits)), + .float => _ = try l.take(s.bits / 8), + .optional => if ((try l.take(1))[0] != 0) try l.skip(s.child), + .one => if (try l.scalar(u32) == 0) { + _ = try l.made(&.{}, .@"1"); + l.shared.items[l.shared.items.len - 1].dead = true; + try l.skip(s.child); + }, + .slice => if (try l.scalar(u32) == 0) { + const n = try l.scalar(u64); + if (n > 0) { + _ = try l.made(&.{}, .@"1"); + l.shared.items[l.shared.items.len - 1].dead = true; + } + try l.skipMany(s.child, n); + }, + .prefix => try l.skipMany(s.child, try l.scalar(u64)), + .array => try l.skipMany(s.child, s.len), + .@"struct" => for (s.fields) |f| try l.skip(f.ty), + .@"union" => { + const ordinal = try l.scalar(u16); + if (ordinal >= s.fields.len) return error.BadDump; + try l.skip(s.fields[ordinal].ty); + }, + .err => _ = try l.name(), + .error_union => if ((try l.take(1))[0] != 0) try l.skip(s.child) else { + _ = try l.name(); + }, + .custom => _ = try l.take(try l.count()), + .bitset => _ = try l.take((try l.count() + 63) / 64 * 8), + } + } + + fn skipMany(l: *Self, ty: u32, n: u64) DecodeError!void { + const s = l.src[ty]; + if (s.kind == .int or s.kind == .bool) { + const size: u64 = if (s.kind == .bool) 1 else intBytes(s.bits); + if (n > l.bytes.len) return error.EndOfDump; + _ = try l.take(@intCast(n * size)); + return; + } + for (0..try countOf(n)) |_| try l.skip(ty); + } +}; + +/// `out` as a new `T` is before a load reads its fields: each field's +/// default, an allocator `gpa`. +fn freshOf(comptime T: type, out: *T, gpa: std.mem.Allocator) void { + if (comptime @typeInfo(T) != .@"struct" or isList(T) or isAtomic(T) or isBitset(T) or kindOf(T) == .custom or kindOf(T) == .skip) return; + const s = @typeInfo(T).@"struct"; + inline for (s.field_names, s.field_types, s.field_attrs) |field, F, attr| { + if (attr.@"comptime") continue; + if (comptime attr.default_value_ptr) |dp| { + @field(out, field) = @as(*const F, @ptrCast(@alignCast(dp))).*; + } else if (comptime F == std.mem.Allocator) { + @field(out, field) = gpa; + } else if (comptime !walkedField(T, field)) { + @compileError("walk: " ++ @typeName(T) ++ "." ++ field ++ " has no default to load to"); + } + } +} + +fn walkedField(comptime T: type, comptime field: []const u8) bool { + inline for (comptime dumpFields(T)) |n| if (comptime std.mem.eql(u8, n, field)) return true; + return false; +} + +/// A value `save` made, `gpa`'s; what was let go is said in `notes` when +/// it is given. +pub fn load(comptime T: type, gpa: std.mem.Allocator, bytes: []const u8, notes: ?*std.ArrayList(u8)) DecodeError!T { + var l = try Load(&.{T}).init(gpa, bytes); + defer l.deinit(); + errdefer l.rollback(); + const v = try l.get(T); + if (notes) |n| try n.appendSlice(gpa, l.notes.items); + return v; +} + +// ---- a dump as a database: the same walk, by name, into xitdb's maps ---- +// +// A dump (Db.zig) is a xitdb database in memory, its bytes one value of the +// state file, written by the walk by name: a struct is a map whose keys are +// its fields' names (`putKey`: a reader goes through them by name, never by +// a hash of its own), a union a map of its one field, a slice, an array or +// a list of records a list, of plain numbers one bytes value (its format +// tag the numbers' kind and width), an enum the bytes of its name, a number +// a uint or an int (a wider one its bytes), an optional an absent key (an +// explicit none where the field's default is not null), a type with +// `dumpWrite` its bytes, and a `.blob`'s text of `blob_min` bytes and up +// its BLAKE3 hash (tag "b3"): the text is kept once beside the dump +// (`Blob`). A pointer or a slice met again is the first one's value again: +// what two fields share is shared again. +// +// Another build reads it by name: a field the dump has not takes its +// default, a key this build has not is passed over, a value of another kind +// takes its default and is said (`notes`); with no default the value it is +// part of is refused, and an element of an array of optional pointers (a +// session's panes) is then left out, nothing above it. + +pub const Mem = xitdb.Database(.memory, u256); + +/// A text a dump keeps beside it, once: its BLAKE3 hash and its bytes (the +/// session's, while the dump is made). +pub const Blob = struct { hash: [32]u8, bytes: []const u8 }; + +/// A field's key: its name's word, unique within its struct (a reader +/// matches names, so another build's words need not be these). +fn nameKey(comptime name: []const u8) u256 { + return comptime std.hash.Wyhash.hash(0, name); +} + +/// Whether a run of `E` is one bytes value: plain numbers. +fn numbers(comptime E: type) bool { + return switch (@typeInfo(E)) { + .int => |i| @sizeOf(E) * 8 == i.bits and @sizeOf(E) <= 8, + .bool => true, + .float => |f| f.bits == 32 or f.bits == 64, + else => false, + }; +} + +/// A run of numbers' format tag: their kind and byte width ("u4", "i8", "b1"). +fn numbersTag(comptime E: type) [2]u8 { + const kind: u8 = switch (@typeInfo(E)) { + .int => |i| if (i.signedness == .signed) 'i' else 'u', + .bool => 'b', + .float => 'f', + else => unreachable, + }; + return .{ kind, '0' + @sizeOf(E) }; +} + +const blob_tag = "b3".*; +const wide_tag = "w8".*; +const custom_tag = "cu".*; +const bitset_tag = "bs".*; + +fn typeWord(comptime T: type) u64 { + return comptime std.hash.Wyhash.hash(0, @typeName(T)); +} + +/// Writes values into a database in memory, by name (see above). +pub const Put = struct { + gpa: std.mem.Allocator, + /// Each pointer and slice written, by address, length and type, and + /// where its value is: met again, that value is written again. + memo: std.AutoHashMapUnmanaged(Key, xitdb.Slot) = .empty, + /// The blobs met, each once. + blobs: std.ArrayListUnmanaged(Blob) = .empty, + in_blob: bool = false, + + const Key = struct { addr: usize, len: usize, ty: u64 }; + const Cursor = Mem.Cursor(.read_write); + + pub fn deinit(w: *Put) void { + w.memo.deinit(w.gpa); + w.blobs.deinit(w.gpa); + } + + /// `v` written as `name`'s value in `map` (a dump's roots). + pub fn member(w: *Put, map: Mem.HashMap(.read_write), comptime name: []const u8, comptime T: type, v: *const T) anyerror!void { + try map.putKey(comptime nameKey(name), .{ .bytes = name }); + var at = try map.putCursor(comptime nameKey(name)); + _ = try w.value(T, v, &at); + } + + /// `v` written at `c`; where its value is. + pub fn value(w: *Put, comptime T: type, v: *const T, c: *Cursor) anyerror!xitdb.Slot { + if (comptime isAtomic(T)) return w.value(@FieldType(T, "raw"), &v.raw, c); + if (comptime isList(T)) return w.many(@typeInfo(@FieldType(T, "items")).pointer.child, v.items, c, true); + switch (comptime kindOf(T)) { + .skip, .void => try c.write(.{ .slot = null }), + .bool => try c.write(.{ .uint = @intFromBool(v.*) }), + .int => if (@typeInfo(T).int.bits <= 64) { + try c.write(if (@typeInfo(T).int.signedness == .signed) .{ .int = v.* } else .{ .uint = v.* }); + } else { + const wide: i128 = @intCast(v.*); + try c.write(.{ .bytes_object = .{ .value = std.mem.asBytes(&wide), .format_tag = wide_tag } }); + }, + .float => try c.write(.{ .float = v.* }), + .@"enum" => if (std.enums.tagName(T, v.*)) |name| { + try c.write(.{ .bytes = name }); + } else try c.write(.{ .int = @intCast(@backingInt(v.*)) }), + .optional => { + const C = @typeInfo(T).optional.child; + if (v.*) |*payload| { + // An allocator, say, is no state: there or not, which a + // load answers with its own. + if (comptime kindOf(Canon(C)) == .skip) try c.write(.{ .uint = 1 }) else return w.value(C, payload, c); + } else try c.write(.{ .slot = null }); + }, + .one => { + const C = @typeInfo(T).pointer.child; + const key: Key = .{ .addr = @intFromPtr(v.*), .len = @max(1, @sizeOf(C)), .ty = typeWord(T) }; + if (w.memo.get(key)) |slot| { + try c.write(.{ .slot = slot }); + return slot; + } + const slot = try w.value(C, v.*, c); + try w.memo.put(w.gpa, key, slot); + return slot; + }, + .slice => return w.many(@typeInfo(T).pointer.child, v.*, c, true), + .array => return w.many(@typeInfo(T).array.child, v, c, false), + .prefix => unreachable, + .@"struct" => return w.fields(T, v, c), + .@"union" => { + const map = try Mem.HashMap(.read_write).init(c.*); + switch (v.*) { + inline else => |*payload, tag| { + const name = @tagName(tag); + try map.putKey(comptime nameKey(name), .{ .bytes = name }); + var at = try map.putCursor(comptime nameKey(name)); + _ = try w.value(@TypeOf(payload.*), payload, &at); + }, + } + return map.slot(); + }, + // No type a dump walks has them. + .err, .error_union => unreachable, + .custom => { + var buf: [4096]u8 = undefined; + var out = try c.writer(&buf); + try T.dumpWrite(v, w.gpa, &out.interface); + out.format_tag = custom_tag; + try out.finish(); + }, + .bitset => { + const words = (v.bit_length + @bitSizeOf(usize) - 1) / @bitSizeOf(usize); + var buf: [64]u8 = undefined; + var out = try c.writer(&buf); + try out.interface.writeAll(std.mem.asBytes(&@as(u64, v.bit_length))); + if (words > 0) try out.interface.writeAll(std.mem.sliceAsBytes(v.masks[0..words])); + out.format_tag = bitset_tag; + try out.finish(); + }, + } + return c.slot(); + } + + /// A run of `E`: numbers as one bytes value (a blob's text by its + /// hash), records as a list; a slice met again (`shared`) its first + /// value. + fn many(w: *Put, comptime E: type, items: []const E, c: *Cursor, comptime shared: bool) anyerror!xitdb.Slot { + const key: Key = .{ .addr = @intFromPtr(items.ptr), .len = items.len, .ty = typeWord([]const E) }; + if (shared and items.len > 0) if (w.memo.get(key)) |slot| { + try c.write(.{ .slot = slot }); + return slot; + }; + const slot = if (comptime numbers(E)) slot: { + const bytes = std.mem.sliceAsBytes(items); + if (E == u8 and w.in_blob and bytes.len >= blob_min) { + var sum: [32]u8 = undefined; + std.crypto.hash.Blake3.hash(bytes, &sum, .{}); + const known = for (w.blobs.items) |b| { + if (std.mem.eql(u8, &b.hash, &sum)) break true; + } else false; + if (!known) try w.blobs.append(w.gpa, .{ .hash = sum, .bytes = bytes }); + try c.write(.{ .bytes_object = .{ .value = &sum, .format_tag = blob_tag } }); + } else try c.write(.{ .bytes_object = .{ .value = bytes, .format_tag = numbersTag(E) } }); + break :slot try c.slot(); + } else slot: { + const list = try Mem.ArrayList(.read_write).init(c.*); + for (items) |*e| { + var at = try list.appendCursor(); + _ = try w.value(E, e, &at); + } + break :slot try list.slot(); + }; + if (shared and items.len > 0) try w.memo.put(w.gpa, key, slot); + return slot; + } + + fn fields(w: *Put, comptime T: type, v: *const T, c: *Cursor) anyerror!xitdb.Slot { + const map = try Mem.HashMap(.read_write).init(c.*); + const packed_struct = comptime @typeInfo(T).@"struct".layout == .@"packed"; + inline for (comptime dumpFields(T)) |name| { + const F = @FieldType(T, name); + if (comptime kindOf(Canon(F)) != .void) put: { + // Null where the field's default is: no key at all. + if (comptime @typeInfo(F) == .optional and defaultIsNull(T, name)) if (@field(v, name) == null) break :put; + const was = w.in_blob; + w.in_blob = was or comptime blob(T, name); + defer w.in_blob = was; + try map.putKey(comptime nameKey(name), .{ .bytes = name }); + var at = try map.putCursor(comptime nameKey(name)); + if (comptime cutArray(T, name)) { + const all = &@field(v, name); + _ = try w.many(@typeInfo(F).array.child, all[0..@min(all.len, lengthIn(v, comptime lengthOf(T, name).?))], &at, false); + } else if (comptime packed_struct) { + const copy: F = @field(v, name); + _ = try w.value(F, ©, &at); + } else _ = try w.value(F, &@field(v, name), &at); + } + } + return map.slot(); + } +}; + +fn defaultIsNull(comptime T: type, comptime name: []const u8) bool { + const F = @FieldType(T, name); + const attr = @typeInfo(T).@"struct".field_attrs[std.meta.fieldIndex(T, name).?]; + const dp = attr.default_value_ptr orelse return false; + return @as(*const F, @ptrCast(@alignCast(dp))).* == null; +} + +/// Reads values a `Put` wrote, by name, as another build may have written +/// them (see above). +pub const Get = struct { + /// Where what is read is made (a `replica.alloc` field's own allocator + /// while it is read). + gpa: std.mem.Allocator, + /// The reader's own lists'. + own: std.mem.Allocator, + /// The texts its blobs' hashes name (Db.zig's `blobs`), by hash. + blobs: ?Mem.HashMap(.read_only) = null, + /// Each pointer and slice made so far: what a value met again is, and + /// what `rollback` frees. + made: std.ArrayList(Made) = .empty, + /// Where each value made is: met again, the same one. + memo: std.AutoHashMapUnmanaged(u128, usize) = .empty, + /// What a type's `dumpRead` made, freed by its `dumpFree` too. + customs: std.ArrayList(struct { ptr: *anyopaque, gpa: std.mem.Allocator, free: *const fn (*anyopaque, std.mem.Allocator) void }) = .empty, + /// What was let go, for the person whose session it is. + notes: std.ArrayList(u8) = .empty, + /// The field being read, for a note. + field: []const u8 = "", + allocs: Allocators = .{}, + + const Cursor = Mem.Cursor(.read_only); + pub const Error = error{ BadDump, Incompatible, OutOfMemory }; + + pub fn init(gpa: std.mem.Allocator) Get { + return .{ .gpa = gpa, .own = gpa }; + } + + pub fn deinit(l: *Get) void { + l.made.deinit(l.own); + l.memo.deinit(l.own); + l.customs.deinit(l.own); + l.notes.deinit(l.own); + } + + /// Everything read so far freed: a load that fails leaves nothing. + /// What it was read into must not be used after (nor freed). + pub fn rollback(l: *Get) void { + for (l.customs.items) |c| c.free(c.ptr, c.gpa); + for (l.made.items) |m| if (m.bytes.len > 0) m.gpa.rawFree(m.bytes, m.alignment, @returnAddress()); + l.customs.clearRetainingCapacity(); + l.made.clearRetainingCapacity(); + l.memo.clearRetainingCapacity(); + } + + pub fn note(l: *Get, comptime fmt: []const u8, args: anytype) void { + if (l.notes.items.len > 4096) return; + l.notes.print(l.own, fmt ++ "\n", args) catch {}; + } + + /// A note on a type's field, its names given at run time (Load's). + fn noteField(l: *Get, comptime what: []const u8, type_name: []const u8, field: []const u8) void { + l.note("{s}.{s}: " ++ what, .{ type_name, field }); + } + + /// The value at `c`, made: what it points at is `gpa`'s. + pub fn get(l: *Get, comptime T: type, c: Cursor) Error!T { + var out: T = undefined; + try l.fresh(T, &out); + try l.value(T, c, &out); + return out; + } + + /// The struct at `c` read into `out` as it stands: a field the dump + /// holds is replaced (what it held is not freed), every other one is + /// left as it is, and one another build cannot give is left too, and + /// noted. + pub fn into(l: *Get, comptime T: type, c: Cursor, out: *T) Error!void { + try l.fields(T, c, out, true); + } + + /// Where the value of `name` is in the map at `c` (a dump's roots), by + /// its name; null when it is not there. + pub fn member(c: Cursor, name: []const u8) Error!?Cursor { + const map = Mem.HashMap(.read_only).init(c) catch return error.BadDump; + var it = map.iterator() catch return error.BadDump; + while (it.next() catch return error.BadDump) |kv_at| { + const kv = kv_at.readKeyValuePair() catch return error.BadDump; + var buf: [64]u8 = undefined; + const got = kv.key_cursor.readBytes(&buf) catch continue; + if (std.mem.eql(u8, got, name)) return kv.value_cursor; + } + return null; + } + + fn fresh(l: *Get, comptime T: type, out: *T) Error!void { + freshOf(T, out, l.gpa); + } + + fn slotWord(slot: xitdb.Slot) u128 { + return @as(u72, @bitCast(slot)); + } + + fn slotOf(c: Cursor) Error!xitdb.Slot { + return c.slot() catch error.BadDump; + } + + /// Whether the value at `slot` has a place of its own (an inline number + /// or a short text is its slot alone: no identity to share). + fn placed(slot: xitdb.Slot) bool { + return switch (slot.tag) { + .none, .uint, .int, .float, .short_bytes => false, + else => true, + }; + } + + /// An allocation made for the value at `slot`, kept: what a value met + /// again is, and what `rollback` frees. + fn keep(l: *Get, bytes: []u8, alignment: std.mem.Alignment, slot: xitdb.Slot) Error!usize { + try l.made.append(l.own, .{ .bytes = bytes, .alignment = alignment, .gpa = l.gpa }); + const at = l.made.items.len - 1; + // Not kept after all: the caller frees it. + if (placed(slot)) l.memo.put(l.own, slotWord(slot), at) catch |err| { + _ = l.made.pop(); + return err; + }; + return at; + } + + /// The value made before for the same place, when there was one. + fn again(l: *Get, slot: xitdb.Slot) Error!?[]u8 { + if (!placed(slot)) return null; + const at = l.memo.get(slotWord(slot)) orelse return null; + // Made, then let go of by the reader's caller (a dump's mounts). + if (at >= l.made.items.len) return null; + const m = l.made.items[at]; + if (m.dead) return error.Incompatible; + return m.bytes; + } + + /// `T` read from `c` into `out`, which `fresh` has made ready. + fn value(l: *Get, comptime T: type, c: Cursor, out: *T) Error!void { + if (comptime isAtomic(T)) { + const R = @FieldType(T, "raw"); + var raw: R = undefined; + try l.fresh(R, &raw); + try l.value(R, c, &raw); + out.* = .{ .raw = raw }; + return; + } + const slot = try slotOf(c); + if (comptime isList(T)) { + const got = try l.slice(@typeInfo(@FieldType(T, "items")).pointer.child, c, slot); + out.* = .empty; + out.items = got; + out.capacity = got.len; + return; + } + switch (comptime kindOf(T)) { + .skip, .void => {}, + .bool => out.* = switch (slot.tag) { + .uint => slot.value != 0, + else => return error.Incompatible, + }, + .int => out.* = try l.int(T, c, slot), + .float => out.* = switch (slot.tag) { + .float => @floatCast(@as(f64, @bitCast(slot.value))), + else => return error.Incompatible, + }, + .@"enum" => { + const e = @typeInfo(T).@"enum"; + switch (slot.tag) { + .bytes, .short_bytes => { + var buf: [256]u8 = undefined; + const name = c.readBytes(&buf) catch return error.Incompatible; + inline for (e.field_names) |field| if (std.mem.eql(u8, name, field)) { + out.* = @field(T, field); + return; + }; + l.note("{s}: no {s} here", .{ l.field, name }); + return error.Incompatible; + }, + .int, .uint => if (e.mode == .nonexhaustive) { + const n: i64 = @bitCast(slot.value); + out.* = @fromBackingInt(@intCast(std.math.cast(e.tag_type, n) orelse return error.Incompatible)); + } else return error.Incompatible, + else => return error.Incompatible, + } + }, + .optional => { + const C = @typeInfo(T).optional.child; + if (slot.tag == .none) { + out.* = null; + return; + } + if (comptime kindOf(Canon(C)) == .skip) { + out.* = if (comptime C == std.mem.Allocator) l.gpa else null; + return; + } + // Through a local, as the byte loader does: a pointer's + // null is its address. + if (comptime @typeInfo(C) == .pointer) { + var payload: C = undefined; + try l.value(C, c, &payload); + out.* = payload; + return; + } + out.* = @as(C, undefined); + try l.fresh(C, &out.*.?); + l.value(C, c, &out.*.?) catch |err| { + out.* = null; + return err; + }; + }, + .one => { + const C = @typeInfo(T).pointer.child; + if (try l.again(slot)) |bytes| { + out.* = @ptrCast(@alignCast(bytes.ptr)); + return; + } + const one = try l.gpa.create(C); + const at = l.keep(std.mem.asBytes(one), .of(C), slot) catch |err| { + l.gpa.destroy(one); + return err; + }; + try l.fresh(C, one); + l.value(C, c, one) catch |err| { + // Left half made: no later value may be it. + l.made.items[at].dead = true; + return err; + }; + out.* = one; + }, + .slice => { + if (comptime @typeInfo(T).pointer.sentinel_ptr != null) @compileError("walk: a sentinel slice: " ++ @typeName(T)); + out.* = try l.slice(@typeInfo(T).pointer.child, c, slot); + }, + .array => try l.elements(@typeInfo(T).array.child, c, slot, out), + .prefix => unreachable, + .@"struct" => try l.fields(T, c, out, false), + .@"union" => { + const u = @typeInfo(T).@"union"; + const map = Mem.HashMap(.read_only).init(c) catch return error.Incompatible; + var it = map.iterator() catch return error.BadDump; + const kv_at = (it.next() catch return error.BadDump) orelse return error.Incompatible; + const kv = kv_at.readKeyValuePair() catch return error.BadDump; + var buf: [256]u8 = undefined; + const name = kv.key_cursor.readBytes(&buf) catch return error.Incompatible; + inline for (u.field_names, u.field_types) |field, F| if (std.mem.eql(u8, name, field)) { + out.* = @unionInit(T, field, undefined); + try l.fresh(F, &@field(out.*, field)); + return l.value(F, kv.value_cursor, &@field(out.*, field)); + }; + l.note("{s}: no {s} here", .{ l.field, name }); + return error.Incompatible; + }, + .err, .error_union => unreachable, + .custom => { + const got = c.readBytesObjectAlloc(l.own, null) catch return error.Incompatible; + defer l.own.free(got.value); + T.dumpRead(out, l.gpa, got.value) catch |err| { + if (err == error.OutOfMemory) return error.OutOfMemory; + l.note("{s}: {t}", .{ l.field, err }); + return error.Incompatible; + }; + if (comptime @hasDecl(T, "dumpFree")) try l.customs.append(l.own, .{ .ptr = out, .gpa = l.gpa, .free = @ptrCast(&T.dumpFree) }); + }, + .bitset => { + const got = c.readBytesObjectAlloc(l.own, null) catch return error.Incompatible; + defer l.own.free(got.value); + if (got.value.len < 8) return error.BadDump; + const bits = countOf(std.mem.bytesToValue(u64, got.value[0..8])) catch return error.BadDump; + const words = (bits + @bitSizeOf(usize) - 1) / @bitSizeOf(usize); + if (got.value.len != 8 + words * @sizeOf(usize)) return error.BadDump; + out.* = try .initEmpty(l.gpa, bits); + if (words > 0) @memcpy(std.mem.sliceAsBytes(out.masks[0..words]), got.value[8..]); + }, + } + } + + fn int(l: *Get, comptime I: type, c: Cursor, slot: xitdb.Slot) Error!I { + _ = l; + return switch (slot.tag) { + .uint => std.math.cast(I, slot.value) orelse error.Incompatible, + .int => std.math.cast(I, @as(i64, @bitCast(slot.value))) orelse error.Incompatible, + .bytes, .short_bytes => wide: { + var buf: [16]u8 = undefined; + const got = c.readBytesObject(&buf) catch return error.Incompatible; + if (got.value.len != 16 or !std.mem.eql(u8, &(got.format_tag orelse return error.Incompatible), &wide_tag)) return error.Incompatible; + break :wide std.math.cast(I, std.mem.bytesToValue(i128, got.value[0..16])) orelse error.Incompatible; + }, + else => error.Incompatible, + }; + } + + /// Numbers' `bytes` (format `tag`) as `E`s into `out`, as many as fit: + /// another width of the same kind (another build's) converted one by + /// one. How many the bytes hold. + fn convert(comptime E: type, bytes: []const u8, tag: [2]u8, out: []E) Error!usize { + const width: usize = if (tag[1] >= '1' and tag[1] <= '8') tag[1] - '0' else return error.BadDump; + if (bytes.len % width != 0) return error.BadDump; + const n = bytes.len / width; + const fits = @min(n, out.len); + if (std.mem.eql(u8, &tag, &numbersTag(E))) { + @memcpy(std.mem.sliceAsBytes(out[0..fits]), bytes[0 .. fits * width]); + return n; + } + if (tag[0] != numbersTag(E)[0]) return error.Incompatible; + for (out[0..fits], 0..) |*e, i| { + const raw = bytes[i * width ..][0..width]; + e.* = switch (@typeInfo(E)) { + .int => |info| if (info.signedness == .signed) cast: { + var wide: i64 = 0; + @memcpy(std.mem.asBytes(&wide)[0..width], raw); + if (width < 8) { + const shift: u6 = @intCast(64 - width * 8); + wide = (wide << shift) >> shift; + } + break :cast std.math.cast(E, wide) orelse return error.Incompatible; + } else cast: { + var wide: u64 = 0; + @memcpy(std.mem.asBytes(&wide)[0..width], raw); + break :cast std.math.cast(E, wide) orelse return error.Incompatible; + }, + .float => if (width == 8) @floatCast(std.mem.bytesToValue(f64, raw[0..8])) else if (width == 4) @floatCast(std.mem.bytesToValue(f32, raw[0..4])) else return error.Incompatible, + .bool => raw[0] != 0, + else => unreachable, + }; + } + return n; + } + + /// The numbers' bytes at `c` and their format tag, `alloc`'s. + fn numbersAt(c: Cursor, alloc: std.mem.Allocator) Error!struct { bytes: []u8, tag: [2]u8 } { + const got = c.readBytesObjectAlloc(alloc, null) catch |err| return if (err == error.OutOfMemory) error.OutOfMemory else error.Incompatible; + const bytes: []u8 = @constCast(got.value); + const tag = got.format_tag orelse { + alloc.free(bytes); + return error.Incompatible; + }; + return .{ .bytes = bytes, .tag = tag }; + } + + /// A slice of `E` at `c`: numbers' bytes, a blob's text by its hash, or + /// a list; one met again is the same. + fn slice(l: *Get, comptime E: type, c: Cursor, slot: xitdb.Slot) Error![]E { + if (try l.again(slot)) |bytes| return @as([*]E, @ptrCast(@alignCast(bytes.ptr)))[0 .. bytes.len / @max(1, @sizeOf(E))]; + if (comptime numbers(E)) { + switch (slot.tag) { + .bytes, .short_bytes => {}, + else => return error.Incompatible, + } + if (E == u8) if (try l.blob(c, slot)) |text| return text; + // A text, as it is written: its bytes are the slice. + if (E == u8) { + const got = try numbersAt(c, l.gpa); + if (!std.mem.eql(u8, &got.tag, &numbersTag(u8))) { + l.gpa.free(got.bytes); + return error.Incompatible; + } + if (got.bytes.len == 0) { + l.gpa.free(got.bytes); + return &.{}; + } + _ = l.keep(got.bytes, .@"1", slot) catch |err| { + l.gpa.free(got.bytes); + return err; + }; + return got.bytes; + } + const got = try numbersAt(c, l.own); + defer l.own.free(got.bytes); + const width: usize = if (got.tag[1] >= '1' and got.tag[1] <= '8') got.tag[1] - '0' else return error.BadDump; + const n = got.bytes.len / width; + if (n == 0) return &.{}; + const many = try l.gpa.alloc(E, n); + const at = l.keep(std.mem.sliceAsBytes(many), .of(E), slot) catch |err| { + l.gpa.free(many); + return err; + }; + _ = convert(E, got.bytes, got.tag, many) catch |err| { + l.made.items[at].dead = true; + return err; + }; + return many; + } + const list = Mem.ArrayList(.read_only).init(c) catch return error.Incompatible; + const n = countOf(list.count() catch return error.BadDump) catch return error.BadDump; + if (n == 0) return &.{}; + const many = try l.gpa.alloc(E, n); + const at = l.keep(std.mem.sliceAsBytes(many), .of(E), slot) catch |err| { + l.gpa.free(many); + return err; + }; + l.listInto(E, list, many) catch |err| { + l.made.items[at].dead = true; + return err; + }; + return many; + } + + /// A blob's text, when `c` holds a blob's hash: made in `gpa`'s. + fn blob(l: *Get, c: Cursor, slot: xitdb.Slot) Error!?[]u8 { + var buf: [32]u8 = undefined; + const got = c.readBytesObject(&buf) catch return null; + const tag = got.format_tag orelse return null; + if (!std.mem.eql(u8, &tag, &blob_tag) or got.value.len != 32) return null; + const texts = l.blobs orelse return error.BadDump; + const at = (texts.getCursor(std.mem.readInt(u256, got.value[0..32], .big)) catch return error.BadDump) orelse return error.BadDump; + const text = at.readBytesAlloc(l.gpa, null) catch |err| return if (err == error.OutOfMemory) error.OutOfMemory else error.BadDump; + const bytes: []u8 = @constCast(text); + _ = l.keep(bytes, .@"1", slot) catch |err| { + l.gpa.free(bytes); + return err; + }; + return bytes; + } + + /// An array of `E` at `c`: as many as it holds, the rest as they are. + fn elements(l: *Get, comptime E: type, c: Cursor, slot: xitdb.Slot, out: []E) Error!void { + if (comptime numbers(E)) { + switch (slot.tag) { + .bytes, .short_bytes => {}, + else => return error.Incompatible, + } + const got = try numbersAt(c, l.own); + defer l.own.free(got.bytes); + _ = try convert(E, got.bytes, got.tag, out); + return; + } + const list = Mem.ArrayList(.read_only).init(c) catch return error.Incompatible; + try l.listInto(E, list, out); + } + + /// The list's elements into `out`, as many as fit; an element of an + /// array of optional pointers (a session's panes) that cannot be read is + /// left out, not the array. + fn listInto(l: *Get, comptime E: type, list: Mem.ArrayList(.read_only), out: []E) Error!void { + const droppable = comptime @typeInfo(E) == .optional and @typeInfo(@typeInfo(E).optional.child) == .pointer; + var failed = false; + var it = list.iterator() catch return error.BadDump; + var i: usize = 0; + while (it.next() catch return error.BadDump) |at| : (i += 1) { + if (i >= out.len) break; + try l.fresh(E, &out[i]); + l.value(E, at, &out[i]) catch |err| { + if (err != error.Incompatible) return err; + if (droppable) { + out[i] = null; + l.note("{s}[{d}] left out", .{ l.field, i }); + } else failed = true; + }; + } + if (failed) return error.Incompatible; + } + + fn fields(l: *Get, comptime T: type, c: Cursor, out: *T, existing: bool) Error!void { + const names = comptime dumpFields(T); + const outer = l.field; + defer l.field = outer; + const map = Mem.HashMap(.read_only).init(c) catch return error.Incompatible; + var found: std.StaticBitSet(@max(1, names.len)) = .empty; + var failed = false; + var it = map.iterator() catch return error.BadDump; + while (it.next() catch return error.BadDump) |kv_at| { + const kv = kv_at.readKeyValuePair() catch return error.BadDump; + var buf: [256]u8 = undefined; + // A key that is no field's name of this build: passed over. + const name = kv.key_cursor.readBytes(&buf) catch continue; + const k: ?usize = inline for (names, 0..) |field, k| { + if (std.mem.eql(u8, name, field)) break k; + } else null; + const at = k orelse continue; + found.set(at); + inline for (names, 0..) |field, i| if (i == at) { + l.field = field; + l.oneField(T, field, kv.value_cursor, out, existing) catch |err| { + if (err != error.Incompatible) return err; + const attr = comptime @typeInfo(T).@"struct".field_attrs[std.meta.fieldIndex(T, field).?]; + if (comptime attr.default_value_ptr) |dp| { + @field(out, field) = @as(*const @FieldType(T, field), @ptrCast(@alignCast(dp))).*; + l.noteField("its kind changed; its default taken", @typeName(T), field); + } else if (existing) { + l.noteField("its kind changed; left as it was", @typeName(T), field); + } else failed = true; + }; + }; + } + // A field the writer did not have (or held null at a null default): + // its default (`fresh`), or the value cannot be made. + inline for (names, 0..) |field, i| if (!found.isSet(i)) { + const F = @FieldType(T, field); + const attr = comptime @typeInfo(T).@"struct".field_attrs[std.meta.fieldIndex(T, field).?]; + if (comptime attr.default_value_ptr == null and kindOf(Canon(F)) != .void) { + if (!existing) { + l.noteField("not in the dump", @typeName(T), field); + failed = true; + } + } else if (comptime @typeInfo(F) == .optional and defaultIsNull(T, field)) if (existing) { + // A null left out: null here too. + @field(out, field) = null; + }; + }; + if (failed) return error.Incompatible; + } + + fn oneField(l: *Get, comptime T: type, comptime field: []const u8, c: Cursor, out: *T, existing: bool) Error!void { + const F = @FieldType(T, field); + const packed_struct = comptime @typeInfo(T).@"struct".layout == .@"packed"; + const gpa = l.gpa; + defer l.gpa = gpa; + if (comptime allocOf(T, field)) |which| if (@field(l.allocs, which)) |a| { + l.gpa = a; + }; + // A field this build compiles out (a void field): passed over, + // said when it held something. + if (comptime kindOf(Canon(F)) == .void) { + if ((try slotOf(c)).tag != .none) l.note("{s}: not in this build", .{l.field}); + return; + } + if (comptime cutArray(T, field)) { + const slot = try slotOf(c); + return l.elements(@typeInfo(F).array.child, c, slot, &@field(out, field)); + } + // A struct held in place in one read as it stands (the root's): + // what it does not hold stays as it is too. + if (comptime kindOf(Canon(F)) == .@"struct" and Canon(F) == F and @typeInfo(F).@"struct".layout != .@"packed") if (existing) { + return l.fields(F, c, &@field(out, field), true); + }; + if (packed_struct) { + var copy: F = undefined; + try l.fresh(F, ©); + try l.value(F, c, ©); + @field(out, field) = copy; + return; + } + try l.fresh(F, &@field(out, field)); + try l.value(F, c, &@field(out, field)); + } +}; + +test "a value comes back from its bytes" { + const E = union(enum) { key: struct { cp: u21, text: []const u8 }, tick, failed: anyerror!u32 }; + var buf: [256]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + const values = [_]E{ .{ .key = .{ .cp = 'x', .text = "x" } }, .tick, .{ .failed = error.FileNotFound }, .{ .failed = 9 } }; + for (&values) |*v| try encode(E, v, &w); + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + var r: Reader = .{ .bytes = w.buffered() }; + for (&values) |*v| try std.testing.expectEqual(digest(E, v), digest(E, &try decode(E, &r, arena.allocator()))); + try std.testing.expectEqual(r.bytes.len, r.at); +} + +test "an error is taped by its name, which another build reads back as its own" { + // The build's number for an error is its own: 451 of 505 names were + // numbered otherwise in a Linux window's build than a terminal's, so a + // window replica read a terminal session's FileNotFound as another. + var buf: [64]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + const failed: error{ FileNotFound, NotDir }!u32 = error.NotDir; + try encode(@TypeOf(failed), &failed, &w); + try std.testing.expectEqualSlices(u8, "\x00\x06\x00NotDir", w.buffered()); + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + var r: Reader = .{ .bytes = w.buffered() }; + try std.testing.expectError(error.NotDir, try decode(@TypeOf(failed), &r, arena.allocator())); + // A name this build's set lacks (an OS's own): the tape is another + // build's, and the replay diverges rather than read some other error. + r = .{ .bytes = "\x00\x0c\x00FileTooLarge" }; + try std.testing.expectError(error.NoSuchError, decode(@TypeOf(failed), &r, arena.allocator())); + // An anyerror (a host's report) is read back as one of tape.Failure's. + const Report = struct { err: anyerror }; + w = .fixed(&buf); + try encode(Report, &.{ .err = error.FileNotFound }, &w); + r = .{ .bytes = w.buffered() }; + try std.testing.expectEqual(error.FileNotFound, (try decode(Report, &r, arena.allocator())).err); +} + +test "an enum is digested by its name, which another build may number otherwise" { + // registry.Builtin as a Linux build makes it (Tty9p in it) and as a + // FreeBSD one does: LocationsConfig is another number in each. + const Linux = enum { Look, Tty9p, LocationsConfig }; + const FreeBSD = enum { Look, LocationsConfig }; + const S = struct { from: Linux, also: [2]Linux }; + const T = struct { from: FreeBSD, also: [2]FreeBSD }; + try std.testing.expectEqual(digest(S, &.{ .from = .LocationsConfig, .also = .{ .Look, .LocationsConfig } }), digest(T, &.{ .from = .LocationsConfig, .also = .{ .Look, .LocationsConfig } })); + try std.testing.expect(digest(S, &.{ .from = .Look, .also = .{ .Look, .Look } }) != digest(S, &.{ .from = .Tty9p, .also = .{ .Look, .Look } })); +} + +test "a digest is of values: the same text at two addresses is one digest" { + const S = struct { name: []const u8, n: u32, next: ?*const u32 }; + const a = "same text"; + var b: [9]u8 = undefined; + @memcpy(&b, a); + const x: u32 = 7; + const y: u32 = 7; + try std.testing.expectEqual(digest(S, &.{ .name = a, .n = 1, .next = &x }), digest(S, &.{ .name = &b, .n = 1, .next = &y })); + try std.testing.expect(digest(S, &.{ .name = a, .n = 1, .next = &x }) != digest(S, &.{ .name = a, .n = 2, .next = &x })); +} + +test "an annotated field is in no digest, and a length cuts its array" { + const S = struct { + kept: u32, + cache: u32, + ring: [4]u8, + ring_len: u8, + pub const replica = .{ .derived = .{"cache"}, .len = .{.{ "ring", "ring_len" }} }; + }; + try std.testing.expectEqual( + digest(S, &.{ .kept = 1, .cache = 2, .ring = .{ 1, 2, 9, 9 }, .ring_len = 2 }), + digest(S, &.{ .kept = 1, .cache = 3, .ring = .{ 1, 2, 0, 0 }, .ring_len = 2 }), + ); +} + +test "an optional slice comes back, and the fields after it" { + const S = struct { before: u32 = 0, command: ?[]u8 = null, after: u32 = 0 }; + var text = "sleep 30".*; + const bytes = try save(S, std.testing.allocator, &.{ .before = 1, .command = &text, .after = 2 }); + defer std.testing.allocator.free(bytes); + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const back = try load(S, arena.allocator(), bytes, null); + try std.testing.expectEqualStrings("sleep 30", back.command.?); + try std.testing.expectEqual(2, back.after); +} + +test "a dump comes back whole: shared things shared, lists and runs as long as they were" { + const gpa = std.testing.allocator; + const Leaf = struct { n: u21, name: []const u8 }; + const Mode = enum { a, b, c }; + const S = struct { + mode: Mode = .a, + leaf: *Leaf, + same_leaf: *Leaf, + text: []u8, + same_text: []u8, + list: std.ArrayList(u16) = .empty, + maybe: ?Leaf = null, + either: union(enum) { none, some: u32, many: []const u16 } = .none, + ring: [4]u8 = @splat(0), + ring_len: u8 = 0, + room: []i32 = &.{}, + room_len: u8 = 0, + cache: u64 = 7, + alloc: std.mem.Allocator, + flags: packed struct { x: bool = false, y: u3 = 0 } = .{}, + pub const replica = .{ .derived = .{"cache"}, .len = .{ .{ "ring", "ring_len" }, .{ "room", "room_len" } } }; + }; + var leaf: Leaf = .{ .n = 0x1fffff, .name = "leaf" }; + var room = [_]i32{ 4, 5, -1, -1 }; + var text = "shared text".*; + var list: std.ArrayList(u16) = .empty; + defer list.deinit(gpa); + try list.appendSlice(gpa, &.{ 1, 2, 3 }); + const x: S = .{ .mode = .c, .leaf = &leaf, .same_leaf = &leaf, .text = &text, .same_text = &text, .list = list, .maybe = .{ .n = 3, .name = "maybe" }, .either = .{ .many = &.{ 9, 8 } }, .ring = .{ 5, 6, 0xAA, 0xAA }, .ring_len = 2, .room = &room, .room_len = 2, .cache = 99, .alloc = gpa, .flags = .{ .x = true, .y = 5 } }; + const bytes = try save(S, gpa, &x); + defer gpa.free(bytes); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const y = try load(S, arena.allocator(), bytes, null); + try std.testing.expectEqual(digest(S, &x), digest(S, &y)); + try std.testing.expect(y.leaf == y.same_leaf and y.text.ptr == y.same_text.ptr); + try std.testing.expectEqual(@as(u64, 7), y.cache); + try std.testing.expectEqualSlices(u16, &.{ 1, 2, 3 }, y.list.items); + try std.testing.expectEqual(true, y.flags.x); + // A slice its `len` cuts keeps its room. + try std.testing.expectEqual(@as(usize, 4), y.room.len); + try std.testing.expectEqualSlices(i32, &.{ 4, 5 }, y.room[0..2]); + // A fixpoint: what was read is written as it was. + const again = try save(S, gpa, &y); + defer gpa.free(again); + try std.testing.expectEqualSlices(u8, bytes, again); +} + +test "a dump crosses builds: a field added takes its default, one removed is passed over, one changed is left out" { + const gpa = std.testing.allocator; + const Old = struct { + const Color = enum { red, green, blue }; + const Pane = struct { name: []const u8, color: Color = .red, gone: u32 = 1, width: u16 = 0, kind: u32 = 0 }; + panes: [3]?*Pane = @splat(null), + count: u8 = 0, + renamed: u32 = 0, + }; + const New = struct { + // Values renumbered and one added before the others. + const Color = enum { cyan, blue, red, green }; + const Wide = struct { a: u8 }; + const Pane = struct { added: bool = true, color: Color = .cyan, width: u32 = 0, name: []const u8, kind: Wide = .{ .a = 4 } }; + // A pane's required field changed kind: that pane is left out. + const Strict = struct { name: u8 }; + panes: [4]?*Pane = @splat(null), + count: u16 = 0, + renamed_now: u32 = 5, + }; + var one: Old.Pane = .{ .name = "one", .color = .blue, .gone = 9, .width = 300, .kind = 2 }; + var two: Old.Pane = .{ .name = "two", .color = .green }; + const old: Old = .{ .panes = .{ &one, null, &two }, .count = 2, .renamed = 7 }; + const bytes = try save(Old, gpa, &old); + defer gpa.free(bytes); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + // The notes are made where the load's values are. + var notes: std.ArrayList(u8) = .empty; + const new = try load(New, arena.allocator(), bytes, ¬es); + try std.testing.expectEqual(@as(u16, 2), new.count); + try std.testing.expectEqual(@as(u32, 5), new.renamed_now); + const a = new.panes[0].?; + try std.testing.expectEqualStrings("one", a.name); + try std.testing.expectEqual(New.Color.blue, a.color); + try std.testing.expectEqual(@as(u32, 300), a.width); + try std.testing.expect(a.added); + try std.testing.expectEqual(@as(u8, 4), a.kind.a); + try std.testing.expect(new.panes[1] == null and new.panes[3] == null); + try std.testing.expectEqual(New.Color.green, new.panes[2].?.color); + try std.testing.expect(std.mem.indexOf(u8, notes.items, "kind") != null); + + const Strict = struct { + const Pane = struct { name: u8 }; + panes: [3]?*Pane = @splat(null), + count: u8 = 0, + }; + notes.clearRetainingCapacity(); + const strict = try load(Strict, arena.allocator(), bytes, ¬es); + try std.testing.expect(strict.panes[0] == null and strict.panes[2] == null); + try std.testing.expectEqual(@as(u8, 2), strict.count); + try std.testing.expect(std.mem.indexOf(u8, notes.items, "left out") != null); + + // And back: the newer build's dump read by the older one. + const newer = try save(New, gpa, &new); + defer gpa.free(newer); + const back = try load(Old, arena.allocator(), newer, null); + try std.testing.expectEqualStrings("two", back.panes[2].?.name); + try std.testing.expectEqual(@as(u32, 1), back.panes[0].?.gone); + try std.testing.expectEqual(Old.Color.blue, back.panes[0].?.color); +} + +test "a dump that is not one, or is cut short, is refused" { + const gpa = std.testing.allocator; + const S = struct { a: u32, b: []const u8 }; + try std.testing.expectError(error.BadDump, load(S, gpa, "not a dump", null)); + const bytes = try save(S, gpa, &.{ .a = 1, .b = "bee" }); + defer gpa.free(bytes); + // What it made before the end is freed again. + try std.testing.expectError(error.EndOfDump, load(S, gpa, bytes[0 .. bytes.len - 2], null)); +} + +test "a blob of 4 KiB and up is digested by its length, what it holds told by its keeper's revision; a smaller one by its bytes" { + const gpa = std.testing.allocator; + const File = struct { + pub const replica = .{ .blob = .{"content"} }; + content: []u8, + revision: u32 = 0, + }; + const text = try gpa.alloc(u8, 64 << 10); + defer gpa.free(text); + @memset(text, 'a'); + var f: File = .{ .content = text }; + const before = digest(File, &f); + // Written in place: the same digest, until its revision says so. + text[1000] = 'b'; + try std.testing.expectEqual(before, digest(File, &f)); + f.revision += 1; + try std.testing.expect(digest(File, &f) != before); + // Another length is another digest. + f.revision = 0; + f.content = text[0 .. text.len - 1]; + try std.testing.expect(digest(File, &f) != before); + // A small one by its bytes. + var small = "abc".*; + f.content = &small; + const was = digest(File, &f); + small[1] = 'x'; + try std.testing.expect(digest(File, &f) != was); +} + +test "a shape's numbers are written as {d} writes them" { + inline for (.{ 0, 7, 10, 65535, -1, -300, std.math.minInt(i128), std.math.maxInt(u128) }) |n| + try std.testing.expectEqualStrings(std.fmt.comptimePrint("{d}", .{n}), comptime decimal(n)); +} |
