summaryrefslogtreecommitdiff
path: root/core
diff options
context:
space:
mode:
Diffstat (limited to 'core')
-rw-r--r--core/Core.zig87
-rw-r--r--core/File.zig642
-rw-r--r--core/Jump.zig9
-rw-r--r--core/Messages.zig12
-rw-r--r--core/Output.zig1
-rw-r--r--core/Places.zig11
-rw-r--r--core/Query.zig40
-rw-r--r--core/Text.zig27
-rw-r--r--core/draw.zig3
-rw-r--r--core/dump.zig132
-rw-r--r--core/exec.zig7
-rw-r--r--core/fuzz.zig53
-rw-r--r--core/jj.zig173
-rw-r--r--core/layout.zig35
-rw-r--r--core/look.zig55
-rw-r--r--core/lsp/Ask.zig2
-rw-r--r--core/mouse.zig14
-rw-r--r--core/ninep/events.zig4
-rw-r--r--core/normal.zig185
-rw-r--r--core/panes.zig75
-rw-r--r--core/replica.zig213
-rw-r--r--core/rollback.zig3
-rw-r--r--core/root.zig6
-rw-r--r--core/surface.zig4
-rw-r--r--core/views.zig153
-rw-r--r--core/walk.zig525
-rw-r--r--core/walk.zig.orig2618
27 files changed, 2223 insertions, 2866 deletions
diff --git a/core/Core.zig b/core/Core.zig
index 4c8aa2eb..835eb86c 100644
--- a/core/Core.zig
+++ b/core/Core.zig
@@ -87,7 +87,19 @@ const Pardes = @This();
/// One client's view of the session (views.zig): its screen and layout,
/// its focus, its pointer and gestures, its jumps, its key prefixes.
pub const View = struct {
- pub const replica = .{ .len = .{ .{ "leader_keys", "leader_n" }, .{ "col_x", "ncol" }, .{ "col_w", "ncol" } } };
+ pub const replica = .{
+ .len = .{ .{ "leader_keys", "leader_n" }, .{ "cols", "ncol" }, .{ "col_x", "ncol" }, .{ "col_w", "ncol" } },
+ // What its keyboard is on: a pane there; window mode's outline and
+ // a kind's press and hover, slots; its screen, a grid a frontend
+ // sizes (walk.zig `.index`).
+ .index = .{ .{ "active", Pardes, "focusPanes" }, .{ "window_pick", Pardes, "panes" }, .{ "kind_grab", Pardes, "panes" }, .{ "kind_hover", Pardes, "panes" }, .{ "screen_w", "grids" }, .{ "screen_h", "grids" } },
+ // Its geometry, read back as the session holds it (a view opened
+ // and not laid out yet has none, on a join's client too, whose
+ // kinds are told its views as the session's are): on its screen,
+ // a pane's rect and a column's `col_x` with its width (walk.zig
+ // `.within`).
+ .within = .{ .{ "rects", "onScreen" }, .{ "col_w", "columnOnScreen" } },
+ };
/// A view's slot in `Pardes.views`, as it crosses the core's edge: an
/// entry's argument or answer, the wire's welcome. A type of its own,
/// so a pane's slot (`Pane.Id`) is not taken for it; the core's own
@@ -202,6 +214,28 @@ pub const View = struct {
pastes: u32 = 0,
links: u32 = 0,
link: pardes.Effect.Buf(256) = .{},
+
+ /// A side of a grid a frontend sizes: a cell at least (a zero is
+ /// refused, not clamped, as the wire refuses one: abi/wire.zig
+ /// `getCols`), past no display's (a frame is as many cells as it
+ /// holds, Surface.cells: a damaged image's asked 111 GB).
+ pub fn grids(_: *const View, n: usize) bool {
+ return n >= 1 and n <= max_grid;
+ }
+ pub const max_grid = 4096;
+
+ /// Pane slot `id`'s rect on the screen, where the layout pass puts
+ /// every one (a frame is the screen's cells: one past it, drawn, is a
+ /// cell outside the frame).
+ pub fn onScreen(v: *const View, id: usize) bool {
+ const r = v.rects[id];
+ return @as(u32, r.x) + r.w <= v.screen_w and @as(u32, r.y) + r.h <= v.screen_h;
+ }
+
+ /// Column `c` on the screen: its left edge and its width.
+ pub fn columnOnScreen(v: *const View, c: usize) bool {
+ return @as(u32, v.col_x[c]) + v.col_w[c] <= v.screen_w;
+ }
};
gpa: std.mem.Allocator,
@@ -475,6 +509,11 @@ pub const replica = .{
"in_head", "in_len",
// The views no frontend here draws (views.zig).
"undrawn",
+ // A step's own, set and put back within it (a key's replay across
+ // the ranges, normal.replaySels; a word's run, exec.zig): as
+ // `init` makes them between any two steps.
+ "multi_first", "multi_stop", "multi_index",
+ "multi_count", "exec_depth", "exec_column",
// How this process was started, and the last dump it made for
// its host to write: a session loaded elsewhere has its own.
"opts", "dump_out", "dump_export",
@@ -487,8 +526,38 @@ pub const replica = .{
// server's own part of `fs` says so in fs.Namespace.)
.authority = .{ "host", "store", "recent", "db", "fallback" },
.len = .{ .{ "look_src", "n_look_src" }, .{ "session_dir", "session_dir_len" }, .{ "session_home", "session_home_len" }, .{ "session_shell", "session_shell_len" } },
+ // The live view is an open one; a ThemeFile's pane a slot (walk.zig
+ // `.index`).
+ .index = .{ .{ "live", "openViews" }, .{ "theme_file_pane", "panes" } },
+ // A pane another build's dump could not give: out of every layout.
+ .left_out = "dropMissing",
};
+/// What an index into the session names (walk.zig `.index`): an open view.
+pub fn openViews(p: *const Pardes, k: usize) bool {
+ return k < Views.max and p.views[k] != null;
+}
+
+/// A pane there.
+pub fn openPanes(p: *const Pardes, id: usize) bool {
+ return id < MAX_PANES and p.panes[id] != null;
+}
+
+/// What a view's keyboard may be on: a pane there, or any slot in a window
+/// with none (the last column's Delcol leaves one, layout.zig `delColumn`).
+pub fn focusPanes(p: *const Pardes, id: usize) bool {
+ if (id >= MAX_PANES) return false;
+ if (p.panes[id] != null) return true;
+ return for (p.panes) |slot| {
+ if (slot != null) break false;
+ } else true;
+}
+
+/// The panes a view's columns list that are not there (another build's
+/// dump left them out: walk.zig `left_out`) taken out of them, and its
+/// keyboard on one that is.
+pub const dropMissing = pardes.dump.dropMissing;
+
/// The message row's entry points, called from everywhere as
/// `p.setMessage(...)`; they live with the rest of it in Messages.zig.
pub const setStatus = Messages.setStatus;
@@ -1684,7 +1753,7 @@ fn updateInner(p: *Pardes, ev: Event) void {
v.cell_pixels.w = @max(1, sz.cell_pixels.w);
v.cell_pixels.h = @max(1, sz.cell_pixels.h);
layout.compute(p);
- p.resize_count += 1;
+ p.resize_count +|= 1;
},
.output => |o| {
const pane = p.panes[o.pane.index()] orelse return;
@@ -1923,7 +1992,7 @@ pub fn sync(p: *Pardes) void {
// had any; a folded pane shows its first line only. Its prefix
// is made once, on the stack: this runs on every event, and not
// every event may take from the scratch arena.
- var wrap_room: [32 * 1024]u8 = undefined;
+ var wrap_room: [Pane.prefix_room]u8 = undefined;
var wrap_fba = std.heap.FixedBufferAllocator.init(&wrap_room);
const wa = wrap_fba.allocator();
const prefix: ?[]const u8 = tagline.prefixIn(p, wa, pane) catch null;
@@ -2217,9 +2286,9 @@ pub const PendingWrite = struct { bytes: []u8, off: usize = 0 };
/// place on screen (`col_x`, `col_w`) is worked out each sync, as a pane's
/// rect is.
pub const Column = struct {
- // Zeroed, not undefined: a digest takes the whole of it, a release
- // build's heap leaves its unused slots whatever was there before, and
- // two replicas must agree on them (core/replica.zig).
+ /// Its panes, as far as `n` says (what a digest, a dump and a copy take),
+ /// each a pane there (walk.zig `.index`).
+ pub const replica = .{ .len = .{.{ "panes", "n" }}, .index = .{.{ "panes", Pardes, "openPanes" }} };
panes: [MAX_PANES]usize = @splat(0),
n: usize = 0,
weight: u64 = column_weight_unit,
@@ -3871,11 +3940,11 @@ test "raw terminal cursor follows its active row only while that row is visible"
try std.testing.expectEqual(rect.x + config.GUTTER + 3, live.x);
try std.testing.expectEqual(body_y + 2, live.y);
- pane.scrollBy(-1);
+ pane.scrollBy(p.settings.tab, -1);
const scrolled = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor;
try std.testing.expectEqual(live.x, scrolled.x);
try std.testing.expectEqual(live.y + 1, scrolled.y);
- pane.scrollBy(-@as(i32, pane.rows));
+ pane.scrollBy(p.settings.tab, -@as(i32, pane.rows));
try std.testing.expect((try p.render(frame.allocator())).cursor == null);
pane.followOutput();
const returned = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor;
@@ -3929,7 +3998,7 @@ test "tty output follows only from the bottom" {
try std.testing.expect(bottom > 0);
// Scrolled back, the reader stays put however much the shell prints.
- sp.scrollBy(-10);
+ sp.scrollBy(p.settings.tab, -10);
p.sync();
const parked = sp.termTop();
try std.testing.expect(parked < bottom);
diff --git a/core/File.zig b/core/File.zig
index b2df6c0f..07dfa52d 100644
--- a/core/File.zig
+++ b/core/File.zig
@@ -98,7 +98,7 @@ pub const State = struct {
/// from the text whenever it is wanted.
// Syntax caches must not load through the dump loader's core allocator.
pub const replica = .{
- .derived = .{ "cap", "line_starts", "line_cap", "highlights", "highlight_start", "syntax_dirty", "node_tree", "node_tree_revision", "node_tree_edits", "node_history", "tables" },
+ .derived = .{ "cap", "line_starts", "line_cap", "widest", "highlights", "highlight_start", "syntax_dirty", "node_tree", "node_tree_revision", "node_tree_edits", "node_history", "tables" },
// Big texts, dumped and sent by their hash (core/walk.zig). The
// text is written in place by `replace`, but never while a join
// sends it (memory.zig `pin`): then an edit puts a new buffer in
@@ -108,8 +108,21 @@ pub const State = struct {
// none of their bytes, and takes back what a speculation wrote
// (core/rollback.zig `Epoch.wrote`).
.journal = .{ "content", "line_starts" },
+ // Where the view's top is, held to its text (walk.zig `.place`);
+ // its row in that line is any (an edit leaves it past the line's
+ // rows, read as the last: `top`), as the session holds it.
+ .place = .{.{ "scroll", "lastLine" }},
};
+ /// The last line a view's top may be at: its text's. A clean file a
+ /// slim dump left the text of (dump.zig `Slim`, read from its file
+ /// again when it is revived) has a line a byte of what it saved at most,
+ /// in the rows a view counts (`Pane.wrap_line`).
+ pub fn lastLine(f: *const State) usize {
+ if (f.content.len == 0) if (f.saved_len) |n| return @min(n, std.math.maxInt(i32));
+ return modal.lineCount(f.content) -| 1;
+ }
+
path: []u8,
content: []u8,
/// The bytes `content`'s buffer has room for (0: as many as it holds):
@@ -160,11 +173,18 @@ pub const State = struct {
/// A directory pane's entries (Dir.zig), its output `.dir`.
listing: ?panes.Dir.State = null,
mini: ?Mini.State = null,
+ /// The view's top: the line its first row is of, and that row of the
+ /// line's wrapped rows (`Top`): each view's own (views.zig), digested,
+ /// dumped.
scroll: usize = 0,
+ scroll_row: u32 = 0,
/// `line_starts[i]` is line i's byte offset. Empty means not built yet.
line_starts: []usize = &.{},
/// The room `line_starts` has, as `cap` is `content`'s.
line_cap: usize = 0,
+ /// The widest any line is, found with the index and kept with it
+ /// (`Widest`): what tells a view whose rows are its lines (`oneRow`).
+ widest: Widest = .{},
/// One tree_sitter_gpa-owned syntax.Syn byte per highlighted source byte.
highlights: []u8 = &.{},
location_rows: []locations.Row = &.{},
@@ -526,7 +546,7 @@ pub fn rowTable(pane: *const Pane, row: i32) ?*const Tables.Table {
const f = if (pane.file) |*file| file else return null;
if (row < 0 or f.tables.list.items.len == 0 or !f.tables.current(f)) return null;
const table = f.tables.find(@intCast(row)) orelse return null;
- const width = wrapWidth(pane, pane.body_wrapped);
+ const width = wrapWidth(pane, pane.view.wrap);
if (width > 0 and table.width > width) return null;
return table;
}
@@ -605,6 +625,24 @@ pub fn renderedLineDisplayCol(tab: u16, pane: *const Pane, row: i32, line_text:
pub fn fitEnd(tab: u16, text: []const u8, start: usize, width: usize) usize {
var end = start;
var used: usize = 0;
+ // A vector of printable ASCII at a time, a cell a byte, while the width
+ // is past it and the byte after it is ASCII too: what the loop below
+ // takes a byte at a time (it leaves the ASCII byte a non-ASCII one
+ // follows to the grapheme walk). Every row walk is this loop.
+ while (used + lanes < width and end + lanes < text.len and text[end + lanes] < 0x80) {
+ const v: Lanes = text[end..][0..lanes].*;
+ if (@reduce(.Or, v -% @as(Lanes, @splat(0x20)) >= @as(Lanes, @splat(0x5f)))) break;
+ used += lanes;
+ end += lanes;
+ }
+ // The rest of a row of printable ASCII in one vector more: its bytes and
+ // the two after them printable ASCII, the row ends where the width does
+ // (what the loops below find a byte at a time).
+ if (used < width and width - used + 2 <= lanes and end + lanes <= text.len) {
+ const v: Lanes = text[end..][0..lanes].*;
+ const bad: @Int(.unsigned, lanes) = @bitCast(v -% @as(Lanes, @splat(0x20)) >= @as(Lanes, @splat(0x5f)));
+ if (@ctz(bad) >= width - used + 2) return end + (width - used);
+ }
while (used < width and end < text.len) {
const b = text[end];
if (b < 0x20 or b >= 0x7f) break;
@@ -612,6 +650,10 @@ pub fn fitEnd(tab: u16, text: []const u8, start: usize, width: usize) usize {
used += 1;
end += 1;
}
+ // A full row before a printable ASCII byte no non-ASCII byte follows (a
+ // grapheme of its own, a cell wide): the row ends there, nothing walked
+ // (every wrapped row ends so, and the walk cost a row a hundred more).
+ if (used == width and end > start and end < text.len and text[end] -% 0x20 < 0x5f and (end + 1 == text.len or text[end + 1] < 0x80)) return end;
while (end < text.len) {
const next_end = modal.nextGrapheme(text, end);
const next_used = used +| graphemeDisplayWidth(tab, text[end..next_end]);
@@ -629,20 +671,91 @@ pub fn lineIndex(gpa: std.mem.Allocator, f: *State) ![]const usize {
if (f.line_starts.len > 0) return f.line_starts;
// Exact allocation: deinitPane frees `line_starts` itself, so the stored
// slice must span the complete allocation rather than spare capacity.
- const starts = try gpa.alloc(usize, lineCount(f.content));
+ const found = countLines(f.content);
+ const starts = try gpa.alloc(usize, found.newlines + 1);
starts[0] = 0;
- var i: usize = 1;
- var off: usize = 0;
- while (std.mem.indexOfScalarPos(u8, f.content, off, '\n')) |nl| {
- off = nl + 1;
- starts[i] = off;
- i += 1;
- }
+ f.widest = .{ .bytes = fillLines(f.content, 0, starts[1..]), .tabbed = found.tabbed };
f.line_starts = starts;
f.line_cap = 0;
return starts;
}
+/// The widest a text's lines are, at most: the most bytes between two
+/// newlines, and whether a tab is among them. A tab is `tab` cells, any
+/// other byte at most one (graphemeDisplayWidth), so a line is never
+/// wider than its bytes, times the tab width where a tab may be. Made
+/// with the line index and kept by its edits, only ever made wider: an
+/// edit taking the widest line away leaves it so (`oneRow` then walks,
+/// and finds the same rows).
+pub const Widest = struct {
+ bytes: usize = 0,
+ tabbed: bool = false,
+
+ fn cells(w: Widest, tab: u16) usize {
+ return if (w.tabbed) w.bytes *| @max(tab, 1) else w.bytes;
+ }
+};
+
+const lanes = std.simd.suggestVectorLength(u8) orelse 16;
+const Lanes = @Vector(lanes, u8);
+
+/// The newlines in `bytes` and whether a tab is among them: a lane's own
+/// sum a vector, added up every 255 (std.mem.count's popcount of a mask is
+/// a dozen instructions a vector on a baseline x86-64).
+fn countLines(bytes: []const u8) struct { newlines: usize, tabbed: bool } {
+ const one: Lanes = @splat(1);
+ const zero: Lanes = @splat(0);
+ var newlines: usize = 0;
+ var tabs = zero;
+ var i: usize = 0;
+ while (bytes.len - i >= lanes) {
+ var sums = zero;
+ for (0..@min((bytes.len - i) / lanes, 255)) |_| {
+ const v: Lanes = bytes[i..][0..lanes].*;
+ sums += @select(u8, v == @as(Lanes, @splat('\n')), one, zero);
+ tabs |= @select(u8, v == @as(Lanes, @splat('\t')), one, zero);
+ i += lanes;
+ }
+ newlines += @reduce(.Add, @as(@Vector(lanes, u16), sums));
+ }
+ var tabbed = @reduce(.Or, tabs) != 0;
+ for (bytes[i..]) |b| {
+ newlines += @intFromBool(b == '\n');
+ tabbed = tabbed or b == '\t';
+ }
+ return .{ .newlines = newlines, .tabbed = tabbed };
+}
+
+/// The start after each newline of `bytes` (its byte `off` past it) into
+/// `out`, a vector at a time, a newline's place off its mask (a search for
+/// each cost a short line ~57 instructions); and the most bytes of `bytes`
+/// between two newlines or an end.
+fn fillLines(bytes: []const u8, off: usize, out: []usize) usize {
+ const Mask = @Int(.unsigned, lanes);
+ var n: usize = 0;
+ var from: usize = 0;
+ var widest: usize = 0;
+ var i: usize = 0;
+ while (i + lanes <= bytes.len) : (i += lanes) {
+ const v: Lanes = bytes[i..][0..lanes].*;
+ var nl: Mask = @bitCast(v == @as(Lanes, @splat('\n')));
+ while (nl != 0) : (nl &= nl - 1) {
+ const at = i + @ctz(nl);
+ widest = @max(widest, at - from);
+ from = at + 1;
+ out[n] = off + from;
+ n += 1;
+ }
+ }
+ for (bytes[i..], i..) |b, at| if (b == '\n') {
+ widest = @max(widest, at - from);
+ from = at + 1;
+ out[n] = off + from;
+ n += 1;
+ };
+ return @max(widest, bytes.len - from);
+}
+
/// The whole buffer of a text's bytes, its room past them included.
fn textRoom(f: *const State) []u8 {
return f.content.ptr[0..@max(f.cap, f.content.len)];
@@ -668,7 +781,10 @@ pub const Span = struct { head: usize, tail: usize };
fn shiftIndex(gpa: std.mem.Allocator, f: *State, off: usize, len: usize, bytes: []const u8) void {
const starts = f.line_starts;
const room = indexRoom(f);
- const n = starts.len - (std.sort.upperBound(usize, starts, off + len, ascending) - std.sort.upperBound(usize, starts, off, ascending)) + std.mem.count(u8, bytes, "\n");
+ const first = std.sort.upperBound(usize, starts, off, ascending);
+ const found = countLines(bytes);
+ const added = found.newlines;
+ const n = starts.len - (std.sort.upperBound(usize, starts, off + len, ascending) - first) + added;
var out = room;
if (n > room.len) {
out = gpa.alloc(usize, n + @max(n / 8, 512)) catch {
@@ -679,10 +795,17 @@ fn shiftIndex(gpa: std.mem.Allocator, f: *State, off: usize, len: usize, bytes:
};
@memcpy(out[0..starts.len], starts);
} else pardes.rollback.Epoch.wrote(gpa, usize, room, starts.len, n, off, f.content[off..][0..len], bytes.len);
- shiftStarts(out, starts.len, n, off, len, bytes);
+ const inside = shiftStarts(out, starts.len, n, off, len, bytes);
if (out.ptr != room.ptr) pardes.memory.freeRaw(gpa, room);
f.line_starts = out[0..n];
f.line_cap = out.len;
+ // The widest: what the edit put in, and the two lines it joined at
+ // its ends (the line `off` is on, the one its last newline starts).
+ const total = f.content.len - len + bytes.len;
+ const ends = [2]usize{ first - 1, first - 1 + added };
+ var widest = @max(f.widest.bytes, inside);
+ for (ends) |l| widest = @max(widest, (if (l + 1 < n) f.line_starts[l + 1] - 1 else total) - f.line_starts[l]);
+ f.widest = .{ .bytes = widest, .tabbed = f.widest.tabbed or found.tabbed };
}
/// The first `len` of `room`, a line index, through the edit that puts
@@ -692,7 +815,8 @@ fn shiftIndex(gpa: std.mem.Allocator, f: *State, off: usize, len: usize, bytes:
/// only the moving is a pass over the index, and only from the edit on. The
/// edit turned round (`cut` its length in, `bytes` what it took out) gives
/// the index before it back: a rollback's (core/rollback.zig `unwrite`).
-pub fn shiftStarts(room: []usize, len: usize, n: usize, off: usize, cut: usize, bytes: []const u8) void {
+/// The most bytes of `bytes` between two newlines or an end (fillLines).
+pub fn shiftStarts(room: []usize, len: usize, n: usize, off: usize, cut: usize, bytes: []const u8) usize {
const starts = room[0..len];
const kept = std.sort.upperBound(usize, starts, off, ascending);
const moved = len - std.sort.upperBound(usize, starts, off + cut, ascending);
@@ -709,13 +833,7 @@ pub fn shiftStarts(room: []usize, len: usize, n: usize, off: usize, cut: usize,
} else for (0..moved) |k| {
room[to + k] = room[from + k] - cut + bytes.len;
}
- var i = kept;
- var at: usize = 0;
- while (std.mem.indexOfScalarPos(u8, bytes, at, '\n')) |nl| {
- at = nl + 1;
- room[i] = off + at;
- i += 1;
- }
+ return fillLines(bytes, off, room[kept..]);
}
/// line count, O(1) once the index is warm
@@ -982,9 +1100,9 @@ pub fn relayer(p: *Pardes, f: *State, new: []u8, spans: []ReadOnly, layer: u32)
// selection's anchor and ranges in the live view, a cursor and a top
// line in the others.
const Place = struct { row: *i32, col: *i32, at: usize };
- const Top = struct { line: *usize, at: usize };
+ const Kept = struct { line: *usize, at: usize };
var places: std.ArrayList(Place) = .empty;
- var tops: std.ArrayList(Top) = .empty;
+ var tops: std.ArrayList(Kept) = .empty;
const At = struct {
fn of(q: *Pardes, g: *State, row: i32, col: i32) usize {
const r: usize = @intCast(@max(0, row));
@@ -1031,7 +1149,7 @@ pub fn relayer(p: *Pardes, f: *State, new: []u8, spans: []ReadOnly, layer: u32)
place.row.* = @intCast(pos.row);
place.col.* = @intCast(pos.col);
}
- for (tops.items) |top| top.line.* = positionIn(p.gpa, f, bufferOffset(f, top.at, false)).row;
+ for (tops.items) |kept| kept.line.* = positionIn(p.gpa, f, bufferOffset(f, kept.at, false)).row;
return true;
}
@@ -1222,6 +1340,7 @@ fn edit(p: *Pardes, f: *State, off: usize, len: usize, bytes_in: []const u8, who
tf.cap = f.cap;
tf.line_starts = f.line_starts;
tf.line_cap = f.line_cap;
+ tf.widest = f.widest;
if (!told and tf.context.revision == f.revision -% 1) tf.context.revision = f.revision;
// Its copy of the read-only lines, moved as this one's were (the
// layer's own edit sets them after, jj.showLayer).
@@ -1409,6 +1528,7 @@ pub fn zerox(p: *Pardes, from: usize, to: usize) !*Pane {
.cap = f.cap,
.line_starts = f.line_starts,
.line_cap = f.line_cap,
+ .widest = f.widest,
.history = f.history,
.revision = f.revision,
.saved_revision = f.saved_revision,
@@ -1419,6 +1539,7 @@ pub fn zerox(p: *Pardes, from: usize, to: usize) !*Pane {
.on_disk = f.on_disk,
.mtime = f.mtime,
.scroll = f.scroll,
+ .scroll_row = f.scroll_row,
.tree_context = f.tree_context,
.twin = f.twin,
};
@@ -1650,11 +1771,390 @@ fn pageEnd(tab: u16, pane: *Pane) usize {
}
fn setPageScroll(pane: *Pane, line: usize) void {
+ setTop(pane, .{ .line = @min(line, nlines(pane.gpa, &pane.file.?) -| 1) });
+}
+
+/// A view's top: the line its first row is of (`State.scroll`) and that
+/// row of the line's rows as wrapped (`State.scroll_row`; one row
+/// unwrapped). A scroll moves it by rows through the lines.
+pub const Top = struct { line: usize, row: u32 = 0 };
+
+/// The row of line `line` that shows its byte `col` (a line's last row
+/// every byte past its start, as wrapRow has it), as fillBody wraps it.
+pub fn rowOf(tab: u16, pane: *const Pane, line: usize, col: usize) u32 {
+ return rowIn(tab, pane, line, col).row;
+}
+
+/// The rows line `line` takes in `pane`'s view.
+pub fn lineRows(tab: u16, pane: *const Pane, line: usize) u32 {
+ return rowIn(tab, pane, line, std.math.maxInt(usize)).rows;
+}
+
+/// Whether every line of `pane`'s view is one row: none wider than a row
+/// (the text's widest, kept with its index), so its rows are its lines and
+/// the walks below are line arithmetic, nothing read.
+fn oneRow(tab: u16, pane: *const Pane, width: usize) bool {
const f = &pane.file.?;
- const to = @min(line, nlines(pane.gpa, f) -| 1);
- if (to == f.scroll) return;
- f.scroll = to;
- f.syntax_dirty = true;
+ return width == 0 or (f.line_starts.len > 0 and f.widest.cells(tab) <= width);
+}
+
+const RowIn = struct { row: u32, rows: u32 };
+
+/// rowOf's row and lineRows' rows, in one walk of the line: the one walk
+/// of a line's rows every map from rows to lines asks, beside the
+/// geometry's own map of the body (the same `fitEnd` at the same width).
+fn rowIn(tab: u16, pane: *const Pane, line: usize, col: usize) RowIn {
+ const width = wrapWidth(pane, pane.view.wrap);
+ if (pane.file != null and oneRow(tab, pane, width)) {
+ if (builtin.mode == .debug) std.debug.assert(rowWalked(tab, pane, width, line, col, .{}, &.{}).rows == 1);
+ return .{ .row = 0, .rows = 1 };
+ }
+ return rowWalked(tab, pane, width, line, col, .{}, &.{});
+}
+
+/// How far a walk of a line's rows goes once the row showing its byte is
+/// found: `after` rows past it and `least` in all, its rows a lower bound
+/// then (what `show` needs of a long line); else to its end.
+const Bound = struct { after: u32 = std.math.maxInt(u32), least: u32 = 0 };
+
+/// rowIn's walk at `width`, as far as `bound`; `starts`, when it has room,
+/// keeps the first byte of each row walked after the first, the last
+/// `starts.len` of them (row `r` at `r % starts.len`; its caller's row 0).
+fn rowWalked(tab: u16, pane: *const Pane, width: usize, line: usize, col: usize, bound: Bound, starts: []usize) RowIn {
+ const f = if (pane.file) |*file| file else return .{ .row = 0, .rows = 1 };
+ if (width == 0) return .{ .row = 0, .rows = 1 };
+ const text = sourceLine(pane, @intCast(line));
+ // No more bytes than a row has cells and no tab is one row: a tab is
+ // `tab` cells, any other byte at most one (Widest); no grapheme walked
+ // (the lines a page or a margin crosses, nearly all of a source's).
+ if (text.len <= width and std.mem.indexOfScalar(u8, text, '\t') == null) {
+ if (builtin.mode == .debug) std.debug.assert(fitEnd(tab, text, 0, width) >= text.len);
+ return .{ .row = 0, .rows = 1 };
+ }
+ var guide: [1024]u8 = undefined;
+ var at: usize = 0;
+ var row: u32 = 0;
+ var found: ?u32 = null;
+ while (true) {
+ const end = fitEnd(tab, text, at, width - displayWidth(tab, guideOf(f, text, at, width, &guide)));
+ if (found == null and col < end) found = row;
+ if (end >= text.len or end <= at) return .{ .row = found orelse row, .rows = row + 1 };
+ if (found) |r| if (row >= r +| bound.after and row + 1 >= bound.least) return .{ .row = r, .rows = row + 1 };
+ at = end;
+ row += 1;
+ if (starts.len > 0) starts[row % starts.len] = at;
+ }
+}
+
+/// Where `pane`'s view starts: a row past its line's last (the text
+/// rewrapped, an edit, the layer's lines come or gone) is read as its
+/// last, as the geometry's walk found it (no walk of the line a frame).
+pub fn top(tab: u16, pane: *Pane) Top {
+ if (pane.file.?.scroll_row > 0) geometry(tab, pane);
+ return topNow(tab, pane);
+}
+
+/// `top` off a geometry made already (a step that made it reads its key
+/// once: each hash of it costs a long line's step a hundredth more).
+fn topNow(tab: u16, pane: *Pane) Top {
+ const f = &pane.file.?;
+ return .{ .line = f.scroll, .row = if (f.scroll_row == 0) 0 else topSkip(tab, pane).row };
+}
+
+/// The top's row in its line (held at the line's last) and its first byte,
+/// for the geometry made now: the one read of `Pane.top_skip`, a cache
+/// keyed by the geometry it is of. A step that moves the top hands the
+/// next geometry its byte (`show`, `scrollRows`), and a view drawn or
+/// stepped in since leaves its own: one keyed for another geometry is
+/// another view's top, or another place's, never this one's, and is
+/// walked again here.
+fn topSkip(tab: u16, pane: *Pane) @FieldType(Pane, "top_skip") {
+ if (pane.top_skip.key == pane.geometry_key) return pane.top_skip;
+ const f = &pane.file.?;
+ const width = wrapWidth(pane, pane.view.wrap);
+ const text = if (f.scroll < nlines(pane.gpa, f)) sourceLine(pane, @intCast(f.scroll)) else "";
+ var guide: [1024]u8 = undefined;
+ var row: u32 = 0;
+ var at: usize = 0;
+ while (row < f.scroll_row and width > 0) : (row += 1) {
+ const end = fitEnd(tab, text, at, width - displayWidth(tab, guideOf(f, text, at, width, &guide)));
+ if (end >= text.len or end <= at) break;
+ at = end;
+ }
+ pane.top_skip = .{ .key = pane.geometry_key, .row = row, .at = at };
+ return pane.top_skip;
+}
+
+pub fn setTop(pane: *Pane, to: Top) void {
+ const f = &pane.file.?;
+ if (to.line != f.scroll) f.syntax_dirty = true;
+ f.scroll = to.line;
+ f.scroll_row = to.row;
+}
+
+/// The place `n` rows below `from` (above it, `n` negative) through the
+/// lines' rows, held at the text's first row and at its last line's last;
+/// and the rows it moved.
+pub fn walkRows(tab: u16, pane: *Pane, from: Top, n: i64) Walked {
+ return walkKnown(tab, pane, from, n, null);
+}
+
+/// A line's rows its caller has walked already (show's, the cursor's
+/// line): a walk reads them, not the line again.
+const Known = struct { line: usize, rows: u32 };
+
+const Walked = struct { to: Top, moved: i64 };
+
+fn walkKnown(tab: u16, pane: *Pane, from: Top, n: i64, known: ?Known) Walked {
+ const last = nlines(pane.gpa, &pane.file.?) -| 1;
+ if (!oneRow(tab, pane, wrapWidth(pane, pane.view.wrap))) return walkedRows(tab, pane, from, n, last, known);
+ const to = if (n < 0) from.line -| @abs(n) else if (from.line >= last) from.line else @min(from.line +| @abs(n), last);
+ const w: Walked = .{ .to = .{ .line = to }, .moved = @as(i64, @intCast(to)) - @as(i64, @intCast(from.line)) };
+ if (builtin.mode == .debug) std.debug.assert(std.meta.eql(w, walkedRows(tab, pane, from, n, last, known)));
+ return w;
+}
+
+fn walkedRows(tab: u16, pane: *Pane, from: Top, n: i64, last: usize, known: ?Known) Walked {
+ var map: ?bool = null;
+ const width = wrapWidth(pane, pane.view.wrap);
+ var t = from;
+ var rows = rowsOf(tab, pane, width, &map, known, t.line);
+ t.row = @min(t.row, rows - 1);
+ var left = n;
+ while (left > 0) {
+ const room = rows - 1 - t.row;
+ if (left <= room) {
+ t.row += @intCast(left);
+ left = 0;
+ } else if (t.line >= last) {
+ left -= room;
+ t.row = rows - 1;
+ break;
+ } else {
+ left -= room + 1;
+ t.line += 1;
+ t.row = 0;
+ rows = rowsOf(tab, pane, width, &map, known, t.line);
+ }
+ }
+ while (left < 0) {
+ if (-left <= t.row) {
+ t.row -= @intCast(-left);
+ left = 0;
+ } else if (t.line == 0) {
+ left += t.row;
+ t.row = 0;
+ break;
+ } else {
+ left += t.row + 1;
+ t.line -= 1;
+ rows = rowsOf(tab, pane, width, &map, known, t.line);
+ t.row = rows - 1;
+ }
+ }
+ return .{ .to = t, .moved = n - left };
+}
+
+/// The rows from `from` down to line `line`'s first row (up to it,
+/// negative), or null when it is more than `bound` rows away.
+pub fn rowsTo(tab: u16, pane: *const Pane, from: Top, line: usize, bound: u32) ?i64 {
+ if (!oneRow(tab, pane, wrapWidth(pane, pane.view.wrap))) return rowsWalked(tab, pane, from, line, bound);
+ const d = @as(i64, @intCast(line)) - @as(i64, @intCast(from.line)) - from.row;
+ const to: ?i64 = if ((line > from.line and d > bound) or (line < from.line and -d > bound)) null else d;
+ if (builtin.mode == .debug) std.debug.assert(std.meta.eql(to, rowsWalked(tab, pane, from, line, bound)));
+ return to;
+}
+
+fn rowsWalked(tab: u16, pane: *const Pane, from: Top, line: usize, bound: u32) ?i64 {
+ var map: ?bool = null;
+ const width = wrapWidth(pane, pane.view.wrap);
+ var d: i64 = -@as(i64, from.row);
+ var l = from.line;
+ while (l < line) : (l += 1) {
+ d += rowsOf(tab, pane, width, &map, null, l);
+ if (d > bound) return null;
+ }
+ while (l > line) {
+ l -= 1;
+ d -= rowsOf(tab, pane, width, &map, null, l);
+ if (-d > bound) return null;
+ }
+ return d;
+}
+
+/// Whether `pane`'s map (the geometry) is of the view as it is now: only
+/// then may a walk read a line's rows off it (derived state, made by
+/// whoever asked first).
+fn mapFresh(tab: u16, pane: *const Pane) bool {
+ return pane.wrap_n > 0 and pane.geometry_key == geometryKey(tab, pane, &pane.file.?);
+}
+
+/// The rows line `line` takes: counted off the map when the map is fresh
+/// and holds all of them in the body (no line walked: a page, a cursor
+/// past the body's edge), else walked (a walk's: no line is one row). Its
+/// walk's `map`: whether the map is fresh, asked the first time a line in
+/// it is.
+fn rowsOf(tab: u16, pane: *const Pane, width: usize, map: *?bool, known: ?Known, line: usize) u32 {
+ if (known) |k| if (k.line == line) return k.rows;
+ if (pane.wrap_n > pane.context_rows and line >= pane.wrap_line[pane.context_rows] and line <= pane.wrap_line[pane.wrap_n - 1] and
+ (map.* orelse fresh: {
+ map.* = mapFresh(tab, pane);
+ break :fresh map.*.?;
+ }))
+ {
+ const f = &pane.file.?;
+ var rows: u32 = 0;
+ var i: usize = pane.context_rows;
+ while (i < pane.wrap_n) : (i += 1) {
+ if (pane.wrap_line[i] == line) {
+ // Rows of it above the top are not in the map: its top row
+ // starts past its first byte.
+ if (rows == 0 and i == pane.context_rows and line == f.scroll and pane.wrap_col[i] > 0) break;
+ rows += 1;
+ } else if (rows > 0) return rows;
+ }
+ }
+ return rowWalked(tab, pane, width, line, std.math.maxInt(usize), .{}, &.{}).rows;
+}
+
+/// `pane`'s view moved `delta` rows (a wheel's notch is one): the rows it
+/// moved.
+pub fn scrollRows(tab: u16, pane: *Pane, delta: i64) i64 {
+ geometry(tab, pane);
+ const t = topNow(tab, pane);
+ // Down to a row the body shows: the map has it, its line and its row in
+ // that line, no line walked (a notch, a page).
+ const i = @as(i64, pane.context_rows) + delta;
+ if (delta > 0 and pane.wrap_n > 0 and i < shownNow(pane) + @as(i64, pane.context_rows)) {
+ const k: usize = @intCast(i);
+ const line: usize = @intCast(pane.wrap_line[k]);
+ if (line < nlines(pane.gpa, &pane.file.?)) {
+ var row: u32 = if (line == t.line) t.row else 0;
+ for (pane.wrap_line[pane.context_rows..k]) |l| row += @intFromBool(l == pane.wrap_line[k]);
+ setTop(pane, .{ .line = line, .row = row });
+ // Its first byte is the map's: the geometry starts there.
+ if (pane.body_wrapped) pane.top_skip = .{ .key = geometryKey(tab, pane, &pane.file.?), .row = row, .at = @intCast(pane.wrap_col[k]) };
+ return delta;
+ }
+ }
+ const w = walkRows(tab, pane, t, delta);
+ setTop(pane, w.to);
+ return w.moved;
+}
+
+/// The rows of `pane`'s body under its context rows, of its geometry as
+/// the view is now (made again first if stale: a key's step reads it
+/// before any draw, and only the state it is made of may decide it).
+pub fn shownRows(tab: u16, pane: *Pane) u16 {
+ geometry(tab, pane);
+ return shownNow(pane);
+}
+
+fn shownNow(pane: *const Pane) u16 {
+ const visible = if (pane.body_visible_rows > 0) @min(pane.wrap_n, pane.body_visible_rows) else pane.wrap_n;
+ return @max(1, if (pane.wrap_n == 0) pane.rows else visible -| pane.context_rows);
+}
+
+/// The view moved when line `line_at`'s row that shows its byte `col` is
+/// out of the body's margins (`margin_rows` rows, helix's scrolloff, at
+/// most half of it): by the rows that show the line's rows whole inside
+/// them, or that row where the line is taller than they leave. A cursor's
+/// (Pane.ensureCursorVisible's, for a file) or a result's.
+pub fn show(tab: u16, pane: *Pane, line_at: i32, col: i32, margin_rows: i64) void {
+ const f = &pane.file.?;
+ geometry(tab, pane);
+ const t = topNow(tab, pane);
+ // The line held at the top (a sticky context row): as it is.
+ if (pane.context_rows < pane.wrap_n and pane.wrap_line[pane.context_rows] == t.line) {
+ for (pane.wrap_line[0..pane.context_rows]) |row| if (row == line_at) return;
+ }
+ const body: i64 = shownNow(pane);
+ const margin: i64 = @min(margin_rows, @divTrunc(body - 1, 2));
+ // The row in the body (the map's, made just now), or none: the line is
+ // above the top, or below the map. Inside the band the view stays, and
+ // no line is walked (a key's step, nearly always).
+ const mapped: i64 = pane.wrapRow(tab, line_at, col).row - @as(i64, pane.context_rows);
+ const row: ?i64 = if (mapped >= 0 and mapped < @max(pane.wrap_n, pane.rows) -| pane.context_rows) mapped else null;
+ if (row) |r| if (r >= margin and r <= body - 1 - margin) return;
+ const line: usize = @intCast(@max(0, line_at));
+ // The line walked once and no further than the view needs (`Bound`: a
+ // long line's rows past the band are not), the first bytes of its last
+ // rows kept: where the view lands in it, its geometry starts there.
+ const width = wrapWidth(pane, pane.view.wrap);
+ var ring: [limits.wrap_rows]usize = undefined;
+ ring[0] = 0;
+ const starts = ring[0..@intCast(@min(body, ring.len))];
+ const at = if (oneRow(tab, pane, width)) RowIn{ .row = 0, .rows = 1 } else rowWalked(tab, pane, width, line, @intCast(@max(0, col)), .{ .after = @intCast(margin), .least = @intCast(body - 2 * margin + 1) }, starts);
+ const known: Known = .{ .line = line, .rows = at.rows };
+ defer if (f.scroll == line and f.scroll_row < at.rows and at.rows - 1 - f.scroll_row < starts.len) {
+ pane.top_skip = .{ .key = geometryKey(tab, pane, f), .row = f.scroll_row, .at = starts[f.scroll_row % starts.len] };
+ };
+ if (pane.follow_edges != 0 and (row == null or row.? < 0 or row.? >= body)) pane.follow_crossed = true;
+ const whole = at.rows <= body - 2 * margin;
+ if (if (row) |r| r < margin else line <= t.line) {
+ if (pane.follow_edges & 1 != 0) return;
+ setTop(pane, walkKnown(tab, pane, .{ .line = line, .row = if (whole) 0 else at.row }, -margin, known).to);
+ } else if (if (row) |r| r > body - 1 - margin else true) {
+ if (pane.follow_edges & 2 != 0) return;
+ // The margin only reveals text: a pane its whole text fits in
+ // never scrolls for it; a longer one keeps helix's clamp at the
+ // text's last line.
+ var past = walkKnown(tab, pane, .{ .line = line, .row = if (whole) at.rows - 1 else at.row }, margin, known).to;
+ if (t.line == 0 and t.row == 0 and pane.textFits()) {
+ const stop = @max(line, nlines(pane.gpa, f) -| 1 -| @intFromBool(std.mem.endsWith(u8, f.content, "\n")));
+ if (past.line > stop) past = .{ .line = stop, .row = lineRows(tab, pane, stop) - 1 };
+ }
+ setTop(pane, walkKnown(tab, pane, past, -(body - 1), known).to);
+ }
+}
+
+/// The line whose first row (no wrapped line's later row) is nearest body
+/// row `from` inside the body's band (`margin` rows in from each edge, at
+/// most half of it, under its context rows): the first at or below it
+/// going `.down`, else the last above it; `.up` the other way round. Where
+/// a view key leaves a cursor (Text.scrollViewMove, normal.halfPageMove);
+/// null when the band has none (inside a line taller than the body): the
+/// cursor stays.
+pub fn textRowLine(tab: u16, pane: *Pane, from: i64, margin: i64, way: enum { down, up }) ?i32 {
+ geometry(tab, pane);
+ const lines: i32 = @intCast(nlines(pane.gpa, &pane.file.?));
+ const held: i64 = pane.context_rows;
+ const shown: i64 = shownRows(tab, pane);
+ const m = @min(margin, @divTrunc(shown - 1, 2));
+ const lo = held + m;
+ const hi = held + shown - 1 - m;
+ for ([2]i64{ if (way == .down) 1 else -1, if (way == .down) -1 else 1 }) |step| {
+ var vr = std.math.clamp(held + from, lo, hi);
+ while (vr >= lo and vr <= hi) : (vr += step) {
+ const w = pane.wrapAt(tab, @intCast(vr));
+ if ((w.at == 0 or !pane.body_wrapped) and w.line < lines) return w.line;
+ }
+ }
+ return null;
+}
+
+pub const Bytes = struct { start: usize, end: usize };
+
+/// The bytes of the text `pane`'s body shows: its first row's first to its
+/// last row's last (whole lines unwrapped, as each row is one).
+pub fn shownBytes(tab: u16, pane: *Pane) Bytes {
+ const f = &pane.file.?;
+ const shown = shownRows(tab, pane);
+ if (!pane.body_wrapped) return .{ .start = lineStart(pane.gpa, f, f.scroll), .end = lineStart(pane.gpa, f, f.scroll + shown) };
+ const first = pane.context_rows;
+ const last = first + shown - 1;
+ const start = lineStart(pane.gpa, f, @intCast(pane.wrap_line[first])) + @as(usize, @intCast(pane.wrap_col[first]));
+ const line: usize = @intCast(pane.wrap_line[last]);
+ if (line >= nlines(pane.gpa, f)) return .{ .start = start, .end = f.content.len };
+ const text = sourceLine(pane, @intCast(line));
+ return .{ .start = start, .end = lineStart(pane.gpa, f, line) + fitEnd(tab, text, @intCast(pane.wrap_col[last]), wrapWidth(pane, pane.view.wrap) -| pane.wrap_pad[last]) };
+}
+
+/// A call stack's row after its line's first starts with its tree's guide
+/// (locations.treeContinuation), in `buffer`; any other row with none.
+fn guideOf(f: *const State, text: []const u8, at: usize, width: usize, buffer: *[1024]u8) []const u8 {
+ if (at == 0 or width <= 1 or f.output == null or !std.meta.eql(f.output.?.from, Output.Origin{ .query = .callstack })) return "";
+ return locations.treeContinuation(text, buffer, width - 1);
}
/// `pane` out of its Follow chain (Unfollow, or a chain down to it): a
@@ -2131,12 +2631,12 @@ fn prepareContextRows(pane: *Pane, file: *State) void {
if (!file.tree_context or !supportsContext(pane) or pane.rows > pane.wrap_line.len) return;
const capacity = @min(pane.rows -| 1, pane.context_row_limit orelse std.math.maxInt(u16)); // retain an ordinary body row
// The declarations are the file's lines; the rows, the buffer's.
- const top = fileRow(file, file.scroll);
+ const top_line = fileRow(file, file.scroll);
for (file.context.declarations) |declaration| {
- if (declaration.start_line >= top) break;
- if (declaration.end_line < top) continue;
+ if (declaration.start_line >= top_line) break;
+ if (declaration.end_line < top_line) continue;
var line = declaration.start_line;
- while (line <= declaration.header_end_line and line < top) : (line += 1) {
+ while (line <= declaration.header_end_line and line < top_line) : (line += 1) {
if (pane.context_rows >= capacity) return;
const row = bufferRow(file, line);
if (pane.context_rows > 0 and row <= pane.wrap_line[pane.context_rows - 1]) continue;
@@ -2183,9 +2683,18 @@ pub fn bodyText(tab: u16, arena: std.mem.Allocator, pane: *Pane, f: *State) ![]c
/// which each step sets.
pub fn geometry(tab: u16, pane: *Pane) void {
const f = if (pane.file) |*file| file else return;
- const key = geometryKey(pane, f);
+ const key = geometryKey(tab, pane, f);
if (pane.geometry_key == key) return;
pane.geometry_key = key;
+ // The key of what the map was made from: the walk brings the text's
+ // index and tables up to it (`line_starts`, `tables.revision`, in the
+ // key), and with the key from before, a step's second ask made it all
+ // again. The top's row it found or took is that key's too.
+ defer {
+ const made = geometryKey(tab, pane, f);
+ pane.top_skip.key = made;
+ pane.geometry_key = made;
+ }
pane.body_rows = 0;
pane.body_visible_rows = 0;
pane.context_row_limit = null;
@@ -2217,9 +2726,9 @@ fn mapRows(tab: u16, pane: *Pane, f: *State) usize {
}
/// Everything the geometry is made of, hashed: the text (its revision and
-/// length), where it is scrolled, the pane's size, its tables, its context
-/// declarations, the session's view.
-fn geometryKey(pane: *const Pane, f: *const State) u64 {
+/// length), where it is scrolled, the pane's size, the tab's width, its
+/// tables, its context declarations, the session's view.
+fn geometryKey(tab: u16, pane: *const Pane, f: *const State) u64 {
const t = &f.tables;
const facts = .{
f.revision, f.content.len, f.scroll, pane.hscroll,
@@ -2228,7 +2737,7 @@ fn geometryKey(pane: *const Pane, f: *const State) u64 {
if (f.output) |o| pardes.walk.digest(Output.Origin, &o.from) else 0, std.hash.Wyhash.hash(0, f.path), f.tree_context, f.context.revision orelse 0,
f.context.declarations.len, f.line_starts.len, t.revision orelse 0, t.list.items.len,
pane.view.wrap, pane.view.layered, pane.view.body_h, pane.view.tagline_h,
- pane.view.rect_h, laneCells(pane) + @as(u16, pane.layers.heat),
+ pane.view.rect_h, laneCells(pane) + @as(u16, pane.layers.heat), f.scroll_row, tab,
};
// One hash of them laid out as words: every reader of the map asks for
// this key, a hundred times a frame.
@@ -2254,8 +2763,11 @@ fn fillBody(comptime layered: bool, tab: u16, dst: ?[]u8, pane: *Pane, f: *State
// row below asks whether it is that one.
const end_slot: usize = if (total > 0 and endSlot(pane, total - 1)) total - 1 else std.math.maxInt(usize);
var body_line: usize = f.scroll;
- var body_at: usize = 0;
+ // The top line from the view's row in it (`top`): walked once a
+ // geometry (the map's pass), its text's pass a frame starting there.
+ var body_at: usize = topSkip(tab, pane).at;
var written: usize = 0;
+ var guide_buffer: [1024]u8 = undefined;
for (0..if (pane.body_rows > 0) pane.body_rows else pane.rows) |i| {
if (i > 0) {
if (dst) |out| out[written] = '\n';
@@ -2265,12 +2777,7 @@ fn fillBody(comptime layered: bool, tab: u16, dst: ?[]u8, pane: *Pane, f: *State
const row = if (context) @as(usize, @intCast(pane.wrap_line[i])) else body_line;
const at = if (context) 0 else body_at;
const text = if (row < total) sourceLine(pane, @intCast(row)) else "";
- var guide_buffer: [1024]u8 = undefined;
- const guide = if (at > 0 and width > 1 and f.output != null and
- std.meta.eql(f.output.?.from, Output.Origin{ .query = .callstack }))
- locations.treeContinuation(text, &guide_buffer, width - 1)
- else
- "";
+ const guide = guideOf(f, text, at, width, &guide_buffer);
const pad = displayWidth(tab, guide);
// Headers use one screen row per source row, preserving signatures
// without allowing a long ancestor to consume the whole viewport.
@@ -2709,6 +3216,11 @@ test "the ASCII run in fitEnd survives an exhaustive byte sweep" {
}
test "the ASCII run in fitEnd cuts where the grapheme walk would" {
+ const run = struct {
+ fn of(comptime c: u8, comptime n: usize) [n]u8 {
+ return @splat(c);
+ }
+ }.of;
const reference = struct {
fn fitEnd(text: []const u8, start: usize, width: usize) usize {
var end = start;
@@ -2739,6 +3251,12 @@ test "the ASCII run in fitEnd cuts where the grapheme walk would" {
// an ASCII byte followed by a continuation byte is NOT its own cluster
"e\u{0301}x",
"\u{1f1e6}\u{1f1e7}ok",
+ // runs longer than a vector (the vector loop), each ending at a
+ // non-ASCII byte, a combining mark, a tab, or the text's end
+ &(run('x', 40) ++ "\u{00e9}".* ++ run('y', 40)),
+ &(run('a', 32) ++ "\u{0301}".* ++ run('b', 17)),
+ &(run('c', 47) ++ "\t".* ++ run('d', 20)),
+ &run('z', 100),
};
for (cases) |text| {
var width: usize = 0;
@@ -2769,7 +3287,7 @@ test "a line index shifted in place equals a rebuilt one, and the edit turned ro
const del = r.uintAtMost(usize, @min(12, text.items.len - at));
var ins: [12]u8 = undefined;
const ins_len = r.uintAtMost(usize, 12);
- for (ins[0..ins_len]) |*c| c.* = "ab\n"[r.uintLessThan(usize, 3)];
+ for (ins[0..ins_len]) |*c| c.* = "ab\n\t"[r.uintLessThan(usize, 4)];
const before = try gpa.dupe(usize, f.line_starts);
defer gpa.free(before);
const cut = try gpa.dupe(u8, text.items[at..][0..del]);
@@ -2781,12 +3299,18 @@ test "a line index shifted in place equals a rebuilt one, and the edit turned ro
const want = try lineIndex(gpa, &fresh);
defer gpa.free(want);
try std.testing.expectEqualSlices(usize, want, f.line_starts);
+ // The kept widest is never less than the text's, made anew exact.
+ var widest: usize = 0;
+ var lines = std.mem.splitScalar(u8, text.items, '\n');
+ while (lines.next()) |line| widest = @max(widest, line.len);
+ try std.testing.expectEqual(Widest{ .bytes = widest, .tabbed = std.mem.indexOfScalar(u8, text.items, '\t') != null }, fresh.widest);
+ try std.testing.expect(f.widest.bytes >= widest and (f.widest.tabbed or !fresh.widest.tabbed));
// Every tenth turned round in a copy, as a rollback takes it back.
if (round % 10 == 0) {
const room = try gpa.alloc(usize, indexRoom(&f).len);
defer gpa.free(room);
@memcpy(room[0..f.line_starts.len], f.line_starts);
- shiftStarts(room, f.line_starts.len, before.len, at, ins_len, cut);
+ _ = shiftStarts(room, f.line_starts.len, before.len, at, ins_len, cut);
try std.testing.expectEqualSlices(usize, before, room[0..before.len]);
}
}
@@ -3164,3 +3688,31 @@ test "Syntax off in a patch's pane takes the language's ink and leaves the patch
if (pass == 1) try std.testing.expect(differ);
}
}
+
+test "a view scrolled by rows into a line of tabs, the tab width changed after a frame: its body drawn from the row the new width makes, as a core loaded from it draws it" {
+ const gpa = std.testing.allocator;
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 });
+ defer p.deinit();
+ var text: std.ArrayList(u8) = .empty;
+ defer text.deinit(gpa);
+ try text.appendSlice(gpa, "head\n");
+ for (0..40) |i| try text.print(gpa, "\tw{d}", .{i});
+ try text.appendSlice(gpa, "\ntail\n");
+ const pane = try p.setTestFile(text.items);
+ try std.testing.expect(p.executeBuiltinLine(0, "Tab 8"));
+ // The top on line 1's fourth row (at 8 cells a tab), drawn.
+ const f = &pane.file.?;
+ f.scroll = 1;
+ f.scroll_row = 3;
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ _ = try p.render(arena.allocator());
+ try std.testing.expect(p.executeBuiltinLine(0, "Tab 2"));
+ const drawn = try bodyText(p.settings.tab, arena.allocator(), pane, f);
+ const bytes = try pardes.dump.dumpBytes(p);
+ defer gpa.free(bytes);
+ const loaded = try pardes.dump.load(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }, bytes, null);
+ defer loaded.deinit();
+ const lp = loaded.panes[0].?;
+ try std.testing.expectEqualStrings(try bodyText(loaded.settings.tab, arena.allocator(), lp, &lp.file.?), drawn);
+}
diff --git a/core/Jump.zig b/core/Jump.zig
index ccdb8fdc..a83b6ab4 100644
--- a/core/Jump.zig
+++ b/core/Jump.zig
@@ -27,12 +27,19 @@ cur: usize = 0,
/// (a query answered: Ctrl-o goes back to where it was asked).
force: bool = false,
-pub const replica = .{ .len = .{.{ "list", "n" }} };
+/// `cur` held to the places there are (walk.zig `.place`).
+pub const replica = .{ .len = .{.{ "list", "n" }}, .place = .{.{ "cur", "lastCur" }} };
+
+pub fn lastCur(j: *const Jump) usize {
+ return j.n -| 1;
+}
const Mouse = pardes.Mouse;
const recent_path_cap = limits.host_path_cap;
pub const Loc = struct {
+ /// Its pane's slot (walk.zig `.index`), that pane while `serial` says.
+ pub const replica = .{ .index = .{.{ "pane", Pardes, "panes" }} };
pane: u16,
/// 0 once its pane has closed: a file's entry stays, reopened by a
/// jump to it from `path_hash`'s recent entry.
diff --git a/core/Messages.zig b/core/Messages.zig
index 18b10ff8..040b8d2c 100644
--- a/core/Messages.zig
+++ b/core/Messages.zig
@@ -19,6 +19,10 @@ const Pardes = pardes.Pardes;
const Messages = @This();
+/// Where its ring's next line goes and how many it holds, held to the ring
+/// where a dump is read back (walk.zig `.place`).
+pub const replica = .{ .place = .{ .{ "head", "lastSlot" }, .{ "len", "size" } } };
+
/// The message-row log: a fixed ring, never allocated, never grown. See
/// `logMessage` and the `Messages` builtin.
log: [limits.message_log]LoggedMessage = @splat(.{}),
@@ -26,6 +30,14 @@ log: [limits.message_log]LoggedMessage = @splat(.{}),
head: usize = 0,
len: usize = 0,
+pub fn lastSlot(m: *const Messages) usize {
+ return m.log.len - 1;
+}
+
+pub fn size(m: *const Messages) usize {
+ return m.log.len;
+}
+
pub const LoggedMessage = struct {
pub const cap = 256;
pub const replica = .{ .len = .{.{ "text", "len" }} };
diff --git a/core/Output.zig b/core/Output.zig
index a1e5865e..380fadb1 100644
--- a/core/Output.zig
+++ b/core/Output.zig
@@ -1041,6 +1041,7 @@ pub fn openErrors(p: *Pardes, id: usize, content: []u8) !void {
pub fn resetBody(p: *Pardes, pane: *Pane) void {
const v = p.view();
pane.file.?.scroll = 0;
+ pane.file.?.scroll_row = 0;
pane.body.cur_row = 0;
pane.body.cur_col = 0;
pane.body.cur_pinned = true;
diff --git a/core/Places.zig b/core/Places.zig
index 1c24e992..6c3ac9ab 100644
--- a/core/Places.zig
+++ b/core/Places.zig
@@ -561,9 +561,12 @@ pub fn goTo(set: *Places, tab: u16, pane: *Pane, i: usize, add: bool) void {
}
set.current = i;
set.gen +%= 1;
- const off = pane.scroll();
- if (t.cur_row < off or t.cur_row >= off + @as(i32, pane.rows))
- pane.scrollBy(t.cur_row - off - @divTrunc(@as(i32, pane.rows), 2));
+ // Off the view, its row half the body's rows down (as zz).
+ const line: usize = @intCast(@max(0, t.cur_row));
+ const row = panes.File.rowOf(tab, pane, line, @intCast(@max(0, t.cur_col)));
+ const body: i64 = panes.File.shownRows(tab, pane);
+ const on = if (panes.File.rowsTo(tab, pane, panes.File.top(tab, pane), line, @intCast(body))) |d| d + row else -1;
+ if (on < 0 or on >= body) panes.File.setTop(pane, panes.File.walkRows(tab, pane, .{ .line = line, .row = row }, -@divTrunc(body, 2)).to);
t.show(tab);
}
@@ -634,7 +637,7 @@ pub fn restore(set: *Places, tab: u16, pane: *Pane) void {
r.head = @min(r.head, f.content.len);
}
pane.body.setRanges(tab, f.content, set.snap, &.{}, set.snap_pri, set.snap_expl);
- f.scroll = set.snap_scroll;
+ panes.File.setTop(pane, .{ .line = set.snap_scroll });
f.syntax_dirty = true;
pane.hscroll = set.snap_hscroll;
}
diff --git a/core/Query.zig b/core/Query.zig
index 3023cc60..feebb6cd 100644
--- a/core/Query.zig
+++ b/core/Query.zig
@@ -344,7 +344,7 @@ pub fn toLineOne(p: *Pardes, id: usize) void {
t.cur_pinned = true;
rp.query.?.seen_row = 0;
edit.enterInsert(p.editor(), t, .line_end, 1) catch |err| return p.reportError(.at(id), "query", err);
- showCurrent(rp);
+ showCurrent(p.settings.tab, rp);
}
/// The rows' state for a new question: nothing found yet.
@@ -456,7 +456,7 @@ fn makeAllRows(p: *Pardes, id: usize) !void {
// The current one: the first hit row, until a step moves it.
if (q.current == null or q.current.? >= q.items.items.len) q.current = firstHit(q);
countCurrent(q);
- showCurrent(rp);
+ showCurrent(p.settings.tab, rp);
}
/// The names the query matches, best first, `Names.max_rows` of them: each
@@ -533,7 +533,7 @@ fn makeNameRows(p: *Pardes, id: usize) !void {
// The best is current until a step or a click moves it.
q.current = if (shown > 0) 0 else null;
countCurrent(q);
- showCurrent(rp);
+ showCurrent(p.settings.tab, rp);
if (q.current == null) blankPreview(p, id) else showTarget(p, id);
}
@@ -1157,7 +1157,7 @@ fn showPlacesCurrent(p: *Pardes, id: usize) void {
};
// Stepped out of the window the live rows are: made again around it.
if (q.current == null and set.current != null and !q.frozen and set.from == rp.serial) q.made_gen = std.math.maxInt(u64);
- showCurrent(rp);
+ showCurrent(p.settings.tab, rp);
}
fn firstHit(q: *const Query) ?usize {
@@ -1233,7 +1233,7 @@ fn makeGrepRows(p: *Pardes, id: usize, full: bool) !void {
q.more = p.stream.busyFor(rp.serial);
q.current = current orelse firstHit(q);
countGrepCurrent(q);
- showCurrent(rp);
+ showCurrent(p.settings.tab, rp);
if (q.current == null) blankPreview(p, id) else if (!shown) showTarget(p, id);
}
@@ -1326,7 +1326,7 @@ pub fn fillList(p: *Pardes, owner_id: usize, source: Source, rows: []const u8) v
if (t.mode == .insert) edit.exitInsert(p.editor(), t);
t.vsel.active = false;
t.nsel = 0;
- caretTo(rp, q.current orelse 0);
+ caretTo(p.settings.tab, rp, q.current orelse 0);
showTarget(p, qid);
}
@@ -1448,7 +1448,7 @@ fn makeListRows(p: *Pardes, id: usize, pat: []const u8) !void {
}
}
countCurrent(q);
- showCurrent(rp);
+ showCurrent(p.settings.tab, rp);
}
// ---- the current row ----
@@ -1457,7 +1457,7 @@ fn makeListRows(p: *Pardes, id: usize, pat: []const u8) !void {
/// elsewhere, line 1 kept when it can be. Its mark is `paint`'s, drawn
/// from `current`: no selection, so no click, sweep or chord clears it and
/// no B2 or B3 borrows it.
-fn showCurrent(rp: *Pane) void {
+fn showCurrent(tab: u16, rp: *Pane) void {
const q = rp.query orelse return;
if (rp.body.cur_row != 0 and rp.focus == .body) return;
const c = q.current orelse return;
@@ -1465,24 +1465,19 @@ fn showCurrent(rp: *Pane) void {
// Typed into, line 1 stays in view whatever the current row: what you
// type is never scrolled away (the live rows start just before the
// current one, so it sits under line 1). Frozen, the row is scrolled to.
- if (!q.frozen) {
- if (rp.scroll() != 0) rp.scrollBy(-rp.scroll());
- return;
- }
- const off = rp.scroll();
- const shown = off + @as(i32, rp.rows) - 1;
- if (r > shown) rp.scrollBy(r - shown) else if (r < off) rp.scrollBy(r - off);
+ if (rp.file == null) return;
+ if (!q.frozen) return panes.File.setTop(rp, .{ .line = 0 });
+ panes.File.show(tab, rp, r, 0, 0);
}
/// The caret on item `i`'s row, the row in view.
-fn caretTo(rp: *Pane, i: usize) void {
+fn caretTo(tab: u16, rp: *Pane, i: usize) void {
const r: i32 = @intCast(i + 1);
rp.body.cur_row = r;
rp.body.cur_col = 0;
rp.body.cur_pinned = true;
rp.query.?.seen_row = r;
- const off = rp.scroll();
- if (r >= off + @as(i32, rp.rows)) rp.scrollBy(r - off - @as(i32, rp.rows) + 1) else if (r < off) rp.scrollBy(r - off);
+ if (rp.file != null) panes.File.show(tab, rp, r, 0, 0);
}
/// The first of pane `tp`'s places on line `line` (1-based), if any.
@@ -1513,7 +1508,7 @@ fn setCurrent(p: *Pardes, id: usize, i: usize, show: bool) void {
if (tp.places.from == rp.serial and tp.serial == q.owner) q.k = hi + 1 else countCurrent(q);
} else countCurrent(q);
} else countCurrent(q) else countCurrent(q);
- showCurrent(rp);
+ showCurrent(p.settings.tab, rp);
if (show) showTarget(p, id);
}
@@ -1572,6 +1567,7 @@ fn blankPreview(p: *Pardes, qid: usize) void {
File.setContent(p, f, empty);
f.saved_revision = f.revision;
f.scroll = 0;
+ f.scroll_row = 0;
}
/// Where the current row points, shown with the keyboard left where it is:
@@ -1689,6 +1685,7 @@ fn displayPreview(p: *Pardes, qid: usize, path: []const u8, at: look.Spot) void
File.setContent(p, f, bytes);
f.saved_revision = f.revision;
f.scroll = 0;
+ f.scroll_row = 0;
f.syntax_dirty = true;
pane.hscroll = 0;
// another file: its own places, found below
@@ -1698,6 +1695,7 @@ fn displayPreview(p: *Pardes, qid: usize, path: []const u8, at: look.Spot) void
look.clearNavigationSelection(p, pane);
if (at.line == 0 or at.line > File.nlines(p.gpa, f)) {
f.scroll = 0;
+ f.scroll_row = 0;
f.syntax_dirty = true;
pane.body.cur_row = 0;
pane.body.cur_col = 0;
@@ -1917,7 +1915,7 @@ pub fn cancel(p: *Pardes, id: usize) void {
q.frozen = true;
rp.body.cur_row = 0;
rp.body.cur_col = 0;
- showCurrent(rp);
+ showCurrent(p.settings.tab, rp);
// Its places again, as Enter left them.
if (q.source == .text) if (owner_id) |oid| if (parse(q.asked)) |a| {
const owner = p.panes[oid].?;
@@ -1983,7 +1981,7 @@ pub fn key(p: *Pardes, id: usize, k: Key) bool {
// The caret on the rows goes to the current row, as j and k
// would have taken it there.
if (t.cur_row != 0) if (q.current) |c| {
- caretTo(rp, c);
+ caretTo(p.settings.tab, rp, c);
};
return true;
}
diff --git a/core/Text.zig b/core/Text.zig
index 54d69a74..37feb081 100644
--- a/core/Text.zig
+++ b/core/Text.zig
@@ -339,10 +339,19 @@ pub fn scrollViewMove(t: *Text, tab: u16, text: []const u8, range: modal.Selecti
if (t.what != .body) return;
const w = t.pane() orelse return;
const margin: i32 = @min(config.scroll_off, @divTrunc(@as(i32, w.rows) - 1, 2));
- w.scrollBy(delta);
+ w.scrollBy(tab, delta);
const top = w.scroll();
const last_row: i32 = @intCast(File.textLineCount(t, text) - 1);
const cur = modal.selectionCursor(text, range);
+ // A file's rows are not its lines: a line's first row at the margin,
+ // none (inside a line taller than the body) leaving the cursor be.
+ if (w.file != null) {
+ const snap = File.textRowLine(tab, w, if (delta > 0) margin else File.shownRows(tab, w) - 1 - margin, margin, if (delta > 0) .down else .up) orelse return;
+ const head = File.textLineStart(t, text, @intCast(snap));
+ if (if (delta > 0) head <= cur else head >= cur) return;
+ const anchor = if (t.select) range.anchor else head;
+ return setRange(t, tab, text, 0, .{ .anchor = anchor, .head = head }, false);
+ }
if (delta > 0) {
const snap: i32 = @max(0, @min(top + margin, last_row));
const head = File.textLineStart(t, text, @intCast(snap));
@@ -417,6 +426,8 @@ pub const Place = struct {
/// (`entries[first..][0..n]`), and the places at its edges: an undo goes
/// back to `before`, a redo to `after`, where it was undone from.
pub const Step = struct {
+ /// Its entries are the journal's (walk.zig `.index`, a span).
+ pub const replica = .{ .index = .{.{ "first", Journal, "entries", "n" }} };
first: usize,
n: usize = 0,
before: Place,
@@ -429,12 +440,26 @@ pub const Step = struct {
/// limits.undo_max steps and limits.undo_bytes of what they hold, the
/// oldest step dropped first and the newest kept whatever its size.
pub const Journal = struct {
+ /// `done` held to its steps, `bytes` to what its entries hold (walk.zig
+ /// `.place`).
+ pub const replica = .{ .place = .{ .{ "done", "stepCount" }, .{ "bytes", "entryBytes" } } };
steps: std.ArrayList(Step) = .empty,
done: usize = 0,
entries: std.ArrayList(Entry) = .empty,
/// What the entries hold: the bytes they took out, and their own size.
bytes: usize = 0,
+ pub fn stepCount(j: *const Journal) usize {
+ return j.steps.items.len;
+ }
+
+ /// What `bytes` says, its one place: what the entries hold.
+ pub fn entryBytes(j: *const Journal) [2]usize {
+ var n: usize = 0;
+ for (j.entries.items) |e| n +|= held(e);
+ return .{ n, n };
+ }
+
pub fn deinit(j: *Journal, gpa: std.mem.Allocator) void {
for (j.entries.items) |e| free(gpa, e);
j.entries.deinit(gpa);
diff --git a/core/draw.zig b/core/draw.zig
index 5263f7bf..ff76aa75 100644
--- a/core/draw.zig
+++ b/core/draw.zig
@@ -111,7 +111,8 @@ pub fn place(p: *Pardes, s: *Surface) void {
// path, a generated text's revision with it (rows rewritten as its
// view moved are another text's); none for a terminal or a picture.
const doc: u64 = if (pane.file) |f| std.hash.Wyhash.hash(if (f.output != null) f.revision else 0, f.path) else 0;
- s.addRegion(.{ .kind = .body, .owner = owner, .serial = pane.serial, .active = active, .line = line, .doc = doc, .rect = .{ .x = r.x + config.GUTTER, .y = body_y, .w = r.w - config.GUTTER, .h = body_h } });
+ const row: u32 = if (pane.file != null) panes.File.top(p.settings.tab, pane).row else 0;
+ s.addRegion(.{ .kind = .body, .owner = owner, .serial = pane.serial, .active = active, .line = line, .row = row, .doc = doc, .rect = .{ .x = r.x + config.GUTTER, .y = body_y, .w = r.w - config.GUTTER, .h = body_h } });
var rail: Region = .{ .kind = .rail, .owner = owner, .serial = pane.serial, .active = active, .rect = .{ .x = r.x, .y = body_y, .w = config.GUTTER, .h = body_h } };
// A kind's rail is its paint's (drawPane); every other pane's is
// here.
diff --git a/core/dump.zig b/core/dump.zig
index deb18dba..b4561ae2 100644
--- a/core/dump.zig
+++ b/core/dump.zig
@@ -555,21 +555,25 @@ fn ensureKind(p: *Pardes, pane: *pardes.panes.Pane) !void {
pane.terminal = try pardes.Term.open(&p.outside, pardes.panes.emulatorGpa(p.gpa), @max(1, pane.cols), @max(1, pane.rows));
}
-/// The panes a column lists that are not there (another build's dump left
-/// them out) taken out of it, and the keyboard on one that is.
-fn dropMissing(p: *Pardes) void {
- const v = p.view();
- for (0..p.view().ncol) |c| {
- var n: usize = 0;
- for (v.cols[c].panes[0..p.view().cols[c].n]) |id| if (id < MAX_PANES and p.panes[id] != null) {
- v.cols[c].panes[n] = id;
- n += 1;
- };
- v.cols[c].n = n;
- }
- if (v.active >= MAX_PANES or p.panes[v.active] == null) v.active = for (p.panes, 0..) |slot, i| {
- if (slot != null) break i;
- } else 0;
+/// The panes each view's columns list that are not there (another build's
+/// dump left them out) taken out of them, and its keyboard on one that is:
+/// at the load's end, and where the core's fields end (walk.zig
+/// `left_out`), before what names a pane is held to one there. Every view:
+/// the live one may not be one yet then. (Their lengths are held already.)
+pub fn dropMissing(p: *Pardes) void {
+ for (&p.views) |*slot| if (slot.*) |*v| {
+ for (v.cols[0..v.ncol]) |*col| {
+ var n: usize = 0;
+ for (col.panes[0..col.n]) |id| if (id < MAX_PANES and p.panes[id] != null) {
+ col.panes[n] = id;
+ n += 1;
+ };
+ col.n = n;
+ }
+ if (v.active >= MAX_PANES or p.panes[v.active] == null) v.active = for (p.panes, 0..) |s, i| {
+ if (s != null) break i;
+ } else 0;
+ };
}
/// The replacement core for a Restore of the dump at `from`, whose log says
@@ -1024,6 +1028,104 @@ test "a dump keeps the session's settings, and a restore applies them" {
try std.testing.expect(!restored.settings.wrap);
}
+test "a view's geometry is read back as the session holds it, never laid out again; a rect or a column off its screen is refused, the field named" {
+ const gpa = std.testing.allocator;
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
+ defer p.deinit();
+ // Not what the layout pass would make of its columns (a view opened
+ // and not laid out yet has no rects at all): as the session has it.
+ p.view().rects[0].h -= 1;
+ const held = p.view().rects[0];
+ inline for (.{ byteDump, dumpBytes }) |dumpOf| {
+ const bytes = try dumpOf(p);
+ defer gpa.free(bytes);
+ const q = try load(gpa, p.opts, bytes, null);
+ defer q.deinit();
+ try std.testing.expectEqual(held, q.view().rects[0]);
+ }
+ // The fuzz's restore road, seed 589: an image whose pane 0 said 534
+ // rows on a 24-row screen, drawn: surface.zig's `at` asserted.
+ const Off = struct { at: *u16, to: u16, why: []const u8 };
+ for ([_]Off{
+ .{ .at = &p.view().rects[0].h, .to = 534, .why = "View.rects[0] is not within" },
+ .{ .at = &p.view().col_w[0], .to = 900, .why = "View.col_w[0] is not within" },
+ // A column's edge is held with its width.
+ .{ .at = &p.view().col_x[0], .to = 900, .why = "View.col_w[0] is not within" },
+ }) |off| {
+ const was = off.at.*;
+ off.at.* = off.to;
+ defer off.at.* = was;
+ inline for (.{ byteDump, dumpBytes }) |dumpOf| {
+ const bytes = try dumpOf(p);
+ defer gpa.free(bytes);
+ var notes: std.ArrayList(u8) = .empty;
+ defer notes.deinit(gpa);
+ try std.testing.expectError(error.BadDump, load(gpa, p.opts, bytes, &notes));
+ std.testing.expect(std.mem.indexOf(u8, notes.items, off.why) != null) catch |err| {
+ std.debug.print("refused, but not by {s}: {s}\n", .{ off.why, notes.items });
+ return err;
+ };
+ }
+ }
+}
+
+test "a dump whose index names no view or pane there is refused, the field named; a top past its text is its last line; a key's replay is not dumped" {
+ // The fuzz's join road (core/fuzz.zig): `live` read past the views
+ // (views.zig `bit`), a file's top past its text (File.zig fillBody's
+ // `wrap_line`), and `multi_count` sizing a yank's register at 17 GB.
+ const gpa = std.testing.allocator;
+ const p = try Pardes.init(gpa, .{ .tty_only = true });
+ defer p.deinit();
+ const pane = try p.setTestFile("one\ntwo\n");
+ const id = p.view().active;
+ const Refused = struct {
+ fn by(q: *Pardes, why: []const u8) !void {
+ inline for (.{ byteDump, dumpBytes }) |dumpOf| {
+ const bytes = try dumpOf(q);
+ defer q.gpa.free(bytes);
+ var notes: std.ArrayList(u8) = .empty;
+ defer notes.deinit(q.gpa);
+ try std.testing.expectError(error.BadDump, load(q.gpa, q.opts, bytes, &notes));
+ std.testing.expect(std.mem.indexOf(u8, notes.items, why) != null) catch |err| {
+ std.debug.print("refused, but not by {s}: {s}\n", .{ why, notes.items });
+ return err;
+ };
+ }
+ }
+ };
+ // No view open to write the shares of (the live one's are its panes').
+ p.live = 9;
+ p.views_open = 0;
+ try Refused.by(p, "live says 9");
+ p.live = 0;
+ p.views_open = 1;
+ p.view().active = 9;
+ try Refused.by(p, ".active says 9");
+ p.view().active = id;
+ const col = &p.view().cols[0].panes[0];
+ col.* = 9;
+ try Refused.by(p, "Column.panes says 9");
+ col.* = id;
+ pane.sized_by = 7;
+ try Refused.by(p, "Pane.sized_by says 7");
+ pane.sized_by = 0;
+ // Where a thing is, past its end: its last place, the session there.
+ pane.file.?.scroll = 1 << 40;
+ p.multi_count = 1 << 30;
+ inline for (.{ byteDump, dumpBytes }) |dumpOf| {
+ const bytes = try dumpOf(p);
+ defer gpa.free(bytes);
+ const q = try load(gpa, p.opts, bytes, null);
+ defer q.deinit();
+ try std.testing.expectEqual(@as(usize, 2), q.panes[id].?.file.?.scroll);
+ try std.testing.expectEqual(@as(usize, 1), q.multi_count);
+ _ = q.frame_arena.reset(.retain_capacity);
+ _ = try q.render(q.frame_arena.allocator());
+ }
+ pane.file.?.scroll = 0;
+ p.multi_count = 1;
+}
+
test "a session with every column it may hold dumps and restores them all" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 1200, .rows = 24 });
diff --git a/core/exec.zig b/core/exec.zig
index d1e1830f..2528805f 100644
--- a/core/exec.zig
+++ b/core/exec.zig
@@ -1057,11 +1057,8 @@ pub fn applySettingBuiltin(p: *Pardes, setting: config.Settings.Setting, arg: ?[
},
}
if (setting.action == .tab) {
- for (p.panes, 0..) |slot, id| {
- p.surface.body_layers[id].rows = 0;
- const pane = slot orelse continue;
- pane.geometry_key = 0;
- }
+ // The geometry's key holds the tab's width: made again where it is read.
+ for (&p.surface.body_layers) |*layer| layer.rows = 0;
look.cancelLookHover(p);
}
if (setting.action == .tagline_size and p.settings.font.tagline_percent != previous_tagline_percent)
diff --git a/core/fuzz.zig b/core/fuzz.zig
index 4f291d64..616636ab 100644
--- a/core/fuzz.zig
+++ b/core/fuzz.zig
@@ -713,9 +713,42 @@ fn damage(r: Random, b: []u8, n: usize) usize {
/// What is done with a dump once it loads: a join's is digested (the
/// session's digest decides before anything draws it: replica.fromDump),
-/// a Restore's or an Upgrade's image is drawn.
+/// a Restore's or an Upgrade's image is not; then each is used (`use`).
const Road = enum { join, restore };
+/// A core loaded used as its user would: drawn at the size it says, then
+/// smaller and larger (a resize each), then given keys and a wheel notch each
+/// way and drawn again. A load that draws and then dies at a key is the same
+/// fault as one that dies drawing.
+fn use(q: *Pardes) void {
+ const K = pardes.Key;
+ const steps = [_]pardes.Event{
+ .{ .resize = .{ .cols = 40, .rows = 12 } },
+ .{ .resize = .{ .cols = 200, .rows = 60 } },
+ .{ .key = .{ .cp = 'j' } },
+ .{ .key = .{ .cp = 'w' } },
+ .{ .key = .{ .cp = 'x' } },
+ .{ .key = .{ .cp = 'd' } },
+ .{ .key = .{ .cp = 'u' } },
+ .{ .key = .{ .cp = K.page_down } },
+ .{ .key = .{ .cp = K.page_up } },
+ .{ .key = .{ .cp = 'k' } },
+ .{ .key = .{ .cp = K.escape } },
+ .{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = 100, .row = 30 } },
+ .{ .mouse = .{ .button = .wheel_up, .kind = .press, .col = 100, .row = 30 } },
+ };
+ for (0..steps.len + 1) |at| {
+ if (at < 3 or at == steps.len) {
+ q.sync();
+ _ = q.frame_arena.reset(.retain_capacity);
+ _ = q.render(q.frame_arena.allocator()) catch {};
+ }
+ if (at == steps.len) return;
+ q.update(steps[at]);
+ while (q.nextEffect()) |_| {}
+ }
+}
+
fn loadSeed(whole: []const u8, road: Road, seed: u64) !void {
var prng: Random.DefaultPrng = .init(seed);
const r = prng.random();
@@ -733,14 +766,9 @@ fn loadSeed(whole: []const u8, road: Road, seed: u64) !void {
var notes: std.ArrayList(u8) = .empty;
defer notes.deinit(gpa);
if (pardes.dump.load(gpa, .{ .cols = 80, .rows = 24 }, b[0..n], &notes)) |q| {
- switch (road) {
- .join => _ = pardes.tape.digestOf(q),
- .restore => {
- _ = q.frame_arena.reset(.retain_capacity);
- _ = q.render(q.frame_arena.allocator()) catch {};
- },
- }
- q.deinit();
+ defer q.deinit();
+ if (road == .join) _ = pardes.tape.digestOf(q);
+ use(q);
} else |err| if (seed == 0) return err;
try testing.expectEqual(@as(usize, 0), cap.refused);
}
@@ -754,9 +782,10 @@ test "a dump and an image cut, flipped and grown: refused or loaded, never a pan
defer gpa.free(bytes);
const image = try pardes.dump.dumpBytes(p);
defer gpa.free(image);
- // Seconds a road. The image's past 1024 seeds reach xitdb's own reader
- // (a slot's tag past its kinds: a `switch` on it), a dependency's.
- for ([_][]const u8{ bytes, image }, [_]Road{ .join, .restore }, [_]u64{ 4096, 1024 }) |whole, road, n| {
+ // Seconds a road, each core used (`use`). The image's past 1779 seeds
+ // reach xitdb's own reader (a slot's tag past its kinds: a `switch` on
+ // it), a dependency's.
+ for ([_][]const u8{ bytes, image }, [_]Road{ .join, .restore }, [_]u64{ 2048, 1024 }) |whole, road, n| {
try loadSeed(whole, road, 0);
for (1..n + 1) |seed| try loadSeed(whole, road, seed);
}
diff --git a/core/jj.zig b/core/jj.zig
index 176ead49..c1d07662 100644
--- a/core/jj.zig
+++ b/core/jj.zig
@@ -3306,6 +3306,179 @@ test "a description is whole, its title and its author never cut: in a pane narr
}
}
+/// 60 numbered lines, line 20 of 130 numbered words (12 rows or more at
+/// 60 columns), and a change to line 40 whose title wraps over several
+/// rows: the rows a view scrolls through, the layer's description among
+/// them.
+const Tall = struct {
+ const title = "a title long enough to wrap: the description of this change says what it does and why at some length, " ++
+ "and then says it again in other words, and once more, so that no pane of sixty columns holds it in fewer than four rows " ++
+ "beside its author and its age";
+
+ fn repo(gpa: std.mem.Allocator) !?Repo {
+ var base: std.ArrayList(u8) = .empty;
+ defer base.deinit(gpa);
+ var changed: std.ArrayList(u8) = .empty;
+ defer changed.deinit(gpa);
+ for (0..60) |i| {
+ const from = base.items.len;
+ if (i == 20) {
+ for (0..130) |w| try base.print(gpa, "t{d:0>3} ", .{w});
+ try base.append(gpa, '\n');
+ } else try base.print(gpa, "line {d:0>2}\n", .{i});
+ try changed.appendSlice(gpa, if (i == 40) "line 40 changed\n" else base.items[from..]);
+ }
+ return Repo.with(gpa, &.{ .{ base.items, "base" }, .{ changed.items, title } }, null);
+ }
+
+ /// The buffer's line the description is.
+ fn description(f: *const File.State) !usize {
+ for (f.layer.lines) |l| if (std.mem.indexOf(u8, f.content[l.at..][0..l.len], title[0..20]) != null)
+ return std.mem.count(u8, f.content[0..l.at], "\n");
+ return error.NoDescription;
+ }
+
+ /// The rows of the text above line `line`'s row that shows its byte
+ /// `col`, in `pane`'s view.
+ fn rowsAbove(tab: u16, pane: *Pane, line: usize, col: usize) usize {
+ var n: usize = File.rowOf(tab, pane, line, col);
+ for (0..line) |l| n += File.lineRows(tab, pane, l);
+ return n;
+ }
+};
+
+test "a view scrolls by rows through a line wrapped over 12 rows and a change's description wrapped over several (a line of the layer): a wheel's notch is one row down the whole text and back, PageDown and PageUp a page of rows, zj and zk one; a held j and k keep the cursor's row three rows inside the body" {
+ const gpa = testing.allocator;
+ var repo = try Tall.repo(gpa) orelse return error.SkipZigTest;
+ defer repo.deinit(gpa);
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 24, .windowed = false });
+ defer p.deinit();
+ const tab = p.settings.tab;
+ var line: [4200]u8 = undefined;
+ p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) });
+ const id = p.view().active;
+ const pane = p.panes[id].?;
+ p.update(.{ .command = "Changes @-" });
+ p.sync();
+ const f = &pane.file.?;
+ try testing.expect(File.lineRows(tab, pane, 20) >= 12);
+ try testing.expect(File.lineRows(tab, pane, try Tall.description(f)) >= 4);
+ var total: usize = 0;
+ for (0..File.nlines(gpa, f)) |l| total += File.lineRows(tab, pane, l);
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ const shot = struct {
+ fn of(q: *Pardes, w: *Pane, a: std.mem.Allocator) ![]const []const u8 {
+ return Ghosts.rows(q, w, a, try a.alloc([]const u8, 256));
+ }
+ }.of;
+ const rect = p.view().rects[id];
+ const at = .{ .col = rect.x + 10, .row = p.bodyTop(pane, rect) + 5 };
+ const notch = struct {
+ fn of(down: bool, x: u16, y: u16) pardes.Event {
+ return .{ .mouse = .{ .button = if (down) .wheel_down else .wheel_up, .kind = .press, .col = x, .row = y } };
+ }
+ }.of;
+ // Every row of the text at the body's top in turn, a notch each: the
+ // body's rows one up.
+ var was = try shot(p, pane, arena.allocator());
+ const kept = was.len - 1;
+ var all: std.ArrayList([]const u8) = .empty;
+ try all.append(arena.allocator(), was[0]);
+ while (true) {
+ p.update(notch(true, at.col, at.row));
+ const now = try shot(p, pane, arena.allocator());
+ if (std.mem.eql(u8, now[0], was[0])) break;
+ for (now[0 .. kept - 1], was[1..kept]) |n, w| try testing.expectEqualStrings(w, n);
+ try all.append(arena.allocator(), now[0]);
+ was = now;
+ }
+ try testing.expectEqual(total, all.items.len);
+ // And back up, a row a notch.
+ var back = all.items.len - 1;
+ while (back > 0) : (back -= 1) {
+ p.update(notch(false, at.col, at.row));
+ const now = try shot(p, pane, arena.allocator());
+ try testing.expectEqualStrings(all.items[back - 1], now[0]);
+ for (now[1..kept], was[0 .. kept - 1]) |n, w| try testing.expectEqualStrings(w, n);
+ was = now;
+ }
+ const indexOf = struct {
+ fn in(rows: []const []const u8, row: []const u8) usize {
+ for (rows, 0..) |r, i| if (std.mem.eql(u8, r, row)) return i;
+ return rows.len;
+ }
+ }.in;
+ // PageDown and PageUp: a page of rows each, the text's last row at the
+ // top the furthest.
+ var top: usize = 0;
+ while (top < all.items.len - 1) {
+ p.update(.{ .key = .{ .cp = pardes.Key.page_down } });
+ top = @min(top + pane.rows, all.items.len - 1);
+ try testing.expectEqual(top, indexOf(all.items, (try shot(p, pane, arena.allocator()))[0]));
+ }
+ while (top > 0) {
+ p.update(.{ .key = .{ .cp = pardes.Key.page_up } });
+ top -|= pane.rows;
+ try testing.expectEqual(top, indexOf(all.items, (try shot(p, pane, arena.allocator()))[0]));
+ }
+ // zj and zk: a row each, through line 20's rows and the description's.
+ for (0..all.items.len - 1) |n| {
+ for ("zj") |k| p.update(.{ .key = .{ .cp = k, .text = &[_]u8{k} } });
+ try testing.expectEqual(n + 1, indexOf(all.items, (try shot(p, pane, arena.allocator()))[0]));
+ }
+ for (0..all.items.len - 1) |n| {
+ for ("zk") |k| p.update(.{ .key = .{ .cp = k, .text = &[_]u8{k} } });
+ try testing.expectEqual(all.items.len - 2 - n, indexOf(all.items, (try shot(p, pane, arena.allocator()))[0]));
+ }
+ // A held j from the first line to the last and a held k back: the
+ // cursor's row three rows (`scroll_off`) inside the body's edges, or
+ // as far as the text before or after it goes.
+ p.update(.{ .command = "Look a.zig:1" });
+ const body = File.shownRows(tab, pane);
+ for ("jk") |cp| for (0..total) |_| {
+ p.update(.{ .key = .{ .cp = cp, .text = &[_]u8{cp} } });
+ const t = File.top(tab, pane);
+ const cur = Tall.rowsAbove(tab, pane, @intCast(pane.body.cur_row), @intCast(pane.body.cur_col));
+ const on = cur - Tall.rowsAbove(tab, pane, t.line, 0) - t.row;
+ try testing.expect(on >= @min(pardes.config.scroll_off, cur));
+ try testing.expect(on <= body - 1 - @min(pardes.config.scroll_off, total - 1 - cur));
+ };
+}
+
+test "a client wheels its session's view a row a notch into a change's description wrapped over several rows (a line of the layer), agreeing with the session at every notch; a client joined over that view loads its row" {
+ var repo = try Tall.repo(testing.allocator) orelse return error.SkipZigTest;
+ defer repo.deinit(testing.allocator);
+ const R = pardes.replica;
+ const a = try R.Authority.init(testing.allocator, .{ .cols = 60, .rows = 24 }, .{});
+ defer a.deinit();
+ const r = try R.Replica.init(testing.allocator, 1, try a.unit(0, 0));
+ defer r.deinit();
+ var line: [4200]u8 = undefined;
+ r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) }));
+ r.confirm(try a.local(.{ .command = "Changes @-" }));
+ r.settle();
+ const id = a.core.view().active;
+ const af = &a.core.panes[id].?.file.?;
+ const desc = try Tall.description(af);
+ const rect = a.core.view().rects[id];
+ const notch: pardes.Event = .{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = rect.x + 10, .row = rect.y + 5 } };
+ var n: usize = 0;
+ while (af.scroll != desc or af.scroll_row != 2) : (n += 1) {
+ if (n > 300) return error.NeverThere;
+ const m = try testing.allocator.dupe(u8, try r.input(notch));
+ defer testing.allocator.free(m);
+ r.confirm(try a.take(m));
+ r.settle();
+ try testing.expect(r.diverged == null);
+ try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core()));
+ const rf = &r.core().panes[id].?.file.?;
+ try testing.expectEqual(af.scroll, rf.scroll);
+ try testing.expectEqual(af.scroll_row, rf.scroll_row);
+ }
+ try R.loadsAsSession(a, 2);
+}
+
test "at one place a change's ghost rows come before its description: a line it changed and the next it took away, then its description" {
const gpa = testing.allocator;
const fn_text = "fn f() void {\n a();\n b();\n c();\n d();\n}\n";
diff --git a/core/layout.zig b/core/layout.zig
index 4c7d6afb..7fa57ee9 100644
--- a/core/layout.zig
+++ b/core/layout.zig
@@ -845,10 +845,14 @@ fn bodyRows(p: *const Pardes, id: usize) u16 {
fn blankRows(p: *const Pardes, id: usize) u16 {
const pane = p.panes[id].?;
const rows = bodyRows(p, id);
- const used: usize = if (pane.file) |*f|
- // The empty line after a final newline shows nothing.
- (panes.File.nlines(p.gpa, f) -| @intFromBool(std.mem.endsWith(u8, f.content, "\n"))) -| f.scroll
- else if (pane.isTerminal())
+ const used: usize = if (pane.file) |*f| used: {
+ // The rows from the view's top to the text's end, a wrapped line's
+ // each; the empty line after a final newline shows nothing.
+ const end = panes.File.nlines(p.gpa, f) -| @intFromBool(std.mem.endsWith(u8, f.content, "\n"));
+ const top = panes.File.top(p.settings.tab, pane);
+ if (end <= top.line) break :used 0;
+ break :used @intCast(panes.File.rowsTo(p.settings.tab, pane, top, end, rows) orelse rows);
+ } else if (pane.isTerminal())
@as(usize, panes.Term.grid(pane.terminal).cursor_y) + 1
else
rows;
@@ -2158,3 +2162,26 @@ test "tiny screens keep pane space before adding a column tag" {
try std.testing.expectEqual(TOPBAR_H, p.view().rects[0].y);
_ = try p.render(p.scratch.allocator());
}
+
+test "a new pane goes below the rows a pane's text takes, a wrapped line's each counted: a pane whose few lines fill its rows keeps them all" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(io, .{ .sub_path = "b.txt", .data = "other\n" });
+ var buf: [std.Io.Dir.max_path_bytes]u8 = undefined;
+ const dir = buf[0..try tmp.dir.realPath(io, &buf)];
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 40 });
+ defer p.deinit();
+ p.settings.wrap = true;
+ // Two lines of 400 bytes: seven rows each at this width.
+ const long = &@as([400]u8, @splat('a'));
+ const pane = try p.setTestFile(long ++ "\n" ++ long ++ "\n");
+ const a = p.view().active;
+ const used = panes.File.lineRows(p.settings.tab, pane, 0) + panes.File.lineRows(p.settings.tab, pane, 1);
+ try std.testing.expect(used >= 12);
+ var line: [4200]u8 = undefined;
+ p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}/b.txt", .{dir}) });
+ try std.testing.expect(p.view().active != a);
+ try std.testing.expect(p.view().rects[a].h -| pane.tag_rows >= used);
+}
diff --git a/core/look.zig b/core/look.zig
index 72bb42eb..ee6debf9 100644
--- a/core/look.zig
+++ b/core/look.zig
@@ -499,9 +499,7 @@ pub fn jumpResult(p: *Pardes, id: usize, row: usize) bool {
rp.body.nsel = 0;
rp.body.cur_row = r;
rp.body.cur_pinned = true;
- const off = rp.scroll();
- const last = off + @as(i32, rp.rows) - 1;
- if (r < off) rp.scrollBy(r - off) else if (r > last) rp.scrollBy(r - last);
+ if (rp.file != null) panes.File.show(p.settings.tab, rp, r, 0, 0);
var realbuf: [4096]u8 = undefined;
const span = if (tr.commands)
wholeRowSpan(ln)
@@ -820,14 +818,9 @@ pub fn focusPaneLine(p: *Pardes, id: usize, at_in: Spot, landing: enum { center,
};
if (pane.file) |*f| {
if (at.line > panes.File.nlines(p.gpa, f)) return;
- if (landing == .center) {
- // center, clamp at top; a text that fits is shown whole
- const next = if (pane.textFits()) 0 else (at.line - 1) -| pane.rows / 2;
- if (next != f.scroll) {
- f.scroll = next;
- f.syntax_dirty = true;
- }
- }
+ // centred (its first row of text half the body's rows down, as
+ // zz), clamped at the top; a text that fits is shown whole
+ if (landing == .center) panes.File.setTop(pane, if (pane.textFits()) .{ .line = 0 } else panes.File.walkRows(p.settings.tab, pane, .{ .line = at.line - 1, .row = panes.File.rowOf(p.settings.tab, pane, at.line - 1, 0) }, -@as(i64, pane.rows / 2)).to);
}
pane.body.cur_row = std.math.cast(i32, at.line - 1) orelse return;
pane.body.cur_col = columnOn(pane, pane.body.cur_row, at.col);
@@ -1697,11 +1690,13 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void {
// miss of its line too.
if (p.fs.failures != failures) return;
layout.compute(p);
- nt.file.?.scroll -|= @max(1, v.rects[free].h -| BOX_H) / 2;
+ // Its line half the body's rows down, a wrapped line's
+ // rows above it counted.
+ const centered = panes.File.walkRows(p.settings.tab, nt, .{ .line = nt.file.?.scroll }, -@as(i64, @max(1, v.rects[free].h -| BOX_H) / 2)).to;
+ panes.File.setTop(nt, centered);
if (target.at.end_line != 0) {
- const centered = nt.file.?.scroll;
selectSpan(p, nt, target.at);
- nt.file.?.scroll = centered;
+ panes.File.setTop(nt, centered);
}
opened = free;
}
@@ -1932,6 +1927,35 @@ test "lookableLineSpan prefers the longest run, so a blank inside a path is one
);
}
+test "a Look that opens a file in a pane of its own puts its line half the body's rows down, a wrapped line's rows above it counted" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ // Line 10 of 600 bytes, eleven rows or more in a pane 60 wide.
+ var text: std.ArrayList(u8) = .empty;
+ defer text.deinit(gpa);
+ for (0..60) |i| if (i == 10) {
+ try text.appendNTimes(gpa, 'a', 600);
+ try text.append(gpa, '\n');
+ } else try text.print(gpa, "line {d:0>2}\n", .{i});
+ try tmp.dir.writeFile(io, .{ .sub_path = "c.txt", .data = text.items });
+ var buf: [std.Io.Dir.max_path_bytes]u8 = undefined;
+ const dir = buf[0..try tmp.dir.realPath(io, &buf)];
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 40 });
+ defer p.deinit();
+ p.settings.wrap = true;
+ _ = try p.setTestFile("x\n");
+ var line: [4200]u8 = undefined;
+ p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}/c.txt:14", .{dir}) });
+ const id = p.view().active;
+ const pane = p.panes[id].?;
+ try std.testing.expect(panes.File.lineRows(p.settings.tab, pane, 10) >= 11);
+ try std.testing.expectEqual(@as(i32, 13), pane.body.cur_row);
+ const half: i64 = @max(1, p.view().rects[id].h -| BOX_H) / 2;
+ try std.testing.expectEqual(half, panes.File.rowsTo(p.settings.tab, pane, panes.File.top(p.settings.tab, pane), 13, 100).?);
+}
+
test "a miss names a long path by its start and its end, its middle given up to …" {
var cut: [miss_path_cap + "…".len]u8 = undefined;
const long = "/home/someone/" ++ std.mem.asBytes(&@as([80][5]u8, @splat("deep/".*))) ++ "the-file.zig";
@@ -2313,6 +2337,7 @@ test "Look on a diff: headers and a hunk line's prefix are the whole line, hover
// Back to the diff, scrolled to its top again.
p.view().active = 0;
pane.file.?.scroll = 0;
+ pane.file.?.scroll_row = 0;
p.sync();
_ = frame.reset(.retain_capacity);
_ = try p.render(frame.allocator());
@@ -2386,6 +2411,7 @@ test "a click, a 9P whole-line look and an empty event write-back take one expan
for (points) |at| {
p.view().active = 0;
pane.file.?.scroll = 0;
+ pane.file.?.scroll_row = 0;
pane.body.cur_row = 0;
p.sync();
_ = frame.reset(.retain_capacity);
@@ -2462,6 +2488,7 @@ test "every entry point to Look takes one expansion: a diff line and a file:12:5
pane.body.cur_col = case.col;
pane.body.cur_pinned = true;
pane.file.?.scroll = 0;
+ pane.file.?.scroll_row = 0;
p.sync();
_ = frame.reset(.retain_capacity);
_ = try p.render(frame.allocator());
diff --git a/core/lsp/Ask.zig b/core/lsp/Ask.zig
index 4d57f21e..29d36f0a 100644
--- a/core/lsp/Ask.zig
+++ b/core/lsp/Ask.zig
@@ -27,6 +27,8 @@ seq: u32 = 0,
last: ?struct { kind: lsp.Kind, arg: Effect.Buf(128), serial: u32, offset: u32 } = null,
/// The query whose answer is awaited.
wait: ?struct {
+ /// Its pane's slot (walk.zig `.index`), that pane while `serial` says.
+ pub const replica = .{ .index = .{.{ "pane", pardes.Pardes, "panes" }} };
id: u32,
kind: lsp.Kind,
pane: Pane.Id,
diff --git a/core/mouse.zig b/core/mouse.zig
index 2d731acf..14700995 100644
--- a/core/mouse.zig
+++ b/core/mouse.zig
@@ -702,7 +702,7 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void {
const id = hovered orelse return;
const pane = p.panes[id].?;
if (!programWheel(p, id, m, mcol, mrow))
- pane.scrollBy(if (m.button == .wheel_up) -config.wheel_rows else config.wheel_rows);
+ pane.scrollBy(p.settings.tab, if (m.button == .wheel_up) -config.wheel_rows else config.wheel_rows);
},
.wheel_left, .wheel_right => {
if (m.kind != .press) return;
@@ -779,7 +779,7 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void {
return pane.places.goTo(p.settings.tab, pane, i, false);
};
// gutter scrollbar: a left click scrolls UP to that row
- pane.scrollBy(-(@as(i32, mrow) - @as(i32, body_y)));
+ pane.scrollBy(p.settings.tab, -(@as(i32, mrow) - @as(i32, body_y)));
} else {
const on_tag = mrow >= tag_y and mrow < tag_y + pane.tag_rows;
if (on_tag and mcol < r.x + TAG_TEXT_INSET) return;
@@ -847,7 +847,7 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void {
if (mcol < r.x + config.GUTTER and !on_tag) {
const local = @as(i32, mrow) - @as(i32, body_y);
if (m.button == config.look_button) v.active = id;
- pane.scrollBy(if (m.button == config.look_button) local else -local);
+ pane.scrollBy(p.settings.tab, if (m.button == config.look_button) local else -local);
} else if (edit.pointerTextSelection(p, id, mcol, mrow, m.body_hit, v.pointer_tag_hit)) |pointed| {
if (m.button == config.look_button) v.active = id;
pane.clearPointerSelection(@backingInt(m.button));
@@ -1150,11 +1150,15 @@ pub fn edgeScroll(p: *Pardes) void {
const sl = &pane.sel[sel_slot];
if (s.anchor == null) s.anchor = sweepPoint(p, pane, sl.r0, sl.c0) orelse return;
const before = pane.scroll();
- pane.scrollBy(s.edge);
+ // A file's view moves by rows (File.Top), a terminal's rows are lines.
+ const moved: i64 = if (pane.file != null) panes.File.scrollRows(p.settings.tab, pane, s.edge) else blk: {
+ pane.scrollBy(p.settings.tab, s.edge);
+ break :blk pane.scroll() - before;
+ };
// The start's row follows its text while it is on the screen, and
// stays on the body's edge row once it is off (the anchor keeps it).
const top: i32 = pane.tag_rows;
- sl.r0 = std.math.clamp(sl.r0 - (pane.scroll() - before), top, top + @as(i32, pane.rows) - 1);
+ sl.r0 = std.math.clamp(sl.r0 - @as(i32, @intCast(moved)), top, top + @as(i32, pane.rows) - 1);
}
/// The text position under a body cell of the sweep's space.
diff --git a/core/ninep/events.zig b/core/ninep/events.zig
index f1e17324..e18b5d96 100644
--- a/core/ninep/events.zig
+++ b/core/ninep/events.zig
@@ -1406,14 +1406,14 @@ test "a click in the body reports the offsets of the word it takes, so the recor
}) |c| for ([_]pardes.Mouse.Button{ config.look_button, config.exec_button }, [_][]const u8{ c.look, c.exec }) |button, want| {
// The pointer rests on the word first, as a hand's does, and
// the hover preview comes up under it.
- p.panes[id].?.scrollBy(c.scroll);
+ p.panes[id].?.scrollBy(p.settings.tab, c.scroll);
_ = try p.render(frame.allocator());
p.update(.{ .mouse = .{ .button = .none, .kind = .motion, .col = c.x, .row = c.y } });
for (0..200) |_| p.update(.tick);
p.update(.{ .mouse = .{ .button = button, .kind = .press, .col = c.x, .row = c.y } });
p.update(.{ .mouse = .{ .button = button, .kind = .release, .col = c.x, .row = c.y } });
try testing.expectEqualStrings(want, call(p, .{ .tag = 2, .op = .read, .node = event, .handle = h, .size = 256 }).bytes);
- p.panes[id].?.scrollBy(-c.scroll);
+ p.panes[id].?.scrollBy(p.settings.tab, -c.scroll);
};
// A click on nothing expands to nothing, and acme then says
// nothing (look.c:37, exec.c:141).
diff --git a/core/normal.zig b/core/normal.zig
index 89fd72f6..1f7ce1a7 100644
--- a/core/normal.zig
+++ b/core/normal.zig
@@ -339,11 +339,22 @@ fn startJump(p: *Pardes, pane: *Pane, t: *Text) edit.Error!void {
const text = try edit.flatSurface(p.editor(), t);
const cursor = modal.selectionCursor(text, t.primaryRange(text, 0));
const top: usize = @intCast(@max(0, pane.scroll()));
- const start = @min(modal.lineStartOffset(text, top), text.len);
- const end = @min(modal.lineStartOffset(text, top + pane.rows), text.len);
+ // A file's words the body shows, its rows' bytes; a terminal's rows
+ // are its lines.
+ const shown = if (pane.file != null) File.shownBytes(p.settings.tab, pane) else File.Bytes{ .start = modal.lineStartOffset(text, top), .end = modal.lineStartOffset(text, top + pane.rows) };
+ const start = @min(shown.start, text.len);
+ const end = @min(shown.end, text.len);
const letters = config.jump_label_alphabet.len;
try pane.jump.resize(p.gpa, letters * letters);
- pane.jump.shrinkRetainingCapacity(modal.jumpWords(text, cursor, start, end, pane.jump.items));
+ const n = modal.jumpWords(text, cursor, start, end, pane.jump.items);
+ // A word the body's first row starts inside of (a wrapped line's row
+ // cut mid-word) begins above it: no label it would not show.
+ var kept: usize = 0;
+ for (pane.jump.items[0..n]) |r| if (@min(r.anchor, r.head) >= start) {
+ pane.jump.items[kept] = r;
+ kept += 1;
+ };
+ pane.jump.shrinkRetainingCapacity(kept);
pane.jump_first = null;
}
@@ -946,14 +957,31 @@ fn verticalMove(tab: u16, t: *Text, text: []const u8, range: modal.Selection, do
t.sticky_col = @intCast(goal);
}
-/// Ctrl-d/u: scroll half a page AND move the cursor by the same rows
+/// Ctrl-d/u: the view half the body's rows on, and the cursor where it
+/// stood on the screen (inside the margins): on the line whose first row is
+/// now there, the next one the way it went past a wrapped line's later
+/// row, and the rows the view could not move (the text's end) further.
+/// None in the body (inside a line taller than it): it stays, off the
+/// view, and the view where it went. A terminal's rows are its lines: both
+/// move by them.
fn halfPageMove(tab: u16, t: *Text, text: []const u8, range: modal.Selection, down: bool) void {
// a view to move through is a body's; a tag or an answer is all shown
if (t.what != .body) return;
const w = t.pane() orelse return;
const half: i32 = @max(1, @divTrunc(@as(i32, w.rows), 2));
- w.scrollBy(if (down) half else -half);
- verticalMove(tab, t, text, range, down, @intCast(half), 0);
+ if (w.file == null) {
+ w.scrollBy(tab, if (down) half else -half);
+ return verticalMove(tab, t, text, range, down, @intCast(half), 0);
+ }
+ const body: i64 = File.shownRows(tab, w);
+ const margin = @min(config.scroll_off, @divTrunc(body - 1, 2));
+ const from = File.top(tab, w);
+ const line: usize = @intCast(@max(0, t.cur_row));
+ const on: i64 = if (File.rowsTo(tab, w, from, line, @intCast(body))) |d| d + File.rowOf(tab, w, line, @intCast(@max(0, t.cur_col))) else if (line < from.line) 0 else body - 1;
+ const moved = File.scrollRows(tab, w, if (down) half else -half);
+ const to = File.textRowLine(tab, w, on + (if (down) half else -half) - moved, margin, if (down) .down else .up) orelse return;
+ if (to == t.cur_row) return;
+ verticalMove(tab, t, text, range, to > t.cur_row, @abs(to - t.cur_row), 0);
}
/// gt/gb: view-relative rows, col 0, scrolloff clamped (helix goto_window)
@@ -961,11 +989,28 @@ fn gotoWindow(tab: u16, t: *Text, text: []const u8, range: modal.Selection, whic
// a view to move through is a body's; a tag or an answer is all shown
if (t.what != .body) return;
const w = t.pane() orelse return;
+ const n: i32 = @intCast(cnt - 1);
+ if (w.file != null) {
+ // In rows, as helix's goto_window: the row `margin + n` in from the
+ // body's top or its last row of text, inside the margins, the
+ // cursor on the first byte it shows (a wrapped line's later row).
+ const shown: i32 = File.shownRows(tab, w);
+ const held: i32 = w.context_rows;
+ const lines = File.textLineCount(t, text);
+ var last: i32 = shown - 1;
+ while (last > 0 and w.wrapAt(tab, held + last).line >= lines) last -= 1;
+ const margin: i32 = @min(config.scroll_off, @divTrunc(shown - 1, 2));
+ const vr = std.math.clamp(@min(@max(switch (which) {
+ .top => margin + n,
+ .bottom => last - (margin + n),
+ }, margin), last - margin), 0, last);
+ const at = w.wrapAt(tab, held + vr);
+ return pointMove(tab, t, text, range, File.textLineStart(t, text, @intCast(at.line)) + if (w.body_wrapped) @as(usize, @intCast(at.at)) else 0);
+ }
const margin: i32 = @min(config.scroll_off, @divTrunc(@as(i32, w.rows) - 1, 2));
const top = w.scroll();
const last_row: i32 = @intCast(File.textLineCount(t, text) - 1);
const last_vis: i32 = @min(@as(i32, w.rows) - 1, last_row - top);
- const n: i32 = @intCast(cnt - 1);
var vline: i32 = switch (which) {
.top => top + margin + n,
.bottom => top + last_vis - (margin + n),
@@ -1235,13 +1280,28 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error!
// helix align_view: the cursor's row goes `above` rows down the
// view, the middle of an odd one and the upper middle of an even one
.view_top, .view_center, .view_bottom => if (t.what == .body) {
- const above: i32 = switch (a.role) {
- .view_top => 0,
- .view_center => @divTrunc(@as(i32, pane.rows) - 1, 2),
- else => @as(i32, pane.rows) - 1,
- };
- pane.scrollBy(t.cur_row - (pane.scroll() + above));
- pane.ensureCursorVisible(p.settings.tab);
+ // In rows: zt shows the cursor's line from its first row, a
+ // line taller than the body from the cursor's.
+ const tab = p.settings.tab;
+ if (pane.file == null) {
+ const above: i32 = switch (a.role) {
+ .view_top => 0,
+ .view_center => @divTrunc(@as(i32, pane.rows) - 1, 2),
+ else => @as(i32, pane.rows) - 1,
+ };
+ pane.scrollBy(tab, t.cur_row - (pane.scroll() + above));
+ } else {
+ const body: i64 = File.shownRows(tab, pane);
+ const line: usize = @intCast(@max(0, t.cur_row));
+ const row = File.rowOf(tab, pane, line, @intCast(@max(0, t.cur_col)));
+ const at: File.Top = .{ .line = line, .row = if (a.role == .view_top and row < body) 0 else row };
+ File.setTop(pane, File.walkRows(tab, pane, at, switch (a.role) {
+ .view_top => 0,
+ .view_center => -@divTrunc(body - 1, 2),
+ else => -(body - 1),
+ }).to);
+ }
+ pane.ensureCursorVisible(tab);
},
// helix align_view_middle: the cursor's column to the middle of an
// unwrapped view
@@ -1429,6 +1489,103 @@ test "gj/gk step the wrapped rows a body draws while j/k keep the file's lines"
try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row);
}
+/// 10 short lines, line 10 of 200 numbered words (17 rows or more at 60
+/// columns), 40 short lines after it; the view's top four rows into line
+/// 10, the cursor on a row the body shows.
+fn wrappedView(p: *Pardes) !*Pane {
+ p.settings.wrap = true;
+ var text: std.ArrayList(u8) = .empty;
+ defer text.deinit(p.gpa);
+ for (0..51) |i| if (i == 10) {
+ for (0..200) |w| try text.print(p.gpa, "w{d:0>3} ", .{w});
+ try text.append(p.gpa, '\n');
+ } else try text.print(p.gpa, "line {d:0>2}\n", .{i});
+ const pane = try p.setTestFile(text.items);
+ File.setTop(pane, .{ .line = 10, .row = 4 });
+ p.sync();
+ const at = pane.wrapAt(p.settings.tab, pane.context_rows + 6);
+ pane.body.cur_row = at.line;
+ pane.body.cur_col = at.at;
+ return pane;
+}
+
+test "gt and gb go to the row scroll_off rows in from the body's top and from its bottom, a wrapped line's later row as any, the cursor on its first byte; the view stays" {
+ const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 60, .rows = 24 });
+ defer p.deinit();
+ const tab = p.settings.tab;
+ const pane = try wrappedView(p);
+ const top = File.top(tab, pane);
+ try std.testing.expectEqual(@as(u32, 4), top.row);
+ for ("tb") |k| {
+ p.update(.{ .key = .{ .cp = 'g', .text = "g" } });
+ p.update(.{ .key = .{ .cp = k, .text = &[_]u8{k} } });
+ try std.testing.expectEqual(top, File.top(tab, pane));
+ const row: i32 = if (k == 't') config.scroll_off else File.shownRows(tab, pane) - 1 - config.scroll_off;
+ const want = pane.wrapAt(tab, pane.context_rows + row);
+ try std.testing.expectEqual(want.line, pane.body.cur_row);
+ try std.testing.expectEqual(want.at, pane.body.cur_col);
+ }
+}
+
+test "gt after a step that moved the view off the place its geometry was made for: the row scroll_off in from the body's top under the context rows the view has now, as a core loaded from the session goes" {
+ const gpa = std.testing.allocator;
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 });
+ defer p.deinit();
+ const pane = try p.setTestFile("pub const Box = struct {\n pub fn run() void {\n" ++ (std.mem.asBytes(&@as([30][21]u8, @splat(" // body line\n".*)))) ++ " }\n};\n");
+ p.gpa.free(pane.file.?.path);
+ pane.file.?.path = try p.gpa.dupe(u8, "/test.zig");
+ if (!File.supportsContext(pane)) return error.SkipZigTest;
+ pane.file.?.tree_context = true;
+ // The view inside the function, its two headers held over the body,
+ // drawn.
+ File.setTop(pane, .{ .line = 3 });
+ p.sync();
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ _ = try p.render(arena.allocator());
+ try std.testing.expectEqual(@as(u16, 2), pane.context_rows);
+ // Two notches up: the top on the function's header, one header held
+ // (the geometry the second notch read was the one before it).
+ const rect = p.view().rects[0];
+ for (0..2) |_| p.update(.{ .mouse = .{ .button = .wheel_up, .kind = .press, .col = rect.x + 10, .row = rect.y + 5 } });
+ try std.testing.expectEqual(@as(usize, 1), pane.file.?.scroll);
+ const bytes = try pardes.dump.dumpBytes(p);
+ defer gpa.free(bytes);
+ const loaded = try pardes.dump.load(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }, bytes, null);
+ defer loaded.deinit();
+ for ([_]*Pardes{ p, loaded }) |core| for ("gt") |k| core.update(.{ .key = .{ .cp = k, .text = &[_]u8{k} } });
+ try std.testing.expectEqual(loaded.panes[0].?.body.cur_row, pane.body.cur_row);
+ try std.testing.expectEqual(@as(u16, 1), pane.context_rows);
+ try std.testing.expectEqual(pane.wrapAt(p.settings.tab, 1 + config.scroll_off).line, pane.body.cur_row);
+}
+
+test "gw labels the words the body shows and no others: none on a wrapped line's rows above the view's top" {
+ const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 60, .rows = 24 });
+ defer p.deinit();
+ const tab = p.settings.tab;
+ const pane = try wrappedView(p);
+ p.update(.{ .key = .{ .cp = 'g', .text = "g" } });
+ p.update(.{ .key = .{ .cp = 'w', .text = "w" } });
+ try std.testing.expect(pane.jump.items.len > 20);
+ const f = &pane.file.?;
+ const shown = File.shownRows(tab, pane);
+ // Rows with a label: the body's first and its last among them.
+ var labelled: [2]bool = .{ false, false };
+ for (pane.jump.items) |r| {
+ const at = @min(r.anchor, r.head);
+ const line = std.mem.count(u8, f.content[0..at], "\n");
+ const col = at - File.lineStart(p.gpa, f, line);
+ // The row that shows its first byte is in the body, at or after
+ // that row's start (no row above the top).
+ const row = pane.wrapRow(tab, @intCast(line), @intCast(col));
+ try std.testing.expect(row.row >= pane.context_rows and row.row < pane.context_rows + shown);
+ try std.testing.expect(col >= row.at);
+ if (row.row == pane.context_rows) labelled[0] = true;
+ if (row.row == pane.context_rows + shown - 1) labelled[1] = true;
+ }
+ try std.testing.expectEqual([2]bool{ true, true }, labelled);
+}
+
test "flat text movement and selection replay need no scratch rows" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 12 });
diff --git a/core/panes.zig b/core/panes.zig
index 02ee805f..8939bd05 100644
--- a/core/panes.zig
+++ b/core/panes.zig
@@ -31,12 +31,22 @@ pub const Pane = struct {
/// it (views.zig). (The 9P server's part of `fs` says so in its type.)
pub const replica = .{
.local = .{ "pv", "pv_known" },
- .derived = .{ "wrap_line", "wrap_col", "wrap_pad", "wrap_n", "body_wrapped", "context_rows", "body_rows", "body_visible_rows", "context_row_limit", "geometry_key", "geometry_len", "notices", "pan" },
+ .derived = .{ "wrap_line", "wrap_col", "wrap_pad", "wrap_n", "body_wrapped", "context_rows", "body_rows", "body_visible_rows", "context_row_limit", "geometry_key", "geometry_len", "top_skip", "notices", "pan" },
.len = .{ .{ "msg", "msg_len" }, .{ "msg_older", "msg_older_len" }, .{ "question", "question_len" }, .{ "shell_tail", "shell_tail_len" }, .{ "sel_snap", "nsel_snap" } },
// A picture's memory is its own allocator's (a dump loaded makes
// it there).
.alloc = .{ .{ "addon", "image" }, .{ "pdf", "image" }, .{ "terminal", "terminal" } },
+ // Slots of the session's (walk.zig `.index`): a view's, a pane's,
+ // each looked at before it is used (one gone since is no error).
+ .index = .{ .{ "sized_by", Pardes, "views" }, .{ "prompt_view", Pardes, "views" }, .{ "search_pane", Pardes, "panes" } },
+ // The tag's prefix as it was placed: one its room holds.
+ .place = .{.{ "tag_lead", "leadRoom" }},
};
+ /// The room a tag's computed prefix is made in, each step (Pardes.sync).
+ pub const prefix_room = 32 * 1024;
+ pub fn leadRoom(_: *const Pane) usize {
+ return prefix_room;
+ }
/// A pane's slot in `Pardes.panes`, as it crosses the core's edge: an
/// entry's argument or answer, an event's, an effect's, a host call's.
/// A type of its own, so a view's slot (`View.Id`) is not taken for
@@ -309,6 +319,12 @@ pub const Pane = struct {
wrap_n: u16 = 0,
/// A row map also exists for sticky headers when soft wrapping is off.
body_wrapped: bool = false,
+ /// Where the view's top is inside its line's rows (File.Top) for the
+ /// geometry of `key`: the row it is and the bytes of the line before
+ /// it, found by the geometry's walk or by the step that put the top
+ /// there; read only through File.topSkip, which walks one of another
+ /// key again (another view's top, a step's for the next geometry).
+ top_skip: struct { key: u64 = 0, row: u32 = 0, at: usize = 0 } = .{},
context_rows: u16 = 0,
body_rows: u16 = 0,
body_visible_rows: u16 = 0,
@@ -636,15 +652,11 @@ pub const Pane = struct {
return .{ .row = -1, .at = 0 };
}
- pub fn scrollBy(pane: *Pane, delta: i32) void {
- if (pane.file) |*f| {
- const max: i64 = @intCast(File.nlines(pane.gpa, f) -| 1);
- const n = std.math.clamp(@as(i64, @intCast(f.scroll)) + delta, 0, max);
- const next: usize = @intCast(n);
- if (next != f.scroll) {
- f.scroll = next;
- f.syntax_dirty = true;
- }
+ /// The view moved `delta` rows: a file's through its lines' wrapped
+ /// rows (File.Top), a terminal's through its history.
+ pub fn scrollBy(pane: *Pane, tab: u16, delta: i32) void {
+ if (pane.file != null) {
+ _ = File.scrollRows(tab, pane, delta);
} else if (pane.addon == null) {
// the vt scrolls in SHELL rows; convert through the edit buffer.
// The alternate screen has no history (ghostty's scrolls none):
@@ -668,43 +680,14 @@ pub const Pane = struct {
}
pub fn ensureCursorVisible(pane: *Pane, tab: u16) void {
- File.geometry(tab, pane);
- const off = pane.scroll();
- var in_context = false;
- // The map is the view's as it is now (File.geometry): an ancestor is
- // pinned only in the view it was found for.
- if (pane.context_rows < pane.wrap_n and pane.wrap_line[pane.context_rows] == off) {
- for (pane.wrap_line[0..pane.context_rows]) |row| {
- if (row == pane.body.cur_row) {
- in_context = true;
- break;
- }
- }
- }
- // Scrolloff is measured in the ordinary body, excluding sticky rows.
- var margin: i32 = @min(config.scroll_off, @divTrunc(@as(i32, pane.rows) - 1, 2));
- var last = off + @as(i32, pane.rows) - 1;
- const visible_rows = if (pane.body_visible_rows > 0) @min(pane.wrap_n, pane.body_visible_rows) else pane.wrap_n;
- if (pane.context_rows < visible_rows) {
- const lines_shown = pane.wrap_line[visible_rows - 1] - pane.wrap_line[pane.context_rows];
- last = off + lines_shown;
- margin = @min(margin, @divTrunc(@max(0, lines_shown), 2));
- }
- if (!in_context) {
- if (pane.follow_edges != 0 and (pane.body.cur_row < off or pane.body.cur_row > last)) pane.follow_crossed = true;
+ if (pane.file != null) File.show(tab, pane, pane.body.cur_row, pane.body.cur_col, config.scroll_off) else {
+ // A terminal's rows are its lines.
+ const off = pane.scroll();
+ const margin: i32 = @min(config.scroll_off, @divTrunc(@as(i32, pane.rows) - 1, 2));
+ const last = off + @as(i32, pane.rows) - 1;
if (pane.body.cur_row < off + margin) {
- if (pane.follow_edges & 1 == 0) pane.scrollBy(pane.body.cur_row - margin - off);
- } else if (pane.body.cur_row > last - margin and pane.follow_edges & 2 == 0) {
- var to = pane.body.cur_row + margin;
- if (pane.file) |*f| {
- // The margin only reveals text: a pane its whole text
- // fits in never scrolls for it. A longer one keeps
- // helix's clamp at the buffer's last line.
- const lines: i32 = @intCast(File.nlines(pane.gpa, f));
- to = @min(to, if (off == 0 and pane.textFits()) @max(pane.body.cur_row, lines - 1 - @intFromBool(std.mem.endsWith(u8, f.content, "\n"))) else lines - 1);
- }
- pane.scrollBy(@max(0, to - last));
- }
+ pane.scrollBy(tab, pane.body.cur_row - margin - off);
+ } else if (pane.body.cur_row > last - margin) pane.scrollBy(tab, pane.body.cur_row + margin - last);
}
if (pane.file) |f| {
if (pane.body_wrapped) return;
diff --git a/core/replica.zig b/core/replica.zig
index 829972c2..2a66cc3d 100644
--- a/core/replica.zig
+++ b/core/replica.zig
@@ -1911,6 +1911,18 @@ pub const Peers = struct {
return n;
}
+ /// The time the session's pump reads after its wait, when that wait
+ /// took a client's post and nothing else (`only_mail`, the shell's word
+ /// for its wait): the core's clock as it stands, so the pump's unit
+ /// moves nothing a client's speculation stands on; null otherwise (the
+ /// shell's clock). Held only while a post waits (`mail`): a wait that
+ /// ran out took none, and the pump after it is the one its deadline
+ /// asked for (a window's wait that ran out was held, 2026-11-24: a
+ /// deadline never met, the session stepped a millisecond for ever).
+ pub fn heldNow(ps: *const Peers, core: *const Pardes, only_mail: bool) ?u64 {
+ return if (only_mail and ps.recording and ps.mail.load(.acquire) and core.clock.started) core.clock.now_ns else null;
+ }
+
pub fn post(ps: *Peers, note: Note) void {
ps.lock.lockUncancelable(ps.io);
if (note == .join and ps.upgrading.load(.monotonic)) {
@@ -3100,7 +3112,7 @@ fn loadAgain(gpa: Allocator, j: *Joined, have: ?*Have, why: []u8, session: []con
/// The fields a replica loaded from the join's dump `bytes` has other than
/// the session as it dumped them (the digest a field at a time the dump
/// ends with: dump.joinParts), named in `out`.
-fn loadDiffers(r: *Replica, bytes: []const u8, out: []u8) []const u8 {
+pub fn loadDiffers(r: *Replica, bytes: []const u8, out: []u8) []const u8 {
const want = pardes.dump.joinParts(r.gpa, bytes) orelse return "(the dump names no field) ";
defer r.gpa.free(want);
var arena: std.heap.ArenaAllocator = .init(r.gpa);
@@ -4534,6 +4546,160 @@ test "bytes: a client's wheel over a terminal is its own view's: applied at once
try std.testing.expect(placeIn(b.r.core(), b.r.view, id).? < back);
}
+test "a view's top is a line and a row of its block: a client's wheel into a line wrapped over rows moves it a row a notch, the session agrees through a rollback, and a dump keeps the row" {
+ const gpa = std.testing.allocator;
+ var text: std.ArrayList(u8) = .empty;
+ defer text.deinit(gpa);
+ // Line 3 is 60 words: four rows at this width.
+ for (0..40) |i| if (i == 3) {
+ for (0..60) |w| try text.print(gpa, "w{d:0>3} ", .{w});
+ try text.append(gpa, '\n');
+ } else try text.print(gpa, "line {d}\n", .{i});
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host());
+ defer a.deinit();
+ const was = Stepping.begin(&a.t, null);
+ _ = try a.core.setTestFile(text.items);
+ was.end();
+ _ = try a.unit(0, 0);
+ const id = a.core.view().active;
+ // A client joined from the session's dump: the text is in it.
+ const r = try joinedNow(a, 1, 0);
+ defer r.deinit();
+ const rect = a.core.view().rects[id];
+ const notch: pardes.Event = .{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = rect.x + 10, .row = rect.y + 5 } };
+ // Three notches to line 3's first row, two into its block.
+ for (0..5) |_| {
+ const m = try gpa.dupe(u8, try r.input(notch));
+ defer gpa.free(m);
+ r.confirm(try a.take(m));
+ r.settle();
+ try agrees(a, r);
+ }
+ for ([_]*Pardes{ a.core, r.core() }) |core| {
+ try std.testing.expectEqual(@as(usize, 3), core.panes[id].?.file.?.scroll);
+ try std.testing.expectEqual(@as(u32, 2), core.panes[id].?.file.?.scroll_row);
+ }
+ // A notch of the client's on top of the session's own key (one that
+ // leaves the view be): the copy put back, the notch applied over it.
+ const again = try gpa.dupe(u8, try r.input(notch));
+ defer gpa.free(again);
+ r.confirm(try a.local(.{ .key = .{ .cp = pardes.Key.escape } }));
+ r.settle();
+ r.confirm(try a.take(again));
+ r.settle();
+ try agrees(a, r);
+ try std.testing.expectEqual(@as(u32, 3), r.core().panes[id].?.file.?.scroll_row);
+ // A client joining over the view scrolled into the block has the row.
+ const late = try joinedNow(a, 2, 0);
+ defer late.deinit();
+ try agrees(a, late);
+ try std.testing.expectEqual(@as(u32, 3), late.core().panes[id].?.file.?.scroll_row);
+ // The client's view keys, each after the session drew (its geometry
+ // made for the frame; the client's is not): what a key reads of the
+ // body's rows is made of the state alone (the soak's divergence at a
+ // Ctrl-b, before File.shownRows laid the geometry out first).
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ for ([_]pardes.Key{ .{ .cp = 'b', .ctrl = true }, .{ .cp = 'f', .ctrl = true }, .{ .cp = 'd', .ctrl = true }, .{ .cp = 'u', .ctrl = true }, .{ .cp = 'e', .ctrl = true } }) |k| {
+ for (0..3) |_| {
+ {
+ const drew = Stepping.begin(&a.t, null);
+ defer drew.end();
+ _ = try a.core.render(arena.allocator());
+ }
+ const m = try gpa.dupe(u8, try r.input(.{ .key = k }));
+ defer gpa.free(m);
+ r.confirm(try a.take(m));
+ r.settle();
+ try agrees(a, r);
+ }
+ }
+ // A session's dump keeps the row.
+ const bytes = try pardes.dump.dumpBytes(a.core);
+ defer gpa.free(bytes);
+ const loaded = try pardes.dump.load(gpa, .{ .cols = 80, .rows = 24 }, bytes, null);
+ defer loaded.deinit();
+ try std.testing.expectEqual(walk.digest(Pardes, a.core), walk.digest(Pardes, loaded));
+ try std.testing.expectEqual(a.core.panes[id].?.file.?.scroll_row, loaded.panes[id].?.file.?.scroll_row);
+}
+
+test "a text's views under random orders of the session's and a client's keys, wheels and draws, keys of the session's between a client's and its confirm (rollbacks): every side agrees (an explorer of a view's rows)" {
+ const gpa = std.testing.allocator;
+ var text: std.ArrayList(u8) = .empty;
+ defer text.deinit(gpa);
+ // Lines of one row and of several (wrapped at 80 columns).
+ for (0..120) |i| if (i % 7 == 3) {
+ for (0..20 + i % 40) |w| try text.print(gpa, "w{d:0>3} ", .{w});
+ try text.append(gpa, '\n');
+ } else try text.print(gpa, "line {d}\n", .{i});
+ const keys = [_]pardes.Key{
+ .{ .cp = 'j', .text = "j" }, .{ .cp = 'k', .text = "k" },
+ .{ .cp = 'w', .text = "w" }, .{ .cp = 'b', .text = "b" },
+ .{ .cp = 'b', .ctrl = true }, .{ .cp = 'f', .ctrl = true },
+ .{ .cp = 'd', .ctrl = true }, .{ .cp = 'u', .ctrl = true },
+ .{ .cp = 'G', .text = "G" }, .{ .cp = 'z', .text = "z" },
+ .{ .cp = 't', .text = "t" }, .{ .cp = 'i', .text = "i" },
+ .{ .cp = 'x', .text = "x" }, .{ .cp = pardes.Key.escape },
+ .{ .cp = '/', .text = "/" }, .{ .cp = pardes.Key.enter },
+ };
+ for (0..view_orders) |seed| {
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host());
+ defer a.deinit();
+ const was = Stepping.begin(&a.t, null);
+ _ = try a.core.setTestFile(text.items);
+ was.end();
+ _ = try a.unit(0, 0);
+ const id = a.core.view().active;
+ const r = try joinedNow(a, 1, 0);
+ defer r.deinit();
+ const opened = try a.openView(1);
+ r.view = opened.view;
+ r.confirm(opened.unit);
+ r.settle();
+ try agrees(a, r);
+ var prng: std.Random.DefaultPrng = .init(seed);
+ const rand = prng.random();
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ for (0..150) |_| {
+ const rect = a.core.views[r.view].?.rects[id];
+ const at = .{ .col = rect.x + 10, .row = rect.y + rect.h / 2 };
+ const ev: pardes.Event = switch (rand.uintLessThan(u8, 10)) {
+ 0 => .{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = at.col, .row = at.row } },
+ 1 => .{ .mouse = .{ .button = .wheel_up, .kind = .press, .col = at.col, .row = at.row } },
+ else => .{ .key = keys[rand.uintLessThan(usize, keys.len)] },
+ };
+ if (rand.boolean()) {
+ const drew = Stepping.begin(&a.t, null);
+ defer drew.end();
+ _ = arena.reset(.retain_capacity);
+ _ = try a.core.render(arena.allocator());
+ }
+ if (rand.uintLessThan(u8, 4) == 0) _ = r.draw(.{ .ctx = null, .f = null });
+ if (rand.uintLessThan(u8, 3) == 0) {
+ // The session's own key, then nothing of the client's.
+ r.confirm(try a.local(.{ .key = keys[rand.uintLessThan(usize, keys.len)] }));
+ r.settle();
+ } else {
+ const m = try gpa.dupe(u8, try r.input(ev));
+ defer gpa.free(m);
+ // Sometimes the session's own key first: the client's
+ // applied at once is rolled back and replayed.
+ if (rand.uintLessThan(u8, 3) == 0) {
+ r.confirm(try a.local(.{ .key = keys[rand.uintLessThan(usize, keys.len)] }));
+ r.settle();
+ }
+ r.confirm(try a.take(m));
+ r.settle();
+ }
+ agrees(a, r) catch |err| {
+ std.debug.print("seed {d}: diverged\n", .{seed});
+ return err;
+ };
+ }
+ }
+}
+
/// Seeds of the explorer below a run of the suite takes; 3,000 were run
/// once (reports/pardes-term-join-10.md).
const view_orders = 30;
@@ -6461,6 +6627,45 @@ test "a kind's place moved in a step of another view's: a replica's key that rea
try agrees(a, r);
}
+/// Placed, plain (PA_PLAIN): a client runs it, and its state is the rows
+/// its last view was told.
+const Viewed = struct {
+ const pa = pardes.Kind.c;
+ const words = [_]pa.pa_word{std.mem.zeroInit(pa.pa_word, .{ .name = "Viewed", .opens = 1, .doc = "the rows its view was told" })};
+ const ops = std.mem.zeroInit(pardes.Kind.Ops, .{
+ .head = std.mem.zeroInit(pa.pa_head, .{ .size = @sizeOf(pa.pa_head), .abi = pardes.Kind.abi, .name = "viewed".* ++ @as([10]u8, @splat(0)), .version = 1, .exts = "", .flags = pa.PA_PLAIN, .words = &words, .nwords = 1 }),
+ .open = Placed.open,
+ .paint = Placed.paint,
+ .view = Placed.view,
+ });
+};
+
+test "a client joins with its session's geometry as the session holds it: the view opened for it, not laid out yet, is not laid out in the client either, and a plain kind is told the same views on both" {
+ // The soak's (test/replicas.zig): a client parted at its first unit
+ // after its join, `addon pdf: its state after view is not the
+ // session's`: it had laid every view out at its load, its own new one
+ // too, which the session lays out at that view's first input.
+ const gpa = std.testing.allocator;
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host());
+ defer a.deinit();
+ var words: [64]pardes.Kind.LoadedWord = undefined;
+ const viewed = pardes.Kind.loadedOf(&Viewed.ops, "/x/viewed.so", @splat(7), &words);
+ _ = try a.local(.{ .addon = .{ .op = .load, .pane = .at(0), .kind = &viewed } });
+ _ = try a.local(.{ .command = "Viewed" });
+ const kid = a.core.view().active;
+ const joined = (try a.join(1, null)).?;
+ defer gpa.free(joined.dump);
+ const r = try Replica.initDump(gpa, 1, joined.view, joined.dump, .{ .cols = 80, .rows = 24 });
+ defer r.deinit();
+ try std.testing.expect(r.loaded(joined.digest));
+ try runsHere(r, kid, &Viewed.ops);
+ try std.testing.expectEqual(a.core.views[joined.view].?.rects[kid], r.core().views[joined.view].?.rects[kid]);
+ // The session's own step tells the kind each view whose facts changed.
+ r.confirm(try a.local(.tick));
+ r.settle();
+ try agrees(a, r);
+}
+
/// A kind whose every key asks a job, for the job tokens' test.
const Jobber = struct {
const pa = pardes.Kind.c;
@@ -7172,12 +7377,16 @@ const may_wait = [_]Wait{
.{ .what = "DumpThemes", .on = .any, .stop = "the authority's own state", .why = "the theme files written" },
// A +Preview's text is read from the session's disk.
.{ .what = "Search *", .on = .any, .stop = "preview", .why = "a +Preview's file, from the session's disk" },
+ // jj run in the session's tree (jj.zig `show`, `diffChange`,
+ // `diffPair`): what its repository holds, the session's disk.
+ .{ .what = "At *", .on = .any, .stop = "jj", .why = "a file at a revision, asked of the session's repository" },
// A kind's own state on the session (a PDF's document): asking it.
.{ .what = "*", .on = .addon, .stop = "a kind's search", .why = "a search in a kind's pane: its own state, the session's" },
.{ .what = "*", .on = .addon, .stop = "a kind's address", .why = "a place in a kind's pane (`Look doc.pdf:3`): its own state" },
.{ .what = "*", .on = .addon, .stop = "a kind's close", .why = "a kind's pane closed: its state let go on the session" },
.{ .what = "*", .on = .addon, .stop = "a kind's word", .why = "a word to a kind (a key it takes as one): its own state" },
.{ .what = "*", .on = .addon, .stop = "a kind's open", .why = "a kind's pane opened (`Life`): its state made on the session" },
+ .{ .what = "*", .on = .addon, .stop = "a key into a kind's pane", .why = "a key to a kind this client does not run (no library for it here, or not PA_PLAIN): its state the session's" },
} ++ (if (pardes.builtins.capabilities.font_picker) [_]Wait{
// A window's view's words, which a terminal's build has too: a window
// client of its session runs them.
@@ -7233,7 +7442,7 @@ const walk_samples = [_]struct { []const u8, []const u8 }{
.{ "Msg", "hi" }, .{ "ThemeFile", "t.zon" }, .{ "Edit", "s/a/b/" }, .{ "Mini", "x" },
.{ "Find", "x" }, .{ "Grep", "x" }, .{ "Rename", "x" }, .{ "WsSymbols", "x" },
.{ "Theme", "acme" }, .{ "Font", "Mono 12" }, .{ "TaglineSize", "100" }, .{ "WindowOpacity", "100" },
- .{ "MessageLinger", "1000" }, .{ "InactiveDim", "0" }, .{ "GripWidth", "100" },
+ .{ "MessageLinger", "1000" }, .{ "InactiveDim", "0" }, .{ "GripWidth", "100" }, .{ "At", "@-" },
};
fn keyName(buf: []u8, k: pardes.Key) []const u8 {
diff --git a/core/rollback.zig b/core/rollback.zig
index 61fb7b89..2702594c 100644
--- a/core/rollback.zig
+++ b/core/rollback.zig
@@ -249,7 +249,8 @@ pub const Epoch = struct {
const cut = e.taken.items[w.at..][0..w.cut];
if (w.index) {
const room = @as([*]usize, @ptrFromInt(w.addr))[0..w.room];
- pardes.panes.File.shiftStarts(room, w.len, w.was, w.off, w.ins, cut);
+ // The text's widest is the copy's, put back with it.
+ _ = pardes.panes.File.shiftStarts(room, w.len, w.was, w.off, w.ins, cut);
} else {
const room = @as([*]u8, @ptrFromInt(w.addr))[0..w.room];
const tail = w.len - w.off - w.ins;
diff --git a/core/root.zig b/core/root.zig
index 773c7588..63b77964 100644
--- a/core/root.zig
+++ b/core/root.zig
@@ -748,13 +748,15 @@ const kept_out = [_]struct { []const u8, []const u8, []const u8 }{
.{ "Core.zig", "shell_rows", "a terminal's rows as read here, swept at every update; the terminal's own digest covers its active area, not its history (Term.zig `calls`)" },
.{ "Core.zig", "diff_output locations_cache tty_filter_palette body_chrome", "caches of pure functions of their key (a text, a theme): a step finds what it would make; a query row's colours from them are out of its digest (locations.Row.digest), and what a step asks a worker to paint is never decided by them (Stream.paintRows)" },
.{ "Core.zig", "retired_panes", "panes torn down this step, freed at its end" },
+ .{ "Core.zig", "multi_first multi_stop multi_index multi_count exec_depth exec_column", "a step's own: set by a key's replay across the ranges (normal.replaySels) and a word's run (exec.zig), each put back before the step ends; between steps what `init` makes, so a load takes them as it makes them (a dump's said 2^30 ranges once: a yank sized its register by it)" },
+ .{ "Core.zig", "rects col_x col_w", "a view's geometry: the layout pass's (layout.compute) over its columns and screen, at every sync and resize, and at a load (dump.afterLoad); never read before it" },
.{ "Core.zig", "distrusted frames tape", "Options: the client's own list, its runner's statistics, its tape" },
.{ "Event.zig", "native_image_patches", "what this process's shell can take" },
.{ "panes.zig", "pv pv_known", "the views' shares as this process parks them (views.zig)" },
- .{ "panes.zig", "wrap_line wrap_col wrap_pad wrap_n body_wrapped context_rows body_rows body_visible_rows context_row_limit geometry_key geometry_len", "File.geometry's, made by whoever asks first (a frame or a step) from everything its key hashes of the step's state; a tab change resets the key" },
+ .{ "panes.zig", "wrap_line wrap_col wrap_pad wrap_n body_wrapped context_rows body_rows body_visible_rows context_row_limit geometry_key geometry_len top_skip", "File.geometry's, made by whoever asks first (a frame or a step) from everything its key hashes of the step's state (the tab's width too); top_skip, keyed by the geometry it is of, read only through File.topSkip, which walks one of another key again" },
.{ "panes.zig views.zig", "notices", "made again from the step's state at the top of update and presented, and at sync (Messages.collectNotices); a frame's are its own" },
.{ "panes.zig views.zig", "pan", "written by steps only (sync, a view unparked) from the pane and its terminal" },
- .{ "File.zig", "cap line_starts line_cap", "the text's line index, of its bytes" },
+ .{ "File.zig", "cap line_starts line_cap widest", "the text's line index, of its bytes, and the widest line it found (an upper bound: which walk answers, never what)" },
.{ "File.zig", "highlights highlight_start syntax_dirty", "how a text looks, painted by frames: read by frames, and by a query's rows for colours only (out of their digest; what a step asks a worker to paint is never decided by them, Stream.paintRows)" },
.{ "File.zig", "allocator", "ContextCache's: what its declarations were made with, the parse's or a load's (a machine's handle, no state)" },
.{ "File.zig", "declarations", "ContextCache's: the text's at its revision (dumped, digested), parsed again from the text at a load" },
diff --git a/core/surface.zig b/core/surface.zig
index 5b381958..98696721 100644
--- a/core/surface.zig
+++ b/core/surface.zig
@@ -130,9 +130,11 @@ pub const Region = struct {
/// A notice's index in its pane's `notices`.
notice: u8 = 0,
/// A body's view: the first line it shows (a file's scroll, a
- /// terminal's grid offset), and the text it shows (`draw.place`'s doc:
+ /// terminal's grid offset) and which of that line's wrapped rows its
+ /// first row is (File.Top), and the text it shows (`draw.place`'s doc:
/// 0 for a terminal or a picture), which a frontend's glide follows.
line: i32 = 0,
+ row: u32 = 0,
doc: u64 = 0,
/// A body drawn as a strip of pictures (a PDF): how far down the strip
/// it shows, in pixels. Its placements are laid at the whole pixel; a
diff --git a/core/views.zig b/core/views.zig
index f414eb6c..e5f2038e 100644
--- a/core/views.zig
+++ b/core/views.zig
@@ -63,9 +63,11 @@ pub const PaneView = struct {
follow_scroll: usize = 0,
scrolled_to: ?usize = null,
body: Part(Text, &body_fields) = .{},
- /// A document's scroll and size; a terminal's size is its pty's, which
- /// every view shows (sized by its last typist, `Pardes.sync`).
+ /// A document's scroll (its top: File.Top) and size; a terminal's size
+ /// is its pty's, which every view shows (sized by its last typist,
+ /// `Pardes.sync`).
scroll: usize = 0,
+ scroll_row: u32 = 0,
cols: u16 = 1,
rows: u16 = 1,
@@ -80,6 +82,12 @@ pub const Shares = struct {
k: u8,
panes: []const Share = &.{},
+ /// Its view, a slot (walk.zig `.index`).
+ pub const replica = .{ .index = .{.{ "k", "slots" }} };
+ pub fn slots(_: *const Shares, k: usize) bool {
+ return k < max;
+ }
+
pub const Share = struct { id: u16, pv: PaneView };
};
@@ -252,7 +260,10 @@ fn extract(pane: *const Pane) PaneView {
var v: PaneView = .{ .cols = pane.cols, .rows = pane.rows };
copy(&pane_fields, &v, pane);
copy(&body_fields, &v.body, &pane.body);
- if (pane.file) |f| v.scroll = f.scroll;
+ if (pane.file) |f| {
+ v.scroll = f.scroll;
+ v.scroll_row = f.scroll_row;
+ }
return v;
}
@@ -269,6 +280,7 @@ fn apply(pane: *Pane, v: *const PaneView) void {
// brought back inside it.
const lines = File.nlines(pane.gpa, f);
f.scroll = @min(v.scroll, lines -| 1);
+ f.scroll_row = v.scroll_row;
if (pane.body.cur_row >= lines) {
pane.body.vsel.active = false;
pane.body.nsel = 0;
@@ -552,7 +564,10 @@ pub fn within(p: *Pardes, k: u8, ctx: anytype, comptime f: fn (@TypeOf(ctx), *Pa
pane.cols = pv.cols;
pane.rows = pv.rows;
}
- if (pane.file) |*file| file.scroll = pv.scroll;
+ if (pane.file) |*file| {
+ file.scroll = pv.scroll;
+ file.scroll_row = pv.scroll_row;
+ }
pv.body.sels = &.{};
pv.body.nsel = 0;
};
@@ -883,6 +898,136 @@ test "a view drawn while another is live keeps its own cursors" {
try testing.expectEqual(@as(u16, 1), pane.body.nsel);
}
+test "a view drawn after another view's step moved the top into a long wrapped line, the two alike before it: drawn from its own top, line 0, not from the row the step found in the other's line" {
+ const gpa = testing.allocator;
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
+ defer p.deinit();
+ // A short first line, and line 10 wrapped over more rows than the body.
+ var text: std.ArrayList(u8) = .empty;
+ defer text.deinit(gpa);
+ try text.appendSlice(gpa, "short\n");
+ for (1..10) |i| try text.print(gpa, "line {d}\n", .{i});
+ for (0..500) |w| try text.print(gpa, "w{d:0>4} ", .{w});
+ try text.appendSlice(gpa, "\nlast\n");
+ const pane = try p.setTestFile(text.items);
+ const k = p.openView().?;
+ // View 0's step puts the cursor at line 10's end: the top goes into
+ // that line's rows, a row far past line 0's five bytes. View k is
+ // where view 0 was: its top line 0, its size view 0's.
+ pane.body.cur_row = 10;
+ pane.body.cur_col = @intCast(pardes.panes.File.sourceLine(pane, 10).len - 1);
+ pane.body.cur_pinned = true;
+ pane.ensureCursorVisible(p.settings.tab);
+ p.sync();
+ try testing.expectEqual(@as(usize, 10), pane.file.?.scroll);
+ try testing.expect(pane.file.?.scroll_row > 0);
+ const Seen = struct {
+ short: bool = false,
+ fn present(ctx: ?*anyopaque, s: *const pardes.Surface) bool {
+ const seen: *@This() = @ptrCast(@alignCast(ctx.?));
+ var row: [512]u8 = undefined;
+ for (0..s.rows) |y| {
+ var n: usize = 0;
+ for (s.cells[y * s.cols ..][0..s.cols]) |c| {
+ if (n + c.len > row.len) break;
+ @memcpy(row[n..][0..c.len], c.text[0..c.len]);
+ n += c.len;
+ }
+ if (std.mem.indexOf(u8, row[0..n], "short") != null) seen.short = true;
+ }
+ return true;
+ }
+ };
+ var seen: Seen = .{};
+ _ = try drawOne(p, k.index(), .{ .ctx = &seen, .f = Seen.present });
+ try testing.expect(seen.short);
+}
+
+test "a view's step after another view's step moved the top, the two alike before it: it scrolls from its own top's row, as a core loaded from the session (none of its geometry) does" {
+ const gpa = testing.allocator;
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
+ defer p.deinit();
+ // Line 3 wrapped over several rows, line 10 over more than the body.
+ var text: std.ArrayList(u8) = .empty;
+ defer text.deinit(gpa);
+ for (0..12) |i| switch (i) {
+ 3, 10 => {
+ for (0..@as(usize, if (i == 3) 60 else 500)) |w| try text.print(gpa, "w{d:0>4} ", .{w});
+ try text.append(gpa, '\n');
+ },
+ else => try text.print(gpa, "line {d}\n", .{i}),
+ };
+ const pane = try p.setTestFile(text.items);
+ const f = &pane.file.?;
+ // Both views' top on line 3's third row, the cursor on it.
+ pane.body.cur_row = 3;
+ pane.body.cur_col = 150;
+ f.scroll = 3;
+ f.scroll_row = 2;
+ p.sync();
+ const k = p.openView().?;
+ // View 0's step: the cursor to line 10's end, the top into its rows.
+ pane.body.cur_row = 10;
+ pane.body.cur_col = @intCast(pardes.panes.File.sourceLine(pane, 10).len - 1);
+ pane.body.cur_pinned = true;
+ pane.ensureCursorVisible(p.settings.tab);
+ p.sync();
+ try testing.expect(f.scroll == 10 and f.scroll_row > 2);
+ // The session as a client joining it loads it: no geometry made.
+ const bytes = try pardes.dump.dumpBytes(p);
+ defer gpa.free(bytes);
+ const loaded = try pardes.dump.load(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }, bytes, null);
+ defer loaded.deinit();
+ // View k's PageDown in each, from line 3's third row.
+ for ([_]*Pardes{ p, loaded }) |core| {
+ core.toView(k);
+ core.update(.{ .key = .{ .cp = pardes.Key.page_down } });
+ }
+ const lf = &loaded.panes[0].?.file.?;
+ try testing.expectEqual(lf.scroll, f.scroll);
+ try testing.expectEqual(lf.scroll_row, f.scroll_row);
+}
+
+test "a view's top on a wrapped line's third row, the line taken out by another view and the next one empty: its top row past its line's, read as its last, and the session's dump loads as the session" {
+ const gpa = testing.allocator;
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
+ defer p.deinit();
+ var text: std.ArrayList(u8) = .empty;
+ defer text.deinit(gpa);
+ for (0..30) |i| switch (i) {
+ 3 => {
+ for (0..60) |w| try text.print(gpa, "w{d:0>4} ", .{w});
+ try text.append(gpa, '\n');
+ },
+ 4 => try text.append(gpa, '\n'),
+ else => try text.print(gpa, "line {d}\n", .{i}),
+ };
+ const pane = try p.setTestFile(text.items);
+ const f = &pane.file.?;
+ // View k: its top on line 3's third row, its cursor well inside the body.
+ pane.body.cur_row = 10;
+ f.scroll = 3;
+ f.scroll_row = 2;
+ p.sync();
+ const k = p.openView().?;
+ // View 0 takes line 3 out: view k's top line is the empty one after it.
+ cursorTo(p, pane, 3);
+ typeKeys(p, "xd");
+ p.toView(k);
+ // A step of view k's own: its cursor inside the band, its top kept.
+ escape(p);
+ try testing.expectEqual(@as(usize, 3), f.scroll);
+ try testing.expectEqual(@as(usize, 0), pardes.panes.File.sourceLine(pane, 3).len);
+ try testing.expectEqual(@as(u32, 2), f.scroll_row);
+ try testing.expectEqual(pardes.panes.File.Top{ .line = 3, .row = 0 }, pardes.panes.File.top(p.settings.tab, pane));
+ // A client joining loads the session's dump as the session.
+ const bytes = try pardes.dump.dumpBytes(p);
+ defer gpa.free(bytes);
+ const loaded = try pardes.dump.load(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }, bytes, null);
+ defer loaded.deinit();
+ try testing.expectEqual(pardes.walk.digest(Pardes, p), pardes.walk.digest(Pardes, loaded));
+}
+
test "a view not live keeps its place in a text another view edits" {
const gpa = testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
diff --git a/core/walk.zig b/core/walk.zig
index 5e91490c..7a77fdb6 100644
--- a/core/walk.zig
+++ b/core/walk.zig
@@ -257,14 +257,270 @@ fn pastHeld(comptime T: type, v: *const T, held: ?*const [pairs(T)]usize) ?Past
return null;
}
-/// Every name an annotation gives is a field: a rename cannot quietly put
-/// a field back in the digest.
+// ---- an index read back is held to what it names ----
+//
+// A field that NAMES one of the things a session holds (a view by its slot,
+// a pane by its) says what, beside it, as a length says its buffer; a field
+// that says WHERE in a thing it is (a scroll, a row), the thing's last place:
+//
+// pub const replica = .{
+// // One of the slots field `views` has (as many as it holds), or one
+// // a predicate of the struct says is there (`fn (*const T, usize)
+// // bool`); a third word, one of the things of the struct named
+// // second that holds this one (held where ITS fields end, every
+// // value of this type it holds); a fourth, the field counting a
+// // span of them from it (all within the field named third).
+// .index = .{ .{ "sized_by", Pardes, "views" }, .{ "live", "openViews" }, .{ "first", Journal, "entries", "n" } },
+// // Its last place, a function of the struct (`fn (*const T) usize`),
+// // or its first and last (`[2]usize`).
+// .place = .{ .{ "scroll", "lastLine" } },
+// // Where each of its entries (as far as its length says) may be,
+// // a predicate of the struct by the entry's place in the field
+// // (`fn (*const T, usize) bool`): a view's rects on its screen.
+// .within = .{ .{ "rects", "onScreen" } },
+// // What a load that left one of its things out (another build's
+// // pane) does to what names it (`fn (*T) void`), before its indexes
+// // are held.
+// .left_out = "dropMissing",
+// };
+//
+// A value read back (a tape, a dump, an image: bytes from another process or
+// the disk) is held to them where its fields end, beside its lengths
+// (`pastHeld`), every declaration of every type at once: an index that names
+// none is REFUSED, its field named (the dump is not the session: the view,
+// the pane it names is not there), and so is an entry that is not where it
+// may be (no session's: a rect past its screen); a place past its thing's
+// last is that LAST (the session is there, its view a line off). A field
+// that names a slot by its type (`Pane.Id`, `View.Id`) and says nothing is
+// a compile error (`checkSlots`); a bare integer that does is found by
+// reading, as the lengths' were, until it is typed as its slot.
+
+fn declared(comptime T: type, comptime kind: []const u8) usize {
+ return if (@hasDecl(T, "replica") and @hasField(@TypeOf(T.replica), kind)) @field(T.replica, kind).len else 0;
+}
+
+/// An index read back that names none of what it says it indexes, or
+/// (`within`) the entry `says` of a field that is not where it may be.
+const Unnamed = struct { holder: []const u8, name: []const u8, says: usize, of: []const u8, within: bool = false };
+
+/// What an index field says, as a number: an integer, an optional one's (null
+/// names nothing), a slot's enum's (`Pane.Id`).
+fn number(comptime F: type, v: F) ?usize {
+ return switch (@typeInfo(F)) {
+ .int => std.math.cast(usize, v) orelse std.math.maxInt(usize),
+ .optional => |o| if (v) |x| number(o.child, x) else null,
+ .@"enum" => |e| number(e.tag_type, @backingInt(v)),
+ else => @compileError("walk: an `index` names a thing by a number, not " ++ @typeName(F)),
+ };
+}
+
+/// How many of field `name`'s elements `v` holds: as far as its length says.
+fn heldOf(comptime T: type, v: *const T, comptime name: []const u8) usize {
+ const all = &@field(v, name);
+ if (comptime isList(@TypeOf(all.*))) return all.items.len;
+ return if (comptime lengthOf(T, name)) |len| @min(lengthIn(v, len), all.len) else all.len;
+}
+
+/// Whether `h` has the thing `i` names by `what`: a field of it (one of its
+/// slots), or a predicate of it.
+fn hasThing(comptime H: type, h: *const H, comptime what: []const u8, i: usize) bool {
+ if (comptime @hasField(H, what)) {
+ return i < heldOf(H, h, what);
+ } else return @field(H, what)(h, i);
+}
+
+/// The first number field `name` of `u` says (each of an array as far as its
+/// length says) that names no thing of `h`'s by `what`.
+fn firstUnnamed(comptime U: type, u: *const U, comptime name: []const u8, comptime H: type, h: *const H, comptime what: []const u8) ?usize {
+ const F = @FieldType(U, name);
+ if (comptime @typeInfo(F) == .array) {
+ for (@field(u, name)[0..heldOf(U, u, name)]) |e| if (number(@typeInfo(F).array.child, e)) |i| if (!hasThing(H, h, what, i)) return i;
+ return null;
+ }
+ const i = number(F, @field(u, name)) orelse return null;
+ return if (hasThing(H, h, what, i)) null else i;
+}
+
+/// `at` held to `[first, last]`: a place past its thing's last is that last.
+fn clampTo(comptime F: type, at: *F, first: usize, last: usize) void {
+ switch (@typeInfo(F)) {
+ .int => if (at.* > last) {
+ at.* = @intCast(last);
+ } else if (at.* < first) {
+ at.* = @intCast(first);
+ },
+ .optional => |o| if (at.*) |*x| clampTo(o.child, x, first, last),
+ else => @compileError("walk: a `place` is a number, not " ++ @typeName(F)),
+ }
+}
+
+/// The types `T`'s value holds whose indexes name `T`'s things (a third word
+/// `T`): held where `T`'s fields end.
+fn heldIn(comptime T: type) []const type {
+ comptime {
+ if (!@hasDecl(T, "replica")) return &.{};
+ var out: []const type = &.{};
+ for (graph(&.{T})) |U| if (@typeInfo(U) == .@"struct") for (0..declared(U, "index")) |k| {
+ const d = U.replica.index[k];
+ if (d.len >= 3) if (d[1] == T) {
+ out = out ++ .{U};
+ break;
+ };
+ };
+ return out;
+ }
+}
+
+/// Whether a value of `X` can hold a `U`, as a dump walks it.
+fn reaches(comptime X: type, comptime U: type) bool {
+ comptime {
+ @setEvalBranchQuota(100_000_000);
+ return switch (kindOf(Canon(X))) {
+ .@"struct", .optional, .one, .slice, .array, .@"union" => for (graph(&.{Canon(X)})) |Y| {
+ if (Y == U) break true;
+ } else false,
+ else => false,
+ };
+ }
+}
+
+/// `v`'s places held to their things' last, then the first of its indexes,
+/// and of every value it holds whose indexes name its things, that names
+/// none (see above).
+fn heldIndexes(comptime T: type, v: *T) ?Unnamed {
+ inline for (0..comptime declared(T, "place")) |k| {
+ const d = T.replica.place[k];
+ const held = @field(T, d[1])(v);
+ const span: [2]usize = if (@TypeOf(held) == usize) .{ 0, held } else held;
+ clampTo(@FieldType(T, d[0]), &@field(v, d[0]), span[0], span[1]);
+ }
+ inline for (0..comptime declared(T, "index")) |k| {
+ const d = T.replica.index[k];
+ if (comptime d.len == 2) if (firstUnnamed(T, v, d[0], T, v, d[1])) |i|
+ return .{ .holder = @typeName(T), .name = d[0], .says = i, .of = @typeName(T) ++ "." ++ d[1] };
+ }
+ inline for (0..comptime declared(T, "within")) |k| {
+ const d = T.replica.within[k];
+ for (0..heldOf(T, v, d[0])) |i| if (!@field(T, d[1])(v, i))
+ return .{ .holder = @typeName(T), .name = d[0], .says = i, .of = @typeName(T) ++ "." ++ d[1], .within = true };
+ }
+ inline for (comptime heldIn(T)) |U| if (visit(T, v, U, T, v, 0)) |bad| return bad;
+ return null;
+}
+
+/// Every `U` that `x` holds (its fields as a dump walks them, as far as each
+/// length says; optionals, arrays, slices, lists, unions and pointers
+/// followed), its indexes into `h`'s things held; the first that names none.
+/// A value nested past `max_depth` (a pointer that is its own holder: a
+/// damaged dump's) is refused too.
+fn visit(comptime X: type, x: *const X, comptime U: type, comptime H: type, h: *const H, depth: u16) ?Unnamed {
+ if (comptime !reaches(X, U)) return null;
+ if (depth == max_depth) return .{ .holder = @typeName(X), .name = "", .says = depth, .of = "a depth a session's values nest to" };
+ if (X == U) inline for (0..comptime declared(U, "index")) |k| {
+ const d = U.replica.index[k];
+ if (comptime d.len >= 3) if (comptime d[1] == H) {
+ const of = @typeName(H) ++ "." ++ d[2];
+ if (comptime d.len == 3) {
+ if (firstUnnamed(U, x, d[0], H, h, d[2])) |i| return .{ .holder = @typeName(U), .name = d[0], .says = i, .of = of };
+ } else {
+ // A span: as many as its count says from it, all there (an
+ // empty one may stand at their end).
+ const end = @as(usize, @field(x, d[0])) +| @field(x, d[3]);
+ if (end > heldOf(H, h, d[2])) return .{ .holder = @typeName(U), .name = d[0], .says = @field(x, d[0]), .of = of };
+ }
+ };
+ };
+ switch (@typeInfo(X)) {
+ .optional => |o| if (x.*) |*c| return visit(o.child, c, U, H, h, depth + 1),
+ .array => |a| for (x) |*e| if (visit(a.child, e, U, H, h, depth + 1)) |bad| return bad,
+ .pointer => |p| switch (p.size) {
+ .one => return visit(p.child, x.*, U, H, h, depth + 1),
+ .slice => for (x.*) |*e| if (visit(p.child, e, U, H, h, depth + 1)) |bad| return bad,
+ else => {},
+ },
+ .@"struct" => {
+ if (comptime isAtomic(X)) return visit(@FieldType(X, "raw"), &x.raw, U, H, h, depth + 1);
+ if (comptime isList(X)) return visit(@FieldType(X, "items"), &x.items, U, H, h, depth + 1);
+ inline for (comptime dumpFields(X)) |name| {
+ const F = @FieldType(X, name);
+ if (comptime reaches(F, U)) {
+ if (comptime lengthOf(X, name) != null) {
+ for (@field(x, name)[0..heldOf(X, x, name)]) |*e| if (visit(Element(F), e, U, H, h, depth + 1)) |bad| return bad;
+ } else if (visit(F, &@field(x, name), U, H, h, depth + 1)) |bad| return bad;
+ }
+ }
+ },
+ .@"union" => switch (x.*) {
+ inline else => |*payload| return visit(@TypeOf(payload.*), payload, U, H, h, depth + 1),
+ },
+ else => {},
+ }
+ return null;
+}
+
+/// `out`'s lengths held to what their buffers hold as read (`pastHeld`), and
+/// its indexes to what they name (`heldIndexes`), where a reader (`Loader`,
+/// `Get`) has read its fields: the dump refused, the field named. One that
+/// left a thing out since `dropped` (another build's pane) first has `T`'s
+/// `left_out` take out what names it.
+fn holdTo(l: anytype, comptime T: type, out: *T, held: *const [pairs(T)]usize, dropped: usize) error{BadDump}!void {
+ if (pastHeld(T, out, held)) |past| {
+ l.note("{s}.{s} says {d}, past the {d} its buffer holds: refused", .{ @typeName(T), past.name, past.says, past.holds });
+ return error.BadDump;
+ }
+ if (comptime @hasDecl(T, "replica")) if (comptime @hasField(@TypeOf(T.replica), "left_out")) if (l.dropped != dropped) @field(T, T.replica.left_out)(out);
+ if (heldIndexes(T, out)) |bad| {
+ if (bad.within)
+ l.note("{s}.{s}[{d}] is not within {s}: refused", .{ bad.holder, bad.name, bad.says, bad.of })
+ else
+ l.note("{s}.{s} says {d}, which names none of {s}: refused", .{ bad.holder, bad.name, bad.says, bad.of });
+ return error.BadDump;
+ }
+}
+
+/// A slot's type (`Pane.Id`, `View.Id`: an enum that is `at` a slot and
+/// gives its `index`), bare, optional or in an array.
+fn isSlot(comptime F: type) bool {
+ return switch (@typeInfo(F)) {
+ .optional => |o| isSlot(o.child),
+ .array => |a| isSlot(a.child),
+ .@"enum" => @hasDecl(F, "at") and @hasDecl(F, "index"),
+ else => false,
+ };
+}
+
+/// A field a dump carries that names a slot by its type says what it
+/// indexes (`.index`): a compile error otherwise, so that one added later
+/// is held where it is read back.
+fn checkSlots(comptime T: type) void {
+ for (dumpFields(T)) |name| if (isSlot(@FieldType(T, name))) {
+ for (0..declared(T, "index")) |k| {
+ if (std.mem.eql(u8, T.replica.index[k][0], name)) break;
+ } else @compileError("walk: " ++ @typeName(T) ++ "." ++ name ++ " names a slot: say what it indexes (`replica.index`)");
+ };
+}
+
+/// Every name an annotation gives is a field (and what an index or a place
+/// says it is held to, a field or a function): a rename cannot quietly put a
+/// field back in the digest, nor take one out of its rule.
fn checkAnnotations(comptime T: type) void {
if (!@hasDecl(T, "replica")) return;
inline for (@typeInfo(@TypeOf(T.replica)).@"struct".field_names) |kind| {
+ if (comptime std.mem.eql(u8, kind, "left_out")) {
+ if (!@hasDecl(T, T.replica.left_out)) @compileError("walk: " ++ @typeName(T) ++ " has no " ++ T.replica.left_out ++ " for what a load left out");
+ continue;
+ }
inline for (@field(T.replica, kind)) |entry| {
- const name = if (comptime std.mem.eql(u8, kind, "len") or std.mem.eql(u8, kind, "alloc")) entry[0] else entry;
+ const held = comptime std.mem.eql(u8, kind, "index") or std.mem.eql(u8, kind, "place") or std.mem.eql(u8, kind, "within");
+ const pair = comptime held or std.mem.eql(u8, kind, "len") or std.mem.eql(u8, kind, "alloc");
+ const name = if (pair) entry[0] else entry;
if (!@hasField(T, name)) @compileError("walk: " ++ @typeName(T) ++ " annotates no field " ++ name);
+ if (held) {
+ const H = if (entry.len >= 3) entry[1] else T;
+ const what = if (entry.len >= 3) entry[2] else entry[1];
+ if (entry.len == 4) if (!@hasField(T, entry[3])) @compileError("walk: " ++ @typeName(T) ++ " counts its span by no field " ++ entry[3]);
+ if (!@hasField(H, what) and !@hasDecl(H, what)) @compileError("walk: " ++ @typeName(T) ++ "." ++ name ++ " is held to " ++ what ++ ", which " ++ @typeName(H) ++ " has not");
+ }
}
}
}
@@ -632,7 +888,7 @@ pub fn decode(comptime T: type, r: *Reader, a: std.mem.Allocator) TapeError!T {
try decodeError(F, r, &@field(out, name));
} else @field(out, name) = try decode(F, r, a);
}
- if (pastHeld(T, &out, null) != null) return error.BadTape;
+ if (pastHeld(T, &out, null) != null or heldIndexes(T, &out) != null) return error.BadTape;
return out;
},
.@"union" => |u| {
@@ -816,7 +1072,10 @@ fn collect(comptime T: type, comptime list: []const type) []const type {
comptime {
for (list) |U| if (U == T) return list;
var out: []const type = list ++ .{T};
- if (kindOf(T) == .@"struct") checkAnnotations(T);
+ if (kindOf(T) == .@"struct") {
+ checkAnnotations(T);
+ checkSlots(T);
+ }
for (children(T)) |C| out = collect(C, out);
return out;
}
@@ -1139,8 +1398,11 @@ fn countOf(n: u64) DecodeError!usize {
}
/// An allocation a load made: what a reference to it finds, and what a
-/// failed load frees.
-const Made = struct { bytes: []u8, alignment: std.mem.Alignment, gpa: std.mem.Allocator, dead: bool = false };
+/// failed load frees. `of`: what it holds (`typeWord` of its element); a
+/// reference read back is to a value of its own type, or the dump is
+/// refused (a damaged one would have one type's bytes read as another's,
+/// pointers and all).
+const Made = struct { bytes: []u8, alignment: std.mem.Alignment, gpa: std.mem.Allocator, dead: bool = false, of: u64 = 0 };
/// How far a reader had made things before a value: what that value made
/// is everything after it (`letGo`).
@@ -1203,6 +1465,8 @@ pub const Loader = struct {
filled: usize = 0,
/// How deep `skip` is in the dump's own types.
depth: u16 = 0,
+ /// How many things (a session's panes) it left out (`holdTo`).
+ dropped: usize = 0,
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) };
@@ -1248,8 +1512,8 @@ pub const Loader = struct {
}
}
- 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 });
+ fn made(l: *Self, bytes: []u8, alignment: std.mem.Alignment, of: u64) DecodeError!usize {
+ try l.shared.append(l.own, .{ .bytes = bytes, .alignment = alignment, .gpa = l.gpa, .of = of });
return l.shared.items.len - 1;
}
@@ -1348,6 +1612,11 @@ pub const Loader = struct {
/// The next root, made: what it points at is `gpa`'s.
pub fn get(l: *Self, comptime T: type) DecodeError!T {
+ // A root that fails lets go of what it had made: its caller's books
+ // (a load's, cut back past what it frees itself) never hold half
+ // of a value.
+ const at = l.mark();
+ errdefer l.letGo(at);
var out: T = undefined;
try l.fresh(T, &out);
try l.value(T, try l.root(), &out);
@@ -1489,12 +1758,12 @@ pub const Loader = struct {
},
.one => {
const C = @typeInfo(T).pointer.child;
- if (try l.ref()) |again| {
+ if (try l.ref(C)) |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| {
+ const at = l.made(std.mem.asBytes(one), .of(C), typeWord(C)) catch |err| {
l.gpa.destroy(one);
return err;
};
@@ -1548,6 +1817,10 @@ pub const Loader = struct {
.bitset => {
const bits = try l.bitCount();
out.* = try .initEmpty(l.gpa, bits);
+ l.customs.append(l.own, .{ .ptr = out, .gpa = l.gpa, .free = @ptrCast(&Bits(T).free) }) catch |err| {
+ out.deinit(l.gpa);
+ return err;
+ };
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)));
},
@@ -1556,22 +1829,23 @@ pub const Loader = struct {
/// 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 {
+ fn ref(l: *Self, comptime E: type) 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;
+ if (got.of != typeWord(E)) return error.BadDump;
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))];
+ if (try l.ref(E)) |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 - l.at) return error.EndOfDump;
const many = try l.gpa.alloc(E, n);
- const at = l.made(std.mem.sliceAsBytes(many), .of(E)) catch |err| {
+ const at = l.made(std.mem.sliceAsBytes(many), .of(E), typeWord(E)) catch |err| {
l.gpa.free(many);
return err;
};
@@ -1616,6 +1890,7 @@ pub const Loader = struct {
if (droppable) {
l.letGo(before);
out[i] = null;
+ l.dropped += 1;
l.note("{s}[{d}] left out", .{ l.field, i });
} else failed = true;
};
@@ -1628,6 +1903,7 @@ pub const Loader = struct {
const packed_struct = comptime @typeInfo(T).@"struct".layout == .@"packed";
const outer = l.field;
defer l.field = outer;
+ const dropped = l.dropped;
// How far each array a length cuts was read: none yet (one read in
// place holds what it held).
var held: [pairs(T)]usize = @splat(if (existing) std.math.maxInt(usize) else 0);
@@ -1638,7 +1914,7 @@ pub const Loader = struct {
try l.oneField(T, field, s.fields[k].ty, out, packed_struct, existing);
if (comptime pairAt(T, field)) |i| held[i] = l.filled;
}
- return l.heldTo(T, out, &held);
+ return holdTo(l, T, out, &held, dropped);
}
var found: std.StaticBitSet(@max(1, names.len)) = .empty;
var failed = false;
@@ -1682,15 +1958,7 @@ pub const Loader = struct {
}
};
if (failed) return error.Incompatible;
- return l.heldTo(T, out, &held);
- }
-
- /// `out`'s lengths held to what their buffers hold as read (`pastHeld`):
- /// the dump refused, the length named.
- fn heldTo(l: *Self, comptime T: type, out: *const T, held: *const [pairs(T)]usize) DecodeError!void {
- const past = pastHeld(T, out, held) orelse return;
- l.note("{s}.{s} says {d}, past the {d} its buffer holds: refused", .{ @typeName(T), past.name, past.says, past.holds });
- return error.BadDump;
+ return holdTo(l, T, out, &held, dropped);
}
fn oneField(l: *Self, comptime T: type, comptime field: []const u8, ty: u32, out: *T, comptime packed_struct: bool, existing: bool) DecodeError!void {
@@ -1735,14 +2003,14 @@ pub const Loader = struct {
.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");
+ _ = try l.made(&.{}, .@"1", 0);
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");
+ _ = try l.made(&.{}, .@"1", 0);
l.shared.items[l.shared.items.len - 1].dead = true;
}
try l.skipMany(s.child, n);
@@ -1777,6 +2045,16 @@ pub const Loader = struct {
}
};
+/// A bitset a load made, freed as a `dumpRead`'s value is (`customs`) when
+/// the load fails or what held it is let go: its words are no `made` slice.
+fn Bits(comptime T: type) type {
+ return struct {
+ fn free(b: *T, gpa: std.mem.Allocator) void {
+ b.deinit(gpa);
+ }
+ };
+}
+
/// `out` as a new `T` is before a load reads its fields: each field's
/// default, an allocator `gpa`.
fn freshOf(comptime T: type, out: *T, gpa: std.mem.Allocator) void {
@@ -2067,6 +2345,8 @@ pub const Get = struct {
allocs: Allocators = .{},
/// How many elements the last array read holds (`pastHeld`).
filled: usize = 0,
+ /// How many things (a session's panes) it left out (`holdTo`).
+ dropped: usize = 0,
const Cursor = Mem.Cursor(.read_only);
pub const Error = error{ BadDump, Incompatible, OutOfMemory };
@@ -2119,6 +2399,9 @@ pub const Get = struct {
/// The value at `c`, made: what it points at is `gpa`'s.
pub fn get(l: *Get, comptime T: type, c: Cursor) Error!T {
+ // As `Loader.get`: a value that fails leaves nothing made.
+ const at = l.mark();
+ errdefer l.letGo(at);
var out: T = undefined;
try l.fresh(T, &out);
try l.value(T, c, &out);
@@ -2170,8 +2453,8 @@ pub const Get = struct {
/// An allocation made for the value at `slot`, kept: what a value met
/// again is, and what `rollback` frees.
- fn keep(l: *Get, bytes: []u8, alignment: std.mem.Alignment, slot: xitdb.Slot) Error!usize {
- try l.made.append(l.own, .{ .bytes = bytes, .alignment = alignment, .gpa = l.gpa });
+ fn keep(l: *Get, bytes: []u8, alignment: std.mem.Alignment, slot: xitdb.Slot, of: u64) Error!usize {
+ try l.made.append(l.own, .{ .bytes = bytes, .alignment = alignment, .gpa = l.gpa, .of = of });
const at = l.made.items.len - 1;
// Not kept after all: the caller frees it.
if (placed(slot)) l.memo.put(l.own, slotWord(slot), at) catch |err| {
@@ -2182,13 +2465,14 @@ pub const Get = struct {
}
/// The value made before for the same place, when there was one.
- fn again(l: *Get, slot: xitdb.Slot) Error!?[]u8 {
+ fn again(l: *Get, slot: xitdb.Slot, comptime E: type) Error!?[]u8 {
if (!placed(slot)) return null;
const at = l.memo.get(slotWord(slot)) orelse return null;
// Made, then let go of by the reader's caller (a dump's mounts).
if (at >= l.made.items.len) return null;
const m = l.made.items[at];
if (m.dead) return error.Incompatible;
+ if (m.of != typeWord(E)) return error.BadDump;
return m.bytes;
}
@@ -2268,12 +2552,12 @@ pub const Get = struct {
},
.one => {
const C = @typeInfo(T).pointer.child;
- if (try l.again(slot)) |bytes| {
+ if (try l.again(slot, C)) |bytes| {
out.* = @ptrCast(@alignCast(bytes.ptr));
return;
}
const one = try l.gpa.create(C);
- const at = l.keep(std.mem.asBytes(one), .of(C), slot) catch |err| {
+ const at = l.keep(std.mem.asBytes(one), .of(C), slot, typeWord(C)) catch |err| {
l.gpa.destroy(one);
return err;
};
@@ -2328,6 +2612,10 @@ pub const Get = struct {
const words = (bits + @bitSizeOf(usize) - 1) / @bitSizeOf(usize);
if (got.value.len != 8 + words * @sizeOf(usize)) return error.BadDump;
out.* = try .initEmpty(l.gpa, bits);
+ l.customs.append(l.own, .{ .ptr = out, .gpa = l.gpa, .free = @ptrCast(&Bits(T).free) }) catch |err| {
+ out.deinit(l.gpa);
+ return err;
+ };
if (words > 0) @memcpy(std.mem.sliceAsBytes(out.masks[0..words]), got.value[8..]);
},
}
@@ -2399,7 +2687,7 @@ pub const Get = struct {
/// A slice of `E` at `c`: numbers' bytes, a blob's text by its hash, or
/// a list; one met again is the same.
fn slice(l: *Get, comptime E: type, c: Cursor, slot: xitdb.Slot) Error![]E {
- if (try l.again(slot)) |bytes| return @as([*]E, @ptrCast(@alignCast(bytes.ptr)))[0 .. bytes.len / @max(1, @sizeOf(E))];
+ if (try l.again(slot, E)) |bytes| return @as([*]E, @ptrCast(@alignCast(bytes.ptr)))[0 .. bytes.len / @max(1, @sizeOf(E))];
if (comptime numbers(E)) {
switch (slot.tag) {
.bytes, .short_bytes => {},
@@ -2417,7 +2705,7 @@ pub const Get = struct {
l.gpa.free(got.bytes);
return &.{};
}
- _ = l.keep(got.bytes, .@"1", slot) catch |err| {
+ _ = l.keep(got.bytes, .@"1", slot, typeWord(u8)) catch |err| {
l.gpa.free(got.bytes);
return err;
};
@@ -2429,7 +2717,7 @@ pub const Get = struct {
const n = got.bytes.len / width;
if (n == 0) return &.{};
const many = try l.gpa.alloc(E, n);
- const at = l.keep(std.mem.sliceAsBytes(many), .of(E), slot) catch |err| {
+ const at = l.keep(std.mem.sliceAsBytes(many), .of(E), slot, typeWord(E)) catch |err| {
l.gpa.free(many);
return err;
};
@@ -2446,7 +2734,7 @@ pub const Get = struct {
// sizes nothing.
if (n > (c.db.core.length() catch return error.BadDump) / (@bitSizeOf(xitdb.Slot) / 8)) return error.BadDump;
const many = try l.gpa.alloc(E, n);
- const at = l.keep(std.mem.sliceAsBytes(many), .of(E), slot) catch |err| {
+ const at = l.keep(std.mem.sliceAsBytes(many), .of(E), slot, typeWord(E)) catch |err| {
l.gpa.free(many);
return err;
};
@@ -2467,7 +2755,7 @@ pub const Get = struct {
const at = (texts.getCursor(std.mem.readInt(u256, got.value[0..32], .big)) catch return error.BadDump) orelse return error.BadDump;
const text = at.readBytesAlloc(l.gpa, most(at)) catch |err| return if (err == error.OutOfMemory) error.OutOfMemory else error.BadDump;
const bytes: []u8 = @constCast(text);
- _ = l.keep(bytes, .@"1", slot) catch |err| {
+ _ = l.keep(bytes, .@"1", slot, typeWord(u8)) catch |err| {
l.gpa.free(bytes);
return err;
};
@@ -2508,6 +2796,7 @@ pub const Get = struct {
if (droppable) {
l.letGo(before);
out[i] = null;
+ l.dropped += 1;
l.note("{s}[{d}] left out", .{ l.field, i });
} else failed = true;
};
@@ -2519,6 +2808,7 @@ pub const Get = struct {
const names = comptime dumpFields(T);
const outer = l.field;
defer l.field = outer;
+ const dropped = l.dropped;
const map = Mem.HashMap(.read_only).init(c) catch return error.Incompatible;
var found: std.StaticBitSet(@max(1, names.len)) = .empty;
var failed = false;
@@ -2570,9 +2860,7 @@ pub const Get = struct {
};
};
if (failed) return error.Incompatible;
- const past = pastHeld(T, out, &held) orelse return;
- l.note("{s}.{s} says {d}, past the {d} its buffer holds: refused", .{ @typeName(T), past.name, past.says, past.holds });
- return error.BadDump;
+ return holdTo(l, T, out, &held, dropped);
}
fn oneField(l: *Get, comptime T: type, comptime field: []const u8, c: Cursor, out: *T, existing: bool) Error!void {
@@ -2884,6 +3172,165 @@ test "a length past what its buffer holds is refused where it is read back (a ta
try std.testing.expectError(error.BadDump, get.get(Room, (try Get.member(root, "room")).?));
}
+test "an index read back that names none of its things is refused, its field named, in a tape, a dump and an image, and so is an entry not where it may be; a place past its thing's last is that last" {
+ const S = struct {
+ const Self = @This();
+ const Inner = struct {
+ at: u8 = 0,
+ list: [3]u8 = @splat(0),
+ n: u8 = 0,
+ // Indexes into the struct holding it, held where its fields end.
+ pub const replica = .{ .len = .{.{ "list", "n" }}, .index = .{ .{ "at", Self, "there" }, .{ "list", Self, "there" } } };
+ };
+ things: [4]?u8 = @splat(null),
+ live: u8 = 0,
+ slot: ?u16 = null,
+ scroll: u32 = 0,
+ inner: [2]?*Inner = @splat(null),
+ edges: [2]u8 = @splat(0),
+ pub const replica = .{ .index = .{ .{ "live", "there" }, .{ "slot", "things" } }, .place = .{.{ "scroll", "last" }}, .within = .{.{ "edges", "inside" }} };
+ pub fn there(s: *const Self, i: usize) bool {
+ return i < s.things.len and s.things[i] != null;
+ }
+ pub fn inside(s: *const Self, i: usize) bool {
+ return s.edges[i] < 8;
+ }
+ pub fn last(_: *const Self) usize {
+ return 9;
+ }
+ };
+ const gpa = std.testing.allocator;
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ const a = arena.allocator();
+ var inner: S.Inner = .{ .at = 2, .list = .{ 0, 2, 1 }, .n = 2 };
+ const good: S = .{ .things = .{ 1, null, 3, null }, .live = 2, .slot = 3, .scroll = 50, .inner = .{ &inner, null } };
+ // Each a value no session has: the field it names.
+ const Bad = struct { []const u8, S };
+ var bad_at: S.Inner = .{ .at = 1 };
+ var bad_list: S.Inner = .{ .list = .{ 0, 3, 0 }, .n = 2 };
+ const bad = [_]Bad{
+ .{ "S.live says 1", blk: {
+ var v = good;
+ v.live = 1;
+ break :blk v;
+ } },
+ .{ "S.slot says 4", blk: {
+ var v = good;
+ v.slot = 4;
+ break :blk v;
+ } },
+ .{ "Inner.at says 1", blk: {
+ var v = good;
+ v.inner[1] = &bad_at;
+ break :blk v;
+ } },
+ .{ "Inner.list says 3", blk: {
+ var v = good;
+ v.inner[1] = &bad_list;
+ break :blk v;
+ } },
+ .{ "S.edges[1] is not within", blk: {
+ var v = good;
+ v.edges = .{ 7, 8 };
+ break :blk v;
+ } },
+ };
+ const n_bad = bad.len;
+ var notes: std.ArrayList(u8) = .empty;
+
+ // A dump.
+ const bytes = try save(S, gpa, &good);
+ defer gpa.free(bytes);
+ const back = try load(S, a, bytes, null);
+ try std.testing.expectEqual(@as(u32, 9), back.scroll);
+ try std.testing.expectEqual(@as(?u16, 3), back.slot);
+ for (bad) |b| {
+ const dumped = try save(S, gpa, &b[1]);
+ defer gpa.free(dumped);
+ notes.clearRetainingCapacity();
+ try std.testing.expectError(error.BadDump, load(S, a, dumped, &notes));
+ try std.testing.expect(std.mem.indexOf(u8, notes.items, b[0]) != null);
+ }
+
+ // A tape.
+ var buf: [256]u8 = undefined;
+ var w: std.Io.Writer = .fixed(&buf);
+ try encode(S, &good, &w);
+ for (bad) |b| try encode(S, &b[1], &w);
+ var r: Reader = .{ .bytes = w.buffered() };
+ try std.testing.expectEqual(@as(u32, 9), (try decode(S, &r, a)).scroll);
+ for (bad) |_| try std.testing.expectError(error.BadTape, decode(S, &r, a));
+
+ // An image.
+ var image: std.Io.Writer.Allocating = .init(gpa);
+ defer image.deinit();
+ var db = try Mem.init(std.Io.failing, .{ .buffer = &image, .file_id = 0 });
+ var put: Put = .{ .gpa = gpa };
+ defer put.deinit();
+ try db.runContext(struct {
+ put: *Put,
+ good: *const S,
+ bad: []const Bad,
+ pub fn run(ctx: @This(), cursor: *Mem.Cursor(.read_write)) !void {
+ const map = try Mem.HashMap(.read_write).init(cursor.*);
+ try ctx.put.member(map, "good", S, ctx.good);
+ inline for (0..n_bad) |i| try ctx.put.member(map, std.fmt.comptimePrint("bad{d}", .{i}), S, &ctx.bad[i][1]);
+ }
+ }{ .put = &put, .good = &good, .bad = &bad });
+ var get: Get = .init(a);
+ defer get.deinit();
+ const root = db.rootCursor().readOnly();
+ try std.testing.expectEqual(@as(u32, 9), (try get.get(S, (try Get.member(root, "good")).?)).scroll);
+ inline for (0..n_bad) |i| {
+ get.notes.clearRetainingCapacity();
+ try std.testing.expectError(error.BadDump, get.get(S, (try Get.member(root, std.fmt.comptimePrint("bad{d}", .{i}))).?));
+ try std.testing.expect(std.mem.indexOf(u8, get.notes.items, bad[i][0]) != null);
+ }
+}
+
+test "a thing another build's dump left out takes what named it with it (`left_out`), before the indexes are held" {
+ const Old = struct {
+ const Thing = struct { n: u32 = 0 };
+ things: [2]?*Thing = @splat(null),
+ at: ?u8 = null,
+ };
+ // A thing whose `n` changed kind, no default: it is left out.
+ const New = struct {
+ const Self = @This();
+ const Thing = struct { n: struct { a: u8 } };
+ things: [2]?*Thing = @splat(null),
+ at: ?u8 = null,
+ pub const replica = .{ .index = .{.{ "at", "there" }}, .left_out = "forget" };
+ pub fn there(s: *const Self, i: usize) bool {
+ return i < s.things.len and s.things[i] != null;
+ }
+ pub fn forget(s: *Self) void {
+ if (s.at) |i| if (!s.there(i)) {
+ s.at = null;
+ };
+ }
+ };
+ const Unforgiving = struct {
+ const Self = @This();
+ things: [2]?*New.Thing = @splat(null),
+ at: ?u8 = null,
+ pub const replica = .{ .index = .{.{ "at", "there" }} };
+ pub fn there(s: *const Self, i: usize) bool {
+ return i < s.things.len and s.things[i] != null;
+ }
+ };
+ const gpa = std.testing.allocator;
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ var one: Old.Thing = .{ .n = 1 };
+ const bytes = try save(Old, gpa, &.{ .things = .{ &one, null }, .at = 0 });
+ defer gpa.free(bytes);
+ const new = try load(New, arena.allocator(), bytes, null);
+ try std.testing.expect(new.things[0] == null and new.at == null);
+ try std.testing.expectError(error.BadDump, load(Unforgiving, arena.allocator(), bytes, null));
+}
+
test "a bitset's count read back is held to the bytes left, read or passed over, in a dump and an image: never a size that overflows" {
const gpa = std.testing.allocator;
const B = struct { bits: std.DynamicBitSetUnmanaged = .{}, after: []const u8 = "" };
diff --git a/core/walk.zig.orig b/core/walk.zig.orig
deleted file mode 100644
index d870052d..00000000
--- a/core/walk.zig.orig
+++ /dev/null
@@ -1,2618 +0,0 @@
-//! The reflective walk over the core's state: one comptime `@typeInfo` walk
-//! that hashes a session into a digest (the replay harness compares two),
-//! encodes values for the tape, and dumps a session for another build to
-//! load by name: into a xitdb database's maps (`Put`, `Get`: a Dump,
-//! Restore, -l, an Upgrade, a handover; Db.zig), or as bytes with a table
-//! of its types (`Dump`, `Load`: a closed pane, the join of phase 5, and
-//! for one release the `.dump` files before). The rollback copy is to walk
-//! the same way (docs/next-daemon.md).
-//!
-//! Values, never addresses: a pointer is followed to what it points at, a
-//! slice is its elements, an ArrayList its items, a hash map its entries in
-//! no order. A type the walk cannot see into (an opaque handle, a function,
-//! an untagged union, a many-pointer) is a compile error naming it, until
-//! the struct that holds it says what the field is:
-//!
-//! pub const replica = .{
-//! // This process's own: presentation, timing, the host's handles
-//! // and caches. A replica has its own and never compares them.
-//! .local = .{ "frames", "surface" },
-//! // Recomputed from the rest whenever it is wanted.
-//! .derived = .{ "wrap_line" },
-//! // Held by the session that performs effects alone.
-//! .authority = .{ "host" },
-//! // A field written only as far as another says: hashed that far.
-//! .len = .{ .{ "jumps", "njumps" } },
-//! // What a field holds is made with another allocator on a load.
-//! .alloc = .{ .{ "image", "image" } },
-//! // Immutable blobs: replaced whole, never written, freed raw
-//! // (memory.freeRaw). A digest hashes each once and
-//! // folds that word in; a replica's rollback copy pins them.
-//! .blob = .{ "content" },
-//! };
-//!
-//! None of the three kinds is in a digest or a dump. A type (a struct or a
-//! tagged union) with a `pub fn digest(*const T, *Hasher) void` of its own
-//! hashes itself; one with
-//! `dumpWrite`, `dumpRead` (and `dumpFree`) dumps itself as bytes.
-const std = @import("std");
-const xitdb = @import("xitdb");
-
-pub const Hasher = std.hash.Wyhash;
-const builtin = @import("builtin");
-
-/// Whether `T.name` holds blobs (`.blob`): a file's text, an undo entry's
-/// bytes, a register's text, a file's location rows.
-pub fn blob(comptime T: type, comptime name: []const u8) bool {
- @setEvalBranchQuota(100_000);
- if (!@hasDecl(T, "replica") or !@hasField(@TypeOf(T.replica), "blob")) return false;
- inline for (T.replica.blob) |n| if (comptime std.mem.eql(u8, n, name)) return true;
- return false;
-}
-
-// ---- a blob in a digest: its length ----
-//
-// A digest walks the whole core at every unit a replica is sent (and every
-// unit a replica replays): a 100 MB file was hashed in full each time, then
-// once and kept as a word by its address while texts were never written in
-// place. A blob of `blob_min` bytes or more is digested as its length now,
-// never its bytes: a file's text says what it holds by its revision
-// (File.State.revision, in the digest), and the other blobs are replaced
-// whole, never written. A smaller one is hashed as any slice is.
-
-const blob_min = 4096;
-threadlocal var in_blob: bool = false;
-
-/// A blob as a digest takes it: its length.
-fn hashBlob(comptime E: type, items: []const E, h: *Hasher) void {
- // The list is the C heap's (a replica client's), which a build with no
- // libc has none of.
- if (comptime builtin.link_libc) if (blobs_out) |list| list.append(std.heap.c_allocator, std.mem.sliceAsBytes(items)) catch {};
- h.update(std.mem.asBytes(&items.len));
-}
-
-/// Where `blobs` notes every blob.
-threadlocal var blobs_out: ?*std.ArrayListUnmanaged([]const u8) = null;
-
-/// Every blob of `v` a digest takes as one (`blob_min` bytes and up), as
-/// its bytes, onto `out` (the C heap's): a replica client's, which knows
-/// its blobs by content (core/replica.zig `Have`).
-pub fn blobs(comptime T: type, v: *const T, out: *std.ArrayListUnmanaged([]const u8)) void {
- blobs_out = out;
- defer blobs_out = null;
- _ = digest(T, v);
-}
-
-pub fn digest(comptime T: type, v: *const T) u64 {
- var h = Hasher.init(0);
- hash(T, v, &h);
- return h.final();
-}
-
-/// A digest of each field `hash` would walk, in order (what a divergence
-/// is narrowed down by); `names` are theirs.
-pub fn fieldDigests(comptime T: type, v: *const T, out: []u64) []u64 {
- var n: usize = 0;
- const s = @typeInfo(T).@"struct";
- inline for (s.field_names, s.field_types, s.field_attrs) |name, F, attr| {
- if (attr.@"comptime" or comptime excluded(T, name)) continue;
- var h = Hasher.init(0);
- const was = in_blob;
- in_blob = comptime blob(T, name);
- defer in_blob = was;
- if (comptime lengthOf(T, name)) |len| {
- hashSlice(Element(F), @field(v, name)[0..lengthIn(v, len)], &h);
- } else hash(F, &@field(v, name), &h);
- out[n] = h.final();
- n += 1;
- }
- return out[0..n];
-}
-
-pub fn fieldNames(comptime T: type) []const []const u8 {
- comptime {
- var names: []const []const u8 = &.{};
- const s = @typeInfo(T).@"struct";
- for (s.field_names, s.field_attrs) |name, attr| {
- if (attr.@"comptime" or excluded(T, name)) continue;
- names = names ++ .{name};
- }
- return names;
- }
-}
-
-/// Types that are machinery, never state: an allocator, the Io, a lock.
-pub fn machinery(comptime T: type) bool {
- inline for (.{ std.mem.Allocator, std.Io, std.Io.Mutex, std.Io.Condition, std.Thread, std.heap.ArenaAllocator }) |M| if (T == M) return true;
- return false;
-}
-
-/// Bytes that are the value whole: no padding, no pointer.
-fn flat(comptime T: type) bool {
- return switch (@typeInfo(T)) {
- .int => @sizeOf(T) * 8 == @bitSizeOf(T),
- .bool => true,
- .@"enum" => |e| @sizeOf(T) * 8 == @bitSizeOf(e.tag_type),
- else => false,
- };
-}
-
-/// A field the walk cannot follow: a pointer to an opaque thing or a
-/// function, or a many-pointer, bare or optional (the struct holding it is
-/// named in the error, not the walk's depth).
-fn opaqueTo(comptime F: type) bool {
- return switch (@typeInfo(F)) {
- .optional => |o| opaqueTo(o.child),
- .pointer => |p| p.size == .many or p.size == .c or switch (@typeInfo(p.child)) {
- .@"opaque", .@"fn" => true,
- else => false,
- },
- else => false,
- };
-}
-
-fn excluded(comptime T: type, comptime name: []const u8) bool {
- @setEvalBranchQuota(100_000);
- if (!@hasDecl(T, "replica")) return false;
- inline for (.{ "local", "derived", "authority" }) |kind| {
- if (@hasField(@TypeOf(T.replica), kind)) inline for (@field(T.replica, kind)) |n| {
- if (comptime std.mem.eql(u8, n, name)) return true;
- };
- }
- return false;
-}
-
-/// What a `len`-cut field holds: a fixed array's, or a slice's room (a
-/// selection's ranges, made once and used `nsel` deep).
-fn Element(comptime F: type) type {
- return switch (@typeInfo(F)) {
- .array => |a| a.child,
- .pointer => |p| p.child,
- else => @compileError("walk: a `len` cuts an array or a slice, not " ++ @typeName(F)),
- };
-}
-
-pub fn lengthIn(v: anytype, comptime len: []const u8) usize {
- const n = @field(v, len);
- return if (@typeInfo(@TypeOf(n)) == .optional) (if (n) |k| k else 0) else n;
-}
-
-/// How far the field `len` names says its array is written (null: none).
-pub fn lengthOf(comptime T: type, comptime name: []const u8) ?[]const u8 {
- @setEvalBranchQuota(100_000);
- if (!@hasDecl(T, "replica") or !@hasField(@TypeOf(T.replica), "len")) return null;
- inline for (T.replica.len) |pair| if (comptime std.mem.eql(u8, pair[0], name)) return pair[1];
- return null;
-}
-
-/// Every name an annotation gives is a field: a rename cannot quietly put
-/// a field back in the digest.
-fn checkAnnotations(comptime T: type) void {
- if (!@hasDecl(T, "replica")) return;
- inline for (@typeInfo(@TypeOf(T.replica)).@"struct".field_names) |kind| {
- inline for (@field(T.replica, kind)) |entry| {
- const name = if (comptime std.mem.eql(u8, kind, "len") or std.mem.eql(u8, kind, "alloc")) entry[0] else entry;
- if (!@hasField(T, name)) @compileError("walk: " ++ @typeName(T) ++ " annotates no field " ++ name);
- }
- }
-}
-
-pub fn hash(comptime T: type, v: *const T, h: *Hasher) void {
- switch (@typeInfo(T)) {
- .void, .null, .undefined => {},
- .bool => h.update(&.{@intFromBool(v.*)}),
- .int => hashInt(T, v.*, h),
- .float => h.update(std.mem.asBytes(v)),
- .@"enum" => hashEnum(T, v.*, h),
- .optional => |o| if (v.*) |*payload| {
- h.update(&.{1});
- hash(o.child, payload, h);
- } else h.update(&.{0}),
- .array => |a| if (comptime flatHash(a.child)) h.update(std.mem.sliceAsBytes(v)) else for (v) |*e| hash(a.child, e, h),
- .pointer => |p| switch (p.size) {
- .one => hash(p.child, v.*, h),
- .slice => hashSlice(p.child, v.*, h),
- else => @compileError("walk: a many-pointer has no length: " ++ @typeName(T)),
- },
- .@"struct" => |s| {
- if (comptime machinery(T)) return;
- if (comptime @hasDecl(T, "digest") and @TypeOf(T.digest) == fn (*const T, *Hasher) void) return v.digest(h);
- if (s.layout == .@"packed") return hashInt(s.backing_integer.?, @bitCast(v.*), h);
- if (comptime isList(T))
- return hashSlice(@typeInfo(@FieldType(T, "items")).pointer.child, v.items, h);
- // std.atomic.Value: what it holds.
- if (comptime isAtomic(T)) return hash(@FieldType(T, "raw"), &v.raw, h);
- // A worker's future is a handle of the host's, never state.
- if (comptime @hasField(T, "any_future")) return;
- // std.DynamicBitSetUnmanaged: its bits.
- if (comptime isBitset(T)) {
- h.update(std.mem.asBytes(&v.bit_length));
- return h.update(std.mem.sliceAsBytes(v.masks[0 .. (v.bit_length + @bitSizeOf(usize) - 1) / @bitSizeOf(usize)]));
- }
- comptime checkAnnotations(T);
- inline for (s.field_names, s.field_types, s.field_attrs) |name, F, attr| {
- if (attr.@"comptime" or comptime excluded(T, name)) continue;
- if (comptime opaqueTo(F)) @compileError("walk: " ++ @typeName(T) ++ "." ++ name ++ " is " ++ @typeName(F) ++ ", which no walk sees into: say what it is (`replica`)");
- const was = in_blob;
- in_blob = comptime blob(T, name);
- defer in_blob = was;
- if (comptime lengthOf(T, name)) |len| {
- hashSlice(Element(F), @field(v, name)[0..lengthIn(v, len)], h);
- } else hash(F, &@field(v, name), h);
- }
- },
- .@"union" => |u| {
- if (u.tag_type == null) @compileError("walk: an untagged union: " ++ @typeName(T));
- if (comptime @hasDecl(T, "digest") and @TypeOf(T.digest) == fn (*const T, *Hasher) void) return v.digest(h);
- const tag: u.tag_type.? = v.*;
- hash(u.tag_type.?, &tag, h);
- switch (v.*) {
- inline else => |*payload| hash(@TypeOf(payload.*), payload, h),
- }
- },
- .error_set => h.update(@errorName(v.*)),
- .error_union => |e| if (v.*) |*payload| {
- h.update(&.{1});
- hash(e.payload, payload, h);
- } else |err| {
- h.update(&.{0});
- h.update(@errorName(err));
- },
- else => @compileError("walk: cannot hash " ++ @typeName(T)),
- }
-}
-
-/// Bytes a digest takes whole: an enum's are its build's number, not it.
-fn flatHash(comptime T: type) bool {
- return flat(T) and @typeInfo(T) != .@"enum";
-}
-
-/// An enum by its name, as a dump reads it, not by its number: an enum
-/// made at compile time numbers its words as its build has them
-/// (`registry.Builtin` has fewer in a FreeBSD build than a Linux one, which
-/// has Tty9p), so a window client here of a session on the box loaded a
-/// +LocationsConfig to another digest. A name's word (its hash, fixed
-/// width, so that two names in a row are not one), looked up by number
-/// where the words are numbered 0 up; one numbered by hand, or a value no
-/// word has, by its number.
-fn hashEnum(comptime T: type, v: T, h: *Hasher) void {
- const e = @typeInfo(T).@"enum";
- const words: ?[e.field_names.len]u64 = comptime words: {
- @setEvalBranchQuota(100_000);
- var out: [e.field_names.len]u64 = undefined;
- for (e.field_names, e.field_values, 0..) |name, n, i| {
- if (n != i) break :words null;
- out[i] = std.hash.Wyhash.hash(0, name);
- }
- break :words out;
- };
- const n = @backingInt(v);
- if (words) |table| if (n >= 0 and n < table.len) return h.update(std.mem.asBytes(&table[@intCast(n)]));
- hashInt(e.tag_type, n, h);
-}
-
-/// An integer by its value: one narrower than its bytes (a u21, an i2) has
-/// bits in memory that are no part of it.
-fn hashInt(comptime I: type, n: I, h: *Hasher) void {
- const W = @Int(@typeInfo(I).int.signedness, @sizeOf(I) * 8);
- const wide: W = n;
- h.update(std.mem.asBytes(&wide));
-}
-
-fn hashSlice(comptime E: type, items: []const E, h: *Hasher) void {
- if (in_blob and items.len * @sizeOf(E) >= blob_min) return hashBlob(E, items, h);
- h.update(std.mem.asBytes(&items.len));
- if (comptime flatHash(E)) return h.update(std.mem.sliceAsBytes(items));
- for (items) |*e| hash(E, e, h);
-}
-
-/// The value as bytes, the same walk: what the tape carries (core/tape.zig),
-/// to a replica of another build too (a window of a terminal's session, a
-/// Linux client of a FreeBSD one). Native byte order, which every machine
-/// pardes runs on shares, and an error by its name: its number is its
-/// build's own (a Linux terminal's FileNotFound is a window's
-/// NoDefaultValue). What a field is laid out as (a std.Io.File.Stat's
-/// `nlink` is another width on FreeBSD) is the tape's shape, which
-/// wire.semantics hashes (`shape`).
-pub fn encode(comptime T: type, v: *const T, w: *std.Io.Writer) std.Io.Writer.Error!void {
- switch (@typeInfo(T)) {
- .void, .null, .undefined => {},
- .bool, .int, .float, .@"enum" => try w.writeAll(std.mem.asBytes(v)),
- .optional => |o| if (comptime machinery(o.child)) try w.writeByte(0) else if (v.*) |*payload| {
- try w.writeByte(1);
- try encode(o.child, payload, w);
- } else try w.writeByte(0),
- .array => |a| if (comptime flat(a.child)) try w.writeAll(std.mem.sliceAsBytes(v)) else for (v) |*e| try encode(a.child, e, w),
- .pointer => |p| switch (p.size) {
- .one => try encode(p.child, v.*, w),
- .slice => {
- try w.writeAll(std.mem.asBytes(&v.len));
- if (comptime flat(p.child)) try w.writeAll(std.mem.sliceAsBytes(v.*)) else for (v.*) |*e| try encode(p.child, e, w);
- },
- else => @compileError("walk: a many-pointer has no length: " ++ @typeName(T)),
- },
- .@"struct" => |s| {
- if (comptime machinery(T)) return;
- if (s.layout == .@"packed") return w.writeAll(std.mem.asBytes(v));
- inline for (s.field_names, s.field_types, s.field_attrs) |name, F, attr| {
- if (attr.@"comptime" or comptime excluded(T, name)) continue;
- try encode(F, &@field(v, name), w);
- }
- },
- .@"union" => |u| {
- if (u.tag_type == null) @compileError("walk: an untagged union: " ++ @typeName(T));
- const tag: u.tag_type.? = v.*;
- try encode(u.tag_type.?, &tag, w);
- switch (v.*) {
- inline else => |*payload| try encode(@TypeOf(payload.*), payload, w),
- }
- },
- .error_set => try encodeError(T, v.*, w),
- .error_union => |e| if (v.*) |*payload| {
- try w.writeByte(1);
- try encode(e.payload, payload, w);
- } else |err| {
- try w.writeByte(0);
- try encodeError(e.error_set, err, w);
- },
- else => @compileError("walk: cannot encode " ++ @typeName(T)),
- }
-}
-
-/// What `encode` lays each of `types` out as, in words: each field, element
-/// and tag where it goes, an enum's names and numbers, an error as an
-/// error (it goes by its name). wire.semantics hashes the tape's: builds
-/// whose tapes differ in shape, as a FreeBSD std.Io.File.Stat differs from
-/// a Linux one, refuse each other's replicas in words, not read each other
-/// out of step.
-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");
- return out;
- }
-}
-
-fn shapeOf(comptime T: type, comptime depth: u8) []const u8 {
- comptime {
- if (depth > 32) @compileError("walk: the tape's shape nests past 32 deep at " ++ @typeName(T) ++ ": a type that holds itself?");
- return switch (@typeInfo(T)) {
- .void, .null, .undefined => "v",
- .bool => "b",
- .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 ++ (n ++ "=" ++ decimal(v) ++ ",");
- break :blk out ++ "}";
- },
- .optional => |o| if (machinery(o.child)) "0" else "?" ++ shapeOf(o.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),
- else => @compileError("walk: a many-pointer has no length: " ++ @typeName(T)),
- },
- .@"struct" => |s| blk: {
- if (machinery(T)) break :blk "";
- 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) ++ ",");
- }
- 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) ++ ",");
- break :blk out ++ ")";
- },
- .error_set => "error",
- .error_union => |e| "!" ++ shapeOf(e.payload, depth + 1),
- else => @compileError("walk: cannot encode " ++ @typeName(T)),
- };
- }
-}
-
-/// `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 {
- if (comptime E == anyerror and builtin.mode == .debug) if (errorNamed(E, @errorName(err)) == null)
- std.debug.panic("walk: error.{s} is taped as an anyerror, which a replica reads back only as one of tape.Failure's: add the set it comes from", .{@errorName(err)});
- try writeName(w, @errorName(err));
-}
-
-/// The error of `E` called `name`. `anyerror` keeps no list of its names
-/// to look one up in: one is read back as one of tape.Failure's, what a
-/// host reports as failed (the tape's only anyerrors).
-fn errorNamed(comptime E: type, name: []const u8) ?E {
- const Named = if (E == anyerror) @import("tape.zig").Failure else E;
- inline for (@typeInfo(Named).error_set.error_names.?) |n| if (std.mem.eql(u8, name, n)) return @field(Named, n);
- return null;
-}
-
-pub const Reader = struct {
- bytes: []const u8,
- at: usize = 0,
-
- pub fn take(r: *Reader, n: usize) error{EndOfTape}![]const u8 {
- if (r.bytes.len - r.at < n) return error.EndOfTape;
- defer r.at += n;
- return r.bytes[r.at..][0..n];
- }
-
- fn scalar(r: *Reader, comptime T: type) error{EndOfTape}!T {
- return std.mem.bytesToValue(T, try r.take(@sizeOf(T)));
- }
-};
-
-/// What an error read back is when this build has none of that name (an
-/// OS's own, a newer build's): the tape is another build's, and diverges.
-const TapeError = error{ EndOfTape, OutOfMemory, NoSuchError };
-
-/// The inverse of `encode`; slices (and what a pointer points at) are made
-/// in `a`. A field `encode` left out is its default.
-pub fn decode(comptime T: type, r: *Reader, a: std.mem.Allocator) TapeError!T {
- switch (@typeInfo(T)) {
- .void, .null, .undefined => return {},
- .bool => return (try r.take(1))[0] != 0,
- .int, .float, .@"enum" => return r.scalar(T),
- .optional => |o| {
- if ((try r.take(1))[0] == 0) return null;
- if (comptime machinery(o.child)) unreachable;
- return try decode(o.child, r, a);
- },
- .array => |a_info| {
- var out: T = undefined;
- if (comptime flat(a_info.child)) {
- @memcpy(std.mem.sliceAsBytes(&out), try r.take(@sizeOf(T)));
- } else for (&out) |*e| {
- e.* = try decode(a_info.child, r, a);
- }
- return out;
- },
- .pointer => |p| switch (p.size) {
- .one => {
- const out = try a.create(p.child);
- out.* = try decode(p.child, r, a);
- return out;
- },
- .slice => {
- const n = try r.scalar(usize);
- const out = try a.alloc(p.child, n);
- if (comptime flat(p.child)) {
- @memcpy(std.mem.sliceAsBytes(out), try r.take(n * @sizeOf(p.child)));
- } else for (out) |*e| {
- e.* = try decode(p.child, r, a);
- }
- return out;
- },
- else => @compileError("walk: a many-pointer has no length: " ++ @typeName(T)),
- },
- .@"struct" => |s| {
- if (s.layout == .@"packed") return r.scalar(T);
- var out: T = undefined;
- inline for (s.field_names, s.field_types, s.field_attrs) |name, F, attr| {
- if (attr.@"comptime") continue;
- if (comptime excluded(T, name)) {
- const default = attr.default_value_ptr orelse @compileError("walk: " ++ name ++ " has no default to decode to");
- @field(out, name) = @as(*const F, @ptrCast(@alignCast(default))).*;
- } else if (comptime @typeInfo(F) == .error_set) {
- // No `!anyerror` to return it through: read in place.
- try decodeError(F, r, &@field(out, name));
- } else @field(out, name) = try decode(F, r, a);
- }
- return out;
- },
- .@"union" => |u| {
- const tag = try decode(u.tag_type.?, r, a);
- inline for (u.field_names, u.field_types) |name, F| if (tag == @field(u.tag_type.?, name)) {
- return @unionInit(T, name, try decode(F, r, a));
- };
- unreachable;
- },
- .error_union => |e| {
- if ((try r.take(1))[0] != 0) return try decode(e.payload, r, a);
- // The value's error, not decode's own.
- var err: e.error_set = undefined;
- try decodeError(e.error_set, r, &err);
- return @as(T, err);
- },
- else => @compileError("walk: cannot decode " ++ @typeName(T)),
- }
-}
-
-/// An error by its name, as `encode` wrote it, into `out`: no error union
-/// holds an error set.
-fn decodeError(comptime E: type, r: *Reader, out: *E) TapeError!void {
- const len = try r.scalar(u16);
- out.* = errorNamed(E, try r.take(len)) orelse return error.NoSuchError;
-}
-
-// ---- the dump: the same walk, by name, for another build ----
-//
-// A dump (docs/next-daemon.md, phase 2) is `dump_magic`, then a table of
-// every type its roots' walk reaches -- each struct's and union's fields by
-// name, each enum's names, each number's width -- then each root's value,
-// laid out as `encode` lays it out but for three things: an enum or a
-// union's tag is its place among the table's names, a pointer or a slice met
-// again is a reference to the first (what two fields share is shared again),
-// and a type with a `dumpWrite` of its own is its bytes, counted.
-//
-// A build that is not the writer's matches by name: a field added since
-// takes its default, one removed is passed over, one whose kind changed
-// takes its default and says so (`Decoder.notes`). With no default to take,
-// the value it is part of is refused (`error.Incompatible`), and an element
-// of an array of optional pointers (a session's panes) is then left out,
-// nothing above it. A dump whose table is this build's own is read field
-// after field, no name asked.
-//
-// Native byte order: the machines pardes runs on are all little-endian.
-
-const dump_magic = "pardes-dump\x00\x02\n";
-
-const Kind = enum(u8) { skip, void, bool, int, float, @"enum", optional, one, slice, array, prefix, @"struct", @"union", err, error_union, custom, bitset };
-
-/// std's lists: their items, not the capacity behind them (nor, in a safe
-/// build, the lock that checks no pointer into them moves).
-pub fn isList(comptime T: type) bool {
- if (@typeInfo(T) != .@"struct" or !@hasField(T, "items") or !@hasField(T, "capacity")) return false;
- const n = @typeInfo(T).@"struct".field_names.len;
- return n == 2 or (n == 3 and @hasField(T, "pointer_stability"));
-}
-fn isAtomic(comptime T: type) bool {
- return @typeInfo(T) == .@"struct" and @hasField(T, "raw") and @typeInfo(T).@"struct".field_names.len == 1 and @hasDecl(T, "load");
-}
-fn isBitset(comptime T: type) bool {
- return @typeInfo(T) == .@"struct" and @hasField(T, "bit_length") and @hasField(T, "masks") and @typeInfo(T).@"struct".field_names.len == 2;
-}
-
-/// A field written only as far as its `len` says: a count, then that many.
-fn Prefix(comptime E: type) type {
- return struct {
- pub const element = E;
- };
-}
-
-/// What the dump walks `T` as: an atomic as what it holds, a list as its
-/// items.
-fn Canon(comptime T: type) type {
- if (comptime isAtomic(T)) return Canon(@FieldType(T, "raw"));
- if (comptime isList(T)) return []@typeInfo(@FieldType(T, "items")).pointer.child;
- return T;
-}
-
-fn kindOf(comptime T: type) Kind {
- return switch (@typeInfo(T)) {
- .void, .null, .undefined => .void,
- .bool => .bool,
- .int => .int,
- .float => .float,
- .@"enum" => .@"enum",
- .optional => .optional,
- .array => .array,
- .pointer => |p| switch (p.size) {
- .one => .one,
- .slice => .slice,
- else => @compileError("walk: a many-pointer has no length: " ++ @typeName(T)),
- },
- .@"struct" => if (machinery(T) or @hasField(T, "any_future"))
- .skip
- else if (@hasDecl(T, "dumpWrite"))
- .custom
- else if (@hasDecl(T, "element") and T == Prefix(T.element))
- .prefix
- else if (isBitset(T))
- .bitset
- else
- .@"struct",
- .@"union" => |u| if (u.tag_type == null) @compileError("walk: an untagged union: " ++ @typeName(T)) else .@"union",
- else => @compileError("walk: cannot dump " ++ @typeName(T)),
- };
-}
-
-/// The fields of struct `T` a dump holds, in order.
-fn dumpFields(comptime T: type) []const [:0]const u8 {
- comptime {
- @setEvalBranchQuota(1_000_000);
- var names: []const [:0]const u8 = &.{};
- const s = @typeInfo(T).@"struct";
- for (s.field_names, s.field_types, s.field_attrs) |name, F, attr| {
- if (attr.@"comptime" or excluded(T, name) or kindOf(Canon(F)) == .skip) continue;
- if (opaqueTo(F)) @compileError("walk: " ++ @typeName(T) ++ "." ++ name ++ " is " ++ @typeName(F) ++ ", which no walk sees into: say what it is (`replica`)");
- names = names ++ .{name};
- }
- return names;
- }
-}
-
-/// The type a dump walks field `name` of `T` as.
-fn FieldDump(comptime T: type, comptime name: []const u8) type {
- const F = @FieldType(T, name);
- if (comptime cutArray(T, name)) return Prefix(Canon(@typeInfo(F).array.child));
- return Canon(F);
-}
-
-/// A fixed array a `len` cuts, which a dump writes as far as it says. A
-/// slice it cuts (a text's room for its ranges, made whole) is written
-/// whole, room and all, which only plain numbers may be: a load gives it
-/// the room it had.
-fn cutArray(comptime T: type, comptime name: []const u8) bool {
- const F = @FieldType(T, name);
- if (comptime lengthOf(T, name) == null) return false;
- if (@typeInfo(F) == .array) return true;
- if (!plain(Element(F))) @compileError("walk: " ++ @typeName(T) ++ "." ++ name ++ " is a slice a `len` cuts, of what a dump cannot write past the cut");
- return false;
-}
-
-/// Every bit pattern one of its values: what a dump may write where
-/// nothing was ever written.
-fn plain(comptime T: type) bool {
- return switch (@typeInfo(T)) {
- .int, .float => true,
- .array => |a| plain(a.child),
- .@"struct" => |st| st.layout != .@"packed" and blk: {
- for (st.field_types) |F| if (!plain(F)) break :blk false;
- break :blk true;
- },
- else => false,
- };
-}
-
-fn children(comptime T: type) []const type {
- comptime {
- return switch (kindOf(T)) {
- .optional => &.{Canon(@typeInfo(T).optional.child)},
- .one, .slice => &.{Canon(@typeInfo(T).pointer.child)},
- .array => &.{Canon(@typeInfo(T).array.child)},
- .prefix => &.{T.element},
- .@"struct" => blk: {
- var out: []const type = &.{};
- for (dumpFields(T)) |name| out = out ++ .{FieldDump(T, name)};
- break :blk out;
- },
- .@"union" => blk: {
- var out: []const type = &.{};
- for (@typeInfo(T).@"union".field_types) |F| out = out ++ .{Canon(F)};
- break :blk out;
- },
- else => &.{},
- };
- }
-}
-
-fn collect(comptime T: type, comptime list: []const type) []const type {
- comptime {
- for (list) |U| if (U == T) return list;
- var out: []const type = list ++ .{T};
- if (kindOf(T) == .@"struct") checkAnnotations(T);
- for (children(T)) |C| out = collect(C, out);
- return out;
- }
-}
-
-/// Every type the walk of `roots` reaches, each once.
-fn graph(comptime roots: []const type) []const type {
- comptime {
- @setEvalBranchQuota(100_000_000);
- var list: []const type = &.{};
- for (roots) |R| list = collect(Canon(R), list);
- return list;
- }
-}
-
-/// The types the walk of `roots` reaches that walk themselves by hand (a
-/// `digest` or a `dumpWrite` of their own): the ones whose digest can take
-/// what their dump does not carry, which the one walk holds for the rest.
-pub fn handWalked(comptime roots: []const type) []const type {
- comptime {
- var out: []const type = &.{};
- for (graph(roots)) |T| switch (@typeInfo(T)) {
- .@"struct", .@"union" => if (@hasDecl(T, "dumpWrite") or (@hasDecl(T, "digest") and @TypeOf(T.digest) == fn (*const T, *Hasher) void)) {
- out = out ++ .{T};
- },
- else => {},
- };
- return out;
- }
-}
-
-fn indexIn(comptime types: []const type, comptime T: type) u32 {
- comptime {
- @setEvalBranchQuota(100_000_000);
- for (types, 0..) |U, i| if (U == T) return i;
- @compileError("walk: not in the dump's table: " ++ @typeName(T));
- }
-}
-
-/// How many bytes an integer of `bits` is written in: its own size.
-fn intBytes(bits: u16) usize {
- return if (bits == 0) 0 else if (bits <= 8) 1 else if (bits <= 16) 2 else if (bits <= 32) 4 else if (bits <= 64) 8 else 16;
-}
-
-fn writeName(w: *std.Io.Writer, name: []const u8) !void {
- try w.writeAll(std.mem.asBytes(&@as(u16, @intCast(name.len))));
- try w.writeAll(name);
-}
-
-fn writeU32(w: *std.Io.Writer, n: u32) !void {
- try w.writeAll(std.mem.asBytes(&n));
-}
-
-fn writeTable(comptime types: []const type, w: *std.Io.Writer) !void {
- try writeU32(w, types.len);
- inline for (types) |T| {
- const k = comptime kindOf(T);
- try w.writeByte(@backingInt(k));
- switch (k) {
- .int => {
- try w.writeByte(@intFromBool(@typeInfo(T).int.signedness == .signed));
- try w.writeAll(std.mem.asBytes(&@as(u16, @typeInfo(T).int.bits)));
- },
- .float => try w.writeAll(std.mem.asBytes(&@as(u16, @typeInfo(T).float.bits))),
- .@"enum" => {
- const e = @typeInfo(T).@"enum";
- const tag = @typeInfo(e.tag_type).int;
- try w.writeByte(@intFromBool(tag.signedness == .signed));
- try w.writeAll(std.mem.asBytes(&@as(u16, tag.bits)));
- try writeU32(w, e.field_names.len);
- inline for (e.field_names, e.field_values) |name, value| {
- try writeName(w, name);
- try w.writeAll(std.mem.asBytes(&@as(i128, value)));
- }
- },
- .array => {
- try w.writeAll(std.mem.asBytes(&@as(u64, @typeInfo(T).array.len)));
- try writeU32(w, comptime indexIn(types, children(T)[0]));
- },
- .optional, .one, .slice, .prefix, .error_union => try writeU32(w, comptime indexIn(types, children(T)[0])),
- .@"struct" => {
- const names = comptime dumpFields(T);
- try writeU32(w, names.len);
- inline for (names) |name| {
- try writeName(w, name);
- try writeU32(w, comptime indexIn(types, FieldDump(T, name)));
- }
- },
- .@"union" => {
- const u = @typeInfo(T).@"union";
- try writeU32(w, u.field_names.len);
- inline for (u.field_names, u.field_types) |name, F| {
- try writeName(w, name);
- try writeU32(w, comptime indexIn(types, Canon(F)));
- }
- },
- .custom => try writeName(w, @typeName(T)),
- .skip, .void, .bool, .err, .bitset => {},
- }
- }
-}
-
-/// Integers by value, in the bytes `intBytes` gives them: a `u21`'s
-/// padding is no part of it.
-fn putInt(comptime I: type, n: I, w: *std.Io.Writer) !void {
- const info = @typeInfo(I).int;
- const W = @Int(info.signedness, intBytes(info.bits) * 8);
- const wide: W = n;
- try w.writeAll(std.mem.asBytes(&wide));
-}
-
-/// The table of `types` as bytes, made once a process (it is the build's):
-/// a store record or a dump writes it, a load compares it.
-fn tableOf(comptime types: []const type) []const u8 {
- const Once = struct {
- // Of these types alone: a container that named none of its
- // function's parameters would be one for every table.
- const of = types;
- /// 0 none, 1 being made, 2 made.
- var state: std.atomic.Value(u8) = .init(0);
- var bytes: []const u8 = &.{};
- };
- if (Once.state.load(.acquire) == 2) return Once.bytes;
- if (Once.state.cmpxchgStrong(0, 1, .acquire, .monotonic) == null) {
- var out: std.Io.Writer.Allocating = .init(std.heap.page_allocator);
- writeTable(types, &out.writer) catch @panic("walk: out of memory for a dump's table");
- Once.bytes = out.toOwnedSlice() catch @panic("walk: out of memory for a dump's table");
- Once.state.store(2, .release);
- } else while (Once.state.load(.acquire) != 2) std.atomic.spinLoopHint();
- return Once.bytes;
-}
-
-/// A blob's bytes a dump left out (`Dump.deferred`): they go at `at`.
-pub const Deferred = struct { at: usize, bytes: []const u8 };
-
-/// Writes a dump of `roots`' values, one `put` each in order.
-pub fn Dump(comptime roots: []const type) type {
- return struct {
- const Self = @This();
- pub const types = graph(roots);
-
- gpa: std.mem.Allocator,
- out: std.Io.Writer.Allocating,
- memo: std.AutoHashMapUnmanaged(Key, u32) = .empty,
- /// Set: a `.blob`'s bytes (of `blob_min` and up) are not written but
- /// noted, where they go and what they are; the dump with them put
- /// back in place is the dump. A replica's join streams them from
- /// its writer thread (core/replica.zig), the session's step paying
- /// for the rest alone.
- deferred: ?*std.ArrayListUnmanaged(Deferred) = null,
- in_blob: bool = false,
-
- const Key = struct { addr: usize, len: usize, ty: u32 };
-
- pub fn init(gpa: std.mem.Allocator) !Self {
- var d: Self = .{ .gpa = gpa, .out = .init(gpa) };
- errdefer d.out.deinit();
- try d.out.writer.writeAll(dump_magic);
- try d.out.writer.writeAll(tableOf(types));
- return d;
- }
-
- pub fn deinit(d: *Self) void {
- d.memo.deinit(d.gpa);
- d.out.deinit();
- }
-
- /// The dump, the caller's (gpa).
- pub fn finish(d: *Self) ![]u8 {
- d.memo.deinit(d.gpa);
- d.memo = .empty;
- return d.out.toOwnedSlice();
- }
-
- pub fn put(d: *Self, comptime T: type, v: *const T) !void {
- try writeU32(&d.out.writer, comptime indexIn(types, Canon(T)));
- try d.value(T, v);
- }
-
- /// Whether the pointer or slice at `addr` was met before: its
- /// reference written if so, else 0 and it is noted.
- fn seen(d: *Self, comptime T: type, addr: usize, len: usize) Error!bool {
- const w = &d.out.writer;
- if (len == 0) {
- try writeU32(w, 0);
- return false;
- }
- const got = try d.memo.getOrPut(d.gpa, .{ .addr = addr, .len = len, .ty = comptime indexIn(types, Canon(T)) });
- if (got.found_existing) {
- try writeU32(w, got.value_ptr.*);
- return true;
- }
- got.value_ptr.* = @intCast(d.memo.count());
- try writeU32(w, 0);
- return false;
- }
-
- const Error = std.Io.Writer.Error || std.mem.Allocator.Error;
-
- fn items(d: *Self, comptime E: type, slice: []const E) Error!void {
- const w = &d.out.writer;
- try w.writeAll(std.mem.asBytes(&@as(u64, slice.len)));
- if (comptime flat(E)) return w.writeAll(std.mem.sliceAsBytes(slice));
- for (slice) |*e| try d.value(E, e);
- }
-
- fn value(d: *Self, comptime T: type, v: *const T) Error!void {
- if (comptime isAtomic(T)) return d.value(@FieldType(T, "raw"), &v.raw);
- const w = &d.out.writer;
- if (comptime isList(T)) {
- const E = @typeInfo(@FieldType(T, "items")).pointer.child;
- if (try d.seen([]E, @intFromPtr(v.items.ptr), v.items.len)) return;
- return d.items(E, v.items);
- }
- switch (comptime kindOf(T)) {
- .skip, .void => {},
- .bool => try w.writeByte(@intFromBool(v.*)),
- .int => try putInt(T, v.*, w),
- .float => try w.writeAll(std.mem.asBytes(v)),
- .@"enum" => try putInt(@typeInfo(T).@"enum".tag_type, @backingInt(v.*), w),
- .optional => if (v.*) |*payload| {
- try w.writeByte(1);
- try d.value(@typeInfo(T).optional.child, payload);
- } else try w.writeByte(0),
- .one => {
- const C = @typeInfo(T).pointer.child;
- if (try d.seen(T, @intFromPtr(v.*), @max(1, @sizeOf(C)))) return;
- try d.value(C, v.*);
- },
- .slice => {
- const E = @typeInfo(T).pointer.child;
- if (try d.seen(T, @intFromPtr(v.ptr), v.len)) return;
- if (comptime flat(E)) if (d.in_blob) if (d.deferred) |later| {
- const bytes = std.mem.sliceAsBytes(v.*);
- if (bytes.len >= blob_min) {
- try w.writeAll(std.mem.asBytes(&@as(u64, v.len)));
- return later.append(d.gpa, .{ .at = d.out.writer.end, .bytes = bytes });
- }
- };
- try d.items(E, v.*);
- },
- .array => {
- const E = @typeInfo(T).array.child;
- if (comptime flat(E)) return w.writeAll(std.mem.sliceAsBytes(v));
- for (v) |*e| try d.value(E, e);
- },
- .prefix => unreachable,
- .@"struct" => {
- const packed_struct = comptime @typeInfo(T).@"struct".layout == .@"packed";
- inline for (comptime dumpFields(T)) |name| {
- const F = @FieldType(T, name);
- const was = d.in_blob;
- d.in_blob = was or comptime blob(T, name);
- defer d.in_blob = was;
- if (comptime cutArray(T, name)) {
- const all = &@field(v, name);
- try d.items(@typeInfo(F).array.child, all[0..@min(all.len, lengthIn(v, comptime lengthOf(T, name).?))]);
- } else if (packed_struct) {
- const copy: F = @field(v, name);
- try d.value(F, &copy);
- } else try d.value(F, &@field(v, name));
- }
- },
- .@"union" => {
- const tag = std.meta.activeTag(v.*);
- const ordinal: u16 = inline for (@typeInfo(T).@"union".field_names, 0..) |name, i| {
- if (tag == @field(std.meta.Tag(T), name)) break i;
- } else unreachable;
- try w.writeAll(std.mem.asBytes(&ordinal));
- switch (v.*) {
- inline else => |*payload| try d.value(@TypeOf(payload.*), payload),
- }
- },
- // Kinds an old dump's table may name (`skip`); no type walked here has them.
- .err, .error_union => unreachable,
- .custom => {
- const at = d.out.writer.end;
- try w.writeAll(&std.mem.toBytes(@as(u64, 0)));
- T.dumpWrite(v, d.gpa, w) catch return error.WriteFailed;
- const n: u64 = d.out.writer.end - at - 8;
- @memcpy(d.out.writer.buffer[at..][0..8], std.mem.asBytes(&n));
- },
- .bitset => {
- try w.writeAll(std.mem.asBytes(&@as(u64, v.bit_length)));
- const words = (v.bit_length + @bitSizeOf(usize) - 1) / @bitSizeOf(usize);
- if (words > 0) try w.writeAll(std.mem.sliceAsBytes(v.masks[0..words]));
- },
- }
- }
- };
-}
-
-/// One value `T` as a dump of its own (gpa): a closed pane, a terminal's
-/// parts that are not its emulator.
-pub fn save(comptime T: type, gpa: std.mem.Allocator, v: *const T) ![]u8 {
- var d = try Dump(&.{T}).init(gpa);
- errdefer d.deinit();
- try d.put(T, v);
- return d.finish();
-}
-
-const DecodeError = error{ EndOfDump, BadDump, Incompatible, OutOfMemory };
-
-/// The allocators a `replica.alloc` annotation may name, beside the
-/// loader's own: `.alloc = .{ .{ "image", "image" } }` makes what field
-/// `image` holds with `allocs.image`.
-const Allocators = struct {
- image: ?std.mem.Allocator = null,
- terminal: ?std.mem.Allocator = null,
-};
-
-fn allocOf(comptime T: type, comptime name: []const u8) ?[]const u8 {
- if (!@hasDecl(T, "replica") or !@hasField(@TypeOf(T.replica), "alloc")) return null;
- inline for (T.replica.alloc) |pair| if (comptime std.mem.eql(u8, pair[0], name)) return pair[1];
- return null;
-}
-
-fn countOf(n: u64) DecodeError!usize {
- return std.math.cast(usize, n) orelse error.BadDump;
-}
-
-/// An allocation a load made: what a reference to it finds, and what a
-/// failed load frees.
-const Made = struct { bytes: []u8, alignment: std.mem.Alignment, gpa: std.mem.Allocator, dead: bool = false };
-
-/// A type as the dump's writer had it.
-const SrcType = struct {
- kind: Kind,
- signed: bool = false,
- bits: u16 = 0,
- child: u32 = 0,
- len: u64 = 0,
- /// A struct's or union's fields, an enum's names (and `value`s).
- fields: []const SrcField = &.{},
-};
-const SrcField = struct { name: []const u8, ty: u32 = 0, value: i128 = 0 };
-
-/// 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 {
- pub fn init(gpa: std.mem.Allocator, bytes: []const u8) DecodeError!Loader {
- return Loader.init(gpa, bytes, tableOf(graph(roots)));
- }
- };
-}
-
-/// `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();
-
- /// 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 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;
- }
-
- pub fn deinit(l: *Self) void {
- l.shared.deinit(l.own);
- l.customs.deinit(l.own);
- l.notes.deinit(l.own);
- l.arena.deinit();
- }
-
- /// 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 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 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 scalar(l: *Self, comptime T: type) DecodeError!T {
- return std.mem.bytesToValue(T, try l.take(@sizeOf(T)));
- }
-
- /// 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 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 => {},
- }
- }
- for (l.src) |t| {
- if (t.child >= n) return error.BadDump;
- for (t.fields) |f| if (f.ty >= n) return error.BadDump;
- }
- }
-
- 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 {};
- }
-
- /// 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 });
- }
-
- fn root(l: *Self) DecodeError!u32 {
- const ty = try l.scalar(u32);
- if (ty >= l.src.len) return error.BadDump;
- return ty;
- }
-
- /// 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;
- }
-
- /// 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 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));
- 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 });
- 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)));
- },
- }
- }
-
- /// 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;
- };
- 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;
- };
- }
- 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);
- }
- 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.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;
- };
- };
- }
- // 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;
- }
- }
- };
- 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));
- }
-
- /// 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.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);
- }
-};
-
-/// `out` as a new `T` is before a load reads its fields: each field's
-/// default, an allocator `gpa`.
-fn freshOf(comptime T: type, out: *T, gpa: std.mem.Allocator) void {
- if (comptime @typeInfo(T) != .@"struct" or isList(T) or isAtomic(T) or isBitset(T) or kindOf(T) == .custom or kindOf(T) == .skip) return;
- const s = @typeInfo(T).@"struct";
- inline for (s.field_names, s.field_types, s.field_attrs) |field, F, attr| {
- if (attr.@"comptime") continue;
- if (comptime attr.default_value_ptr) |dp| {
- @field(out, field) = @as(*const F, @ptrCast(@alignCast(dp))).*;
- } else if (comptime F == std.mem.Allocator) {
- @field(out, field) = gpa;
- } else if (comptime !walkedField(T, field)) {
- @compileError("walk: " ++ @typeName(T) ++ "." ++ field ++ " has no default to load to");
- }
- }
-}
-
-fn walkedField(comptime T: type, comptime field: []const u8) bool {
- inline for (comptime dumpFields(T)) |n| if (comptime std.mem.eql(u8, n, field)) return true;
- return false;
-}
-
-/// A value `save` made, `gpa`'s; what was let go is said in `notes` when
-/// it is given.
-pub fn load(comptime T: type, gpa: std.mem.Allocator, bytes: []const u8, notes: ?*std.ArrayList(u8)) DecodeError!T {
- var l = try Load(&.{T}).init(gpa, bytes);
- defer l.deinit();
- errdefer l.rollback();
- const v = try l.get(T);
- if (notes) |n| try n.appendSlice(gpa, l.notes.items);
- return v;
-}
-
-// ---- a dump as a database: the same walk, by name, into xitdb's maps ----
-//
-// A dump (Db.zig) is a xitdb database in memory, its bytes one value of the
-// state file, written by the walk by name: a struct is a map whose keys are
-// its fields' names (`putKey`: a reader goes through them by name, never by
-// a hash of its own), a union a map of its one field, a slice, an array or
-// a list of records a list, of plain numbers one bytes value (its format
-// tag the numbers' kind and width), an enum the bytes of its name, a number
-// a uint or an int (a wider one its bytes), an optional an absent key (an
-// explicit none where the field's default is not null), a type with
-// `dumpWrite` its bytes, and a `.blob`'s text of `blob_min` bytes and up
-// its BLAKE3 hash (tag "b3"): the text is kept once beside the dump
-// (`Blob`). A pointer or a slice met again is the first one's value again:
-// what two fields share is shared again.
-//
-// Another build reads it by name: a field the dump has not takes its
-// default, a key this build has not is passed over, a value of another kind
-// takes its default and is said (`notes`); with no default the value it is
-// part of is refused, and an element of an array of optional pointers (a
-// session's panes) is then left out, nothing above it.
-
-pub const Mem = xitdb.Database(.memory, u256);
-
-/// A text a dump keeps beside it, once: its BLAKE3 hash and its bytes (the
-/// session's, while the dump is made).
-pub const Blob = struct { hash: [32]u8, bytes: []const u8 };
-
-/// A field's key: its name's word, unique within its struct (a reader
-/// matches names, so another build's words need not be these).
-fn nameKey(comptime name: []const u8) u256 {
- return comptime std.hash.Wyhash.hash(0, name);
-}
-
-/// Whether a run of `E` is one bytes value: plain numbers.
-fn numbers(comptime E: type) bool {
- return switch (@typeInfo(E)) {
- .int => |i| @sizeOf(E) * 8 == i.bits and @sizeOf(E) <= 8,
- .bool => true,
- .float => |f| f.bits == 32 or f.bits == 64,
- else => false,
- };
-}
-
-/// A run of numbers' format tag: their kind and byte width ("u4", "i8", "b1").
-fn numbersTag(comptime E: type) [2]u8 {
- const kind: u8 = switch (@typeInfo(E)) {
- .int => |i| if (i.signedness == .signed) 'i' else 'u',
- .bool => 'b',
- .float => 'f',
- else => unreachable,
- };
- return .{ kind, '0' + @sizeOf(E) };
-}
-
-const blob_tag = "b3".*;
-const wide_tag = "w8".*;
-const custom_tag = "cu".*;
-const bitset_tag = "bs".*;
-
-fn typeWord(comptime T: type) u64 {
- return comptime std.hash.Wyhash.hash(0, @typeName(T));
-}
-
-/// Writes values into a database in memory, by name (see above).
-pub const Put = struct {
- gpa: std.mem.Allocator,
- /// Each pointer and slice written, by address, length and type, and
- /// where its value is: met again, that value is written again.
- memo: std.AutoHashMapUnmanaged(Key, xitdb.Slot) = .empty,
- /// The blobs met, each once.
- blobs: std.ArrayListUnmanaged(Blob) = .empty,
- in_blob: bool = false,
-
- const Key = struct { addr: usize, len: usize, ty: u64 };
- const Cursor = Mem.Cursor(.read_write);
-
- pub fn deinit(w: *Put) void {
- w.memo.deinit(w.gpa);
- w.blobs.deinit(w.gpa);
- }
-
- /// `v` written as `name`'s value in `map` (a dump's roots).
- pub fn member(w: *Put, map: Mem.HashMap(.read_write), comptime name: []const u8, comptime T: type, v: *const T) anyerror!void {
- try map.putKey(comptime nameKey(name), .{ .bytes = name });
- var at = try map.putCursor(comptime nameKey(name));
- _ = try w.value(T, v, &at);
- }
-
- /// `v` written at `c`; where its value is.
- pub fn value(w: *Put, comptime T: type, v: *const T, c: *Cursor) anyerror!xitdb.Slot {
- if (comptime isAtomic(T)) return w.value(@FieldType(T, "raw"), &v.raw, c);
- if (comptime isList(T)) return w.many(@typeInfo(@FieldType(T, "items")).pointer.child, v.items, c, true);
- switch (comptime kindOf(T)) {
- .skip, .void => try c.write(.{ .slot = null }),
- .bool => try c.write(.{ .uint = @intFromBool(v.*) }),
- .int => if (@typeInfo(T).int.bits <= 64) {
- try c.write(if (@typeInfo(T).int.signedness == .signed) .{ .int = v.* } else .{ .uint = v.* });
- } else {
- const wide: i128 = @intCast(v.*);
- try c.write(.{ .bytes_object = .{ .value = std.mem.asBytes(&wide), .format_tag = wide_tag } });
- },
- .float => try c.write(.{ .float = v.* }),
- .@"enum" => if (std.enums.tagName(T, v.*)) |name| {
- try c.write(.{ .bytes = name });
- } else try c.write(.{ .int = @intCast(@backingInt(v.*)) }),
- .optional => {
- const C = @typeInfo(T).optional.child;
- if (v.*) |*payload| {
- // An allocator, say, is no state: there or not, which a
- // load answers with its own.
- if (comptime kindOf(Canon(C)) == .skip) try c.write(.{ .uint = 1 }) else return w.value(C, payload, c);
- } else try c.write(.{ .slot = null });
- },
- .one => {
- const C = @typeInfo(T).pointer.child;
- const key: Key = .{ .addr = @intFromPtr(v.*), .len = @max(1, @sizeOf(C)), .ty = typeWord(T) };
- if (w.memo.get(key)) |slot| {
- try c.write(.{ .slot = slot });
- return slot;
- }
- const slot = try w.value(C, v.*, c);
- try w.memo.put(w.gpa, key, slot);
- return slot;
- },
- .slice => return w.many(@typeInfo(T).pointer.child, v.*, c, true),
- .array => return w.many(@typeInfo(T).array.child, v, c, false),
- .prefix => unreachable,
- .@"struct" => return w.fields(T, v, c),
- .@"union" => {
- const map = try Mem.HashMap(.read_write).init(c.*);
- switch (v.*) {
- inline else => |*payload, tag| {
- const name = @tagName(tag);
- try map.putKey(comptime nameKey(name), .{ .bytes = name });
- var at = try map.putCursor(comptime nameKey(name));
- _ = try w.value(@TypeOf(payload.*), payload, &at);
- },
- }
- return map.slot();
- },
- // No type a dump walks has them.
- .err, .error_union => unreachable,
- .custom => {
- var buf: [4096]u8 = undefined;
- var out = try c.writer(&buf);
- try T.dumpWrite(v, w.gpa, &out.interface);
- out.format_tag = custom_tag;
- try out.finish();
- },
- .bitset => {
- const words = (v.bit_length + @bitSizeOf(usize) - 1) / @bitSizeOf(usize);
- var buf: [64]u8 = undefined;
- var out = try c.writer(&buf);
- try out.interface.writeAll(std.mem.asBytes(&@as(u64, v.bit_length)));
- if (words > 0) try out.interface.writeAll(std.mem.sliceAsBytes(v.masks[0..words]));
- out.format_tag = bitset_tag;
- try out.finish();
- },
- }
- return c.slot();
- }
-
- /// A run of `E`: numbers as one bytes value (a blob's text by its
- /// hash), records as a list; a slice met again (`shared`) its first
- /// value.
- fn many(w: *Put, comptime E: type, items: []const E, c: *Cursor, comptime shared: bool) anyerror!xitdb.Slot {
- const key: Key = .{ .addr = @intFromPtr(items.ptr), .len = items.len, .ty = typeWord([]const E) };
- if (shared and items.len > 0) if (w.memo.get(key)) |slot| {
- try c.write(.{ .slot = slot });
- return slot;
- };
- const slot = if (comptime numbers(E)) slot: {
- const bytes = std.mem.sliceAsBytes(items);
- if (E == u8 and w.in_blob and bytes.len >= blob_min) {
- var sum: [32]u8 = undefined;
- std.crypto.hash.Blake3.hash(bytes, &sum, .{});
- const known = for (w.blobs.items) |b| {
- if (std.mem.eql(u8, &b.hash, &sum)) break true;
- } else false;
- if (!known) try w.blobs.append(w.gpa, .{ .hash = sum, .bytes = bytes });
- try c.write(.{ .bytes_object = .{ .value = &sum, .format_tag = blob_tag } });
- } else try c.write(.{ .bytes_object = .{ .value = bytes, .format_tag = numbersTag(E) } });
- break :slot try c.slot();
- } else slot: {
- const list = try Mem.ArrayList(.read_write).init(c.*);
- for (items) |*e| {
- var at = try list.appendCursor();
- _ = try w.value(E, e, &at);
- }
- break :slot try list.slot();
- };
- if (shared and items.len > 0) try w.memo.put(w.gpa, key, slot);
- return slot;
- }
-
- fn fields(w: *Put, comptime T: type, v: *const T, c: *Cursor) anyerror!xitdb.Slot {
- const map = try Mem.HashMap(.read_write).init(c.*);
- const packed_struct = comptime @typeInfo(T).@"struct".layout == .@"packed";
- inline for (comptime dumpFields(T)) |name| {
- const F = @FieldType(T, name);
- if (comptime kindOf(Canon(F)) != .void) put: {
- // Null where the field's default is: no key at all.
- if (comptime @typeInfo(F) == .optional and defaultIsNull(T, name)) if (@field(v, name) == null) break :put;
- const was = w.in_blob;
- w.in_blob = was or comptime blob(T, name);
- defer w.in_blob = was;
- try map.putKey(comptime nameKey(name), .{ .bytes = name });
- var at = try map.putCursor(comptime nameKey(name));
- if (comptime cutArray(T, name)) {
- const all = &@field(v, name);
- _ = try w.many(@typeInfo(F).array.child, all[0..@min(all.len, lengthIn(v, comptime lengthOf(T, name).?))], &at, false);
- } else if (comptime packed_struct) {
- const copy: F = @field(v, name);
- _ = try w.value(F, &copy, &at);
- } else _ = try w.value(F, &@field(v, name), &at);
- }
- }
- return map.slot();
- }
-};
-
-fn defaultIsNull(comptime T: type, comptime name: []const u8) bool {
- const F = @FieldType(T, name);
- const attr = @typeInfo(T).@"struct".field_attrs[std.meta.fieldIndex(T, name).?];
- const dp = attr.default_value_ptr orelse return false;
- return @as(*const F, @ptrCast(@alignCast(dp))).* == null;
-}
-
-/// Reads values a `Put` wrote, by name, as another build may have written
-/// them (see above).
-pub const Get = struct {
- /// Where what is read is made (a `replica.alloc` field's own allocator
- /// while it is read).
- gpa: std.mem.Allocator,
- /// The reader's own lists'.
- own: std.mem.Allocator,
- /// The texts its blobs' hashes name (Db.zig's `blobs`), by hash.
- blobs: ?Mem.HashMap(.read_only) = null,
- /// Each pointer and slice made so far: what a value met again is, and
- /// what `rollback` frees.
- made: std.ArrayList(Made) = .empty,
- /// Where each value made is: met again, the same one.
- memo: std.AutoHashMapUnmanaged(u128, usize) = .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 = "",
- allocs: Allocators = .{},
-
- const Cursor = Mem.Cursor(.read_only);
- pub const Error = error{ BadDump, Incompatible, OutOfMemory };
-
- pub fn init(gpa: std.mem.Allocator) Get {
- return .{ .gpa = gpa, .own = gpa };
- }
-
- pub fn deinit(l: *Get) void {
- l.made.deinit(l.own);
- l.memo.deinit(l.own);
- l.customs.deinit(l.own);
- l.notes.deinit(l.own);
- }
-
- /// 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: *Get) void {
- for (l.customs.items) |c| c.free(c.ptr, c.gpa);
- for (l.made.items) |m| if (m.bytes.len > 0) m.gpa.rawFree(m.bytes, m.alignment, @returnAddress());
- l.customs.clearRetainingCapacity();
- l.made.clearRetainingCapacity();
- l.memo.clearRetainingCapacity();
- }
-
- pub fn note(l: *Get, comptime fmt: []const u8, args: anytype) void {
- if (l.notes.items.len > 4096) return;
- 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;
- try l.fresh(T, &out);
- try l.value(T, c, &out);
- return out;
- }
-
- /// The struct at `c` 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, and one another build cannot give is left too, and
- /// noted.
- pub fn into(l: *Get, comptime T: type, c: Cursor, out: *T) Error!void {
- try l.fields(T, c, out, true);
- }
-
- /// Where the value of `name` is in the map at `c` (a dump's roots), by
- /// its name; null when it is not there.
- pub fn member(c: Cursor, name: []const u8) Error!?Cursor {
- const map = Mem.HashMap(.read_only).init(c) catch return error.BadDump;
- var it = map.iterator() catch return error.BadDump;
- while (it.next() catch return error.BadDump) |kv_at| {
- const kv = kv_at.readKeyValuePair() catch return error.BadDump;
- var buf: [64]u8 = undefined;
- const got = kv.key_cursor.readBytes(&buf) catch continue;
- if (std.mem.eql(u8, got, name)) return kv.value_cursor;
- }
- return null;
- }
-
- fn fresh(l: *Get, comptime T: type, out: *T) Error!void {
- freshOf(T, out, l.gpa);
- }
-
- fn slotWord(slot: xitdb.Slot) u128 {
- return @as(u72, @bitCast(slot));
- }
-
- fn slotOf(c: Cursor) Error!xitdb.Slot {
- return c.slot() catch error.BadDump;
- }
-
- /// Whether the value at `slot` has a place of its own (an inline number
- /// or a short text is its slot alone: no identity to share).
- fn placed(slot: xitdb.Slot) bool {
- return switch (slot.tag) {
- .none, .uint, .int, .float, .short_bytes => false,
- else => true,
- };
- }
-
- /// An allocation made for the value at `slot`, kept: what a value met
- /// again is, and what `rollback` frees.
- fn keep(l: *Get, bytes: []u8, alignment: std.mem.Alignment, slot: xitdb.Slot) Error!usize {
- try l.made.append(l.own, .{ .bytes = bytes, .alignment = alignment, .gpa = l.gpa });
- const at = l.made.items.len - 1;
- // Not kept after all: the caller frees it.
- if (placed(slot)) l.memo.put(l.own, slotWord(slot), at) catch |err| {
- _ = l.made.pop();
- return err;
- };
- return at;
- }
-
- /// The value made before for the same place, when there was one.
- fn again(l: *Get, slot: xitdb.Slot) Error!?[]u8 {
- if (!placed(slot)) return null;
- const at = l.memo.get(slotWord(slot)) orelse return null;
- // Made, then let go of by the reader's caller (a dump's mounts).
- if (at >= l.made.items.len) return null;
- const m = l.made.items[at];
- if (m.dead) return error.Incompatible;
- return m.bytes;
- }
-
- /// `T` read from `c` into `out`, which `fresh` has made ready.
- fn value(l: *Get, comptime T: type, c: Cursor, out: *T) Error!void {
- if (comptime isAtomic(T)) {
- const R = @FieldType(T, "raw");
- var raw: R = undefined;
- try l.fresh(R, &raw);
- try l.value(R, c, &raw);
- out.* = .{ .raw = raw };
- return;
- }
- const slot = try slotOf(c);
- if (comptime isList(T)) {
- const got = try l.slice(@typeInfo(@FieldType(T, "items")).pointer.child, c, slot);
- out.* = .empty;
- out.items = got;
- out.capacity = got.len;
- return;
- }
- switch (comptime kindOf(T)) {
- .skip, .void => {},
- .bool => out.* = switch (slot.tag) {
- .uint => slot.value != 0,
- else => return error.Incompatible,
- },
- .int => out.* = try l.int(T, c, slot),
- .float => out.* = switch (slot.tag) {
- .float => @floatCast(@as(f64, @bitCast(slot.value))),
- else => return error.Incompatible,
- },
- .@"enum" => {
- const e = @typeInfo(T).@"enum";
- switch (slot.tag) {
- .bytes, .short_bytes => {
- var buf: [256]u8 = undefined;
- const name = c.readBytes(&buf) catch return error.Incompatible;
- inline for (e.field_names) |field| if (std.mem.eql(u8, name, field)) {
- out.* = @field(T, field);
- return;
- };
- l.note("{s}: no {s} here", .{ l.field, name });
- return error.Incompatible;
- },
- .int, .uint => if (e.mode == .nonexhaustive) {
- const n: i64 = @bitCast(slot.value);
- out.* = @fromBackingInt(@intCast(std.math.cast(e.tag_type, n) orelse return error.Incompatible));
- } else return error.Incompatible,
- else => return error.Incompatible,
- }
- },
- .optional => {
- const C = @typeInfo(T).optional.child;
- if (slot.tag == .none) {
- out.* = null;
- return;
- }
- if (comptime kindOf(Canon(C)) == .skip) {
- out.* = if (comptime C == std.mem.Allocator) l.gpa else null;
- return;
- }
- // Through a local, as the byte loader does: a pointer's
- // null is its address.
- if (comptime @typeInfo(C) == .pointer) {
- var payload: C = undefined;
- try l.value(C, c, &payload);
- out.* = payload;
- return;
- }
- out.* = @as(C, undefined);
- try l.fresh(C, &out.*.?);
- l.value(C, c, &out.*.?) catch |err| {
- out.* = null;
- return err;
- };
- },
- .one => {
- const C = @typeInfo(T).pointer.child;
- if (try l.again(slot)) |bytes| {
- out.* = @ptrCast(@alignCast(bytes.ptr));
- return;
- }
- const one = try l.gpa.create(C);
- const at = l.keep(std.mem.asBytes(one), .of(C), slot) catch |err| {
- l.gpa.destroy(one);
- return err;
- };
- try l.fresh(C, one);
- l.value(C, c, one) catch |err| {
- // Left half made: no later value may be it.
- l.made.items[at].dead = true;
- return err;
- };
- out.* = one;
- },
- .slice => {
- if (comptime @typeInfo(T).pointer.sentinel_ptr != null) @compileError("walk: a sentinel slice: " ++ @typeName(T));
- out.* = try l.slice(@typeInfo(T).pointer.child, c, slot);
- },
- .array => try l.elements(@typeInfo(T).array.child, c, slot, out),
- .prefix => unreachable,
- .@"struct" => try l.fields(T, c, out, false),
- .@"union" => {
- const u = @typeInfo(T).@"union";
- const map = Mem.HashMap(.read_only).init(c) catch return error.Incompatible;
- var it = map.iterator() catch return error.BadDump;
- const kv_at = (it.next() catch return error.BadDump) orelse return error.Incompatible;
- const kv = kv_at.readKeyValuePair() catch return error.BadDump;
- var buf: [256]u8 = undefined;
- const name = kv.key_cursor.readBytes(&buf) catch return error.Incompatible;
- inline for (u.field_names, u.field_types) |field, F| if (std.mem.eql(u8, name, field)) {
- out.* = @unionInit(T, field, undefined);
- try l.fresh(F, &@field(out.*, field));
- return l.value(F, kv.value_cursor, &@field(out.*, field));
- };
- l.note("{s}: no {s} here", .{ l.field, name });
- return error.Incompatible;
- },
- .err, .error_union => unreachable,
- .custom => {
- const got = c.readBytesObjectAlloc(l.own, null) catch return error.Incompatible;
- defer l.own.free(got.value);
- T.dumpRead(out, l.gpa, got.value) 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 got = c.readBytesObjectAlloc(l.own, null) catch return error.Incompatible;
- defer l.own.free(got.value);
- if (got.value.len < 8) return error.BadDump;
- const bits = countOf(std.mem.bytesToValue(u64, got.value[0..8])) catch return error.BadDump;
- const words = (bits + @bitSizeOf(usize) - 1) / @bitSizeOf(usize);
- if (got.value.len != 8 + words * @sizeOf(usize)) return error.BadDump;
- out.* = try .initEmpty(l.gpa, bits);
- if (words > 0) @memcpy(std.mem.sliceAsBytes(out.masks[0..words]), got.value[8..]);
- },
- }
- }
-
- fn int(l: *Get, comptime I: type, c: Cursor, slot: xitdb.Slot) Error!I {
- _ = l;
- return switch (slot.tag) {
- .uint => std.math.cast(I, slot.value) orelse error.Incompatible,
- .int => std.math.cast(I, @as(i64, @bitCast(slot.value))) orelse error.Incompatible,
- .bytes, .short_bytes => wide: {
- var buf: [16]u8 = undefined;
- const got = c.readBytesObject(&buf) catch return error.Incompatible;
- if (got.value.len != 16 or !std.mem.eql(u8, &(got.format_tag orelse return error.Incompatible), &wide_tag)) return error.Incompatible;
- break :wide std.math.cast(I, std.mem.bytesToValue(i128, got.value[0..16])) orelse error.Incompatible;
- },
- else => error.Incompatible,
- };
- }
-
- /// Numbers' `bytes` (format `tag`) as `E`s into `out`, as many as fit:
- /// another width of the same kind (another build's) converted one by
- /// one. How many the bytes hold.
- fn convert(comptime E: type, bytes: []const u8, tag: [2]u8, out: []E) Error!usize {
- const width: usize = if (tag[1] >= '1' and tag[1] <= '8') tag[1] - '0' else return error.BadDump;
- if (bytes.len % width != 0) return error.BadDump;
- const n = bytes.len / width;
- const fits = @min(n, out.len);
- if (std.mem.eql(u8, &tag, &numbersTag(E))) {
- @memcpy(std.mem.sliceAsBytes(out[0..fits]), bytes[0 .. fits * width]);
- return n;
- }
- if (tag[0] != numbersTag(E)[0]) return error.Incompatible;
- for (out[0..fits], 0..) |*e, i| {
- const raw = bytes[i * width ..][0..width];
- e.* = switch (@typeInfo(E)) {
- .int => |info| if (info.signedness == .signed) cast: {
- var wide: i64 = 0;
- @memcpy(std.mem.asBytes(&wide)[0..width], raw);
- if (width < 8) {
- const shift: u6 = @intCast(64 - width * 8);
- wide = (wide << shift) >> shift;
- }
- break :cast std.math.cast(E, wide) orelse return error.Incompatible;
- } else cast: {
- var wide: u64 = 0;
- @memcpy(std.mem.asBytes(&wide)[0..width], raw);
- break :cast std.math.cast(E, wide) orelse return error.Incompatible;
- },
- .float => if (width == 8) @floatCast(std.mem.bytesToValue(f64, raw[0..8])) else if (width == 4) @floatCast(std.mem.bytesToValue(f32, raw[0..4])) else return error.Incompatible,
- .bool => raw[0] != 0,
- else => unreachable,
- };
- }
- return n;
- }
-
- /// The numbers' bytes at `c` and their format tag, `alloc`'s.
- fn numbersAt(c: Cursor, alloc: std.mem.Allocator) Error!struct { bytes: []u8, tag: [2]u8 } {
- const got = c.readBytesObjectAlloc(alloc, null) catch |err| return if (err == error.OutOfMemory) error.OutOfMemory else error.Incompatible;
- const bytes: []u8 = @constCast(got.value);
- const tag = got.format_tag orelse {
- alloc.free(bytes);
- return error.Incompatible;
- };
- return .{ .bytes = bytes, .tag = tag };
- }
-
- /// A slice of `E` at `c`: numbers' bytes, a blob's text by its hash, or
- /// a list; one met again is the same.
- fn slice(l: *Get, comptime E: type, c: Cursor, slot: xitdb.Slot) Error![]E {
- if (try l.again(slot)) |bytes| return @as([*]E, @ptrCast(@alignCast(bytes.ptr)))[0 .. bytes.len / @max(1, @sizeOf(E))];
- if (comptime numbers(E)) {
- switch (slot.tag) {
- .bytes, .short_bytes => {},
- else => return error.Incompatible,
- }
- if (E == u8) if (try l.blob(c, slot)) |text| return text;
- // A text, as it is written: its bytes are the slice.
- if (E == u8) {
- const got = try numbersAt(c, l.gpa);
- if (!std.mem.eql(u8, &got.tag, &numbersTag(u8))) {
- l.gpa.free(got.bytes);
- return error.Incompatible;
- }
- if (got.bytes.len == 0) {
- l.gpa.free(got.bytes);
- return &.{};
- }
- _ = l.keep(got.bytes, .@"1", slot) catch |err| {
- l.gpa.free(got.bytes);
- return err;
- };
- return got.bytes;
- }
- const got = try numbersAt(c, l.own);
- defer l.own.free(got.bytes);
- const width: usize = if (got.tag[1] >= '1' and got.tag[1] <= '8') got.tag[1] - '0' else return error.BadDump;
- const n = got.bytes.len / width;
- if (n == 0) return &.{};
- const many = try l.gpa.alloc(E, n);
- const at = l.keep(std.mem.sliceAsBytes(many), .of(E), slot) catch |err| {
- l.gpa.free(many);
- return err;
- };
- _ = convert(E, got.bytes, got.tag, many) catch |err| {
- l.made.items[at].dead = true;
- return err;
- };
- return many;
- }
- const list = Mem.ArrayList(.read_only).init(c) catch return error.Incompatible;
- const n = countOf(list.count() catch return error.BadDump) catch return error.BadDump;
- if (n == 0) return &.{};
- const many = try l.gpa.alloc(E, n);
- const at = l.keep(std.mem.sliceAsBytes(many), .of(E), slot) catch |err| {
- l.gpa.free(many);
- return err;
- };
- l.listInto(E, list, many) catch |err| {
- l.made.items[at].dead = true;
- return err;
- };
- return many;
- }
-
- /// A blob's text, when `c` holds a blob's hash: made in `gpa`'s.
- fn blob(l: *Get, c: Cursor, slot: xitdb.Slot) Error!?[]u8 {
- var buf: [32]u8 = undefined;
- const got = c.readBytesObject(&buf) catch return null;
- const tag = got.format_tag orelse return null;
- if (!std.mem.eql(u8, &tag, &blob_tag) or got.value.len != 32) return null;
- const texts = l.blobs orelse return error.BadDump;
- const at = (texts.getCursor(std.mem.readInt(u256, got.value[0..32], .big)) catch return error.BadDump) orelse return error.BadDump;
- const text = at.readBytesAlloc(l.gpa, null) catch |err| return if (err == error.OutOfMemory) error.OutOfMemory else error.BadDump;
- const bytes: []u8 = @constCast(text);
- _ = l.keep(bytes, .@"1", slot) catch |err| {
- l.gpa.free(bytes);
- return err;
- };
- return bytes;
- }
-
- /// An array of `E` at `c`: as many as it holds, the rest as they are.
- fn elements(l: *Get, comptime E: type, c: Cursor, slot: xitdb.Slot, out: []E) Error!void {
- if (comptime numbers(E)) {
- switch (slot.tag) {
- .bytes, .short_bytes => {},
- else => return error.Incompatible,
- }
- const got = try numbersAt(c, l.own);
- defer l.own.free(got.bytes);
- _ = try convert(E, got.bytes, got.tag, out);
- return;
- }
- const list = Mem.ArrayList(.read_only).init(c) catch return error.Incompatible;
- try l.listInto(E, list, out);
- }
-
- /// The list's elements into `out`, as many as fit; an element of an
- /// array of optional pointers (a session's panes) that cannot be read is
- /// left out, not the array.
- fn listInto(l: *Get, comptime E: type, list: Mem.ArrayList(.read_only), out: []E) Error!void {
- const droppable = comptime @typeInfo(E) == .optional and @typeInfo(@typeInfo(E).optional.child) == .pointer;
- var failed = false;
- var it = list.iterator() catch return error.BadDump;
- var i: usize = 0;
- while (it.next() catch return error.BadDump) |at| : (i += 1) {
- if (i >= out.len) break;
- try l.fresh(E, &out[i]);
- l.value(E, at, &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;
- };
- }
- if (failed) return error.Incompatible;
- }
-
- fn fields(l: *Get, comptime T: type, c: Cursor, out: *T, existing: bool) Error!void {
- const names = comptime dumpFields(T);
- const outer = l.field;
- defer l.field = outer;
- const map = Mem.HashMap(.read_only).init(c) catch return error.Incompatible;
- var found: std.StaticBitSet(@max(1, names.len)) = .empty;
- var failed = false;
- var it = map.iterator() catch return error.BadDump;
- while (it.next() catch return error.BadDump) |kv_at| {
- const kv = kv_at.readKeyValuePair() catch return error.BadDump;
- var buf: [256]u8 = undefined;
- // A key that is no field's name of this build: passed over.
- const name = kv.key_cursor.readBytes(&buf) catch continue;
- const k: ?usize = inline for (names, 0..) |field, k| {
- if (std.mem.eql(u8, name, field)) break k;
- } else null;
- const at = k orelse continue;
- found.set(at);
- inline for (names, 0..) |field, i| if (i == at) {
- l.field = field;
- l.oneField(T, field, kv.value_cursor, out, 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.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;
- };
- };
- }
- // A field the writer did not have (or held null at a null default):
- // its default (`fresh`), or the value cannot be made.
- inline for (names, 0..) |field, i| if (!found.isSet(i)) {
- const F = @FieldType(T, field);
- 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.noteField("not in the dump", @typeName(T), field);
- failed = true;
- }
- } else if (comptime @typeInfo(F) == .optional and defaultIsNull(T, field)) if (existing) {
- // A null left out: null here too.
- @field(out, field) = null;
- };
- };
- if (failed) return error.Incompatible;
- }
-
- fn oneField(l: *Get, comptime T: type, comptime field: []const u8, c: Cursor, out: *T, existing: bool) Error!void {
- const F = @FieldType(T, field);
- const packed_struct = comptime @typeInfo(T).@"struct".layout == .@"packed";
- const gpa = l.gpa;
- defer l.gpa = gpa;
- if (comptime allocOf(T, field)) |which| if (@field(l.allocs, which)) |a| {
- l.gpa = a;
- };
- // A field this build compiles out (a void field): passed over,
- // said when it held something.
- if (comptime kindOf(Canon(F)) == .void) {
- if ((try slotOf(c)).tag != .none) l.note("{s}: not in this build", .{l.field});
- return;
- }
- if (comptime cutArray(T, field)) {
- const slot = try slotOf(c);
- return l.elements(@typeInfo(F).array.child, c, slot, &@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) {
- return l.fields(F, c, &@field(out, field), true);
- };
- if (packed_struct) {
- var copy: F = undefined;
- try l.fresh(F, &copy);
- try l.value(F, c, &copy);
- @field(out, field) = copy;
- return;
- }
- try l.fresh(F, &@field(out, field));
- try l.value(F, c, &@field(out, field));
- }
-};
-
-test "a value comes back from its bytes" {
- const E = union(enum) { key: struct { cp: u21, text: []const u8 }, tick, failed: anyerror!u32 };
- var buf: [256]u8 = undefined;
- var w: std.Io.Writer = .fixed(&buf);
- const values = [_]E{ .{ .key = .{ .cp = 'x', .text = "x" } }, .tick, .{ .failed = error.FileNotFound }, .{ .failed = 9 } };
- for (&values) |*v| try encode(E, v, &w);
- var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
- defer arena.deinit();
- var r: Reader = .{ .bytes = w.buffered() };
- for (&values) |*v| try std.testing.expectEqual(digest(E, v), digest(E, &try decode(E, &r, arena.allocator())));
- try std.testing.expectEqual(r.bytes.len, r.at);
-}
-
-test "an error is taped by its name, which another build reads back as its own" {
- // The build's number for an error is its own: 451 of 505 names were
- // numbered otherwise in a Linux window's build than a terminal's, so a
- // window replica read a terminal session's FileNotFound as another.
- var buf: [64]u8 = undefined;
- var w: std.Io.Writer = .fixed(&buf);
- const failed: error{ FileNotFound, NotDir }!u32 = error.NotDir;
- try encode(@TypeOf(failed), &failed, &w);
- try std.testing.expectEqualSlices(u8, "\x00\x06\x00NotDir", w.buffered());
- var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
- defer arena.deinit();
- var r: Reader = .{ .bytes = w.buffered() };
- try std.testing.expectError(error.NotDir, try decode(@TypeOf(failed), &r, arena.allocator()));
- // A name this build's set lacks (an OS's own): the tape is another
- // build's, and the replay diverges rather than read some other error.
- r = .{ .bytes = "\x00\x0c\x00FileTooLarge" };
- try std.testing.expectError(error.NoSuchError, decode(@TypeOf(failed), &r, arena.allocator()));
- // An anyerror (a host's report) is read back as one of tape.Failure's.
- const Report = struct { err: anyerror };
- w = .fixed(&buf);
- try encode(Report, &.{ .err = error.FileNotFound }, &w);
- r = .{ .bytes = w.buffered() };
- try std.testing.expectEqual(error.FileNotFound, (try decode(Report, &r, arena.allocator())).err);
-}
-
-test "an enum is digested by its name, which another build may number otherwise" {
- // registry.Builtin as a Linux build makes it (Tty9p in it) and as a
- // FreeBSD one does: LocationsConfig is another number in each.
- const Linux = enum { Look, Tty9p, LocationsConfig };
- const FreeBSD = enum { Look, LocationsConfig };
- const S = struct { from: Linux, also: [2]Linux };
- const T = struct { from: FreeBSD, also: [2]FreeBSD };
- try std.testing.expectEqual(digest(S, &.{ .from = .LocationsConfig, .also = .{ .Look, .LocationsConfig } }), digest(T, &.{ .from = .LocationsConfig, .also = .{ .Look, .LocationsConfig } }));
- try std.testing.expect(digest(S, &.{ .from = .Look, .also = .{ .Look, .Look } }) != digest(S, &.{ .from = .Tty9p, .also = .{ .Look, .Look } }));
-}
-
-test "a digest is of values: the same text at two addresses is one digest" {
- const S = struct { name: []const u8, n: u32, next: ?*const u32 };
- const a = "same text";
- var b: [9]u8 = undefined;
- @memcpy(&b, a);
- const x: u32 = 7;
- const y: u32 = 7;
- try std.testing.expectEqual(digest(S, &.{ .name = a, .n = 1, .next = &x }), digest(S, &.{ .name = &b, .n = 1, .next = &y }));
- try std.testing.expect(digest(S, &.{ .name = a, .n = 1, .next = &x }) != digest(S, &.{ .name = a, .n = 2, .next = &x }));
-}
-
-test "an annotated field is in no digest, and a length cuts its array" {
- const S = struct {
- kept: u32,
- cache: u32,
- ring: [4]u8,
- ring_len: u8,
- pub const replica = .{ .derived = .{"cache"}, .len = .{.{ "ring", "ring_len" }} };
- };
- try std.testing.expectEqual(
- digest(S, &.{ .kept = 1, .cache = 2, .ring = .{ 1, 2, 9, 9 }, .ring_len = 2 }),
- digest(S, &.{ .kept = 1, .cache = 3, .ring = .{ 1, 2, 0, 0 }, .ring_len = 2 }),
- );
-}
-
-test "an optional slice comes back, and the fields after it" {
- const S = struct { before: u32 = 0, command: ?[]u8 = null, after: u32 = 0 };
- var text = "sleep 30".*;
- const bytes = try save(S, std.testing.allocator, &.{ .before = 1, .command = &text, .after = 2 });
- defer std.testing.allocator.free(bytes);
- var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
- defer arena.deinit();
- const back = try load(S, arena.allocator(), bytes, null);
- try std.testing.expectEqualStrings("sleep 30", back.command.?);
- try std.testing.expectEqual(2, back.after);
-}
-
-test "a dump comes back whole: shared things shared, lists and runs as long as they were" {
- const gpa = std.testing.allocator;
- const Leaf = struct { n: u21, name: []const u8 };
- const Mode = enum { a, b, c };
- const S = struct {
- mode: Mode = .a,
- leaf: *Leaf,
- same_leaf: *Leaf,
- text: []u8,
- same_text: []u8,
- list: std.ArrayList(u16) = .empty,
- maybe: ?Leaf = null,
- either: union(enum) { none, some: u32, many: []const u16 } = .none,
- ring: [4]u8 = @splat(0),
- ring_len: u8 = 0,
- room: []i32 = &.{},
- room_len: u8 = 0,
- cache: u64 = 7,
- alloc: std.mem.Allocator,
- flags: packed struct { x: bool = false, y: u3 = 0 } = .{},
- pub const replica = .{ .derived = .{"cache"}, .len = .{ .{ "ring", "ring_len" }, .{ "room", "room_len" } } };
- };
- var leaf: Leaf = .{ .n = 0x1fffff, .name = "leaf" };
- var room = [_]i32{ 4, 5, -1, -1 };
- var text = "shared text".*;
- var list: std.ArrayList(u16) = .empty;
- defer list.deinit(gpa);
- try list.appendSlice(gpa, &.{ 1, 2, 3 });
- const x: S = .{ .mode = .c, .leaf = &leaf, .same_leaf = &leaf, .text = &text, .same_text = &text, .list = list, .maybe = .{ .n = 3, .name = "maybe" }, .either = .{ .many = &.{ 9, 8 } }, .ring = .{ 5, 6, 0xAA, 0xAA }, .ring_len = 2, .room = &room, .room_len = 2, .cache = 99, .alloc = gpa, .flags = .{ .x = true, .y = 5 } };
- const bytes = try save(S, gpa, &x);
- defer gpa.free(bytes);
- var arena: std.heap.ArenaAllocator = .init(gpa);
- defer arena.deinit();
- const y = try load(S, arena.allocator(), bytes, null);
- try std.testing.expectEqual(digest(S, &x), digest(S, &y));
- try std.testing.expect(y.leaf == y.same_leaf and y.text.ptr == y.same_text.ptr);
- try std.testing.expectEqual(@as(u64, 7), y.cache);
- try std.testing.expectEqualSlices(u16, &.{ 1, 2, 3 }, y.list.items);
- try std.testing.expectEqual(true, y.flags.x);
- // A slice its `len` cuts keeps its room.
- try std.testing.expectEqual(@as(usize, 4), y.room.len);
- try std.testing.expectEqualSlices(i32, &.{ 4, 5 }, y.room[0..2]);
- // A fixpoint: what was read is written as it was.
- const again = try save(S, gpa, &y);
- defer gpa.free(again);
- try std.testing.expectEqualSlices(u8, bytes, again);
-}
-
-test "a dump crosses builds: a field added takes its default, one removed is passed over, one changed is left out" {
- const gpa = std.testing.allocator;
- const Old = struct {
- const Color = enum { red, green, blue };
- const Pane = struct { name: []const u8, color: Color = .red, gone: u32 = 1, width: u16 = 0, kind: u32 = 0 };
- panes: [3]?*Pane = @splat(null),
- count: u8 = 0,
- renamed: u32 = 0,
- };
- const New = struct {
- // Values renumbered and one added before the others.
- const Color = enum { cyan, blue, red, green };
- const Wide = struct { a: u8 };
- const Pane = struct { added: bool = true, color: Color = .cyan, width: u32 = 0, name: []const u8, kind: Wide = .{ .a = 4 } };
- // A pane's required field changed kind: that pane is left out.
- const Strict = struct { name: u8 };
- panes: [4]?*Pane = @splat(null),
- count: u16 = 0,
- renamed_now: u32 = 5,
- };
- var one: Old.Pane = .{ .name = "one", .color = .blue, .gone = 9, .width = 300, .kind = 2 };
- var two: Old.Pane = .{ .name = "two", .color = .green };
- const old: Old = .{ .panes = .{ &one, null, &two }, .count = 2, .renamed = 7 };
- const bytes = try save(Old, gpa, &old);
- defer gpa.free(bytes);
- var arena: std.heap.ArenaAllocator = .init(gpa);
- defer arena.deinit();
- // The notes are made where the load's values are.
- var notes: std.ArrayList(u8) = .empty;
- const new = try load(New, arena.allocator(), bytes, &notes);
- try std.testing.expectEqual(@as(u16, 2), new.count);
- try std.testing.expectEqual(@as(u32, 5), new.renamed_now);
- const a = new.panes[0].?;
- try std.testing.expectEqualStrings("one", a.name);
- try std.testing.expectEqual(New.Color.blue, a.color);
- try std.testing.expectEqual(@as(u32, 300), a.width);
- try std.testing.expect(a.added);
- try std.testing.expectEqual(@as(u8, 4), a.kind.a);
- try std.testing.expect(new.panes[1] == null and new.panes[3] == null);
- try std.testing.expectEqual(New.Color.green, new.panes[2].?.color);
- try std.testing.expect(std.mem.indexOf(u8, notes.items, "kind") != null);
-
- const Strict = struct {
- const Pane = struct { name: u8 };
- panes: [3]?*Pane = @splat(null),
- count: u8 = 0,
- };
- notes.clearRetainingCapacity();
- const strict = try load(Strict, arena.allocator(), bytes, &notes);
- try std.testing.expect(strict.panes[0] == null and strict.panes[2] == null);
- try std.testing.expectEqual(@as(u8, 2), strict.count);
- try std.testing.expect(std.mem.indexOf(u8, notes.items, "left out") != null);
-
- // And back: the newer build's dump read by the older one.
- const newer = try save(New, gpa, &new);
- defer gpa.free(newer);
- const back = try load(Old, arena.allocator(), newer, null);
- try std.testing.expectEqualStrings("two", back.panes[2].?.name);
- try std.testing.expectEqual(@as(u32, 1), back.panes[0].?.gone);
- try std.testing.expectEqual(Old.Color.blue, back.panes[0].?.color);
-}
-
-test "a dump that is not one, or is cut short, is refused" {
- const gpa = std.testing.allocator;
- const S = struct { a: u32, b: []const u8 };
- try std.testing.expectError(error.BadDump, load(S, gpa, "not a dump", null));
- const bytes = try save(S, gpa, &.{ .a = 1, .b = "bee" });
- defer gpa.free(bytes);
- // What it made before the end is freed again.
- try std.testing.expectError(error.EndOfDump, load(S, gpa, bytes[0 .. bytes.len - 2], null));
-}
-
-test "a blob of 4 KiB and up is digested by its length, what it holds told by its keeper's revision; a smaller one by its bytes" {
- const gpa = std.testing.allocator;
- const File = struct {
- pub const replica = .{ .blob = .{"content"} };
- content: []u8,
- revision: u32 = 0,
- };
- const text = try gpa.alloc(u8, 64 << 10);
- defer gpa.free(text);
- @memset(text, 'a');
- var f: File = .{ .content = text };
- const before = digest(File, &f);
- // Written in place: the same digest, until its revision says so.
- text[1000] = 'b';
- try std.testing.expectEqual(before, digest(File, &f));
- f.revision += 1;
- try std.testing.expect(digest(File, &f) != before);
- // Another length is another digest.
- f.revision = 0;
- f.content = text[0 .. text.len - 1];
- try std.testing.expect(digest(File, &f) != before);
- // A small one by its bytes.
- var small = "abc".*;
- f.content = &small;
- const was = digest(File, &f);
- 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));
-}