wuica-cli 0.1.9 → 0.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,357 @@
1
+ // Assembly syntax highlighting, the DOM-free half: the tokens of a line of x86-64 assembly (Intel or AT&T syntax, gcc
2
+ // and clang output, objdump -d lines with or without the byte column). The page's editor overlay and any later consumer
3
+ // (the CLI, a report) colour them through the class names (className) so that they agree; the npm package ships a copy
4
+ // (packages/wuica/lib/web, web-modules.json). tests-js/web_asm_tokens.mjs tests it.
5
+ //
6
+ // tokenize(line, syntax, opts) -> [{start, end, kind}]: every character of the line in exactly one token, in order;
7
+ // never throws; linear in the length of the line. Kinds (a small set: the page is deliberately plain):
8
+ // label a label's definition ("loop:", ".LBB0_3:", "1:", objdump's "<f>:" header)
9
+ // mnemonic the instruction's mnemonic: the first word after the labels and prefixes (by position, not by a list;
10
+ // AT&T's size suffix is part of it: addq)
11
+ // prefix lock, rep*, notrack, bnd, data16, segment prefixes before the mnemonic, {vex}, {evex}, ...
12
+ // register general-purpose (64/32/16/8-bit, ah/bh/ch/dh), rip/eip, xmm/ymm/zmm, k0-k7, segment, x87 st(i)/st, mm,
13
+ // control and debug registers; the mask register in {k1}
14
+ // number immediates and displacements: 42, -8 (the sign is punct), 0x1f, 1fh, 0b101, $42 (AT&T, with its $)
15
+ // size dword ptr, ymmword ptr (one token), byte/word/... without ptr, offset, and the operand decorations
16
+ // {z}, {1to8}, {sae}, {rn-sae} (their letters; the braces are punct)
17
+ // symbol a label's use: a branch target, a memory operand's symbol (.LCPI0_0, printf@PLT, 1b, 1f), $sym's sym,
18
+ // objdump's <f+0x10> name
19
+ // directive .p2align, .globl, .section, ... (the operands are tokens of their own)
20
+ // comment # ..., // ..., /* ... */ (on the line; tokenizeText follows one over several lines), a ';' that starts
21
+ // the line, and a ';' after a statement when the assembly diagnostics say the rest was taken as a comment
22
+ // (asm-regions.js commentFixes: the assembler's rule; without diagnostics a ';' separates statements, as
23
+ // LLVM and GNU as read it)
24
+ // punct , [ ] ( ) { } < > + - * : % $ = and a ';' that separates statements
25
+ // address objdump's address column (" 4005d0:", with its colon)
26
+ // bytes objdump's byte column ("48 83 c0 01")
27
+ // space white space
28
+ // text anything else: a quoted string, a stray character
29
+ // error only where the caller passes diagnostics with a column range (opts.diagnostics); never guessed
30
+ //
31
+ // tokenizeLine(line, syntax, opts) -> {tokens, open}: one line of a text for a caller that tokenizes a text a line at a
32
+ // time (the page's editor: only the lines in view); syntax 'intel' or 'att' (detected once for the text by the caller);
33
+ // opts {objdump: the line is read as objdump's (objdumpLine, when objdumpText says the text is objdump's), block: a block
34
+ // comment is open at its start, diagnostics: the line's}; open: a block comment is open at its end. tokenizeText is the
35
+ // same, line after line.
36
+ // tokenizeText(text, syntax, opts) -> one token list per line: the syntax detected once for the text ('auto':
37
+ // loop-find.js detectSyntax), objdump text recognised once (a line with objdump's indented address and tab, its byte
38
+ // column or its function header; then every address-prefixed line is read as objdump's), block comments followed across
39
+ // lines; opts.diagnostics [{line, column, endColumn?, severity}] of the whole text.
40
+ // className(kind) -> 'tok-' + kind; ansi(line, tokens) -> the line with ANSI colours (not used by the CLI yet).
41
+
42
+ import { detectSyntax } from './loop-find.js';
43
+ import { commentFixes } from './asm-regions.js';
44
+
45
+ export const KINDS = Object.freeze(['label', 'mnemonic', 'prefix', 'register', 'number', 'size', 'symbol', 'directive', 'comment',
46
+ 'punct', 'address', 'bytes', 'space', 'text', 'error']);
47
+
48
+ export const className = (kind) => `tok-${kind}`;
49
+ const ANSI = { label: 33, mnemonic: 1, prefix: 35, register: 36, number: 32, size: 35, symbol: 33, directive: 34, comment: 2, address: 2, bytes: 2, error: 31 };
50
+ export const ansi = (line, tokens) => tokens.map((t) => (ANSI[t.kind] ? `\x1b[${ANSI[t.kind]}m${line.slice(t.start, t.end)}\x1b[0m` : line.slice(t.start, t.end))).join('');
51
+
52
+ // ---- the words ------------------------------------------------------------------------------------------------------
53
+
54
+ // The registers, one table for both syntaxes (lower case; AT&T writes them with %, which is punct).
55
+ const REGISTERS = new Set([
56
+ ...['rax', 'rbx', 'rcx', 'rdx', 'rsi', 'rdi', 'rbp', 'rsp', 'eax', 'ebx', 'ecx', 'edx', 'esi', 'edi', 'ebp', 'esp',
57
+ 'ax', 'bx', 'cx', 'dx', 'si', 'di', 'bp', 'sp', 'al', 'bl', 'cl', 'dl', 'sil', 'dil', 'bpl', 'spl', 'ah', 'bh', 'ch', 'dh',
58
+ 'rip', 'eip', 'ip', 'cs', 'ds', 'es', 'fs', 'gs', 'ss', 'st'],
59
+ ...Array.from({ length: 8 }, (_, i) => [`r${i + 8}`, `r${i + 8}d`, `r${i + 8}w`, `r${i + 8}b`, `r${i + 8}l`, `k${i}`, `mm${i}`, `st${i}`, `cr${i}`, `dr${i}`]).flat(),
60
+ ...Array.from({ length: 32 }, (_, i) => [`xmm${i}`, `ymm${i}`, `zmm${i}`]).flat(),
61
+ 'cr8', 'tmm0', 'tmm1', 'tmm2', 'tmm3', 'tmm4', 'tmm5', 'tmm6', 'tmm7',
62
+ ]);
63
+ export const isRegister = (word) => REGISTERS.has(String(word).toLowerCase());
64
+
65
+ const SIZES = new Set(['byte', 'word', 'dword', 'qword', 'tbyte', 'tword', 'oword', 'fword', 'xword', 'mmword', 'xmmword', 'ymmword', 'zmmword', 'real4', 'real8', 'real10']);
66
+ const SIZE_WORDS = new Set(['ptr', 'offset', 'short', 'near', 'far']);
67
+ // prefixes before the mnemonic (as loop-find.js and ab-diff.js read them)
68
+ const PREFIXES = new Set(['lock', 'rep', 'repe', 'repz', 'repne', 'repnz', 'bnd', 'notrack', 'xacquire', 'xrelease', 'data16', 'data32',
69
+ 'addr32', 'addr16', 'cs', 'ds', 'es', 'ss', 'fs', 'gs', 'rex', 'rex64']);
70
+
71
+ // ---- the scanner ----------------------------------------------------------------------------------------------------
72
+
73
+ const WS = /[ \t\f\v\r\n]+/y;
74
+ const IDENT = /[A-Za-z_.$@?][\w.$@?]*/y;
75
+ const NUM = /[0-9][\w]*/y; // a number or a numeric label reference (1b, 1f), classified below
76
+ const LABEL = /(?:[A-Za-z_.$@?][\w.$@?]*|[0-9]+|"[^"\n]*")(?=[ \t]*:(?!:))/y;
77
+ const BRANCH = /^(?:j[a-z]{1,4}|call[lqw]?|loop[a-z]{0,2}|xbegin)$/i;
78
+ const STRING = /"(?:[^"\\]|\\.)*"?|'(?:[^'\\]|\\.)*'?/y;
79
+ const OD_ADDR = /([ \t]*)([0-9a-fA-F]+:)(?=[ \t]|$)/y;
80
+ const OD_BYTES = /((?:[0-9a-fA-F]{2} )*[0-9a-fA-F]{2})(?= ?(?:\t| |[ \t]*$))/y;
81
+ const OD_HEADER = /^([ \t]*)([0-9a-fA-F]+)([ \t]+)(<[^>]*>)([ \t]*:)([ \t]*)$/;
82
+ const SIZE_PTR = /([A-Za-z]+[0-9]*)([ \t]+)(ptr)\b/iy;
83
+
84
+ const match = (re, s, i) => { re.lastIndex = i; const m = re.exec(s); return m && m.index === i ? m : null; };
85
+ const isNumber = (w) => /^(?:0[xX][0-9a-fA-F]+|0[bB][01]+|[0-9][0-9a-fA-F]*[hH]|[0-9]+(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|[0-9]+[oOqQ])$/.test(w);
86
+
87
+ // The comment and separator structure of a line: [{start, end, code: bool, sep: bool}] (code: a statement's text;
88
+ // sep: a ';' that separates statements; the rest comments). block: a block comment is open at the start of the line.
89
+ function segments(line, block, commentFrom) {
90
+ const out = [];
91
+ let i = 0, start = 0, q = false;
92
+ const n = line.length;
93
+ const push = (a, b, type) => { if (b > a) out.push({ start: a, end: b, type }); };
94
+ if (block) {
95
+ const e = line.indexOf('*/');
96
+ if (e < 0) return { segs: [{ start: 0, end: n, type: 'comment' }], open: true };
97
+ push(0, e + 2, 'comment');
98
+ i = start = e + 2;
99
+ }
100
+ // a ';' that starts the line (after white space) is a comment (loop-find.js leadingSemicolons)
101
+ const lead = /^[ \t]*;/.exec(line.slice(i, Math.min(n, i + 256)));
102
+ if (lead && !block) { push(0, lead[0].length - 1, 'code'); push(lead[0].length - 1, n, 'comment'); return { segs: out, open: false }; }
103
+ for (; i < n; i++) {
104
+ const c = line[i];
105
+ if (q) { if (c === '\\') i++; else if (c === '"') q = false; continue; }
106
+ if (c === '"') { q = true; continue; }
107
+ if (i === commentFrom) { push(start, i, 'code'); push(i, n, 'comment'); return { segs: out, open: false }; }
108
+ if (c === '#' || (c === '/' && line[i + 1] === '/')) { push(start, i, 'code'); push(i, n, 'comment'); return { segs: out, open: false }; }
109
+ if (c === '/' && line[i + 1] === '*') {
110
+ push(start, i, 'code');
111
+ const e = line.indexOf('*/', i + 2);
112
+ if (e < 0) { push(i, n, 'comment'); return { segs: out, open: true }; }
113
+ push(i, e + 2, 'comment');
114
+ i = e + 1; start = e + 2;
115
+ continue;
116
+ }
117
+ if (c === ';') { push(start, i, 'code'); push(i, i + 1, 'sep'); start = i + 1; }
118
+ }
119
+ push(start, n, 'code');
120
+ return { segs: out, open: false };
121
+ }
122
+
123
+ // The tokens of one statement's text, line[a, b): labels, prefixes, mnemonic or directive, operands.
124
+ function statement(line, a, b, att, objdump, out) {
125
+ const s = line.slice(0, b); // the regexes stop at b (a slice of the line up to it: linear overall)
126
+ let i = a;
127
+ const tok = (end, kind) => { if (end > i) { out.push({ start: i, end, kind }); i = end; } };
128
+ const space = () => { const m = match(WS, s, i); if (m) tok(i + m[0].length, 'space'); };
129
+ space();
130
+ if (objdump && i < b) {
131
+ // objdump: the address, the byte column, then the instruction
132
+ const m = match(OD_ADDR, s, i);
133
+ if (m) {
134
+ tok(i + m[2].length, 'address');
135
+ space();
136
+ const by = match(OD_BYTES, s, i);
137
+ if (by) { tok(i + by[1].length, 'bytes'); space(); }
138
+ }
139
+ }
140
+ // labels
141
+ for (;;) {
142
+ const m = match(LABEL, s, i);
143
+ if (!m) break;
144
+ tok(i + m[0].length, 'label');
145
+ space();
146
+ tok(i + 1, 'punct'); // the ':'
147
+ space();
148
+ }
149
+ if (i >= b) return;
150
+ // prefixes, then the mnemonic or a directive
151
+ let first = true, branch = false;
152
+ for (;;) {
153
+ if (s[i] === '{') { // a pseudo-prefix: {vex}, {evex}, {disp32}
154
+ const e = s.indexOf('}', i);
155
+ if (e < 0 || !/^\{[\w ]+\}$/.test(s.slice(i, e + 1))) break;
156
+ tok(e + 1, 'prefix'); space();
157
+ continue;
158
+ }
159
+ const m = match(IDENT, s, i);
160
+ if (!m) break;
161
+ const w = m[0], lw = w.toLowerCase();
162
+ const after = s[i + w.length];
163
+ if (first && w[0] === '.') { tok(i + w.length, 'directive'); space(); break; }
164
+ if ((PREFIXES.has(lw) || /^rex\.\w+$/.test(lw)) && after !== ':' && after !== ',' && /\S/.test(s.slice(i + w.length, b))) { tok(i + w.length, 'prefix'); space(); first = false; continue; }
165
+ if (after === ':' || after === '=') break; // not a mnemonic: an assignment or a segment
166
+ tok(i + w.length, 'mnemonic'); space();
167
+ branch = BRANCH.test(w);
168
+ break;
169
+ }
170
+ operands(s, i, b, att, out, branch);
171
+ }
172
+
173
+ // The operands (and whatever else follows a mnemonic or directive), s[i, b). branch: a direct branch's mnemonic: a bare
174
+ // number as its first operand is its target (objdump: "jne 401126 <loop+0x6>"), a symbol.
175
+ function operands(s, i, b, att, out, branch = false) {
176
+ const tok = (end, kind) => { if (end > i) { out.push({ start: i, end, kind }); i = end; } };
177
+ let brace = false; // inside { } (a mask or decoration)
178
+ let target = branch; // the next operand is a branch target
179
+ while (i < b) {
180
+ const c = s[i];
181
+ let m;
182
+ if ((m = match(WS, s, i))) { tok(i + m[0].length, 'space'); continue; }
183
+ if (c === '%') {
184
+ tok(i + 1, 'punct');
185
+ continue;
186
+ }
187
+ if (c === '$' && /[0-9]/.test(s[i + 1] ?? '')) {
188
+ m = match(NUM, s, i + 1);
189
+ tok(i + 1 + m[0].length, isNumber(m[0]) ? 'number' : 'symbol');
190
+ continue;
191
+ }
192
+ if (c === '"' || c === "'") { m = match(STRING, s, i); tok(i + m[0].length, 'text'); continue; }
193
+ if ((m = match(NUM, s, i))) {
194
+ const w = m[0];
195
+ if (brace && /^1to\d+$/i.test(w)) tok(i + w.length, 'size');
196
+ else if (target && /^(?:0[xX])?[0-9a-fA-F]+$/.test(w)) tok(i + w.length, 'symbol');
197
+ else tok(i + w.length, isNumber(w) ? 'number' : /^[0-9]+[bf]$/i.test(w) ? 'symbol' : 'text');
198
+ continue;
199
+ }
200
+ if ((m = match(IDENT, s, i))) {
201
+ const w = m[0], lw = w.toLowerCase();
202
+ if (c === '$') { tok(i + 1, 'punct'); continue; } // $sym: the $ alone, the symbol next
203
+ if (REGISTERS.has(lw)) {
204
+ // st(1): the register with its parentheses
205
+ if (lw === 'st' && /^\(\d\)$/.test(s.slice(i + 2, i + 5)) && i + 5 <= b) { tok(i + 5, 'register'); continue; }
206
+ tok(i + w.length, 'register');
207
+ continue;
208
+ }
209
+ if (SIZES.has(lw)) {
210
+ const p = match(SIZE_PTR, s, i);
211
+ tok(p && p.index + p[0].length <= b && p[1].toLowerCase() === lw ? i + p[0].length : i + w.length, 'size');
212
+ continue;
213
+ }
214
+ if (SIZE_WORDS.has(lw) || (brace && /^(?:z|sae|r[nduz]-sae)$/i.test(w))) { tok(i + w.length, 'size'); continue; }
215
+ tok(i + w.length, 'symbol');
216
+ continue;
217
+ }
218
+ target = false;
219
+ if (c === '{') brace = true;
220
+ else if (c === '}') brace = false;
221
+ tok(i + 1, '[](){}<>,+-*:%$=!~&|^/'.includes(c) ? 'punct' : 'text');
222
+ }
223
+ }
224
+
225
+ // After the tokens are made: the diagnostics' column ranges (1-based columns, end exclusive or the end of the token at
226
+ // the column) become 'error', splitting tokens where they begin and end.
227
+ function markErrors(tokens, ranges) {
228
+ if (!ranges.length) return tokens;
229
+ const out = [];
230
+ for (const t of tokens) {
231
+ let parts = [{ ...t }];
232
+ for (const [a, b] of ranges) {
233
+ if (b <= t.start || a >= t.end) continue;
234
+ const next = [];
235
+ for (const p of parts) {
236
+ if (b <= p.start || a >= p.end || p.kind === 'error') { next.push(p); continue; }
237
+ if (a > p.start) next.push({ start: p.start, end: a, kind: p.kind });
238
+ next.push({ start: Math.max(a, p.start), end: Math.min(b, p.end), kind: 'error' });
239
+ if (b < p.end) next.push({ start: b, end: p.end, kind: p.kind });
240
+ }
241
+ parts = next;
242
+ }
243
+ out.push(...parts);
244
+ }
245
+ return out;
246
+ }
247
+
248
+ // The column ranges [start, end) of a line's error diagnostics: from the column to endColumn, else to the end of the
249
+ // word at the column (to the end of the line for a column past the code).
250
+ function errorRanges(line, diags) {
251
+ const out = [];
252
+ for (const d of diags) {
253
+ if (d.severity && d.severity !== 'error') continue;
254
+ const col = Number(d.column);
255
+ if (!(col >= 1)) continue;
256
+ const a = Math.min(col - 1, line.length);
257
+ let b = Number(d.endColumn) > col ? Number(d.endColumn) - 1 : -1;
258
+ if (b < 0) b = a + Math.max(1, (/^\S*/.exec(line.slice(a, a + 256))?.[0] ?? '').length);
259
+ out.push([a, Math.min(b, Math.max(line.length, a + 1))]);
260
+ }
261
+ return out.filter(([a, b]) => b > a && a < line.length);
262
+ }
263
+
264
+ // The column (0-based) from which the line is a comment because of a ';' the assembler could not read as a separator
265
+ // (asm-regions.js commentFixes, given the line's diagnostics), or -1.
266
+ function semicolonComment(line, diags) {
267
+ const errs = diags.filter((d) => d.severity === 'error' || /taken as a comment/.test(d.message ?? ''));
268
+ if (!errs.length) return -1;
269
+ const { fixes } = commentFixes(errs.map((d) => ({ ...d, line: 1, severity: 'error', column: d.message && /taken as a comment/.test(d.message) ? d.column + 1 : d.column })), line);
270
+ const fixed = fixes.get(1);
271
+ if (!fixed) return -1;
272
+ for (let i = 0; i < line.length; i++) if (line[i] !== fixed[i]) return i;
273
+ return -1;
274
+ }
275
+
276
+ function lineTokens(line, att, objdump, block, diags) {
277
+ const n = line.length;
278
+ if (!n) return { tokens: [], open: block };
279
+ const out = [];
280
+ const header = objdump && !block ? OD_HEADER.exec(line) : null;
281
+ if (header) {
282
+ let at = 0;
283
+ for (const [k, kind] of [[1, 'space'], [2, 'address'], [3, 'space'], [4, 'label'], [5, 'punct'], [6, 'space']]) {
284
+ if (header[k]) out.push({ start: at, end: at + header[k].length, kind });
285
+ at += header[k].length;
286
+ }
287
+ return { tokens: out, open: false };
288
+ }
289
+ const commentFrom = diags.length ? semicolonComment(line, diags) : -1;
290
+ const { segs, open } = segments(line, block, commentFrom);
291
+ let firstCode = true;
292
+ for (const g of segs) {
293
+ if (g.type === 'comment') out.push({ start: g.start, end: g.end, kind: 'comment' });
294
+ else if (g.type === 'sep') out.push({ start: g.start, end: g.end, kind: 'punct' });
295
+ else { statement(line, g.start, g.end, att, objdump && firstCode, out); firstCode = false; }
296
+ }
297
+ const ranges = diags.length ? errorRanges(line, diags).filter(([a]) => commentFrom < 0 || a < commentFrom) : [];
298
+ return { tokens: ranges.length ? markErrors(out, ranges) : out, open };
299
+ }
300
+
301
+ // A line whose tokens cannot be made (not expected): one text token.
302
+ const whole = (line) => (line.length ? [{ start: 0, end: line.length, kind: 'text' }] : []);
303
+
304
+ // The objdump form of one line on its own: an address column ended by a tab (as objdump writes it), a byte column, or
305
+ // the function header (objdump indents the address; a numeric label at the start of the line, "2:\tdecq %rcx", stays a
306
+ // label).
307
+ const looksObjdump = (line) => /^[ \t]+[0-9a-fA-F]+:\t/.test(line) || /^[ \t]*[0-9a-fA-F]+:[ \t]+(?:[0-9a-fA-F]{2} )*[0-9a-fA-F]{2}(?:\t| )/.test(line) || OD_HEADER.test(line);
308
+
309
+ // The tokens of one line. syntax: 'intel', 'att' or 'auto' (detectSyntax of the line, else Intel). opts: {objdump
310
+ // (true/false; default: from the line), diagnostics: [{column, endColumn?, severity, message}] of this line, block
311
+ // (a block comment is open at its start)}.
312
+ export function tokenize(line, syntax = 'auto', opts = {}) {
313
+ const s = typeof line === 'string' ? line : String(line ?? '');
314
+ try {
315
+ const att = syntax === 'att' || (syntax !== 'intel' && detectSyntax(s) === 'att');
316
+ const od = typeof opts.objdump === 'boolean' ? opts.objdump : looksObjdump(s);
317
+ return lineTokens(s, att, od, !!opts.block, Array.isArray(opts.diagnostics) ? opts.diagnostics : []).tokens;
318
+ } catch {
319
+ return whole(s);
320
+ }
321
+ }
322
+
323
+ // The tokens of every line of a text (lines split at \n; a CR before it is white space). syntax 'auto': detected
324
+ // once for the text. opts: {diagnostics: [{line (1-based), column, endColumn?, severity, message}]}.
325
+ export function tokenizeText(text, syntax = 'auto', opts = {}) {
326
+ const t = typeof text === 'string' ? text : String(text ?? '');
327
+ const lines = t.split('\n');
328
+ let att = syntax === 'att', od = false;
329
+ try {
330
+ if (syntax !== 'att' && syntax !== 'intel') att = detectSyntax(t) === 'att';
331
+ od = objdumpText(lines);
332
+ } catch { /* plain */ }
333
+ const byLine = new Map();
334
+ for (const d of Array.isArray(opts.diagnostics) ? opts.diagnostics : []) if (d && d.line >= 1) (byLine.get(d.line) ?? byLine.set(d.line, []).get(d.line)).push(d);
335
+ let block = false;
336
+ return lines.map((l, k) => {
337
+ const r = tokenizeLine(l, att ? 'att' : 'intel', { objdump: od && objdumpLine(l), block, diagnostics: byLine.get(k + 1) ?? [] });
338
+ block = r.open;
339
+ return r.tokens;
340
+ });
341
+ }
342
+
343
+ // One line with the state it starts and ends in (see the top): {tokens, open}; never throws (a line that cannot be
344
+ // read is one text token, and closes a block comment).
345
+ export function tokenizeLine(line, syntax = 'intel', opts = {}) {
346
+ const s = typeof line === 'string' ? line : String(line ?? '');
347
+ try {
348
+ return lineTokens(s, syntax === 'att', !!opts.objdump, !!opts.block, Array.isArray(opts.diagnostics) ? opts.diagnostics : []);
349
+ } catch {
350
+ return { tokens: whole(s), open: false };
351
+ }
352
+ }
353
+ // The text (its lines) is objdump's: one line looks like objdump's on its own (then every line with an address column
354
+ // is read as objdump's: objdumpLine).
355
+ export const objdumpText = (lines) => lines.some(looksObjdump);
356
+ // in objdump text: a line with an address column or the header
357
+ export const objdumpLine = (l) => /^[ \t]*[0-9a-fA-F]+:/.test(l) || OD_HEADER.test(l);
@@ -38,9 +38,37 @@ export function parseDiagnostics(text) {
38
38
  return out;
39
39
  }
40
40
 
41
- // Removes GNU as's {load} / {store} pseudo-prefixes at the start of a line (LLVM 22 says "unknown prefix").
41
+ // The text as the module gets it, the one preparation for the page and the npm package (lib/wasm.js): no byte order
42
+ // mark at the start (not code: LLVM would reject it), a NUL character as a space (the module reads a C string, which
43
+ // ends at the first NUL: clang -g -S writes NULs into the comments of its .debug_str bytes, and the text after one,
44
+ // with the labels it defines, would be lost), stripHints, and no line table (withoutLineTable). Lines and columns stay
45
+ // where they are.
46
+ export function prepareSource(text) {
47
+ return withoutLineTable(stripHints(String(text).replace(/^\uFEFF/, '').replace(/\0/g, ' ')));
48
+ }
49
+
50
+ // The line table's directives, a `.loc` and a numbered `.file` on a line of their own (after labels), blanked (the columns stay): the
51
+ // bytes of the code do not depend on them (asm-regions.js reads the lines from them before), while LLVM 22 rejects some
52
+ // of gcc's: DWARF 5 (gcc 11 and later -g) with ".file 0" gives "unassigned file number in '.loc'", a "view N" operand
53
+ // "unknown sub-directive". A view's symbol (.LVU3), which the debug sections can use, is defined as 0 after the text.
54
+ const LINE_TABLE = /^([ \t]*(?:[\w.$@]+:[ \t]*)*)(\.loc[ \t][^\n;#]*|\.file[ \t]+\d+[ \t](?:"(?:[^"\\\n]|\\.)*"|[^\n;#"])*)/gm;
55
+ export function withoutLineTable(text) {
56
+ const views = new Set();
57
+ const out = text.replace(LINE_TABLE, (_, lead, d) => {
58
+ const v = /\bview[ \t]+([A-Za-z_.$][\w.$]*)/.exec(d);
59
+ if (d.startsWith('.loc') && v) views.add(v[1]);
60
+ return lead + ' '.repeat(d.length);
61
+ });
62
+ return views.size ? `${out}\n${[...views].map((n) => `.set ${n}, 0`).join('\n')}\n` : out;
63
+ }
64
+
65
+ // Removes GNU as's {load} / {store} pseudo-prefixes at the start of a line (LLVM 22 says "unknown prefix"), and reads
66
+ // directives of newer compilers that the bundled LLVM 22 does not know: clang 23's `.prefalign LOG2, END, FILL` (a
67
+ // function's preferred alignment) as `.p2align LOG2`, the alignment clang 22 wrote there (after labels, in any case, up to
68
+ // a ';' or '#': what follows stays). Lines stay where they are.
42
69
  export function stripHints(text) {
43
- return text.replace(/^([ \t]*)\{(?:load|store)\}[ \t]*/gm, '$1');
70
+ return text.replace(/^([ \t]*)\{(?:load|store)\}[ \t]*/gm, '$1')
71
+ .replace(/^([ \t]*(?:[\w.$@]+:[ \t]*)*)\.prefalign[ \t]+(\d+)[^\n#;]*/gim, '$1.p2align $2');
44
72
  }
45
73
 
46
74
  // LLVM (like GNU as) reads ';' as a separator between statements, not as a comment, so "add rax, 1 ; note" fails with
@@ -79,8 +107,10 @@ export function isWasm(bytes) {
79
107
  }
80
108
 
81
109
  export class WasmAssembler {
82
- #module;
83
- #x = null;
110
+ /** @type {any} */
111
+ #module; // a WebAssembly.Module, or a function that makes the exports (create())
112
+ /** @type {any} */
113
+ #x = null; // the instance's exports
84
114
 
85
115
  // source: the bytes of wuica_asm.wasm, a WebAssembly.Module, or (tests) a function that returns a fresh object with
86
116
  // the exports.
@@ -114,7 +144,7 @@ export class WasmAssembler {
114
144
  if (i.kind !== 'function') throw new Error(`wuica_asm.wasm: unsupported import ${i.module}.${i.name}`);
115
145
  (imports[i.module] ??= {})[i.name] = () => 52;
116
146
  }
117
- x = (await WebAssembly.instantiate(this.#module, imports)).exports;
147
+ x = (await WebAssembly.instantiate(/** @type {WebAssembly.Module} */ (this.#module), imports)).exports;
118
148
  }
119
149
  for (const name of ['memory', 'malloc', 'free', 'wuica_assemble']) {
120
150
  if (!x[name]) throw new Error(`wuica_asm.wasm: export "${name}" is missing`);
@@ -155,7 +185,7 @@ export class WasmAssembler {
155
185
  if (!(syntax in SYNTAX)) throw new TypeError(`unknown syntax: ${syntax}`);
156
186
  if (!this.#x) await this.#instantiate();
157
187
  // (a byte order mark at the start is not code: LLVM would reject it)
158
- const plain = stripHints(String(text).replace(/^\uFEFF/, '').replace(/\0/g, ' '));
188
+ const plain = prepareSource(text);
159
189
  const mode = codeModeError(plain);
160
190
  if (mode) return { ok: false, diagnostics: [{ severity: 'error', ...mode }] };
161
191
  const source = new TextEncoder().encode(plain + '\0');
@@ -0,0 +1,165 @@
1
+ // Two blocks, A (before) and B (after), on one microarchitecture: one result object for `wuica diff`, the MCP tool
2
+ // diff_blocks and POST /api/diff/<arch>. Throughput before and after, speed-up, per element when both sides give their
3
+ // elements per iteration, bottlenecks and limits before and after, the change of each port's uops, the instructions that
4
+ // were added, removed or changed (ab-diff.js: the alignment of the page's A–B view), and each side's decode errors and
5
+ // warnings. No DOM; the package's copy is in packages/wuica/lib/web (web-modules.json).
6
+ //
7
+ // Numbers as compare and what-if give them: tp and the limits as the analyzer gives them (two decimals), delta and
8
+ // speedup rounded to two decimals, perElement tp / per unrounded (as compare's and what-if's perElement), the uop changes
9
+ // rounded to two decimals as the uop table shows them.
10
+
11
+ import { compareResponses, MINOR } from './ab-diff.js';
12
+ import { compare as compareMarkdown, shownLabels, text as mdText } from './markdown.js';
13
+
14
+ const r2 = (v) => (typeof v === 'number' && Number.isFinite(v) ? Math.round(v * 100) / 100 : null);
15
+ const side = (r, per) => ({
16
+ tp: r.tp, mode: r.mode, bottlenecks: r.bottlenecks, decodeErrors: r.decodeErrors ?? 0,
17
+ ...(r.unsupported ? { unsupported: r.unsupported } : {}), // (the CPU cannot run this side's code: caveats.js cannotRun)
18
+ ...(per ? { perElement: r.tp / per } : {}), ...(r.loop ? { loop: r.loop } : {}),
19
+ ...(r.stderr?.length ? { stderr: r.stderr } : {}),
20
+ });
21
+
22
+ // A's and B's modes differ (a loop against a block run unrolled): not comparable, as what-if says of such a variant.
23
+ const modeName = (m) => (m === 'loop' ? 'as a loop' : 'unrolled (it does not end with a branch)');
24
+ function notComparable(ra, rb) {
25
+ const error = `not comparable: A is analyzed ${modeName(ra.mode)}, B ${modeName(rb.mode)}`;
26
+ return { code: 1, error, stderr: [{ text: error }] };
27
+ }
28
+
29
+ // The result from the two analyze() responses (or the failure for a mode mismatch). opts: {per: [elements per iteration
30
+ // of A, of B] (both or none), sourceA, sourceB (the assembly text: branch targets as its labels)}.
31
+ /** @param {any} ra @param {any} rb @param {{per?: number[] | null, sourceA?: string | null, sourceB?: string | null}} [opts] @returns {any} */
32
+ export function diffResult(ra, rb, { per = null, sourceA = null, sourceB = null } = {}) {
33
+ if (ra.mode !== rb.mode) return notComparable(ra, rb);
34
+ const [pa, pb] = per ?? [null, null];
35
+ const cmp = compareResponses(ra, rb);
36
+ const t = cmp.tp;
37
+ // a side the CPU cannot run (unsupported, caveats.js cannotRun): its number is no result, so neither are the change
38
+ // and the speedup: verdict "not comparable", no delta, no speedup, in every form
39
+ const no = !!(ra.unsupported || rb.unsupported);
40
+ /** @type {any} */
41
+ const out = { code: 0, arch: ra.arch, a: side(ra, pa), b: side(rb, pb), ...(no ? { verdict: 'not comparable' } : { delta: r2(t.delta), speedup: r2(t.speedup), verdict: t.verdict }) };
42
+ if (pa && pb) {
43
+ const pe = compareResponses(ra, rb, { workA: pa, workB: pb }).tp;
44
+ out.perElement = { a: ra.tp / pa, b: rb.tp / pb, ...(no ? { verdict: 'not comparable' } : { delta: pe.delta, speedup: r2(pe.speedup), verdict: pe.verdict }) };
45
+ }
46
+ out.bottlenecks = { a: cmp.bottlenecks.a, b: cmp.bottlenecks.b, gone: cmp.bottlenecks.gone, new: cmp.bottlenecks.new };
47
+ out.limits = cmp.limits.map((l) => ({ name: l.name, a: l.a, b: l.b, delta: r2(l.delta) }));
48
+ // uops per iteration of each port (the ports both sides have), and the change
49
+ const d = cmp.diff;
50
+ const total = (r, i) => Number(r2(r.rows.reduce((s, x) => s + (Number(x.values?.[i]) || 0), 0)));
51
+ out.ports = d.portsComparable ? d.columns.filter((c) => c.kind === 'port').map((c) => ({ port: c.name, a: total(ra, c.ia), b: total(rb, c.ib), delta: r2(total(rb, c.ib) - total(ra, c.ia)) })) : [];
52
+ // the instructions that differ (branch targets as labels where the text gives them)
53
+ const labels = new Map();
54
+ for (const [r, source] of [[ra, sourceA], [rb, sourceB]]) shownLabels(r, typeof source === 'string' ? { source } : {}).forEach((l, i) => labels.set(r.rows[i], l));
55
+ const label = (u) => (u ? labels.get(u.row) ?? u.label : null);
56
+ out.instructions = {
57
+ counts: d.counts,
58
+ changes: d.rows.filter((x) => x.status !== 'same').map((x) => ({
59
+ status: x.status, a: label(x.a), b: label(x.b),
60
+ uops: Object.fromEntries(d.columns.map((c, k) => [c.name === 'Issued' ? 'issued' : c.name, r2(x.deltas[k])]).filter(([, v]) => v !== 0)),
61
+ ...(x.minor ? { minor: true } : {}), // (ab-diff.js MINOR: left out of the Markdown and the text)
62
+ })),
63
+ };
64
+ // the warnings of each side (decode errors, assembler warnings, the exits taken as not taken), named
65
+ const warnings = [...(ra.stderr ?? []).map((l) => ({ ...l, text: `A: ${l.text}` })), ...(rb.stderr ?? []).map((l) => ({ ...l, text: `B: ${l.text}` }))];
66
+ if (warnings.length) out.stderr = warnings;
67
+ return out;
68
+ }
69
+
70
+ // The two analyses and the result: {result, a, b} (a, b: the analyze() responses), or {failure}. request: {a: {source
71
+ // | hex, syntax, loop, func, options?}, b: {...}, options?, per?: N | [A, B]}; `options` apply to both sides unless a
72
+ // side has its own. w: anything with analyze(arch, request) (and resolveArch). A failure names the side ("A: ", "B: ")
73
+ // only when it belongs to that side.
74
+ /** @param {any} w @param {string} arch @param {any} request @returns {Promise<any>} */
75
+ export async function diffAnalyses(w, arch, request) {
76
+ const bad = (error, code = 1) => ({ failure: { code, error, stderr: [{ text: error }] } });
77
+ if (request === null || typeof request !== 'object' || Array.isArray(request)) return bad('the request must be an object');
78
+ const unknown = Object.keys(request).filter((k) => !['a', 'b', 'options', 'per'].includes(k));
79
+ if (unknown.length) return bad(`unknown request field(s): ${unknown.join(', ')} (known: a, b, options, per)`);
80
+ for (const k of ['a', 'b']) {
81
+ const x = request[k];
82
+ if (x === null || typeof x !== 'object' || Array.isArray(x)) return bad(`\`${k}\` must be a block: {source | hex, syntax?, loop?, func?, options?}`);
83
+ }
84
+ if (request.options !== undefined && (request.options === null || typeof request.options !== 'object' || Array.isArray(request.options))) return bad('`options` must be an object');
85
+ let per = request.per ?? null;
86
+ if (per !== null) {
87
+ if (typeof per === 'number') per = [per, per];
88
+ const ok = Array.isArray(per) && per.length === 2 && per.every((n) => typeof n === 'number' && Number.isFinite(n) && n > 0);
89
+ if (!ok) return bad('`per` must be a positive number (elements per iteration of both) or [A, B]');
90
+ }
91
+ if (typeof w.resolveArch === 'function' && !w.resolveArch(arch)) {
92
+ const r = await w.analyze(arch, request.a); // the library's message for an unknown microarchitecture
93
+ if (r.code) return { failure: r };
94
+ }
95
+ const one = (x) => (request.options !== undefined && x.options === undefined ? { ...x, options: request.options } : x);
96
+ // an error of the options both sides share is the request's, not a side's
97
+ const named = (k, r) => {
98
+ const shared = request.options !== undefined && request[k].options === undefined && /option/.test(r.error ?? '');
99
+ return { failure: shared ? r : { ...r, error: `${k.toUpperCase()}: ${r.error}` } };
100
+ };
101
+ const ra = await w.analyze(arch, one(request.a));
102
+ if (ra.code) return named('a', ra);
103
+ const rb = await w.analyze(arch, one(request.b));
104
+ if (rb.code) return named('b', rb);
105
+ const text = (x) => (typeof x.source === 'string' ? x.source : null);
106
+ const result = diffResult(ra, rb, { per, sourceA: text(request.a), sourceB: text(request.b) });
107
+ if (result.code) return { failure: result };
108
+ return { result, a: ra, b: rb, per, sourceA: text(request.a), sourceB: text(request.b) };
109
+ }
110
+
111
+ // diffAnalyses' result alone, or its failure.
112
+ /** @param {any} w @param {string} arch @param {any} request @returns {Promise<any>} */
113
+ export async function diffRequest(w, arch, request) {
114
+ const x = await diffAnalyses(w, arch, request);
115
+ return x.failure ?? x.result;
116
+ }
117
+
118
+ // Markdown of diffAnalyses' result (markdown.js compare: the page's A–B tables) with the microarchitecture named
119
+ // (opts.archTitle, e.g. "SKL · Skylake (2015)") and each side's warnings, or of its failure.
120
+ /** @param {any} x @param {{archTitle?: string}} [opts] */
121
+ export function diffMarkdown(x, { archTitle } = {}) {
122
+ if (x.failure) return `**diff failed:** ${mdText(x.failure.error)}\n`;
123
+ const [pa, pb] = x.per ?? [1, 1];
124
+ const shownA = shownLabels(x.a, typeof x.sourceA === 'string' ? { source: x.sourceA } : {});
125
+ const shownB = shownLabels(x.b, typeof x.sourceB === 'string' ? { source: x.sourceB } : {});
126
+ const head = `**A–B on ${mdText(archTitle ?? x.result.arch)}**\n\n`;
127
+ const warnings = (x.result.stderr ?? []).map((l) => `- ${mdText(l.text)}`).join('\n');
128
+ return head + compareMarkdown(x.a, x.b, { workA: pa, workB: pb, shownA, shownB }) + (warnings ? `\n${warnings}\n` : '');
129
+ }
130
+
131
+ // The result as text (the CLI without -md, the REST API's text/plain): cycles with two decimals, per element as the CLI
132
+ // prints it (three significant digits below 0.1).
133
+ const f2 = (v) => (v === null || v === undefined ? '-' : Number(v).toFixed(2));
134
+ const fe = (v) => (v === null || v === undefined ? '-' : v !== 0 && Math.abs(v) < 0.1 ? Number(v).toPrecision(3) : f2(v));
135
+ const sg = (v, f = f2) => (v === null || v === undefined ? '' : `${v > 0 ? '+' : ''}${f(v)}`);
136
+ export function diffText(r) {
137
+ if (r.code) return `diff failed: ${r.error}\n`;
138
+ const pct = r.a.tp > 0 ? ` ${sg((100 * (r.b.tp - r.a.tp)) / r.a.tp, (v) => Number(v).toFixed(1))}%` : '';
139
+ // a side whose code the CPU cannot run (unsupported): its number is no result, so no verdict
140
+ const bad = [['A', r.a.unsupported], ['B', r.b.unsupported]].filter(([, x]) => x).map(([k, x]) => `${k} ${x}`);
141
+ const verdict = (v, same) => (bad.length ? `not comparable: ${bad.join(', ')}` : same ? 'the same' : v);
142
+ const lines = [`${r.arch}: A ${f2(r.a.tp)} B ${f2(r.b.tp)} cycles per iteration (${verdict(`${sg(r.delta)},${pct}; speedup ${f2(r.speedup)}x`, r.verdict === 'same')})`];
143
+ if (r.perElement) lines.push(`per element: A ${fe(r.perElement.a)} B ${fe(r.perElement.b)} (${verdict(`${sg(r.perElement.delta, fe)}; speedup ${f2(r.perElement.speedup)}x`, r.perElement.verdict === 'same')})`);
144
+ const names = (xs) => (xs.length ? xs.join(', ') : 'unknown');
145
+ lines.push(`bottleneck: A ${names(r.bottlenecks.a)} -> B ${names(r.bottlenecks.b)}`);
146
+ for (const l of r.stderr ?? []) lines.push(`warning: ${l.text.replace(/^([AB]: )Warning: /, '$1')}`);
147
+ const w = Math.max(5, ...r.limits.map((l) => l.name.length));
148
+ lines.push('', ` ${'limit'.padEnd(w)} ${'A'.padStart(7)} ${'B'.padStart(7)} ${'delta'.padStart(7)}`);
149
+ for (const l of r.limits) lines.push(` ${l.name.padEnd(w)} ${f2(l.a).padStart(7)} ${f2(l.b).padStart(7)} ${(l.delta ? sg(l.delta) : '').padStart(7)}`.trimEnd());
150
+ const moved = r.ports.filter((p) => Math.abs(p.delta) >= MINOR); // (a change under MINOR, as the instructions': not listed)
151
+ lines.push('', `ports (uops per iteration): ${moved.length ? moved.map((p) => `${p.port} ${f2(p.a)} -> ${f2(p.b)}`).join(', ') : 'no change'}`);
152
+ // (minor changes of uops, ab-diff.js MINOR, are counted as the same and not listed)
153
+ const minor = r.instructions.changes.filter((x) => x.minor).length;
154
+ const c = { ...r.instructions.counts, changed: r.instructions.counts.changed - minor };
155
+ const said = [['modified', 'with other operands'], ['changed', 'with other uops'], ['added', 'only in B'], ['removed', 'only in A']].filter(([k]) => c[k]).map(([k, t]) => `${c[k]} ${t}`);
156
+ lines.push(`instructions: ${said.length ? said.join('; ') : 'the same'}${minor ? ` (changes under ${MINOR} uops not listed: ${minor})` : ''}`);
157
+ const MARK = { changed: '*', modified: '~', added: '+', removed: '-' };
158
+ for (const x of r.instructions.changes.filter((y) => !y.minor)) {
159
+ const what = x.status === 'added' ? x.b : x.status === 'removed' ? x.a : x.status === 'modified' ? `${x.a} -> ${x.b}` : x.a;
160
+ const uops = Object.entries(x.uops).map(([k, v]) => `${k} ${sg(v)}`).join(', ');
161
+ lines.push(` ${MARK[x.status]} ${what}${uops ? ` (${uops})` : ''}`);
162
+ }
163
+ if (said.length) lines.push(` (~ other operands, * same instruction with other uops, + only in B, - only in A; uops per iteration, B - A)`);
164
+ return lines.join('\n') + '\n';
165
+ }