diff options
| -rw-r--r-- | core/Core.zig | 203 | ||||
| -rw-r--r-- | core/Db.zig | 6 | ||||
| -rw-r--r-- | core/Dir.zig | 13 | ||||
| -rw-r--r-- | core/Effect.zig | 2 | ||||
| -rw-r--r-- | core/Jump.zig | 2 | ||||
| -rw-r--r-- | core/Output.zig | 2 | ||||
| -rw-r--r-- | core/Plumb.zig | 2 | ||||
| -rw-r--r-- | core/Query.zig | 2 | ||||
| -rw-r--r-- | core/builtins.zig | 14 | ||||
| -rw-r--r-- | core/config.zig | 36 | ||||
| -rw-r--r-- | core/dump.zig | 52 | ||||
| -rw-r--r-- | core/edit_cmd.zig | 10 | ||||
| -rw-r--r-- | core/exec.zig | 16 | ||||
| -rw-r--r-- | core/fs.zig | 105 | ||||
| -rw-r--r-- | core/hunks.zig | 2 | ||||
| -rw-r--r-- | core/look.zig | 4 | ||||
| -rw-r--r-- | core/ninep/ctl.zig | 10 | ||||
| -rw-r--r-- | core/ninep/pane.zig | 4 | ||||
| -rw-r--r-- | core/replica.zig | 2 | ||||
| -rw-r--r-- | core/rollback.zig | 37 | ||||
| -rw-r--r-- | core/root.zig | 9 | ||||
| -rw-r--r-- | core/sam_edit.zig | 4 | ||||
| -rw-r--r-- | core/tape.zig | 404 | ||||
| -rw-r--r-- | dev/file_watch.zig | 4 | ||||
| -rw-r--r-- | dev/gui/gui.zig | 16 | ||||
| -rw-r--r-- | dev/host_io.zig | 2 | ||||
| -rw-r--r-- | dev/tui/tui.zig | 2 | ||||
| -rw-r--r-- | runtime/macos.zig | 4 | ||||
| -rw-r--r-- | runtime/main.zig | 6 | ||||
| -rw-r--r-- | runtime/upgrade.zig | 4 |
30 files changed, 565 insertions, 414 deletions
diff --git a/core/Core.zig b/core/Core.zig index 0e37f945..3876b3e8 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -78,7 +78,6 @@ const recent_files = @import("recent.zig"); const sel_slot = pardes.sel_slot; const syntax = pardes.syntax; const tagline = pardes.tagline; -const tape = pardes.tape; const test_api = pardes.test_api; const themes = pardes.themes; const turn = &pardes.turn; @@ -195,6 +194,13 @@ image_gpa: std.mem.Allocator, kinds: pardes.Kind.Registry = .{}, tree_sitter_gpa: std.mem.Allocator, opts: Options, +/// The tape this core's steps record on, replay from or go through (a +/// session nobody records: `tape.none`), as `gpa` is its allocator: this +/// process's own, in no digest, dump or rollback copy (`replica.local`, +/// rollback.zig's `unsaved`). Set when the core is made (`Options.tape`; +/// `tape.adoptCore` for a client's join, `tape.adopt` for a Restore) and +/// by the session's clients (replica.zig `Peers`). +tape: *pardes.tape.Tape, resize_count: usize = 0, panes: [MAX_PANES]?*Pane = @splat(null), @@ -446,6 +452,7 @@ pub const replica = .{ // How this process was started, and the last dump it made for // its host to write: a session loaded elsewhere has its own. "opts", "dump_out", "dump_export", + "tape", }, .derived = .{ "shell_rows", "diff_output", "locations_cache", "retired_panes", "tty_filter_palette", "body_chrome" }, // The host's handles, the 9P server's fids and log, the state file @@ -514,6 +521,9 @@ pub fn create(gpa: std.mem.Allocator, opts: Options) !*Pardes { .kinds = .started(opts.addons), .tree_sitter_gpa = opts.tree_sitter_allocator orelse gpa, .opts = opts, + // The global still set beside the field (P20): a core made while + // a tape records (PARDES_RECORD, a replica's step) is its. + .tape = opts.tape orelse pardes.tape.on orelse &pardes.tape.none, .tty_toggle = opts.tty_toggle, .views = .{ View{ .frontend = .{ .windowed = opts.windowed }, @@ -538,14 +548,13 @@ pub fn create(gpa: std.mem.Allocator, opts: Options) !*Pardes { /// A new session, its tape written from here when PARDES_RECORD asks. pub fn init(gpa: std.mem.Allocator, opts: Options) !*Pardes { - tape.startFromEnv(); - const taped = tape.enter(null, .{ .init = opts }); - const p = initSession(gpa, opts) catch |err| { - tape.leave(null, taped); - return err; - }; - tape.leave(p, taped); - return p; + pardes.tape.startFromEnv(); + const taped = pardes.tape.enter(null, .{ .init = opts }); + // The tape adopts the core made, none on a failure. + var made: ?*Pardes = null; + defer pardes.tape.leave(made, taped); + made = try initSession(gpa, opts); + return made.?; } fn initSession(gpa: std.mem.Allocator, opts: Options) !*Pardes { @@ -700,15 +709,15 @@ pub fn recentGpa(_: *const Pardes) std.mem.Allocator { pub fn loadRecent(p: *Pardes) void { // A replica's Recent is its own, in memory: the recording session's // state file is every session's of its user (core/tape.zig). - if (tape.replaying()) p.db.kind = .off; + if (pardes.tape.replaying()) p.db.kind = .off; p.db.readRecent(p); } /// Whether `path` is one Recent keeps: a file on this host's disk, not /// the served tree's (`/virtual/`) nor a name never saved. -pub fn recentKeeps(path: []const u8) bool { +pub fn recentKeeps(tape: *pardes.tape.Tape, path: []const u8) bool { const local = filesystem.localPath(path) orelse return false; - return exec.kindOf(local) == .file; + return exec.kindOf(tape, local) == .file; } /// A file pane or a kind's (a PDF, a picture) closing: its place noted in Recent, when @@ -763,11 +772,11 @@ pub fn recentDot(pane: *const Pane) ?struct { path: []const u8, line: u32, col: /// reads them: its process's options, so the authority's /// (`tape.authority`); a replica's are its own process's. pub fn configDir(p: *Pardes) ?[]const u8 { - return tape.authority(optsConfigDir, .{p}); + return pardes.tape.authority(optsConfigDir, .{p}); } pub fn startupPath(p: *Pardes) ?[]const u8 { - return tape.authority(optsStartupPath, .{p}); + return pardes.tape.authority(optsStartupPath, .{p}); } fn optsConfigDir(p: *Pardes) ?[]const u8 { @@ -782,7 +791,7 @@ fn optsStartupPath(p: *Pardes) ?[]const u8 { /// in scratch. Recent is the authority's (every window of its user /// writes it): a replica has its answer (`tape.authority`). pub fn recentByHash(p: *Pardes, hash: u64) ?recent_files.Entry { - return tape.authority(recentFound, .{ p, hash }); + return pardes.tape.authority(recentFound, .{ p, hash }); } fn recentFound(p: *Pardes, hash: u64) ?recent_files.Entry { @@ -795,9 +804,9 @@ fn recentFound(p: *Pardes, hash: u64) ?recent_files.Entry { } pub fn deinit(p: *Pardes) void { - const taped = tape.enter(p, .{ .deinit = tape.current(p) }); - tape.forget(p); - defer tape.leave(null, taped); + const taped = pardes.tape.enter(p, .{ .deinit = pardes.tape.current(p) }); + pardes.tape.forget(p); + defer pardes.tape.leave(null, taped); if (std.c.getenv("PARDES_FRAMES")) |path| p.frames.dump(std.mem.span(path)); // Every file open now is closed with its dot, and the list kept. for (p.panes) |slot| if (slot) |pane| p.noteClosed(pane); @@ -863,8 +872,8 @@ pub fn endSession(p: *Pardes) void { /// shell feedback after write_dump: remember where the dump landed (the /// topbar grows a `Restore <path>` word pointing at it) pub fn setLastDump(p: *Pardes, path: []const u8) void { - const taped = tape.enter(p, .{ .set_last_dump = path }); - defer tape.leave(p, taped); + const taped = pardes.tape.enter(p, .{ .set_last_dump = path }); + defer pardes.tape.leave(p, taped); p.pointRestoreAt(path); ctlfs.events.notePath(p, "dump", path); } @@ -892,8 +901,8 @@ pub fn pointRestoreAt(p: *Pardes, path: []const u8) void { /// the shell polls this each frame: a pending Restore's dump path, or null pub fn takeRestore(p: *Pardes) ?[]const u8 { - const taped = tape.enter(p, .take_restore); - defer tape.leave(p, taped); + const taped = pardes.tape.enter(p, .take_restore); + defer pardes.tape.leave(p, taped); const r = p.restore_req; p.restore_req = null; return r; @@ -917,7 +926,7 @@ fn reportFocus(p: *Pardes) void { // session's step makes the write, off the tape on both sides // (tape.hostCall's pty_write), so the switch shows at once and the // program hears of it a round trip later. - if (tape.speculating() and tape.screenState()) return; + if (pardes.tape.speculating() and pardes.tape.screenState()) return; if (v.focus_told) |old| if (p.panes[old.id]) |pane| { if (pane.serial == old.serial and pardes.Term.modes(pane.terminal).focus) p.emitWrite(old.id, "\x1b[O"); }; @@ -969,8 +978,8 @@ pub fn parkPendingWrite(p: *Pardes, id: usize, bytes: []const u8) void { /// The shell reports the spawned pane's working directory (and later cwd /// changes it observes, e.g. via /proc/<pid>/cwd before each frame). pub fn setCwd(p: *Pardes, id: usize, cwd: []const u8) void { - const taped = tape.enter(p, .{ .set_cwd = .{ .id = id, .cwd = cwd } }); - defer tape.leave(p, taped); + const taped = pardes.tape.enter(p, .{ .set_cwd = .{ .id = id, .cwd = cwd } }); + defer pardes.tape.leave(p, taped); const pane = p.panes[id] orelse return; // A command pane stays the directory's it was run for (newCommand). if (pane.command != null) return; @@ -1005,8 +1014,8 @@ pub fn shellBin(p: *const Pardes) []const u8 { /// or null with no room. An input, as every host write into the core /// is: a replica of the session makes the same pane. pub fn adoptShell(p: *Pardes) ?u8 { - const taped = tape.enter(p, .adopt_shell); - defer tape.leave(p, taped); + const taped = pardes.tape.enter(p, .adopt_shell); + defer pardes.tape.leave(p, taped); var newest: u32 = 0; for (p.panes) |slot| if (slot) |pn| { newest = @max(newest, pn.serial); @@ -1022,16 +1031,16 @@ pub fn adoptShell(p: *Pardes) ?u8 { /// A terminal's reader failed (no end of file: the host closed its pty): /// its pane takes keys again, and why is said. pub fn readerFailed(p: *Pardes, id: u8, err: anyerror) void { - const taped = tape.enter(p, .{ .reader_failed = .{ .id = id, .err = err } }); - defer tape.leave(p, taped); + const taped = pardes.tape.enter(p, .{ .reader_failed = .{ .id = id, .err = err } }); + defer pardes.tape.leave(p, taped); const pane = p.panes[id] orelse return; pane.body.mode = .normal; p.reportError(id, "terminal reader", err); } pub fn acknowledgeShell(p: *Pardes, id: usize, executable: []const u8, prompt_marks: bool) void { - const taped = tape.enter(p, .{ .acknowledge_shell = .{ .id = id, .executable = executable, .prompt_marks = prompt_marks } }); - defer tape.leave(p, taped); + const taped = pardes.tape.enter(p, .{ .acknowledge_shell = .{ .id = id, .executable = executable, .prompt_marks = prompt_marks } }); + defer pardes.tape.leave(p, taped); if (id < MAX_PANES) if (p.panes[id]) |pane| { ctlfs.pty.shellGone(p, pane, true); // a respawn replaced whatever ran pane.shell_failed = false; @@ -1068,8 +1077,8 @@ pub fn acknowledgeShell(p: *Pardes, id: usize, executable: []const u8, prompt_ma /// them and a terminal's replica of a window's session must step as /// the window does. pub fn takeFontRequest(p: *Pardes) ?[]const u8 { - const taped = tape.enter(p, .take_font_request); - defer tape.leave(p, taped); + const taped = pardes.tape.enter(p, .take_font_request); + defer pardes.tape.leave(p, taped); if (!p.settings.font.pending or p.font_request_taken) return null; const path = p.settings.font.requested_path.get(); if (path.len == 0) return null; @@ -1083,8 +1092,8 @@ pub fn observeFont( effective_size_hundredths: u16, unit: config.Runtime.FontSizeUnit, ) bool { - const taped = tape.enter(p, .{ .observe_font = .{ .name = effective_name, .size = effective_size_hundredths, .unit = unit } }); - defer tape.leave(p, taped); + const taped = pardes.tape.enter(p, .{ .observe_font = .{ .name = effective_name, .size = effective_size_hundredths, .unit = unit } }); + defer pardes.tape.leave(p, taped); if (!p.settings.font.effective_name.set(effective_name)) return false; p.settings.font.effective_size_hundredths = effective_size_hundredths; p.settings.font.effective_size_unit = unit; @@ -1099,8 +1108,8 @@ pub fn acknowledgeFont( effective_size_hundredths: u16, unit: config.Runtime.FontSizeUnit, ) bool { - const taped = tape.enter(p, .{ .acknowledge_font = .{ .name = effective_name, .size = effective_size_hundredths, .unit = unit } }); - defer tape.leave(p, taped); + const taped = pardes.tape.enter(p, .{ .acknowledge_font = .{ .name = effective_name, .size = effective_size_hundredths, .unit = unit } }); + defer pardes.tape.leave(p, taped); if (!p.settings.font.pending or !p.font_request_taken) return false; const changed = !std.mem.eql( u8, @@ -1116,8 +1125,8 @@ pub fn acknowledgeFont( } pub fn rejectFont(p: *Pardes) void { - const taped = tape.enter(p, .reject_font); - defer tape.leave(p, taped); + const taped = pardes.tape.enter(p, .reject_font); + defer pardes.tape.leave(p, taped); if (!p.settings.font.pending or !p.font_request_taken) return; p.settings.font.pending = false; p.font_request_taken = false; @@ -1144,8 +1153,8 @@ pub inline fn view(p: anytype) if (@typeInfo(@TypeOf(p)).pointer.attrs.@"const") /// `pardes --attach`ed), as the live one is laid out; null at /// Views.max. Not live until `toView`. pub fn openView(p: *Pardes) ?u8 { - const taped = tape.enter(p, .open_view); - defer tape.leave(p, taped); + const taped = pardes.tape.enter(p, .open_view); + defer pardes.tape.leave(p, taped); // Every view taken: one kept for a client that has not come back // for it (Views.away) goes first. ponytail: no timer lets one go; // until its place is wanted it costs a parked slot, and a terminal @@ -1166,8 +1175,8 @@ pub fn openView(p: *Pardes) ?u8 { /// The client of view `k` gone: its view goes, the others stay. The /// last one stays the session's own. pub fn closeView(p: *Pardes, k: u8) void { - const taped = tape.enter(p, .{ .close_view = k }); - defer tape.leave(p, taped); + const taped = pardes.tape.enter(p, .{ .close_view = k }); + defer pardes.tape.leave(p, taped); Views.close(p, k); p.sync(); // What its sync queued (a terminal it sized, sized again) done here, @@ -1181,8 +1190,8 @@ pub fn closeView(p: *Pardes, k: u8) void { /// goes, and the session's own is laid out as it was (Views.closeKeeping), /// which the client's rejoin copies. Settled as `closeView` is. pub fn leaveView(p: *Pardes, k: u8) void { - const taped = tape.enter(p, .{ .leave_view = k }); - defer tape.leave(p, taped); + const taped = pardes.tape.enter(p, .{ .leave_view = k }); + defer pardes.tape.leave(p, taped); Views.closeKeeping(p, k); p.sync(); p.settle(); @@ -1191,8 +1200,8 @@ pub fn leaveView(p: *Pardes, k: u8) void { /// The client of view `k` gone, to join again for it (an Upgrade's /// rejoin, a divergence's): its view kept as it is (Views.away). pub fn awayView(p: *Pardes, k: u8) void { - const taped = tape.enter(p, .{ .away_view = k }); - defer tape.leave(p, taped); + const taped = pardes.tape.enter(p, .{ .away_view = k }); + defer pardes.tape.leave(p, taped); Views.away(p, k); } @@ -1200,8 +1209,8 @@ pub fn awayView(p: *Pardes, k: u8) void { /// as it left it; false when it was let go meanwhile. Settled as /// `openView` is, for the join's dump next. pub fn rejoinView(p: *Pardes, k: u8) bool { - const taped = tape.enter(p, .{ .rejoin_view = k }); - defer tape.leave(p, taped); + const taped = pardes.tape.enter(p, .{ .rejoin_view = k }); + defer pardes.tape.leave(p, taped); if (!Views.isAway(p, k)) return false; p.views_away &= ~(@as(u8, 1) << @intCast(k)); p.settle(); @@ -1212,8 +1221,8 @@ pub fn rejoinView(p: *Pardes, k: u8) bool { /// Into view `k`, before the input its client sent. pub fn toView(p: *Pardes, k: u8) void { if (k == p.live) return; - const taped = tape.enter(p, .{ .to_view = k }); - defer tape.leave(p, taped); + const taped = pardes.tape.enter(p, .{ .to_view = k }); + defer pardes.tape.leave(p, taped); Views.to(p, k); } @@ -1221,14 +1230,14 @@ pub fn toView(p: *Pardes, k: u8) void { /// file reloading under it, a theme file rewritten on disk. `pump` draws /// only when it has a reason to, and this is the reason. pub fn invalidate(p: *Pardes) void { - const taped = tape.enter(p, .invalidate); - defer tape.leave(p, taped); + const taped = pardes.tape.enter(p, .invalidate); + defer pardes.tape.leave(p, taped); p.needs_frame = true; } pub fn reloadWatchedFile(p: *Pardes, id: u8, bytes: []const u8) bool { - const taped = tape.enter(p, .{ .reload_watched_file = .{ .id = id, .bytes = bytes } }); - defer tape.leave(p, taped); + const taped = pardes.tape.enter(p, .{ .reload_watched_file = .{ .id = id, .bytes = bytes } }); + defer pardes.tape.leave(p, taped); p.invalidate(); look.invalidateLookHover(p, id); const applied = p.applyWatchedFileChanged(id, bytes); @@ -1245,8 +1254,8 @@ pub fn emit(p: *Pardes, e: Effect) void { } pub fn nextEffect(p: *Pardes) ?Effect { - const taped = tape.enter(p, .next_effect); - defer tape.leave(p, taped); + const taped = pardes.tape.enter(p, .next_effect); + defer pardes.tape.leave(p, taped); p.refillPendingWrites(); if (p.effects_len == 0) { p.effects_head = 0; @@ -1331,8 +1340,8 @@ pub fn hostKillJob(p: *const Pardes, id: usize) bool { /// on it, or written to it from now on, hears `error shell gone` /// rather than wait for a prompt that never comes. pub fn shellFailed(p: *Pardes, id: u8, err: anyerror) void { - const taped = tape.enter(p, .{ .shell_failed = .{ .id = id, .err = err } }); - defer tape.leave(p, taped); + const taped = pardes.tape.enter(p, .{ .shell_failed = .{ .id = id, .err = err } }); + defer pardes.tape.leave(p, taped); const pane = p.panes[id] orelse return; pane.shell_failed = true; ctlfs.pty.shellGone(p, pane, false); @@ -1354,8 +1363,8 @@ pub fn shellFailed(p: *Pardes, id: u8, err: anyerror) void { /// A shell started again in a terminal whose shell runs (pty/ctl's /// exec) did not start: the host kept the running one, so only said. pub fn restartFailed(p: *Pardes, id: u8, err: anyerror) void { - const taped = tape.enter(p, .{ .restart_failed = .{ .id = id, .err = err } }); - defer tape.leave(p, taped); + const taped = pardes.tape.enter(p, .{ .restart_failed = .{ .id = id, .err = err } }); + defer pardes.tape.leave(p, taped); if (p.panes[id] == null) return; p.sayShellFailure(id, err); } @@ -1368,7 +1377,7 @@ fn sayShellFailure(p: *Pardes, id: u8, err: anyerror) void { // The script is there; the program its `#!` names is not. var said: pardes.Kind.Buf(320) = .{}; var interp: [256]u8 = undefined; - const name = tape.value(.interpreter, missingInterpreter, .{ pane.shell orelse p.shellBin(), &interp }); + const name = pardes.tape.value(.interpreter, missingInterpreter, .{ pane.shell orelse p.shellBin(), &interp }); p.reportFailure(id, if (name) |n| said.print("shell: interpreter {s} not found", .{n}) else "shell: interpreter not found"); } else { p.reportError(id, "shell", err); @@ -1388,18 +1397,18 @@ fn missingInterpreter(bin: []const u8, out: []u8) ?[]const u8 { /// The directory a write of `path` that failed with `err` went into: /// what is there (a directory when it is no local path), whether it is /// missing, and whether that is because one above refuses (EACCES). -fn parentTrouble(path: []const u8, err: anyerror) struct { dir: []const u8, kind: ?std.Io.File.Kind, missing: bool, denied: bool } { +fn parentTrouble(tape: *pardes.tape.Tape, path: []const u8, err: anyerror) struct { dir: []const u8, kind: ?std.Io.File.Kind, missing: bool, denied: bool } { const dir = std.Io.Dir.path.dirname(path) orelse "/"; const local = filesystem.localPath(dir); - const kind: ?std.Io.File.Kind = if (local) |l| exec.kindOf(l) else .directory; + const kind: ?std.Io.File.Kind = if (local) |l| exec.kindOf(tape, l) else .directory; const missing = err == error.FileNotFound or err == error.NotDir or kind != .directory; const denied = missing and (if (local) |l| tape.value(.denied, filesystem.deniedAbove, .{l}) else false); return .{ .dir = dir, .kind = kind, .missing = missing, .denied = denied }; } pub fn saveFailed(p: *Pardes, id: u8, path: []const u8, err: anyerror) void { - const taped = tape.enter(p, .{ .save_failed = .{ .id = id, .path = path, .err = err } }); - defer tape.leave(p, taped); + const taped = pardes.tape.enter(p, .{ .save_failed = .{ .id = id, .path = path, .err = err } }); + defer pardes.tape.leave(p, taped); if (p.panes[id]) |pane| if (pane.file) |*f| { // The `-%` spelling fs.zig already uses for "make this dirty". f.saved_revision = f.revision -% 1; @@ -1407,7 +1416,7 @@ pub fn saveFailed(p: *Pardes, id: u8, path: []const u8, err: anyerror) void { var what: pardes.Kind.Buf(limits.host_path_cap + 32) = .{}; // A write into a directory that is not there: said so, in the words // a mount reads as ENOENT; EACCES when one above refuses. - const parent = parentTrouble(path, err); + const parent = parentTrouble(p.tape, path, err); if (parent.denied) p.reportFailure(id, what.print("Save {s}: permission denied", .{path[0..@min(path.len, limits.host_path_cap)]})) else if (parent.missing) @@ -1422,13 +1431,13 @@ pub fn saveFailed(p: *Pardes, id: u8, path: []const u8, err: anyerror) void { /// Save's does. pub fn dumpFailed(p: *Pardes, path: []const u8, err: anyerror) void { const v = p.view(); - const taped = tape.enter(p, .{ .dump_failed = .{ .path = path, .err = err } }); - defer tape.leave(p, taped); + const taped = pardes.tape.enter(p, .{ .dump_failed = .{ .path = path, .err = err } }); + defer pardes.tape.leave(p, taped); var what: [limits.host_path_cap + 8]u8 = undefined; const operation = std.fmt.bufPrint(&what, "Dump {s}", .{path[0..@min(path.len, limits.host_path_cap)]}) catch unreachable; // cap + 5 fits cap + 8 // Into a DumpDir that is not there: said so, ENOENT, as a Save is; // one that is there but no directory (`/dev/null`) says that. - const parent = parentTrouble(path, err); + const parent = parentTrouble(p.tape, path, err); var said: pardes.Kind.Buf(limits.host_path_cap + 48) = .{}; if (parent.denied and parent.kind == null) p.reportFailure(v.active, said.print("{s}: permission denied", .{operation})) @@ -1465,8 +1474,8 @@ pub fn animationActive(p: *const Pardes) bool { pub fn pump(p: *Pardes, host: Host) !void { p.host = host; - const taped = tape.enter(p, .pump); - defer tape.leave(p, taped); + 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; @@ -1550,8 +1559,8 @@ pub fn settle(p: *Pardes) void { /// authority's tape of it to read the same. The session's own pump /// draws it after. pub fn step(p: *Pardes) void { - const taped = tape.enter(p, .step); - defer tape.leave(p, taped); + const taped = pardes.tape.enter(p, .step); + defer pardes.tape.leave(p, taped); p.settle(); } @@ -1562,8 +1571,8 @@ pub fn step(p: *Pardes) void { /// that changes a pane costs a frame, which is why a round trip on a /// local socket costs microseconds and not a vsync. pub fn serveFs(p: *Pardes, req: ctlfs.Req) ctlfs.Reply { - const taped = tape.enter(p, .{ .serve_fs = req }); - defer tape.leave(p, taped); + const taped = pardes.tape.enter(p, .{ .serve_fs = req }); + defer pardes.tape.leave(p, taped); // The held write of an Edit whose commands run, asked again by a // retry of its park: still waiting, or its answer, never run twice. if (p.fs.edit_hold) |*h| if (h.names(req)) { @@ -1604,8 +1613,8 @@ pub fn serveFs(p: *Pardes, req: ctlfs.Req) ctlfs.Reply { pub fn update(p: *Pardes, ev: Event) void { const v = p.view(); - const taped = tape.enter(p, .{ .update = ev }); - defer tape.leave(p, taped); + const taped = pardes.tape.enter(p, .{ .update = ev }); + defer pardes.tape.leave(p, taped); defer pardes.panes.File.syncTwins(p); defer p.reportFocus(); // A tick with no deadline due is the one event that cannot change @@ -1756,15 +1765,15 @@ fn fsReport(p: *Pardes) void { pub fn readSessionFacts(p: *Pardes) void { // A dump made since carries them all: its shell is never empty. if (p.session_shell_len != 0) return; - if (p.session_dir_len == null) if (tape.value(.env, processDir, .{&p.session_dir})) |dir| { + if (p.session_dir_len == null) if (pardes.tape.value(.env, processDir, .{&p.session_dir})) |dir| { std.mem.copyForwards(u8, &p.session_dir, dir); p.session_dir_len = @intCast(dir.len); }; - if (tape.value(.env, filesystem.processHome, .{})) |home| if (home.len <= p.session_home.len) { + if (pardes.tape.value(.env, filesystem.processHome, .{})) |home| if (home.len <= p.session_home.len) { @memcpy(p.session_home[0..home.len], home); p.session_home_len = @intCast(home.len); }; - const shell = tape.value(.env, config.defaultShell, .{}); + const shell = pardes.tape.value(.env, config.defaultShell, .{}); const kept = shell[0..@min(shell.len, p.session_shell.len)]; @memcpy(p.session_shell[0..kept.len], kept); p.session_shell_len = @intCast(kept.len); @@ -1783,7 +1792,7 @@ pub fn sessionShell(p: *const Pardes) []const u8 { /// A path's leading `~` (alone, or before `/` or `:`) as the session's home; /// `~user` that user's (fs.expandHomeFrom). pub fn expandHome(p: *const Pardes, path: []const u8, out: *[4096]u8) []const u8 { - return filesystem.expandHomeFrom(path, out, p.sessionHome()); + return filesystem.expandHomeFrom(p.tape, path, out, p.sessionHome()); } /// The session's home, null for none. @@ -1808,8 +1817,8 @@ pub const SavePath = Effect.Buf(effect_path_cap); /// What was said of a failure just now on pane `id` is also the waiting /// 9P write's (9p_io, `fs.late_failure`). pub fn noteLateFailure(p: *Pardes, id: usize) void { - const taped = tape.enter(p, .{ .note_late_failure = id }); - defer tape.leave(p, taped); + const taped = pardes.tape.enter(p, .{ .note_late_failure = id }); + defer pardes.tape.leave(p, taped); // Said by reportFailure just now: its words fitted whole, the // reason kept; else what the message row has. const said = if (p.fs.said_at == p.fs.failures and p.fs.said_len > 0) @@ -1824,8 +1833,8 @@ pub fn noteLateFailure(p: *Pardes, id: usize) void { /// under it now, a drag's moving end and a look-hover's word. pub fn presented(p: *Pardes) void { const v = p.view(); - const taped = tape.enter(p, .presented); - defer tape.leave(p, taped); + const taped = pardes.tape.enter(p, .presented); + defer pardes.tape.leave(p, taped); if (v.pointer_inside and v.drag != .none) { v.hover_col = v.pointer_raw_col; v.hover_row = v.pointer_raw_row; @@ -1837,8 +1846,8 @@ pub fn presented(p: *Pardes) void { /// The window's answer to a WindowOpacity: done, or `failure` says why /// not, `applied` the opacity it keeps. pub fn windowOpacityDone(p: *Pardes, applied: u8, failure: ?[]const u8) void { - const taped = tape.enter(p, .{ .window_opacity_done = .{ .applied = applied, .failure = failure } }); - defer tape.leave(p, taped); + const taped = pardes.tape.enter(p, .{ .window_opacity_done = .{ .applied = applied, .failure = failure } }); + defer pardes.tape.leave(p, taped); p.settings.window_opacity_pending = false; const reason = failure orelse return; // Do not claim a value the compositor refused; an explicit retry of @@ -1970,7 +1979,7 @@ pub fn sync(p: *Pardes) void { // A directory pane's entries follow its width, as acme's // columns do (Dir.fit). if (pane.file) |file| if (file.listing != null and r.h > pane.tag_rows) pardes.panes.Dir.fit(p, pane, pane.cols); - if (pane.pending_command.wait == .input) pane.releasePendingCommand(p, id, tape.value(.prompt, struct { + if (pane.pending_command.wait == .input) pane.releasePendingCommand(p, id, pardes.tape.value(.prompt, struct { fn ready(at: *const Pane) bool { return pardes.Term.prompt(at.terminal).input_ready; } @@ -1982,7 +1991,7 @@ pub fn sync(p: *Pardes) void { // its shell's FIRST prompt, or never: typed later it would land // in whatever runs then, or in the middle of a line someone // typed (Pane.greeting). - if (pane.greet and pane.isTerminal() and p.resize_count > 0) switch (tape.value(.prompt, Pane.greeting, .{pane})) { + if (pane.greet and pane.isTerminal() and p.resize_count > 0) switch (pardes.tape.value(.prompt, Pane.greeting, .{pane})) { .wait => {}, .never => pane.greet = false, .now => { @@ -2107,8 +2116,8 @@ pub fn nextWake(p: *const Pardes) ?u64 { /// the look-hover delay) is jumped to its end in one step and drawn /// once. Idle, time is not banked: the next wait starts from now. pub fn advance(p: *Pardes, now_ns: u64) void { - const taped = tape.enter(p, .{ .advance = now_ns }); - defer tape.leave(p, taped); + const taped = pardes.tape.enter(p, .{ .advance = now_ns }); + defer pardes.tape.leave(p, taped); // The first time a shell's clock is seen, core time starts there. const started = p.clock.started; p.clock.started = true; @@ -2119,7 +2128,7 @@ pub fn advance(p: *Pardes, now_ns: u64) void { // The session's ticks are the recording session's: a picture still // decoding or a fade still moving asks for frames the way a message // waiting to go does, and a replica that draws nothing has none. - while (tape.value(.wake, nextWake, .{p})) |due| { + while (pardes.tape.value(.wake, nextWake, .{p})) |due| { if (due > now_ns) break; // Only waiting until `due`: its counters move there at once. const held = (due - p.clock.stepped_ns) / frame; @@ -2241,9 +2250,9 @@ pub const Boot = enum { }; pub const Options = struct { - /// Not taped: the client's list of distrusted kinds, and where its - /// runner keeps its frame statistics. - pub const replica = .{ .local = .{ "distrusted", "frames" } }; + /// Not taped: the client's list of distrusted kinds, where its runner + /// keeps its frame statistics, and the core's tape. + pub const replica = .{ .local = .{ "distrusted", "frames", "tape" } }; tty_only: bool = false, /// The first view's frontend is a window (`Pardes.frontend`), as a /// window's build says: an option, taped with the rest, so that a @@ -2288,6 +2297,8 @@ pub const Options = struct { /// A client's: the kinds it caught breaking PA_PLAIN, its frontend's /// list, which outlives each core it joins with. In no tape and no dump. distrusted: ?*pardes.Addon.Distrusted = null, + /// The core's tape (`Pardes.tape`); null: `tape.on`'s, or `tape.none`. + tape: ?*pardes.tape.Tape = null, /// What the host's scan of the addon directories found (Addon.scan). addons: []const pardes.Kind.Loaded = &.{}, tree_sitter_allocator: ?std.mem.Allocator = null, diff --git a/core/Db.zig b/core/Db.zig index e8d606ec..cbeee5fb 100644 --- a/core/Db.zig +++ b/core/Db.zig @@ -89,9 +89,9 @@ pub fn deinit(db: *Db) void { /// The state file's path for the DumpDir setting `dir_setting`, made in /// `buf`; null with no home to keep it in. -pub fn statePath(buf: []u8, dir_setting: []const u8) ?[]const u8 { +pub fn statePath(tape: *pardes.tape.Tape, buf: []u8, dir_setting: []const u8) ?[]const u8 { var dir_buf: [4096]u8 = undefined; - const dir = pardes.dump.directory(&dir_buf, dir_setting) orelse return null; + const dir = pardes.dump.directory(tape, &dir_buf, dir_setting) orelse return null; return std.fmt.bufPrint(buf, "{s}/" ++ file_name, .{dir}) catch null; } @@ -1126,7 +1126,7 @@ fn opened(db: *Db, p: *Pardes) ?*Open { .off => return null, .disk => { var buf: [4200]u8 = undefined; - const path = statePath(&buf, p.settings.dump_dir.get()) orelse return null; + const path = statePath(p.tape, &buf, p.settings.dump_dir.get()) orelse return null; if (db.open) |o| { // The same file still: another session's compaction renames // a new one over it, which this one then opens. diff --git a/core/Dir.zig b/core/Dir.zig index 1be67378..3c74d704 100644 --- a/core/Dir.zig +++ b/core/Dir.zig @@ -46,17 +46,17 @@ pub fn ofName(name: []const u8) []const u8 { /// (plan9port lib9 dirread, acme's dircmp): every name but `.` and `..`, /// 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(gpa: std.mem.Allocator, dir: []const u8) ![]u8 { +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; if (local.len > own.len) return error.NameTooLong; @memcpy(own[0..local.len], local); - return pardes.tape.site(.dir_listing, gpa, readHost, .{ gpa, own[0..local.len] }); + return tape.site(.dir_listing, gpa, readHost, .{ gpa, own[0..local.len] }); } -fn readHost(gpa: std.mem.Allocator, local: []const u8) ![]u8 { +fn readHost(io: std.Io, gpa: std.mem.Allocator, local: []const u8) ![]u8 { var entries: std.ArrayList([]u8) = .empty; defer { for (entries.items) |entry| gpa.free(entry); @@ -64,7 +64,6 @@ fn readHost(gpa: std.mem.Allocator, local: []const u8) ![]u8 { } var total: usize = 0; { - const io = std.Io.Threaded.global_single_threaded.io(); var d = try std.Io.Dir.cwd().openDir(io, local, .{ .iterate = true }); defer d.close(io); var it = d.iterate(); @@ -165,7 +164,7 @@ pub fn fit(p: *Pardes, pane: *Pane, cols: usize) void { pub fn refresh(p: *Pardes, id: usize) !void { const pane = p.panes[id] orelse return error.NoPane; const serial = pane.serial; - const names = try read(p.gpa, ofName(pane.file.?.path)); + const names = try read(p.tape, p.gpa, ofName(pane.file.?.path)); // The pane may have closed while the turn was out. const now = p.panes[id] orelse return p.gpa.free(names); if (now.serial != serial) return p.gpa.free(names); @@ -195,7 +194,7 @@ pub fn look(p: *Pardes, from: usize, dir: []const u8) void { } var said: [limits.host_path_cap + 16]u8 = undefined; const what = std.fmt.bufPrint(&said, "look: {s}", .{name[0..@min(name.len, limits.host_path_cap)]}) catch unreachable; // cap and 6 fit - const names = read(p.gpa, dir) catch |err| { + const names = read(p.tape, p.gpa, dir) catch |err| { p.gpa.free(name); return p.reportError(from, what, err); }; @@ -307,7 +306,7 @@ test "a directory reads as acme lists it: dotfiles kept, . and .. not, directori try tmp.dir.symLink(io, "a", "link", .{ .is_directory = true }); var buf: [4096]u8 = undefined; const dir = buf[0..try tmp.dir.realPath(io, &buf)]; - const names = try read(testing.allocator, dir); + const names = try read(&pardes.tape.none, testing.allocator, dir); defer testing.allocator.free(names); // Bytewise, as dircmp's memcmp: `.` before capitals before small // letters, and `a.d/` before `a/` because `.` is before `/`. diff --git a/core/Effect.zig b/core/Effect.zig index 4d2009fb..dad2979c 100644 --- a/core/Effect.zig +++ b/core/Effect.zig @@ -280,7 +280,7 @@ pub fn writeChecked(p: *Pardes, id: u8, serial: u32, path: []const u8, bytes: [] // A Save makes the directories its file goes in, and any above them, // first: one rule, for the pane's own name and `Save path` alike. A // directory it cannot make leaves the write to fail and say why. - if (filesystem.localPath(path)) |local| filesystem.makeDirs(std.Io.Dir.path.dirname(local) orelse "/"); + 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, id, path, bytes) else if (!p.fallback.writeFile(path, bytes)) p.saveFailed(id, path, error.OutOfMemory); diff --git a/core/Jump.zig b/core/Jump.zig index 3b8c8d01..6d12495e 100644 --- a/core/Jump.zig +++ b/core/Jump.zig @@ -296,7 +296,7 @@ pub fn jumpBy(p: *Pardes, delta: i32) void { // Deleted since, or Recent has forgotten it: its entries go (the // first said), and the step goes on to the next place, never // stuck on one that cannot open. - if (found == null or !Pardes.recentKeeps(found.?.path)) { + if (found == null or !Pardes.recentKeeps(p.tape, found.?.path)) { var said: Kind.Buf(recent_path_cap + 32) = .{}; if (found) |e| p.setMessage(v.active, said.print("{s}: deleted, skipped", .{e.path[0..@min(e.path.len, recent_path_cap)]})); const hash = j.path_hash; diff --git a/core/Output.zig b/core/Output.zig index 42341002..1395b06f 100644 --- a/core/Output.zig +++ b/core/Output.zig @@ -601,7 +601,7 @@ pub fn openUnsaved(p: *Pardes, id: usize, content: []u8) void { const own = if (pane.file) |f| panes.Dir.ofName(f.path) else pane.cwdSlice(); // Its directory gone (or never there, a name not yet saved): the list // goes in the session's, where a look from it can still resolve. - const dir = if (pardes.filesystem.localPath(own)) |local| (if (exec.kindOf(local) == .directory) own else p.sessionDir()) else own; + const dir = if (pardes.filesystem.localPath(own)) |local| (if (exec.kindOf(p.tape, local) == .directory) own else p.sessionDir()) else own; const free = p.freeSlot() orelse return p.gpa.free(content); _ = open(p, free, dir, .unsaved, "", content) catch |err| return p.reportError(id, "+Unsaved", err); layout.placeNew(p, id, id, free, .doc); diff --git a/core/Plumb.zig b/core/Plumb.zig index 89f1a52d..a28ba5a8 100644 --- a/core/Plumb.zig +++ b/core/Plumb.zig @@ -477,7 +477,7 @@ const Parser = struct { var buf: [4096]u8 = undefined; const p = ps.p orelse return ps.fail("can't open {s} for inclusion", .{name}); const path = if (name[0] == '/') name else std.fmt.bufPrint(&buf, "{s}/{s}", .{ p.configDir() orelse "", name }) catch name; - break :text fs.readFile(ps.arena, path) catch return ps.fail("can't open {s} for inclusion", .{path}); + break :text fs.readFile(p.tape, ps.arena, path) catch return ps.fail("can't open {s} for inclusion", .{path}); }; const file = ps.file; const line = ps.line; diff --git a/core/Query.zig b/core/Query.zig index 30b07e92..e8011a1f 100644 --- a/core/Query.zig +++ b/core/Query.zig @@ -1667,7 +1667,7 @@ fn displayPreview(p: *Pardes, qid: usize, path: []const u8, at: look.Spot) void const pane = p.panes[id].?; const f = &pane.file.?; if (!std.mem.eql(u8, f.path, path)) { - if (exec.kindOf(path)) |kind| if (kind != .file) return; + if (exec.kindOf(p.tape, path)) |kind| if (kind != .file) return; const bytes = pardes.tape.site(.preview, p.gpa, filesystem.read, .{ p, path }) catch return; if (std.mem.indexOfScalar(u8, bytes[0..@min(bytes.len, 8000)], 0) != null) { p.gpa.free(bytes); diff --git a/core/builtins.zig b/core/builtins.zig index 6b291628..a79e4b66 100644 --- a/core/builtins.zig +++ b/core/builtins.zig @@ -493,7 +493,7 @@ pub const Restore = struct { // name. Else a label of the state file's. var full_buf: [4096]u8 = undefined; var label_buf: [256]u8 = undefined; - const file = if (typed) |t| dump.restoreFile(t, c.p.settings.dump_dir.get(), &full_buf) else null; + const file = if (typed) |t| dump.restoreFile(c.p.tape, t, c.p.settings.dump_dir.get(), &full_buf) else null; const name = if (file) |path| path else pardes.tape.authority(pardes.Db.labelled, .{ &c.p.db, c.p, typed, @as([]u8, &label_buf) }) orelse { var buf: pardes.Kind.Buf(320) = .{}; return c.p.reportFailure(c.id, if (typed) |t| buf.print("Restore: no dump labelled {s}", .{t}) else "Restore: no dump yet; name one"); @@ -503,7 +503,7 @@ pub const Restore = struct { // the host reads it only after this step, where nobody hears. // First, so a Restore that could never happen spends no warning. if (file) |path| { - const bytes = @import("fs.zig").readFile(c.p.gpa, path) catch |err| { + const bytes = @import("fs.zig").readFile(c.p.tape, c.p.gpa, path) catch |err| { var buf: pardes.Kind.Buf(limits.host_path_cap + 160) = .{}; var words: [128]u8 = undefined; const why = switch (err) { @@ -583,7 +583,7 @@ pub const Mount = struct { // A socket path that is not there: said so (ENOENT), not a dial // that went unanswered. const sock_path: ?[]const u8 = if (std.mem.startsWith(u8, dial, "unix!")) dial[5..] else if (dial.len > 0 and dial[0] == '/') dial else null; - if (sock_path) |path| if (@import("exec.zig").kindOf(path) == null) { + if (sock_path) |path| if (@import("exec.zig").kindOf(c.p.tape, path) == null) { if (c.p.fs.mounts.pop()) |gone| { c.p.gpa.free(gone.name); c.p.gpa.free(gone.dial); @@ -850,7 +850,7 @@ pub const Get = struct { // edits are asked about: there would be nothing to load over them. if (typed.len > 0) if (@import("fs.zig").localPath(path)) |local| { var said: pardes.Kind.Buf(320) = .{}; - const kind = exec.kindOf(local); + const kind = exec.kindOf(c.p.tape, local); if (kind == null or kind.? == .directory) return c.p.reportFailure(c.id, said.print("Get: {s}: {s}", .{ path[0..@min(path.len, 256)], if (kind == null) "no such file" else "is a directory" })); }; @@ -909,8 +909,8 @@ pub const Incl = struct { return p.reportFailure(c.id, said.print("Incl: invalid directory: {s} is relative", .{shown})); var home_buf: [4096]u8 = undefined; const expanded = p.expandHome(dir_word, &home_buf); - if (@import("fs.zig").localPath(expanded)) |local| if (exec.kindOf(local) != .directory) - return p.reportFailure(c.id, if (exec.kindOf(local) != null) + if (@import("fs.zig").localPath(expanded)) |local| if (exec.kindOf(p.tape, local) != .directory) + return p.reportFailure(c.id, if (exec.kindOf(p.tape, local) != null) said.print("Incl: not a directory: {s}", .{shown}) else said.print("Incl: no such directory: {s}", .{shown})); @@ -1321,7 +1321,7 @@ pub const Config = struct { /// directory. fn openConfigFile(c: Ctx, name: []const u8, path: []const u8, initial: []const u8) void { var real_buf: [4096]u8 = undefined; - const real = if (pardes.filesystem.resolveOs(path, &real_buf)) |r| r.path else null; + const real = if (pardes.filesystem.resolveOs(c.p.tape, path, &real_buf)) |r| r.path else null; for (c.p.panes, 0..) |slot, id| { const pane = slot orelse continue; const f = pane.file orelse continue; diff --git a/core/config.zig b/core/config.zig index f1e2a239..792a7e62 100644 --- a/core/config.zig +++ b/core/config.zig @@ -834,7 +834,7 @@ pub const Runtime = struct { } /// `home`: what `~` is (the session's: Pardes.session_home). - pub fn apply(state: *Runtime, setting: Setting, argument: ?[]const u8, home: ?[]const u8) bool { + pub fn apply(state: *Runtime, tape: *pardes.tape.Tape, setting: Setting, argument: ?[]const u8, home: ?[]const u8) bool { switch (setting.action) { // Every toggle names a bool field of its own, so one line covers // all of them and a new toggle needs no arm here. Bare, a toggle @@ -868,7 +868,7 @@ pub const Runtime = struct { var home_buf: [4096]u8 = undefined; // The session's disk's answer, as a failed save's (Core.zig): // a client's replay takes it, never its own disk's. - if (pardes.tape.value(.denied, pardes.filesystem.deniedAbove, .{pardes.filesystem.expandHomeFrom(text, &home_buf, home)})) return false; + if (tape.value(.denied, pardes.filesystem.deniedAbove, .{pardes.filesystem.expandHomeFrom(tape, text, &home_buf, home)})) return false; } if (!state.dump_dir.set(text)) return false; }, @@ -1072,28 +1072,28 @@ pub const Runtime = struct { const verbose = find("Verbose").?; try std.testing.expect(state.verbose); // Bare, it flips: that is what a tagline word does. - try std.testing.expect(apply(&state, verbose, null, null)); + try std.testing.expect(apply(&state, &pardes.tape.none, verbose, null, null)); try std.testing.expect(!state.verbose); // Told, it SETS -- twice over, so the second call proves it is not // flipping past the value it was given. - try std.testing.expect(apply(&state, verbose, "on", null)); + try std.testing.expect(apply(&state, &pardes.tape.none, verbose, "on", null)); try std.testing.expect(state.verbose); - try std.testing.expect(apply(&state, verbose, " on\n", null)); + try std.testing.expect(apply(&state, &pardes.tape.none, verbose, " on\n", null)); try std.testing.expect(state.verbose); - try std.testing.expect(apply(&state, verbose, "off", null)); + try std.testing.expect(apply(&state, &pardes.tape.none, verbose, "off", null)); try std.testing.expect(!state.verbose); - try std.testing.expect(apply(&state, verbose, "off", null)); + try std.testing.expect(apply(&state, &pardes.tape.none, verbose, "off", null)); try std.testing.expect(!state.verbose); // And anything else is refused rather than silently flipping. - try std.testing.expect(!apply(&state, verbose, "maybe", null)); + try std.testing.expect(!apply(&state, &pardes.tape.none, verbose, "maybe", null)); try std.testing.expect(!state.verbose); } test "simple setting application mutates only its plain field" { var state: Runtime = .{}; - try std.testing.expect(apply(&state, find("Wrap").?, null, null)); + try std.testing.expect(apply(&state, &pardes.tape.none, find("Wrap").?, null, null)); try std.testing.expect(!state.wrap); - try std.testing.expect(apply(&state, find("Shell").?, " fish\n", null)); + try std.testing.expect(apply(&state, &pardes.tape.none, find("Shell").?, " fish\n", null)); try std.testing.expectEqualStrings("fish", state.shell.requested.get()); try std.testing.expect(state.shell.pending); } @@ -1103,13 +1103,13 @@ pub const Runtime = struct { var state: Runtime = .{}; for ([_][]const u8{ "1", " 82\n", "100" }) |argument| { - try std.testing.expect(apply(&state, setting, argument, null)); + try std.testing.expect(apply(&state, &pardes.tape.none, setting, argument, null)); try std.testing.expectEqual(try std.fmt.parseInt(u8, std.mem.trim(u8, argument, " \t\r\n"), 10), state.font.tagline_percent); } state.font.tagline_percent = 67; for ([_]?[]const u8{ null, "", "0", "101", "-1", "50%", "999999999999999999999" }) |argument| { - try std.testing.expect(!apply(&state, setting, argument, null)); + try std.testing.expect(!apply(&state, &pardes.tape.none, setting, argument, null)); try std.testing.expectEqual(@as(u8, 67), state.font.tagline_percent); } } @@ -1123,7 +1123,7 @@ pub const Runtime = struct { for ([_][]const u8{ "0", " 85\n", "100" }, [_]u8{ 0, 85, 100 }) |argument, expected| { state.window_opacity_pending = false; - try std.testing.expect(apply(&state, setting, argument, null)); + try std.testing.expect(apply(&state, &pardes.tape.none, setting, argument, null)); try std.testing.expectEqual(expected, state.window_opacity); try std.testing.expect(state.window_opacity_pending); } @@ -1131,12 +1131,12 @@ pub const Runtime = struct { state.window_opacity = 85; state.window_opacity_pending = false; for ([_]?[]const u8{ null, "", " \t\n", "101", "-1", "+85", "85%", "0.5", "85.0", "85 20", "8_5", "0x55", "999999999999999999999" }) |argument| { - try std.testing.expect(!apply(&state, setting, argument, null)); + try std.testing.expect(!apply(&state, &pardes.tape.none, setting, argument, null)); try std.testing.expectEqual(@as(u8, 85), state.window_opacity); try std.testing.expect(!state.window_opacity_pending); } // Reissuing the same request still asks the host to apply it again. - try std.testing.expect(apply(&state, setting, "85", null)); + try std.testing.expect(apply(&state, &pardes.tape.none, setting, "85", null)); try std.testing.expect(state.window_opacity_pending); } @@ -1192,7 +1192,7 @@ pub const Runtime = struct { .{ "GripWidth", "200" }, .{ "InactiveDim", "35" }, .{ "CallstackDepth", "16" }, .{ "Tab", "8" }, }; - for (values) |v| try std.testing.expect(apply(&state, find(v[0]).?, v[1], null)); + for (values) |v| try std.testing.expect(apply(&state, &pardes.tape.none, find(v[0]).?, v[1], null)); try std.testing.expect(state.font.requested_name.set("Wanted Mono")); try std.testing.expect(state.font.requested_path.set("/fonts/wanted.ttf")); state.font.requested_size_hundredths = 1850; @@ -1841,11 +1841,11 @@ test "CallstackDepth is bounded and keeps the last valid runtime limit" { var state: Runtime = .{}; try std.testing.expectEqual(@as(u8, 8), state.callstack_depth); for ([_][]const u8{ "1", "8", "16", "64" }) |value| { - try std.testing.expect(Runtime.apply(&state, Runtime.find("CallstackDepth").?, value, null)); + try std.testing.expect(Runtime.apply(&state, &pardes.tape.none, Runtime.find("CallstackDepth").?, value, null)); try std.testing.expectEqual(try std.fmt.parseInt(u8, value, 10), state.callstack_depth); } for ([_][]const u8{ "0", "65", "256", "-1", "+8", "1_6", "eight", "" }) |value| { - try std.testing.expect(!Runtime.apply(&state, Runtime.find("CallstackDepth").?, value, null)); + try std.testing.expect(!Runtime.apply(&state, &pardes.tape.none, Runtime.find("CallstackDepth").?, value, null)); try std.testing.expectEqual(@as(u8, 64), state.callstack_depth); } } diff --git a/core/dump.zig b/core/dump.zig index d8d87fc6..e6e13a64 100644 --- a/core/dump.zig +++ b/core/dump.zig @@ -43,12 +43,12 @@ fn hostEnv(name: [*:0]const u8) ?[*:0]u8 { /// Where the state file is (Db.zig) and relative Restore names are looked /// up: the `DumpDir` setting when set (a leading `~/` is the home /// directory), else the default. -pub fn directory(buf: []u8, dir_setting: []const u8) ?[]const u8 { +pub fn directory(tape: *pardes.tape.Tape, buf: []u8, dir_setting: []const u8) ?[]const u8 { if (dir_setting.len == 0) return defaultDirectory(buf); var joined: [4096]u8 = undefined; // `~/x`, else a relative one from the directory pardes started in: the // same place however it was written, and shown so. - const raw = pardes.filesystem.expandHome(dir_setting, &joined); + const raw = pardes.filesystem.expandHome(tape, dir_setting, &joined); var fba_buf: [4096]u8 = undefined; var fba = std.heap.FixedBufferAllocator.init(&fba_buf); var cwd_buf: [1024]u8 = undefined; @@ -98,11 +98,11 @@ const Session = walk.Dump(&.{ Pardes, []const filesystem.Mount, OnDisk, []const const SessionLoad = walk.Load(&.{ Pardes, []const filesystem.Mount, OnDisk, []const u8, []const views.Shares }); const OnDisk = [MAX_PANES]bool; -fn onDisk(pane: *const pardes.panes.Pane) bool { +fn onDisk(tape: *pardes.tape.Tape, pane: *const pardes.panes.Pane) bool { const f = pane.file orelse return false; if (f.output != null) return false; const local = filesystem.localPath(f.path) orelse return false; - return exec.kindOf(local) != null; + return exec.kindOf(tape, local) != null; } pub fn dumpState(p: *Pardes) !void { @@ -177,8 +177,8 @@ pub fn dumpTo(p: *Pardes, to: ?[]const u8) !void { /// with a `/` or `~/` (as it resolves, else as typed: the read says why), /// or a bare word that names a file in the DumpDir or the directory pardes /// runs in; null for one that names none: a label of the state file's. -pub fn restoreFile(name: []const u8, dir_setting: []const u8, out: *[4096]u8) ?[]const u8 { - const path = filesystem.restorePath(name, dir_setting, out); +pub fn restoreFile(tape: *pardes.tape.Tape, name: []const u8, dir_setting: []const u8, out: *[4096]u8) ?[]const u8 { + const path = filesystem.restorePath(tape, name, dir_setting, out); if (std.mem.indexOfScalar(u8, name, '/') != null or std.mem.startsWith(u8, name, "~")) return path; return if (std.Io.Dir.path.isAbsolute(path)) path else null; } @@ -187,7 +187,7 @@ pub fn restoreFile(name: []const u8, dir_setting: []const u8, out: *[4096]u8) ?[ /// or an old byte dump), else the state file's dump of that label. pub fn restoreBytes(p: *Pardes, gpa: std.mem.Allocator, name: []const u8) ![]u8 { var buf: [4096]u8 = undefined; - if (restoreFile(name, p.settings.dump_dir.get(), &buf)) |path| return filesystem.readFile(gpa, path); + if (restoreFile(p.tape, name, p.settings.dump_dir.get(), &buf)) |path| return filesystem.readFile(p.tape, gpa, path); const got = p.db.getDump(p, gpa, name) catch |err| return if (err == error.OutOfMemory) error.OutOfMemory else error.BadDump; return got orelse error.FileNotFound; } @@ -222,7 +222,7 @@ pub fn image(p: *Pardes, name: []const u8) ![]u8 { var names: std.Io.Writer.Allocating = .init(gpa); defer names.deinit(); for (p.panes, &on_disk) |slot, *on| if (slot) |pane| { - on.* = onDisk(pane); + on.* = onDisk(p.tape, pane); panes += 1; const shown: []const u8 = if (pane.addon) |k| k.path else if (pane.file) |f| (if (f.output == null) f.path else "") else pane.cwdSlice(); if (shown.len == 0 or names.written().len + shown.len > 4096) continue; @@ -263,15 +263,18 @@ pub fn image(p: *Pardes, name: []const u8) ![]u8 { pub fn dumpJoin(p: *Pardes, deferred: *std.ArrayListUnmanaged(walk.Deferred)) ![]u8 { slim_terminals = true; defer slim_terminals = false; - join_files = true; - defer join_files = false; + // The join's file reads are the session's host's, between its steps: + // with its io, which the core's tape holds (a walk's hook takes no more). + join_files = p.tape.io; + defer join_files = null; return dumpWith(p, deferred); } /// `dumpJoin`'s and `dumpExit`'s: a terminal dumps its size, not its emulator. pub var slim_terminals = false; -/// `dumpJoin`'s: a plain kind's pane carries its file (SlotRecord.file). -var join_files = false; +/// `dumpJoin`'s: a plain kind's pane carries its file (SlotRecord.file), +/// read with this io. +var join_files: ?std.Io = null; fn dumpWith(p: *Pardes, deferred: ?*std.ArrayListUnmanaged(walk.Deferred)) ![]u8 { var d = try Session.init(p.gpa); @@ -282,7 +285,7 @@ fn dumpWith(p: *Pardes, deferred: ?*std.ArrayListUnmanaged(walk.Deferred)) ![]u8 try d.put([]const filesystem.Mount, &mounts); var on_disk: OnDisk = @splat(false); for (p.panes, &on_disk) |slot, *on| if (slot) |pane| { - on.* = onDisk(pane); + on.* = onDisk(p.tape, pane); }; try d.put(OnDisk, &on_disk); const theme: []const u8 = colors.themes[@min(p.settings.theme, colors.themes.len - 1)].name; @@ -536,12 +539,11 @@ pub fn restore(p: *Pardes, bytes: []const u8, from: []const u8) !*Pardes { pub fn initFromDump(gpa: std.mem.Allocator, opts: Options, bytes: []const u8) !*Pardes { pardes.tape.startFromEnv(); const taped = pardes.tape.enter(null, .{ .init_from_dump = .{ .opts = opts, .bytes = bytes } }); - const p = (if (Handover.carries(gpa, bytes)) carriedWindow(gpa, opts, bytes) else loadAndRevive(gpa, opts, bytes, null, null)) catch |err| { - pardes.tape.leave(null, taped); - return err; - }; - pardes.tape.leave(p, taped); - return p; + // The tape adopts the core made, none on a failure. + var made: ?*Pardes = null; + defer pardes.tape.leave(made, taped); + made = try (if (Handover.carries(gpa, bytes)) carriedWindow(gpa, opts, bytes) else loadAndRevive(gpa, opts, bytes, null, null)); + return made.?; } /// A window of its own for panes a grip carried out of another (Handover): @@ -692,7 +694,7 @@ fn revivePane(p: *Pardes, id: usize, pane: *pardes.panes.Pane, was_on_disk: bool // Its file gone from disk since the dump: its text is nowhere else, so // it is said deleted, and Del, Exit and Restore ask first. One never on // disk (a name not yet saved) comes back as it was. - if (was_on_disk and !onDisk(pane)) pardes.panes.File.deleted(p, @intCast(id)); + if (was_on_disk and !onDisk(p.tape, pane)) pardes.panes.File.deleted(p, @intCast(id)); } // ---- one pane to and from a dump: the store's, a handover's ---- @@ -809,10 +811,10 @@ pub fn slotWrite(s: *const Kind.Slot, gpa: std.mem.Allocator, w: *std.Io.Writer) // Paid only at a client's join: the session keeps no file's bytes. var file: ?[]u8 = null; defer if (file) |f| s.gpa.free(f); - if (join_files and s.plain != null and s.ops != null) if (filesystem.localPath(s.path)) |path| { + if (join_files) |io| if (s.plain != null and s.ops != null) if (filesystem.localPath(s.path)) |path| { const z = try s.gpa.dupeSentinel(u8, path, 0); defer s.gpa.free(z); - file = filesystem.readHost(s.gpa, z, pardes.memory.limits.max_file_bytes) catch null; + file = filesystem.readHost(io, s.gpa, z, pardes.memory.limits.max_file_bytes) catch null; r.file = file; }; const bytes = try walk.save(SlotRecord, gpa, &r); @@ -945,9 +947,9 @@ fn revivePdf(p: *Pardes, id: usize, pane: *pardes.panes.Pane, old: *pardes.panes test "a DumpDir reads back absolute, however it was written" { var buf: [4096]u8 = undefined; - try std.testing.expectEqualStrings("/tmp/dumps", directory(&buf, "/tmp/dumps/").?); - try std.testing.expectEqualStrings("/tmp/dumps", directory(&buf, "/tmp//x/../dumps").?); - const rel = directory(&buf, "rel/"); + try std.testing.expectEqualStrings("/tmp/dumps", directory(&pardes.tape.none, &buf, "/tmp/dumps/").?); + try std.testing.expectEqualStrings("/tmp/dumps", directory(&pardes.tape.none, &buf, "/tmp//x/../dumps").?); + const rel = directory(&pardes.tape.none, &buf, "rel/"); try std.testing.expect(std.Io.Dir.path.isAbsolute(rel.?) and std.mem.endsWith(u8, rel.?, "/rel")); } diff --git a/core/edit_cmd.zig b/core/edit_cmd.zig index a87fdfa2..495ec786 100644 --- a/core/edit_cmd.zig +++ b/core/edit_cmd.zig @@ -77,9 +77,9 @@ const World = struct { if (std.mem.eql(u8, f.path, path)) return true; } const local = filesystem.localPath(path) orelse return true; - if (@import("exec.zig").kindOf(local) == .directory) return said(bool, why, "B: {s} is a directory", .{path}) orelse false; + if (@import("exec.zig").kindOf(w.p.tape, local) == .directory) return said(bool, why, "B: {s} is a directory", .{path}) orelse false; var buf: [4096]u8 = undefined; - if (filesystem.resolveOs(local, &buf) == null) return said(bool, why, "B: {s}: no such file", .{path}) orelse false; + if (filesystem.resolveOs(w.p.tape, local, &buf) == null) return said(bool, why, "B: {s}: no such file", .{path}) orelse false; return true; } @@ -92,7 +92,7 @@ const World = struct { fn open(ctx: *anyopaque, path: []const u8, why: *sam.Why) ?sam.File { const w: *World = @ptrCast(@alignCast(ctx)); const p = w.p; - if (filesystem.localPath(path)) |local| if (@import("exec.zig").kindOf(local) == .directory) + if (filesystem.localPath(path)) |local| if (@import("exec.zig").kindOf(p.tape, local) == .directory) return said(sam.File, why, "B: {s} is a directory", .{path}); // A look opens it, or finds it open, where a look would; the // keyboard stays where the Edit ran. @@ -112,7 +112,7 @@ const World = struct { fn read(ctx: *anyopaque, arena: std.mem.Allocator, path: []const u8, why: *sam.Why) ?[]const u8 { const w: *World = @ptrCast(@alignCast(ctx)); - if (filesystem.localPath(path)) |local| if (@import("exec.zig").kindOf(local) == .directory) + if (filesystem.localPath(path)) |local| if (@import("exec.zig").kindOf(w.p.tape, local) == .directory) return said([]const u8, why, "{s} is a directory", .{path}); const bytes = filesystem.read(w.p, path) catch |err| { // In the words Get says them (builtins.Get). @@ -177,7 +177,7 @@ pub fn run(p: *Pardes, id: usize, command: []const u8) void { var world: World = .{ .p = p, .from = id, .arena = arena }; var why: sam.Why = .{}; var text: pardes.Kind.Buf(260) = .{}; - const res = sam.run(arena, files.items, cur, command, .{ .ctx = &world, .check = World.check, .open = World.open, .read = World.read, .refuseGet = World.refuseGet, .home = p.sessionHome() }, &why) catch |err| switch (err) { + const res = sam.run(arena, files.items, cur, command, .{ .ctx = &world, .check = World.check, .open = World.open, .read = World.read, .refuseGet = World.refuseGet, .home = p.sessionHome(), .tape = p.tape }, &why) catch |err| switch (err) { error.Edit => return p.reportFailure(id, text.print("Edit: {s}", .{why.text()})), error.OutOfMemory => return p.reportError(id, "Edit", err), }; diff --git a/core/exec.zig b/core/exec.zig index 3f3b16a7..0e09e175 100644 --- a/core/exec.zig +++ b/core/exec.zig @@ -423,19 +423,19 @@ pub fn missingDir(p: *Pardes, dir: []const u8) bool { // the shell would start: no command or terminal runs there, and none // is made to say `exit 127`. const local = @import("fs.zig").localPath(dir) orelse return std.mem.startsWith(u8, dir, "/n/"); - return kindOf(local) != .directory; + return kindOf(p.tape, local) != .directory; } /// What `path` is on this host, null when it is not there; the turn out /// while it asks (it may be inside a mount this editor serves). -pub fn kindOf(path: []const u8) ?std.Io.File.Kind { +pub fn kindOf(tape: *pardes.tape.Tape, path: []const u8) ?std.Io.File.Kind { var buf: [4096]u8 = undefined; const z = std.fmt.bufPrintSentinel(&buf, "{s}", .{path}, 0) catch return null; - return pardes.tape.site(.kind, null, kindHost, .{z}); + return tape.site(.kind, null, kindHost, .{z}); } -fn kindHost(z: [:0]const u8) ?std.Io.File.Kind { - const stat = @import("fs.zig").statPath(std.Io.Threaded.global_single_threaded.io(), z, .{}) catch return null; +fn kindHost(io: std.Io, z: [:0]const u8) ?std.Io.File.Kind { + const stat = @import("fs.zig").statPath(io, z, .{}) catch return null; return stat.kind; } @@ -1039,18 +1039,18 @@ pub fn applySettingBuiltin(p: *Pardes, setting: config.Runtime.Setting, arg: ?[] var text: pardes.Kind.Buf(340) = .{}; return p.reportFailure(v.active, text.print("Shell: {s}", .{refused})); } - if (!p.settings.apply(setting, want, p.sessionHome())) p.reportFailure(v.active, "Shell: takes " ++ comptime config.Runtime.takes(.shell).?); + if (!p.settings.apply(p.tape, setting, want, p.sessionHome())) p.reportFailure(v.active, "Shell: takes " ++ comptime config.Runtime.takes(.shell).?); }, // Bare, each says its value, as acme's Tab says the width. inline .tab, .callstack_depth => |_, tag| if (arg == null) { var said: pardes.Kind.Buf(40) = .{}; return p.setMessage(v.active, said.print("{s} {d}", .{ setting.word, @field(p.settings, @tagName(tag)) })); - } else if (!p.settings.apply(setting, arg, p.sessionHome())) { + } else if (!p.settings.apply(p.tape, setting, arg, p.sessionHome())) { var said: pardes.Kind.Buf(96) = .{}; p.reportFailure(v.active, said.print("{s}{s}: takes {s}", .{ setting.word, if (tag == .tab) ": invalid tab width" else "", comptime config.Runtime.takes(tag).? })); }, // Said with what it takes: its words, its range. - else => if (!p.settings.apply(setting, arg, p.sessionHome())) { + else => if (!p.settings.apply(p.tape, setting, arg, p.sessionHome())) { var buf: [160]u8 = undefined; var text: std.Io.Writer = .fixed(&buf); // A list of values too long for the row is cut. diff --git a/core/fs.zig b/core/fs.zig index f58e108b..27c28c9a 100644 --- a/core/fs.zig +++ b/core/fs.zig @@ -166,8 +166,7 @@ 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 io = std.Io.Threaded.global_single_threaded.io(); - const stat = pardes.tape.site(.os_stat, null, osStat, .{ io, path }) catch return Reply.fail(req.tag, E.NOENT); + const stat = p.tape.site(.os_stat, null, osStat, .{path}) catch return Reply.fail(req.tag, E.NOENT); const attr: Reply.Attr = .{ .name = if (req.node == os_root) "os" else std.Io.Dir.path.basename(path), .node = req.node, .dir = stat.kind == .directory, .size = stat.size, .mode = if (stat.kind == .directory) 0o755 else 0o644, .mtime = stat.mtime }; switch (req.op) { .getattr => return .{ .tag = req.tag, .attr = attr }, @@ -183,7 +182,7 @@ pub fn osHandle(p: *pardes.Pardes, req: Req) Reply { var buf: [4096]u8 = undefined; const joined = std.fmt.bufPrint(&buf, "{s}/{s}", .{ std.mem.trimEnd(u8, path, "/"), req.data }) catch return Reply.fail(req.tag, E.NOENT); var normalized_buf: [4096]u8 = undefined; - const normalized = resolveOs(joined, &normalized_buf) orelse return Reply.fail(req.tag, E.NOENT); + const normalized = resolveOs(p.tape, joined, &normalized_buf) orelse return Reply.fail(req.tag, E.NOENT); const node = osNode(p, normalized.path) catch return Reply.fail(req.tag, E.NFILE); return osHandle(p, .{ .tag = req.tag, .op = .getattr, .node = node }); }, @@ -191,7 +190,7 @@ pub fn osHandle(p: *pardes.Pardes, req: Req) Reply { // Listed into a buffer of this request's own first; the shared // reply buffer is another request's to use while the turn is out. var listing: [16 * 1024]u8 = undefined; - const listed = pardes.tape.site(.os_listing, null, osListing, .{ io, path, req.off, req.size, &listing }) catch |err| + const listed = p.tape.site(.os_listing, null, osListing, .{ path, req.off, req.size, &listing }) catch |err| return Reply.fail(req.tag, if (err == error.NotDir) E.NOTDIR else E.IO); const out = p.fs.stage(p.gpa); out.appendSlice(p.gpa, listed) catch return Reply.fail(req.tag, E.NOMEM); @@ -207,7 +206,7 @@ pub fn osHandle(p: *pardes.Pardes, req: Req) Reply { var z: [4096]u8 = undefined; const path_z = std.fmt.bufPrintSentinel(&z, "{s}", .{path}, 0) catch return Reply.fail(req.tag, E.NOENT); var buf: [ninep_io.msize]u8 = undefined; // a read never asks for more than a frame - const got = switch (pardes.tape.site(.os_rw, null, osReadWrite, .{ path_z, req, attr, &buf })) { + const got = switch (p.tape.site(.os_rw, null, osReadWrite, .{ path_z, req, attr, &buf })) { .reply => |reply| return reply, .read => |bytes| bytes, }; @@ -242,7 +241,8 @@ fn osListing(io: std.Io, path: []const u8, off: u64, size: u32, listing: *[16 * var buf: [4096]u8 = undefined; const joined = std.fmt.bufPrint(&buf, "{s}/{s}", .{ std.mem.trimEnd(u8, path, "/"), entry.name }) catch continue; var normalized_buf: [4096]u8 = undefined; - const normalized = resolveOs(joined, &normalized_buf) orelse continue; + // Inside a site's body, out of the turn: nothing in it is taped. + const normalized = resolveOs(&pardes.tape.none, joined, &normalized_buf) orelse continue; const child = dir.statFile(io, entry.name, .{}) catch continue; if (skip > 0) { skip -= 1; @@ -306,14 +306,14 @@ pub fn statPath(io: std.Io, path: []const u8, options: std.Io.Dir.StatFileOption /// Make `dir` and each directory above it that is missing, as `mkdir -p` /// does: one already there is no failure. A failure shows at the open /// that follows. -pub fn makeDirs(dir: []const u8) void { +pub fn makeDirs(tape: *pardes.tape.Tape, dir: []const u8) void { if (comptime !platform_has_fs) return; if (dir.len == 0) return; - pardes.tape.site(.make_dirs, null, makeDirsHost, .{dir}); + tape.site(.make_dirs, null, makeDirsHost, .{dir}); } -fn makeDirsHost(dir: []const u8) void { - _ = std.Io.Dir.cwd().createDirPathStatus(std.Io.Threaded.global_single_threaded.io(), dir, .fromMode(0o755)) catch {}; +fn makeDirsHost(io: std.Io, dir: []const u8) void { + _ = std.Io.Dir.cwd().createDirPathStatus(io, dir, .fromMode(0o755)) catch {}; } /// Whether `dir` is not there to make because one above it refuses: its @@ -339,6 +339,8 @@ pub fn localPath(path: []const u8) ?[]const u8 { } pub fn resolve(p: ?*pardes.Pardes, word: []const u8, cwd: []const u8, out: *[4096]u8) ?Resolved { + // The core's tape; none without a core (the launcher's, a test's). + const tape = if (p) |core| core.tape else &pardes.tape.none; if (word.len == 0 or std.mem.indexOfScalar(u8, word, 0) != null) return null; var joined_buf: [4096]u8 = undefined; const joined = if (word[0] == '/') word else std.fmt.bufPrint(&joined_buf, "{s}/{s}", .{ cwd, word }) catch return null; @@ -351,7 +353,7 @@ pub fn resolve(p: ?*pardes.Pardes, word: []const u8, cwd: []const u8, out: *[409 const path = if (cut < explicit.len) explicit[cut..] else "/"; if (std.mem.eql(u8, name, "os")) { var native_buf: [4096]u8 = undefined; - const native = resolveOs(path, &native_buf) orelse return null; + const native = resolveOs(tape, path, &native_buf) orelse return null; return .{ .path = std.fmt.bufPrint(out, "/n/os{s}", .{native.path}) catch return null }; } if (std.mem.eql(u8, name, "self")) return resolveVirtual(p, path, out); @@ -368,7 +370,7 @@ pub fn resolve(p: ?*pardes.Pardes, word: []const u8, cwd: []const u8, out: *[409 } if (std.mem.eql(u8, joined, "/virtual")) return resolveVirtual(p, "/", out); if (std.mem.startsWith(u8, joined, "/virtual/")) return resolveVirtual(p, joined[8..], out); - if (resolveOs(joined, out)) |found| return found; + if (resolveOs(tape, joined, out)) |found| return found; if (resolveVirtual(p, joined, out)) |found| return found; // `.`, `..` and `./x` name the pane's directory, never the served tree: // with that directory gone they name nothing (`.` would be /virtual/). @@ -398,14 +400,15 @@ pub fn dotRelative(word: []const u8) bool { /// runs it through here: look (B3 and 9P), name, Save, ThemeFile, DumpDir, /// Restore, a forwarded `pardes ~/x`. The path itself when there is no /// `~` to expand, or no home for it. -pub fn expandHome(path: []const u8, out: *[4096]u8) []const u8 { +pub fn expandHome(tape: *pardes.tape.Tape, path: []const u8, out: *[4096]u8) []const u8 { if (path.len == 0 or path[0] != '~') return path; // Home as the session that recorded found it (core/tape.zig). - return pardes.tape.value(.env, expandHomeHost, .{ path, out }); + return tape.value(.env, expandHomeHost, .{ path, out }); } fn expandHomeHost(path: []const u8, out: *[4096]u8) []const u8 { - return expandHomeFrom(path, out, processHome()); + // A site's body: nothing in it is taped. + return expandHomeFrom(&pardes.tape.none, path, out, processHome()); } /// This process's home: $HOME, else its passwd entry's; null for none. @@ -416,10 +419,10 @@ pub fn processHome() ?[]const u8 { /// expandHome with the home given (null: none, `~` left as typed): a /// session's (Pardes.expandHome), or this process's. `~user` is that /// user's passwd entry, as the session that recorded found it. -pub fn expandHomeFrom(path: []const u8, out: *[4096]u8, given: ?[]const u8) []const u8 { +pub fn expandHomeFrom(tape: *pardes.tape.Tape, path: []const u8, out: *[4096]u8, given: ?[]const u8) []const u8 { if (path.len == 0 or path[0] != '~') return path; const end = std.mem.indexOfAny(u8, path, "/:") orelse path.len; - const home = (if (end == 1) given else pardes.tape.value(.env, userHome, .{path[1..end]})) orelse return path; + const home = (if (end == 1) given else tape.value(.env, userHome, .{path[1..end]})) orelse return path; const trimmed = std.mem.trimEnd(u8, home, "/"); const rest = path[end..]; if (trimmed.len == 0 and (rest.len == 0 or rest[0] != '/')) return std.fmt.bufPrint(out, "/{s}", .{rest}) catch path; @@ -439,11 +442,11 @@ fn userHome(name: []const u8) ?[]const u8 { return std.mem.span(pw.dir orelse return null); } -pub fn resolveOs(path: []const u8, out: *[4096]u8) ?Resolved { +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 pardes.tape.site(.resolve, null, resolveHost, .{ path_z, out }); + return tape.site(.resolve, null, resolveHost, .{ path_z, out }); } fn resolveHost(path_z: [:0]const u8, out: *[4096]u8) ?Resolved { @@ -492,8 +495,8 @@ pub fn readLimit(p: *pardes.Pardes, path: []const u8, max_bytes: usize) ReadErro const remote_path = if (cut < explicit.len) explicit[cut..] else "/"; if (std.mem.eql(u8, name, "os")) { var native_buf: [4096]u8 = undefined; - const native = resolveOs(remote_path, &native_buf) orelse return readFileLimit(p.gpa, path, limit); - if (!native.dir) return readFileLimit(p.gpa, path, limit); + const native = resolveOs(p.tape, remote_path, &native_buf) orelse return readFileLimit(p.tape, p.gpa, path, limit); + if (!native.dir) return readFileLimit(p.tape, p.gpa, path, limit); // The node stays in the table until no connection names it either // (runtime/9p_io.zig, collectOs): a client may have walked to it too. const node = try osNode(p, native.path); @@ -507,7 +510,7 @@ pub fn readLimit(p: *pardes.Pardes, path: []const u8, max_bytes: usize) ReadErro if (!std.mem.eql(u8, name, mount.name)) continue; // A peer answers on its own time, and the peer may be this very // editor: the turn goes out with the request. - return pardes.tape.site(.read_mount, p.gpa, ninep_io.Client.readMount, .{ p.gpa, mount.dial, remote_path, path, limit }); + return p.tape.site(.read_mount, p.gpa, ninep_io.Client.readMount, .{ p.gpa, mount.dial, remote_path, path, limit }); } return error.FileNotFound; } @@ -515,7 +518,7 @@ pub fn readLimit(p: *pardes.Pardes, path: []const u8, max_bytes: usize) ReadErro const name = path[9..]; if (tree.resolveSelf(p, name)) |node| return readNode(p, node, path, limit); } - return readFileLimit(p.gpa, path, limit); + return readFileLimit(p.tape, p.gpa, path, limit); } fn readNode(p: *pardes.Pardes, initial_node: u64, path: []const u8, limit: usize) ![]u8 { @@ -682,39 +685,39 @@ fn isDir(path: [*:0]const u8) bool { return true; } -pub fn readFile(gpa: std.mem.Allocator, path: []const u8) ![]u8 { - return readFileLimit(gpa, path, limits.max_file_bytes); +pub fn readFile(tape: *pardes.tape.Tape, gpa: std.mem.Allocator, path: []const u8) ![]u8 { + return readFileLimit(tape, gpa, path, limits.max_file_bytes); } /// The file a Restore of `typed` reads (restorePath), whole. -pub fn readRestore(gpa: std.mem.Allocator, typed: []const u8, dir_setting: []const u8) ![]u8 { +pub fn readRestore(tape: *pardes.tape.Tape, gpa: std.mem.Allocator, typed: []const u8, dir_setting: []const u8) ![]u8 { var buf: [4096]u8 = undefined; - return readFile(gpa, restorePath(typed, dir_setting, &buf)); + return readFile(tape, gpa, restorePath(tape, typed, dir_setting, &buf)); } /// The file a Restore of `typed` reads, whole: `~` expanded, a relative name /// the DumpDir's when one is there, else the current directory's. What the /// log and the message say, not the name as typed. `typed` itself (home /// expanded) when nothing resolves: the read then says why. -pub fn restorePath(typed: []const u8, dir_setting: []const u8, out: *[4096]u8) []const u8 { +pub fn restorePath(tape: *pardes.tape.Tape, typed: []const u8, dir_setting: []const u8, out: *[4096]u8) []const u8 { var home_buf: [4096]u8 = undefined; - const path = expandHome(typed, &home_buf); + const path = expandHome(tape, typed, &home_buf); if (!std.Io.Dir.path.isAbsolute(path)) { var dir_buf: [4096]u8 = undefined; - if (@import("dump.zig").directory(&dir_buf, dir_setting)) |base| { + if (@import("dump.zig").directory(tape, &dir_buf, dir_setting)) |base| { var buf: [4096]u8 = undefined; if (std.fmt.bufPrint(&buf, "{s}/{s}", .{ base, path })) |candidate| { - if (resolveOs(candidate, out)) |r| if (!r.dir) return r.path; + if (resolveOs(tape, candidate, out)) |r| if (!r.dir) return r.path; } else |_| {} } } - if (resolveOs(path, out)) |r| return r.path; + if (resolveOs(tape, path, out)) |r| return r.path; const n = @min(path.len, out.len); @memcpy(out[0..n], path[0..n]); return out[0..n]; } -fn readFileLimit(gpa: std.mem.Allocator, path: []const u8, limit: usize) ![]u8 { +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; @@ -729,12 +732,12 @@ fn readFileLimit(gpa: std.mem.Allocator, path: []const u8, limit: usize) ![]u8 { const path_z = std.fmt.bufPrintSentinel(&pathbuf, "{s}", .{native}, 0) catch return error.PathTooLong; // The path may be a mount this editor serves: the turn goes out with the // syscalls, and the bytes come back into memory of the caller's own. - return pardes.tape.site(.read_file, gpa, readHost, .{ gpa, path_z, limit }); + return tape.site(.read_file, gpa, readHost, .{ gpa, path_z, limit }); } /// The disk's file at `path_z`, whole: the session's read, and a replica /// client's of a read it was sent by hash (tape.zig `byHash`). -pub fn readHost(gpa: std.mem.Allocator, path_z: [:0]const u8, limit: usize) ![]u8 { +pub fn readHost(io: std.Io, gpa: std.mem.Allocator, path_z: [:0]const u8, limit: usize) ![]u8 { const fd = libc.open(path_z, .{ .ACCMODE = .RDONLY, .NONBLOCK = true }); if (fd < 0) return switch (libc.errno(fd)) { .ACCES, .PERM => error.PermissionDenied, @@ -745,7 +748,7 @@ pub fn readHost(gpa: std.mem.Allocator, path_z: [:0]const u8, limit: usize) ![]u }; defer _ = libc.close(fd); // What it is before its bytes are read, for a watch armed over them. - const before = (std.Io.File{ .handle = fd, .flags = .{ .nonblocking = true } }).stat(std.Io.Threaded.global_single_threaded.io()) catch null; + const before = (std.Io.File{ .handle = fd, .flags = .{ .nonblocking = true } }).stat(io) catch null; // A device (/dev/zero, a tty) is no file to read whole: said so, not // read to the stream limit and called too large. @@ -1280,10 +1283,10 @@ test "bounded reads apply the same limits to self bodies and embedded sources" { try std.testing.expectEqualStrings(source.contents, bytes); try std.testing.expectError(error.FileTooLarge, readLimit(p, path, source.contents.len - 1)); } - const bytes = try readFileLimit(gpa, "/virtual/src/look.zig", source.contents.len); + const bytes = try readFileLimit(&pardes.tape.none, gpa, "/virtual/src/look.zig", source.contents.len); defer gpa.free(bytes); try std.testing.expectEqualStrings(source.contents, bytes); - try std.testing.expectError(error.FileTooLarge, readFileLimit(gpa, "/virtual/src/look.zig", source.contents.len - 1)); + try std.testing.expectError(error.FileTooLarge, readFileLimit(&pardes.tape.none, gpa, "/virtual/src/look.zig", source.contents.len - 1)); } } @@ -1336,7 +1339,7 @@ test "bounded reads probe size-unknown proc files at the exact limit" { try std.testing.expect(expected.len > 0); var storage: [256 * 1024]u8 = undefined; var fixed = std.heap.FixedBufferAllocator.init(&storage); - const bounded = try readFileLimit(fixed.allocator(), "/proc/version", limits.max_stream_bytes); + const bounded = try readFileLimit(&pardes.tape.none, fixed.allocator(), "/proc/version", limits.max_stream_bytes); try std.testing.expectEqualStrings(expected, bounded); fixed.allocator().free(bounded); for ([_][]const u8{ "/proc/version", "/n/os/proc/version" }) |path| { @@ -1385,7 +1388,7 @@ test "oversized OS files fail before allocating their contents" { var path_buf: [4096]u8 = undefined; const path_len = try tmp.dir.realPathFile(std.testing.io, "oversized", &path_buf); var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = 0 }); - try std.testing.expectError(error.FileTooLarge, readFile(failing.allocator(), path_buf[0..path_len])); + try std.testing.expectError(error.FileTooLarge, readFile(&pardes.tape.none, failing.allocator(), path_buf[0..path_len])); try std.testing.expectEqual(@as(usize, 0), failing.allocations); } @@ -1465,16 +1468,16 @@ test "a leading ~ is home, from HOME or else the passwd entry" { var out: [4096]u8 = undefined; const home = homeDir(std.c.getenv("HOME")) orelse return error.SkipZigTest; var want: [4096]u8 = undefined; - try std.testing.expectEqualStrings(try std.fmt.bufPrint(&want, "{s}/x:12", .{std.mem.trimEnd(u8, home, "/")}), expandHome("~/x:12", &out)); - try std.testing.expectEqualStrings(std.mem.trimEnd(u8, home, "/"), expandHome("~", &out)); - try std.testing.expectEqualStrings("a/~/b", expandHome("a/~/b", &out)); - try std.testing.expectEqualStrings("~no-such-user-pardes/x", expandHome("~no-such-user-pardes/x", &out)); - try std.testing.expectEqualStrings("/", expandHome("~root", &out)[0..1]); + try std.testing.expectEqualStrings(try std.fmt.bufPrint(&want, "{s}/x:12", .{std.mem.trimEnd(u8, home, "/")}), expandHome(&pardes.tape.none, "~/x:12", &out)); + try std.testing.expectEqualStrings(std.mem.trimEnd(u8, home, "/"), expandHome(&pardes.tape.none, "~", &out)); + try std.testing.expectEqualStrings("a/~/b", expandHome(&pardes.tape.none, "a/~/b", &out)); + try std.testing.expectEqualStrings("~no-such-user-pardes/x", expandHome(&pardes.tape.none, "~no-such-user-pardes/x", &out)); + try std.testing.expectEqualStrings("/", expandHome(&pardes.tape.none, "~root", &out)[0..1]); // HOME unset: the passwd entry's home. const pw = std.c.getpwuid(std.c.getuid()) orelse return error.SkipZigTest; var from_passwd: [4096]u8 = undefined; - try std.testing.expectEqualStrings(try std.fmt.bufPrint(&from_passwd, "{s}/y", .{std.mem.trimEnd(u8, std.mem.span(pw.dir.?), "/")}), expandHomeFrom("~/y", &out, homeDir(null))); + try std.testing.expectEqualStrings(try std.fmt.bufPrint(&from_passwd, "{s}/y", .{std.mem.trimEnd(u8, std.mem.span(pw.dir.?), "/")}), expandHomeFrom(&pardes.tape.none, "~/y", &out, homeDir(null))); } test "Restore prefers default directory then falls back to original path" { @@ -1490,25 +1493,25 @@ test "Restore prefers default directory then falls back to original path" { defer gpa.free(nested); try tmp.dir.createDirPath(std.testing.io, nested); try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "dumps/a.dump", .data = "short name" }); - const short = try readRestore(gpa, "a.dump", base); + const short = try readRestore(&pardes.tape.none, gpa, "a.dump", base); defer gpa.free(short); try std.testing.expectEqualStrings("short name", short); try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "a.dump", .data = "original" }); - const fallback = try readRestore(gpa, relative, base); + const fallback = try readRestore(&pardes.tape.none, gpa, relative, base); defer gpa.free(fallback); try std.testing.expectEqualStrings("original", fallback); const candidate = try std.fmt.allocPrint(gpa, "{s}/{s}", .{ base, relative }); defer gpa.free(candidate); try writeFile(candidate, "default"); - const preferred = try readRestore(gpa, relative, base); + const preferred = try readRestore(&pardes.tape.none, gpa, relative, base); defer gpa.free(preferred); try std.testing.expectEqualStrings("default", preferred); const absolute = try tmp.dir.realPathFileAlloc(std.testing.io, "a.dump", gpa); defer gpa.free(absolute); - const direct = try readRestore(gpa, absolute, base); + const direct = try readRestore(&pardes.tape.none, gpa, absolute, base); defer gpa.free(direct); try std.testing.expectEqualStrings("original", direct); - try std.testing.expectError(error.FileNotFound, readRestore(gpa, "missing-restore-test.dump", base)); + try std.testing.expectError(error.FileNotFound, readRestore(&pardes.tape.none, gpa, "missing-restore-test.dump", base)); } test { diff --git a/core/hunks.zig b/core/hunks.zig index d3a8f5a7..a7d8e6cb 100644 --- a/core/hunks.zig +++ b/core/hunks.zig @@ -634,7 +634,7 @@ pub fn word(c: pardes.builtins.Ctx) void { while (true) { var buf: [4096]u8 = undefined; const dot_git = std.fmt.bufPrint(&buf, "{s}/.git", .{dir}) catch return declined(p, c.id, "Diff: not in a git work tree"); - if (pardes.exec.kindOf(dot_git) != null) break; + if (pardes.exec.kindOf(p.tape, dot_git) != null) break; dir = std.Io.Dir.path.dirname(dir) orelse return declined(p, c.id, "Diff: not in a git work tree"); } // ponytail: a hex word that names no commit leaves git's error in a command pane, not a search; check the object first if that bites. diff --git a/core/look.zig b/core/look.zig index 170e5ea9..e075bbae 100644 --- a/core/look.zig +++ b/core/look.zig @@ -1032,7 +1032,7 @@ fn lookUnresolved(p: *Pardes, id: usize, pane: *Pane, trimmed: []const u8, text: if (filesystem.dotRelative(trimmed)) { const dir = Pardes.paneDir(pane); var said: Kind.Buf(4096 + 104) = .{}; - const gone = if (filesystem.localPath(dir)) |local| exec.kindOf(local) != .directory else false; + const gone = if (filesystem.localPath(dir)) |local| exec.kindOf(p.tape, local) != .directory else false; if (gone) return p.reportFailure(id, said.print("look: {s}: no such directory", .{dir[0..@min(dir.len, 4096)]})); // A file not there is a miss, as `x` and `/abs/x` are: said and // logged, the write answered with nothing. @@ -1569,7 +1569,7 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { .dir => |dir| { // A directory that is not there (the pane's own, gone): said, // ENOENT, no terminal made in it. - if (filesystem.localPath(dir)) |local| if (exec.kindOf(local) != .directory) { + if (filesystem.localPath(dir)) |local| if (exec.kindOf(p.tape, local) != .directory) { var said: Kind.Buf(4096 + 104) = .{}; return p.reportFailure(id, said.print("look: {s}: no such directory", .{dir[0..@min(dir.len, 4096)]})); }; diff --git a/core/ninep/ctl.zig b/core/ninep/ctl.zig index 81600582..a4f16597 100644 --- a/core/ninep/ctl.zig +++ b/core/ninep/ctl.zig @@ -571,7 +571,7 @@ fn checkBuiltin(p: *Pardes, req: Req, line: []const u8, scope: builtins.Scope) ? .callstack_depth => arg.len == 0 or (std.fmt.parseInt(u8, arg, 10) catch 0) -% 1 < pardes.lsp.callstack_max_depth, else => probe: { var probe = p.settings; - break :probe probe.apply(setting, if (arg.len > 0) arg else null, p.sessionHome()); + break :probe probe.apply(p.tape, setting, if (arg.len > 0) arg else null, p.sessionHome()); }, }; if (takes) return null; @@ -679,13 +679,13 @@ pub fn writePager(p: *Pardes, req: Req) Reply { } if (dir.len > 0) if (pardes.filesystem.localPath(dir)) |local| { // A file there is no directory, ENOTDIR; nothing there, ENOENT. - if (exec_line.kindOf(local) != .directory) { - if (exec_line.kindOf(local) != null) + if (exec_line.kindOf(p.tape, local) != .directory) { + if (exec_line.kindOf(p.tape, local) != null) return tree.failText(req.tag, E.NOTDIR, std.fmt.bufPrint(&p.fs.ename, "pager: {s}: not a directory", .{dir[0..@min(dir.len, 256)]}) catch &p.fs.ename); // cut to ename's 320 return tree.failText(req.tag, E.NOENT, std.fmt.bufPrint(&p.fs.ename, "pager: {s}: no such directory", .{dir[0..@min(dir.len, 256)]}) catch &p.fs.ename); // cut to ename's 320 } // Nor one that may not be written, as a file's name there is refused. - if (pardes.filesystem.deniedAbove(local)) + if (p.tape.value(.denied, pardes.filesystem.deniedAbove, .{local})) return tree.failText(req.tag, E.PERM, std.fmt.bufPrint(&p.fs.ename, "pager: {s}: permission denied", .{dir[0..@min(dir.len, 256)]}) catch &p.fs.ename); // cut to ename's 320 }; const id = pardes.panes.Output.openPager(p, p.view().active, dir) catch |err| @@ -773,7 +773,7 @@ pub fn writeRoot(p: *Pardes, req: Req) Reply { if (!apply) continue; // ponytail: read on the 9P task, a small local file; a big // one would want pardes.turn's yield. - const bytes = fs.readFile(p.gpa, path) catch |err| return refuseQuoting(p, req, @errorName(err), path, ""); + const bytes = fs.readFile(p.tape, p.gpa, path) catch |err| return refuseQuoting(p, req, @errorName(err), path, ""); defer p.gpa.free(bytes); _ = pardes.Handover.adopt(p, bytes) catch |err| return refuseQuoting(p, req, @errorName(err), path, ""); continue; diff --git a/core/ninep/pane.zig b/core/ninep/pane.zig index 16d7762a..96a50703 100644 --- a/core/ninep/pane.zig +++ b/core/ninep/pane.zig @@ -900,7 +900,7 @@ fn writeName(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { // A directory (`~`, `/`, `foo/`) is no file to name a pane after: a // Save could only fail. Said now, EISDIR. const is_dir = name[name.len - 1] == '/' or std.mem.eql(u8, full, "/") or - (if (fs.localPath(full)) |local| exec.kindOf(local) == .directory else false); + (if (fs.localPath(full)) |local| exec.kindOf(p.tape, local) == .directory else false); if (is_dir) return tree.failText(req.tag, E.ISDIR, std.fmt.bufPrint(&p.fs.ename, "name: {s} is a directory, not a file", .{full[0..@min(full.len, 256)]}) catch &p.fs.ename); // cut to ename's 320 nameBuffer(p, id, full, false) catch |err| return Reply.fail(req.tag, switch (err) { error.OutOfMemory => E.NOMEM, @@ -944,7 +944,7 @@ pub fn nameBuffer(p: *Pardes, id: usize, full: []const u8, preserve_tag: bool) ! p.emit(.{ .watch = .{ .pane = @intCast(id), .on = false } }); events.noteLog(p, .rename, pane); // A name given: whether a file there is on disk is the disk's to say. - f.on_disk = f.output == null and pardes.Pardes.recentKeeps(f.path); + f.on_disk = f.output == null and pardes.Pardes.recentKeeps(p.tape, f.path); if (f.on_disk) p.recent.opened(p.recentGpa(), f.path); } diff --git a/core/replica.zig b/core/replica.zig index 01a0b79d..ae2616b7 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -2214,6 +2214,7 @@ pub const Peers = struct { ps.t.whole_digest = std.c.getenv("PARDES_REPLICA_TRACE") == null; ps.screens = .init(ps.gpa); tape.on = &ps.t; + core.tape = &ps.t; ps.recording = true; ps.samples = std.c.getenv("PARDES_REPLICA_STATS") != null; } @@ -2418,6 +2419,7 @@ pub const Peers = struct { 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); ps.recording = false; } diff --git a/core/rollback.zig b/core/rollback.zig index a6c6e5bd..53c7b210 100644 --- a/core/rollback.zig +++ b/core/rollback.zig @@ -523,11 +523,12 @@ fn annotatedStruct(comptime T: type) bool { /// own: on the host's heap (Pardes.recentGpa), which the epoch never puts a /// free off for, so their bytes put back would point at what is freed. A /// step reads what the authority holds of them off the tape -/// (tape.authority), never a replica's. +/// (tape.authority), never a replica's. And the core's tape (`Pardes.tape`, +/// `Options.tape`): the process's, which a rollback leaves where it is. fn unsaved(comptime name: []const u8) bool { return std.mem.eql(u8, name, "effects") or std.mem.eql(u8, name, "in_q") or std.mem.eql(u8, name, "frames") or std.mem.eql(u8, name, "own_frames") or std.mem.eql(u8, name, "shell_rows") or std.mem.eql(u8, name, "echo") or std.mem.eql(u8, name, "store") or - std.mem.eql(u8, name, "recent"); + std.mem.eql(u8, name, "recent") or std.mem.eql(u8, name, "tape"); } fn annotated(comptime T: type, comptime kind: []const u8, comptime name: []const u8) bool { @@ -801,3 +802,35 @@ test "a rollback leaves the store and Recent as a speculation left them: they li p.deinit(); try std.testing.expectEqual(@as(usize, 0), e.live.count()); } + +test "a core's tape is this process's own: no digest or dump holds it, and a rollback leaves it where it was set" { + var e: Epoch = .{ .child = std.testing.allocator }; + defer e.deinit(); + const gpa = e.allocator(); + const p = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml", .image_allocator = gpa, .tree_sitter_allocator = gpa, .frame_allocator = gpa }); + p.pump(.{}) catch {}; + // Given none, a core's tape is the one nobody records. + try std.testing.expect(p.tape == &pardes.tape.none); + var other = pardes.tape.memory(std.testing.allocator); + defer pardes.tape.release(&other); + const digest = walk.digest(Pardes, p); + const dumped = try pardes.dump.byteDump(p); + p.tape = &other; + try std.testing.expectEqual(digest, walk.digest(Pardes, p)); + const again = try pardes.dump.byteDump(p); + try std.testing.expectEqualSlices(u8, dumped, again); + gpa.free(again); + gpa.free(dumped); + p.tape = &pardes.tape.none; + // Handed another while a copy is held (a client joins: replica.zig's + // Peers), it keeps it when the copy is put back. + var c: Copy = .{}; + defer c.deinit(); + try c.take(&e, p); + p.tape = &other; + try std.testing.expect(c.restore()); + try std.testing.expect(p.tape == &other); + p.tape = &pardes.tape.none; + p.deinit(); + try std.testing.expectEqual(@as(usize, 0), e.live.count()); +} diff --git a/core/root.zig b/core/root.zig index 04909bd7..706c833d 100644 --- a/core/root.zig +++ b/core/root.zig @@ -480,6 +480,7 @@ const allowed_vars = [_]struct { []const u8, []const u8, []const u8 }{ .{ "syntax.zig", "handed handed_exts handed_n", "the languages an editor library's user hands in" }, .{ "syntax.zig", "held_trees", "the trees of the core being stepped, switched per step" }, .{ "tape.zig", "on", "the tape of the core being stepped, switched per step" }, + .{ "tape.zig", "none", "the tape of a session nobody records: never written" }, .{ "walk.zig", "in_blob blobs_out", "a walk's context, set and put back (threadlocal)" }, .{ "walk.zig", "state bytes", "a type's table, made once" }, .{ "term/TerminalImages.zig", "started", "the PNG resize has its allocator, set at start" }, @@ -607,7 +608,7 @@ const machine_lines = [_]struct { []const u8, usize, []const u8 }{ .{ "Addon.zig", 48, "the process's addon libraries: the start's scan of their directories, dlopen, the crash mark; the host's, never a step's" }, .{ "Core.zig", 5, "the session's directory read once at its start (taped), a frame log (PARDES_FRAMES), a host_io type" }, .{ "Db.zig", 18, "the state file every session of the user shares: the authority's (`db`), off in every replica" }, - .{ "Dir.zig", 2, "a directory's listing, the function under tape.site(.dir_listing)" }, + .{ "Dir.zig", 1, "a directory's listing, the function under tape.site(.dir_listing), its io the tape's" }, .{ "Effect.zig", 1, "host_io, named for the host entries it performs" }, .{ "FrameStats.zig", 7, "a frame's clock and log: frames are local, never digested" }, .{ "Handover.zig", 29, "a window carried to another process over a socket: the session's host" }, @@ -621,8 +622,8 @@ const machine_lines = [_]struct { []const u8, usize, []const u8 }{ .{ "dump.zig", 4, "a dump's clock and the state file's directory (XDG, the process's directory): the session's side (a client's Restore waits)" }, .{ "echo.zig", 1, "PARDES_REPLICA_TRACE: a trace" }, .{ "edit_cmd.zig", 1, "Edit's pipe environment (host_io.commandEnv): kept in Pipe.edit_run, `.authority` state, read only by the host's `pipe`, which a client never calls" }, - .{ "exec.zig", 4, "kindOf's stat (tape.site(.kind)) and Shell's check (tape.site(.shell))" }, - .{ "fs.zig", 39, "the file system behind the tape's sites (open, read, write, stat, mkdir, access), the process's home (read once at the start, taped), the 9P transport" }, + .{ "exec.zig", 3, "kindOf's stat (tape.site(.kind), its io the tape's) and Shell's check (tape.site(.shell))" }, + .{ "fs.zig", 38, "the file system behind the tape's sites (open, read, write, stat, mkdir, access; their io the tape's), the process's home (read once at the start, taped), the 9P transport" }, .{ "hunks.zig", 1, "a test helper's file read" }, .{ "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)" }, @@ -630,7 +631,7 @@ const machine_lines = [_]struct { []const u8, usize, []const u8 }{ .{ "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", 10, "the tape's own files and host_io's types: a recording, a replay" }, + .{ "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" }, .{ "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" }, diff --git a/core/sam_edit.zig b/core/sam_edit.zig index 4d7d6a27..0f4a70ba 100644 --- a/core/sam_edit.zig +++ b/core/sam_edit.zig @@ -85,6 +85,8 @@ pub const World = struct { refuseGet: *const fn (ctx: *anyopaque, id: usize, why: *Why) bool, /// What `~` is: the session's home (null: none). home: ?[]const u8 = null, + /// The session's tape, which a `~user` read goes through (none: nobody's). + tape: *@import("tape.zig").Tape = &@import("tape.zig").none, }; /// What an Edit came to: every file (those `B` opened after the ones it @@ -670,7 +672,7 @@ const Exec = struct { fn pathIn(ex: *Exec, fi: usize, name_in: []const u8) Failure![]const u8 { // `~` and `~user` as Get, Incl and Save read them. var home: [4096]u8 = undefined; - const name = try ex.arena.dupe(u8, @import("fs.zig").expandHomeFrom(name_in, &home, if (ex.world) |w| w.home else null)); + const name = try ex.arena.dupe(u8, @import("fs.zig").expandHomeFrom(if (ex.world) |w| w.tape else &@import("tape.zig").none, name_in, &home, if (ex.world) |w| w.home else null)); if (name.len > 0 and name[0] == '/') return name; const dir = std.Io.Dir.path.dirnamePosix(ex.files.items[fi].name) orelse "/"; return std.Io.Dir.path.resolvePosix(ex.arena, &.{ dir, name }); diff --git a/core/tape.zig b/core/tape.zig index 270147c2..dc80887c 100644 --- a/core/tape.zig +++ b/core/tape.zig @@ -15,8 +15,11 @@ //! made, and each digest is checked against the recorded one -- by two //! replicas at different addresses and a third that never draws. //! -//! The local path pays a null check a call: `on` is null unless -//! PARDES_RECORD names where to write, `<prefix><pid>.tape`. +//! The local path pays a check a call: `on` is null, and a core's tape is +//! `none` (it records nothing), unless PARDES_RECORD names where to write, +//! `<prefix><pid>.tape`. A core holds its tape (`Pardes.tape`) as it holds +//! its allocator; the free functions read `on`, set beside it, until the +//! last of their callers is handed the tape (P20). const std = @import("std"); const pardes = @import("root.zig"); const walk = @import("walk.zig"); @@ -27,6 +30,10 @@ const libc = std.c; pub var on: ?*Tape = null; +/// The tape of a session nobody records (`Tape.through`): a core's when it +/// is given none, so `Pardes.tape` is never null. Nothing writes it. +pub var none: Tape = .{ .gpa = std.heap.page_allocator, .replay = false, .through = true, .scratch = .init(std.heap.page_allocator), .arena = .init(std.heap.page_allocator) }; + /// Every call into the core a host makes (a 9P connection task's too). pub const Input = union(enum) { init: pardes.Options, @@ -217,6 +224,12 @@ const set_mask = 0xff; pub const Tape = struct { gpa: std.mem.Allocator, + /// Zig's `io`, handed to a site's body: in core/, a body is the only + /// code that holds one. + io: std.Io = std.Io.Threaded.global_single_threaded.io(), + /// A session nobody records (`none`): every call goes through as it + /// is, and nothing is taped. + through: bool = false, replay: bool, /// The core whose digest is taken (a Restore replaces it). core: ?*Pardes = null, @@ -462,7 +475,7 @@ pub const Tape = struct { for (t.files.items) |f| if (std.mem.eql(u8, &f.hash, hash)) return f.bytes; const path = t.reading orelse return null; if (!t.local_files or !is_path) return null; - const file = pardes.filesystem.readHost(t.gpa, path, pardes.memory.limits.max_file_bytes) catch return null; + const file = pardes.filesystem.readHost(t.io, t.gpa, path, pardes.memory.limits.max_file_bytes) catch return null; defer t.gpa.free(file); // The answer as `record` wrote it: an error union's yes, a length, the bytes. const bytes = t.gpa.alloc(u8, 9 + file.len) catch return null; @@ -594,11 +607,17 @@ pub const Tape = struct { fn dumpRoundTrip(t: *Tape, p: *Pardes) void { on = null; defer on = t; + // The core's own tape aside too: the dump's reads are no input. + p.tape = &none; + defer p.tape = t; const bytes = pardes.dump.dumpBytes(p) catch |err| return t.diverge("dump failed: {t}", .{err}); defer t.gpa.free(bytes); var notes: std.ArrayList(u8) = .empty; defer notes.deinit(t.gpa); - const q = pardes.dump.load(t.gpa, p.opts, bytes, ¬es) catch |err| return t.diverge("dump load failed: {t}", .{err}); + // Its own core, on no tape (the session's options name this one). + var opts = p.opts; + opts.tape = &none; + const q = pardes.dump.load(t.gpa, opts, bytes, ¬es) catch |err| return t.diverge("dump load failed: {t}", .{err}); defer q.deinit(); if (notes.items.len > 0) return t.diverge("dump of this build had notes: {s}", .{notes.items}); var want: Parts = undefined; @@ -657,6 +676,7 @@ pub const Tape = struct { opts.image_allocator = gpa; opts.tree_sitter_allocator = gpa; opts.frame_allocator = gpa; + opts.tape = t; t.core = switch (input) { .init => Pardes.init(gpa, opts), .init_from_dump => |d| pardes.dump.initFromDump(gpa, opts, d.bytes), @@ -673,6 +693,7 @@ pub const Tape = struct { .restore => |rs| { const nc = pardes.dump.restore(p, rs.bytes, rs.from) 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 @@ -728,6 +749,204 @@ pub const Tape = struct { } t.finishInput(); } + + // ---- the entry points, on the handle a step is given (`Pardes.tape`, + // or a `tape: *Tape` parameter); the free functions below are the + // same on `on` until the last of their callers is moved ---- + + /// A syscall of the core's own, `f(args)`, made out of the turn (a 9P + /// request through a mount of this very session is answered meanwhile): + /// recorded with what it returned, or answered from the tape and never + /// made. A result with slices is decoded into `a` on replay, the allocator + /// `f` would have used. + pub fn site(t: *Tape, comptime s: Site, a: ?std.mem.Allocator, comptime f: anytype, args: anytype) @typeInfo(@TypeOf(f)).@"fn".return_type.? { + return t.call(s, a, f, args, true); + } + + /// A read of the host's that is no syscall out of the turn (the clock, the + /// environment) or yields for itself: as `site`. + pub fn value(t: *Tape, comptime s: Site, comptime f: anytype, args: anytype) @typeInfo(@TypeOf(f)).@"fn".return_type.? { + return t.call(s, null, f, args, false); + } + + /// A read of what the authority alone holds (`.authority` state a step + /// makes digested state from: the session's closed panes, and Recent, which + /// every session of its user writes; the 9P server's readers and socket), + /// taped as `value` is; a speculation that reaches it waits for the + /// authority's answer, as at a host call. A replica's own is never read. + /// What it returns is the tape's arena's on a replay: `f` returns what + /// lives to the step's end (scratch, or the authority's own), and the + /// caller copies what it keeps. + /// + /// A yes or no (whether a script reads a pane's events, whether the + /// session serves a socket) is guessed by a speculation, mosh's way: the + /// authority's last answer to that question, as a replayed unit gave it, + /// recorded as the answer, so its unit confirms the guess or rolls it back. + /// A Look or a click's command in a pane then shows at once, not a round + /// trip late. ponytail: bools alone; a list (the closed panes, Recent) + /// changes with what the user does, and is asked of the authority. + pub fn authority(t: *Tape, comptime f: anytype, args: anytype) @typeInfo(@TypeOf(f)).@"fn".return_type.? { + if (comptime @typeInfo(@TypeOf(f)).@"fn".return_type.? == bool) { + if (t.speculating) if (t.answers.get(question(f, args))) |was| { + const id: u16 = @as(u16, host_fns.len) + @backingInt(Site.authority); + t.record(.host, u16, &id); + t.record(.ret, bool, &was); + return was; + }; + if (t.replay) { + const got = t.value(.authority, f, args); + t.answers.put(t.gpa, question(f, args), got) catch {}; + return got; + } + } + t.poison("the authority's own state"); + return t.value(.authority, f, args); + } + + /// A budget of `budget_ns` from `since_ns` on the monotonic clock is spent: + /// what the clock said is taped, so a replica stops its work where this did. + pub fn over(t: *Tape, since_ns: u64, budget_ns: u64) bool { + return t.value(.budget, overNow, .{ since_ns, budget_ns }); + } + + /// A body whose first parameter is an `std.Io` its caller does not pass + /// is handed the tape's (`args` are the rest): the only way core/ comes + /// to hold one. + fn call(t: *Tape, comptime s: Site, a: ?std.mem.Allocator, comptime f: anytype, args: anytype, comptime yields: bool) @typeInfo(@TypeOf(f)).@"fn".return_type.? { + const R = @typeInfo(@TypeOf(f)).@"fn".return_type.?; + const params = @typeInfo(@TypeOf(f)).@"fn".param_types; + const full = if (comptime params.len == args.len + 1 and params[0] == std.Io) .{t.io} ++ args else args; + comptime { + const Listed = if (@typeInfo(R) == .error_union) anyerror!@typeInfo(R).error_union.payload else R; + for (results) |T| { + if (T == Listed) break; + } else @compileError("tape: the site ." ++ @tagName(s) ++ " returns " ++ @typeName(R) ++ ", which tape.results does not list"); + } + // No tape where there is no host to record or replay one. + if (t.through) return if (yields) out(f, full) else @call(.auto, f, full); + const id: u16 = @as(u16, host_fns.len) + @backingInt(s); + if (comptime s == .read_file) t.reading = args[1]; + defer if (comptime s == .read_file) { + t.reading = null; + }; + if (t.replay) { + // Diverged (said in `diverged`): what a speculation gets, harmless, + // for the rest of the input. A replica joins again; a replay says so. + if (!t.expectHost(id, @tagName(s))) return poisonOf(R); + var ret = t.last_ret; + return walk.decode(R, &ret, a orelse t.arena.allocator()) catch { + t.diverge("the tape's answer to {t} is short", .{s}); + return poisonOf(R); + }; + } + // The host's own (a shell's spawn asking the shell), or one inside a + // site's syscall: the outer call is the record. + if (t.host_side) return if (yields) out(f, full) else @call(.auto, f, full); + // A syscall a speculating replica must not make: its input waits for + // the authority's answer. + if (yields and t.speculating) { + t.poisoned = true; + t.poisoned_by = @tagName(s); + return poisonOf(R); + } + if (comptime s == .clock or s == .mtime) if (if (t.speculating) t.guess else t.stamp) |g| { + const r = guessed(R, g); + t.record(.host, u16, &id); + t.record(.ret, R, &r); + return r; + }; + t.record(.host, u16, &id); + t.seeFields(); + t.host_side = true; + const r = if (yields) out(f, full) else @call(.auto, f, full); + t.host_side = false; + t.noteWrites(); + t.record(.ret, R, &r); + return r; + } + + /// Asked by `turn.yield`: a syscall a replica must never make. + pub fn replaying(t: *const Tape) bool { + return t.replay or t.speculating; + } + + /// A syscall of the core's that is no site, made by a replica: what it + /// returns is the authority's to say. A speculation waits for it, and a + /// replay has diverged. + pub fn stray(t: *Tape) void { + if (t.through) return; + if (t.speculating) t.poisoned = true else t.diverge("a syscall that is no tape site, made replaying", .{}); + } + + /// Inside a step: one being recorded, a replica's replay of one, or its + /// speculation. A read made between steps (a frame drawn) is none. + pub fn stepping(t: *const Tape) bool { + return t.depth > 0 or t.replay or t.speculating; + } + + /// A replica's core under screen-state terminals: its emulators are + /// written by `apply` alone, never by its own steps. + pub fn screenReplica(t: *const Tape) bool { + return t.screen_state and (t.replay or t.speculating); + } + + /// An authority recording for screen-state replicas. + pub fn screenAuthority(t: *const Tape) bool { + return t.screen_state and !t.replay and !t.speculating; + } + + /// What a speculation reached is the authority's (`why`): the input is + /// undone and waits for the authority's order. + pub fn poison(t: *Tape, why: []const u8) void { + if (t.speculating) { + t.poisoned = true; + t.poisoned_by = why; + } + } + + /// A replica's speculation leaves what is the authority's be (a terminal's + /// emulator, a kind's state): true, and the input waits for its order. + pub fn authorityOnly(t: *Tape, comptime why: []const u8) bool { + if (!t.speculating) return false; + t.poison(why); + return true; + } + + /// A speculation that moves a terminal's view: a screen-state replica's + /// may (its rollback puts the view back, replica.zig `views`, and a delta + /// sets it), any other stops (`authorityOnly`). + pub fn viewOnly(t: *Tape, comptime why: []const u8) bool { + if (!t.speculating) return false; + if (t.screen_state) { + t.touched = true; + return false; + } + t.poison(why); + return true; + } + + /// A speculation read a terminal's rows or moved its view (`Tape.touched`). + pub fn touchTerminal(t: *Tape) void { + if (t.speculating) t.touched = true; + } + + /// The core a Restore made is the session's from here. + pub fn adopt(t: *Tape, p: *Pardes) void { + p.tape = t; + if (t.replay or t.through) return; + t.core = p; + t.wrap(p); + } + + /// Whether `p` is the core being recorded (a Restore's old one is not). + pub fn current(t: *const Tape, p: *const Pardes) bool { + return t.core == null or t.core == p; + } + + /// The session's core is freed: no digest of it after. + pub fn forget(t: *Tape, p: *Pardes) void { + if (t.core == p) t.core = null; + } }; const pardes_fields = walk.fieldNames(Pardes); @@ -818,6 +1037,12 @@ fn partsDiffer(got: []const u64, want: []const u64, a: std.mem.Allocator) []cons pub const Entered = struct { outer: bool = false }; pub inline fn enter(p: ?*Pardes, input: Input) Entered { + // A core's tape is the one `on` says while both are (P20: the global + // goes at the last step): every entry a safe build makes checks it. + // With none on, a client's core is entered between its steps (its own + // frame drawn, Replica.draw), its tape idle. + if (std.debug.runtime_safety) if (p) |core| if (if (on) |t| core.tape != t else core.tape.stepping()) + @panic("tape: a core's field is not the tape being stepped (tape.on)"); const t = on orelse return .{}; return t.enterInput(p, &input); } @@ -826,24 +1051,18 @@ pub inline fn leave(p: ?*Pardes, e: Entered) void { if (e.outer) on.?.leaveInput(p); } -/// The core a Restore made is the session's from here. +// The entry points on `on`, the methods' (`Tape.site` and the rest). + pub fn adopt(p: *Pardes) void { - const t = on orelse return; - if (t.replay) return; - t.core = p; - t.wrap(p); + (on orelse &none).adopt(p); } -/// Whether `p` is the core being recorded (a Restore's old one is not). pub fn current(p: *const Pardes) bool { - const t = on orelse return true; - return t.core == null or t.core == p; + return (on orelse &none).current(p); } -/// The session's core is freed: no digest of it after. pub fn forget(p: *Pardes) void { - const t = on orelse return; - if (t.core == p) t.core = null; + (on orelse &none).forget(p); } /// The Host function `i`, through the tape. @@ -999,54 +1218,16 @@ fn hostCall(comptime i: usize, comptime R: type, ctx: ?*anyopaque, args: anytype return r; } -/// A syscall of the core's own, `f(args)`, made out of the turn (a 9P -/// request through a mount of this very session is answered meanwhile): -/// recorded with what it returned, or answered from the tape and never -/// made. A result with slices is decoded into `a` on replay, the allocator -/// `f` would have used. pub fn site(comptime s: Site, a: ?std.mem.Allocator, comptime f: anytype, args: anytype) @typeInfo(@TypeOf(f)).@"fn".return_type.? { - return call(s, a, f, args, true); + return (on orelse &none).site(s, a, f, args); } -/// A read of the host's that is no syscall out of the turn (the clock, the -/// environment) or yields for itself: as `site`. pub fn value(comptime s: Site, comptime f: anytype, args: anytype) @typeInfo(@TypeOf(f)).@"fn".return_type.? { - return call(s, null, f, args, false); + return (on orelse &none).value(s, f, args); } -/// A read of what the authority alone holds (`.authority` state a step -/// makes digested state from: the session's closed panes, and Recent, which -/// every session of its user writes; the 9P server's readers and socket), -/// taped as `value` is; a speculation that reaches it waits for the -/// authority's answer, as at a host call. A replica's own is never read. -/// What it returns is the tape's arena's on a replay: `f` returns what -/// lives to the step's end (scratch, or the authority's own), and the -/// caller copies what it keeps. -/// -/// A yes or no (whether a script reads a pane's events, whether the -/// session serves a socket) is guessed by a speculation, mosh's way: the -/// authority's last answer to that question, as a replayed unit gave it, -/// recorded as the answer, so its unit confirms the guess or rolls it back. -/// A Look or a click's command in a pane then shows at once, not a round -/// trip late. ponytail: bools alone; a list (the closed panes, Recent) -/// changes with what the user does, and is asked of the authority. pub fn authority(comptime f: anytype, args: anytype) @typeInfo(@TypeOf(f)).@"fn".return_type.? { - if (comptime @typeInfo(@TypeOf(f)).@"fn".return_type.? == bool) if (on) |t| { - const key = question(f, args); - if (t.speculating) if (t.answers.get(key)) |was| { - const id: u16 = @as(u16, host_fns.len) + @backingInt(Site.authority); - t.record(.host, u16, &id); - t.record(.ret, bool, &was); - return was; - }; - if (t.replay) { - const got = value(.authority, f, args); - t.answers.put(t.gpa, key, got) catch {}; - return got; - } - }; - poison("the authority's own state"); - return value(.authority, f, args); + return (on orelse &none).authority(f, args); } /// What `authority` was asked: `f` and its arguments as they are. @@ -1056,57 +1237,6 @@ fn question(comptime f: anytype, args: anytype) u64 { return h.final(); } -fn call(comptime s: Site, a: ?std.mem.Allocator, comptime f: anytype, args: anytype, comptime yields: bool) @typeInfo(@TypeOf(f)).@"fn".return_type.? { - const R = @typeInfo(@TypeOf(f)).@"fn".return_type.?; - comptime { - const Listed = if (@typeInfo(R) == .error_union) anyerror!@typeInfo(R).error_union.payload else R; - for (results) |T| { - if (T == Listed) break; - } else @compileError("tape: the site ." ++ @tagName(s) ++ " returns " ++ @typeName(R) ++ ", which tape.results does not list"); - } - // No tape where there is no host to record or replay one. - const t = on orelse return if (yields) out(f, args) else @call(.auto, f, args); - const id: u16 = @as(u16, host_fns.len) + @backingInt(s); - if (comptime s == .read_file) t.reading = args[1]; - defer if (comptime s == .read_file) { - t.reading = null; - }; - if (t.replay) { - // Diverged (said in `diverged`): what a speculation gets, harmless, - // for the rest of the input. A replica joins again; a replay says so. - if (!t.expectHost(id, @tagName(s))) return poisonOf(R); - var ret = t.last_ret; - return walk.decode(R, &ret, a orelse t.arena.allocator()) catch { - t.diverge("the tape's answer to {t} is short", .{s}); - return poisonOf(R); - }; - } - // The host's own (a shell's spawn asking the shell), or one inside a - // site's syscall: the outer call is the record. - if (t.host_side) return if (yields) out(f, args) else @call(.auto, f, args); - // A syscall a speculating replica must not make: its input waits for - // the authority's answer. - if (yields and t.speculating) { - t.poisoned = true; - t.poisoned_by = @tagName(s); - return poisonOf(R); - } - if (comptime s == .clock or s == .mtime) if (if (t.speculating) t.guess else t.stamp) |g| { - const r = guessed(R, g); - t.record(.host, u16, &id); - t.record(.ret, R, &r); - return r; - }; - t.record(.host, u16, &id); - t.seeFields(); - t.host_side = true; - const r = if (yields) out(f, args) else @call(.auto, f, args); - t.host_side = false; - t.noteWrites(); - t.record(.ret, R, &r); - return r; -} - pub const Guess = struct { real_ns: i64, mono_ns: i64, gmtoff: i32 }; /// A record's bytes by hash kept for a replica's replays (`files`, the @@ -1141,6 +1271,7 @@ pub fn recordDigest(t: *Tape) void { /// one it replays into. pub fn adoptCore(t: *Tape, p: *Pardes) void { t.core = p; + p.tape = t; p.host = t.hostOf(t.mask); } @@ -1155,10 +1286,8 @@ pub fn resync(t: *Tape) void { t.real = .{}; } -/// A budget of `budget_ns` from `since_ns` on the monotonic clock is spent: -/// what the clock said is taped, so a replica stops its work where this did. pub fn over(since_ns: u64, budget_ns: u64) bool { - return value(.budget, overNow, .{ since_ns, budget_ns }); + return (on orelse &none).over(since_ns, budget_ns); } fn overNow(since_ns: u64, budget_ns: u64) bool { @@ -1172,88 +1301,57 @@ pub fn out(comptime f: anytype, args: anytype) @typeInfo(@TypeOf(f)).@"fn".retur return @call(.auto, f, args); } -/// Asked by `turn.yield`: a syscall a replica must never make. pub fn replaying() bool { - return if (on) |t| t.replay or t.speculating else false; + return (on orelse &none).replaying(); } -/// A syscall of the core's that is no site, made by a replica: what it -/// returns is the authority's to say. A speculation waits for it, and a -/// replay has diverged. pub fn stray() void { - const t = on orelse return; - if (t.speculating) t.poisoned = true else t.diverge("a syscall that is no tape site, made replaying", .{}); + (on orelse &none).stray(); } /// A replica speculating (core/replica.zig): state only the authority /// changes (a terminal's emulator) is left alone, and the input waits. pub fn speculating() bool { - return if (on) |t| t.speculating else false; + return (on orelse &none).speculating; } -/// Inside a step: one being recorded, a replica's replay of one, or its -/// speculation. A read made between steps (a frame drawn) is none. pub fn stepping() bool { - return if (on) |t| t.depth > 0 or t.replay or t.speculating else false; + return (on orelse &none).stepping(); } /// Screen-state terminals, on either side (`Tape.screen_state`). pub fn screenState() bool { - return if (on) |t| t.screen_state else false; + return (on orelse &none).screen_state; } -/// A replica's core under screen-state terminals: its emulators are -/// written by `apply` alone, never by its own steps. pub fn screenReplica() bool { - return if (on) |t| t.screen_state and (t.replay or t.speculating) else false; + return (on orelse &none).screenReplica(); } -/// An authority recording for screen-state replicas. pub fn screenAuthority() bool { - return if (on) |t| t.screen_state and !t.replay and !t.speculating else false; + return (on orelse &none).screenAuthority(); } -/// What a speculation reached is the authority's (`why`): the input is -/// undone and waits for the authority's order. pub fn poison(why: []const u8) void { - if (on) |t| if (t.speculating) { - t.poisoned = true; - t.poisoned_by = why; - }; + (on orelse &none).poison(why); } /// A replica's replay came to another state than the authority's (`why`): -/// it joins again. +/// it joins again. (No method: `Tape.diverged` is the field it writes.) pub fn diverged(why: []const u8) void { if (on) |t| if (t.replay) t.diverge("{s}", .{why}); } -/// A replica's speculation leaves what is the authority's be (a terminal's -/// emulator, a kind's state): true, and the input waits for its order. pub fn authorityOnly(comptime why: []const u8) bool { - if (!speculating()) return false; - poison(why); - return true; + return (on orelse &none).authorityOnly(why); } -/// A speculation that moves a terminal's view: a screen-state replica's -/// may (its rollback puts the view back, replica.zig `views`, and a delta -/// sets it), any other stops (`authorityOnly`). pub fn viewOnly(comptime why: []const u8) bool { - if (!speculating()) return false; - if (screenState()) { - touchTerminal(); - return false; - } - poison(why); - return true; + return (on orelse &none).viewOnly(why); } -/// A speculation read a terminal's rows or moved its view (`Tape.touched`). pub fn touchTerminal() void { - if (on) |t| if (t.speculating) { - t.touched = true; - }; + (on orelse &none).touchTerminal(); } /// A harmless stand-in for what a host call or a syscall would have diff --git a/dev/file_watch.zig b/dev/file_watch.zig index b2205173..9d868e07 100644 --- a/dev/file_watch.zig +++ b/dev/file_watch.zig @@ -609,7 +609,7 @@ pub fn applyThemeEffect( // What fails here is the ThemeFile write's failure too, which waits on // this (the one-failure rule): late, as a Save's. const pane = request.pane; - const bytes = filesystem.readFile(gpa, request.path) catch |err| { + const bytes = filesystem.readFile(&pardes.tape.none, gpa, request.path) catch |err| { colors.failThemeFile(core, generation, err); core.noteLateFailure(pane); return false; @@ -641,7 +641,7 @@ pub fn reloadTheme( if (comptime builtin.os.tag == .macos) { if (watches[theme_slot]) |*entry| remarkFile(entry, request.path); } - const bytes = filesystem.readFile(gpa, request.path) catch |err| { + const bytes = filesystem.readFile(&pardes.tape.none, gpa, request.path) catch |err| { core.invalidate(); colors.failThemeFile(core, watched.serial, err); return false; diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig index 909c83c6..237b7b85 100644 --- a/dev/gui/gui.zig +++ b/dev/gui/gui.zig @@ -611,7 +611,7 @@ fn syncReplicaFont(g: *Gui, f: *const @FieldType(pardes.config.Runtime, "font"), log.warn("the session's font is not installed here: {s}", .{name}); return false; }; - const bytes = filesystem.readFile(gpa, face.path) catch return false; + const bytes = filesystem.readFile(&pardes.tape.none, gpa, face.path) catch return false; if (!g.atlas.setFont(gpa, bytes)) return false; if (f.requested_size_hundredths != 0) g.px = @as(f32, @floatFromInt(f.requested_size_hundredths)) / 100; @@ -627,7 +627,7 @@ fn loadFallbackFonts(g: *Gui, gpa: std.mem.Allocator) void { defer arena_state.deinit(); for (fonts.fallbacks(arena_state.allocator())) |candidate| { if (g.atlas.fallback_count == max_fallback_fonts) break; - const bytes = filesystem.readFile(gpa, candidate.path) catch continue; + const bytes = filesystem.readFile(&pardes.tape.none, gpa, candidate.path) catch continue; _ = g.atlas.addFallback(gpa, bytes, true); } } @@ -1050,7 +1050,7 @@ fn localSession( var core = if (upgrade.resumed) |*rec| try upgrade.load(gpa, allocs.pardes, opts, rec) else if (opts.load_path) |lp| blk: { - const bytes = try @import("core").filesystem.readFile(gpa, lp); + const bytes = try @import("core").filesystem.readFile(&pardes.tape.none, gpa, lp); defer gpa.free(bytes); break :blk try pardes.dump.initFromDump(allocs.pardes, opts, bytes); } else try pardes.Pardes.init(allocs.pardes, opts); @@ -3065,7 +3065,7 @@ fn pollFrame(ctx: ?*anyopaque) void { frame_probe.?.period_ns = refreshNs(g); syncTaglineFont(g, core); if (core.takeFontRequest()) |path| blk: { - const bytes = filesystem.readFile(s.gpa, path) catch { + const bytes = filesystem.readFile(&pardes.tape.none, s.gpa, path) catch { core.rejectFont(); break :blk; }; @@ -6179,7 +6179,7 @@ test "FreeType and HarfBuzz allocate from the gui allocator and give it all back try std.testing.expect(!atlas.substitutes(0, atlas.glyphForCodepoint('-').glyph)); // A font with ligatures runs the whole HarfBuzz pass. - const bytes = try filesystem.readFile(std.testing.allocator, "assets/MapleMono-NF-Regular.ttf"); + const bytes = try filesystem.readFile(&pardes.tape.none, std.testing.allocator, "assets/MapleMono-NF-Regular.ttf"); defer std.testing.allocator.free(bytes); var maple = try Atlas.init(std.testing.allocator, bytes); defer maple.deinit(std.testing.allocator); @@ -6272,7 +6272,7 @@ test "installed Nerd Symbols fallback covers Yazi directory icons" { if (std.mem.eql(u8, font.name, "SymbolsNerdFont-Regular")) break font; } else return; - const bytes = try filesystem.readFile(std.testing.allocator, candidate.path); + const bytes = try filesystem.readFile(&pardes.tape.none, std.testing.allocator, candidate.path); defer std.testing.allocator.free(bytes); var atlas = try Atlas.init(std.testing.allocator, bytes); defer atlas.deinit(std.testing.allocator); @@ -7502,7 +7502,7 @@ test "insert cursor overlays without replacing the character beneath it" { } test "a ligature draws across its cells, one slice each, and comes apart under the cursor" { - const bytes = try filesystem.readFile(std.testing.allocator, "assets/MapleMono-NF-Regular.ttf"); + const bytes = try filesystem.readFile(&pardes.tape.none, std.testing.allocator, "assets/MapleMono-NF-Regular.ttf"); defer std.testing.allocator.free(bytes); var g = try textTestGui(bytes, 27); defer font_allocator = std.heap.smp_allocator; @@ -8298,7 +8298,7 @@ test "the atlas's bytes: a fixed key list at 27 px and at 54 px (2x) rasterizes // move (.scratch/sketch/briefs/gpu-s0.md); a change here is a change // to every frame. const want = [2][2]u64{ .{ 0xa03053f14e2c5472, 0x9029886b638b07d5 }, .{ 0xcbaa53a0103aaff5, 0x7563d69768f7d867 } }; - const maple = try filesystem.readFile(std.testing.allocator, "assets/MapleMono-NF-Regular.ttf"); + const maple = try filesystem.readFile(&pardes.tape.none, std.testing.allocator, "assets/MapleMono-NF-Regular.ttf"); defer std.testing.allocator.free(maple); defer display_scale = 1; var got: [2][2]u64 = undefined; diff --git a/dev/host_io.zig b/dev/host_io.zig index 1e03cdaf..377263a4 100644 --- a/dev/host_io.zig +++ b/dev/host_io.zig @@ -1518,7 +1518,7 @@ pub fn writeDump(core: *pardes.Pardes, bytes: []const u8) void { error.AccessDenied => error.AccessDenied, else => error.InputOutput, }; - return core.dumpFailed(pardes.Db.statePath(&path, core.settings.dump_dir.get()) orelse core.settings.dump_dir.get(), said); + return core.dumpFailed(pardes.Db.statePath(&pardes.tape.none, &path, core.settings.dump_dir.get()) orelse core.settings.dump_dir.get(), said); }; core.setLastDump(label); } diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig index 5b5c1e67..5a42ae5e 100644 --- a/dev/tui/tui.zig +++ b/dev/tui/tui.zig @@ -962,7 +962,7 @@ fn localSession( var core = if (upgrade.resumed) |*rec| try upgrade.load(gpa, allocs.pardes, options, rec) else if (options.load_path) |lp| blk: { - const bytes = try filesystem.readFile(gpa, lp); + const bytes = try filesystem.readFile(&pardes.tape.none, gpa, lp); defer gpa.free(bytes); break :blk try pardes.dump.initFromDump(allocs.pardes, options, bytes); } else try pardes.Pardes.init(allocs.pardes, options); diff --git a/runtime/macos.zig b/runtime/macos.zig index 3e9c7b9b..4f8bd709 100644 --- a/runtime/macos.zig +++ b/runtime/macos.zig @@ -643,7 +643,7 @@ fn setThemeFileWatch(st: *State, request_generation: u32, on: bool) void { hostWatchFile(theme_watch_pane, stopped, null, 0); if (!on) return; const request = colors.themeFileRequest(st.core, request_generation) orelse return; - const bytes = filesystem.readFile(st.gpa, request.path) catch |err| { + const bytes = filesystem.readFile(&pardes.tape.none, st.gpa, request.path) catch |err| { colors.failThemeFile(st.core, request_generation, err); return; }; @@ -665,7 +665,7 @@ fn reloadWatchedTheme(st: *State, announce: bool) bool { const watched = if (st.file_watches.entries[theme_watch_pane]) |*entry| entry else return false; const request = colors.themeFileRequest(st.core, watched.serial) orelse return false; if (!std.mem.eql(u8, watched.path, request.path)) return false; - const bytes = filesystem.readFile(st.gpa, watched.path) catch |err| { + const bytes = filesystem.readFile(&pardes.tape.none, st.gpa, watched.path) catch |err| { colors.failThemeFile(st.core, watched.serial, err); return false; }; diff --git a/runtime/main.zig b/runtime/main.zig index 11aceaeb..92821c8a 100644 --- a/runtime/main.zig +++ b/runtime/main.zig @@ -1370,7 +1370,7 @@ fn nativeMain(std_init: std.process.Init) !void { } // `pardes '~/x'`, quoted so the shell left it: home, as a look's. var home_buf: [4096]u8 = undefined; - const word = pardes.filesystem.expandHome(typed_word, &home_buf); + const word = pardes.filesystem.expandHome(&pardes.tape.none, typed_word, &home_buf); const target = @import("core").look.parsePathLine(word); // `@pN[:addr]` addresses a pane of this session: one it has is // looked at, one it has not is refused, never a file of that name. @@ -1388,14 +1388,14 @@ fn nativeMain(std_init: std.process.Init) !void { } var realbuf: [4096]u8 = undefined; var newbuf: [4096]u8 = undefined; - const found_path: ?[]const u8 = if (pardes.filesystem.isVirtual(target.path)) target.path else if (pardes.filesystem.resolveOs(target.path, &realbuf)) |r| r.path else null; + const found_path: ?[]const u8 = if (pardes.filesystem.isVirtual(target.path)) target.path else if (pardes.filesystem.resolveOs(&pardes.tape.none, target.path, &realbuf)) |r| r.path else null; const path = found_path orelse named: { // A name not there yet, as acme's B takes one: its directory // resolved and the name kept, a pane made for it that Save // creates the file from. const base = std.Io.Dir.path.basename(target.path); if (base.len == 0 or std.mem.eql(u8, base, ".") or std.mem.eql(u8, base, "..")) Refuse.with(init.io, word, error.NotAFileName); - const dir = pardes.filesystem.resolveOs(std.Io.Dir.path.dirname(target.path) orelse ".", &realbuf) orelse { + const dir = pardes.filesystem.resolveOs(&pardes.tape.none, std.Io.Dir.path.dirname(target.path) orelse ".", &realbuf) orelse { // Its directory not there either: the name made absolute as // written, and the pane's Save makes the directories. var cwd_buf: [4096]u8 = undefined; diff --git a/runtime/upgrade.zig b/runtime/upgrade.zig index e145eb70..6ee5d29c 100644 --- a/runtime/upgrade.zig +++ b/runtime/upgrade.zig @@ -346,7 +346,7 @@ var state_path: [4200]u8 = undefined; /// for a new build that cannot load it. Null when it is, else why in words /// (`why`'s). pub fn dumpInto(core: *pardes.Pardes, rec: *Record, at: *[1024:0]u8, why: []u8) ?[]const u8 { - const path = pardes.Db.statePath(&state_path, core.settings.dump_dir.get()) orelse return "Upgrade: no directory for the session's dump; this session stays as it is"; + const path = pardes.Db.statePath(&pardes.tape.none, &state_path, core.settings.dump_dir.get()) orelse return "Upgrade: no directory for the session's dump; this session stays as it is"; var name: [64]u8 = undefined; const label = std.fmt.bufPrint(&name, "upgrade-{d}", .{std.c.getpid()}) catch unreachable; const bytes = pardes.dump.image(core, label) catch |err| { @@ -393,7 +393,7 @@ pub fn load(gpa: std.mem.Allocator, core_gpa: std.mem.Allocator, opts: pardes.Op const loaded = loaded: { if (libc.getenv("PARDES_TEST_UPGRADE_REFUSE")) |how| if (rec.refused.len == 0 or std.mem.eql(u8, std.mem.span(how), "all")) break :loaded error.RefusedByTest; - const bytes = (if (rec.label.len > 0) pardes.Db.readDumpAt(gpa, rec.dump, rec.label) else pardes.filesystem.readFile(gpa, rec.dump)) catch |err| break :loaded err; + const bytes = (if (rec.label.len > 0) pardes.Db.readDumpAt(gpa, rec.dump, rec.label) else pardes.filesystem.readFile(&pardes.tape.none, gpa, rec.dump)) catch |err| break :loaded err; defer gpa.free(bytes); break :loaded pardes.dump.resumeFromDump(core_gpa, opts, bytes, &kept); }; |
