summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/CHANGELOG.md44
-rw-r--r--src/Core.zig20
-rw-r--r--src/Effect.zig16
-rw-r--r--src/Plumb.zig503
-rw-r--r--src/builtins.zig93
-rw-r--r--src/config.zig1
-rw-r--r--src/exec.zig3
-rw-r--r--src/fs-help.txt2
-rw-r--r--src/fs.zig5
-rw-r--r--src/gui/gui.zig1
-rw-r--r--src/host_io.zig126
-rw-r--r--src/hunks.zig118
-rw-r--r--src/look.zig287
-rw-r--r--src/macos.zig1
-rw-r--r--src/ninep/ctl.zig4
-rw-r--r--src/ninep/events.zig4
-rw-r--r--src/ninep/tree.zig73
-rw-r--r--src/pardes.zig1
-rw-r--r--src/plumbing30
-rw-r--r--src/tui/tui.zig1
-rw-r--r--src/walk.zig1026
-rw-r--r--src/wire.zig8
22 files changed, 1504 insertions, 863 deletions
diff --git a/src/CHANGELOG.md b/src/CHANGELOG.md
index e398b43f..2f5d00f0 100644
--- a/src/CHANGELOG.md
+++ b/src/CHANGELOG.md
@@ -9,6 +9,36 @@
(docs/next-terminal.md). Editing a terminal's text is the core's, on a
copy of its rows, as before; nothing a session does changes.
+- A diff paged (`git show | pardes -`) is a plumbing message, as acme's
+ `plumb -i` sends what it shows: `type text/x-diff` to `edit`, which a
+ default rule makes `showdiff`, its +Pager stacked in a +Diff as before.
+ Take the rule out and the +Pager stays as text; a program reading
+ `plumb/edit` sees the diff. The `edit` port shows any message's data
+ with `action=showdata` (stacked with `showdiff`).
+
+- A port the plumbing rules name is a file a program reads,
+ `plumb/<port>`, as Plan 9's plumber serves one: every open reads its
+ own copy of what is sent there from then on (`cat plumb/edit` sees each
+ file a look opens), a read held until a message comes. A message to a
+ port no one reads runs its rule set's `start`, or with `plumb client`
+ waits for the port's first reader.
+
+- A look asks the plumber first, as acme's does: once the pane's own
+ readings are done and a name already open in a pane is focused, what
+ is looked at is sent (`type text`, `src pardes`, `wdir` the pane's
+ directory), and only what no rule set takes is Look's own. The default
+ rules keep every look as it was: the browser for a URL, a bare `.diff`
+ or `.patch` stacked in a +Diff, `git show` of a commit hash in a git
+ work tree are now rules of `src/plumbing`, no longer written into
+ Look. `Diff` takes a file or a revision (`Diff fix.patch`, `Diff
+ 3f2a9c1`), and a rule's Diff that cannot declines, so the look goes
+ on. `Plumb` opens your plumbing file (`<config>/plumbing`, `include
+ basic` until you save one), read at start and applied when saved; the
+ one-line `Plumb suffix .svg to image` rules are gone, refused in words
+ (write a rule set: `data matches '.*\.svg'`, `arg isfile $data`,
+ `plumb to image`). A program a rule starts runs detached, as Plan 9's
+ plumber starts one, with no pane; a failure to start it is said.
+
- A search with a class whose range ends at `\xff` (`[\x80-\xff]`, in an
address, `s`, a plumbing rule) no longer takes the editor down: mvzr
counted the range past a byte's end.
@@ -21,8 +51,7 @@
(`edit`, `web`, a loaded kind) or to a word or command started, with
Plan 9's words when it cannot. A session starts with `include basic`,
pardes's rules (`src/plumbing`). Kept in a dump. `$1`-`$9` are refused,
- the regular expressions having no submatches. A look does not ask it
- yet.
+ the regular expressions having no submatches.
- A query pane's row looked at on its address (its gutter) opens the
row's place however the look arrives, as a click there always did: an
@@ -48,6 +77,17 @@
A column resizes by its box, left of its tag; a pane by its own box,
or in a window by the rule above it.
+- An edit to the core recompiles it about 2 s sooner again (`core-test`,
+ 16 % fewer of the compiler's instructions, 4.4 MB less code in a Debug
+ test): a load's note on a field (another build's dump) is written from
+ the type's and the field's names at run time, where every type and
+ field had its own copy of the code that writes one; one byte dump's
+ reader serves a session, a pane and the rest, where each had its own;
+ and what tells a replica's build from another's (`wire.semantics`)
+ joins its two long parts on, and the tape's shape writes its numbers
+ itself and copies each line it builds once, where it formatted them
+ and copied the line again for each piece, at every compile.
+
- An edit to the core recompiles it about 3 s sooner (`core-test`, 13 s to
10 s): the build keeps each grammar's highlight patterns that pardes
colours once, where every compile of every program that takes the core
diff --git a/src/Core.zig b/src/Core.zig
index 7d8cfb0e..a3ace8f9 100644
--- a/src/Core.zig
+++ b/src/Core.zig
@@ -208,9 +208,6 @@ db: Db = .{},
/// (`stdio.h`, `<foo.h>`) is tried in, in order. The session's, seeded
/// with C's (/usr/include, /usr/local/include), kept in a dump.
incl: std.ArrayList([]u8) = .empty,
-/// Plumb's rules, the user's, tried in order before the built-in ones
-/// (look.resolve), the first to match taking the look. Kept in a dump.
-plumb: std.ArrayList([]u8) = .empty,
/// The plumber's rules (Plumb.zig): plumb/rules and plumb/send's, the
/// defaults (`include basic`) until something writes others. Kept in a dump.
plumber: Plumb = .{},
@@ -230,9 +227,11 @@ next_serial: u32 = 0,
/// The column whose tag the running command came from, while it runs:
/// the column acme's commands take from their Text's col.
exec_column: ?usize = null,
-/// The directory a `plumb start`'s command runs in, while it runs
-/// (Plumb.run): the message's wdir, which no pane need have.
-exec_dir: ?[]const u8 = null,
+/// While a word a plumbing rule started runs (Plumb.run): whether it
+/// declined the message, saying nothing (Diff on a file with no hunk, a
+/// revision outside a git work tree), so that the send is refused and a
+/// look looks itself. Null while no rule's word runs.
+plumb_declined: ?bool = null,
/// Panes made this step that found no room in their column
/// (layout.placeNew): closed at the step's end, once whatever made them
/// is done with them.
@@ -273,8 +272,10 @@ unattended: bool = false,
haptic: HapticSlot = if (platform == .macos) .none else {},
/// The look just run found nothing (look.zig missed).
look_missed: bool = false,
-/// The look being run opens a .diff or .patch as text, not its +Diff:
-/// Diff going back from a +Diff, Edit's B (it edits the file).
+/// The look being run opens what it names, unplumbed (Plumb.zig): a
+/// .diff as text, not stacked in a +Diff (Diff going back from a +Diff,
+/// Edit's B, which edits the file), and the `edit` port's open of a
+/// message the plumber already matched.
look_text: bool = false,
look_hover_wait: ?look.LookHoverWait = null,
/// The place a look-hover last found nothing to open: the pointer
@@ -763,8 +764,6 @@ pub fn deinit(p: *Pardes) void {
p.recent.deinit(p.recentGpa());
for (p.incl.items) |dir| p.gpa.free(dir);
p.incl.deinit(p.gpa);
- for (p.plumb.items) |rule| p.gpa.free(rule);
- p.plumb.deinit(p.gpa);
p.plumber.deinit(p.gpa);
for (p.twin_groups.items) |group| p.gpa.free(group.path);
p.twin_groups.deinit(p.gpa);
@@ -1719,7 +1718,6 @@ fn processDir(buf: *[limits.host_path_cap]u8) ?[]const u8 {
/// The directory a word run from pane `id`'s text or tag runs in, or,
/// from a header, the session's.
pub fn execDir(p: *Pardes, id: usize) []const u8 {
- if (p.exec_dir) |dir| return dir;
if (p.exec_header) return p.sessionDir();
return paneDir(p.panes[id] orelse return p.sessionDir());
}
diff --git a/src/Effect.zig b/src/Effect.zig
index e161d1db..7f0c3fdf 100644
--- a/src/Effect.zig
+++ b/src/Effect.zig
@@ -46,6 +46,10 @@ pub const Effect = union(enum) {
/// and ends the shell, rather than leave it running with nobody to read.
close_pty: struct { pane: u8 },
open_link: Buf(256),
+ /// A program a plumbing rule starts (Plumb.run): its directory, then
+ /// its argv, each ended by a NUL. A failure to start it is said at
+ /// pane `pane`.
+ start: struct { pane: u8, line: Buf(effect_path_cap) },
/// write this pane's file content to its path; the shell reads both off
/// the core (content is unbounded, effects are fixed-size values)
save_file: struct { pane: u8 },
@@ -132,6 +136,18 @@ pub fn perform(p: *Pardes, e: Effect) void {
f(p.host.ctx, u.slice())
else
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 w = why orelse return;
+ var words = std.mem.splitScalar(u8, st.line.slice(), 0);
+ _ = words.next(); // its directory
+ const prog = words.next() orelse "";
+ var said: pardes.Kind.Buf(160) = .{};
+ p.reportFailure(st.pane, said.print("plumb start: {s}: {s}", .{ prog[0..@min(64, prog.len)], w }));
+ },
.save_file => |sf| {
const pane = p.panes[sf.pane] orelse return;
const f = if (pane.file) |*file| file else return;
diff --git a/src/Plumb.zig b/src/Plumb.zig
index 57a19b14..5299a8c3 100644
--- a/src/Plumb.zig
+++ b/src/Plumb.zig
@@ -10,9 +10,10 @@ const std = @import("std");
const pardes = @import("pardes.zig");
const fs = @import("fs.zig");
const look = @import("look.zig");
-const exec = @import("exec.zig");
const layout = @import("layout.zig");
const Kind = @import("Kind.zig");
+const tape = @import("tape.zig");
+const events = @import("ninep/events.zig");
const Regex = @import("regexp.zig").Regex;
const Pardes = pardes.Pardes;
@@ -24,6 +25,17 @@ text: std.ArrayList(u8) = .empty,
/// are `include basic`'s, so a session starts with the defaults, and so
/// does a dump made before the plumber.
written: bool = false,
+/// Every port a rule has named this session, in the order they were
+/// named, never dropped (plumber(4)'s directory): plumb/<port>'s files,
+/// a port's index its node.
+ports: std.ArrayList([]u8) = .empty,
+/// The rules in force read, kept until their text changes (by its hash):
+/// a send parses nothing (29k instructions a send in a fast build, half
+/// of what a URL's costs). Each process's own.
+parsed: ?struct { hash: u64, rules: Rules } = null,
+parsed_arena: ?std.heap.ArenaAllocator = null,
+
+pub const replica = .{ .derived = .{ "parsed", "parsed_arena" } };
/// The default rules, which `include basic` names, as Plan 9's names
/// /lib/plumb/basic.
@@ -45,7 +57,10 @@ pub const e_client = "no port for \"client\" rule";
pub const e_empty = "empty argument list";
pub fn deinit(pl: *Plumb, gpa: std.mem.Allocator) void {
+ if (pl.parsed_arena) |*a| a.deinit();
pl.text.deinit(gpa);
+ for (pl.ports.items) |name| gpa.free(name);
+ pl.ports.deinit(gpa);
}
// ---- the message ----
@@ -496,6 +511,22 @@ fn rulesOf(p: *Pardes, arena: std.mem.Allocator) Parser.Error!Rules {
return ps.rules;
}
+/// The rules in force, read once for every send until they change. A
+/// send made while a rule's word runs (a look it makes) reads them into
+/// the step's scratch: the send it runs in holds the kept ones.
+fn inForceRules(p: *Pardes) Parser.Error!Rules {
+ const pl = &p.plumber;
+ const hash = std.hash.Wyhash.hash(0, source(p));
+ if (pl.parsed) |c| if (c.hash == hash) return c.rules;
+ if (p.plumb_declined != null) return rulesOf(p, p.scratch.allocator());
+ pl.parsed = null;
+ if (pl.parsed_arena) |*a| a.deinit();
+ pl.parsed_arena = .init(p.gpa);
+ const rules = try rulesOf(p, pl.parsed_arena.?.allocator());
+ pl.parsed = .{ .hash = hash, .rules = rules };
+ return rules;
+}
+
/// The rules in force as plumb/rules reads them, the defaults printed
/// (in the step's scratch) while none were written.
pub fn inForce(p: *Pardes) []const u8 {
@@ -507,17 +538,115 @@ pub fn inForce(p: *Pardes) []const u8 {
return out.written();
}
+/// What the `Plumb` word says to a rule written after it.
+pub const e_word = "Plumb takes no rule now: rules are plumb(6) rule sets, in <config>/plumbing (Plumb opens it) or written to plumb/rules";
+
+/// The plumbing file, the user's rules beside init (plumber(4)'s
+/// $home/lib/plumbing), in `buf`; null with no configuration directory.
+pub fn filePath(p: *Pardes, buf: *[4096]u8) ?[]const u8 {
+ const dir = p.configDir() orelse return null;
+ return std.fmt.bufPrint(buf, "{s}/plumbing", .{std.mem.trimEnd(u8, dir, "/")}) catch null;
+}
+
+/// At boot, the plumbing file's rules in force, if it is there (the
+/// plumber reading $home/lib/plumbing); a refusal is said, as an init
+/// line that fails is, and the defaults stay. Either way the ports the
+/// rules in force name have their files.
+pub fn boot(p: *Pardes) void {
+ if (rulesOf(p, p.scratch.allocator())) |rules| notePorts(p, rules.ports.items) catch {} else |_| {}
+ var buf: [4096]u8 = undefined;
+ const path = filePath(p, &buf) orelse return;
+ const text = fs.read(p, path) catch return;
+ defer p.gpa.free(text);
+ if (apply(p, false, "plumbing", text)) |why| p.reportFailure(p.view().active, why);
+}
+
+/// A file saved from pane `pane`: when it is the plumbing file, its rules
+/// in force now, or the save says why not and the rules stay as they were
+/// (plumb.ms's `cp lib/plumbing /mnt/plumb/rules`, done for you).
+pub fn saved(p: *Pardes, pane: usize, path: []const u8, text: []const u8) void {
+ var buf: [4096]u8 = undefined;
+ const mine = filePath(p, &buf) orelse return;
+ if (!std.mem.eql(u8, mine, path)) return;
+ if (apply(p, false, "plumbing", text)) |why| p.reportFailure(pane, why);
+}
+
+/// `names` added to the session's ports, those it has not yet, in order;
+/// none when they would be more than max_ports.
+fn notePorts(p: *Pardes, names: []const []const u8) error{ TooMany, OutOfMemory }!void {
+ var new: usize = 0;
+ for (names) |n| new += @intFromBool(portIndex(p, n) == null);
+ if (p.plumber.ports.items.len + new > max_ports) return error.TooMany;
+ try p.plumber.ports.ensureUnusedCapacity(p.gpa, new);
+ for (names) |n| if (portIndex(p, n) == null) p.plumber.ports.appendAssumeCapacity(try p.gpa.dupe(u8, n));
+}
+
+/// The port named `name`'s index, its file's node.
+pub fn portIndex(p: *const Pardes, name: []const u8) ?u8 {
+ for (p.plumber.ports.items, 0..) |n, i| if (std.mem.eql(u8, n, name)) return @intCast(i);
+ return null;
+}
+
+pub fn portName(p: *const Pardes, index: u8) ?[]const u8 {
+ return if (index < p.plumber.ports.items.len) p.plumber.ports.items[index] else null;
+}
+
+/// Whether a program reads port `index` (an open of its file): the
+/// authority's 9P state, asked through the tape.
+fn portRead(p: *Pardes, index: u8) bool {
+ for (&p.fs.opens) |*o| if (o.node != 0 and o.what == .port and o.what.port.index == index) return true;
+ return false;
+}
+
+/// `m` packed onto `q` (a reader's, the held ones'), after `lead` (a
+/// held message's port); false when it is over what a queue holds.
+fn enqueue(p: *Pardes, q: *events.Queue, lead: []const u8, m: *const Msg) bool {
+ var out: std.Io.Writer.Allocating = .init(p.scratch.allocator());
+ out.writer.writeAll(lead) catch return false;
+ m.pack(&out.writer) catch return false;
+ if (out.written().len + 4 > q.cap) return false;
+ q.push(p.gpa, out.written());
+ return true;
+}
+
+/// A copy of `m` to every reader of port `index` (plumber(4)'s queuesend:
+/// every fid open when it was sent), each read held for one answered.
+fn fanOut(p: *Pardes, index: u8, m: *const Msg) void {
+ for (&p.fs.opens) |*o| if (o.node != 0 and o.what == .port and o.what.port.index == index) {
+ if (!enqueue(p, &o.what.port.queue, "", m)) {
+ var said: Kind.Buf(160) = .{};
+ events.notePath(p, "err -", said.print("plumb/{s}: a message of {d} bytes is over a reader's {d} KiB, not sent to it", .{ portName(p, index).?, m.data.len, events.queue_cap / 1024 }));
+ }
+ };
+ p.fs.news = true;
+}
+
+/// A port's file opened (tree.zig): what `client` rules held for it, the
+/// opener's (plumber(4)'s queueheld).
+pub fn opened(p: *Pardes, index: u8, q: *events.Queue) void {
+ const held = &p.fs.plumb_held;
+ var kept: events.Queue = .{};
+ while (held.peek()) |record| {
+ if (record[0] == index) {
+ q.push(p.gpa, record[1..]);
+ } else kept.push(p.gpa, record);
+ held.pop();
+ }
+ held.deinit(p.gpa);
+ held.* = kept;
+}
+
/// No rules at all: a `>` to plumb/rules, before what it writes.
pub fn clear(p: *Pardes) void {
p.plumber.text.clearRetainingCapacity();
p.plumber.written = true;
}
-/// `more` read after the rules in force (`keep`) or in their place, and
-/// what that makes kept as the rules: plumb/rules' write and its close's
-/// rest. Null when taken, else why not, in the step's scratch, the rules
-/// as they were.
-pub fn apply(p: *Pardes, keep: bool, more: []const u8) ?[]const u8 {
+/// `more` (read from `name`) read after the rules in force (`keep`) or in
+/// their place, and what that makes kept as the rules: plumb/rules' write
+/// and its close's rest, the plumbing file saved or read at boot. Null
+/// when taken, else why not, in the step's scratch, the rules as they were.
+pub fn apply(p: *Pardes, keep: bool, name: []const u8, more: []const u8) ?[]const u8 {
const arena = p.scratch.allocator();
var ps: Parser = .{ .arena = arena, .p = p, .check = true };
const said = said: {
@@ -525,11 +654,15 @@ pub fn apply(p: *Pardes, keep: bool, more: []const u8) ?[]const u8 {
ps.feed("plumb/rules", source(p)) catch break :said ps.why;
ps.finish() catch break :said ps.why;
}
- ps.feed("plumb/rules", more) catch break :said ps.why;
+ ps.feed(name, more) catch break :said ps.why;
ps.finish() catch break :said ps.why;
var out: std.Io.Writer.Allocating = .init(arena);
ps.rules.print(&out.writer) catch break :said "out of memory";
if (out.written().len > max_text) break :said std.fmt.comptimePrint("rules too long; max {d} KiB", .{max_text / 1024});
+ notePorts(p, ps.rules.ports.items) catch |err| break :said switch (err) {
+ error.TooMany => std.fmt.comptimePrint("too many ports; max {d}", .{max_ports}),
+ error.OutOfMemory => "out of memory",
+ };
p.plumber.text.clearRetainingCapacity();
p.plumber.text.appendSlice(p.gpa, out.written()) catch break :said "out of memory";
p.plumber.written = true;
@@ -550,6 +683,9 @@ const Send = struct {
from: ?usize,
arena: std.mem.Allocator,
rules: Rules,
+ /// The data as a look sent it (`Seen`): a message to `edit` that still
+ /// holds it is Look's to open.
+ looked: ?[]const u8 = null,
memo_name: ?[]const u8 = null,
memo_wdir: []const u8 = "",
memo: ?fs.Resolved = null,
@@ -571,23 +707,10 @@ const Send = struct {
fn search(s: *Send, wdir: []const u8, name: []const u8) ?fs.Resolved {
if (name.len == 0) return null;
- if (fs.resolve(s.p, name, wdir, &s.memo_buf)) |found| return found;
- if (name[0] == '/' or fs.dotRelative(name)) return null;
- if (s.from) |id| {
- const v = s.p.view();
- var seen: [pardes.MAX_PANES][]const u8 = undefined;
- var nseen: usize = 0;
- var n: usize = 1;
- cand: while (n <= v.jumps.n) : (n += 1) {
- const k = v.jumps.list[v.jumps.n - n].pane;
- if (k == id) continue;
- const dir = Pardes.paneDir(s.p.panes[k] orelse continue);
- if (std.mem.eql(u8, dir, wdir)) continue;
- for (seen[0..nseen]) |d| if (std.mem.eql(u8, d, dir)) continue :cand;
- seen[nseen] = dir;
- nseen += 1;
- if (fs.resolve(s.p, name, dir, &s.memo_buf)) |found| return found;
- }
+ var dirs: look.Dirs = .init(s.p, s.from, wdir);
+ while (dirs.next()) |dir| {
+ if (fs.resolve(s.p, name, dir, &s.memo_buf)) |found| return found;
+ if (name[0] == '/' or fs.dotRelative(name)) return null;
}
for (s.p.incl.items) |dir| if (fs.resolve(s.p, name, dir, &s.memo_buf)) |found| return found;
return null;
@@ -711,14 +834,42 @@ const Port = enum {
web,
};
+/// What a look found of the name it sends (look.zig's resolveLookTarget:
+/// in its pane's directory, the jump list's, Incl's), which `isfile` and
+/// `isdir` take as found rather than ask the disk again: the same answer,
+/// and Look's own readings of a name kept (a URL, `//`: no file).
+pub const Seen = struct { name: []const u8, found: ?fs.Resolved };
+
+/// Where a send went.
+pub const Sent = union(enum) {
+ /// Taken: started, or given to the port that reads it.
+ done,
+ /// To `edit` as the look sent it (`Seen`): Look opens what it found,
+ /// as acme's own look opens a file.
+ look,
+ /// Taken by nothing, in Plan 9's words; or what a rule started
+ /// declined it (`declined`).
+ refused: []const u8,
+};
+
+/// What a send a rule's started word declined says (Pardes.plumb_declined):
+/// fsys.c's words for a message nothing takes.
+pub const e_declined = "no matching plumb rule";
+
/// A message matched against the rules and sent where they say (fsys.c's
/// write of `send`, then dispose), from pane `from` (a look's) or from
/// plumb/send (null: the pane with the keyboard runs what it starts).
-/// Null when it went somewhere, else why not, in Plan 9's words, in the
-/// step's scratch.
-pub fn send(p: *Pardes, from: ?usize, msg: Msg) ?[]const u8 {
+/// `seen` is a look's, what it found of the name it sends. A refusal is in
+/// the step's scratch.
+pub fn send(p: *Pardes, from: ?usize, msg: Msg, seen: ?Seen) Sent {
const arena = p.scratch.allocator();
- var s: Send = .{ .p = p, .from = from, .arena = arena, .rules = rulesOf(p, arena) catch return "plumb/rules: the rules in force do not read" };
+ var s: Send = .{ .p = p, .from = from, .arena = arena, .rules = inForceRules(p) catch return .{ .refused = "plumb/rules: the rules in force do not read" } };
+ if (seen) |look_seen| {
+ s.looked = msg.data;
+ s.memo_name = look_seen.name;
+ s.memo_wdir = msg.wdir;
+ s.memo = look_seen.found;
+ }
var m = msg;
var e: Exec = .{ .m = &m };
const set: ?Set = for (s.rules.items.items) |item| {
@@ -727,36 +878,46 @@ pub fn send(p: *Pardes, from: ?usize, msg: Msg) ?[]const u8 {
else => continue,
};
e = .{ .m = &m };
- if (s.matchSet(candidate, &e) catch return "out of memory") break candidate;
+ if (s.matchSet(candidate, &e) catch return .{ .refused = "out of memory" }) break candidate;
} else null;
const id = from orelse p.view().active;
// dispose.
- if (m.dst.len == 0) return startup(&s, id, set orelse return e_no_port, &e);
- if (std.meta.stringToEnum(Port, m.dst)) |port| {
- deliver(&s, id, port, &m);
- return null;
+ if (m.dst.len == 0) return startup(&s, id, set orelse return .{ .refused = e_no_port }, &e);
+ const port = portIndex(p, m.dst);
+ // A port pardes reads itself: its readers' copies (a program reading
+ // plumb/edit sees every open, plumber(4)'s fan-out), the authority's
+ // alone to hand out, so asked of nobody; then pardes's own.
+ if (std.meta.stringToEnum(Port, m.dst)) |own| {
+ if (port) |i| fanOut(p, i, &m);
+ return deliver(&s, id, own, &m);
}
if (p.kinds.byName(m.dst)) |k| {
+ if (port) |i| fanOut(p, i, &m);
openInKind(&s, id, k, &m);
- return null;
+ return .done;
}
- // A port nobody reads: what the rule set starts, if it is one a rule
- // names; one no rule names is no port, and the message goes nowhere,
- // as fsys.c's dispose finds no Dirtab for it.
- if (!s.rules.named(m.dst)) return null;
- return startup(&s, id, set orelse return e_no_start, &e);
+ // One no rule ever named is none, and the message goes nowhere, as
+ // fsys.c's dispose finds no Dirtab for it. Another goes to its readers,
+ // whom only the authority knows (its 9P opens); with none, what the
+ // rule set starts.
+ const i = port orelse return .done;
+ if (tape.authority(portRead, .{ p, i })) {
+ fanOut(p, i, &m);
+ return .done;
+ }
+ return startup(&s, id, set orelse return .{ .refused = e_no_start }, &e);
}
/// match.c's startup: the rule set's `start` or `client`, its words
/// expanded, run.
-fn startup(s: *Send, id: usize, set: Set, e: *const Exec) ?[]const u8 {
+fn startup(s: *Send, id: usize, set: Set, e: *const Exec) Sent {
const act = for (set.acts) |a| {
if (a.verb == .start) break a;
if (a.verb == .client) {
- if (e.m.dst.len == 0) return e_client;
+ if (e.m.dst.len == 0) return .{ .refused = e_client };
break a;
}
- } else return e_no_start;
+ } else return .{ .refused = e_no_start };
// buildargv: one expansion a word.
var argv: std.ArrayList([]const u8) = .empty;
var rest = act.arg;
@@ -764,63 +925,144 @@ fn startup(s: *Send, id: usize, set: Set, e: *const Exec) ?[]const u8 {
rest = std.mem.trimStart(u8, rest, " \t");
if (rest.len == 0) break;
var buf: [4096]u8 = undefined;
- const word, const took = expand(&s.rules, e, rest, &buf) catch return "string-too-long";
- argv.append(s.arena, s.arena.dupe(u8, word) catch return "out of memory") catch return "out of memory";
+ const word, const took = expand(&s.rules, e, rest, &buf) catch return .{ .refused = "string-too-long" };
+ argv.append(s.arena, s.arena.dupe(u8, word) catch return .{ .refused = "out of memory" }) catch return .{ .refused = "out of memory" };
rest = rest[took..];
}
- if (argv.items.len == 0) return e_empty;
- run(s.p, id, e.m.wdir, argv.items);
- return null;
+ if (argv.items.len == 0) return .{ .refused = e_empty };
+ if (run(s.p, id, e.m.wdir, argv.items)) |why| return .{ .refused = why };
+ // `client`: the message waits for the port's first reader, the program
+ // it started perhaps (plumber(4)'s hold); held messages past what the
+ // queue keeps push out the oldest.
+ if (act.verb == .client) if (portIndex(s.p, e.m.dst)) |i| {
+ if (!enqueue(s.p, &s.p.fs.plumb_held, &.{i}, e.m)) return .{ .refused = "plumb: message too big to hold for a client" };
+ };
+ return .done;
}
-/// What a `plumb start` (and, until ports are read, a `plumb client`) runs:
+/// What a `plumb start` or a `plumb client` runs:
/// the one place that decides it (question 4 of docs/next-plumber.md).
-/// Its words as pardes's exec runs a line from the message's pane: a
-/// builtin or a kind's word in place, any other line a command pane in
-/// `wdir`, each word one argument to $SHELL -c however it is spelled.
-/// Plan 9's runs detached, with no window.
-fn run(p: *Pardes, id: usize, wdir: []const u8, argv: []const []const u8) void {
+/// A builtin or a kind's word runs in place, from the message's pane, as
+/// a line of it would; one that cannot do what the message asks declines
+/// (Pardes.plumb_declined), saying nothing, and the send is refused, so a
+/// look looks itself. Any other is a program, started as Plan 9's plumber
+/// starts one (match.c's startup): detached, no pane, its argv exec'd in
+/// `wdir` with no shell (a rule that wants one says `sh -c`), by the host
+/// (Effect.start), which says a failure to start in the log. Null when it
+/// ran, else why not.
+fn run(p: *Pardes, id: usize, wdir: []const u8, argv: []const []const u8) ?[]const u8 {
const arena = p.scratch.allocator();
- const line = std.mem.join(arena, " ", argv) catch return p.reportError(id, "plumb", error.OutOfMemory);
- if (p.executeBuiltinLine(id, line)) return;
- var quoted: std.Io.Writer.Allocating = .init(arena);
- for (argv, 0..) |a, i| {
- if (i > 0) quoted.writer.writeByte(' ') catch return;
- quoted.writer.writeByte('\'') catch return;
- for (a) |c| {
- if (c == '\'') {
- quoted.writer.writeAll("'\\''") catch return;
- } else quoted.writer.writeByte(c) catch return;
- }
- quoted.writer.writeByte('\'') catch return;
- }
- p.exec_dir = if (wdir.len > 0) wdir else null;
- defer p.exec_dir = null;
- _ = exec.runCommand(p, id, quoted.written());
+ const line = std.mem.join(arena, " ", argv) catch return "out of memory";
+ const outer = p.plumb_declined;
+ p.plumb_declined = false;
+ defer p.plumb_declined = outer;
+ // Started, not clicked: no name said for it under Verbose.
+ const announce = p.announce;
+ p.announce = false;
+ defer p.announce = announce;
+ if (p.executeBuiltinLine(id, line)) return if (p.plumb_declined.?) e_declined else null;
+ // Its directory, then its words, each ended by a NUL.
+ var start: pardes.Effect.Buf(pardes.effect_path_cap) = .{};
+ for ([_][]const []const u8{ &.{wdir}, argv }) |words| for (words) |w| {
+ if (std.mem.indexOfScalar(u8, w, 0) != null) return "plumb start: a NUL in a word";
+ if (start.len + w.len + 1 > start.data.len) return std.fmt.comptimePrint("plumb start: over {d} bytes", .{pardes.effect_path_cap});
+ @memcpy(start.data[start.len..][0..w.len], w);
+ start.data[start.len + w.len] = 0;
+ start.len += @intCast(w.len + 1);
+ };
+ p.emit(.{ .start = .{ .pane = @intCast(id), .line = start } });
+ return null;
}
/// What pardes does with a message to a port it reads. Like a message
/// queued to a reader in Plan 9, the send is done: what goes wrong after
/// is said as a look's failure is.
-fn deliver(s: *Send, id: usize, port: Port, m: *const Msg) void {
+fn deliver(s: *Send, id: usize, port: Port, m: *const Msg) Sent {
const p = s.p;
switch (port) {
.web => {
- if (m.data.len > 256) return p.reportFailure(id, "plumb: web: a URL is at most 256 bytes");
- p.emit(.{ .open_link = .from(m.data) });
+ if (m.data.len > 256) p.reportFailure(id, "plumb: web: a URL is at most 256 bytes") else p.emit(.{ .open_link = .from(m.data) });
},
.edit => {
- // acme's plumblook: the data a name in wdir, at its addr.
+ // acme's plumbshow, for `plumb -i`: the data shown, not a name.
+ var action_buf: [4096]u8 = undefined;
+ const action = attrValue(m.attr, "action", &action_buf) orelse "";
+ if (std.mem.eql(u8, action, "showdata") or std.mem.eql(u8, action, "showdiff")) {
+ show(s, id, m, std.mem.eql(u8, action, "showdiff"));
+ return .done;
+ }
var buf: [4096]u8 = undefined;
const addr = attrValue(m.attr, "addr", &buf) orelse "";
+ // A look's own name, as it sent it: its own look opens it.
+ if (s.looked) |data| if (addr.len == 0 and std.mem.eql(u8, data, m.data)) return .look;
+ // acme's plumblook: the data a name in wdir, at its addr,
+ // opened as Look opens one and not sent again.
const relative = m.data.len > 0 and m.data[0] != '/' and m.data[0] != '~' and m.wdir.len > 0;
const text = std.fmt.allocPrint(s.arena, "{s}{s}{s}{s}{s}", .{
if (relative) m.wdir else "", if (relative) "/" else "", m.data,
if (addr.len > 0) ":" else "", addr,
- }) catch return p.reportError(id, "plumb", error.OutOfMemory);
+ }) catch {
+ p.reportError(id, "plumb", error.OutOfMemory);
+ return .done;
+ };
+ const was = p.look_text;
+ p.look_text = true;
+ defer p.look_text = was;
look.lookAt(p, id, text);
},
}
+ return .done;
+}
+
+/// The edit port's `showdata` and `showdiff` (acme's plumbshow): the data
+/// in the pane `filename` names, the pane that sent it first (a +Pager's
+/// own text), else a new one so named (`+Plumbed` with none), clean;
+/// `showdiff` then stacks it in a +Diff in that pane's place (hunks.paged),
+/// as a diff paged always was.
+fn show(s: *Send, id: usize, m: *const Msg, diff: bool) void {
+ const p = s.p;
+ var buf: [4096]u8 = undefined;
+ const filename = attrValue(m.attr, "filename", &buf) orelse "";
+ const named = std.mem.eql(u8, filename, if (p.panes[id]) |pn| (if (pn.file) |f| f.path else "") else "");
+ const shown: usize = if (named) id else shown: {
+ const name = if (filename.len > 0) filename else "+Plumbed";
+ const free = p.freeSlot() orelse return p.reportError(id, "plumb", error.NoPaneSlots);
+ pardes.panes.newScratchFor(p, id, .scratch);
+ const made = p.panes[free] orelse return;
+ @import("ninep/pane.zig").nameBuffer(p, free, name, false) catch |err| return p.reportError(id, "plumb", err);
+ const f = &made.file.?;
+ _ = pardes.panes.File.replace(p, f, 0, f.content.len, m.data);
+ f.saved_revision = f.revision;
+ break :shown free;
+ };
+ if (diff) @import("hunks.zig").paged(p, shown);
+}
+
+/// A +Pager filled (ninep/ctl.zig fillPager) with a diff (File.looksLikeDiff:
+/// `git show`, a mailed patch): sent to `edit`, as acme's `plumb -i`
+/// sends what it shows, `type text/x-diff`, `action=showdata` and the
+/// +Pager's name; the default rules make it `showdiff`, stacked in a +Diff
+/// in the +Pager's place. Other text paged is not sent: the look rules
+/// would read it whole (a `matches` over a MiB of output, up to the
+/// regular expressions' budget, at each page).
+pub fn paged(p: *Pardes, id: usize) void {
+ const pane = p.panes[id] orelse return;
+ const f = pane.file orelse return;
+ if (!f.pager_diff) return;
+ var attr: std.Io.Writer.Allocating = .init(p.scratch.allocator());
+ attr.writer.writeAll("action=showdata filename=") catch return;
+ // mesg.c's quote, for a name with a blank, a quote, `=` or a tab.
+ const quote = std.mem.indexOfAny(u8, f.path, " '=\t") != null;
+ if (quote) attr.writer.writeByte('\'') catch return;
+ for (f.path) |c| {
+ if (c == '\'') attr.writer.writeByte('\'') catch return;
+ attr.writer.writeByte(c) catch return;
+ }
+ if (quote) attr.writer.writeByte('\'') catch return;
+ switch (send(p, id, .{ .src = "pager", .dst = "edit", .wdir = Pardes.paneDir(pane), .type = "text/x-diff", .attr = attr.written(), .data = f.content }, null)) {
+ .done, .look => {},
+ .refused => |why| p.reportFailure(id, why),
+ }
}
/// A message to a loaded kind's port: its data, a file, opened in that kind
@@ -992,7 +1234,7 @@ test "plumb: rc's quoting, variables and the message's in an expansion, the firs
const Tried = struct { m: Msg, set: ?usize };
fn tryRules(p: *Pardes, text: []const u8, msg: Msg) !Tried {
- try testing.expect(apply(p, false, text) == null);
+ try testing.expect(apply(p, false, "plumb/rules", text) == null);
const arena = p.scratch.allocator();
var s: Send = .{ .p = p, .from = null, .arena = arena, .rules = try rulesOf(p, arena) };
var m = msg;
@@ -1100,29 +1342,29 @@ test "plumb: dispose: no rule and no dst, a start, the web port, a port no rule
const p = try Pardes.init(testing.allocator, .{ .cols = 80, .rows = 24 });
defer p.deinit();
_ = try p.setTestFile("x\n");
- try testing.expect(apply(p, false, "include basic\n\ntype\tis\tmsg\nplumb\tstart\tMsg $data\n\ntype\tis\tnone\nplumb\tto\tnobody\n\ntype\tis\tclient\nplumb\tclient\tMsg x\n\n") == null);
- try testing.expectEqualStrings(e_no_port, send(p, null, .{ .type = "text", .data = "no such thing" }).?);
+ try testing.expect(apply(p, false, "plumb/rules", "include basic\n\ntype\tis\tmsg\nplumb\tstart\tMsg $data\n\ntype\tis\tnone\nplumb\tto\tnobody\n\ntype\tis\tclient\nplumb\tclient\tMsg x\n\n") == null);
+ try testing.expectEqualStrings(e_no_port, send(p, null, .{ .type = "text", .data = "no such thing" }, null).refused);
// A start of a builtin runs it in place.
- try testing.expect(send(p, null, .{ .type = "msg", .data = "hello" }) == null);
+ try testing.expect(send(p, null, .{ .type = "msg", .data = "hello" }, null) == .done);
const pane = p.panes[p.view().active].?;
try testing.expectEqualStrings("hello", pane.msg[0..pane.msg_len]);
- try testing.expectEqualStrings(e_client, send(p, null, .{ .type = "client" }).?);
- try testing.expectEqualStrings(e_no_start, send(p, null, .{ .type = "none" }).?);
- try testing.expectEqualStrings(e_no_start, send(p, null, .{ .dst = "nobody", .type = "x" }).?);
+ try testing.expectEqualStrings(e_client, send(p, null, .{ .type = "client" }, null).refused);
+ try testing.expectEqualStrings(e_no_start, send(p, null, .{ .type = "none" }, null).refused);
+ try testing.expectEqualStrings(e_no_start, send(p, null, .{ .dst = "nobody", .type = "x" }, null).refused);
// A port no rule names goes nowhere, said nothing (fsys.c's dispose).
- try testing.expect(send(p, null, .{ .dst = "elsewhere", .data = "x" }) == null);
+ try testing.expect(send(p, null, .{ .dst = "elsewhere", .data = "x" }, null) == .done);
// A URL to the web port: the host's opener.
while (p.nextEffect()) |_| {}
- try testing.expect(send(p, null, .{ .type = "text", .data = "https://ziglang.org" }) == null);
- var opened = false;
+ try testing.expect(send(p, null, .{ .type = "text", .data = "https://ziglang.org" }, null) == .done);
+ var linked = false;
while (p.nextEffect()) |e| switch (e) {
.open_link => |u| {
try testing.expectEqualStrings("https://ziglang.org", u.slice());
- opened = true;
+ linked = true;
},
else => {},
};
- try testing.expect(opened);
+ try testing.expect(linked);
}
test "plumb: rules written replace or add, a refusal keeps them as they were, and a dump keeps them" {
@@ -1131,10 +1373,10 @@ test "plumb: rules written replace or add, a refusal keeps them as they were, an
// Every session starts with the defaults.
try testing.expect(std.mem.indexOf(u8, inForce(p), "plumb\tto\tweb") != null);
try testing.expect(!p.plumber.written);
- try testing.expect(apply(p, false, "type is a\nplumb to edit\n") == null);
- try testing.expect(apply(p, true, "type is b\nplumb to edit\n") == null);
+ try testing.expect(apply(p, false, "plumb/rules", "type is a\nplumb to edit\n") == null);
+ try testing.expect(apply(p, true, "plumb/rules", "type is b\nplumb to edit\n") == null);
try testing.expectEqualStrings("type\tis\ta\nplumb\tto\tedit\n\ntype\tis\tb\nplumb\tto\tedit\n\n", p.plumber.text.items);
- try testing.expectEqualStrings("plumb/rules:1: unknown verb isnt", apply(p, true, "type isnt c\n").?);
+ try testing.expectEqualStrings("plumb/rules:1: unknown verb isnt", apply(p, true, "plumb/rules", "type isnt c\n").?);
try testing.expectEqualStrings("type\tis\ta\nplumb\tto\tedit\n\ntype\tis\tb\nplumb\tto\tedit\n\n", p.plumber.text.items);
try pardes.dump.dumpState(p);
const restored = try pardes.dump.restore(p, p.dump_out.?, "/tmp/pardes.dump.zon");
@@ -1239,3 +1481,86 @@ test "plumb: plan9port's basic parses, its ¡-￿ classes UTF-8's bytes and its
// The rune range as written is refused, in regexp.zig's words.
try testing.expectEqualStrings("t:1: bad regular expression: a range of runes wider than 256 in [...] is not supported", try reread(arena.allocator(), "data matches '[a-zA-Z¡-￿0-9_\\-./]+'\nplumb to edit\n"));
}
+
+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;
+ const root = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)];
+ const p = try Pardes.init(testing.allocator, .{ .cols = 100, .rows = 30, .config_dir = root });
+ defer p.deinit();
+ _ = try p.setTestFile("x\n");
+ var path_buf: [4096]u8 = undefined;
+ const path = filePath(p, &path_buf).?;
+ try testing.expect(std.mem.endsWith(u8, path, "/plumbing"));
+ // Not there yet: a pane of its name holding `include basic`.
+ try testing.expect(p.executeBuiltinLine(0, "Plumb"));
+ const made = p.panes[p.view().active].?;
+ try testing.expectEqualStrings(path, made.file.?.path);
+ try testing.expectEqualStrings("include basic\n", made.file.?.content);
+ // A rule after the word is refused, in words.
+ try testing.expect(p.executeBuiltinLine(0, "Plumb suffix .svg to image"));
+ const first = p.panes[0].?;
+ try testing.expectEqualStrings(e_word, first.msg[0..first.msg_len]);
+ // Saved: its rules, or why not, the rules as they were.
+ saved(p, 0, path, "type is text\ndata matches 'x.*'\nplumb to web\n");
+ try testing.expectEqualStrings("type\tis\ttext\ndata\tmatches\t'x.*'\nplumb\tto\tweb\n\n", inForce(p));
+ saved(p, 0, path, "type is text\ndata isnt x\nplumb to web\n");
+ try testing.expectEqualStrings("plumbing:2: unknown verb isnt", first.msg[0..first.msg_len]);
+ try testing.expectEqualStrings("type\tis\ttext\ndata\tmatches\t'x.*'\nplumb\tto\tweb\n\n", inForce(p));
+ // Another file saved is no plumbing.
+ saved(p, 0, "/elsewhere/plumbing", "type is text\nplumb to edit\n");
+ try testing.expect(std.mem.indexOf(u8, inForce(p), "'x.*'") != null);
+ // At boot: the file's rules.
+ try tmp.dir.writeFile(testing.io, .{ .sub_path = "plumbing", .data = "type is text\ndata matches 'y.*'\nplumb to web\n" });
+ const q = try Pardes.init(testing.allocator, .{ .cols = 100, .rows = 30, .config_dir = root });
+ defer q.deinit();
+ try testing.expectEqualStrings("type\tis\ttext\ndata\tmatches\t'y.*'\nplumb\tto\tweb\n\n", inForce(q));
+}
+
+test "plumb: a diff paged is sent to edit, stacked in a +Diff by the default rule; without it the +Pager stays, and a reader of plumb/edit gets it" {
+ const p = try Pardes.init(testing.allocator, .{ .tty_only = true });
+ defer p.deinit();
+ const page = "commit 0123456789abcdef0123456789abcdef01234567\ndiff --git a/x b/x\n--- a/x\n+++ b/x\n@@ -1 +1 @@\n-old\n+new\n";
+ const Page = struct {
+ fn fill(pp: *Pardes, text: []const u8) !usize {
+ const id = try pardes.panes.Output.openPager(pp, 0, "/pardes-plumb-page");
+ var held: std.ArrayList(u8) = .empty;
+ defer held.deinit(pp.gpa);
+ try held.appendSlice(pp.gpa, text);
+ try @import("ninep/ctl.zig").fillPager(pp, pp.panes[id].?.serial, &held);
+ return id;
+ }
+ fn diffs(pp: *Pardes) usize {
+ var n: usize = 0;
+ for (pp.panes) |slot| if (slot) |pn| if (pn.file) |f| {
+ n += @intFromBool(std.mem.indexOf(u8, f.path, "/+Diff") != null);
+ };
+ return n;
+ }
+ };
+ // The defaults: the +Pager stacked into a +Diff, and gone.
+ const stacked = try Page.fill(p, page);
+ try testing.expect(p.panes[stacked] == null or !std.mem.endsWith(u8, p.panes[stacked].?.file.?.path, "+Pager"));
+ try testing.expectEqual(@as(usize, 1), Page.diffs(p));
+ // Text that is no diff is not sent: its +Pager stays, as ever.
+ const plain = try Page.fill(p, "just text\n");
+ try testing.expect(std.mem.endsWith(u8, p.panes[plain].?.file.?.path, "+Pager"));
+ // The paged-diff rule taken out: the edit port shows the data where
+ // it is, and the +Pager stays as text.
+ try testing.expect(apply(p, false, "plumb/rules", "type is text\narg isfile $data\nplumb to edit\n") == null);
+ const kept = try Page.fill(p, page);
+ try testing.expect(std.mem.endsWith(u8, p.panes[kept].?.file.?.path, "+Pager"));
+ try testing.expectEqualStrings(page, p.panes[kept].?.file.?.content);
+ try testing.expectEqual(@as(usize, 1), Page.diffs(p));
+ // From another sender: shown in a pane of its filename's, clean, and
+ // with showdiff stacked.
+ try testing.expect(send(p, 0, .{ .src = "test", .dst = "edit", .type = "text", .attr = "action=showdata filename=/elsewhere/notes", .data = "a note\n" }, null) == .done);
+ const shown = p.panes[p.view().active].?;
+ try testing.expectEqualStrings("/elsewhere/notes", shown.file.?.path);
+ try testing.expectEqualStrings("a note\n", shown.file.?.content);
+ try testing.expectEqual(shown.file.?.revision, shown.file.?.saved_revision);
+ try testing.expect(send(p, 0, .{ .src = "test", .dst = "edit", .type = "text/x-diff", .attr = "action=showdiff filename=/elsewhere/change", .data = page }, null) == .done);
+ try testing.expectEqual(@as(usize, 2), Page.diffs(p));
+}
diff --git a/src/builtins.zig b/src/builtins.zig
index d106330e..300e196a 100644
--- a/src/builtins.zig
+++ b/src/builtins.zig
@@ -5,6 +5,7 @@ const tagline = @import("tagline.zig");
const dump = @import("dump.zig");
const exec = @import("exec.zig");
const look = @import("look.zig");
+const PlumbRules = @import("Plumb.zig");
const edit = @import("edit.zig");
const colors = @import("colors.zig");
const Pardes = pardes.Pardes;
@@ -65,8 +66,6 @@ pub const PaneKind = enum {
picture,
/// A terminal, or a +Pager: a program's colours.
program_colors,
- /// A text pane showing a diff: a .diff, a .patch, a +Pager holding one.
- diff,
pub fn has(kind: PaneKind, pane: *const panes.Pane) bool {
return switch (kind) {
@@ -74,7 +73,6 @@ pub const PaneKind = enum {
.image => pane.addon != null,
.picture => pane.addon != null or pane.isTerminal(),
.program_colors => pane.isTerminal() or (pane.file != null and pane.file.?.pager),
- .diff => @import("hunks.zig").shows(pane),
};
}
@@ -84,7 +82,6 @@ pub const PaneKind = enum {
.image => "an image",
.picture => "an image or a terminal",
.program_colors => "a terminal or a +Pager",
- .diff => "a diff or a +Diff",
};
}
};
@@ -942,43 +939,18 @@ pub const Incl = struct {
}
};
-/// The plumber's rules, for the session, one a line as plumb(6) orders a
-/// rule: `Plumb suffix .svg to image` makes a look at an existing `.svg`
-/// file an image pane. The user's rules are tried in the order given,
-/// before the built-in ones, and the first that matches takes the look.
-/// Bare, it lists them; `Plumb -` empties the list.
+/// Open the plumbing file, the plumber's rules (plumb(6)'s rule sets) in
+/// the configuration directory beside `init`: saved, they are the rules in
+/// force. Not there yet, it holds `include basic`, the default rules.
pub const Plumb = struct {
pub const scope: Scope = .session;
pub const takes_arg = true;
pub fn run(c: Ctx) void {
- const p = c.p;
- const typed = std.mem.trim(u8, c.arg orelse "", " \t\r\n");
- if (std.mem.eql(u8, typed, "-")) {
- for (p.plumb.items) |rule| p.gpa.free(rule);
- p.plumb.clearRetainingCapacity();
- return p.setMessage(c.id, "Plumb: none");
- }
- if (typed.len > 0) {
- var said: [320]u8 = undefined;
- if (look.plumbRuleError(&p.kinds, typed)) |why|
- return p.reportFailure(c.id, std.fmt.bufPrint(&said, "Plumb: {s}", .{why}) catch "Plumb: invalid rule");
- // One blank between words, as the list shows it.
- var rule: std.ArrayList(u8) = .empty;
- defer rule.deinit(p.gpa);
- var words = std.mem.tokenizeAny(u8, typed, " \t");
- while (words.next()) |w| {
- if (rule.items.len > 0) rule.append(p.gpa, ' ') catch |err| return p.reportError(c.id, "Plumb", err);
- rule.appendSlice(p.gpa, w) catch |err| return p.reportError(c.id, "Plumb", err);
- }
- p.plumb.ensureUnusedCapacity(p.gpa, 1) catch |err| return p.reportError(c.id, "Plumb", err);
- p.plumb.appendAssumeCapacity(rule.toOwnedSlice(p.gpa) catch |err| return p.reportError(c.id, "Plumb", err));
- return;
- }
- var list: std.Io.Writer.Allocating = .init(p.scratch.allocator());
- list.writer.writeAll("Plumb:") catch |err| return p.reportError(c.id, "Plumb", err);
- for (p.plumb.items, 0..) |rule, i| list.writer.print("{s} {s}", .{ if (i == 0) "" else ";", rule }) catch |err| return p.reportError(c.id, "Plumb", err);
- if (p.plumb.items.len == 0) list.writer.writeAll(" none") catch |err| return p.reportError(c.id, "Plumb", err);
- p.setMessage(c.id, list.written());
+ if (std.mem.trim(u8, c.arg orelse "", " \t\r\n").len > 0) return c.p.reportFailure(c.id, PlumbRules.e_word);
+ var buf: [4096]u8 = undefined;
+ const path = PlumbRules.filePath(c.p, &buf) orelse
+ return c.p.reportFailure(c.id, "Plumb: no plumbing file here: no configuration directory");
+ openConfigFile(c, "Plumb", path, "include basic\n");
}
};
@@ -1092,11 +1064,11 @@ pub const Filter = struct {
}
};
-/// Stack a diff's hunks as a diff viewer shows them, each under its place and the declarations around it, in a +Diff; on a +Diff, show the diff itself as text.
+/// Stack a diff's hunks as a diff viewer shows them, each under its place and the declarations around it, in a +Diff; on a +Diff, show the diff itself as text. `Diff <file>` stacks that diff's, `Diff <revision>` git show's.
/// The diff viewer's one registration: its word and traits here, all else
/// its own (hunks.zig).
pub const Diff = struct {
- pub const needs: PaneKind = .diff;
+ pub const takes_arg = true;
pub const output: OutputTraits = .{ .name = config.diff_buffer, .steps = true, .locations = true };
pub const run = @import("hunks.zig").word;
};
@@ -1339,25 +1311,36 @@ pub const Config = struct {
pub fn run(c: Ctx) void {
const path = c.p.startupPath() orelse
return c.p.reportFailure(c.id, "Config: no startup file here: no configuration directory");
- var real_buf: [4096]u8 = undefined;
- const real = if (pardes.filesystem.resolveOs(path, &real_buf)) |r| r.path else null;
- for (c.p.panes, 0..) |slot, id| {
- const pane = slot orelse continue;
- const f = pane.file orelse continue;
- if (f.output != null) continue;
- if (!std.mem.eql(u8, f.path, path) and !(if (real) |r| std.mem.eql(u8, f.path, r) else false)) continue;
- return look.focusPaneLine(c.p, id, .{}, .keep);
- }
- if (real != null) return look.lookAt(c.p, c.id, path);
- // Not there yet: a pane named for it, which Save makes.
- const free = c.p.freeSlot() orelse return c.p.reportError(c.id, "Config", error.NoPaneSlots);
- panes.newScratchFor(c.p, c.id, .scratch);
- if (c.p.panes[free] == null) return;
- @import("ninep/pane.zig").nameBuffer(c.p, free, path, false) catch |err| return c.p.reportError(c.id, "Config", err);
- c.p.view().active = free;
+ openConfigFile(c, "Config", path, "");
}
};
+/// A file of the configuration directory's (Config's init, Plumb's
+/// plumbing) in a pane: its pane when it is open, else the file, else a
+/// pane of that name holding `initial`, for Save to make it and its
+/// directory.
+fn openConfigFile(c: Ctx, name: []const u8, path: []const u8, initial: []const u8) void {
+ var real_buf: [4096]u8 = undefined;
+ const real = if (pardes.filesystem.resolveOs(path, &real_buf)) |r| r.path else null;
+ for (c.p.panes, 0..) |slot, id| {
+ const pane = slot orelse continue;
+ const f = pane.file orelse continue;
+ if (f.output != null) continue;
+ if (!std.mem.eql(u8, f.path, path) and !(if (real) |r| std.mem.eql(u8, f.path, r) else false)) continue;
+ return look.focusPaneLine(c.p, id, .{}, .keep);
+ }
+ if (real != null) return look.lookAt(c.p, c.id, path);
+ // Not there yet: a pane named for it, which Save makes.
+ const free = c.p.freeSlot() orelse return c.p.reportError(c.id, name, error.NoPaneSlots);
+ panes.newScratchFor(c.p, c.id, .scratch);
+ const made = c.p.panes[free] orelse return;
+ @import("ninep/pane.zig").nameBuffer(c.p, free, path, false) catch |err| return c.p.reportError(c.id, name, err);
+ if (initial.len > 0) if (made.file) |*f| {
+ _ = panes.File.replace(c.p, f, 0, f.content.len, initial);
+ };
+ c.p.view().active = free;
+}
+
/// Open the settings in effect, each a word to click, and the startup
/// file's path.
pub const DumpConfig = struct {
diff --git a/src/config.zig b/src/config.zig
index 8a1528a8..0568fa26 100644
--- a/src/config.zig
+++ b/src/config.zig
@@ -1828,6 +1828,7 @@ test "reference.typ's #fstree is the tree the session serves, file for file" {
const under = if (f.inPty() and f != .pty) "pane/<n>/pty/" else "pane/<n>/";
try served.put(gpa, try std.fmt.allocPrint(gpa, "{s}{s}{s}", .{ under, f.fileName(), if (f.isDir()) "/" else "" }), {});
};
+ try served.put(gpa, "plumb/<port>", {});
try served.put(gpa, "col/<n>/", {});
for (std.enums.values(tree.ColFile)) |f| if (f != .dir)
try served.put(gpa, try std.fmt.allocPrint(gpa, "col/<n>/{s}", .{f.fileName()}), {});
diff --git a/src/exec.zig b/src/exec.zig
index b4c20f45..5f5a2206 100644
--- a/src/exec.zig
+++ b/src/exec.zig
@@ -746,7 +746,7 @@ pub fn runCommand(p: *Pardes, from: usize, line: []const u8) ?usize {
// Nor one leased: an open that was answered its serial and is still
// open reads that pane's output, which another client's command must
// not replace; a new pane runs it instead.
- const reuse: ?usize = if (!p.exec_header and p.exec_column == null and p.exec_dir == null and src != null and src.?.command != null and src.?.command_done and !src.?.command_pty and !leased(p, src.?.serial)) from else for (p.panes, 0..) |slot, i| {
+ const reuse: ?usize = if (!p.exec_header and p.exec_column == null and src != null and src.?.command != null and src.?.command_done and !src.?.command_pty and !leased(p, src.?.serial)) from else for (p.panes, 0..) |slot, i| {
const other = slot orelse continue;
if (p.exec_column) |c| if (if (layout.findPane(p, i)) |f| f.col != c else true) continue;
if (other.command != null and other.command_done and !other.command_pty and std.mem.eql(u8, other.cwdSlice(), dir) and !leased(p, other.serial)) break i;
@@ -903,6 +903,7 @@ pub fn executeBuiltinLine(p: *Pardes, id: usize, txt: []const u8) bool {
}
pub fn applyStartupConfig(p: *Pardes) void {
+ @import("Plumb.zig").boot(p);
applyInitText(p, p.opts.startup_config orelse return, false);
}
diff --git a/src/fs-help.txt b/src/fs-help.txt
index 4e43a476..9a87843d 100644
--- a/src/fs-help.txt
+++ b/src/fs-help.txt
@@ -19,7 +19,7 @@ recent files opened lately, closed ones too: open|closed <path>
dumps the dumps the state file keeps, the newest first: <label> <date> <size> <panes>
layout a line per column: serial index x width current|notcurrent empty|full pane-serials; then active <serial>
tag the workspace tag, tagexec a word as a click in it; col/<serial>/ a column's tag, ctl, exec; rmdir: empty only
-plumb/ rules: the plumber's rules, plumb(6)'s (a write adds rule sets, > replaces); send: write a message, six lines then data
+plumb/ rules: the plumber's rules, plumb(6)'s (a write adds rule sets, > replaces); send: write a message, six lines then data; <port>: read the messages sent to it
pane/new open it to make a pane (<session dir>/+New) in the active column; the read answers its serial
pane/<n>/ name body tag ctl addr dot limit data xdata sel dirty mark scroll errors event look exec tagexec rows; rmdir closes
rows: a line a row, kind (m c p; d decl, u unmarked) line col end_line end_col source_column location_end code_start styles path; styles - or N:start+len=role,... (keyword string number comment, add del emph line, joined by .); a write at 0 replaces
diff --git a/src/fs.zig b/src/fs.zig
index b5cb979b..f6bf4fed 100644
--- a/src/fs.zig
+++ b/src/fs.zig
@@ -948,6 +948,10 @@ pub const Namespace = struct {
/// The editor-wide event ring: panes made, renamed, saved and closed, and
/// what the editor said. Recorded whether or not anyone reads /log.
log: tree.events.Queue = .{ .cap = limits.log_bytes },
+ /// Messages a plumbing rule's `client` holds for a port no one reads
+ /// yet (Plumb.zig), each its port's index then the message packed: the
+ /// port's first reader takes them (plumber(4)'s queueheld).
+ plumb_held: tree.events.Queue = .{},
/// What the last look or exec created or touched, answered by reading
/// either of those files.
results: [MAX_PANES]u32 = undefined,
@@ -969,6 +973,7 @@ pub const Namespace = struct {
for (st.closed_lines.items) |*line| line.bytes.deinit(gpa);
st.closed_lines.deinit(gpa);
st.log.deinit(gpa);
+ st.plumb_held.deinit(gpa);
st.out.deinit(gpa);
}
diff --git a/src/gui/gui.zig b/src/gui/gui.zig
index 1ec3bca3..d4603bec 100644
--- a/src/gui/gui.zig
+++ b/src/gui/gui.zig
@@ -2966,6 +2966,7 @@ const Shell = struct {
.set_clipboard = setClipboard,
.read_clipboard = readClipboard,
.open_link = openLink,
+ .start = host_io.startDetached,
.lsp = lsp,
.pipe = pipe,
.search = search,
diff --git a/src/host_io.zig b/src/host_io.zig
index 0e1d29fd..206341f9 100644
--- a/src/host_io.zig
+++ b/src/host_io.zig
@@ -59,6 +59,9 @@ pub const Host = struct {
set_clipboard: ?*const fn (ctx: ?*anyopaque, text: []const u8) void = null,
read_clipboard: ?*const fn (ctx: ?*anyopaque) void = null,
open_link: ?*const fn (ctx: ?*anyopaque, url: []const u8) void = null,
+ /// A plumbing rule's program (Effect.start): every host's is
+ /// startDetached. Null once it runs, else why not.
+ start: ?*const fn (ctx: ?*anyopaque, line: []const u8, why: []u8) ?[]const u8 = null,
lsp: ?*const fn (ctx: ?*anyopaque, req: Lsp.Request) void = null,
pipe: ?*const fn (ctx: ?*anyopaque, id: u32) void = null,
/// Start the streaming search of this generation on a worker
@@ -268,6 +271,9 @@ pub const Fallback = struct {
files: std.StringHashMapUnmanaged([]u8) = .empty,
clipboard: std.ArrayListUnmanaged(u8) = .empty,
link: std.ArrayListUnmanaged(u8) = .empty,
+ /// The programs plumbing rules started, as Effect.start packs them,
+ /// one a line.
+ started: std.ArrayListUnmanaged(u8) = .empty,
spawned: [pardes.MAX_PANES]bool = @splat(false),
watched: [pardes.MAX_PANES]bool = @splat(false),
@@ -280,6 +286,7 @@ pub const Fallback = struct {
f.files.deinit(f.gpa);
f.clipboard.deinit(f.gpa);
f.link.deinit(f.gpa);
+ f.started.deinit(f.gpa);
}
pub fn writeFile(f: *Fallback, path: []const u8, bytes: []const u8) bool {
@@ -315,6 +322,12 @@ pub const Fallback = struct {
f.link.clearRetainingCapacity();
f.link.appendSlice(f.gpa, url) catch {};
}
+
+ pub fn start(f: *Fallback, line: []const u8) ?[]const u8 {
+ f.started.appendSlice(f.gpa, line) catch return "out of memory";
+ f.started.append(f.gpa, '\n') catch return "out of memory";
+ return null;
+ }
};
/// What a pixel host's loop takes from its workers, in order: each pane's
@@ -2456,6 +2469,108 @@ const darwin = struct {
}
};
+/// A program a plumbing rule starts (Effect.start), as Plan 9's plumber
+/// starts one (match.c's startup): out of the editor's way, a session of
+/// its own reaped by init, stdin, stdout and stderr /dev/null and no other
+/// fd of the editor's, its argv exec'd (no shell: a rule that wants one
+/// says `sh -c`) in its directory. `line` is its directory, then its argv,
+/// each ended by a NUL. Null once it runs, else why not, as errno says it,
+/// in `why` (as the tape replays a host's words): a pipe closed at the
+/// exec carries the child's errno back.
+pub fn startDetached(_: ?*anyopaque, line: []const u8, why: []u8) ?[]const u8 {
+ const words = startWords(line) orelse return null;
+ const n = @min(words.len, why.len);
+ @memcpy(why[0..n], words[0..n]);
+ return why[0..n];
+}
+
+fn startWords(line: []const u8) ?[]const u8 {
+ var buf: [pardes.effect_path_cap]u8 = undefined;
+ if (line.len == 0 or line.len > buf.len or line[line.len - 1] != 0) return "malformed";
+ @memcpy(buf[0..line.len], line);
+ var argv: [64:null]?[*:0]const u8 = @splat(null);
+ var n: usize = 0;
+ var at: usize = 0;
+ var dir: [*:0]const u8 = undefined;
+ while (at < line.len) {
+ const end = std.mem.indexOfScalarPos(u8, line, at, 0).?;
+ const word: [*:0]const u8 = @ptrCast(&buf[at]);
+ if (at == 0) dir = word else if (n < argv.len) {
+ argv[n] = word;
+ n += 1;
+ } else return "more than 64 words";
+ at = end + 1;
+ }
+ if (n == 0) return "no program";
+ var fds: [2]c_int = undefined;
+ if (libc.pipe(&fds) != 0) return "no pipe";
+ for (fds) |fd| _ = libc.fcntl(fd, libc.F.SETFD, @as(c_int, libc.FD_CLOEXEC));
+ const first = libc.fork();
+ if (first < 0) {
+ _ = libc.close(fds[0]);
+ _ = libc.close(fds[1]);
+ return "no fork";
+ }
+ if (first == 0) {
+ // Only async-signal-safe calls between fork and exec.
+ _ = libc.setsid();
+ if (libc.fork() != 0) libc._exit(0);
+ resetChildSignals();
+ // What failed, then errno: 'd' the directory, 'x' the exec.
+ const Fail = struct {
+ fn say(fd: c_int, what: u8) noreturn {
+ var said: [5]u8 = undefined;
+ said[0] = what;
+ std.mem.writeInt(u32, said[1..5], @intFromEnum(libc.errno(-1)), .little);
+ _ = libc.write(fd, &said, said.len);
+ libc._exit(127);
+ }
+ };
+ const err_fd = libc.fcntl(fds[1], libc.F.DUPFD_CLOEXEC, @as(c_int, 3));
+ if (err_fd < 0) libc._exit(127);
+ if (dir[0] != 0 and libc.chdir(dir) != 0) Fail.say(err_fd, 'd');
+ const null_fd = libc.open("/dev/null", .{ .ACCMODE = .RDWR }, @as(libc.mode_t, 0));
+ if (null_fd >= 0) for (0..3) |i| {
+ _ = libc.dup2(null_fd, @intCast(i));
+ };
+ // Every fd of the editor's but the errno pipe's gone: a pty's
+ // master held open would keep its terminal alive.
+ if (libc.dup2(err_fd, 3) < 0) libc._exit(127);
+ _ = libc.fcntl(3, libc.F.SETFD, @as(c_int, libc.FD_CLOEXEC));
+ const shut = if (comptime builtin.os.tag == .linux)
+ std.os.linux.close_range(4, std.math.maxInt(i32), .{ .UNSHARE = false, .CLOEXEC = false }) == 0
+ else
+ false;
+ if (!shut) {
+ var fd: c_int = 4;
+ while (fd < 1024) : (fd += 1) _ = libc.close(fd);
+ }
+ _ = execvp(argv[0].?, &argv);
+ Fail.say(3, 'x');
+ }
+ _ = libc.close(fds[1]);
+ while (libc.waitpid(first, null, 0) < 0 and libc.errno(-1) == .INTR) {}
+ var said: [5]u8 = undefined;
+ var got: usize = 0;
+ while (got < said.len) {
+ const r = libc.read(fds[0], said[got..].ptr, said.len - got);
+ if (r < 0 and libc.errno(r) == .INTR) continue;
+ if (r <= 0) break;
+ got += @intCast(r);
+ }
+ _ = libc.close(fds[0]);
+ if (got < said.len) return null;
+ const code = std.mem.readInt(u32, said[1..5], .little);
+ const E = libc.E;
+ if (code == @intFromEnum(E.NOENT)) return if (said[0] == 'd') "its directory: no such directory" else "not found";
+ if (code == @intFromEnum(E.ACCES)) return "permission denied";
+ if (code == @intFromEnum(E.NOTDIR)) return "not a directory";
+ if (code == @intFromEnum(E.NOEXEC)) return "not an executable";
+ return if (said[0] == 'd') "its directory: cannot go there" else "cannot start it";
+}
+
+extern "c" fn execvp(file: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int;
+
/// A terminal pane's shell is done with (its pane gone, its pty closed or at
/// end of file): say hangup, for a shell that ignores the tty's, and see it
/// reaped, killed if it is still there 100 ms on. A thread does the waiting
@@ -3004,6 +3119,8 @@ pub fn writeFile(core: *pardes.Pardes, watches: *file_watch.Table, pane: u8, pat
core.setMessage(pane, pardes.Messages.Message.stamp(&mbuf, "saved", path));
// The init file, saved here (Config): its settings take effect now.
pardes.exec.reapplyInitFile(core, path, bytes);
+ // The plumbing file (Plumb): its rules in force now.
+ pardes.Plumb.saved(core, pane, path, bytes);
}
/// A Dump's write: into the state file under a label of its own
@@ -3863,3 +3980,12 @@ test "LSP query answers, and a newer one cancels it" {
core.update(.{ .lsp_resp = .{ .id = last, .rows = batch.items[0].lsp.rows } });
try std.testing.expect(core.lsp_ask.wait == null);
}
+
+test "a plumbing rule's program starts detached, or says why not: a program not found, a directory not there" {
+ if (comptime builtin.os.tag != .linux) return;
+ var why: [64]u8 = undefined;
+ try std.testing.expect(startDetached(null, "/\x00true\x00", &why) == null);
+ try std.testing.expectEqualStrings("not found", startDetached(null, "/\x00no-such-program-x\x00", &why).?);
+ try std.testing.expectEqualStrings("its directory: no such directory", startDetached(null, "/no/such/dir\x00true\x00", &why).?);
+ try std.testing.expectEqualStrings("malformed", startDetached(null, "/\x00true", &why).?);
+}
diff --git a/src/hunks.zig b/src/hunks.zig
index afd2ac9d..2fa86ccd 100644
--- a/src/hunks.zig
+++ b/src/hunks.zig
@@ -601,45 +601,83 @@ fn trimmedWidth(section: []const u8) usize {
// ---- the +Diff in the editor ----
//
-// Its word (Diff), the open and the text it goes back to; and the three
-// hooks the generic code calls, one call each (look.zig's bare look and
-// commit look, ninep/ctl.zig's filled +Pager), which a plumber's rules
-// would replace.
+// Its word (Diff), the open and the text it goes back to, and the
+// restack of a paged diff. A bare look at a .diff, a commit hash and a
+// paged diff are plumbing rules (src/plumbing) that start Diff or ask the
+// edit port to show the diff (Plumb.show).
-/// The `Diff` word (builtins.zig registers it): on a +Diff, the diff it
-/// stacks as text; on a diff, its hunks stacked in a +Diff.
+/// The `Diff` word (builtins.zig registers it). Bare, on a +Diff, the diff
+/// it stacks as text; on a diff, its hunks stacked in a +Diff. With a file
+/// (a .diff, a .patch: relative to the pane's directory), its hunks
+/// stacked so; with a revision (7 to 40 lowercase hex digits, a letter and
+/// a digit among them), `git show` of it, paged into a +Pager that stacks
+/// its hunks (ctl.fillPager), run in the pane's git work tree. A plumbing
+/// rule's Diff that cannot (no hunk, no work tree) declines, saying
+/// nothing (Pardes.plumb_declined), and the look looks itself.
pub fn word(c: pardes.builtins.Ctx) void {
- const f = &c.pane.file.?;
- if (diffSource(c.p, f)) |source| return showDiffText(c.p, c.id, source);
- _ = openDiff(c.p, c.id, f.path, f.content) catch |err| switch (err) {
- error.NoHunks => c.p.reportFailure(c.id, "Diff: no hunk in it"),
- else => c.p.reportError(c.id, "hunks", err),
+ const p = c.p;
+ const arg = std.mem.trim(u8, c.arg orelse "", " \t\r\n");
+ if (arg.len == 0) {
+ if (!shows(c.pane)) return p.reportFailure(c.id, "Diff: only a diff or a +Diff pane takes it");
+ const f = &c.pane.file.?;
+ if (diffSource(p, f)) |source| return showDiffText(p, c.id, source);
+ _ = openDiff(p, c.id, f.path, f.content) catch |err| switch (err) {
+ error.NoHunks => p.reportFailure(c.id, "Diff: no hunk in it"),
+ else => p.reportError(c.id, "hunks", err),
+ };
+ return;
+ }
+ if (isCommitHash(arg)) {
+ var dir = pardes.filesystem.localPath(Pardes.paneDir(c.pane)) orelse return declined(p, c.id, "Diff: not in a git work tree");
+ while (true) {
+ var buf: [4096]u8 = undefined;
+ const dot_git = std.fmt.bufPrint(&buf, "{s}/.git", .{dir}) catch return declined(p, c.id, "Diff: not in a git work tree");
+ if (pardes.exec.kindOf(dot_git) != null) break;
+ dir = std.Io.Dir.path.dirname(dir) orelse return declined(p, c.id, "Diff: not in a git work tree");
+ }
+ // ponytail: a hex word that names no commit leaves git's error in a command pane, not a search; check the object first if that bites.
+ var line: [64]u8 = undefined;
+ const dst = pardes.exec.execute(p, c.id, std.fmt.bufPrint(&line, "git show {s}", .{arg}) catch unreachable) orelse return;
+ if (p.panes[dst]) |cp| cp.command_pages = true;
+ return;
+ }
+ var buf: [4096]u8 = undefined;
+ const path = if (arg[0] == '/') arg else std.fmt.bufPrint(&buf, "{s}/{s}", .{ std.mem.trimEnd(u8, Pardes.paneDir(c.pane), "/"), arg }) catch arg;
+ const bytes = pardes.filesystem.read(p, path) catch |err| {
+ if (p.plumb_declined != null) return declined(p, c.id, "");
+ return p.reportError(c.id, path, err);
+ };
+ defer p.gpa.free(bytes);
+ p.view().active = openDiff(p, c.id, path, bytes) catch |err| switch (err) {
+ error.NoHunks => return declined(p, c.id, "Diff: no hunk in it"),
+ else => {
+ if (p.plumb_declined != null) return declined(p, c.id, "");
+ return p.reportError(c.id, "hunks", err);
+ },
};
}
-/// A pane the word works on: a diff (a .diff, a .patch, a +Pager holding
-/// one) or a +Diff.
-pub fn shows(pane: *const Pane) bool {
- const f = pane.file orelse return false;
- return pane.colorAlgo() == .diff or (f.output != null and std.meta.eql(f.output.?.from, Output.Origin{ .cmd = .Diff }));
+/// A Diff that cannot do what it was asked: a plumbing rule's declines,
+/// saying nothing; one typed says `why`.
+fn declined(p: *Pardes, id: usize, why: []const u8) void {
+ if (p.plumb_declined) |*d| {
+ d.* = true;
+ return;
+ }
+ p.reportFailure(id, why);
}
-/// The hook of a bare look at a .diff or a .patch (look.zig's open): its
-/// hunks stacked in a +Diff, which takes the keyboard as the file would;
-/// false, for look to open it as text, when it is no such file, a place in
-/// one, one with no hunk, or the text is what is asked (showDiffText).
-pub fn lookedAt(p: *Pardes, id: usize, path: []const u8, at: pardes.look.Spot) bool {
- if (p.look_text or at.line != 0 or !(std.mem.endsWith(u8, path, ".diff") or std.mem.endsWith(u8, path, ".patch"))) return false;
- const bytes = pardes.filesystem.read(p, path) catch return false;
- defer p.gpa.free(bytes);
- p.view().active = openDiff(p, id, path, bytes) catch return false;
- return true;
+/// A pane the bare word works on: a diff (a .diff, a .patch, a +Pager
+/// holding one) or a +Diff.
+fn shows(pane: *const Pane) bool {
+ const f = pane.file orelse return false;
+ return pane.colorAlgo() == .diff or (f.output != null and std.meta.eql(f.output.?.from, Output.Origin{ .cmd = .Diff }));
}
-/// The hook of a +Pager filled with a diff (ninep/ctl.zig's fillPager:
-/// `git show`, difftui's patches): its hunks stacked in a +Diff in the
-/// +Pager's place, the +Pager closed. The keyboard stays where it was, as
-/// a page's.
+/// A pane holding a diff (a +Pager filled with one: `git show`, difftui's
+/// patches; the edit port's `showdiff`, Plumb.show): its hunks stacked in
+/// a +Diff in its place, the pane closed. The keyboard stays where it was,
+/// as a page's.
pub fn paged(p: *Pardes, id: usize) void {
const f = &p.panes[id].?.file.?;
const keyboard = p.view().active;
@@ -650,26 +688,6 @@ pub fn paged(p: *Pardes, id: usize) void {
if (p.panes[keyboard] != null) p.view().active = keyboard;
}
-/// The hook of a commit hash (7 to 40 hex digits, a letter and a digit
-/// among them; look.zig's look at a word) looked at inside a git repository: `git show` it, paged into a +Pager,
-/// which stacks its hunks in a +Diff (ctl.fillPager); the command pane
-/// goes when it succeeds (Pane.commandDone).
-// ponytail: a hex word that names no commit leaves git's error in a command pane, not a search; check the object first if that bites.
-pub fn lookedAtCommit(p: *Pardes, id: usize, pane: *Pane, hash: []const u8) bool {
- if (!isCommitHash(hash)) return false;
- var dir = pardes.filesystem.localPath(Pardes.paneDir(pane)) orelse return false;
- while (true) {
- var buf: [4096]u8 = undefined;
- const dot_git = std.fmt.bufPrint(&buf, "{s}/.git", .{dir}) catch return false;
- if (pardes.exec.kindOf(dot_git) != null) break;
- dir = std.Io.Dir.path.dirname(dir) orelse return false;
- }
- var line: [64]u8 = undefined;
- const dst = pardes.exec.execute(p, id, std.fmt.bufPrint(&line, "git show {s}", .{hash}) catch return false) orelse return true;
- if (p.panes[dst]) |c| c.command_pages = true;
- return true;
-}
-
fn isCommitHash(hex: []const u8) bool {
if (hex.len < 7 or hex.len > 40) return false;
var digit = false;
diff --git a/src/look.zig b/src/look.zig
index 115e3683..b32c46ac 100644
--- a/src/look.zig
+++ b/src/look.zig
@@ -4,7 +4,7 @@ const builtin = @import("builtin");
const libc = std.c;
const pardes = @import("pardes.zig");
const exec = @import("exec.zig");
-const hunks = @import("hunks.zig");
+const Plumb = @import("Plumb.zig");
const config = @import("config.zig");
const diff = @import("diff.zig");
const platform_has_fs = filesystem.platform_has_fs;
@@ -153,56 +153,6 @@ pub fn lineSpan(p: ?*pardes.Pardes, line: []const u8, cwd: []const u8, realbuf:
return null;
}
-/// Where a `Plumb` rule sends what it matched: the targets the built-in
-/// rules below make (url: the browser, through `xdg-open`), or a loaded
-/// kind by its name (`image`, `pdf`).
-pub const Port = enum { url, dir, file };
-
-/// A rule as `Plumb` takes it, plumb(6)'s order on one line: `<test>
-/// [word ...] to <port>`, the test `prefix` (the text starts so), `suffix`
-/// (an existing file's name ends so, any case), `isdir` or `isfile`; the
-/// port `url`, `dir`, `file` or a kind `kinds` has.
-/// Null when it is one; otherwise what is wrong with it, said.
-pub fn plumbRuleError(kinds: *const Kind.Registry, rule: []const u8) ?[]const u8 {
- var words = std.mem.tokenizeAny(u8, rule, " \t");
- const how = words.next() orelse return "a rule: <test> [word ...] to <port>";
- const takes = if (std.mem.eql(u8, how, "prefix") or std.mem.eql(u8, how, "suffix"))
- true
- else if (std.mem.eql(u8, how, "isdir") or std.mem.eql(u8, how, "isfile"))
- false
- else
- return "invalid test: prefix, suffix, isdir or isfile";
- var n: usize = 0;
- while (words.next()) |w| : (n += 1) {
- if (!std.mem.eql(u8, w, "to")) continue;
- if (takes and n == 0) return "invalid rule: prefix and suffix take a word";
- if (!takes and n > 0) return "invalid rule: isdir and isfile take no word";
- const port = words.next() orelse return "invalid rule: to names no port";
- if (std.meta.stringToEnum(Port, port) == null and kinds.byName(port) == null)
- return "invalid port: url, dir, file or a loaded kind";
- if (words.next() != null) return "invalid rule: a word after the port";
- return null;
- }
- return "invalid rule: no `to <port>`";
-}
-
-/// What a rule's port makes of what it matched; null when it cannot (no
-/// such file, a directory to `file`, a kind gone since): the next rule tries.
-fn plumbTarget(p: *pardes.Pardes, port: []const u8, text: []const u8, found: ?filesystem.Resolved, at: Spot) ?Target {
- const to = std.meta.stringToEnum(Port, port);
- if (to == .url) return .{ .url = if (found) |f| f.path else text };
- const f = found orelse return null;
- if (to == null) {
- const k = p.kinds.byName(port) orelse return null;
- return if (f.dir) null else .{ .kind = .{ .path = f.path, .kind = k, .at = at } };
- }
- return switch (to.?) {
- .url => unreachable,
- .dir => if (f.dir) .{ .dir = f.path } else null,
- .file => if (f.dir) null else .{ .file = .{ .path = f.path, .at = at } },
- };
-}
-
pub fn resolve(p: ?*pardes.Pardes, word_raw: []const u8, cwd: []const u8, realbuf: *[4096]u8) Target {
const trimmed = std.mem.trim(u8, word_raw, " \t\r\n");
const pl = parsePathLine(trimmed);
@@ -225,42 +175,6 @@ pub fn resolve(p: ?*pardes.Pardes, word_raw: []const u8, cwd: []const u8, realbu
}
}
- if (p) |pp| if (pp.plumb.items.len > 0) {
- var found: ?filesystem.Resolved = null;
- var looked = false;
- for (pp.plumb.items) |rule| {
- var words = std.mem.tokenizeAny(u8, rule, " \t");
- const how = words.next() orelse continue;
- // The file is asked about once, and only by a rule that needs it.
- const prefix = std.mem.eql(u8, how, "prefix");
- if (!looked and !prefix) {
- found = filesystem.resolve(p, word, cwd, realbuf);
- looked = true;
- }
- const file = if (found) |f| !f.dir else false;
- var hit = std.mem.eql(u8, how, "isfile") and file or
- std.mem.eql(u8, how, "isdir") and found != null and !file;
- var port: []const u8 = "";
- while (words.next()) |w| {
- if (std.mem.eql(u8, w, "to")) {
- port = words.next() orelse "";
- break;
- }
- if (prefix and std.mem.startsWith(u8, trimmed, w)) hit = true;
- // A suffix is a file's: plumb's basic pairs each with `arg isfile`.
- if (std.mem.eql(u8, how, "suffix") and file and std.ascii.endsWithIgnoreCase(found.?.path, w)) hit = true;
- }
- if (!hit) continue;
- const url = std.mem.eql(u8, port, "url");
- if (!looked and !url) {
- found = filesystem.resolve(p, word, cwd, realbuf);
- looked = true;
- }
- // A prefix rule's url is the text, never a file it also names.
- if (plumbTarget(pp, port, trimmed, if (prefix and url) null else found, pl.at)) |t| return t;
- }
- };
-
for (config.url_schemes) |scheme| {
if (std.mem.startsWith(u8, trimmed, scheme)) return .{ .url = trimmed };
}
@@ -873,25 +787,59 @@ pub fn clearNavigationSelection(p: *Pardes, pane: *Pane) void {
if (v.drag == .select and p.panes[v.drag.select.id] == pane) v.drag = .none;
}
+/// The directories a relative name is looked for in, in order, as acme's
+/// look tries its window's and then the other windows' (Incl's come
+/// after, the caller's, as includename's): `first` (the pane's own, a
+/// plumb message's wdir), then the directory of each pane of the jump list
+/// but `from`, newest first, each once.
+pub const Dirs = struct {
+ p: *Pardes,
+ from: ?usize,
+ seen: [MAX_PANES + 1][]const u8 = undefined,
+ nseen: usize = 0,
+ /// The next of the jump list's, counted from its newest.
+ n: usize = 1,
+
+ pub fn init(p: *Pardes, from: ?usize, first: ?[]const u8) Dirs {
+ var d: Dirs = .{ .p = p, .from = from };
+ if (first) |dir| {
+ d.seen[0] = dir;
+ d.nseen = 1;
+ d.n = 0;
+ }
+ return d;
+ }
+
+ pub fn next(d: *Dirs) ?[]const u8 {
+ if (d.n == 0) {
+ d.n = 1;
+ return d.seen[0];
+ }
+ const id = d.from orelse return null;
+ const jumps = &d.p.view().jumps;
+ cand: while (d.n <= jumps.n) {
+ const k = jumps.list[jumps.n - d.n].pane;
+ d.n += 1;
+ if (k == id) continue;
+ const dir = Pardes.paneDir(d.p.panes[k] orelse continue);
+ for (d.seen[0..d.nseen]) |s| if (std.mem.eql(u8, s, dir)) continue :cand;
+ d.seen[d.nseen] = dir;
+ d.nseen += 1;
+ return dir;
+ }
+ return null;
+ }
+};
+
/// Resolve without changing focus or falling back to search. PDF links use
/// the same location rules as an ordinary Look before offering a choice.
fn resolveLookTarget(p: *Pardes, id: usize, txt: []const u8, realbuf: *[4096]u8) Target {
- const v = p.view();
const trimmed = std.mem.trim(u8, txt, " \t\r\n");
const pl = parsePathLine(trimmed);
if (pl.path.len > 0) if (openPaneTarget(p, pl.path, pl.at)) |target| return target;
var found: Target = .none;
- var seen: [MAX_PANES][]const u8 = undefined;
- var nseen: usize = 0;
- var n: usize = 0;
- cand: while (n <= v.jumps.n) : (n += 1) {
- const k: usize = if (n == 0) id else v.jumps.list[v.jumps.n - n].pane;
- if (n > 0 and k == id) continue; // tried first, skip the rerun
- const op = p.panes[k] orelse continue;
- const dir = Pardes.paneDir(op);
- for (seen[0..nseen]) |s| if (std.mem.eql(u8, s, dir)) continue :cand;
- seen[nseen] = dir;
- nseen += 1;
+ var dirs: Dirs = .init(p, id, if (p.panes[id]) |op| Pardes.paneDir(op) else null);
+ while (dirs.next()) |dir| {
if (pl.path.len > 0 and pl.path[0] != '/') {
var joinbuf: [2048]u8 = undefined;
if (std.fmt.bufPrint(&joinbuf, "{s}/{s}", .{ dir, pl.path }) catch null) |j|
@@ -1090,7 +1038,6 @@ fn lookUnresolved(p: *Pardes, id: usize, pane: *Pane, trimmed: []const u8, text:
// 9P is no keyboard input, and searches whatever the key mode.
if (pane.addon != null or (pane.body.mode == .tty and !p.fs.serving)) return;
if (text.len == 0) return;
- if (hunks.lookedAtCommit(p, id, pane, trimmed)) return;
if (pane.file != null) return lookWord(p, id, pane, text);
p.word_look = true;
defer p.word_look = false;
@@ -1558,6 +1505,36 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void {
for (0..pane.sel.len) |slot| pane.clearPointerSelection(slot);
pane.sel = @splat(.{});
}
+ // The plumber, asked before Look's own look as acme asks it (look.c's
+ // look3): what is looked at, sent from this pane. A name already open
+ // in a pane is focused first, never sent; nor is a look that opens
+ // as text (look_text), or the edit port's open of what was. A message
+ // the rules give back to `edit` as sent is Look's own to open, on what
+ // it found; one nothing takes, Look's too.
+ const shown = switch (found) {
+ .pane => true,
+ .file => |f| openPaneTarget(p, f.path, f.at) != null,
+ .kind => |k| openPaneTarget(p, k.path, .{}) != null,
+ .none, .dir, .url => false,
+ };
+ if (!shown and !p.look_text) {
+ const msg: Plumb.Msg = .{
+ .src = if (pane.addon) |k| k.nameOf() else if (pane.body.mode == .tty and !p.fs.serving) "term" else "pardes",
+ .wdir = Pardes.paneDir(pane),
+ .type = "text",
+ .data = trimmed,
+ };
+ const seen: Plumb.Seen = .{ .name = pl.path, .found = switch (found) {
+ .file => |f| .{ .path = f.path },
+ .kind => |k| .{ .path = k.path },
+ .dir => |d| .{ .path = d, .dir = true },
+ .none, .url, .pane => null,
+ } };
+ switch (Plumb.send(p, id, msg, seen)) {
+ .done => return,
+ .look, .refused => {},
+ }
+ }
switch (found) {
.none => lookUnresolved(p, id, pane, trimmed, std.mem.trimEnd(u8, txt, "\r\n")),
.pane => |t| {
@@ -1582,7 +1559,8 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void {
focusPaneLine(p, t.id, t.at, .center);
settleLine(p, id, trimmed, t.at, before, null);
},
- .url => |u| if (u.len <= 256) p.emit(.{ .open_link = .from(u) }),
+ // acme's own look opens no URL: the plumber's web port does.
+ .url => lookUnresolved(p, id, pane, trimmed, std.mem.trimEnd(u8, txt, "\r\n")),
.dir => |dir| {
// A directory that is not there (the pane's own, gone): said,
// ENOENT, no terminal made in it.
@@ -1603,7 +1581,6 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void {
const before = v.active;
var opened: ?usize = null;
if (!focusPaneByPath(p, target.path, target.at)) {
- if (hunks.lookedAt(p, id, target.path, target.at)) return;
const free = p.freeSlot() orelse return p.reportError(id, "look", error.NoPaneSlots);
const nt = panes.File.open(p, free, target.path, target.at.line) catch |err|
return lookOpenFailed(p, id, target.path, err);
@@ -2649,51 +2626,83 @@ test "Look on a diff line is the look of the address it names, selected by hand:
try std.testing.expectEqual(@as(i32, 1), seen[0].row);
}
-test "Plumb: the user's rules come before the built-in ones, the first that matches wins, a bad rule is refused, a dump keeps them" {
+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/>" });
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "shot.PNG", .data = "x" });
var dir_buf: [4096]u8 = undefined;
const root = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)];
+ var pic_buf: [4200]u8 = undefined;
+ const pic = try std.fmt.bufPrint(&pic_buf, "{s}/pic.svg", .{root});
const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 30 });
defer p.deinit();
- // A kind as a library brings it, its name and extension (no code: a
- // look only names it).
- try std.testing.expect(p.kinds.take(.{ .name = "image", .exts = ".png" }, "") == null);
+ const pane = try p.setTestFile("see https://ziglang.org here\n");
+ // The defaults: a URL to the web port, the host's opener; the hover
+ // asks resolve, as before.
+ lookAt(p, 0, "https://ziglang.org");
+ var linked = false;
+ while (p.nextEffect()) |e| if (e == .open_link) {
+ try std.testing.expectEqualStrings("https://ziglang.org", e.open_link.slice());
+ linked = true;
+ };
+ try std.testing.expect(linked);
var real: [4096]u8 = undefined;
- // None by default: today's ladder.
- try std.testing.expect(resolve(p, "pic.svg", root, &real) == .file);
- try std.testing.expect(resolve(p, "shot.PNG", root, &real) == .kind);
- try std.testing.expect(resolve(p, "https://ziglang.org", root, &real) == .url);
- try std.testing.expect(p.executeBuiltinLine(0, "Plumb suffix .svg .SVGZ to image"));
- try std.testing.expect(p.executeBuiltinLine(0, "Plumb suffix .png to file"));
- try std.testing.expect(p.executeBuiltinLine(0, "Plumb prefix https:// to file"));
- try std.testing.expect(p.executeBuiltinLine(0, "Plumb prefix gopher:// to url"));
- try std.testing.expect(resolve(p, "pic.svg", root, &real) == .kind);
- // Any case, as the kinds' extensions are.
- try std.testing.expect(resolve(p, "shot.PNG", root, &real) == .file);
- // A rule that cannot make its target (no such file) lets the next try.
try std.testing.expect(resolve(p, "https://ziglang.org", root, &real) == .url);
- try std.testing.expectEqualStrings("gopher://x", resolve(p, "gopher://x", root, &real).url);
- // A suffix is a file's: a word naming no file matches none.
- try std.testing.expect(resolve(p, "nothere.svg", root, &real) == .none);
- // Refused, in words, the list as it was: a kind not loaded too.
- for ([_][]const u8{ "Plumb matches x to image", "Plumb suffix to image", "Plumb isdir .x to dir", "Plumb suffix .x to nowhere", "Plumb suffix .x to pdf", "Plumb suffix .x", "Plumb suffix .x to image extra" }) |bad|
- try std.testing.expect(p.executeBuiltinLine(0, bad));
- try std.testing.expectEqual(@as(usize, 4), p.plumb.items.len);
- try std.testing.expectEqualStrings("suffix .svg .SVGZ to image", p.plumb.items[0]);
- try std.testing.expect(p.executeBuiltinLine(0, "Plumb"));
- const pane = p.panes[0].?;
- try std.testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "; suffix .png to file") != null);
- try pardes.dump.dumpState(p);
- const restored = try pardes.dump.restore(p, p.dump_out.?, "/tmp/pardes.dump.zon");
- defer restored.deinit();
- try std.testing.expectEqual(@as(usize, 4), restored.plumb.items.len);
- // The kind gone, its rule is tried like any that cannot: the ladder's.
- p.kinds.drop(p.kinds.byName("image").?);
- try std.testing.expect(resolve(p, "pic.svg", root, &real) == .file);
- try std.testing.expect(p.executeBuiltinLine(0, "Plumb -"));
- try std.testing.expectEqual(@as(usize, 0), p.plumb.items.len);
+ // A rule set written first takes what it matches: its word started in
+ // place, from the looking pane, and no pane opened.
+ try std.testing.expect(Plumb.apply(p, false, "plumb/rules", "type is text\ndata matches '.*\\.svg'\narg isfile $data\nplumb start Msg svg $file\n\ninclude basic\n") == null);
+ lookAt(p, 0, pic);
+ try std.testing.expectEqual(@as(usize, 0), p.view().active);
+ var said_buf: [4300]u8 = undefined;
+ try std.testing.expectEqualStrings(try std.fmt.bufPrint(&said_buf, "svg {s}", .{pic}), pane.msg[0..pane.msg_len]);
+ // A name open in a pane is focused, never sent.
+ p.look_text = true;
+ lookAt(p, 0, pic);
+ p.look_text = false;
+ const opened = p.view().active;
+ try std.testing.expect(opened != 0);
+ p.view().active = 0;
+ p.setMessage(0, "before");
+ lookAt(p, 0, pic);
+ try std.testing.expectEqual(opened, p.view().active);
+ try std.testing.expectEqualStrings("before", pane.msg[0..pane.msg_len]);
+ // With no web rule, a URL is a word Look searches for.
+ p.view().active = 0;
+ try std.testing.expect(Plumb.apply(p, false, "plumb/rules", "type is text\narg isfile $data\nplumb to edit\n") == null);
+ while (p.nextEffect()) |_| {}
+ lookAt(p, 0, "https://ziglang.org");
+ while (p.nextEffect()) |e| try std.testing.expect(e != .open_link);
+ const dot = @import("ninep/pane.zig").dotOf(pane);
+ try std.testing.expectEqualStrings("https://ziglang.org", pane.file.?.content[dot.q0..dot.q1]);
+}
+
+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 (!platform_has_fs) return;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.createDir(std.testing.io, ".git", .default_dir);
+ try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "notes.txt", .data = "fixed in 3f2a9c1\n" });
+ var dir_buf: [4096]u8 = undefined;
+ const root = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)];
+ const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 30 });
+ defer p.deinit();
+ // /test.txt: its directory, /, is in no work tree.
+ const pane = try p.setTestFile("fixed in 3f2a9c1\n");
+ lookAt(p, 0, "3f2a9c1");
+ const dot = @import("ninep/pane.zig").dotOf(pane);
+ try std.testing.expectEqualStrings("3f2a9c1", pane.file.?.content[dot.q0..dot.q1]);
+ for (p.panes) |slot| if (slot) |pn| try std.testing.expect(pn.command == null);
+ var notes_buf: [4200]u8 = undefined;
+ lookAt(p, 0, try std.fmt.bufPrint(&notes_buf, "{s}/notes.txt", .{root}));
+ const notes = p.view().active;
+ try std.testing.expect(notes != 0);
+ lookAt(p, notes, "3f2a9c1");
+ var paged = false;
+ for (p.panes) |slot| if (slot) |pn| if (pn.command) |cmd| {
+ try std.testing.expect(std.mem.endsWith(u8, cmd, "git show 3f2a9c1"));
+ try std.testing.expect(pn.command_pages);
+ paged = true;
+ };
+ try std.testing.expect(paged);
}
diff --git a/src/macos.zig b/src/macos.zig
index 3dc87e1a..389a4b4a 100644
--- a/src/macos.zig
+++ b/src/macos.zig
@@ -1624,6 +1624,7 @@ const vtable: pardes.Host.VTable = .{
.set_clipboard = setClipboard,
.read_clipboard = readClipboard,
.open_link = openLink,
+ .start = host_io.startDetached,
.lsp = lspRequest,
.pipe = pipeRequest,
};
diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig
index c4947504..f717fc26 100644
--- a/src/ninep/ctl.zig
+++ b/src/ninep/ctl.zig
@@ -366,7 +366,7 @@ pub fn readResults(p: *Pardes, req: Req) Reply {
const looking = if (tree.Node.target(req.node)) |t| switch (t) {
.top => |f| f == .look,
.pane => |pt| pt.file == .look,
- .col => false,
+ .col, .port => false,
} else false;
for (kept) |serial| if (!looking or p.paneBySerial(serial) != null)
out.print(p.gpa, "{d}\n", .{serial}) catch return Reply.fail(req.tag, E.NOMEM);
@@ -718,7 +718,7 @@ pub fn fillPager(p: *Pardes, serial: u32, held: *std.ArrayList(u8)) error{OutOfM
panes.File.setContent(p, f, page.text);
f.pager_spans = page.spans;
f.saved_revision = f.revision;
- if (f.pager_diff) @import("../hunks.zig").paged(p, id);
+ pardes.Plumb.paged(p, id);
}
/// The editor's step: the text of /pager opens closed unread goes in.
diff --git a/src/ninep/events.zig b/src/ninep/events.zig
index dd9b488c..5b5378b1 100644
--- a/src/ninep/events.zig
+++ b/src/ninep/events.zig
@@ -233,6 +233,10 @@ pub fn noteError(p: *Pardes, req: Req, reply: Reply) void {
if ((f == .exec or f == .look) and p.fs.ran_at != 0)
serial = name.print("{d}", .{p.fs.ran_at});
},
+ .port => |i| {
+ serial = "-";
+ file = name.print("plumb/{s}", .{pardes.Plumb.portName(p, i) orelse "?"});
+ },
.col => |c| {
serial = "-";
file = if (c.file == .dir)
diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig
index 8902f11e..e5e521c3 100644
--- a/src/ninep/tree.zig
+++ b/src/ninep/tree.zig
@@ -101,6 +101,7 @@ fn truncates(req: Req) bool {
.pane => true,
.col => |c| c.file == .tag,
.top => |f| f == .tag or f == .rules,
+ .port => false,
};
}
@@ -156,6 +157,9 @@ pub const Open = struct {
/// is not whole yet (rule sets with no blank line after them, a
/// message short of its data).
plumb,
+ /// An open reading a plumb port (Plumb.zig's ports, plumber(4)'s):
+ /// the messages sent to it since the open, packed, a read each.
+ port: struct { index: u8, queue: events.Queue = .{} },
} = .{ .snapshot = null },
/// What a write to a file of command lines left unfinished: a last line
/// with no newline yet, or an Edit block still open. A write through a
@@ -212,6 +216,7 @@ pub const Open = struct {
gpa.free(run.line);
},
.frozen => |bytes| gpa.free(bytes),
+ .port => |*port| port.queue.deinit(gpa),
.event, .pty_data, .ctl, .lines, .writes, .pager, .plumb => {},
}
o.pending.deinit(gpa);
@@ -380,6 +385,10 @@ pub const ColFile = enum(u5) {
}
};
const col_bit: u59 = 1 << 58;
+/// plumb/<port>: a port by its place in Plumb's list, which only grows;
+/// past a pane serial's 32 bits and clear of the host tree's and the
+/// archive's high bits (fs.os_node, sources.archive_node).
+const port_bit: u59 = 1 << 40;
pub const Node = packed struct(u64) {
file: u5 = 0,
@@ -394,11 +403,16 @@ pub const Node = packed struct(u64) {
return @bitCast(Node{ .file = @backingInt(file), .serial = col_bit | @as(u59, serial) });
}
+ pub fn ofPort(index: u8) u64 {
+ return @bitCast(Node{ .serial = port_bit | @as(u59, index) });
+ }
+
pub fn target(node: u64) ?Target {
const n: Node = @bitCast(node);
if (n.serial == 0) {
return .{ .top = std.enums.fromInt(TopFile, n.file) orelse return null };
}
+ if (n.serial & port_bit != 0) return .{ .port = std.math.cast(u8, n.serial & ~port_bit) orelse return null };
if (n.serial & col_bit != 0) return .{ .col = .{
.serial = std.math.cast(u32, n.serial & ~col_bit) orelse return null,
.file = std.enums.fromInt(ColFile, n.file) orelse return null,
@@ -414,6 +428,7 @@ pub const Target = union(enum) {
top: TopFile,
pane: struct { serial: u32, file: PaneFile },
col: struct { serial: u32, file: ColFile },
+ port: u8,
};
/// Opening /pane/new makes a pane and reading the open fid answers its
@@ -574,7 +589,7 @@ fn serve(p: *Pardes, req: Req) Reply {
const target = Node.target(req.node) orelse return Reply.fail(req.tag, E.NOENT);
if (req.op == .write or req.op == .setattr) p.fs.origin = switch (target) {
.pane => |t| @as(u8, if (t.file == .body or t.file == .tag) 'E' else 'F'),
- .top, .col => 'F',
+ .top, .col, .port => 'F',
};
return switch (req.op) {
.lookup => lookup(p, req, target),
@@ -596,7 +611,7 @@ fn serve(p: *Pardes, req: Req) Reply {
fn runAttr(p: *Pardes, req: Req, target: Target) ?Reply.Attr {
const t = switch (target) {
.pane => |t| t,
- .top, .col => return null,
+ .top, .col, .port => return null,
};
if (t.file != .pty_run) return null;
const run = if (req.handle != 0) openOf(p, req) else for (&p.fs.opens) |*o| {
@@ -608,6 +623,12 @@ fn runAttr(p: *Pardes, req: Req, target: Target) ?Reply.Attr {
fn attrOf(p: *Pardes, target: Target) ?Reply.Attr {
switch (target) {
+ .port => |i| return .{
+ .name = Plumb.portName(p, i) orelse return null,
+ .node = Node.ofPort(i),
+ .mode = 0o444,
+ .mtime = p.fs.started,
+ },
.top => |f| return .{
.name = f.fileName(),
.node = @backingInt(f),
@@ -704,6 +725,7 @@ fn lookup(p: *Pardes, req: Req, target: Target) Reply {
else => return Reply.fail(req.tag, E.NOTDIR),
},
.col => |c| if (c.file == .dir) @backingInt(TopFile.col) else return Reply.fail(req.tag, E.NOTDIR),
+ .port => return Reply.fail(req.tag, E.NOTDIR),
};
return handle(p, .{ .tag = req.tag, .op = .getattr, .node = parent });
}
@@ -728,9 +750,10 @@ fn lookup(p: *Pardes, req: Req, target: Target) Reply {
if (serial == 0) return Reply.fail(req.tag, E.NOENT);
break :dir if (f == .pane) Node.of(serial, .dir) else Node.ofCol(serial, .dir);
},
- .plumb => if (std.mem.eql(u8, name, "rules")) @backingInt(TopFile.rules) else if (std.mem.eql(u8, name, "send")) @backingInt(TopFile.send) else return Reply.fail(req.tag, E.NOENT),
+ .plumb => if (std.mem.eql(u8, name, "rules")) @backingInt(TopFile.rules) else if (std.mem.eql(u8, name, "send")) @backingInt(TopFile.send) else if (Plumb.portIndex(p, name)) |i| Node.ofPort(i) else return Reply.fail(req.tag, E.NOENT),
else => return Reply.fail(req.tag, E.NOTDIR),
},
+ .port => return Reply.fail(req.tag, E.NOTDIR),
.col => |c| col: {
if (c.file != .dir) return Reply.fail(req.tag, E.NOTDIR);
const f = std.meta.stringToEnum(ColFile, name) orelse return Reply.fail(req.tag, E.NOENT);
@@ -790,8 +813,15 @@ fn stageDir(p: *Pardes, out: *std.ArrayList(u8), target: Target, off: u64) error
try stageDirent(out, p.gpa, Node.of(serial, .dir), true, name);
}
},
- .plumb => inline for (.{ TopFile.rules, TopFile.send }) |t| {
- if (skip > 0) skip -= 1 else try stageDirent(out, p.gpa, @backingInt(t), false, t.fileName());
+ // plumber(4)'s order: rules, send, then the ports as rules
+ // named them.
+ .plumb => {
+ inline for (.{ TopFile.rules, TopFile.send }) |t| {
+ if (skip > 0) skip -= 1 else try stageDirent(out, p.gpa, @backingInt(t), false, t.fileName());
+ }
+ for (p.plumber.ports.items, 0..) |name, i| {
+ if (skip > 0) skip -= 1 else try stageDirent(out, p.gpa, Node.ofPort(@intCast(i)), false, name);
+ }
},
.col => for (0..p.view().ncol) |c| {
if (skip > 0) {
@@ -812,6 +842,7 @@ fn stageDir(p: *Pardes, out: *std.ArrayList(u8), target: Target, off: u64) error
if (skip > 0) skip -= 1 else try stageDirent(out, p.gpa, Node.ofCol(c.serial, f), false, f.fileName());
}
},
+ .port => return error.NotDir,
.pane => |t| {
const id = p.paneBySerial(t.serial) orelse return error.FileNotFound;
const terminal = p.panes[id].?.isTerminal();
@@ -872,6 +903,9 @@ fn open(p: *Pardes, req: Req, target: Target) Reply {
.col => |c| if (layout.columnBySerial(p, c.serial) == null)
return Reply.fail(req.tag, E.NOENT)
else if (linesOpen(target, req)) .lines else if (c.file == .ctl) .{ .frozen = &.{} } else return .{ .tag = req.tag },
+ // A reader of the port: what is sent to it from now on, and what a
+ // `client` rule held for its first.
+ .port => |i| if (req.omode & 3 != 0) return Reply.fail(req.tag, E.PERM) else .{ .port = .{ .index = i } },
.pane => |t| what: {
const pn = p.panes[p.paneBySerial(t.serial) orelse return Reply.fail(req.tag, E.NOENT)].?;
if (t.file.inPty() and !pn.isTerminal()) return Reply.fail(req.tag, E.NOENT);
@@ -929,6 +963,7 @@ fn open(p: *Pardes, req: Req, target: Target) Reply {
pn.fs.event_reader = pn.fs.event_reader or reader;
},
.pty_data => pane_of.?.fs.pty_reader = true,
+ .port => |*port| Plumb.opened(p, port.index, &port.queue),
.run, .ctl, .lines, .writes, .pager, .plumb => {},
}
return .{ .tag = req.tag, .handle = @intCast(i + 1) };
@@ -940,7 +975,7 @@ fn remove(p: *Pardes, req: Req) Reply {
const target = Node.target(req.node) orelse return Reply.fail(req.tag, E.NOENT);
const t = switch (target) {
.pane => |t| t,
- .top => return Reply.fail(req.tag, E.PERM),
+ .top, .port => return Reply.fail(req.tag, E.PERM),
.col => |c| return cols.remove(p, req, c.serial, c.file),
};
if (t.file != .dir) return Reply.fail(req.tag, E.PERM);
@@ -1027,7 +1062,7 @@ fn releaseHandle(p: *Pardes, req: Req) void {
.ctl => if (pn.fs.lock == req.handle) {
pn.fs.lock = null;
},
- .snapshot, .log, .lines, .writes, .frozen, .pager, .plumb => {},
+ .snapshot, .log, .lines, .writes, .frozen, .pager, .plumb, .port => {},
};
o.deinit(p.gpa);
}
@@ -1046,6 +1081,7 @@ fn setattr(p: *Pardes, req: Req, target: Target) Reply {
},
.col => |c| if (c.file == .tag and cols.truncate(p, c.serial) != .ok) return Reply.fail(req.tag, E.NOENT),
.top => |f| if (f == .tag and cols.truncate(p, null) != .ok) return Reply.fail(req.tag, E.NOMEM) else if (f == .rules) Plumb.clear(p),
+ .port => return Reply.fail(req.tag, E.PERM),
};
return .{ .tag = req.tag, .attr = attrOf(p, target) orelse return Reply.fail(req.tag, E.NOENT) };
}
@@ -1056,6 +1092,8 @@ fn read(p: *Pardes, req: Req, target: Target) Reply {
if (open_record) |o| if (o.what == .pager) ctl.fillPager(p, o.what.pager, &o.pending) catch return Reply.fail(req.tag, E.NOMEM);
// A listing reads what it was at the open.
if (open_record) |o| if (o.what == .frozen) return window(p, req, o.what.frozen);
+ // A port: a message a read, held until one is sent.
+ if (open_record) |o| if (o.what == .port) return events.readQueue(p, req, &o.what.port.queue);
const stream = if (open_record) |o| switch (o.what) {
.log => o,
.event => |reader| if (reader) o else null,
@@ -1182,6 +1220,8 @@ fn readFile(p: *Pardes, req: Req, target: Target) Reply {
.exec => ctl.readResults(p, req),
else => Reply.fail(req.tag, E.PERM),
},
+ // Read through its open (read), never without one.
+ .port => return Reply.fail(req.tag, E.PERM),
}
}
@@ -1193,6 +1233,7 @@ fn linesFile(target: Target) bool {
// `name` too: one name, however its writes cut it, applied once
// its newline comes, or with its write when that is whole.
.pane => |t| t.file == .look or t.file == .exec or t.file == .ctl or t.file == .tagexec or t.file == .name or t.file == .rows,
+ .port => false,
};
}
@@ -1202,6 +1243,7 @@ fn resultsFile(target: Target) bool {
.top => |f| f == .look or f == .exec or f == .tagexec or f == .pager,
.col => |c| c.file == .exec,
.pane => |t| t.file == .look or t.file == .exec or t.file == .tagexec,
+ .port => false,
};
}
@@ -1248,6 +1290,7 @@ fn ctlFile(target: Target) bool {
.top => |f| f == .ctl,
.col => |c| c.file == .ctl,
.pane => |t| t.file == .ctl,
+ .port => false,
};
}
@@ -1398,6 +1441,7 @@ fn writeNow(p: *Pardes, req: Req, target: Target) Reply {
.exec => cols.writeExec(p, req, c.serial),
.dir => Reply.fail(req.tag, E.PERM),
},
+ .port => return Reply.fail(req.tag, E.PERM),
}
}
@@ -1408,7 +1452,7 @@ fn writeNow(p: *Pardes, req: Req, target: Target) Reply {
fn writeRules(p: *Pardes, req: Req) Reply {
const done: Reply = .{ .tag = req.tag, .written = @intCast(req.data.len) };
// A close's rest (runClosedLines), or a write with no open: whole.
- const o = openOf(p, req) orelse return if (Plumb.apply(p, true, req.data)) |why| failText(req.tag, E.INVAL, why) else done;
+ const o = openOf(p, req) orelse return if (Plumb.apply(p, true, "plumb/rules", req.data)) |why| failText(req.tag, E.INVAL, why) else done;
if (o.pending.items.len + req.data.len > Plumb.max_text) {
o.pending.clearRetainingCapacity();
return failText(req.tag, E.INVAL, std.fmt.comptimePrint("rules too long; max {d} KiB", .{Plumb.max_text / 1024}));
@@ -1416,7 +1460,7 @@ fn writeRules(p: *Pardes, req: Req) Reply {
o.pending.appendSlice(p.gpa, req.data) catch return Reply.fail(req.tag, E.NOMEM);
const end = Plumb.wholeSets(o.pending.items);
if (end == 0) return done;
- const why = Plumb.apply(p, true, o.pending.items[0..end]);
+ const why = Plumb.apply(p, true, "plumb/rules", o.pending.items[0..end]);
if (why != null) o.pending.clearRetainingCapacity() else {
const rest = o.pending.items.len - end;
std.mem.copyForwards(u8, o.pending.items[0..rest], o.pending.items[end..]);
@@ -1449,7 +1493,10 @@ fn writeSend(p: *Pardes, req: Req) Reply {
},
.msg => |m| {
defer if (o) |op| op.pending.clearRetainingCapacity();
- if (Plumb.send(p, null, m)) |why| return failText(req.tag, E.IO, why);
+ switch (Plumb.send(p, null, m, null)) {
+ .refused => |why| return failText(req.tag, E.IO, why),
+ .done, .look => {},
+ }
return .{ .tag = req.tag, .written = @intCast(req.data.len) };
},
}
@@ -1668,9 +1715,9 @@ test "readdir lists the root and a pane directory without creating anything" {
@memcpy(plumb_bytes[0..plumb_reply.bytes.len], plumb_reply.bytes);
var plumb_buf: [4]th.Dirent = undefined;
const plumb = th.dirents(plumb_bytes[0..plumb_reply.bytes.len], &plumb_buf);
- try testing.expectEqual(@as(usize, 2), plumb.len);
- try testing.expectEqualStrings("rules", plumb[0].name);
- try testing.expectEqualStrings("send", plumb[1].name);
+ // Then the ports the default rules name, in their order.
+ try testing.expectEqual(@as(usize, 4), plumb.len);
+ for ([_][]const u8{ "rules", "send", "web", "edit" }, plumb) |want, got| try testing.expectEqualStrings(want, got.name);
var idbuf: [16]u8 = undefined;
try testing.expect(th.nameAt(top, try std.fmt.bufPrint(&idbuf, "{d}", .{serial})) == null);
try testing.expect(th.nameAt(top, "self") == null);
diff --git a/src/pardes.zig b/src/pardes.zig
index 86530157..f173861b 100644
--- a/src/pardes.zig
+++ b/src/pardes.zig
@@ -8,6 +8,7 @@ pub const glide = @import("glide.zig");
pub const FrameStats = @import("FrameStats.zig");
pub const modal = @import("modal.zig");
pub const look = @import("look.zig");
+pub const Plumb = @import("Plumb.zig");
pub const filesystem = @import("fs.zig");
pub const ctlfs = @import("ninep/tree.zig");
pub const syntax = @import("syntax.zig");
diff --git a/src/plumbing b/src/plumbing
index 74c1f306..4e8cd702 100644
--- a/src/plumbing
+++ b/src/plumbing
@@ -4,13 +4,24 @@
# hold takes it, and its actions say where it goes: a port pardes reads
# itself (edit: a file or directory opened as Look opens one; web: the
# host's browser; a loaded kind by its name, `image`, `pdf`), another
-# port a program reads, or a word or command started.
+# port a program reads, or a word or program started. One that none
+# takes is Look's own: a file or directory opened, else the word
+# searched for. A look sends what it looks at: type text, src pardes
+# (term from a terminal's raw mode, a kind's name from its pane), wdir
+# its pane's directory, data the name as Look reads it.
# urls go to the web browser (the host's: xdg-open, open on macOS)
type is text
data matches 'https?://.*'
plumb to web
+# a diff or patch looked at bare is stacked in a +Diff; one with no
+# hunk in it opens as text
+type is text
+data matches '.*\.(diff|patch)'
+arg isfile $data
+plumb start Diff $file
+
# existing directories, and existing files at the place written after
# them, go to the editor; a file a kind shows (a picture, a PDF) to
# that kind
@@ -21,3 +32,20 @@ plumb to edit
type is text
arg isfile $data
plumb to edit
+
+# a commit hash looked at in the editor, in a git work tree: git show,
+# stacked in a +Diff (outside one, Diff declines and the word is
+# searched for)
+type is text
+src is pardes
+data matches '[0-9a-f]{7,40}'
+data matches '[0-9a-f]*[0-9][0-9a-f]*'
+data matches '[0-9a-f]*[a-f][0-9a-f]*'
+plumb start Diff $0
+
+# a diff paged (git show, git log -p) is shown stacked in a +Diff in
+# its +Pager's place
+type is text/x-diff
+attr delete action
+attr add action=showdiff
+plumb to edit
diff --git a/src/tui/tui.zig b/src/tui/tui.zig
index 4c0ded5b..ce2dc84a 100644
--- a/src/tui/tui.zig
+++ b/src/tui/tui.zig
@@ -1311,6 +1311,7 @@ const Shell = struct {
.set_clipboard = setClipboard,
.read_clipboard = readClipboard,
.open_link = openLink,
+ .start = host_io.startDetached,
.lsp = lsp,
.pipe = pipe,
.search = search,
diff --git a/src/walk.zig b/src/walk.zig
index 3641d327..0f181cfa 100644
--- a/src/walk.zig
+++ b/src/walk.zig
@@ -367,7 +367,7 @@ pub fn shape(comptime types: []const type) []const u8 {
comptime {
@setEvalBranchQuota(10_000_000);
var out: []const u8 = "";
- for (types) |T| out = out ++ shapeOf(T, 0) ++ "\n";
+ for (types) |T| out = out ++ (shapeOf(T, 0) ++ "\n");
return out;
}
}
@@ -378,15 +378,15 @@ fn shapeOf(comptime T: type, comptime depth: u8) []const u8 {
return switch (@typeInfo(T)) {
.void, .null, .undefined => "v",
.bool => "b",
- .int => |i| std.fmt.comptimePrint("{t}{d}", .{ i.signedness, i.bits }),
- .float => |f| std.fmt.comptimePrint("f{d}", .{f.bits}),
+ .int => |i| @tagName(i.signedness) ++ decimal(i.bits),
+ .float => |f| "f" ++ decimal(f.bits),
.@"enum" => |e| blk: {
var out: []const u8 = shapeOf(e.tag_type, depth + 1) ++ "{";
- for (e.field_names, e.field_values) |n, v| out = out ++ std.fmt.comptimePrint("{s}={d},", .{ n, v });
+ for (e.field_names, e.field_values) |n, v| out = out ++ (n ++ "=" ++ decimal(v) ++ ",");
break :blk out ++ "}";
},
.optional => |o| if (machinery(o.child)) "0" else "?" ++ shapeOf(o.child, depth + 1),
- .array => |a| std.fmt.comptimePrint("[{d}]", .{a.len}) ++ shapeOf(a.child, depth + 1),
+ .array => |a| "[" ++ decimal(a.len) ++ "]" ++ shapeOf(a.child, depth + 1),
.pointer => |p| switch (p.size) {
.one => shapeOf(p.child, depth + 1),
.slice => "[]" ++ shapeOf(p.child, depth + 1),
@@ -397,13 +397,13 @@ fn shapeOf(comptime T: type, comptime depth: u8) []const u8 {
var out: []const u8 = if (s.layout == .@"packed") "p{" else "{";
for (s.field_names, s.field_types, s.field_attrs) |name, F, attr| {
if (attr.@"comptime" or excluded(T, name)) continue;
- out = out ++ name ++ ":" ++ shapeOf(F, depth + 1) ++ ",";
+ out = out ++ (name ++ ":" ++ shapeOf(F, depth + 1) ++ ",");
}
break :blk out ++ "}";
},
.@"union" => |u| blk: {
var out: []const u8 = shapeOf(u.tag_type.?, depth + 1) ++ "(";
- for (u.field_names, u.field_types) |name, F| out = out ++ name ++ ":" ++ shapeOf(F, depth + 1) ++ ",";
+ for (u.field_names, u.field_types) |name, F| out = out ++ (name ++ ":" ++ shapeOf(F, depth + 1) ++ ",");
break :blk out ++ ")";
},
.error_set => "error",
@@ -413,6 +413,15 @@ fn shapeOf(comptime T: type, comptime depth: u8) []const u8 {
}
}
+/// `n` in decimal, as `{d}` writes it: memoized, where comptimePrint (an
+/// inline function) formats again at every call, 5e6 of the compiler's
+/// instructions each.
+fn decimal(comptime n: comptime_int) []const u8 {
+ if (n < 0) return "-" ++ decimal(-n);
+ if (n < 10) return &.{'0' + n};
+ return decimal(n / 10) ++ &[_]u8{'0' + n % 10};
+}
+
/// An error by its name. An `anyerror` must be one `decode` can read back
/// (`errorNamed`): a Debug build stops at one that is not, as it is taped.
fn encodeError(comptime E: type, err: E, w: *std.Io.Writer) std.Io.Writer.Error!void {
@@ -1006,540 +1015,555 @@ const SrcType = struct {
};
const SrcField = struct { name: []const u8, ty: u32 = 0, value: i128 = 0 };
-/// Reads a dump of `roots`, one `into` or `get` each in order.
+/// Reads a dump of `roots`, one `into` or `get` each in order: a `Loader`
+/// told this build's table of them.
pub fn Load(comptime roots: []const type) type {
return struct {
- const Self = @This();
- const types = graph(roots);
+ pub fn init(gpa: std.mem.Allocator, bytes: []const u8) DecodeError!Loader {
+ return Loader.init(gpa, bytes, tableOf(graph(roots)));
+ }
+ };
+}
- /// Where what is read is made (a `replica.alloc` field's own
- /// allocator while it is read).
- gpa: std.mem.Allocator,
- /// The loader's own lists'.
- own: std.mem.Allocator,
- bytes: []const u8,
- at: usize = 0,
- arena: std.heap.ArenaAllocator,
- src: []SrcType = &.{},
- /// Its table is this build's: no name is asked.
- same: bool = false,
- /// Each pointer and slice made so far: what a reference finds, and
- /// what `rollback` frees.
- shared: std.ArrayList(Made) = .empty,
- /// What a type's `dumpRead` made, freed by its `dumpFree` too.
- customs: std.ArrayList(struct { ptr: *anyopaque, gpa: std.mem.Allocator, free: *const fn (*anyopaque, std.mem.Allocator) void }) = .empty,
- /// What was let go, for the person whose session it is.
- notes: std.ArrayList(u8) = .empty,
- /// The field being read, for a note.
- field: []const u8 = "",
- /// Where a field's annotation (`replica.alloc`) says its values are
- /// made instead of `gpa`.
- allocs: Allocators = .{},
+/// `Load`'s reader, one for every root set: it reads by the dump's own
+/// table, and this build's (`table`) only says whether the two are one.
+pub const Loader = struct {
+ const Self = @This();
- pub fn init(gpa: std.mem.Allocator, bytes: []const u8) DecodeError!Self {
- var l: Self = .{ .gpa = gpa, .own = gpa, .bytes = bytes, .arena = .init(gpa) };
- errdefer l.arena.deinit();
- if (!std.mem.startsWith(u8, bytes, dump_magic)) return error.BadDump;
- l.at = dump_magic.len;
- const table_at = l.at;
- try l.readTable();
- l.same = std.mem.eql(u8, tableOf(types), bytes[table_at..l.at]);
- return l;
- }
+ /// Where what is read is made (a `replica.alloc` field's own
+ /// allocator while it is read).
+ gpa: std.mem.Allocator,
+ /// The loader's own lists'.
+ own: std.mem.Allocator,
+ bytes: []const u8,
+ at: usize = 0,
+ arena: std.heap.ArenaAllocator,
+ src: []SrcType = &.{},
+ /// Its table is this build's: no name is asked.
+ same: bool = false,
+ /// Each pointer and slice made so far: what a reference finds, and
+ /// what `rollback` frees.
+ shared: std.ArrayList(Made) = .empty,
+ /// What a type's `dumpRead` made, freed by its `dumpFree` too.
+ customs: std.ArrayList(struct { ptr: *anyopaque, gpa: std.mem.Allocator, free: *const fn (*anyopaque, std.mem.Allocator) void }) = .empty,
+ /// What was let go, for the person whose session it is.
+ notes: std.ArrayList(u8) = .empty,
+ /// The field being read, for a note.
+ field: []const u8 = "",
+ /// Where a field's annotation (`replica.alloc`) says its values are
+ /// made instead of `gpa`.
+ allocs: Allocators = .{},
- pub fn deinit(l: *Self) void {
- l.shared.deinit(l.own);
- l.customs.deinit(l.own);
- l.notes.deinit(l.own);
- l.arena.deinit();
- }
+ pub fn init(gpa: std.mem.Allocator, bytes: []const u8, table: []const u8) DecodeError!Self {
+ var l: Self = .{ .gpa = gpa, .own = gpa, .bytes = bytes, .arena = .init(gpa) };
+ errdefer l.arena.deinit();
+ if (!std.mem.startsWith(u8, bytes, dump_magic)) return error.BadDump;
+ l.at = dump_magic.len;
+ const table_at = l.at;
+ try l.readTable();
+ l.same = std.mem.eql(u8, table, bytes[table_at..l.at]);
+ return l;
+ }
- /// Everything read so far freed: a load that fails leaves nothing.
- /// What it was read into must not be used after (nor freed).
- pub fn rollback(l: *Self) void {
- for (l.customs.items) |c| c.free(c.ptr, c.gpa);
- for (l.shared.items) |m| if (m.bytes.len > 0) m.gpa.rawFree(m.bytes, m.alignment, @returnAddress());
- l.customs.clearRetainingCapacity();
- l.shared.clearRetainingCapacity();
- }
+ pub fn deinit(l: *Self) void {
+ l.shared.deinit(l.own);
+ l.customs.deinit(l.own);
+ l.notes.deinit(l.own);
+ l.arena.deinit();
+ }
- fn made(l: *Self, bytes: []u8, alignment: std.mem.Alignment) DecodeError!usize {
- try l.shared.append(l.own, .{ .bytes = bytes, .alignment = alignment, .gpa = l.gpa });
- return l.shared.items.len - 1;
- }
+ /// Everything read so far freed: a load that fails leaves nothing.
+ /// What it was read into must not be used after (nor freed).
+ pub fn rollback(l: *Self) void {
+ for (l.customs.items) |c| c.free(c.ptr, c.gpa);
+ for (l.shared.items) |m| if (m.bytes.len > 0) m.gpa.rawFree(m.bytes, m.alignment, @returnAddress());
+ l.customs.clearRetainingCapacity();
+ l.shared.clearRetainingCapacity();
+ }
- fn take(l: *Self, n: usize) DecodeError![]const u8 {
- if (l.bytes.len - l.at < n) return error.EndOfDump;
- defer l.at += n;
- return l.bytes[l.at..][0..n];
- }
+ fn made(l: *Self, bytes: []u8, alignment: std.mem.Alignment) DecodeError!usize {
+ try l.shared.append(l.own, .{ .bytes = bytes, .alignment = alignment, .gpa = l.gpa });
+ return l.shared.items.len - 1;
+ }
- fn scalar(l: *Self, comptime T: type) DecodeError!T {
- return std.mem.bytesToValue(T, try l.take(@sizeOf(T)));
- }
+ fn take(l: *Self, n: usize) DecodeError![]const u8 {
+ if (l.bytes.len - l.at < n) return error.EndOfDump;
+ defer l.at += n;
+ return l.bytes[l.at..][0..n];
+ }
- /// A count, as this machine counts (a wasm32 one has 32 bits).
- fn count(l: *Self) DecodeError!usize {
- return countOf(try l.scalar(u64));
- }
+ fn scalar(l: *Self, comptime T: type) DecodeError!T {
+ return std.mem.bytesToValue(T, try l.take(@sizeOf(T)));
+ }
- fn name(l: *Self) DecodeError![]const u8 {
- return l.take(try l.scalar(u16));
- }
+ /// A count, as this machine counts (a wasm32 one has 32 bits).
+ fn count(l: *Self) DecodeError!usize {
+ return countOf(try l.scalar(u64));
+ }
- fn readTable(l: *Self) DecodeError!void {
- const a = l.arena.allocator();
- const n = try l.scalar(u32);
- if (n > l.bytes.len) return error.BadDump;
- l.src = try a.alloc(SrcType, n);
- for (l.src) |*t| {
- const k = std.enums.fromInt(Kind, (try l.take(1))[0]) orelse return error.BadDump;
- t.* = .{ .kind = k };
- switch (k) {
- .int => {
- t.signed = (try l.take(1))[0] != 0;
- t.bits = try l.scalar(u16);
- },
- .float => t.bits = try l.scalar(u16),
- .@"enum" => {
- t.signed = (try l.take(1))[0] != 0;
- t.bits = try l.scalar(u16);
- const list = try a.alloc(SrcField, try l.scalar(u32));
- for (list) |*f| f.* = .{ .name = try l.name(), .value = try l.scalar(i128) };
- t.fields = list;
- },
- .array => {
- t.len = try l.scalar(u64);
- t.child = try l.scalar(u32);
- },
- .optional, .one, .slice, .prefix, .error_union => t.child = try l.scalar(u32),
- .@"struct", .@"union" => {
- const nfields = try l.scalar(u32);
- if (nfields > l.bytes.len) return error.BadDump;
- const list = try a.alloc(SrcField, nfields);
- for (list) |*f| f.* = .{ .name = try l.name(), .ty = try l.scalar(u32) };
- t.fields = list;
- },
- .custom => _ = try l.name(),
- .skip, .void, .bool, .err, .bitset => {},
- }
- }
- for (l.src) |t| {
- if (t.child >= n) return error.BadDump;
- for (t.fields) |f| if (f.ty >= n) return error.BadDump;
+ fn name(l: *Self) DecodeError![]const u8 {
+ return l.take(try l.scalar(u16));
+ }
+
+ fn readTable(l: *Self) DecodeError!void {
+ const a = l.arena.allocator();
+ const n = try l.scalar(u32);
+ if (n > l.bytes.len) return error.BadDump;
+ l.src = try a.alloc(SrcType, n);
+ for (l.src) |*t| {
+ const k = std.enums.fromInt(Kind, (try l.take(1))[0]) orelse return error.BadDump;
+ t.* = .{ .kind = k };
+ switch (k) {
+ .int => {
+ t.signed = (try l.take(1))[0] != 0;
+ t.bits = try l.scalar(u16);
+ },
+ .float => t.bits = try l.scalar(u16),
+ .@"enum" => {
+ t.signed = (try l.take(1))[0] != 0;
+ t.bits = try l.scalar(u16);
+ const list = try a.alloc(SrcField, try l.scalar(u32));
+ for (list) |*f| f.* = .{ .name = try l.name(), .value = try l.scalar(i128) };
+ t.fields = list;
+ },
+ .array => {
+ t.len = try l.scalar(u64);
+ t.child = try l.scalar(u32);
+ },
+ .optional, .one, .slice, .prefix, .error_union => t.child = try l.scalar(u32),
+ .@"struct", .@"union" => {
+ const nfields = try l.scalar(u32);
+ if (nfields > l.bytes.len) return error.BadDump;
+ const list = try a.alloc(SrcField, nfields);
+ for (list) |*f| f.* = .{ .name = try l.name(), .ty = try l.scalar(u32) };
+ t.fields = list;
+ },
+ .custom => _ = try l.name(),
+ .skip, .void, .bool, .err, .bitset => {},
}
}
-
- pub fn note(l: *Self, comptime fmt: []const u8, args: anytype) void {
- if (l.notes.items.len > 4096) return;
- l.notes.print(l.own, fmt ++ "\n", args) catch {};
+ for (l.src) |t| {
+ if (t.child >= n) return error.BadDump;
+ for (t.fields) |f| if (f.ty >= n) return error.BadDump;
}
+ }
- fn root(l: *Self) DecodeError!u32 {
- const ty = try l.scalar(u32);
- if (ty >= l.src.len) return error.BadDump;
- return ty;
- }
+ pub fn note(l: *Self, comptime fmt: []const u8, args: anytype) void {
+ if (l.notes.items.len > 4096) return;
+ l.notes.print(l.own, fmt ++ "\n", args) catch {};
+ }
- /// The next root, made: what it points at is `gpa`'s.
- pub fn get(l: *Self, comptime T: type) DecodeError!T {
- var out: T = undefined;
- try l.fresh(T, &out);
- try l.value(T, try l.root(), &out);
- return out;
- }
+ /// A note on a type's field, its names given as run-time strings:
+ /// one instance of `note` (and of std's `print`) a message, where
+ /// a tuple of the comptime names made one a type, field and message.
+ fn noteField(l: *Self, comptime what: []const u8, type_name: []const u8, field: []const u8) void {
+ l.note("{s}.{s}: " ++ what, .{ type_name, field });
+ }
- /// The next root read into `out` as it stands: a field the dump
- /// holds is replaced (what it held is not freed), every other one
- /// is left as it is. A field another build cannot give is left too,
- /// and noted.
- pub fn into(l: *Self, comptime T: type, out: *T) DecodeError!void {
- const ty = try l.root();
- const s = l.src[ty];
- if (s.kind != .@"struct") return error.BadDump;
- try l.fields(T, s, out, true);
- }
+ fn root(l: *Self) DecodeError!u32 {
+ const ty = try l.scalar(u32);
+ if (ty >= l.src.len) return error.BadDump;
+ return ty;
+ }
- fn fresh(l: *Self, comptime T: type, out: *T) DecodeError!void {
- freshOf(T, out, l.gpa);
- }
+ /// The next root, made: what it points at is `gpa`'s.
+ pub fn get(l: *Self, comptime T: type) DecodeError!T {
+ var out: T = undefined;
+ try l.fresh(T, &out);
+ try l.value(T, try l.root(), &out);
+ return out;
+ }
- /// Whether the source's `ty` and `T` are of one kind, else the
- /// source's value passed over.
- fn kindMatches(l: *Self, comptime T: type, ty: u32) DecodeError!bool {
- if (l.same) return true;
- const want = comptime kindOf(Canon(T));
- const got = l.src[ty].kind;
- if (got == want) return true;
- // A field that came to hold a count and so many, or stopped.
- if ((want == .array and got == .prefix) or (want == .prefix and got == .array)) return true;
- try l.skip(ty);
- return false;
- }
+ /// The next root read into `out` as it stands: a field the dump
+ /// holds is replaced (what it held is not freed), every other one
+ /// is left as it is. A field another build cannot give is left too,
+ /// and noted.
+ pub fn into(l: *Self, comptime T: type, out: *T) DecodeError!void {
+ const ty = try l.root();
+ const s = l.src[ty];
+ if (s.kind != .@"struct") return error.BadDump;
+ try l.fields(T, s, out, true);
+ }
- fn readInt(l: *Self, comptime I: type, s: SrcType) DecodeError!I {
- if (l.same) {
- const info = @typeInfo(I).int;
- const W = @Int(info.signedness, intBytes(info.bits) * 8);
- return @intCast(try l.scalar(W));
- }
- const n = intBytes(s.bits);
- const raw = try l.take(n);
- var wide: u128 = 0;
- for (raw, 0..) |b, i| wide |= @as(u128, b) << @intCast(i * 8);
- if (s.signed and n > 0) {
- const shift: u7 = @intCast(128 - n * 8);
- const signed: i128 = @as(i128, @bitCast(wide << shift)) >> shift;
- return std.math.cast(I, signed) orelse error.Incompatible;
- }
- return std.math.cast(I, wide) orelse error.Incompatible;
+ fn fresh(l: *Self, comptime T: type, out: *T) DecodeError!void {
+ freshOf(T, out, l.gpa);
+ }
+
+ /// Whether the source's `ty` and `T` are of one kind, else the
+ /// source's value passed over.
+ fn kindMatches(l: *Self, comptime T: type, ty: u32) DecodeError!bool {
+ if (l.same) return true;
+ const want = comptime kindOf(Canon(T));
+ const got = l.src[ty].kind;
+ if (got == want) return true;
+ // A field that came to hold a count and so many, or stopped.
+ if ((want == .array and got == .prefix) or (want == .prefix and got == .array)) return true;
+ try l.skip(ty);
+ return false;
+ }
+
+ fn readInt(l: *Self, comptime I: type, s: SrcType) DecodeError!I {
+ if (l.same) {
+ const info = @typeInfo(I).int;
+ const W = @Int(info.signedness, intBytes(info.bits) * 8);
+ return @intCast(try l.scalar(W));
+ }
+ const n = intBytes(s.bits);
+ const raw = try l.take(n);
+ var wide: u128 = 0;
+ for (raw, 0..) |b, i| wide |= @as(u128, b) << @intCast(i * 8);
+ if (s.signed and n > 0) {
+ const shift: u7 = @intCast(128 - n * 8);
+ const signed: i128 = @as(i128, @bitCast(wide << shift)) >> shift;
+ return std.math.cast(I, signed) orelse error.Incompatible;
}
+ return std.math.cast(I, wide) orelse error.Incompatible;
+ }
- /// `T` read from the source's type `ty` into `out`, which `fresh`
- /// has made ready.
- fn value(l: *Self, comptime T: type, ty: u32, out: *T) DecodeError!void {
- if (comptime isAtomic(T)) {
- const R = @FieldType(T, "raw");
- var raw: R = undefined;
- try l.fresh(R, &raw);
- try l.value(R, ty, &raw);
- out.* = .{ .raw = raw };
- return;
- }
- // A field this build compiles out (a void field): passed over,
- // said only when it held something.
- if (comptime kindOf(Canon(T)) == .void) if (!l.same and l.src[ty].kind != .void) {
- const held = l.src[ty].kind != .optional or (l.at < l.bytes.len and l.bytes[l.at] != 0);
- try l.skip(ty);
- if (held) l.note("{s}: not in this build", .{l.field});
- return;
- };
- if (!try l.kindMatches(T, ty)) return error.Incompatible;
- const s = l.src[ty];
- if (comptime isList(T)) {
- const E = @typeInfo(@FieldType(T, "items")).pointer.child;
- const got = try l.slice(E, s);
- out.* = .empty;
- out.items = got;
- out.capacity = got.len;
- return;
- }
- switch (comptime kindOf(T)) {
- .skip, .void => {},
- .bool => out.* = (try l.take(1))[0] != 0,
- .int => out.* = try l.readInt(T, s),
- .float => out.* = if (l.same or s.bits == @typeInfo(T).float.bits) try l.scalar(T) else return error.Incompatible,
- .@"enum" => {
- const e = @typeInfo(T).@"enum";
- if (l.same) {
- out.* = @fromBackingInt(@intCast(try l.readInt(e.tag_type, s)));
- return;
- }
- const n = try l.readInt(i128, s);
- const was = for (s.fields) |f| {
- if (f.value == n) break f.name;
- } else null;
- if (was) |w| inline for (e.field_names) |field| if (std.mem.eql(u8, w, field)) {
- out.* = @field(T, field);
- return;
- };
- if (e.mode == .nonexhaustive and was == null)
- if (std.math.cast(e.tag_type, n)) |tag| {
- out.* = @fromBackingInt(@intCast(tag));
- return;
- };
- l.note("{s}: no {s} here", .{ l.field, was orelse "such value" });
- return error.Incompatible;
- },
- .optional => {
- const C = @typeInfo(T).optional.child;
- if ((try l.take(1))[0] == 0) {
- out.* = null;
- return;
- }
- if (comptime kindOf(Canon(C)) == .skip) {
- out.* = if (comptime C == std.mem.Allocator) l.gpa else null;
- return;
- }
- // A slice's or a pointer's null is its address: set to
- // an undefined payload, the optional itself is undefined,
- // and ReleaseSafe's optimizer read it as null (a pane's
- // `?[]u8` command one byte long, every field after it out
- // of step). Read through a local and set it from that.
- if (comptime @typeInfo(C) == .pointer) {
- var payload: C = undefined;
- try l.value(C, s.child, &payload);
- out.* = payload;
- return;
- }
- out.* = @as(C, undefined);
- try l.fresh(C, &out.*.?);
- l.value(C, s.child, &out.*.?) catch |err| {
- out.* = null;
- return err;
- };
- },
- .one => {
- const C = @typeInfo(T).pointer.child;
- if (try l.ref()) |again| {
- out.* = @ptrCast(@alignCast(again.ptr));
+ /// `T` read from the source's type `ty` into `out`, which `fresh`
+ /// has made ready.
+ fn value(l: *Self, comptime T: type, ty: u32, out: *T) DecodeError!void {
+ if (comptime isAtomic(T)) {
+ const R = @FieldType(T, "raw");
+ var raw: R = undefined;
+ try l.fresh(R, &raw);
+ try l.value(R, ty, &raw);
+ out.* = .{ .raw = raw };
+ return;
+ }
+ // A field this build compiles out (a void field): passed over,
+ // said only when it held something.
+ if (comptime kindOf(Canon(T)) == .void) if (!l.same and l.src[ty].kind != .void) {
+ const held = l.src[ty].kind != .optional or (l.at < l.bytes.len and l.bytes[l.at] != 0);
+ try l.skip(ty);
+ if (held) l.note("{s}: not in this build", .{l.field});
+ return;
+ };
+ if (!try l.kindMatches(T, ty)) return error.Incompatible;
+ const s = l.src[ty];
+ if (comptime isList(T)) {
+ const E = @typeInfo(@FieldType(T, "items")).pointer.child;
+ const got = try l.slice(E, s);
+ out.* = .empty;
+ out.items = got;
+ out.capacity = got.len;
+ return;
+ }
+ switch (comptime kindOf(T)) {
+ .skip, .void => {},
+ .bool => out.* = (try l.take(1))[0] != 0,
+ .int => out.* = try l.readInt(T, s),
+ .float => out.* = if (l.same or s.bits == @typeInfo(T).float.bits) try l.scalar(T) else return error.Incompatible,
+ .@"enum" => {
+ const e = @typeInfo(T).@"enum";
+ if (l.same) {
+ out.* = @fromBackingInt(@intCast(try l.readInt(e.tag_type, s)));
+ return;
+ }
+ const n = try l.readInt(i128, s);
+ const was = for (s.fields) |f| {
+ if (f.value == n) break f.name;
+ } else null;
+ if (was) |w| inline for (e.field_names) |field| if (std.mem.eql(u8, w, field)) {
+ out.* = @field(T, field);
+ return;
+ };
+ if (e.mode == .nonexhaustive and was == null)
+ if (std.math.cast(e.tag_type, n)) |tag| {
+ out.* = @fromBackingInt(@intCast(tag));
return;
- }
- const one = try l.gpa.create(C);
- const at = l.made(std.mem.asBytes(one), .of(C)) catch |err| {
- l.gpa.destroy(one);
- return err;
};
- try l.fresh(C, one);
- l.value(C, s.child, one) catch |err| {
- // Left half made: no later reference may find it.
- l.shared.items[at].dead = true;
- return err;
- };
- out.* = one;
- },
- .slice => {
- const E = @typeInfo(T).pointer.child;
- const got = try l.slice(E, s);
- if (comptime @typeInfo(T).pointer.sentinel_ptr != null) @compileError("walk: a sentinel slice: " ++ @typeName(T));
- out.* = got;
- },
- .array => {
- const E = @typeInfo(T).array.child;
- const n: u64 = if (s.kind == .prefix) try l.scalar(u64) else s.len;
- try l.elements(E, s.child, n, out);
- },
- .prefix => unreachable,
- .@"struct" => try l.fields(T, s, out, false),
- .@"union" => {
- const u = @typeInfo(T).@"union";
- const ordinal = try l.scalar(u16);
- if (ordinal >= s.fields.len) return error.BadDump;
- const was = s.fields[ordinal];
- inline for (u.field_names, u.field_types, 0..) |field, F, i| {
- if (if (l.same) ordinal == i else std.mem.eql(u8, was.name, field)) {
- out.* = @unionInit(T, field, undefined);
- try l.fresh(F, &@field(out.*, field));
- return l.value(F, was.ty, &@field(out.*, field));
- }
+ l.note("{s}: no {s} here", .{ l.field, was orelse "such value" });
+ return error.Incompatible;
+ },
+ .optional => {
+ const C = @typeInfo(T).optional.child;
+ if ((try l.take(1))[0] == 0) {
+ out.* = null;
+ return;
+ }
+ if (comptime kindOf(Canon(C)) == .skip) {
+ out.* = if (comptime C == std.mem.Allocator) l.gpa else null;
+ return;
+ }
+ // A slice's or a pointer's null is its address: set to
+ // an undefined payload, the optional itself is undefined,
+ // and ReleaseSafe's optimizer read it as null (a pane's
+ // `?[]u8` command one byte long, every field after it out
+ // of step). Read through a local and set it from that.
+ if (comptime @typeInfo(C) == .pointer) {
+ var payload: C = undefined;
+ try l.value(C, s.child, &payload);
+ out.* = payload;
+ return;
+ }
+ out.* = @as(C, undefined);
+ try l.fresh(C, &out.*.?);
+ l.value(C, s.child, &out.*.?) catch |err| {
+ out.* = null;
+ return err;
+ };
+ },
+ .one => {
+ const C = @typeInfo(T).pointer.child;
+ if (try l.ref()) |again| {
+ out.* = @ptrCast(@alignCast(again.ptr));
+ return;
+ }
+ const one = try l.gpa.create(C);
+ const at = l.made(std.mem.asBytes(one), .of(C)) catch |err| {
+ l.gpa.destroy(one);
+ return err;
+ };
+ try l.fresh(C, one);
+ l.value(C, s.child, one) catch |err| {
+ // Left half made: no later reference may find it.
+ l.shared.items[at].dead = true;
+ return err;
+ };
+ out.* = one;
+ },
+ .slice => {
+ const E = @typeInfo(T).pointer.child;
+ const got = try l.slice(E, s);
+ if (comptime @typeInfo(T).pointer.sentinel_ptr != null) @compileError("walk: a sentinel slice: " ++ @typeName(T));
+ out.* = got;
+ },
+ .array => {
+ const E = @typeInfo(T).array.child;
+ const n: u64 = if (s.kind == .prefix) try l.scalar(u64) else s.len;
+ try l.elements(E, s.child, n, out);
+ },
+ .prefix => unreachable,
+ .@"struct" => try l.fields(T, s, out, false),
+ .@"union" => {
+ const u = @typeInfo(T).@"union";
+ const ordinal = try l.scalar(u16);
+ if (ordinal >= s.fields.len) return error.BadDump;
+ const was = s.fields[ordinal];
+ inline for (u.field_names, u.field_types, 0..) |field, F, i| {
+ if (if (l.same) ordinal == i else std.mem.eql(u8, was.name, field)) {
+ out.* = @unionInit(T, field, undefined);
+ try l.fresh(F, &@field(out.*, field));
+ return l.value(F, was.ty, &@field(out.*, field));
}
- try l.skip(was.ty);
- l.note("{s}: no {s} here", .{ l.field, was.name });
+ }
+ try l.skip(was.ty);
+ l.note("{s}: no {s} here", .{ l.field, was.name });
+ return error.Incompatible;
+ },
+ .err, .error_union => unreachable,
+ .custom => {
+ const bytes = try l.take(try l.count());
+ T.dumpRead(out, l.gpa, bytes) catch |err| {
+ if (err == error.OutOfMemory) return error.OutOfMemory;
+ l.note("{s}: {t}", .{ l.field, err });
return error.Incompatible;
- },
- .err, .error_union => unreachable,
- .custom => {
- const bytes = try l.take(try l.count());
- T.dumpRead(out, l.gpa, bytes) catch |err| {
- if (err == error.OutOfMemory) return error.OutOfMemory;
- l.note("{s}: {t}", .{ l.field, err });
- return error.Incompatible;
- };
- if (comptime @hasDecl(T, "dumpFree")) try l.customs.append(l.own, .{ .ptr = out, .gpa = l.gpa, .free = @ptrCast(&T.dumpFree) });
- },
- .bitset => {
- const bits = try l.count();
- out.* = try .initEmpty(l.gpa, bits);
- const words = (bits + @bitSizeOf(usize) - 1) / @bitSizeOf(usize);
- if (words > 0) @memcpy(std.mem.sliceAsBytes(out.masks[0..words]), try l.take(words * @sizeOf(usize)));
- },
- }
+ };
+ if (comptime @hasDecl(T, "dumpFree")) try l.customs.append(l.own, .{ .ptr = out, .gpa = l.gpa, .free = @ptrCast(&T.dumpFree) });
+ },
+ .bitset => {
+ const bits = try l.count();
+ out.* = try .initEmpty(l.gpa, bits);
+ const words = (bits + @bitSizeOf(usize) - 1) / @bitSizeOf(usize);
+ if (words > 0) @memcpy(std.mem.sliceAsBytes(out.masks[0..words]), try l.take(words * @sizeOf(usize)));
+ },
}
+ }
- /// A reference to a pointer or slice made before, or null for a
- /// new one (its length then read).
- fn ref(l: *Self) DecodeError!?[]u8 {
- const n = try l.scalar(u32);
- if (n == 0) return null;
- if (n > l.shared.items.len) return error.BadDump;
- const got = l.shared.items[n - 1];
- if (got.dead) return error.Incompatible;
- return got.bytes;
- }
+ /// A reference to a pointer or slice made before, or null for a
+ /// new one (its length then read).
+ fn ref(l: *Self) DecodeError!?[]u8 {
+ const n = try l.scalar(u32);
+ if (n == 0) return null;
+ if (n > l.shared.items.len) return error.BadDump;
+ const got = l.shared.items[n - 1];
+ if (got.dead) return error.Incompatible;
+ return got.bytes;
+ }
- fn slice(l: *Self, comptime E: type, s: SrcType) DecodeError![]E {
- if (try l.ref()) |again| return @as([*]E, @ptrCast(@alignCast(again.ptr)))[0 .. again.len / @max(1, @sizeOf(E))];
- const n = try l.count();
- if (n == 0) return &.{};
- if (n > l.bytes.len) return error.BadDump;
- const many = try l.gpa.alloc(E, n);
- const at = l.made(std.mem.sliceAsBytes(many), .of(E)) catch |err| {
- l.gpa.free(many);
- return err;
- };
- l.elements(E, s.child, n, many) catch |err| {
- l.shared.items[at].dead = true;
- return err;
+ fn slice(l: *Self, comptime E: type, s: SrcType) DecodeError![]E {
+ if (try l.ref()) |again| return @as([*]E, @ptrCast(@alignCast(again.ptr)))[0 .. again.len / @max(1, @sizeOf(E))];
+ const n = try l.count();
+ if (n == 0) return &.{};
+ if (n > l.bytes.len) return error.BadDump;
+ const many = try l.gpa.alloc(E, n);
+ const at = l.made(std.mem.sliceAsBytes(many), .of(E)) catch |err| {
+ l.gpa.free(many);
+ return err;
+ };
+ l.elements(E, s.child, n, many) catch |err| {
+ l.shared.items[at].dead = true;
+ return err;
+ };
+ return many;
+ }
+
+ /// `n` elements of the source's type `ty` into `out` (an array or
+ /// a slice), as many as it holds, the rest passed over.
+ fn elements(l: *Self, comptime E: type, ty: u32, n: u64, out: []E) DecodeError!void {
+ const keep: usize = @intCast(@min(n, out.len));
+ const s = l.src[ty];
+ // Bytes copied whole between builds when both sides agree on
+ // them: integers and bools (an enum's numbers may not be the other's).
+ const bulk = if (comptime flat(E)) l.same or (comptime flatHash(E)) and s.kind == (comptime kindOf(E)) and
+ (s.kind == .bool or (s.bits == @bitSizeOf(E) and s.signed == (@typeInfo(E) == .int and @typeInfo(E).int.signedness == .signed))) else false;
+ if (bulk) {
+ if (n > l.bytes.len) return error.EndOfDump;
+ @memcpy(std.mem.sliceAsBytes(out[0..keep]), try l.take(keep * @sizeOf(E)));
+ _ = try l.take(@intCast((n - keep) * @sizeOf(E)));
+ return;
+ }
+ // An array of optional pointers (a session's panes): one that
+ // cannot be read is left out, not the array.
+ const droppable = comptime @typeInfo(E) == .optional and @typeInfo(@typeInfo(E).optional.child) == .pointer;
+ var failed = false;
+ for (0..try countOf(n)) |i| {
+ if (i >= keep) {
+ try l.skip(ty);
+ continue;
+ }
+ try l.fresh(E, &out[i]);
+ l.value(E, ty, &out[i]) catch |err| {
+ if (err != error.Incompatible) return err;
+ if (droppable) {
+ out[i] = null;
+ l.note("{s}[{d}] left out", .{ l.field, i });
+ } else failed = true;
};
- return many;
}
+ if (failed) return error.Incompatible;
+ }
- /// `n` elements of the source's type `ty` into `out` (an array or
- /// a slice), as many as it holds, the rest passed over.
- fn elements(l: *Self, comptime E: type, ty: u32, n: u64, out: []E) DecodeError!void {
- const keep: usize = @intCast(@min(n, out.len));
- const s = l.src[ty];
- // Bytes copied whole between builds when both sides agree on
- // them: integers and bools (an enum's numbers may not be the other's).
- const bulk = if (comptime flat(E)) l.same or (comptime flatHash(E)) and s.kind == (comptime kindOf(E)) and
- (s.kind == .bool or (s.bits == @bitSizeOf(E) and s.signed == (@typeInfo(E) == .int and @typeInfo(E).int.signedness == .signed))) else false;
- if (bulk) {
- if (n > l.bytes.len) return error.EndOfDump;
- @memcpy(std.mem.sliceAsBytes(out[0..keep]), try l.take(keep * @sizeOf(E)));
- _ = try l.take(@intCast((n - keep) * @sizeOf(E)));
- return;
+ fn fields(l: *Self, comptime T: type, s: SrcType, out: *T, existing: bool) DecodeError!void {
+ const names = comptime dumpFields(T);
+ const packed_struct = comptime @typeInfo(T).@"struct".layout == .@"packed";
+ const outer = l.field;
+ defer l.field = outer;
+ if (l.same) {
+ if (s.fields.len != names.len) return error.BadDump;
+ inline for (names, 0..) |field, k| {
+ l.field = field;
+ try l.oneField(T, field, s.fields[k].ty, out, packed_struct, existing);
}
- // An array of optional pointers (a session's panes): one that
- // cannot be read is left out, not the array.
- const droppable = comptime @typeInfo(E) == .optional and @typeInfo(@typeInfo(E).optional.child) == .pointer;
- var failed = false;
- for (0..try countOf(n)) |i| {
- if (i >= keep) {
- try l.skip(ty);
- continue;
- }
- try l.fresh(E, &out[i]);
- l.value(E, ty, &out[i]) catch |err| {
+ return;
+ }
+ var found: std.StaticBitSet(@max(1, names.len)) = .empty;
+ var failed = false;
+ for (s.fields) |f| {
+ const k: ?usize = inline for (names, 0..) |field, k| {
+ if (std.mem.eql(u8, f.name, field)) break k;
+ } else null;
+ const at = k orelse {
+ try l.skip(f.ty);
+ continue;
+ };
+ found.set(at);
+ inline for (names, 0..) |field, i| if (i == at) {
+ l.field = field;
+ l.oneField(T, field, f.ty, out, packed_struct, existing) catch |err| {
if (err != error.Incompatible) return err;
- if (droppable) {
- out[i] = null;
- l.note("{s}[{d}] left out", .{ l.field, i });
+ const attr = comptime @typeInfo(T).@"struct".field_attrs[std.meta.fieldIndex(T, field).?];
+ if (comptime attr.default_value_ptr) |dp| {
+ @field(out, field) = @as(*const @FieldType(T, field), @ptrCast(@alignCast(dp))).*;
+ l.noteField("its kind changed; its default taken", @typeName(T), field);
+ } else if (existing) {
+ l.noteField("its kind changed; left as it was", @typeName(T), field);
} else failed = true;
};
- }
- if (failed) return error.Incompatible;
+ };
}
-
- fn fields(l: *Self, comptime T: type, s: SrcType, out: *T, existing: bool) DecodeError!void {
- const names = comptime dumpFields(T);
- const packed_struct = comptime @typeInfo(T).@"struct".layout == .@"packed";
- const outer = l.field;
- defer l.field = outer;
- if (l.same) {
- if (s.fields.len != names.len) return error.BadDump;
- inline for (names, 0..) |field, k| {
- l.field = field;
- try l.oneField(T, field, s.fields[k].ty, out, packed_struct, existing);
+ // A field the writer did not have: its default (`fresh`), or
+ // the value cannot be made.
+ inline for (names, 0..) |field, i| if (!found.isSet(i)) {
+ const attr = comptime @typeInfo(T).@"struct".field_attrs[std.meta.fieldIndex(T, field).?];
+ if (comptime attr.default_value_ptr == null) {
+ if (!existing) {
+ l.noteField("not in the dump", @typeName(T), field);
+ failed = true;
}
- return;
- }
- var found: std.StaticBitSet(@max(1, names.len)) = .empty;
- var failed = false;
- for (s.fields) |f| {
- const k: ?usize = inline for (names, 0..) |field, k| {
- if (std.mem.eql(u8, f.name, field)) break k;
- } else null;
- const at = k orelse {
- try l.skip(f.ty);
- continue;
- };
- found.set(at);
- inline for (names, 0..) |field, i| if (i == at) {
- l.field = field;
- l.oneField(T, field, f.ty, out, packed_struct, existing) catch |err| {
- if (err != error.Incompatible) return err;
- const attr = comptime @typeInfo(T).@"struct".field_attrs[std.meta.fieldIndex(T, field).?];
- if (comptime attr.default_value_ptr) |dp| {
- @field(out, field) = @as(*const @FieldType(T, field), @ptrCast(@alignCast(dp))).*;
- l.note("{s}.{s}: its kind changed; its default taken", .{ @typeName(T), field });
- } else if (existing) {
- l.note("{s}.{s}: its kind changed; left as it was", .{ @typeName(T), field });
- } else failed = true;
- };
- };
}
- // A field the writer did not have: its default (`fresh`), or
- // the value cannot be made.
- inline for (names, 0..) |field, i| if (!found.isSet(i)) {
- const attr = comptime @typeInfo(T).@"struct".field_attrs[std.meta.fieldIndex(T, field).?];
- if (comptime attr.default_value_ptr == null) {
- if (!existing) {
- l.note("{s}.{s}: not in the dump", .{ @typeName(T), field });
- failed = true;
- }
- }
- };
- if (failed) return error.Incompatible;
- }
+ };
+ if (failed) return error.Incompatible;
+ }
- fn oneField(l: *Self, comptime T: type, comptime field: []const u8, ty: u32, out: *T, comptime packed_struct: bool, existing: bool) DecodeError!void {
- const F = @FieldType(T, field);
- const gpa = l.gpa;
- defer l.gpa = gpa;
- if (comptime allocOf(T, field)) |which| if (@field(l.allocs, which)) |a| {
- l.gpa = a;
- };
- if (comptime cutArray(T, field)) {
- return l.value(F, ty, &@field(out, field));
- }
- // A struct held in place in one read as it stands (the root's):
- // what it does not hold stays as it is too.
- if (comptime kindOf(Canon(F)) == .@"struct" and Canon(F) == F and @typeInfo(F).@"struct".layout != .@"packed") if (existing) {
- if (!try l.kindMatches(F, ty)) return error.Incompatible;
- return l.fields(F, l.src[ty], &@field(out, field), true);
- };
- if (packed_struct) {
- var copy: F = undefined;
- try l.fresh(F, &copy);
- try l.value(F, ty, &copy);
- @field(out, field) = copy;
- return;
- }
- try l.fresh(F, &@field(out, field));
- try l.value(F, ty, &@field(out, field));
+ fn oneField(l: *Self, comptime T: type, comptime field: []const u8, ty: u32, out: *T, comptime packed_struct: bool, existing: bool) DecodeError!void {
+ const F = @FieldType(T, field);
+ const gpa = l.gpa;
+ defer l.gpa = gpa;
+ if (comptime allocOf(T, field)) |which| if (@field(l.allocs, which)) |a| {
+ l.gpa = a;
+ };
+ if (comptime cutArray(T, field)) {
+ return l.value(F, ty, &@field(out, field));
}
+ // A struct held in place in one read as it stands (the root's):
+ // what it does not hold stays as it is too.
+ if (comptime kindOf(Canon(F)) == .@"struct" and Canon(F) == F and @typeInfo(F).@"struct".layout != .@"packed") if (existing) {
+ if (!try l.kindMatches(F, ty)) return error.Incompatible;
+ return l.fields(F, l.src[ty], &@field(out, field), true);
+ };
+ if (packed_struct) {
+ var copy: F = undefined;
+ try l.fresh(F, &copy);
+ try l.value(F, ty, &copy);
+ @field(out, field) = copy;
+ return;
+ }
+ try l.fresh(F, &@field(out, field));
+ try l.value(F, ty, &@field(out, field));
+ }
- /// The source's value of type `ty` passed over.
- fn skip(l: *Self, ty: u32) DecodeError!void {
- const s = l.src[ty];
- switch (s.kind) {
- .skip, .void => {},
- .bool => _ = try l.take(1),
- .int, .@"enum" => _ = try l.take(intBytes(s.bits)),
- .float => _ = try l.take(s.bits / 8),
- .optional => if ((try l.take(1))[0] != 0) try l.skip(s.child),
- .one => if (try l.scalar(u32) == 0) {
+ /// The source's value of type `ty` passed over.
+ fn skip(l: *Self, ty: u32) DecodeError!void {
+ const s = l.src[ty];
+ switch (s.kind) {
+ .skip, .void => {},
+ .bool => _ = try l.take(1),
+ .int, .@"enum" => _ = try l.take(intBytes(s.bits)),
+ .float => _ = try l.take(s.bits / 8),
+ .optional => if ((try l.take(1))[0] != 0) try l.skip(s.child),
+ .one => if (try l.scalar(u32) == 0) {
+ _ = try l.made(&.{}, .@"1");
+ l.shared.items[l.shared.items.len - 1].dead = true;
+ try l.skip(s.child);
+ },
+ .slice => if (try l.scalar(u32) == 0) {
+ const n = try l.scalar(u64);
+ if (n > 0) {
_ = try l.made(&.{}, .@"1");
l.shared.items[l.shared.items.len - 1].dead = true;
- try l.skip(s.child);
- },
- .slice => if (try l.scalar(u32) == 0) {
- const n = try l.scalar(u64);
- if (n > 0) {
- _ = try l.made(&.{}, .@"1");
- l.shared.items[l.shared.items.len - 1].dead = true;
- }
- try l.skipMany(s.child, n);
- },
- .prefix => try l.skipMany(s.child, try l.scalar(u64)),
- .array => try l.skipMany(s.child, s.len),
- .@"struct" => for (s.fields) |f| try l.skip(f.ty),
- .@"union" => {
- const ordinal = try l.scalar(u16);
- if (ordinal >= s.fields.len) return error.BadDump;
- try l.skip(s.fields[ordinal].ty);
- },
- .err => _ = try l.name(),
- .error_union => if ((try l.take(1))[0] != 0) try l.skip(s.child) else {
- _ = try l.name();
- },
- .custom => _ = try l.take(try l.count()),
- .bitset => _ = try l.take((try l.count() + 63) / 64 * 8),
- }
+ }
+ try l.skipMany(s.child, n);
+ },
+ .prefix => try l.skipMany(s.child, try l.scalar(u64)),
+ .array => try l.skipMany(s.child, s.len),
+ .@"struct" => for (s.fields) |f| try l.skip(f.ty),
+ .@"union" => {
+ const ordinal = try l.scalar(u16);
+ if (ordinal >= s.fields.len) return error.BadDump;
+ try l.skip(s.fields[ordinal].ty);
+ },
+ .err => _ = try l.name(),
+ .error_union => if ((try l.take(1))[0] != 0) try l.skip(s.child) else {
+ _ = try l.name();
+ },
+ .custom => _ = try l.take(try l.count()),
+ .bitset => _ = try l.take((try l.count() + 63) / 64 * 8),
}
+ }
- fn skipMany(l: *Self, ty: u32, n: u64) DecodeError!void {
- const s = l.src[ty];
- if (s.kind == .int or s.kind == .bool) {
- const size: u64 = if (s.kind == .bool) 1 else intBytes(s.bits);
- if (n > l.bytes.len) return error.EndOfDump;
- _ = try l.take(@intCast(n * size));
- return;
- }
- for (0..try countOf(n)) |_| try l.skip(ty);
+ fn skipMany(l: *Self, ty: u32, n: u64) DecodeError!void {
+ const s = l.src[ty];
+ if (s.kind == .int or s.kind == .bool) {
+ const size: u64 = if (s.kind == .bool) 1 else intBytes(s.bits);
+ if (n > l.bytes.len) return error.EndOfDump;
+ _ = try l.take(@intCast(n * size));
+ return;
}
- };
-}
+ for (0..try countOf(n)) |_| try l.skip(ty);
+ }
+};
/// `out` as a new `T` is before a load reads its fields: each field's
/// default, an allocator `gpa`.
@@ -1854,6 +1878,11 @@ pub const Get = struct {
l.notes.print(l.own, fmt ++ "\n", args) catch {};
}
+ /// A note on a type's field, its names given at run time (Load's).
+ fn noteField(l: *Get, comptime what: []const u8, type_name: []const u8, field: []const u8) void {
+ l.note("{s}.{s}: " ++ what, .{ type_name, field });
+ }
+
/// The value at `c`, made: what it points at is `gpa`'s.
pub fn get(l: *Get, comptime T: type, c: Cursor) Error!T {
var out: T = undefined;
@@ -2270,9 +2299,9 @@ pub const Get = struct {
const attr = comptime @typeInfo(T).@"struct".field_attrs[std.meta.fieldIndex(T, field).?];
if (comptime attr.default_value_ptr) |dp| {
@field(out, field) = @as(*const @FieldType(T, field), @ptrCast(@alignCast(dp))).*;
- l.note("{s}.{s}: its kind changed; its default taken", .{ @typeName(T), field });
+ l.noteField("its kind changed; its default taken", @typeName(T), field);
} else if (existing) {
- l.note("{s}.{s}: its kind changed; left as it was", .{ @typeName(T), field });
+ l.noteField("its kind changed; left as it was", @typeName(T), field);
} else failed = true;
};
};
@@ -2284,7 +2313,7 @@ pub const Get = struct {
const attr = comptime @typeInfo(T).@"struct".field_attrs[std.meta.fieldIndex(T, field).?];
if (comptime attr.default_value_ptr == null and kindOf(Canon(F)) != .void) {
if (!existing) {
- l.note("{s}.{s}: not in the dump", .{ @typeName(T), field });
+ l.noteField("not in the dump", @typeName(T), field);
failed = true;
}
} else if (comptime @typeInfo(F) == .optional and defaultIsNull(T, field)) if (existing) {
@@ -2564,3 +2593,8 @@ test "a blob of 4 KiB and up is digested by its length, what it holds told by it
small[1] = 'x';
try std.testing.expect(digest(File, &f) != was);
}
+
+test "a shape's numbers are written as {d} writes them" {
+ inline for (.{ 0, 7, 10, 65535, -1, -300, std.math.minInt(i128), std.math.maxInt(u128) }) |n|
+ try std.testing.expectEqualStrings(std.fmt.comptimePrint("{d}", .{n}), comptime decimal(n));
+}
diff --git a/src/wire.zig b/src/wire.zig
index cd1554b9..9773d222 100644
--- a/src/wire.zig
+++ b/src/wire.zig
@@ -61,16 +61,18 @@ const family = switch (config.platform) {
/// their options and dependencies; -Dstamp-commit stamps one.
pub const semantics: u64 = blk: {
@setEvalBranchQuota(1_000_000);
+ // 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{s}\n{s}",
+ "wire {d}\npardes {s} {s}\n{s} grammars {} {} {} {} workspace_tag {} sources {}\nusize {d} {t}\n",
.{
version, config.version, config.commit orelse "unstamped",
family, config.syntax_highlighting, config.syntax_zig_grammar,
config.syntax_minimal_grammars, config.syntax_full_grammars, config.workspace_tag,
config.embed_sources, @sizeOf(usize), builtin.cpu.arch.endian(),
- config.deps, pardes.tape.shape,
},
- ));
+ ) ++ config.deps ++ "\n" ++ pardes.tape.shape);
};
/// EndOfStream: the message ends early; WriteFailed: no room for it.