wuica-cli 0.0.0-stage → 0.1.7

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.
Files changed (44) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +436 -2
  3. package/bin/wuica-mcp.js +16 -0
  4. package/bin/wuica.js +25 -0
  5. package/dist/data/arch/ADL-P.json.br +0 -0
  6. package/dist/data/arch/BDW.json.br +0 -0
  7. package/dist/data/arch/CFL.json.br +0 -0
  8. package/dist/data/arch/CLX.json.br +0 -0
  9. package/dist/data/arch/HSW.json.br +0 -0
  10. package/dist/data/arch/ICL.json.br +0 -0
  11. package/dist/data/arch/ICX.json.br +0 -0
  12. package/dist/data/arch/IVB.json.br +0 -0
  13. package/dist/data/arch/KBL.json.br +0 -0
  14. package/dist/data/arch/RKL.json.br +0 -0
  15. package/dist/data/arch/SKL.json.br +0 -0
  16. package/dist/data/arch/SKX.json.br +0 -0
  17. package/dist/data/arch/SNB.json.br +0 -0
  18. package/dist/data/arch/TGL.json.br +0 -0
  19. package/dist/data/arch/ZEN3.json.br +0 -0
  20. package/dist/data/uarch.json.br +0 -0
  21. package/dist/manifest.json +81 -0
  22. package/dist/wuica_asm.wasm.br +0 -0
  23. package/dist/wuica_wasm.wasm.br +0 -0
  24. package/index.d.ts +372 -0
  25. package/lib/archs.js +44 -0
  26. package/lib/cli.js +430 -0
  27. package/lib/core.js +36 -0
  28. package/lib/details.js +60 -0
  29. package/lib/files.js +18 -0
  30. package/lib/index.js +474 -0
  31. package/lib/insights.js +100 -0
  32. package/lib/mcp.js +366 -0
  33. package/lib/thread-worker.js +46 -0
  34. package/lib/threads.js +224 -0
  35. package/lib/wasm.js +221 -0
  36. package/lib/web/accum.js +202 -0
  37. package/lib/web/asm-regions.js +415 -0
  38. package/lib/web/assembler.js +188 -0
  39. package/lib/web/caveats.js +206 -0
  40. package/lib/web/loop-find.js +492 -0
  41. package/lib/whatif.js +136 -0
  42. package/licenses/LICENSE-LLVM.txt +279 -0
  43. package/licenses/LICENSE-XED.txt +178 -0
  44. package/package.json +58 -4
