polycomp 0.0.0-stage → 0.3.0
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.
- package/Cargo.toml +25 -0
- package/bin/native/polycomp.exe +0 -0
- package/bin/polycomp.js +25 -0
- package/js/frontend.js +1061 -0
- package/js/index.cjs +245 -0
- package/js/index.d.ts +2 -0
- package/js/index.mjs +19 -0
- package/js/polycomp-vm.mjs +1047 -0
- package/package.json +41 -5
- package/src/ast.rs +329 -0
- package/src/bundle.rs +3307 -0
- package/src/diagnostics.rs +276 -0
- package/src/interpreter.rs +1565 -0
- package/src/ir.rs +272 -0
- package/src/jit.rs +1151 -0
- package/src/lib.rs +11 -0
- package/src/lowering.rs +1157 -0
- package/src/main.rs +655 -0
- package/src/optimizer.rs +660 -0
- package/src/parser.rs +4755 -0
- package/src/resolver.rs +722 -0
- package/src/runtime.rs +1104 -0
- package/README.md +0 -3
|
@@ -0,0 +1,1047 @@
|
|
|
1
|
+
// PolyComp Pure-JS Frontend VM & Cryptographic Verifier (Zero Dependencies)
|
|
2
|
+
// Works identically in Chrome/Firefox/Safari, React/Vite/Next.js, Deno, Bun, Workers, and Node.js.
|
|
3
|
+
|
|
4
|
+
const textEncoder = new TextEncoder();
|
|
5
|
+
const textDecoder = new TextDecoder();
|
|
6
|
+
const M64 = 0xffffffffffffffffn;
|
|
7
|
+
|
|
8
|
+
const B64_INV = new Int16Array(256).fill(-1);
|
|
9
|
+
{
|
|
10
|
+
const alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
11
|
+
for (let i = 0; i < alpha.length; i++) B64_INV[alpha.charCodeAt(i)] = i;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function base64Decode(str) {
|
|
15
|
+
const bytes = [];
|
|
16
|
+
for (let i = 0; i < str.length; i++) {
|
|
17
|
+
const c = str.charCodeAt(i);
|
|
18
|
+
if (c === 10 || c === 13 || c === 32 || c === 9) continue;
|
|
19
|
+
bytes.push(c);
|
|
20
|
+
}
|
|
21
|
+
if (bytes.length === 0 || bytes.length % 4 !== 0) {
|
|
22
|
+
throw new Error("E0707: invalid base64 payload length");
|
|
23
|
+
}
|
|
24
|
+
const pad = (bytes[bytes.length - 1] === 61 ? 1 : 0) + (bytes[bytes.length - 2] === 61 ? 1 : 0);
|
|
25
|
+
const out = new Uint8Array((bytes.length / 4) * 3 - pad);
|
|
26
|
+
let oi = 0;
|
|
27
|
+
for (let i = 0; i < bytes.length; i += 4) {
|
|
28
|
+
const isLast = i + 4 === bytes.length;
|
|
29
|
+
const a = B64_INV[bytes[i]];
|
|
30
|
+
const b = B64_INV[bytes[i + 1]];
|
|
31
|
+
const padC = bytes[i + 2] === 61;
|
|
32
|
+
const padD = bytes[i + 3] === 61;
|
|
33
|
+
if ((padC || padD) && !isLast) throw new Error("E0707: invalid base64 padding");
|
|
34
|
+
if (padC && !padD) throw new Error("E0707: invalid base64 padding");
|
|
35
|
+
const c = padC ? 0 : B64_INV[bytes[i + 2]];
|
|
36
|
+
const d = padD ? 0 : B64_INV[bytes[i + 3]];
|
|
37
|
+
if (a < 0 || b < 0 || c < 0 || d < 0) throw new Error("E0707: invalid base64 char");
|
|
38
|
+
const t = (a << 18) | (b << 12) | (c << 6) | d;
|
|
39
|
+
out[oi++] = (t >>> 16) & 0xff;
|
|
40
|
+
if (!padC) out[oi++] = (t >>> 8) & 0xff;
|
|
41
|
+
if (!padD) out[oi++] = t & 0xff;
|
|
42
|
+
}
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function decodeHexExact(hex, byteLen) {
|
|
47
|
+
const clean = hex.trim();
|
|
48
|
+
if (clean.length !== byteLen * 2) return null;
|
|
49
|
+
const out = new Uint8Array(byteLen);
|
|
50
|
+
for (let i = 0; i < byteLen; i++) {
|
|
51
|
+
const hi = parseInt(clean[i * 2], 16);
|
|
52
|
+
const lo = parseInt(clean[i * 2 + 1], 16);
|
|
53
|
+
if (Number.isNaN(hi) || Number.isNaN(lo)) return null;
|
|
54
|
+
out[i] = (hi << 4) | lo;
|
|
55
|
+
}
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function bytesToHex(bytes) {
|
|
60
|
+
let s = "";
|
|
61
|
+
for (let i = 0; i < bytes.length; i++) s += bytes[i].toString(16).padStart(2, "0");
|
|
62
|
+
return s;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// --- SHA-512 & Ed25519 verify_strict ---
|
|
66
|
+
const SHA512_K = [
|
|
67
|
+
0x428a2f98d728ae22n,0x7137449123ef65cdn,0xb5c0fbcfec4d3b2fn,0xe9b5dba58189dbbcn,
|
|
68
|
+
0x3956c25bf348b538n,0x59f111f1b605d019n,0x923f82a4af194f9bn,0xab1c5ed5da6d8118n,
|
|
69
|
+
0xd807aa98a3030242n,0x12835b0145706fben,0x243185be4ee4b28cn,0x550c7dc3d5ffb4e2n,
|
|
70
|
+
0x72be5d74f27b896fn,0x80deb1fe3b1696b1n,0x9bdc06a725c71235n,0xc19bf174cf692694n,
|
|
71
|
+
0xe49b69c19ef14ad2n,0xefbe4786384f25e3n,0x0fc19dc68b8cd5b5n,0x240ca1cc77ac9c65n,
|
|
72
|
+
0x2de92c6f592b0275n,0x4a7484aa6ea6e483n,0x5cb0a9dcbd41fbd4n,0x76f988da831153b5n,
|
|
73
|
+
0x983e5152ee66dfabn,0xa831c66d2db43210n,0xb00327c898fb213fn,0xbf597fc7beef0ee4n,
|
|
74
|
+
0xc6e00bf33da88fc2n,0xd5a79147930aa725n,0x06ca6351e003826fn,0x142929670a0e6e70n,
|
|
75
|
+
0x27b70a8546d22ffcn,0x2e1b21385c26c926n,0x4d2c6dfc5ac42aedn,0x53380d139d95b3dfn,
|
|
76
|
+
0x650a73548baf63den,0x766a0abb3c77b2a8n,0x81c2c92e47edaee6n,0x92722c851482353bn,
|
|
77
|
+
0xa2bfe8a14cf10364n,0xa81a664bbc423001n,0xc24b8b70d0f89791n,0xc76c51a30654be30n,
|
|
78
|
+
0xd192e819d6ef5218n,0xd69906245565a910n,0xf40e35855771202an,0x106aa07032bbd1b8n,
|
|
79
|
+
0x19a4c116b8d2d0c8n,0x1e376c085141ab53n,0x2748774cdf8eeb99n,0x34b0bcb5e19b48a8n,
|
|
80
|
+
0x391c0cb3c5c95a63n,0x4ed8aa4ae3418acbn,0x5b9cca4f7763e373n,0x682e6ff3d6b2b8a3n,
|
|
81
|
+
0x748f82ee5defb2fcn,0x78a5636f43172f60n,0x84c87814a1f0ab72n,0x8cc702081a6439ecn,
|
|
82
|
+
0x90befffa23631e28n,0xa4506cebde82bde9n,0xbef9a3f7b2c67915n,0xc67178f2e372532bn,
|
|
83
|
+
0xca273eceea26619cn,0xd186b8c721c0c207n,0xeada7dd6cde0eb1en,0xf57d4f7fee6ed178n,
|
|
84
|
+
0x06f067aa72176fban,0x0a637dc5a2c898a6n,0x113f9804bef90daen,0x1b710b35131c471bn,
|
|
85
|
+
0x28db77f523047d84n,0x32caab7b40c72493n,0x3c9ebe0a15c9bebcn,0x431d67c49c100d4cn,
|
|
86
|
+
0x4cc5d4becb3e42b6n,0x597f299cfc657e2an,0x5fcb6fab3ad6faecn,0x6c44198c4a475817n,
|
|
87
|
+
];
|
|
88
|
+
const rotr64 = (x, n) => ((x >> BigInt(n)) | (x << BigInt(64 - n))) & M64;
|
|
89
|
+
function sha512(msg) {
|
|
90
|
+
const bitLen = BigInt(msg.length) * 8n;
|
|
91
|
+
const padLen = (112 - ((msg.length + 1) % 128) + 128) % 128;
|
|
92
|
+
const buf = new Uint8Array(msg.length + 1 + padLen + 16);
|
|
93
|
+
buf.set(msg);
|
|
94
|
+
buf[msg.length] = 0x80;
|
|
95
|
+
const dv = new DataView(buf.buffer);
|
|
96
|
+
dv.setBigUint64(buf.length - 16, bitLen >> 64n, false);
|
|
97
|
+
dv.setBigUint64(buf.length - 8, bitLen & M64, false);
|
|
98
|
+
const H = [
|
|
99
|
+
0x6a09e667f3bcc908n,0xbb67ae8584caa73bn,0x3c6ef372fe94f82bn,0xa54ff53a5f1d36f1n,
|
|
100
|
+
0x510e527fade682d1n,0x9b05688c2b3e6c1fn,0x1f83d9abfb41bd6bn,0x5be0cd19137e2179n,
|
|
101
|
+
];
|
|
102
|
+
const W = new Array(80);
|
|
103
|
+
for (let off = 0; off < buf.length; off += 128) {
|
|
104
|
+
for (let i = 0; i < 16; i++) W[i] = dv.getBigUint64(off + i * 8, false);
|
|
105
|
+
for (let i = 16; i < 80; i++) {
|
|
106
|
+
const s0 = rotr64(W[i - 15], 1) ^ rotr64(W[i - 15], 8) ^ (W[i - 15] >> 7n);
|
|
107
|
+
const s1 = rotr64(W[i - 2], 19) ^ rotr64(W[i - 2], 61) ^ (W[i - 2] >> 6n);
|
|
108
|
+
W[i] = (W[i - 16] + s0 + W[i - 7] + s1) & M64;
|
|
109
|
+
}
|
|
110
|
+
let [a, b, c, d, e, f, g, h] = H;
|
|
111
|
+
for (let i = 0; i < 80; i++) {
|
|
112
|
+
const S1 = rotr64(e, 14) ^ rotr64(e, 18) ^ rotr64(e, 41);
|
|
113
|
+
const ch = (e & f) ^ ((~e & M64) & g);
|
|
114
|
+
const t1 = (h + S1 + ch + SHA512_K[i] + W[i]) & M64;
|
|
115
|
+
const S0 = rotr64(a, 28) ^ rotr64(a, 34) ^ rotr64(a, 39);
|
|
116
|
+
const maj = (a & b) ^ (a & c) ^ (b & c);
|
|
117
|
+
const t2 = (S0 + maj) & M64;
|
|
118
|
+
h = g; g = f; f = e; e = (d + t1) & M64;
|
|
119
|
+
d = c; c = b; b = a; a = (t1 + t2) & M64;
|
|
120
|
+
}
|
|
121
|
+
H[0]=(H[0]+a)&M64; H[1]=(H[1]+b)&M64; H[2]=(H[2]+c)&M64; H[3]=(H[3]+d)&M64;
|
|
122
|
+
H[4]=(H[4]+e)&M64; H[5]=(H[5]+f)&M64; H[6]=(H[6]+g)&M64; H[7]=(H[7]+h)&M64;
|
|
123
|
+
}
|
|
124
|
+
const out = new Uint8Array(64);
|
|
125
|
+
const odv = new DataView(out.buffer);
|
|
126
|
+
for (let i = 0; i < 8; i++) odv.setBigUint64(i * 8, H[i], false);
|
|
127
|
+
return out;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const ED_P = (1n << 255n) - 19n;
|
|
131
|
+
const ED_L = (1n << 252n) + 27742317777372353535851937790883648493n;
|
|
132
|
+
const mod = (a, m) => { const r = a % m; return r >= 0n ? r : r + m; };
|
|
133
|
+
function powMod(base, exp, m) {
|
|
134
|
+
let res = 1n, b = mod(base, m), e = exp;
|
|
135
|
+
while (e > 0n) { if (e & 1n) res = (res * b) % m; b = (b * b) % m; e >>= 1n; }
|
|
136
|
+
return res;
|
|
137
|
+
}
|
|
138
|
+
const invP = (x) => powMod(x, ED_P - 2n, ED_P);
|
|
139
|
+
const ED_D = mod(-121665n * invP(121666n), ED_P);
|
|
140
|
+
const ED_I = powMod(2n, (ED_P - 1n) / 4n, ED_P);
|
|
141
|
+
const ED_BY = mod(4n * invP(5n), ED_P);
|
|
142
|
+
const ED_BX = (() => {
|
|
143
|
+
const yy = (ED_BY * ED_BY) % ED_P;
|
|
144
|
+
const xx = mod((yy - 1n) * invP(ED_D * yy + 1n), ED_P);
|
|
145
|
+
let x = powMod(xx, (ED_P + 3n) / 8n, ED_P);
|
|
146
|
+
if (mod(x * x - xx, ED_P) !== 0n) x = (x * ED_I) % ED_P;
|
|
147
|
+
if ((x & 1n) !== 0n) x = ED_P - x;
|
|
148
|
+
return x;
|
|
149
|
+
})();
|
|
150
|
+
const ED_B = [ED_BX, ED_BY, 1n, (ED_BX * ED_BY) % ED_P];
|
|
151
|
+
const ED_ZERO = [0n, 1n, 1n, 0n];
|
|
152
|
+
|
|
153
|
+
function leBytesToBigInt(bytes) {
|
|
154
|
+
let n = 0n;
|
|
155
|
+
for (let i = bytes.length - 1; i >= 0; i--) n = (n << 8n) | BigInt(bytes[i]);
|
|
156
|
+
return n;
|
|
157
|
+
}
|
|
158
|
+
function ptAdd([X1, Y1, Z1, T1], [X2, Y2, Z2, T2]) {
|
|
159
|
+
const A = mod((Y1 - X1) * (Y2 - X2), ED_P);
|
|
160
|
+
const B = mod((Y1 + X1) * (Y2 + X2), ED_P);
|
|
161
|
+
const C = mod(2n * ED_D * T1 * T2, ED_P);
|
|
162
|
+
const D = mod(2n * Z1 * Z2, ED_P);
|
|
163
|
+
const E = mod(B - A, ED_P);
|
|
164
|
+
const F = mod(D - C, ED_P);
|
|
165
|
+
const G = mod(D + C, ED_P);
|
|
166
|
+
const H = mod(B + A, ED_P);
|
|
167
|
+
return [mod(E * F, ED_P), mod(G * H, ED_P), mod(F * G, ED_P), mod(E * H, ED_P)];
|
|
168
|
+
}
|
|
169
|
+
function ptMul(pt, scalar) {
|
|
170
|
+
let res = ED_ZERO, cur = pt, k = scalar;
|
|
171
|
+
while (k > 0n) { if (k & 1n) res = ptAdd(res, cur); cur = ptAdd(cur, cur); k >>= 1n; }
|
|
172
|
+
return res;
|
|
173
|
+
}
|
|
174
|
+
function ptEq([X1, Y1, Z1], [X2, Y2, Z2]) {
|
|
175
|
+
return mod(X1 * Z2 - X2 * Z1, ED_P) === 0n && mod(Y1 * Z2 - Y2 * Z1, ED_P) === 0n;
|
|
176
|
+
}
|
|
177
|
+
function decompressPt(bytes32) {
|
|
178
|
+
const copy = new Uint8Array(bytes32);
|
|
179
|
+
const sign = (copy[31] >> 7) & 1;
|
|
180
|
+
copy[31] &= 0x7f;
|
|
181
|
+
const y = leBytesToBigInt(copy);
|
|
182
|
+
if (y >= ED_P) return null;
|
|
183
|
+
const yy = (y * y) % ED_P;
|
|
184
|
+
const u = mod(yy - 1n, ED_P);
|
|
185
|
+
const v = mod(ED_D * yy + 1n, ED_P);
|
|
186
|
+
if (v === 0n) return null;
|
|
187
|
+
const uv3 = mod(u * powMod(v, 3n, ED_P), ED_P);
|
|
188
|
+
const uv7 = mod(u * powMod(v, 7n, ED_P), ED_P);
|
|
189
|
+
let x = mod(uv3 * powMod(uv7, (ED_P - 5n) / 8n, ED_P), ED_P);
|
|
190
|
+
const vx2 = mod(v * x * x, ED_P);
|
|
191
|
+
if (vx2 !== u) {
|
|
192
|
+
if (vx2 === mod(-u, ED_P)) x = (x * ED_I) % ED_P;
|
|
193
|
+
else return null;
|
|
194
|
+
}
|
|
195
|
+
if (x === 0n && sign === 1) return null;
|
|
196
|
+
if (Number(x & 1n) !== sign) x = ED_P - x;
|
|
197
|
+
return [x, y, 1n, (x * y) % ED_P];
|
|
198
|
+
}
|
|
199
|
+
function ed25519VerifyStrict(pubBytes, msg, sigBytes) {
|
|
200
|
+
if (pubBytes.length !== 32 || sigBytes.length !== 64) return false;
|
|
201
|
+
const A = decompressPt(pubBytes);
|
|
202
|
+
if (!A || ptEq(ptMul(A, 8n), ED_ZERO)) return false;
|
|
203
|
+
const Rbytes = sigBytes.subarray(0, 32);
|
|
204
|
+
const S = leBytesToBigInt(sigBytes.subarray(32, 64));
|
|
205
|
+
if (S >= ED_L) return false;
|
|
206
|
+
const R = decompressPt(Rbytes);
|
|
207
|
+
if (!R) return false;
|
|
208
|
+
const hInput = new Uint8Array(64 + msg.length);
|
|
209
|
+
hInput.set(Rbytes, 0); hInput.set(pubBytes, 32); hInput.set(msg, 64);
|
|
210
|
+
const h = mod(leBytesToBigInt(sha512(hInput)), ED_L);
|
|
211
|
+
return ptEq(ptMul(ED_B, S), ptAdd(R, ptMul(A, h)));
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// --- BLAKE3 + XChaCha20-Poly1305 ---
|
|
215
|
+
const B3_IV = new Uint32Array([
|
|
216
|
+
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
|
|
217
|
+
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
|
|
218
|
+
]);
|
|
219
|
+
const B3_PERM = [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8];
|
|
220
|
+
const rotr32 = (x, n) => ((x >>> n) | (x << (32 - n))) >>> 0;
|
|
221
|
+
const rotl32 = (x, n) => ((x << n) | (x >>> (32 - n))) >>> 0;
|
|
222
|
+
|
|
223
|
+
function b3G(s, a, b, c, d, mx, my) {
|
|
224
|
+
s[a] = (s[a] + s[b] + mx) >>> 0; s[d] = rotr32(s[d] ^ s[a], 16);
|
|
225
|
+
s[c] = (s[c] + s[d]) >>> 0; s[b] = rotr32(s[b] ^ s[c], 12);
|
|
226
|
+
s[a] = (s[a] + s[b] + my) >>> 0; s[d] = rotr32(s[d] ^ s[a], 8);
|
|
227
|
+
s[c] = (s[c] + s[d]) >>> 0; s[b] = rotr32(s[b] ^ s[c], 7);
|
|
228
|
+
}
|
|
229
|
+
function b3Compress(cv, blkBytes, ctr, blkLen, flags) {
|
|
230
|
+
const padded = new Uint8Array(64);
|
|
231
|
+
padded.set(blkBytes);
|
|
232
|
+
const dv = new DataView(padded.buffer);
|
|
233
|
+
let m = new Uint32Array(16);
|
|
234
|
+
for (let i = 0; i < 16; i++) m[i] = dv.getUint32(i * 4, true);
|
|
235
|
+
const s = new Uint32Array(16);
|
|
236
|
+
for (let i = 0; i < 8; i++) s[i] = cv[i];
|
|
237
|
+
s[8] = B3_IV[0]; s[9] = B3_IV[1]; s[10] = B3_IV[2]; s[11] = B3_IV[3];
|
|
238
|
+
s[12] = ctr >>> 0; s[13] = Math.floor(ctr / 0x100000000) >>> 0;
|
|
239
|
+
s[14] = blkLen >>> 0; s[15] = flags >>> 0;
|
|
240
|
+
for (let r = 0; r < 7; r++) {
|
|
241
|
+
b3G(s,0,4,8,12,m[0],m[1]); b3G(s,1,5,9,13,m[2],m[3]); b3G(s,2,6,10,14,m[4],m[5]); b3G(s,3,7,11,15,m[6],m[7]);
|
|
242
|
+
b3G(s,0,5,10,15,m[8],m[9]); b3G(s,1,6,11,12,m[10],m[11]); b3G(s,2,7,8,13,m[12],m[13]); b3G(s,3,4,9,14,m[14],m[15]);
|
|
243
|
+
const nm = new Uint32Array(16);
|
|
244
|
+
for (let i = 0; i < 16; i++) nm[i] = m[B3_PERM[i]];
|
|
245
|
+
m = nm;
|
|
246
|
+
}
|
|
247
|
+
for (let i = 0; i < 8; i++) { s[i] ^= s[i + 8]; s[i + 8] ^= cv[i]; }
|
|
248
|
+
return s;
|
|
249
|
+
}
|
|
250
|
+
function b3HashInternal(data, keyWords, baseFlags, outLen) {
|
|
251
|
+
const cv = new Uint32Array(keyWords);
|
|
252
|
+
if (data.length === 0) {
|
|
253
|
+
const w = b3Compress(cv, new Uint8Array(0), 0, 0, baseFlags | 1 | 2 | 8);
|
|
254
|
+
return new Uint8Array(w.buffer).slice(0, outLen);
|
|
255
|
+
}
|
|
256
|
+
const numBlocks = Math.ceil(data.length / 64);
|
|
257
|
+
for (let i = 0; i < numBlocks; i++) {
|
|
258
|
+
const blk = data.subarray(i * 64, Math.min((i + 1) * 64, data.length));
|
|
259
|
+
let fl = baseFlags | (i === 0 ? 1 : 0);
|
|
260
|
+
if (i === numBlocks - 1) {
|
|
261
|
+
fl |= 2 | 8;
|
|
262
|
+
const out = new Uint8Array(outLen);
|
|
263
|
+
let pos = 0, ctr = 0;
|
|
264
|
+
while (pos < outLen) {
|
|
265
|
+
const w = b3Compress(cv, blk, ctr++, blk.length, fl);
|
|
266
|
+
const wb = new Uint8Array(w.buffer);
|
|
267
|
+
const take = Math.min(64, outLen - pos);
|
|
268
|
+
out.set(wb.subarray(0, take), pos);
|
|
269
|
+
pos += take;
|
|
270
|
+
}
|
|
271
|
+
return out;
|
|
272
|
+
} else {
|
|
273
|
+
const w = b3Compress(cv, blk, 0, blk.length, fl);
|
|
274
|
+
for (let k = 0; k < 8; k++) cv[k] = w[k];
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
function blake3DeriveKey(context, material, outLen = 32) {
|
|
279
|
+
const ctxBytes = textEncoder.encode(context);
|
|
280
|
+
const ctxHash = b3HashInternal(ctxBytes, B3_IV, 32, 32);
|
|
281
|
+
const ctxWords = new Uint32Array(ctxHash.buffer, ctxHash.byteOffset, 8);
|
|
282
|
+
return b3HashInternal(material, ctxWords, 64, outLen);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
const CHACHA_SIGMA = new Uint32Array([0x61707865, 0x3320646e, 0x79622d32, 0x6b206574]);
|
|
286
|
+
function chachaQR(s, a, b, c, d) {
|
|
287
|
+
s[a] = (s[a] + s[b]) >>> 0; s[d] = rotl32(s[d] ^ s[a], 16);
|
|
288
|
+
s[c] = (s[c] + s[d]) >>> 0; s[b] = rotl32(s[b] ^ s[c], 12);
|
|
289
|
+
s[a] = (s[a] + s[b]) >>> 0; s[d] = rotl32(s[d] ^ s[a], 8);
|
|
290
|
+
s[c] = (s[c] + s[d]) >>> 0; s[b] = rotl32(s[b] ^ s[c], 7);
|
|
291
|
+
}
|
|
292
|
+
function chachaPermute(s) {
|
|
293
|
+
for (let i = 0; i < 10; i++) {
|
|
294
|
+
chachaQR(s,0,4,8,12); chachaQR(s,1,5,9,13); chachaQR(s,2,6,10,14); chachaQR(s,3,7,11,15);
|
|
295
|
+
chachaQR(s,0,5,10,15); chachaQR(s,1,6,11,12); chachaQR(s,2,7,8,13); chachaQR(s,3,4,9,14);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
function chachaBlock(keyWords, counter, nonceWords) {
|
|
299
|
+
const init = new Uint32Array(16);
|
|
300
|
+
init.set(CHACHA_SIGMA, 0); init.set(keyWords, 4); init[12] = counter >>> 0; init.set(nonceWords, 13);
|
|
301
|
+
const s = new Uint32Array(init);
|
|
302
|
+
chachaPermute(s);
|
|
303
|
+
for (let i = 0; i < 16; i++) s[i] = (s[i] + init[i]) >>> 0;
|
|
304
|
+
return new Uint8Array(s.buffer);
|
|
305
|
+
}
|
|
306
|
+
function hchacha20(key32, nonce16) {
|
|
307
|
+
const kd = new DataView(key32.buffer, key32.byteOffset, 32);
|
|
308
|
+
const nd = new DataView(nonce16.buffer, nonce16.byteOffset, 16);
|
|
309
|
+
const s = new Uint32Array(16);
|
|
310
|
+
s.set(CHACHA_SIGMA, 0);
|
|
311
|
+
for (let i = 0; i < 8; i++) s[4 + i] = kd.getUint32(i * 4, true);
|
|
312
|
+
for (let i = 0; i < 4; i++) s[12 + i] = nd.getUint32(i * 4, true);
|
|
313
|
+
chachaPermute(s);
|
|
314
|
+
return new Uint32Array([s[0], s[1], s[2], s[3], s[12], s[13], s[14], s[15]]);
|
|
315
|
+
}
|
|
316
|
+
function poly1305Mac(otk32, aad, ct) {
|
|
317
|
+
const r = leBytesToBigInt(otk32.subarray(0, 16)) & 0x0ffffffc0ffffffc0ffffffc0fffffffn;
|
|
318
|
+
const s = leBytesToBigInt(otk32.subarray(16, 32));
|
|
319
|
+
const p = (1n << 130n) - 5n;
|
|
320
|
+
let acc = 0n;
|
|
321
|
+
const feedBlock = (blk) => {
|
|
322
|
+
const n = leBytesToBigInt(blk) | (1n << BigInt(blk.length * 8));
|
|
323
|
+
acc = ((acc + n) * r) % p;
|
|
324
|
+
};
|
|
325
|
+
const padFeed = (data) => {
|
|
326
|
+
for (let i = 0; i < data.length; i += 16) {
|
|
327
|
+
const slice = data.subarray(i, Math.min(i + 16, data.length));
|
|
328
|
+
if (slice.length === 16) feedBlock(slice);
|
|
329
|
+
else { const padded = new Uint8Array(16); padded.set(slice); feedBlock(padded); }
|
|
330
|
+
}
|
|
331
|
+
};
|
|
332
|
+
padFeed(aad); padFeed(ct);
|
|
333
|
+
const lens = new Uint8Array(16);
|
|
334
|
+
const ldv = new DataView(lens.buffer);
|
|
335
|
+
ldv.setBigUint64(0, BigInt(aad.length), true);
|
|
336
|
+
ldv.setBigUint64(8, BigInt(ct.length), true);
|
|
337
|
+
feedBlock(lens);
|
|
338
|
+
acc = (acc + s) & ((1n << 128n) - 1n);
|
|
339
|
+
const tag = new Uint8Array(16);
|
|
340
|
+
let t = acc;
|
|
341
|
+
for (let i = 0; i < 16; i++) { tag[i] = Number(t & 0xffn); t >>= 8n; }
|
|
342
|
+
return tag;
|
|
343
|
+
}
|
|
344
|
+
function xchacha20Poly1305Decrypt(key32, nonce24, aad, ctWithTag) {
|
|
345
|
+
if (ctWithTag.length < 16) throw new Error("E0714: truncated ciphertext");
|
|
346
|
+
const subkeyWords = hchacha20(key32, nonce24.subarray(0, 16));
|
|
347
|
+
const n12 = new Uint8Array(12);
|
|
348
|
+
n12.set(nonce24.subarray(16, 24), 4);
|
|
349
|
+
const n12dv = new DataView(n12.buffer);
|
|
350
|
+
const nWords = new Uint32Array([n12dv.getUint32(0, true), n12dv.getUint32(4, true), n12dv.getUint32(8, true)]);
|
|
351
|
+
const otk = chachaBlock(subkeyWords, 0, nWords).subarray(0, 32);
|
|
352
|
+
const ct = ctWithTag.subarray(0, ctWithTag.length - 16);
|
|
353
|
+
const tag = ctWithTag.subarray(ctWithTag.length - 16);
|
|
354
|
+
const expTag = poly1305Mac(otk, aad, ct);
|
|
355
|
+
let diff = 0;
|
|
356
|
+
for (let i = 0; i < 16; i++) diff |= tag[i] ^ expTag[i];
|
|
357
|
+
if (diff !== 0) throw new Error("E0714: Part 2 Decryption failed: wrong key or corrupted payload");
|
|
358
|
+
const out = new Uint8Array(ct.length);
|
|
359
|
+
for (let i = 0; i < ct.length; i += 64) {
|
|
360
|
+
const ks = chachaBlock(subkeyWords, 1 + Math.floor(i / 64), nWords);
|
|
361
|
+
const end = Math.min(i + 64, ct.length);
|
|
362
|
+
for (let j = i; j < end; j++) out[j] = ct[j] ^ ks[j - i];
|
|
363
|
+
}
|
|
364
|
+
return out;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// --- PolyComp Format Parsing & Unsealing ---
|
|
368
|
+
const VM_SEAL_MIX = new Uint8Array([
|
|
369
|
+
0xa4, 0x19, 0x7d, 0x52, 0xe0, 0x8c, 0x31, 0x6b, 0xf7, 0x42, 0x95, 0x0e, 0x83, 0xc6, 0x11, 0xda,
|
|
370
|
+
0x58, 0x07, 0xbe, 0x64, 0x2a, 0xd9, 0x4f, 0x73, 0x91, 0xe2, 0x3c, 0x85, 0x16, 0xab, 0x60, 0xf4,
|
|
371
|
+
]);
|
|
372
|
+
const VERIFY_DOMAIN = textEncoder.encode("POLYCOMP-IR-VERIFY-V3\0");
|
|
373
|
+
const ARMOR_BEGIN = "-----BEGIN POLYCOMP SECURE IR-----";
|
|
374
|
+
const ARMOR_END = "-----END POLYCOMP SECURE IR-----";
|
|
375
|
+
const PLAIN_BANNER = "; === POLYCOMP-IR-V3 ===";
|
|
376
|
+
const PLAIN_BEGIN_IR = "; --- BEGIN IR ---";
|
|
377
|
+
const PLAIN_END_IR = "; --- END IR ---";
|
|
378
|
+
|
|
379
|
+
const IR_TYPES = ["Dynamic", "Void", "Bool", "I64", "F64", "Str"];
|
|
380
|
+
const BINOPS = ["Add","Sub","Mul","Div","FloorDiv","Mod","Eq","Ne","Lt","Le","Gt","Ge","And","Or","BitAnd","BitOr","BitXor","Shl","Shr"];
|
|
381
|
+
const UNOPS = ["Neg","Not","BitNot","BitsToF64"];
|
|
382
|
+
const BUILTINS = ["Print","Println","Printf","Len","Str","Int","Float","Bool","Abs","Min","Max","Sqrt","Pow","Push","Pop","TypeOf","AllocBuf","ReadU8","WriteU8","BufLen","ClockMs","Assert"];
|
|
383
|
+
|
|
384
|
+
function concatBytes(...arrays) {
|
|
385
|
+
const total = arrays.reduce((s, a) => s + a.length, 0);
|
|
386
|
+
const out = new Uint8Array(total);
|
|
387
|
+
let off = 0;
|
|
388
|
+
for (const a of arrays) { out.set(a, off); off += a.length; }
|
|
389
|
+
return out;
|
|
390
|
+
}
|
|
391
|
+
function eqBytes(a, b) {
|
|
392
|
+
if (a.length !== b.length) return false;
|
|
393
|
+
let d = 0;
|
|
394
|
+
for (let i = 0; i < a.length; i++) d |= a[i] ^ b[i];
|
|
395
|
+
return d === 0;
|
|
396
|
+
}
|
|
397
|
+
function normalizeText(s) {
|
|
398
|
+
return (s.startsWith("\ufeff") ? s.slice(1) : s).replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
399
|
+
}
|
|
400
|
+
function computeOriginFingerprint(pubkey, flags, salt) {
|
|
401
|
+
return blake3DeriveKey("polycomp-origin-fingerprint-v3", concatBytes(pubkey, new Uint8Array([flags]), salt), 32);
|
|
402
|
+
}
|
|
403
|
+
function deriveVmSealedKey(salt, nonce, pubkey) {
|
|
404
|
+
const vdv = new DataView(VM_SEAL_MIX.buffer);
|
|
405
|
+
const pdv = new DataView(pubkey.buffer, pubkey.byteOffset, 32);
|
|
406
|
+
const sdv = new DataView(salt.buffer, salt.byteOffset, 16);
|
|
407
|
+
const ndv = new DataView(nonce.buffer, nonce.byteOffset, 24);
|
|
408
|
+
const state = [0n, 0n, 0n, 0n];
|
|
409
|
+
for (let i = 0; i < 4; i++) state[i] = vdv.getBigUint64(i * 8, true) ^ pdv.getBigUint64(i * 8, true);
|
|
410
|
+
state[0] ^= sdv.getBigUint64(0, true);
|
|
411
|
+
state[1] ^= (sdv.getBigUint64(8, true) + ndv.getBigUint64(0, true)) & M64;
|
|
412
|
+
state[2] ^= ndv.getBigUint64(8, true);
|
|
413
|
+
const n2 = ndv.getBigUint64(16, true);
|
|
414
|
+
state[3] ^= ((n2 << 17n) | (n2 >> 47n)) & M64;
|
|
415
|
+
for (let r = 0n; r < 16n; r++) {
|
|
416
|
+
state[0] = (state[0] + state[1] + ((r * 0x9e3779b97f4a7c15n) & M64)) & M64;
|
|
417
|
+
const x3 = state[3] ^ state[0];
|
|
418
|
+
state[3] = ((x3 << 23n) | (x3 >> 41n)) & M64;
|
|
419
|
+
state[2] = (state[2] + state[3]) & M64;
|
|
420
|
+
const x1 = state[1] ^ state[2];
|
|
421
|
+
state[1] = ((x1 << 13n) | (x1 >> 51n)) & M64;
|
|
422
|
+
state[0] = (state[0] * 0xbf58476d1ce4e5b9n) & M64;
|
|
423
|
+
state.push(state.shift());
|
|
424
|
+
}
|
|
425
|
+
const mixBytes = new Uint8Array(32);
|
|
426
|
+
const mdv = new DataView(mixBytes.buffer);
|
|
427
|
+
for (let i = 0; i < 4; i++) mdv.setBigUint64(i * 8, state[i], true);
|
|
428
|
+
return blake3DeriveKey("polycomp-v4-vm-sealed-stream", concatBytes(mixBytes, salt, nonce, pubkey), 32);
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
function parseArmoredPolyx(text) {
|
|
432
|
+
const trimmed = text.trim();
|
|
433
|
+
if (!trimmed.startsWith(ARMOR_BEGIN + "\n")) throw new Error("E0707: missing POLYX begin armor");
|
|
434
|
+
const afterBegin = trimmed.slice(ARMOR_BEGIN.length + 1);
|
|
435
|
+
const sep = afterBegin.indexOf("\n\n");
|
|
436
|
+
if (sep < 0) throw new Error("E0707: missing POLYX header separator");
|
|
437
|
+
const canonicalHeader = afterBegin.slice(0, sep);
|
|
438
|
+
const rest = afterBegin.slice(sep + 2);
|
|
439
|
+
const endToken = "\n" + ARMOR_END;
|
|
440
|
+
const endIdx = rest.indexOf(endToken);
|
|
441
|
+
if (endIdx < 0) throw new Error("E0707: missing POLYX end armor");
|
|
442
|
+
const b64Part = rest.slice(0, endIdx);
|
|
443
|
+
const tail = rest.slice(endIdx + endToken.length).trim();
|
|
444
|
+
if (!tail.startsWith("Signature:")) throw new Error("E0712: missing Signature line");
|
|
445
|
+
const sigBytes = decodeHexExact(tail.slice("Signature:".length), 64);
|
|
446
|
+
if (!sigBytes) throw new Error("E0712: malformed Ed25519 signature");
|
|
447
|
+
const hdr = {};
|
|
448
|
+
for (const line of canonicalHeader.split("\n")) {
|
|
449
|
+
const colon = line.indexOf(":");
|
|
450
|
+
if (colon < 0) throw new Error("E0707: malformed POLYX header line");
|
|
451
|
+
hdr[line.slice(0, colon).trim()] = line.slice(colon + 1).trim();
|
|
452
|
+
}
|
|
453
|
+
if (hdr.Format !== "POLYX003" || hdr.Version !== "3") throw new Error("E0708: unsupported POLYX format/version");
|
|
454
|
+
const obfuscated = hdr.Obfuscated === "true";
|
|
455
|
+
const pubkeyBytes = decodeHexExact(hdr.Signer || "", 32);
|
|
456
|
+
const originFp = decodeHexExact(hdr.Origin || "", 32);
|
|
457
|
+
const salt = decodeHexExact(hdr.Salt || "", 16);
|
|
458
|
+
const nonce = decodeHexExact(hdr.Nonce || "", 24);
|
|
459
|
+
if (!pubkeyBytes || !originFp || !salt || !nonce) throw new Error("E0707: missing POLYX header fields");
|
|
460
|
+
const ciphertext = base64Decode(b64Part);
|
|
461
|
+
const sigMsg = concatBytes(VERIFY_DOMAIN, textEncoder.encode(canonicalHeader), new Uint8Array([10, 10]), ciphertext);
|
|
462
|
+
return {
|
|
463
|
+
canonicalHeader, kdf: hdr.KDF, obfuscated, flags: 1 | (obfuscated ? 2 : 0),
|
|
464
|
+
pubkeyBytes, originFp, salt, nonce, ciphertext, sigBytes, sigMsg,
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
function deserializePermutedBytecode(data, salt, nonce) {
|
|
469
|
+
const sboxRand = blake3DeriveKey("polycomp-vm-opcode-sbox-v4", concatBytes(VM_SEAL_MIX, salt, nonce), 512);
|
|
470
|
+
const sdv = new DataView(sboxRand.buffer, sboxRand.byteOffset, 512);
|
|
471
|
+
const enc = Array.from({ length: 256 }, (_, i) => i);
|
|
472
|
+
for (let i = 255; i > 0; i--) {
|
|
473
|
+
const j = sdv.getUint16(i * 2, true) % (i + 1);
|
|
474
|
+
const tmp = enc[i]; enc[i] = enc[j]; enc[j] = tmp;
|
|
475
|
+
}
|
|
476
|
+
const dec = new Uint8Array(256);
|
|
477
|
+
for (let p = 0; p < 256; p++) dec[enc[p]] = p;
|
|
478
|
+
|
|
479
|
+
const initDigest = blake3DeriveKey("polycomp-vm-rolling-whitener-v4", concatBytes(VM_SEAL_MIX, salt, nonce), 8);
|
|
480
|
+
let streamState = new DataView(initDigest.buffer, initDigest.byteOffset, 8).getBigUint64(0, true);
|
|
481
|
+
function splitmixNext() {
|
|
482
|
+
streamState = (streamState + 0x9e3779b97f4a7c15n) & M64;
|
|
483
|
+
let z = streamState;
|
|
484
|
+
z = ((z ^ (z >> 30n)) * 0xbf58476d1ce4e5b9n) & M64;
|
|
485
|
+
z = ((z ^ (z >> 27n)) * 0x94d049bb133111ebn) & M64;
|
|
486
|
+
return (z ^ (z >> 31n)) & M64;
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
let pos = 0, strCtr = 0;
|
|
490
|
+
const dv = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
|
491
|
+
const take = (n) => {
|
|
492
|
+
if (pos + n > data.length) throw new Error("E0716: unexpected EOF in VM bytecode");
|
|
493
|
+
const s = data.subarray(pos, pos + n); pos += n; return s;
|
|
494
|
+
};
|
|
495
|
+
const op = () => dec[take(1)[0]];
|
|
496
|
+
const u8 = () => take(1)[0] ^ Number(splitmixNext() & 0xffn);
|
|
497
|
+
const u32 = () => { const raw = dv.getUint32(pos, true); pos += 4; return (raw ^ Number(splitmixNext() & 0xffffffffn)) >>> 0; };
|
|
498
|
+
const i64 = () => { const raw = dv.getBigUint64(pos, true); pos += 8; return BigInt.asIntN(64, raw ^ splitmixNext()); };
|
|
499
|
+
const f64 = () => {
|
|
500
|
+
const raw = dv.getBigUint64(pos, true); pos += 8;
|
|
501
|
+
const ab = new ArrayBuffer(8); const tdv = new DataView(ab);
|
|
502
|
+
tdv.setBigUint64(0, raw ^ splitmixNext(), true);
|
|
503
|
+
return tdv.getFloat64(0, true);
|
|
504
|
+
};
|
|
505
|
+
const rstr = () => {
|
|
506
|
+
const len = u32(), padLen = u8(); take(padLen);
|
|
507
|
+
const raw = take(len);
|
|
508
|
+
const ctrBytes = new Uint8Array(4); new DataView(ctrBytes.buffer).setUint32(0, strCtr++, true);
|
|
509
|
+
const mask = blake3DeriveKey("polycomp-str-mask-v4", concatBytes(VM_SEAL_MIX, salt, nonce, ctrBytes), len);
|
|
510
|
+
const out = new Uint8Array(len);
|
|
511
|
+
for (let i = 0; i < len; i++) out[i] = raw[i] ^ mask[i];
|
|
512
|
+
return textDecoder.decode(out);
|
|
513
|
+
};
|
|
514
|
+
const regList = () => Array.from({ length: u32() }, () => u32());
|
|
515
|
+
|
|
516
|
+
const headChaff = op(); take(headChaff);
|
|
517
|
+
const entryFn = u32(), entryName = rstr();
|
|
518
|
+
const initFns = Array.from({ length: u32() }, () => u32());
|
|
519
|
+
const exports = Array.from({ length: u32() }, () => [rstr(), u32()]);
|
|
520
|
+
const fnLen = u32(), functions = [];
|
|
521
|
+
for (let fi = 0; fi < fnLen; fi++) {
|
|
522
|
+
const id = u32(), moduleId = u32(), qualifiedName = rstr();
|
|
523
|
+
const params = Array.from({ length: u32() }, () => [u32(), IR_TYPES[op()]]);
|
|
524
|
+
const returnType = IR_TYPES[op()];
|
|
525
|
+
const registerTypes = Array.from({ length: u32() }, () => IR_TYPES[op()]);
|
|
526
|
+
const bbLen = u32(), blocks = [];
|
|
527
|
+
for (let bi = 0; bi < bbLen; bi++) {
|
|
528
|
+
const bbId = u32(), insLen = u32(), instructions = [];
|
|
529
|
+
for (let ii = 0; ii < insLen; ii++) {
|
|
530
|
+
const tag = op();
|
|
531
|
+
switch (tag) {
|
|
532
|
+
case 1: {
|
|
533
|
+
const dst = u32(), ck = op();
|
|
534
|
+
const c = ck === 0 ? { k: "nil", v: null } : ck === 1 ? { k: "bool", v: u8() !== 0 } : ck === 2 ? { k: "int", v: i64() } : ck === 3 ? { k: "float", v: f64() } : { k: "str", v: rstr() };
|
|
535
|
+
instructions.push({ op: "LoadConst", dst, c }); break;
|
|
536
|
+
}
|
|
537
|
+
case 2: instructions.push({ op: "Move", dst: u32(), src: u32() }); break;
|
|
538
|
+
case 3: instructions.push({ op: "Cast", dst: u32(), ty: IR_TYPES[op()], src: u32() }); break;
|
|
539
|
+
case 4: instructions.push({ op: "BinOp", bop: BINOPS[op()], dst: u32(), l: u32(), r: u32() }); break;
|
|
540
|
+
case 5: instructions.push({ op: "UnaryOp", uop: UNOPS[op()], dst: u32(), src: u32() }); break;
|
|
541
|
+
case 6: instructions.push({ op: "CallLazy", dst: u32(), site: u32(), args: regList() }); break;
|
|
542
|
+
case 7: instructions.push({ op: "CallFn", dst: u32(), fnId: u32(), args: regList() }); break;
|
|
543
|
+
case 8: instructions.push({ op: "CallIndirect", dst: u32(), fnReg: u32(), args: regList() }); break;
|
|
544
|
+
case 9: instructions.push({ op: "CallBuiltin", dst: u32(), builtin: BUILTINS[u32()], args: regList() }); break;
|
|
545
|
+
case 10: instructions.push({ op: "ResolveFn", dst: u32(), site: u32() }); break;
|
|
546
|
+
case 11: instructions.push({ op: "LoadFnRef", dst: u32(), fnId: u32() }); break;
|
|
547
|
+
case 12: { const has = op() !== 0; instructions.push({ op: "Return", reg: has ? u32() : null }); break; }
|
|
548
|
+
case 13: instructions.push({ op: "BranchIf", cond: u32(), t: u32(), f: u32() }); break;
|
|
549
|
+
case 14: instructions.push({ op: "Jump", t: u32() }); break;
|
|
550
|
+
case 15: instructions.push({ op: "CreateArray", dst: u32(), items: regList() }); break;
|
|
551
|
+
case 16: instructions.push({ op: "GetIndex", dst: u32(), obj: u32(), idx: u32() }); break;
|
|
552
|
+
case 17: instructions.push({ op: "SetIndex", obj: u32(), idx: u32(), val: u32() }); break;
|
|
553
|
+
case 18: instructions.push({ op: "CreateObject", dst: u32(), cname: rstr() }); break;
|
|
554
|
+
case 19: instructions.push({ op: "SetField", obj: u32(), field: rstr(), val: u32() }); break;
|
|
555
|
+
case 20: instructions.push({ op: "GetField", dst: u32(), obj: u32(), field: rstr() }); break;
|
|
556
|
+
case 21: instructions.push({ op: "AllocBuffer", dst: u32(), size: u32() }); break;
|
|
557
|
+
case 22: instructions.push({ op: "StoreByte", buf: u32(), off: u32(), val: u32() }); break;
|
|
558
|
+
case 23: instructions.push({ op: "LoadByte", dst: u32(), buf: u32(), off: u32() }); break;
|
|
559
|
+
default: throw new Error("E0716: unknown VM opcode " + tag);
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
blocks.push({ id: bbId, instructions });
|
|
563
|
+
}
|
|
564
|
+
functions.push({ id, moduleId, qualifiedName, params, returnType, registerTypes, blocks });
|
|
565
|
+
}
|
|
566
|
+
return { entryFn, entryName, initFns, exports, functions };
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
// --- Plain UTF-8 POLYIR03 Parser ---
|
|
570
|
+
function parseEscapedStr(s) {
|
|
571
|
+
let p = s.trimStart();
|
|
572
|
+
if (!p.startsWith('"')) throw new Error("E0716: expected quoted string");
|
|
573
|
+
let out = "", i = 1;
|
|
574
|
+
while (i < p.length) {
|
|
575
|
+
const ch = p[i];
|
|
576
|
+
if (ch === '"') return [out, p.slice(i + 1)];
|
|
577
|
+
if (ch === "\\") {
|
|
578
|
+
i++; const esc = p[i++];
|
|
579
|
+
if (esc === '"') out += '"';
|
|
580
|
+
else if (esc === "\\") out += "\\";
|
|
581
|
+
else if (esc === "n") out += "\n";
|
|
582
|
+
else if (esc === "r") out += "\r";
|
|
583
|
+
else if (esc === "t") out += "\t";
|
|
584
|
+
else if (esc === "0") out += "\0";
|
|
585
|
+
else if (esc === "u" && p[i] === "{") {
|
|
586
|
+
const end = p.indexOf("}", i + 1);
|
|
587
|
+
out += String.fromCodePoint(parseInt(p.slice(i + 1, end), 16));
|
|
588
|
+
i = end + 1;
|
|
589
|
+
} else throw new Error("E0716: invalid string escape");
|
|
590
|
+
} else { out += ch; i++; }
|
|
591
|
+
}
|
|
592
|
+
throw new Error("E0716: unterminated IR string");
|
|
593
|
+
}
|
|
594
|
+
function escapeStr(s) {
|
|
595
|
+
let out = '"';
|
|
596
|
+
for (const ch of s) {
|
|
597
|
+
const code = ch.codePointAt(0);
|
|
598
|
+
if (ch === '"') out += '\\"';
|
|
599
|
+
else if (ch === "\\") out += "\\\\";
|
|
600
|
+
else if (ch === "\n") out += "\\n";
|
|
601
|
+
else if (ch === "\r") out += "\\r";
|
|
602
|
+
else if (ch === "\t") out += "\\t";
|
|
603
|
+
else if (ch === "\0") out += "\\0";
|
|
604
|
+
else if (code < 0x20 || code === 0x7f) out += `\\u{${code.toString(16)}}`;
|
|
605
|
+
else out += ch;
|
|
606
|
+
}
|
|
607
|
+
return out + '"';
|
|
608
|
+
}
|
|
609
|
+
const splitWs = (s) => { const t = s.trimStart(); const idx = t.search(/\s/); return idx < 0 ? [t, ""] : [t.slice(0, idx), t.slice(idx).trimStart()]; };
|
|
610
|
+
const parseReg = (s) => parseInt(s.trim().replace(/^r/, ""), 10);
|
|
611
|
+
const parseBb = (s) => parseInt(s.trim().replace(/^bb/, ""), 10);
|
|
612
|
+
const parseHash = (s) => parseInt(s.trim().replace(/^#/, ""), 10);
|
|
613
|
+
const parseRegList = (s) => { const inner = s.trim().slice(1, -1).trim(); return inner ? inner.split(",").map(parseReg) : []; };
|
|
614
|
+
const parseIdList = (s) => { const inner = s.trim().slice(1, -1).trim(); return inner ? inner.split(",").map((x) => parseInt(x.trim(), 10)) : []; };
|
|
615
|
+
const parseExportsList = (s) => {
|
|
616
|
+
let p = s.trim().slice(1, -1).trim(); const out = [];
|
|
617
|
+
while (p.length > 0) {
|
|
618
|
+
const [name, rest] = parseEscapedStr(p);
|
|
619
|
+
const eq = rest.trimStart().slice(1).trimStart();
|
|
620
|
+
const m = /^(\d+)(.*)$/.exec(eq);
|
|
621
|
+
out.push([name, parseInt(m[1], 10)]);
|
|
622
|
+
p = m[2].trimStart();
|
|
623
|
+
if (p.startsWith(",")) p = p.slice(1).trimStart(); else break;
|
|
624
|
+
}
|
|
625
|
+
return out;
|
|
626
|
+
};
|
|
627
|
+
function parsePlainInstr(line) {
|
|
628
|
+
const sp = line.indexOf(" ");
|
|
629
|
+
const op = (sp < 0 ? line : line.slice(0, sp)).trim();
|
|
630
|
+
const rest = (sp < 0 ? "" : line.slice(sp + 1)).trim();
|
|
631
|
+
switch (op) {
|
|
632
|
+
case "load_const": {
|
|
633
|
+
const [dt, r1] = splitWs(rest); const dst = parseReg(dt); const [kind, valStr] = splitWs(r1);
|
|
634
|
+
let c;
|
|
635
|
+
if (kind === "nil") c = { k: "nil", v: null };
|
|
636
|
+
else if (kind === "bool") c = { k: "bool", v: valStr.trim() === "true" };
|
|
637
|
+
else if (kind === "int") c = { k: "int", v: BigInt(valStr.trim()) };
|
|
638
|
+
else if (kind === "float") c = { k: "float", v: parseFloat(valStr.trim()) };
|
|
639
|
+
else if (kind === "float_bits") { const ab = new ArrayBuffer(8); new DataView(ab).setBigUint64(0, BigInt(valStr.trim()), true); c = { k: "float", v: new DataView(ab).getFloat64(0, true) }; }
|
|
640
|
+
else if (kind === "str") c = { k: "str", v: parseEscapedStr(valStr)[0] };
|
|
641
|
+
else throw new Error("E0716: unknown constant " + kind);
|
|
642
|
+
return { op: "LoadConst", dst, c };
|
|
643
|
+
}
|
|
644
|
+
case "move": { const [a, b] = splitWs(rest); return { op: "Move", dst: parseReg(a), src: parseReg(b) }; }
|
|
645
|
+
case "cast": { const [d, r1] = splitWs(rest); const [ty, s] = splitWs(r1); return { op: "Cast", dst: parseReg(d), ty, src: parseReg(s) }; }
|
|
646
|
+
case "binop": { const [bop, r1] = splitWs(rest); const [d, r2] = splitWs(r1); const [l, r] = splitWs(r2); return { op: "BinOp", bop, dst: parseReg(d), l: parseReg(l), r: parseReg(r) }; }
|
|
647
|
+
case "unary": { const [uop, r1] = splitWs(rest); const [d, s] = splitWs(r1); return { op: "UnaryOp", uop, dst: parseReg(d), src: parseReg(s) }; }
|
|
648
|
+
case "call_fn": { const [d, r1] = splitWs(rest); const [id, args] = splitWs(r1); return { op: "CallFn", dst: parseReg(d), fnId: parseHash(id), args: parseRegList(args) }; }
|
|
649
|
+
case "call_indirect": { const [d, r1] = splitWs(rest); const [f, args] = splitWs(r1); return { op: "CallIndirect", dst: parseReg(d), fnReg: parseReg(f), args: parseRegList(args) }; }
|
|
650
|
+
case "call_builtin": { const [d, r1] = splitWs(rest); const [b, args] = splitWs(r1); return { op: "CallBuiltin", dst: parseReg(d), builtin: b, args: parseRegList(args) }; }
|
|
651
|
+
case "load_fn_ref": { const [d, id] = splitWs(rest); return { op: "LoadFnRef", dst: parseReg(d), fnId: parseHash(id) }; }
|
|
652
|
+
case "return": return { op: "Return", reg: rest ? parseReg(rest) : null };
|
|
653
|
+
case "branch_if": { const [c, r1] = splitWs(rest); const [t, f] = splitWs(r1); return { op: "BranchIf", cond: parseReg(c), t: parseBb(t), f: parseBb(f) }; }
|
|
654
|
+
case "jump": return { op: "Jump", t: parseBb(rest) };
|
|
655
|
+
case "create_array": { const [d, items] = splitWs(rest); return { op: "CreateArray", dst: parseReg(d), items: parseRegList(items) }; }
|
|
656
|
+
case "get_index": { const [d, r1] = splitWs(rest); const [o, i] = splitWs(r1); return { op: "GetIndex", dst: parseReg(d), obj: parseReg(o), idx: parseReg(i) }; }
|
|
657
|
+
case "set_index": { const [o, r1] = splitWs(rest); const [i, v] = splitWs(r1); return { op: "SetIndex", obj: parseReg(o), idx: parseReg(i), val: parseReg(v) }; }
|
|
658
|
+
case "create_object": { const [d, r1] = splitWs(rest); return { op: "CreateObject", dst: parseReg(d), cname: parseEscapedStr(r1)[0] }; }
|
|
659
|
+
case "set_field": { const [o, r1] = splitWs(rest); const [fn, r2] = parseEscapedStr(r1); return { op: "SetField", obj: parseReg(o), field: fn, val: parseReg(r2) }; }
|
|
660
|
+
case "get_field": { const [d, r1] = splitWs(rest); const [o, r2] = splitWs(r1); return { op: "GetField", dst: parseReg(d), obj: parseReg(o), field: parseEscapedStr(r2)[0] }; }
|
|
661
|
+
case "alloc_buf": { const [d, s] = splitWs(rest); return { op: "AllocBuffer", dst: parseReg(d), size: parseReg(s) }; }
|
|
662
|
+
case "store_byte": { const [b, r1] = splitWs(rest); const [o, v] = splitWs(r1); return { op: "StoreByte", buf: parseReg(b), off: parseReg(o), val: parseReg(v) }; }
|
|
663
|
+
case "load_byte": { const [d, r1] = splitWs(rest); const [b, o] = splitWs(r1); return { op: "LoadByte", dst: parseReg(d), buf: parseReg(b), off: parseReg(o) }; }
|
|
664
|
+
default: throw new Error("E0716: unknown plain IR op " + op);
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
function parsePlainIrText(norm) {
|
|
668
|
+
let hdrPart = "", irBody = norm;
|
|
669
|
+
const bi = norm.indexOf(PLAIN_BEGIN_IR);
|
|
670
|
+
if (bi >= 0) {
|
|
671
|
+
hdrPart = norm.slice(0, bi);
|
|
672
|
+
let rest = norm.slice(bi + PLAIN_BEGIN_IR.length);
|
|
673
|
+
if (rest.startsWith("\n")) rest = rest.slice(1);
|
|
674
|
+
const ei = rest.indexOf(PLAIN_END_IR);
|
|
675
|
+
irBody = ei >= 0 ? rest.slice(0, ei) : rest;
|
|
676
|
+
}
|
|
677
|
+
let entryFn = null, entryName = null, initFns = [], exports = [], saltHex = null, signerHex = null, originHex = null, sigHex = null;
|
|
678
|
+
for (const raw of hdrPart.split("\n")) {
|
|
679
|
+
const t = raw.trim();
|
|
680
|
+
if (!t.startsWith(";")) continue;
|
|
681
|
+
const c = t.slice(1).trim();
|
|
682
|
+
if (c.startsWith("entry:")) {
|
|
683
|
+
const v = c.slice(6).trim(); const sp = v.indexOf(" ");
|
|
684
|
+
entryFn = parseInt(v.slice(0, sp), 10); entryName = parseEscapedStr(v.slice(sp + 1))[0];
|
|
685
|
+
} else if (c.startsWith("inits:")) initFns = parseIdList(c.slice(6));
|
|
686
|
+
else if (c.startsWith("exports:")) exports = parseExportsList(c.slice(8));
|
|
687
|
+
else if (c.startsWith("salt:")) saltHex = c.slice(5).trim();
|
|
688
|
+
else if (c.startsWith("signer:")) signerHex = c.slice(7).trim();
|
|
689
|
+
else if (c.startsWith("origin:")) originHex = c.slice(7).trim();
|
|
690
|
+
else if (c.startsWith("signature:")) sigHex = c.slice(10).trim();
|
|
691
|
+
}
|
|
692
|
+
const lines = irBody.split("\n"), functions = [];
|
|
693
|
+
for (let i = 0; i < lines.length; ) {
|
|
694
|
+
const line = lines[i].trim();
|
|
695
|
+
if (!line || line.startsWith(";")) { i++; continue; }
|
|
696
|
+
const [fidTok, r1] = splitWs(line.slice(3));
|
|
697
|
+
const [qname, r2] = parseEscapedStr(r1);
|
|
698
|
+
const [modTok, r3] = splitWs(r2);
|
|
699
|
+
const [retTok, r4] = splitWs(r3);
|
|
700
|
+
const paramsRaw = r4.trim().replace(/^params=/, "").replace(/\{$/, "").trim();
|
|
701
|
+
const pInner = paramsRaw.slice(1, -1).trim();
|
|
702
|
+
const params = pInner ? pInner.split(",").map((p) => { const [rn, tn] = p.trim().split(":"); return [parseReg(rn), tn]; }) : [];
|
|
703
|
+
i++;
|
|
704
|
+
let registerTypes = [], blocks = [], curBb = null;
|
|
705
|
+
while (i < lines.length) {
|
|
706
|
+
const bl = lines[i++].trim();
|
|
707
|
+
if (!bl || bl.startsWith(";")) continue;
|
|
708
|
+
if (bl === "}") { if (curBb) blocks.push(curBb); break; }
|
|
709
|
+
if (bl.startsWith("regs:")) { const ri = bl.slice(5).trim().slice(1, -1).trim(); registerTypes = ri ? ri.split(",").map((x) => x.trim()) : []; continue; }
|
|
710
|
+
if (/^bb\d+:$/.test(bl)) { if (curBb) blocks.push(curBb); curBb = { id: parseInt(bl.slice(2, -1), 10), instructions: [] }; continue; }
|
|
711
|
+
curBb.instructions.push(parsePlainInstr(bl));
|
|
712
|
+
}
|
|
713
|
+
functions.push({ id: parseHash(fidTok), moduleId: parseInt(modTok.slice(4), 10), qualifiedName: qname, params, returnType: retTok.slice(4), registerTypes, blocks });
|
|
714
|
+
}
|
|
715
|
+
if (functions.length === 0) throw new Error("E0716: IR contains 0 functions");
|
|
716
|
+
const fEntry = entryFn ?? functions[0].id;
|
|
717
|
+
const fName = entryName ?? "main";
|
|
718
|
+
if (exports.length === 0) exports.push([fName, fEntry]);
|
|
719
|
+
return {
|
|
720
|
+
bundle: { entryFn: fEntry, entryName: fName, initFns, exports, functions },
|
|
721
|
+
irBody,
|
|
722
|
+
sig: (saltHex && signerHex && originHex && sigHex) ? { saltHex, signerHex, originHex, sigHex } : null,
|
|
723
|
+
};
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
// --- PolyComp JS Virtual Machine ---
|
|
727
|
+
const NIL = { t: "nil", v: null };
|
|
728
|
+
const VBool = (b) => ({ t: "bool", v: Boolean(b) });
|
|
729
|
+
const VInt = (i) => ({ t: "int", v: BigInt.asIntN(64, BigInt(i)) });
|
|
730
|
+
const VFloat = (f) => ({ t: "float", v: Number(f) });
|
|
731
|
+
const VStr = (s) => ({ t: "str", v: String(s) });
|
|
732
|
+
|
|
733
|
+
function isTruthy(val) {
|
|
734
|
+
switch (val.t) {
|
|
735
|
+
case "nil": return false;
|
|
736
|
+
case "bool": return val.v;
|
|
737
|
+
case "int": return val.v !== 0n;
|
|
738
|
+
case "float": return val.v !== 0 && !Number.isNaN(val.v);
|
|
739
|
+
case "str": return val.v.length > 0;
|
|
740
|
+
case "array": return val.v.length > 0;
|
|
741
|
+
default: return true;
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
function formatValue(val) {
|
|
745
|
+
switch (val.t) {
|
|
746
|
+
case "nil": return "nil";
|
|
747
|
+
case "bool": return String(val.v);
|
|
748
|
+
case "int": return val.v.toString();
|
|
749
|
+
case "float": return Number.isInteger(val.v) && Math.abs(val.v) < 1e15 ? val.v.toFixed(1) : String(val.v);
|
|
750
|
+
case "str": return val.v;
|
|
751
|
+
case "array": return `[${val.v.map(formatValue).join(", ")}]`;
|
|
752
|
+
case "object": {
|
|
753
|
+
const parts = [];
|
|
754
|
+
for (const [k, v] of val.fields.entries()) parts.push(`${k}: ${formatValue(v)}`);
|
|
755
|
+
return `${val.className} { ${parts.join(", ")} }`;
|
|
756
|
+
}
|
|
757
|
+
case "buffer": return `<buffer:${val.v.length}B>`;
|
|
758
|
+
case "fn": return `<fn#${val.v}>`;
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
function formatPrintf(fmt, args) {
|
|
762
|
+
let out = "", ai = 0;
|
|
763
|
+
for (let i = 0; i < fmt.length; i++) {
|
|
764
|
+
if (fmt[i] === "%") {
|
|
765
|
+
if (fmt[i + 1] === "%") { out += "%"; i++; continue; }
|
|
766
|
+
let spec = "", j = i + 1;
|
|
767
|
+
while (j < fmt.length) { spec += fmt[j]; if (/[a-zA-Z]/.test(fmt[j])) break; j++; }
|
|
768
|
+
i = j;
|
|
769
|
+
const val = args[ai++] ?? NIL;
|
|
770
|
+
if (spec.endsWith("f") || spec.endsWith("g")) {
|
|
771
|
+
const f = val.t === "float" ? val.v : val.t === "int" ? Number(val.v) : 0;
|
|
772
|
+
const m = /^\.(\d+)f$/.exec(spec);
|
|
773
|
+
out += m ? f.toFixed(parseInt(m[1], 10)) : String(f);
|
|
774
|
+
} else if (spec.endsWith("d") || spec.endsWith("i")) {
|
|
775
|
+
const iv = val.t === "int" ? val.v : val.t === "float" ? BigInt(Math.trunc(val.v)) : val.t === "bool" ? (val.v ? 1n : 0n) : 0n;
|
|
776
|
+
out += iv.toString();
|
|
777
|
+
} else out += formatValue(val);
|
|
778
|
+
} else out += fmt[i];
|
|
779
|
+
}
|
|
780
|
+
return out;
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
function runBundle(bundle, options = {}) {
|
|
784
|
+
const fnMap = new Map();
|
|
785
|
+
for (const f of bundle.functions) fnMap.set(f.id, f);
|
|
786
|
+
let stdout = "";
|
|
787
|
+
const emitOut = (txt) => {
|
|
788
|
+
stdout += txt;
|
|
789
|
+
if (options.onStdout) options.onStdout(txt);
|
|
790
|
+
else if (options.streamStdout && typeof console !== "undefined") console.log(txt.replace(/\n$/, ""));
|
|
791
|
+
};
|
|
792
|
+
let vmCalls = 0;
|
|
793
|
+
function castVal(val, ty) {
|
|
794
|
+
if (ty === "Dynamic" || ty === "Void") return val;
|
|
795
|
+
if (ty === "Bool") return VBool(isTruthy(val));
|
|
796
|
+
if (ty === "I64") {
|
|
797
|
+
if (val.t === "int") return val;
|
|
798
|
+
if (val.t === "float") return VInt(Math.trunc(val.v));
|
|
799
|
+
if (val.t === "bool") return VInt(val.v ? 1n : 0n);
|
|
800
|
+
throw new Error(`E0513: cannot cast ${val.t} to int`);
|
|
801
|
+
}
|
|
802
|
+
if (ty === "F64") {
|
|
803
|
+
if (val.t === "float") return val;
|
|
804
|
+
if (val.t === "int") return VFloat(Number(val.v));
|
|
805
|
+
if (val.t === "bool") return VFloat(val.v ? 1.0 : 0.0);
|
|
806
|
+
throw new Error(`E0513: cannot cast ${val.t} to float`);
|
|
807
|
+
}
|
|
808
|
+
if (ty === "Str") return val.t === "str" ? val : VStr(formatValue(val));
|
|
809
|
+
return val;
|
|
810
|
+
}
|
|
811
|
+
function evalUnary(op, v) {
|
|
812
|
+
if (op === "Not") return VBool(!isTruthy(v));
|
|
813
|
+
if (op === "Neg") return v.t === "int" ? VInt(-v.v) : VFloat(-v.v);
|
|
814
|
+
if (op === "BitNot") return VInt(~v.v);
|
|
815
|
+
if (op === "BitsToF64") {
|
|
816
|
+
const ab = new ArrayBuffer(8); const dv = new DataView(ab);
|
|
817
|
+
dv.setBigInt64(0, v.v, true); return VFloat(dv.getFloat64(0, true));
|
|
818
|
+
}
|
|
819
|
+
throw new Error(`E0514: unsupported unary op ${op}`);
|
|
820
|
+
}
|
|
821
|
+
function evalBinop(op, l, r) {
|
|
822
|
+
if (op === "Add" && (l.t === "str" || r.t === "str")) return VStr(formatValue(l) + formatValue(r));
|
|
823
|
+
if (l.t === "int" && r.t === "int") {
|
|
824
|
+
const a = l.v, b = r.v;
|
|
825
|
+
switch (op) {
|
|
826
|
+
case "Add": return VInt(a + b);
|
|
827
|
+
case "Sub": return VInt(a - b);
|
|
828
|
+
case "Mul": return VInt(a * b);
|
|
829
|
+
case "Div": if (b === 0n) throw new Error("E0504: division by zero"); return VInt(a / b);
|
|
830
|
+
case "FloorDiv": { if (b === 0n) throw new Error("E0504: division by zero"); let q = a / b; if (a % b !== 0n && ((a ^ b) < 0n)) q -= 1n; return VInt(q); }
|
|
831
|
+
case "Mod": if (b === 0n) throw new Error("E0504: modulo by zero"); return VInt(a % b);
|
|
832
|
+
case "Eq": return VBool(a === b); case "Ne": return VBool(a !== b);
|
|
833
|
+
case "Lt": return VBool(a < b); case "Le": return VBool(a <= b);
|
|
834
|
+
case "Gt": return VBool(a > b); case "Ge": return VBool(a >= b);
|
|
835
|
+
case "BitAnd": return VInt(a & b); case "BitOr": return VInt(a | b); case "BitXor": return VInt(a ^ b);
|
|
836
|
+
case "Shl": return VInt(a << (b & 63n)); case "Shr": return VInt(a >> (b & 63n));
|
|
837
|
+
case "And": return VBool(a !== 0n && b !== 0n); case "Or": return VBool(a !== 0n || b !== 0n);
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
if ((l.t === "float" || l.t === "int") && (r.t === "float" || r.t === "int")) {
|
|
841
|
+
const a = l.t === "float" ? l.v : Number(l.v), b = r.t === "float" ? r.v : Number(r.v);
|
|
842
|
+
switch (op) {
|
|
843
|
+
case "Add": return VFloat(a + b); case "Sub": return VFloat(a - b); case "Mul": return VFloat(a * b);
|
|
844
|
+
case "Div": return VFloat(a / b); case "FloorDiv": return VFloat(Math.floor(a / b)); case "Mod": return VFloat(a % b);
|
|
845
|
+
case "Eq": return VBool(a === b); case "Ne": return VBool(a !== b);
|
|
846
|
+
case "Lt": return VBool(a < b); case "Le": return VBool(a <= b);
|
|
847
|
+
case "Gt": return VBool(a > b); case "Ge": return VBool(a >= b);
|
|
848
|
+
case "And": return VBool(a !== 0 && b !== 0); case "Or": return VBool(a !== 0 || b !== 0);
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
if (l.t === "bool" && r.t === "bool") {
|
|
852
|
+
if (op === "Eq") return VBool(l.v === r.v); if (op === "Ne") return VBool(l.v !== r.v);
|
|
853
|
+
if (op === "And") return VBool(l.v && r.v); if (op === "Or") return VBool(l.v || r.v);
|
|
854
|
+
}
|
|
855
|
+
if (l.t === "str" && r.t === "str") {
|
|
856
|
+
if (op === "Eq") return VBool(l.v === r.v); if (op === "Ne") return VBool(l.v !== r.v);
|
|
857
|
+
if (op === "Lt") return VBool(l.v < r.v); if (op === "Le") return VBool(l.v <= r.v);
|
|
858
|
+
if (op === "Gt") return VBool(l.v > r.v); if (op === "Ge") return VBool(l.v >= r.v);
|
|
859
|
+
}
|
|
860
|
+
if (op === "Eq") return VBool(l.t === r.t && l.v === r.v);
|
|
861
|
+
if (op === "Ne") return VBool(l.t !== r.t || l.v !== r.v);
|
|
862
|
+
throw new Error(`E0515: unsupported binary op ${op} between ${l.t} and ${r.t}`);
|
|
863
|
+
}
|
|
864
|
+
function evalBuiltin(name, args) {
|
|
865
|
+
switch (name) {
|
|
866
|
+
case "Print": emitOut(args.map(formatValue).join(" ")); return NIL;
|
|
867
|
+
case "Println": emitOut(args.map(formatValue).join(" ") + "\n"); return NIL;
|
|
868
|
+
case "Printf": { const s = formatPrintf(args[0] ? formatValue(args[0]) : "", args.slice(1)); emitOut(s); return VInt(s.length); }
|
|
869
|
+
case "Len": return VInt(args[0].t === "object" ? args[0].fields.size : args[0].v.length);
|
|
870
|
+
case "Str": return VStr(formatValue(args[0] ?? NIL));
|
|
871
|
+
case "Int": return castVal(args[0] ?? VInt(0), "I64");
|
|
872
|
+
case "Float": return castVal(args[0] ?? VFloat(0), "F64");
|
|
873
|
+
case "Bool": return VBool(isTruthy(args[0] ?? NIL));
|
|
874
|
+
case "Abs": return args[0].t === "int" ? VInt(args[0].v < 0n ? -args[0].v : args[0].v) : VFloat(Math.abs(args[0].v));
|
|
875
|
+
case "Min": return evalBinop("Lt", args[0], args[1]).v ? args[0] : args[1];
|
|
876
|
+
case "Max": return evalBinop("Gt", args[0], args[1]).v ? args[0] : args[1];
|
|
877
|
+
case "Sqrt": return VFloat(Math.sqrt(args[0].t === "int" ? Number(args[0].v) : args[0].v));
|
|
878
|
+
case "Pow": return VFloat(Math.pow(args[0].t === "int" ? Number(args[0].v) : args[0].v, args[1].t === "int" ? Number(args[1].v) : args[1].v));
|
|
879
|
+
case "Push": args[0].v.push(args[1]); return VInt(args[0].v.length);
|
|
880
|
+
case "Pop": return args[0].v.pop() ?? NIL;
|
|
881
|
+
case "TypeOf": return VStr(args[0]?.t ?? "nil");
|
|
882
|
+
case "AllocBuf": return { t: "buffer", v: new Uint8Array(Number(args[0].v)) };
|
|
883
|
+
case "ReadU8": return VInt(args[0].v[Number(args[1].v)]);
|
|
884
|
+
case "WriteU8": args[0].v[Number(args[1].v)] = Number(args[2].v & 0xffn); return NIL;
|
|
885
|
+
case "BufLen": return VInt(args[0].v.length);
|
|
886
|
+
case "ClockMs": return VInt(Date.now());
|
|
887
|
+
case "Assert": if (!isTruthy(args[0])) throw new Error("E0407: assertion failed"); return VBool(true);
|
|
888
|
+
default: throw new Error(`E0516: unknown builtin ${name}`);
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
function invoke(fnId, args) {
|
|
892
|
+
vmCalls++;
|
|
893
|
+
const fn = fnMap.get(fnId);
|
|
894
|
+
if (!fn) throw new Error(`E0501: missing function #${fnId}`);
|
|
895
|
+
const regs = new Array(fn.registerTypes.length).fill(NIL);
|
|
896
|
+
for (let i = 0; i < fn.params.length; i++) regs[fn.params[i][0]] = castVal(args[i] ?? NIL, fn.params[i][1]);
|
|
897
|
+
let bbIdx = 0, ip = 0;
|
|
898
|
+
while (bbIdx < fn.blocks.length) {
|
|
899
|
+
const bb = fn.blocks[bbIdx];
|
|
900
|
+
if (ip >= bb.instructions.length) break;
|
|
901
|
+
const ins = bb.instructions[ip];
|
|
902
|
+
switch (ins.op) {
|
|
903
|
+
case "LoadConst": regs[ins.dst] = ins.c.k === "nil" ? NIL : ins.c.k === "bool" ? VBool(ins.c.v) : ins.c.k === "int" ? VInt(ins.c.v) : ins.c.k === "float" ? VFloat(ins.c.v) : VStr(ins.c.v); ip++; break;
|
|
904
|
+
case "Move": regs[ins.dst] = regs[ins.src]; ip++; break;
|
|
905
|
+
case "Cast": regs[ins.dst] = castVal(regs[ins.src], ins.ty); ip++; break;
|
|
906
|
+
case "BinOp": regs[ins.dst] = evalBinop(ins.bop, regs[ins.l], regs[ins.r]); ip++; break;
|
|
907
|
+
case "UnaryOp": regs[ins.dst] = evalUnary(ins.uop, regs[ins.src]); ip++; break;
|
|
908
|
+
case "CallFn": regs[ins.dst] = invoke(ins.fnId, ins.args.map((r) => regs[r])); ip++; break;
|
|
909
|
+
case "CallIndirect": regs[ins.dst] = invoke(regs[ins.fnReg].v, ins.args.map((r) => regs[r])); ip++; break;
|
|
910
|
+
case "CallBuiltin": regs[ins.dst] = evalBuiltin(ins.builtin, ins.args.map((r) => regs[r])); ip++; break;
|
|
911
|
+
case "LoadFnRef": regs[ins.dst] = { t: "fn", v: ins.fnId }; ip++; break;
|
|
912
|
+
case "Return": return ins.reg !== null ? regs[ins.reg] : NIL;
|
|
913
|
+
case "BranchIf": bbIdx = isTruthy(regs[ins.cond]) ? ins.t : ins.f; ip = 0; break;
|
|
914
|
+
case "Jump": bbIdx = ins.t; ip = 0; break;
|
|
915
|
+
case "CreateArray": regs[ins.dst] = { t: "array", v: ins.items.map((r) => regs[r]) }; ip++; break;
|
|
916
|
+
case "GetIndex": regs[ins.dst] = regs[ins.obj].t === "buffer" ? VInt(regs[ins.obj].v[Number(regs[ins.idx].v)]) : regs[ins.obj].v[Number(regs[ins.idx].v)]; ip++; break;
|
|
917
|
+
case "SetIndex": if (regs[ins.obj].t === "buffer") regs[ins.obj].v[Number(regs[ins.idx].v)] = Number(regs[ins.val].v & 0xffn); else regs[ins.obj].v[Number(regs[ins.idx].v)] = regs[ins.val]; ip++; break;
|
|
918
|
+
case "CreateObject": regs[ins.dst] = { t: "object", className: ins.cname, fields: new Map() }; ip++; break;
|
|
919
|
+
case "SetField": regs[ins.obj].fields.set(ins.field, regs[ins.val]); ip++; break;
|
|
920
|
+
case "GetField": regs[ins.dst] = regs[ins.obj].fields.get(ins.field) ?? NIL; ip++; break;
|
|
921
|
+
case "AllocBuffer": regs[ins.dst] = { t: "buffer", v: new Uint8Array(Number(regs[ins.size].v)) }; ip++; break;
|
|
922
|
+
case "StoreByte": regs[ins.buf].v[Number(regs[ins.off].v)] = Number(regs[ins.val].v & 0xffn); ip++; break;
|
|
923
|
+
case "LoadByte": regs[ins.dst] = VInt(regs[ins.buf].v[Number(regs[ins.off].v)]); ip++; break;
|
|
924
|
+
default: throw new Error(`E0517: unsupported instruction ${ins.op}`);
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
return NIL;
|
|
928
|
+
}
|
|
929
|
+
for (const initId of bundle.initFns) invoke(initId, []);
|
|
930
|
+
const entryName = options.entry || bundle.entryName || "main";
|
|
931
|
+
let targetId = bundle.entryFn;
|
|
932
|
+
if (entryName !== bundle.entryName) {
|
|
933
|
+
const exp = bundle.exports.find(([n]) => n === entryName);
|
|
934
|
+
if (!exp) throw new Error(`E0501: function '${entryName}' not found in IR bundle`);
|
|
935
|
+
targetId = exp[1];
|
|
936
|
+
}
|
|
937
|
+
const args = (options.args || []).map((a) =>
|
|
938
|
+
typeof a === "bigint" || (typeof a === "number" && Number.isInteger(a)) ? VInt(a) :
|
|
939
|
+
typeof a === "number" ? VFloat(a) :
|
|
940
|
+
typeof a === "boolean" ? VBool(a) :
|
|
941
|
+
typeof a === "string" ? VStr(a) : NIL
|
|
942
|
+
);
|
|
943
|
+
const ret = invoke(targetId, args);
|
|
944
|
+
const jsRet = ret.t === "int" ? (ret.v >= BigInt(Number.MIN_SAFE_INTEGER) && ret.v <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(ret.v) : ret.v) : ret.v;
|
|
945
|
+
return {
|
|
946
|
+
returnValue: jsRet,
|
|
947
|
+
returnType: ret.t,
|
|
948
|
+
formattedReturn: formatValue(ret),
|
|
949
|
+
stdout,
|
|
950
|
+
stats: { engine: "js-vm", vmInvocations: vmCalls, functionsCount: bundle.functions.length },
|
|
951
|
+
};
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
// --- Public Frontend API ---
|
|
955
|
+
function isIrOrPolyx(text) {
|
|
956
|
+
if (typeof text !== "string") return false;
|
|
957
|
+
const t = text.replace(/^\ufeff/, "").trimStart();
|
|
958
|
+
return t.startsWith(ARMOR_BEGIN) || t.startsWith(PLAIN_BANNER) || t.startsWith(PLAIN_BEGIN_IR) || /^;\s*entry:/m.test(t) || /^fn\s+#\d+\s+/m.test(t);
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
function verify(irOrPolyxText, options = {}) {
|
|
962
|
+
const norm = normalizeText(irOrPolyxText);
|
|
963
|
+
const trimmed = norm.trimStart();
|
|
964
|
+
if (trimmed.startsWith(ARMOR_BEGIN)) {
|
|
965
|
+
const parsed = parseArmoredPolyx(norm);
|
|
966
|
+
const expectedFp = computeOriginFingerprint(parsed.pubkeyBytes, parsed.flags, parsed.salt);
|
|
967
|
+
if (!eqBytes(parsed.originFp, expectedFp)) throw new Error("E0709: Part 1 Verifier failed: invalid origin fingerprint");
|
|
968
|
+
let pinnedMatch = null;
|
|
969
|
+
if (options.verifyKey) {
|
|
970
|
+
const pin = decodeHexExact(options.verifyKey.replace(/^hex:/, ""), 32);
|
|
971
|
+
if (!pin || !eqBytes(parsed.pubkeyBytes, pin)) throw new Error("E0711: Part 1 Verifier failed: publisher key mismatch");
|
|
972
|
+
pinnedMatch = true;
|
|
973
|
+
}
|
|
974
|
+
if (!ed25519VerifyStrict(parsed.pubkeyBytes, parsed.sigMsg, parsed.sigBytes)) {
|
|
975
|
+
throw new Error("E0712: Part 1 Verifier failed: invalid Ed25519 signature");
|
|
976
|
+
}
|
|
977
|
+
return {
|
|
978
|
+
format: "POLYX003", version: 3, encrypted: true, obfuscated: parsed.obfuscated,
|
|
979
|
+
signed: true, keyless: parsed.kdf === "vm-sealed",
|
|
980
|
+
signerPubkeyHex: bytesToHex(parsed.pubkeyBytes), pinnedPublisherMatch: pinnedMatch,
|
|
981
|
+
payloadBytes: parsed.ciphertext.length,
|
|
982
|
+
};
|
|
983
|
+
}
|
|
984
|
+
const plain = parsePlainIrText(norm);
|
|
985
|
+
if (!plain.sig) throw new Error("E0712: Part 1 Verifier failed: unsigned .polyir container");
|
|
986
|
+
const salt = decodeHexExact(plain.sig.saltHex, 16);
|
|
987
|
+
const pub = decodeHexExact(plain.sig.signerHex, 32);
|
|
988
|
+
const orig = decodeHexExact(plain.sig.originHex, 32);
|
|
989
|
+
const sig = decodeHexExact(plain.sig.sigHex, 64);
|
|
990
|
+
if (!salt || !pub || !orig || !sig) throw new Error("E0712: malformed signature fields");
|
|
991
|
+
if (!eqBytes(orig, computeOriginFingerprint(pub, 0, salt))) throw new Error("E0709: invalid origin fingerprint");
|
|
992
|
+
let pinnedMatch = null;
|
|
993
|
+
if (options.verifyKey) {
|
|
994
|
+
const pin = decodeHexExact(options.verifyKey.replace(/^hex:/, ""), 32);
|
|
995
|
+
if (!pin || !eqBytes(pub, pin)) throw new Error("E0711: publisher key mismatch");
|
|
996
|
+
pinnedMatch = true;
|
|
997
|
+
}
|
|
998
|
+
const initsStr = `[${plain.bundle.initFns.join(", ")}]`;
|
|
999
|
+
const expStr = `[${plain.bundle.exports.map(([n, id]) => `${escapeStr(n)}=${id}`).join(", ")}]`;
|
|
1000
|
+
const meta = `POLYIR03\nv=3\nentry=${plain.bundle.entryFn} ${escapeStr(plain.bundle.entryName)}\ninits=${initsStr}\nexports=${expStr}\nsalt=${plain.sig.saltHex}\nsigner=${plain.sig.signerHex}\norigin=${plain.sig.originHex}\n`;
|
|
1001
|
+
const sigMsg = concatBytes(VERIFY_DOMAIN, textEncoder.encode(meta), textEncoder.encode(plain.irBody));
|
|
1002
|
+
if (!ed25519VerifyStrict(pub, sigMsg, sig)) throw new Error("E0712: invalid Ed25519 signature");
|
|
1003
|
+
return {
|
|
1004
|
+
format: "POLYIR03", version: 3, encrypted: false, obfuscated: false, signed: true, keyless: true,
|
|
1005
|
+
signerPubkeyHex: plain.sig.signerHex, pinnedPublisherMatch: pinnedMatch, payloadBytes: plain.irBody.length,
|
|
1006
|
+
};
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
function decodeIr(irOrPolyxText, options = {}) {
|
|
1010
|
+
const norm = normalizeText(irOrPolyxText);
|
|
1011
|
+
const trimmed = norm.trimStart();
|
|
1012
|
+
if (trimmed.startsWith(ARMOR_BEGIN)) {
|
|
1013
|
+
const report = verify(irOrPolyxText, options);
|
|
1014
|
+
const parsed = parseArmoredPolyx(norm);
|
|
1015
|
+
let key32;
|
|
1016
|
+
if (parsed.kdf === "vm-sealed") {
|
|
1017
|
+
key32 = deriveVmSealedKey(parsed.salt, parsed.nonce, parsed.pubkeyBytes);
|
|
1018
|
+
} else if (parsed.kdf === "blake3-raw") {
|
|
1019
|
+
const rawKey = decodeHexExact((options.key || "").replace(/^hex:/, ""), 32);
|
|
1020
|
+
if (!rawKey) throw new Error("E0713: key-locked .polyx requires 32-byte hex key");
|
|
1021
|
+
key32 = blake3DeriveKey("polycomp-v3-xchacha20-raw", concatBytes(rawKey, parsed.salt), 32);
|
|
1022
|
+
} else {
|
|
1023
|
+
throw new Error("E0715: Argon2id passphrase .polyx requires native polycomp CLI");
|
|
1024
|
+
}
|
|
1025
|
+
const plainBytes = xchacha20Poly1305Decrypt(key32, parsed.nonce, textEncoder.encode(parsed.canonicalHeader), parsed.ciphertext);
|
|
1026
|
+
return { bundle: deserializePermutedBytecode(plainBytes, parsed.salt, parsed.nonce), report };
|
|
1027
|
+
}
|
|
1028
|
+
const plain = parsePlainIrText(norm);
|
|
1029
|
+
if (!plain.sig) {
|
|
1030
|
+
if (!options.allowUnsigned) throw new Error("E0712: unsigned .polyir requires { allowUnsigned: true }");
|
|
1031
|
+
return {
|
|
1032
|
+
bundle: plain.bundle,
|
|
1033
|
+
report: { format: "POLYIR03", version: 3, encrypted: false, obfuscated: false, signed: false, keyless: true, signerPubkeyHex: "unsigned", pinnedPublisherMatch: null, payloadBytes: plain.irBody.length },
|
|
1034
|
+
};
|
|
1035
|
+
}
|
|
1036
|
+
const report = verify(irOrPolyxText, options);
|
|
1037
|
+
return { bundle: plain.bundle, report };
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
function execute(irOrPolyxText, options = {}) {
|
|
1041
|
+
const { bundle, report } = decodeIr(irOrPolyxText, options);
|
|
1042
|
+
const out = runBundle(bundle, options);
|
|
1043
|
+
return { ...out, verification: report };
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
export { execute, verify, decodeIr, isIrOrPolyx, runBundle };
|
|
1047
|
+
export default { execute, verify, decodeIr, isIrOrPolyx, runBundle };
|