diff options
Diffstat (limited to 'core')
| -rw-r--r-- | core/Jump.zig | 33 | ||||
| -rw-r--r-- | core/Kind.zig | 11 | ||||
| -rw-r--r-- | core/Messages.zig | 21 | ||||
| -rw-r--r-- | core/Query.zig | 30 | ||||
| -rw-r--r-- | core/Stream.zig | 51 | ||||
| -rw-r--r-- | core/colors.zig | 52 | ||||
| -rw-r--r-- | core/diff.zig | 7 | ||||
| -rw-r--r-- | core/fuzz.zig | 98 | ||||
| -rw-r--r-- | core/hunks.zig | 6 | ||||
| -rw-r--r-- | core/look.zig | 134 | ||||
| -rw-r--r-- | core/replica.zig | 32 | ||||
| -rw-r--r-- | core/walk.zig | 39 |
12 files changed, 485 insertions, 29 deletions
diff --git a/core/Jump.zig b/core/Jump.zig index b68da32d..ccdb8fdc 100644 --- a/core/Jump.zig +++ b/core/Jump.zig @@ -203,12 +203,15 @@ pub fn trackJump(p: *Pardes) void { }; } // Two in a row the same (a closed one reopened beside its own, - // or the entry between them gone): one entry, one step. - if (w > 0 and std.meta.eql(v.jumps.list[w - 1], kept)) { + // or the entry between them gone): one entry, one step; the same + // as the digest sees them (a text's `place` is bytes undefined). + // Compared where it is stored (w <= i: read already): a pointer + // to `kept` put it on the stack for every entry of every step. + v.jumps.list[w] = kept; + if (w > 0 and pardes.walk.eql(Loc, &v.jumps.list[w - 1], &v.jumps.list[w])) { if (i == v.jumps.cur) cur = w - 1; continue; } - v.jumps.list[w] = kept; w += 1; } v.jumps.n = w; @@ -361,12 +364,34 @@ test "the jump list never holds two entries in a row the same, when the one betw p.view().jumps.cur = 3; pane.body.cur_row = 80; // where you are now: far from both trackJump(p); - for (1..p.view().jumps.n) |i| try std.testing.expect(!std.meta.eql(p.view().jumps.list[i - 1], p.view().jumps.list[i])); + for (1..p.view().jumps.n) |i| try std.testing.expect(!pardes.walk.eql(Loc, &p.view().jumps.list[i - 1], &p.view().jumps.list[i])); try std.testing.expectEqual(@as(usize, 3), p.view().jumps.n); try std.testing.expectEqual(@as(u32, 1), p.view().jumps.list[0].line); try std.testing.expectEqual(@as(u32, 150), p.view().jumps.list[1].line); } +test "two entries the same but for the bytes past their place's length are one entry, as the digest sees them, on every build" { + const p = try Pardes.init(std.testing.allocator, .{ .cols = 60, .rows = 40 }); + defer p.deinit(); + const pane = try p.setTestFile(std.mem.asBytes(&@as([200][2]u8, @splat("a\n".*)))); + // A text's entry has no place: `.place = .{}`, its bytes undefined, + // 0xAA on every Debug process and each release process's own (the + // stack's, a load's): one entry on every side or a client parts. + var a: Loc = .{ .pane = 0, .serial = pane.serial, .line = 1, .col = 1 }; + var b = a; + @memset(&a.place.bytes, 0x11); + @memset(&b.place.bytes, 0x22); + p.view().jumps.list[0] = a; + p.view().jumps.list[1] = .{ .pane = 5, .serial = 999, .line = 1, .col = 1 }; + p.view().jumps.list[2] = b; + p.view().jumps.list[3] = .{ .pane = 0, .serial = pane.serial, .line = 150, .col = 1 }; + p.view().jumps.n = 4; + p.view().jumps.cur = 3; + pane.body.cur_row = 80; + trackJump(p); + try std.testing.expectEqual(@as(usize, 3), p.view().jumps.n); +} + test "jump history skips an entry whose pane slot or serial is gone, leaving the selection" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 60, .rows = 12 }); defer p.deinit(); diff --git a/core/Kind.zig b/core/Kind.zig index 5d2dcdb0..764b6f06 100644 --- a/core/Kind.zig +++ b/core/Kind.zig @@ -41,7 +41,7 @@ comptime { if (@sizeOf(usize) == 8) for (.{ .{ c.pa_cell, 20 }, .{ c.pa_window, 24 }, .{ c.pa_rect, 16 }, .{ c.pa_cells, 8 }, .{ c.pa_placement, 80 }, .{ c.pa_paint, 48 }, .{ c.pa_key, 8 }, .{ c.pa_mouse, 16 }, - .{ c.pa_api, 120 }, .{ c.pa_out, 16 }, .{ c.pa_word, 32 }, .{ c.pa_head, 56 }, + .{ c.pa_api, 128 }, .{ c.pa_out, 16 }, .{ c.pa_word, 32 }, .{ c.pa_head, 56 }, .{ c.pa_ops, 208 }, .{ c.pa_view, 32 }, .{ c.pa_tick, 128 }, }) |r| if (@sizeOf(r[0]) != r[1]) @compileError(std.fmt.comptimePrint("{s} is {d} bytes, the header says {d}", .{ @typeName(r[0]), @sizeOf(r[0]), r[1] })); } @@ -1229,6 +1229,15 @@ pub const api: c.pa_api = .{ return token; } }.f, + .panic = struct { + /// An addon's panic is pardes's (its root's handler: the crash + /// record, the terminal, the clients): a call into it never returns. + fn f(msg: [*c]const u8, n: u32) callconv(.c) void { + var buf: [512]u8 = undefined; + const said = cSlice(msg, n); + @panic(std.fmt.bufPrint(&buf, "an addon's panic: {s}", .{said}) catch said); + } + }.f, .found = struct { /// Gathered in the call: the search's answer, or onto its +Search after. fn f(rows: [*c]const u8, n: u32) callconv(.c) void { diff --git a/core/Messages.zig b/core/Messages.zig index 46dab136..18b10ff8 100644 --- a/core/Messages.zig +++ b/core/Messages.zig @@ -192,6 +192,7 @@ pub fn expireUnattended(p: *Pardes) void { for (p.panes) |slot| { const pane = slot orelse continue; if (pane.msg_len == 0 and pane.msg_older_len == 0) continue; + if (awaited(p, pane)) continue; if (now - pane.msg_said_ms < p.settings.message_linger_ms) continue; pane.msg_len = 0; pane.msg_life = .{}; @@ -200,10 +201,30 @@ pub fn expireUnattended(p: *Pardes) void { } } +/// A message waits for someone to see it, and a view kept for its client's +/// return (views.away: an Upgrade's clients, a divergence's) is someone +/// on the way: what its keyboard's pane says (an Upgrade's outcome, +/// upgrade.zig `tellEveryView`) is that client's until it is back for its +/// view (Pardes.rejoinView: its join's dump has it) or the view's kept +/// time is up; no other view's input and no unattended clock take it. A +/// pair's one client is such a client; the session's own frontend is +/// none (its view is never away). A session no build could load starts +/// afresh with no view kept: a pair's is held attended for its client +/// instead (tui.zig `Own.start`). +fn awaited(p: *const Pardes, pane: *const Pane) bool { + if (p.views_away == 0) return false; + for (p.views, 0..) |slot, k| if (slot) |v| { + if (pardes.views.isAway(p, @intCast(k)) and p.panes[v.active] == pane and + p.clock.now_ns -| v.away_ns < pardes.views.away_kept_ns) return true; + }; + return false; +} + /// The key or click that used to clear the message row now starts each /// line's exit: it stays `message_linger_ms`, then goes. A line already /// on its way out keeps its own timing. pub fn dismissMessage(p: *Pardes, pane: *Pane) void { + if (awaited(p, pane)) return; if (pane.msg_len > 0 and dismissLine(p, &pane.msg_life)) { pane.msg_len = 0; pane.msg_life = .{}; diff --git a/core/Query.zig b/core/Query.zig index 228cdd0e..3023cc60 100644 --- a/core/Query.zig +++ b/core/Query.zig @@ -486,7 +486,12 @@ fn makeNameRows(p: *Pardes, id: usize) !void { var meta: locations.Row = .{ .kind = .match, .path = &.{}, .at = .{}, .location_end = 0, .code_start = 0, .mark_occurrence = false }; var pathbuf: [4096 + 32]u8 = undefined; switch (q.source) { - .find => meta.path = @constCast(std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), row }) catch row), + .find => { + // A name the worker quoted (look.quoted) opens as it is named. + var namebuf: [4096]u8 = undefined; + const name = if (row.len > 1 and row[0] == '"' and row[row.len - 1] == '"') look.unquoted(&namebuf, row[1 .. row.len - 1]) else row; + meta.path = @constCast(std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), name }) catch row); + }, .recent => { const t = look.parsePathLine(row); meta.path = @constCast(if (t.path.len > 0 and t.path[0] == '/') t.path else std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), t.path }) catch t.path); @@ -1030,7 +1035,8 @@ fn writePlacesRows(p: *Pardes, q: *Query, out: *std.ArrayList(u8), rows: *std.Ar const index = try File.lineIndex(p.gpa, f); const path = addressOf(p.scratch.allocator(), tp); var relbuf: [4096]u8 = undefined; - const rel = lookPath(&relbuf, path, dir); + var namebuf: [8192]u8 = undefined; + const rel = std.fmt.bufPrint(&namebuf, "{f}", .{look.quoted(lookPath(&relbuf, path, dir))}) catch lookPath(&relbuf, path, dir); const width = addressWidth(rel, index.len); var sh: Shades = .{}; defer sh.done(p); @@ -1194,10 +1200,11 @@ fn makeGrepRows(p: *Pardes, id: usize, full: bool) !void { defer sh.done(p); var width: usize = 0; var relbuf: [4096]u8 = undefined; + var namebuf: [8192]u8 = undefined; for (q.found.items[lo..hi], lo..) |fd, i| { const name = q.found_bytes.items[fd.path..][0..fd.path_len]; const path = std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), name }) catch continue; - const rel = lookPath(&relbuf, path, dir); + const rel = std.fmt.bufPrint(&namebuf, "{f}", .{look.quoted(lookPath(&relbuf, path, dir))}) catch lookPath(&relbuf, path, dir); if (!std.mem.eql(u8, name, last_path)) { last_path = name; try q.items.append(p.gpa, .{ .kind = .header }); @@ -1259,19 +1266,21 @@ pub fn take(p: *Pardes, q: *Query, kind: Stream.Kind, rows: []const u8) void { const t = look.parsePathLine(ln); if (t.at.line == 0 or t.path.len == 0) continue; const code = if (t.end < ln.len) ln[t.end + 1 ..] else ""; - // A row is a line's text, a file's name in it unescaped (one - // named `a:5000000000:b` reads as `a` at line 5000000000): one - // whose numbers a Found cannot hold is passed over. + // The worker writes a name that needs it quoted (look.quoted: + // a newline in it was a row of its own); one whose numbers a + // Found cannot hold is passed over. + var namebuf: [4096]u8 = undefined; + const name = if (ln[0] == '"') look.unquoted(&namebuf, t.path) else t.path; const found: Found = .{ .path = std.math.cast(u32, q.found_bytes.items.len) orelse return, - .path_len = std.math.cast(u16, t.path.len) orelse continue, + .path_len = std.math.cast(u16, name.len) orelse continue, .line = std.math.cast(u32, t.at.line) orelse continue, .col = std.math.cast(u32, t.at.col -| 1) orelse continue, .end = std.math.cast(u32, if (t.at.end_col > 0) t.at.end_col else t.at.col) orelse continue, - .code = std.math.cast(u32, q.found_bytes.items.len + t.path.len) orelse return, + .code = std.math.cast(u32, q.found_bytes.items.len + name.len) orelse return, .code_len = std.math.cast(u32, code.len) orelse continue, }; - q.found_bytes.appendSlice(p.gpa, t.path) catch return; + q.found_bytes.appendSlice(p.gpa, name) catch return; q.found_bytes.appendSlice(p.gpa, code) catch return; q.found.append(p.gpa, found) catch return; }, @@ -1357,13 +1366,14 @@ fn makeListRows(p: *Pardes, id: usize, pat: []const u8) !void { defer sh.done(p); var width: usize = 0; var relbuf: [4096]u8 = undefined; + var namebuf: [8192]u8 = undefined; for (sorted.items, 0..) |ln, li| { if (ln.len == 0) continue; if (pat.len > 0 and std.ascii.findIgnoreCase(ln, pat) == null) continue; const t = look.parsePathLine(ln); if (t.at.line == 0) continue; const path = if (t.path.len > 0 and t.path[0] == '/') t.path else std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), t.path }) catch continue; - const rel = lookPath(&relbuf, path, dir); + const rel = std.fmt.bufPrint(&namebuf, "{f}", .{look.quoted(lookPath(&relbuf, path, dir))}) catch lookPath(&relbuf, path, dir); if (!std.mem.eql(u8, t.path, last_path)) { last_path = t.path; try q.items.append(p.gpa, .{ .kind = .header }); diff --git a/core/Stream.zig b/core/Stream.zig index c231d413..2f700cb4 100644 --- a/core/Stream.zig +++ b/core/Stream.zig @@ -835,13 +835,13 @@ const Worker = struct { const ln = std.mem.trimEnd(u8, raw, " \t\r\n"); var cut = @min(ln.len, 400); while (cut > 0 and cut < ln.len and ln[cut] & 0xc0 == 0x80) cut -= 1; - try w.rows.print(w.gpa, "{s}:{d}:{d}{c}{d} {s}\n", .{ path, line, from + 1, config.range_sep, end, ln[0..cut] }); + try w.rows.print(w.gpa, "{f}:{d}:{d}{c}{d} {s}\n", .{ look.quoted(path), line, from + 1, config.range_sep, end, ln[0..cut] }); w.total += 1; } /// A listing's file: its name, relative to the base. fn file(w: *Worker, path: []const u8) !bool { - try w.rows.print(w.gpa, "{s}\n", .{path}); + try w.rows.print(w.gpa, "{f}\n", .{look.quoted(path)}); w.total += 1; try w.maybeSend(); return w.checkCap(); @@ -1278,6 +1278,53 @@ test "Stream: the listing of files for Find on a worker, a cap of hits stops the try testing.expectEqual(State.done, p.stream.state); } +test "Stream: a file named `a\\nb:1:1` is one Grep row and one Find name, its own, for the walk and rg; a row is a line" { + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + var root_buf: [4096]u8 = undefined; + // Up to 2026-11-23 its row, `a\nb:1:1:1:1-6 needle`, was two: `a` + // (no place) and a hit in a file `b`, line 1, that has none. + const odd = "a\nb:1:1"; + try tmp.dir.writeFile(testing.io, .{ .sub_path = odd, .data = "needle\n" }); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "b", .data = "hay\n" }); + const root = root_buf[0..try tmp.dir.realPath(testing.io, &root_buf)]; + for ([_]Engine{ .walk, .rg }) |engine| { + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 }); + defer p.deinit(); + const pane = try p.setTestFile("x\n"); + p.gpa.free(pane.file.?.path); + pane.file.?.path = try std.Io.Dir.path.join(p.gpa, &.{ root, "main.txt" }); + p.advance(1); + p.stream.engine = engine; + // No host workers: the search runs on the loop at the next tick. + panes.Query.open(p, 0, .grep, "", false); + const qp = for (p.panes) |slot| { + if (slot) |qp| if (qp.query != null) break qp; + } else return error.NoQueryPane; + const q = qp.query.?; + try query(p, qp.serial, .grep, "needle", root, .now); + p.update(.tick); + p.update(.tick); + if (engine == .rg and p.stream.used != .rg) return; // no rg here + try testing.expectEqual(@as(usize, 1), q.found.items.len); + const fd = q.found.items[0]; + try testing.expectEqualStrings(odd, q.found_bytes.items[fd.path..][0..fd.path_len]); + try testing.expectEqual(@as(u32, 1), fd.line); + // The pane's rows: a line each, its name's newline written `\n`. + const f = &qp.file.?; + try testing.expectEqual(std.mem.count(u8, f.content, "\n"), f.location_rows.len); + try testing.expect(std.mem.indexOf(u8, f.content, "\"a\\nb:1:1\"") != null); + // Find: the same name, once, opening that file. + panes.Query.open(p, 0, .find, "", false); + p.update(.tick); + p.update(.tick); + const fq = for (p.panes) |slot| { + if (slot) |fp| if (fp.query) |got| if (got.source == .find) break got; + } else return error.NoFindPane; + try testing.expectEqual(@as(usize, 2), fq.names.cands.items.len); + } +} + test "Stream: a big text's declarations are parsed on a worker, never the loop, and the rows of its / regroup under them" { if (comptime !syntax.minimal_grammars) return error.SkipZigTest; const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 }); diff --git a/core/colors.zig b/core/colors.zig index 7e692fe5..5579ed05 100644 --- a/core/colors.zig +++ b/core/colors.zig @@ -687,6 +687,29 @@ fn revertThemeFile(p: *Pardes) void { p.emit(.{ .theme_file = .{ .generation = generation, .on = loaded.len > 0 } }); } +/// The deepest a theme file's brackets nest: its schema is three levels +/// deep, and std's ZON parser recurses a level a bracket with no bound of +/// its own (a file 5 000 deep overflowed a 16 MiB stack in a Debug build: +/// the session's end, at every start that loaded it). +const max_theme_nesting = 64; + +/// How deep `source`'s brackets nest, as std's tokenizer reads it (strings +/// and comments are tokens of their own). +fn nesting(source: [:0]const u8) usize { + var tokens: std.zig.Tokenizer = .init(source); + var depth: usize = 0; + var most: usize = 0; + while (true) switch (tokens.next().tag) { + .eof => return most, + .l_brace, .l_bracket, .l_paren => { + depth += 1; + most = @max(most, depth); + }, + .r_brace, .r_bracket, .r_paren => depth -|= 1, + else => {}, + }; +} + pub fn loadThemeFile(p: *Pardes, generation: u32, bytes: []const u8) bool { // ZON's generated field dispatch grows with the complete theme schema. @setEvalBranchQuota(10000); @@ -700,6 +723,10 @@ pub fn loadThemeFile(p: *Pardes, generation: u32, bytes: []const u8) bool { return false; }; defer p.gpa.free(source); + if (nesting(source) > max_theme_nesting) { + themeFileFailure(p, request, std.fmt.comptimePrint("nested past {d} levels", .{max_theme_nesting})); + return false; + } // The parse's results live in `arena`; the theme kept owns only its name. var arena: std.heap.ArenaAllocator = .init(p.gpa); defer arena.deinit(); @@ -931,6 +958,31 @@ test "a theme file that cannot be read is named in the failure" { try std.testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "theme file /nowhere/mine.zon: ") != null); } +test "a theme file nested 10, 1 000 and 100 000 deep is refused in words, never a stack overflow" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .config_dir = "/tmp/pardes-config" }); + defer p.deinit(); + for ([_]usize{ 10, 1000, 100_000 }) |depth| { + requestThemeFile(p, 0, "themes/deep.zon"); + var source: std.ArrayList(u8) = .empty; + defer source.deinit(gpa); + try source.appendSlice(gpa, ".{ .name = \"deep\", .bg = "); + for (0..depth) |_| try source.appendSlice(gpa, ".{"); + try source.appendSlice(gpa, "1"); + for (0..depth) |_| try source.append(gpa, '}'); + try source.appendSlice(gpa, " }\n"); + p.panes[0].?.msg_len = 0; + // Up to 2026-11-23 std's parser took it: 5 000 deep overflowed the + // stack (a Debug build's 16 MiB). + try std.testing.expect(!loadThemeFile(p, p.theme_file_generation, source.items)); + const said = p.panes[0].?.msg[0..p.panes[0].?.msg_len]; + std.testing.expect(std.mem.indexOf(u8, said, "theme file /tmp/pardes-config/themes/deep.zon: ") != null) catch |err| { + std.debug.print("{d} deep: said {s}\n", .{ depth, said }); + return err; + }; + } +} + test "ThemeFile parses ZON atomically and Theme returns to the compiled ring" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, diff --git a/core/diff.zig b/core/diff.zig index 659576d3..edf037fe 100644 --- a/core/diff.zig +++ b/core/diff.zig @@ -294,11 +294,14 @@ fn range(line: []const u8, at: *usize) ?[2]usize { return .{ start, 1 }; } +/// A header's number: a line of a file, or a count of them, so a u32 (no +/// file pardes opens has more lines); one past it makes the line no header, +/// where the walk's count would overflow (a crafted `+18446744073709551615`). fn number(line: []const u8, at: *usize) ?usize { const from = at.*; - var n: usize = 0; + var n: u32 = 0; while (at.* < line.len and std.ascii.isDigit(line[at.*])) : (at.* += 1) - n = std.math.add(usize, std.math.mul(usize, n, 10) catch return null, line[at.*] - '0') catch return null; + n = std.math.add(u32, std.math.mul(u32, n, 10) catch return null, line[at.*] - '0') catch return null; return if (at.* > from) n else null; } diff --git a/core/fuzz.zig b/core/fuzz.zig index 0fce6f9d..4f291d64 100644 --- a/core/fuzz.zig +++ b/core/fuzz.zig @@ -784,3 +784,101 @@ test "9P: a rows style past the syntax's kinds is refused, never drawn" { _ = try p.render(p.frame_arena.allocator()); } } + +// --------------------------------------------------------------------------- +// (v, vi) Numbers in a file's text and in another program's answer: a +// diff's hunk headers (a `.diff` drawn, the patch view, a look's target) +// and a language server's rows (each kind's answer landed, stepped, drawn; +// the same places typed to Look). + +const diff = @import("diff.zig"); +const hunks = @import("hunks.zig"); +const lsp = pardes.lsp; + +/// Around what an int of each width holds, and past it. +const numbers = [_][]const u8{ "0", "1", "2", "3", "5", "65535", "2147483647", "2147483648", "3000000000", "4294967295", "4294967296", "9223372036854775807", "9223372036854775808", "18446744073709551615", "18446744073709551616", "99999999999999999999999" }; + +fn draw(p: *Pardes) !void { + p.sync(); + _ = p.frame_arena.reset(.retain_capacity); + _ = try p.render(p.frame_arena.allocator()); +} + +fn diffSeed(gpa: std.mem.Allocator, seed: u64) !void { + var prng: Random.DefaultPrng = .init(seed); + const r = prng.random(); + var text: std.ArrayList(u8) = .empty; + defer text.deinit(gpa); + try text.appendSlice(gpa, "diff --git a/x.zig b/x.zig\n--- a/x.zig\n+++ b/x.zig\n"); + for (0..1 + r.uintLessThan(usize, 3)) |_| { + try text.print(gpa, "@@ -{s}", .{pick(r, numbers)}); + if (chance(r, 0.7)) try text.print(gpa, ",{s}", .{pick(r, numbers)}); + try text.print(gpa, " +{s}", .{pick(r, numbers)}); + if (chance(r, 0.7)) try text.print(gpa, ",{s}", .{pick(r, numbers)}); + try text.appendSlice(gpa, " @@ fn x()\n"); + const lines = [_][]const u8{ " const a = 1;\n", "-const b = 2;\n", "+const b = 3;\n", "\\ No newline at end of file\n", "\n", "--- y\n", "+++ y\n", "text\n" }; + for (0..r.uintLessThan(usize, 9)) |_| try text.appendSlice(gpa, pick(r, lines)); + } + // A `.diff` drawn. + const p = try th.withFile(gpa, text.items); + defer p.deinit(); + const pane = p.panes[p.view().active].?; + gpa.free(pane.file.?.path); + pane.file.?.path = try gpa.dupe(u8, "/change.diff"); + pane.file.?.syntax_dirty = true; + try draw(p); + // The patch view. + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const ctx: hunks.Ctx = .{ .arena = arena.allocator() }; + _ = hunks.format(&ctx, "", text.items) catch {}; + // A look's target, at every row. + var rows: std.ArrayList([]const u8) = .empty; + defer rows.deinit(gpa); + var it = std.mem.splitScalar(u8, text.items, '\n'); + while (it.next()) |row| try rows.append(gpa, row); + for (0..rows.items.len) |row| _ = diff.targetAt(rows.items, row, false); +} + +test "a diff's hunk headers with numbers past any file's: drawn, formatted and looked at, never a panic" { + for (seeds) |seed| for (0..4) |k| try diffSeed(testing.allocator, seed *% 31 +% k); +} + +fn lspSeed(gpa: std.mem.Allocator, seed: u64) !void { + var prng: Random.DefaultPrng = .init(seed); + const r = prng.random(); + const p = try th.withFile(gpa, "alpha one\n\tbeta\n\t\tgamma \xe6\x97\xa5\n\n"); + defer p.deinit(); + var rows: std.ArrayList(u8) = .empty; + defer rows.deinit(gpa); + for (0..1 + r.uintLessThan(usize, 4)) |_| { + // As lsp.sourceSpanRow writes them; the file's own name. + try rows.print(gpa, "/test.txt:{s}:{s}", .{ pick(r, numbers), pick(r, numbers) }); + if (chance(r, 0.5)) try rows.print(gpa, "-{s}", .{pick(r, numbers)}); + try rows.appendSlice(gpa, " alpha\n"); + } + const kinds = [_]lsp.Kind{ .definition, .declaration, .implementation, .references, .diagnostics, .document_symbols, .workspace_symbols }; + const kind = pick(r, kinds); + if (lsp.supports.contains(kind)) { + p.lspRequest(0, kind, ""); + while (p.nextEffect()) |_| {} + if (p.lsp_ask.wait) |wait| p.update(.{ .lsp_resp = .{ .id = wait.id, .rows = rows.items } }); + try draw(p); + for ("nNjk\r") |key| { + p.update(.{ .key = .{ .cp = if (key == '\r') pardes.Key.enter else key } }); + try draw(p); + } + } + // The same places typed. + var look: [96]u8 = undefined; + p.update(.{ .command = try std.fmt.bufPrint(&look, "Look /test.txt:{s}:{s}", .{ pick(r, numbers), pick(r, numbers) }) }); + try draw(p); + p.update(.{ .command = try std.fmt.bufPrint(&look, "Look /test.txt:{s}:{s}-{s}:{s}", .{ pick(r, numbers), pick(r, numbers), pick(r, numbers), pick(r, numbers) }) }); + try draw(p); + p.update(.{ .command = try std.fmt.bufPrint(&look, "Look /test.txt:{s}-{s}", .{ pick(r, numbers), pick(r, numbers) }) }); + try draw(p); +} + +test "a language server's rows and a typed Look with numbers past any file's: landed, stepped and drawn, never a panic" { + for (seeds) |seed| for (0..4) |k| try lspSeed(testing.allocator, seed *% 31 +% k); +} diff --git a/core/hunks.zig b/core/hunks.zig index 8f56f8f1..fdc040da 100644 --- a/core/hunks.zig +++ b/core/hunks.zig @@ -15,6 +15,7 @@ const std = @import("std"); const diff = @import("diff.zig"); const syntax = @import("syntax.zig"); const locations = @import("locations.zig"); +const look = @import("look.zig"); const pardes = @import("root.zig"); const Pardes = pardes.Pardes; @@ -385,7 +386,7 @@ fn flush(ctx: *const Ctx, out: *Out, hunk: *Hunk, memo: *SourceMemo, scratch: *[ var row = declaration.start_line; while (row <= declaration.header_end_line and row < start_row) : (row += 1) { if (row == declaration.start_line and ctx.tslocations) { - const label = try std.fmt.allocPrint(arena, "{s}:{d}", .{ shown, row + 1 }); + const label = try std.fmt.allocPrint(arena, "{f}:{d}", .{ look.quoted(shown), row + 1 }); try out.row(arena, label, .{ .kind = .declaration, .path = shown, .line = row + 1, .location_end = label.len, .code_start = label.len }); } // A blank where a hunk line has its marker: the code aligns. @@ -396,7 +397,8 @@ fn flush(ctx: *const Ctx, out: *Out, hunk: *Hunk, memo: *SourceMemo, scratch: *[ // The hunk's label: a step for n and N, and a look's place. const line_no = change_row + 1; var label: std.Io.Writer.Allocating = .init(arena); - try label.writer.print("{s}:{d}", .{ shown, line_no }); + // The name as a row writes it (look.quoted): a `:` in it never splits it. + try label.writer.print("{f}:{d}", .{ look.quoted(shown), line_no }); const location_end = label.written().len; if (depth > 0) { try label.writer.writeByte(' '); diff --git a/core/look.zig b/core/look.zig index b240b6e2..72bb42eb 100644 --- a/core/look.zig +++ b/core/look.zig @@ -67,13 +67,89 @@ fn num(tok: []const u8, i: usize) struct { v: usize, end: usize } { return .{ .v = v, .end = j }; } +/// A file's name in a row (a Grep's, Find's, a query pane's, the patch +/// view's), written as git writes an unusual one (quote_c_style): one with +/// a control byte, a `"`, a `\` or a `:` in double quotes, `\n \t \r \" \\` +/// and `\ooo` for any other control byte, so that a row is one line and its +/// name never splits at a `:`. Any other name as it is. +pub fn quoted(name: []const u8) Quoted { + return .{ .name = name }; +} + +pub const Quoted = struct { + name: []const u8, + + pub fn format(q: Quoted, w: *std.Io.Writer) std.Io.Writer.Error!void { + for (q.name) |c| { + if (c < 0x20 or c == 0x7f or c == '"' or c == '\\' or c == config.line_col_sep) break; + } else return w.writeAll(q.name); + try w.writeByte('"'); + for (q.name) |c| switch (c) { + '\n' => try w.writeAll("\\n"), + '\t' => try w.writeAll("\\t"), + '\r' => try w.writeAll("\\r"), + '"', '\\' => try w.print("\\{c}", .{c}), + 0...0x08, 0x0b, 0x0c, 0x0e...0x1f, 0x7f => try w.print("\\{o:0>3}", .{c}), + else => try w.writeByte(c), + }; + try w.writeByte('"'); + } +}; + +/// A quoted name's inside (parsePathLine's path of a `"`-led word) read +/// back into `buf` (escapes only shrink it: `buf` as long as `inside` is +/// enough). +pub fn unquoted(buf: []u8, inside: []const u8) []const u8 { + var n: usize = 0; + var i: usize = 0; + while (i < inside.len and n < buf.len) : (n += 1) { + const c = inside[i]; + i += 1; + buf[n] = c; + if (c != '\\' or i == inside.len) continue; + const e = inside[i]; + i += 1; + buf[n] = switch (e) { + 'n' => '\n', + 't' => '\t', + 'r' => '\r', + 'a' => 0x07, + 'b' => 0x08, + 'v' => 0x0b, + 'f' => 0x0c, + else => e, + }; + // `\ooo`: three octal digits. + if (i + 2 <= inside.len) if (std.fmt.parseInt(u8, inside[i - 1 .. i + 2], 8)) |v| { + buf[n] = v; + i += 2; + } else |_| {}; + } + return buf[0..n]; +} + +/// Where a `"`-led word's quoted name closes (`quoted`'s), past its +/// escapes; null when it is no quoted name. +fn quoteEnd(tok: []const u8) ?usize { + if (tok.len < 2 or tok[0] != '"') return null; + var i: usize = 1; + while (i < tok.len) : (i += 1) switch (tok[i]) { + '\\' => i += 1, + '"' => return i, + else => {}, + }; + return null; +} + pub fn parsePathLine(tok: []const u8) struct { path: []const u8, at: Spot, end: usize } { - var sep: usize = 0; + // A quoted name (a row's: `quoted`) is the path whole, its `:` its own. + const close = quoteEnd(tok); + var sep: usize = if (close) |c| c + 1 else 0; while (sep < tok.len) : (sep += 1) { if (tok[sep] != config.line_col_sep) continue; const l = num(tok, sep + 1); if (l.end == sep + 1) continue; // no digits after ':' - const path = tok[0..sep]; + const path = if (close) |c| tok[1..c] else tok[0..sep]; var i = l.end; if (i < tok.len and tok[i] == config.range_sep) { const e = num(tok, i + 1); @@ -753,20 +829,29 @@ pub fn focusPaneLine(p: *Pardes, id: usize, at_in: Spot, landing: enum { center, } } } - pane.body.cur_row = @intCast(at.line - 1); - pane.body.cur_col = if (at.col > 0) @intCast(at.col - 1) else 0; + 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); pane.body.cur_pinned = true; if (at.end_line != 0) return selectSpan(p, pane, at); pane.ensureCursorVisible(p.settings.tab); } +/// A place's column (from 1) as a cursor's on `row`: past the line's end (a +/// server's answer, a typed number: any) it is the end, as a search's +/// landing and clampCursor have it. A terminal's (a jump's) as it was. +fn columnOn(pane: *const Pane, row: i32, col: usize) i32 { + if (pane.file == null) return std.math.lossyCast(i32, col -| 1); + return @intCast(@min(col -| 1, panes.File.sourceLine(pane, row).len)); +} + fn selectSpan(p: *Pardes, pane: *Pane, at: Spot) void { const text = edit.flatSurface(p.editor(), &pane.body) catch |err| return p.reportError(.at(p.view().active), "look", err); // saturating, not `- 1`: `f.zig:0-5` is a legal thing to type and a // 1-based zero is the same nothing an absent number is - const acol: i32 = @intCast(at.col -| 1); - const ecol: i32 = if (at.end_col > 0) @intCast(at.end_col - 1) else std.math.maxInt(i32); - const r = panes.Text.cellRange(text, @intCast(at.line -| 1), acol, @intCast(at.end_line -| 1), ecol); + // Any number a place has: cellRange clamps each to the text. + const acol = std.math.lossyCast(i32, at.col -| 1); + const ecol: i32 = if (at.end_col > 0) std.math.lossyCast(i32, at.end_col - 1) else std.math.maxInt(i32); + const r = panes.Text.cellRange(text, std.math.lossyCast(i32, at.line -| 1), acol, std.math.lossyCast(i32, at.end_line -| 1), ecol); pane.body.setRange(p.settings.tab, text, 0, r, true); } @@ -1605,7 +1690,7 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { const free = p.freeSlot() orelse return p.reportError(.at(id), "look", error.NoPaneSlots); const nt = panes.File.open(p, free, target.path, target.at.line) catch |err| return lookOpenFailed(p, id, target.path, err); - if (target.at.col > 0) nt.body.cur_col = @intCast(target.at.col - 1); + nt.body.cur_col = columnOn(nt, nt.body.cur_row, target.at.col); const failures = p.fs.failures; layout.placeNew(p, id, id, free, .doc); // Refused a place: that is the look's one failure, not a @@ -2025,6 +2110,39 @@ test "Look copies its operand before releasing pointer selection storage" { try std.testing.expectEqual(.none, p.view().drag); } +test "a Look whose column is past its line's end lands at the end, however big; a line past the file's is a miss" { + const p = try Pardes.init(std.testing.allocator, .{ .cols = 60, .rows = 12 }); + defer p.deinit(); + const pane = try p.setTestFile("alpha\n\tbeta\n"); + // Up to 2026-11-23 a column past i32 panicked the session (`@intCast` + // in focusPaneLine): any text a B3 or Look takes, a server's row. + for ([_][]const u8{ "/test.txt:2:9", "/test.txt:2:3000000000", "/test.txt:2:18446744073709551615" }) |place| { + lookAt(p, 0, place); + try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); + try std.testing.expectEqual(@as(i32, 5), pane.body.cur_col); + } + // A span past the text: selected to its end. + lookAt(p, 0, "/test.txt:1:2-3000000000:3000000000"); + try std.testing.expect(pane.body.vsel.active); + pane.body.cur_row = 0; + lookAt(p, 0, "/test.txt:3000000000:1"); + try std.testing.expectEqual(@as(i32, 0), pane.body.cur_row); +} + +test "a file's name written as a row writes it reads back whole: a newline, a `:5:`, a quote, a control byte; a plain name as it is" { + var row: [256]u8 = undefined; + var back: [256]u8 = undefined; + for ([_][]const u8{ "a\nb:1:1", "a:5:b.txt", "say \"hi\".txt", "bell\x07\x1b[31m", "back\\slash", "plain/name.zig" }) |name| { + const written = try std.fmt.bufPrint(&row, "{f}:12:3-5 code", .{quoted(name)}); + try std.testing.expect(std.mem.indexOfScalar(u8, written, '\n') == null); + const got = parsePathLine(written); + try std.testing.expectEqual(@as(usize, 12), got.at.line); + try std.testing.expectEqual(@as(usize, 3), got.at.col); + try std.testing.expectEqualStrings(name, if (written[0] == '"') unquoted(&back, got.path) else got.path); + } + try std.testing.expectEqualStrings("plain/name.zig:1", try std.fmt.bufPrint(&row, "{f}:1", .{quoted("plain/name.zig")})); +} + test "@p names a pane by its serial, as /index does" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 60, .rows = 12 }); defer p.deinit(); diff --git a/core/replica.zig b/core/replica.zig index 72662df6..829972c2 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -3726,6 +3726,11 @@ fn endJoin(j: *Joined, have: ?*Have) void { /// as `Peers.join` sends it: its state, its blobs put back where they go. fn joinedNow(a: *Authority, id: u16, view: u8) !*Replica { const gpa = std.testing.allocator; + // What was recorded goes first, as a join sends it (Peers.dumped): + // left on the tape, the joiner's first unit replayed it over the dump + // it loaded (a session's `init` first: a core made afresh). + a.seq += 1; + _ = try a.unit(0, a.seq); const was = Stepping.begin(&a.t, null); var blobs: std.ArrayListUnmanaged(walk.Deferred) = .empty; defer blobs.deinit(a.core.gpa); @@ -3794,6 +3799,33 @@ fn shows(p: *Pardes, text: []const u8) !bool { return false; } +test "a client joined from a dump keeps the session's jump list through a step: two entries the same but for their place's undefined bytes are one entry on both" { + // The release soak's parting (the witness: `views[3].jumps`): a text's + // entry has `.place = .{}`, bytes undefined: a session's are its + // stack's (here 0x11 and 0x22, the two a release build left), a + // client's what its load left; the step drops the gone entry between + // the two and makes them one where they compare the same. + const gpa = std.testing.allocator; + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); + defer a.deinit(); + const v = a.core.view(); + const serial = a.core.panes[v.active].?.serial; + var at: pardes.Jump.Loc = .{ .pane = @intCast(v.active), .serial = serial, .line = 1, .col = 1 }; + var again = at; + @memset(&at.place.bytes, 0x11); + @memset(&again.place.bytes, 0x22); + v.jumps.list[0] = at; + v.jumps.list[1] = .{ .pane = 5, .serial = 999, .line = 1, .col = 1 }; + v.jumps.list[2] = again; + v.jumps.list[3] = .{ .pane = @intCast(v.active), .serial = serial, .line = 150, .col = 1 }; + v.jumps.n, v.jumps.cur = .{ 4, 3 }; + const r = try joinedNow(a, 1, 0); + defer r.deinit(); + r.confirm(try a.local(.{ .key = .{ .cp = 'l', .text = "l" } })); + try agrees(a, r); + try std.testing.expectEqual(@as(usize, 2), r.core().view().jumps.n); +} + test "a message past the wire's bound is named, never read as the link's end" { var fds: [2]c_int = undefined; try std.testing.expectEqual(0, libc.pipe(&fds)); diff --git a/core/walk.zig b/core/walk.zig index 02e46454..91400bc1 100644 --- a/core/walk.zig +++ b/core/walk.zig @@ -89,6 +89,45 @@ pub fn digest(comptime T: type, v: *const T) u64 { return h.final(); } +/// Equal as the digest sees them, by the digest's rules: what the walk +/// leaves out (a field `replica` names, a Buf's bytes past its length) is +/// not compared; a type that walks itself, by its digest. std.meta.eql +/// compares every byte of an array, and those bytes are undefined: 0xAA on +/// every Debug process, each release process's own garbage; a decision of +/// the core taken on them agrees between a session and its clients in +/// Debug alone. +pub fn eql(comptime T: type, a: *const T, b: *const T) bool { + switch (@typeInfo(T)) { + .void => return true, + .bool, .int, .@"enum" => return a.* == b.*, + .optional => |o| return if (a.*) |*x| (if (b.*) |*y| eql(o.child, x, y) else false) else b.* == null, + .array => |arr| { + if (comptime flatHash(arr.child)) return std.mem.eql(arr.child, a, b); + for (a, b) |*x, *y| if (!eql(arr.child, x, y)) return false; + return true; + }, + .@"struct" => |s| { + if (comptime machinery(T)) return true; + if (comptime s.layout == .@"packed" or @hasDecl(T, "digest") or isList(T) or isAtomic(T) or isBitset(T) or @hasField(T, "any_future")) return digest(T, a) == digest(T, b); + 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 lengthOf(T, name)) |len| { + const x = @field(a, name)[0..lengthIn(a, len)]; + const y = @field(b, name)[0..lengthIn(b, len)]; + if (comptime flatHash(Element(F))) { + if (!std.mem.eql(Element(F), x, y)) return false; + } else { + if (x.len != y.len) return false; + for (x, y) |*p, *q| if (!eql(Element(F), p, q)) return false; + } + } else if (!eql(F, &@field(a, name), &@field(b, name))) return false; + } + return true; + }, + else => return digest(T, a) == digest(T, b), + } +} + /// 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 { |
