1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
|
// 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);
return read(m, h);
}
// patchFile: the same, with the text of the file the diff's first section names
function patchFile(m, diff, text) {
const [p, n] = put(m, diff);
const [t, tn] = put(m, text);
const h = m.ex.patchFile(p, n, t, tn);
m.ex.release(p, n);
m.ex.release(t, tn);
return read(m, h);
}
function read(m, h) {
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);
}
}
// patchFile (a module with a language): xit's bare `@@`, and the file's
// text: the declaration the hunk sits in, from the file's own parse
const oldRs = "fn total(items: &[u32]) -> u32 {\n let mut sum = 0;\n let mut n = 0;\n for i in items { sum += i; }\n n += 1;\n sum\n}\n";
const newRs = "// sums\n" + oldRs.replace("sum += i;", "sum += *i;");
const bare = "diff --git a/src/lib.rs b/src/lib.rs\n--- a/src/lib.rs\n+++ b/src/lib.rs\n@@ -0,0 +1 @@\n+// sums\n@@ -3,3 +4,3 @@\n let mut n = 0;\n- for i in items { sum += i; }\n+ for i in items { sum += *i; }\n n += 1;\n";
const more = bare + "diff --git a/src/b.rs b/src/b.rs\n--- a/src/b.rs\n+++ b/src/b.rs\n@@ -3,3 +4,3 @@\n let mut n = 0;\n- for i in items { sum += i; }\n+ for i in items { sum += *i; }\n n += 1;\n";
const language = process.argv.slice(2).map(load).find((m) => m.ex.highlight);
if (language) {
const lines = (p) => p.rows.map((r) => [r.kind, r.text]);
const plain = lines(patch(language, bare));
// the new file's text: its numbers
expect("patchFile new text", lines(patchFile(language, bare, newRs)), [
["hunk", "src/lib.rs:1"], ["added", "+// sums"],
["declaration", "src/lib.rs:2"], ["declaration", " fn total(items: &[u32]) -> u32 {"],
["hunk", "src/lib.rs:5 *"], ["context", " let mut n = 0;"], ["removed", "- for i in items { sum += i; }"], ["added", "+ for i in items { sum += *i; }"], ["context", " n += 1;"],
]);
// the old file's: found on its side, and numbered so
expect("patchFile old text", lines(patchFile(language, bare, oldRs)).slice(2, 5), [["declaration", "src/lib.rs:1"], ["declaration", " fn total(items: &[u32]) -> u32 {"], ["hunk", "src/lib.rs:4 *"]]);
// a text the diff is not of: the rows as with none
expect("patchFile another text", lines(patchFile(language, bare, "nothing like it\n")), plain);
// a second file: as with no text
const two = lines(patchFile(language, more, newRs));
expect("patchFile second file", two.slice(9), lines(patch(language, more)).slice(plain.length));
}
if (failed) process.exit(1);
console.log("wasm: the modules run");
|