summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--abi/wasm.zig146
-rw-r--r--build.zig102
-rw-r--r--build/core.zig24
-rw-r--r--core/grammar_manifest.zig8
-rw-r--r--core/hunks.zig300
-rw-r--r--core/lib_syntax.zig17
-rw-r--r--core/syntax.zig7
-rw-r--r--docs/typ/building.typ111
-rw-r--r--test/consumer/build.zig77
-rw-r--r--test/consumer/lib.zig95
-rw-r--r--test/consumer/none.zig56
-rw-r--r--test/consumer/one.zig45
-rw-r--r--test/consumer/wasm.mjs113
13 files changed, 977 insertions, 124 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 470d8600..69ada42f 100644
--- a/build.zig
+++ b/build.zig
@@ -26,8 +26,21 @@
//!
//! `.grammars`: the tree-sitter grammars compiled in: `none` (the runtime
//! alone), `minimal` (C, C++ and Zig) or `full` (all of them; the default).
-//! `.editor`: exports `pardes-editor` besides `pardes-syntax`, and with it
-//! fetches uucode, mvzr and vaxis.
+//! `.languages`: instead of `.grammars`, the languages compiled in by name
+//! (`"rust"`, or `&.{ "rust", "go" }`), each with what it needs (markdown
+//! its inline grammar); a name the manifest does not have fails the
+//! configure. `.editor`: exports `pardes-editor` besides `pardes-syntax`,
+//! and with it fetches uucode, mvzr and vaxis.
+//!
+//! The manifest, for a package's build script to read at configure time
+//! (`@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.
@@ -72,13 +85,20 @@ pub const macos_min_version: std.SemanticVersion = .{ .major = 13, .minor = 0, .
pub const TreeSitterGrammars = enum { none, minimal, full };
+/// Every grammar pardes knows (the head comment).
+pub const grammar_manifest = @import("core/grammar_manifest.zig");
+
pub fn build(b: *std.Build) void {
// What a package that depends on pardes may ask for (the head comment).
// pardes's own build takes the mode and the grammars too, and its target
// below, whose default -Dplatform says.
const optimize = b.standardOptimizeOption(.{});
- const grammars = b.option(TreeSitterGrammars, "grammars", "the tree-sitter grammars compiled in: none (the runtime alone), minimal (C, C++ and Zig) or full (all of them; the default)") orelse .full;
- if (!b.isRoot()) return library(b, b.standardTargetOptions(.{}), optimize, grammars, b.option(bool, "editor", "exports pardes-editor besides pardes-syntax, and with it fetches uucode, mvzr and vaxis") orelse false);
+ const grammars_option = b.option(TreeSitterGrammars, "grammars", "the tree-sitter grammars compiled in: none (the runtime alone), minimal (C, C++ and Zig) or full (all of them; the default)");
+ const grammars = grammars_option orelse .full;
+ if (!b.isRoot()) return library(b, b.standardTargetOptions(.{}), optimize, librarySet(
+ grammars_option,
+ b.option([]const []const u8, "languages", "instead of grammars, the languages compiled in by name, each with what it needs"),
+ ), b.option(bool, "editor", "exports pardes-editor besides pardes-syntax, and with it fetches uucode, mvzr and vaxis") orelse false);
// Everything below is pardes's own: the editor, its tests and tools.
// This configure reads the environment (HOME, XDG_DATA_HOME,
@@ -389,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 {
@@ -401,13 +461,38 @@ fn installHome(b: *std.Build, artifact: *std.Build.Step.Compile, home_bin: ?[]co
b.getInstallStep().dependOn(&copy.step);
}
+/// The grammars a dependent package asked for: the languages it named and
+/// what each needs (the manifest's), or its tier's. A language the manifest
+/// does not have, or a tier beside languages, ends the configure: Zig
+/// reports an option it cannot read and builds on (exit code 0).
+fn librarySet(grammars: ?TreeSitterGrammars, languages: ?[]const []const u8) core.GrammarSet {
+ const names = languages orelse return core.tierSet(grammars orelse .full);
+ if (grammars) |tier| fatal("pardes: `.languages` replaces `.grammars` (here .{t}): give one of them", .{tier});
+ var set: core.GrammarSet = @splat(false);
+ for (names) |name| {
+ const i = grammar_manifest.byName(name) orelse fatal("pardes: no language \"{s}\" in its manifest (`.languages`); it has:{s}", .{ name, comptime known: {
+ var all: []const u8 = "";
+ for (grammar_manifest.all) |g| all = all ++ " " ++ g.name;
+ break :known all;
+ } });
+ set[i] = true;
+ for (grammar_manifest.all[i].needs) |need| set[grammar_manifest.byName(need).?] = true;
+ }
+ return set;
+}
+
+fn fatal(comptime format: []const u8, args: anytype) noreturn {
+ std.log.err(format, args);
+ std.process.exit(1);
+}
+
/// What a package that depends on pardes is given (the head comment):
/// `pardes-syntax`, the grammars, highlighting and themes, over tree-sitter
/// and the grammars of its set alone; and with `editor`, `pardes-editor`,
/// whose uucode, mvzr and vaxis (with what its build names) are fetched
/// then and only then. Of vaxis it takes the grapheme width, which uucode
/// alone feeds.
-fn library(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.lang.Optimize, grammars: TreeSitterGrammars, editor: bool) void {
+fn library(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.lang.Optimize, set: core.GrammarSet, editor: bool) void {
var threaded: std.Io.Threaded = .init(b.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
@@ -417,10 +502,11 @@ fn library(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.lang.O
.root_source_file = b.path("core/lib_syntax.zig"),
.link_libc = true,
});
- // A library's options: its grammars, nothing stamped, no window.
- const cfg: core.ShellConfig = .{ .tree_sitter_grammars = grammars };
+ // A library's options: nothing stamped, no window, and a tier only
+ // pardes's own tests read (syntax.zig knows the set by its queries).
+ const cfg: core.ShellConfig = .{ .tree_sitter_grammars = if (std.mem.eql(bool, &set, &core.tierSet(.full))) .full else if (std.mem.eql(bool, &set, &core.tierSet(.minimal))) .minimal else .none };
mod.addOptions("pardes_options", core.options(b, cfg, .{ .root = "core/lib_syntax.zig", .platform = .tui, .terminal = false }, false));
- const ts = core.treeSitter(b, io, target, if (optimize == .debug) .fast else optimize, grammars);
+ const ts = core.treeSitter(b, io, target, if (optimize == .debug) .fast else optimize, set);
const themes = core.generatedThemes(b, io, target, optimize);
mod.addImport("generated_themes", themes);
ts.wire(mod);
diff --git a/build/core.zig b/build/core.zig
index b668211d..63b4a5e9 100644
--- a/build/core.zig
+++ b/build/core.zig
@@ -144,6 +144,16 @@ pub fn generatedThemes(b: *std.Build, io: std.Io, target: std.Build.ResolvedTarg
});
}
+/// The grammars a build compiles in, a flag each in the manifest's order.
+pub const GrammarSet = [grammar_manifest.all.len]bool;
+
+/// A tier's (`-Dgrammars`, a dependent package's `.grammars`).
+pub fn tierSet(tier: TreeSitterGrammars) GrammarSet {
+ var set: GrammarSet = undefined;
+ for (grammar_manifest.all, &set) |g, *in| in.* = tier == .full or (tier == .minimal and g.tier == .minimal);
+ return set;
+}
+
pub const TreeSitter = struct {
mod: *std.Build.Module,
queries: *std.Build.Step.Options,
@@ -158,15 +168,15 @@ pub const TreeSitter = struct {
};
/// tree-sitter's bindings, and for each grammar of the set its queries (the
-/// `ts_queries` options syntax.zig reads) and its parser, a static library.
-/// A grammar not fetched yet is asked for and left out: the configure runs
-/// again once it is there.
-pub fn treeSitter(b: *std.Build, io: std.Io, target: std.Build.ResolvedTarget, c_optimize: std.lang.Optimize, tree_sitter_grammars: TreeSitterGrammars) TreeSitter {
+/// `ts_queries` options syntax.zig reads, and by which it knows the set)
+/// and its parser, a static library. A grammar not fetched yet is asked for
+/// and left out: the configure runs again once it is there.
+pub fn treeSitter(b: *std.Build, io: std.Io, target: std.Build.ResolvedTarget, c_optimize: std.lang.Optimize, set: GrammarSet) TreeSitter {
const tree_sitter_mod = b.dependency("tree_sitter", .{ .target = target, .optimize = c_optimize }).module("tree_sitter");
var ts_libs: std.ArrayList(*std.Build.Step.Compile) = .empty;
const ts_queries = b.addOptions();
- inline for (grammar_manifest.all) |g| {
- if (tree_sitter_grammars == .full or (tree_sitter_grammars == .minimal and g.tier == .minimal)) grammar: {
+ inline for (grammar_manifest.all, set) |g, in| {
+ if (in) grammar: {
const dep = b.dependencyLazy(g.dep, .{}) catch break :grammar;
const upstream = configureRead(b, io, dep.builder.root, g.query, 0x100000) catch @panic("read " ++ g.name ++ " highlights");
// the patterns that colour, filtered here once and not in
@@ -433,7 +443,7 @@ pub fn assemble(b: *std.Build, c: struct {
// nothing else. pardes takes these whatever it builds: the missing ones
// are asked for here in one round, the grammars with them, where each
// `b.dependency` below would end the configure to fetch its own alone.
- const ts = treeSitter(b, io, target, c_optimize, c.shell_cfg.tree_sitter_grammars);
+ const ts = treeSitter(b, io, target, c_optimize, tierSet(c.shell_cfg.tree_sitter_grammars));
inline for (.{ "cloud9", "vaxis", "ghostty", "uucode", "zstbi", "mvzr", "zstd", "xitdb" }) |name| {
// A dependency by path (none of these today) has no hash and is always there.
const dep = @field(zon.dependencies, name);
diff --git a/core/grammar_manifest.zig b/core/grammar_manifest.zig
index b4ff30b9..b0ce146c 100644
--- a/core/grammar_manifest.zig
+++ b/core/grammar_manifest.zig
@@ -17,6 +17,12 @@ pub const Grammar = struct {
query: []const u8 = "queries/highlights.scm",
/// Patterns appended to the highlights query before it is filtered.
highlights_extra: []const u8 = "",
+ /// The grammars it cannot work without, compiled in with it when a
+ /// package names it alone (build.zig's `languages`). Only markdown has
+ /// one: its inline grammar. A fence's or a raw block's language
+ /// (markdown's, typst's) is coloured when it is in the build and left
+ /// plain when it is not.
+ needs: []const []const u8 = &.{},
};
pub const all = [_]Grammar{
@@ -38,7 +44,7 @@ pub const all = [_]Grammar{
.{ .name = "json", .dep = "ts_json", .exts = &.{".json"}, .tier = .full },
.{ .name = "kotlin", .dep = "ts_kotlin", .exts = &.{ ".kt", ".kts" }, .tier = .full, .scanner = true },
.{ .name = "ocaml", .dep = "ts_ocaml", .exts = &.{ ".ml", ".mli" }, .tier = .full, .src = "grammars/ocaml/src", .scanner = true },
- .{ .name = "markdown", .dep = "ts_markdown", .exts = &.{ ".md", ".markdown" }, .tier = .full, .src = "tree-sitter-markdown/src", .scanner = true, .query = "tree-sitter-markdown/queries/highlights.scm" },
+ .{ .name = "markdown", .dep = "ts_markdown", .exts = &.{ ".md", ".markdown" }, .tier = .full, .src = "tree-sitter-markdown/src", .scanner = true, .query = "tree-sitter-markdown/queries/highlights.scm", .needs = &.{"markdown_inline"} },
// Second grammar off the SAME dep: the split_parser markdown repo ships a
// block parser and an inline parser, and bold/italic/code-span live only in
// the inline one. `.exts` is empty because no filename ever selects it — the
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/core/syntax.zig b/core/syntax.zig
index 00ee497f..1bb8fb52 100644
--- a/core/syntax.zig
+++ b/core/syntax.zig
@@ -37,11 +37,10 @@ const Spec = struct {
capture_styles: [256]u8 = undefined,
};
+/// A grammar is in the build when the build gave its queries (build/core.zig
+/// `treeSitter`): a tier's set, or the languages a package named.
fn grammarSelected(comptime g: grammar_manifest.Grammar) bool {
- return switch (g.tier) {
- .minimal => minimal_grammars,
- .full => full_grammars,
- };
+ return @hasDecl(ts_queries, g.name ++ "_highlights");
}
fn specCount() comptime_int {
diff --git a/docs/typ/building.typ b/docs/typ/building.typ
index 94939452..f2b3289f 100644
--- a/docs/typ/building.typ
+++ b/docs/typ/building.typ
@@ -122,18 +122,38 @@ exe.root_module.addImport("pardes-editor", pardes.module("pardes-editor"));
`.grammars`: the tree-sitter grammars compiled in: `none` (the runtime
alone), `minimal` (C, C++ and Zig) or `full` (all of them; the default).
-`.editor`: exports `pardes-editor` besides `pardes-syntax`, and with it
-fetches uucode, mvzr and vaxis.
+`.languages`: instead of `.grammars`, the languages compiled in by name
+(`"rust"`, or `&.{ "rust", "go" }`), each with what it needs (markdown
+its inline grammar); a name the manifest does not have fails the
+configure. `.editor`: exports `pardes-editor` besides `pardes-syntax`,
+and with it fetches uucode, mvzr and vaxis.
+
+The manifest, for a package's build script to read at configure time
+(`@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`, below):
+
+```
+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
to one module, so a package imports one of the two. `test/consumer` is
-such a package, with both shapes; `consumer-test`, which `unit-test` runs,
+such a package, with every shape; `consumer-test`, which `unit-test` runs,
builds and runs it.
`build.zig.zon` names pardes by its path: `.pardes = .{ .path = "../pardes" }`.
+Zig reports an option a dependency does not have, or a value it cannot
+read, and builds on with the default (exit code 0): pardes ends the
+configure itself (exit code 1, the manifest's names) for a language it
+does not have, and for `.grammars` given beside `.languages`.
+
=== The syntax
It is the editor's own code under the names it has there. A language is
@@ -146,6 +166,7 @@ for a language's name.
[`theme`, `themes`, `page`, `ink`, `synInk`], [a theme by name and what it draws a page, its text and each class in],
[`lineCount`, `lineStartOffset`, `lineSlice`], [a line's bytes from its number],
[`grammars`, `supportsPath`, `pathFor`], [every grammar, and whether this build has a path's],
+ [`formatPatch`, `PatchCtx`, `Patch`, `PatchRow`, `PatchSource`], [a unified diff stacked as the patch view shows it (below)],
[`start`, `stop`], [tree-sitter's allocator, and the end of the parsers kept per language],
)
@@ -156,6 +177,85 @@ pardes's `zig-pkg` shares the one copy. What a pane measures stays out: a
cell's width is vaxis's and uucode's, and a tab is `config.tab_width`
cells wherever it stands.
+=== The patch view
+
+`formatPatch` stacks a unified diff as pardes's +Diff shows it, with
+nothing of the editor: each hunk under its `path:line`, what it stands in
+above it, its lines behind their markers on their grounds, and the words a
+changed line changed emphasised (delta's way). It returns a `Patch`, its
+text and a `PatchRow` for each of its lines (row _i_ is line _i_), all in
+the arena it is handed:
+
+#pairs(
+ [`kind`], [`other` (a mailed patch's headers, message, diffstat), `meta` (a section's own words: a mode, a rename, `Binary files ... differ`), `hunk` (its label, a star a declaration it stands in), `declaration` (what it stands in: a declaration's `path:line` and header lines from the file, or git's own words after the `@@`), `context`, `added`, `removed`],
+ [`path`, `line`], [the file its section names, and the line of it the row points at (0 for none)],
+ [`old`, `new`], [a hunk line's numbers in the old and the new file, null on the side it is not on],
+ [`location_end`, `code_start`], [where a label's `path:line` ends and what follows it starts],
+ [`styles`], [a byte a byte of its text: a `Syn` in `syn_bits` (with colours), `ground_add` or `ground_del` on a changed line, `ground_line` on the marker of one no other line changed, `ground_emph` on a changed word],
+ [`no_newline`], [the diff's `\ No newline at end of file` follows it],
+)
+
+What it takes of the program is a `PatchCtx`: an `arena`, and, each with
+a default, `source` (the file a section names, as a `PatchSource`: its
+text and path; none by default, so each hunk is numbered by the diff and
+stands under git's words), `declarations` (none; `PatchCtx.parsed` reads
+them from the file's parse), `colors` (none; `PatchCtx.languages` colours
+each hunk as its file's language), `width` (code points; it decides
+whether two lines are one changed) and `tslocations`. With no `colors`
+and no `declarations` it calls nothing of tree-sitter. A reader with a
+commit's two blobs hands the new one in as `source` (or the old one, for a
+file the commit deleted): the hunk is found in it on either side.
+
+=== In a browser
+
+`wasmModule(b, .{ .language = "rust" })`, called from a package's build
+script after `@import("pardes")` (its dependency named `pardes`), gives
+the compile step of one module for a browser: wasm32-wasi, a reactor (no
+`main`: `_initialize`, then any export), with that language's grammar and
+what it needs, tree-sitter's runtime and pardes's highlighter. With no
+`.language` it is the patch view alone, with no tree-sitter in it and no
+import at all. `.optimize` is `ReleaseSmall` unless given. A name the
+manifest does not have fails the configure. The module is
+`pardes-<language>.wasm`, or `pardes-patch.wasm`; its exports
+(`core/lib_wasm.zig`) are the same in every module:
+
+#pairs(
+ [`memory`, `_initialize`], [its memory, and what a reactor runs once before any other call],
+ [`reserve(len)`, `release(ptr, len)`], [`len` bytes for the page to write an argument into (at least one, so `reserve(0)` is a pointer too), and their return],
+ [`highlight(path, path_len, text, len)`], [(a module with a language) a style byte for each byte of `text`: 0 none, 1 keyword, 2 string, 3 number, 4 comment, as pardes colours the file `path` names by its extension; all 0 for a path of another language. The module's until the next `highlight`],
+ [`patch(text, len)`], [the diff `text` stacked as the patch view shows it, with no file and no colours: a pointer to a header. The module's until the next `patch`],
+)
+
+Each returns 0 when its memory runs out. Pointers and lengths are
+wasm32's: unsigned 32-bit; in memory they are little-endian. `patch`'s
+header is five u32, 20 bytes:
+
+#pairs(
+ [0 `text`, 4 `text_len`], [the rows' text, a line a row, each ending in a newline; the rows' paths follow it in the same buffer],
+ [8 `styles`], [a byte for each byte of the text: `ground_add` 0x80 or `ground_del` 0x40 on a changed line, `ground_line` 0x10 on the marker of one no other line changed, `ground_emph` 0x20 on the words a changed line changed],
+ [12 `rows`, 16 `row_count`], [the rows, a record of nine u32 (36 bytes) each],
+)
+
+and a row's record:
+
+#pairs(
+ [0 `kind`], [0 other, 1 meta, 2 hunk, 3 declaration (git's words after the `@@`), 4 context, 5 added, 6 removed],
+ [4 `old`, 8 `new`], [its numbers in the old and the new file, from 1; 0 where it has none],
+ [12 `code_start`], [where its code starts in its text: after a hunk label's `path:line` and stars],
+ [16 `text_offset`, 20 `text_len`], [its text, without its newline, in the header's `text`],
+ [24 `path_offset`, 28 `path_len`], [its section's path, in the header's `text` too],
+ [32 `flags`], [bit 0: the diff has `\ No newline at end of file` after it],
+)
+
+A module with a language imports three functions of
+`wasi_snapshot_preview1`, `fd_write`, `fd_seek` and `fd_close` (libc's
+streams, which tree-sitter's debug output names; `fd_write` is also how a
+panic's message reaches stderr); a page stubs each (`fd_write` may write
+to the console, the others answer `ENOSYS`, 52). The patch view's module
+imports nothing. `test/consumer/wasm.mjs` is such a page, run by node:
+`consumer-test` builds both shapes through `wasmModule` and runs them when
+`node` is on PATH, and says so when it is not.
+
=== The editor
`pardes-editor` (`core/lib_editor.zig`) is the text pane as a library:
@@ -198,8 +298,9 @@ zig build kitty-harness kitty graphics through a pane end to end (a fake kitt
terminal outside on the tui, the GPU capture on the gui;
kitten icat and chafa too when installed)
zig build syntax deterministic per-byte highlighting snapshots
-zig build consumer-test the library, from a package that depends on pardes (test/consumer);
- unit-test runs it too
+zig build consumer-test the library, from a package that depends on pardes (test/consumer):
+ its shapes, a language named alone, the browser's modules
+ under node; unit-test runs it too
zig build hxlib helix's cases on the library's editor (-- --parity: against the file pane)
zig build behaviour-test behaviour through the 9P tree, in process (test/behaviour/),
and the T1 runner's short run of random 9P requests
diff --git a/test/consumer/build.zig b/test/consumer/build.zig
index c643bfb3..45e1e2e5 100644
--- a/test/consumer/build.zig
+++ b/test/consumer/build.zig
@@ -1,33 +1,96 @@
//! 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; `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; 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");
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, 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.
- 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);
}
+
+ // 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");
+ // 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(.{
+ .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);
+ };
+ // 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");
+ 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 -- <KiB> <keys>`.
const bench = b.addExecutable(.{ .name = "bench", .root_module = b.createModule(.{
.target = target,
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);
+}
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)));
+ };
+}
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");