From 44b4d81cd1ba49a035e66699416639b46723c872 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 21 Nov 2026 01:31:16 -0300 Subject: library: a dependent package names its languages: `.languages = "rust"` (or a list) replaces the `.grammars` tier with the languages named and what each needs, the manifest's new `needs` field (markdown brings markdown_inline; no other grammar needs one: a fence's language is coloured when it is in the build), so a browser reader builds one module per language; a name the manifest does not have, or `.grammars` beside `.languages`, ends the configure with exit 1 and the names it has (Zig only logs an option it cannot read in a dependency and builds on with exit 0); build.zig exports `grammar_manifest` for a consumer's build script to loop over at configure time; build/core.zig treeSitter takes a set (`GrammarSet`, `tierSet`) and syntax.zig knows the set by the queries the build gave (`@hasDecl(ts_queries, ...)`), not by the tier; test/consumer loops over the manifest (`each-language`, 26/26: each language alone is in its build, linked by its symbol, and no other is), `test` runs rust and markdown of it and a configure with `klingon` that fails saying so Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- test/consumer/build.zig | 47 ++++++++++++++++++++++++++++++++++++++++++----- test/consumer/one.zig | 45 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 87 insertions(+), 5 deletions(-) create mode 100644 test/consumer/one.zig (limited to 'test/consumer') diff --git a/test/consumer/build.zig b/test/consumer/build.zig index c643bfb3..fbf19f61 100644 --- a/test/consumer/build.zig +++ b/test/consumer/build.zig @@ -1,21 +1,29 @@ //! A package that depends on pardes, as a program would (build.zig's head //! comment has its lines): pardes's `consumer-test`, which `unit-test` runs, //! runs `zig build test` here. `pardes-syntax` with the minimal grammars, -//! as a program that draws source text itself takes it; and -//! `pardes-editor` with no grammar of pardes's and one of its own, C's, -//! compiled here from the package pardes pins and handed in at run time, -//! as sketchbook's `examples/live` takes it. +//! as a program that draws source text itself takes it; with one language +//! named, for each language of pardes's manifest, read here at configure +//! time; and `pardes-editor` with no grammar of pardes's and one of its own, +//! C's, compiled here from the package pardes pins and handed in at run +//! time, as sketchbook's `examples/live` takes it. const std = @import("std"); +const pardes = @import("pardes"); pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); + // A name pardes's manifest does not have ends the configure: the step + // `bad-language` below runs this build with one. + if (b.option([]const u8, "language", "configure pardes with this one language named, and stop")) |name| { + _ = b.dependency("pardes", .{ .target = target, .optimize = optimize, .languages = name }); + return; + } const syntax = b.dependency("pardes", .{ .target = target, .optimize = optimize, .grammars = .minimal }); const editor = b.dependency("pardes", .{ .target = target, .optimize = optimize, .grammars = .none, .editor = true }); // The grammar of its own: C's, from the package pardes's manifest pins // (so `--pkg-dir` at pardes's zig-pkg has it), as that package builds it. const grammar = b.dependency("ts_c", .{ .target = target, .optimize = .ReleaseFast, .@"build-shared" = false }).artifact("tree-sitter-c"); - const step = b.step("test", "colour, outline and walk a C and a Zig source through pardes's syntax, and edit a text with its editor and a grammar of this package's"); + const step = b.step("test", "colour, outline and walk a C and a Zig source through pardes's syntax, build it with one language named, and edit a text with its editor and a grammar of this package's"); // A file belongs to one module: the syntax alone, and the editor (which // has it as `.syntax`), each a test of its own. for ([_]struct { []const u8, []const u8, *std.Build.Dependency }{ .{ "lib.zig", "pardes-syntax", syntax }, .{ "editor.zig", "pardes-editor", editor } }) |t| { @@ -28,6 +36,35 @@ pub fn build(b: *std.Build) void { if (t[2] == editor) mod.linkLibrary(grammar); step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mod })).step); } + + // Each language a file names, from pardes's manifest: `pardes-syntax` + // with it alone (and what it needs). `test` runs two: rust, alone, and + // markdown, which brings its inline grammar. + const each = b.step("each-language", "build and test pardes-syntax with each language of its manifest named alone"); + for (pardes.grammar_manifest.all) |g| if (g.exts.len > 0) { + const name = b.addOptions(); + name.addOption([]const u8, "name", g.name); + const one = b.addRunArtifact(b.addTest(.{ .name = b.fmt("one-{s}", .{g.name}), .root_module = b.createModule(.{ + .target = target, + .optimize = optimize, + .root_source_file = b.path("one.zig"), + .imports = &.{ + .{ .name = "pardes-syntax", .module = b.dependency("pardes", .{ .target = target, .optimize = optimize, .languages = g.name }).module("pardes-syntax") }, + .{ .name = "language", .module = name.createModule() }, + }, + }) })); + each.dependOn(&one.step); + if (std.mem.eql(u8, g.name, "rust") or std.mem.eql(u8, g.name, "markdown")) step.dependOn(&one.step); + }; + // ...and a name it does not have: the configure fails, saying so. + const bad = b.addSystemCommand(&.{ b.graph.zig_exe, "build", "-Dlanguage=klingon", "--pkg-dir", "../../zig-pkg" }); + bad.setName("a language pardes does not have fails the configure"); + bad.setCwd(b.path(".")); + bad.expectExitCode(1); + bad.addCheck(.{ .expect_stderr_match = "no language \"klingon\"" }); + bad.has_side_effects = true; + step.dependOn(&bad.step); + // What a key costs, a page count and a parse: `zig build bench -- `. const bench = b.addExecutable(.{ .name = "bench", .root_module = b.createModule(.{ .target = target, diff --git a/test/consumer/one.zig b/test/consumer/one.zig new file mode 100644 index 00000000..4a113842 --- /dev/null +++ b/test/consumer/one.zig @@ -0,0 +1,45 @@ +//! `pardes-syntax` built with one language named (`.languages`, build.zig +//! here: the build's loop over pardes's manifest makes one of these a +//! language): that language and what it needs (the manifest's `needs`) are +//! compiled in, and no other. +const std = @import("std"); +const ps = @import("pardes-syntax"); +const language = @import("language").name; + +test "one language named: it and what it needs are in the build, no other grammar is linked" { + const gpa = std.testing.allocator; + ps.start(gpa); + defer ps.stop(); + const g = ps.grammars; + const named = comptime named: { + @setEvalBranchQuota(10_000); + break :named g.all[g.byName(language).?]; + }; + // This test program's own bytes (a Debug build keeps its symbols): a + // name is spelled whole only in its symbol table. + const self = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, "/proc/self/exe", gpa, .unlimited); + defer gpa.free(self); + var name: [64]u8 = undefined; + inline for (g.all) |other| { + const in = comptime std.mem.eql(u8, other.name, named.name) or for (named.needs) |n| { + if (std.mem.eql(u8, n, other.name)) break true; + } else false; + // the parser itself, by its symbol in this program's symbol table: + // linked, or not in it + const symbol = try std.fmt.bufPrint(&name, "\x00tree_sitter_{s}\x00", .{other.name}); + try std.testing.expectEqual(in, std.mem.indexOf(u8, self, symbol) != null); + if (other.exts.len > 0) try std.testing.expectEqual(in, ps.supportsPath(ps.pathFor(other.name).?)); + } + + // what two of them colour: rust alone, and markdown with the inline + // grammar it brings (its bold is markdown_inline's) + for ([_]struct { []const u8, []const u8, []const u8, ps.Syn }{ + .{ "rust", "fn main() { let x = 1; }\n", "fn", .keyword }, + .{ "markdown", "# Title\n\nsome **bold** text\n", "bold", .comment }, + }) |case| if (std.mem.eql(u8, case[0], named.name)) { + const styles = try ps.highlightFileRange(gpa, ps.pathFor(language).?, case[1], 0, case[1].len); + defer gpa.free(styles); + const at = std.mem.indexOf(u8, case[1], case[2]).?; + for (styles[at..][0..case[2].len]) |s| try std.testing.expectEqual(case[3], @as(ps.Syn, @fromBackingInt(s))); + }; +} -- cgit v1.3 From ee5b6aa3ef0bf398c5381498af40fa93d20cf0b3 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 21 Nov 2026 01:59:49 -0300 Subject: library: the patch view without the editor: pardes-syntax exports hunks.format as `formatPatch` with its `PatchCtx` (an arena; optional `source`, `declarations` (`PatchCtx.parsed`), `colors` (`PatchCtx.languages`: highlightDiff's), `width`; their defaults no file, no declaration, no colour, code points) and its rows, `Patch`, `PatchRow` (kind other, meta, hunk, declaration, context, added, removed; the path; the line it points at; the old and the new number, each null where that side has none; location_end, code_start; a style byte a byte; no_newline, the `\\ No newline` the editor folds into the line above); format no longer makes locations.Row (it needs no editor type: the file's first half imports nothing of root.zig's) and the editor's openDiff maps its rows onto a pane's (`paneResult`, one pass, the rows as before, so the +Diff is unchanged), handing in its own source, declarations cache, colours and display width (File.displayWidth, the one use of vaxis: `width` replaces Ctx.tab); with no `colors` the formatter calls nothing of tree-sitter (the grounds and the words a changed line changed are text alone); inferEdits' 8 MiB scratch is made once a format call, not once a run of changed lines (a browser's wasm memory took 8 MiB a run, never given back in the call); test/consumer: a C diff with no file (numbered by the diff, under git's `@@` words, `foo`/`bar` emphasised, coloured as C) and with main.c handed in (its declaration from the parse above `main.c:3 *`), and in a build with no grammar (none.zig: rows, grounds and the changed `*`, no colour; a file handed in places the hunk and makes no declaration up) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/hunks.zig | 300 +++++++++++++++++++++++++++++++++--------------- core/lib_syntax.zig | 17 +++ test/consumer/build.zig | 6 +- test/consumer/lib.zig | 95 +++++++++++++++ test/consumer/none.zig | 56 +++++++++ 5 files changed, 380 insertions(+), 94 deletions(-) create mode 100644 test/consumer/none.zig (limited to 'test/consumer') diff --git a/core/hunks.zig b/core/hunks.zig index 837d2a52..98584980 100644 --- a/core/hunks.zig +++ b/core/hunks.zig @@ -5,6 +5,12 @@ //! green, coloured as their file, and the words a changed line changed on //! a tinted ground as delta emphasises them (its edits.rs and align.rs, here as `inferEdits` //! and `Alignment`). +//! +//! `format`, and what it takes and gives, names no pane and reads no file +//! but through its `Ctx`: `pardes-syntax` exports it (core/lib_syntax.zig) +//! for a program with no editor, a browser's reader, and with no colours +//! handed in it names no grammar either. The +Diff in the editor, the +//! file's second half, maps its rows onto a pane's (`paneResult`). const std = @import("std"); const diff = @import("diff.zig"); const syntax = @import("syntax.zig"); @@ -15,45 +21,132 @@ const Pardes = pardes.Pardes; const Pane = pardes.Pane; const Output = pardes.panes.Output; -const Row = locations.Row; - -/// What `format` takes of the editor it stacks for: its allocators, the -/// files a diff names read as the editor reads them (in pardes an open -/// pane's text, else the disk's, each read a site of the step's tape: -/// openDiff), their declarations, and one setting. +/// What `format` takes of the program it stacks for: an arena, the files a +/// diff names (in pardes an open pane's text, else the disk's, each read a +/// site of the step's tape: openDiff), their declarations, the diff's +/// colours, a text's width, one setting. A program with no files leaves +/// `source` to answer none: each hunk is numbered as the diff numbers it, +/// under git's own function line. pub const Ctx = struct { - /// The text and rows made, the caller's. - gpa: std.mem.Allocator, - /// All else, the call's. + /// What `format` makes and returns, the caller's to keep while it reads + /// the rows, and everything else of the call. arena: std.mem.Allocator, /// `path` as a look from `dir` finds it, its text the arena's (or the - /// editor's, good for the call); null when it is not there. - source: *const fn (ctx: *const Ctx, dir: []const u8, path: []const u8) ?Source, + /// caller's, good for the call); null when it is not there. + source: *const fn (ctx: *const Ctx, dir: []const u8, path: []const u8) ?Source = none, /// The declarations of `bytes`, the file at `path`, outermost first - /// (syntax.analyzeSource's), the arena's. - declarations: *const fn (ctx: *const Ctx, path: []const u8, bytes: []const u8) error{OutOfMemory}![]const syntax.ContextDeclaration, - /// The two above's own. - host: *anyopaque, + /// (`parsed`: syntax.analyzeSource's), the arena's; none by default. + declarations: *const fn (ctx: *const Ctx, path: []const u8, bytes: []const u8) error{OutOfMemory}![]const syntax.ContextDeclaration = noDeclarations, + /// A style byte for each byte of the diff, the arena's, its lines' + /// colours (`languages`: each hunk's as its file's language); null, the + /// grounds alone, and no grammar or tree-sitter in the program. + colors: ?*const fn (ctx: *const Ctx, content: []const u8) anyerror![]u8 = null, + /// The cells `text` takes, by which a removed and an added line are one + /// line changed or two (`max_line_distance`): its code points, or as + /// pardes's panes draw it. + width: *const fn (ctx: *const Ctx, text: []const u8) usize = codepoints, + /// The functions' own. + host: *anyopaque = undefined, /// A declaration above a hunk gets its `path:line` row too /// (LocationsConfig's tslocations). - tslocations: bool, - /// A tab's width in cells (the core's `settings.tab`). - tab: u16, + tslocations: bool = true, + + pub fn none(_: *const Ctx, _: []const u8, _: []const u8) ?Source { + return null; + } + + pub fn noDeclarations(_: *const Ctx, _: []const u8, _: []const u8) error{OutOfMemory}![]const syntax.ContextDeclaration { + return &.{}; + } + + /// The file parsed by its path's grammar, each call. + pub fn parsed(ctx: *const Ctx, path: []const u8, bytes: []const u8) error{OutOfMemory}![]const syntax.ContextDeclaration { + return (syntax.analyzeSource(ctx.arena, path, bytes, true, false) catch return &.{}).declarations; + } + + /// The diff coloured as the editor colours it (syntax.highlightDiff). + pub fn languages(ctx: *const Ctx, content: []const u8) anyerror![]u8 { + return syntax.highlightDiff(ctx.arena, content, 0, content.len); + } + + pub fn codepoints(_: *const Ctx, text: []const u8) usize { + var n: usize = 0; + for (text) |c| n += @intFromBool(c & 0xc0 != 0x80); + return n; + } }; /// A file's text, and its path as `dir` and the path named resolve. pub const Source = struct { path: []const u8, bytes: []const u8 }; -/// The rows `content`, a diff, stacks to, for a pane in `dir`, with each -/// row's metadata (Output.fillRows). Text and rows are `ctx.gpa`'s. -pub fn format(ctx: *const Ctx, dir: []const u8, content: []const u8) !locations.Result { +/// A diff stacked: its text, and a row for each of its lines (row i is +/// line i), the arena's; a row's path may be the diff's own bytes. +pub const Patch = struct { text: []const u8, rows: []const Row }; + +pub const Row = struct { + kind: Kind, + /// The file its section names, as `dir` finds it (the diff's name when + /// it is not found); "" for `other` and `meta`. + path: []const u8 = "", + /// The line of that file it points at, from 1 (0: none): where the file + /// has it now when `source` found it moved, else the diff's number. + line: usize = 0, + /// A hunk line's number in the old and in the new file, as the diff + /// numbers them; null on the side it is not on (an added line's old) + /// and on the rows that are not a hunk's lines. + old: ?usize = null, + new: ?usize = null, + /// Bytes into its text: where its `path:line` ends, and where what + /// follows the label starts (a hunk's stars). + location_end: usize = 0, + code_start: usize = 0, + /// A style byte for each byte of its text, or none: a `Syn` in the low + /// bits (`syntax.syn_bits`, with `colors`) and the grounds over it: + /// `ground_add` or `ground_del` on a changed line, `ground_line` on the + /// marker of one no other line changed, `ground_emph` on the words a + /// changed line changed. + styles: []const u8 = &.{}, + /// The diff's `\ No newline at end of file` follows this line: it has + /// no row of its own (delta shows it so, and the editor). + no_newline: bool = false, + + pub const Kind = enum { + /// What is said around the hunks: a mailed patch's headers, its + /// message and its diffstat, as written. + other, + /// A section's own words: a new file's mode, a rename, `Binary files + /// ... differ` (its `diff` and `index` lines say nothing the labels + /// do not, and its `---`/`+++` are the labels'). + meta, + /// A hunk's label, `path:line` where it changes something, a star + /// for each declaration it stands in. + hunk, + /// What the hunk stands in, above its label: a declaration's + /// `path:line` (`tslocations`) and its header's lines, from the file + /// `source` found and `declarations` read; or, without them, git's + /// own function line from the `@@`. + declaration, + /// A hunk's lines, behind their ` `, `+` or `-`. + context, + added, + removed, + }; +}; + +/// The rows `content`, a diff, stacks to, its files looked for from `dir`. +pub fn format(ctx: *const Ctx, dir: []const u8, content: []const u8) !Patch { const arena = ctx.arena; - const styles = try syntax.highlightDiff(arena, content, 0, content.len); - var out: Out = .{ .gpa = ctx.gpa, .text = .init(ctx.gpa) }; - errdefer out.deinit(); + const styles = if (ctx.colors) |colors| try colors(ctx, content) else plain: { + const none = try arena.alloc(u8, content.len); + @memset(none, 0); + break :plain none; + }; + var out: Out = .{ .text = .init(arena) }; var walk: diff.Walk = .{}; var hunk: Hunk = .{}; var source: SourceMemo = .{}; + // inferEdits' scratch, made once a call. + var scratch: []u8 = &.{}; var at: usize = 0; // The empty text after a last newline is no line. while (at < content.len) { @@ -73,9 +166,11 @@ pub fn format(ctx: *const Ctx, dir: []const u8, content: []const u8) !locations. }); }, // A `\ No newline` belongs to the line above, as delta shows it. - .no_newline => {}, + .no_newline => if (hunk.lines.items.len > 0) { + hunk.lines.items[hunk.lines.items.len - 1].no_newline = true; + }, else => { - try flush(ctx, &out, &hunk, &source, dir); + try flush(ctx, &out, &hunk, &source, &scratch, dir); switch (got.kind) { .hunk => hunk = .{ .path = walk.path(), @@ -86,22 +181,20 @@ pub fn format(ctx: *const Ctx, dir: []const u8, content: []const u8) !locations. }, // What is said around the hunks, a mailed patch's // headers, message and diffstat, as it was written. - .other => try out.row(line, "", .{ .kind = .context, .at = .{} }), + .other => try out.row(arena, line, .{ .kind = .other }), // A section's own words (a new file's mode, a rename, // `Binary files ... differ`), muted; its `diff` and // `index` lines say nothing the labels do not. .meta => if (!std.mem.startsWith(u8, line, "diff ") and !std.mem.startsWith(u8, line, "index ")) - try out.row(line, "", .{ .kind = .context, .declaration = true, .at = .{} }), + try out.row(arena, line, .{ .kind = .meta }), else => {}, } }, } at = nl + 1; } - try flush(ctx, &out, &hunk, &source, dir); - const rows = try out.rows.toOwnedSlice(ctx.gpa); - errdefer locations.freeRows(ctx.gpa, rows); - return .{ .content = try out.text.toOwnedSlice(), .rows = rows, .anchor = null }; + try flush(ctx, &out, &hunk, &source, &scratch, dir); + return .{ .text = out.text.written(), .rows = out.rows.items }; } const HunkLine = struct { @@ -115,6 +208,7 @@ const HunkLine = struct { /// Paired with a line it changed (inferEdits): its words show that; /// unpaired, the whole line was added or removed. paired: bool = false, + no_newline: bool = false, }; const Hunk = struct { @@ -134,37 +228,14 @@ fn gitContext(line: []const u8) []const u8 { } const Out = struct { - gpa: std.mem.Allocator, text: std.Io.Writer.Allocating, rows: std.ArrayList(Row) = .empty, - fn deinit(out: *Out) void { - out.text.deinit(); - locations.freeRowList(out.gpa, &out.rows); - } - - const Meta = struct { - kind: @FieldType(Row, "kind"), - declaration: bool = false, - at: @FieldType(Row, "at"), - location_end: usize = 0, - code_start: usize = 0, - colors: []const u8 = &.{}, - }; - - /// One row: its text, a newline, and its metadata. - fn row(out: *Out, text: []const u8, path: []const u8, meta: Meta) !void { + /// One row: its text, a newline, and what it is. + fn row(out: *Out, arena: std.mem.Allocator, text: []const u8, r: Row) !void { try out.text.writer.writeAll(text); try out.text.writer.writeByte('\n'); - try locations.appendRow(out.gpa, &out.rows, .{ - .kind = meta.kind, - .declaration = meta.declaration, - .path = @constCast(path), - .at = meta.at, - .location_end = meta.location_end, - .code_start = meta.code_start, - .colors = @constCast(meta.colors), - }); + try out.rows.append(arena, r); } }; @@ -276,7 +347,7 @@ fn heldAt(memo: *const SourceMemo, hunk: *const Hunk, comptime side: Side, start return .{ .held = held, .of = @max(of, 1) }; } -fn flush(ctx: *const Ctx, out: *Out, hunk: *Hunk, memo: *SourceMemo, dir: []const u8) !void { +fn flush(ctx: *const Ctx, out: *Out, hunk: *Hunk, memo: *SourceMemo, scratch: *[]u8, dir: []const u8) !void { defer hunk.* = .{}; if (hunk.path.len == 0 or hunk.lines.items.len == 0) return; const arena = ctx.arena; @@ -310,13 +381,12 @@ fn flush(ctx: *const Ctx, out: *Out, hunk: *Hunk, memo: *SourceMemo, dir: []cons depth += 1; var row = declaration.start_line; while (row <= declaration.header_end_line and row < start_row) : (row += 1) { - const at: @FieldType(Row, "at") = .{ .line = row + 1 }; if (row == declaration.start_line and ctx.tslocations) { const label = try std.fmt.allocPrint(arena, "{s}:{d}", .{ shown, row + 1 }); - try out.row(label, shown, .{ .kind = .context, .declaration = true, .at = at, .location_end = label.len, .code_start = label.len }); + 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. - try out.row(try std.fmt.allocPrint(arena, " {s}", .{memo.lines[row]}), shown, .{ .kind = .context, .declaration = true, .at = at }); + try out.row(arena, try std.fmt.allocPrint(arena, " {s}", .{memo.lines[row]}), .{ .kind = .declaration, .path = shown, .line = row + 1 }); } }; @@ -329,12 +399,12 @@ fn flush(ctx: *const Ctx, out: *Out, hunk: *Hunk, memo: *SourceMemo, dir: []cons try label.writer.writeByte(' '); try label.writer.splatByteAll('*', depth); } - try out.row(label.written(), shown, .{ .kind = .match, .at = .{ .line = line_no }, .location_end = location_end, .code_start = label.written().len }); + try out.row(arena, label.written(), .{ .kind = .hunk, .path = shown, .line = line_no, .location_end = location_end, .code_start = label.written().len }); // No file to read declarations from: git's own function line, muted // the same way. With one, git's guess (the last line before the hunk // that looked like a function) would only contradict it. if (side == .neither and hunk.header.len > 0) - try out.row(try std.fmt.allocPrint(arena, " {s}", .{hunk.header}), shown, .{ .kind = .context, .declaration = true, .at = .{ .line = line_no } }); + try out.row(arena, try std.fmt.allocPrint(arena, " {s}", .{hunk.header}), .{ .kind = .declaration, .path = shown, .line = line_no }); // Each run of removed lines and the added lines after it: the words // they changed. @@ -348,7 +418,7 @@ fn flush(ctx: *const Ctx, out: *Out, hunk: *Hunk, memo: *SourceMemo, dir: []cons while (i < lines.len and lines[i].kind == .removed) i += 1; const plus_start = i; while (i < lines.len and lines[i].kind == .added) i += 1; - try inferEdits(ctx.tab, arena, lines[minus_start..plus_start], lines[plus_start..i]); + try inferEdits(ctx, scratch, lines[minus_start..plus_start], lines[plus_start..i]); } // Each line behind its marker, `+`, `-` or a blank, as the diff @@ -368,7 +438,19 @@ fn flush(ctx: *const Ctx, out: *Out, hunk: *Hunk, memo: *SourceMemo, dir: []cons colors[0] = flag; @memcpy(colors[1..], line.styles); const on = moved(if (on_old) line.old else line.new, disk.shift); - try out.row(text, shown, .{ .kind = .preview, .at = .{ .line = @max(1, on) }, .colors = colors }); + try out.row(arena, text, .{ + .kind = switch (line.kind) { + .added => .added, + .removed => .removed, + else => .context, + }, + .path = shown, + .line = @max(1, on), + .old = if (line.kind == .added) null else line.old, + .new = if (line.kind == .removed) null else line.new, + .styles = colors, + .no_newline = line.no_newline, + }); } } @@ -385,18 +467,21 @@ const max_run = 256; const max_cells = 1 << 16; /// Pairs one hunk compares (each a table of up to `max_cells`): past it, the /// rest of its lines are shown unemphasised. And the scratch each pair is -/// aligned in, reused by the next: its table and the ranges it marks. +/// aligned in, reused by the next and by the next run's (one a `format`): +/// its table and the ranges it marks. const max_pairs = 4096; const pair_scratch_bytes = 8 << 20; /// Pair each removed line with the first added line after the last one /// paired that is near enough to it, in order, and emphasise in both the /// tokens one has and the other has not. -fn inferEdits(tab: u16, arena: std.mem.Allocator, minus: []HunkLine, plus: []HunkLine) !void { +fn inferEdits(ctx: *const Ctx, scratch_bytes: *[]u8, minus: []HunkLine, plus: []HunkLine) !void { if (minus.len == 0 or plus.len == 0 or minus.len > max_run or plus.len > max_run) return; + const arena = ctx.arena; const plus_tokens = try arena.alloc([]const []const u8, plus.len); for (plus, plus_tokens) |line, *tokens| tokens.* = try tokenize(arena, line.code); - var scratch: std.heap.FixedBufferAllocator = .init(try @import("memory.zig").unfilled(arena, pair_scratch_bytes)); + if (scratch_bytes.len == 0) scratch_bytes.* = try @import("memory.zig").unfilled(arena, pair_scratch_bytes); + var scratch: std.heap.FixedBufferAllocator = .init(scratch_bytes.*); var pairs: usize = 0; var plus_index: usize = 0; for (minus) |*m| { @@ -410,7 +495,7 @@ fn inferEdits(tab: u16, arena: std.mem.Allocator, minus: []HunkLine, plus: []Hun scratch.reset(); const pair = scratch.allocator(); var alignment = Alignment.init(pair, m_tokens, p_tokens) catch continue; - const marks = annotate(tab, pair, &alignment, m.code, plus[j].code) catch continue; + const marks = annotate(ctx, pair, &alignment, m.code, plus[j].code) catch continue; if (marks.distance > max_line_distance) continue; for (marks.minus) |r| for (m.styles[r[0]..r[1]]) |*b| { b.* |= syntax.ground_emph; @@ -536,7 +621,7 @@ const Marks = struct { /// what each deleted and inserted, and a run of blanks between two changes /// with them; the distance is the changed width over the whole width (a /// kept section counting on both lines). -fn annotate(tab: u16, arena: std.mem.Allocator, a: *const Alignment, minus_line: []const u8, plus_line: []const u8) !Marks { +fn annotate(ctx: *const Ctx, arena: std.mem.Allocator, a: *const Alignment, minus_line: []const u8, plus_line: []const u8) !Marks { var minus: std.ArrayList([2]usize) = .empty; var plus: std.ArrayList([2]usize) = .empty; var x_off: usize = 0; @@ -562,7 +647,7 @@ fn annotate(tab: u16, arena: std.mem.Allocator, a: *const Alignment, minus_line: switch (op) { .deletion => { const r = Take.section(a.x, &x_off, &m_byte, n, minus_line); - const w = trimmedWidth(tab, minus_line[r[0]..r[1]]); + const w = trimmedWidth(ctx, minus_line[r[0]..r[1]]); numer += w; denom += w; try minus.append(arena, r); @@ -571,7 +656,7 @@ fn annotate(tab: u16, arena: std.mem.Allocator, a: *const Alignment, minus_line: .noop => { const r = Take.section(a.x, &x_off, &m_byte, n, minus_line); const section = minus_line[r[0]..r[1]]; - denom += 2 * trimmedWidth(tab, section); + denom += 2 * trimmedWidth(ctx, section); const is_space = std.mem.trim(u8, section, " \t").len == 0; const coalesce = is_space and ((minus_prev == .deletion and plus_prev == .insertion and @@ -585,7 +670,7 @@ fn annotate(tab: u16, arena: std.mem.Allocator, a: *const Alignment, minus_line: }, .insertion => { const r = Take.section(a.y, &y_off, &p_byte, n, plus_line); - const w = trimmedWidth(tab, plus_line[r[0]..r[1]]); + const w = trimmedWidth(ctx, plus_line[r[0]..r[1]]); numer += w; denom += w; try plus.append(arena, r); @@ -597,8 +682,8 @@ fn annotate(tab: u16, arena: std.mem.Allocator, a: *const Alignment, minus_line: return .{ .minus = minus.items, .plus = plus.items, .distance = distance }; } -fn trimmedWidth(tab: u16, section: []const u8) usize { - return @import("File.zig").displayWidth(tab, std.mem.trim(u8, section, " \t")); +fn trimmedWidth(ctx: *const Ctx, section: []const u8) usize { + return ctx.width(ctx, std.mem.trim(u8, section, " \t")); } // ---- the +Diff in the editor ---- @@ -728,18 +813,22 @@ pub fn openDiff(p: *Pardes, id: usize, path: []const u8, content: []const u8) !u // The cache's may go at its next use: kept for the call. return ctx.arena.dupe(syntax.ContextDeclaration, hit.analysis.declarations); } + fn width(ctx: *const Ctx, text: []const u8) usize { + const pp: *Pardes = @ptrCast(@alignCast(ctx.host)); + return pardes.panes.File.displayWidth(pp.settings.tab, text); + } }; const ctx: Ctx = .{ - .gpa = p.gpa, .arena = p.scratch.allocator(), .source = Read.source, .declarations = Read.declarations, + .colors = Ctx.languages, + .width = Read.width, .host = p, .tslocations = p.locations_config.tslocations, - .tab = p.settings.tab, }; const root = sourceRoot(&ctx, dir, content); - const result = try format(&ctx, root, content); + const result = try paneResult(p.gpa, try format(&ctx, root, content)); errdefer { p.gpa.free(result.content); locations.freeRows(p.gpa, result.rows); @@ -756,6 +845,31 @@ pub fn openDiff(p: *Pardes, id: usize, path: []const u8, content: []const u8) !u return Output.fillRows(p, id, root, .{ .cmd = .Diff }, name, arg, result.content, result.rows, null); } +/// `patch`'s text and rows as a pane has them (Output.fillRows), `gpa`'s: a +/// hunk's label is a match n and N step to, what is around the hunks and +/// what they stand in is context (a section's words and a declaration +/// muted), a hunk's lines are previews of their file. +fn paneResult(gpa: std.mem.Allocator, patch: Patch) !locations.Result { + var rows: std.ArrayList(locations.Row) = .empty; + errdefer locations.freeRowList(gpa, &rows); + for (patch.rows) |r| try locations.appendRow(gpa, &rows, .{ + .kind = switch (r.kind) { + .hunk => .match, + .other, .meta, .declaration => .context, + .context, .added, .removed => .preview, + }, + .declaration = r.kind == .meta or r.kind == .declaration, + .path = @constCast(r.path), + .at = .{ .line = r.line }, + .location_end = r.location_end, + .code_start = r.code_start, + .colors = @constCast(r.styles), + }); + const content = try gpa.dupe(u8, patch.text); + errdefer gpa.free(content); + return .{ .content = content, .rows = try rows.toOwnedSlice(gpa), .anchor = null }; +} + /// Diff on a +Diff: the diff it stacks, as text. A pane holding it /// already (the newest: a +Pager folded under its +Diff unfolds) is /// shown; else the file is opened as text. @@ -796,7 +910,7 @@ const TestCtx = struct { fn init(t: *TestCtx) void { t.arena_state = .init(testing.allocator); - t.ctx = .{ .gpa = testing.allocator, .arena = t.arena_state.allocator(), .source = source, .declarations = declarations, .host = t, .tslocations = true, .tab = @import("config.zig").tab_width }; + t.ctx = .{ .arena = t.arena_state.allocator(), .source = source, .declarations = Ctx.parsed, .colors = Ctx.languages, .width = width }; syntax.start(testing.allocator); } @@ -811,8 +925,8 @@ const TestCtx = struct { return .{ .path = full, .bytes = bytes }; } - fn declarations(ctx: *const Ctx, path: []const u8, bytes: []const u8) error{OutOfMemory}![]const syntax.ContextDeclaration { - return (syntax.analyzeSource(ctx.arena, path, bytes, true, false) catch return &.{}).declarations; + fn width(_: *const Ctx, text: []const u8) usize { + return pardes.panes.File.displayWidth(@import("config.zig").tab_width, text); } }; @@ -822,15 +936,17 @@ fn emphasised(line: HunkLine) ![]const u8 { return out.toOwnedSlice(testing.allocator); } -fn expectEmphasis(tab: u16, minus: []const u8, plus: []const u8, want_minus: []const u8, want_plus: []const u8) !void { +fn expectEmphasis(minus: []const u8, plus: []const u8, want_minus: []const u8, want_plus: []const u8) !void { var arena_state: std.heap.ArenaAllocator = .init(testing.allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); + const ctx: Ctx = .{ .arena = arena, .width = TestCtx.width }; + var scratch: []u8 = &.{}; var m = [_]HunkLine{.{ .kind = .removed, .code = minus, .styles = try arena.alloc(u8, minus.len), .old = 1, .new = 1 }}; var p = [_]HunkLine{.{ .kind = .added, .code = plus, .styles = try arena.alloc(u8, plus.len), .old = 2, .new = 1 }}; @memset(m[0].styles, 0); @memset(p[0].styles, 0); - try inferEdits(tab, arena, &m, &p); + try inferEdits(&ctx, &scratch, &m, &p); const got_minus = try emphasised(m[0]); defer testing.allocator.free(got_minus); const got_plus = try emphasised(p[0]); @@ -840,16 +956,16 @@ fn expectEmphasis(tab: u16, minus: []const u8, plus: []const u8, want_minus: []c } test "delta's emphasis: the word a line changed, in both lines" { - try expectEmphasis(@import("config.zig").tab_width, " let x = foo(1);", " let x = bar(1);", "............foo....", "............bar...."); - try expectEmphasis(@import("config.zig").tab_width, "a b c", "a x c", "..b..", "..x.."); + try expectEmphasis(" let x = foo(1);", " let x = bar(1);", "............foo....", "............bar...."); + try expectEmphasis("a b c", "a x c", "..b..", "..x.."); } test "delta's emphasis: lines too far apart are no change of one another" { - try expectEmphasis(@import("config.zig").tab_width, "completely different text", "nothing alike here at all", ".........................", "........................."); + try expectEmphasis("completely different text", "nothing alike here at all", ".........................", "........................."); } test "delta's emphasis: a word added keeps the rest plain" { - try expectEmphasis(@import("config.zig").tab_width, "fn run(a: u32)", "fn run(a: u32, b: u32)", "..............", "............., b: u32."); + try expectEmphasis("fn run(a: u32)", "fn run(a: u32, b: u32)", "..............", "............., b: u32."); } test "delta's alignment: kitten to sitting, as align.rs has it" { @@ -880,7 +996,7 @@ test "a diff stacks to a label a hunk and its lines, markers gone, tinted and st \\ tail \\ ; - const result = try format(&t.ctx, "/pardes-surely-missing-dir", patch); + const result = try paneResult(testing.allocator, try format(&t.ctx, "/pardes-surely-missing-dir", patch)); defer testing.allocator.free(result.content); defer locations.freeRows(testing.allocator, result.rows); try testing.expectEqualStrings("nowhere/x.txt:2\n section one\n keep\n-old value\n+new value\n tail\n", result.content); @@ -919,7 +1035,7 @@ test "a hunk the file has moved since is found where it went, inside its declara \\ b(); \\ ; - const result = try format(&t.ctx, dir, patch); + const result = try paneResult(testing.allocator, try format(&t.ctx, dir, patch)); defer testing.allocator.free(result.content); defer locations.freeRows(testing.allocator, result.rows); try testing.expect(std.mem.indexOf(u8, result.content, "a.zig:3\n const S = struct {\na.zig:5 *\n") != null); @@ -947,7 +1063,7 @@ test "a mailed patch keeps its headers, message and diffstat above its hunks" { \\+b \\ ; - const result = try format(&t.ctx, "/pardes-surely-missing-dir", patch); + const result = try paneResult(testing.allocator, try format(&t.ctx, "/pardes-surely-missing-dir", patch)); defer testing.allocator.free(result.content); defer locations.freeRows(testing.allocator, result.rows); try testing.expectEqualStrings("From 0123 Mon Sep 17 00:00:00 2001\nSubject: [PATCH] change x\n\nWhy it changed.\n---\n x.txt | 2 +-\n\nx.txt:1\n-a\n+b\n", result.content); @@ -1038,7 +1154,7 @@ test "a hunk edited since, beside siblings with its signature's tail, is found i \\ c \\ ; - const result = try format(&t.ctx, dir, patch); + const result = try paneResult(testing.allocator, try format(&t.ctx, dir, patch)); defer testing.allocator.free(result.content); defer locations.freeRows(testing.allocator, result.rows); try testing.expect(std.mem.indexOf(u8, result.content, "a.rs:12\n fn three(\na.rs:15 *\n") != null); diff --git a/core/lib_syntax.zig b/core/lib_syntax.zig index f4f85820..0bb3f510 100644 --- a/core/lib_syntax.zig +++ b/core/lib_syntax.zig @@ -13,6 +13,7 @@ const syntax = @import("syntax.zig"); const colors = @import("colors.zig"); const modal = @import("modal.zig"); +const hunks = @import("hunks.zig"); /// Every grammar pardes knows (`all`), by name or alias (`byName`) and by /// path (`byPath`). The build's `grammars` option says which of them are @@ -70,6 +71,22 @@ pub const ground_emph = syntax.ground_emph; pub const ground_line = syntax.ground_line; pub const Grounds = colors.Grounds; +/// A unified diff stacked as pardes's patch view (its +Diff) shows it: +/// `formatPatch` gives a `Patch`, its text and a `PatchRow` a line: a +/// hunk's `path:line`, the declarations it stands in (or git's function +/// line), its lines with both their numbers, each byte's style (a `Syn` +/// when `colors` are given, the grounds, the words a changed line changed). +/// What it takes of the program is a `PatchCtx`: an arena, and optionally +/// the files the diff names (`source`, a `PatchSource`), their declarations +/// (`PatchCtx.parsed`), the colours (`PatchCtx.languages`, highlightDiff's) +/// and a text's width; with none of them it names no grammar and no +/// tree-sitter. +pub const formatPatch = hunks.format; +pub const PatchCtx = hunks.Ctx; +pub const PatchSource = hunks.Source; +pub const Patch = hunks.Patch; +pub const PatchRow = hunks.Row; + /// The tree-sitter bindings a tree is read through: `tree.rootNode()`, and /// a node's `kind()`, `startByte()`, `endByte()`, `child(i)`, `parent()`. pub const ts = syntax.ts; diff --git a/test/consumer/build.zig b/test/consumer/build.zig index fbf19f61..f8f63712 100644 --- a/test/consumer/build.zig +++ b/test/consumer/build.zig @@ -26,14 +26,16 @@ pub fn build(b: *std.Build) void { const step = b.step("test", "colour, outline and walk a C and a Zig source through pardes's syntax, build it with one language named, and edit a text with its editor and a grammar of this package's"); // A file belongs to one module: the syntax alone, and the editor (which // has it as `.syntax`), each a test of its own. - for ([_]struct { []const u8, []const u8, *std.Build.Dependency }{ .{ "lib.zig", "pardes-syntax", syntax }, .{ "editor.zig", "pardes-editor", editor } }) |t| { + // The patch view with no grammar at all: the editor's package has + // `pardes-syntax` too. + for ([_]struct { []const u8, []const u8, *std.Build.Dependency }{ .{ "lib.zig", "pardes-syntax", syntax }, .{ "editor.zig", "pardes-editor", editor }, .{ "none.zig", "pardes-syntax", editor } }) |t| { const mod = b.createModule(.{ .target = target, .optimize = optimize, .root_source_file = b.path(t[0]), .imports = &.{.{ .name = t[1], .module = t[2].module(t[1]) }}, }); - if (t[2] == editor) mod.linkLibrary(grammar); + if (std.mem.eql(u8, t[1], "pardes-editor")) mod.linkLibrary(grammar); step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mod })).step); } diff --git a/test/consumer/lib.zig b/test/consumer/lib.zig index 7e297920..fa0f8aee 100644 --- a/test/consumer/lib.zig +++ b/test/consumer/lib.zig @@ -159,3 +159,98 @@ test "a diff is a language: its hunks coloured as their file's, its added and re test "every name the library has compiles outside pardes" { std.testing.refAllDecls(pardes); } + +// ---- the patch view (+Diff), without the editor ---- + +const patch_c = + \\diff --git a/main.c b/main.c + \\--- a/main.c + \\+++ b/main.c + \\@@ -2,4 +2,4 @@ int main(void) + \\ { + \\- int x = foo(1); + \\+ int x = bar(1); + \\ return x; + \\ } + \\\ No newline at end of file + \\ +; +/// main.c as the patch leaves it: what a reader hands in as its source. +const main_c = "int main(void)\n{\n int x = bar(1);\n return x;\n}"; + +/// Each byte of `text` that has `bit`, the rest as dots. +fn marked(buf: []u8, text: []const u8, styles: []const u8, bit: u8) []const u8 { + for (buf[0..text.len], text, styles) |*o, c, s| o.* = if (s & bit != 0) c else '.'; + return buf[0..text.len]; +} + +test "a diff stacked with no file to read: numbered by the diff, under git's function line, its changed words emphasised" { + const gpa = std.testing.allocator; + pardes.start(gpa); + defer pardes.stop(); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const ctx: pardes.PatchCtx = .{ .arena = arena.allocator(), .colors = pardes.PatchCtx.languages }; + const p = try pardes.formatPatch(&ctx, "", patch_c); + try std.testing.expectEqualStrings("main.c:3\n int main(void)\n {\n- int x = foo(1);\n+ int x = bar(1);\n return x;\n }\n", p.text); + const Kind = pardes.PatchRow.Kind; + const want = [_]struct { Kind, ?usize, ?usize }{ + .{ .hunk, null, null }, + // the `@@`'s own words: the hunk's context + .{ .declaration, null, null }, + .{ .context, 2, 2 }, + .{ .removed, 3, null }, + .{ .added, null, 3 }, + .{ .context, 4, 4 }, + .{ .context, 5, 5 }, + }; + try std.testing.expectEqual(want.len, p.rows.len); + for (want, p.rows) |w, row| { + try std.testing.expectEqual(w[0], row.kind); + try std.testing.expectEqual(w[1], row.old); + try std.testing.expectEqual(w[2], row.new); + try std.testing.expectEqualStrings("main.c", row.path); + } + try std.testing.expectEqual(3, p.rows[0].line); + try std.testing.expectEqual("main.c:3".len, p.rows[0].location_end); + try std.testing.expect(p.rows[6].no_newline and !p.rows[5].no_newline); + var lines = std.mem.splitScalar(u8, p.text, '\n'); + var buf: [64]u8 = undefined; + for (p.rows) |row| { + const line = lines.next().?; + if (row.styles.len > 0) try std.testing.expectEqual(line.len, row.styles.len); + switch (row.kind) { + // the words a changed line changed, on both lines; each on its + // ground, its marker not on the line's own (it was paired) + .removed => try std.testing.expectEqualStrings(".............foo....", marked(&buf, line, row.styles, pardes.ground_emph)), + .added => try std.testing.expectEqualStrings(".............bar....", marked(&buf, line, row.styles, pardes.ground_emph)), + else => {}, + } + if (row.kind == .removed) try std.testing.expectEqual(pardes.ground_del, row.styles[0]); + if (row.kind == .added) try std.testing.expectEqual(pardes.ground_add, row.styles[0]); + } + // coloured as C: `return` a keyword + const ret = p.rows[5].styles[std.mem.indexOf(u8, " return x;", "return").?]; + try std.testing.expectEqual(pardes.Syn.keyword, @as(pardes.Syn, @fromBackingInt(ret & pardes.syn_bits))); +} + +test "a diff stacked with its file handed in: the declaration it stands in, from the file's own parse" { + const gpa = std.testing.allocator; + pardes.start(gpa); + defer pardes.stop(); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const Given = struct { + fn source(_: *const pardes.PatchCtx, _: []const u8, path: []const u8) ?pardes.PatchSource { + return if (std.mem.eql(u8, path, "main.c")) .{ .path = path, .bytes = main_c } else null; + } + }; + const ctx: pardes.PatchCtx = .{ .arena = arena.allocator(), .source = Given.source, .declarations = pardes.PatchCtx.parsed, .colors = pardes.PatchCtx.languages }; + const p = try pardes.formatPatch(&ctx, "", patch_c); + try std.testing.expectEqualStrings("main.c:1\n int main(void)\nmain.c:3 *\n {\n- int x = foo(1);\n+ int x = bar(1);\n return x;\n }\n", p.text); + try std.testing.expectEqual(pardes.PatchRow.Kind.declaration, p.rows[0].kind); + try std.testing.expectEqual(1, p.rows[0].line); + try std.testing.expectEqual(pardes.PatchRow.Kind.declaration, p.rows[1].kind); + try std.testing.expectEqual(pardes.PatchRow.Kind.hunk, p.rows[2].kind); + try std.testing.expectEqual("main.c:3".len, p.rows[2].location_end); +} diff --git a/test/consumer/none.zig b/test/consumer/none.zig new file mode 100644 index 00000000..a389d429 --- /dev/null +++ b/test/consumer/none.zig @@ -0,0 +1,56 @@ +//! The patch view in a build with no grammar at all (`.grammars = .none`): +//! a diff of a file in a language it does not have still gets its grounds, +//! its changed words and its rows, and the colours it is not given stay +//! out. +const std = @import("std"); +const ps = @import("pardes-syntax"); + +const patch_rs = + \\diff --git a/src/lib.rs b/src/lib.rs + \\--- a/src/lib.rs + \\+++ b/src/lib.rs + \\@@ -10,3 +10,3 @@ fn total(items: &[u32]) -> u32 { + \\ let mut sum = 0; + \\- for i in items { sum += i; } + \\+ for i in items { sum += *i; } + \\ sum + \\ +; + +test "a diff with no grammar in the build: rows, grounds and changed words, no colours" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + try std.testing.expect(!ps.supportsPath("lib.rs")); + const ctx: ps.PatchCtx = .{ .arena = arena.allocator() }; + const p = try ps.formatPatch(&ctx, "", patch_rs); + try std.testing.expectEqualStrings("src/lib.rs:11\n fn total(items: &[u32]) -> u32 {\n let mut sum = 0;\n- for i in items { sum += i; }\n+ for i in items { sum += *i; }\n sum\n", p.text); + try std.testing.expectEqual(ps.PatchRow.Kind.hunk, p.rows[0].kind); + try std.testing.expectEqual(ps.PatchRow.Kind.declaration, p.rows[1].kind); + const removed = p.rows[3]; + const added = p.rows[4]; + try std.testing.expectEqual(.{ 11, null }, .{ removed.old, removed.new }); + try std.testing.expectEqual(.{ null, 11 }, .{ added.old, added.new }); + try std.testing.expectEqual(ps.ground_del, removed.styles[0]); + try std.testing.expectEqual(ps.ground_add, added.styles[0]); + // `*` added: the one word emphasised; no byte has a colour of its own + const star = std.mem.indexOfScalar(u8, "+ for i in items { sum += *i; }", '*').?; + for (added.styles, 0..) |s, i| try std.testing.expectEqual(i == star, s & ps.ground_emph != 0); + for (p.rows) |row| for (row.styles) |s| try std.testing.expectEqual(0, s & ps.syn_bits); +} + +test "with no grammar, a file handed in still places the hunk, and no declaration is made up" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const Given = struct { + fn source(_: *const ps.PatchCtx, _: []const u8, path: []const u8) ?ps.PatchSource { + return .{ .path = path, .bytes = "\n" ++ "\n" ++ "\n" ++ "\n" ++ "\n" ++ "\n" ++ "\n" ++ "\n" ++ + "fn total(items: &[u32]) -> u32 {\n let mut sum = 0;\n for i in items { sum += *i; }\n sum\n}\n" }; + } + }; + const ctx: ps.PatchCtx = .{ .arena = arena.allocator(), .source = Given.source, .declarations = ps.PatchCtx.parsed }; + const p = try ps.formatPatch(&ctx, "", patch_rs); + // found (no `@@` words then: git's guess would only contradict the + // file's own), and no grammar to read a declaration from + try std.testing.expectEqualStrings("src/lib.rs:11\n let mut sum = 0;\n- for i in items { sum += i; }\n+ for i in items { sum += *i; }\n sum\n", p.text); + for (p.rows) |row| try std.testing.expect(row.kind != .declaration); +} -- cgit v1.3 From dea2920233bbb64b20f7ccebd42ac5beab14033d Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 21 Nov 2026 02:30:14 -0300 Subject: library: a browser's module is pardes's build's to make: build.zig exports `wasmModule(b, .{ .language = "rust" })` (the user's ruling: the self-contained module is exposed to the consumer's build.zig): wasm32-wasi, a reactor, one language's grammar and what it needs with tree-sitter's runtime and the highlighter, or with no language the patch view alone; its exports are abi/wasm.zig's (beside the other boundaries: a module of its own whose few globals are the page's, not a core's), the same in every module: `reserve`/`release` (toilet's, at least one byte so reserve(0) is a pointer), `highlight(path, path_len, text, len)` (toilet's without its diff flag: diffs go to the patch view now), `patch(text, len)` (a 20-byte header: the rows' text, a style byte a byte, and nine-u32 records: kind, old, new (0 for none), code_start, the row's text and its path as offsets, flags bit 0 no newline), `memory`, `_initialize`; only those are exported (export_symbol_names, not rdynamic: tree-sitter's and libc's symbols stay inside), and a panic is one `fd_write` to stderr and a trap (std's handler writes through std.Io and imported 26 more WASI functions): a language's module imports fd_write, fd_seek, fd_close (libc's streams, tree-sitter's debug output), the patch view's none, 24,533 bytes (11,108 gzip; with tree-sitter's runtime in it, 139,337); rust's is 1,290,182 (183,568 gzip; its parser object alone 1,134,394); test/consumer makes both through `wasmModule` and runs them under node (wasm.mjs: a page with every WASI import a stub reads the header and records back: rows, numbers, paths, the changed `*`, a no-newline flag, reserve(0), a highlight), saying so when there is no node; `sizes` installs one module a language of the manifest Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- abi/wasm.zig | 146 ++++++++++++++++++++++++++++++++++++++++++++++++ build.zig | 46 +++++++++++++++ test/consumer/build.zig | 30 +++++++++- test/consumer/wasm.mjs | 113 +++++++++++++++++++++++++++++++++++++ 4 files changed, 332 insertions(+), 3 deletions(-) create mode 100644 abi/wasm.zig create mode 100644 test/consumer/wasm.mjs (limited to 'test/consumer') diff --git a/abi/wasm.zig b/abi/wasm.zig new file mode 100644 index 00000000..d2b3889a --- /dev/null +++ b/abi/wasm.zig @@ -0,0 +1,146 @@ +//! A browser's module (build.zig `wasmModule`: wasm32-wasi, a reactor): the +//! functions a page calls, the same in every module. Every pointer and +//! length is a wasm32 address or count, an unsigned 32-bit integer; numbers +//! in memory are little-endian. docs/typ/building.typ has the layouts. +//! +//! - `reserve(len)`: `len` bytes (one at least, so a pointer even for 0) +//! for the page to write an argument into; `release(ptr, len)` gives them +//! back. +//! - `highlight(path, path_len, text, len)` (a module with a language): a +//! style byte for each byte of `text`, a `Syn` (0 none, 1 keyword, 2 +//! string, 3 number, 4 comment), as pardes colours the file `path` names +//! by its extension; all 0 for a file of another language. The module's +//! until the next `highlight`. +//! - `patch(text, len)`: the diff `text` stacked as pardes's patch view +//! shows it (`formatPatch`, with no file and no colours): a `Header`, its +//! rows' text, a style byte for each byte of it, and a `Record` a row. +//! The module's until the next `patch`. +//! +//! Each returns null (0) when its memory runs out. +const std = @import("std"); +const ps = @import("pardes-syntax"); +const options = @import("wasm_options"); + +const gpa = std.heap.wasm_allocator; + +/// A panic's message to stderr (fd 2) in one `fd_write`, then a trap: std's +/// own handler writes through std.Io, which imports 26 more of WASI's +/// functions a page would have to stub. +pub const panic = std.debug.FullPanic(struct { + fn write(message: []const u8, _: ?usize) noreturn { + var written: usize = 0; + _ = std.os.wasi.fd_write(2, &.{.{ .base = message.ptr, .len = message.len }}, 1, &written); + @trap(); + } +}.write); + +comptime { + // A module with no language has no highlighter, and so no tree-sitter. + if (options.highlight) @export(&highlight, .{ .name = "highlight" }); +} + +export fn reserve(len: usize) ?[*]u8 { + return (gpa.alloc(u8, @max(len, 1)) catch return null).ptr; +} + +export fn release(ptr: [*]u8, len: usize) void { + gpa.free(ptr[0..@max(len, 1)]); +} + +var started = false; +var styles: []u8 = &.{}; + +fn highlight(path: [*]const u8, path_len: usize, text: [*]const u8, len: usize) callconv(.c) ?[*]u8 { + if (!started) ps.start(gpa); + started = true; + gpa.free(styles); + styles = ps.highlightFileRange(gpa, path[0..path_len], text[0..len], 0, len) catch &.{}; + // A path in no language this module has, or an empty text: all plain. + if (styles.len == 0) { + styles = gpa.alloc(u8, @max(len, 1)) catch return null; + @memset(styles, 0); + } + return styles.ptr; +} + +/// What `patch` returns, 20 bytes. +pub const Header = extern struct { + /// The rows' text, a line a row, `text_len` bytes; the rows' paths + /// follow it in the same buffer. + text: u32, + text_len: u32, + /// A style byte for each byte of the text. + styles: u32, + /// `row_count` records of 36 bytes. + rows: u32, + row_count: u32, +}; + +/// A row, 36 bytes: nine u32. +pub const Record = extern struct { + /// 0 other, 1 meta, 2 hunk, 3 declaration, 4 context, 5 added, 6 removed + /// (`PatchRow.Kind`). + kind: u32, + /// Its numbers in the old and the new file, from 1; 0 where it has none. + old: u32, + new: u32, + /// Where its code starts, a byte of its text: after a label's + /// `path:line` and stars. + code_start: u32, + /// Its text, without its newline, and its section's path: offsets into + /// the header's `text`. + text_offset: u32, + text_len: u32, + path_offset: u32, + path_len: u32, + /// Bit 0: the diff has `\ No newline at end of file` after it. + flags: u32, +}; + +var arena_state: std.heap.ArenaAllocator = .init(gpa); + +export fn patch(text: [*]const u8, len: usize) ?*const Header { + _ = arena_state.reset(.retain_capacity); + return stack(arena_state.allocator(), text[0..len]) catch null; +} + +fn stack(arena: std.mem.Allocator, diff: []const u8) !*const Header { + const p = try ps.formatPatch(&.{ .arena = arena }, "", diff); + // The text, then each row's path where it changes from the row before. + var text: std.ArrayList(u8) = .empty; + try text.appendSlice(arena, p.text); + const marks = try arena.alloc(u8, p.text.len); + @memset(marks, 0); + const records = try arena.alloc(Record, p.rows.len); + var at: usize = 0; + var path: struct { []const u8, usize } = .{ "", 0 }; + for (p.rows, records) |row, *r| { + const line_len = std.mem.indexOfScalarPos(u8, p.text, at, '\n').? - at; + @memcpy(marks[at..][0..row.styles.len], row.styles); + if (!std.mem.eql(u8, row.path, path[0])) { + path = .{ row.path, text.items.len }; + try text.appendSlice(arena, row.path); + } + r.* = .{ + .kind = @backingInt(row.kind), + .old = @intCast(row.old orelse 0), + .new = @intCast(row.new orelse 0), + .code_start = @intCast(row.code_start), + .text_offset = @intCast(at), + .text_len = @intCast(line_len), + .path_offset = @intCast(path[1]), + .path_len = @intCast(row.path.len), + .flags = @intFromBool(row.no_newline), + }; + at += line_len + 1; + } + const header = try arena.create(Header); + header.* = .{ + .text = @intCast(@intFromPtr(text.items.ptr)), + .text_len = @intCast(p.text.len), + .styles = @intCast(@intFromPtr(marks.ptr)), + .rows = @intCast(@intFromPtr(records.ptr)), + .row_count = @intCast(records.len), + }; + return header; +} diff --git a/build.zig b/build.zig index cae96193..69ada42f 100644 --- a/build.zig +++ b/build.zig @@ -36,6 +36,12 @@ //! (`@import("pardes").grammar_manifest.all`: each grammar's name, its //! extensions and what it needs), is `grammar_manifest`. //! +//! A browser's module, one call a language (`wasmModule`): +//! +//! const pardes = @import("pardes"); +//! b.installArtifact(pardes.wasmModule(b, .{ .language = "rust" })); +//! b.installArtifact(pardes.wasmModule(b, .{})); // the patch view alone +//! //! Every dependency but tree-sitter's runtime is lazy in the manifest, so //! such a package fetches what it asked for and nothing else. //! `pardes-editor` has `pardes-syntax` in it as `.syntax`: a file belongs @@ -403,6 +409,46 @@ pub fn build(b: *std.Build) void { } } +/// A browser's module, one call a language (the head comment): wasm32-wasi +/// as a reactor (no `main`; `_initialize`, then any export), with +/// `language`'s grammar and what it needs, tree-sitter's runtime and +/// pardes's highlighter; or, with no language, the patch view alone, with +/// no tree-sitter in it. Its exports are abi/wasm.zig's (`memory`, +/// `_initialize`, `reserve`, `release`, `patch`, and with a language +/// `highlight`), the same in every module; docs/typ/building.typ has their +/// layouts and the WASI imports a page stubs. The package's dependency on +/// pardes is named "pardes". A name the manifest does not have fails the +/// configure, as `.languages` does. +pub fn wasmModule(b: *std.Build, options: struct { + language: ?[]const u8 = null, + optimize: std.lang.Optimize = .ReleaseSmall, +}) *std.Build.Step.Compile { + const target = b.resolveTargetQuery(.{ .cpu_arch = .wasm32, .os_tag = .wasi }); + const pardes = if (options.language) |name| + b.dependency("pardes", .{ .target = target, .optimize = options.optimize, .languages = name }) + else + b.dependency("pardes", .{ .target = target, .optimize = options.optimize, .grammars = .none }); + const exports = b.addOptions(); + exports.addOption(bool, "highlight", options.language != null); + const module = b.addExecutable(.{ + .name = b.fmt("pardes-{s}", .{options.language orelse "patch"}), + .root_module = b.createModule(.{ + .target = target, + .optimize = options.optimize, + .root_source_file = pardes.path("abi/wasm.zig"), + .imports = &.{ + .{ .name = "pardes-syntax", .module = pardes.module("pardes-syntax") }, + .{ .name = "wasm_options", .module = exports.createModule() }, + }, + }), + }); + module.entry = .disabled; + module.wasi_exec_model = .reactor; + // Its own functions alone: tree-sitter's and libc's stay inside. + module.root_module.export_symbol_names = if (options.language != null) &.{ "reserve", "release", "patch", "highlight" } else &.{ "reserve", "release", "patch" }; + return module; +} + /// Installs `artifact` in the prefix and, given `home_bin`, copies it there /// too (`install` unlinks first, so a running binary is replaced). fn installHome(b: *std.Build, artifact: *std.Build.Step.Compile, home_bin: ?[]const u8) void { diff --git a/test/consumer/build.zig b/test/consumer/build.zig index f8f63712..45e1e2e5 100644 --- a/test/consumer/build.zig +++ b/test/consumer/build.zig @@ -3,9 +3,10 @@ //! runs `zig build test` here. `pardes-syntax` with the minimal grammars, //! as a program that draws source text itself takes it; with one language //! named, for each language of pardes's manifest, read here at configure -//! time; and `pardes-editor` with no grammar of pardes's and one of its own, +//! time; `pardes-editor` with no grammar of pardes's and one of its own, //! C's, compiled here from the package pardes pins and handed in at run -//! time, as sketchbook's `examples/live` takes it. +//! time, as sketchbook's `examples/live` takes it; and the browser's modules +//! pardes's build makes (`wasmModule`), run under node when it is there. const std = @import("std"); const pardes = @import("pardes"); @@ -23,7 +24,7 @@ pub fn build(b: *std.Build) void { // The grammar of its own: C's, from the package pardes's manifest pins // (so `--pkg-dir` at pardes's zig-pkg has it), as that package builds it. const grammar = b.dependency("ts_c", .{ .target = target, .optimize = .ReleaseFast, .@"build-shared" = false }).artifact("tree-sitter-c"); - const step = b.step("test", "colour, outline and walk a C and a Zig source through pardes's syntax, build it with one language named, and edit a text with its editor and a grammar of this package's"); + const step = b.step("test", "colour, outline and walk a C and a Zig source through pardes's syntax, build it with one language named, edit a text with its editor and a grammar of this package's, and run a browser's modules"); // A file belongs to one module: the syntax alone, and the editor (which // has it as `.syntax`), each a test of its own. // The patch view with no grammar at all: the editor's package has @@ -43,7 +44,16 @@ pub fn build(b: *std.Build) void { // with it alone (and what it needs). `test` runs two: rust, alone, and // markdown, which brings its inline grammar. const each = b.step("each-language", "build and test pardes-syntax with each language of its manifest named alone"); + // A browser's module a language, and the patch view's: `sizes` + // installs every one; `test` runs the patch view's and rust's. + const sizes = b.step("sizes", "install a browser's module for each language, and the patch view's, into /bin"); + const patch = pardes.wasmModule(b, .{}); + sizes.dependOn(&b.addInstallArtifact(patch, .{}).step); + var rust: ?*std.Build.Step.Compile = null; for (pardes.grammar_manifest.all) |g| if (g.exts.len > 0) { + const module = pardes.wasmModule(b, .{ .language = g.name }); + sizes.dependOn(&b.addInstallArtifact(module, .{}).step); + if (std.mem.eql(u8, g.name, "rust")) rust = module; const name = b.addOptions(); name.addOption([]const u8, "name", g.name); const one = b.addRunArtifact(b.addTest(.{ .name = b.fmt("one-{s}", .{g.name}), .root_module = b.createModule(.{ @@ -58,6 +68,20 @@ pub fn build(b: *std.Build) void { each.dependOn(&one.step); if (std.mem.eql(u8, g.name, "rust") or std.mem.eql(u8, g.name, "markdown")) step.dependOn(&one.step); }; + // Each run as a page runs it, its WASI imports stubs. + if (b.findProgram(.{ .names = &.{"node"} })) |node| { + const run = b.addSystemCommand(&.{node}); + run.setName("node: the patch view's module and rust's"); + run.addFileArg(b.path("wasm.mjs")); + run.addArtifactArg(patch); + run.addArtifactArg(rust.?); + run.expectExitCode(0); + step.dependOn(&run.step); + } else { + std.debug.print("consumer-test: no node on PATH: the browser's modules are built, not run\n", .{}); + step.dependOn(&patch.step); + step.dependOn(&rust.?.step); + } // ...and a name it does not have: the configure fails, saying so. const bad = b.addSystemCommand(&.{ b.graph.zig_exe, "build", "-Dlanguage=klingon", "--pkg-dir", "../../zig-pkg" }); bad.setName("a language pardes does not have fails the configure"); diff --git a/test/consumer/wasm.mjs b/test/consumer/wasm.mjs new file mode 100644 index 00000000..9e76af0f --- /dev/null +++ b/test/consumer/wasm.mjs @@ -0,0 +1,113 @@ +// The browser's modules pardes builds (build.zig `wasmModule`), run as a +// page runs them: `node wasm.mjs PATCH.wasm LANGUAGE.wasm`. Every WASI +// import is a stub (fd_prestat_get says there is no directory, the rest +// that they are not there), and each module prints what it imports. +import { readFileSync } from "node:fs"; + +let failed = 0; +function expect(what, got, want) { + if (JSON.stringify(got) !== JSON.stringify(want)) { + console.error(`${what}: got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`); + failed++; + } +} + +function load(file) { + const mod = new WebAssembly.Module(readFileSync(file)); + const imports = WebAssembly.Module.imports(mod); + console.log(`${file}: ${imports.length} imports: ${imports.map((i) => i.module + "." + i.name).join(" ")}`); + let memory; + const wasi = new Proxy({}, { + get: (_, name) => (...a) => { + if (name === "fd_prestat_get") return 8; // EBADF: no preopened directory + if (name === "proc_exit") throw Error(`exit ${a[0]}`); + if (name === "fd_write") { + const [, iovs, n, written] = a; + const v = new DataView(memory.buffer); + let sum = 0; + for (let i = 0; i < n; i++) { + const p = v.getUint32(iovs + 8 * i, true), l = v.getUint32(iovs + 8 * i + 4, true); + process.stderr.write(Buffer.from(memory.buffer, p, l)); + sum += l; + } + v.setUint32(written, sum, true); + return 0; + } + return 52; // ENOSYS + }, + }); + const inst = new WebAssembly.Instance(mod, { wasi_snapshot_preview1: wasi }); + memory = inst.exports.memory; + inst.exports._initialize(); + return { ex: inst.exports, mem: () => memory.buffer }; +} + +const enc = new TextEncoder(), dec = new TextDecoder(); +function put(m, text) { + const b = enc.encode(text); + const p = m.ex.reserve(b.length); + new Uint8Array(m.mem(), p, b.length).set(b); + return [p, b.length]; +} + +// patch: the diff stacked, read from the header and its 36-byte records +const kinds = ["other", "meta", "hunk", "declaration", "context", "added", "removed"]; +function patch(m, diff) { + const [p, n] = put(m, diff); + const h = m.ex.patch(p, n); + m.ex.release(p, n); + const v = new DataView(m.mem()); + const [text, textLen, styles, rows, count] = [0, 4, 8, 12, 16].map((o) => v.getUint32(h + o, true)); + const bytes = new Uint8Array(m.mem(), text); + const out = []; + for (let i = 0; i < count; i++) { + const [kind, old, nw, codeStart, off, len, pathOff, pathLen, flags] = [...Array(9)].map((_, f) => v.getUint32(rows + 36 * i + 4 * f, true)); + out.push({ + kind: kinds[kind], old, new: nw, codeStart, flags, + text: dec.decode(bytes.subarray(off, off + len)), + path: dec.decode(bytes.subarray(pathOff, pathOff + pathLen)), + styles: [...new Uint8Array(m.mem(), styles + off, len)], + }); + } + return { text: dec.decode(bytes.subarray(0, textLen)), rows: out }; +} + +const diff = "diff --git a/src/lib.rs b/src/lib.rs\n--- a/src/lib.rs\n+++ b/src/lib.rs\n@@ -10,3 +10,3 @@ fn total(items: &[u32]) -> u32 {\n let mut sum = 0;\n- for i in items { sum += i; }\n+ for i in items { sum += *i; }\n sum\n\\ No newline at end of file\n"; +for (const file of process.argv.slice(2)) { + const m = load(file); + // reserve(0) is a pointer still + const zero = m.ex.reserve(0); + expect(`${file} reserve(0)`, zero !== 0, true); + m.ex.release(zero, 0); + + const p = patch(m, diff); + expect(`${file} patch text`, p.text, "src/lib.rs:11\n fn total(items: &[u32]) -> u32 {\n let mut sum = 0;\n- for i in items { sum += i; }\n+ for i in items { sum += *i; }\n sum\n"); + expect(`${file} patch rows`, p.rows.map((r) => [r.kind, r.old, r.new, r.path, r.flags]), [ + ["hunk", 0, 0, "src/lib.rs", 0], + ["declaration", 0, 0, "src/lib.rs", 0], + ["context", 10, 10, "src/lib.rs", 0], + ["removed", 11, 0, "src/lib.rs", 0], + ["added", 0, 11, "src/lib.rs", 0], + ["context", 12, 12, "src/lib.rs", 1], + ]); + expect(`${file} hunk code start`, p.rows[0].codeStart, "src/lib.rs:11".length); + // the added line: its ground on the marker (0x80), and `*` its changed word (0x20) + const added = p.rows[4]; + expect(`${file} added styles`, added.styles.map((s, i) => (s & 0x20 ? added.text[i] : s & 0x80 ? "+" : ".")).join(""), [...added.text].map((c, i) => (i === 0 ? "+" : c === "*" ? "*" : ".")).join("")); + + if (m.ex.highlight) { + const src = 'fn main() { let s = "x"; }\n'; + const [pp, pn] = put(m, "main.rs"); + const [tp, tn] = put(m, src); + // (a call can grow the memory: its buffer is taken after it) + const at = m.ex.highlight(pp, pn, tp, tn); + const s = new Uint8Array(m.mem(), at, tn); + expect(`${file} highlight fn`, [s[0], s[1]], [1, 1]); + expect(`${file} highlight "x"`, s[src.indexOf('"')], 2); + const c = put(m, "main.c"); + const other = m.ex.highlight(c[0], c[1], tp, tn); + expect(`${file} highlight another language`, [...new Uint8Array(m.mem(), other, tn)].every((b) => b === 0), true); + } +} +if (failed) process.exit(1); +console.log("wasm: the modules run"); -- cgit v1.3