@gmitch215/folio 0.0.0-stage → 1.0.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.
@@ -0,0 +1,505 @@
1
+ import binaryen from 'binaryen';
2
+ import { admission, extract } from "./extract.js";
3
+ import { nativePlan } from "./guards.js";
4
+ const info = (expression) => {
5
+ const id = binaryen.getExpressionId(expression);
6
+ if (id === binaryen.UnreachableId || id === binaryen.NopId) {
7
+ return { id, type: binaryen.getExpressionType(expression) };
8
+ }
9
+ return binaryen.getExpressionInfo(expression);
10
+ };
11
+ function walk(expression, visit) {
12
+ const value = info(expression);
13
+ visit(value);
14
+ for (const key of ['children', 'operands']) {
15
+ for (const child of value[key] ?? [])
16
+ walk(child, visit);
17
+ }
18
+ for (const key of [
19
+ 'body',
20
+ 'condition',
21
+ 'ifTrue',
22
+ 'ifFalse',
23
+ 'ptr',
24
+ 'value',
25
+ 'left',
26
+ 'right',
27
+ 'dest',
28
+ 'source',
29
+ 'size'
30
+ ]) {
31
+ if (key === 'value' && value.id === binaryen.ConstId)
32
+ continue;
33
+ if (typeof value[key] === 'number' && value[key])
34
+ walk(value[key], visit);
35
+ }
36
+ }
37
+ function loopPlan(module, fn, diagnostic) {
38
+ const f = binaryen.getFunctionInfo(fn);
39
+ if (f.results !== binaryen.none) {
40
+ diagnostic.reason = 'non-void entry requires a result merge';
41
+ return;
42
+ }
43
+ const parameters = binaryen.expandType(f.params);
44
+ if (parameters.some((type) => type !== binaryen.i32)) {
45
+ diagnostic.reason = 'non-i32 loop parameters';
46
+ return;
47
+ }
48
+ const root = info(f.body);
49
+ if (root.id !== binaryen.BlockId || root.children.length !== 2)
50
+ return;
51
+ const guard = info(root.children[0]);
52
+ const loop = info(root.children[1]);
53
+ if (guard.id !== binaryen.BreakId ||
54
+ guard.name !== root.name ||
55
+ guard.value ||
56
+ !guard.condition)
57
+ return;
58
+ if (loop.id !== binaryen.LoopId)
59
+ return;
60
+ const zero = info(guard.condition);
61
+ if (zero.id !== binaryen.UnaryId || zero.op !== binaryen.EqZInt32)
62
+ return;
63
+ const counter = info(zero.value);
64
+ if (counter.id !== binaryen.LocalGetId || counter.index >= parameters.length)
65
+ return;
66
+ const body = info(loop.body);
67
+ if (body.id !== binaryen.BlockId || body.children.length < 2)
68
+ return;
69
+ const last = info(body.children.at(-1));
70
+ if (last.id !== binaryen.BreakId || last.name !== loop.name || last.value || !last.condition)
71
+ return;
72
+ const decrement = info(last.condition);
73
+ if (decrement.id !== binaryen.LocalSetId || !decrement.isTee)
74
+ return;
75
+ if (decrement.index !== counter.index)
76
+ return;
77
+ const add = info(decrement.value);
78
+ if (add.id !== binaryen.BinaryId || add.op !== binaryen.AddInt32)
79
+ return;
80
+ const left = info(add.left), right = info(add.right);
81
+ if (left.id !== binaryen.LocalGetId || left.index !== counter.index)
82
+ return;
83
+ if (right.id !== binaryen.ConstId || right.value !== -1)
84
+ return;
85
+ const steps = [];
86
+ const updates = new Set();
87
+ let end = body.children.length - 1;
88
+ while (end > 0) {
89
+ const set = info(body.children[end - 1]);
90
+ if (set.id !== binaryen.LocalSetId || set.isTee || set.index === counter.index)
91
+ break;
92
+ if (set.index >= parameters.length)
93
+ break;
94
+ const update = info(set.value);
95
+ if (update.id !== binaryen.BinaryId || update.op !== binaryen.AddInt32)
96
+ break;
97
+ const source = info(update.left), delta = info(update.right);
98
+ if (source.id !== binaryen.LocalGetId || source.index !== set.index)
99
+ break;
100
+ if (delta.id !== binaryen.ConstId || updates.has(set.index))
101
+ break;
102
+ updates.add(set.index);
103
+ steps.push({ parameter: set.index, step: delta.value });
104
+ end--;
105
+ }
106
+ if (!steps.length || end === 0)
107
+ return;
108
+ const payload = body.children.slice(0, end);
109
+ const written = new Set();
110
+ let safe = true;
111
+ for (const expression of payload) {
112
+ walk(expression, (value) => {
113
+ if (value.id === binaryen.LocalSetId) {
114
+ written.add(value.index);
115
+ if (value.index === counter.index || updates.has(value.index)) {
116
+ diagnostic.reason = 'loop control modified inside the iteration';
117
+ safe = false;
118
+ }
119
+ }
120
+ if (value.id === binaryen.LocalGetId && value.index === counter.index) {
121
+ diagnostic.reason = 'iteration reads the remaining count';
122
+ safe = false;
123
+ }
124
+ if ([binaryen.BreakId, binaryen.SwitchId, binaryen.ReturnId, binaryen.LoopId].includes(value.id) ||
125
+ (value.id === binaryen.CallId && value.isReturn)) {
126
+ diagnostic.reason = 'nested or escaping control flow';
127
+ safe = false;
128
+ }
129
+ });
130
+ }
131
+ if (!safe)
132
+ return;
133
+ function visit(expression, assigned) {
134
+ const value = info(expression);
135
+ const children = (...expressions) => expressions.every((child) => visit(child, assigned));
136
+ switch (value.id) {
137
+ case binaryen.LocalGetId:
138
+ if (written.has(value.index) && !assigned.has(value.index)) {
139
+ diagnostic.reason = 'loop-carried scalar state';
140
+ return false;
141
+ }
142
+ return true;
143
+ case binaryen.LocalSetId:
144
+ if (!visit(value.value, assigned))
145
+ return false;
146
+ assigned.add(value.index);
147
+ return true;
148
+ case binaryen.BlockId:
149
+ return children(...value.children);
150
+ case binaryen.IfId: {
151
+ if (!visit(value.condition, assigned))
152
+ return false;
153
+ const yes = new Set(assigned), no = new Set(assigned);
154
+ if (!visit(value.ifTrue, yes) || (value.ifFalse && !visit(value.ifFalse, no)))
155
+ return false;
156
+ for (const index of yes)
157
+ if (no.has(index))
158
+ assigned.add(index);
159
+ return true;
160
+ }
161
+ case binaryen.SelectId:
162
+ return children(value.ifTrue, value.ifFalse, value.condition);
163
+ case binaryen.CallId:
164
+ return children(...value.operands);
165
+ case binaryen.UnaryId:
166
+ case binaryen.DropId:
167
+ return children(value.value);
168
+ case binaryen.BinaryId:
169
+ return children(value.left, value.right);
170
+ case binaryen.LoadId:
171
+ return children(value.ptr);
172
+ case binaryen.StoreId:
173
+ return children(value.ptr, value.value);
174
+ case binaryen.MemoryCopyId:
175
+ return children(value.dest, value.source, value.size);
176
+ case binaryen.MemoryFillId:
177
+ return children(value.dest, value.value, value.size);
178
+ case binaryen.ConstId:
179
+ case binaryen.GlobalGetId:
180
+ case binaryen.NopId:
181
+ case binaryen.UnreachableId:
182
+ return true;
183
+ default:
184
+ diagnostic.reason = 'iteration analysis does not support this expression';
185
+ return false;
186
+ }
187
+ }
188
+ const assigned = new Set();
189
+ return payload.every((expression) => visit(expression, assigned))
190
+ ? { countParameter: counter.index, steps }
191
+ : undefined;
192
+ }
193
+ /** Prepares guarded parallel paths; unsupported features retain the original module. */
194
+ function prepareTracked(bytes, options = {}) {
195
+ const original = Uint8Array.from(bytes);
196
+ const native = new WebAssembly.Module(original);
197
+ if (options.parallel === 'off')
198
+ return { original, loops: {}, reasons: ['parallel preparation disabled'] };
199
+ const reasons = [];
200
+ const imports = WebAssembly.Module.imports(native);
201
+ if (imports.some((item) => item.kind !== 'memory'))
202
+ reasons.push('host or non-memory imports');
203
+ if (imports.some((item) => item.module === 'folio'))
204
+ reasons.push('reserved import namespace');
205
+ if (imports.filter((item) => item.kind === 'memory').length !== 1)
206
+ reasons.push('one imported memory required');
207
+ let cursor = 8;
208
+ const unsigned = () => {
209
+ let value = 0, shift = 0, byte;
210
+ do {
211
+ byte = original[cursor++];
212
+ value += (byte & 127) * 2 ** shift;
213
+ shift += 7;
214
+ } while (byte & 128);
215
+ return value;
216
+ };
217
+ while (cursor < original.length) {
218
+ const section = original[cursor++];
219
+ const size = unsigned();
220
+ const end = cursor + size;
221
+ if (section === 5 && unsigned() !== 0)
222
+ reasons.push('additional defined memory');
223
+ cursor = end;
224
+ }
225
+ if (reasons.length)
226
+ return { original, loops: {}, reasons };
227
+ let analysisModule;
228
+ const loops = {};
229
+ const loopReasons = {};
230
+ const nativePlans = {};
231
+ try {
232
+ const module = (analysisModule = binaryen.readBinary(original));
233
+ // Native validation already established the source instruction set. Binaryen
234
+ // does not infer every proposal flag from a binary's instruction bodies.
235
+ const compactImports = binaryen.Features
236
+ .CompactImports;
237
+ module.setFeatures(binaryen.Features.All & ~compactImports);
238
+ if (module.getStart())
239
+ reasons.push('start function');
240
+ const raw = module;
241
+ if (raw.getNumDataSegments())
242
+ reasons.push('data segments require initialization isolation');
243
+ const memory = module.hasMemory() ? module.getMemoryInfo() : undefined;
244
+ if (!memory?.shared || memory.is64)
245
+ reasons.push('shared wasm32 memory required');
246
+ if (memory?.shared)
247
+ module.setFeatures(module.getFeatures() | binaryen.Features.Atomics);
248
+ const allowed = new Set([
249
+ binaryen.BlockId,
250
+ binaryen.IfId,
251
+ binaryen.LoopId,
252
+ binaryen.BreakId,
253
+ binaryen.SwitchId,
254
+ binaryen.CallId,
255
+ binaryen.LocalGetId,
256
+ binaryen.LocalSetId,
257
+ binaryen.GlobalGetId,
258
+ binaryen.LoadId,
259
+ binaryen.StoreId,
260
+ binaryen.MemoryCopyId,
261
+ binaryen.MemoryFillId,
262
+ binaryen.ConstId,
263
+ binaryen.UnaryId,
264
+ binaryen.BinaryId,
265
+ binaryen.SelectId,
266
+ binaryen.DropId,
267
+ binaryen.ReturnId,
268
+ binaryen.NopId,
269
+ binaryen.UnreachableId
270
+ ]);
271
+ const calls = new Map();
272
+ const exportedFunctions = new Map();
273
+ for (let index = 0; index < module.getNumExports(); index++) {
274
+ const exported = binaryen.getExportInfo(module.getExportByIndex(index));
275
+ if (exported.kind !== binaryen.ExternalFunction)
276
+ continue;
277
+ const names = exportedFunctions.get(exported.value) ?? [];
278
+ names.push(exported.name);
279
+ exportedFunctions.set(exported.value, names);
280
+ }
281
+ for (let index = 0; index < module.getNumFunctions(); index++) {
282
+ const fn = module.getFunctionByIndex(index);
283
+ const f = binaryen.getFunctionInfo(fn);
284
+ if ([...binaryen.expandType(f.params), ...binaryen.expandType(f.results)].some((type) => ![binaryen.i32, binaryen.i64, binaryen.f32, binaryen.f64].includes(type)))
285
+ reasons.push('reference or vector function signature');
286
+ if (!f.body)
287
+ continue;
288
+ const targets = new Set();
289
+ calls.set(f.name, targets);
290
+ walk(f.body, (value) => {
291
+ if (value.id === binaryen.CallId)
292
+ targets.add(value.target);
293
+ if (!allowed.has(value.id))
294
+ reasons.push(`unsupported expression ${value.id}`);
295
+ if (value.id === binaryen.GlobalGetId)
296
+ reasons.push('global state');
297
+ if (value.isAtomic)
298
+ reasons.push('atomic access');
299
+ if ([binaryen.LoadId, binaryen.StoreId].includes(value.id)) {
300
+ const type = value.id === binaryen.LoadId ? value.type : info(value.value).type;
301
+ if (![binaryen.i32, binaryen.i64, binaryen.f32, binaryen.f64].includes(type))
302
+ reasons.push('unsupported memory value type');
303
+ }
304
+ });
305
+ const diagnostic = { reason: 'loop shape not recognized' };
306
+ const plan = loopPlan(module, fn, diagnostic);
307
+ const names = exportedFunctions.get(f.name) ?? [];
308
+ const proved = names.length && plan ? nativePlan(module, fn) : undefined;
309
+ for (const name of names) {
310
+ if (plan) {
311
+ Object.defineProperty(loops, name, {
312
+ value: plan,
313
+ enumerable: true,
314
+ configurable: true,
315
+ writable: true
316
+ });
317
+ if (proved)
318
+ Object.defineProperty(nativePlans, name, {
319
+ value: proved,
320
+ enumerable: true,
321
+ configurable: true,
322
+ writable: true
323
+ });
324
+ }
325
+ else
326
+ Object.defineProperty(loopReasons, name, {
327
+ value: diagnostic.reason,
328
+ enumerable: true,
329
+ configurable: true,
330
+ writable: true
331
+ });
332
+ }
333
+ }
334
+ const visiting = new Set(), visited = new Set();
335
+ const recursive = (name) => {
336
+ if (visiting.has(name))
337
+ return true;
338
+ if (visited.has(name))
339
+ return false;
340
+ visiting.add(name);
341
+ if ([...(calls.get(name) ?? [])].some(recursive))
342
+ return true;
343
+ visiting.delete(name);
344
+ visited.add(name);
345
+ return false;
346
+ };
347
+ if ([...calls.keys()].some(recursive))
348
+ reasons.push('recursive call graph retains original owner stack');
349
+ if (reasons.length)
350
+ return { original, loops: {}, reasons: [...new Set(reasons)] };
351
+ const reserved = [
352
+ '__folio_load',
353
+ '__folio_store',
354
+ '__folio_exhausted',
355
+ '__folio_set_fuel',
356
+ '__folio_load64',
357
+ '__folio_store64',
358
+ '__folio_copy',
359
+ '__folio_fill'
360
+ ];
361
+ if (reserved.some((name) => module.getFunction(name) || module.getExport(name)) ||
362
+ module.getGlobal('__folio_fuel')) {
363
+ return { original, loops: {}, reasons: ['reserved function name'] };
364
+ }
365
+ module.addGlobal('__folio_fuel', binaryen.i32, true, module.i32.const(0));
366
+ const lowered = module;
367
+ function tick() {
368
+ const module = lowered;
369
+ return module.block(null, [
370
+ module.global.set('__folio_fuel', module.i32.sub(module.global.get('__folio_fuel', binaryen.i32), module.i32.const(1))),
371
+ module.if(module.i32.le_s(module.global.get('__folio_fuel', binaryen.i32), module.i32.const(0)), module.call(reserved[2], [], binaryen.none))
372
+ ]);
373
+ }
374
+ function lower(expression) {
375
+ const module = lowered;
376
+ const v = info(expression);
377
+ switch (v.id) {
378
+ case binaryen.BlockId:
379
+ return module.block(v.name, v.children.map(lower), v.type);
380
+ case binaryen.IfId:
381
+ return module.if(lower(v.condition), lower(v.ifTrue), v.ifFalse ? lower(v.ifFalse) : undefined);
382
+ case binaryen.LoopId:
383
+ return module.loop(v.name, module.block(null, [tick(), lower(v.body)], v.type));
384
+ case binaryen.BreakId:
385
+ return module.br(v.name, v.condition ? lower(v.condition) : undefined, v.value ? lower(v.value) : undefined);
386
+ case binaryen.SwitchId:
387
+ return module.switch(v.names, v.defaultName, lower(v.condition), v.value ? lower(v.value) : undefined);
388
+ case binaryen.CallId:
389
+ return v.isReturn
390
+ ? module.return_call(v.target, v.operands.map(lower), v.type)
391
+ : module.call(v.target, v.operands.map(lower), v.type);
392
+ case binaryen.LocalSetId:
393
+ return v.isTee
394
+ ? module.local.tee(v.index, lower(v.value), v.type)
395
+ : module.local.set(v.index, lower(v.value));
396
+ case binaryen.LoadId: {
397
+ const wide = v.type === binaryen.i64 || v.type === binaryen.f64;
398
+ const loaded = module.call(reserved[wide ? 4 : 0], [
399
+ lower(v.ptr),
400
+ module.i32.const(v.offset),
401
+ module.i32.const(v.bytes),
402
+ module.i32.const(Number(v.isSigned))
403
+ ], wide ? binaryen.i64 : binaryen.i32);
404
+ return v.type === binaryen.f32
405
+ ? module.f32.reinterpret(loaded)
406
+ : v.type === binaryen.f64
407
+ ? module.f64.reinterpret(loaded)
408
+ : loaded;
409
+ }
410
+ case binaryen.StoreId: {
411
+ const type = info(v.value).type;
412
+ const wide = type === binaryen.i64 || type === binaryen.f64;
413
+ const value = lower(v.value);
414
+ return module.call(reserved[wide ? 5 : 1], [
415
+ lower(v.ptr),
416
+ type === binaryen.f32
417
+ ? module.i32.reinterpret(value)
418
+ : type === binaryen.f64
419
+ ? module.i64.reinterpret(value)
420
+ : value,
421
+ module.i32.const(v.offset),
422
+ module.i32.const(v.bytes)
423
+ ], binaryen.none);
424
+ }
425
+ case binaryen.MemoryCopyId:
426
+ return module.call(reserved[6], [lower(v.dest), lower(v.source), lower(v.size)], binaryen.none);
427
+ case binaryen.MemoryFillId:
428
+ return module.call(reserved[7], [lower(v.dest), lower(v.value), lower(v.size)], binaryen.none);
429
+ case binaryen.UnaryId:
430
+ return binaryen._BinaryenUnary(module.ptr, v.op, lower(v.value));
431
+ case binaryen.BinaryId:
432
+ return binaryen._BinaryenBinary(module.ptr, v.op, lower(v.left), lower(v.right));
433
+ case binaryen.SelectId:
434
+ return module.select(lower(v.condition), lower(v.ifTrue), lower(v.ifFalse));
435
+ case binaryen.DropId:
436
+ return module.drop(lower(v.value));
437
+ case binaryen.ReturnId:
438
+ return module.return(v.value ? lower(v.value) : undefined);
439
+ default:
440
+ return expression;
441
+ }
442
+ }
443
+ const count = module.getNumFunctions();
444
+ for (let index = 0; index < count; index++) {
445
+ const fn = module.getFunctionByIndex(index);
446
+ const body = binaryen.getFunctionInfo(fn).body;
447
+ if (body)
448
+ binaryen._BinaryenFunctionSetBody(fn, module.block(null, [tick(), lower(body)], info(body).type));
449
+ }
450
+ const fourI32 = binaryen.createType(Array(4).fill(binaryen.i32));
451
+ module.addFunctionImport(reserved[0], 'folio', 'load', fourI32, binaryen.i32);
452
+ module.addFunctionImport(reserved[1], 'folio', 'store', fourI32, binaryen.none);
453
+ module.addFunctionImport(reserved[4], 'folio', 'load64', fourI32, binaryen.i64);
454
+ module.addFunctionImport(reserved[5], 'folio', 'store64', binaryen.createType([binaryen.i32, binaryen.i64, binaryen.i32, binaryen.i32]), binaryen.none);
455
+ const threeI32 = binaryen.createType(Array(3).fill(binaryen.i32));
456
+ module.addFunctionImport(reserved[6], 'folio', 'copy', threeI32, binaryen.none);
457
+ module.addFunctionImport(reserved[7], 'folio', 'fill', threeI32, binaryen.none);
458
+ module.addFunctionImport(reserved[2], 'folio', 'exhausted', binaryen.none, binaryen.none);
459
+ module.addFunction(reserved[3], binaryen.i32, binaryen.none, [], module.global.set('__folio_fuel', module.local.get(0, binaryen.i32)));
460
+ module.addFunctionExport(reserved[3], reserved[3]);
461
+ if (!module.validate())
462
+ throw new Error('invalid transactional lowering');
463
+ return {
464
+ original,
465
+ transactional: module.emitBinary(),
466
+ loops,
467
+ loopReasons,
468
+ native: nativePlans,
469
+ reasons: []
470
+ };
471
+ }
472
+ catch (error) {
473
+ return {
474
+ original,
475
+ loops: {},
476
+ reasons: [
477
+ `parallel preparation unavailable: ${error instanceof Error ? error.message : String(error)}`
478
+ ]
479
+ };
480
+ }
481
+ finally {
482
+ analysisModule?.dispose();
483
+ }
484
+ }
485
+ /**
486
+ * Keeps the original native module and adds independently validated optimizations. A module
487
+ * with no region above `minimumRegionWork` gets no control plan and runs untouched.
488
+ */
489
+ export function prepare(bytes, options = {}) {
490
+ admission(options);
491
+ const prepared = prepareTracked(bytes, options);
492
+ if (options.parallel !== 'off') {
493
+ try {
494
+ prepared.control = extract(prepared.original, prepareTracked, {
495
+ minimumRegionWork: options.minimumRegionWork,
496
+ assumedTripCount: options.assumedTripCount,
497
+ refused: (reason) => (prepared.controlReasons ??= []).push(reason)
498
+ });
499
+ }
500
+ catch (error) {
501
+ prepared.reasons.push(`control-flow extraction unavailable: ${error instanceof Error ? error.message : String(error)}`);
502
+ }
503
+ }
504
+ return prepared;
505
+ }
@@ -0,0 +1,27 @@
1
+ import type { ExecutionReport } from './node.ts';
2
+ import type { TransactionResult } from './transaction.ts';
3
+ export interface RegionCall {
4
+ export: string;
5
+ args: readonly (number | bigint)[];
6
+ }
7
+ /** Owns only effect-free regions. The original Wasm stack remains the coordinator. */
8
+ export declare class Coordinator {
9
+ #private;
10
+ readonly report: ExecutionReport;
11
+ constructor(options: {
12
+ memory: WebAssembly.Memory;
13
+ workerMemory: WebAssembly.Memory;
14
+ width: number;
15
+ profile: boolean;
16
+ /** Wasm global the generated barriers read; raised while regions are queued or running. */
17
+ pending?: {
18
+ value: unknown;
19
+ };
20
+ dispatch: (worker: number, calls: RegionCall[]) => Promise<TransactionResult[]>;
21
+ native: (call: RegionCall) => void;
22
+ });
23
+ enqueue(call: RegionCall): Promise<void> | undefined;
24
+ /** Bounded polling also joins an earlier trapping region before an infinite loop. */
25
+ poll(): Promise<void> | undefined;
26
+ flush(): Promise<void> | undefined;
27
+ }