@@ -0,0 +1,415 @@
1
+ // Marked regions and .loc lines of pasted assembly. No DOM (tests-js/web_asm_regions.mjs runs it under Node).
2
+ //
3
+ // Region markers (the first marked region is analyzed; the text around it is still assembled, so labels, directives
4
+ // and a back-branch to a label outside the region keep their meaning and encodings):
5
+ // # LLVM-MCA-BEGIN [name] ... # LLVM-MCA-END [name] (llvm-mca; also with // or ; as the comment)
6
+ // # wuica-begin [name] ... # wuica-end (the same, wuica's own name)
7
+ // IACA / OSACA byte markers: mov ebx, 111 + .byte 0x64, 0x67, 0x90 ... mov ebx, 222 + .byte 0x64, 0x67, 0x90
8
+ // (AT&T: movl $111, %ebx); the markers themselves are not part of the region.
9
+ // .loc / .file (gcc -g -S, clang -g -S): each instruction gets the line of the .loc before it (main file only: the
10
+ // file with the most .loc lines in the analyzed code); srcmap.js shows the cost per line.
11
+ //
12
+ // How: the assembler (assembler.js) returns the .text bytes only, without offsets. The text is assembled with local
13
+ // labels at the region's ends and at each .loc (labels have no size: the layout is the same), and a trailer appended
14
+ // at the end of .text that holds a magic word and the distance of each label to the trailer:
15
+ // .text / .Lwuica_z: / .long MAGIC, .Lwuica_z-.Lwuica_0, ...
16
+ // The trailer is cut off again; the distances give the offsets. gcc's ".loc ... view N" (which LLVM rejects) loses
17
+ // its view operand (its symbol is set to 0). No line is added or removed (diagnostics keep their
18
+ // line numbers; columns are corrected where a label was put in front of a statement). If that text does not assemble
19
+ // for a reason of its own (a region or a .loc in another section), the plain text is assembled instead.
20
+
21
+ import { stripHints } from './assembler.js';
22
+ import { statements, preparePaste, loopName, normalizeText, isText } from './loop-find.js';
23
+
24
+ const MAGIC = 0x77756963; // 'ciuw'
25
+ // a cheap test first: without any of these the text is assembled as it is (no other work)
26
+ const QUICK = /LLVM-MCA-|wuica-|\.loc\s|\b111\b/i;
27
+ const MARKER = /^\s*(?:#|\/\/|;)\s*(LLVM-MCA-BEGIN|LLVM-MCA-END|wuica-begin|wuica-end)(?![\w-])[ \t]*([^\s#;]*)/i;
28
+ const IACA_MOV = /^mov[l]?\s+(?:ebx\s*,\s*(111|222)|\$(111|222)\s*,\s*%ebx)$/i;
29
+ const IACA_BYTES = /^\.byte\s+(?:0x64|100)\s*,\s*(?:0x67|103)\s*,\s*(?:0x90|144)$/i;
30
+ const LABELS = /^(?:\s*(?:[\w.$@]+|"[^"]*")\s*:)*\s*/;
31
+
32
+ export const MARKERS_TITLE = 'region markers: # LLVM-MCA-BEGIN [name] … # LLVM-MCA-END, # wuica-begin … # wuica-end (also // or ;), '
33
+ + "IACA's mov ebx, 111 / 222 + .byte 0x64,0x67,0x90; only the first region is analyzed";
34
+
35
+ const quoted = (s) => [...s.matchAll(/"((?:[^"\\]|\\.)*)"/g)].map((m) => m[1]);
36
+ const sectionName = (args) => (/^\s*("?)([^",\s]+)\1/.exec(args)?.[2] ?? '');
37
+
38
+ // text: the pasted assembly. Returns null (nothing marked: assemble the text as it is) or
39
+ // { text: the text to assemble, labels: [name], regions: [{name, line}], region: {name, line, begin, end} | null
40
+ // (begin/end: indexes into labels; end null: to the end of the code), locs: [{label, file, line}],
41
+ // files: Map(number -> name), shifts: Map(line -> [{col, len}]), lineCount, error: {line, message} | null }
42
+ // opts (loop-find.js, preparePaste): pick {begin, end}: lines (1-based) of the code to analyze when nothing is marked (the
43
+ // loop: its first instruction at or after `begin` to the end of line `end`); stubs: symbols to define right after the
44
+ // analyzed code (the loop's exits: its conditional branches out of it are then short and not taken).
45
+ export function planMarked(text, { pick = null, stubs = [] } = {}) {
46
+ text = String(text ?? '');
47
+ if (!QUICK.test(text) && !pick && !stubs.length) return null;
48
+ const lines = stripHints(text.replace(/^\uFEFF/, '')).split('\n');
49
+ const labels = [];
50
+ const inserts = []; // {line, col, label}
51
+ const regions = [];
52
+ let region = null, pendingBegin = false, error = null;
53
+ const locs = [], files = new Map(), views = new Set();
54
+ let inText = true, prev = false;
55
+ const stack = [];
56
+ let iaca = null; // {kind: '111' | '222', line, col} of a mov that can be an IACA marker
57
+ let block = false;
58
+ const label = (line, col) => { const name = `.Lwuica_${labels.length}`; labels.push(name); inserts.push({ line, col, label: name }); return labels.length - 1; };
59
+ const replaced = new Map(); // line -> new text (marker comments)
60
+ const stubText = stubs.map((n) => ` ${n}:`).join('');
61
+ let stubsPlaced = !stubs.length;
62
+ let pickPending = false;
63
+ if (pick) { region = { name: 'loop', line: pick.begin, begin: null, end: null, auto: true }; pickPending = true; }
64
+
65
+ const begin = (name, line) => {
66
+ regions.push({ name, line });
67
+ if (regions.length === 1) { region = { name, line, begin: null, end: null }; pendingBegin = true; }
68
+ };
69
+
70
+ for (let i = 0; i < lines.length; i++) {
71
+ let line = lines[i];
72
+ const mk = !block && MARKER.exec(line);
73
+ if (mk) {
74
+ const kind = mk[1].toLowerCase();
75
+ const name = mk[2] ?? '';
76
+ if (kind.endsWith('begin')) {
77
+ begin(name, i + 1);
78
+ replaced.set(i, '');
79
+ } else if (region && region.end === null && !region.closed && (!name || !region.name || name === region.name)) {
80
+ if (pendingBegin) { error ??= { line: region.line, message: 'the marked region has no instructions' }; pendingBegin = false; }
81
+ region.closed = true;
82
+ region.end = labels.length;
83
+ labels.push('.Lwuica_' + labels.length);
84
+ replaced.set(i, labels[region.end] + ':' + stubText);
85
+ stubsPlaced = true;
86
+ } else {
87
+ replaced.set(i, '');
88
+ }
89
+ continue;
90
+ }
91
+ // block comments (the columns stay)
92
+ if (block || line.includes('/*')) {
93
+ let out = '', k = 0;
94
+ while (k < line.length) {
95
+ if (block) { const e = line.indexOf('*/', k); if (e < 0) { out += ' '.repeat(line.length - k); k = line.length; } else { out += ' '.repeat(e + 2 - k); k = e + 2; block = false; } } else { const s = line.indexOf('/*', k); if (s < 0) { out += line.slice(k); k = line.length; } else { out += line.slice(k, s); k = s; block = true; } }
96
+ }
97
+ line = out;
98
+ }
99
+ const sts = statements(line);
100
+ for (const st of sts) {
101
+ const lead = LABELS.exec(st.text)[0].length;
102
+ const body = st.text.slice(lead);
103
+ if (!body) continue;
104
+ const col = st.at + lead;
105
+ if (iaca) {
106
+ const m = iaca;
107
+ iaca = null;
108
+ if (IACA_BYTES.test(body)) {
109
+ if (m.kind === '111') begin('', m.line + 1);
110
+ else if (region && !region.closed) {
111
+ if (pendingBegin) { error ??= { line: region.line, message: 'the marked region has no instructions' }; pendingBegin = false; }
112
+ region.closed = true;
113
+ region.end = label(m.line, m.col);
114
+ }
115
+ continue;
116
+ }
117
+ // a plain mov after all: the region's first instruction, if one is wanted
118
+ if (pendingBegin && m.inText) { region.begin = label(m.line, m.col); pendingBegin = false; }
119
+ }
120
+ if (body[0] === '.') {
121
+ const d = /^\.([\w.]+)\s*(.*)$/.exec(body);
122
+ const name = d?.[1].toLowerCase() ?? '';
123
+ const args = d?.[2] ?? '';
124
+ // an objdump line with its bytes (loop-find.js) starts the picked code like an instruction
125
+ if (name === 'byte' && pickPending && inText && i + 1 >= pick.begin) { region.begin = label(i, col); pickPending = false; }
126
+ if (name === 'loc') {
127
+ const m = /^(\d+)\s+(\d+)/.exec(args);
128
+ if (m && inText) locs.push({ label: label(i, col), file: Number(m[1]), line: Number(m[2]) });
129
+ // gcc's "view N" operand, which LLVM rejects ("unknown sub-directive"): blanked (the columns stay)
130
+ // (a symbol of it, which the debug sections can use, is defined as 0 in the trailer)
131
+ const v = /\bview\s+(\S+)/.exec(body);
132
+ if (v) {
133
+ const at = col + v.index;
134
+ lines[i] = lines[i].slice(0, at) + ' '.repeat(v[0].length) + lines[i].slice(at + v[0].length);
135
+ if (/^[A-Za-z_.$][\w.$]*$/.test(v[1])) views.add(v[1]);
136
+ }
137
+ } else if (name === 'file') {
138
+ const m = /^(\d+)\s/.exec(args);
139
+ const q = quoted(args);
140
+ if (m && q.length) files.set(Number(m[1]), q.length > 1 ? q[1] : q[0]);
141
+ } else if (name === 'text') { prev = inText; inText = true; }
142
+ else if (name === 'data' || name === 'bss') { prev = inText; inText = false; }
143
+ else if (name === 'section') { prev = inText; inText = isText(args); }
144
+ else if (name === 'pushsection') { stack.push(inText); prev = inText; inText = isText(args); }
145
+ else if (name === 'popsection') { prev = inText; inText = stack.pop() ?? true; }
146
+ else if (name === 'previous') { [inText, prev] = [prev, inText]; }
147
+ continue;
148
+ }
149
+ if (/^[\w.$@]+\s*=/.test(body)) continue; // a symbol assignment
150
+ // an instruction
151
+ if (pickPending && inText && i + 1 >= pick.begin) { region.begin = label(i, col); pickPending = false; }
152
+ // (a mov that can be an IACA marker is decided by the next statement)
153
+ const im = IACA_MOV.exec(body);
154
+ if (im) iaca = { kind: im[1] ?? im[2], line: i, col, inText };
155
+ else if (pendingBegin && inText) { region.begin = label(i, col); pendingBegin = false; }
156
+ }
157
+ // the end of the picked code: a label after the last statement of its last line (and the exits)
158
+ if (pick && i + 1 === pick.end && region.begin !== null && region.end === null && sts.length) {
159
+ const st = sts[sts.length - 1];
160
+ region.end = labels.length;
161
+ const name = `.Lwuica_${labels.length}`;
162
+ labels.push(name);
163
+ inserts.push({ line: i, col: st.at + st.text.length, text: `; ${name}:${stubText}` });
164
+ stubsPlaced = true;
165
+ }
166
+ }
167
+ if (pick && region.begin === null) error ??= { line: pick.begin, message: 'the loop has no instructions' };
168
+ if (pendingBegin) error ??= { line: region.line, message: 'the marked region has no instructions' };
169
+ if (!regions.length && !locs.length && !pick && !stubs.length) return null;
170
+ // the new text: marker lines replaced, labels put in front of statements (right to left within a line)
171
+ const shifts = new Map();
172
+ const byLine = new Map();
173
+ for (const x of inserts) (byLine.get(x.line) ?? byLine.set(x.line, []).get(x.line)).push(x);
174
+ for (const [i, xs] of byLine) {
175
+ xs.sort((a, b) => b.col - a.col);
176
+ let l = lines[i];
177
+ const sh = [];
178
+ for (const x of xs) { const ins = x.text ?? `${x.label}: `; l = l.slice(0, x.col) + ins + l.slice(x.col); sh.push({ col: x.col, len: ins.length }); }
179
+ lines[i] = l;
180
+ shifts.set(i + 1, sh);
181
+ }
182
+ for (const [i, t] of replaced) lines[i] = t;
183
+ const lineCount = lines.length;
184
+ const parts = [];
185
+ for (let k = 0; k < labels.length; k += 32) parts.push(`.long ${labels.slice(k, k + 32).map((n) => `.Lwuica_z-${n}`).join(', ')}`);
186
+ const sets = [...views].map((n) => `.set ${n}, 0\n`).join('');
187
+ const tail = stubsPlaced ? '' : `${stubs.map((n) => `${n}:`).join('\n')}\n`; // the exits at the end of the code
188
+ const out = `${lines.join('\n')}\n${sets}.text\n${tail}.Lwuica_z:\n.long ${MAGIC}\n${parts.join('\n')}\n`;
189
+ if (region) delete region.closed;
190
+ return { text: out, labels, regions, region, locs, files, shifts, lineCount, error };
191
+ }
192
+
193
+ // The diagnostics of the rewritten text in the user's columns; those of the trailer dropped.
194
+ function mapDiagnostics(plan, diagnostics) {
195
+ const out = [];
196
+ for (const d of diagnostics) {
197
+ if (d.line && d.line > plan.lineCount) continue;
198
+ let column = d.column;
199
+ if (d.line && column) {
200
+ // the inserts in the new text's columns (left to right), each moves what follows it
201
+ let acc = 0, minus = 0;
202
+ for (const s of [...(plan.shifts.get(d.line) ?? [])].sort((a, b) => a.col - b.col)) {
203
+ const at = s.col + acc;
204
+ if (column - 1 >= at + s.len) minus += s.len; else if (column - 1 >= at) { minus = column - 1 - s.col; break; }
205
+ acc += s.len;
206
+ }
207
+ column -= minus;
208
+ }
209
+ out.push({ ...d, column });
210
+ }
211
+ return out;
212
+ }
213
+
214
+ // After a successful assembly of plan.text: {code, offsets} (code: the bytes without the trailer; offsets: one per
215
+ // label), or null (no trailer: not the real assembler).
216
+ export function readTrailer(plan, bytes) {
217
+ const n = plan.labels.length;
218
+ const z = bytes.length - 4 - 4 * n;
219
+ if (z < 0) return null;
220
+ const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
221
+ if (dv.getUint32(z, true) !== MAGIC) return null;
222
+ const offsets = [];
223
+ for (let k = 0; k < n; k++) {
224
+ const o = z - dv.getUint32(z + 4 + 4 * k, true);
225
+ if (o < 0 || o > z) return null;
226
+ offsets.push(o);
227
+ }
228
+ return { code: bytes.subarray(0, z), offsets };
229
+ }
230
+
231
+ const base = (p) => String(p).split(/[\\/]/).pop();
232
+
233
+ // The analyzed bytes and the source lines of a plan: {bytes, region, source} or {error}.
234
+ export function cutPlan(plan, code, offsets) {
235
+ let start = 0, end = code.length, region = null;
236
+ if (plan.region) {
237
+ const r = plan.region;
238
+ if (plan.error) return { error: plan.error };
239
+ start = offsets[r.begin];
240
+ end = r.end === null ? code.length : offsets[r.end];
241
+ if (!(end > start)) return { error: { line: r.line, message: 'the marked region has no machine code in .text' } };
242
+ region = r.auto ? { auto: true } : { name: r.name, line: r.line, index: 0, count: plan.regions.length };
243
+ }
244
+ let source = null;
245
+ if (plan.locs.length) {
246
+ const at = plan.locs.map((l) => ({ off: offsets[l.label], file: l.file, line: l.line }))
247
+ .filter((x) => x.off >= start && x.off < end);
248
+ // the .loc in force at the region's start (the last one before it) counts too
249
+ const before = plan.locs.map((l) => ({ off: offsets[l.label], file: l.file, line: l.line })).filter((x) => x.off < start).pop();
250
+ if (before) at.unshift({ ...before, off: start });
251
+ const count = new Map();
252
+ for (const x of at) if (x.line > 0) count.set(x.file, (count.get(x.file) ?? 0) + 1);
253
+ let main = null, best = 0;
254
+ for (const [f, c] of count) if (c > best) { best = c; main = f; }
255
+ if (main !== null) {
256
+ const spans = at.map((x) => ({ off: x.off - start, line: x.file === main && x.line > 0 ? x.line : null }))
257
+ .sort((a, b) => a.off - b.off)
258
+ .filter((x, k, all) => k + 1 === all.length || all[k + 1].off !== x.off); // of several at one offset the last
259
+ const name = plan.files.get(main);
260
+ source = { text: null, file: name ? base(name) : null, spans };
261
+ }
262
+ }
263
+ return { bytes: code.slice(start, end), region, source };
264
+ }
265
+
266
+ // One assembly of a text with its marked region (or picked loop) and .loc lines.
267
+ async function assembleOnce(assemble, text, prep) {
268
+ const plan = planMarked(text, prep ? { pick: prep.pick, stubs: prep.stubs } : {});
269
+ if (!plan) return assemble(text);
270
+ const r = await assemble(plan.text);
271
+ if (r.ok) {
272
+ const t = readTrailer(plan, r.bytes);
273
+ if (!t) return assemble(text); // not the real assembler (the mock): the plain text
274
+ const c = cutPlan(plan, t.code, t.offsets);
275
+ const diagnostics = mapDiagnostics(plan, r.diagnostics);
276
+ if (c.error) return { ok: false, diagnostics: [{ line: c.error.line, column: null, severity: 'error', message: c.error.message }] };
277
+ return { ok: true, bytes: c.bytes, diagnostics, region: c.region?.auto ? null : c.region, source: c.source };
278
+ }
279
+ const own = r.diagnostics.some((d) => d.severity === 'error' && (!d.line || d.line > plan.lineCount));
280
+ if (!own) return { ...r, diagnostics: mapDiagnostics(plan, r.diagnostics) };
281
+ // the labels or the trailer failed (a region or a .loc outside .text): the plain text
282
+ const p = await assemble(text);
283
+ if (!p.ok || !plan.region || plan.region.auto) return p;
284
+ return { ok: false, diagnostics: [{ line: plan.region.line, column: null, severity: 'error', message: 'the marked region is not in .text' }] };
285
+ }
286
+
287
+ // ';' after a statement. LLVM (like GNU as) reads it as a separator: what follows is assembled as a statement if it can
288
+ // be. Pasted listings use it for comments (MASM, NASM, Compiler Explorer). The rule:
289
+ // - what follows assembles: it is assembled (a separator), with a note that names it, unless the ';' chains
290
+ // statements as GNU as code writes it (no space before the ';': "dec rcx; jnz 1b")
291
+ // - it does not assemble, for any reason: it is a comment (nothing after a ';' turns a valid line into an error),
292
+ // with a note if it starts with a mnemonic ("add the next element"); silently if it does not ("sum += a[i]")
293
+ // A ';' at the start of a line is always a comment (loop-find.js, leadingSemicolons).
294
+
295
+ // The columns (0-based) of the ';' separators of a line, outside quotes and before a comment.
296
+ function separators(line) {
297
+ const out = [];
298
+ let q = false;
299
+ for (let i = 0; i < line.length; i++) {
300
+ const c = line[i];
301
+ if (q) { if (c === '\\') i++; else if (c === '"') q = false; continue; }
302
+ if (c === '"') q = true;
303
+ else if (c === '#' || (c === '/' && line[i + 1] === '/')) break;
304
+ else if (c === ';') out.push(i);
305
+ }
306
+ return out;
307
+ }
308
+
309
+ // After a failed assembly: the lines whose error lies after a ';' get that ';' as '#'. {fixes: Map line -> new text,
310
+ // notes: [{line, column, severity: 'note', message}]}.
311
+ export function commentFixes(diagnostics, text) {
312
+ const lines = String(text).split('\n');
313
+ const fixes = new Map(), notes = [];
314
+ for (const d of diagnostics ?? []) {
315
+ if (d.severity !== 'error' || !d.line || !d.column) continue;
316
+ const l = fixes.get(d.line) ?? lines[d.line - 1] ?? '';
317
+ const at = separators(l).filter((p) => p < d.column - 1).pop();
318
+ if (at === undefined || !l.slice(0, at).trim()) continue;
319
+ fixes.set(d.line, l.slice(0, at) + '#' + l.slice(at + 1));
320
+ if (!/^(?:invalid instruction mnemonic|unexpected token at start of statement)/.test(d.message)) {
321
+ notes.push({ line: d.line, column: at + 1, severity: 'note', message: "text after ';' taken as a comment" });
322
+ }
323
+ }
324
+ return { fixes, notes };
325
+ }
326
+
327
+ // After a successful assembly: a note for each ';' whose rest was assembled as a statement (see above), unless the ';'
328
+ // is written as GNU as chains statements, right after the statement ("dec rcx; jnz 1b").
329
+ export function separatorNotes(text) {
330
+ const notes = [];
331
+ String(text).split('\n').forEach((l, i) => {
332
+ const seps = separators(l);
333
+ seps.forEach((at, k) => {
334
+ const before = l.slice(0, at), seg = l.slice(at + 1, seps[k + 1] ?? l.length).replace(/(#|\/\/).*$/, '').trim();
335
+ if (!before.trim() || !seg || !/\s$/.test(before)) return;
336
+ notes.push({ line: i + 1, column: at + 1, severity: 'note', message: `';' separates statements: '${seg}' was assembled (use # for a comment)` });
337
+ });
338
+ });
339
+ return notes;
340
+ }
341
+
342
+ // Assembles text with its marked region and .loc lines: assembler.assemble's result plus region ({name, line, index,
343
+ // count} | null) and source ({text: null, file, spans: [{off, line}]} | null). assemble(text) -> promise of that result.
344
+ // A ';' comment after a statement is retried as '#' (above).
345
+ // opts.loop ('auto', 'whole' or a loop's index): the text is assembled for an analysis (loop-find.js): objdump lines,
346
+ // the loop or the body of a function, the exits as not taken. The result then also has loop ({index, count, name, line,
347
+ // endLine, address, alignment} | null: what was picked), loops ([{begin, end, label}]: the choices), body ({begin, end}
348
+ // | null), choosable (a choice matters: code around the loop or the body) and alignment (from
349
+ // the text's addresses, or null), and the notes (exits, undefined jump targets) among its diagnostics.
350
+ export async function assembleMarked(assemble, text, opts = {}) {
351
+ const analysis = opts.loop !== undefined && opts.loop !== null;
352
+ const prep = analysis ? preparePaste(text, { loop: opts.loop, func: opts.func }) : null;
353
+ if (prep?.error) return { ok: false, diagnostics: [{ line: null, column: null, severity: 'error', message: prep.error }] };
354
+ let work = prep ? prep.text : normalizeText(text);
355
+ const fallback = new Map(prep?.fallback ?? []);
356
+ const commentNotes = [];
357
+ let r;
358
+ for (let round = 0; ; round++) {
359
+ r = await assembleOnce(assemble, work, prep);
360
+ if (r.ok || round >= 8) break;
361
+ // retry: ';' comments; objdump lines the assembler rejects, as their bytes
362
+ const { fixes, notes } = commentFixes(r.diagnostics, work);
363
+ commentNotes.push(...notes);
364
+ for (const d of r.diagnostics) {
365
+ if (d.severity === 'error' && d.line && !fixes.has(d.line) && fallback.has(d.line)) { fixes.set(d.line, fallback.get(d.line)); fallback.delete(d.line); }
366
+ }
367
+ if (!fixes.size) break;
368
+ const lines = work.split('\n');
369
+ for (const [l, t] of fixes) lines[l - 1] = t;
370
+ work = lines.join('\n');
371
+ }
372
+ if (r.ok) {
373
+ const notes = [...commentNotes, ...separatorNotes(work)];
374
+ if (notes.length) r = { ...r, diagnostics: [...r.diagnostics, ...notes] };
375
+ }
376
+ if (!prep) return r;
377
+ const loop = prep.choice === null ? null : {
378
+ index: prep.choice === 'body' ? null : prep.choice, count: prep.loops.length, name: loopName(prep),
379
+ line: prep.pick.begin, endLine: prep.pick.end, lines: prep.pick.lines, address: prep.address, alignment: prep.alignment,
380
+ };
381
+ const out = { ...r, loop, loops: prep.loops, body: prep.body, choosable: prep.choosable, alignment: prep.alignment };
382
+ if (r.ok && prep.notes.length) out.diagnostics = [...r.diagnostics, ...prep.notes];
383
+ return out;
384
+ }
385
+
386
+ // The assembler with marked regions (assemble() as assembleMarked; everything else as the assembler's own).
387
+ // assemble(text, syntax, {loop, ...}): loop as assembleMarked's; the other options go to the assembler.
388
+ export function withRegions(assembler) {
389
+ if (!assembler) return assembler;
390
+ const assemble = (text, syntax, opts) => {
391
+ const { loop, ...rest } = opts ?? {};
392
+ return assembleMarked((t) => assembler.assemble(t, syntax, opts ? rest : opts), text, { loop });
393
+ };
394
+ return new Proxy(assembler, {
395
+ get(target, prop) {
396
+ if (prop === 'assemble') return assemble;
397
+ const v = Reflect.get(target, prop, target);
398
+ return typeof v === 'function' ? v.bind(target) : v;
399
+ },
400
+ });
401
+ }
402
+
403
+ // The source line of each instruction row of a response (srcmap.js): spans [{off, line}] sorted by offset; the rows'
404
+ // opcodes give the offsets (as listing.js). [line | null per instruction row].
405
+ export function spanLines(rows, spans) {
406
+ const out = [];
407
+ let off = 0, k = -1;
408
+ for (const r of rows ?? []) {
409
+ if (r?.kind !== 'instr') continue;
410
+ while (k + 1 < spans.length && spans[k + 1].off <= off) k++;
411
+ out.push(k >= 0 ? spans[k].line : null);
412
+ off += (String(r.opcode ?? '').match(/[0-9a-f]{2}/gi) ?? []).length;
413
+ }
414
+ return out;
415
+ }
@@ -0,0 +1,188 @@
1
+ // Adapter for the assembler module (wuica_asm.wasm: LLVM's x86 assembler, built in assembler/). The rest of the
2
+ // page only uses: WasmAssembler.create(bytes), assemble(text, syntax) and the result shape below. The page runs small
3
+ // sources on its own thread and large ones in a worker (assembler-rpc.js).
4
+ //
5
+ // The interface is the one of assembler/README.md ("Interface", "Rules"): exports memory, _initialize, malloc,
6
+ // free, wuica_assemble, wuica_fatal_message; no imports (the import object is {});
7
+ // int wuica_assemble(const char *text /* UTF-8, NUL-terminated */, int syntax /* 0 Intel, 1 AT&T */,
8
+ // unsigned char *out, unsigned out_cap, char *err, unsigned err_cap)
9
+ // returns the number of .text bytes, or -1 (diagnostics in err), -2 (out too small: "N bytes needed"),
10
+ // -3 (bad arguments / internal error); err holds llvm-mc style diagnostics, or warnings on success.
11
+ // _initialize() once per instance; views of the memory after each call; a trap (out of memory) makes the instance
12
+ // unusable: it is dropped and the next call instantiates the compiled module again.
13
+ // GNU as's {load}/{store} hints, which LLVM rejects, are removed at the start of a line, as the README suggests
14
+ // (they only pick between two encodings of the same length).
15
+ //
16
+ // assemble() resolves to
17
+ // { ok: true, bytes: Uint8Array, diagnostics: [...] } diagnostics: warnings, if any
18
+ // { ok: false, diagnostics: [{ line, column, severity, message }] } line/column are 1-based or null
19
+ // No DOM and no fetch in here.
20
+
21
+ export const SYNTAX = Object.freeze({ intel: 0, att: 1 });
22
+ const ERR_CAP = 16384;
23
+ const OUT_CAP = 1 << 16;
24
+ // At most this much machine code (as in the npm package), assembled or given as hex: a block this large is already
25
+ // more than the analyzer can simulate in its memory.
26
+ export const MAX_CODE_BYTES = 1 << 20;
27
+ export const tooMuchCode = (bytes) => `Too much machine code: ${bytes.toLocaleString('en-US')} bytes (at most ${MAX_CODE_BYTES.toLocaleString('en-US')})`;
28
+
29
+ // llvm-mc's diagnostics: "<input>:LINE:COL: error: MESSAGE", followed by the source line and a caret line.
30
+ export function parseDiagnostics(text) {
31
+ const out = [];
32
+ for (const l of String(text ?? '').split('\n')) {
33
+ const m = /^[^:\n]*:(\d+):(\d+): (error|warning|note): (.*)$/.exec(l);
34
+ if (m) out.push({ line: Number(m[1]), column: Number(m[2]), severity: m[3], message: m[4].trim() });
35
+ }
36
+ const rest = String(text ?? '').trim();
37
+ if (out.length === 0 && rest !== '') out.push({ line: null, column: null, severity: 'error', message: rest.split('\n')[0] });
38
+ return out;
39
+ }
40
+
41
+ // Removes GNU as's {load} / {store} pseudo-prefixes at the start of a line (LLVM 22 says "unknown prefix").
42
+ export function stripHints(text) {
43
+ return text.replace(/^([ \t]*)\{(?:load|store)\}[ \t]*/gm, '$1');
44
+ }
45
+
46
+ // LLVM (like GNU as) reads ';' as a separator between statements, not as a comment, so "add rax, 1 ; note" fails with
47
+ // "invalid instruction mnemonic 'note'". Such an error (right after a ';') gets a hint. diagnostics: changed in place.
48
+ export function semicolonHint(diagnostics, text) {
49
+ const lines = String(text).split('\n');
50
+ for (const d of diagnostics) {
51
+ if (d.severity !== 'error' || !d.line || !d.column || !/^(invalid instruction mnemonic|unexpected token at start of statement)/.test(d.message)) continue;
52
+ if (/;\s*$/.test((lines[d.line - 1] ?? '').slice(0, d.column - 1))) d.message += " (';' separates instructions; comments start with '#')";
53
+ }
54
+ return diagnostics;
55
+ }
56
+
57
+ // The analyzer only models 64-bit code: a source that switches the assembler to 16- or 32-bit mode (.code16,
58
+ // .code16gcc, .code32; LLVM accepts them in lower case only) would be analyzed as 64-bit code without a word.
59
+ // Returns {line, column, message} for the first such directive (outside comments), or null.
60
+ export function codeModeError(text) {
61
+ const plain = String(text).replace(/\/\*[\s\S]*?\*\//g, (c) => c.replace(/[^\n]/g, ' ')); // block comments, lines kept
62
+ const lines = plain.split('\n');
63
+ for (let i = 0; i < lines.length; i++) {
64
+ const code = lines[i].replace(/(#|\/\/).*$/, '');
65
+ let at = 0;
66
+ for (const stmt of code.split(';')) {
67
+ const m = /^(\s*(?:[\w.$@]+:\s*)*)(\.code(?:16gcc|16|32))(?=\s|$)/.exec(stmt);
68
+ if (m) return { line: i + 1, column: at + m[1].length + 1, message: `${m[2]}: only 64-bit code can be analyzed` };
69
+ at += stmt.length + 1;
70
+ }
71
+ }
72
+ return null;
73
+ }
74
+
75
+ // True if the bytes are a WebAssembly module. A static host may answer a missing file with an HTML page and
76
+ // status 200, so the status of the response is not enough.
77
+ export function isWasm(bytes) {
78
+ return bytes?.length >= 8 && bytes[0] === 0 && bytes[1] === 0x61 && bytes[2] === 0x73 && bytes[3] === 0x6d;
79
+ }
80
+
81
+ export class WasmAssembler {
82
+ #module;
83
+ #x = null;
84
+
85
+ // source: the bytes of wuica_asm.wasm, a WebAssembly.Module, or (tests) a function that returns a fresh object with
86
+ // the exports.
87
+ static async create(source) {
88
+ const a = new WasmAssembler();
89
+ if (typeof source === 'function' || source instanceof WebAssembly.Module) {
90
+ a.#module = source;
91
+ } else {
92
+ if (!isWasm(source)) throw new Error('wuica_asm.wasm is not a WebAssembly module');
93
+ a.#module = await WebAssembly.compile(source);
94
+ }
95
+ await a.#instantiate();
96
+ return a;
97
+ }
98
+
99
+ // The size of the instance's memory (it only grows: the most it has used); 0 if there is no instance.
100
+ get memoryBytes() { return this.#x?.memory.buffer.byteLength ?? 0; }
101
+
102
+ // Drops the instance (and its memory); the next call makes a new one.
103
+ reset() { this.#x = null; }
104
+
105
+ async #instantiate() {
106
+ let x;
107
+ if (typeof this.#module === 'function') {
108
+ x = this.#module();
109
+ } else {
110
+ // The module is specified to have no imports. If a build has some after all (WASI), give it functions that
111
+ // fail with ENOSYS instead of refusing to load.
112
+ const imports = {};
113
+ for (const i of WebAssembly.Module.imports(this.#module)) {
114
+ if (i.kind !== 'function') throw new Error(`wuica_asm.wasm: unsupported import ${i.module}.${i.name}`);
115
+ (imports[i.module] ??= {})[i.name] = () => 52;
116
+ }
117
+ x = (await WebAssembly.instantiate(this.#module, imports)).exports;
118
+ }
119
+ for (const name of ['memory', 'malloc', 'free', 'wuica_assemble']) {
120
+ if (!x[name]) throw new Error(`wuica_asm.wasm: export "${name}" is missing`);
121
+ }
122
+ x._initialize?.(); // static constructors; once per instance, before anything else
123
+ this.#x = x;
124
+ }
125
+
126
+ #cstr(ptr) {
127
+ const mem = new Uint8Array(this.#x.memory.buffer);
128
+ let end = mem.indexOf(0, ptr);
129
+ if (end < 0) end = mem.length;
130
+ return new TextDecoder().decode(mem.subarray(ptr, end));
131
+ }
132
+
133
+ #run(source, syntax, outCap) {
134
+ const x = this.#x;
135
+ const textPtr = x.malloc(source.length);
136
+ const outPtr = x.malloc(outCap);
137
+ const errPtr = x.malloc(ERR_CAP);
138
+ try {
139
+ if (!textPtr || !outPtr || !errPtr) throw new Error('the assembler is out of memory');
140
+ new Uint8Array(x.memory.buffer).set(source, textPtr); // a view made after the last malloc
141
+ const status = x.wuica_assemble(textPtr, syntax, outPtr, outCap, errPtr, ERR_CAP);
142
+ // Views after the call: the memory can have grown.
143
+ const message = this.#cstr(errPtr);
144
+ const bytes = status >= 0 ? new Uint8Array(x.memory.buffer).slice(outPtr, outPtr + status) : null;
145
+ return { status, bytes, message };
146
+ } finally {
147
+ if (textPtr) x.free(textPtr);
148
+ if (outPtr) x.free(outPtr);
149
+ if (errPtr) x.free(errPtr);
150
+ }
151
+ }
152
+
153
+ // text: assembly source; syntax: 'intel' | 'att'.
154
+ async assemble(text, syntax = 'intel') {
155
+ if (!(syntax in SYNTAX)) throw new TypeError(`unknown syntax: ${syntax}`);
156
+ if (!this.#x) await this.#instantiate();
157
+ // (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, ' '));
159
+ const mode = codeModeError(plain);
160
+ if (mode) return { ok: false, diagnostics: [{ severity: 'error', ...mode }] };
161
+ const source = new TextEncoder().encode(plain + '\0');
162
+ let r;
163
+ try {
164
+ r = this.#run(source, SYNTAX[syntax], OUT_CAP);
165
+ if (r.status === -2) {
166
+ const need = Number(/(\d+) bytes needed/.exec(r.message)?.[1]);
167
+ if (need > MAX_CODE_BYTES) {
168
+ return { ok: false, diagnostics: [{ line: null, column: null, severity: 'error', message: tooMuchCode(need) }] };
169
+ }
170
+ if (need > OUT_CAP) r = this.#run(source, SYNTAX[syntax], need);
171
+ }
172
+ } catch (e) {
173
+ // A trap (LLVM's fatal error handler). The instance is unusable afterwards: drop it, the next call makes a new one.
174
+ let fatal = '';
175
+ try { const p = this.#x.wuica_fatal_message?.(); if (p) fatal = this.#cstr(p); } catch { /* ignore */ }
176
+ this.#x = null;
177
+ const message = fatal || (e instanceof Error ? e.message : String(e));
178
+ return { ok: false, diagnostics: [{ line: null, column: null, severity: 'error', message: `the assembler failed: ${message}` }] };
179
+ }
180
+ const diagnostics = parseDiagnostics(r.message);
181
+ if (r.status >= 0) return { ok: true, bytes: r.bytes, diagnostics };
182
+ semicolonHint(diagnostics, plain);
183
+ if (!diagnostics.some((d) => d.severity === 'error')) {
184
+ diagnostics.push({ line: null, column: null, severity: 'error', message: `the assembler failed (code ${r.status})` });
185
+ }
186
+ return { ok: false, diagnostics };
187
+ }
188
+ }