const std = @import("std"); pub const layout = @import("layout.zig"); /// The core's step: `advance` runs a `.tick` a frame of this, and /// `nextWake` answers in whole frames of it. pub const frame_ms: u32 = 16; pub const frame_ns: u64 = frame_ms * std.time.ns_per_ms; pub const glide = @import("dev").glide; pub const FrameStats = @import("FrameStats.zig"); pub const modal = @import("modal.zig"); pub const look = @import("look.zig"); pub const Plumb = @import("Plumb.zig"); pub const filesystem = @import("fs.zig"); pub const ctlfs = @import("ninep/tree.zig"); pub const syntax = @import("syntax.zig"); pub const tracy = @import("tracy.zig"); pub const panes = @import("panes.zig"); const locations = @import("locations.zig"); pub const tagline = @import("tagline.zig"); /// A program's colours on a pane's body (a terminal's cells, its images). pub const ansi = @import("ansi.zig"); /// Predicted echo for a replica's terminal panes (`Pardes.echo`). pub const Echo = @import("echo.zig").Echo; pub const exec = @import("exec.zig"); const recent_files = @import("recent.zig"); const Store = @import("Store.zig"); pub const Db = @import("Db.zig"); pub const mouse = @import("mouse.zig"); pub const normal = @import("normal.zig"); pub const edit = @import("edit.zig"); pub const draw = @import("draw.zig"); pub const Messages = @import("Messages.zig"); pub const Registers = @import("Registers.zig"); pub const Macro = @import("Macro.zig"); pub const Editor = @import("Editor.zig"); pub const Pipe = @import("Pipe.zig"); pub const Stream = @import("Stream.zig"); pub const Handover = @import("Handover.zig"); pub const colors = @import("colors.zig"); pub const Theme = colors.Theme; pub const themes = colors.themes; pub const ChromeTheme = colors.ChromeTheme; /// The screen types live in surface.zig; every shell names them through here. pub const Color = @import("surface.zig").Color; pub const FontRole = @import("surface.zig").FontRole; pub const CellStyle = @import("surface.zig").CellStyle; pub const Cell = @import("surface.zig").Cell; pub const Placement = @import("surface.zig").Placement; pub const Raster = @import("surface.zig").Raster; pub const RectPx = @import("surface.zig").RectPx; pub const NativeGeometry = @import("surface.zig").NativeGeometry; pub const containGeometry = @import("surface.zig").containGeometry; pub const RectCell = @import("surface.zig").RectCell; pub const Surface = @import("surface.zig").Surface; pub const Facts = @import("surface.zig").Facts; pub const Region = @import("surface.zig").Region; pub const Chrome = @import("surface.zig").Chrome; pub const RailTick = @import("surface.zig").RailTick; pub const RailHeat = @import("surface.zig").Heat; pub const Lane = @import("surface.zig").Lane; pub const MAX_REGIONS = @import("surface.zig").MAX_REGIONS; /// What comes in (Event.zig). pub const Mouse = @import("Event.zig").Mouse; pub const Key = @import("Event.zig").Key; pub const hit = @import("Event.zig").hit; pub const sel_slot = @import("Event.zig").sel_slot; pub const CellPixels = @import("Event.zig").CellPixels; pub const Event = @import("Event.zig").Event; /// What goes out (Effect.zig). pub const PtySignal = @import("Effect.zig").PtySignal; pub const PtySize = @import("Effect.zig").PtySize; pub const WatchMode = @import("Effect.zig").WatchMode; pub const effect_path_cap = @import("Effect.zig").effect_path_cap; pub const effect_write_cap = @import("Effect.zig").effect_write_cap; pub const Effect = @import("Effect.zig").Effect; pub const builtins = @import("builtins.zig"); /// Every builtin as JSON, for the docs (tools/gen_builtins_json.zig). pub const builtins_json = @import("builtins_json.zig"); const limits = memory.limits; pub const selection_pipe = @import("selection_pipe.zig"); pub const config = @import("config.zig"); pub const memory = @import("memory.zig"); pub const tape = @import("tape.zig"); pub const walk = @import("walk.zig"); pub const wire = @import("wire"); pub const views = @import("views.zig"); pub const rollback = @import("rollback.zig"); pub const replica = @import("replica.zig"); pub const Kind = @import("Kind.zig"); /// The terminal, as the core calls it (core/term/ behind it). pub const Term = @import("Term.zig"); pub const keys = @import("keys.zig"); pub const Addon = @import("Addon.zig"); pub const dump = @import("dump.zig"); pub const lsp = @import("lsp/lsp.zig"); /// What the runtime's files name of the core beside the above (9p_io). pub const ctl = @import("ninep/ctl.zig"); pub const edit_cmd = @import("edit_cmd.zig"); pub const host_io = @import("dev").host_io; pub const file_watch = @import("dev").file_watch; pub const Host = host_io.Host; pub const frameMark = tracy.frameMark; /// The shell this build is for (build.zig's `-Dplatform`). pub const platform = @import("pardes_options").platform; pub const version = @import("build_info").version; pub const commit: ?[]const u8 = @import("build_info").commit; pub const font_picker = platform == .gui or platform == .macos; /// Whose turn it is with the core (Turn.zig): one per process, like the /// editor it belongs to. A process that never starts it -- a test -- has no /// second thread, and every yield is a no-op. pub var turn: Turn = .{}; pub const Turn = @import("Turn.zig"); pub const Jump = @import("Jump.zig"); const Loc = Jump.Loc; pub const can_attach = platform == .tui or platform == .gui; /// The machine's fonts: every desktop build's, which steps a window's Font /// as the window does (builtins.capabilities), and the Mac's. pub const fonts = if (builtins.capabilities.font_picker) @import("dev").fonts else struct {}; pub const Pane = panes.Pane; const Text = panes.Text; /// Pane slots, where a session keeps many files and terminals open. A slot /// costs its share of the fixed tables (MAX_PANES-sized arrays in the core /// and its surface) whether or not a pane is in it; a pane itself is /// allocated when it opens. pub const MAX_PANES = 64; pub const Layer = @import("Layer.zig"); pub const RowMetrics = Layer.Metrics; pub const TagHit = Layer.TagHit; pub const TagKind = Layer.Kind; /// A tag shows at most this many lines; past them it is cut, like a line /// too long for its width. pub const MAX_TAG_ROWS = 8; /// Panes, then columns, then the workspace bar, then each pane's notice /// bands: a band to a tag, however many lines it has. pub const MAX_TAG_LAYERS = MAX_PANES + MAX_COLS + 1 + MAX_PANES * Pane.Notices.max; pub const NOTICE_LAYER_BASE = MAX_PANES + MAX_COLS + 1; /// Columns a session holds (each costs about 8 KB of state, a column tag /// being most of it). pub const MAX_COLS = 16; const column_weight_unit = layout.column_weight_unit; pub const TOPBAR_H: u16 = 1; pub const COLBAR_H: u16 = 1; pub const BOX_H: u16 = 1; pub const TAG_TEXT_INSET: u16 = config.GUTTER; pub fn taglineOriginCol(p: *const Pardes, col: u16, row: u16) f32 { const v = p.view(); if (row < p.topBarHeight()) return 0; if (row < p.topBarHeight() + layout.columnBarHeight(p)) { for (v.col_x[0..p.view().ncol], v.col_w[0..p.view().ncol]) |x, w| if (col >= x and col - x < w) return @floatFromInt(x); } for (p.panes, 0..) |slot, id| { const pane = slot orelse continue; const r = v.rects[id]; const tag_y = p.tagTop(pane, r); if (row >= tag_y and row < tag_y + pane.tag_rows and col >= r.x and col < r.x + r.w) return @floatFromInt(r.x); } return @floatFromInt(col); } pub fn gridColAt(p: ?*const Pardes, x: f32, row: u16, body_w: f32, tagline_w: f32) u16 { const body = @max(body_w, 1); const tag = @max(tagline_w, 1); if (row < (if (p) |core| core.topBarHeight() else TOPBAR_H)) return colFromSpan(x, tag); if (p) |core| if (row < core.topBarHeight() + layout.columnBarHeight(core)) { for (core.view().col_x[0..core.view().ncol], core.view().col_w[0..core.view().ncol]) |origin, width| { if (width == 0) continue; const left = @as(f32, @floatFromInt(origin)) * body; const right = @as(f32, @floatFromInt(origin + width)) * body; if (x < left or x >= right) continue; return origin + @as(u16, @intFromFloat(@min( @floor(@max(0, x - left) / tag), @as(f32, @floatFromInt(width - 1)), ))); } }; if (p) |core| for (core.panes, 0..) |slot, id| { const pane = slot orelse continue; const r = core.view().rects[id]; const tag_y = core.tagTop(pane, r); if (row < tag_y or row >= tag_y + pane.tag_rows or r.w == 0) continue; const left = @as(f32, @floatFromInt(r.x)) * body; const right = @as(f32, @floatFromInt(r.x + r.w)) * body; if (x < left or x >= right) continue; const within: u16 = @intFromFloat(@min( @floor(@max(0, x - left) / tag), @as(f32, @floatFromInt(r.w - 1)), )); return r.x + within; }; return colFromSpan(x, body); } fn colFromSpan(x: f32, span: f32) u16 { return @intFromFloat(@min(@floor(@max(x, 0) / span), 10_000)); } pub const Builtin = builtins.registry.Builtin(); pub const test_api = if (@import("builtin").is_test) struct { pub fn runBuiltin( p: *Pardes, name: []const u8, id: usize, txt: []const u8, arg: ?[]const u8, ) bool { const command = std.meta.stringToEnum(Builtin, name) orelse return false; exec.runBuiltin(p, command, id, txt, arg); return true; } /// What the core wrote to pane `pane`'s pty (every pane's, for null) /// since the last drain, every effect taken off: as much as `buf` holds. pub fn ptyBytes(p: *Pardes, pane: ?u8, buf: []u8) []const u8 { var n: usize = 0; while (p.nextEffect()) |effect| switch (effect) { .write => |w| { if (pane != null and w.pane.index() != pane.?) continue; const b = w.bytes.slice(); if (n + b.len > buf.len) break; @memcpy(buf[n..][0..b.len], b); n += b.len; }, else => {}, }; return buf[0..n]; } } else struct {}; fn chordName(comptime c: config.Chord) []const u8 { comptime { const mods = (if (c.ctrl) "C-" else "") ++ (if (c.alt) "A-" else "") ++ (if (c.shift) "S-" else ""); for (@typeInfo(Key).@"struct".decl_names) |d| { if (@TypeOf(@field(Key, d)) != u21) continue; if (@field(Key, d) == c.cp) return mods ++ d; } if (c.cp < 0x20 or c.cp > 0x7e) @compileError("chord has no name for the index"); return mods ++ &[_]u8{@as(u8, @intCast(c.cp))}; } } fn shortcuts(comptime b: Builtin) []const u8 { comptime { @setEvalBranchQuota(20000); // each part after ", "; the first one's is cut off at the end var s: []const u8 = ""; if (b == .Window) s = s ++ ", " ++ chordName(config.window_prefix[0]); for (config.jump_keys) |jk| if (jk.cmd == b) { s = s ++ ", " ++ chordName(jk.chord); }; if (config.look_cmd == b) { for (config.look_key) |k| s = s ++ ", " ++ chordName(k); s = s ++ ", " ++ @tagName(config.look_button) ++ "-click"; } if (config.exec_cmd == b) { for (config.exec_key) |k| s = s ++ ", " ++ chordName(k); s = s ++ ", " ++ @tagName(config.exec_button) ++ "-click"; } var it = std.mem.tokenizeScalar(u8, config.topbar_str, ' '); while (it.next()) |w| if (std.mem.eql(u8, w, @tagName(b))) { s = s ++ ", topbar"; }; return if (s.len == 0) s else s[2..]; } } fn leaderKeys(comptime path: []const u8) []const u8 { comptime { var s: []const u8 = "SPC"; for (path) |c| s = s ++ " " ++ [_]u8{c}; return s; } } const Row = struct { path: ?[]const u8, cmd: Builtin, line: []const u8 }; pub const builtin_rows: [std.enums.values(Builtin).len]Row = blk: { // one pass per builtin per config table, and the insertion sort below is // O(n²) comptime branches on top of it @setEvalBranchQuota(200000); var rows: [std.enums.values(Builtin).len]Row = undefined; // the widest spaced-out path ("l D" = 3) and the widest name, so the three // columns line up var keyw: usize = 0; var namew: usize = 0; for (std.enums.values(Builtin)) |b| { if (config.leader_path.get(b)) |p| keyw = @max(keyw, 2 * p.len - 1); namew = @max(namew, @tagName(b).len); } for (std.enums.values(Builtin), 0..) |b, i| { const leader = if (config.leader_path.get(b)) |path| leaderKeys(path) else ""; const rest = shortcuts(b); const named = @tagName(b) ++ (if (rest.len == 0) "" else (&@as([namew - @tagName(b).len]u8, @splat(' '))) ++ " " ++ rest); rows[i] = .{ .path = config.leader_path.get(b), .cmd = b, .line = leader ++ (&@as([4 + keyw - leader.len]u8, @splat(' '))) ++ " " ++ named, }; } const last = "\x7f"; for (1..rows.len) |i| { var j = i; while (j > 0 and std.mem.lessThan(u8, rows[j].path orelse last, rows[j - 1].path orelse last)) : (j -= 1) { const t = rows[j]; rows[j] = rows[j - 1]; rows[j - 1] = t; } } break :blk rows; }; comptime { @setEvalBranchQuota(20000); // one branch per string byte, behind the decl walk that folds Builtin var it = std.mem.tokenizeScalar(u8, config.topbar_str, ' '); words: while (it.next()) |w| { for (@typeInfo(Builtin).@"enum".field_names) |name| if (std.mem.eql(u8, name, w)) continue :words; @compileError("topbar word is not a builtin: " ++ w); } } /// Said by a session's own frontend at its focus-in, when the build at the /// path it started from is not its own (upgrade.noticeNewer). pub const newer_build_words = "a newer pardes is installed: Upgrade (SPC s U) moves this session onto it"; pub const Rect = layout.Rect; pub const Pardes = @import("Core.zig"); pub const Options = Pardes.Options; pub const Boot = Pardes.Boot; pub const Haptic = Pardes.Haptic; test "a compact tagline anchors at its own pane, and both shells step from the same origin" { if (Term.ops == null) return error.SkipZigTest; // a shell const p = try Pardes.init(std.testing.allocator, .{ .cols = 120, .rows = 24 }); defer p.deinit(); _ = try p.newShell(1, ""); try std.testing.expect(layout.splitColumn(p, 0, 1, false)); p.sync(); // Two panes side by side put two tags on ONE row, which is the case a // per-row origin gets wrong and the reason this is asked per cell. const left = p.view().rects[0]; const right = p.view().rects[1]; try std.testing.expect(right.x > left.x); try std.testing.expectEqual(@as(f32, @floatFromInt(left.x)), taglineOriginCol(p, left.x + 3, left.y)); try std.testing.expectEqual(@as(f32, @floatFromInt(right.x)), taglineOriginCol(p, right.x + 3, right.y)); // The topbar's origin is column zero always — it is not a pane rect, which // is why row zero is right even in a window with no core to ask. try std.testing.expectEqual(@as(f32, 0), taglineOriginCol(p, 40, 0)); const body_row = left.y + 2; try std.testing.expectEqual(@as(f32, 7), taglineOriginCol(p, 7, body_row)); const body_w: f32 = 10; const tag_w: f32 = 8; for (p.view().col_x[0..p.view().ncol], p.view().col_w[0..p.view().ncol]) |origin, width| { if (width == 0) continue; const col = origin; try std.testing.expectEqual(@as(f32, @floatFromInt(origin)), taglineOriginCol(p, col, TOPBAR_H)); const glyph_x = @as(f32, @floatFromInt(origin)) * body_w; try std.testing.expectEqual(col, gridColAt(p, glyph_x + tag_w / 2, TOPBAR_H, body_w, tag_w)); } for ([_]u16{ 0, 1, 5, 40, 119 }) |col| { const origin = taglineOriginCol(p, col, left.y); const sdl = origin * (body_w - tag_w) + @as(f32, @floatFromInt(col)) * tag_w; const appkit = origin * body_w + (@as(f32, @floatFromInt(col)) - origin) * tag_w; try std.testing.expectEqual(sdl, appkit); } for ([_]u16{ 0, 1, 4, 9 }) |offset| { const col = left.x + offset; if (offset >= left.w) break; const origin = taglineOriginCol(p, col, left.y); const glyph_x = origin * body_w + (@as(f32, @floatFromInt(col)) - origin) * tag_w; try std.testing.expectEqual(col, gridColAt(p, glyph_x + tag_w / 2, left.y, body_w, tag_w)); } // The topbar's pointer grid is compact from column zero, with no pane to // anchor to — the one tag row that is right with or without a core. try std.testing.expectEqual(@as(u16, 3), gridColAt(p, 3.5 * tag_w, 0, body_w, tag_w)); try std.testing.expectEqual(@as(u16, 3), gridColAt(null, 3.5 * tag_w, 0, body_w, tag_w)); // A body row is untouched: still the body grid, still divided by the body // cell. Only tag rows compact. try std.testing.expectEqual(@as(u16, 3), gridColAt(p, 3.5 * body_w, body_row, body_w, tag_w)); } test { _ = @import("fuzz.zig"); _ = @import("Addon.zig"); _ = @import("rollback.zig"); _ = @import("Core.zig"); _ = @import("Plumb.zig"); _ = @import("lsp/Ask.zig"); _ = @import("Jump.zig"); _ = @import("keys.zig"); _ = @import("Effect.zig"); _ = @import("tape.zig"); _ = @import("replica.zig"); _ = Term; _ = @import("echo.zig"); _ = @import("ansi.zig"); _ = @import("modal.zig"); _ = @import("tagline.zig"); _ = @import("hunks.zig"); _ = @import("builtins_json.zig"); _ = @import("exec.zig"); _ = @import("look.zig"); _ = @import("sam_edit.zig"); _ = @import("edit_cmd.zig"); _ = @import("mouse.zig"); _ = @import("normal.zig"); _ = @import("regexp.zig"); _ = @import("edit.zig"); _ = @import("Messages.zig"); _ = @import("Registers.zig"); _ = @import("Macro.zig"); _ = @import("selection_pipe.zig"); _ = @import("Pipe.zig"); _ = @import("colors.zig"); _ = @import("surface.zig"); _ = @import("body_layer.zig"); _ = @import("draw.zig"); _ = @import("dump.zig"); // its tests ran nowhere before _ = @import("recent.zig"); _ = @import("Store.zig"); _ = @import("Db.zig"); _ = @import("Places.zig"); _ = @import("FrameStats.zig"); _ = @import("Query.zig"); _ = @import("Names.zig"); _ = @import("Stream.zig"); _ = @import("Tables.zig"); _ = @import("Handover.zig"); _ = @import("walk.zig"); _ = @import("views.zig"); _ = Turn; // A window's build links the window's C (font.c over FreeType and // HarfBuzz) into each of its programs, and their allocator (ui_malloc // and the rest) is gui.zig's. if (comptime @import("pardes_options").terminal and platform == .gui) _ = @import("dev").gui; } /// The container-level `var`s core/ may hold (at the top of a file, in a /// container, a function's struct's static), by file, each line's names /// with why none is a core's state. Nothing else of a core is a process /// global (docs: the reorganisation's R2): what a step reads lives in the /// core's memory, which the rollback copy saves and the digest covers. A /// `var` in a test block is the test's and needs no line. const allowed_vars = [_]struct { []const u8, []const u8, []const u8 }{ .{ "Addon.zig", "libs found found_words found_text found_file found_head nfound scanned heads nheads heads_changed", "the process's addon libraries and the start's scan of them" }, .{ "Addon.zig", "marked marked_len", "the crash mark set around a library's load" }, .{ "Kind.zig", "current", "the kind call in progress, put back at its end (threadlocal)" }, .{ "Kind.zig", "breach", "Debug: the first call over budget, for the addon test tool" }, .{ "Kind.zig", "drawer heap seed_base", "set once by the host at start" }, .{ "Kind.zig", "ready drawn", "this process's draws: those done, each keyed by its core, pane and serial, and the last token given, which no rollback takes back" }, .{ "Names.zig", "dp_rows dp_trace", "the scorer's scratch, written before it is read in one call" }, .{ "Turn.zig", "yield_depth", "this thread's nesting of yields (threadlocal)" }, .{ "Term.zig", "writes reloads", "this process's emulators' writes, read across one replay on its thread (the replica engine's one rule), and its reloads' count and time" }, .{ "c_heap.zig", "allocators allocators_len allocators_lock last", "the C heap's registry of allocators and its lookup's memo" }, .{ "c_heap.zig", "test_allocator stateless", "its tests'" }, .{ "config.zig", "other_build addon_sources", "the docs check's data, a test's" }, .{ "dump.zig", "terminal_gpa slim_terminals join_files", "a dump's or a load's mode, set and put back around it" }, .{ "dump.zig", "empty", "the empty undo a slim dump points a file at for one call" }, .{ "edit.zig", "drawing", "a frame is being drawn, set and put back around it" }, .{ "fs.zig", "last_reads last_read", "the host's last whole-file reads, read by its watch alone" }, .{ "memory.zig", "pardes_bits pardes_region frame_bits frame_region lsp_bits lsp_region tree_sitter_bits tree_sitter_region image_bits image_region addon_bits addon_region host_bits host_region lsp_query_buffer lsp_query_busy pins_lock pins pin_count put_off", "the process's memory regions themselves" }, .{ "replica.zig", "gpa", "zstd's allocator for its C heap, a test's to set" }, .{ "replica.zig", "live_peers", "the session's clients, for its panic handler" }, .{ "replica.zig", "core tasks", "a test host's" }, .{ "rollback.zig", "fill", "a test's fill byte for new allocations, set at start" }, .{ "root.zig", "turn", "the process's turn: the lock steps and 9P tasks take" }, .{ "sam_edit.zig", "opened", "a test fixture's" }, .{ "selection_pipe.zig", "lock procs len stopped next next_token", "the process's running pipes and their stop tokens (the session's alone)" }, .{ "syntax.zig", "specs diff_pieces diff_clock", "memos of pure functions: grammars made lazily, a hunk's styles by its bytes" }, .{ "syntax.zig", "syntax_allocator syntax_started", "tree-sitter's allocator, set once at start" }, .{ "syntax.zig", "handed handed_exts handed_n", "the languages an editor library's user hands in" }, .{ "syntax.zig", "held_trees", "the trees of the core being stepped, switched per step" }, .{ "tape.zig", "on", "the tape of the core being stepped, switched per step" }, .{ "tape.zig", "none", "the tape of a session nobody records: never written" }, .{ "walk.zig", "in_blob blobs_out", "a walk's context, set and put back (threadlocal)" }, .{ "walk.zig", "state bytes", "a type's table, made once" }, .{ "term/TerminalImages.zig", "started", "the PNG resize has its allocator, set at start" }, }; /// The container-level `var`s of a Zig source, each `name` and `line`: /// a comment, a string, a character and a `\\` line are not code, and a /// test block is skipped whole. const Var = struct { name: []const u8, line: usize }; fn containerVars(src: []const u8, gpa: std.mem.Allocator, out: *std.ArrayList(Var)) !void { // Each open brace's: a container's ('c'), a test's ('t'), a block's. var open: std.ArrayList(u8) = .empty; defer open.deinit(gpa); var tests: usize = 0; var line: usize = 1; var i: usize = 0; while (i < src.len) { const c = src[i]; if (c == '\n') line += 1; if ((c == '/' or c == '\\') and i + 1 < src.len and src[i + 1] == c) { i = std.mem.indexOfScalarPos(u8, src, i, '\n') orelse src.len; } else if (c == '"' or c == '\'') { i += 1; while (i < src.len and src[i] != c) : (i += 1) if (src[i] == '\\') { i += 1; }; i += 1; } else if (c == '{') { const kind = braceKind(src[0..i]); if (kind == 't') tests += 1; try open.append(gpa, kind); i += 1; } else if (c == '}') { if ((open.pop() orelse 0) == 't') tests -= 1; i += 1; } else if (std.ascii.isAlphabetic(c) or c == '_') { const end = wordEnd(src, i); if (tests == 0 and std.mem.eql(u8, src[i..end], "var") and (open.items.len == 0 or open.getLast() == 'c')) { var at = end; while (at < src.len and std.ascii.isWhitespace(src[at])) at += 1; try out.append(gpa, .{ .name = src[at..wordEnd(src, at)], .line = line }); } i = end; } else i += 1; } } fn wordEnd(src: []const u8, from: usize) usize { var i = from; while (i < src.len and (std.ascii.isAlphanumeric(src[i]) or src[i] == '_')) i += 1; return i; } /// What the brace after `before` opens: a container's body (`struct {`, /// `union(enum) {`, `enum(u8) {`), a test's (`test "name" {`, `test {`), /// or a block. fn braceKind(before: []const u8) u8 { var j = before.len; while (j > 0 and std.ascii.isWhitespace(before[j - 1])) j -= 1; if (j > 0 and before[j - 1] == ')') { var depth: usize = 0; while (j > 0) { j -= 1; if (before[j] == ')') depth += 1; if (before[j] == '(') depth -= 1; if (depth == 0) break; } while (j > 0 and std.ascii.isWhitespace(before[j - 1])) j -= 1; } else if (j > 0 and before[j - 1] == '"') { j -= 1; while (j > 0 and before[j - 1] != '"') j -= 1; if (j > 0) j -= 1; while (j > 0 and std.ascii.isWhitespace(before[j - 1])) j -= 1; } const end = j; while (j > 0 and (std.ascii.isAlphanumeric(before[j - 1]) or before[j - 1] == '_')) j -= 1; const word = before[j..end]; for ([_][]const u8{ "struct", "union", "enum", "opaque" }) |w| if (std.mem.eql(u8, word, w)) return 'c'; return if (std.mem.eql(u8, word, "test")) 't' else 'b'; } test "nothing of a core is a process global: every container-level var in core/ is one the list allows, with its reason" { const gpa = std.testing.allocator; const io = std.testing.io; var dir = try std.Io.Dir.cwd().openDir(io, "core", .{ .iterate = true }); defer dir.close(io); var walker = try dir.walk(gpa); defer walker.deinit(); var found: std.ArrayList(Var) = .empty; defer found.deinit(gpa); var files: usize = 0; var unlisted: usize = 0; while (try walker.next(io)) |e| { if (e.kind != .file or !std.mem.endsWith(u8, e.basename, ".zig")) continue; files += 1; const src = try e.dir.readFileAlloc(io, e.basename, gpa, .limited(16 << 20)); defer gpa.free(src); found.clearRetainingCapacity(); try containerVars(src, gpa, &found); for (found.items) |v| { var listed = false; for (allowed_vars) |a| if (std.mem.eql(u8, a[0], e.path)) { var names = std.mem.tokenizeScalar(u8, a[1], ' '); while (names.next()) |n| listed = listed or std.mem.eql(u8, n, v.name); }; if (listed) continue; std.debug.print("core/{s}:{d}: `var {s}` is a process global: the core's state goes in its memory (a field), or the var on root.zig's allowed_vars with why it is not a core's\n", .{ e.path, v.line, v.name }); unlisted += 1; } } try std.testing.expect(files > 100); try std.testing.expectEqual(@as(usize, 0), unlisted); } /// The lines of each file of core/ that name the machine outside a test: /// `std.c.`, `libc.`, `std.posix.`, `getenv`, std.Io's File, Dir, net and /// Threaded (a path's text, `Dir.path`, and `max_path_bytes` are none), /// `@import("dev")` and `@import("runtime")`, and the host's table /// (`host.vtable`, `host.ctx`: only the tape's own lines call the host, a /// call made past it is no call a replica replays), by file, how many and /// why. A step's read of its own machine with no tape diverges a far /// client, and the soak (one machine) never sees it: a new line here makes /// someone look. /// The count is a file's, so it cannot tell a step's read from its host /// half's; the reason says which the file's are. const machine_lines = [_]struct { []const u8, usize, []const u8 }{ .{ "Addon.zig", 54, "the process's addon libraries: the start's scan of their directories, dlopen, the crash mark (whose: the pid alive); the host's, never a step's" }, .{ "Core.zig", 5, "the session's directory read once at its start (taped), a frame log (PARDES_FRAMES), a host_io type" }, .{ "Db.zig", 18, "the state file every session of the user shares: the authority's (`db`), off in every replica" }, .{ "Dir.zig", 1, "a directory's listing, the function under tape.site(.dir_listing), its io the tape's" }, .{ "Effect.zig", 1, "host_io, named for the host entries it performs" }, .{ "FrameStats.zig", 7, "a frame's clock and log: frames are local, never digested" }, .{ "Handover.zig", 29, "a window carried to another process over a socket: the session's host" }, .{ "Kind.zig", 1, "host_io's KindJob: a kind's job is the host's" }, .{ "Messages.zig", 6, "the message clock, read through tape.value(.clock); PARDES_NOTIME, the tests', read by a host's `stamp` alone (between steps, or in a host's call), whose text the tape carries in the setMessage it makes: never a step's" }, .{ "Output.zig", 2, "the fonts module (Fonts lists them under tape.site(.fonts)) and the build's version line" }, .{ "Stream.zig", 14, "the disk search's worker: it runs off the step and its batches are inputs" }, .{ "builtins.zig", 2, "Mount's probe (tape.site(.probe)) and Term's shell check (tape.site(.shell))" }, .{ "config.zig", 6, "the default shell, read once at the start (taped); the config file read at startup and written by DumpConfig (the session's); the docs check's" }, .{ "draw.zig", 1, "PARDES_TEST_CLOCK: a frame's, not a step's" }, .{ "dump.zig", 4, "a dump's clock and the state file's directory (XDG, the process's directory): the session's side (a client's Restore waits)" }, .{ "echo.zig", 1, "PARDES_REPLICA_TRACE: a trace" }, .{ "edit_cmd.zig", 1, "Edit's pipe environment (host_io.commandEnv): kept in Pipe.edit_run, `.authority` state, read only by the host's `pipe`, which a client never calls" }, .{ "exec.zig", 3, "kindOf's stat (tape.site(.kind), its io the tape's) and Shell's check (tape.site(.shell))" }, .{ "fs.zig", 38, "the file system behind the tape's sites (open, read, write, stat, mkdir, access; their io the tape's), the process's home (read once at the start, taped), the 9P transport" }, .{ "hunks.zig", 1, "a test helper's file read" }, .{ "jj.zig", 11, "jj run under tape.site(.jj) on an io of its own (the tape's spawns nothing) with this process's environment, the signal mask cleared as Stream's children's: the session's, a replica replays its answer; or on a worker for `Changes`, its answer an input, with the wall clock it was made at (tape.value(.clock) on the loop) for its descriptions' ages; a test's shell inbox (dev)" }, .{ "look.zig", 6, "openLink's fork (the host's: a view's frontend opens a link) and a remote's error name" }, .{ "memory.zig", 7, "the memory regions themselves (mmap, madvise, their locks)" }, .{ "replica.zig", 89, "the client and session engines: sockets, threads, clocks, the blob cache, traces" }, .{ "rollback.zig", 1, "a test helper's directory" }, .{ "root.zig", 4, "dev's modules re-exported (host_io, file_watch, glide, fonts)" }, .{ "selection_pipe.zig", 14, "a pipe's child processes and their files: the host's `pipe` entry" }, .{ "tape.zig", 12, "the tape's own files and host_io's types: a recording, a replay; the `io` a tape hands a site's body; which host the core holds (noteHost), the one file that names the host's table" }, .{ "lsp/lsp.zig", 1, "the language server's client (dev): the host's `lsp` entry" }, .{ "ninep/ctl.zig", 1, "the session's pid in a 9P read: the session's server" }, .{ "ninep/events.zig", 2, "the 9P event log's clock: the session's server" }, .{ "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)" }, }; /// The lines of `src` that name the machine (`machine_lines`'s rules). fn machineLines(src: []const u8, gpa: std.mem.Allocator, out: *std.ArrayList(usize)) !void { const names = [_][]const u8{ "std.c.", "libc.", "std.posix.", "getenv", "std.Io.File", "std.Io.Dir", "std.Io.net", "std.Io.Threaded", "Io.File", "Io.Dir", "Io.net", "Io.Threaded", "host.vtable", "host.ctx" }; const pure = [_][]const u8{ "std.Io.Dir.path.", "Io.Dir.path.", "std.Io.Dir.max_path_bytes", "Io.Dir.max_path_bytes" }; var open: std.ArrayList(u8) = .empty; defer open.deinit(gpa); var tests: usize = 0; var line: usize = 1; var i: usize = 0; while (i < src.len) { const c = src[i]; if (c == '\n') line += 1; const at = src[i..]; if ((c == '/' or c == '\\') and i + 1 < src.len and src[i + 1] == c) { i = std.mem.indexOfScalarPos(u8, src, i, '\n') orelse src.len; } else if (c == '@' and tests == 0 and (std.mem.startsWith(u8, at, "@import(\"dev\")") or std.mem.startsWith(u8, at, "@import(\"runtime\")"))) { if (out.items.len == 0 or out.getLast() != line) try out.append(gpa, line); i += 1; } else if (c == '"' or c == '\'') { i += 1; while (i < src.len and src[i] != c) : (i += 1) if (src[i] == '\\') { i += 1; }; i += 1; } else if (c == '{') { const kind = braceKind(src[0..i]); if (kind == 't') tests += 1; try open.append(gpa, kind); i += 1; } else if (c == '}') { if ((open.pop() orelse 0) == 't') tests -= 1; i += 1; } else if (std.ascii.isAlphabetic(c) or c == '_') { const named = for (names) |n| { if (std.mem.startsWith(u8, at, n)) break true; } else false; const path = for (pure) |n| { if (std.mem.startsWith(u8, at, n)) break true; } else false; if (tests == 0 and named and !path and (out.items.len == 0 or out.getLast() != line)) try out.append(gpa, line); i = wordEnd(src, i); } else i += 1; } } test "what core/ asks of the machine is where the list says, with why: a new line naming libc, std.c, std.posix, getenv, a std.Io file, directory or socket, dev or runtime is named" { const gpa = std.testing.allocator; const io = std.testing.io; var dir = try std.Io.Dir.cwd().openDir(io, "core", .{ .iterate = true }); defer dir.close(io); var walker = try dir.walk(gpa); defer walker.deinit(); var found: std.ArrayList(usize) = .empty; defer found.deinit(gpa); var wrong: usize = 0; var seen: [machine_lines.len]bool = @splat(false); while (try walker.next(io)) |e| { if (e.kind != .file or !std.mem.endsWith(u8, e.basename, ".zig")) continue; const src = try e.dir.readFileAlloc(io, e.basename, gpa, .limited(16 << 20)); defer gpa.free(src); found.clearRetainingCapacity(); try machineLines(src, gpa, &found); const listed: usize = for (machine_lines, 0..) |m, k| { if (std.mem.eql(u8, m[0], e.path)) { seen[k] = true; break m[1]; } } else 0; if (found.items.len == listed) continue; wrong += 1; std.debug.print("core/{s}: {d} lines name the machine, root.zig's machine_lines says {d}:", .{ e.path, found.items.len, listed }); for (found.items) |l| std.debug.print(" {d}", .{l}); std.debug.print("\n a step that reads its own machine with no tape diverges a far client: tape the read (tape.site, tape.value), or count the line with why it is not a step's\n", .{}); } for (machine_lines, seen) |m, s| if (!s) { wrong += 1; std.debug.print("core/{s}: on machine_lines, and no such file\n", .{m[0]}); }; try std.testing.expectEqual(@as(usize, 0), wrong); } /// Every field kept out of the digest and the dump as a process's own /// (`.local`) or as made again from the rest (`.derived`): who writes it, /// and why what a step reads of it is what that step's own state makes, so /// a core that drew a frame and one that did not, or one joined since, step /// alike (a frame writes several; a step that read one a frame left as its /// state did not make it diverged a client: Pane.notices, then Tables' /// reading, 2026-11-19). A file, its names, the reason. const kept_out = [_]struct { []const u8, []const u8, []const u8 }{ .{ "Core.zig", "surface facts frames own_frames chrome frame_arena scratch echo undrawn", "the frame's own and the views drawn here: written by frames (and chrome by a theme's step), read by frames and the runner; no step reads them" }, .{ "Core.zig", "needs_frame", "whether to draw: steps set it, the loop reads it; no step's outcome reads it" }, .{ "Core.zig", "effects effects_head effects_len in_q in_head in_len opts dump_out dump_export tape", "this process's queues, options and tape, drained or set by its host" }, .{ "Core.zig", "shell_rows", "a terminal's rows as read here, swept at every update; the terminal's own digest covers its active area, not its history (Term.zig `calls`)" }, .{ "Core.zig", "diff_output locations_cache tty_filter_palette body_chrome", "caches of pure functions of their key (a text, a theme): a step finds what it would make; a query row's colours from them are out of its digest (locations.Row.digest), and what a step asks a worker to paint is never decided by them (Stream.paintRows)" }, .{ "Core.zig", "retired_panes", "panes torn down this step, freed at its end" }, .{ "Core.zig", "distrusted frames tape", "Options: the client's own list, its runner's statistics, its tape" }, .{ "Event.zig", "native_image_patches", "what this process's shell can take" }, .{ "panes.zig", "pv pv_known", "the views' shares as this process parks them (views.zig)" }, .{ "panes.zig", "wrap_line wrap_col wrap_pad wrap_n body_wrapped context_rows body_rows body_visible_rows context_row_limit geometry_key geometry_len", "File.geometry's, made by whoever asks first (a frame or a step) from everything its key hashes of the step's state; a tab change resets the key" }, .{ "panes.zig", "ghosts ghost_text", "the session's `Changes` answers' ghost rows (Pardes.changes, in the digest) as the geometry reads them: set by jj.showGhosts in each step while a view shows them and as an answer lands, which resets the geometry's key" }, .{ "panes.zig views.zig", "notices", "made again from the step's state at the top of update and presented, and at sync (Messages.collectNotices); a frame's are its own" }, .{ "panes.zig views.zig", "pan", "written by steps only (sync, a view unparked) from the pane and its terminal" }, .{ "File.zig", "cap line_starts line_cap", "the text's line index, of its bytes" }, .{ "File.zig", "highlights highlight_start syntax_dirty", "how a text looks, painted by frames: read by frames, and by a query's rows for colours only (out of their digest; what a step asks a worker to paint is never decided by them, Stream.paintRows)" }, .{ "File.zig", "allocator", "ContextCache's: what its declarations were made with, the parse's or a load's (a machine's handle, no state)" }, .{ "File.zig", "declarations", "ContextCache's: the text's at its revision (dumped, digested), parsed again from the text at a load" }, .{ "File.zig", "node_tree node_tree_revision node_tree_edits node_history", "the parse of the text at its revision, made by the first key that walks it" }, .{ "File.zig", "tables", "the whole text's, read at once by whoever asks first (Tables.ensure): no reading under way that a frame could move" }, .{ "Text.zig", "room", "a buffer's capacity" }, .{ "Kind.zig", "ops st gpa arena plain file opened reloads jobs record", "the kind's code and memory here: a plain kind's block is in the copy, and its state hash is checked at every call (Kind.Call.end)" }, .{ "Kind.zig", "thumb_at thumb_span pointer painted over used", "a frame's: written by a paint; `painted` is read by a tick of a kind that is not plain, whose calls are the authority's alone" }, .{ "Places.zig", "ticks ticks_gen re", "the rail's ticks, made again when the places move (`gen`), and the compiled pattern, of the pattern" }, .{ "Plumb.zig", "parsed parsed_arena", "the rules parsed, of their text" }, .{ "Stream.zig", "parse_ns paint paint_retired paint_count ahead ahead_for painted_ahead painted_on_loop ahead_seen ahead_ask", "the workers' paints and timings: how a text looks, and numbers" }, .{ "walk.zig", "cache", "a test's own type" }, }; test "every field kept out of the digest and the dump is one the list names, with who writes it and why a step's read of it is the step's" { const gpa = std.testing.allocator; const io = std.testing.io; var dir = try std.Io.Dir.cwd().openDir(io, "core", .{ .iterate = true }); defer dir.close(io); var walker = try dir.walk(gpa); defer walker.deinit(); var unlisted: usize = 0; var seen: usize = 0; while (try walker.next(io)) |e| { if (e.kind != .file or !std.mem.endsWith(u8, e.basename, ".zig")) continue; const src = try e.dir.readFileAlloc(io, e.basename, gpa, .limited(16 << 20)); defer gpa.free(src); for ([_][]const u8{ ".local = .{", ".derived = .{" }) |head| { var at: usize = 0; while (std.mem.indexOfPos(u8, src, at, head)) |start| { const end = std.mem.indexOfScalarPos(u8, src, start, '}') orelse break; at = end; // Not in a comment or a string (walk.zig's example, this test). const before = src[(std.mem.lastIndexOfScalar(u8, src[0..start], '\n') orelse 0)..start]; if (std.mem.indexOf(u8, before, "//") != null or std.mem.indexOfScalar(u8, before, '"') != null) continue; var lines = std.mem.splitScalar(u8, src[start + head.len .. end], '\n'); while (lines.next()) |whole| { const line = whole[0 .. std.mem.indexOf(u8, whole, "//") orelse whole.len]; var quoted = std.mem.splitScalar(u8, line, '"'); _ = quoted.next(); while (quoted.next()) |name| { _ = quoted.next(); seen += 1; const listed = listed: for (kept_out) |k| { var files = std.mem.tokenizeScalar(u8, k[0], ' '); const here = while (files.next()) |f| { if (std.mem.eql(u8, f, e.path)) break true; } else false; if (!here) continue; var names = std.mem.tokenizeScalar(u8, k[1], ' '); while (names.next()) |n| if (std.mem.eql(u8, n, name)) break :listed true; } else false; if (listed) continue; std.debug.print("core/{s}: `{s}` is kept out of the digest and the dump: on root.zig's kept_out, with who writes it and why a step reads only what its own state makes\n", .{ e.path, name }); unlisted += 1; } } } } } try std.testing.expect(seen > 60); try std.testing.expectEqual(@as(usize, 0), unlisted); }