summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--abi/wire.zig23
-rw-r--r--build.zig110
-rw-r--r--build/core.zig109
-rw-r--r--build/library.zig49
-rw-r--r--build/patches.zig5
-rw-r--r--build/tools.zig7
-rw-r--r--core/CHANGELOG.md23
-rw-r--r--core/Core.zig55
-rw-r--r--core/Dir.zig2
-rw-r--r--core/Effect.zig62
-rw-r--r--core/File.zig17
-rw-r--r--core/Output.zig2
-rw-r--r--core/Plumb.zig2
-rw-r--r--core/Query.zig7
-rw-r--r--core/Stream.zig26
-rw-r--r--core/body_layer.zig5
-rw-r--r--core/builtins.zig10
-rw-r--r--core/config.zig2
-rw-r--r--core/draw.zig1
-rw-r--r--core/dump.zig7
-rw-r--r--core/edit_cmd.zig4
-rw-r--r--core/exec.zig10
-rw-r--r--core/fs.zig15
-rw-r--r--core/grammar_manifest.zig4
-rw-r--r--core/keys.zig3
-rw-r--r--core/lib_syntax.zig4
-rw-r--r--core/look.zig16
-rw-r--r--core/mouse.zig1
-rw-r--r--core/ninep/pty.zig16
-rw-r--r--core/ninep/tree.zig15
-rw-r--r--core/panes.zig24
-rw-r--r--core/replica.zig422
-rw-r--r--core/root.zig19
-rw-r--r--core/syntax.zig113
-rw-r--r--core/tape.zig251
-rw-r--r--dev/Host.zig46
-rw-r--r--dev/file_watch.zig14
-rw-r--r--dev/gui/gui.zig8
-rw-r--r--dev/tui/tui.zig61
-rw-r--r--docs/next-editor.md4
-rw-r--r--docs/next-run.md13
-rw-r--r--docs/next-terminal.md2
-rw-r--r--docs/typ/building.typ81
-rw-r--r--docs/typ/command-line.txt6
-rw-r--r--runtime/9p_io.zig6
-rw-r--r--runtime/client.zig12
-rw-r--r--runtime/daemon.zig105
-rw-r--r--runtime/main.zig79
-rw-r--r--runtime/session.zig14
-rw-r--r--test/behaviour/panes.zig1
-rw-r--r--test/behaviour/settings.zig2
-rw-r--r--test/consumer/bench.zig (renamed from test/lib/bench.zig)0
-rw-r--r--test/consumer/build.zig42
-rw-r--r--test/consumer/build.zig.zon16
-rw-r--r--test/consumer/editor.zig (renamed from test/lib/editor.zig)0
-rw-r--r--test/consumer/lib.zig (renamed from test/lib/lib.zig)0
-rw-r--r--test/daemon.py365
-rw-r--r--test/delay_relay.py10
-rw-r--r--test/fs_namespace.zig3
-rw-r--r--test/lib/build.zig34
-rw-r--r--test/lib/build.zig.zon10
-rw-r--r--test/output.zig11
-rw-r--r--test/panes.zig12
-rw-r--r--test/process.zig3
-rw-r--r--test/process/terminals.zig9
-rw-r--r--test/process/tty_terminals.zig4
-rw-r--r--test/terminal.zig2
67 files changed, 1675 insertions, 741 deletions
diff --git a/abi/wire.zig b/abi/wire.zig
index 1f7d02d2..8713ba98 100644
--- a/abi/wire.zig
+++ b/abi/wire.zig
@@ -63,18 +63,19 @@ const family = switch (config.platform) {
pub const semantics: u64 = blk: {
@setEvalBranchQuota(1_000_000);
// The grammar set as the four words it was hashed as when it was four
- // options (highlighting, zig, minimal, full), so the hash stays.
+ // options (highlighting, zig, minimal, full), so the hash of a minimal
+ // or a full set stays: every set has highlighting, `none` no grammar.
const g = config.grammars;
// The two long ones (the dependencies, 2.5 KB, and the tape's shape,
// 11 KB) joined on, not formatted: formatting them at comptime was 5 %
// of a compile of the core.
break :blk std.hash.Wyhash.hash(0, std.fmt.comptimePrint(
- "wire {d}\npardes {s} {s}\n{s} grammars {} {} {} {} workspace_tag {} sources {}\nusize {d} {t}\n",
+ "wire {d}\npardes {s} {s}\n{s} grammars true {} {} {} workspace_tag {} sources {}\nusize {d} {t}\n",
.{
- version, build_info.version, build_info.commit orelse "unstamped",
- family, g != .disabled, g != .disabled,
- g == .minimal or g == .full, g == .full, config.workspace_tag,
- config.embed_sources, @sizeOf(usize), builtin.cpu.arch.endian(),
+ version, build_info.version, build_info.commit orelse "unstamped",
+ family, g != .none, g != .none,
+ g == .full, config.workspace_tag, config.embed_sources,
+ @sizeOf(usize), builtin.cpu.arch.endian(),
},
) ++ build_info.deps ++ "\n" ++ pardes.tape.shape);
};
@@ -191,6 +192,10 @@ pub const ServerTag = enum(u8) {
/// unit naming it: the hash, the whole's length and this piece's place
/// (u64le each), then at most 1 MiB of it (core/replica.zig).
blob = 0x0a,
+ /// The session's last word on a link: it ended, with its exit code.
+ ended = 0x0b,
+ /// ...or this client left it running (a Detach typed in it): its name.
+ left = 0x0c,
};
pub const ServerMsg = union(ServerTag) {
@@ -208,6 +213,8 @@ pub const ServerMsg = union(ServerTag) {
blobs: []const u8,
zstd: []const u8,
blob: []const u8,
+ ended: u8,
+ left: []const u8,
};
/// A message's header, for a payload sent on its own (a unit, a dump's
@@ -243,6 +250,8 @@ pub fn decodeServer(tag: u8, payload: []const u8) Error!ServerMsg {
.blobs => return .{ .blobs = payload },
.zstd => return .{ .zstd = payload },
.blob => return .{ .blob = payload },
+ .ended => .{ .ended = try r.takeByte() },
+ .left => .{ .left = try r.take(try r.takeInt(u16, .little)) },
};
try end(&r);
return msg;
@@ -267,6 +276,8 @@ pub fn encodeServer(out: []u8, msg: ServerMsg) Error![]const u8 {
.pong => |v| try w.writeInt(u64, v, .little),
.dump, .unit, .screen, .blobs, .zstd, .blob => |bytes| try w.writeAll(bytes),
.check => |v| try w.writeInt(u64, v, .little),
+ .ended => |code| try w.writeByte(code),
+ .left => |name| try putSlice16(&w, name),
}
try finishMessage(&w, at);
return w.buffered();
diff --git a/build.zig b/build.zig
index fc0c5044..125f4dcc 100644
--- a/build.zig
+++ b/build.zig
@@ -1,3 +1,40 @@
+//! pardes: the editor, and the library it is for a program that draws
+//! source text itself. `zig build -Dplatform=tui` (or `gui`, `macos`)
+//! builds the editor; docs/typ/building.typ has the rest.
+//!
+//! A package that depends on pardes is given its syntax, `pardes-syntax`
+//! (`core/lib_syntax.zig`):
+//!
+//! const pardes = b.dependency("pardes", .{
+//! .target = target,
+//! .optimize = optimize,
+//! .grammars = .minimal,
+//! });
+//! exe.root_module.addImport("pardes-syntax", pardes.module("pardes-syntax"));
+//!
+//! and, when it asks, the text pane, `pardes-editor`
+//! (`core/lib_editor.zig`), here with a grammar of its own handed in at
+//! run time:
+//!
+//! const pardes = b.dependency("pardes", .{
+//! .target = target,
+//! .optimize = optimize,
+//! .grammars = .none,
+//! .editor = true,
+//! });
+//! exe.root_module.addImport("pardes-editor", pardes.module("pardes-editor"));
+//!
+//! `.grammars`: the tree-sitter grammars compiled in: `none` (the runtime
+//! alone), `minimal` (C, C++ and Zig) or `full` (all of them; the default).
+//! `.editor`: exports `pardes-editor` besides `pardes-syntax`, and with it
+//! fetches uucode, mvzr and vaxis.
+//!
+//! Every dependency but tree-sitter's runtime is lazy in the manifest, so
+//! such a package fetches what it asked for and nothing else.
+//! `pardes-editor` has `pardes-syntax` in it as `.syntax`: a file belongs
+//! to one module, so a package imports one of the two. `test/consumer` is
+//! such a package, with both shapes; `lib-test`, which `unit-test` runs,
+//! builds and runs it.
const std = @import("std");
const builtin = @import("builtin");
const core = @import("build/core.zig");
@@ -8,6 +45,7 @@ const macos = @import("build/macos.zig");
const tools = @import("build/tools.zig");
const tests = @import("build/tests.zig");
const process_build = @import("build/process.zig");
+const patches = @import("build/patches.zig");
/// The package manifest, imported untyped (build/core.zig has the reason).
const zon = @import("build.zig.zon");
@@ -32,12 +70,17 @@ pub const PerfBuild = struct {
pub const macos_min_version: std.SemanticVersion = .{ .major = 13, .minor = 0, .patch = 0 };
-pub const TreeSitterGrammars = enum { disabled, zig, minimal, full };
+pub const TreeSitterGrammars = enum { none, minimal, full };
pub fn build(b: *std.Build) void {
- // A package that depends on pardes takes its library; nothing of the
- // editor is configured for it.
- if (!b.isRoot()) return @import("build/library.zig").build(b);
+ // What a package that depends on pardes may ask for (the head comment).
+ // pardes's own build takes the mode and the grammars too, and its target
+ // below, whose default -Dplatform says.
+ const optimize = b.standardOptimizeOption(.{});
+ const grammars = b.option(TreeSitterGrammars, "grammars", "the tree-sitter grammars compiled in: none (the runtime alone), minimal (C, C++ and Zig) or full (all of them; the default)") orelse .full;
+ if (!b.isRoot()) return library(b, b.standardTargetOptions(.{}), optimize, grammars, b.option(bool, "editor", "exports pardes-editor besides pardes-syntax, and with it fetches uucode, mvzr and vaxis") orelse false);
+
+ // Everything below is pardes's own: the editor, its tests and tools.
// This configure reads the environment (HOME, XDG_DATA_HOME,
// HX_HARNESS), the clock (-Dtest-rebuild) and vendor/themes and
// vendor/queries without telling the configure cache, so it is never
@@ -79,7 +122,6 @@ pub fn build(b: *std.Build) void {
},
},
});
- const optimize = b.standardOptimizeOption(.{});
// one substring, because that is what a dev loop needs: see the unit-test
// step for why the whole-binary run is worth narrowing
const test_filters: []const []const u8 = if (b.option([]const u8, "test-filter", "run only tests whose name contains this")) |f|
@@ -108,7 +150,6 @@ pub fn build(b: *std.Build) void {
}),
});
const c_optimize: std.lang.Optimize = if (optimize == .debug) .fast else optimize;
- const tree_sitter_grammars = b.option(TreeSitterGrammars, "tree-sitter", "tree-sitter grammar set: disabled, zig, minimal (c/c++/zig), full") orelse .full;
const tracy = b.option([]const u8, "tracy", "enable Tracy profiling; supply the path to a Tracy source checkout");
const macos_sdk = b.option([]const u8, "macos-sdk", "the macOS SDK a gui built for macOS from another system takes SDL's headers and frameworks from");
const macos_identity = b.option([]const u8, "macos-identity", "codesigning identity for pardes.app (default: ad-hoc)") orelse "-";
@@ -141,7 +182,7 @@ pub fn build(b: *std.Build) void {
const pdf_scroll_bench_step = b.step("pdf-scroll-bench", "benchmark fast continuous-strip PDF scrolling in ReleaseFast (-Doptimize=ReleaseFast -- [--json] [--reps N] [--warmup N] [--path FILE])");
const shell_cfg: core.ShellConfig = .{
- .tree_sitter_grammars = tree_sitter_grammars,
+ .tree_sitter_grammars = grammars,
.tracy = tracy,
.workspace_tag = workspace_tag,
.embed_sources = embed_sources,
@@ -175,8 +216,8 @@ pub fn build(b: *std.Build) void {
// core.module.
const root_set = core.module(b, parts, .{ .root = if (platform == .macos) "runtime/macos.zig" else "runtime/main.zig", .platform = platform, .builtin_addons = compiled_in, .tracy = true, .util = true });
const root_mod = root_set.root;
- // hxdiff's headless core and pardes-isolate are the primary shell's
- // configuration compiled two more ways, not two more frontends.
+ // hxdiff's headless core is the primary shell's configuration compiled
+ // another way, not another frontend.
const core_cfg: core.Core = .{ .root = "core/root.zig", .platform = platform, .builtin_addons = compiled_in, .tracy = true };
const core_set = core.module(b, parts, core_cfg);
const core_module = core_set.root;
@@ -186,7 +227,6 @@ pub fn build(b: *std.Build) void {
// and shell-test runs them all with one.
const lean_cfg: core.Core = .{ .root = "core/root.zig", .platform = platform, .builtin_addons = compiled_in, .terminal = false };
const core_lean = core.module(b, parts, lean_cfg);
- const isolated_mod: ?*std.Build.Module = if (platform == .tui) core.module(b, parts, .{ .root = "runtime/main.zig", .platform = platform, .builtin_addons = compiled_in, .isolated = true }).root else null;
// `zig build static`'s: the addons compiled in (Addon.zig). Linked
// statically on musl alone, as glibc links only dynamically; the gui's
// is dynamic (SDL and the GPU need the display's libraries) with the
@@ -270,17 +310,6 @@ pub fn build(b: *std.Build) void {
static_step.dependOn(&b.addFail("static is the terminal's on musl (-Dplatform=tui -Dtarget=x86_64-linux-musl) or the gui's (-Dplatform=gui)").step);
const run = b.addRunArtifact(exe);
b.step("run", "descend to the pardes").dependOn(&run.step);
- if (isolated_mod) |iso| {
- const iso_exe = b.addExecutable(.{
- .name = "pardes-isolate",
- .root_module = iso,
- });
- const run_iso = b.addRunArtifact(iso_exe);
- // Something to look at on arrival, read out of the binary itself.
- run_iso.addPassthruArgs();
- const iso_step = b.step("run-isolated", "descend to a pardes with no host but the terminal");
- iso_step.dependOn(&run_iso.step);
- }
const addon_libs: []const *std.Build.Step.Compile = if (a.pdf.lib) |l| b.allocator.dupe(*std.Build.Step.Compile, &.{ a.image_addon, l }) catch @panic("OOM") else &.{a.image_addon};
// The scripted language server the tests' sessions and the tty cases ask.
@@ -371,3 +400,42 @@ fn installHome(b: *std.Build, artifact: *std.Build.Step.Compile, home_bin: ?[]co
copy.has_side_effects = true;
b.getInstallStep().dependOn(&copy.step);
}
+
+/// What a package that depends on pardes is given (the head comment):
+/// `pardes-syntax`, the grammars, highlighting and themes, over tree-sitter
+/// and the grammars of its set alone; and with `editor`, `pardes-editor`,
+/// whose uucode, mvzr and vaxis (with what its build names) are fetched
+/// then and only then. Of vaxis it takes the grapheme width, which uucode
+/// alone feeds.
+fn library(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.lang.Optimize, grammars: TreeSitterGrammars, editor: bool) void {
+ var threaded: std.Io.Threaded = .init(b.allocator, .{});
+ defer threaded.deinit();
+ const io = threaded.io();
+ const mod = b.addModule("pardes-syntax", .{
+ .target = target,
+ .optimize = optimize,
+ .root_source_file = b.path("core/lib_syntax.zig"),
+ .link_libc = true,
+ });
+ // A library's options: its grammars, nothing stamped, no window.
+ const cfg: core.ShellConfig = .{ .tree_sitter_grammars = grammars };
+ mod.addOptions("pardes_options", core.options(b, cfg, .{ .root = "core/lib_syntax.zig", .platform = .tui, .terminal = false }, false));
+ const ts = core.treeSitter(b, io, target, if (optimize == .debug) .fast else optimize, grammars);
+ const themes = core.generatedThemes(b, io, target, optimize);
+ mod.addImport("generated_themes", themes);
+ ts.wire(mod);
+ mod.addImport("c_heap", b.createModule(.{ .target = target, .optimize = optimize, .root_source_file = b.path("core/c_heap.zig") }));
+ if (!editor) return;
+ const uucode = core.uucodeModule(b, target, optimize) orelse return;
+ const mvzr = patches.mvzr(b, patches.tool(b), b.dependencyLazy("mvzr", .{ .target = target, .optimize = optimize }) catch return, target, optimize);
+ const vaxis_dep = b.dependencyLazy("vaxis", .{ .target = target, .optimize = optimize, .external_uucode = true }) catch return;
+ const width = b.addWriteFiles();
+ _ = width.addCopyFile(vaxis_dep.path("src/gwidth.zig"), "gwidth.zig");
+ const vaxis = b.createModule(.{
+ .target = target,
+ .optimize = optimize,
+ .root_source_file = width.add("vaxis.zig", "pub const gwidth = @import(\"gwidth.zig\");\n"),
+ .imports = &.{.{ .name = "uucode", .module = uucode }},
+ });
+ _ = core.editorModule(b, "pardes-editor", target, optimize, cfg, .{ .themes = themes, .ts = ts, .uucode = uucode, .mvzr = mvzr, .vaxis = vaxis });
+}
diff --git a/build/core.zig b/build/core.zig
index 4e4a748b..b668211d 100644
--- a/build/core.zig
+++ b/build/core.zig
@@ -83,7 +83,6 @@ pub fn options(b: *std.Build, cfg: ShellConfig, c: Core, pdf: bool) *std.Build.S
o.addOption(Platform, "platform", c.platform);
o.addOption(TreeSitterGrammars, "grammars", cfg.tree_sitter_grammars);
o.addOption(bool, "terminal", c.terminal);
- o.addOption(bool, "isolated", c.isolated);
o.addOption(bool, "builtin_addons", c.builtin_addons);
// ...the pdf one only when it is built (-Dpdf=false leaves it out).
o.addOption(bool, "builtin_pdf", c.builtin_addons and pdf);
@@ -146,15 +145,15 @@ pub fn generatedThemes(b: *std.Build, io: std.Io, target: std.Build.ResolvedTarg
}
pub const TreeSitter = struct {
- mod: ?*std.Build.Module,
- queries: ?*std.Build.Step.Options,
+ mod: *std.Build.Module,
+ queries: *std.Build.Step.Options,
libs: std.ArrayList(*std.Build.Step.Compile),
/// tree-sitter, the grammars' parsers and their queries, into `m`.
pub fn wire(ts: TreeSitter, m: *std.Build.Module) void {
- if (ts.mod) |x| m.addImport("tree-sitter", x);
+ m.addImport("tree-sitter", ts.mod);
for (ts.libs.items) |lib| m.linkLibrary(lib);
- if (ts.queries) |x| m.addOptions("ts_queries", x);
+ m.addOptions("ts_queries", ts.queries);
}
};
@@ -163,61 +162,51 @@ pub const TreeSitter = struct {
/// A grammar not fetched yet is asked for and left out: the configure runs
/// again once it is there.
pub fn treeSitter(b: *std.Build, io: std.Io, target: std.Build.ResolvedTarget, c_optimize: std.lang.Optimize, tree_sitter_grammars: TreeSitterGrammars) TreeSitter {
- var ts_mod: ?*std.Build.Module = null;
- var ts_queries_opts: ?*std.Build.Step.Options = null;
+ const tree_sitter_mod = b.dependency("tree_sitter", .{ .target = target, .optimize = c_optimize }).module("tree_sitter");
var ts_libs: std.ArrayList(*std.Build.Step.Compile) = .empty;
- if (tree_sitter_grammars != .disabled) {
- const tree_sitter_mod = b.dependency("tree_sitter", .{ .target = target, .optimize = c_optimize }).module("tree_sitter");
- ts_mod = tree_sitter_mod;
+ const ts_queries = b.addOptions();
+ inline for (grammar_manifest.all) |g| {
+ if (tree_sitter_grammars == .full or (tree_sitter_grammars == .minimal and g.tier == .minimal)) grammar: {
+ const dep = b.dependencyLazy(g.dep, .{}) catch break :grammar;
+ const upstream = configureRead(b, io, dep.builder.root, g.query, 0x100000) catch @panic("read " ++ g.name ++ " highlights");
+ // the patterns that colour, filtered here once and not in
+ // every compile, and the whole query, the filter's test's
+ const query = std.mem.concat(b.allocator, u8, &.{ upstream, g.highlights_extra }) catch @panic("OOM");
+ ts_queries.addOption([]const u8, g.name ++ "_highlights_unfiltered", query);
+ ts_queries.addOption([]const u8, g.name ++ "_highlights", grammar_manifest.colorQuery(query, b.allocator.alloc(u8, query.len) catch @panic("OOM")));
+ // helix's textobject queries, vendored (vendor/queries); a
+ // grammar without one gets none
+ const objects = configureRead(b, io, b.root, "vendor/queries/" ++ g.name ++ "/textobjects.scm", 0x100000) catch "";
+ ts_queries.addOption([]const u8, g.name ++ "_textobjects", objects);
+ // and their indent queries, beside them
+ const indents = configureRead(b, io, b.root, "vendor/queries/" ++ g.name ++ "/indents.scm", 0x100000) catch "";
+ ts_queries.addOption([]const u8, g.name ++ "_indents", indents);
- const ts_queries = b.addOptions();
- inline for (grammar_manifest.all) |g| {
- if (tree_sitter_grammars == .full or
- (tree_sitter_grammars == .minimal and g.tier != .full) or
- (tree_sitter_grammars == .zig and g.tier == .zig))
- grammar: {
- const dep = b.dependencyLazy(g.dep, .{}) catch break :grammar;
- const upstream = configureRead(b, io, dep.builder.root, g.query, 0x100000) catch @panic("read " ++ g.name ++ " highlights");
- // the patterns that colour, filtered here once and not in
- // every compile, and the whole query, the filter's test's
- const query = std.mem.concat(b.allocator, u8, &.{ upstream, g.highlights_extra }) catch @panic("OOM");
- ts_queries.addOption([]const u8, g.name ++ "_highlights_unfiltered", query);
- ts_queries.addOption([]const u8, g.name ++ "_highlights", grammar_manifest.colorQuery(query, b.allocator.alloc(u8, query.len) catch @panic("OOM")));
- // helix's textobject queries, vendored (vendor/queries); a
- // grammar without one gets none
- const objects = configureRead(b, io, b.root, "vendor/queries/" ++ g.name ++ "/textobjects.scm", 0x100000) catch "";
- ts_queries.addOption([]const u8, g.name ++ "_textobjects", objects);
- // and their indent queries, beside them
- const indents = configureRead(b, io, b.root, "vendor/queries/" ++ g.name ++ "/indents.scm", 0x100000) catch "";
- ts_queries.addOption([]const u8, g.name ++ "_indents", indents);
-
- const lib = b.addLibrary(.{
- .name = "tree-sitter-" ++ g.name,
- .root_module = b.createModule(.{ .target = target, .optimize = c_optimize, .link_libc = true }),
- .linkage = .static,
- });
- // Every allocation a grammar's external scanner makes goes to the
- // runtime's allocator, which syntax.zig points at a Zig one:
- // TREE_SITTER_REUSE_ALLOCATOR for the scanners that use
- // ts_malloc, and core/tree_sitter_heap.h for the ones that call
- // malloc themselves.
- const ts_cflags = [_][]const u8{
- "-fno-sanitize=function",
- "-DTREE_SITTER_REUSE_ALLOCATOR",
- // From the compiler's working directory, the root
- // package's: pardes's own, or the one that depends on it.
- "-include",
- b.root.joinString(b.allocator, "core/tree_sitter_heap.h") catch @panic("OOM"),
- };
- lib.root_module.addCSourceFile(.{ .file = dep.path(g.src ++ "/parser.c"), .flags = &ts_cflags });
- if (g.scanner) lib.root_module.addCSourceFile(.{ .file = dep.path(g.src ++ "/scanner.c"), .flags = &ts_cflags });
- lib.root_module.addIncludePath(dep.path(g.src));
- ts_libs.append(b.allocator, lib) catch @panic("OOM");
- }
+ const lib = b.addLibrary(.{
+ .name = "tree-sitter-" ++ g.name,
+ .root_module = b.createModule(.{ .target = target, .optimize = c_optimize, .link_libc = true }),
+ .linkage = .static,
+ });
+ // Every allocation a grammar's external scanner makes goes to the
+ // runtime's allocator, which syntax.zig points at a Zig one:
+ // TREE_SITTER_REUSE_ALLOCATOR for the scanners that use
+ // ts_malloc, and core/tree_sitter_heap.h for the ones that call
+ // malloc themselves.
+ const ts_cflags = [_][]const u8{
+ "-fno-sanitize=function",
+ "-DTREE_SITTER_REUSE_ALLOCATOR",
+ // From the compiler's working directory, the root
+ // package's: pardes's own, or the one that depends on it.
+ "-include",
+ b.root.joinString(b.allocator, "core/tree_sitter_heap.h") catch @panic("OOM"),
+ };
+ lib.root_module.addCSourceFile(.{ .file = dep.path(g.src ++ "/parser.c"), .flags = &ts_cflags });
+ if (g.scanner) lib.root_module.addCSourceFile(.{ .file = dep.path(g.src ++ "/scanner.c"), .flags = &ts_cflags });
+ lib.root_module.addIncludePath(dep.path(g.src));
+ ts_libs.append(b.allocator, lib) catch @panic("OOM");
}
- ts_queries_opts = ts_queries;
}
- return .{ .mod = ts_mod, .queries = ts_queries_opts, .libs = ts_libs };
+ return .{ .mod = tree_sitter_mod, .queries = ts_queries, .libs = ts_libs };
}
/// uucode with pardes's configuration (uucode_config.zig), which ghostty
@@ -308,8 +297,6 @@ pub const Core = struct {
platform: Platform,
/// The terminal module; without it (core-test) a shell boot is a scratch pane.
terminal: bool = true,
- /// pardes-isolate's: no host but the terminal.
- isolated: bool = false,
/// The addons compiled in and registered at start (Addon.zig): the
/// static step's, and every core off Linux, whose loader has no memfd.
builtin_addons: bool = false,
@@ -368,7 +355,7 @@ pub fn module(b: *std.Build, p: Parts, c: Core) Modules {
const root = if (!in_runtime) m else if (std.mem.eql(u8, c.root, "runtime/root.zig")) runtime else b.createModule(.{ .target = p.target, .optimize = p.optimize, .root_source_file = b.path(c.root), .link_libc = true });
// Each options module once, so that the modules share it: a file is in
// one module of a compilation.
- const ts_queries = if (p.ts.queries) |q| q.createModule() else null;
+ const ts_queries = p.ts.queries.createModule();
const doc_typ = p.doc_typ.createModule();
const pardes_options = options(b, p.cfg, c, p.pdf != null).createModule();
const build_info = p.info.createModule();
@@ -380,8 +367,8 @@ pub fn module(b: *std.Build, p: Parts, c: Core) Modules {
x.addImport("plain", p.plain);
x.addImport("pardes_addon", p.kind);
x.addImport("generated_themes", p.themes);
- if (p.ts.mod) |ts| x.addImport("tree-sitter", ts);
- if (ts_queries) |q| x.addImport("ts_queries", q);
+ x.addImport("tree-sitter", p.ts.mod);
+ x.addImport("ts_queries", ts_queries);
x.addImport("mvzr", p.mvzr);
x.addImport("c_heap", p.c_heap);
x.addImport("vaxis", p.vaxis);
diff --git a/build/library.zig b/build/library.zig
deleted file mode 100644
index 8a23debc..00000000
--- a/build/library.zig
+++ /dev/null
@@ -1,49 +0,0 @@
-const std = @import("std");
-const TreeSitterGrammars = @import("../build.zig").TreeSitterGrammars;
-const core = @import("core.zig");
-const patches = @import("patches.zig");
-
-/// pardes as a library, all a package that depends on it is given: the
-/// `pardes-syntax` module (core/lib_syntax.zig), the grammars, highlighting
-/// and themes for a program that draws source text itself. It takes
-/// tree-sitter and the grammars of its `tree-sitter` option and no other
-/// dependency, so nothing else is fetched (build.zig.zon). test/lib is such
-/// a package, which `lib-test` builds.
-pub fn build(b: *std.Build) void {
- const target = b.standardTargetOptions(.{});
- const optimize = b.standardOptimizeOption(.{});
- const tree_sitter_grammars = b.option(TreeSitterGrammars, "tree-sitter", "tree-sitter grammar set: disabled, zig, minimal (c/c++/zig), full") orelse .full;
- var threaded: std.Io.Threaded = .init(b.allocator, .{});
- defer threaded.deinit();
- const io = threaded.io();
- const mod = b.addModule("pardes-syntax", .{
- .target = target,
- .optimize = optimize,
- .root_source_file = b.path("core/lib_syntax.zig"),
- .link_libc = true,
- });
- // A library's options: its grammars, nothing stamped, no window.
- const cfg: core.ShellConfig = .{ .tree_sitter_grammars = tree_sitter_grammars };
- mod.addOptions("pardes_options", core.options(b, cfg, .{ .root = "core/lib_syntax.zig", .platform = .tui, .terminal = false }, false));
- const ts = core.treeSitter(b, io, target, if (optimize == .debug) .fast else optimize, tree_sitter_grammars);
- const themes = core.generatedThemes(b, io, target, optimize);
- mod.addImport("generated_themes", themes);
- ts.wire(mod);
- mod.addImport("c_heap", b.createModule(.{ .target = target, .optimize = optimize, .root_source_file = b.path("core/c_heap.zig") }));
- // The editor, `pardes-editor`, to a package that asks for it: uucode,
- // mvzr and vaxis (with what its build names) are fetched then and only
- // then. Of vaxis it takes the grapheme width, which uucode alone feeds.
- if (!(b.option(bool, "editor", "also export `pardes-editor`, the text pane as a library (fetches uucode, mvzr and vaxis)") orelse false)) return;
- const uucode = core.uucodeModule(b, target, optimize) orelse return;
- const mvzr = patches.mvzr(b, patches.tool(b), b.dependencyLazy("mvzr", .{ .target = target, .optimize = optimize }) catch return, target, optimize);
- const vaxis_dep = b.dependencyLazy("vaxis", .{ .target = target, .optimize = optimize, .external_uucode = true }) catch return;
- const width = b.addWriteFiles();
- _ = width.addCopyFile(vaxis_dep.path("src/gwidth.zig"), "gwidth.zig");
- const vaxis = b.createModule(.{
- .target = target,
- .optimize = optimize,
- .root_source_file = width.add("vaxis.zig", "pub const gwidth = @import(\"gwidth.zig\");\n"),
- .imports = &.{.{ .name = "uucode", .module = uucode }},
- });
- _ = core.editorModule(b, "pardes-editor", target, optimize, cfg, .{ .themes = themes, .ts = ts, .uucode = uucode, .mvzr = mvzr, .vaxis = vaxis });
-}
diff --git a/build/patches.zig b/build/patches.zig
index 7c7b2d60..7d87b9f1 100644
--- a/build/patches.zig
+++ b/build/patches.zig
@@ -34,7 +34,8 @@ fn apply(b: *std.Build, patch: *std.Build.Step.Compile, dep: *std.Build.Dependen
/// startup width queries' `CSI 1;1R` arrived as two F3s, which a shell
/// pane took for text (build/patches/vaxis_parser.zig).
/// - ESC before a CSI or SS3 key (rxvt's Alt+arrow) is Alt on that key,
-/// not Alt+Escape followed by `[A` as text.
+/// not Alt+Escape followed by `[A` as text; before anything else (a
+/// mouse report: Alt is in its button) it is the Escape key.
/// - An X10 mouse report and a kitty graphics reply cut short by a read
/// wait for their rest: the first became three bytes of text, the
/// second sliced past its input.
@@ -56,7 +57,7 @@ const vaxis_parser = [_]Edit{
\\ if (inner.n == 0) return inner;
\\ if (inner.event) |*event| switch (event.*) {
\\ .key_press, .key_release => |*key| key.mods.alt = true,
- \\ else => {},
+ \\ else => return .{ .event = .{ .key_press = .{ .codepoint = Key.escape } }, .n = 1 },
\\ };
\\ inner.n += 1;
\\ return inner;
diff --git a/build/tools.zig b/build/tools.zig
index 62e9817a..a4b41dd7 100644
--- a/build/tools.zig
+++ b/build/tools.zig
@@ -250,12 +250,13 @@ pub fn add(b: *std.Build, c: struct {
if (testMatch(b, c.unit_profile, c.test_filters, syntax_test_step)) |check| check.addArtifactArg(syntax_test);
// The library as a package that depends on pardes is given it
- // (`library`): test/lib's own `zig build test`, over the packages
+ // (`library`): test/consumer's own `zig build test`, over the packages
// this checkout has fetched.
const lib_test = b.addSystemCommand(&.{ b.graph.zig_exe, "build", "test", "--pkg-dir", "../../zig-pkg" });
- lib_test.setCwd(b.path("test/lib"));
+ lib_test.setName("zig build test in test/consumer, a package that depends on pardes");
+ lib_test.setCwd(b.path("test/consumer"));
lib_test.has_side_effects = true;
- const lib_test_step = b.step("lib-test", "build and test the library from a package that depends on pardes (test/lib)");
+ const lib_test_step = b.step("lib-test", "build and test the library from a package that depends on pardes (test/consumer)");
lib_test_step.dependOn(&lib_test.step);
const history = b.addExecutable(.{
diff --git a/core/CHANGELOG.md b/core/CHANGELOG.md
index fe9adec8..faa02ade 100644
--- a/core/CHANGELOG.md
+++ b/core/CHANGELOG.md
@@ -2,6 +2,10 @@
## Unreleased
+- `pardes new --detach[=NAME]` returns once the session runs (registered
+ and listening), printing its name, exit 0; the session runs on in a
+ session of its own. `pardes --detach=NAME` without `new` is still the
+ session itself, until it ends.
- `pardes attach NAME` (and `pardes-gui attach NAME`) is always a client:
a process of its own with its own view, whatever the session was
started in. A session's own terminal or window is only the one it was
@@ -9,8 +13,9 @@
back. Before, an attach to a detached terminal's session handed it this
terminal (the attach waiting as its stub), and `pardes-gui attach` asked
a detached window's session to open its own window again and exited 0.
- A client's Detach ends it with "'NAME' let this client go" and exit 1,
- where the stub said "detached from 'NAME'" and exited 0. Bare, `pardes
+ A client's Detach ends it with "detached from 'NAME', which is still
+ running" and exit 0, as the stub's did (the session's last word on a
+ link, `left`); a session's end, with its code (`ended`). Bare, `pardes
attach` takes the one detached session, else the one session, of either
kind; with several it names them all.
@@ -232,9 +237,9 @@
grammars, highlighting, declarations, syntax tree and themes as the
editor has them, for a program that draws source text itself. Every
dependency but tree-sitter's runtime is lazy in the manifest, so such a
- package fetches the runtime and the grammars of its `tree-sitter` set
+ package fetches the runtime and the grammars of its `grammars` set
and nothing else; `zig build lib-test`, which `unit-test` runs, builds
- one (`test/lib`). The markdown grammar is pinned by its commit: its
+ one (`test/consumer`). The markdown grammar is pinned by its commit: its
branch has moved, and a fresh checkout could not fetch it.
- Enter, `o` and `O` give the new line helix's indent where the file's
@@ -590,6 +595,16 @@
- A scroll in the window never moves the tree-sitter context rows: the
body glides under them.
+- `zig build run-isolated` and its `pardes-isolate` are gone: the
+ terminal's pardes with no host but the terminal and no filesystem had
+ not compiled for some releases, and nothing ran it. So is
+ `-Dtree-sitter=disabled`, a pardes with no tree-sitter, which did not
+ compile either; every build has tree-sitter's runtime. The grammar set
+ is `-Dgrammars` (`.grammars` for a package that depends on pardes, no
+ longer `.@"tree-sitter"`): `none`, the runtime alone, where a program
+ hands in a grammar of its own at run time, `minimal` or `full`; the
+ `zig` set, which `none` replaces, is gone.
+
## 0.24
- Edit runs all of acme's commands: `< | >` through your Shell (one undo
diff --git a/core/Core.zig b/core/Core.zig
index 9a542940..7ebcc020 100644
--- a/core/Core.zig
+++ b/core/Core.zig
@@ -1324,18 +1324,15 @@ fn nextQueued(p: *Pardes) ?Event {
}
pub fn hostForegroundName(p: *const Pardes, id: usize, buf: []u8) ?[]const u8 {
- const f = p.host.vtable.fg_name orelse return null;
- return f(p.host.ctx, .at(id), buf);
+ return p.tape.host(p, .fg_name, .{ .at(id), buf }) orelse null;
}
pub fn hostTtyTaken(p: *const Pardes, id: usize) bool {
- const f = p.host.vtable.tty_taken orelse return false;
- return f(p.host.ctx, .at(id));
+ return p.tape.host(p, .tty_taken, .{.at(id)}) orelse false;
}
pub fn hostKillJob(p: *const Pardes, id: usize) bool {
- const f = p.host.vtable.kill_job orelse return false;
- return f(p.host.ctx, .at(id));
+ return p.tape.host(p, .kill_job, .{.at(id)}) orelse false;
}
/// A terminal whose shell could not be started: said, and a run waiting
@@ -1471,25 +1468,22 @@ pub fn animationActive(p: *const Pardes) bool {
}
pub fn pump(p: *Pardes, host: Host) !void {
- // By hand, not `taped`: the host is set before the enter, which wraps it, and is no input.
+ // By hand, not `taped`: the host is set before the enter, which says which functions it has if it is another, and is no input.
p.host = host;
const taped = pardes.tape.enter(p, .pump);
defer pardes.tape.leave(p, taped);
- // The host as the tape sees it, while it records.
- const h = p.host;
- const v = h.vtable;
- if (v.wait_input) |f| {
+ if (p.tape.has(p, .wait_input)) {
// Asleep until input or until the core's next deadline
// (nextWake); 0 is no timeout at all.
// The clock read whether or not it is wanted: what a replica
// waits on is its own (a picture decoding wakes only a frame
// that draws it), and the tape has the same calls either way.
- const now = if (v.now) |clock| clock(h.ctx) else p.clock.now_ns;
+ const now = p.tape.host(p, .now, .{}) orelse p.clock.now_ns;
const timeout: u32 = if (p.nextWake()) |due| wake: {
const ms = ((due -| now) + std.time.ns_per_ms - 1) / std.time.ns_per_ms;
break :wake @intCast(std.math.clamp(ms, 1, std.math.maxInt(u32)));
} else 0;
- f(h.ctx, timeout);
+ _ = p.tape.host(p, .wait_input, .{timeout});
}
// Detached, nobody's key dismisses a message: they go on the clock,
// here in the step, where the clock read is taped (the host's wait
@@ -1497,46 +1491,54 @@ pub fn pump(p: *Pardes, host: Host) !void {
// go).
Messages.expireUnattended(p);
p.frames.mark_start = FrameStats.nowNs();
- if (v.now) |clock| p.advance(clock(h.ctx));
+ if (p.tape.host(p, .now, .{})) |now| p.advance(now);
p.settle();
// A quitting frame has already freed what it would draw.
if (p.quit) return;
- if (v.poll_frame) |f| f(h.ctx);
+ _ = p.tape.host(p, .poll_frame, .{});
// Nothing to draw: do not spend a frame, and above all do not block on
// the display for one. This is what keeps the frame rate governing
// rendering and nothing else.
// A shell with a clock draws what `advance` stepped; one without
// steps its own `.tick`s and draws while a deadline is due.
- if (!p.needs_frame and (v.now != null or !p.animationActive())) return p.frames.idle();
+ if (!p.needs_frame and (p.tape.has(p, .now) or !p.animationActive())) return p.frames.idle();
// No one to see it: the frame stays owed (needs_frame), not drawn.
// A pty streaming into an unwatched session spent most of its time
// drawing what nobody looked at.
- if (v.watched) |f| if (!f(h.ctx)) return;
+ if (!(p.tape.host(p, .watched, .{}) orelse true)) return;
// The one view this process shows (a replica client's is its own
// process's to draw), drawn as it is if another's is live.
// Not shown by the frontend (Host.present): owed.
var skipped = false;
const shown = Views.shown(p);
if (shown != p.live) {
- if (shown) |k| skipped = !try Views.drawOne(p, k, .{ .ctx = h.ctx, .f = v.present });
+ if (shown) |k| skipped = !try Views.drawOne(p, k, .{ .ctx = p, .f = presentTaped });
} else {
_ = p.frame_arena.reset(.{ .retain_with_limit = memory.limits.frame_kept });
p.frames.mark_update = FrameStats.nowNs();
p.frames.view = if (p.panes[p.view().active]) |pane| pane.scroll() else 0;
const surface = try p.render(p.frame_arena.allocator());
p.frames.mark_render = FrameStats.nowNs();
- if (v.present) |f| skipped = !f(h.ctx, surface);
+ skipped = !(p.tape.host(p, .present, .{surface}) orelse true);
Stream.askAhead(p);
}
// Settled before post_present: a shell ticks there, and what that
// tick moves owes the next frame.
p.needs_frame = skipped;
- if (v.post_present) |f| f(h.ctx);
+ _ = p.tape.host(p, .post_present, .{});
// Still moving: the next frame is owed a period from now.
const owed = if (p.nextWake()) |due| due <= p.clock.stepped_ns + frame_ns else false;
p.frames.record(FrameStats.nowNs(), owed, skipped);
}
+/// The pump's other view presented as its own is, through the tape:
+/// `present` stays inside `views.within`, whose live view the host's
+/// `presented` reads.
+fn presentTaped(ctx: ?*anyopaque, surface: *const pardes.Surface) bool {
+ const p: *Pardes = @ptrCast(@alignCast(ctx.?));
+ return p.tape.host(p, .present, .{surface}) orelse true;
+}
+
/// What a pump does between its wait and its frame: the queued inputs
/// and the effects. Also the session at a step boundary, taken now (an
/// Upgrade's dump, upgrade.zig).
@@ -2073,7 +2075,7 @@ pub fn nextWake(p: *const Pardes) ?u64 {
};
// Del's question goes up at the end of its delay: a frame then, and
// none after (stepped time has reached it).
- for (p.panes) |slot| if (slot) |pane| if (pane.prompt == .del_side and pane.question_due_ns > p.clock.stepped_ns) {
+ for (p.panes) |slot| if (slot) |pane| if (pane.prompt == .del_side and pane.question_due_ns > p.clock.stepped_ns and pane.question_due_ns != Pane.question_asked) {
const wait = @max(1, (pane.question_due_ns - p.clock.stepped_ns + frame_ns - 1) / frame_ns);
frames = if (frames) |soonest| @min(soonest, wait) else wait;
};
@@ -2114,6 +2116,10 @@ fn advanceInner(p: *Pardes, now_ns: u64) void {
p.clock.started = true;
p.clock.now_ns = now_ns;
if (!started) p.clock.stepped_ns = now_ns;
+ // Del's question asked since the last advance: its delay from now.
+ for (p.panes) |slot| if (slot) |pane| if (pane.question_due_ns == Pane.question_asked) {
+ pane.question_due_ns = now_ns + config.del_question_delay_ns;
+ };
const frame = frame_ns;
var moving: u32 = 0;
// The session's ticks are the recording session's: a picture still
@@ -2273,6 +2279,11 @@ pub const Options = struct {
startup_config: ?[]const u8 = null,
ninep_name: []const u8 = "",
ninep_tcp: ?[]const u8 = null,
+ /// This process's end of a socket pair its launch made (runtime/main.zig,
+ /// PARDES_PAIR): a session's first client is on it, taken before its
+ /// first effects (runtime/session.zig); a client's session is on it,
+ /// its first join made there with no hello (replica.join).
+ pair: ?c_int = null,
mounts: []const filesystem.Mount = &.{},
config_dir: ?[]const u8 = null,
/// Where what outlives the session is kept (Db.zig): the user's state
@@ -2502,7 +2513,6 @@ test "LocationsConfig command reports partial updates and survives restore" {
}
test "TreeContext rows in the tag style keep the message rows" {
- if (comptime !syntax.enabled) return error.SkipZigTest;
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 60, .rows = 16 });
defer p.deinit();
const pane = try p.setTestFile("pub const Box = struct {\n pub fn run() void {\n" ++ (std.mem.asBytes(&@as([30][16]u8, @splat(" // body\n".*)))) ++ " }\n};\n");
@@ -2545,7 +2555,6 @@ test "TreeContext rows in the tag style keep the message rows" {
}
test "TreeContext command and custom tag survive a workspace round trip" {
- if (comptime !syntax.enabled) return error.SkipZigTest;
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
defer p.deinit();
const pane = try p.setTestFile("pub fn main() void {}\n");
diff --git a/core/Dir.zig b/core/Dir.zig
index 29c5cdc8..869a7cd5 100644
--- a/core/Dir.zig
+++ b/core/Dir.zig
@@ -47,7 +47,6 @@ pub fn ofName(name: []const u8) []const u8 {
/// dotfiles too; a directory's, a link to one's too, ending in `/`; sorted
/// bytewise, the `/` counted; each ending in a newline.
pub fn read(tape: *pardes.tape.Tape, gpa: std.mem.Allocator, dir: []const u8) ![]u8 {
- if (comptime !filesystem.platform_has_fs) return error.FileNotFound;
const local = filesystem.localPath(dir) orelse return error.NotLocal;
// Its own copy: the caller's may be a pane's, gone while the turn is out.
var own: [4096]u8 = undefined;
@@ -294,7 +293,6 @@ test "a wide character counts its cells, not its bytes" {
}
test "a directory reads as acme lists it: dotfiles kept, . and .. not, directories and links to them marked, sorted bytewise" {
- if (comptime !filesystem.platform_has_fs) return;
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
const io = testing.io;
diff --git a/core/Effect.zig b/core/Effect.zig
index 5e821065..cabfe8ea 100644
--- a/core/Effect.zig
+++ b/core/Effect.zig
@@ -116,34 +116,33 @@ pub const perform = tape.taped(performInner);
fn performInner(p: *Pardes, e: Effect) void {
// A Save performed on one twin is every twin's (File.syncTwins).
defer panes.File.syncTwins(p);
- const v = p.host.vtable;
switch (e) {
// The host reads the pane (its command, its shell) as it forks,
// so the slot must still hold the pane the spawn was for.
- .spawn => |s| if (if (p.panes[s.pane.index()]) |pane| pane.serial != s.serial else true) {} else if (v.spawn) |f| f(p.host.ctx, s.pane, if (s.cwd.len == 0) (p.spawn_dirs[s.pane.index()] orelse "") else s.cwd.slice()) else {
+ .spawn => |s| if (if (p.panes[s.pane.index()]) |pane| pane.serial != s.serial else true) {} else p.tape.host(p, .spawn, .{ s.pane, if (s.cwd.len == 0) (p.spawn_dirs[s.pane.index()] orelse "") else s.cwd.slice() }) orelse {
p.fallback.spawned[s.pane.index()] = true;
},
// A pane with no child is silent: nothing invents output on its
// screen, and the bytes are dropped rather than transcribed.
- .write => |w| if (v.pty_write) |f| f(p.host.ctx, w.pane, w.bytes.slice()),
- .resize_pty => |r| if (v.pty_resize) |f| f(p.host.ctx, r.pane, r.cols, r.rows),
+ .write => |w| _ = p.tape.host(p, .pty_write, .{ w.pane, w.bytes.slice() }),
+ .resize_pty => |r| _ = p.tape.host(p, .pty_resize, .{ r.pane, r.cols, r.rows }),
// A signal for a pane that closed, its slot retaken in the same
// step, would reach another pane's child.
- .signal_pty => |s| if (if (p.panes[s.pane.index()]) |pane| pane.serial != s.serial else true) {} else if (v.pty_signal) |f| f(p.host.ctx, s.pane, s.sig),
- .close_pty => |c| if (v.close_pty) |f| f(p.host.ctx, c.pane),
+ .signal_pty => |s| if (if (p.panes[s.pane.index()]) |pane| pane.serial != s.serial else true) {} else p.tape.host(p, .pty_signal, .{ s.pane, s.sig }) orelse {},
+ .close_pty => |c| _ = p.tape.host(p, .close_pty, .{c.pane}),
// The view's frontend opens it, yanks and pastes, on its own
// machine (View.yanks); the host here only for a view no client
// draws (tape.hostCall).
.open_link => |u| {
p.view().links +%= 1;
p.view().link = u;
- if (v.open_link) |f| f(p.host.ctx, u.slice()) else p.fallback.setLink(u.slice());
+ p.tape.host(p, .open_link, .{u.slice()}) orelse p.fallback.setLink(u.slice());
},
// Plan 9's plumber's, detached (host_io.startDetached); in-process
// (a test), kept to look at.
.start => |st| {
var why_buf: [64]u8 = undefined;
- const why = if (v.start) |f| f(p.host.ctx, st.line.slice(), &why_buf) else p.fallback.start(st.line.slice());
+ const why = p.tape.host(p, .start, .{ st.line.slice(), &why_buf }) orelse p.fallback.start(st.line.slice());
const w = why orelse return;
var words = std.mem.splitScalar(u8, st.line.slice(), 0);
_ = words.next(); // its directory
@@ -191,37 +190,31 @@ fn performInner(p: *Pardes, e: Effect) void {
},
.write_dump => {
const out = p.dump_out orelse return;
- if (v.write_dump) |f| {
- f(p.host.ctx, out);
- } else {
+ p.tape.host(p, .write_dump, .{out}) orelse {
_ = p.fallback.writeFile(host_io.Fallback.dump_path, out);
p.setLastDump(host_io.Fallback.dump_path);
- }
+ };
},
.set_clipboard => {
p.view().yanks +%= 1;
const text = p.registers.text(p.gpa, '+') orelse "";
- if (v.set_clipboard) |f| f(p.host.ctx, text) else p.fallback.setClipboard(text);
+ p.tape.host(p, .set_clipboard, .{text}) orelse p.fallback.setClipboard(text);
},
// No desktop to ask: answer from the in-process clipboard at once,
// which is the same shape as a host answering later.
.read_clipboard => {
p.view().pastes +%= 1;
- if (v.read_clipboard) |f| f(p.host.ctx) else p.update(.{ .paste = p.fallback.clipboard.items });
+ p.tape.host(p, .read_clipboard, .{}) orelse p.update(.{ .paste = p.fallback.clipboard.items });
},
- .lsp => |q| if (v.lsp) |f|
- f(p.host.ctx, .{ .id = q.id, .kind = q.kind, .pane = q.pane, .offset = q.offset, .arg = q.arg.slice() })
- else
+ .lsp => |q| p.tape.host(p, .lsp, .{.{ .id = q.id, .kind = q.kind, .pane = q.pane, .offset = q.offset, .arg = q.arg.slice() }}) orelse
p.update(.{ .lsp_resp = .{ .id = q.id, .rows = "" } }),
- .pipe => |q| if (v.pipe) |f|
- f(p.host.ctx, q.id)
- else
+ .pipe => |q| p.tape.host(p, .pipe, .{q.id}) orelse
p.update(.{ .pipe_resp = .{ .id = q.id, .success = false, .outputs = &.{} } }),
// No workers here (a test, a board): it runs on the loop.
- .search => |q| if (v.search) |f| f(p.host.ctx, q.gen) else Stream.runHere(p, q.gen, false),
+ .search => |q| p.tape.host(p, .search, .{q.gen}) orelse Stream.runHere(p, q.gen, false),
// No windows here (a test, the tty): it stays.
- .hand_over => |h| if (v.hand_over) |f| {
- if (p.handover.bytes) |bytes| f(p.host.ctx, h.seq, bytes);
+ .hand_over => |h| if (p.tape.has(p, .hand_over)) {
+ if (p.handover.bytes) |bytes| _ = p.tape.host(p, .hand_over, .{ h.seq, bytes });
} else p.update(.{ .handed = .{ .seq = h.seq, .failure = "no other windows here" } }),
.edit_write => {
// Each write takes the bytes `w` took when it ran: the text
@@ -247,24 +240,21 @@ fn performInner(p: *Pardes, e: Effect) void {
} else ctlfs.events.noteLogAs(p, .save, pane, w.path);
}
},
- .watch => |w| if (v.watch_file) |f| {
+ .watch => |w| {
// What a watch is about: a real file, or a kind's (a PDF's).
const path: []const u8 = if (p.panes[w.pane.index()]) |pane| (if (pane.file) |file| (if (file.output == null) file.path else "") else if (pane.addon) |k| k.path else "") else "";
- f(p.host.ctx, w.pane, path, w.on, w.mode);
- } else {
- p.fallback.watched[w.pane.index()] = w.on;
+ p.tape.host(p, .watch_file, .{ w.pane, path, w.on, w.mode }) orelse {
+ p.fallback.watched[w.pane.index()] = w.on;
+ };
},
- .theme_file => |t| if (v.watch_theme) |f| f(p.host.ctx, t.generation, t.on),
- .dump_themes => |d| if (v.dump_themes) |f| f(p.host.ctx, d.pane),
- .detach => |d| if (v.detach) |f|
- f(p.host.ctx)
- else
- p.reportError(d.pane, "detach", error.NotAttached),
+ .theme_file => |t| _ = p.tape.host(p, .watch_theme, .{ t.generation, t.on }),
+ .dump_themes => |d| _ = p.tape.host(p, .dump_themes, .{d.pane}),
+ .detach => |d| p.tape.host(p, .detach, .{}) orelse p.reportError(d.pane, "detach", error.NotAttached),
// dlopen is the same on every host, so none has a method of its
// own; a replica's core holds no library (what it brought comes in
// the event this taped).
- .addon => |a| if (!tape.replaying()) @import("Addon.zig").perform(p, a.op, a.pane.index(), a.arg.slice()),
- .job => |j| if (v.job) |f| f(p.host.ctx, j.pane, j.serial, j.token) else if (!tape.replaying()) host_io.KindJob.runHere(p, j.pane.index(), j.serial, j.token),
+ .addon => |a| if (!p.tape.replaying()) @import("Addon.zig").perform(p, a.op, a.pane.index(), a.arg.slice()),
+ .job => |j| p.tape.host(p, .job, .{ j.pane, j.serial, j.token }) orelse if (!p.tape.replaying()) host_io.KindJob.runHere(p, j.pane.index(), j.serial, j.token),
// the loop's own condition; a host tears down after its own loop
.quit => p.endSession(),
}
@@ -282,7 +272,7 @@ pub fn writeChecked(p: *Pardes, id: u8, serial: u32, path: []const u8, bytes: []
if (filesystem.localPath(path)) |local| filesystem.makeDirs(p.tape, std.Io.Dir.path.dirname(local) orelse "/");
// The in-process filesystem reports the same way a real host does,
// so an OOM there leaves the pane dirty rather than looking saved.
- if (p.host.vtable.write_file) |f| f(p.host.ctx, .at(id), path, bytes) else if (!p.fallback.writeFile(path, bytes)) p.saveFailed(.at(id), path, error.OutOfMemory);
+ p.tape.host(p, .write_file, .{ .at(id), path, bytes }) orelse if (!p.fallback.writeFile(path, bytes)) p.saveFailed(.at(id), path, error.OutOfMemory);
const pane = p.panes[id] orelse return null;
if (pane.serial != serial) return null;
if (p.fs.failures == failures) return pane;
diff --git a/core/File.zig b/core/File.zig
index 75d8049b..ceb6d03b 100644
--- a/core/File.zig
+++ b/core/File.zig
@@ -1579,7 +1579,7 @@ pub fn refreshHighlights(p: *Pardes) void {
// itself on the frame, a third of the work; the stretch around it
// comes painted ahead (paintAhead) where there are workers.
const far = f.highlights.len == 0 or need_end <= f.highlight_start or need_start >= f.highlight_start + f.highlights.len;
- const slack: usize = if (far and p.host.vtable.search != null) 0 else if (f.highlights.len == 0) 0 else pane.rows;
+ const slack: usize = if (far and p.tape.has(p, .search)) 0 else if (f.highlights.len == 0) 0 else pane.rows;
const whole = pane.colorAlgo() == .locations or f.tree_context;
// Painted ahead on a worker (Stream.paintAhead): taken, no parse.
if (!whole and pane.colorAlgo() == .source) if (Stream.takeAhead(p, pane.serial, f.revision, need_start, need_end)) |got| {
@@ -2312,7 +2312,6 @@ test "a pager's text is a diff when it holds a diff header or a unified hunk" {
}
test "a long line is painted only around the caret" {
- if (!syntax.enabled) return;
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 });
defer p.deinit();
const line = try std.testing.allocator.alloc(u8, 600 << 10);
@@ -2357,6 +2356,20 @@ test "a caret deep in a long line scrolls the view sideways to it, measured from
try std.testing.expectEqual(@as(i32, 0), pane.hscroll);
}
+test "a caret left of a view scrolled sideways is not drawn in the gutter" {
+ const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 });
+ defer p.deinit();
+ p.settings.wrap = false;
+ const pane = try p.setTestFile("short1 END_A_MARKER_WAY_OUT_RIGHT_padpadpadpadpadpadpadpadpadpadpad_TAIL\n");
+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena.deinit();
+ try std.testing.expect((try p.render(arena.allocator())).cursor != null);
+ // One wheel notch (4 columns) of the 7 the gutter is: the caret, at
+ // column 0, was drawn 3 columns into the gutter.
+ pane.hscroll = 4;
+ try std.testing.expect((try p.render(arena.allocator())).cursor == null);
+}
+
test "undo and redo walk back and forth through every step of random edits, joined entries and all" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
diff --git a/core/Output.zig b/core/Output.zig
index 759bada9..c7bfde14 100644
--- a/core/Output.zig
+++ b/core/Output.zig
@@ -907,7 +907,7 @@ pub fn openBuild(p: *Pardes, id: usize) !void {
@tagName(builtin.abi), @tagName(build_options.platform),
});
try w.print("grammars {s}\naddons {s}\nsemantics {x:0>16}\n\ndependencies\n{s}", .{
- if (build_options.grammars == .full) "full" else if (build_options.grammars == .minimal) "minimal" else "none",
+ @tagName(build_options.grammars),
if (build_options.builtin_addons) "compiled in" else "loaded from <prefix>/lib/pardes/addons",
@import("wire").semantics,
build_info.deps,
diff --git a/core/Plumb.zig b/core/Plumb.zig
index aeebfc64..f51ddace 100644
--- a/core/Plumb.zig
+++ b/core/Plumb.zig
@@ -1314,7 +1314,6 @@ test "plumb: a set rewrites the message for good, attr delete of one absent fail
}
test "plumb: isfile and isdir find a name as Look does, past its place, in the message's directory then Incl's; $file is where" {
- if (!fs.platform_has_fs) return;
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
try tmp.dir.writeFile(testing.io, .{ .sub_path = "it.zig", .data = "x\n" });
@@ -1482,7 +1481,6 @@ test "plumb: plan9port's basic parses, its ¡-￿ classes UTF-8's bytes and its
}
test "plumb: the Plumb word opens the plumbing file, include basic until one is saved; saved, or read at boot, its rules are in force, a bad one said with its line" {
- if (!fs.platform_has_fs) return;
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var dir_buf: [4096]u8 = undefined;
diff --git a/core/Query.zig b/core/Query.zig
index 704206e6..ebb44155 100644
--- a/core/Query.zig
+++ b/core/Query.zig
@@ -2294,7 +2294,6 @@ fn settle(p: *Pardes) void {
}
test "Find: names fuzzy per keystroke, the group born with its +Preview, nothing else moves, Enter promotes the preview in place" {
- if (!filesystem.platform_has_fs) return;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
try tmp.dir.createDirPath(std.testing.io, "src");
@@ -2346,7 +2345,6 @@ test "Find: names fuzzy per keystroke, the group born with its +Preview, nothing
}
test "Grep: lines of the files under the owner's directory, under their file; All: every pane's, under @pN in serial order, a line once" {
- if (!filesystem.platform_has_fs) return;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "b.zig", .data = "const needle = 1;\nconst hay = 2;\nneedle needle\n" });
@@ -2568,7 +2566,6 @@ test "Enter on a frozen query pane's rows after its text was edited: no row to l
}
test "a query row's place is its text: the match tinted after it, B3 on it opens the place, the rows saved and read again still Look" {
- if (!filesystem.platform_has_fs) return;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 48 });
@@ -2627,7 +2624,6 @@ test "a query row's place is its text: the match tinted after it, B3 on it opens
}
test "the +Preview: the query's hits in its file are its places, the row's one current and selected, coloured as the file is" {
- if (!filesystem.platform_has_fs) return;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
const text = "const needle = 1;\nconst hay = 2;\nfn f() void {\n _ = needle;\n}\npub const needle_too = needle;\n";
@@ -2662,7 +2658,6 @@ test "the +Preview: the query's hits in its file are its places, the row's one c
sel = pv.body.primaryRange(pv.file.?.content, 0);
try std.testing.expectEqual(expected.items[2].start, @min(sel.anchor, sel.head));
// its colours the file's, as its own pane paints them
- if (!syntax.enabled) return;
var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
defer frame.deinit();
_ = try p.render(frame.allocator());
@@ -2674,7 +2669,6 @@ test "the +Preview: the query's hits in its file are its places, the row's one c
}
test "a row's address is the shortest path a Look from the query pane resolves: in its directory, under it, above it, else absolute" {
- if (!filesystem.platform_has_fs) return;
if (!pardes.lsp.supports.contains(.references)) return;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
@@ -2716,7 +2710,6 @@ test "a row's address is the shortest path a Look from the query pane resolves:
}
test "a query row's address reaches every way a look arrives: an empty look written back to event and the whole row written to look, as the mouse on it" {
- if (!filesystem.platform_has_fs) return;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 48 });
diff --git a/core/Stream.zig b/core/Stream.zig
index 5960d249..1f4a7405 100644
--- a/core/Stream.zig
+++ b/core/Stream.zig
@@ -311,7 +311,7 @@ pub fn takeAhead(p: *Pardes, serial: u32, revision: u32, need_start: usize, need
/// workers, and only for a grammar a worker can paint (syntax.readyApart).
pub fn paintAhead(p: *Pardes, serial: u32, revision: u32, path: []const u8, content: []const u8, from: usize, to: usize) void {
const s = &p.stream;
- if (p.host.vtable.search == null or p.fs.serving or to <= from or to > content.len) return;
+ if (!p.tape.has(p, .search) or p.fs.serving or to <= from or to > content.len) return;
const a = s.ahead_for;
if (s.ahead.len != 0 and a.serial == serial and a.revision == revision and from >= a.start and to <= a.start + s.ahead.len) return;
// A stretch bigger than this (a few lines of a minified file) is not
@@ -343,7 +343,7 @@ pub fn paintAhead(p: *Pardes, serial: u32, revision: u32, path: []const u8, cont
pub fn askAhead(p: *Pardes) void {
const gen = p.stream.ahead_ask orelse return;
p.stream.ahead_ask = null;
- if (p.host.vtable.search) |f| f(p.host.ctx, gen);
+ _ = p.tape.host(p, .search, .{gen});
}
/// A file's colours for the query rows that show its lines, the whole
@@ -355,7 +355,7 @@ pub fn askAhead(p: *Pardes) void {
/// one revision of a file.
pub fn paintRows(p: *Pardes, path: []const u8) void {
const s = &p.stream;
- if (s.rows_paint != null or p.host.vtable.search == null) return;
+ if (s.rows_paint != null or !p.tape.has(p, .search)) return;
// Asked while a 9P write is served (a script's Grep): not now, as no
// paint is (the write would wait for it to settle); the next step asks.
if (p.fs.serving) {
@@ -452,7 +452,7 @@ pub fn parseFor(p: *Pardes, id: usize) void {
s.parse_next = .{ .serial = pane.serial, .revision = f.revision };
return;
}
- const workers = p.host.vtable.search != null and !p.fs.serving;
+ const workers = p.tape.has(p, .search) and !p.fs.serving;
if (!workers and f.content.len > 64 << 10) return;
const job = TextJob.make(p.gpa, pane.serial, f.revision, 0, f.path, f.content) orelse return;
s.gen +%= 1;
@@ -478,7 +478,6 @@ fn parseWork(io: std.Io, job: *TextJob, ctx: ?*anyopaque, sink: Sink) void {
}
fn now() u64 {
- if (comptime !filesystem.platform_has_fs) return 0;
const t = std.Io.Clock.awake.now(std.Io.Threaded.global_single_threaded.io());
return @intCast(@max(0, t.nanoseconds));
}
@@ -559,7 +558,7 @@ pub fn step(p: *Pardes) void {
s.state = .searching;
// A script's write (whose answer says whether it found anything) and a
// host with no workers: done before this returns.
- if (p.host.vtable.search != null and !p.fs.serving) p.emit(.{ .search = .{ .gen = s.gen } }) else runHere(p, s.gen, false);
+ if (p.tape.has(p, .search) and !p.fs.serving) p.emit(.{ .search = .{ .gen = s.gen } }) else runHere(p, s.gen, false);
}
/// When the core next needs a tick for the stream: the end of the pause.
@@ -635,10 +634,6 @@ pub fn runHere(p: *Pardes, gen: u32, comptime in_call: bool) void {
};
return;
}
- if (comptime !filesystem.platform_has_fs) {
- p.stream.state = .failed;
- return;
- }
const s = &p.stream;
if (gen != s.gen or s.state != .searching) return;
const job = makeJob(p.gpa, s) catch |err| {
@@ -1163,7 +1158,6 @@ const Rogue = struct {
};
test "Stream: a stale generation's rows never land in the query pane, however two generations race (walk and rg)" {
- if (comptime !filesystem.platform_has_fs) return;
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var root_buf: [4096]u8 = undefined;
@@ -1243,7 +1237,6 @@ test "Stream: a stale generation's rows never land in the query pane, however tw
}
test "Stream: the listing of files for Find on a worker, a cap of hits stops the walk on the loop" {
- if (comptime !filesystem.platform_has_fs) return;
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var root_buf: [4096]u8 = undefined;
@@ -1273,7 +1266,6 @@ test "Stream: the listing of files for Find on a worker, a cap of hits stops the
}
test "Stream: a big text's declarations are parsed on a worker, never the loop, and the rows of its / regroup under them" {
- if (comptime !filesystem.platform_has_fs) return;
const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 });
defer p.deinit();
var text: std.ArrayList(u8) = .empty;
@@ -1312,7 +1304,6 @@ test "Stream: a big text's declarations are parsed on a worker, never the loop,
}
test "Stream: a scroll's colours are painted ahead on a worker, so PageDown after PageDown parses nothing on the frame" {
- if (comptime !filesystem.platform_has_fs or !syntax.enabled) return;
const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 });
defer p.deinit();
var text: std.ArrayList(u8) = .empty;
@@ -1355,7 +1346,6 @@ test "Stream: a scroll's colours are painted ahead on a worker, so PageDown afte
}
test "Stream: a Grep stops at its 2000 lines and waits; More in the query pane's tag goes on" {
- if (comptime !filesystem.platform_has_fs) return;
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var root_buf: [4096]u8 = undefined;
@@ -1404,8 +1394,7 @@ test "Stream: a Grep stops at its 2000 lines and waits; More in the query pane's
}
test "Stream: a Grep's rows recoloured are made again, never written, and a dump of them dropped by an edit loads to its digest" {
- if (comptime !filesystem.platform_has_fs) return;
- if (!syntax.enabled or !syntax.readyApart("c.zig")) return;
+ if (!syntax.readyApart("c.zig")) return;
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
// Rows enough that a digest keeps a word for them (walk's blob_min).
@@ -1476,8 +1465,7 @@ test "Stream: a Grep's rows recoloured are made again, never written, and a dump
}
test "Stream: a Grep's rows are coloured as their file's language colours them, the file painted on a worker, the match tint on top" {
- if (comptime !filesystem.platform_has_fs) return;
- if (!syntax.enabled or !syntax.readyApart("c.zig")) return;
+ if (!syntax.readyApart("c.zig")) return;
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
const text = "const std = @import(\"std\");\npub fn value() u32 {\n return 42; // value\n}\n";
diff --git a/core/body_layer.zig b/core/body_layer.zig
index 7dc097ad..1582136c 100644
--- a/core/body_layer.zig
+++ b/core/body_layer.zig
@@ -512,7 +512,10 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane
)
else
ccol;
- if (prow >= pane.tag_rows and cx >= 0 and prow < body_bottom and cx < tw)
+ // Left of a view scrolled sideways it is off the view, not
+ // in the gutter.
+ const left: i32 = if (pane.file != null) panes.File.gutterWidth(pane) else 0;
+ if (prow >= pane.tag_rows and cx >= left and prow < body_bottom and cx < tw)
s.cursor = .{ .x = tx + @as(u16, @intCast(cx)), .y = body_y + @as(u16, @intCast(prow - pane.tag_rows)), .bar = pane.body.mode == .insert };
}
} else if (pane.terminal != null) visible: {
diff --git a/core/builtins.zig b/core/builtins.zig
index 2740e05a..894478fd 100644
--- a/core/builtins.zig
+++ b/core/builtins.zig
@@ -547,8 +547,7 @@ pub const Adopt = struct {
pub const scope: Scope = .session;
pub const enabled = pardes.can_attach;
pub fn run(c: Ctx) void {
- const adopt = c.p.host.vtable.adopt orelse return c.p.reportFailure(c.id, "Adopt: no pardes daemon is keeping shells for this session");
- adopt(c.p.host.ctx, .at(c.id));
+ c.p.tape.host(c.p, .adopt, .{.at(c.id)}) orelse c.p.reportFailure(c.id, "Adopt: no pardes daemon is keeping shells for this session");
}
};
@@ -559,8 +558,7 @@ pub const Upgrade = struct {
pub const scope: Scope = .session;
pub const enabled = pardes.can_attach;
pub fn run(c: Ctx) void {
- const upgrade = c.p.host.vtable.upgrade orelse return c.p.reportFailure(c.id, "Upgrade: this pardes cannot move to another build in place");
- upgrade(c.p.host.ctx, .at(c.id));
+ c.p.tape.host(c.p, .upgrade, .{.at(c.id)}) orelse c.p.reportFailure(c.id, "Upgrade: this pardes cannot move to another build in place");
}
};
@@ -700,11 +698,9 @@ pub const Fonts = struct {
/// Show the declarations enclosing the top row at the pane's head, on or off.
pub const TreeContext = struct {
- pub const enabled = pardes.syntax.enabled;
pub const takes_arg = true;
pub fn run(c: Ctx) void {
- if (comptime !enabled) unreachable;
if (!panes.File.supportsContext(c.pane)) return c.p.reportFailure(c.id, "TreeContext: only a source file the parser knows has context");
const file = &c.pane.file.?;
const arg = std.mem.trim(u8, c.arg orelse "", " \t\r\n");
@@ -1044,7 +1040,7 @@ pub const Del = struct {
!c.pane.collapsed and c.pane.prompt == .none)
{
c.pane.prompt = .del_side;
- c.pane.question_due_ns = exec.clockNow(c.p) + config.del_question_delay_ns;
+ c.pane.question_due_ns = Pane.question_asked;
c.p.view().active = c.id;
var rec: [32]u8 = undefined;
pardes.ctlfs.events.notePath(c.p, "ask", std.fmt.bufPrint(&rec, "{d} del k j", .{c.pane.serial}) catch unreachable); // a u32 fits 32
diff --git a/core/config.zig b/core/config.zig
index 3dbfe566..f43604ad 100644
--- a/core/config.zig
+++ b/core/config.zig
@@ -159,7 +159,7 @@ pub const leader_path = paths: {
if (builtins.capabilities.pixels) table.set(.GripWidth, null);
table.set(.InactiveDim, null);
if (builtins.capabilities.pixels) table.set(.Pet, null);
- if (builtins.TreeContext.enabled) table.set(.TreeContext, null);
+ table.set(.TreeContext, null);
table.set(.ThemeFile, null);
table.set(.DumpThemes, null);
table.set(.Mount, null);
diff --git a/core/draw.zig b/core/draw.zig
index 5ff31af6..b87eb56f 100644
--- a/core/draw.zig
+++ b/core/draw.zig
@@ -1295,7 +1295,6 @@ test "a wide glyph cut by a tag's or a notice's edge is joined into the grid as
}
test "a body with context rows is painted once, and the grid's rows are what a plain paint of it gives" {
- if (comptime !@import("syntax.zig").enabled) return error.SkipZigTest;
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 60, .rows = 16 });
defer p.deinit();
const pane = try p.setTestFile("pub const Box = struct {\n pub fn run() void {\n" ++ (std.mem.asBytes(&@as([30][21]u8, @splat(" // body line\n".*)))) ++ " }\n};\n");
diff --git a/core/dump.zig b/core/dump.zig
index eb0ef263..c348dec2 100644
--- a/core/dump.zig
+++ b/core/dump.zig
@@ -11,7 +11,6 @@ const exec = @import("exec.zig");
const colors = @import("colors.zig");
const config = @import("config.zig");
const platform = pardes.platform;
-const isolated = pardes.isolated;
const MAX_PANES = pardes.MAX_PANES;
const MAX_COLS = pardes.MAX_COLS;
const effect_path_cap = pardes.effect_path_cap;
@@ -662,13 +661,11 @@ fn revivePane(p: *Pardes, id: usize, pane: *pardes.panes.Pane, was_on_disk: bool
if (pane.terminal != null) {
// A command pane comes back finished, showing what it said: its
// command is not run again. A host that runs shells starts one
- // under the history in the old one's directory; an isolated build
- // only shows it.
+ // under the history in the old one's directory.
if (pane.command != null) {
pane.command_done = true;
return;
}
- if (comptime isolated) return;
if (pane.cwdSlice().len > effect_path_cap) return;
// Its shell not there, made ready for a new one: what the old
// shell was, ran and said is gone with it (the REPL it ran, the
@@ -1060,7 +1057,6 @@ test "a pane restored with unsaved text is asked about by Exit, Restore, Del and
test "a loaded terminal's history stays above its banner, the cursor where it was" {
if (pardes.Term.ops == null) return error.SkipZigTest; // it reads the emulator
- if (comptime isolated) return error.SkipZigTest;
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 });
defer p.deinit();
@@ -1082,7 +1078,6 @@ test "a loaded terminal's history stays above its banner, the cursor where it wa
test "an upgraded session's dump keeps its views and its running terminal as they were, and settings the startup config would change" {
if (pardes.Term.ops == null) return error.SkipZigTest; // a shell, dumped and loaded
- if (comptime isolated) return error.SkipZigTest;
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12, .startup_config = "Verbose off\n" });
defer p.deinit();
diff --git a/core/edit_cmd.zig b/core/edit_cmd.zig
index 9f1f7862..9a5c6865 100644
--- a/core/edit_cmd.zig
+++ b/core/edit_cmd.zig
@@ -610,7 +610,6 @@ test "an Edit whose file is edited while its commands run is refused whole" {
}
test "X over open files, w, e, r, f, B and D on panes and the disk" {
- if (comptime !filesystem.platform_has_fs) return error.SkipZigTest;
const gpa = testing.allocator;
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
@@ -687,7 +686,6 @@ test "X over open files, w, e, r, f, B and D on panes and the disk" {
}
test "an Edit's w to a file changed on disk is refused once, as Save is, and the others are written" {
- if (comptime !filesystem.platform_has_fs) return error.SkipZigTest;
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.txt", .data = "a\n" });
@@ -723,7 +721,6 @@ test "an Edit's w to a file changed on disk is refused once, as Save is, and the
}
test "an Edit with no command runs beside one whose commands run, unless it touches what that one changes" {
- if (comptime !filesystem.platform_has_fs) return error.SkipZigTest;
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
try tmp.dir.writeFile(testing.io, .{ .sub_path = "other.txt", .data = "x\n" });
@@ -784,7 +781,6 @@ test "a session that ends while an Edit's commands run lets the Edit go" {
}
test "e and r say a file that cannot be read as Get says it" {
- if (comptime !filesystem.platform_has_fs) return error.SkipZigTest;
const p = try th.withFile(testing.allocator, "x\n");
defer p.deinit();
const ctl = tree.Node.of(th.serialOf(p), .ctl);
diff --git a/core/exec.zig b/core/exec.zig
index 1ec47eb3..18b519ff 100644
--- a/core/exec.zig
+++ b/core/exec.zig
@@ -418,7 +418,7 @@ fn refusedPlacement(p: *Pardes, id: usize) bool {
/// Whether a shell would be started in `dir` and `dir` is not there: asked
/// only of a host that starts shells, and only of a local path.
pub fn missingDir(p: *Pardes, dir: []const u8) bool {
- if (p.host.vtable.spawn == null) return false;
+ if (!p.tape.has(p, .spawn)) return false;
// A peer's directory (`/n/peer/x`) is no directory on this host, where
// the shell would start: no command or terminal runs there, and none
// is made to say `exit 127`.
@@ -535,7 +535,7 @@ const repl_quiet_ns: u64 = 100 * std.time.ns_per_ms;
/// The host's clock now; core time (`now_ns`, `stepped_ns`) is as old as
/// the last frame, seconds in an idle session.
pub fn clockNow(p: *Pardes) u64 {
- return if (p.host.vtable.now) |clock| clock(p.host.ctx) else p.clock.now_ns;
+ return p.tape.host(p, .now, .{}) orelse p.clock.now_ns;
}
/// Sends the Enters a paste into pane `id`'s REPL is owed: when the REPL
@@ -708,7 +708,7 @@ pub fn executeFrom(p: *Pardes, id: usize, txt: []const u8, from_body: bool) ?usi
const pad = std.math.clamp(max_row - cursor_abs, 0, @as(i32, pane.rows));
for (0..@intCast(pad)) |_| p.emitWrite(id, "\r");
};
- pane.noteCommand(cmd);
+ pane.noteCommand(cmd, panes.Term.prompt(pane.terminal).started);
if (pane.queuePendingCommand(cmd) catch |err| {
p.reportError(.at(id), "queue command", err);
return id;
@@ -1018,7 +1018,7 @@ pub fn applySettingBuiltin(p: *Pardes, setting: config.Settings.Setting, arg: ?[
const spec = config.Settings.FontSpec.parse(arg orelse return) orelse return;
// The session's machine's fonts, a question to its disk: a
// client's replay takes the session's answer, never its own.
- const found = pardes.tape.site(.fonts, p.scratch.allocator(), fontNamed, .{ p.scratch.allocator(), spec.name });
+ const found = p.tape.site(.fonts, p.scratch.allocator(), fontNamed, .{ p.scratch.allocator(), spec.name });
const nul = std.mem.indexOfScalar(u8, found, 0) orelse return;
if (!p.settings.requestFont(found[0..nul], found[nul + 1 ..], spec.size_hundredths)) return;
p.font_request_taken = false;
@@ -1035,7 +1035,7 @@ pub fn applySettingBuiltin(p: *Pardes, setting: config.Settings.Setting, arg: ?[
return p.setMessage(.at(v.active), said.print("Shell: the default again, {s} ($SHELL, else /bin/sh)", .{p.sessionShell()[0..@min(p.sessionShell().len, 256)]}));
}
var why: [320]u8 = undefined;
- if (pardes.tape.site(.shell, null, @import("dev").host_io.Shell.refusal, .{ want[0..@min(want.len, 200)], &why })) |refused| {
+ if (p.tape.site(.shell, null, @import("dev").host_io.Shell.refusal, .{ want[0..@min(want.len, 200)], &why })) |refused| {
var text: pardes.Kind.Buf(340) = .{};
return p.reportFailure(v.active, text.print("Shell: {s}", .{refused}));
}
diff --git a/core/fs.zig b/core/fs.zig
index 0797beb0..6e5829e1 100644
--- a/core/fs.zig
+++ b/core/fs.zig
@@ -163,7 +163,6 @@ fn osNode(p: *pardes.Pardes, path: []const u8) !u64 {
/// outlives the yield, and nothing is staged into the shared reply buffer
/// until the turn is back.
pub fn osHandle(p: *pardes.Pardes, req: Req) Reply {
- if (comptime !platform_has_fs) return Reply.fail(req.tag, E.NOENT);
const path = osPath(p, req.node) orelse return Reply.fail(req.tag, E.NOENT);
if (req.op == .release) return .{ .tag = req.tag };
const stat = p.tape.site(.os_stat, null, osStat, .{path}) catch return Reply.fail(req.tag, E.NOENT);
@@ -307,7 +306,6 @@ pub fn statPath(io: std.Io, path: []const u8, options: std.Io.Dir.StatFileOption
/// does: one already there is no failure. A failure shows at the open
/// that follows.
pub fn makeDirs(tape: *pardes.tape.Tape, dir: []const u8) void {
- if (comptime !platform_has_fs) return;
if (dir.len == 0) return;
tape.site(.make_dirs, null, makeDirsHost, .{dir});
}
@@ -320,7 +318,6 @@ fn makeDirsHost(io: std.Io, dir: []const u8) void {
/// nearest ancestor that is there may not be searched or written (EACCES:
/// `noperm/a/b`, `/proc/1/root/x`).
pub fn deniedAbove(dir: []const u8) bool {
- if (comptime !platform_has_fs) return false;
var at: ?[]const u8 = dir;
while (at) |d| : (at = std.Io.Dir.path.dirname(d)) {
var z: [4096]u8 = undefined;
@@ -443,7 +440,6 @@ fn userHome(name: []const u8) ?[]const u8 {
}
pub fn resolveOs(tape: *pardes.tape.Tape, path: []const u8, out: *[4096]u8) ?Resolved {
- if (comptime !platform_has_fs) return null;
var z: [4096]u8 = undefined;
const path_z = std.fmt.bufPrintSentinel(&z, "{s}", .{path}, 0) catch return null;
return tape.site(.resolve, null, resolveHost, .{ path_z, out });
@@ -676,8 +672,6 @@ fn findEmbeddedSource(path: []const u8, allow_root_suffix: bool) ?Source {
return null;
}
-pub const platform_has_fs = !pardes.isolated;
-
fn isDir(path: [*:0]const u8) bool {
const fd = libc.open(path, .{ .ACCMODE = .RDONLY, .DIRECTORY = true, .CLOEXEC = true });
if (fd < 0) return false;
@@ -719,8 +713,8 @@ pub fn restorePath(tape: *pardes.tape.Tape, typed: []const u8, dir_setting: []co
fn readFileLimit(tape: *pardes.tape.Tape, gpa: std.mem.Allocator, path: []const u8, limit: usize) ![]u8 {
if (std.mem.indexOfScalar(u8, path, 0) != null) return error.OpenFailed;
- if (!platform_has_fs or std.mem.startsWith(u8, path, "/virtual/")) {
- const archive_path = if (std.mem.startsWith(u8, path, "/virtual/")) path[9..] else path;
+ if (std.mem.startsWith(u8, path, "/virtual/")) {
+ const archive_path = path[9..];
var normalized_buf: [4096]u8 = undefined;
const normalized = normalizeVirtualPath(archive_path, &normalized_buf) orelse return error.OpenFailed;
const source = findEmbeddedSource(normalized, true) orelse return error.OpenFailed;
@@ -1215,7 +1209,6 @@ test "self files share the regular file limit without preallocating it" {
}
test "bounded reads accept exact OS file lengths and empty files" {
- if (!platform_has_fs) return error.SkipZigTest;
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true });
defer p.deinit();
@@ -1327,7 +1320,7 @@ test "bounded reads release terminal snapshots after success and size refusal" {
}
test "bounded reads probe size-unknown proc files at the exact limit" {
- if (!platform_has_fs or @import("builtin").os.tag != .linux) return error.SkipZigTest;
+ if (@import("builtin").os.tag != .linux) return error.SkipZigTest;
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true });
defer p.deinit();
@@ -1379,7 +1372,6 @@ test "self file reads release partial allocations when memory runs out" {
}
test "oversized OS files fail before allocating their contents" {
- if (!platform_has_fs) return error.SkipZigTest;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
const file = try tmp.dir.createFile(std.testing.io, "oversized", .{});
@@ -1481,7 +1473,6 @@ test "a leading ~ is home, from HOME or else the passwd entry" {
}
test "Restore prefers default directory then falls back to original path" {
- if (!platform_has_fs) return error.SkipZigTest;
const gpa = std.testing.allocator;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
diff --git a/core/grammar_manifest.zig b/core/grammar_manifest.zig
index 711c31a4..b4ff30b9 100644
--- a/core/grammar_manifest.zig
+++ b/core/grammar_manifest.zig
@@ -5,7 +5,7 @@
const std = @import("std");
-pub const Tier = enum { zig, minimal, full };
+pub const Tier = enum { minimal, full };
pub const Grammar = struct {
name: []const u8,
@@ -58,7 +58,7 @@ pub const all = [_]Grammar{
\\"#" @keyword
\\
},
- .{ .name = "zig", .dep = "ts_zig", .exts = &.{ ".zig", ".zon" }, .tier = .zig },
+ .{ .name = "zig", .dep = "ts_zig", .exts = &.{ ".zig", ".zon" }, .tier = .minimal },
};
/// The names a language goes by besides its grammar's: a fence's `py`,
diff --git a/core/keys.zig b/core/keys.zig
index 72e3bb3b..8bfe8315 100644
--- a/core/keys.zig
+++ b/core/keys.zig
@@ -717,6 +717,9 @@ test "the Del question shows only once its delay is up: a quick SPC d j never se
p.update(.{ .key = .{ .cp = 'd' } });
const pane = p.panes[mid].?;
try std.testing.expectEqual(Pane.Prompt.del_side, pane.prompt);
+ // Its time is the next advance's (the host's clock, in its pump).
+ try std.testing.expectEqual(Pane.question_asked, pane.question_due_ns);
+ p.advance(asked_at);
try std.testing.expectEqual(asked_at + config.del_question_delay_ns, pane.question_due_ns);
// Asked, and nothing on the band yet.
_ = try p.render(frame.allocator());
diff --git a/core/lib_syntax.zig b/core/lib_syntax.zig
index a25af884..f4f85820 100644
--- a/core/lib_syntax.zig
+++ b/core/lib_syntax.zig
@@ -4,7 +4,7 @@
//! coloured as pardes has it. Nothing is copied here: these are the editor's
//! own grammars and highlighting (syntax.zig), themes (colors.zig) and line
//! arithmetic (modal.zig), under the names they have there. Whatever is
-//! named here compiles with tree-sitter and the grammars alone; test/lib
+//! named here compiles with tree-sitter and the grammars alone; test/consumer
//! imports it as such a package and holds it to that.
//!
//! A language is told by a path's extension, as in the editor; `pathFor`
@@ -15,7 +15,7 @@ const colors = @import("colors.zig");
const modal = @import("modal.zig");
/// Every grammar pardes knows (`all`), by name or alias (`byName`) and by
-/// path (`byPath`). The build's `tree-sitter` option says which of them are
+/// path (`byPath`). The build's `grammars` option says which of them are
/// compiled in, and `supportsPath` answers for this build.
pub const grammars = @import("grammar_manifest.zig");
pub const supportsPath = syntax.supportsPath;
diff --git a/core/look.zig b/core/look.zig
index 1023a532..1d296775 100644
--- a/core/look.zig
+++ b/core/look.zig
@@ -7,7 +7,6 @@ const exec = @import("exec.zig");
const Plumb = @import("Plumb.zig");
const config = @import("config.zig");
const diff = @import("diff.zig");
-const platform_has_fs = filesystem.platform_has_fs;
const layout = @import("layout.zig");
const modal = @import("modal.zig");
const tagline = @import("tagline.zig");
@@ -1758,7 +1757,6 @@ test "parsePathLine: `end` separates a whole-token target from a lenient read" {
}
test "lookableSpan peels prose punctuation off a path, largest first" {
- if (!platform_has_fs) return;
var realbuf: [4096]u8 = undefined;
try std.testing.expectEqualDeep(
@as(?Span, .{ .start = 0, .end = "core/look.zig".len }),
@@ -1782,7 +1780,6 @@ test "lookableSpan peels prose punctuation off a path, largest first" {
}
test "lookableLineSpan takes the row's location and stops before its text" {
- if (!platform_has_fs) return;
var realbuf: [4096]u8 = undefined;
try std.testing.expectEqualDeep(
@as(?Span, .{ .start = 0, .end = "core/look.zig:12:5-9".len }),
@@ -1813,7 +1810,6 @@ test "lookableLineSpan takes the row's location and stops before its text" {
}
test "lookableLineSpan prefers the longest run, so a blank inside a path is one span" {
- if (!platform_has_fs) return;
var realbuf: [4096]u8 = undefined;
const io = std.testing.io;
var tmp = std.testing.tmpDir(.{});
@@ -2054,7 +2050,6 @@ test "a pointer resting where a look-hover found nothing does not wake the core
}
test "Look on each kind of diff line opens the new file at the line it names" {
- if (!platform_has_fs) return;
const numbered = "line 1\nline 2\nline 3\nline 4\nline 5\nline 6\nline 7\nline 8\nline 9\n" ++
"line 10\nline 11\nline 12\nline 13\nline 14\nline 15\n";
const diff_text =
@@ -2116,7 +2111,6 @@ test "Look on each kind of diff line opens the new file at the line it names" {
}
test "Look on plain diff -u output: names as written, timestamps cut, next to the diff" {
- if (!platform_has_fs) return;
const diff_text = "--- old/x.zig\t2026-09-30 10:00:00.000000000 +0000\n" ++
"+++ new/x.zig\t2026-09-30 11:00:00.000000000 +0000\n" ++
"@@ -1,2 +1,3 @@\n" ++
@@ -2136,7 +2130,6 @@ test "Look on plain diff -u output: names as written, timestamps cut, next to th
}
test "Look on a diff: headers and a hunk line's prefix are the whole line, hover and click alike" {
- if (!platform_has_fs) return;
const numbered = "one\ntwo\nthree\nfour\nfive\nsix\n";
const diff_text =
\\diff --git a/src/old.zig b/src/new.zig
@@ -2223,7 +2216,6 @@ test "Look on a diff: headers and a hunk line's prefix are the whole line, hover
}
test "a click, a 9P whole-line look and an empty event write-back take one expansion on every kind of diff line, a blank context line too" {
- if (!platform_has_fs) return;
const diff_text =
\\diff --git a/src/new.zig b/src/new.zig
\\--- a/src/new.zig
@@ -2286,7 +2278,6 @@ test "a click, a 9P whole-line look and an empty event write-back take one expan
}
test "every entry point to Look takes one expansion: a diff line and a file:12:5: line land in one place by each" {
- if (!platform_has_fs) return;
const numbered = "l1\nl2\nl3\nl4\nl5\nl6\nl7\nl8\nl9\nl10\nl11\nline 12 here\nl13\n";
const diff_text =
\\diff --git a/src/x.zig b/src/x.zig
@@ -2378,7 +2369,6 @@ test "every entry point to Look takes one expansion: a diff line and a file:12:5
}
test "a tag word looked at by a click and by Enter is one record to an event reader; an exec on a diff line takes its word, never the address" {
- if (!platform_has_fs) return;
const diff_text =
\\diff --git a/src/x.zig b/src/x.zig
\\--- a/src/x.zig
@@ -2449,7 +2439,6 @@ test "a tag word looked at by a click and by Enter is one record to an event rea
}
test "Incl's directories find a name found nowhere else, <name> too; bare Incl lists them, Incl - empties them, and a dump keeps them" {
- if (!platform_has_fs) return;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
try tmp.dir.createDirPath(std.testing.io, "inc");
@@ -2489,7 +2478,6 @@ test "Incl's directories find a name found nowhere else, <name> too; bare Incl l
test "LookNext in a command pane walks its own file:line places, whoever walked last" {
if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane
- if (!platform_has_fs) return;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "x.c", .data = "a\nb\nc\n" });
@@ -2546,7 +2534,6 @@ test "Look outside a diff pane expands and looks as ever" {
}
test "Look on a diff under each git prefix opens the repository's file, and a real a/ directory under --no-prefix" {
- if (!platform_has_fs) return;
const Case = struct { text: []const u8, file: []const u8 };
const cases = [_]Case{
.{ .text = "diff --git a/src/x.zig b/src/x.zig\n--- a/src/x.zig\n+++ b/src/x.zig\n@@ -1,2 +1,2 @@\n-one\n+uno\n two\n", .file = "/src/x.zig" },
@@ -2573,7 +2560,6 @@ test "Look on a diff under each git prefix opens the repository's file, and a re
}
test "Look on a diff line is the look of the address it names, selected by hand: a cached patch, the checkout elsewhere" {
- if (!platform_has_fs) return;
const io = std.testing.io;
const patch = "diff --git a/entry/src/entry.rs b/entry/src/entry.rs\n--- a/entry/src/entry.rs\n+++ b/entry/src/entry.rs\n" ++
"@@ -1,2 +1,2 @@\n-fn old() {}\n+fn new() {}\n fn kept() {}\n";
@@ -2635,7 +2621,6 @@ test "Look on a diff line is the look of the address it names, selected by hand:
}
test "Plumb: a look sends what it looks at, the rules written first: a rule's word or port takes it, a name open in a pane is focused unsent, one nothing takes is Look's own" {
- if (!platform_has_fs) return;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "pic.svg", .data = "<svg/>" });
@@ -2687,7 +2672,6 @@ test "Plumb: a look sends what it looks at, the rules written first: a rule's wo
test "Plumb: a commit hash looked at in a git work tree is git show's, paged; outside one Diff declines, and the word is searched for" {
if (pardes.Term.ops == null) return error.SkipZigTest; // a command pane
- if (!platform_has_fs) return;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
try tmp.dir.createDir(std.testing.io, ".git", .default_dir);
diff --git a/core/mouse.zig b/core/mouse.zig
index 1882b691..465d8a01 100644
--- a/core/mouse.zig
+++ b/core/mouse.zig
@@ -1819,7 +1819,6 @@ test "a press on a notice's chip is the same state whichever frame this process
// The same through a body hit (edit.pointerTextSelection, a sweep's drag),
// on a compact body layer (TreeContext), which a pixel shell inverts.
test "a body press, drag and release are the same state whichever frame this process drew last" {
- if (comptime !pardes.syntax.enabled) return error.SkipZigTest;
const gpa = std.testing.allocator;
const a = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 });
defer a.deinit();
diff --git a/core/ninep/pty.zig b/core/ninep/pty.zig
index 26bb7661..4b0cee66 100644
--- a/core/ninep/pty.zig
+++ b/core/ninep/pty.zig
@@ -66,7 +66,7 @@ pub fn writeCtl(p: *Pardes, req: Req, id: usize) Reply {
// interpreter is not: refused, and the running shell kept.
const bin = pane.shell orelse p.shellBin();
var why: [320]u8 = undefined;
- if (pardes.tape.site(.shell, null, @import("dev").host_io.Shell.refusal, .{ bin[0..@min(bin.len, 200)], &why })) |refused|
+ if (p.tape.site(.shell, null, @import("dev").host_io.Shell.refusal, .{ bin[0..@min(bin.len, 200)], &why })) |refused|
return tree.failText(req.tag, E.NOENT, std.fmt.bufPrint(&p.fs.ename, "exec: {s}", .{refused[0..@min(refused.len, 300)]}) catch &p.fs.ename); // cut to ename's 320
};
if (verb(p, id, line, apply)) |why| return tree.failText(req.tag, E.INVAL, why);
@@ -220,7 +220,7 @@ pub fn writeRun(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply {
for (line) |c| if (c < ' ' and c != '\t') return tree.failText(req.tag, E.INVAL, e_bad_line);
const pf = &pane.fs;
if (pane.terminal == null) return tree.failText(req.tag, E.INVAL, e_bad_line);
- const marks = pardes.Term.prompt(pane.terminal);
+ const marks = marksOf(pane);
if (pane.shell_failed) {
// Its shell never started: no prompt is coming to wait for.
answer(p, slot, "error shell gone", .{});
@@ -288,7 +288,7 @@ pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void {
if (pane.terminal == null) return;
const pf = &pane.fs;
const slot = waitingRun(p, pane) orelse return;
- const marks = pardes.Term.prompt(pane.terminal);
+ const marks = marksOf(pane);
if (slot.phase == .waiting) {
if (pf.unmarked) {
answer(p, slot, "error no prompt marks", .{});
@@ -305,7 +305,7 @@ pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void {
if (pardes.Term.modes(pane.terminal).alternate) pane.feedOutput(p, "\x1b[?1049l");
p.emitWrite(id, slot.line);
p.emitWrite(id, "\r");
- pane.noteCommand(slot.line);
+ pane.noteCommand(slot.line, marks.started);
// The run is the shell's first command: a greeting `ls` typed at the
// same prompt would run after it, and its C would be taken for ours.
pane.greet = false;
@@ -360,6 +360,14 @@ pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void {
finish(p, slot, pane, done.status);
}
+/// The shell's marks as the session's emulator has them (taped), as a
+/// run's step reads them: a screen-state replica's emulator is the last
+/// delta's, which comes at a frame and can be a unit behind the one it
+/// replays.
+fn marksOf(pane: *const Pane) pardes.Term.Prompt {
+ return pardes.tape.value(.prompt, pardes.Term.prompt, .{pane.terminal});
+}
+
/// Answers a run whose command ended with `status`: the header and the
/// output it printed.
fn finish(p: *Pardes, slot: *Run, pane: *Pane, status_code: ?i32) void {
diff --git a/core/ninep/tree.zig b/core/ninep/tree.zig
index 46a4e3d2..1eaaa8cb 100644
--- a/core/ninep/tree.zig
+++ b/core/ninep/tree.zig
@@ -928,9 +928,11 @@ fn open(p: *Pardes, req: Req, target: Target) Reply {
};
},
};
- const i = for (p.fs.opens, 0..) |o, i| {
- if (o.node == 0) break i;
- } else return Reply.fail(req.tag, E.NFILE);
+ // The handle every later request of this open names: the session's 9P
+ // server's, told to a replica as the answer it was. A client joined
+ // since holds none of the opens made before it, and its first free
+ // record would be another than the session's.
+ const i = p.tape.authority(freeOpen, .{p}) orelse return Reply.fail(req.tag, E.NFILE);
const o = &p.fs.opens[i];
o.* = .{ .node = req.node, .what = what };
if (resultsFile(target)) {
@@ -969,6 +971,13 @@ fn open(p: *Pardes, req: Req, target: Target) Reply {
return .{ .tag = req.tag, .handle = @intCast(i + 1) };
}
+/// The first open record free.
+fn freeOpen(p: *Pardes) ?u64 {
+ return for (p.fs.opens, 0..) |o, i| {
+ if (o.node == 0) break i;
+ } else null;
+}
+
/// Tremove closes a pane. Nothing else in the tree can be removed, and this
/// is also where an ORCLOSE open lands, so every node is checked here.
fn remove(p: *Pardes, req: Req) Reply {
diff --git a/core/panes.zig b/core/panes.zig
index fd152e1e..1c103bd1 100644
--- a/core/panes.zig
+++ b/core/panes.zig
@@ -53,6 +53,10 @@ pub const Pane = struct {
return @backingInt(id);
}
};
+ /// Del's question asked, its time not had yet: the step that asks
+ /// reads no clock (a far client's would wait on the session's), and
+ /// core time is the last frame's, seconds old in an idle session.
+ pub const question_asked: u64 = std.math.maxInt(u64);
/// The words that throw unsaved text away (builtins.zig warnModified).
pub const Discarding = enum { Exit, Restore, get, Del, Delcol };
@@ -218,7 +222,9 @@ pub const Pane = struct {
repl_enter: u8 = 0,
repl_enter_due_ns: u64 = 0,
/// When Del's question (`del_side`) goes up on the notice band, on the
- /// shell's clock (config.del_question_delay_ns after it was asked).
+ /// shell's clock (config.del_question_delay_ns after it was asked):
+ /// `question_asked` until the next advance, which counts the delay
+ /// from its own time (Core.advance).
question_due_ns: u64 = 0,
/// A question with its answers in it (`repl_choice`).
question: [96]u8 = undefined,
@@ -715,7 +721,7 @@ pub const Pane = struct {
pub fn feedOutput(pane: *Pane, p: *Pardes, bytes: []const u8) void {
// There are no pty reads at all without an emulator to parse them into.
const state = pane.terminal orelse return;
- if (tape.authorityOnly("a terminal's output")) return;
+ if (p.tape.authorityOnly("a terminal's output")) return;
const has_positions = pane.ovl != null or pane.body.cur_pinned or pane.body.vsel.active or
pane.body.nsel > 0 or pane.body.last_edit != null or pane.look_at != null or
pane.body.ed_undo_len > 0 or pane.body.ed_redo_len > 0 or pane.pointerRowCount() > 0;
@@ -1026,11 +1032,11 @@ pub const Pane = struct {
/// started, for Kill: it runs from the shell's next C mark to its D.
/// ponytail: of several lines queued for a shell not up yet, only the
/// last is remembered, as the first of them.
- pub fn noteCommand(pane: *Pane, line: []const u8) void {
- const state = pane.terminal orelse return;
+ pub fn noteCommand(pane: *Pane, line: []const u8, started: u32) void {
+ if (pane.terminal == null) return;
const said = std.mem.trim(u8, line, " \t");
const word = said[0 .. std.mem.indexOfAny(u8, said, " \t") orelse said.len];
- var sent: @typeInfo(@FieldType(Pane, "sent_command")).optional.child = .{ .seq = Term.prompt(state).started +% 1 };
+ var sent: @typeInfo(@FieldType(Pane, "sent_command")).optional.child = .{ .seq = started +% 1 };
sent.len = @intCast(@min(word.len, sent.word.len));
@memcpy(sent.word[0..sent.len], word[0..sent.len]);
pane.sent_command = sent;
@@ -1166,7 +1172,6 @@ pub fn createDoc(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane {
/// A terminal pane: a pane and its emulator. Slot ownership, serial
/// assignment and spawn effects remain core lifecycle invariants.
pub fn createTerminal(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane {
- if (tape.authorityOnly("open a terminal")) return error.OutOfMemory;
const pane = try createDoc(gpa, cols, rows);
errdefer gpa.destroy(pane);
pane.terminal = try Term.open(emulatorGpa(gpa), cols, rows);
@@ -1230,7 +1235,7 @@ pub fn retirePane(p: *Pardes, pane: *Pane) void {
if (pane.isTerminal()) p.emit(.{ .close_pty = .{ .pane = .at(id) } });
// Its pty's end and its emulator are the authority's: a replica's
// speculation that closes a terminal waits for it.
- if (pane.terminal != null) tape.poison("close a terminal");
+ if (pane.terminal != null) p.tape.poison("close a terminal");
ctlfs.events.noteRetire(p, pane);
// ...and so do bytes still queued for the pty it no longer has.
p.dropPendingWrite(id);
@@ -1271,7 +1276,7 @@ pub fn teardownPane(p: *Pardes, pane: *Pane) void {
}
// A pane with none (a file's, a picker's, a preview's) closes in a
// speculation as anywhere.
- if (pane.terminal) |state| if (!tape.authorityOnly("close a terminal")) {
+ if (pane.terminal) |state| if (!p.tape.authorityOnly("close a terminal")) {
Term.close(state, p.gpa);
pane.terminal = null;
};
@@ -1307,6 +1312,8 @@ pub fn installPane(p: *Pardes, id: usize, pane: *Pane) void {
pub fn newShell(p: *Pardes, id: usize, cwd: []const u8) !*Pane {
std.debug.assert(p.panes[id] == null);
if (cwd.len > limits.host_path_cap) return error.PathTooLong;
+ // A speculation opens no emulator: a terminal is the authority's to open.
+ if (p.tape.authorityOnly("open a terminal")) return error.OutOfMemory;
const pane = try panes.createTerminal(p.gpa, p.view().screen_w, p.view().screen_h);
// Named by the directory it is started in from the first, so the
// shell saying it is there is no rename (`new N /` then `rename`);
@@ -1339,6 +1346,7 @@ pub fn newCommand(p: *Pardes, id: usize, cwd: []const u8, line: []const u8) !*Pa
if (cwd.len > limits.host_path_cap) return error.PathTooLong;
const owned = try p.gpa.dupe(u8, line);
errdefer p.gpa.free(owned);
+ if (p.tape.authorityOnly("open a terminal")) return error.OutOfMemory;
const pane = try panes.createTerminal(p.gpa, p.view().screen_w, p.view().screen_h);
pane.command = owned;
pane.command_pty = true;
diff --git a/core/replica.zig b/core/replica.zig
index 14757d9a..781bd211 100644
--- a/core/replica.zig
+++ b/core/replica.zig
@@ -1887,6 +1887,16 @@ pub const Peer = struct {
peer.cond.signal(io);
}
+ /// Its last message: queued, and its writer ends once it is written.
+ fn last(peer: *Peer, words: []const u8) void {
+ const io = peer.peers.io;
+ peer.send(&.{words});
+ peer.lock.lockUncancelable(io);
+ peer.closing = true;
+ peer.cond.signal(io);
+ peer.lock.unlock(io);
+ }
+
fn writeLoop(peer: *Peer) void {
const io = peer.peers.io;
defer peer.done.store(true, .release);
@@ -2230,7 +2240,10 @@ pub const Peers = struct {
}
}
- fn join(ps: *Peers, core: *Pardes, joining: Joining) void {
+ /// A client on `joining.fd` joined: a dump of the session now, its
+ /// threads started. At a step boundary (`boundary`), or a session's
+ /// first client before its first effects (runtime/session.zig).
+ pub fn join(ps: *Peers, core: *Pardes, joining: Joining) void {
const fd = joining.fd;
const t0 = nowNs();
defer {
@@ -2401,14 +2414,14 @@ pub const Peers = struct {
if (ps.count() == 0) return;
var out: [600]u8 = undefined;
const words = wire.encodeServer(&out, .{ .refused = why }) catch return;
- const io = ps.io;
- for (ps.list) |slot| if (slot) |peer| {
- peer.send(&.{words});
- peer.lock.lockUncancelable(io);
- peer.closing = true;
- peer.cond.signal(io);
- peer.lock.unlock(io);
- };
+ for (ps.list) |slot| if (slot) |peer| peer.last(words);
+ ps.flushed200();
+ // Each joins again for its view, kept in the dump (views.away).
+ ps.drop(core, true);
+ }
+
+ /// What each client was sent goes first, for up to 200 ms.
+ fn flushed200(ps: *Peers) void {
const until = nowNs() + 200 * std.time.ns_per_ms;
while (nowNs() < until) {
const busy = for (ps.list) |slot| {
@@ -2418,8 +2431,6 @@ pub const Peers = struct {
const ts: libc.timespec = .{ .sec = 0, .nsec = 2 * std.time.ns_per_ms };
_ = libc.nanosleep(&ts, null);
}
- // Each joins again for its view, kept in the dump (views.away).
- ps.drop(core, true);
}
/// A join's dump and pins let go: written, or its client gone.
@@ -2442,21 +2453,30 @@ pub const Peers = struct {
daemon.clients(pids[0..n]);
}
- /// Detach typed in client view `k`'s: its link ends (its reader says
- /// it is gone, and the next boundary lets it go).
+ /// Detach typed in client view `k`'s: told it left the session running
+ /// (`left`), its last word; the client goes, and its reader says so.
pub fn detach(ps: *Peers, k: u8) bool {
for (ps.list) |slot| if (slot) |peer| if (peer.view == k) {
- _ = libc.shutdown(peer.fd, 2);
+ var out: [wire.max_name + 8]u8 = undefined;
+ peer.last(wire.encodeServer(&out, .{ .left = ps.name[0..@min(ps.name.len, wire.max_name)] }) catch unreachable);
return true;
};
return false;
}
+ /// The session ends with `code`: every client told so (`ended`), its
+ /// last word, before the links are let go (`dropAll`).
+ pub fn ended(ps: *Peers, code: u8) void {
+ var out: [16]u8 = undefined;
+ const words = wire.encodeServer(&out, .{ .ended = code }) catch unreachable;
+ for (ps.list) |slot| if (slot) |peer| peer.last(words);
+ ps.flushed200();
+ }
+
fn stop(ps: *Peers, core: *Pardes) void {
if (!ps.recording) return;
pardes.panes.resizeDeferred(core);
ps.screens.deinit(core);
- if (core.host.vtable == &ps.t.vtable) core.host = ps.t.real;
tape.on = null;
core.tape = core.opts.tape orelse &tape.none;
tape.release(&ps.t);
@@ -2576,13 +2596,14 @@ pub fn dial(gpa: Allocator, path: []const u8, session: []const u8, why: []u8, ha
}
/// `dial`'s, on a connection made: the hello, then the join. The
-/// connection is closed if the join fails.
-fn joinOn(gpa: Allocator, fd: c_int, session: []const u8, why: []u8, have: ?*Have, view: ?u8) ?Joined {
+/// connection is closed if the join fails. No session named: no hello, a
+/// pair's (Options.pair), whose session took it as its first client.
+fn joinOn(gpa: Allocator, fd: c_int, session: ?[]const u8, why: []u8, have: ?*Have, view: ?u8) ?Joined {
var out: [wire.hello_max + 16]u8 = undefined;
- const hello = wire.encodeClient(&out, .{ .hello = .{ .session = session, .view = view } }) catch {
+ const hello = if (session) |name| wire.encodeClient(&out, .{ .hello = .{ .session = name, .view = view } }) catch {
_ = libc.close(fd);
return said(why, "that session's name is too long", .{});
- };
+ } else out[0..0];
// Its first word, in the same write: whether it is far.
const far = wire.encodeClient(out[hello.len..], .{ .far = have != null }) catch unreachable;
var j: Joined = .{ .fd = fd, .pid = 0, .client = 0, .view = 0, .gmtoff = 0, .dump = &.{} };
@@ -2915,7 +2936,7 @@ pub fn bye(fd: c_int, again: bool) void {
/// What the session streams a client after its dump, as its frontend's loop
/// takes it: a unit's and a terminal message's bytes and a refusal's words
/// on the C heap, the loop's to free.
-pub const Said = union(enum) { unit: []u8, screen: []u8, checked: u64, refused: []u8, blob: []u8 };
+pub const Said = union(enum) { unit: []u8, screen: []u8, checked: u64, refused: []u8, blob: []u8, ended: u8, left };
/// The session's stream off `fd`, each message handed to `post` until the
/// link ends (a refusal ends it too); `post` says whether it took it (one
@@ -2930,13 +2951,16 @@ pub fn readLink(gpa: Allocator, fd: c_int, rest: *Framer, ctx: anytype, comptime
.blob => .{ .blob = std.heap.c_allocator.dupe(u8, payload) catch return false },
.check => .{ .checked = (wire.decodeServer(tag, payload) catch return false).check },
.refused => .{ .refused = std.heap.c_allocator.dupe(u8, (wire.decodeServer(tag, payload) catch return false).refused) catch return false },
+ .ended => .{ .ended = (wire.decodeServer(tag, payload) catch return false).ended },
+ .left => .left,
.pong, .welcome, .dump, .blobs, .zstd => return true,
};
if (!post(x, msg)) switch (msg) {
.unit, .screen, .refused, .blob => |b| std.heap.c_allocator.free(b),
- .checked => {},
+ .checked, .ended, .left => {},
};
- return msg != .refused;
+ // A last word ends the stream.
+ return msg == .unit or msg == .screen or msg == .checked or msg == .blob;
}
};
rest.run(gpa, fd, ctx, Take.take);
@@ -2946,11 +2970,23 @@ pub fn readLink(gpa: Allocator, fd: c_int, rest: *Framer, ctx: anytype, comptime
if (!post(ctx, .{ .refused = words })) std.heap.c_allocator.free(words);
}
+/// A join's failure that is its session's end, whenever it came (the
+/// session or its daemon gone, or hung up before the dump was whole): a
+/// client joining again then goes as at a hang-up (`.gone`), in the same
+/// words, never as a join that failed.
+pub fn ended(why: []const u8) bool {
+ const words = std.mem.sliceTo(why, 0);
+ for ([_][]const u8{ "the session hung up", "nothing answers at ", "no session called " }) |w|
+ if (std.mem.startsWith(u8, words, w)) return true;
+ return false;
+}
+
/// The words a client goes with when its session runs another build now.
const upgrade_words = "session upgraded to a newer pardes: upgrade this client too";
/// A replica client's join, the terminal's and the window's alike (their
-/// `runClient`): the session at `path` dialled, its build checked to be this
+/// `runClient`): the session at `path` dialled (or, first, the one on its
+/// pair, `o.pair`), its build checked to be this
/// one's, and its dump loaded into a replica checked against the session
/// as it was dumped. Or, `old` given, joined again once old's link has
/// ended, for old's view (`redial`): the core it leaves held meanwhile so
@@ -2963,6 +2999,7 @@ pub fn join(gpa: Allocator, j: *Joined, path: []const u8, session: []const u8, o
const t0 = nowNs();
if (old) |prev| {
j.* = redial(gpa, path, session, why, have, prev.diverged == null, j.view) orelse {
+ if (ended(why)) return null;
var words: [600]u8 = undefined;
const said_ = std.mem.sliceTo(why, 0);
@memcpy(words[0..said_.len], said_);
@@ -2971,7 +3008,7 @@ pub fn join(gpa: Allocator, j: *Joined, path: []const u8, session: []const u8, o
};
if (have) |h| h.left();
prev.deinit();
- } else j.* = sameBuild(gpa, dial(gpa, path, session, why, have, null) orelse return null, why) orelse return null;
+ } else j.* = sameBuild(gpa, (if (o.pair) |fd| joinOn(gpa, fd, null, why, have, null) else dial(gpa, path, session, why, have, null)) orelse return null, why) orelse return null;
defer {
if (have) |h| h.store(gpa, j) else gpa.free(j.dump);
j.dump = &.{};
@@ -3073,6 +3110,9 @@ pub const Link = struct {
visible: u32 = 0,
/// What the session said as it let this client go (the C heap's).
refused: ?[]u8 = null,
+ /// Its last word: it ended, with this code; or this client left it.
+ ended: ?u8 = null,
+ left: bool = false,
/// A line over its frame, until its next key (`notify`): why it joined
/// again. The client's own, never the session's core.
notice_buf: [240]u8 = undefined,
@@ -3191,6 +3231,14 @@ pub const Link = struct {
c.refused = words;
c.quit = true;
},
+ .ended => |code| {
+ c.ended = code;
+ c.quit = true;
+ },
+ .left => {
+ c.left = true;
+ c.quit = true;
+ },
}
if (c.r.diverged != null) c.quit = true;
}
@@ -3571,6 +3619,14 @@ test "a client joining again after a divergence is told at once that its session
const t0 = nowNs();
try std.testing.expect(redial(std.testing.allocator, "/nonexistent/pardes-replica.sock", "gone", &why, null, false, 1) == null);
try std.testing.expect(nowNs() - t0 < 100 * std.time.ns_per_ms);
+ try std.testing.expect(ended(&why));
+ // Its session ending as it joins: hung up before the dump was whole,
+ // its end too, said as the end it is.
+ var fds: [2]c_int = undefined;
+ try std.testing.expectEqual(0, libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM, 0, &fds));
+ _ = libc.close(fds[1]);
+ try std.testing.expect(joinOn(std.testing.allocator, fds[0], "gone", &why, null, 1) == null);
+ try std.testing.expect(ended(&why));
}
test "a replica's own keys apply at once, confirm on the fast path, and end at the authority's digest" {
@@ -4389,6 +4445,119 @@ test "bytes: a client joins from a dump with its terminals whole, and every side
try sameTerminals(b.a, late);
}
+test "a session's first client on the socket it starts with (Options.pair), joined there with no hello before the session's first effects: the boot shell's spawn and first bytes reach it and the digests agree" {
+ try firstOnPair(false);
+}
+
+test "bytes: a session's first client on its pair, taken before its first effects, has the boot shell's first bytes with no reload of them (the session's one at the join is of its emulator before any byte, the client's none); a client after them makes every side reload" {
+ try firstOnPair(true);
+}
+
+/// A session's first client on a socket pair (runtime/session.zig's, then
+/// the client's first join on its end), the session's first effects after:
+/// its boot shell spawned, its first bytes output; the client quiet and
+/// checked. Bytes: the client loaded as the soak's bytes clients are
+/// (`replica.join` loads the screen-state kind until the switch).
+fn firstOnPair(bytes: bool) !void {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
+ const gpa = std.testing.allocator;
+ const Spawns = struct {
+ fn spawn(ctx: ?*anyopaque, _: pardes.Pane.Id, _: []const u8) void {
+ const n: *u32 = @ptrCast(@alignCast(ctx.?));
+ n.* += 1;
+ }
+ const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .spawn = spawn };
+ };
+ var spawns: u32 = 0;
+ var fds: [2]c_int = undefined;
+ if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket;
+ const opts: pardes.Options = .{ .cols = 80, .rows = 24, .boot = .tty };
+ const core = try Pardes.init(gpa, opts);
+ defer core.deinit();
+ core.host = .{ .ctx = &spawns, .vtable = &Spawns.vtable };
+ var ps: Peers = .{ .gpa = gpa, .io = std.testing.io, .name = "pair", .bytes = bytes, .detached = true };
+ defer ps.deinit();
+ defer live_peers = null;
+ defer ps.dropAll(core);
+ const reloads = pardes.Term.reloads.n;
+ ps.join(core, .{ .fd = fds[0] });
+ var j: Joined = undefined;
+ var why: [600]u8 = @splat(0);
+ const r = if (bytes) r: {
+ j = joinOn(gpa, fds[1], null, &why, null, null) orelse return error.JoinFailed;
+ defer gpa.free(j.dump);
+ const r = try Replica.initDump(gpa, j.client, j.view, j.dump, opts);
+ r.t.screen_state = false;
+ r.core().echo = null;
+ break :r r;
+ } else r: {
+ var o = opts;
+ o.pair = fds[1];
+ break :r join(gpa, &j, "", "", o, null, &why, null) orelse {
+ std.debug.print("the join failed: {s}\n", .{std.mem.sliceTo(&why, 0)});
+ return error.JoinFailed;
+ };
+ };
+ defer r.deinit();
+ defer {
+ _ = libc.close(j.fd);
+ j.rest.deinit(gpa);
+ }
+ try std.testing.expect(r.loaded(j.digest));
+ // The first effects, the boot shell's spawn among them; its first bytes.
+ while (core.nextEffect()) |e| core.perform(e);
+ try std.testing.expectEqual(@as(u32, 1), spawns);
+ const shell: u8 = for (core.panes, 0..) |slot, id| {
+ if (slot) |pane| if (pane.isTerminal()) break @intCast(id);
+ } else return error.NoShell;
+ core.update(.{ .output = .{ .pane = .at(shell), .bytes = "first$ " } });
+ ps.boundary(core);
+ // Its check, answered after every unit and terminal message before it.
+ try std.testing.expect(askCheck(j.fd));
+ while (!ps.mail.load(.acquire)) std.Thread.yield() catch {};
+ ps.boundary(core);
+ const Take = struct {
+ r: *Replica,
+ fd: c_int,
+ digest: ?u64 = null,
+ fn take(t: *@This(), tag: u8, payload: []const u8) bool {
+ switch (std.enums.fromInt(wire.ServerTag, tag) orelse return false) {
+ .unit => t.r.confirm(payload),
+ .screen => if (t.r.screen(payload)) |reply| {
+ _ = sendScreen(t.fd, reply);
+ },
+ .check => {
+ t.digest = (wire.decodeServer(tag, payload) catch return false).check;
+ return false;
+ },
+ else => {},
+ }
+ return true;
+ }
+ };
+ var take: Take = .{ .r = r, .fd = j.fd };
+ j.rest.run(gpa, j.fd, &take, Take.take);
+ r.settle();
+ if (r.diverged) |w| std.debug.print("diverged: {s}\n", .{w});
+ try std.testing.expect(r.diverged == null);
+ try std.testing.expectEqual(take.digest.?, r.digest());
+ // Bytes: the session's reload at the join, of an emulator that held
+ // nothing yet (Pardes.init made it, the spawn is a first effect); the
+ // client loaded it from the dump and replayed every byte since.
+ try std.testing.expectEqual(reloads + @intFromBool(bytes), pardes.Term.reloads.n);
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ const rows = try pardes.Term.viewport(r.core().panes[shell].?.terminal.?, arena.allocator(), false);
+ try std.testing.expect(std.mem.indexOf(u8, rows[0], "first$") != null);
+ if (!bytes) return;
+ // One that comes after the shell's bytes: every side reloads.
+ var late: [2]c_int = undefined;
+ if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &late) != 0) return error.NoSocket;
+ defer _ = libc.close(late[1]);
+ ps.join(core, .{ .fd = late[0] });
+ try std.testing.expectEqual(reloads + 2, pardes.Term.reloads.n);
+}
+
test "bytes: a session's output past a unit's bound is cut into units under it, between two reads" {
if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
const gpa = std.testing.allocator;
@@ -5004,7 +5173,6 @@ test "a client joined from a dump moves through another view's pane as the sessi
}
test "a client joined from a dump makes a `/` query's rows as the session does, though only the session has drawn its owner" {
- if (comptime !pardes.syntax.enabled) return error.SkipZigTest;
const gpa = std.testing.allocator;
const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, TestHost.host(), false);
defer a.deinit();
@@ -6542,7 +6710,6 @@ test "a client joined from a dump makes a `/` query's rows as the session does,
}
}
};
- if (comptime !pardes.syntax.enabled) return error.SkipZigTest;
const gpa = std.testing.allocator;
const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, .{ .vtable = &WorkerSearch.vtable }, false);
defer a.deinit();
@@ -6703,3 +6870,206 @@ test "a far client's replay of a message its session's host stamped takes the se
try agrees(a, r);
try std.testing.expect(try shows(r.core(), "--:--:-- yanked x"));
}
+
+// A script's `pty/run` in a shell (ninep/pty.zig): the open, the line, the
+// marks that end it, its answer read and the open released, each a step of
+// the session's, with a client that joined from a dump taking every unit.
+test "a client joined from a dump takes a 9P pty/run in a shell as the session does: the line sent at the prompt, its end answered" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
+ const gpa = std.testing.allocator;
+ const RunHost = struct {
+ fn taken(_: ?*anyopaque, _: pardes.Pane.Id) bool {
+ return false;
+ }
+ fn write(_: ?*anyopaque, _: pardes.Pane.Id, _: []const u8) void {}
+ const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .tty_taken = taken, .pty_write = write };
+ };
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, .{ .vtable = &RunHost.vtable }, false);
+ defer a.deinit();
+ const r = try Replica.init(gpa, 1, try a.unit(0, 0), false);
+ defer r.deinit();
+ const shell: u8 = for (a.core.panes, 0..) |slot, id| {
+ if (slot) |pane| if (pane.isTerminal()) break @intCast(id);
+ } else return error.NoShell;
+ const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07";
+ a.output(.{ .output = .{ .pane = .at(shell), .bytes = prompt ++ "ls\r\n\x1b]133;C;aid=pardes\x07a b\r\n\x1b]133;D;0;aid=pardes\x07" ++ prompt } });
+ r.confirm((try a.pending()).?);
+ r.settle();
+ // A script's listing open, held across the join (a reader of /index).
+ {
+ const was = Stepping.begin(&a.t, null);
+ _ = a.core.serveFs(.{ .tag = 9, .op = .open, .node = @backingInt(pardes.ctlfs.TopFile.index) });
+ was.end();
+ a.seq += 1;
+ r.confirm(try a.unit(0, a.seq));
+ r.settle();
+ }
+ const joined = (try a.join(2, null)).?;
+ defer gpa.free(joined.dump);
+ r.confirm(joined.unit);
+ const late = try Replica.initDump(gpa, 2, joined.view, joined.dump, .{ .cols = 80, .rows = 24 });
+ defer late.deinit();
+ late.t.screen_state = false;
+ late.core().echo = null;
+ try std.testing.expectEqual(joined.digest, late.digest());
+ const node = pardes.ctlfs.Node.of(a.core.panes[shell].?.serial, .pty_run);
+ const Serve = struct {
+ fn serve(s: *Authority, rs: []const *Replica, req: pardes.ctlfs.Req) !pardes.ctlfs.Reply {
+ const was = Stepping.begin(&s.t, null);
+ const reply = s.core.serveFs(req);
+ s.core.pump(s.host) catch {};
+ was.end();
+ s.seq += 1;
+ const u = try s.unit(0, s.seq);
+ for (rs) |x| {
+ x.confirm(u);
+ x.settle();
+ }
+ return reply;
+ }
+ fn output(s: *Authority, rs: []const *Replica, pane: u8, bytes: []const u8) !void {
+ s.output(.{ .output = .{ .pane = .at(pane), .bytes = bytes } });
+ const u = (try s.pending()).?;
+ for (rs) |x| {
+ x.confirm(u);
+ x.settle();
+ }
+ }
+ };
+ const both = [_]*Replica{ r, late };
+ const h = (try Serve.serve(a, &both, .{ .tag = 1, .op = .open, .node = node, .omode = 2 })).handle;
+ _ = try Serve.serve(a, &both, .{ .tag = 2, .op = .write, .node = node, .handle = h, .data = "true\n" });
+ try Serve.output(a, &both, shell, "true\r\n\x1b]133;C;aid=pardes\x07\x1b]133;D;0;aid=pardes\x07" ++ prompt);
+ const answer = try Serve.serve(a, &both, .{ .tag = 3, .op = .read, .node = node, .handle = h, .size = 64 });
+ try std.testing.expectEqualStrings("exit 0\n", a.core.fsPayload(answer));
+ _ = try Serve.serve(a, &both, .{ .tag = 4, .op = .release, .node = node, .handle = h, .opened = true });
+ try Serve.output(a, &both, shell, "\x1b]133;A;cl=line;aid=pardes\x07");
+ try agrees(a, r);
+ try agrees(a, late);
+}
+
+// The same run with the terminals crossing as screen state (a session's
+// clients', until the switch to bytes): a replica's emulator is the
+// deltas', its marks not the session's.
+test "a client of screen-state terminals takes a 9P pty/run in a shell as the session does" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a shell
+ const gpa = std.testing.allocator;
+ const RunHost = struct {
+ fn taken(_: ?*anyopaque, _: pardes.Pane.Id) bool {
+ return false;
+ }
+ fn write(_: ?*anyopaque, _: pardes.Pane.Id, _: []const u8) void {}
+ const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .tty_taken = taken, .pty_write = write };
+ };
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, .{ .vtable = &RunHost.vtable }, true);
+ defer a.deinit();
+ var screens: Screens = .init(gpa);
+ defer screens.deinit(a.core);
+ const peer = try screens.addPeer();
+ const r = try Replica.init(gpa, 1, try a.unit(0, 0), true);
+ defer r.deinit();
+ const shell: u8 = for (a.core.panes, 0..) |slot, id| {
+ if (slot) |pane| if (pane.isTerminal()) break @intCast(id);
+ } else return error.NoShell;
+ const Step = struct {
+ var second: ?*Replica = null;
+ fn take(s: *Authority, sc: *Screens, p: u16, x: *Replica, u: []const u8) !void {
+ const gpa_ = std.testing.allocator;
+ const kept = try gpa_.dupe(u8, u);
+ defer gpa_.free(kept);
+ // The unit first, its screens at the frame after (Peers).
+ x.confirm(kept);
+ x.settle();
+ if (second) |y| {
+ y.confirm(kept);
+ y.settle();
+ }
+ try deliver(s, sc, p, x, .flush);
+ if (second) |y| try deliver(s, sc, p + 1, y, .flush);
+ }
+ fn serve(s: *Authority, sc: *Screens, p: u16, x: *Replica, req: pardes.ctlfs.Req) !pardes.ctlfs.Reply {
+ const was = Stepping.begin(&s.t, null);
+ const reply = s.core.serveFs(req);
+ s.core.pump(s.host) catch {};
+ was.end();
+ s.seq += 1;
+ try take(s, sc, p, x, try s.unit(0, s.seq));
+ return reply;
+ }
+ fn output(s: *Authority, sc: *Screens, p: u16, x: *Replica, pane: u8, bytes: []const u8) !void {
+ s.output(.{ .output = .{ .pane = .at(pane), .bytes = bytes } });
+ try take(s, sc, p, x, (try s.pending()).?);
+ }
+ };
+ const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07";
+ try Step.output(a, &screens, peer, r, shell, prompt ++ "ls\r\n\x1b]133;C;aid=pardes\x07a b\r\n\x1b]133;D;0;aid=pardes\x07" ++ prompt);
+ // A second client joins now, from the session's dump.
+ const joined = (try a.join(2, null)).?;
+ defer gpa.free(joined.dump);
+ try Step.take(a, &screens, peer, r, joined.unit);
+ const late = try Replica.initDump(gpa, 2, joined.view, joined.dump, .{ .cols = 80, .rows = 24 });
+ defer late.deinit();
+ const peer2 = try screens.addPeer();
+ try deliver(a, &screens, peer2, late, .flush);
+ Step.second = late;
+ defer Step.second = null;
+ const node = pardes.ctlfs.Node.of(a.core.panes[shell].?.serial, .pty_run);
+ for (0..2) |_| {
+ const h = (try Step.serve(a, &screens, peer, r, .{ .tag = 1, .op = .open, .node = node, .omode = 2 })).handle;
+ _ = try Step.serve(a, &screens, peer, r, .{ .tag = 2, .op = .write, .node = node, .handle = h, .data = "true\n" });
+ try Step.output(a, &screens, peer, r, shell, "true\r\n\x1b]133;C;aid=pardes\x07\x1b]133;D;0;aid=pardes\x07" ++ prompt);
+ const answer = try Step.serve(a, &screens, peer, r, .{ .tag = 3, .op = .read, .node = node, .handle = h, .size = 64 });
+ try std.testing.expectEqualStrings("exit 0\n", a.core.fsPayload(answer));
+ _ = try Step.serve(a, &screens, peer, r, .{ .tag = 4, .op = .release, .node = node, .handle = h, .opened = true });
+ }
+ try agrees(a, r);
+ try agrees(a, late);
+}
+
+// Del with a pane above and below asks which way the space goes, its
+// question shown once a delay is up (builtins.zig): its time was the
+// host's clock read in the step, an answering entry a speculation stops at.
+test "a far client's Del with panes above and below is applied at once, and its question's time is the session's" {
+ const gpa = std.testing.allocator;
+ const Clocked = struct {
+ var now_ns: u64 = 7 * std.time.ns_per_s;
+ fn now(_: ?*anyopaque) u64 {
+ return now_ns;
+ }
+ const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .now = now };
+ };
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 30, .file = "mise.toml" }, .{ .vtable = &Clocked.vtable }, false);
+ defer a.deinit();
+ _ = try a.local(.{ .command = "New" });
+ const mid = a.core.view().active;
+ _ = try a.local(.{ .command = "New" });
+ {
+ const was = Stepping.begin(&a.t, null);
+ defer was.end();
+ a.core.view().active = mid;
+ }
+ const r = try joinedFresh(a);
+ defer r.deinit();
+ var sent: std.ArrayListUnmanaged([]u8) = .empty;
+ defer {
+ for (sent.items) |m| gpa.free(m);
+ sent.deinit(gpa);
+ }
+ Clocked.now_ns += std.time.ns_per_s;
+ try key(r, ' ', &sent);
+ try key(r, 'd', &sent);
+ try std.testing.expectEqual(@as(usize, 2), r.applied);
+ try std.testing.expect(r.core().panes[mid].?.prompt == .del_side);
+ for (sent.items) |m| {
+ r.confirm(try a.take(m));
+ r.settle();
+ }
+ try std.testing.expectEqual(@as(u32, 0), r.stats.mispredicted);
+ try agrees(a, r);
+ // The question shows a delay after it was asked, on the session's clock.
+ a.pump();
+ r.confirm((try a.pending()).?);
+ r.settle();
+ try agrees(a, r);
+ try std.testing.expectEqual(Clocked.now_ns + pardes.config.del_question_delay_ns, r.core().panes[mid].?.question_due_ns);
+}
diff --git a/core/root.zig b/core/root.zig
index a57934a6..5300ce93 100644
--- a/core/root.zig
+++ b/core/root.zig
@@ -103,8 +103,6 @@ pub const platform = @import("pardes_options").platform;
pub const version = @import("build_info").version;
pub const commit: ?[]const u8 = @import("build_info").commit;
-pub const isolated = @import("pardes_options").isolated;
-
pub const font_picker = platform == .gui or platform == .macos;
/// Whose turn it is with the core (Turn.zig): one per process, like the
@@ -600,10 +598,13 @@ test "nothing of a core is a process global: every container-level var in core/
/// The lines of each file of core/ that name the machine outside a test:
/// `std.c.`, `libc.`, `std.posix.`, `getenv`, std.Io's File, Dir, net and
-/// Threaded (a path's text, `Dir.path`, and `max_path_bytes` are none), and
-/// `@import("dev")` and `@import("runtime")`, by file, how many and why. A
-/// step's read of its own machine with no tape diverges a far client, and
-/// the soak (one machine) never sees it: a new line here makes someone look.
+/// Threaded (a path's text, `Dir.path`, and `max_path_bytes` are none),
+/// `@import("dev")` and `@import("runtime")`, and the host's table
+/// (`host.vtable`, `host.ctx`: only the tape's own lines call the host, a
+/// call made past it is no call a replica replays), by file, how many and
+/// why. A step's read of its own machine with no tape diverges a far
+/// client, and the soak (one machine) never sees it: a new line here makes
+/// someone look.
/// The count is a file's, so it cannot tell a step's read from its host
/// half's; the reason says which the file's are.
const machine_lines = [_]struct { []const u8, usize, []const u8 }{
@@ -629,11 +630,11 @@ const machine_lines = [_]struct { []const u8, usize, []const u8 }{
.{ "hunks.zig", 1, "a test helper's file read" },
.{ "look.zig", 6, "openLink's fork (the host's: a view's frontend opens a link) and a remote's error name" },
.{ "memory.zig", 7, "the memory regions themselves (mmap, madvise, their locks)" },
- .{ "replica.zig", 70, "the client and session engines: sockets, threads, clocks, the blob cache, traces" },
+ .{ "replica.zig", 73, "the client and session engines: sockets, threads, clocks, the blob cache, traces" },
.{ "rollback.zig", 1, "a test helper's directory" },
.{ "root.zig", 4, "dev's modules re-exported (host_io, file_watch, glide, fonts)" },
.{ "selection_pipe.zig", 14, "a pipe's child processes and their files: the host's `pipe` entry" },
- .{ "tape.zig", 11, "the tape's own files and host_io's types: a recording, a replay; the `io` a tape hands a site's body" },
+ .{ "tape.zig", 12, "the tape's own files and host_io's types: a recording, a replay; the `io` a tape hands a site's body; which host the core holds (noteHost), the one file that names the host's table" },
.{ "lsp/lsp.zig", 1, "the language server's client (dev): the host's `lsp` entry" },
.{ "ninep/ctl.zig", 1, "the session's pid in a 9P read: the session's server" },
.{ "ninep/events.zig", 2, "the 9P event log's clock: the session's server" },
@@ -645,7 +646,7 @@ const machine_lines = [_]struct { []const u8, usize, []const u8 }{
/// The lines of `src` that name the machine (`machine_lines`'s rules).
fn machineLines(src: []const u8, gpa: std.mem.Allocator, out: *std.ArrayList(usize)) !void {
- const names = [_][]const u8{ "std.c.", "libc.", "std.posix.", "getenv", "std.Io.File", "std.Io.Dir", "std.Io.net", "std.Io.Threaded", "Io.File", "Io.Dir", "Io.net", "Io.Threaded" };
+ const names = [_][]const u8{ "std.c.", "libc.", "std.posix.", "getenv", "std.Io.File", "std.Io.Dir", "std.Io.net", "std.Io.Threaded", "Io.File", "Io.Dir", "Io.net", "Io.Threaded", "host.vtable", "host.ctx" };
const pure = [_][]const u8{ "std.Io.Dir.path.", "Io.Dir.path.", "std.Io.Dir.max_path_bytes", "Io.Dir.max_path_bytes" };
var open: std.ArrayList(u8) = .empty;
defer open.deinit(gpa);
diff --git a/core/syntax.zig b/core/syntax.zig
index ba3851ab..19831ec2 100644
--- a/core/syntax.zig
+++ b/core/syntax.zig
@@ -7,17 +7,11 @@ const regexp = @import("regexp.zig");
const c_heap = @import("c_heap");
const diff = @import("diff.zig");
-pub const enabled = config.grammars != .disabled;
-const minimal_grammars = config.grammars == .minimal or config.grammars == .full;
+const minimal_grammars = config.grammars != .none;
const full_grammars = config.grammars == .full;
-pub const ts = if (enabled) @import("tree-sitter") else struct {
- pub const Language = opaque {};
- pub const Query = opaque {};
- pub const Parser = opaque {};
- pub const QueryCursor = opaque {};
-};
-const ts_queries = if (enabled) @import("ts_queries") else struct {};
+pub const ts = @import("tree-sitter");
+const ts_queries = @import("ts_queries");
const LanguageFn = *const fn () callconv(.c) *const ts.Language;
@@ -43,7 +37,6 @@ const Spec = struct {
fn grammarSelected(comptime g: grammar_manifest.Grammar) bool {
return switch (g.tier) {
- .zig => enabled,
.minimal => minimal_grammars,
.full => full_grammars,
};
@@ -92,28 +85,24 @@ extern fn ts_set_allocator(
) void;
pub fn start(gpa: std.mem.Allocator) void {
- if (comptime enabled) {
- std.debug.assert(!syntax_started);
- stop();
- syntax_allocator = gpa;
- syntax_started = true;
- ts_set_allocator(syntax_heap.malloc, syntax_heap.calloc, syntax_heap.realloc, syntax_heap.free);
- }
+ std.debug.assert(!syntax_started);
+ stop();
+ syntax_allocator = gpa;
+ syntax_started = true;
+ ts_set_allocator(syntax_heap.malloc, syntax_heap.calloc, syntax_heap.realloc, syntax_heap.free);
}
pub fn stop() void {
- if (comptime enabled) {
- for (&specs) |*spec| dropSpec(spec);
- forgetLanguages();
- for (&diff_pieces) |*slot| {
- if (slot.*) |piece| syntax_allocator.free(piece.styles);
- slot.* = null;
- }
- diff_clock = 0;
- ts_set_allocator(null, null, null, null);
- syntax_started = false;
- syntax_allocator = undefined;
+ for (&specs) |*spec| dropSpec(spec);
+ forgetLanguages();
+ for (&diff_pieces) |*slot| {
+ if (slot.*) |piece| syntax_allocator.free(piece.styles);
+ slot.* = null;
}
+ diff_clock = 0;
+ ts_set_allocator(null, null, null, null);
+ syntax_started = false;
+ syntax_allocator = undefined;
}
const Selected = struct {
@@ -254,7 +243,6 @@ fn runQuery(styles: []u8, sel: Selected, tree: *ts.Tree, base: usize) void {
pub fn highlightFileRange(gpa: std.mem.Allocator, path: []const u8, content: []const u8, start_raw: usize, end_raw: usize) ![]u8 {
const zone = tracy.zone(@src(), "highlightFileRange");
defer zone.end();
- if (!enabled) return &.{};
const selected = (try forExt(std.Io.Dir.path.extension(path))) orelse return &.{};
const start_byte = @min(start_raw, content.len);
const end_byte = @max(start_byte, @min(end_raw, content.len));
@@ -269,7 +257,6 @@ pub fn highlightFileRange(gpa: std.mem.Allocator, path: []const u8, content: []c
/// no injections (markdown's and typst's reach the shared parsers), made
/// ready here, on the loop, so the worker only reads its query.
pub fn readyApart(path: []const u8) bool {
- if (!enabled) return false;
const selected = (forExt(std.Io.Dir.path.extension(path)) catch return false) orelse return false;
return !std.mem.eql(u8, selected.name, "markdown") and !std.mem.eql(u8, selected.name, "typst");
}
@@ -278,7 +265,6 @@ pub fn readyApart(path: []const u8) bool {
/// parse and a query cursor of its own, the grammar's query shared (it
/// is only read); `halt` ends the parse early. After `readyApart`.
pub fn highlightApart(gpa: std.mem.Allocator, path: []const u8, source: []const u8, halt: *const std.atomic.Value(bool)) ![]u8 {
- if (comptime !enabled) return &.{};
const shared = (try forExt(std.Io.Dir.path.extension(path))) orelse return &.{};
const tree = try parseApart(shared.lang, source, halt);
defer tree.destroy();
@@ -335,7 +321,6 @@ pub const ContextDeclaration = struct {
};
pub fn supportsPath(path: []const u8) bool {
- if (!enabled) return false;
return byExt(std.Io.Dir.path.extension(path)) != null;
}
@@ -345,7 +330,6 @@ pub fn supportsPath(path: []const u8) bool {
/// since its parse (`editTree`), the parse reuses what those left alone: a
/// character typed into a 9k-line file costs a few hundred µs, not 50 ms.
pub fn parseTree(path: []const u8, content: []const u8, old: ?*anyopaque) ?*anyopaque {
- if (!enabled) return null;
const selected = (forExt(std.Io.Dir.path.extension(path)) catch return null) orelse return null;
const tree = selected.parser.parseString(content, @ptrCast(@alignCast(old))) orelse return null;
if (held_trees) |h| h.born.append(h.meta, @ptrCast(tree)) catch {};
@@ -357,7 +341,6 @@ pub fn parseTree(path: []const u8, content: []const u8, old: ?*anyopaque) ?*anyo
/// places follow the edit; what it says of the edited bytes is stale until
/// `parseTree` with it.
pub fn editTree(tree: *anyopaque, before: []const u8, old: []const u8, ins: []const u8) void {
- if (!enabled) return;
const from = advance(.{ .row = 0, .column = 0 }, before);
const t: *ts.Tree = @ptrCast(@alignCast(tree));
t.edit(.{
@@ -387,7 +370,6 @@ pub const HeldTrees = struct {
};
pub fn freeTree(tree: *anyopaque) void {
- if (!enabled) return;
if (held_trees) |h| {
for (h.born.items, 0..) |t, i| if (t == tree) {
_ = h.born.swapRemove(i);
@@ -400,7 +382,6 @@ pub fn freeTree(tree: *anyopaque) void {
}
pub fn destroyTree(tree: *anyopaque) void {
- if (!enabled) return;
const t: *ts.Tree = @ptrCast(@alignCast(tree));
t.destroy();
}
@@ -412,7 +393,7 @@ pub const Span = struct { from: usize, to: usize };
/// The spans `walk` takes the byte range [from, to) to, into `out`; `at` is
/// the range's cursor. None when the tree has nothing to say there.
pub fn walkNodes(tree_ptr: *anyopaque, walk: NodeWalk, from: usize, to: usize, at: usize, out: []Span) usize {
- if (!enabled or out.len == 0) return 0;
+ if (out.len == 0) return 0;
const tree: *const ts.Tree = @ptrCast(@alignCast(tree_ptr));
const lo: u32 = @intCast(@min(from, std.math.maxInt(u32)));
const hi: u32 = @intCast(@min(to, std.math.maxInt(u32)));
@@ -497,7 +478,6 @@ fn objectQuery(path: []const u8) ?*ts.Query {
/// The grammar's indent query for `path` (core/indent.zig) and the
/// grammar's name; null when it has none.
pub fn indentQuery(path: []const u8) ?struct { *ts.Query, []const u8 } {
- if (!enabled) return null;
const spec = specFor(path) orelse return null;
return .{ lazyQuery(spec, &spec.indents) orelse return null, spec.name };
}
@@ -563,7 +543,6 @@ fn matchSpan(q: *const ts.Query, match: anytype, capture: u32, text: []const u8)
/// `mi`/`ma`: the smallest `object.inside` (or `.around`) holding byte `at`
/// (helix textobject_treesitter). None without a query or such an object.
pub fn objectAt(path: []const u8, tree_ptr: *anyopaque, text: []const u8, object: Object, around: bool, at: usize) ?Span {
- if (!enabled) return null;
const q = objectQuery(path) orelse return null;
var buf: [32]u8 = undefined;
const want = std.fmt.bufPrint(&buf, "{s}.{s}", .{ objectName(object), if (around) "around" else "inside" }) catch return null;
@@ -587,7 +566,6 @@ pub fn objectAt(path: []const u8, tree_ptr: *anyopaque, text: []const u8, object
/// previous one ending before it (helix goto_treesitter_object), from the
/// first of `.movement`, `.around`, `.inside` the query names.
pub fn objectNext(path: []const u8, tree_ptr: *anyopaque, text: []const u8, object: Object, forward: bool, at: usize) ?Span {
- if (!enabled) return null;
const q = objectQuery(path) orelse return null;
var buf: [32]u8 = undefined;
const capture = for ([_][]const u8{ "movement", "around", "inside" }) |kind| {
@@ -628,7 +606,7 @@ pub const SourceAnalysis = struct {
};
pub fn analyzeSource(gpa: std.mem.Allocator, path: []const u8, content: []const u8, want_declarations: bool, want_colors: bool) !SourceAnalysis {
- if (!enabled or content.len == 0 or (!want_declarations and !want_colors)) return .{};
+ if (content.len == 0 or (!want_declarations and !want_colors)) return .{};
const selected = (try forExt(std.Io.Dir.path.extension(path))) orelse return .{};
const tree = selected.parser.parseString(content, null) orelse return .{};
defer tree.destroy();
@@ -652,7 +630,6 @@ pub fn contextDeclarations(gpa: std.mem.Allocator, path: []const u8, content: []
/// (`parseApart`). `halt` ends the parse and the walk early
/// (error.Canceled): a 1.2 MB file is seconds in a Debug build.
pub fn declarationsApart(gpa: std.mem.Allocator, path: []const u8, content: []const u8, halt: *const std.atomic.Value(bool)) ![]ContextDeclaration {
- if (comptime !enabled) return &.{};
if (content.len == 0) return &.{};
const ext = std.Io.Dir.path.extension(path);
const spec = specs: for (&specs) |*spec| {
@@ -796,7 +773,6 @@ pub fn highlightLocations(gpa: std.mem.Allocator, content: []const u8, start_byt
const start_byte = @min(start_byte_raw, content.len);
const end_byte = @max(start_byte, @min(end_byte_raw, content.len));
const source = content[start_byte..end_byte];
- if (!enabled) return &.{};
const styles = try gpa.alloc(u8, source.len);
errdefer gpa.free(styles);
@memset(styles, 0);
@@ -829,7 +805,7 @@ pub fn highlightLocations(gpa: std.mem.Allocator, content: []const u8, start_byt
/// padded location column. This also colors context whose location is hidden.
/// Consecutive source rows share one parse, retaining multiline syntax.
pub fn highlightLocationRows(gpa: std.mem.Allocator, content: []const u8, rows: []const locations.Row) ![]u8 {
- if (!enabled or content.len == 0 or rows.len == 0) return &.{};
+ if (content.len == 0 or rows.len == 0) return &.{};
const styles = try gpa.alloc(u8, content.len);
errdefer gpa.free(styles);
@memset(styles, 0);
@@ -1111,7 +1087,7 @@ const DiffWindow = struct {
};
fn paintDiffPiece(gpa: std.mem.Allocator, window: DiffWindow, bytes: []const u8, at: usize, kinds: []const diff.Kind, path: []const u8) !void {
- const selected: ?Selected = if (enabled and syntax_started) (forExt(std.Io.Dir.path.extension(path)) catch null) else null;
+ const selected: ?Selected = if (syntax_started) (forExt(std.Io.Dir.path.extension(path)) catch null) else null;
if (selected) |sel| {
const hash = std.hash.Wyhash.hash(std.hash.Wyhash.hash(0, sel.name), bytes);
diff_clock += 1;
@@ -1269,7 +1245,6 @@ test {
}
test "every vendored textobject and indent query compiles against its grammar" {
- if (!enabled) return;
var failed: usize = 0;
for (&specs) |*spec| for ([_]Lazy{ spec.objects, spec.indents }, [_][]const u8{ "textobjects", "indents" }) |lazy, what| {
if (lazy.src.len == 0) continue;
@@ -1285,7 +1260,6 @@ test "every vendored textobject and indent query compiles against its grammar" {
}
test "syntax context nested Zig containers and multiline function signatures" {
- if (!enabled) return;
const gpa = std.testing.allocator;
start(gpa);
defer stop();
@@ -1317,7 +1291,7 @@ test "syntax context nested Zig containers and multiline function signatures" {
}
test "syntax context Python class and function body excludes first statement" {
- if (!enabled or !full_grammars) return;
+ if (!full_grammars) return;
const gpa = std.testing.allocator;
start(gpa);
defer stop();
@@ -1330,7 +1304,6 @@ test "syntax context Python class and function body excludes first statement" {
}
test "syntax context multiline bindings and C++ namespaces preserve declaration starts" {
- if (!enabled) return;
const gpa = std.testing.allocator;
start(gpa);
defer stop();
@@ -1340,7 +1313,7 @@ test "syntax context multiline bindings and C++ namespaces preserve declaration
try std.testing.expectEqual(@as(usize, 1), zig_declarations.len);
try std.testing.expectEqual(@as(usize, 0), zig_declarations[0].start_line);
try std.testing.expectEqual(@as(usize, 1), zig_declarations[0].header_end_line);
- if (!minimal_grammars and !full_grammars) return;
+ if (!minimal_grammars) return;
const cpp_source = "namespace example {\nstruct Outer {\n int run() {\n return 1;\n }\n};\n}\n";
const cpp_declarations = try contextDeclarations(gpa, "nested.cpp", cpp_source);
defer gpa.free(cpp_declarations);
@@ -1352,7 +1325,7 @@ test "syntax context multiline bindings and C++ namespaces preserve declaration
}
test "syntax context Rust modules impls and methods remain nested" {
- if (!enabled or !full_grammars) return;
+ if (!full_grammars) return;
const gpa = std.testing.allocator;
start(gpa);
defer stop();
@@ -1368,7 +1341,7 @@ test "syntax context Rust modules impls and methods remain nested" {
}
test "syntax formatted locations color hidden context and preserve multiline source" {
- if (!enabled or (!minimal_grammars and !full_grammars)) return;
+ if (!minimal_grammars) return;
const gpa = std.testing.allocator;
start(gpa);
defer stop();
@@ -1393,7 +1366,7 @@ test "syntax formatted locations color hidden context and preserve multiline sou
}
test "syntax formatted locations separate alignment from Markdown indentation" {
- if (!enabled or !full_grammars) return;
+ if (!full_grammars) return;
const gpa = std.testing.allocator;
start(gpa);
defer stop();
@@ -1409,7 +1382,6 @@ test "syntax formatted locations separate alignment from Markdown indentation" {
}
test "syntax a results row is coloured by the file its location names" {
- if (!enabled) return;
start(std.testing.allocator);
defer stop();
const gpa = std.testing.allocator;
@@ -1432,7 +1404,6 @@ test "syntax a results row is coloured by the file its location names" {
}
test "syntax a buffer with no locations in it keeps no highlights at all" {
- if (!enabled) return;
start(std.testing.allocator);
defer stop();
const content = "nothing has been said yet\n0: save: AccessDenied (x2)\n";
@@ -1460,7 +1431,7 @@ test "syntax codeAfterLocation takes whole-token locations and nothing else" {
}
test "syntax default full grammar set highlights Typst source" {
- if (!enabled or !full_grammars) return;
+ if (!full_grammars) return;
start(std.testing.allocator);
defer stop();
@@ -1483,7 +1454,7 @@ test "syntax default full grammar set highlights Typst source" {
}
test "syntax Typst markup constructs paint and raw blocks inject their language" {
- if (!enabled or !full_grammars) return;
+ if (!full_grammars) return;
start(std.testing.allocator);
defer stop();
@@ -1527,7 +1498,7 @@ test "syntax Typst markup constructs paint and raw blocks inject their language"
}
test "syntax markdown highlights markup, injects inline spans and fenced code blocks" {
- if (!enabled or !full_grammars) return;
+ if (!full_grammars) return;
start(std.testing.allocator);
defer stop();
@@ -1559,7 +1530,7 @@ test "syntax markdown highlights markup, injects inline spans and fenced code bl
}
test "syntax inline fast path agrees with full Markdown query" {
- if (!enabled or !full_grammars) return;
+ if (!full_grammars) return;
start(std.testing.allocator);
defer stop();
const selected = (try forLang("markdown_inline")).?;
@@ -1606,7 +1577,7 @@ test "syntax inline fast path agrees with full Markdown query" {
}
test "syntax plain Markdown keeps block styles without starting the inline parser" {
- if (!enabled or !full_grammars) return;
+ if (!full_grammars) return;
start(std.testing.allocator);
defer stop();
const source = "# Heading\n\nPlain prose.\n\n indented code\n";
@@ -1648,7 +1619,6 @@ test "syntax highlightDiff colors unified diff lines by prefix" {
}
test "syntax a Zig hunk is coloured as Zig, each side parsed whole" {
- if (!enabled) return;
start(std.testing.allocator);
defer stop();
const diff_text =
@@ -1689,7 +1659,7 @@ test "syntax a Zig hunk is coloured as Zig, each side parsed whole" {
}
test "syntax a Python hunk is coloured as Python" {
- if (!enabled or !full_grammars) return;
+ if (!full_grammars) return;
start(std.testing.allocator);
defer stop();
const diff_text =
@@ -1710,7 +1680,6 @@ test "syntax a Python hunk is coloured as Python" {
}
test "syntax a deleted file's lines are coloured in its language" {
- if (!enabled) return;
start(std.testing.allocator);
defer stop();
const diff_text =
@@ -1730,7 +1699,6 @@ test "syntax a deleted file's lines are coloured in its language" {
}
test "syntax a hunk in no known language keeps the line colours" {
- if (!enabled) return;
start(std.testing.allocator);
defer stop();
const diff_text =
@@ -1747,7 +1715,6 @@ test "syntax a hunk in no known language keeps the line colours" {
}
test "syntax git diff output in a command pane is told and coloured by its rows" {
- if (!enabled) return;
start(std.testing.allocator);
defer stop();
// A command pane's rows: its command line, then git's output, with one
@@ -1780,7 +1747,6 @@ test "syntax git diff output in a command pane is told and coloured by its rows"
}
test "syntax a section's small hunks share one parse" {
- if (!enabled) return;
const gpa = std.testing.allocator;
start(gpa);
defer stop();
@@ -1802,7 +1768,6 @@ test "syntax a section's small hunks share one parse" {
}
test "syntax a hunk painted once is kept, and a long one is parsed in pieces" {
- if (!enabled) return;
const gpa = std.testing.allocator;
start(gpa);
defer stop();
@@ -1832,7 +1797,6 @@ test "syntax a hunk painted once is kept, and a long one is parsed in pieces" {
}
test "syntax result fragments preserve source indentation and inline markup" {
- if (!enabled) return;
start(std.testing.allocator);
defer stop();
const fixtures = [_]struct { path: []const u8, source: []const u8 }{
@@ -1862,7 +1826,6 @@ test "syntax result fragments preserve source indentation and inline markup" {
}
test "syntax query filtering preserves upstream colors" {
- if (!enabled) return;
var allocator: std.heap.DebugAllocator(.{ .stack_trace_frames = 0, .safety = true }) = .init;
defer if (allocator.deinit() != .ok) @panic("leaked syntax query allocations");
start(allocator.allocator());
@@ -1893,7 +1856,6 @@ test "syntax query filtering preserves upstream colors" {
}
test "syntax Zig keyword captures cover both bytes beyond line ten thousand" {
- if (!enabled) return;
start(std.testing.allocator);
defer stop();
const code = "pub fn main() void {\n if (true) return;\n}\n";
@@ -1911,7 +1873,6 @@ test "syntax Zig keyword captures cover both bytes beyond line ten thousand" {
}
test "syntax allocator switching clears default-runtime caches" {
- if (!enabled) return;
const source = "fn main() void {}";
const initial = try highlightFileRange(std.testing.allocator, "a.zig", source, 0, source.len);
std.testing.allocator.free(initial);
@@ -1927,7 +1888,7 @@ test "syntax allocator switching clears default-runtime caches" {
}
test "syntax location context snapshots retain omitted multiline comment scope" {
- if (!enabled or (!minimal_grammars and !full_grammars)) return;
+ if (!minimal_grammars) return;
const gpa = std.testing.allocator;
start(gpa);
defer stop();
@@ -1953,7 +1914,6 @@ test "syntax location context snapshots retain omitted multiline comment scope"
}
test "syntax declaration locations clear snapshots without muting ordinary context" {
- if (!enabled) return;
const gpa = std.testing.allocator;
start(gpa);
defer stop();
@@ -1973,7 +1933,7 @@ test "syntax declaration locations clear snapshots without muting ordinary conte
}
test "syntax stacked addresses do not split multiline source groups" {
- if (!enabled or (!minimal_grammars and !full_grammars)) return;
+ if (!minimal_grammars) return;
const gpa = std.testing.allocator;
start(gpa);
defer stop();
@@ -1998,7 +1958,6 @@ test "syntax stacked addresses do not split multiline source groups" {
}
test "syntax source analysis preserves declarations and injected colors" {
- if (!enabled) return;
const gpa = std.testing.allocator;
start(gpa);
defer stop();
@@ -2059,7 +2018,7 @@ test "syntax source analysis preserves declarations and injected colors" {
}
test "tables are the pipe_tables tree-sitter finds" {
- if (!enabled or !full_grammars) return;
+ if (!full_grammars) return;
start(std.testing.allocator);
defer stop();
const Tables = @import("Tables.zig");
@@ -2128,7 +2087,6 @@ test "tables are the pipe_tables tree-sitter finds" {
}
test "a kept tree told its edits parses to the fresh parse's tree, places and all" {
- if (!enabled) return error.SkipZigTest;
const gpa = std.testing.allocator;
const a = "const std = @import(\"std\");\n\nfn f(x: u32) u32 {\n return x;\n}\n\ntest \"t\" {\n _ = f(1);\n}\n";
const old_tree = parseTree("a.zig", a, null) orelse return error.NoTree;
@@ -2168,7 +2126,6 @@ test "a kept tree told its edits parses to the fresh parse's tree, places and al
}
test "syntax: a grammar handed in at run time colours and walks as the one compiled in" {
- if (!enabled) return error.SkipZigTest;
const gpa = std.testing.allocator;
start(gpa);
defer stop();
diff --git a/core/tape.zig b/core/tape.zig
index f705636f..7f28621e 100644
--- a/core/tape.zig
+++ b/core/tape.zig
@@ -25,7 +25,8 @@ const pardes = @import("root.zig");
const walk = @import("walk.zig");
const host_io = @import("dev").host_io;
const Pardes = pardes.Pardes;
-const VTable = pardes.Host.VTable;
+const Host = pardes.Host;
+const VTable = Host.VTable;
const libc = std.c;
pub var on: ?*Tape = null;
@@ -160,7 +161,7 @@ pub const results = .{
// Recent's entry for a closed jump, the closed panes' names.
?@import("Store.zig").Record,
?@import("recent.zig").Entry, []const @import("Store.zig").Named,
- @import("Kind.zig").Outcome,
+ @import("Kind.zig").Outcome, pardes.Term.Prompt,
};
/// What a host reports to the core as failed (`shell_failed`, `save_failed`,
@@ -185,7 +186,7 @@ fn ErrorOf(comptime f: anytype) type {
pub const shape = blk: {
var types: []const type = &.{ Input, Site, []const u64, struct { u8, u64 } };
for (results) |R| types = types ++ .{R};
- for (host_fns) |f| types = types ++ .{@typeInfo(@typeInfo(@typeInfo(@FieldType(VTable, f)).optional.child).pointer.child).@"fn".return_type.?};
+ for (host_fns) |f| types = types ++ .{Host.Ret(@field(Host.Fn, f))};
for (watched) |name| types = types ++ .{Watched(name)};
break :blk walk.shape(types);
};
@@ -245,18 +246,24 @@ pub const Tape = struct {
/// call out of it is the host's to answer.
host_side: bool = true,
depth: u32 = 0,
- vtable: VTable = .{},
// Recording.
fd: c_int = -1,
buf: std.ArrayList(u8) = .empty,
scratch: std.Io.Writer.Allocating,
- real: pardes.Host = .{},
+ /// The host whose functions were last said (`noteHost`).
+ real: Host = .{},
seen: [watched.len]u64 = @splat(0),
// Replaying.
in: walk.Reader = .{ .bytes = &.{} },
arena: std.heap.ArenaAllocator,
last_ret: walk.Reader = .{ .bytes = &.{} },
+ /// Which functions the session's host has, a bit each in the table's
+ /// order (`Host.mask`): what a replica's core answers by (`has`).
mask: u64 = 0,
+ /// A replica's (a client's, a replay's), from its first replay or its
+ /// join (`replayUnit`, `adoptCore`): its core has no host, and asks
+ /// the tape what the session's has, between its steps too (a frame).
+ replica: bool = false,
skips_render: bool = false,
digests: u64 = 0,
diverged: ?[]const u8 = null,
@@ -388,38 +395,17 @@ pub const Tape = struct {
inline for (watched, 0..) |name, i| t.seen[i] = walk.digest(Watched(name), watchedOf(p, name));
}
- /// The host's functions go through the tape while it records, whoever
- /// set `p.host` last.
- fn wrap(t: *Tape, p: *Pardes) void {
- if (p.host.vtable == &t.vtable) return;
- // The same host given again (each pump is given its host): only
- // the wrapper put back.
- if (p.host.vtable == t.real.vtable and p.host.ctx == t.real.ctx) {
- p.host = .{ .ctx = t, .vtable = &t.vtable };
- return;
- }
+ /// Which functions the session's host has, said at an entry whose
+ /// core holds another host than the last said (each pump is given its
+ /// host again: then nothing).
+ fn noteHost(t: *Tape, p: *const Pardes) void {
+ if (p.host.vtable == t.real.vtable and p.host.ctx == t.real.ctx) return;
t.real = p.host;
- var mask: u64 = 0;
- inline for (host_fns, 0..) |f, i| if (@field(t.real.vtable.*, f) != null) {
- mask |= @as(u64, 1) << i;
- };
- p.host = t.hostOf(mask);
- const set: struct { u8, u64 } = .{ set_mask, mask };
+ t.mask = p.host.mask();
+ const set: struct { u8, u64 } = .{ set_mask, t.mask };
t.record(.set, @TypeOf(set), &set);
}
- /// The tape as a host with these functions.
- fn hostOf(t: *Tape, mask: u64) pardes.Host {
- t.mask = mask;
- t.vtable = .{};
- inline for (host_fns, 0..) |f, i| if (mask & (@as(u64, 1) << i) != 0 or
- (t.skips_render and comptime std.mem.eql(u8, f, "watched")))
- {
- @field(t.vtable, f) = &Wrap(i).f;
- };
- return .{ .ctx = t, .vtable = &t.vtable };
- }
-
fn enterInput(t: *Tape, p: ?*Pardes, input: *const Input) Entered {
if (!t.host_side) return .{};
t.host_side = false;
@@ -428,7 +414,7 @@ pub const Tape = struct {
if (p) |core| {
if (t.core == null) t.core = core;
t.noteWrites();
- t.wrap(core);
+ t.noteHost(core);
}
// A terminal's output crosses as screen state, not as its bytes.
if (t.screen_state and input.* == .update and input.update.args[0] == .output) {
@@ -445,7 +431,7 @@ pub const Tape = struct {
if (t.replay) return;
if (p) |core| if (t.core == null) {
t.core = core;
- t.wrap(core);
+ t.noteHost(core);
};
t.record(.done, void, &{});
if ((t.depth == 0 or t.every) and !t.no_digest and !t.unit_digests) recordDigest(t);
@@ -653,8 +639,7 @@ pub const Tape = struct {
fn applySet(t: *Tape, r: *walk.Reader) void {
const which = (r.take(1) catch return)[0];
if (which == set_mask) {
- const host = t.hostOf(std.mem.bytesToValue(u64, r.take(8) catch return));
- if (t.core) |p| p.host = host;
+ t.mask = std.mem.bytesToValue(u64, r.take(8) catch return);
return;
}
const p = t.core orelse return;
@@ -697,7 +682,6 @@ pub const Tape = struct {
.init_from_dump => |d| pardes.dump.initFromDump(gpa, opts, d.bytes),
else => unreachable,
} catch |err| return t.diverge("init failed: {t}", .{err});
- t.core.?.host = t.hostOf(t.mask);
return t.finishInput();
},
else => {},
@@ -709,7 +693,6 @@ pub const Tape = struct {
const nc = pardes.dump.restore(p, a.args[0], a.args[1]) catch |err| return t.diverge("restore failed: {t}", .{err});
t.core = nc;
nc.tape = t;
- nc.host = t.hostOf(t.mask);
},
// The session is over (or the core a Restore replaced is
// freed): nothing done now is compared.
@@ -720,7 +703,7 @@ pub const Tape = struct {
}
return t.skip();
},
- .pump => p.pump(t.hostOf(t.mask)) catch {},
+ .pump => p.pump(.{}) catch {},
.render => if (t.skips_render) return t.skip() else {
_ = p.frame_arena.reset(.retain_capacity);
_ = p.render(p.frame_arena.allocator()) catch {};
@@ -857,6 +840,26 @@ pub const Tape = struct {
return r;
}
+ /// One call out to the session's host, `f(args)`: made and recorded
+ /// with what it answered; answered from the tape on a replay; refused
+ /// to a speculation, or recorded as made (`keeps_stopping`). Null: the
+ /// session's host has no such function.
+ pub inline fn host(t: *Tape, p: *const Pardes, comptime f: Host.Fn, args: Host.Args(f)) ?Host.Ret(f) {
+ // Nobody records: the call it always was.
+ if (t.through) return p.host.call(f, args);
+ if (!t.has(p, f)) return null;
+ return hostCall(t, p, f, args);
+ }
+
+ /// Whether the session's host has `f`, asked apart from a call: a
+ /// replica's core has no host, and answers as its session's did.
+ pub fn has(t: *const Tape, p: *const Pardes, comptime f: Host.Fn) bool {
+ if (!t.replica) return p.host.has(f);
+ // A replica that never draws asks, and is told no one watches (`hostCall`).
+ if (comptime f == .watched) if (t.skips_render) return true;
+ return t.mask & (@as(u64, 1) << @backingInt(f)) != 0;
+ }
+
/// Asked by `turn.yield`: a syscall a replica must never make.
pub fn replaying(t: *const Tape) bool {
return t.replay or t.speculating;
@@ -922,7 +925,7 @@ pub const Tape = struct {
p.tape = t;
if (t.replay or t.through) return;
t.core = p;
- t.wrap(p);
+ t.noteHost(p);
}
/// Whether `p` is the core being recorded (a Restore's old one is not).
@@ -1138,100 +1141,64 @@ fn tagOf(comptime entry: anytype, comptime Made: type) [:0]const u8 {
return found orelse @compileError("tape: no variant of Input names the entry " ++ @typeName(Made) ++ " (a line `<tag>: Args(<the entry>)` in tape.Input)");
}
-/// The Host function `i`, through the tape.
-fn Wrap(comptime i: usize) type {
- const Fn = @typeInfo(@typeInfo(@FieldType(VTable, host_fns[i])).optional.child).pointer.child;
- const info = @typeInfo(Fn).@"fn";
- const R = info.return_type.?;
- const P = info.param_types;
- return switch (P.len) {
- 1 => struct {
- fn f(ctx: ?*anyopaque) R {
- return hostCall(i, R, ctx, .{});
- }
- },
- 2 => struct {
- fn f(ctx: ?*anyopaque, a: P[1].?) R {
- return hostCall(i, R, ctx, .{a});
- }
- },
- 3 => struct {
- fn f(ctx: ?*anyopaque, a: P[1].?, b: P[2].?) R {
- return hostCall(i, R, ctx, .{ a, b });
- }
- },
- 4 => struct {
- fn f(ctx: ?*anyopaque, a: P[1].?, b: P[2].?, c: P[3].?) R {
- return hostCall(i, R, ctx, .{ a, b, c });
- }
- },
- 5 => struct {
- fn f(ctx: ?*anyopaque, a: P[1].?, b: P[2].?, c: P[3].?, d: P[4].?) R {
- return hostCall(i, R, ctx, .{ a, b, c, d });
- }
- },
- else => @compileError("tape: a host function of more arguments"),
- };
-}
-
/// The Host entries that return nothing and still stop a speculation, each
/// with why; a speculation records any other as made and goes on (`hostCall`).
/// The entries that answer stop by nature: the answer is the session's.
-const keeps_stopping = .{
+const keeps_stopping = [_]Host.Fn{
// A shell's input: a device by the user's line (a far shell may feel
// like ssh), and off the tape with screen-state terminals.
- "pty_write",
+ .pty_write,
// Its host says into the core on every call that the shell started
// and where (host_io.forkShell: acknowledgeShell, setCwd), and gives
// the turn away: a rollback every time, nothing gained.
- "spawn",
+ .spawn,
// Its host writes the core outside any record (exec.reapplyInitFile,
// Plumb.saved, fs.writeSelf) besides `saved` or the failure, every call.
- "write_file",
+ .write_file,
// Their hosts say done or failed into the core on every call
// (setLastDump, dumpFailed; setMessage, reportError): a rollback every
// time, nothing gained.
- "write_dump",
- "dump_themes",
+ .write_dump,
+ .dump_themes,
// The session's own: it execs itself after the step, carries a window
// away, or lets its frontend go (writing `frontend` and `unattended`).
- "upgrade",
- "hand_over",
- "detach",
+ .upgrade,
+ .hand_over,
+ .detach,
// The loop's, never a step's.
- "wait_input",
- "present",
- "post_present",
- "poll_frame",
+ .wait_input,
+ .present,
+ .post_present,
+ .poll_frame,
};
-fn keepsStopping(comptime name: []const u8, args: anytype) bool {
+fn keepsStopping(comptime f: Host.Fn, args: Host.Args(f)) bool {
// Turned on, its host loads the theme file into the core outside any
// record (colors.loadThemeFile: custom_theme, theme_file_loaded);
// turned off it only lets the file go.
- if (comptime std.mem.eql(u8, name, "watch_theme")) return args[1];
- inline for (keeps_stopping) |s| if (comptime std.mem.eql(u8, s, name)) return true;
- return false;
+ if (comptime f == .watch_theme) return args[1];
+ return comptime std.mem.indexOfScalar(Host.Fn, &keeps_stopping, f) != null;
}
/// The entries a view's frontend makes on its own machine (P16).
-fn forTheView(comptime name: []const u8) bool {
- return std.mem.eql(u8, name, "set_clipboard") or std.mem.eql(u8, name, "read_clipboard") or std.mem.eql(u8, name, "open_link");
+fn forTheView(comptime f: Host.Fn) bool {
+ return f == .set_clipboard or f == .read_clipboard or f == .open_link;
}
-fn hostCall(comptime i: usize, comptime R: type, ctx: ?*anyopaque, args: anytype) R {
- const t: *Tape = @ptrCast(@alignCast(ctx.?));
- const name = host_fns[i];
+/// The one body of a call out to the host through the tape (`Tape.host`).
+fn hostCall(t: *Tape, p: *const Pardes, comptime f: Host.Fn, args: Host.Args(f)) Host.Ret(f) {
+ const R = Host.Ret(f);
+ const name = @tagName(f);
// A terminal's answers and what is typed at it from its output are the
// authority's to write, never a replica's: off the tape on both sides.
if (comptime std.mem.eql(u8, name, "pty_write")) if (t.screen_state and !t.speculating) {
- if (!t.replay) @call(.auto, @field(t.real.vtable.*, name).?, .{t.real.ctx} ++ args);
+ if (!t.replay) _ = p.host.call(f, args);
return;
};
if (t.replay) {
// A replica that never draws is never watched: it asks no one.
if (comptime std.mem.eql(u8, name, "watched")) if (t.skips_render) return false;
- if (!t.expectHost(i, name)) return std.mem.zeroes(R);
+ if (!t.expectHost(@backingInt(f), name)) return std.mem.zeroes(R);
var ret = t.last_ret;
if (R == ?[]const u8) {
// fg_name's answer is written into the caller's buffer.
@@ -1243,7 +1210,7 @@ fn hostCall(comptime i: usize, comptime R: type, ctx: ?*anyopaque, args: anytype
}
return walk.decode(R, &ret, t.arena.allocator()) catch std.mem.zeroes(R);
}
- const id: u16 = i;
+ const id: u16 = @backingInt(f);
if (t.speculating) {
// Nobody watches a replica's step: its frames are its own, drawn
// outside it (and the authority's host says so too, or the
@@ -1258,7 +1225,7 @@ fn hostCall(comptime i: usize, comptime R: type, ctx: ?*anyopaque, args: anytype
// on. The session's unit records the same, or more where its host
// wrote the core during the call (an input it made, a watched field
// set), and the client rolls back.
- if (R == void and !keepsStopping(name, args)) {
+ if (R == void and !keepsStopping(f, args)) {
t.record(.host, u16, &id);
t.record(.ret, void, &{});
return;
@@ -1270,17 +1237,16 @@ fn hostCall(comptime i: usize, comptime R: type, ctx: ?*anyopaque, args: anytype
// A client's yank, paste or link is its own frontend's, made on its own
// machine from its view's record (Pardes.View.yanks): never the
// session's, whose host makes them for a view no client draws.
- if (comptime forTheView(name)) if (t.core) |p| if (p.undrawn & (@as(u8, 1) << @intCast(p.live)) != 0) {
+ if (comptime forTheView(f)) if (p.undrawn & (@as(u8, 1) << @intCast(p.live)) != 0) {
t.record(.host, u16, &id);
t.record(.ret, void, &{});
return;
};
- const real = @field(t.real.vtable.*, name).?;
t.record(.host, u16, &id);
t.seeFields();
const outer = !t.host_side;
t.host_side = true;
- const r = @call(.auto, real, .{t.real.ctx} ++ args);
+ const r = p.host.call(f, args).?;
t.host_side = !outer;
t.noteWrites();
t.record(.ret, R, &r);
@@ -1347,7 +1313,7 @@ pub fn recordDigest(t: *Tape) void {
pub fn adoptCore(t: *Tape, p: *Pardes) void {
t.core = p;
p.tape = t;
- p.host = t.hostOf(t.mask);
+ t.replica = true;
}
/// A replica joins the session recorded on `t` (core/replica.zig): what the
@@ -1355,9 +1321,6 @@ pub fn adoptCore(t: *Tape, p: *Pardes) void {
/// input, for a core made from a dump, which has neither.
pub fn resync(t: *Tape) void {
t.seen = @splat(0);
- if (t.core) |p| if (p.host.vtable == &t.vtable) {
- p.host = t.real;
- };
t.real = .{};
}
@@ -1484,6 +1447,7 @@ pub fn release(t: *Tape) void {
/// tape's core as the authority applied them, each digest checked; why
/// they diverged, or null.
pub fn replayUnit(t: *Tape, bytes: []const u8) ?[]const u8 {
+ t.replica = true;
t.replay = true;
t.speculating = false;
defer t.replay = false;
@@ -1818,6 +1782,73 @@ test "every place that sets the global tape aside sets the core's field aside: a
try std.testing.expectEqual(@as(usize, 0), wrong);
}
+/// The pump's own calls: a host with a clock and a frontend that shows
+/// every frame; `more` has one function besides.
+const Pumped = struct {
+ ns: u64,
+ fn now(ctx: ?*anyopaque) u64 {
+ const h: *Pumped = @ptrCast(@alignCast(ctx.?));
+ h.ns += std.time.ns_per_ms;
+ return h.ns;
+ }
+ fn seen(_: ?*anyopaque) bool {
+ return true;
+ }
+ fn present(_: ?*anyopaque, _: *const pardes.Surface) bool {
+ return true;
+ }
+ fn poll(_: ?*anyopaque) void {}
+ const one: VTable = .{ .now = now, .watched = seen, .present = present };
+ const more: VTable = .{ .now = now, .watched = seen, .present = present, .poll_frame = poll };
+
+ /// Recorded `bytes`: how many times which functions the host has was
+ /// said, the last said, and the calls of each function.
+ fn said(bytes: []const u8) struct { sets: usize = 0, mask: u64 = 0, calls: [host_fns.len]usize = @splat(0) } {
+ var got: @typeInfo(@TypeOf(said)).@"fn".return_type.? = .{};
+ var r: walk.Reader = .{ .bytes = bytes };
+ while (nextRecord(&r)) |rec| {
+ if (rec.kind == .set and rec.payload[0] == set_mask) {
+ got.sets += 1;
+ got.mask = std.mem.bytesToValue(u64, rec.payload[1..9]);
+ }
+ if (rec.kind == .host) {
+ const id = std.mem.bytesToValue(u16, rec.payload[0..2]);
+ if (id < host_fns.len) got.calls[id] += 1;
+ }
+ }
+ return got;
+ }
+};
+
+test "a core pumped twice with one host and once with another: which functions its host has is said at the first pump and the third, its clock, watch and present at each; a replica replays the three units to the same digest" {
+ const gpa = std.testing.allocator;
+ const R = pardes.replica;
+ var first: Pumped = .{ .ns = 0 };
+ var second: Pumped = .{ .ns = 1 << 40 };
+ const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24 }, .{ .ctx = &first, .vtable = &Pumped.one }, false);
+ defer a.deinit();
+ const boot = Pumped.said(a.t.buf.items);
+ try std.testing.expectEqual(Host.mask(.{ .vtable = &Pumped.one }), boot.mask);
+ const r = try R.Replica.init(gpa, 1, try a.unit(0, 0), false);
+ defer r.deinit();
+ const hosts = [_]Host{ .{ .ctx = &first, .vtable = &Pumped.one }, .{ .ctx = &second, .vtable = &Pumped.more } };
+ for (hosts, [_]usize{ 0, 1 }, 1..) |h, sets, seq| {
+ a.host = h;
+ a.apply(.{ .resize = .{ .cols = @intCast(80 + seq), .rows = 24 } });
+ const got = Pumped.said(a.t.buf.items);
+ try std.testing.expectEqual(sets, got.sets);
+ if (sets > 0) try std.testing.expectEqual(h.mask(), got.mask);
+ inline for (.{ .now, .watched, .present }) |f| try std.testing.expect(got.calls[@backingInt(@as(Host.Fn, f))] > 0);
+ try std.testing.expectEqual(@intFromBool(h.has(.poll_frame)), got.calls[@backingInt(Host.Fn.poll_frame)]);
+ a.seq += 1;
+ r.confirm(try a.unit(0, a.seq));
+ }
+ r.settle();
+ if (r.diverged) |why| std.debug.print("diverged: {s}\n", .{why});
+ try std.testing.expect(r.diverged == null);
+ try std.testing.expectEqual(R.digestOf(a), r.digest());
+}
+
test "a client's frame drawn between its steps records nothing into its idle tape" {
const gpa = std.testing.allocator;
const p = try @import("ninep/harness.zig").withFile(gpa, "x\n");
diff --git a/dev/Host.zig b/dev/Host.zig
index a23c9ef5..cb7aefe1 100644
--- a/dev/Host.zig
+++ b/dev/Host.zig
@@ -1,6 +1,8 @@
+const std = @import("std");
const pardes = @import("core");
const host_io = @import("host_io.zig");
const Lsp = host_io.Lsp;
+const Host = @This();
ctx: ?*anyopaque = null,
vtable: *const VTable = &.{},
@@ -64,3 +66,47 @@ pub const VTable = struct {
/// absent, it runs on the loop.
job: ?*const fn (ctx: ?*anyopaque, pane: pardes.Pane.Id, serial: u32, token: u32) void = null,
};
+
+// What a call names, gives and gets, derived from the table: the core calls
+// out through its tape, `p.tape.host(p, .pty_write, .{ pane, bytes })`.
+
+/// One of the table's functions, by its field's name: `.pty_write`. The
+/// tape numbers a call by it (the table's order).
+pub const Fn = std.meta.FieldEnum(VTable);
+
+/// What `f` is given after `ctx`, in order.
+pub fn Args(comptime f: Fn) type {
+ const params = @typeInfo(Of(f)).@"fn".param_types;
+ var types: [params.len - 1]type = undefined;
+ for (params[1..], &types) |P, *T| T.* = P.?;
+ return @Tuple(&types);
+}
+
+/// What `f` answers.
+pub fn Ret(comptime f: Fn) type {
+ return @typeInfo(Of(f)).@"fn".return_type.?;
+}
+
+fn Of(comptime f: Fn) type {
+ return @typeInfo(@typeInfo(@FieldType(VTable, @tagName(f))).optional.child).pointer.child;
+}
+
+/// Whether this host has `f`.
+pub fn has(h: Host, comptime f: Fn) bool {
+ return @field(h.vtable.*, @tagName(f)) != null;
+}
+
+/// Which functions it has, a bit each in the table's order.
+pub fn mask(h: Host) u64 {
+ var m: u64 = 0;
+ inline for (@typeInfo(VTable).@"struct".field_names, 0..) |name, i| {
+ if (@field(h.vtable.*, name) != null) m |= @as(u64, 1) << i;
+ }
+ return m;
+}
+
+/// `f(args)` of this host; null: it has no such function.
+pub inline fn call(h: Host, comptime f: Fn, args: Args(f)) ?Ret(f) {
+ const func = @field(h.vtable.*, @tagName(f)) orelse return null;
+ return @call(.auto, func, .{h.ctx} ++ args);
+}
diff --git a/dev/file_watch.zig b/dev/file_watch.zig
index 58229d90..c575f436 100644
--- a/dev/file_watch.zig
+++ b/dev/file_watch.zig
@@ -761,7 +761,7 @@ pub fn identify(io: std.Io, path: []const u8) !Identity {
}
test "a restored file is watched again: one clean takes what its file became since the dump, one unsaved keeps its text" {
- if (comptime !supported or !filesystem.platform_has_fs) return;
+ if (comptime !supported) return;
const io = std.testing.io;
const gpa = std.testing.allocator;
for ([_]bool{ false, true }) |dirty| {
@@ -803,7 +803,7 @@ test "a restored file is watched again: one clean takes what its file became sin
}
test "a Zerox twin's save wakes its other twin's watch, which says nothing: their text is the file's already" {
- if (comptime !supported or !filesystem.platform_has_fs) return;
+ if (comptime !supported) return;
const io = std.testing.io;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
@@ -835,7 +835,7 @@ test "a Zerox twin's save wakes its other twin's watch, which says nothing: thei
}
test "ordinary file watches still reconcile changes between open and watch" {
- if (comptime !supported or !filesystem.platform_has_fs) return;
+ if (comptime !supported) return;
const io = std.testing.io;
const gpa = std.testing.allocator;
var tmp = std.testing.tmpDir(.{});
@@ -870,7 +870,7 @@ test "ordinary file watches still reconcile changes between open and watch" {
}
test "a kind's pane whose file changed between its open and its watch opens again from it" {
- if (comptime !supported or !filesystem.platform_has_fs) return;
+ if (comptime !supported) return;
const io = std.testing.io;
const gpa = std.testing.allocator;
var tmp = std.testing.tmpDir(.{});
@@ -899,7 +899,7 @@ test "a kind's pane whose file changed between its open and its watch opens agai
}
test "explicit OS directory watches refresh prefix-preserving listings" {
- if (comptime !supported or !filesystem.platform_has_fs) return;
+ if (comptime !supported) return;
const gpa = std.testing.allocator;
const core = try pardes.Pardes.init(gpa, .{ .tty_only = true });
defer core.deinit();
@@ -1012,7 +1012,7 @@ test "theme watch reloads valid ZON and keeps the last theme across a bad save"
}
test "a watched file deleted wakes the watch at once, and its pane says so" {
- if (comptime !supported or !filesystem.platform_has_fs or builtin.os.tag != .linux) return;
+ if (comptime !supported or builtin.os.tag != .linux) return;
const io = std.testing.io;
const gpa = std.testing.allocator;
var tmp = std.testing.tmpDir(.{});
@@ -1045,7 +1045,7 @@ test "a watched file deleted wakes the watch at once, and its pane says so" {
}
test "a session's watches: a marked file's change posted to the queue, the reader ended at the end" {
- if (comptime !supported or !filesystem.platform_has_fs) return;
+ if (comptime !supported) return;
const io = std.testing.io;
const gpa = std.testing.allocator;
var tmp = std.testing.tmpDir(.{});
diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig
index 72ad1eed..201c23df 100644
--- a/dev/gui/gui.zig
+++ b/dev/gui/gui.zig
@@ -1343,7 +1343,7 @@ const Client = struct {
defer cl.lock.unlock(cl.io);
for (cl.inbox.items) |msg| switch (msg) {
.unit, .screen, .refused, .blob => |b| std.heap.c_allocator.free(b),
- .checked => {},
+ .checked, .ended, .left => {},
};
cl.inbox.clearRetainingCapacity();
}
@@ -1428,6 +1428,12 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_
.done => {},
.gone => Said.no(io, "'{s}' let this client go (a Detach in it, or the session's end)", .{to.session}),
.failed => Said.no(io, "{s}", .{start.said()}),
+ .left => {
+ var said: [600]u8 = undefined;
+ std.Io.File.stderr().writeStreamingAll(io, std.fmt.bufPrint(&said, "pardes-gui: detached from '{s}', which is still running; come back with `pardes-gui attach {s}`\n", .{ to.session, to.session }) catch "pardes-gui: detached\n") catch {};
+ std.process.exit(0);
+ },
+ .ended => |code| std.process.exit(code),
}
}
diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig
index 86956eb5..e5e28f6e 100644
--- a/dev/tui/tui.zig
+++ b/dev/tui/tui.zig
@@ -700,7 +700,7 @@ const Tty = struct {
while (t.loop.tryEvent() catch null) |ev| switch (ev) {
.said => |msg| switch (msg) {
.unit, .screen, .refused, .blob => |b| std.heap.c_allocator.free(b),
- .checked => {},
+ .checked, .ended, .left => {},
},
.paste => |b| t.sh.gpa.free(@constCast(b)),
else => {},
@@ -789,6 +789,22 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8,
screen.leave();
Said.no(io, "'{s}' let this client go (a Detach in it, or the session's end)", .{session});
},
+ .left => {
+ screen.leave();
+ var said: [600]u8 = undefined;
+ std.Io.File.stderr().writeStreamingAll(io, std.fmt.bufPrint(&said, "pardes: detached from '{s}', which is still running; come back with `pardes attach {s}`\n", .{ session, session }) catch "pardes: detached\n") catch {};
+ std.process.exit(0);
+ },
+ .ended => |code| {
+ screen.leave();
+ // A pair's client is its session's parent: its status once it
+ // is gone, as a terminal's job ends with its program.
+ if (opts.pair != null) {
+ var status: c_int = 0;
+ while (libc.waitpid(@intCast(start.joined.pid), &status, 0) < 0 and libc.errno(-1) == .INTR) {}
+ }
+ std.process.exit(code);
+ },
.failed => {
screen.leave();
Said.no(io, "{s}", .{start.said()});
@@ -949,7 +965,6 @@ const Own = struct {
.test_clock = host_io.testClock(),
.peers = &l.peers,
.ptys = &l.ptys,
- .session = l,
};
const sh = &o.sh;
sh.screen = o.screen;
@@ -1077,9 +1092,6 @@ const Shell = struct {
/// The session's ptys (runtime/session.zig's); a client's, an empty
/// table over an empty queue.
ptys: *host_io.Ptys,
- /// The session's loop (its `watch`, the daemon's notes); a client's
- /// and a test's, none.
- session: ?*Own.Session = null,
/// What `takeQueue` takes off the ptys' queue, and whether the loop
/// was woken for it since it last did (one wake, not one a read ahead
/// of the terminal's keys in the loop's queue).
@@ -1150,17 +1162,9 @@ const Shell = struct {
}
fn host(s: *Shell) host_io.Host {
- return .{ .ctx = s, .vtable = if (comptime pardes.isolated) &isolated_vtable else &vtable };
+ return .{ .ctx = s, .vtable = &vtable };
}
- const isolated_vtable: host_io.Host.VTable = .{
- .wait_input = waitInput,
- .now = clockNow,
- .present = presentFrame,
- .post_present = postPresent,
- .poll_frame = ownFrame,
- };
-
const vtable: host_io.Host.VTable = .{
.wait_input = waitInput,
.now = clockNow,
@@ -1224,10 +1228,10 @@ const Shell = struct {
/// and the shell has its terminal again), the session left running.
fn detach(ctx: ?*anyopaque) void {
const s = of(ctx);
- // A replica client's: its link ends.
+ if (!daemon.kept()) return s.core.reportFailure(s.core.view().active, "Detach: no pardes daemon lists this session (it is its terminal's job)");
+ // A replica client's: its last word, and its link ends.
if (s.peers.detach(s.core.live)) return;
if (s.detached()) return s.core.reportFailure(s.core.view().active, "Detach: detached already (no terminal of its own)");
- if (!daemon.kept()) return s.core.reportFailure(s.core.view().active, "Detach: no pardes daemon lists this session (it is its terminal's job)");
s.leaveTerminal();
}
@@ -1535,10 +1539,7 @@ const Shell = struct {
return true;
}
// The terminal went: a session the daemon keeps carries on
- // without it, to be attached again. Gone before the first
- // frame, the reader that takes the daemon's `ok` (kept
- // waits on it) is not started yet: started here.
- if (s.session) |l| l.watch();
+ // without it, to be attached again.
if (daemon.kept()) {
if (!s.detached()) s.leaveTerminal();
return true;
@@ -1561,10 +1562,10 @@ const Shell = struct {
};
if (echo) s.focused_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds);
c.take(said);
- if (said == .refused) return true;
+ if (said == .refused or said == .ended or said == .left) return true;
} else switch (said) {
.unit, .screen, .refused, .blob => |b| std.heap.c_allocator.free(b),
- .checked => {},
+ .checked, .ended, .left => {},
},
.link_gone => if (s.client) |c| {
c.link.quit = true;
@@ -2359,6 +2360,22 @@ test "an ESC read by itself is the Escape key at once" {
t.vx.caps.kitty_keyboard = false;
}
+test "an Escape read with the click after it is the Escape key, then the click" {
+ var t: TestInput = undefined;
+ try t.init();
+ defer t.deinit();
+ // A busy session reads them in one: no terminal sends Alt on a mouse
+ // report as an ESC before it (it is in the report's button).
+ var reader: TestReader = .{ .parts = &.{"\x1b\x1b[<1;105;9M"} };
+ try readInput(&t.loop, &reader, &t.vx, &t.feed);
+ try std.testing.expectEqual(.winsize, std.meta.activeTag((try t.loop.tryEvent()).?));
+ const escape = (try t.loop.tryEvent()).?.key_press;
+ try std.testing.expectEqual(vaxis.Key.escape, escape.codepoint);
+ try std.testing.expect(!escape.mods.alt);
+ try std.testing.expectEqual(.mouse, std.meta.activeTag((try t.loop.tryEvent()).?));
+ try std.testing.expect(try t.loop.tryEvent() == null);
+}
+
test "a frame's answer is taken wherever the reads cut it, and never typed" {
const gpa = std.testing.allocator;
var t: TestInput = undefined;
diff --git a/docs/next-editor.md b/docs/next-editor.md
index e7168256..4b62f6b0 100644
--- a/docs/next-editor.md
+++ b/docs/next-editor.md
@@ -72,7 +72,7 @@ registers before it writes anything. A ring never refuses: it drops its
oldest snapshots, never part of one (an undo ring holds at least one whole
text, checked at compile time).
-**Measured** (test/lib `zig build bench`, a text in C's shape, a key typed
+**Measured** (test/consumer `zig build bench`, a text in C's shape, a key typed
into its middle, 200 keys, this machine): a key at 1, 16, 64 KiB is 13,
173 and 692 µs in Debug (270k, 3.1M, 12.2M instructions) and 0.7, 7.7 and
30 µs in ReleaseFast: the 64 KiB key is 4% of a 16 ms frame in Debug. A
@@ -82,7 +82,7 @@ text's and the cursor's); the first after a jump moves the gap, 3, 5 and
optimised in every mode): once a changed key, not a frame, so no
incremental re-parse.
-A package taking the editor (test/lib) compiles cold in 6.4 s (126e9
+A package taking the editor (test/consumer) compiles cold in 6.4 s (126e9
instructions), an edit of its own file in 0.95 s plainly and 0.09-0.11 s
under `--watch -fincremental`. pardes itself: core-test's full recompile
238.8e9 instructions before and after; the typing cells of `zig build
diff --git a/docs/next-run.md b/docs/next-run.md
index 74eab197..c2d3488b 100644
--- a/docs/next-run.md
+++ b/docs/next-run.md
@@ -56,11 +56,11 @@ work` (or `pardes-gui attach work`) is a client of the detached session,
its own process in this terminal or window. What differs from having the
session's own frontend back: the client is a second process (a terminal's
10-16 MB, a window's about 110 MB); an addon that is not plain runs in the
-session alone (its panes show a line saying so); its Detach, or its
-terminal closing, ends the client with "'work' let this client go" and exit
-1, where the stub said "detached from 'work'" and exit 0 (the last word a
-session sends its client, and exit codes, are the next steps: "B" in
-`.scratch/sketch/reports/pardes-last-step-design.md`).
+session alone (its panes show a line saying so); its Detach ends the
+client with "detached from 'work', which is still running" and exit 0, as
+the stub's did: the session's last word on a link says which of two things
+happened, `left` (a Detach in that client) or `ended` with the session's
+exit code, which the client exits with.
## What it removed
@@ -212,6 +212,3 @@ session takes back.
own (the daemon's list, and so /sessions, still says `attached`, a wire
word). After the change that frontend can only be the first one: is
"has a frontend" the word, or "with its first frontend"?
-- A client's Detach exits 1 with "let this client go", where the stub's
- said "detached from" and exited 0: the session's last word to a client
- (step B of the last-step design) would let it say which.
diff --git a/docs/next-terminal.md b/docs/next-terminal.md
index ad21ef9b..a34fc0f2 100644
--- a/docs/next-terminal.md
+++ b/docs/next-terminal.md
@@ -161,7 +161,7 @@ The ptys stay host resources:
- The records the terminal writes (cells, placements) live in the interface module, or in a leaf module surface.zig's types are moved into. surface.zig today imports `pardes.zig` (surface.zig:3), so its cell types have to be lifted out.
- **Registration.**
- main.zig hands the core `&term.ops` (`Pardes.Options.terminal`, or one global set at start beside `pardes.turn`).
- - Every root that builds a product imports `term`: the exe, the static build, `run-isolated`, the gui.
+ - Every root that builds a product imports `term`: the exe, the static build, the gui.
- `core_module` does not. build.zig's `wireCore` stops giving it ghostty-vt, wuffs and zstbi, and core-test's link loses `-lc++`.
- **The no-terminal core.** A core with no terminal ops (only a test can build one) boots to a scratch pane and says once "no terminal in this build". Words that make terminals (`Term`, `Repl`, an exec with no idle shell) refuse in words. `takesCommandLine` is false.
- **The test fixtures.** This is decided at Phase 1 from the count of tests that need a real shell, as opposed to the ones that merely boot one:
diff --git a/docs/typ/building.typ b/docs/typ/building.typ
index 8bfcb85b..d4732fa9 100644
--- a/docs/typ/building.typ
+++ b/docs/typ/building.typ
@@ -60,7 +60,7 @@ must share with its session; `pardes --help` lists every flag.
[`-Dplatform`], [`tui`, `gui`, `macos`; absent: the tui and SDL shells together, installed into `~/.local`],
[`-Dpdf`], [bool: build the pdf addon, fetching MuPDF the first time; default on once MuPDF is fetched, and off Linux],
[`-Djpx`], [bool, `true`: JPEG 2000, and with it scanned PDFs],
- [`-Dtree-sitter`], [`disabled`, `zig`, `minimal`, `full`; `full`],
+ [`-Dgrammars`], [the tree-sitter grammars compiled in: `none` (the runtime alone), `minimal` (C, C++ and Zig) or `full` (all of them; the default)],
[`-Dembed-sources`], [bool, `false`: serve the sources under #file("/src")],
[`-Dhome-install`], [bool: a bare `zig build` also copies the binaries into `~/.local/bin` and the addon steps theirs into `$XDG_DATA_HOME/pardes/addons`, default true; with `-Dplatform` only `true` copies, and the addons alone],
[`-Dstamp-commit`], [bool: the git commit in `--version` and crash records; on for release builds and the `~/.local` install],
@@ -92,23 +92,50 @@ moves an anchor fails that file's step. Each table says why, edit by edit.
== As a library <library>
-A Zig package that depends on pardes is given one module and nothing of
-the editor: `pardes-syntax` (`core/lib_syntax.zig`), for a program that
-draws source text itself and wants it parsed and coloured as pardes has
-it.
+As `build.zig`'s head comment says it, word for word:
+
+A package that depends on pardes is given its syntax, `pardes-syntax`
+(`core/lib_syntax.zig`):
```
-// build.zig.zon
-.pardes = .{ .path = "../pardes" },
-// build.zig
const pardes = b.dependency("pardes", .{
.target = target,
.optimize = optimize,
- .@"tree-sitter" = .minimal,
+ .grammars = .minimal,
});
exe.root_module.addImport("pardes-syntax", pardes.module("pardes-syntax"));
```
+and, when it asks, the text pane, `pardes-editor`
+(`core/lib_editor.zig`), here with a grammar of its own handed in at
+run time:
+
+```
+const pardes = b.dependency("pardes", .{
+ .target = target,
+ .optimize = optimize,
+ .grammars = .none,
+ .editor = true,
+});
+exe.root_module.addImport("pardes-editor", pardes.module("pardes-editor"));
+```
+
+`.grammars`: the tree-sitter grammars compiled in: `none` (the runtime
+alone), `minimal` (C, C++ and Zig) or `full` (all of them; the default).
+`.editor`: exports `pardes-editor` besides `pardes-syntax`, and with it
+fetches uucode, mvzr and vaxis.
+
+Every dependency but tree-sitter's runtime is lazy in the manifest, so
+such a package fetches what it asked for and nothing else.
+`pardes-editor` has `pardes-syntax` in it as `.syntax`: a file belongs
+to one module, so a package imports one of the two. `test/consumer` is
+such a package, with both shapes; `lib-test`, which `unit-test` runs,
+builds and runs it.
+
+`build.zig.zon` names pardes by its path: `.pardes = .{ .path = "../pardes" }`.
+
+=== The syntax
+
It is the editor's own code under the names it has there. A language is
told by a path's extension, as in the editor, and `pathFor` gives a path
for a language's name.
@@ -122,35 +149,21 @@ for a language's name.
[`start`, `stop`], [tree-sitter's allocator, and the end of the parsers kept per language],
)
-The `tree-sitter` option is the build's own: `zig`, `minimal` (C, C++
-and Zig) or `full`, the default. Every dependency but tree-sitter's
-runtime is lazy in the manifest, so the package fetches the runtime and
-its set's grammars and compiles those alone; pardes's own build asks for
-what it is missing in one round. Zig still unpacks a lazy package whose
-archive its global cache already holds; `--pkg-dir` (or `ZIG_LOCAL_PKG_DIR`)
-at pardes's `zig-pkg` shares the one copy. What a pane measures stays
-out: a cell's width is vaxis's and uucode's, and a tab is
-`config.tab_width` cells wherever it stands. `test/lib` is such a
-package, and `zig build lib-test` builds and runs it.
+pardes's own build takes `-Dgrammars` too, and asks for what it is
+missing in one round. Zig still unpacks a lazy package whose archive its
+global cache already holds; `--pkg-dir` (or `ZIG_LOCAL_PKG_DIR`) at
+pardes's `zig-pkg` shares the one copy. What a pane measures stays out: a
+cell's width is vaxis's and uucode's, and a tab is `config.tab_width`
+cells wherever it stands.
=== The editor
`pardes-editor` (`core/lib_editor.zig`) is the text pane as a library:
helix's keys on a text kept in memory, no files, commands, builtins,
-prompts or views. A package asks for it, and is then given uucode, mvzr
-and vaxis's grapheme width besides; one that does not fetches nothing more.
-It has `pardes-syntax` in it as `.syntax`: a file belongs to one module, so
-a package imports one of the two.
-
-```
-const pardes = b.dependency("pardes", .{
- .target = target,
- .optimize = optimize,
- .@"tree-sitter" = .minimal,
- .editor = true,
-});
-exe.root_module.addImport("pardes-editor", pardes.module("pardes-editor"));
-```
+prompts or views. Of vaxis it takes the grapheme width alone. With
+`.grammars = .none` it has no grammar of pardes's: a program hands its
+own in at run time (`Language`, below), linking the grammar's parser
+itself, as `test/consumer` does with C's.
The editor is a value of plain data, `Editor(capacity)`: no pointer, no
allocator, every capacity in its type, so a program keeps it where it
@@ -186,7 +199,7 @@ zig build kitty-harness kitty graphics through a pane end to end (a fake kitt
kitten icat and chafa too when installed)
zig build syntax-test tree-sitter tests without building the editor
zig build syntax deterministic per-byte highlighting snapshots
-zig build lib-test the library, from a package that depends on pardes (test/lib);
+zig build lib-test the library, from a package that depends on pardes (test/consumer);
unit-test runs it too
zig build hxlib helix's cases on the library's editor (-- --parity: against the file pane)
zig build behaviour-test behaviour through the 9P tree, in process (test/behaviour/),
diff --git a/docs/typ/command-line.txt b/docs/typ/command-line.txt
index 3c73fed4..0ced145f 100644
--- a/docs/typ/command-line.txt
+++ b/docs/typ/command-line.txt
@@ -95,8 +95,10 @@ See also: ps, attach
Start a session here, even in a pane of another: in this terminal for
pardes, a window for pardes-gui, or with --detach none until one
-attaches. Bare `pardes` takes the same flags, and starts one unless
-it is in a pane (where it hands its FILE to that session).
+attaches, which returns once the session runs and prints its name.
+Bare `pardes` takes the same flags, and starts one unless it is in a
+pane (where it hands its FILE to that session); its --detach is the
+session itself, until it ends (a supervisor's way).
Usage:
pardes new [flags] [FILE]
diff --git a/runtime/9p_io.zig b/runtime/9p_io.zig
index bcb0f81b..aaca377d 100644
--- a/runtime/9p_io.zig
+++ b/runtime/9p_io.zig
@@ -1896,7 +1896,9 @@ pub const Client = struct {
/// same open, as /pane/new answers its own open: a session's last
/// answer, from another client, can never be what comes back. `exec
/// 3<>file`. `more` (`pardes -`'s text after its /pager line) goes in
- /// Twrites at rising offsets, each answer giving the next its budget.
+ /// Twrites at rising offsets. Untimed once connected: the answer comes
+ /// when the session's step has run, however long a loaded machine
+ /// takes over 256 MiB, and a session that died ends the connection.
pub fn ask(gpa: std.mem.Allocator, dial: []const u8, path: []const u8, request: []const u8, more: []const u8) ![]u8 {
if (comptime !supported) return error.Unsupported;
var names: [max_depth][]const u8 = undefined;
@@ -1905,6 +1907,7 @@ pub const Client = struct {
errdefer said = remote;
const s = try startSession(dial, path);
defer endSession(s, false);
+ s.deadline = std.math.maxInt(i64);
const fid = try walkTo(s, names[0..n], &remote);
_ = try s.ask(.{ .open = .{ .fid = fid, .mode = ninep.ordwr } }, &remote);
var written: usize = 0;
@@ -1914,7 +1917,6 @@ pub const Client = struct {
const count = (try s.ask(.{ .write = .{ .fid = fid, .offset = written, .data = chunk } }, &remote)).write;
if (count == 0 or count > chunk.len) return Error.Botch;
written += count;
- s.deadline = nowMs() +| write_budget_ms;
}
var out: std.ArrayList(u8) = .empty;
errdefer out.deinit(gpa);
diff --git a/runtime/client.zig b/runtime/client.zig
index 544be588..1314d3fb 100644
--- a/runtime/client.zig
+++ b/runtime/client.zig
@@ -109,9 +109,10 @@ pub const Start = struct {
}
};
-/// How a client's joins ended: it quit, the session let it go, or it could
-/// not join again (`Start.said`).
-pub const Ended = enum { done, gone, failed };
+/// How a client's joins ended: it quit, the session let it go, it could
+/// not join again (`Start.said`), it left the session running (a Detach in
+/// it), or the session ended, with its code.
+pub const Ended = union(enum) { done, gone, failed, left, ended: u8 };
pub fn Loop(comptime Frontend: type) type {
return struct {
@@ -170,11 +171,14 @@ pub fn Loop(comptime Frontend: type) type {
// What it made since it joined, kept for its next start.
if (s.have) |h| h.keep(s.r.core());
s.r.deinit();
+ if (link.left) return .left;
+ if (link.ended) |code| return .{ .ended = code };
return if (link.gone) .gone else .done;
}
// The session again, the core it leaves held meanwhile: its
// blobs are not sent again.
- s.r = replica.join(s.gpa, &s.joined, s.dial.path, s.dial.session, s.o, s.have, &s.why, s.r) orelse return .failed;
+ s.r = replica.join(s.gpa, &s.joined, s.dial.path, s.dial.session, s.o, s.have, &s.why, s.r) orelse
+ return if (replica.ended(&s.why)) .gone else .failed;
}
}
diff --git a/runtime/daemon.zig b/runtime/daemon.zig
index 80e1cc09..9b566e60 100644
--- a/runtime/daemon.zig
+++ b/runtime/daemon.zig
@@ -290,10 +290,11 @@ fn hello(fd: c_int, k: Kind, pid: libc.pid_t, named: []const u8, detached: bool)
/// This session's registration (`register`), which forkShell and the hosts
/// tell of their ptys; -1 with none (no daemon, or PARDES_DAEMON=off).
pub var link: c_int = -1;
-/// The daemon said `ok` to the hello, and the link has not ended since;
-/// `gone` once it has ended for good (`readNotes`).
-var up = std.atomic.Value(bool).init(false);
-var gone = std.atomic.Value(bool).init(false);
+/// The hello's answer, as the reader took it (`readNotes`): `up`, the
+/// daemon said `ok` and the link has not ended since; `gone`, it has ended
+/// for good; `asked` until either (and while a new daemon is dialled).
+const Answer = enum(u32) { asked, up, gone };
+var answer = std.atomic.Value(Answer).init(.asked);
/// The session is ending (`quit`): its link's end is no daemon's death.
var quitting = std.atomic.Value(bool).init(false);
/// A new daemon took the hello since the last one died: the rest of what
@@ -306,6 +307,8 @@ var detached_now = std.atomic.Value(bool).init(false);
var name_buf: [128]u8 = undefined;
var name_len: usize = 0;
var reader: ?std.Thread = null;
+/// Where the reader hands each note (`notesTo`).
+var notes: ?struct { ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) void } = null;
pub fn name() []const u8 {
return name_buf[0..name_len];
@@ -314,12 +317,22 @@ pub fn name() []const u8 {
/// Whether a daemon keeps this session: what Detach, and a terminal's end,
/// need, or the session would be left where nothing can attach to it. A
/// daemon just started answers the hello once it runs, so this waits for
-/// that answer (up to 2 s): never on a startup's path, only on those two.
+/// that answer, or the link's end, whenever they come: never on a startup's
+/// path, only on those two. The reader takes it: started here if the first
+/// frame has not started it yet.
pub fn kept() bool {
if (link < 0) return false;
- var waited: u32 = 0;
- while (!up.load(.acquire) and !gone.load(.acquire) and waited < 2000) : (waited += 1) sleepMs(1);
- return up.load(.acquire);
+ watch();
+ if (reader == null) return false;
+ const io = std.Io.Threaded.global_single_threaded.io();
+ while (answer.load(.acquire) == .asked) io.futexWaitUncancelable(Answer, &answer.raw, .asked);
+ return answer.load(.acquire) == .up;
+}
+
+/// The reader's word on the hello's answer, to `kept` waiting on it.
+fn settle(a: Answer) void {
+ answer.store(a, .release);
+ std.Io.Threaded.global_single_threaded.io().futexWake(Answer, &answer.raw, 1);
}
/// The name a session goes by: its 9P socket's (`--9p=`, `--detach=`), else
@@ -438,11 +451,18 @@ pub const Note = union(enum) {
pub const Joining = struct { fd: c_int, view: ?u8 = null };
-/// Hands every note the daemon sends on to `deliver`, on a thread of its
+/// Where every note the daemon sends goes, once `watch` has started the
+/// reader: the session's, before its first step.
+pub fn notesTo(ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) void) void {
+ notes = .{ .ctx = ctx, .deliver = deliver };
+}
+
+/// Hands every note the daemon sends on (`notesTo`), on a thread of its
/// own, until the link ends (`quit`). Called each loop: started once.
-pub fn watch(ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) void) void {
+pub fn watch() void {
+ const n = notes orelse return;
if (link < 0 or reader != null) return;
- reader = std.Thread.spawn(.{}, readNotes, .{ link, ctx, deliver }) catch null;
+ reader = std.Thread.spawn(.{}, readNotes, .{ link, n.ctx, n.deliver }) catch null;
}
fn readNotes(fd: c_int, ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) void) void {
@@ -452,7 +472,7 @@ fn readNotes(fd: c_int, ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, no
var words = std.mem.tokenizeScalar(u8, got.words, ' ');
const verb = words.next() orelse "";
if (std.meta.stringToEnum(enum { ok, replica, adopted }, verb)) |v| switch (v) {
- .ok => up.store(true, .release),
+ .ok => settle(.up),
.replica => {
const view = std.fmt.parseInt(u8, words.next() orelse "", 10) catch null;
if (got.nfds >= 1) deliver(ctx, .{ .replica = .{ .fd = got.fds[0], .view = view } });
@@ -482,12 +502,12 @@ fn readNotes(fd: c_int, ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, no
// link's end is what wakes this, never a timer. One that never took
// it (another build's daemon), or the session's own end, is not:
// an end begun while it dialled finds the new link (`quit`).
- if (!up.swap(false, .acq_rel) or quitting.load(.acquire) or !redial(fd) or quitting.load(.acquire)) break;
+ if (answer.swap(.asked, .acq_rel) != .up or quitting.load(.acquire) or !redial(fd) or quitting.load(.acquire)) break;
retell.store(true, .release);
deliver(ctx, .relinked);
}
// Not kept, until the session's end.
- gone.store(true, .release);
+ settle(.gone);
}
/// A new connection in the place of `fd`, the link (its number kept, so
@@ -600,6 +620,12 @@ fn stubWait(session: libc.pid_t, pipe: c_int) noreturn {
const said = buf[0..len];
const out = std.Io.File.stderr();
const io = std.Io.Threaded.global_single_threaded.io();
+ // `new --detach`'s session runs (`launched`): its name, for a script.
+ if (said.len > 0 and said[0] == 'r') {
+ var text: [520]u8 = undefined;
+ std.Io.File.stdout().writeStreamingAll(io, std.fmt.bufPrint(&text, "{s}\n", .{said[1..]}) catch said[1..]) catch {};
+ libc._exit(0);
+ }
if (said.len > 0 and said[0] == 'd') {
var text: [700]u8 = undefined;
const who = said[1..];
@@ -695,6 +721,57 @@ pub fn forkSession(conn: c_int) ?void {
stubWait(pid, pipe[0]);
}
+/// `pardes new --detach`: the session forked off in a session of its own,
+/// its stdin /dev/null, and this process its stub until the session runs
+/// (`launched`): it then prints the name and exits 0, or with the
+/// session's status if it ended first. Returns in the session, called
+/// `named` (else by its pid); when no fork can be made, here, which is
+/// then the session.
+pub fn launch(named: []const u8) void {
+ var pipe: [2]c_int = undefined;
+ if (libc.pipe(&pipe) != 0) return;
+ ninep_io.setCloexec(pipe[0]);
+ ninep_io.setCloexec(pipe[1]);
+ const pid = libc.fork();
+ if (pid < 0) {
+ _ = libc.close(pipe[0]);
+ _ = libc.close(pipe[1]);
+ return;
+ }
+ if (pid == 0) {
+ _ = libc.close(pipe[0]);
+ _ = libc.setsid();
+ const null_fd = libc.open("/dev/null", .{ .ACCMODE = .RDWR, .CLOEXEC = true }, @as(libc.mode_t, 0));
+ if (null_fd >= 0) _ = libc.dup2(null_fd, 0);
+ if (null_fd > 0) _ = libc.close(null_fd);
+ stub = pipe[1];
+ launching = true;
+ setName(named);
+ return;
+ }
+ _ = libc.close(pipe[1]);
+ stubWait(pid, pipe[0]);
+}
+
+/// Forked by `launch`, and its stub not told yet.
+var launching = false;
+
+/// The session of a `new --detach` runs: registered (the daemon took its
+/// hello, when there is one) and listening. Its stub told, with its name;
+/// its stdout and stderr, still the launch's until now, let go.
+pub fn launched() void {
+ if (!launching) return;
+ launching = false;
+ _ = kept();
+ tellStub(stub, "r{s}", .{name()});
+ stub = -1;
+ const null_fd = libc.open("/dev/null", .{ .ACCMODE = .RDWR, .CLOEXEC = true }, @as(libc.mode_t, 0));
+ if (null_fd < 0) return;
+ _ = libc.dup2(null_fd, 1);
+ _ = libc.dup2(null_fd, 2);
+ if (null_fd > 2) _ = libc.close(null_fd);
+}
+
// ---- the daemon ----
const Conn = struct {
diff --git a/runtime/main.zig b/runtime/main.zig
index a791ffec..be2aa54b 100644
--- a/runtime/main.zig
+++ b/runtime/main.zig
@@ -323,8 +323,10 @@ const cmds = std.EnumArray(Cmd, Doc).init(.{
.doc =
\\Start a session here, even in a pane of another: in this terminal for
\\pardes, a window for pardes-gui, or with --detach none until one
- \\attaches. Bare `pardes` takes the same flags, and starts one unless
- \\it is in a pane (where it hands its FILE to that session).
+ \\attaches, which returns once the session runs and prints its name.
+ \\Bare `pardes` takes the same flags, and starts one unless it is in a
+ \\pane (where it hands its FILE to that session); its --detach is the
+ \\session itself, until it ends (a supervisor's way).
,
.examples = &.{
.{ "pardes new", "a session here, its shell pane in tty mode" },
@@ -1157,6 +1159,8 @@ fn nativeMain(std_init: std.process.Init) !void {
const resuming = upgrade.resumed != null;
var session_only = true;
var new_session = false;
+ // `pardes new`: with --detach it returns once the session runs.
+ var new_verb = false;
var explicit_tty = false;
var detach: ?[]const u8 = null;
var attach: ?[]const u8 = null;
@@ -1168,6 +1172,7 @@ fn nativeMain(std_init: std.process.Init) !void {
if (!resuming and args.len > 1) if (std.meta.stringToEnum(Cmd, args[1])) |cmd| switch (cmd) {
.new => {
new_session = true;
+ new_verb = true;
i = 2;
},
.attach => {
@@ -1282,12 +1287,6 @@ fn nativeMain(std_init: std.process.Init) !void {
}
opts.tty_only = explicit_tty or session_only;
opts.mounts = mounts[0..mounts_len];
- // `zig build run-isolated` with nothing named: something to look at on
- // arrival, read out of the binary itself.
- if (pardes.isolated and positional == null) {
- session_only = false;
- positional = "src/pardes.zig";
- }
if (detach != null and attach != null)
badArgs(init.io, "--detach and --attach are opposites: one runs the session, the other joins one", .{});
// --wait waits on the pane a FILE opens: with none there is nothing to
@@ -1537,6 +1536,9 @@ fn nativeMain(std_init: std.process.Init) !void {
// socket holds already (a plain session is named by its pid too).
if (name.len != 0 and !resuming and ninep_io.taken(name)) die(init.io, "a session named {s} is already running", .{name});
if (opts.ninep_name.len == 0) opts.ninep_name = name;
+ // `new --detach` forks the session and returns once it runs; the
+ // flag alone is the session itself (a supervisor's, a harness's).
+ if (new_verb and !resuming) daemon.launch(opts.ninep_name);
// Said where it was started (stderr, as the log says it): no pane
// anyone sees would show it. The session runs on, with no 9P.
var pid_buf: [16]u8 = undefined;
@@ -1565,6 +1567,11 @@ fn nativeMain(std_init: std.process.Init) !void {
};
detached = if (pardes.platform == .gui) !rec.window else rec.nttys == 0;
daemon.resumeLink(rec.link, rec.stub, kind, opts.ninep_name, detached);
+ } else if (pardes.platform == .tui and detach == null and std.c.getenv("PARDES_PAIR") != null) {
+ // The last step's way, behind its variable until it is the default:
+ // this terminal a client of a session forked off for it (`pair`).
+ pair(init, &opts);
+ term = .detached;
} else if (daemon.wanted()) {
if (detach != null or pardes.platform == .gui) {
_ = daemon.register(null, kind, opts.ninep_name, detach != null);
@@ -1701,6 +1708,54 @@ fn commOf(io: std.Io, pid: []const u8, buf: *[64]u8) []const u8 {
return std.mem.trimEnd(u8, std.Io.Dir.cwd().readFile(io, path, buf) catch return "", "\n");
}
+/// PARDES_PAIR: `pardes` in a terminal as a session and its first client
+/// over a socket pair (docs/next-run.md; the last step's design, 1.1). The
+/// daemon dialled first, as for a stub; then a fork: the parent the CLIENT
+/// (the shell's job, the terminal its own; signals reach what draws), its
+/// first join on its end of the pair; the child the SESSION (setsid, 0, 1
+/// and 2 on /dev/null, detached), its end of the pair its first client,
+/// taken before its first effects (runtime/session.zig). Returns in the
+/// session; the client exits. No fork to be had: returns, and this process
+/// is the session, with no terminal: said by the caller's run.
+fn pair(init: std.process.Init, opts: *pardes.Options) void {
+ const conn: ?c_int = if (daemon.wanted()) daemon.connect(true) else null;
+ var fds: [2]c_int = undefined;
+ if (std.c.socketpair(std.c.AF.UNIX, std.c.SOCK.STREAM | std.c.SOCK.CLOEXEC, 0, &fds) != 0)
+ die(init.io, "no socket pair for a session and its terminal", .{});
+ // The session laid out at the terminal's size: no reflow at the join.
+ var ws: std.posix.winsize = undefined;
+ if (std.c.ioctl(0, std.posix.T.IOCGWINSZ, &ws) == 0 and ws.col > 0 and ws.row > 0) {
+ opts.cols = ws.col;
+ opts.rows = ws.row;
+ }
+ const pid = std.c.fork();
+ if (pid < 0) die(init.io, "no fork for a session and its terminal", .{});
+ if (pid == 0) {
+ _ = std.c.close(fds[1]);
+ _ = std.c.setsid();
+ const null_fd = std.c.open("/dev/null", .{ .ACCMODE = .RDWR, .CLOEXEC = true }, @as(std.c.mode_t, 0));
+ if (null_fd >= 0) for (0..3) |i| {
+ _ = std.c.dup2(null_fd, @intCast(i));
+ };
+ if (null_fd > 2) _ = std.c.close(null_fd);
+ opts.pair = fds[0];
+ // The daemon is the client's to start; the hello is this one's.
+ daemon.startPending(false);
+ if (conn) |c| _ = daemon.register(c, .tty, opts.ninep_name, true);
+ return;
+ }
+ _ = std.c.close(fds[0]);
+ if (conn) |c| _ = std.c.close(c);
+ daemon.startPending(true);
+ var name_buf: [16]u8 = undefined;
+ const name = if (opts.ninep_name.len != 0) opts.ninep_name else std.fmt.bufPrint(&name_buf, "{d}", .{pid}) catch unreachable; // a pid fits 16
+ var sock_buf: [ninep_io.sun_path_len:0]u8 = undefined;
+ var o = opts.*;
+ o.pair = fds[1];
+ @import("dev").tui.runClient(init, o, daemon.replicaSocket(&sock_buf) orelse "", name, false) catch |err| die(init.io, "{t}", .{err});
+ std.process.exit(0);
+}
+
/// The replica client of this build's frontend: a terminal's (tui.zig) or a
/// window's (gui.zig).
fn clientOf(init: std.process.Init, opts: pardes.Options, path: []const u8, name: []const u8, far: bool) !void {
@@ -1787,8 +1842,11 @@ fn attachClient(init: std.process.Init, opts: pardes.Options, where: []const u8,
Ssh.child = pid;
Ssh.path = here;
_ = atexit(Ssh.end);
+ // Its file is there a moment before ssh listens on it: until a
+ // connect answers.
var waited: u32 = 0;
- while (std.meta.isError(std.Io.Dir.cwd().access(io, here, .{}))) : (waited += 1) {
+ const probe = while (true) : (waited += 1) {
+ if (cloud9.transport.connectFd(.{ .unix = here }, cloud9.transport.nowMs() + 100)) |fd| break fd else |_| {}
var status: c_int = 0;
if (std.c.waitpid(pid, &status, std.c.W.NOHANG) == pid) {
Ssh.child = 0;
@@ -1797,7 +1855,8 @@ fn attachClient(init: std.process.Init, opts: pardes.Options, where: []const u8,
if (waited > 3000) die(io, "--attach: ssh to {s} set up no forward in 30 s", .{where});
const ts: std.c.timespec = .{ .sec = 0, .nsec = 10 * std.time.ns_per_ms };
_ = std.c.nanosleep(&ts, null);
- }
+ };
+ _ = std.c.close(probe);
clientOf(init, opts, here, name, true) catch |err| die(io, "--attach: {t}", .{err});
std.process.exit(0);
}
diff --git a/runtime/session.zig b/runtime/session.zig
index 64846319..e4eb0300 100644
--- a/runtime/session.zig
+++ b/runtime/session.zig
@@ -100,9 +100,14 @@ pub fn Loop(comptime Frontend: type) type {
l.host = try fe.open(&l);
defer fe.close(&l);
+ daemon.notesTo(&l, note);
defer l.peers.deinit();
// Before the core goes: each client sees its link end.
defer l.peers.dropAll(l.core);
+ // A first client on the socket it was started with, before its
+ // first effects: it has every terminal from its first byte, and
+ // no reload (Core.openView).
+ if (o.pair) |fd| l.peers.join(l.core, .{ .fd = fd });
l.effects();
// ...and its shells, once a fresh session's own has a directory
// to adopt them in.
@@ -113,12 +118,17 @@ pub fn Loop(comptime Frontend: type) type {
l.ptys.start(l.core);
l.watches.start();
try fe.start(&l);
+ // A `new --detach`'s launch returns now.
+ daemon.launched();
while (!l.core.quit) {
pardes.turn.bump(&pardes.turn.restores);
try l.core.pump(l.host);
// Its unit to each replica client, and theirs taken in.
l.peers.boundary(l.core);
+ // A pair's session with no daemon ends with its last link:
+ // nothing could attach to it again.
+ if (o.pair != null and daemon.link < 0 and l.peers.count() == 0) break;
fe.sent();
upgrade.locate();
// Asked in the step (the word), done between steps: the
@@ -132,6 +142,8 @@ pub fn Loop(comptime Frontend: type) type {
if (l.core.quit) break;
if (l.core.takeRestore()) |rp| l.restore(rp);
}
+ // The clients' last word: the session ended (Exit).
+ l.peers.ended(0);
// Its serve threads read the core: they end first.
if (l.fs) |f| {
f.deinit(l.gpa);
@@ -148,7 +160,7 @@ pub fn Loop(comptime Frontend: type) type {
/// since the last one died told the shells' masters it held.
pub fn watch(l: *L) void {
if (daemon.relinked()) l.ptys.tellDaemon();
- daemon.watch(l, note);
+ daemon.watch();
}
/// The daemon's thread: an adopted shell onto the queue (taken
diff --git a/test/behaviour/panes.zig b/test/behaviour/panes.zig
index dcde9c4d..4d4c812c 100644
--- a/test/behaviour/panes.zig
+++ b/test/behaviour/panes.zig
@@ -888,7 +888,6 @@ test "panes: truncating body empties it, and a stat says the length after" {
}
test "panes: a rename colours a source its new name's language names, its text unchanged" {
- if (@import("pardes_options").grammars == .disabled) return error.SkipZigTest;
var s = try Session.initFile(std.testing.allocator, "fn check() void {}\n");
defer s.deinit();
const n = try s.focused();
diff --git a/test/behaviour/settings.zig b/test/behaviour/settings.zig
index cacee701..a6e09f35 100644
--- a/test/behaviour/settings.zig
+++ b/test/behaviour/settings.zig
@@ -158,7 +158,6 @@ test "settings: Back and Forward written to exec keep to the focused file" {
});
}
-const syntax = @import("pardes_options").grammars != .disabled;
/// The style /screen draws the cell `into` cells into the first place
/// `text` is drawn.
@@ -190,7 +189,6 @@ fn keywordsIn(s: *Session, want: []const u8) !usize {
}
test "settings: keywords stay coloured in every row a pane grows into" {
- if (!syntax) return error.SkipZigTest;
var s = try Session.initFile(std.testing.allocator, std.mem.asBytes(&@as([100][33]u8, @splat("pub fn f() void { if (true) {} }\n".*))));
defer s.deinit();
try s.write(s.at("/pane/{d}/name", .{try s.focused()}), "/resize.zig\n");
diff --git a/test/lib/bench.zig b/test/consumer/bench.zig
index 7e945064..7e945064 100644
--- a/test/lib/bench.zig
+++ b/test/consumer/bench.zig
diff --git a/test/consumer/build.zig b/test/consumer/build.zig
new file mode 100644
index 00000000..ca63bb6e
--- /dev/null
+++ b/test/consumer/build.zig
@@ -0,0 +1,42 @@
+//! A package that depends on pardes, as a program would (build.zig's head
+//! comment has its lines): pardes's `lib-test`, which `unit-test` runs,
+//! runs `zig build test` here. `pardes-syntax` with the minimal grammars,
+//! as a program that draws source text itself takes it; and
+//! `pardes-editor` with no grammar of pardes's and one of its own, C's,
+//! compiled here from the package pardes pins and handed in at run time,
+//! as sketchbook's `examples/live` takes it.
+const std = @import("std");
+
+pub fn build(b: *std.Build) void {
+ const target = b.standardTargetOptions(.{});
+ const optimize = b.standardOptimizeOption(.{});
+ const syntax = b.dependency("pardes", .{ .target = target, .optimize = optimize, .grammars = .minimal });
+ const editor = b.dependency("pardes", .{ .target = target, .optimize = optimize, .grammars = .none, .editor = true });
+ // The grammar of its own: C's, from the package pardes's manifest pins
+ // (so `--pkg-dir` at pardes's zig-pkg has it), as that package builds it.
+ const grammar = b.dependency("ts_c", .{ .target = target, .optimize = .ReleaseFast, .@"build-shared" = false }).artifact("tree-sitter-c");
+ const step = b.step("test", "colour, outline and walk a C and a Zig source through pardes's syntax, and edit a text with its editor and a grammar of this package's");
+ // A file belongs to one module: the syntax alone, and the editor (which
+ // has it as `.syntax`), each a test of its own.
+ for ([_]struct { []const u8, []const u8, *std.Build.Dependency }{ .{ "lib.zig", "pardes-syntax", syntax }, .{ "editor.zig", "pardes-editor", editor } }) |t| {
+ const mod = b.createModule(.{
+ .target = target,
+ .optimize = optimize,
+ .root_source_file = b.path(t[0]),
+ .imports = &.{.{ .name = t[1], .module = t[2].module(t[1]) }},
+ });
+ if (t[2] == editor) mod.linkLibrary(grammar);
+ step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mod })).step);
+ }
+ // What a key costs, a page count and a parse: `zig build bench -- <KiB> <keys>`.
+ const bench = b.addExecutable(.{ .name = "bench", .root_module = b.createModule(.{
+ .target = target,
+ .optimize = optimize,
+ .root_source_file = b.path("bench.zig"),
+ .imports = &.{.{ .name = "pardes-editor", .module = editor.module("pardes-editor") }},
+ }) });
+ bench.root_module.linkLibrary(grammar);
+ const run_bench = b.addRunArtifact(bench);
+ run_bench.addPassthruArgs();
+ b.step("bench", "a key typed into the library's editor at a size, its pages and a parse").dependOn(&run_bench.step);
+}
diff --git a/test/consumer/build.zig.zon b/test/consumer/build.zig.zon
new file mode 100644
index 00000000..c367775b
--- /dev/null
+++ b/test/consumer/build.zig.zon
@@ -0,0 +1,16 @@
+.{
+ .name = .pardes_consumer,
+ .version = "0.0.0",
+ .dependencies = .{
+ .pardes = .{ .path = "../.." },
+ // The grammar this package hands pardes's editor: the one pardes's
+ // own manifest pins, so `--pkg-dir` at its zig-pkg has it.
+ .ts_c = .{
+ .url = "git+https://github.com/pierrelgol/tree-sitter-c#67949e4c8dc630c18a522919f2bde2e025a0d025",
+ .hash = "tree_sitter_c-0.24.2-y5boS-htQACe3pz6jHq4tpS8dB6WIo4-zk_ct7lAjvQT",
+ },
+ },
+ .minimum_zig_version = "0.17.1",
+ .paths = .{""},
+ .fingerprint = 0xb5ce4ba417a79812,
+}
diff --git a/test/lib/editor.zig b/test/consumer/editor.zig
index 22690915..22690915 100644
--- a/test/lib/editor.zig
+++ b/test/consumer/editor.zig
diff --git a/test/lib/lib.zig b/test/consumer/lib.zig
index 7e297920..7e297920 100644
--- a/test/lib/lib.zig
+++ b/test/consumer/lib.zig
diff --git a/test/daemon.py b/test/daemon.py
index d134732b..f8402af2 100644
--- a/test/daemon.py
+++ b/test/daemon.py
@@ -25,8 +25,13 @@ private HOME and runtime directory:
`ssh -L` forwards, say), timed
python3 -B test/daemon.py --clients <pardes>
the replica clients alone
+ python3 -B test/daemon.py --launch <pardes>
+ `pardes new --detach` returns once its session runs
+ python3 -B test/daemon.py --pair <pardes>
+ PARDES_PAIR: a terminal's session and its first client
python3 -B test/daemon.py --relink <pardes>
- the daemon killed: its sessions register again with the next
+ the daemon killed: its sessions register again with the next; and
+ one stopped: an Adopt waits for its answer to the hello
python3 -B test/daemon.py --far <pardes>
the far clients and their blob cache alone, and a file by its hash
python3 -B test/daemon.py --games <pardes> <lib> [seconds]
@@ -265,8 +270,11 @@ class Replica:
is read, whole. A daemon of another replica protocol (an older
build's, across an Upgrade) is dialled again in its own."""
name = session.encode()
- self.send(0x01, struct.pack('<HQH', wire or self.WIRE, build, len(name)) + name + b'\xff')
- self.send(0x06, b'\x00')
+ # Its first word (not far) in the same write, as a client's join
+ # sends it (core/replica.zig joinOn): a refused hello's connection
+ # is closed, and a second write after it would meet that.
+ hello = struct.pack('<HQH', wire or self.WIRE, build, len(name)) + name + b'\xff'
+ self.s.sendall(struct.pack('<BI', 0x01, len(hello)) + hello + struct.pack('<BIB', 0x06, 1, 0))
tag, body = self.read()
if tag == 0x01:
pid, n = struct.unpack_from('<IH', body)
@@ -479,10 +487,10 @@ def clients(binary):
wait_for('client A out of insert mode', lambda: normal_again(ta))
wait_for('client A agrees again', lambda: agreed(root / 'a.check', seen))
assert sess.poll() is None
- # Detach typed in it: it alone goes.
+ # Detach typed in it: it alone goes, and says so (exit 0).
os.write(ta.master, b' sD')
wait_for('client A let go', lambda: a.poll() is not None, timeout=10)
- assert b'let this client go' in ta.text(), ta.text()[-300:]
+ assert a.returncode == 0 and b"detached from 'files', which is still running" in ta.text(), ta.text()[-300:]
# A third client, a shell: its keys wait for the session (a pty
# write), its output comes back in units, the same on both sides.
nine.write(f'/pane/{pane}/exec', b'Term\n')
@@ -526,6 +534,234 @@ def clients(binary):
shutil.rmtree(root, ignore_errors=True)
+def launch(binary):
+ """`pardes new --detach=NAME` returns once its session is registered
+ and listening: exit 0, the name on stdout, the session a process of its
+ own in a session of its own, listed by `ps` and answering 9P at once;
+ bare `--detach`, its pid is its name; a name taken is refused in words,
+ exit 1; `pardes --detach=NAME` (no `new`) is still the session itself;
+ nothing left behind."""
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='rl-', dir=scratch))
+ env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
+ TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
+ (root / 'config' / 'pardes').mkdir(parents=True)
+ (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
+ (root / 'notes.txt').write_text('notes\n')
+
+ def cli(*args, timeout=30):
+ return subprocess.run([binary, *args], env=env, cwd=root, capture_output=True, timeout=timeout,
+ stdin=subprocess.DEVNULL)
+
+ def status_pid(name):
+ with Client(root / f'pardes-9p-{name}.sock') as c:
+ return int(dict(line.split(maxsplit=1) for line in c.read('/status').decode().splitlines())['pid'])
+
+ try:
+ t0 = time.monotonic()
+ try:
+ out = cli('new', '--detach=work', 'notes.txt', timeout=15)
+ except subprocess.TimeoutExpired:
+ raise AssertionError(f'launch: `new --detach=work` had not returned after {time.monotonic() - t0:.1f} s')
+ took = time.monotonic() - t0
+ assert out.returncode == 0 and out.stdout == b'work\n', out
+ # Registered and listening when it returned: no wait here.
+ assert (root / 'pardes-9p-work.sock').exists(), list(root.iterdir())
+ pid = status_pid('work')
+ listed = cli('ps').stdout.decode()
+ assert f'session work {pid} (tty, detached)' in listed, listed
+ assert alive(pid) and os.getsid(pid) == pid, (pid, os.getsid(pid))
+ out = cli('new', '--detach')
+ assert out.returncode == 0 and out.stdout.strip().isdigit(), out
+ unnamed = int(out.stdout)
+ assert status_pid(str(unnamed)) == unnamed and f'session {unnamed} {unnamed} (tty, detached)' in cli('ps').stdout.decode()
+ taken = cli('new', '--detach=work')
+ assert taken.returncode == 1 and taken.stderr == b'pardes: a session named work is already running\n', taken
+ # The flag alone runs the session in this process, as a supervisor
+ # or a harness wants it.
+ fg = subprocess.Popen([binary, '--detach=fg'], env=env, cwd=root, stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
+ wait_for('the foreground session\'s socket', (root / 'pardes-9p-fg.sock').exists)
+ assert status_pid('fg') == fg.pid and fg.poll() is None
+ print(f'launch: `new --detach=work` returned 0 in {took:.2f} s with its name, session {pid} listed and listening '
+ f'in a session of its own; unnamed it said {unnamed}; a taken name refused; `--detach=fg` is its own session')
+ for name in ('work', str(unnamed), 'fg'):
+ assert cli('kill', name).returncode == 0
+ fg.wait(timeout=10)
+ wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=10)
+ print('launch: nothing left behind')
+ finally:
+ for p in processes(root):
+ try:
+ os.kill(p, signal.SIGKILL)
+ except OSError:
+ pass
+ shutil.rmtree(root, ignore_errors=True)
+
+
+def pair(binary):
+ """PARDES_PAIR: `pardes FILE` in a terminal is a session forked off for
+ it with this terminal its first client (the last step's design, 1.1):
+ the job the client, the terminal its own; the session its child, in a
+ session of its own, registered (`ps`: detached, the client listed),
+ the file drawn, keys in, the digests agreed once quiet; the session's
+ Exit ends both. With no daemon the client killed outright ends the
+ session (its last link). Nothing left behind."""
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='rp-', dir=scratch))
+ env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
+ TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1', PARDES_PAIR='1')
+ (root / 'config' / 'pardes').mkdir(parents=True)
+ (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
+ notes = root / 'notes.txt'
+ notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30)))
+ terms = []
+
+ def session_of(name):
+ sock = root / f'pardes-9p-{name}.sock'
+ wait_for(f'session {name}\'s 9P socket', sock.exists)
+ nine = Client(sock)
+ return nine, int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
+
+ try:
+ t = Term(30, 100)
+ terms.append(t)
+ c = t.spawn([binary, '--9p=pair', str(notes)], dict(env, PARDES_REPLICA_CHECK=str(root / 'pair.check')))
+ nine, session = session_of('pair')
+ assert session != c.pid and ppid(session) == c.pid and os.getsid(session) == session, (session, c.pid)
+ wait_for('the file drawn on the terminal', lambda: b'line 3 of the notes' in t.text(), timeout=30)
+ listed = lambda: subprocess.run([binary, 'ps'], env=env, capture_output=True).stdout.decode()
+ wait_for('the client listed', lambda: f'session pair {session} (tty, detached)' in listed()
+ and f'client {c.pid} ' in listed())
+ pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
+ os.write(t.master, b'Ofrom-the-pair\x1b')
+ wait_for('its keys in the session\'s text', lambda: b'from-the-pair' in nine.read(f'/pane/{pane}/body'))
+ wait_for('out of insert mode', lambda: normal_again(t))
+ wait_for('the client agrees once quiet', lambda: agreed(root / 'pair.check', 0))
+ exit_session(nine, pane)
+ code = c.wait(timeout=60)
+ assert code == 0 and not alive(session), (code, alive(session))
+ print(f'pair: client {c.pid} (the job) and session {session} (its child, setsid, listed detached with the client); '
+ f'drawn, typed, agreed; Exit ended both (the client exit {code})')
+ nine.socket.close()
+ lone = Term(24, 80)
+ terms.append(lone)
+ c2 = lone.spawn([binary, '--9p=lone', str(notes)], dict(env, PARDES_DAEMON='off'))
+ nine2, session2 = session_of('lone')
+ wait_for('the lone pair drawn', lambda: b'line 3 of the notes' in lone.text(), timeout=30)
+ nine2.socket.close()
+ os.kill(c2.pid, signal.SIGKILL)
+ c2.wait(timeout=10)
+ wait_for('the lone session ended with its last link', lambda: not alive(session2), timeout=20)
+ wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20)
+ print(f'pair: with no daemon, client {c2.pid} killed outright, its session {session2} ended; nothing left behind')
+ finally:
+ for p in processes(root):
+ try:
+ os.kill(p, signal.SIGKILL)
+ except OSError:
+ pass
+ for t in terms:
+ t.close()
+ shutil.rmtree(root, ignore_errors=True)
+
+
+def pair_rows(binary):
+ """PARDES_PAIR, the shell's view (the last step's design, 1.1) and a
+ session's lifetime (2.2 B), one row a step. With a daemon: a Detach in
+ the pair's client says so and exits 0, the session runs on (listed); an
+ attach is a client again; TERM to the client puts its terminal back and
+ the session runs on; so does a KILL, and a closed terminal (HUP): each a
+ loss, not a close. With none: a Detach refused (nothing could attach),
+ the client on; its terminal closed, the session ends with its last link."""
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='rq-', dir=scratch))
+ env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
+ TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1', PARDES_PAIR='1')
+ (root / 'config' / 'pardes').mkdir(parents=True)
+ (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
+ notes = root / 'notes.txt'
+ notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30)))
+ terms = []
+
+ def listed():
+ return subprocess.run([binary, 'ps'], env=env, capture_output=True).stdout.decode()
+
+ def drawn(t):
+ wait_for('drawn', lambda: b'line 3 of the notes' in t.text(), timeout=30)
+
+ def typed_detach(t, nine, pane):
+ # Its view the live one (it typed last), then the word.
+ os.write(t.master, b'j')
+ time.sleep(.3)
+ nine.write(f'/pane/{pane}/exec', b'Detach\n')
+
+ def started(name, e):
+ t = Term(30, 100)
+ terms.append(t)
+ c = t.spawn([binary, f'--9p={name}', str(notes)], e)
+ wait_for('the socket', (root / f'pardes-9p-{name}.sock').exists)
+ nine = Client(root / f'pardes-9p-{name}.sock')
+ session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
+ pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
+ drawn(t)
+ return t, c, nine, session, pane
+
+ try:
+ t, c, nine, session, pane = started('rows', env)
+ typed_detach(t, nine, pane)
+ assert c.wait(timeout=20) == 0, c.returncode
+ wait_for('the detach said', lambda: b"pardes: detached from 'rows', which is still running; come back with `pardes attach rows`" in t.text())
+ assert alive(session) and f'session rows {session} (tty, detached)' in listed()
+ print('pair rows: Detach in the client: said, exit 0; the session runs on, listed')
+ for how in ('TERM', 'KILL', 'HUP'):
+ tt = Term(30, 100)
+ terms.append(tt)
+ a = tt.spawn([binary, 'attach', 'rows'], env)
+ drawn(tt)
+ wait_for('the client listed', lambda: f'client {a.pid} ' in listed())
+ if how == 'HUP':
+ tt.close()
+ terms.remove(tt)
+ else:
+ os.kill(a.pid, getattr(signal, 'SIG' + how))
+ a.wait(timeout=20)
+ if how == 'TERM':
+ wait_for('its terminal put back', lambda: tt.text().rfind(b'\x1b[?1049l') > tt.text().rfind(b'\x1b[?1049h'))
+ wait_for('the client unlisted', lambda: f'client {a.pid} ' not in listed())
+ assert alive(session), how
+ print(f'pair rows: a client ended by {how}: the session runs on')
+ nine.socket.close()
+ assert subprocess.run([binary, 'kill', 'rows'], env=env, capture_output=True, timeout=30).returncode == 0
+ wait_for('the session ended', lambda: not alive(session), timeout=30)
+ t, c, nine, session, pane = started('lone', dict(env, PARDES_DAEMON='off'))
+ typed_detach(t, nine, pane)
+ time.sleep(1)
+ assert c.poll() is None and alive(session), 'a Detach with no daemon is refused'
+ nine.socket.close()
+ t.close()
+ terms.remove(t)
+ c.wait(timeout=20)
+ wait_for('the lone session ended with its last link', lambda: not alive(session), timeout=20)
+ wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20)
+ print('pair rows: no daemon: a Detach refused, the client on; its terminal closed, the session ended; nothing left')
+ finally:
+ for p in processes(root):
+ try:
+ os.kill(p, signal.SIGKILL)
+ except OSError:
+ pass
+ for t in terms:
+ t.close()
+ shutil.rmtree(root, ignore_errors=True)
+
+
def manage(binary):
"""`pardes --ps`, `--kill=NAME` and `--kill-all`: two detached sessions
and their shells listed, one session killed outright and its shell
@@ -736,6 +972,78 @@ def relink(binary):
shutil.rmtree(root, ignore_errors=True)
+def answer_late(binary):
+ """A session's Adopt asked at once, while its daemon has not answered
+ its hello (stopped 3 s, as a loaded machine can keep it), and before
+ the session's reader of the daemon has run: answered when the daemon
+ answers, never refused on a clock (daemon.zig `kept`)."""
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='ra-', dir=scratch))
+ env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
+ TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
+ (root / 'config' / 'pardes').mkdir(parents=True)
+ (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
+ started = []
+ terms = []
+ wake = None
+ try:
+ term = Term()
+ terms.append(term)
+ stub = term.spawn([binary, '--tty', '--9p=one'], env)
+ started.append(stub.pid)
+ wait_for('the first session', (root / 'pardes-9p-one.sock').exists)
+ one = Client(root / 'pardes-9p-one.sock')
+ session = int(dict(line.split(maxsplit=1) for line in one.read('/status').decode().splitlines())['pid'])
+ started.append(session)
+ shell_pid = int(run(one, terminals(one)[0], b'echo $$\n').split(b'\n')[1])
+ started.append(shell_pid)
+ daemon = [p for p in processes(root) if cmdline(p)[1:2] == [b'--daemon']][0]
+ started.append(daemon)
+ wait_for('its shell listed', lambda: f'shell {shell_pid}' in subprocess.run(
+ [binary, '--ps'], env=env, capture_output=True, timeout=30).stdout.decode())
+ os.kill(session, signal.SIGKILL)
+ one.socket.close()
+ wait_for('the killed session gone', lambda: not alive(session))
+ os.kill(daemon, signal.SIGSTOP)
+ wake = threading.Timer(3, lambda: os.kill(daemon, signal.SIGCONT))
+ wake.start()
+ term = Term()
+ terms.append(term)
+ stub = term.spawn([binary, '--tty', '--9p=two'], env)
+ started.append(stub.pid)
+ wait_for('the next session', (root / 'pardes-9p-two.sock').exists)
+ two = Client(root / 'pardes-9p-two.sock', timeout=30)
+ started.append(int(dict(line.split(maxsplit=1) for line in two.read('/status').decode().splitlines())['pid']))
+ before = set(terminals(two))
+ asked = time.monotonic()
+ two.write(f'/pane/{min(before)}/exec', b'Adopt\n')
+ took = time.monotonic() - asked
+ pane = wait_for('the adopted pane', lambda: set(terminals(two)) - before).pop()
+ assert run(two, pane, b'echo $$\n').split(b'\n')[1] == str(shell_pid).encode()
+ print(f'answer late: an Adopt asked while the daemon was stopped waited {took:.1f} s for its answer, '
+ f'and shell {shell_pid} was adopted')
+ exit_session(two, pane)
+ two.socket.close()
+ wait_for('the shells hung up', lambda: not alive(shell_pid))
+ wait_for('the daemon gone once idle', lambda: not alive(daemon), timeout=5)
+ finally:
+ if wake:
+ wake.cancel()
+ for t in terms:
+ try:
+ t.close()
+ except OSError:
+ pass
+ for pid in started + processes(root):
+ try:
+ os.kill(pid, signal.SIGKILL)
+ except (ProcessLookupError, PermissionError):
+ pass
+ shutil.rmtree(root, ignore_errors=True)
+
+
class Window:
"""A pardes-gui in test mode, its window offscreen and hidden, its keys
written to its stdin (the test feed: Escape as `CSI 27 u`, which a
@@ -966,10 +1274,10 @@ def window_clients(binary, gui_binary):
wait_for('the window\'s keys after the upgrade', lambda: b'after-upgrade-W' in body(), timeout=30)
wait_for('the window client agrees after the upgrade', lambda: agreed(dcheck, seen), timeout=30)
assert wd.p.poll() is None
- # Detach typed in it: it alone goes, and says why.
+ # Detach typed in it: it alone goes, and says so (exit 0).
wd.keys(b' sD')
wait_for('the window client let go', lambda: wd.p.poll() is not None, timeout=15)
- assert 'let this client go' in wd.said(), wd.said()[-500:]
+ assert wd.p.returncode == 0 and "detached from 'files', which is still running" in wd.said(), wd.said()[-500:]
# A link a line: the first join sent every blob, its rejoins held them.
links = joins(root / 'wd.stats')
assert len(links) == 3 and links[0]['blobs'] > 0 and links[0]['from_memory'] + links[0]['from_disk'] == 0, links
@@ -1183,12 +1491,13 @@ def far(binary):
f_join = joins(root / 'f.stats')[0]
assert f_join['from_disk'] > 0 and cached(cache) <= (1 << 20) + (64 << 10), (f_join, cached(cache))
far_joins(root / 'pardes-replica.sock', 'files', binary, 200)
- # Through ssh (a stand-in forwarding as `ssh -L` does): a client
- # refused and one detached each end their ssh and its socket (one
- # refused left both, 2026-10-30).
+ # Through ssh (a stand-in forwarding as `ssh -L` does, its socket
+ # bound 0.5 s before it listens: the client dials until it answers):
+ # a client refused and one detached each end their ssh and its
+ # socket (one refused left both, 2026-10-30).
fake = root / 'ssh'
fake.write_text('#!/bin/sh\nwhile [ $# -gt 0 ]; do case $1 in -L) fwd=$2; shift;; esac; shift; done\n'
- f'exec {sys.executable} -B {Path(__file__).parent / "delay_relay.py"} "${{fwd%%:*}}" "${{fwd#*:}}" --delay 0\n')
+ f'exec {sys.executable} -B {Path(__file__).parent / "delay_relay.py"} "${{fwd%%:*}}" "${{fwd#*:}}" --delay 0 --bound 500\n')
fake.chmod(0o755)
senv = dict(env, PARDES_SSH=str(fake), PARDES_REMOTE_RUNTIME=str(root), TMPDIR=str(root))
@@ -1272,7 +1581,10 @@ def by_hash(binary):
started.append(sess.pid)
wait_for('the replica socket', (root / 'pardes-replica.sock').exists)
wait_for('the session\'s 9P socket', (root / 'pardes-9p-files.sock').exists)
- nine = Client(root / 'pardes-9p-files.sock')
+ # Each reply waited for as long as the opens it answers take: the
+ # 17 MiB file's Look took 1.6-6.6 s in a Debug build at a load of
+ # 35 (ninep.py's 5 s is a reply's whole wait).
+ nine = Client(root / 'pardes-9p-files.sock', timeout=60)
pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
(ta, a), (tf, f) = client('a', False), client('f', True)
seen = {n: len(checks(root / f'{n}.check')) for n in 'af'}
@@ -1521,8 +1833,12 @@ def main(binary, cycles):
clients(binary)
far(binary)
by_hash(binary)
+ launch(binary)
+ pair(binary)
+ pair_rows(binary)
manage(binary)
relink(binary)
+ answer_late(binary)
shell = terminals(client)[0]
shell_pid = int(run(client, shell, b'echo $$\n').split(b'\n')[1])
started.append(shell_pid)
@@ -1557,8 +1873,8 @@ def main(binary, cycles):
terminal closed: it ends; the session and its shell run on."""
if how == 'detach':
client.write(f'/pane/{shell}/exec', b'Detach\n')
- assert c.wait(timeout=10) == 1, c.returncode
- wait_for('the client says it was let go', lambda: b'let this client go' in term.text())
+ assert c.wait(timeout=10) == 0, c.returncode
+ wait_for('the client says it detached', lambda: b"detached from 'work', which is still running" in term.text())
else:
term.close()
c.wait(timeout=10)
@@ -1686,8 +2002,8 @@ def main(binary, cycles):
# The end: the session quits, its shells hang up, its client and
# the daemon go.
exit_session(client, pane)
- assert stub.wait(timeout=10) == 1, stub.returncode
- wait_for('the client says it was let go', lambda: b'let this client go' in term.text())
+ assert stub.wait(timeout=10) == 0, stub.returncode
+ assert b'let this client go' not in term.text(), term.text()[-300:]
client.socket.close()
term.close()
wait_for('the adopted shell hung up', lambda: not alive(shell_pid))
@@ -2106,10 +2422,15 @@ def upgrades(old, new):
sock = root / 'pardes-9p-again.sock'
wait_for('the next session', sock.exists)
client = Client(sock)
- started.append(int(dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines())['pid']))
- # Its reader of the daemon starts after its first frame: an Adopt
- # before that waits for an `ok` nobody reads, and is refused.
+ again = int(dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines())['pid'])
+ started.append(again)
+ # A build before daemon.zig's `kept` waited for the hello's answer
+ # (the new-to-old run) refused an Adopt before its reader of the
+ # daemon ran (after its first frame), or within 2 s of a slow `ok`:
+ # it is asked once the daemon lists it (answer_late tests the wait).
wait_for('the next session\'s first frame', lambda: b'\x1b[?1049h' in term.text())
+ wait_for('the next session listed by the daemon', lambda: f'session again {again} ' in subprocess.run(
+ [str(binary), '--ps'], env=env, capture_output=True, timeout=30).stdout.decode())
before = set(terminals(client))
client.write(f'/pane/{min(before)}/exec', b'Adopt\n')
pane = wait_for('the adopted pane', lambda: set(terminals(client)) - before).pop()
@@ -2231,8 +2552,14 @@ if __name__ == '__main__':
clients(sys.argv[2])
elif sys.argv[1:2] == ['--manage']:
manage(sys.argv[2])
+ elif sys.argv[1:2] == ['--launch']:
+ launch(sys.argv[2])
+ elif sys.argv[1:2] == ['--pair']:
+ pair(sys.argv[2])
+ pair_rows(sys.argv[2])
elif sys.argv[1:2] == ['--relink']:
relink(sys.argv[2])
+ answer_late(sys.argv[2])
elif sys.argv[1:2] == ['--games']:
games(sys.argv[2], sys.argv[3], float(sys.argv[4]) if len(sys.argv) > 4 else 10)
elif sys.argv[1:2] == ['--far']:
diff --git a/test/delay_relay.py b/test/delay_relay.py
index c600a3aa..b0d48e38 100644
--- a/test/delay_relay.py
+++ b/test/delay_relay.py
@@ -8,7 +8,7 @@ the ones before it have crossed at that rate, then waits out the delay. An
optional jitter adds up to that many ms more to each chunk's delay, at
random, its order kept (a chunk never overtakes the one before it).
- python3 -B test/delay_relay.py LISTEN TARGET --delay MS [--rate MB/s] [--jitter MS]
+ python3 -B test/delay_relay.py LISTEN TARGET --delay MS [--rate MB/s] [--jitter MS] [--bound MS]
python3 -B test/delay_relay.py --self-check
An address is a path (a Unix socket) or host:port (TCP). The one-way
@@ -46,7 +46,9 @@ def dial(address):
return s
-def listen(address):
+def listen(address, bound=0.0):
+ """Bound, then listening `bound` s later (an ssh -L's socket file is
+ there a moment before it answers)."""
family, addr = parse(address)
s = socket.socket(family)
if family == socket.AF_UNIX:
@@ -57,6 +59,7 @@ def listen(address):
else:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(addr)
+ time.sleep(bound)
s.listen(64)
return s
@@ -260,8 +263,9 @@ def main():
ap.add_argument('--delay', type=float, required=True, help='one-way delay, ms')
ap.add_argument('--rate', type=float, help='a bandwidth cap, MB/s')
ap.add_argument('--jitter', type=float, default=0, help='up to this many ms more a chunk, at random')
+ ap.add_argument('--bound', type=float, default=0, help='ms between the bind and the listen')
a = ap.parse_args()
- listener = listen(a.listen)
+ listener = listen(a.listen, a.bound / 1000)
print(f'relaying {a.listen} -> {a.target}, {a.delay} ms each way'
+ (f', {a.rate} MB/s' if a.rate else '') + (f', jitter {a.jitter} ms' if a.jitter else ''), flush=True)
try:
diff --git a/test/fs_namespace.zig b/test/fs_namespace.zig
index ceda8158..90b610a9 100644
--- a/test/fs_namespace.zig
+++ b/test/fs_namespace.zig
@@ -118,7 +118,6 @@ test "transactional restore preserves host capabilities and advances pane identi
}
test "filesystem resolves OS first then virtual with explicit mounts and parent paths" {
- if (!filesystem.platform_has_fs) return error.SkipZigTest;
const gpa = std.testing.allocator;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
@@ -185,7 +184,6 @@ test "filesystem resolves OS first then virtual with explicit mounts and parent
}
test "explicit OS file opens and restores keep their names and request watches" {
- if (!filesystem.platform_has_fs) return error.SkipZigTest;
const gpa = std.testing.allocator;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
@@ -286,7 +284,6 @@ test "owned cwd failed file opens never publish a pane or retain a reservation"
}
test "images decode through explicit filesystem mounts, and a dump's pane reads its file again through the same mount" {
- if (!filesystem.platform_has_fs) return error.SkipZigTest;
const gpa = std.testing.allocator;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
diff --git a/test/lib/build.zig b/test/lib/build.zig
deleted file mode 100644
index 436517d4..00000000
--- a/test/lib/build.zig
+++ /dev/null
@@ -1,34 +0,0 @@
-//! A package that depends on pardes for its library, as a program that draws
-//! source text itself would: pardes's `lib-test` step runs `zig build test`
-//! here, so the `pardes-syntax` module is built the way such a package
-//! builds it (build.zig's `library`), with the minimal grammars, and
-//! `pardes-editor`, the text pane as a library, which it asks for.
-const std = @import("std");
-
-pub fn build(b: *std.Build) void {
- const target = b.standardTargetOptions(.{});
- const optimize = b.standardOptimizeOption(.{});
- const pardes = b.dependency("pardes", .{ .target = target, .optimize = optimize, .@"tree-sitter" = .minimal, .editor = true });
- const step = b.step("test", "colour, outline and walk a C and a Zig source through pardes's library, and edit a text with its editor");
- // A file belongs to one module: the syntax alone, and the editor (which
- // has it as `.syntax`), each a test of its own.
- for ([_][2][]const u8{ .{ "lib.zig", "pardes-syntax" }, .{ "editor.zig", "pardes-editor" } }) |t| {
- const tests = b.addTest(.{ .root_module = b.createModule(.{
- .target = target,
- .optimize = optimize,
- .root_source_file = b.path(t[0]),
- .imports = &.{.{ .name = t[1], .module = pardes.module(t[1]) }},
- }) });
- step.dependOn(&b.addRunArtifact(tests).step);
- }
- // What a key costs, a page count and a parse: `zig build bench -- <KiB> <keys>`.
- const bench = b.addExecutable(.{ .name = "bench", .root_module = b.createModule(.{
- .target = target,
- .optimize = optimize,
- .root_source_file = b.path("bench.zig"),
- .imports = &.{.{ .name = "pardes-editor", .module = pardes.module("pardes-editor") }},
- }) });
- const run_bench = b.addRunArtifact(bench);
- run_bench.addPassthruArgs();
- b.step("bench", "a key typed into the library's editor at a size, its pages and a parse").dependOn(&run_bench.step);
-}
diff --git a/test/lib/build.zig.zon b/test/lib/build.zig.zon
deleted file mode 100644
index d8c31c3f..00000000
--- a/test/lib/build.zig.zon
+++ /dev/null
@@ -1,10 +0,0 @@
-.{
- .name = .pardes_lib_test,
- .version = "0.0.0",
- .dependencies = .{
- .pardes = .{ .path = "../.." },
- },
- .minimum_zig_version = "0.17.1",
- .paths = .{""},
- .fingerprint = 0x3f9948734dd377c7,
-}
diff --git a/test/output.zig b/test/output.zig
index c5ddddd5..77de7649 100644
--- a/test/output.zig
+++ b/test/output.zig
@@ -138,7 +138,7 @@ test "location producers retain rendered location match and diagnostic styles" {
} else if (origin == .search or origin == .cmd) {
try std.testing.expectEqual(pardes.Color{ .rgb = chrome.search_bg }, first.style.bg);
}
- if (!diagnostic and pardes.syntax.enabled) {
+ if (!diagnostic) {
const number = start + std.mem.indexOf(u8, code, "42").?;
try std.testing.expectEqual(pardes.Color{ .rgb = p.theme().num }, outputCell(p, surface, id, number).style.fg);
}
@@ -428,7 +428,6 @@ test "Mini dump preserves its exact virtual snapshot and body writes detach colo
}
test "Mini syntax colors survive themes and rendering without source access" {
- if (!pardes.syntax.enabled) return error.SkipZigTest;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "demo.zig", .data = "pub fn main() void {\n if (true) return;\n}\n" });
@@ -619,7 +618,6 @@ fn selectedOutputText(pane: *const pardes.Pane) ?[]const u8 {
}
test "LookNext/LookPrev skips formatted context and selects comment match locations" {
- if (!pardes.syntax.enabled) return error.SkipZigTest;
for ([_]panes.Output.Origin{ .search, .{ .query = .references } }) |origin| {
for ([_]bool{ false, true }) |tslocations| {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 30 });
@@ -786,7 +784,7 @@ test "identical result refresh keeps warm content caches without allocation" {
const index = try panes.File.lineIndex(p.gpa, file);
const styles = try std.testing.allocator.dupe(u8, file.highlights);
defer std.testing.allocator.free(styles);
- if (@import("pardes_options").grammars != .disabled) try std.testing.expect(styles.len > 0);
+ try std.testing.expect(styles.len > 0);
const revision = file.revision;
const saved_revision = file.saved_revision;
const body_ptr = file.content.ptr;
@@ -1048,7 +1046,6 @@ test "result alignment chunks assign boundary context to nearest match with prev
}
test "declaration context ellipses mark only final header lines before omitted source" {
- if (!pardes.syntax.enabled) return error.SkipZigTest;
const text = "const Outer = struct {\n" ++
"\n" ++
" pub fn run(\n" ++
@@ -1161,7 +1158,6 @@ test "LSP occurrence tint follows the supplied source span through context" {
}
test "result context upper bound stops at earliest enclosing declaration" {
- if (!pardes.syntax.enabled) return error.SkipZigTest;
const text = "// unrelated prelude\n" ++
"const unrelated = 1;\n" ++
"\n" ++
@@ -1227,7 +1223,6 @@ test "result context upper bound stops at earliest enclosing declaration" {
}
test "stacked search and LSP results retain source tint navigation and dump ownership" {
- if (!pardes.syntax.enabled) return error.SkipZigTest;
const first = "\tfoo + 界 + foo;";
const second = " return foo;";
const source_text = "const Box = struct {\n fn run() void {\n" ++ first ++ "\n const neighbor = 42;\n" ++ second ++ "\n }\n};\n";
@@ -1348,7 +1343,6 @@ test "stacked search and LSP results retain source tint navigation and dump owne
}
test "location analysis cache refreshes unsaved ancestry and query context" {
- if (!pardes.syntax.enabled) return error.SkipZigTest;
const before = "const Outer = struct {\n" ++
" fn first() void {\n" ++
" marker();\n" ++
@@ -1429,7 +1423,6 @@ test "location analysis cache refreshes unsaved ancestry and query context" {
}
test "location cache eviction retains early colors and honors disk and unsaved replacements" {
- if (!pardes.syntax.enabled) return error.SkipZigTest;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
var dir_buf: [4096]u8 = undefined;
diff --git a/test/panes.zig b/test/panes.zig
index dbdbec2f..6bda3519 100644
--- a/test/panes.zig
+++ b/test/panes.zig
@@ -152,7 +152,6 @@ const BodyHitTests = struct {
}
test "compact TreeContext mouse follows source rows in reclaimed space" {
- if (!syntax.enabled) return error.SkipZigTest;
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 64, .rows = 18 });
defer p.deinit();
p.view().row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 8, .tagline_h = 10 };
@@ -201,7 +200,6 @@ const BodyHitTests = struct {
const LineNumberLookTests = struct {
test "right-click on a line number looks at that line, sticky context headers included" {
- if (!syntax.enabled) return error.SkipZigTest;
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 64, .rows = 18 });
defer p.deinit();
p.view().row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 8, .tagline_h = 10 };
@@ -259,7 +257,6 @@ const TreeContextTests = struct {
}
test "TreeContext separators mark source gaps without splitting multiline signatures" {
- if (!syntax.enabled) return error.SkipZigTest;
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 64, .rows = 18 });
defer p.deinit();
const pane = try setZigFile(p, "const Box = struct {\n\n // omitted member comment\n\n pub fn work(\n value: usize,\n ) void {\n" ++ std.mem.asBytes(&@as([30][16]u8, @splat(" // body\n".*))) ++ " }\n};\n");
@@ -291,7 +288,6 @@ const TreeContextTests = struct {
test "TreeContext Look to an open file discards the old viewport extent" {
for ([_]bool{ false, true }) |context| {
- if (context and !syntax.enabled) continue;
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 64, .rows = 18 });
defer p.deinit();
const pane = try setZigFile(p, "pub fn work() void {\n" ++ std.mem.asBytes(&@as([100][12]u8, @splat(" // body\n".*))) ++ "}\n");
@@ -316,7 +312,6 @@ const TreeContextTests = struct {
}
test "TreeContext sticky declarations preserve the body while clicked and edited" {
- if (!syntax.enabled) return error.SkipZigTest;
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 64, .rows = 18 });
defer p.deinit();
const pane = try setZigFile(p, source);
@@ -368,7 +363,6 @@ const TreeContextTests = struct {
}
test "TreeContext unwrapped headers map Unicode and survive source replacement" {
- if (!syntax.enabled) return error.SkipZigTest;
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 48, .rows = 14 });
defer p.deinit();
const pane = try setZigFile(p, "pub fn @\"界name\"(\n\tvalue: usize,\n) void {\n" ++ std.mem.asBytes(&@as([12][15]u8, @splat(" _ = value;\n".*))) ++ "}\n");
@@ -407,7 +401,6 @@ const TreeContextTests = struct {
}
test "TreeContext clipped headers leave wrapped body cursor coordinates intact" {
- if (!syntax.enabled) return error.SkipZigTest;
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 24, .rows = 12 });
defer p.deinit();
const body = " // 012345678901234567890123456789界tail";
@@ -1717,7 +1710,6 @@ const OutputTests = struct {
}
test "Callstack aligns source below locations and keeps exact emphasis and navigation" {
- if (!syntax.enabled) return error.SkipZigTest;
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 30 });
defer p.deinit();
const source = " pub fn caller(\n value: u32,\n ) void {\n work(value);\n }\n";
@@ -1759,7 +1751,6 @@ const OutputTests = struct {
}
test "Callstack signatures share unsaved tree context and keep guides out of Look selections" {
- if (!syntax.enabled) return error.SkipZigTest;
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 110, .rows = 30 });
defer p.deinit();
const source = "const Box = struct {\n" ++
@@ -1853,7 +1844,6 @@ const OutputTests = struct {
}
test "Locations context uses unsaved sources and navigation visits only matches" {
- if (!syntax.enabled) return error.SkipZigTest;
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 30 });
defer p.deinit();
p.locations_config.layout = .@"inline";
@@ -1968,7 +1958,6 @@ const OutputTests = struct {
}
test "Locations visible declarations are muted and stars count scopes rather than signature lines" {
- if (!syntax.enabled) return error.SkipZigTest;
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 });
defer p.deinit();
p.locations_config.layout = .@"inline";
@@ -3541,7 +3530,6 @@ test "cancelled normal gestures leave no count or subprefix through raw tty mode
}
test "Zig keywords keep every rendered byte colored across line-number widths" {
- if (!syntax.enabled) return error.SkipZigTest;
const gpa = std.testing.allocator;
const samples = [_][]const u8{
"pub fn main() void { if (true) {} }\n",
diff --git a/test/process.zig b/test/process.zig
index 8bcbddeb..e2a4f592 100644
--- a/test/process.zig
+++ b/test/process.zig
@@ -916,7 +916,8 @@ pub const Child = struct {
while (environ[i]) |kv| {
const entry = std.mem.span(kv);
const eq = std.mem.indexOfScalar(u8, entry, '=') orelse entry.len;
- if (std.mem.startsWith(u8, entry, "PARDES_") or std.mem.indexOf(u8, entry[0..eq], "PAGER") != null) {
+ // PARDES_PAIR kept: the suite run as pairs (main.zig `pair`).
+ if ((std.mem.startsWith(u8, entry, "PARDES_") and !std.mem.startsWith(u8, entry, "PARDES_PAIR=")) or std.mem.indexOf(u8, entry[0..eq], "PAGER") != null) {
var name: [256]u8 = undefined;
const n = std.fmt.bufPrintSentinel(&name, "{s}", .{entry[0..@min(eq, 255)]}, 0) catch _exit(126);
_ = unsetenv(n);
diff --git a/test/process/terminals.zig b/test/process/terminals.zig
index 24772ced..d9c3bcca 100644
--- a/test/process/terminals.zig
+++ b/test/process/terminals.zig
@@ -262,7 +262,9 @@ fn rawKey(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
/// thousand: nothing printed is nothing kept), then a probe typed and
/// taken back with ^U.
fn drive(gpa: std.mem.Allocator, exe: [:0]const u8, script: []const u8, key: ?u8, rows: usize) !void {
- var d = try process.Detached.start(gpa, exe, "agent", .{});
+ // No builtin announces itself: Term's name would linger on the screen
+ // (MessageLinger, 800 ms) and go between `before` and ^U's answer.
+ var d = try process.Detached.start(gpa, exe, "agent", .{ .init = "Verbose off\n" });
defer d.deinit();
const f = &d.files;
try d.put("command.sh", f.at("exec /bin/sh -c '{s}'\n", .{script}));
@@ -300,7 +302,10 @@ fn drive(gpa: std.mem.Allocator, exe: [:0]const u8, script: []const u8, key: ?u8
try f.write(data, "\x15");
const back_by = eh.nowMs() + 10_000;
while (!std.mem.eql(u8, try f.screen(), before)) {
- if (eh.nowMs() > back_by) return error.ScreenNotRestored;
+ if (eh.nowMs() > back_by) {
+ std.debug.print("before:\n{s}\nafter ^U:\n{s}\n", .{ before, try f.screen() });
+ return error.ScreenNotRestored;
+ }
sleepMs(10);
}
}
diff --git a/test/process/tty_terminals.zig b/test/process/tty_terminals.zig
index d5540818..dfb027e2 100644
--- a/test/process/tty_terminals.zig
+++ b/test/process/tty_terminals.zig
@@ -844,7 +844,9 @@ fn exec_bigdrag(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
try t.drag("middle", "150", 31);
try t.drag("middle", "198", 59);
try t.release("middle", "198", 59);
- try t.stable(500, 8000);
+ // Bash fails each swept chunk as a command, one by one: under load
+ // that runs well past 8 s, so the quiet is waited for once, with the
+ // cap the sweep's other waits have.
try t.stable(800, 30000);
// still alive: type and execute a marker command
try t.press("left", "105", 41);
diff --git a/test/terminal.zig b/test/terminal.zig
index b7b9cd33..ec050c7a 100644
--- a/test/terminal.zig
+++ b/test/terminal.zig
@@ -203,7 +203,6 @@ test "a terminal's dump restores the cells it drew, its history and where its vi
}
test "a restored command pane comes back finished, its command not run again" {
- if (comptime pardes.isolated) return error.SkipZigTest;
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 });
defer p.deinit();
@@ -233,7 +232,6 @@ test "a restored command pane comes back finished, its command not run again" {
}
test "a restored terminal keeps its history above a marker and gets a shell where it was" {
- if (comptime pardes.isolated) return error.SkipZigTest;
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 });
defer p.deinit();