interplane.Get Omega
Read in your language

omega-mv

Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.

Brought by drakestapleton

branch main Branches Tags History

omega-mv / seed / wasm / v7 / oracle.js

773 lines · 31864 bytes Raw Blame History
1#!/usr/bin/env node
2// SPDX-License-Identifier: Apache-2.0
3// Independent read-only oracle for OSC IR wire versions 1 and 7.
4//
5// Written from spec/one-layer-format.md sections 3..7 and 10 and
6// docs/one_layer/OMEGESE.md 11.1/11.2 only. It shares no code with
7// seed/wasm/irwasm.om, seed/wasm/oracle.js, seed/omc/omc.om, the C IR tools,
8// or seed/wasm/v7/writer.js (the fixture writer). It is a referee: it never
9// produces IR or wasm.
10//
11// node oracle.js check UNIT -> ACCEPT v1|v7 / REFUSE CLASS detail
12// node oracle.js run [--codes] UNIT SCRIPT
13//
14// Exit: check 0 accept, 1 refuse, 2 usage. run 0 done, 1 unit refused,
15// 2 usage/script error, 3 oracle resource limit (not an Omega result).
16'use strict';
17
18const fs = require('fs');
19
20const MAGIC = [0x4f, 0x53, 0x43, 0x31, 0x49, 0x52, 0x00];
21const V1_INPUT_MAX = 2620251;
22const V7_INPUT_MAX = 8388608;
23const MAX_FUNCS = 32;
24const MAX_PARAMS = 6;
25const MAX_VREGS = 480;
26const MAX_BLOCKS = 512;
27const MAX_INSNS = 4096;
28const MAX_STRUCTS = 16;
29const MAX_REGIONS = 1024;
30const MAX_COUNT = 16777216;
31const NAME_MAX = 63;
32const CLAUSE_MAX = 255;
33const NONE = 0xffff;
34const STEP_LIMIT = 200000000;
35
36// Scalar wire tags.
37const T_VOID = 0, T_BOOL = 1, T_F32 = 13, T_F64 = 14;
38const isInt = (t) => t >= 2 && t <= 9;
39const isFloat = (t) => t === T_F32 || t === T_F64;
40const isValue = (t) => t === T_BOOL || isInt(t) || isFloat(t);
41const isSigned = (t) => t >= 6 && t <= 9;
42const intWidth = (t) => [0, 1, 8, 16, 32, 64, 8, 16, 32, 64][t];
43const elemBytes = (t) => (t === T_F32 ? 4 : t === T_F64 ? 8 : intWidth(t) / 8);
44const BITCAST_SET = { 2: 0, 6: 0, 3: 1, 7: 1, 4: 2, 8: 2, 13: 2, 5: 3, 9: 3, 14: 3 };
45
46// Opcodes.
47const OP = {
48 CONST: 1, MOV: 2, BIN: 3, UN: 4, CMP: 5, CAST: 6, LOAD: 9, STORE: 10,
49 CALL: 11, TRAP: 12, BR: 13, CBR: 14, RET: 15,
50 RLOAD: 30, RSTORE: 31, BITCAST: 32, RINIT: 33,
51};
52const isTerm = (op) => op === OP.BR || op === OP.CBR || op === OP.RET;
53
54class Refusal extends Error {
55 constructor(cls, detail) {
56 super(cls + ' ' + detail);
57 this.cls = cls;
58 this.detail = detail;
59 }
60}
61const refuse = (cls, detail) => { throw new Refusal(cls, detail); };
62
63// ---------------------------------------------------------------- reader
64class Reader {
65 constructor(buf) { this.buf = buf; this.pos = 0; }
66 need(n, what) {
67 if (this.pos + n > this.buf.length) refuse('TRUNCATED', what + ' at byte ' + this.pos);
68 }
69 u8(what) { this.need(1, what); return this.buf[this.pos++]; }
70 u16(what) { this.need(2, what); const v = this.buf[this.pos] | (this.buf[this.pos + 1] << 8); this.pos += 2; return v; }
71 u32(what) { this.need(4, what); const v = this.buf.readUInt32LE(this.pos); this.pos += 4; return v; }
72 u64(what) { this.need(8, what); const v = this.buf.readBigUInt64LE(this.pos); this.pos += 8; return v; }
73 bytes(n, what) { this.need(n, what); const b = this.buf.subarray(this.pos, this.pos + n); this.pos += n; return b; }
74}
75
76function readTag(r, v7, what) {
77 const t = r.u8(what);
78 if (t <= 9) return t;
79 if ((t === T_F32 || t === T_F64) && v7) return t;
80 refuse('UNSUPPORTED_TAG', what + ' tag ' + t);
81}
82
83// Register-like u16 field. 0x8000..0xFFFE never designates anything (spec 3.5
84// RANGE; 10.1 INVALID). 0xFFFF is the "none" sentinel, checked per use.
85function readReg(r, what) {
86 const v = r.u16(what);
87 if (v >= 0x8000 && v !== NONE) refuse('INVALID', what + ' operand 0x' + v.toString(16));
88 return v;
89}
90
91function readFuncText(r, lenBytes, max, what) {
92 const n = lenBytes === 1 ? r.u8(what + ' length') : r.u16(what + ' length');
93 if (n > max) refuse('CAPACITY', what + ' length ' + n);
94 const b = r.bytes(n, what);
95 for (const c of b) if (c === 0) refuse('INVALID', what + ' contains NUL');
96 return b;
97}
98
99function readRegion(r, i) {
100 const what = 'region ' + i;
101 const n = r.u8(what + ' name length');
102 if (n === 0 || n > NAME_MAX) refuse('INVALID', what + ' name length ' + n);
103 const nb = r.bytes(n, what + ' name');
104 for (const c of nb) {
105 if (c === 0 || c >= 0x80 || c === 0x2e) refuse('INVALID', what + ' name byte 0x' + c.toString(16));
106 }
107 const name = nb.toString('latin1');
108 const tag = r.u8(what + ' element');
109 if (!(isInt(tag) || isFloat(tag))) refuse('INVALID', what + ' element tag ' + tag);
110 const cls = r.u8(what + ' class');
111 if (cls === 3) refuse('UNSUPPORTED_OP', what + ' class 3 (workgroup)');
112 if (cls > 3) refuse('INVALID', what + ' class ' + cls);
113 const owner = r.u16(what + ' owner');
114 const count = r.u32(what + ' count');
115 if (count > MAX_COUNT) refuse('INVALID', what + ' count ' + count);
116 if (cls !== 2 && count === 0) refuse('INVALID', what + ' mutable count 0');
117 const initlen = r.u32(what + ' initial length');
118 if (cls !== 2 && initlen !== 0) refuse('INVALID', what + ' initial data on class ' + cls);
119 if (cls === 2 && tag !== 2) refuse('INVALID', what + ' text element tag ' + tag);
120 if (cls === 2 && initlen !== count) refuse('INVALID', what + ' text length ' + initlen + ' != count ' + count);
121 const init = Buffer.from(r.bytes(initlen, what + ' initial data'));
122 return { name, tag, cls, owner, count, init };
123}
124
125function readInsn(r, v7, what) {
126 const op = r.u8(what + ' opcode');
127 const ins = { op, sub: 0, dst: NONE, a: NONE, b: NONE, c: NONE, imm: 0n, args: [] };
128 const reg = (k) => readReg(r, what + ' ' + k);
129 switch (op) {
130 case OP.CONST: ins.dst = reg('dst'); ins.imm = r.u64(what + ' imm'); break;
131 case OP.MOV: case OP.CAST: ins.dst = reg('dst'); ins.a = reg('a'); break;
132 case OP.BIN: case OP.CMP:
133 ins.sub = r.u8(what + ' sub'); ins.dst = reg('dst'); ins.a = reg('a'); ins.b = reg('b'); break;
134 case OP.UN: ins.sub = r.u8(what + ' sub'); ins.dst = reg('dst'); ins.a = reg('a'); break;
135 // LOAD/STORE (9/10) need a reference register, which this profile has not.
136 case OP.CALL: {
137 ins.dst = reg('dst'); ins.callee = reg('callee');
138 const n = r.u8(what + ' nargs');
139 if (n > MAX_PARAMS) refuse('CAPACITY', what + ' nargs ' + n);
140 for (let k = 0; k < n; k++) ins.args.push(reg('arg' + k));
141 break;
142 }
143 case OP.TRAP: ins.imm = BigInt(r.u8(what + ' trap code')); break;
144 case OP.BR: ins.blkT = reg('target'); break;
145 case OP.CBR: ins.a = reg('cond'); ins.blkT = reg('true target'); ins.blkF = reg('false target'); break;
146 case OP.RET: ins.a = reg('a'); break;
147 default:
148 if (op >= 30 && op <= 33 && v7) {
149 if (op === OP.RLOAD) { ins.dst = reg('dst'); ins.rg = reg('region'); ins.b = reg('index'); }
150 else if (op === OP.RSTORE) { ins.rg = reg('region'); ins.b = reg('index'); ins.c = reg('src'); }
151 else if (op === OP.BITCAST) { ins.dst = reg('dst'); ins.a = reg('src'); }
152 else { ins.rg = reg('region'); ins.a = reg('init'); }
153 break;
154 }
155 refuse('UNSUPPORTED_OP', what + ' opcode ' + op);
156 }
157 return ins;
158}
159
160function readFunc(r, v7, fi) {
161 const what = 'function ' + fi;
162 const nameBytes = readFuncText(r, 1, NAME_MAX, what + ' name');
163 for (const c of nameBytes) if (c >= 0x80) refuse('INVALID', what + ' name byte 0x' + c.toString(16));
164 const name = nameBytes.toString('latin1');
165 const nparams = r.u8(what + ' nparams');
166 const ret = readTag(r, v7, what + ' return');
167 const nvregs = r.u16(what + ' nvregs');
168 if (nvregs > MAX_VREGS) refuse('CAPACITY', what + ' nvregs ' + nvregs);
169 const vtype = [];
170 for (let k = 0; k < nvregs; k++) vtype.push(readTag(r, v7, what + ' register ' + k));
171 const nblocks = r.u16(what + ' nblocks');
172 if (nblocks > MAX_BLOCKS) refuse('CAPACITY', what + ' nblocks ' + nblocks);
173 const blocks = [];
174 for (let k = 0; k < nblocks; k++) blocks.push({ first: r.u32(what + ' block first'), count: r.u32(what + ' block count') });
175 const ninsns = r.u32(what + ' ninsns');
176 if (ninsns > MAX_INSNS) refuse('CAPACITY', what + ' ninsns ' + ninsns);
177 const insns = [];
178 for (let k = 0; k < ninsns; k++) insns.push(readInsn(r, v7, what + ' insn ' + k));
179 readFuncText(r, 2, CLAUSE_MAX, what + ' requires');
180 readFuncText(r, 2, CLAUSE_MAX, what + ' ensures');
181 return { name, nameBytes, nparams, ret, nvregs, vtype, blocks, insns };
182}
183
184// ------------------------------------------------------------ validation
185function canonicalConst(t, imm) {
186 if (t === T_BOOL) return imm === 0n || imm === 1n;
187 if (t === T_F64) return true;
188 if (t === T_F32) return imm >> 32n === 0n; // M:f32upper
189 const w = BigInt(intWidth(t));
190 if (isSigned(t)) return BigInt.asUintN(64, BigInt.asIntN(Number(w), imm)) === imm;
191 return imm >> w === 0n;
192}
193
194function validateFunc(u, fi) {
195 const f = u.funcs[fi];
196 const bad = (m) => refuse('INVALID', 'function ' + fi + ' (' + f.name + '): ' + m);
197 if (f.nparams > MAX_PARAMS) bad('nparams ' + f.nparams);
198 if (f.nparams > f.nvregs) bad('nparams exceeds nvregs');
199 if (!(f.ret === T_VOID || isValue(f.ret))) bad('return tag ' + f.ret);
200 f.vtype.forEach((t, k) => { if (!isValue(t)) bad('register ' + k + ' tag ' + t); });
201 if (f.blocks.length === 0 || f.insns.length === 0) bad('empty body');
202 let next = 0;
203 f.blocks.forEach((b, k) => {
204 if (b.first !== next || b.count === 0) bad('block ' + k + ' does not partition');
205 next = b.first + b.count;
206 if (next > f.insns.length) bad('block ' + k + ' past end');
207 });
208 if (next !== f.insns.length) bad('blocks do not cover instructions');
209 f.blocks.forEach((b, k) => {
210 for (let j = b.first; j < b.first + b.count; j++) {
211 const last = j === b.first + b.count - 1;
212 if (isTerm(f.insns[j].op) !== last) bad('block ' + k + ' terminator placement');
213 }
214 });
215
216 const ty = (r, k) => {
217 if (r === NONE || r >= f.nvregs) bad(k + ' register ' + r + ' outside table');
218 return f.vtype[r];
219 };
220 const region = (g, k) => {
221 if (g === NONE || g >= u.regions.length) bad(k + 'region ' + g + ' outside table');
222 const rg = u.regions[g];
223 if (rg.cls === 1 && rg.owner !== fi) bad(k + 'region ' + rg.name + ' owned by function ' + rg.owner); // M:owner
224 return rg;
225 };
226 const blk = (b) => { if (b === NONE || b >= f.blocks.length) bad('branch target ' + b); };
227
228 f.insns.forEach((ins, j) => {
229 const at = 'insn ' + j + ' ';
230 switch (ins.op) {
231 case OP.CONST: if (!canonicalConst(ty(ins.dst, at + 'dst'), ins.imm)) bad(at + 'non-canonical constant'); break;
232 case OP.MOV: if (ty(ins.dst, at + 'dst') !== ty(ins.a, at + 'a')) bad(at + 'MOV type'); break;
233 case OP.BIN: {
234 const t = ty(ins.dst, at + 'dst');
235 if (ty(ins.a, at + 'a') !== t) bad(at + 'BIN a type');
236 const tb = ty(ins.b, at + 'b');
237 const s = ins.sub;
238 if (s < 1 || s > 10) bad(at + 'BIN sub ' + s);
239 if (isFloat(t)) { if (s > 4 || tb !== t) bad(at + 'float BIN sub ' + s); }
240 else if (t === T_BOOL) { if (s < 6 || s > 8 || tb !== t) bad(at + 'bool BIN sub ' + s); }
241 else if (s >= 9) { if (!isInt(tb)) bad(at + 'shift amount type'); }
242 else if (tb !== t) bad(at + 'BIN b type');
243 break;
244 }
245 case OP.UN: {
246 const t = ty(ins.dst, at + 'dst');
247 if (ty(ins.a, at + 'a') !== t) bad(at + 'UN type');
248 const ok = ins.sub === 1 ? isInt(t) || isFloat(t) : ins.sub === 2 ? isInt(t) : ins.sub === 3 ? t === T_BOOL : false;
249 if (!ok) bad(at + 'UN sub ' + ins.sub + ' on tag ' + t);
250 break;
251 }
252 case OP.CMP:
253 if (ins.sub < 1 || ins.sub > 6) bad(at + 'CMP sub ' + ins.sub);
254 if (ty(ins.dst, at + 'dst') !== T_BOOL) bad(at + 'CMP dst not bool');
255 if (ty(ins.a, at + 'a') !== ty(ins.b, at + 'b')) bad(at + 'CMP operand types');
256 break;
257 case OP.CAST: {
258 const d = ty(ins.dst, at + 'dst'), s = ty(ins.a, at + 'a');
259 if (!(isInt(d) || isFloat(d)) || !(isInt(s) || isFloat(s))) bad(at + 'CAST types');
260 break;
261 }
262 case OP.CALL: {
263 if (ins.callee === NONE || ins.callee >= fi) bad(at + 'callee ' + ins.callee + ' is not an earlier function');
264 const g = u.funcs[ins.callee];
265 if (ins.args.length !== g.nparams) bad(at + 'CALL arity');
266 ins.args.forEach((a, k) => { if (ty(a, at + 'arg') !== g.vtype[k]) bad(at + 'CALL arg ' + k + ' type'); });
267 if (g.ret === T_VOID) { if (ins.dst !== NONE) bad(at + 'void call with destination'); }
268 else if (ty(ins.dst, at + 'dst') !== g.ret) bad(at + 'CALL result type');
269 break;
270 }
271 case OP.TRAP: if (ins.imm < 1n || ins.imm > 14n) bad(at + 'trap code ' + ins.imm); break;
272 case OP.BR: blk(ins.blkT); break;
273 case OP.CBR:
274 if (ty(ins.a, at + 'cond') !== T_BOOL) bad(at + 'CBR condition not bool');
275 blk(ins.blkT); blk(ins.blkF);
276 break;
277 case OP.RET:
278 if (f.ret === T_VOID) { if (ins.a !== NONE) bad(at + 'value returned from void'); }
279 else if (ty(ins.a, at + 'a') !== f.ret) bad(at + 'RET type');
280 break;
281 case OP.RLOAD: {
282 const t = ty(ins.dst, at + 'dst');
283 const rg = region(ins.rg, at);
284 if (!isInt(ty(ins.b, at + 'index'))) bad(at + 'index type');
285 if (t !== rg.tag) bad(at + 'RLOAD element type');
286 break;
287 }
288 case OP.RSTORE: {
289 const rg = region(ins.rg, at);
290 if (rg.cls === 2) bad(at + 'RSTORE into read-only text ' + rg.name); // M:textro
291 if (!isInt(ty(ins.b, at + 'index'))) bad(at + 'index type');
292 if (ty(ins.c, at + 'src') !== rg.tag) bad(at + 'RSTORE element type');
293 break;
294 }
295 case OP.BITCAST: {
296 const d = ty(ins.dst, at + 'dst'), s = ty(ins.a, at + 'src');
297 if (BITCAST_SET[d] === undefined || BITCAST_SET[d] !== BITCAST_SET[s]) bad(at + 'BITCAST ' + s + '->' + d);
298 break;
299 }
300 case OP.RINIT: {
301 const rg = region(ins.rg, at);
302 if (rg.cls !== 1) bad(at + 'RINIT of non-local region ' + rg.name);
303 if (ty(ins.a, at + 'init') !== rg.tag) bad(at + 'RINIT type');
304 break;
305 }
306 default: bad(at + 'opcode ' + ins.op);
307 }
308 });
309 definiteAssignment(u, f, fi, bad);
310}
311
312// Uses and definitions of one instruction (registers only).
313function usesOf(ins) {
314 switch (ins.op) {
315 case OP.MOV: case OP.UN: case OP.CAST: case OP.BITCAST: case OP.RET: case OP.CBR: case OP.RINIT:
316 return ins.a === NONE ? [] : [ins.a];
317 case OP.BIN: case OP.CMP: return [ins.a, ins.b];
318 case OP.CALL: return ins.args;
319 case OP.RLOAD: return [ins.b];
320 case OP.RSTORE: return [ins.b, ins.c];
321 default: return [];
322 }
323}
324function defOf(ins) {
325 switch (ins.op) {
326 case OP.CONST: case OP.MOV: case OP.BIN: case OP.UN: case OP.CMP: case OP.CAST:
327 case OP.RLOAD: case OP.BITCAST: case OP.CALL:
328 return ins.dst === NONE ? -1 : ins.dst;
329 default: return -1;
330 }
331}
332
333// Greatest-fixed-point must-analysis over registers and local-region
334// initialization bits (spec 10.2). State vector: nvregs register bits, then
335// one bit per region (only class-1 regions owned by this function matter).
336function definiteAssignment(u, f, fi, bad) {
337 const nb = f.blocks.length, nr = f.nvregs, ng = u.regions.length, n = nr + ng;
338 const entry = new Uint8Array(n);
339 for (let k = 0; k < f.nparams; k++) entry[k] = 1;
340 const succ = f.blocks.map((b) => {
341 const t = f.insns[b.first + b.count - 1];
342 return t.op === OP.BR ? [t.blkT] : t.op === OP.CBR ? [t.blkT, t.blkF] : [];
343 });
344 const reach = new Uint8Array(nb);
345 const stack = [0];
346 reach[0] = 1;
347 while (stack.length) {
348 for (const s of succ[stack.pop()]) if (!reach[s]) { reach[s] = 1; stack.push(s); }
349 }
350 const preds = Array.from({ length: nb }, () => []);
351 succ.forEach((ss, b) => { if (reach[b]) for (const s of ss) preds[s].push(b); });
352
353 const transfer = (b, inState, check) => {
354 const st = Uint8Array.from(inState);
355 const blk = f.blocks[b];
356 for (let j = blk.first; j < blk.first + blk.count; j++) {
357 const ins = f.insns[j];
358 if (check) {
359 for (const r of usesOf(ins)) if (!st[r]) bad('insn ' + j + ' uses register ' + r + ' before definite assignment');
360 if ((ins.op === OP.RLOAD || ins.op === OP.RSTORE) && u.regions[ins.rg].cls === 1 && !st[nr + ins.rg]) { // M:initcheck
361 bad('insn ' + j + ' accesses local region ' + u.regions[ins.rg].name + ' before RINIT on every path');
362 }
363 }
364 const d = defOf(ins);
365 if (d >= 0) st[d] = 1;
366 if (ins.op === OP.RINIT) st[nr + ins.rg] = 1;
367 }
368 return st;
369 };
370
371 // Reachable blocks start at TOP (everything assigned) and only shrink.
372 const out = f.blocks.map((_, b) => (reach[b] ? new Uint8Array(n).fill(1) : null));
373 const inOf = (b) => {
374 if (!reach[b]) return entry; // unreachable: validated from the entry state
375 const st = b === 0 ? Uint8Array.from(entry) : new Uint8Array(n).fill(1);
376 for (const p of preds[b]) {
377 const o = out[p];
378 for (let k = 0; k < n; k++) st[k] &= o[k]; // M:meet
379 }
380 return st;
381 };
382 let changed = true;
383 while (changed) {
384 changed = false;
385 for (let b = 0; b < nb; b++) {
386 if (!reach[b]) continue;
387 const o = transfer(b, inOf(b), false);
388 for (let k = 0; k < n; k++) if (o[k] !== out[b][k]) { out[b] = o; changed = true; break; }
389 }
390 }
391 for (let b = 0; b < nb; b++) transfer(b, inOf(b), true);
392}
393
394function validateUnit(u) {
395 const bad = (m) => refuse('INVALID', m);
396 const module = new Set();
397 u.regions.forEach((rg, i) => {
398 if (rg.cls === 1) {
399 if (rg.owner === NONE || rg.owner >= u.funcs.length) bad('region ' + i + ' local owner ' + rg.owner);
400 } else {
401 if (rg.owner !== NONE) bad('region ' + i + ' module owner ' + rg.owner);
402 if (module.has(rg.name)) bad('duplicate module region ' + rg.name);
403 module.add(rg.name);
404 }
405 });
406 const locals = new Set();
407 u.regions.forEach((rg) => {
408 if (rg.cls !== 1) return;
409 if (module.has(rg.name)) bad('local region ' + rg.name + ' shadows a module region');
410 const key = rg.owner + '/' + rg.name;
411 if (locals.has(key)) bad('duplicate local region ' + rg.name + ' in function ' + rg.owner);
412 locals.add(key);
413 });
414 const exportsSeen = new Set();
415 const exp = (name) => { if (exportsSeen.has(name)) bad('export name collision ' + JSON.stringify(name)); exportsSeen.add(name); }; // M:export
416 if (u.version === 7) {
417 exp('memory');
418 u.regions.forEach((rg) => { if (rg.cls !== 1) exp('region.' + rg.name); });
419 }
420 u.funcs.forEach((f) => exp(f.name));
421}
422
423function usesV7(u) {
424 if (u.regions.length > 0) return true;
425 for (const f of u.funcs) {
426 if (isFloat(f.ret) || f.vtype.some(isFloat)) return true;
427 if (f.insns.some((i) => i.op >= 30 && i.op <= 33)) return true;
428 }
429 return false;
430}
431
432function decode(buf) {
433 if (buf.length > V7_INPUT_MAX) refuse('CAPACITY', 'input ' + buf.length + ' bytes');
434 const headIsV7 = buf.length >= 8 && MAGIC.every((m, i) => buf[i] === m) && buf[7] === 7;
435 if (buf.length > V1_INPUT_MAX && !headIsV7) refuse('CAPACITY', 'input ' + buf.length + ' bytes');
436 const r = new Reader(buf);
437 for (let i = 0; i < 7; i++) if (r.u8('magic') !== MAGIC[i]) refuse('MAGIC', 'byte ' + i);
438 const version = r.u8('version');
439 if (version !== 1 && version !== 7) refuse('VERSION', 'version ' + version);
440 const v7 = version === 7;
441 const u = { version, regions: [], funcs: [] };
442 if (v7) {
443 const ns = r.u8('nstructs');
444 if (ns > MAX_STRUCTS) refuse('CAPACITY', 'nstructs ' + ns);
445 if (ns > 0) refuse('UNSUPPORTED_TAG', 'struct table (' + ns + ' structs)');
446 const ng = r.u16('nregions');
447 if (ng > MAX_REGIONS) refuse('INVALID', 'nregions ' + ng);
448 for (let i = 0; i < ng; i++) u.regions.push(readRegion(r, i));
449 }
450 const nf = r.u16('nfuncs');
451 if (nf > MAX_FUNCS) refuse('CAPACITY', 'nfuncs ' + nf);
452 for (let i = 0; i < nf; i++) {
453 u.funcs.push(readFunc(r, v7, i));
454 validateFunc(u, i);
455 }
456 validateUnit(u);
457 if (r.pos !== buf.length) refuse('TRAILING', (buf.length - r.pos) + ' bytes after last function'); // M:trailing
458 if (v7 && !usesV7(u)) refuse('VERSION', 'gratuitous v7: no region, float or memory opcode'); // M:gratuitous
459 return u;
460}
461
462// ----------------------------------------------------------- interpreter
463// Integer and bool registers hold their mathematical value as a BigInt
464// (unsigned 0..2^w-1, signed sign-extended, bool 0/1). Float registers hold
465// their raw IEEE bits as a BigInt so CONST/MOV/RLOAD/RSTORE/RINIT/BITCAST
466// transport NaN payloads exactly; arithmetic converts through a DataView.
467class Trap { constructor(code) { this.code = code; } }
468const trap = (code) => { throw new Trap(code); };
469
470const scratch = new DataView(new ArrayBuffer(8));
471function f32val(bits) { scratch.setUint32(0, Number(bits), true); return scratch.getFloat32(0, true); }
472function f32bits(x) { scratch.setFloat32(0, x, true); return BigInt(scratch.getUint32(0, true)); }
473function f64val(bits) { scratch.setBigUint64(0, bits, true); return scratch.getFloat64(0, true); }
474function f64bits(x) { scratch.setFloat64(0, x, true); return scratch.getBigUint64(0, true); }
475const fval = (t, bits) => (t === T_F32 ? f32val(bits) : f64val(bits));
476const fbits = (t, x) => (t === T_F32 ? f32bits(Math.fround(x)) : f64bits(x));
477
478function intMin(t) { return isSigned(t) ? -(1n << BigInt(intWidth(t) - 1)) : 0n; }
479function intMax(t) { return isSigned(t) ? (1n << BigInt(intWidth(t) - 1)) - 1n : (1n << BigInt(intWidth(t))) - 1n; }
480function wrapInt(t, v) { const w = intWidth(t); return isSigned(t) ? BigInt.asIntN(w, v) : BigInt.asUintN(w, v); }
481function checked(t, v) {
482 if (!isSigned(t)) return BigInt.asUintN(intWidth(t), v);
483 if (v < intMin(t) || v > intMax(t)) trap(1);
484 return v;
485}
486
487// Integer to f32 with one rounding (nearest, ties to even), from the exact
488// BigInt. Converting through a double first could round twice.
489function bigToF32Bits(v) {
490 const neg = v < 0n;
491 let m = neg ? -v : v;
492 let x;
493 if (m < (1n << 24n)) x = Number(m);
494 else {
495 const shift = m.toString(2).length - 24;
496 let top = m >> BigInt(shift);
497 const rest = m - (top << BigInt(shift));
498 const half = 1n << BigInt(shift - 1);
499 if (rest > half || (rest === half && (top & 1n) === 1n)) top += 1n;
500 x = Number(top) * 2 ** shift; // M:i2f32
501 }
502 return f32bits(neg ? -x : x);
503}
504
505function castValue(dt, st, v) {
506 if (isInt(st) && isInt(dt)) {
507 if (v < intMin(dt) || v > intMax(dt)) trap(5); // M:cast5
508 return v;
509 }
510 if (isFloat(st) && isInt(dt)) {
511 const x = fval(st, v);
512 if (Number.isNaN(x)) return 0n; // M:satnan
513 if (x === Infinity) return intMax(dt);
514 if (x === -Infinity) return intMin(dt);
515 const t = BigInt(Math.trunc(x));
516 if (t < intMin(dt)) return intMin(dt); // M:satlow
517 if (t > intMax(dt)) return intMax(dt); // M:sathigh
518 return t;
519 }
520 if (isInt(st) && isFloat(dt)) return dt === T_F32 ? bigToF32Bits(v) : f64bits(Number(v));
521 if (st === dt) return v;
522 return fbits(dt, fval(st, v));
523}
524
525function bitcastValue(dt, st, v) {
526 let bits;
527 if (isFloat(st)) bits = v;
528 else bits = BigInt.asUintN(intWidth(st), v);
529 if (isFloat(dt)) return bits;
530 return isSigned(dt) ? BigInt.asIntN(intWidth(dt), bits) : bits; // M:bcsign
531}
532
533function binInt(t, sub, a, b, tb) {
534 const w = intWidth(t);
535 switch (sub) {
536 case 1: return checked(t, a + b);
537 case 2: return checked(t, a - b);
538 case 3: return checked(t, a * b);
539 case 4:
540 if (b === 0n) trap(2);
541 return checked(t, a / b);
542 case 5:
543 if (b === 0n) trap(2);
544 return a % b;
545 case 6: return a & b;
546 case 7: return a | b;
547 case 8: return a ^ b;
548 case 9:
549 if (b < 0n || b >= BigInt(w)) trap(7);
550 return isSigned(t) ? checked(t, a << b) : BigInt.asUintN(w, a << b);
551 case 10:
552 if (b < 0n || b >= BigInt(w)) trap(7);
553 return a >> b;
554 }
555 throw new Error('unreachable BIN ' + sub + ' ' + tb);
556}
557
558function binFloat(t, sub, a, b) {
559 const x = fval(t, a), y = fval(t, b);
560 const r = sub === 1 ? x + y : sub === 2 ? x - y : sub === 3 ? x * y : x / y;
561 return fbits(t, r);
562}
563
564function cmpValues(sub, x, y) {
565 switch (sub) {
566 case 1: return x === y;
567 case 2: return !(x === y);
568 case 3: return x < y;
569 case 4: return x <= y;
570 case 5: return x > y;
571 case 6: return x >= y;
572 }
573 return false;
574}
575
576class Region {
577 constructor(rg) {
578 this.rg = rg;
579 this.w = elemBytes(rg.tag);
580 this.mem = new Uint8Array(rg.count * this.w);
581 if (rg.cls === 2) this.mem.set(rg.init);
582 }
583 index(i) {
584 if (i < 0n || i >= BigInt(this.rg.count)) trap(3); // M:bounds
585 return Number(i) * this.w;
586 }
587 elemBits(v) { return isFloat(this.rg.tag) ? v : BigInt.asUintN(8 * this.w, v); }
588 load(i) {
589 const off = this.index(i);
590 let bits = 0n;
591 for (let k = this.w - 1; k >= 0; k--) bits = (bits << 8n) | BigInt(this.mem[off + k]);
592 const t = this.rg.tag;
593 if (isFloat(t)) return bits;
594 return isSigned(t) ? BigInt.asIntN(8 * this.w, bits) : bits;
595 }
596 writeAt(off, bits) {
597 for (let k = 0; k < this.w; k++) { this.mem[off + k] = Number(bits & 0xffn); bits >>= 8n; }
598 }
599 store(i, v) { this.writeAt(this.index(i), this.elemBits(v)); }
600 fill(v) {
601 this.writeAt(0, this.elemBits(v));
602 for (let have = this.w; have < this.mem.length; have *= 2) {
603 this.mem.copyWithin(have, 0, Math.min(have, this.mem.length - have));
604 }
605 }
606 hex() { return Buffer.from(this.mem).toString('hex'); }
607}
608
609class Instance {
610 constructor(u) {
611 this.u = u;
612 this.steps = 0;
613 this.module = u.regions.map((rg) => (rg.cls === 1 ? null : new Region(rg)));
614 }
615 call(fi, args) {
616 const u = this.u, f = u.funcs[fi];
617 const regs = new Array(f.nvregs).fill(0n);
618 for (let k = 0; k < args.length; k++) regs[k] = args[k];
619 // Fresh local storage on every invocation (spec 10.1 class 1).
620 const local = u.regions.map((rg) => (rg.cls === 1 && rg.owner === fi ? new Region(rg) : null));
621 const reg = (g) => this.module[g] || local[g];
622 let b = 0;
623 for (;;) {
624 const blk = f.blocks[b];
625 let nextBlock = -1;
626 for (let j = blk.first; j < blk.first + blk.count; j++) {
627 if (++this.steps > STEP_LIMIT) throw new Error('step limit ' + STEP_LIMIT + ' exceeded');
628 const ins = f.insns[j];
629 const T = (r) => f.vtype[r];
630 switch (ins.op) {
631 case OP.CONST: regs[ins.dst] = isSigned(T(ins.dst)) ? BigInt.asIntN(intWidth(T(ins.dst)), ins.imm) : ins.imm; break;
632 case OP.MOV: regs[ins.dst] = regs[ins.a]; break;
633 case OP.BIN: {
634 const t = T(ins.dst);
635 if (isFloat(t)) regs[ins.dst] = binFloat(t, ins.sub, regs[ins.a], regs[ins.b]);
636 else regs[ins.dst] = binInt(t, ins.sub, regs[ins.a], regs[ins.b], T(ins.b));
637 break;
638 }
639 case OP.UN: {
640 const t = T(ins.dst), a = regs[ins.a];
641 if (ins.sub === 1) {
642 if (t === T_F32) regs[ins.dst] = a ^ 0x80000000n; // M:fneg
643 else if (t === T_F64) regs[ins.dst] = a ^ 0x8000000000000000n;
644 else regs[ins.dst] = isSigned(t) ? checked(t, -a) : wrapInt(t, -a);
645 } else if (ins.sub === 2) regs[ins.dst] = wrapInt(t, ~a);
646 else regs[ins.dst] = 1n - a;
647 break;
648 }
649 case OP.CMP: {
650 const t = T(ins.a);
651 const x = isFloat(t) ? fval(t, regs[ins.a]) : regs[ins.a];
652 const y = isFloat(t) ? fval(t, regs[ins.b]) : regs[ins.b];
653 regs[ins.dst] = cmpValues(ins.sub, x, y) ? 1n : 0n;
654 break;
655 }
656 case OP.CAST: regs[ins.dst] = castValue(T(ins.dst), T(ins.a), regs[ins.a]); break;
657 case OP.CALL: {
658 const r = this.call(ins.callee, ins.args.map((a) => regs[a]));
659 if (ins.dst !== NONE) regs[ins.dst] = r;
660 break;
661 }
662 case OP.TRAP: trap(Number(ins.imm)); break;
663 case OP.BR: nextBlock = ins.blkT; break;
664 case OP.CBR: nextBlock = regs[ins.a] === 1n ? ins.blkT : ins.blkF; break;
665 case OP.RET: return ins.a === NONE ? null : regs[ins.a];
666 case OP.RLOAD: regs[ins.dst] = reg(ins.rg).load(regs[ins.b]); break;
667 case OP.RSTORE: reg(ins.rg).store(regs[ins.b], regs[ins.c]); break;
668 case OP.BITCAST: regs[ins.dst] = bitcastValue(T(ins.dst), T(ins.a), regs[ins.a]); break;
669 case OP.RINIT: reg(ins.rg).fill(regs[ins.a]); break;
670 default: throw new Error('unreachable opcode ' + ins.op);
671 }
672 }
673 b = nextBlock;
674 }
675 }
676}
677
678// ------------------------------------------------------------------- CLI
679function usage(msg) {
680 process.stderr.write('oracle: ' + msg + '\n' +
681 'usage: oracle.js check UNIT\n oracle.js run [--codes] UNIT SCRIPT\n');
682 process.exit(2);
683}
684
685function readFile(p) {
686 try { return fs.readFileSync(p); } catch (e) { usage('cannot read ' + p + ': ' + e.code); }
687}
688
689function decodeOrRefusal(buf) {
690 try { return { unit: decode(buf) }; } catch (e) {
691 if (e instanceof Refusal) return { refusal: e };
692 throw e;
693 }
694}
695
696function parseArg(t, s) {
697 if (isFloat(t)) {
698 const digits = t === T_F32 ? 8 : 16;
699 if (!new RegExp('^0x[0-9a-fA-F]{' + digits + '}$').test(s)) return null;
700 return BigInt(s);
701 }
702 if (!/^-?[0-9]+$/.test(s)) return null;
703 const v = BigInt(s);
704 if (t === T_BOOL) return v === 0n || v === 1n ? v : null;
705 return v >= intMin(t) && v <= intMax(t) ? v : null;
706}
707
708function formatValue(t, v) {
709 if (t === T_VOID) return 'void';
710 if (t === T_F32) return '0x' + v.toString(16).padStart(8, '0');
711 if (t === T_F64) return '0x' + v.toString(16).padStart(16, '0');
712 return v.toString(10);
713}
714
715function main(argv) {
716 const codes = argv.includes('--codes');
717 const args = argv.filter((a) => a !== '--codes');
718 const cmd = args[0];
719 if (cmd === 'check' && args.length === 2 && !codes) {
720 const res = decodeOrRefusal(readFile(args[1]));
721 if (res.refusal) {
722 process.stdout.write('REFUSE ' + res.refusal.cls + ' ' + res.refusal.detail + '\n');
723 return 1;
724 }
725 process.stdout.write('ACCEPT v' + res.unit.version + '\n');
726 return 0;
727 }
728 if (cmd === 'run' && args.length === 3) {
729 const res = decodeOrRefusal(readFile(args[1]));
730 if (res.refusal) {
731 process.stderr.write('REFUSE ' + res.refusal.cls + ' ' + res.refusal.detail + '\n');
732 return 1;
733 }
734 const u = res.unit;
735 const script = readFile(args[2]).toString('utf8').split('\n');
736 const inst = new Instance(u);
737 const out = [];
738 const flush = () => { if (out.length) process.stdout.write(out.join('')); out.length = 0; };
739 for (let ln = 0; ln < script.length; ln++) {
740 const line = script[ln].trim();
741 if (line === '' || line.startsWith('#')) continue;
742 const w = line.split(/\s+/);
743 const bad = (m) => { flush(); usage('script line ' + (ln + 1) + ': ' + m); };
744 if (w[0] === 'call') {
745 const fi = u.funcs.findIndex((f) => f.name === w[1]);
746 if (fi < 0) bad('no function ' + w[1]);
747 const f = u.funcs[fi];
748 if (w.length - 2 !== f.nparams) bad('expected ' + f.nparams + ' arguments');
749 const vals = w.slice(2).map((s, k) => {
750 const v = parseArg(f.vtype[k], s);
751 if (v === null) bad('argument ' + s + ' does not fit tag ' + f.vtype[k]);
752 return v;
753 });
754 try {
755 const r = inst.call(fi, vals); // M:callsite
756 out.push(f.name + ' = ' + formatValue(f.ret, r) + '\n');
757 } catch (e) {
758 if (!(e instanceof Trap)) { flush(); process.stderr.write('oracle: ' + e.message + '\n'); return 3; }
759 out.push(f.name + ' TRAP' + (codes ? ' code=' + e.code : '') + '\n');
760 }
761 } else if (w[0] === 'region' && w.length === 2) {
762 const g = u.regions.findIndex((rg) => rg.cls !== 1 && rg.name === w[1]);
763 if (g < 0) bad('no module region ' + w[1]);
764 out.push('region ' + w[1] + ' ' + inst.module[g].hex() + '\n');
765 } else bad('unknown command ' + JSON.stringify(line));
766 }
767 flush();
768 return 0;
769 }
770 usage('bad arguments');
771}
772
773process.exitCode = main(process.argv.slice(2));