diff options
Diffstat (limited to 'core')
| -rw-r--r-- | core/CHANGELOG.md | 23 | ||||
| -rw-r--r-- | core/Core.zig | 55 | ||||
| -rw-r--r-- | core/Dir.zig | 2 | ||||
| -rw-r--r-- | core/Effect.zig | 62 | ||||
| -rw-r--r-- | core/File.zig | 17 | ||||
| -rw-r--r-- | core/Output.zig | 2 | ||||
| -rw-r--r-- | core/Plumb.zig | 2 | ||||
| -rw-r--r-- | core/Query.zig | 7 | ||||
| -rw-r--r-- | core/Stream.zig | 26 | ||||
| -rw-r--r-- | core/body_layer.zig | 5 | ||||
| -rw-r--r-- | core/builtins.zig | 10 | ||||
| -rw-r--r-- | core/config.zig | 2 | ||||
| -rw-r--r-- | core/draw.zig | 1 | ||||
| -rw-r--r-- | core/dump.zig | 7 | ||||
| -rw-r--r-- | core/edit_cmd.zig | 4 | ||||
| -rw-r--r-- | core/exec.zig | 10 | ||||
| -rw-r--r-- | core/fs.zig | 15 | ||||
| -rw-r--r-- | core/grammar_manifest.zig | 4 | ||||
| -rw-r--r-- | core/keys.zig | 3 | ||||
| -rw-r--r-- | core/lib_syntax.zig | 4 | ||||
| -rw-r--r-- | core/look.zig | 16 | ||||
| -rw-r--r-- | core/mouse.zig | 1 | ||||
| -rw-r--r-- | core/ninep/pty.zig | 16 | ||||
| -rw-r--r-- | core/ninep/tree.zig | 15 | ||||
| -rw-r--r-- | core/panes.zig | 24 | ||||
| -rw-r--r-- | core/replica.zig | 422 | ||||
| -rw-r--r-- | core/root.zig | 19 | ||||
| -rw-r--r-- | core/syntax.zig | 113 | ||||
| -rw-r--r-- | core/tape.zig | 251 |
29 files changed, 746 insertions, 392 deletions
diff --git a/core/CHANGELOG.md b/core/CHANGELOG.md index fe9adec8..faa02ade 100644 --- a/core/CHANGELOG.md +++ b/core/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +- `pardes new --detach[=NAME]` returns once the session runs (registered + and listening), printing its name, exit 0; the session runs on in a + session of its own. `pardes --detach=NAME` without `new` is still the + session itself, until it ends. - `pardes attach NAME` (and `pardes-gui attach NAME`) is always a client: a process of its own with its own view, whatever the session was started in. A session's own terminal or window is only the one it was @@ -9,8 +13,9 @@ back. Before, an attach to a detached terminal's session handed it this terminal (the attach waiting as its stub), and `pardes-gui attach` asked a detached window's session to open its own window again and exited 0. - A client's Detach ends it with "'NAME' let this client go" and exit 1, - where the stub said "detached from 'NAME'" and exited 0. Bare, `pardes + A client's Detach ends it with "detached from 'NAME', which is still + running" and exit 0, as the stub's did (the session's last word on a + link, `left`); a session's end, with its code (`ended`). Bare, `pardes attach` takes the one detached session, else the one session, of either kind; with several it names them all. @@ -232,9 +237,9 @@ grammars, highlighting, declarations, syntax tree and themes as the editor has them, for a program that draws source text itself. Every dependency but tree-sitter's runtime is lazy in the manifest, so such a - package fetches the runtime and the grammars of its `tree-sitter` set + package fetches the runtime and the grammars of its `grammars` set and nothing else; `zig build lib-test`, which `unit-test` runs, builds - one (`test/lib`). The markdown grammar is pinned by its commit: its + one (`test/consumer`). The markdown grammar is pinned by its commit: its branch has moved, and a fresh checkout could not fetch it. - Enter, `o` and `O` give the new line helix's indent where the file's @@ -590,6 +595,16 @@ - A scroll in the window never moves the tree-sitter context rows: the body glides under them. +- `zig build run-isolated` and its `pardes-isolate` are gone: the + terminal's pardes with no host but the terminal and no filesystem had + not compiled for some releases, and nothing ran it. So is + `-Dtree-sitter=disabled`, a pardes with no tree-sitter, which did not + compile either; every build has tree-sitter's runtime. The grammar set + is `-Dgrammars` (`.grammars` for a package that depends on pardes, no + longer `.@"tree-sitter"`): `none`, the runtime alone, where a program + hands in a grammar of its own at run time, `minimal` or `full`; the + `zig` set, which `none` replaces, is gone. + ## 0.24 - Edit runs all of acme's commands: `< | >` through your Shell (one undo diff --git a/core/Core.zig b/core/Core.zig index 9a542940..7ebcc020 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -1324,18 +1324,15 @@ fn nextQueued(p: *Pardes) ?Event { } pub fn hostForegroundName(p: *const Pardes, id: usize, buf: []u8) ?[]const u8 { - const f = p.host.vtable.fg_name orelse return null; - return f(p.host.ctx, .at(id), buf); + return p.tape.host(p, .fg_name, .{ .at(id), buf }) orelse null; } pub fn hostTtyTaken(p: *const Pardes, id: usize) bool { - const f = p.host.vtable.tty_taken orelse return false; - return f(p.host.ctx, .at(id)); + return p.tape.host(p, .tty_taken, .{.at(id)}) orelse false; } pub fn hostKillJob(p: *const Pardes, id: usize) bool { - const f = p.host.vtable.kill_job orelse return false; - return f(p.host.ctx, .at(id)); + return p.tape.host(p, .kill_job, .{.at(id)}) orelse false; } /// A terminal whose shell could not be started: said, and a run waiting @@ -1471,25 +1468,22 @@ pub fn animationActive(p: *const Pardes) bool { } pub fn pump(p: *Pardes, host: Host) !void { - // By hand, not `taped`: the host is set before the enter, which wraps it, and is no input. + // By hand, not `taped`: the host is set before the enter, which says which functions it has if it is another, and is no input. p.host = host; const taped = pardes.tape.enter(p, .pump); defer pardes.tape.leave(p, taped); - // The host as the tape sees it, while it records. - const h = p.host; - const v = h.vtable; - if (v.wait_input) |f| { + if (p.tape.has(p, .wait_input)) { // Asleep until input or until the core's next deadline // (nextWake); 0 is no timeout at all. // The clock read whether or not it is wanted: what a replica // waits on is its own (a picture decoding wakes only a frame // that draws it), and the tape has the same calls either way. - const now = if (v.now) |clock| clock(h.ctx) else p.clock.now_ns; + const now = p.tape.host(p, .now, .{}) orelse p.clock.now_ns; const timeout: u32 = if (p.nextWake()) |due| wake: { const ms = ((due -| now) + std.time.ns_per_ms - 1) / std.time.ns_per_ms; break :wake @intCast(std.math.clamp(ms, 1, std.math.maxInt(u32))); } else 0; - f(h.ctx, timeout); + _ = p.tape.host(p, .wait_input, .{timeout}); } // Detached, nobody's key dismisses a message: they go on the clock, // here in the step, where the clock read is taped (the host's wait @@ -1497,46 +1491,54 @@ pub fn pump(p: *Pardes, host: Host) !void { // go). Messages.expireUnattended(p); p.frames.mark_start = FrameStats.nowNs(); - if (v.now) |clock| p.advance(clock(h.ctx)); + if (p.tape.host(p, .now, .{})) |now| p.advance(now); p.settle(); // A quitting frame has already freed what it would draw. if (p.quit) return; - if (v.poll_frame) |f| f(h.ctx); + _ = p.tape.host(p, .poll_frame, .{}); // Nothing to draw: do not spend a frame, and above all do not block on // the display for one. This is what keeps the frame rate governing // rendering and nothing else. // A shell with a clock draws what `advance` stepped; one without // steps its own `.tick`s and draws while a deadline is due. - if (!p.needs_frame and (v.now != null or !p.animationActive())) return p.frames.idle(); + if (!p.needs_frame and (p.tape.has(p, .now) or !p.animationActive())) return p.frames.idle(); // No one to see it: the frame stays owed (needs_frame), not drawn. // A pty streaming into an unwatched session spent most of its time // drawing what nobody looked at. - if (v.watched) |f| if (!f(h.ctx)) return; + if (!(p.tape.host(p, .watched, .{}) orelse true)) return; // The one view this process shows (a replica client's is its own // process's to draw), drawn as it is if another's is live. // Not shown by the frontend (Host.present): owed. var skipped = false; const shown = Views.shown(p); if (shown != p.live) { - if (shown) |k| skipped = !try Views.drawOne(p, k, .{ .ctx = h.ctx, .f = v.present }); + if (shown) |k| skipped = !try Views.drawOne(p, k, .{ .ctx = p, .f = presentTaped }); } else { _ = p.frame_arena.reset(.{ .retain_with_limit = memory.limits.frame_kept }); p.frames.mark_update = FrameStats.nowNs(); p.frames.view = if (p.panes[p.view().active]) |pane| pane.scroll() else 0; const surface = try p.render(p.frame_arena.allocator()); p.frames.mark_render = FrameStats.nowNs(); - if (v.present) |f| skipped = !f(h.ctx, surface); + skipped = !(p.tape.host(p, .present, .{surface}) orelse true); Stream.askAhead(p); } // Settled before post_present: a shell ticks there, and what that // tick moves owes the next frame. p.needs_frame = skipped; - if (v.post_present) |f| f(h.ctx); + _ = p.tape.host(p, .post_present, .{}); // Still moving: the next frame is owed a period from now. const owed = if (p.nextWake()) |due| due <= p.clock.stepped_ns + frame_ns else false; p.frames.record(FrameStats.nowNs(), owed, skipped); } +/// The pump's other view presented as its own is, through the tape: +/// `present` stays inside `views.within`, whose live view the host's +/// `presented` reads. +fn presentTaped(ctx: ?*anyopaque, surface: *const pardes.Surface) bool { + const p: *Pardes = @ptrCast(@alignCast(ctx.?)); + return p.tape.host(p, .present, .{surface}) orelse true; +} + /// What a pump does between its wait and its frame: the queued inputs /// and the effects. Also the session at a step boundary, taken now (an /// Upgrade's dump, upgrade.zig). @@ -2073,7 +2075,7 @@ pub fn nextWake(p: *const Pardes) ?u64 { }; // Del's question goes up at the end of its delay: a frame then, and // none after (stepped time has reached it). - for (p.panes) |slot| if (slot) |pane| if (pane.prompt == .del_side and pane.question_due_ns > p.clock.stepped_ns) { + for (p.panes) |slot| if (slot) |pane| if (pane.prompt == .del_side and pane.question_due_ns > p.clock.stepped_ns and pane.question_due_ns != Pane.question_asked) { const wait = @max(1, (pane.question_due_ns - p.clock.stepped_ns + frame_ns - 1) / frame_ns); frames = if (frames) |soonest| @min(soonest, wait) else wait; }; @@ -2114,6 +2116,10 @@ fn advanceInner(p: *Pardes, now_ns: u64) void { p.clock.started = true; p.clock.now_ns = now_ns; if (!started) p.clock.stepped_ns = now_ns; + // Del's question asked since the last advance: its delay from now. + for (p.panes) |slot| if (slot) |pane| if (pane.question_due_ns == Pane.question_asked) { + pane.question_due_ns = now_ns + config.del_question_delay_ns; + }; const frame = frame_ns; var moving: u32 = 0; // The session's ticks are the recording session's: a picture still @@ -2273,6 +2279,11 @@ pub const Options = struct { startup_config: ?[]const u8 = null, ninep_name: []const u8 = "", ninep_tcp: ?[]const u8 = null, + /// This process's end of a socket pair its launch made (runtime/main.zig, + /// PARDES_PAIR): a session's first client is on it, taken before its + /// first effects (runtime/session.zig); a client's session is on it, + /// its first join made there with no hello (replica.join). + pair: ?c_int = null, mounts: []const filesystem.Mount = &.{}, config_dir: ?[]const u8 = null, /// Where what outlives the session is kept (Db.zig): the user's state @@ -2502,7 +2513,6 @@ test "LocationsConfig command reports partial updates and survives restore" { } test "TreeContext rows in the tag style keep the message rows" { - if (comptime !syntax.enabled) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 60, .rows = 16 }); defer p.deinit(); const pane = try p.setTestFile("pub const Box = struct {\n pub fn run() void {\n" ++ (std.mem.asBytes(&@as([30][16]u8, @splat(" // body\n".*)))) ++ " }\n};\n"); @@ -2545,7 +2555,6 @@ test "TreeContext rows in the tag style keep the message rows" { } test "TreeContext command and custom tag survive a workspace round trip" { - if (comptime !syntax.enabled) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); const pane = try p.setTestFile("pub fn main() void {}\n"); diff --git a/core/Dir.zig b/core/Dir.zig index 29c5cdc8..869a7cd5 100644 --- a/core/Dir.zig +++ b/core/Dir.zig @@ -47,7 +47,6 @@ pub fn ofName(name: []const u8) []const u8 { /// dotfiles too; a directory's, a link to one's too, ending in `/`; sorted /// bytewise, the `/` counted; each ending in a newline. pub fn read(tape: *pardes.tape.Tape, gpa: std.mem.Allocator, dir: []const u8) ![]u8 { - if (comptime !filesystem.platform_has_fs) return error.FileNotFound; const local = filesystem.localPath(dir) orelse return error.NotLocal; // Its own copy: the caller's may be a pane's, gone while the turn is out. var own: [4096]u8 = undefined; @@ -294,7 +293,6 @@ test "a wide character counts its cells, not its bytes" { } test "a directory reads as acme lists it: dotfiles kept, . and .. not, directories and links to them marked, sorted bytewise" { - if (comptime !filesystem.platform_has_fs) return; var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); const io = testing.io; diff --git a/core/Effect.zig b/core/Effect.zig index 5e821065..cabfe8ea 100644 --- a/core/Effect.zig +++ b/core/Effect.zig @@ -116,34 +116,33 @@ pub const perform = tape.taped(performInner); fn performInner(p: *Pardes, e: Effect) void { // A Save performed on one twin is every twin's (File.syncTwins). defer panes.File.syncTwins(p); - const v = p.host.vtable; switch (e) { // The host reads the pane (its command, its shell) as it forks, // so the slot must still hold the pane the spawn was for. - .spawn => |s| if (if (p.panes[s.pane.index()]) |pane| pane.serial != s.serial else true) {} else if (v.spawn) |f| f(p.host.ctx, s.pane, if (s.cwd.len == 0) (p.spawn_dirs[s.pane.index()] orelse "") else s.cwd.slice()) else { + .spawn => |s| if (if (p.panes[s.pane.index()]) |pane| pane.serial != s.serial else true) {} else p.tape.host(p, .spawn, .{ s.pane, if (s.cwd.len == 0) (p.spawn_dirs[s.pane.index()] orelse "") else s.cwd.slice() }) orelse { p.fallback.spawned[s.pane.index()] = true; }, // A pane with no child is silent: nothing invents output on its // screen, and the bytes are dropped rather than transcribed. - .write => |w| if (v.pty_write) |f| f(p.host.ctx, w.pane, w.bytes.slice()), - .resize_pty => |r| if (v.pty_resize) |f| f(p.host.ctx, r.pane, r.cols, r.rows), + .write => |w| _ = p.tape.host(p, .pty_write, .{ w.pane, w.bytes.slice() }), + .resize_pty => |r| _ = p.tape.host(p, .pty_resize, .{ r.pane, r.cols, r.rows }), // A signal for a pane that closed, its slot retaken in the same // step, would reach another pane's child. - .signal_pty => |s| if (if (p.panes[s.pane.index()]) |pane| pane.serial != s.serial else true) {} else if (v.pty_signal) |f| f(p.host.ctx, s.pane, s.sig), - .close_pty => |c| if (v.close_pty) |f| f(p.host.ctx, c.pane), + .signal_pty => |s| if (if (p.panes[s.pane.index()]) |pane| pane.serial != s.serial else true) {} else p.tape.host(p, .pty_signal, .{ s.pane, s.sig }) orelse {}, + .close_pty => |c| _ = p.tape.host(p, .close_pty, .{c.pane}), // The view's frontend opens it, yanks and pastes, on its own // machine (View.yanks); the host here only for a view no client // draws (tape.hostCall). .open_link => |u| { p.view().links +%= 1; p.view().link = u; - if (v.open_link) |f| f(p.host.ctx, u.slice()) else p.fallback.setLink(u.slice()); + p.tape.host(p, .open_link, .{u.slice()}) orelse p.fallback.setLink(u.slice()); }, // Plan 9's plumber's, detached (host_io.startDetached); in-process // (a test), kept to look at. .start => |st| { var why_buf: [64]u8 = undefined; - const why = if (v.start) |f| f(p.host.ctx, st.line.slice(), &why_buf) else p.fallback.start(st.line.slice()); + const why = p.tape.host(p, .start, .{ st.line.slice(), &why_buf }) orelse p.fallback.start(st.line.slice()); const w = why orelse return; var words = std.mem.splitScalar(u8, st.line.slice(), 0); _ = words.next(); // its directory @@ -191,37 +190,31 @@ fn performInner(p: *Pardes, e: Effect) void { }, .write_dump => { const out = p.dump_out orelse return; - if (v.write_dump) |f| { - f(p.host.ctx, out); - } else { + p.tape.host(p, .write_dump, .{out}) orelse { _ = p.fallback.writeFile(host_io.Fallback.dump_path, out); p.setLastDump(host_io.Fallback.dump_path); - } + }; }, .set_clipboard => { p.view().yanks +%= 1; const text = p.registers.text(p.gpa, '+') orelse ""; - if (v.set_clipboard) |f| f(p.host.ctx, text) else p.fallback.setClipboard(text); + p.tape.host(p, .set_clipboard, .{text}) orelse p.fallback.setClipboard(text); }, // No desktop to ask: answer from the in-process clipboard at once, // which is the same shape as a host answering later. .read_clipboard => { p.view().pastes +%= 1; - if (v.read_clipboard) |f| f(p.host.ctx) else p.update(.{ .paste = p.fallback.clipboard.items }); + p.tape.host(p, .read_clipboard, .{}) orelse p.update(.{ .paste = p.fallback.clipboard.items }); }, - .lsp => |q| if (v.lsp) |f| - f(p.host.ctx, .{ .id = q.id, .kind = q.kind, .pane = q.pane, .offset = q.offset, .arg = q.arg.slice() }) - else + .lsp => |q| p.tape.host(p, .lsp, .{.{ .id = q.id, .kind = q.kind, .pane = q.pane, .offset = q.offset, .arg = q.arg.slice() }}) orelse p.update(.{ .lsp_resp = .{ .id = q.id, .rows = "" } }), - .pipe => |q| if (v.pipe) |f| - f(p.host.ctx, q.id) - else + .pipe => |q| p.tape.host(p, .pipe, .{q.id}) orelse p.update(.{ .pipe_resp = .{ .id = q.id, .success = false, .outputs = &.{} } }), // No workers here (a test, a board): it runs on the loop. - .search => |q| if (v.search) |f| f(p.host.ctx, q.gen) else Stream.runHere(p, q.gen, false), + .search => |q| p.tape.host(p, .search, .{q.gen}) orelse Stream.runHere(p, q.gen, false), // No windows here (a test, the tty): it stays. - .hand_over => |h| if (v.hand_over) |f| { - if (p.handover.bytes) |bytes| f(p.host.ctx, h.seq, bytes); + .hand_over => |h| if (p.tape.has(p, .hand_over)) { + if (p.handover.bytes) |bytes| _ = p.tape.host(p, .hand_over, .{ h.seq, bytes }); } else p.update(.{ .handed = .{ .seq = h.seq, .failure = "no other windows here" } }), .edit_write => { // Each write takes the bytes `w` took when it ran: the text @@ -247,24 +240,21 @@ fn performInner(p: *Pardes, e: Effect) void { } else ctlfs.events.noteLogAs(p, .save, pane, w.path); } }, - .watch => |w| if (v.watch_file) |f| { + .watch => |w| { // What a watch is about: a real file, or a kind's (a PDF's). const path: []const u8 = if (p.panes[w.pane.index()]) |pane| (if (pane.file) |file| (if (file.output == null) file.path else "") else if (pane.addon) |k| k.path else "") else ""; - f(p.host.ctx, w.pane, path, w.on, w.mode); - } else { - p.fallback.watched[w.pane.index()] = w.on; + p.tape.host(p, .watch_file, .{ w.pane, path, w.on, w.mode }) orelse { + p.fallback.watched[w.pane.index()] = w.on; + }; }, - .theme_file => |t| if (v.watch_theme) |f| f(p.host.ctx, t.generation, t.on), - .dump_themes => |d| if (v.dump_themes) |f| f(p.host.ctx, d.pane), - .detach => |d| if (v.detach) |f| - f(p.host.ctx) - else - p.reportError(d.pane, "detach", error.NotAttached), + .theme_file => |t| _ = p.tape.host(p, .watch_theme, .{ t.generation, t.on }), + .dump_themes => |d| _ = p.tape.host(p, .dump_themes, .{d.pane}), + .detach => |d| p.tape.host(p, .detach, .{}) orelse p.reportError(d.pane, "detach", error.NotAttached), // dlopen is the same on every host, so none has a method of its // own; a replica's core holds no library (what it brought comes in // the event this taped). - .addon => |a| if (!tape.replaying()) @import("Addon.zig").perform(p, a.op, a.pane.index(), a.arg.slice()), - .job => |j| if (v.job) |f| f(p.host.ctx, j.pane, j.serial, j.token) else if (!tape.replaying()) host_io.KindJob.runHere(p, j.pane.index(), j.serial, j.token), + .addon => |a| if (!p.tape.replaying()) @import("Addon.zig").perform(p, a.op, a.pane.index(), a.arg.slice()), + .job => |j| p.tape.host(p, .job, .{ j.pane, j.serial, j.token }) orelse if (!p.tape.replaying()) host_io.KindJob.runHere(p, j.pane.index(), j.serial, j.token), // the loop's own condition; a host tears down after its own loop .quit => p.endSession(), } @@ -282,7 +272,7 @@ pub fn writeChecked(p: *Pardes, id: u8, serial: u32, path: []const u8, bytes: [] if (filesystem.localPath(path)) |local| filesystem.makeDirs(p.tape, std.Io.Dir.path.dirname(local) orelse "/"); // The in-process filesystem reports the same way a real host does, // so an OOM there leaves the pane dirty rather than looking saved. - if (p.host.vtable.write_file) |f| f(p.host.ctx, .at(id), path, bytes) else if (!p.fallback.writeFile(path, bytes)) p.saveFailed(.at(id), path, error.OutOfMemory); + p.tape.host(p, .write_file, .{ .at(id), path, bytes }) orelse if (!p.fallback.writeFile(path, bytes)) p.saveFailed(.at(id), path, error.OutOfMemory); const pane = p.panes[id] orelse return null; if (pane.serial != serial) return null; if (p.fs.failures == failures) return pane; diff --git a/core/File.zig b/core/File.zig index 75d8049b..ceb6d03b 100644 --- a/core/File.zig +++ b/core/File.zig @@ -1579,7 +1579,7 @@ pub fn refreshHighlights(p: *Pardes) void { // itself on the frame, a third of the work; the stretch around it // comes painted ahead (paintAhead) where there are workers. const far = f.highlights.len == 0 or need_end <= f.highlight_start or need_start >= f.highlight_start + f.highlights.len; - const slack: usize = if (far and p.host.vtable.search != null) 0 else if (f.highlights.len == 0) 0 else pane.rows; + const slack: usize = if (far and p.tape.has(p, .search)) 0 else if (f.highlights.len == 0) 0 else pane.rows; const whole = pane.colorAlgo() == .locations or f.tree_context; // Painted ahead on a worker (Stream.paintAhead): taken, no parse. if (!whole and pane.colorAlgo() == .source) if (Stream.takeAhead(p, pane.serial, f.revision, need_start, need_end)) |got| { @@ -2312,7 +2312,6 @@ test "a pager's text is a diff when it holds a diff header or a unified hunk" { } test "a long line is painted only around the caret" { - if (!syntax.enabled) return; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); const line = try std.testing.allocator.alloc(u8, 600 << 10); @@ -2357,6 +2356,20 @@ test "a caret deep in a long line scrolls the view sideways to it, measured from try std.testing.expectEqual(@as(i32, 0), pane.hscroll); } +test "a caret left of a view scrolled sideways is not drawn in the gutter" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + p.settings.wrap = false; + const pane = try p.setTestFile("short1 END_A_MARKER_WAY_OUT_RIGHT_padpadpadpadpadpadpadpadpadpadpad_TAIL\n"); + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + try std.testing.expect((try p.render(arena.allocator())).cursor != null); + // One wheel notch (4 columns) of the 7 the gutter is: the caret, at + // column 0, was drawn 3 columns into the gutter. + pane.hscroll = 4; + try std.testing.expect((try p.render(arena.allocator())).cursor == null); +} + test "undo and redo walk back and forth through every step of random edits, joined entries and all" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); diff --git a/core/Output.zig b/core/Output.zig index 759bada9..c7bfde14 100644 --- a/core/Output.zig +++ b/core/Output.zig @@ -907,7 +907,7 @@ pub fn openBuild(p: *Pardes, id: usize) !void { @tagName(builtin.abi), @tagName(build_options.platform), }); try w.print("grammars {s}\naddons {s}\nsemantics {x:0>16}\n\ndependencies\n{s}", .{ - if (build_options.grammars == .full) "full" else if (build_options.grammars == .minimal) "minimal" else "none", + @tagName(build_options.grammars), if (build_options.builtin_addons) "compiled in" else "loaded from <prefix>/lib/pardes/addons", @import("wire").semantics, build_info.deps, diff --git a/core/Plumb.zig b/core/Plumb.zig index aeebfc64..f51ddace 100644 --- a/core/Plumb.zig +++ b/core/Plumb.zig @@ -1314,7 +1314,6 @@ test "plumb: a set rewrites the message for good, attr delete of one absent fail } test "plumb: isfile and isdir find a name as Look does, past its place, in the message's directory then Incl's; $file is where" { - if (!fs.platform_has_fs) return; var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.writeFile(testing.io, .{ .sub_path = "it.zig", .data = "x\n" }); @@ -1482,7 +1481,6 @@ test "plumb: plan9port's basic parses, its ¡- classes UTF-8's bytes and its } test "plumb: the Plumb word opens the plumbing file, include basic until one is saved; saved, or read at boot, its rules are in force, a bad one said with its line" { - if (!fs.platform_has_fs) return; var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); var dir_buf: [4096]u8 = undefined; diff --git a/core/Query.zig b/core/Query.zig index 704206e6..ebb44155 100644 --- a/core/Query.zig +++ b/core/Query.zig @@ -2294,7 +2294,6 @@ fn settle(p: *Pardes) void { } test "Find: names fuzzy per keystroke, the group born with its +Preview, nothing else moves, Enter promotes the preview in place" { - if (!filesystem.platform_has_fs) return; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.createDirPath(std.testing.io, "src"); @@ -2346,7 +2345,6 @@ test "Find: names fuzzy per keystroke, the group born with its +Preview, nothing } test "Grep: lines of the files under the owner's directory, under their file; All: every pane's, under @pN in serial order, a line once" { - if (!filesystem.platform_has_fs) return; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "b.zig", .data = "const needle = 1;\nconst hay = 2;\nneedle needle\n" }); @@ -2568,7 +2566,6 @@ test "Enter on a frozen query pane's rows after its text was edited: no row to l } test "a query row's place is its text: the match tinted after it, B3 on it opens the place, the rows saved and read again still Look" { - if (!filesystem.platform_has_fs) return; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 48 }); @@ -2627,7 +2624,6 @@ test "a query row's place is its text: the match tinted after it, B3 on it opens } test "the +Preview: the query's hits in its file are its places, the row's one current and selected, coloured as the file is" { - if (!filesystem.platform_has_fs) return; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const text = "const needle = 1;\nconst hay = 2;\nfn f() void {\n _ = needle;\n}\npub const needle_too = needle;\n"; @@ -2662,7 +2658,6 @@ test "the +Preview: the query's hits in its file are its places, the row's one c sel = pv.body.primaryRange(pv.file.?.content, 0); try std.testing.expectEqual(expected.items[2].start, @min(sel.anchor, sel.head)); // its colours the file's, as its own pane paints them - if (!syntax.enabled) return; var frame = std.heap.ArenaAllocator.init(std.testing.allocator); defer frame.deinit(); _ = try p.render(frame.allocator()); @@ -2674,7 +2669,6 @@ test "the +Preview: the query's hits in its file are its places, the row's one c } test "a row's address is the shortest path a Look from the query pane resolves: in its directory, under it, above it, else absolute" { - if (!filesystem.platform_has_fs) return; if (!pardes.lsp.supports.contains(.references)) return; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); @@ -2716,7 +2710,6 @@ test "a row's address is the shortest path a Look from the query pane resolves: } test "a query row's address reaches every way a look arrives: an empty look written back to event and the whole row written to look, as the mouse on it" { - if (!filesystem.platform_has_fs) return; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 48 }); diff --git a/core/Stream.zig b/core/Stream.zig index 5960d249..1f4a7405 100644 --- a/core/Stream.zig +++ b/core/Stream.zig @@ -311,7 +311,7 @@ pub fn takeAhead(p: *Pardes, serial: u32, revision: u32, need_start: usize, need /// workers, and only for a grammar a worker can paint (syntax.readyApart). pub fn paintAhead(p: *Pardes, serial: u32, revision: u32, path: []const u8, content: []const u8, from: usize, to: usize) void { const s = &p.stream; - if (p.host.vtable.search == null or p.fs.serving or to <= from or to > content.len) return; + if (!p.tape.has(p, .search) or p.fs.serving or to <= from or to > content.len) return; const a = s.ahead_for; if (s.ahead.len != 0 and a.serial == serial and a.revision == revision and from >= a.start and to <= a.start + s.ahead.len) return; // A stretch bigger than this (a few lines of a minified file) is not @@ -343,7 +343,7 @@ pub fn paintAhead(p: *Pardes, serial: u32, revision: u32, path: []const u8, cont pub fn askAhead(p: *Pardes) void { const gen = p.stream.ahead_ask orelse return; p.stream.ahead_ask = null; - if (p.host.vtable.search) |f| f(p.host.ctx, gen); + _ = p.tape.host(p, .search, .{gen}); } /// A file's colours for the query rows that show its lines, the whole @@ -355,7 +355,7 @@ pub fn askAhead(p: *Pardes) void { /// one revision of a file. pub fn paintRows(p: *Pardes, path: []const u8) void { const s = &p.stream; - if (s.rows_paint != null or p.host.vtable.search == null) return; + if (s.rows_paint != null or !p.tape.has(p, .search)) return; // Asked while a 9P write is served (a script's Grep): not now, as no // paint is (the write would wait for it to settle); the next step asks. if (p.fs.serving) { @@ -452,7 +452,7 @@ pub fn parseFor(p: *Pardes, id: usize) void { s.parse_next = .{ .serial = pane.serial, .revision = f.revision }; return; } - const workers = p.host.vtable.search != null and !p.fs.serving; + const workers = p.tape.has(p, .search) and !p.fs.serving; if (!workers and f.content.len > 64 << 10) return; const job = TextJob.make(p.gpa, pane.serial, f.revision, 0, f.path, f.content) orelse return; s.gen +%= 1; @@ -478,7 +478,6 @@ fn parseWork(io: std.Io, job: *TextJob, ctx: ?*anyopaque, sink: Sink) void { } fn now() u64 { - if (comptime !filesystem.platform_has_fs) return 0; const t = std.Io.Clock.awake.now(std.Io.Threaded.global_single_threaded.io()); return @intCast(@max(0, t.nanoseconds)); } @@ -559,7 +558,7 @@ pub fn step(p: *Pardes) void { s.state = .searching; // A script's write (whose answer says whether it found anything) and a // host with no workers: done before this returns. - if (p.host.vtable.search != null and !p.fs.serving) p.emit(.{ .search = .{ .gen = s.gen } }) else runHere(p, s.gen, false); + if (p.tape.has(p, .search) and !p.fs.serving) p.emit(.{ .search = .{ .gen = s.gen } }) else runHere(p, s.gen, false); } /// When the core next needs a tick for the stream: the end of the pause. @@ -635,10 +634,6 @@ pub fn runHere(p: *Pardes, gen: u32, comptime in_call: bool) void { }; return; } - if (comptime !filesystem.platform_has_fs) { - p.stream.state = .failed; - return; - } const s = &p.stream; if (gen != s.gen or s.state != .searching) return; const job = makeJob(p.gpa, s) catch |err| { @@ -1163,7 +1158,6 @@ const Rogue = struct { }; test "Stream: a stale generation's rows never land in the query pane, however two generations race (walk and rg)" { - if (comptime !filesystem.platform_has_fs) return; var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); var root_buf: [4096]u8 = undefined; @@ -1243,7 +1237,6 @@ test "Stream: a stale generation's rows never land in the query pane, however tw } test "Stream: the listing of files for Find on a worker, a cap of hits stops the walk on the loop" { - if (comptime !filesystem.platform_has_fs) return; var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); var root_buf: [4096]u8 = undefined; @@ -1273,7 +1266,6 @@ test "Stream: the listing of files for Find on a worker, a cap of hits stops the } test "Stream: a big text's declarations are parsed on a worker, never the loop, and the rows of its / regroup under them" { - if (comptime !filesystem.platform_has_fs) return; const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 }); defer p.deinit(); var text: std.ArrayList(u8) = .empty; @@ -1312,7 +1304,6 @@ test "Stream: a big text's declarations are parsed on a worker, never the loop, } test "Stream: a scroll's colours are painted ahead on a worker, so PageDown after PageDown parses nothing on the frame" { - if (comptime !filesystem.platform_has_fs or !syntax.enabled) return; const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 }); defer p.deinit(); var text: std.ArrayList(u8) = .empty; @@ -1355,7 +1346,6 @@ test "Stream: a scroll's colours are painted ahead on a worker, so PageDown afte } test "Stream: a Grep stops at its 2000 lines and waits; More in the query pane's tag goes on" { - if (comptime !filesystem.platform_has_fs) return; var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); var root_buf: [4096]u8 = undefined; @@ -1404,8 +1394,7 @@ test "Stream: a Grep stops at its 2000 lines and waits; More in the query pane's } test "Stream: a Grep's rows recoloured are made again, never written, and a dump of them dropped by an edit loads to its digest" { - if (comptime !filesystem.platform_has_fs) return; - if (!syntax.enabled or !syntax.readyApart("c.zig")) return; + if (!syntax.readyApart("c.zig")) return; var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); // Rows enough that a digest keeps a word for them (walk's blob_min). @@ -1476,8 +1465,7 @@ test "Stream: a Grep's rows recoloured are made again, never written, and a dump } test "Stream: a Grep's rows are coloured as their file's language colours them, the file painted on a worker, the match tint on top" { - if (comptime !filesystem.platform_has_fs) return; - if (!syntax.enabled or !syntax.readyApart("c.zig")) return; + if (!syntax.readyApart("c.zig")) return; var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); const text = "const std = @import(\"std\");\npub fn value() u32 {\n return 42; // value\n}\n"; diff --git a/core/body_layer.zig b/core/body_layer.zig index 7dc097ad..1582136c 100644 --- a/core/body_layer.zig +++ b/core/body_layer.zig @@ -512,7 +512,10 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane ) else ccol; - if (prow >= pane.tag_rows and cx >= 0 and prow < body_bottom and cx < tw) + // Left of a view scrolled sideways it is off the view, not + // in the gutter. + const left: i32 = if (pane.file != null) panes.File.gutterWidth(pane) else 0; + if (prow >= pane.tag_rows and cx >= left and prow < body_bottom and cx < tw) s.cursor = .{ .x = tx + @as(u16, @intCast(cx)), .y = body_y + @as(u16, @intCast(prow - pane.tag_rows)), .bar = pane.body.mode == .insert }; } } else if (pane.terminal != null) visible: { diff --git a/core/builtins.zig b/core/builtins.zig index 2740e05a..894478fd 100644 --- a/core/builtins.zig +++ b/core/builtins.zig @@ -547,8 +547,7 @@ pub const Adopt = struct { pub const scope: Scope = .session; pub const enabled = pardes.can_attach; pub fn run(c: Ctx) void { - const adopt = c.p.host.vtable.adopt orelse return c.p.reportFailure(c.id, "Adopt: no pardes daemon is keeping shells for this session"); - adopt(c.p.host.ctx, .at(c.id)); + c.p.tape.host(c.p, .adopt, .{.at(c.id)}) orelse c.p.reportFailure(c.id, "Adopt: no pardes daemon is keeping shells for this session"); } }; @@ -559,8 +558,7 @@ pub const Upgrade = struct { pub const scope: Scope = .session; pub const enabled = pardes.can_attach; pub fn run(c: Ctx) void { - const upgrade = c.p.host.vtable.upgrade orelse return c.p.reportFailure(c.id, "Upgrade: this pardes cannot move to another build in place"); - upgrade(c.p.host.ctx, .at(c.id)); + c.p.tape.host(c.p, .upgrade, .{.at(c.id)}) orelse c.p.reportFailure(c.id, "Upgrade: this pardes cannot move to another build in place"); } }; @@ -700,11 +698,9 @@ pub const Fonts = struct { /// Show the declarations enclosing the top row at the pane's head, on or off. pub const TreeContext = struct { - pub const enabled = pardes.syntax.enabled; pub const takes_arg = true; pub fn run(c: Ctx) void { - if (comptime !enabled) unreachable; if (!panes.File.supportsContext(c.pane)) return c.p.reportFailure(c.id, "TreeContext: only a source file the parser knows has context"); const file = &c.pane.file.?; const arg = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); @@ -1044,7 +1040,7 @@ pub const Del = struct { !c.pane.collapsed and c.pane.prompt == .none) { c.pane.prompt = .del_side; - c.pane.question_due_ns = exec.clockNow(c.p) + config.del_question_delay_ns; + c.pane.question_due_ns = Pane.question_asked; c.p.view().active = c.id; var rec: [32]u8 = undefined; pardes.ctlfs.events.notePath(c.p, "ask", std.fmt.bufPrint(&rec, "{d} del k j", .{c.pane.serial}) catch unreachable); // a u32 fits 32 diff --git a/core/config.zig b/core/config.zig index 3dbfe566..f43604ad 100644 --- a/core/config.zig +++ b/core/config.zig @@ -159,7 +159,7 @@ pub const leader_path = paths: { if (builtins.capabilities.pixels) table.set(.GripWidth, null); table.set(.InactiveDim, null); if (builtins.capabilities.pixels) table.set(.Pet, null); - if (builtins.TreeContext.enabled) table.set(.TreeContext, null); + table.set(.TreeContext, null); table.set(.ThemeFile, null); table.set(.DumpThemes, null); table.set(.Mount, null); diff --git a/core/draw.zig b/core/draw.zig index 5ff31af6..b87eb56f 100644 --- a/core/draw.zig +++ b/core/draw.zig @@ -1295,7 +1295,6 @@ test "a wide glyph cut by a tag's or a notice's edge is joined into the grid as } test "a body with context rows is painted once, and the grid's rows are what a plain paint of it gives" { - if (comptime !@import("syntax.zig").enabled) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 60, .rows = 16 }); defer p.deinit(); const pane = try p.setTestFile("pub const Box = struct {\n pub fn run() void {\n" ++ (std.mem.asBytes(&@as([30][21]u8, @splat(" // body line\n".*)))) ++ " }\n};\n"); diff --git a/core/dump.zig b/core/dump.zig index eb0ef263..c348dec2 100644 --- a/core/dump.zig +++ b/core/dump.zig @@ -11,7 +11,6 @@ const exec = @import("exec.zig"); const colors = @import("colors.zig"); const config = @import("config.zig"); const platform = pardes.platform; -const isolated = pardes.isolated; const MAX_PANES = pardes.MAX_PANES; const MAX_COLS = pardes.MAX_COLS; const effect_path_cap = pardes.effect_path_cap; @@ -662,13 +661,11 @@ fn revivePane(p: *Pardes, id: usize, pane: *pardes.panes.Pane, was_on_disk: bool if (pane.terminal != null) { // A command pane comes back finished, showing what it said: its // command is not run again. A host that runs shells starts one - // under the history in the old one's directory; an isolated build - // only shows it. + // under the history in the old one's directory. if (pane.command != null) { pane.command_done = true; return; } - if (comptime isolated) return; if (pane.cwdSlice().len > effect_path_cap) return; // Its shell not there, made ready for a new one: what the old // shell was, ran and said is gone with it (the REPL it ran, the @@ -1060,7 +1057,6 @@ test "a pane restored with unsaved text is asked about by Exit, Restore, Del and test "a loaded terminal's history stays above its banner, the cursor where it was" { if (pardes.Term.ops == null) return error.SkipZigTest; // it reads the emulator - if (comptime isolated) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); defer p.deinit(); @@ -1082,7 +1078,6 @@ test "a loaded terminal's history stays above its banner, the cursor where it wa test "an upgraded session's dump keeps its views and its running terminal as they were, and settings the startup config would change" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell, dumped and loaded - if (comptime isolated) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12, .startup_config = "Verbose off\n" }); defer p.deinit(); diff --git a/core/edit_cmd.zig b/core/edit_cmd.zig index 9f1f7862..9a5c6865 100644 --- a/core/edit_cmd.zig +++ b/core/edit_cmd.zig @@ -610,7 +610,6 @@ test "an Edit whose file is edited while its commands run is refused whole" { } test "X over open files, w, e, r, f, B and D on panes and the disk" { - if (comptime !filesystem.platform_has_fs) return error.SkipZigTest; const gpa = testing.allocator; var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); @@ -687,7 +686,6 @@ test "X over open files, w, e, r, f, B and D on panes and the disk" { } test "an Edit's w to a file changed on disk is refused once, as Save is, and the others are written" { - if (comptime !filesystem.platform_has_fs) return error.SkipZigTest; var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.txt", .data = "a\n" }); @@ -723,7 +721,6 @@ test "an Edit's w to a file changed on disk is refused once, as Save is, and the } test "an Edit with no command runs beside one whose commands run, unless it touches what that one changes" { - if (comptime !filesystem.platform_has_fs) return error.SkipZigTest; var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.writeFile(testing.io, .{ .sub_path = "other.txt", .data = "x\n" }); @@ -784,7 +781,6 @@ test "a session that ends while an Edit's commands run lets the Edit go" { } test "e and r say a file that cannot be read as Get says it" { - if (comptime !filesystem.platform_has_fs) return error.SkipZigTest; const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); const ctl = tree.Node.of(th.serialOf(p), .ctl); diff --git a/core/exec.zig b/core/exec.zig index 1ec47eb3..18b519ff 100644 --- a/core/exec.zig +++ b/core/exec.zig @@ -418,7 +418,7 @@ fn refusedPlacement(p: *Pardes, id: usize) bool { /// Whether a shell would be started in `dir` and `dir` is not there: asked /// only of a host that starts shells, and only of a local path. pub fn missingDir(p: *Pardes, dir: []const u8) bool { - if (p.host.vtable.spawn == null) return false; + if (!p.tape.has(p, .spawn)) return false; // A peer's directory (`/n/peer/x`) is no directory on this host, where // the shell would start: no command or terminal runs there, and none // is made to say `exit 127`. @@ -535,7 +535,7 @@ const repl_quiet_ns: u64 = 100 * std.time.ns_per_ms; /// The host's clock now; core time (`now_ns`, `stepped_ns`) is as old as /// the last frame, seconds in an idle session. pub fn clockNow(p: *Pardes) u64 { - return if (p.host.vtable.now) |clock| clock(p.host.ctx) else p.clock.now_ns; + return p.tape.host(p, .now, .{}) orelse p.clock.now_ns; } /// Sends the Enters a paste into pane `id`'s REPL is owed: when the REPL @@ -708,7 +708,7 @@ pub fn executeFrom(p: *Pardes, id: usize, txt: []const u8, from_body: bool) ?usi const pad = std.math.clamp(max_row - cursor_abs, 0, @as(i32, pane.rows)); for (0..@intCast(pad)) |_| p.emitWrite(id, "\r"); }; - pane.noteCommand(cmd); + pane.noteCommand(cmd, panes.Term.prompt(pane.terminal).started); if (pane.queuePendingCommand(cmd) catch |err| { p.reportError(.at(id), "queue command", err); return id; @@ -1018,7 +1018,7 @@ pub fn applySettingBuiltin(p: *Pardes, setting: config.Settings.Setting, arg: ?[ const spec = config.Settings.FontSpec.parse(arg orelse return) orelse return; // The session's machine's fonts, a question to its disk: a // client's replay takes the session's answer, never its own. - const found = pardes.tape.site(.fonts, p.scratch.allocator(), fontNamed, .{ p.scratch.allocator(), spec.name }); + const found = p.tape.site(.fonts, p.scratch.allocator(), fontNamed, .{ p.scratch.allocator(), spec.name }); const nul = std.mem.indexOfScalar(u8, found, 0) orelse return; if (!p.settings.requestFont(found[0..nul], found[nul + 1 ..], spec.size_hundredths)) return; p.font_request_taken = false; @@ -1035,7 +1035,7 @@ pub fn applySettingBuiltin(p: *Pardes, setting: config.Settings.Setting, arg: ?[ return p.setMessage(.at(v.active), said.print("Shell: the default again, {s} ($SHELL, else /bin/sh)", .{p.sessionShell()[0..@min(p.sessionShell().len, 256)]})); } var why: [320]u8 = undefined; - if (pardes.tape.site(.shell, null, @import("dev").host_io.Shell.refusal, .{ want[0..@min(want.len, 200)], &why })) |refused| { + if (p.tape.site(.shell, null, @import("dev").host_io.Shell.refusal, .{ want[0..@min(want.len, 200)], &why })) |refused| { var text: pardes.Kind.Buf(340) = .{}; return p.reportFailure(v.active, text.print("Shell: {s}", .{refused})); } diff --git a/core/fs.zig b/core/fs.zig index 0797beb0..6e5829e1 100644 --- a/core/fs.zig +++ b/core/fs.zig @@ -163,7 +163,6 @@ fn osNode(p: *pardes.Pardes, path: []const u8) !u64 { /// outlives the yield, and nothing is staged into the shared reply buffer /// until the turn is back. pub fn osHandle(p: *pardes.Pardes, req: Req) Reply { - if (comptime !platform_has_fs) return Reply.fail(req.tag, E.NOENT); const path = osPath(p, req.node) orelse return Reply.fail(req.tag, E.NOENT); if (req.op == .release) return .{ .tag = req.tag }; const stat = p.tape.site(.os_stat, null, osStat, .{path}) catch return Reply.fail(req.tag, E.NOENT); @@ -307,7 +306,6 @@ pub fn statPath(io: std.Io, path: []const u8, options: std.Io.Dir.StatFileOption /// does: one already there is no failure. A failure shows at the open /// that follows. pub fn makeDirs(tape: *pardes.tape.Tape, dir: []const u8) void { - if (comptime !platform_has_fs) return; if (dir.len == 0) return; tape.site(.make_dirs, null, makeDirsHost, .{dir}); } @@ -320,7 +318,6 @@ fn makeDirsHost(io: std.Io, dir: []const u8) void { /// nearest ancestor that is there may not be searched or written (EACCES: /// `noperm/a/b`, `/proc/1/root/x`). pub fn deniedAbove(dir: []const u8) bool { - if (comptime !platform_has_fs) return false; var at: ?[]const u8 = dir; while (at) |d| : (at = std.Io.Dir.path.dirname(d)) { var z: [4096]u8 = undefined; @@ -443,7 +440,6 @@ fn userHome(name: []const u8) ?[]const u8 { } pub fn resolveOs(tape: *pardes.tape.Tape, path: []const u8, out: *[4096]u8) ?Resolved { - if (comptime !platform_has_fs) return null; var z: [4096]u8 = undefined; const path_z = std.fmt.bufPrintSentinel(&z, "{s}", .{path}, 0) catch return null; return tape.site(.resolve, null, resolveHost, .{ path_z, out }); @@ -676,8 +672,6 @@ fn findEmbeddedSource(path: []const u8, allow_root_suffix: bool) ?Source { return null; } -pub const platform_has_fs = !pardes.isolated; - fn isDir(path: [*:0]const u8) bool { const fd = libc.open(path, .{ .ACCMODE = .RDONLY, .DIRECTORY = true, .CLOEXEC = true }); if (fd < 0) return false; @@ -719,8 +713,8 @@ pub fn restorePath(tape: *pardes.tape.Tape, typed: []const u8, dir_setting: []co fn readFileLimit(tape: *pardes.tape.Tape, gpa: std.mem.Allocator, path: []const u8, limit: usize) ![]u8 { if (std.mem.indexOfScalar(u8, path, 0) != null) return error.OpenFailed; - if (!platform_has_fs or std.mem.startsWith(u8, path, "/virtual/")) { - const archive_path = if (std.mem.startsWith(u8, path, "/virtual/")) path[9..] else path; + if (std.mem.startsWith(u8, path, "/virtual/")) { + const archive_path = path[9..]; var normalized_buf: [4096]u8 = undefined; const normalized = normalizeVirtualPath(archive_path, &normalized_buf) orelse return error.OpenFailed; const source = findEmbeddedSource(normalized, true) orelse return error.OpenFailed; @@ -1215,7 +1209,6 @@ test "self files share the regular file limit without preallocating it" { } test "bounded reads accept exact OS file lengths and empty files" { - if (!platform_has_fs) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true }); defer p.deinit(); @@ -1327,7 +1320,7 @@ test "bounded reads release terminal snapshots after success and size refusal" { } test "bounded reads probe size-unknown proc files at the exact limit" { - if (!platform_has_fs or @import("builtin").os.tag != .linux) return error.SkipZigTest; + if (@import("builtin").os.tag != .linux) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true }); defer p.deinit(); @@ -1379,7 +1372,6 @@ test "self file reads release partial allocations when memory runs out" { } test "oversized OS files fail before allocating their contents" { - if (!platform_has_fs) return error.SkipZigTest; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const file = try tmp.dir.createFile(std.testing.io, "oversized", .{}); @@ -1481,7 +1473,6 @@ test "a leading ~ is home, from HOME or else the passwd entry" { } test "Restore prefers default directory then falls back to original path" { - if (!platform_has_fs) return error.SkipZigTest; const gpa = std.testing.allocator; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); diff --git a/core/grammar_manifest.zig b/core/grammar_manifest.zig index 711c31a4..b4ff30b9 100644 --- a/core/grammar_manifest.zig +++ b/core/grammar_manifest.zig @@ -5,7 +5,7 @@ const std = @import("std"); -pub const Tier = enum { zig, minimal, full }; +pub const Tier = enum { minimal, full }; pub const Grammar = struct { name: []const u8, @@ -58,7 +58,7 @@ pub const all = [_]Grammar{ \\"#" @keyword \\ }, - .{ .name = "zig", .dep = "ts_zig", .exts = &.{ ".zig", ".zon" }, .tier = .zig }, + .{ .name = "zig", .dep = "ts_zig", .exts = &.{ ".zig", ".zon" }, .tier = .minimal }, }; /// The names a language goes by besides its grammar's: a fence's `py`, diff --git a/core/keys.zig b/core/keys.zig index 72e3bb3b..8bfe8315 100644 --- a/core/keys.zig +++ b/core/keys.zig @@ -717,6 +717,9 @@ test "the Del question shows only once its delay is up: a quick SPC d j never se p.update(.{ .key = .{ .cp = 'd' } }); const pane = p.panes[mid].?; try std.testing.expectEqual(Pane.Prompt.del_side, pane.prompt); + // Its time is the next advance's (the host's clock, in its pump). + try std.testing.expectEqual(Pane.question_asked, pane.question_due_ns); + p.advance(asked_at); try std.testing.expectEqual(asked_at + config.del_question_delay_ns, pane.question_due_ns); // Asked, and nothing on the band yet. _ = try p.render(frame.allocator()); diff --git a/core/lib_syntax.zig b/core/lib_syntax.zig index a25af884..f4f85820 100644 --- a/core/lib_syntax.zig +++ b/core/lib_syntax.zig @@ -4,7 +4,7 @@ //! coloured as pardes has it. Nothing is copied here: these are the editor's //! own grammars and highlighting (syntax.zig), themes (colors.zig) and line //! arithmetic (modal.zig), under the names they have there. Whatever is -//! named here compiles with tree-sitter and the grammars alone; test/lib +//! named here compiles with tree-sitter and the grammars alone; test/consumer //! imports it as such a package and holds it to that. //! //! A language is told by a path's extension, as in the editor; `pathFor` @@ -15,7 +15,7 @@ const colors = @import("colors.zig"); const modal = @import("modal.zig"); /// Every grammar pardes knows (`all`), by name or alias (`byName`) and by -/// path (`byPath`). The build's `tree-sitter` option says which of them are +/// path (`byPath`). The build's `grammars` option says which of them are /// compiled in, and `supportsPath` answers for this build. pub const grammars = @import("grammar_manifest.zig"); pub const supportsPath = syntax.supportsPath; diff --git a/core/look.zig b/core/look.zig index 1023a532..1d296775 100644 --- a/core/look.zig +++ b/core/look.zig @@ -7,7 +7,6 @@ const exec = @import("exec.zig"); const Plumb = @import("Plumb.zig"); const config = @import("config.zig"); const diff = @import("diff.zig"); -const platform_has_fs = filesystem.platform_has_fs; const layout = @import("layout.zig"); const modal = @import("modal.zig"); const tagline = @import("tagline.zig"); @@ -1758,7 +1757,6 @@ test "parsePathLine: `end` separates a whole-token target from a lenient read" { } test "lookableSpan peels prose punctuation off a path, largest first" { - if (!platform_has_fs) return; var realbuf: [4096]u8 = undefined; try std.testing.expectEqualDeep( @as(?Span, .{ .start = 0, .end = "core/look.zig".len }), @@ -1782,7 +1780,6 @@ test "lookableSpan peels prose punctuation off a path, largest first" { } test "lookableLineSpan takes the row's location and stops before its text" { - if (!platform_has_fs) return; var realbuf: [4096]u8 = undefined; try std.testing.expectEqualDeep( @as(?Span, .{ .start = 0, .end = "core/look.zig:12:5-9".len }), @@ -1813,7 +1810,6 @@ test "lookableLineSpan takes the row's location and stops before its text" { } test "lookableLineSpan prefers the longest run, so a blank inside a path is one span" { - if (!platform_has_fs) return; var realbuf: [4096]u8 = undefined; const io = std.testing.io; var tmp = std.testing.tmpDir(.{}); @@ -2054,7 +2050,6 @@ test "a pointer resting where a look-hover found nothing does not wake the core } test "Look on each kind of diff line opens the new file at the line it names" { - if (!platform_has_fs) return; const numbered = "line 1\nline 2\nline 3\nline 4\nline 5\nline 6\nline 7\nline 8\nline 9\n" ++ "line 10\nline 11\nline 12\nline 13\nline 14\nline 15\n"; const diff_text = @@ -2116,7 +2111,6 @@ test "Look on each kind of diff line opens the new file at the line it names" { } test "Look on plain diff -u output: names as written, timestamps cut, next to the diff" { - if (!platform_has_fs) return; const diff_text = "--- old/x.zig\t2026-09-30 10:00:00.000000000 +0000\n" ++ "+++ new/x.zig\t2026-09-30 11:00:00.000000000 +0000\n" ++ "@@ -1,2 +1,3 @@\n" ++ @@ -2136,7 +2130,6 @@ test "Look on plain diff -u output: names as written, timestamps cut, next to th } test "Look on a diff: headers and a hunk line's prefix are the whole line, hover and click alike" { - if (!platform_has_fs) return; const numbered = "one\ntwo\nthree\nfour\nfive\nsix\n"; const diff_text = \\diff --git a/src/old.zig b/src/new.zig @@ -2223,7 +2216,6 @@ test "Look on a diff: headers and a hunk line's prefix are the whole line, hover } test "a click, a 9P whole-line look and an empty event write-back take one expansion on every kind of diff line, a blank context line too" { - if (!platform_has_fs) return; const diff_text = \\diff --git a/src/new.zig b/src/new.zig \\--- a/src/new.zig @@ -2286,7 +2278,6 @@ test "a click, a 9P whole-line look and an empty event write-back take one expan } test "every entry point to Look takes one expansion: a diff line and a file:12:5: line land in one place by each" { - if (!platform_has_fs) return; const numbered = "l1\nl2\nl3\nl4\nl5\nl6\nl7\nl8\nl9\nl10\nl11\nline 12 here\nl13\n"; const diff_text = \\diff --git a/src/x.zig b/src/x.zig @@ -2378,7 +2369,6 @@ test "every entry point to Look takes one expansion: a diff line and a file:12:5 } test "a tag word looked at by a click and by Enter is one record to an event reader; an exec on a diff line takes its word, never the address" { - if (!platform_has_fs) return; const diff_text = \\diff --git a/src/x.zig b/src/x.zig \\--- a/src/x.zig @@ -2449,7 +2439,6 @@ test "a tag word looked at by a click and by Enter is one record to an event rea } test "Incl's directories find a name found nowhere else, <name> too; bare Incl lists them, Incl - empties them, and a dump keeps them" { - if (!platform_has_fs) return; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.createDirPath(std.testing.io, "inc"); @@ -2489,7 +2478,6 @@ test "Incl's directories find a name found nowhere else, <name> too; bare Incl l test "LookNext in a command pane walks its own file:line places, whoever walked last" { if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane - if (!platform_has_fs) return; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "x.c", .data = "a\nb\nc\n" }); @@ -2546,7 +2534,6 @@ test "Look outside a diff pane expands and looks as ever" { } test "Look on a diff under each git prefix opens the repository's file, and a real a/ directory under --no-prefix" { - if (!platform_has_fs) return; const Case = struct { text: []const u8, file: []const u8 }; const cases = [_]Case{ .{ .text = "diff --git a/src/x.zig b/src/x.zig\n--- a/src/x.zig\n+++ b/src/x.zig\n@@ -1,2 +1,2 @@\n-one\n+uno\n two\n", .file = "/src/x.zig" }, @@ -2573,7 +2560,6 @@ test "Look on a diff under each git prefix opens the repository's file, and a re } test "Look on a diff line is the look of the address it names, selected by hand: a cached patch, the checkout elsewhere" { - if (!platform_has_fs) return; const io = std.testing.io; const patch = "diff --git a/entry/src/entry.rs b/entry/src/entry.rs\n--- a/entry/src/entry.rs\n+++ b/entry/src/entry.rs\n" ++ "@@ -1,2 +1,2 @@\n-fn old() {}\n+fn new() {}\n fn kept() {}\n"; @@ -2635,7 +2621,6 @@ test "Look on a diff line is the look of the address it names, selected by hand: } test "Plumb: a look sends what it looks at, the rules written first: a rule's word or port takes it, a name open in a pane is focused unsent, one nothing takes is Look's own" { - if (!platform_has_fs) return; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "pic.svg", .data = "<svg/>" }); @@ -2687,7 +2672,6 @@ test "Plumb: a look sends what it looks at, the rules written first: a rule's wo test "Plumb: a commit hash looked at in a git work tree is git show's, paged; outside one Diff declines, and the word is searched for" { if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane - if (!platform_has_fs) return; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.createDir(std.testing.io, ".git", .default_dir); diff --git a/core/mouse.zig b/core/mouse.zig index 1882b691..465d8a01 100644 --- a/core/mouse.zig +++ b/core/mouse.zig @@ -1819,7 +1819,6 @@ test "a press on a notice's chip is the same state whichever frame this process // The same through a body hit (edit.pointerTextSelection, a sweep's drag), // on a compact body layer (TreeContext), which a pixel shell inverts. test "a body press, drag and release are the same state whichever frame this process drew last" { - if (comptime !pardes.syntax.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const a = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }); defer a.deinit(); diff --git a/core/ninep/pty.zig b/core/ninep/pty.zig index 26bb7661..4b0cee66 100644 --- a/core/ninep/pty.zig +++ b/core/ninep/pty.zig @@ -66,7 +66,7 @@ pub fn writeCtl(p: *Pardes, req: Req, id: usize) Reply { // interpreter is not: refused, and the running shell kept. const bin = pane.shell orelse p.shellBin(); var why: [320]u8 = undefined; - if (pardes.tape.site(.shell, null, @import("dev").host_io.Shell.refusal, .{ bin[0..@min(bin.len, 200)], &why })) |refused| + if (p.tape.site(.shell, null, @import("dev").host_io.Shell.refusal, .{ bin[0..@min(bin.len, 200)], &why })) |refused| return tree.failText(req.tag, E.NOENT, std.fmt.bufPrint(&p.fs.ename, "exec: {s}", .{refused[0..@min(refused.len, 300)]}) catch &p.fs.ename); // cut to ename's 320 }; if (verb(p, id, line, apply)) |why| return tree.failText(req.tag, E.INVAL, why); @@ -220,7 +220,7 @@ pub fn writeRun(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { for (line) |c| if (c < ' ' and c != '\t') return tree.failText(req.tag, E.INVAL, e_bad_line); const pf = &pane.fs; if (pane.terminal == null) return tree.failText(req.tag, E.INVAL, e_bad_line); - const marks = pardes.Term.prompt(pane.terminal); + const marks = marksOf(pane); if (pane.shell_failed) { // Its shell never started: no prompt is coming to wait for. answer(p, slot, "error shell gone", .{}); @@ -288,7 +288,7 @@ pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void { if (pane.terminal == null) return; const pf = &pane.fs; const slot = waitingRun(p, pane) orelse return; - const marks = pardes.Term.prompt(pane.terminal); + const marks = marksOf(pane); if (slot.phase == .waiting) { if (pf.unmarked) { answer(p, slot, "error no prompt marks", .{}); @@ -305,7 +305,7 @@ pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void { if (pardes.Term.modes(pane.terminal).alternate) pane.feedOutput(p, "\x1b[?1049l"); p.emitWrite(id, slot.line); p.emitWrite(id, "\r"); - pane.noteCommand(slot.line); + pane.noteCommand(slot.line, marks.started); // The run is the shell's first command: a greeting `ls` typed at the // same prompt would run after it, and its C would be taken for ours. pane.greet = false; @@ -360,6 +360,14 @@ pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void { finish(p, slot, pane, done.status); } +/// The shell's marks as the session's emulator has them (taped), as a +/// run's step reads them: a screen-state replica's emulator is the last +/// delta's, which comes at a frame and can be a unit behind the one it +/// replays. +fn marksOf(pane: *const Pane) pardes.Term.Prompt { + return pardes.tape.value(.prompt, pardes.Term.prompt, .{pane.terminal}); +} + /// Answers a run whose command ended with `status`: the header and the /// output it printed. fn finish(p: *Pardes, slot: *Run, pane: *Pane, status_code: ?i32) void { diff --git a/core/ninep/tree.zig b/core/ninep/tree.zig index 46a4e3d2..1eaaa8cb 100644 --- a/core/ninep/tree.zig +++ b/core/ninep/tree.zig @@ -928,9 +928,11 @@ fn open(p: *Pardes, req: Req, target: Target) Reply { }; }, }; - const i = for (p.fs.opens, 0..) |o, i| { - if (o.node == 0) break i; - } else return Reply.fail(req.tag, E.NFILE); + // The handle every later request of this open names: the session's 9P + // server's, told to a replica as the answer it was. A client joined + // since holds none of the opens made before it, and its first free + // record would be another than the session's. + const i = p.tape.authority(freeOpen, .{p}) orelse return Reply.fail(req.tag, E.NFILE); const o = &p.fs.opens[i]; o.* = .{ .node = req.node, .what = what }; if (resultsFile(target)) { @@ -969,6 +971,13 @@ fn open(p: *Pardes, req: Req, target: Target) Reply { return .{ .tag = req.tag, .handle = @intCast(i + 1) }; } +/// The first open record free. +fn freeOpen(p: *Pardes) ?u64 { + return for (p.fs.opens, 0..) |o, i| { + if (o.node == 0) break i; + } else null; +} + /// Tremove closes a pane. Nothing else in the tree can be removed, and this /// is also where an ORCLOSE open lands, so every node is checked here. fn remove(p: *Pardes, req: Req) Reply { diff --git a/core/panes.zig b/core/panes.zig index fd152e1e..1c103bd1 100644 --- a/core/panes.zig +++ b/core/panes.zig @@ -53,6 +53,10 @@ pub const Pane = struct { return @backingInt(id); } }; + /// Del's question asked, its time not had yet: the step that asks + /// reads no clock (a far client's would wait on the session's), and + /// core time is the last frame's, seconds old in an idle session. + pub const question_asked: u64 = std.math.maxInt(u64); /// The words that throw unsaved text away (builtins.zig warnModified). pub const Discarding = enum { Exit, Restore, get, Del, Delcol }; @@ -218,7 +222,9 @@ pub const Pane = struct { repl_enter: u8 = 0, repl_enter_due_ns: u64 = 0, /// When Del's question (`del_side`) goes up on the notice band, on the - /// shell's clock (config.del_question_delay_ns after it was asked). + /// shell's clock (config.del_question_delay_ns after it was asked): + /// `question_asked` until the next advance, which counts the delay + /// from its own time (Core.advance). question_due_ns: u64 = 0, /// A question with its answers in it (`repl_choice`). question: [96]u8 = undefined, @@ -715,7 +721,7 @@ pub const Pane = struct { pub fn feedOutput(pane: *Pane, p: *Pardes, bytes: []const u8) void { // There are no pty reads at all without an emulator to parse them into. const state = pane.terminal orelse return; - if (tape.authorityOnly("a terminal's output")) return; + if (p.tape.authorityOnly("a terminal's output")) return; const has_positions = pane.ovl != null or pane.body.cur_pinned or pane.body.vsel.active or pane.body.nsel > 0 or pane.body.last_edit != null or pane.look_at != null or pane.body.ed_undo_len > 0 or pane.body.ed_redo_len > 0 or pane.pointerRowCount() > 0; @@ -1026,11 +1032,11 @@ pub const Pane = struct { /// started, for Kill: it runs from the shell's next C mark to its D. /// ponytail: of several lines queued for a shell not up yet, only the /// last is remembered, as the first of them. - pub fn noteCommand(pane: *Pane, line: []const u8) void { - const state = pane.terminal orelse return; + pub fn noteCommand(pane: *Pane, line: []const u8, started: u32) void { + if (pane.terminal == null) return; const said = std.mem.trim(u8, line, " \t"); const word = said[0 .. std.mem.indexOfAny(u8, said, " \t") orelse said.len]; - var sent: @typeInfo(@FieldType(Pane, "sent_command")).optional.child = .{ .seq = Term.prompt(state).started +% 1 }; + var sent: @typeInfo(@FieldType(Pane, "sent_command")).optional.child = .{ .seq = started +% 1 }; sent.len = @intCast(@min(word.len, sent.word.len)); @memcpy(sent.word[0..sent.len], word[0..sent.len]); pane.sent_command = sent; @@ -1166,7 +1172,6 @@ pub fn createDoc(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { /// A terminal pane: a pane and its emulator. Slot ownership, serial /// assignment and spawn effects remain core lifecycle invariants. pub fn createTerminal(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { - if (tape.authorityOnly("open a terminal")) return error.OutOfMemory; const pane = try createDoc(gpa, cols, rows); errdefer gpa.destroy(pane); pane.terminal = try Term.open(emulatorGpa(gpa), cols, rows); @@ -1230,7 +1235,7 @@ pub fn retirePane(p: *Pardes, pane: *Pane) void { if (pane.isTerminal()) p.emit(.{ .close_pty = .{ .pane = .at(id) } }); // Its pty's end and its emulator are the authority's: a replica's // speculation that closes a terminal waits for it. - if (pane.terminal != null) tape.poison("close a terminal"); + if (pane.terminal != null) p.tape.poison("close a terminal"); ctlfs.events.noteRetire(p, pane); // ...and so do bytes still queued for the pty it no longer has. p.dropPendingWrite(id); @@ -1271,7 +1276,7 @@ pub fn teardownPane(p: *Pardes, pane: *Pane) void { } // A pane with none (a file's, a picker's, a preview's) closes in a // speculation as anywhere. - if (pane.terminal) |state| if (!tape.authorityOnly("close a terminal")) { + if (pane.terminal) |state| if (!p.tape.authorityOnly("close a terminal")) { Term.close(state, p.gpa); pane.terminal = null; }; @@ -1307,6 +1312,8 @@ pub fn installPane(p: *Pardes, id: usize, pane: *Pane) void { pub fn newShell(p: *Pardes, id: usize, cwd: []const u8) !*Pane { std.debug.assert(p.panes[id] == null); if (cwd.len > limits.host_path_cap) return error.PathTooLong; + // A speculation opens no emulator: a terminal is the authority's to open. + if (p.tape.authorityOnly("open a terminal")) return error.OutOfMemory; const pane = try panes.createTerminal(p.gpa, p.view().screen_w, p.view().screen_h); // Named by the directory it is started in from the first, so the // shell saying it is there is no rename (`new N /` then `rename`); @@ -1339,6 +1346,7 @@ pub fn newCommand(p: *Pardes, id: usize, cwd: []const u8, line: []const u8) !*Pa if (cwd.len > limits.host_path_cap) return error.PathTooLong; const owned = try p.gpa.dupe(u8, line); errdefer p.gpa.free(owned); + if (p.tape.authorityOnly("open a terminal")) return error.OutOfMemory; const pane = try panes.createTerminal(p.gpa, p.view().screen_w, p.view().screen_h); pane.command = owned; pane.command_pty = true; diff --git a/core/replica.zig b/core/replica.zig index 14757d9a..781bd211 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -1887,6 +1887,16 @@ pub const Peer = struct { peer.cond.signal(io); } + /// Its last message: queued, and its writer ends once it is written. + fn last(peer: *Peer, words: []const u8) void { + const io = peer.peers.io; + peer.send(&.{words}); + peer.lock.lockUncancelable(io); + peer.closing = true; + peer.cond.signal(io); + peer.lock.unlock(io); + } + fn writeLoop(peer: *Peer) void { const io = peer.peers.io; defer peer.done.store(true, .release); @@ -2230,7 +2240,10 @@ pub const Peers = struct { } } - fn join(ps: *Peers, core: *Pardes, joining: Joining) void { + /// A client on `joining.fd` joined: a dump of the session now, its + /// threads started. At a step boundary (`boundary`), or a session's + /// first client before its first effects (runtime/session.zig). + pub fn join(ps: *Peers, core: *Pardes, joining: Joining) void { const fd = joining.fd; const t0 = nowNs(); defer { @@ -2401,14 +2414,14 @@ pub const Peers = struct { if (ps.count() == 0) return; var out: [600]u8 = undefined; const words = wire.encodeServer(&out, .{ .refused = why }) catch return; - const io = ps.io; - for (ps.list) |slot| if (slot) |peer| { - peer.send(&.{words}); - peer.lock.lockUncancelable(io); - peer.closing = true; - peer.cond.signal(io); - peer.lock.unlock(io); - }; + for (ps.list) |slot| if (slot) |peer| peer.last(words); + ps.flushed200(); + // Each joins again for its view, kept in the dump (views.away). + ps.drop(core, true); + } + + /// What each client was sent goes first, for up to 200 ms. + fn flushed200(ps: *Peers) void { const until = nowNs() + 200 * std.time.ns_per_ms; while (nowNs() < until) { const busy = for (ps.list) |slot| { @@ -2418,8 +2431,6 @@ pub const Peers = struct { const ts: libc.timespec = .{ .sec = 0, .nsec = 2 * std.time.ns_per_ms }; _ = libc.nanosleep(&ts, null); } - // Each joins again for its view, kept in the dump (views.away). - ps.drop(core, true); } /// A join's dump and pins let go: written, or its client gone. @@ -2442,21 +2453,30 @@ pub const Peers = struct { daemon.clients(pids[0..n]); } - /// Detach typed in client view `k`'s: its link ends (its reader says - /// it is gone, and the next boundary lets it go). + /// Detach typed in client view `k`'s: told it left the session running + /// (`left`), its last word; the client goes, and its reader says so. pub fn detach(ps: *Peers, k: u8) bool { for (ps.list) |slot| if (slot) |peer| if (peer.view == k) { - _ = libc.shutdown(peer.fd, 2); + var out: [wire.max_name + 8]u8 = undefined; + peer.last(wire.encodeServer(&out, .{ .left = ps.name[0..@min(ps.name.len, wire.max_name)] }) catch unreachable); return true; }; return false; } + /// The session ends with `code`: every client told so (`ended`), its + /// last word, before the links are let go (`dropAll`). + pub fn ended(ps: *Peers, code: u8) void { + var out: [16]u8 = undefined; + const words = wire.encodeServer(&out, .{ .ended = code }) catch unreachable; + for (ps.list) |slot| if (slot) |peer| peer.last(words); + ps.flushed200(); + } + fn stop(ps: *Peers, core: *Pardes) void { if (!ps.recording) return; pardes.panes.resizeDeferred(core); ps.screens.deinit(core); - if (core.host.vtable == &ps.t.vtable) core.host = ps.t.real; tape.on = null; core.tape = core.opts.tape orelse &tape.none; tape.release(&ps.t); @@ -2576,13 +2596,14 @@ pub fn dial(gpa: Allocator, path: []const u8, session: []const u8, why: []u8, ha } /// `dial`'s, on a connection made: the hello, then the join. The -/// connection is closed if the join fails. -fn joinOn(gpa: Allocator, fd: c_int, session: []const u8, why: []u8, have: ?*Have, view: ?u8) ?Joined { +/// connection is closed if the join fails. No session named: no hello, a +/// pair's (Options.pair), whose session took it as its first client. +fn joinOn(gpa: Allocator, fd: c_int, session: ?[]const u8, why: []u8, have: ?*Have, view: ?u8) ?Joined { var out: [wire.hello_max + 16]u8 = undefined; - const hello = wire.encodeClient(&out, .{ .hello = .{ .session = session, .view = view } }) catch { + const hello = if (session) |name| wire.encodeClient(&out, .{ .hello = .{ .session = name, .view = view } }) catch { _ = libc.close(fd); return said(why, "that session's name is too long", .{}); - }; + } else out[0..0]; // Its first word, in the same write: whether it is far. const far = wire.encodeClient(out[hello.len..], .{ .far = have != null }) catch unreachable; var j: Joined = .{ .fd = fd, .pid = 0, .client = 0, .view = 0, .gmtoff = 0, .dump = &.{} }; @@ -2915,7 +2936,7 @@ pub fn bye(fd: c_int, again: bool) void { /// What the session streams a client after its dump, as its frontend's loop /// takes it: a unit's and a terminal message's bytes and a refusal's words /// on the C heap, the loop's to free. -pub const Said = union(enum) { unit: []u8, screen: []u8, checked: u64, refused: []u8, blob: []u8 }; +pub const Said = union(enum) { unit: []u8, screen: []u8, checked: u64, refused: []u8, blob: []u8, ended: u8, left }; /// The session's stream off `fd`, each message handed to `post` until the /// link ends (a refusal ends it too); `post` says whether it took it (one @@ -2930,13 +2951,16 @@ pub fn readLink(gpa: Allocator, fd: c_int, rest: *Framer, ctx: anytype, comptime .blob => .{ .blob = std.heap.c_allocator.dupe(u8, payload) catch return false }, .check => .{ .checked = (wire.decodeServer(tag, payload) catch return false).check }, .refused => .{ .refused = std.heap.c_allocator.dupe(u8, (wire.decodeServer(tag, payload) catch return false).refused) catch return false }, + .ended => .{ .ended = (wire.decodeServer(tag, payload) catch return false).ended }, + .left => .left, .pong, .welcome, .dump, .blobs, .zstd => return true, }; if (!post(x, msg)) switch (msg) { .unit, .screen, .refused, .blob => |b| std.heap.c_allocator.free(b), - .checked => {}, + .checked, .ended, .left => {}, }; - return msg != .refused; + // A last word ends the stream. + return msg == .unit or msg == .screen or msg == .checked or msg == .blob; } }; rest.run(gpa, fd, ctx, Take.take); @@ -2946,11 +2970,23 @@ pub fn readLink(gpa: Allocator, fd: c_int, rest: *Framer, ctx: anytype, comptime if (!post(ctx, .{ .refused = words })) std.heap.c_allocator.free(words); } +/// A join's failure that is its session's end, whenever it came (the +/// session or its daemon gone, or hung up before the dump was whole): a +/// client joining again then goes as at a hang-up (`.gone`), in the same +/// words, never as a join that failed. +pub fn ended(why: []const u8) bool { + const words = std.mem.sliceTo(why, 0); + for ([_][]const u8{ "the session hung up", "nothing answers at ", "no session called " }) |w| + if (std.mem.startsWith(u8, words, w)) return true; + return false; +} + /// The words a client goes with when its session runs another build now. const upgrade_words = "session upgraded to a newer pardes: upgrade this client too"; /// A replica client's join, the terminal's and the window's alike (their -/// `runClient`): the session at `path` dialled, its build checked to be this +/// `runClient`): the session at `path` dialled (or, first, the one on its +/// pair, `o.pair`), its build checked to be this /// one's, and its dump loaded into a replica checked against the session /// as it was dumped. Or, `old` given, joined again once old's link has /// ended, for old's view (`redial`): the core it leaves held meanwhile so @@ -2963,6 +2999,7 @@ pub fn join(gpa: Allocator, j: *Joined, path: []const u8, session: []const u8, o const t0 = nowNs(); if (old) |prev| { j.* = redial(gpa, path, session, why, have, prev.diverged == null, j.view) orelse { + if (ended(why)) return null; var words: [600]u8 = undefined; const said_ = std.mem.sliceTo(why, 0); @memcpy(words[0..said_.len], said_); @@ -2971,7 +3008,7 @@ pub fn join(gpa: Allocator, j: *Joined, path: []const u8, session: []const u8, o }; if (have) |h| h.left(); prev.deinit(); - } else j.* = sameBuild(gpa, dial(gpa, path, session, why, have, null) orelse return null, why) orelse return null; + } else j.* = sameBuild(gpa, (if (o.pair) |fd| joinOn(gpa, fd, null, why, have, null) else dial(gpa, path, session, why, have, null)) orelse return null, why) orelse return null; defer { if (have) |h| h.store(gpa, j) else gpa.free(j.dump); j.dump = &.{}; @@ -3073,6 +3110,9 @@ pub const Link = struct { visible: u32 = 0, /// What the session said as it let this client go (the C heap's). refused: ?[]u8 = null, + /// Its last word: it ended, with this code; or this client left it. + ended: ?u8 = null, + left: bool = false, /// A line over its frame, until its next key (`notify`): why it joined /// again. The client's own, never the session's core. notice_buf: [240]u8 = undefined, @@ -3191,6 +3231,14 @@ pub const Link = struct { c.refused = words; c.quit = true; }, + .ended => |code| { + c.ended = code; + c.quit = true; + }, + .left => { + c.left = true; + c.quit = true; + }, } if (c.r.diverged != null) c.quit = true; } @@ -3571,6 +3619,14 @@ test "a client joining again after a divergence is told at once that its session const t0 = nowNs(); try std.testing.expect(redial(std.testing.allocator, "/nonexistent/pardes-replica.sock", "gone", &why, null, false, 1) == null); try std.testing.expect(nowNs() - t0 < 100 * std.time.ns_per_ms); + try std.testing.expect(ended(&why)); + // Its session ending as it joins: hung up before the dump was whole, + // its end too, said as the end it is. + var fds: [2]c_int = undefined; + try std.testing.expectEqual(0, libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM, 0, &fds)); + _ = libc.close(fds[1]); + try std.testing.expect(joinOn(std.testing.allocator, fds[0], "gone", &why, null, 1) == null); + try std.testing.expect(ended(&why)); } test "a replica's own keys apply at once, confirm on the fast path, and end at the authority's digest" { @@ -4389,6 +4445,119 @@ test "bytes: a client joins from a dump with its terminals whole, and every side try sameTerminals(b.a, late); } +test "a session's first client on the socket it starts with (Options.pair), joined there with no hello before the session's first effects: the boot shell's spawn and first bytes reach it and the digests agree" { + try firstOnPair(false); +} + +test "bytes: a session's first client on its pair, taken before its first effects, has the boot shell's first bytes with no reload of them (the session's one at the join is of its emulator before any byte, the client's none); a client after them makes every side reload" { + try firstOnPair(true); +} + +/// A session's first client on a socket pair (runtime/session.zig's, then +/// the client's first join on its end), the session's first effects after: +/// its boot shell spawned, its first bytes output; the client quiet and +/// checked. Bytes: the client loaded as the soak's bytes clients are +/// (`replica.join` loads the screen-state kind until the switch). +fn firstOnPair(bytes: bool) !void { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const gpa = std.testing.allocator; + const Spawns = struct { + fn spawn(ctx: ?*anyopaque, _: pardes.Pane.Id, _: []const u8) void { + const n: *u32 = @ptrCast(@alignCast(ctx.?)); + n.* += 1; + } + const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .spawn = spawn }; + }; + var spawns: u32 = 0; + var fds: [2]c_int = undefined; + if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket; + const opts: pardes.Options = .{ .cols = 80, .rows = 24, .boot = .tty }; + const core = try Pardes.init(gpa, opts); + defer core.deinit(); + core.host = .{ .ctx = &spawns, .vtable = &Spawns.vtable }; + var ps: Peers = .{ .gpa = gpa, .io = std.testing.io, .name = "pair", .bytes = bytes, .detached = true }; + defer ps.deinit(); + defer live_peers = null; + defer ps.dropAll(core); + const reloads = pardes.Term.reloads.n; + ps.join(core, .{ .fd = fds[0] }); + var j: Joined = undefined; + var why: [600]u8 = @splat(0); + const r = if (bytes) r: { + j = joinOn(gpa, fds[1], null, &why, null, null) orelse return error.JoinFailed; + defer gpa.free(j.dump); + const r = try Replica.initDump(gpa, j.client, j.view, j.dump, opts); + r.t.screen_state = false; + r.core().echo = null; + break :r r; + } else r: { + var o = opts; + o.pair = fds[1]; + break :r join(gpa, &j, "", "", o, null, &why, null) orelse { + std.debug.print("the join failed: {s}\n", .{std.mem.sliceTo(&why, 0)}); + return error.JoinFailed; + }; + }; + defer r.deinit(); + defer { + _ = libc.close(j.fd); + j.rest.deinit(gpa); + } + try std.testing.expect(r.loaded(j.digest)); + // The first effects, the boot shell's spawn among them; its first bytes. + while (core.nextEffect()) |e| core.perform(e); + try std.testing.expectEqual(@as(u32, 1), spawns); + const shell: u8 = for (core.panes, 0..) |slot, id| { + if (slot) |pane| if (pane.isTerminal()) break @intCast(id); + } else return error.NoShell; + core.update(.{ .output = .{ .pane = .at(shell), .bytes = "first$ " } }); + ps.boundary(core); + // Its check, answered after every unit and terminal message before it. + try std.testing.expect(askCheck(j.fd)); + while (!ps.mail.load(.acquire)) std.Thread.yield() catch {}; + ps.boundary(core); + const Take = struct { + r: *Replica, + fd: c_int, + digest: ?u64 = null, + fn take(t: *@This(), tag: u8, payload: []const u8) bool { + switch (std.enums.fromInt(wire.ServerTag, tag) orelse return false) { + .unit => t.r.confirm(payload), + .screen => if (t.r.screen(payload)) |reply| { + _ = sendScreen(t.fd, reply); + }, + .check => { + t.digest = (wire.decodeServer(tag, payload) catch return false).check; + return false; + }, + else => {}, + } + return true; + } + }; + var take: Take = .{ .r = r, .fd = j.fd }; + j.rest.run(gpa, j.fd, &take, Take.take); + r.settle(); + if (r.diverged) |w| std.debug.print("diverged: {s}\n", .{w}); + try std.testing.expect(r.diverged == null); + try std.testing.expectEqual(take.digest.?, r.digest()); + // Bytes: the session's reload at the join, of an emulator that held + // nothing yet (Pardes.init made it, the spawn is a first effect); the + // client loaded it from the dump and replayed every byte since. + try std.testing.expectEqual(reloads + @intFromBool(bytes), pardes.Term.reloads.n); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const rows = try pardes.Term.viewport(r.core().panes[shell].?.terminal.?, arena.allocator(), false); + try std.testing.expect(std.mem.indexOf(u8, rows[0], "first$") != null); + if (!bytes) return; + // One that comes after the shell's bytes: every side reloads. + var late: [2]c_int = undefined; + if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &late) != 0) return error.NoSocket; + defer _ = libc.close(late[1]); + ps.join(core, .{ .fd = late[0] }); + try std.testing.expectEqual(reloads + 2, pardes.Term.reloads.n); +} + test "bytes: a session's output past a unit's bound is cut into units under it, between two reads" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; @@ -5004,7 +5173,6 @@ test "a client joined from a dump moves through another view's pane as the sessi } test "a client joined from a dump makes a `/` query's rows as the session does, though only the session has drawn its owner" { - if (comptime !pardes.syntax.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, TestHost.host(), false); defer a.deinit(); @@ -6542,7 +6710,6 @@ test "a client joined from a dump makes a `/` query's rows as the session does, } } }; - if (comptime !pardes.syntax.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, .{ .vtable = &WorkerSearch.vtable }, false); defer a.deinit(); @@ -6703,3 +6870,206 @@ test "a far client's replay of a message its session's host stamped takes the se try agrees(a, r); try std.testing.expect(try shows(r.core(), "--:--:-- yanked x")); } + +// A script's `pty/run` in a shell (ninep/pty.zig): the open, the line, the +// marks that end it, its answer read and the open released, each a step of +// the session's, with a client that joined from a dump taking every unit. +test "a client joined from a dump takes a 9P pty/run in a shell as the session does: the line sent at the prompt, its end answered" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const gpa = std.testing.allocator; + const RunHost = struct { + fn taken(_: ?*anyopaque, _: pardes.Pane.Id) bool { + return false; + } + fn write(_: ?*anyopaque, _: pardes.Pane.Id, _: []const u8) void {} + const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .tty_taken = taken, .pty_write = write }; + }; + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, .{ .vtable = &RunHost.vtable }, false); + defer a.deinit(); + const r = try Replica.init(gpa, 1, try a.unit(0, 0), false); + defer r.deinit(); + const shell: u8 = for (a.core.panes, 0..) |slot, id| { + if (slot) |pane| if (pane.isTerminal()) break @intCast(id); + } else return error.NoShell; + const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07"; + a.output(.{ .output = .{ .pane = .at(shell), .bytes = prompt ++ "ls\r\n\x1b]133;C;aid=pardes\x07a b\r\n\x1b]133;D;0;aid=pardes\x07" ++ prompt } }); + r.confirm((try a.pending()).?); + r.settle(); + // A script's listing open, held across the join (a reader of /index). + { + const was = Stepping.begin(&a.t, null); + _ = a.core.serveFs(.{ .tag = 9, .op = .open, .node = @backingInt(pardes.ctlfs.TopFile.index) }); + was.end(); + a.seq += 1; + r.confirm(try a.unit(0, a.seq)); + r.settle(); + } + const joined = (try a.join(2, null)).?; + defer gpa.free(joined.dump); + r.confirm(joined.unit); + const late = try Replica.initDump(gpa, 2, joined.view, joined.dump, .{ .cols = 80, .rows = 24 }); + defer late.deinit(); + late.t.screen_state = false; + late.core().echo = null; + try std.testing.expectEqual(joined.digest, late.digest()); + const node = pardes.ctlfs.Node.of(a.core.panes[shell].?.serial, .pty_run); + const Serve = struct { + fn serve(s: *Authority, rs: []const *Replica, req: pardes.ctlfs.Req) !pardes.ctlfs.Reply { + const was = Stepping.begin(&s.t, null); + const reply = s.core.serveFs(req); + s.core.pump(s.host) catch {}; + was.end(); + s.seq += 1; + const u = try s.unit(0, s.seq); + for (rs) |x| { + x.confirm(u); + x.settle(); + } + return reply; + } + fn output(s: *Authority, rs: []const *Replica, pane: u8, bytes: []const u8) !void { + s.output(.{ .output = .{ .pane = .at(pane), .bytes = bytes } }); + const u = (try s.pending()).?; + for (rs) |x| { + x.confirm(u); + x.settle(); + } + } + }; + const both = [_]*Replica{ r, late }; + const h = (try Serve.serve(a, &both, .{ .tag = 1, .op = .open, .node = node, .omode = 2 })).handle; + _ = try Serve.serve(a, &both, .{ .tag = 2, .op = .write, .node = node, .handle = h, .data = "true\n" }); + try Serve.output(a, &both, shell, "true\r\n\x1b]133;C;aid=pardes\x07\x1b]133;D;0;aid=pardes\x07" ++ prompt); + const answer = try Serve.serve(a, &both, .{ .tag = 3, .op = .read, .node = node, .handle = h, .size = 64 }); + try std.testing.expectEqualStrings("exit 0\n", a.core.fsPayload(answer)); + _ = try Serve.serve(a, &both, .{ .tag = 4, .op = .release, .node = node, .handle = h, .opened = true }); + try Serve.output(a, &both, shell, "\x1b]133;A;cl=line;aid=pardes\x07"); + try agrees(a, r); + try agrees(a, late); +} + +// The same run with the terminals crossing as screen state (a session's +// clients', until the switch to bytes): a replica's emulator is the +// deltas', its marks not the session's. +test "a client of screen-state terminals takes a 9P pty/run in a shell as the session does" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const gpa = std.testing.allocator; + const RunHost = struct { + fn taken(_: ?*anyopaque, _: pardes.Pane.Id) bool { + return false; + } + fn write(_: ?*anyopaque, _: pardes.Pane.Id, _: []const u8) void {} + const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .tty_taken = taken, .pty_write = write }; + }; + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, .{ .vtable = &RunHost.vtable }, true); + defer a.deinit(); + var screens: Screens = .init(gpa); + defer screens.deinit(a.core); + const peer = try screens.addPeer(); + const r = try Replica.init(gpa, 1, try a.unit(0, 0), true); + defer r.deinit(); + const shell: u8 = for (a.core.panes, 0..) |slot, id| { + if (slot) |pane| if (pane.isTerminal()) break @intCast(id); + } else return error.NoShell; + const Step = struct { + var second: ?*Replica = null; + fn take(s: *Authority, sc: *Screens, p: u16, x: *Replica, u: []const u8) !void { + const gpa_ = std.testing.allocator; + const kept = try gpa_.dupe(u8, u); + defer gpa_.free(kept); + // The unit first, its screens at the frame after (Peers). + x.confirm(kept); + x.settle(); + if (second) |y| { + y.confirm(kept); + y.settle(); + } + try deliver(s, sc, p, x, .flush); + if (second) |y| try deliver(s, sc, p + 1, y, .flush); + } + fn serve(s: *Authority, sc: *Screens, p: u16, x: *Replica, req: pardes.ctlfs.Req) !pardes.ctlfs.Reply { + const was = Stepping.begin(&s.t, null); + const reply = s.core.serveFs(req); + s.core.pump(s.host) catch {}; + was.end(); + s.seq += 1; + try take(s, sc, p, x, try s.unit(0, s.seq)); + return reply; + } + fn output(s: *Authority, sc: *Screens, p: u16, x: *Replica, pane: u8, bytes: []const u8) !void { + s.output(.{ .output = .{ .pane = .at(pane), .bytes = bytes } }); + try take(s, sc, p, x, (try s.pending()).?); + } + }; + const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07"; + try Step.output(a, &screens, peer, r, shell, prompt ++ "ls\r\n\x1b]133;C;aid=pardes\x07a b\r\n\x1b]133;D;0;aid=pardes\x07" ++ prompt); + // A second client joins now, from the session's dump. + const joined = (try a.join(2, null)).?; + defer gpa.free(joined.dump); + try Step.take(a, &screens, peer, r, joined.unit); + const late = try Replica.initDump(gpa, 2, joined.view, joined.dump, .{ .cols = 80, .rows = 24 }); + defer late.deinit(); + const peer2 = try screens.addPeer(); + try deliver(a, &screens, peer2, late, .flush); + Step.second = late; + defer Step.second = null; + const node = pardes.ctlfs.Node.of(a.core.panes[shell].?.serial, .pty_run); + for (0..2) |_| { + const h = (try Step.serve(a, &screens, peer, r, .{ .tag = 1, .op = .open, .node = node, .omode = 2 })).handle; + _ = try Step.serve(a, &screens, peer, r, .{ .tag = 2, .op = .write, .node = node, .handle = h, .data = "true\n" }); + try Step.output(a, &screens, peer, r, shell, "true\r\n\x1b]133;C;aid=pardes\x07\x1b]133;D;0;aid=pardes\x07" ++ prompt); + const answer = try Step.serve(a, &screens, peer, r, .{ .tag = 3, .op = .read, .node = node, .handle = h, .size = 64 }); + try std.testing.expectEqualStrings("exit 0\n", a.core.fsPayload(answer)); + _ = try Step.serve(a, &screens, peer, r, .{ .tag = 4, .op = .release, .node = node, .handle = h, .opened = true }); + } + try agrees(a, r); + try agrees(a, late); +} + +// Del with a pane above and below asks which way the space goes, its +// question shown once a delay is up (builtins.zig): its time was the +// host's clock read in the step, an answering entry a speculation stops at. +test "a far client's Del with panes above and below is applied at once, and its question's time is the session's" { + const gpa = std.testing.allocator; + const Clocked = struct { + var now_ns: u64 = 7 * std.time.ns_per_s; + fn now(_: ?*anyopaque) u64 { + return now_ns; + } + const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .now = now }; + }; + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 30, .file = "mise.toml" }, .{ .vtable = &Clocked.vtable }, false); + defer a.deinit(); + _ = try a.local(.{ .command = "New" }); + const mid = a.core.view().active; + _ = try a.local(.{ .command = "New" }); + { + const was = Stepping.begin(&a.t, null); + defer was.end(); + a.core.view().active = mid; + } + const r = try joinedFresh(a); + defer r.deinit(); + var sent: std.ArrayListUnmanaged([]u8) = .empty; + defer { + for (sent.items) |m| gpa.free(m); + sent.deinit(gpa); + } + Clocked.now_ns += std.time.ns_per_s; + try key(r, ' ', &sent); + try key(r, 'd', &sent); + try std.testing.expectEqual(@as(usize, 2), r.applied); + try std.testing.expect(r.core().panes[mid].?.prompt == .del_side); + for (sent.items) |m| { + r.confirm(try a.take(m)); + r.settle(); + } + try std.testing.expectEqual(@as(u32, 0), r.stats.mispredicted); + try agrees(a, r); + // The question shows a delay after it was asked, on the session's clock. + a.pump(); + r.confirm((try a.pending()).?); + r.settle(); + try agrees(a, r); + try std.testing.expectEqual(Clocked.now_ns + pardes.config.del_question_delay_ns, r.core().panes[mid].?.question_due_ns); +} diff --git a/core/root.zig b/core/root.zig index a57934a6..5300ce93 100644 --- a/core/root.zig +++ b/core/root.zig @@ -103,8 +103,6 @@ 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 isolated = @import("pardes_options").isolated; - pub const font_picker = platform == .gui or platform == .macos; /// Whose turn it is with the core (Turn.zig): one per process, like the @@ -600,10 +598,13 @@ test "nothing of a core is a process global: every container-level var in core/ /// 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), and -/// `@import("dev")` and `@import("runtime")`, 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. +/// 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 }{ @@ -629,11 +630,11 @@ const machine_lines = [_]struct { []const u8, usize, []const u8 }{ .{ "hunks.zig", 1, "a test helper's file read" }, .{ "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", 70, "the client and session engines: sockets, threads, clocks, the blob cache, traces" }, + .{ "replica.zig", 73, "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", 11, "the tape's own files and host_io's types: a recording, a replay; the `io` a tape hands a site's body" }, + .{ "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" }, @@ -645,7 +646,7 @@ const machine_lines = [_]struct { []const u8, usize, []const u8 }{ /// 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" }; + 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); diff --git a/core/syntax.zig b/core/syntax.zig index ba3851ab..19831ec2 100644 --- a/core/syntax.zig +++ b/core/syntax.zig @@ -7,17 +7,11 @@ const regexp = @import("regexp.zig"); const c_heap = @import("c_heap"); const diff = @import("diff.zig"); -pub const enabled = config.grammars != .disabled; -const minimal_grammars = config.grammars == .minimal or config.grammars == .full; +const minimal_grammars = config.grammars != .none; const full_grammars = config.grammars == .full; -pub const ts = if (enabled) @import("tree-sitter") else struct { - pub const Language = opaque {}; - pub const Query = opaque {}; - pub const Parser = opaque {}; - pub const QueryCursor = opaque {}; -}; -const ts_queries = if (enabled) @import("ts_queries") else struct {}; +pub const ts = @import("tree-sitter"); +const ts_queries = @import("ts_queries"); const LanguageFn = *const fn () callconv(.c) *const ts.Language; @@ -43,7 +37,6 @@ const Spec = struct { fn grammarSelected(comptime g: grammar_manifest.Grammar) bool { return switch (g.tier) { - .zig => enabled, .minimal => minimal_grammars, .full => full_grammars, }; @@ -92,28 +85,24 @@ extern fn ts_set_allocator( ) void; pub fn start(gpa: std.mem.Allocator) void { - if (comptime enabled) { - std.debug.assert(!syntax_started); - stop(); - syntax_allocator = gpa; - syntax_started = true; - ts_set_allocator(syntax_heap.malloc, syntax_heap.calloc, syntax_heap.realloc, syntax_heap.free); - } + std.debug.assert(!syntax_started); + stop(); + syntax_allocator = gpa; + syntax_started = true; + ts_set_allocator(syntax_heap.malloc, syntax_heap.calloc, syntax_heap.realloc, syntax_heap.free); } pub fn stop() void { - if (comptime enabled) { - for (&specs) |*spec| dropSpec(spec); - forgetLanguages(); - for (&diff_pieces) |*slot| { - if (slot.*) |piece| syntax_allocator.free(piece.styles); - slot.* = null; - } - diff_clock = 0; - ts_set_allocator(null, null, null, null); - syntax_started = false; - syntax_allocator = undefined; + for (&specs) |*spec| dropSpec(spec); + forgetLanguages(); + for (&diff_pieces) |*slot| { + if (slot.*) |piece| syntax_allocator.free(piece.styles); + slot.* = null; } + diff_clock = 0; + ts_set_allocator(null, null, null, null); + syntax_started = false; + syntax_allocator = undefined; } const Selected = struct { @@ -254,7 +243,6 @@ fn runQuery(styles: []u8, sel: Selected, tree: *ts.Tree, base: usize) void { pub fn highlightFileRange(gpa: std.mem.Allocator, path: []const u8, content: []const u8, start_raw: usize, end_raw: usize) ![]u8 { const zone = tracy.zone(@src(), "highlightFileRange"); defer zone.end(); - if (!enabled) return &.{}; const selected = (try forExt(std.Io.Dir.path.extension(path))) orelse return &.{}; const start_byte = @min(start_raw, content.len); const end_byte = @max(start_byte, @min(end_raw, content.len)); @@ -269,7 +257,6 @@ pub fn highlightFileRange(gpa: std.mem.Allocator, path: []const u8, content: []c /// no injections (markdown's and typst's reach the shared parsers), made /// ready here, on the loop, so the worker only reads its query. pub fn readyApart(path: []const u8) bool { - if (!enabled) return false; const selected = (forExt(std.Io.Dir.path.extension(path)) catch return false) orelse return false; return !std.mem.eql(u8, selected.name, "markdown") and !std.mem.eql(u8, selected.name, "typst"); } @@ -278,7 +265,6 @@ pub fn readyApart(path: []const u8) bool { /// parse and a query cursor of its own, the grammar's query shared (it /// is only read); `halt` ends the parse early. After `readyApart`. pub fn highlightApart(gpa: std.mem.Allocator, path: []const u8, source: []const u8, halt: *const std.atomic.Value(bool)) ![]u8 { - if (comptime !enabled) return &.{}; const shared = (try forExt(std.Io.Dir.path.extension(path))) orelse return &.{}; const tree = try parseApart(shared.lang, source, halt); defer tree.destroy(); @@ -335,7 +321,6 @@ pub const ContextDeclaration = struct { }; pub fn supportsPath(path: []const u8) bool { - if (!enabled) return false; return byExt(std.Io.Dir.path.extension(path)) != null; } @@ -345,7 +330,6 @@ pub fn supportsPath(path: []const u8) bool { /// since its parse (`editTree`), the parse reuses what those left alone: a /// character typed into a 9k-line file costs a few hundred µs, not 50 ms. pub fn parseTree(path: []const u8, content: []const u8, old: ?*anyopaque) ?*anyopaque { - if (!enabled) return null; const selected = (forExt(std.Io.Dir.path.extension(path)) catch return null) orelse return null; const tree = selected.parser.parseString(content, @ptrCast(@alignCast(old))) orelse return null; if (held_trees) |h| h.born.append(h.meta, @ptrCast(tree)) catch {}; @@ -357,7 +341,6 @@ pub fn parseTree(path: []const u8, content: []const u8, old: ?*anyopaque) ?*anyo /// places follow the edit; what it says of the edited bytes is stale until /// `parseTree` with it. pub fn editTree(tree: *anyopaque, before: []const u8, old: []const u8, ins: []const u8) void { - if (!enabled) return; const from = advance(.{ .row = 0, .column = 0 }, before); const t: *ts.Tree = @ptrCast(@alignCast(tree)); t.edit(.{ @@ -387,7 +370,6 @@ pub const HeldTrees = struct { }; pub fn freeTree(tree: *anyopaque) void { - if (!enabled) return; if (held_trees) |h| { for (h.born.items, 0..) |t, i| if (t == tree) { _ = h.born.swapRemove(i); @@ -400,7 +382,6 @@ pub fn freeTree(tree: *anyopaque) void { } pub fn destroyTree(tree: *anyopaque) void { - if (!enabled) return; const t: *ts.Tree = @ptrCast(@alignCast(tree)); t.destroy(); } @@ -412,7 +393,7 @@ pub const Span = struct { from: usize, to: usize }; /// The spans `walk` takes the byte range [from, to) to, into `out`; `at` is /// the range's cursor. None when the tree has nothing to say there. pub fn walkNodes(tree_ptr: *anyopaque, walk: NodeWalk, from: usize, to: usize, at: usize, out: []Span) usize { - if (!enabled or out.len == 0) return 0; + if (out.len == 0) return 0; const tree: *const ts.Tree = @ptrCast(@alignCast(tree_ptr)); const lo: u32 = @intCast(@min(from, std.math.maxInt(u32))); const hi: u32 = @intCast(@min(to, std.math.maxInt(u32))); @@ -497,7 +478,6 @@ fn objectQuery(path: []const u8) ?*ts.Query { /// The grammar's indent query for `path` (core/indent.zig) and the /// grammar's name; null when it has none. pub fn indentQuery(path: []const u8) ?struct { *ts.Query, []const u8 } { - if (!enabled) return null; const spec = specFor(path) orelse return null; return .{ lazyQuery(spec, &spec.indents) orelse return null, spec.name }; } @@ -563,7 +543,6 @@ fn matchSpan(q: *const ts.Query, match: anytype, capture: u32, text: []const u8) /// `mi`/`ma`: the smallest `object.inside` (or `.around`) holding byte `at` /// (helix textobject_treesitter). None without a query or such an object. pub fn objectAt(path: []const u8, tree_ptr: *anyopaque, text: []const u8, object: Object, around: bool, at: usize) ?Span { - if (!enabled) return null; const q = objectQuery(path) orelse return null; var buf: [32]u8 = undefined; const want = std.fmt.bufPrint(&buf, "{s}.{s}", .{ objectName(object), if (around) "around" else "inside" }) catch return null; @@ -587,7 +566,6 @@ pub fn objectAt(path: []const u8, tree_ptr: *anyopaque, text: []const u8, object /// previous one ending before it (helix goto_treesitter_object), from the /// first of `.movement`, `.around`, `.inside` the query names. pub fn objectNext(path: []const u8, tree_ptr: *anyopaque, text: []const u8, object: Object, forward: bool, at: usize) ?Span { - if (!enabled) return null; const q = objectQuery(path) orelse return null; var buf: [32]u8 = undefined; const capture = for ([_][]const u8{ "movement", "around", "inside" }) |kind| { @@ -628,7 +606,7 @@ pub const SourceAnalysis = struct { }; pub fn analyzeSource(gpa: std.mem.Allocator, path: []const u8, content: []const u8, want_declarations: bool, want_colors: bool) !SourceAnalysis { - if (!enabled or content.len == 0 or (!want_declarations and !want_colors)) return .{}; + if (content.len == 0 or (!want_declarations and !want_colors)) return .{}; const selected = (try forExt(std.Io.Dir.path.extension(path))) orelse return .{}; const tree = selected.parser.parseString(content, null) orelse return .{}; defer tree.destroy(); @@ -652,7 +630,6 @@ pub fn contextDeclarations(gpa: std.mem.Allocator, path: []const u8, content: [] /// (`parseApart`). `halt` ends the parse and the walk early /// (error.Canceled): a 1.2 MB file is seconds in a Debug build. pub fn declarationsApart(gpa: std.mem.Allocator, path: []const u8, content: []const u8, halt: *const std.atomic.Value(bool)) ![]ContextDeclaration { - if (comptime !enabled) return &.{}; if (content.len == 0) return &.{}; const ext = std.Io.Dir.path.extension(path); const spec = specs: for (&specs) |*spec| { @@ -796,7 +773,6 @@ pub fn highlightLocations(gpa: std.mem.Allocator, content: []const u8, start_byt const start_byte = @min(start_byte_raw, content.len); const end_byte = @max(start_byte, @min(end_byte_raw, content.len)); const source = content[start_byte..end_byte]; - if (!enabled) return &.{}; const styles = try gpa.alloc(u8, source.len); errdefer gpa.free(styles); @memset(styles, 0); @@ -829,7 +805,7 @@ pub fn highlightLocations(gpa: std.mem.Allocator, content: []const u8, start_byt /// padded location column. This also colors context whose location is hidden. /// Consecutive source rows share one parse, retaining multiline syntax. pub fn highlightLocationRows(gpa: std.mem.Allocator, content: []const u8, rows: []const locations.Row) ![]u8 { - if (!enabled or content.len == 0 or rows.len == 0) return &.{}; + if (content.len == 0 or rows.len == 0) return &.{}; const styles = try gpa.alloc(u8, content.len); errdefer gpa.free(styles); @memset(styles, 0); @@ -1111,7 +1087,7 @@ const DiffWindow = struct { }; fn paintDiffPiece(gpa: std.mem.Allocator, window: DiffWindow, bytes: []const u8, at: usize, kinds: []const diff.Kind, path: []const u8) !void { - const selected: ?Selected = if (enabled and syntax_started) (forExt(std.Io.Dir.path.extension(path)) catch null) else null; + const selected: ?Selected = if (syntax_started) (forExt(std.Io.Dir.path.extension(path)) catch null) else null; if (selected) |sel| { const hash = std.hash.Wyhash.hash(std.hash.Wyhash.hash(0, sel.name), bytes); diff_clock += 1; @@ -1269,7 +1245,6 @@ test { } test "every vendored textobject and indent query compiles against its grammar" { - if (!enabled) return; var failed: usize = 0; for (&specs) |*spec| for ([_]Lazy{ spec.objects, spec.indents }, [_][]const u8{ "textobjects", "indents" }) |lazy, what| { if (lazy.src.len == 0) continue; @@ -1285,7 +1260,6 @@ test "every vendored textobject and indent query compiles against its grammar" { } test "syntax context nested Zig containers and multiline function signatures" { - if (!enabled) return; const gpa = std.testing.allocator; start(gpa); defer stop(); @@ -1317,7 +1291,7 @@ test "syntax context nested Zig containers and multiline function signatures" { } test "syntax context Python class and function body excludes first statement" { - if (!enabled or !full_grammars) return; + if (!full_grammars) return; const gpa = std.testing.allocator; start(gpa); defer stop(); @@ -1330,7 +1304,6 @@ test "syntax context Python class and function body excludes first statement" { } test "syntax context multiline bindings and C++ namespaces preserve declaration starts" { - if (!enabled) return; const gpa = std.testing.allocator; start(gpa); defer stop(); @@ -1340,7 +1313,7 @@ test "syntax context multiline bindings and C++ namespaces preserve declaration try std.testing.expectEqual(@as(usize, 1), zig_declarations.len); try std.testing.expectEqual(@as(usize, 0), zig_declarations[0].start_line); try std.testing.expectEqual(@as(usize, 1), zig_declarations[0].header_end_line); - if (!minimal_grammars and !full_grammars) return; + if (!minimal_grammars) return; const cpp_source = "namespace example {\nstruct Outer {\n int run() {\n return 1;\n }\n};\n}\n"; const cpp_declarations = try contextDeclarations(gpa, "nested.cpp", cpp_source); defer gpa.free(cpp_declarations); @@ -1352,7 +1325,7 @@ test "syntax context multiline bindings and C++ namespaces preserve declaration } test "syntax context Rust modules impls and methods remain nested" { - if (!enabled or !full_grammars) return; + if (!full_grammars) return; const gpa = std.testing.allocator; start(gpa); defer stop(); @@ -1368,7 +1341,7 @@ test "syntax context Rust modules impls and methods remain nested" { } test "syntax formatted locations color hidden context and preserve multiline source" { - if (!enabled or (!minimal_grammars and !full_grammars)) return; + if (!minimal_grammars) return; const gpa = std.testing.allocator; start(gpa); defer stop(); @@ -1393,7 +1366,7 @@ test "syntax formatted locations color hidden context and preserve multiline sou } test "syntax formatted locations separate alignment from Markdown indentation" { - if (!enabled or !full_grammars) return; + if (!full_grammars) return; const gpa = std.testing.allocator; start(gpa); defer stop(); @@ -1409,7 +1382,6 @@ test "syntax formatted locations separate alignment from Markdown indentation" { } test "syntax a results row is coloured by the file its location names" { - if (!enabled) return; start(std.testing.allocator); defer stop(); const gpa = std.testing.allocator; @@ -1432,7 +1404,6 @@ test "syntax a results row is coloured by the file its location names" { } test "syntax a buffer with no locations in it keeps no highlights at all" { - if (!enabled) return; start(std.testing.allocator); defer stop(); const content = "nothing has been said yet\n0: save: AccessDenied (x2)\n"; @@ -1460,7 +1431,7 @@ test "syntax codeAfterLocation takes whole-token locations and nothing else" { } test "syntax default full grammar set highlights Typst source" { - if (!enabled or !full_grammars) return; + if (!full_grammars) return; start(std.testing.allocator); defer stop(); @@ -1483,7 +1454,7 @@ test "syntax default full grammar set highlights Typst source" { } test "syntax Typst markup constructs paint and raw blocks inject their language" { - if (!enabled or !full_grammars) return; + if (!full_grammars) return; start(std.testing.allocator); defer stop(); @@ -1527,7 +1498,7 @@ test "syntax Typst markup constructs paint and raw blocks inject their language" } test "syntax markdown highlights markup, injects inline spans and fenced code blocks" { - if (!enabled or !full_grammars) return; + if (!full_grammars) return; start(std.testing.allocator); defer stop(); @@ -1559,7 +1530,7 @@ test "syntax markdown highlights markup, injects inline spans and fenced code bl } test "syntax inline fast path agrees with full Markdown query" { - if (!enabled or !full_grammars) return; + if (!full_grammars) return; start(std.testing.allocator); defer stop(); const selected = (try forLang("markdown_inline")).?; @@ -1606,7 +1577,7 @@ test "syntax inline fast path agrees with full Markdown query" { } test "syntax plain Markdown keeps block styles without starting the inline parser" { - if (!enabled or !full_grammars) return; + if (!full_grammars) return; start(std.testing.allocator); defer stop(); const source = "# Heading\n\nPlain prose.\n\n indented code\n"; @@ -1648,7 +1619,6 @@ test "syntax highlightDiff colors unified diff lines by prefix" { } test "syntax a Zig hunk is coloured as Zig, each side parsed whole" { - if (!enabled) return; start(std.testing.allocator); defer stop(); const diff_text = @@ -1689,7 +1659,7 @@ test "syntax a Zig hunk is coloured as Zig, each side parsed whole" { } test "syntax a Python hunk is coloured as Python" { - if (!enabled or !full_grammars) return; + if (!full_grammars) return; start(std.testing.allocator); defer stop(); const diff_text = @@ -1710,7 +1680,6 @@ test "syntax a Python hunk is coloured as Python" { } test "syntax a deleted file's lines are coloured in its language" { - if (!enabled) return; start(std.testing.allocator); defer stop(); const diff_text = @@ -1730,7 +1699,6 @@ test "syntax a deleted file's lines are coloured in its language" { } test "syntax a hunk in no known language keeps the line colours" { - if (!enabled) return; start(std.testing.allocator); defer stop(); const diff_text = @@ -1747,7 +1715,6 @@ test "syntax a hunk in no known language keeps the line colours" { } test "syntax git diff output in a command pane is told and coloured by its rows" { - if (!enabled) return; start(std.testing.allocator); defer stop(); // A command pane's rows: its command line, then git's output, with one @@ -1780,7 +1747,6 @@ test "syntax git diff output in a command pane is told and coloured by its rows" } test "syntax a section's small hunks share one parse" { - if (!enabled) return; const gpa = std.testing.allocator; start(gpa); defer stop(); @@ -1802,7 +1768,6 @@ test "syntax a section's small hunks share one parse" { } test "syntax a hunk painted once is kept, and a long one is parsed in pieces" { - if (!enabled) return; const gpa = std.testing.allocator; start(gpa); defer stop(); @@ -1832,7 +1797,6 @@ test "syntax a hunk painted once is kept, and a long one is parsed in pieces" { } test "syntax result fragments preserve source indentation and inline markup" { - if (!enabled) return; start(std.testing.allocator); defer stop(); const fixtures = [_]struct { path: []const u8, source: []const u8 }{ @@ -1862,7 +1826,6 @@ test "syntax result fragments preserve source indentation and inline markup" { } test "syntax query filtering preserves upstream colors" { - if (!enabled) return; var allocator: std.heap.DebugAllocator(.{ .stack_trace_frames = 0, .safety = true }) = .init; defer if (allocator.deinit() != .ok) @panic("leaked syntax query allocations"); start(allocator.allocator()); @@ -1893,7 +1856,6 @@ test "syntax query filtering preserves upstream colors" { } test "syntax Zig keyword captures cover both bytes beyond line ten thousand" { - if (!enabled) return; start(std.testing.allocator); defer stop(); const code = "pub fn main() void {\n if (true) return;\n}\n"; @@ -1911,7 +1873,6 @@ test "syntax Zig keyword captures cover both bytes beyond line ten thousand" { } test "syntax allocator switching clears default-runtime caches" { - if (!enabled) return; const source = "fn main() void {}"; const initial = try highlightFileRange(std.testing.allocator, "a.zig", source, 0, source.len); std.testing.allocator.free(initial); @@ -1927,7 +1888,7 @@ test "syntax allocator switching clears default-runtime caches" { } test "syntax location context snapshots retain omitted multiline comment scope" { - if (!enabled or (!minimal_grammars and !full_grammars)) return; + if (!minimal_grammars) return; const gpa = std.testing.allocator; start(gpa); defer stop(); @@ -1953,7 +1914,6 @@ test "syntax location context snapshots retain omitted multiline comment scope" } test "syntax declaration locations clear snapshots without muting ordinary context" { - if (!enabled) return; const gpa = std.testing.allocator; start(gpa); defer stop(); @@ -1973,7 +1933,7 @@ test "syntax declaration locations clear snapshots without muting ordinary conte } test "syntax stacked addresses do not split multiline source groups" { - if (!enabled or (!minimal_grammars and !full_grammars)) return; + if (!minimal_grammars) return; const gpa = std.testing.allocator; start(gpa); defer stop(); @@ -1998,7 +1958,6 @@ test "syntax stacked addresses do not split multiline source groups" { } test "syntax source analysis preserves declarations and injected colors" { - if (!enabled) return; const gpa = std.testing.allocator; start(gpa); defer stop(); @@ -2059,7 +2018,7 @@ test "syntax source analysis preserves declarations and injected colors" { } test "tables are the pipe_tables tree-sitter finds" { - if (!enabled or !full_grammars) return; + if (!full_grammars) return; start(std.testing.allocator); defer stop(); const Tables = @import("Tables.zig"); @@ -2128,7 +2087,6 @@ test "tables are the pipe_tables tree-sitter finds" { } test "a kept tree told its edits parses to the fresh parse's tree, places and all" { - if (!enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const a = "const std = @import(\"std\");\n\nfn f(x: u32) u32 {\n return x;\n}\n\ntest \"t\" {\n _ = f(1);\n}\n"; const old_tree = parseTree("a.zig", a, null) orelse return error.NoTree; @@ -2168,7 +2126,6 @@ test "a kept tree told its edits parses to the fresh parse's tree, places and al } test "syntax: a grammar handed in at run time colours and walks as the one compiled in" { - if (!enabled) return error.SkipZigTest; const gpa = std.testing.allocator; start(gpa); defer stop(); diff --git a/core/tape.zig b/core/tape.zig index f705636f..7f28621e 100644 --- a/core/tape.zig +++ b/core/tape.zig @@ -25,7 +25,8 @@ const pardes = @import("root.zig"); const walk = @import("walk.zig"); const host_io = @import("dev").host_io; const Pardes = pardes.Pardes; -const VTable = pardes.Host.VTable; +const Host = pardes.Host; +const VTable = Host.VTable; const libc = std.c; pub var on: ?*Tape = null; @@ -160,7 +161,7 @@ pub const results = .{ // Recent's entry for a closed jump, the closed panes' names. ?@import("Store.zig").Record, ?@import("recent.zig").Entry, []const @import("Store.zig").Named, - @import("Kind.zig").Outcome, + @import("Kind.zig").Outcome, pardes.Term.Prompt, }; /// What a host reports to the core as failed (`shell_failed`, `save_failed`, @@ -185,7 +186,7 @@ fn ErrorOf(comptime f: anytype) type { pub const shape = blk: { var types: []const type = &.{ Input, Site, []const u64, struct { u8, u64 } }; for (results) |R| types = types ++ .{R}; - for (host_fns) |f| types = types ++ .{@typeInfo(@typeInfo(@typeInfo(@FieldType(VTable, f)).optional.child).pointer.child).@"fn".return_type.?}; + for (host_fns) |f| types = types ++ .{Host.Ret(@field(Host.Fn, f))}; for (watched) |name| types = types ++ .{Watched(name)}; break :blk walk.shape(types); }; @@ -245,18 +246,24 @@ pub const Tape = struct { /// call out of it is the host's to answer. host_side: bool = true, depth: u32 = 0, - vtable: VTable = .{}, // Recording. fd: c_int = -1, buf: std.ArrayList(u8) = .empty, scratch: std.Io.Writer.Allocating, - real: pardes.Host = .{}, + /// The host whose functions were last said (`noteHost`). + real: Host = .{}, seen: [watched.len]u64 = @splat(0), // Replaying. in: walk.Reader = .{ .bytes = &.{} }, arena: std.heap.ArenaAllocator, last_ret: walk.Reader = .{ .bytes = &.{} }, + /// Which functions the session's host has, a bit each in the table's + /// order (`Host.mask`): what a replica's core answers by (`has`). mask: u64 = 0, + /// A replica's (a client's, a replay's), from its first replay or its + /// join (`replayUnit`, `adoptCore`): its core has no host, and asks + /// the tape what the session's has, between its steps too (a frame). + replica: bool = false, skips_render: bool = false, digests: u64 = 0, diverged: ?[]const u8 = null, @@ -388,38 +395,17 @@ pub const Tape = struct { inline for (watched, 0..) |name, i| t.seen[i] = walk.digest(Watched(name), watchedOf(p, name)); } - /// The host's functions go through the tape while it records, whoever - /// set `p.host` last. - fn wrap(t: *Tape, p: *Pardes) void { - if (p.host.vtable == &t.vtable) return; - // The same host given again (each pump is given its host): only - // the wrapper put back. - if (p.host.vtable == t.real.vtable and p.host.ctx == t.real.ctx) { - p.host = .{ .ctx = t, .vtable = &t.vtable }; - return; - } + /// Which functions the session's host has, said at an entry whose + /// core holds another host than the last said (each pump is given its + /// host again: then nothing). + fn noteHost(t: *Tape, p: *const Pardes) void { + if (p.host.vtable == t.real.vtable and p.host.ctx == t.real.ctx) return; t.real = p.host; - var mask: u64 = 0; - inline for (host_fns, 0..) |f, i| if (@field(t.real.vtable.*, f) != null) { - mask |= @as(u64, 1) << i; - }; - p.host = t.hostOf(mask); - const set: struct { u8, u64 } = .{ set_mask, mask }; + t.mask = p.host.mask(); + const set: struct { u8, u64 } = .{ set_mask, t.mask }; t.record(.set, @TypeOf(set), &set); } - /// The tape as a host with these functions. - fn hostOf(t: *Tape, mask: u64) pardes.Host { - t.mask = mask; - t.vtable = .{}; - inline for (host_fns, 0..) |f, i| if (mask & (@as(u64, 1) << i) != 0 or - (t.skips_render and comptime std.mem.eql(u8, f, "watched"))) - { - @field(t.vtable, f) = &Wrap(i).f; - }; - return .{ .ctx = t, .vtable = &t.vtable }; - } - fn enterInput(t: *Tape, p: ?*Pardes, input: *const Input) Entered { if (!t.host_side) return .{}; t.host_side = false; @@ -428,7 +414,7 @@ pub const Tape = struct { if (p) |core| { if (t.core == null) t.core = core; t.noteWrites(); - t.wrap(core); + t.noteHost(core); } // A terminal's output crosses as screen state, not as its bytes. if (t.screen_state and input.* == .update and input.update.args[0] == .output) { @@ -445,7 +431,7 @@ pub const Tape = struct { if (t.replay) return; if (p) |core| if (t.core == null) { t.core = core; - t.wrap(core); + t.noteHost(core); }; t.record(.done, void, &{}); if ((t.depth == 0 or t.every) and !t.no_digest and !t.unit_digests) recordDigest(t); @@ -653,8 +639,7 @@ pub const Tape = struct { fn applySet(t: *Tape, r: *walk.Reader) void { const which = (r.take(1) catch return)[0]; if (which == set_mask) { - const host = t.hostOf(std.mem.bytesToValue(u64, r.take(8) catch return)); - if (t.core) |p| p.host = host; + t.mask = std.mem.bytesToValue(u64, r.take(8) catch return); return; } const p = t.core orelse return; @@ -697,7 +682,6 @@ pub const Tape = struct { .init_from_dump => |d| pardes.dump.initFromDump(gpa, opts, d.bytes), else => unreachable, } catch |err| return t.diverge("init failed: {t}", .{err}); - t.core.?.host = t.hostOf(t.mask); return t.finishInput(); }, else => {}, @@ -709,7 +693,6 @@ pub const Tape = struct { const nc = pardes.dump.restore(p, a.args[0], a.args[1]) catch |err| return t.diverge("restore failed: {t}", .{err}); t.core = nc; nc.tape = t; - nc.host = t.hostOf(t.mask); }, // The session is over (or the core a Restore replaced is // freed): nothing done now is compared. @@ -720,7 +703,7 @@ pub const Tape = struct { } return t.skip(); }, - .pump => p.pump(t.hostOf(t.mask)) catch {}, + .pump => p.pump(.{}) catch {}, .render => if (t.skips_render) return t.skip() else { _ = p.frame_arena.reset(.retain_capacity); _ = p.render(p.frame_arena.allocator()) catch {}; @@ -857,6 +840,26 @@ pub const Tape = struct { return r; } + /// One call out to the session's host, `f(args)`: made and recorded + /// with what it answered; answered from the tape on a replay; refused + /// to a speculation, or recorded as made (`keeps_stopping`). Null: the + /// session's host has no such function. + pub inline fn host(t: *Tape, p: *const Pardes, comptime f: Host.Fn, args: Host.Args(f)) ?Host.Ret(f) { + // Nobody records: the call it always was. + if (t.through) return p.host.call(f, args); + if (!t.has(p, f)) return null; + return hostCall(t, p, f, args); + } + + /// Whether the session's host has `f`, asked apart from a call: a + /// replica's core has no host, and answers as its session's did. + pub fn has(t: *const Tape, p: *const Pardes, comptime f: Host.Fn) bool { + if (!t.replica) return p.host.has(f); + // A replica that never draws asks, and is told no one watches (`hostCall`). + if (comptime f == .watched) if (t.skips_render) return true; + return t.mask & (@as(u64, 1) << @backingInt(f)) != 0; + } + /// Asked by `turn.yield`: a syscall a replica must never make. pub fn replaying(t: *const Tape) bool { return t.replay or t.speculating; @@ -922,7 +925,7 @@ pub const Tape = struct { p.tape = t; if (t.replay or t.through) return; t.core = p; - t.wrap(p); + t.noteHost(p); } /// Whether `p` is the core being recorded (a Restore's old one is not). @@ -1138,100 +1141,64 @@ fn tagOf(comptime entry: anytype, comptime Made: type) [:0]const u8 { return found orelse @compileError("tape: no variant of Input names the entry " ++ @typeName(Made) ++ " (a line `<tag>: Args(<the entry>)` in tape.Input)"); } -/// The Host function `i`, through the tape. -fn Wrap(comptime i: usize) type { - const Fn = @typeInfo(@typeInfo(@FieldType(VTable, host_fns[i])).optional.child).pointer.child; - const info = @typeInfo(Fn).@"fn"; - const R = info.return_type.?; - const P = info.param_types; - return switch (P.len) { - 1 => struct { - fn f(ctx: ?*anyopaque) R { - return hostCall(i, R, ctx, .{}); - } - }, - 2 => struct { - fn f(ctx: ?*anyopaque, a: P[1].?) R { - return hostCall(i, R, ctx, .{a}); - } - }, - 3 => struct { - fn f(ctx: ?*anyopaque, a: P[1].?, b: P[2].?) R { - return hostCall(i, R, ctx, .{ a, b }); - } - }, - 4 => struct { - fn f(ctx: ?*anyopaque, a: P[1].?, b: P[2].?, c: P[3].?) R { - return hostCall(i, R, ctx, .{ a, b, c }); - } - }, - 5 => struct { - fn f(ctx: ?*anyopaque, a: P[1].?, b: P[2].?, c: P[3].?, d: P[4].?) R { - return hostCall(i, R, ctx, .{ a, b, c, d }); - } - }, - else => @compileError("tape: a host function of more arguments"), - }; -} - /// The Host entries that return nothing and still stop a speculation, each /// with why; a speculation records any other as made and goes on (`hostCall`). /// The entries that answer stop by nature: the answer is the session's. -const keeps_stopping = .{ +const keeps_stopping = [_]Host.Fn{ // A shell's input: a device by the user's line (a far shell may feel // like ssh), and off the tape with screen-state terminals. - "pty_write", + .pty_write, // Its host says into the core on every call that the shell started // and where (host_io.forkShell: acknowledgeShell, setCwd), and gives // the turn away: a rollback every time, nothing gained. - "spawn", + .spawn, // Its host writes the core outside any record (exec.reapplyInitFile, // Plumb.saved, fs.writeSelf) besides `saved` or the failure, every call. - "write_file", + .write_file, // Their hosts say done or failed into the core on every call // (setLastDump, dumpFailed; setMessage, reportError): a rollback every // time, nothing gained. - "write_dump", - "dump_themes", + .write_dump, + .dump_themes, // The session's own: it execs itself after the step, carries a window // away, or lets its frontend go (writing `frontend` and `unattended`). - "upgrade", - "hand_over", - "detach", + .upgrade, + .hand_over, + .detach, // The loop's, never a step's. - "wait_input", - "present", - "post_present", - "poll_frame", + .wait_input, + .present, + .post_present, + .poll_frame, }; -fn keepsStopping(comptime name: []const u8, args: anytype) bool { +fn keepsStopping(comptime f: Host.Fn, args: Host.Args(f)) bool { // Turned on, its host loads the theme file into the core outside any // record (colors.loadThemeFile: custom_theme, theme_file_loaded); // turned off it only lets the file go. - if (comptime std.mem.eql(u8, name, "watch_theme")) return args[1]; - inline for (keeps_stopping) |s| if (comptime std.mem.eql(u8, s, name)) return true; - return false; + if (comptime f == .watch_theme) return args[1]; + return comptime std.mem.indexOfScalar(Host.Fn, &keeps_stopping, f) != null; } /// The entries a view's frontend makes on its own machine (P16). -fn forTheView(comptime name: []const u8) bool { - return std.mem.eql(u8, name, "set_clipboard") or std.mem.eql(u8, name, "read_clipboard") or std.mem.eql(u8, name, "open_link"); +fn forTheView(comptime f: Host.Fn) bool { + return f == .set_clipboard or f == .read_clipboard or f == .open_link; } -fn hostCall(comptime i: usize, comptime R: type, ctx: ?*anyopaque, args: anytype) R { - const t: *Tape = @ptrCast(@alignCast(ctx.?)); - const name = host_fns[i]; +/// The one body of a call out to the host through the tape (`Tape.host`). +fn hostCall(t: *Tape, p: *const Pardes, comptime f: Host.Fn, args: Host.Args(f)) Host.Ret(f) { + const R = Host.Ret(f); + const name = @tagName(f); // A terminal's answers and what is typed at it from its output are the // authority's to write, never a replica's: off the tape on both sides. if (comptime std.mem.eql(u8, name, "pty_write")) if (t.screen_state and !t.speculating) { - if (!t.replay) @call(.auto, @field(t.real.vtable.*, name).?, .{t.real.ctx} ++ args); + if (!t.replay) _ = p.host.call(f, args); return; }; if (t.replay) { // A replica that never draws is never watched: it asks no one. if (comptime std.mem.eql(u8, name, "watched")) if (t.skips_render) return false; - if (!t.expectHost(i, name)) return std.mem.zeroes(R); + if (!t.expectHost(@backingInt(f), name)) return std.mem.zeroes(R); var ret = t.last_ret; if (R == ?[]const u8) { // fg_name's answer is written into the caller's buffer. @@ -1243,7 +1210,7 @@ fn hostCall(comptime i: usize, comptime R: type, ctx: ?*anyopaque, args: anytype } return walk.decode(R, &ret, t.arena.allocator()) catch std.mem.zeroes(R); } - const id: u16 = i; + const id: u16 = @backingInt(f); if (t.speculating) { // Nobody watches a replica's step: its frames are its own, drawn // outside it (and the authority's host says so too, or the @@ -1258,7 +1225,7 @@ fn hostCall(comptime i: usize, comptime R: type, ctx: ?*anyopaque, args: anytype // on. The session's unit records the same, or more where its host // wrote the core during the call (an input it made, a watched field // set), and the client rolls back. - if (R == void and !keepsStopping(name, args)) { + if (R == void and !keepsStopping(f, args)) { t.record(.host, u16, &id); t.record(.ret, void, &{}); return; @@ -1270,17 +1237,16 @@ fn hostCall(comptime i: usize, comptime R: type, ctx: ?*anyopaque, args: anytype // A client's yank, paste or link is its own frontend's, made on its own // machine from its view's record (Pardes.View.yanks): never the // session's, whose host makes them for a view no client draws. - if (comptime forTheView(name)) if (t.core) |p| if (p.undrawn & (@as(u8, 1) << @intCast(p.live)) != 0) { + if (comptime forTheView(f)) if (p.undrawn & (@as(u8, 1) << @intCast(p.live)) != 0) { t.record(.host, u16, &id); t.record(.ret, void, &{}); return; }; - const real = @field(t.real.vtable.*, name).?; t.record(.host, u16, &id); t.seeFields(); const outer = !t.host_side; t.host_side = true; - const r = @call(.auto, real, .{t.real.ctx} ++ args); + const r = p.host.call(f, args).?; t.host_side = !outer; t.noteWrites(); t.record(.ret, R, &r); @@ -1347,7 +1313,7 @@ pub fn recordDigest(t: *Tape) void { pub fn adoptCore(t: *Tape, p: *Pardes) void { t.core = p; p.tape = t; - p.host = t.hostOf(t.mask); + t.replica = true; } /// A replica joins the session recorded on `t` (core/replica.zig): what the @@ -1355,9 +1321,6 @@ pub fn adoptCore(t: *Tape, p: *Pardes) void { /// input, for a core made from a dump, which has neither. pub fn resync(t: *Tape) void { t.seen = @splat(0); - if (t.core) |p| if (p.host.vtable == &t.vtable) { - p.host = t.real; - }; t.real = .{}; } @@ -1484,6 +1447,7 @@ pub fn release(t: *Tape) void { /// tape's core as the authority applied them, each digest checked; why /// they diverged, or null. pub fn replayUnit(t: *Tape, bytes: []const u8) ?[]const u8 { + t.replica = true; t.replay = true; t.speculating = false; defer t.replay = false; @@ -1818,6 +1782,73 @@ test "every place that sets the global tape aside sets the core's field aside: a try std.testing.expectEqual(@as(usize, 0), wrong); } +/// The pump's own calls: a host with a clock and a frontend that shows +/// every frame; `more` has one function besides. +const Pumped = struct { + ns: u64, + fn now(ctx: ?*anyopaque) u64 { + const h: *Pumped = @ptrCast(@alignCast(ctx.?)); + h.ns += std.time.ns_per_ms; + return h.ns; + } + fn seen(_: ?*anyopaque) bool { + return true; + } + fn present(_: ?*anyopaque, _: *const pardes.Surface) bool { + return true; + } + fn poll(_: ?*anyopaque) void {} + const one: VTable = .{ .now = now, .watched = seen, .present = present }; + const more: VTable = .{ .now = now, .watched = seen, .present = present, .poll_frame = poll }; + + /// Recorded `bytes`: how many times which functions the host has was + /// said, the last said, and the calls of each function. + fn said(bytes: []const u8) struct { sets: usize = 0, mask: u64 = 0, calls: [host_fns.len]usize = @splat(0) } { + var got: @typeInfo(@TypeOf(said)).@"fn".return_type.? = .{}; + var r: walk.Reader = .{ .bytes = bytes }; + while (nextRecord(&r)) |rec| { + if (rec.kind == .set and rec.payload[0] == set_mask) { + got.sets += 1; + got.mask = std.mem.bytesToValue(u64, rec.payload[1..9]); + } + if (rec.kind == .host) { + const id = std.mem.bytesToValue(u16, rec.payload[0..2]); + if (id < host_fns.len) got.calls[id] += 1; + } + } + return got; + } +}; + +test "a core pumped twice with one host and once with another: which functions its host has is said at the first pump and the third, its clock, watch and present at each; a replica replays the three units to the same digest" { + const gpa = std.testing.allocator; + const R = pardes.replica; + var first: Pumped = .{ .ns = 0 }; + var second: Pumped = .{ .ns = 1 << 40 }; + const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24 }, .{ .ctx = &first, .vtable = &Pumped.one }, false); + defer a.deinit(); + const boot = Pumped.said(a.t.buf.items); + try std.testing.expectEqual(Host.mask(.{ .vtable = &Pumped.one }), boot.mask); + const r = try R.Replica.init(gpa, 1, try a.unit(0, 0), false); + defer r.deinit(); + const hosts = [_]Host{ .{ .ctx = &first, .vtable = &Pumped.one }, .{ .ctx = &second, .vtable = &Pumped.more } }; + for (hosts, [_]usize{ 0, 1 }, 1..) |h, sets, seq| { + a.host = h; + a.apply(.{ .resize = .{ .cols = @intCast(80 + seq), .rows = 24 } }); + const got = Pumped.said(a.t.buf.items); + try std.testing.expectEqual(sets, got.sets); + if (sets > 0) try std.testing.expectEqual(h.mask(), got.mask); + inline for (.{ .now, .watched, .present }) |f| try std.testing.expect(got.calls[@backingInt(@as(Host.Fn, f))] > 0); + try std.testing.expectEqual(@intFromBool(h.has(.poll_frame)), got.calls[@backingInt(Host.Fn.poll_frame)]); + a.seq += 1; + r.confirm(try a.unit(0, a.seq)); + } + r.settle(); + if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why}); + try std.testing.expect(r.diverged == null); + try std.testing.expectEqual(R.digestOf(a), r.digest()); +} + test "a client's frame drawn between its steps records nothing into its idle tape" { const gpa = std.testing.allocator; const p = try @import("ninep/harness.zig").withFile(gpa, "x\n"); |
