summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-21 02:30:14 -0300
committerGabriel Schneider <[email protected]>2026-11-21 02:52:47 -0300
commitdea2920233bbb64b20f7ccebd42ac5beab14033d (patch)
tree4d1622bffae6fbf653764ea33cb038afd6f02754
parentee5b6aa3ef0bf398c5381498af40fa93d20cf0b3 (diff)
downloadpardes-dea2920233bbb64b20f7ccebd42ac5beab14033d.tar.gz
pardes-dea2920233bbb64b20f7ccebd42ac5beab14033d.zip
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 <[email protected]> Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
-rw-r--r--abi/wasm.zig146
-rw-r--r--build.zig46
-rw-r--r--test/consumer/build.zig30
-rw-r--r--test/consumer/wasm.mjs113
4 files changed, 332 insertions, 3 deletions
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 <prefix>/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");