tricu

A lazy functional language based on Tree Calculus
Log | Files | Refs | README | LICENSE

io-private.js (2262B)


      1 // Private native-adapter validation runner, not RuntimeSession IO dispatch.
      2 // Bare computations only; no facility implementation/capability advertisement.
      3 import { Core } from './io-core.js';
      4 import { canonicalNat } from './io-protocol.js';
      5 export function constructors(base) {
      6     const natural = (value) => {
      7         const bits = [];
      8         if (value < 0n)
      9             throw new Error('negative natural');
     10         for (; value; value >>= 1n)
     11             bits.push(value & 1n ? base.stem(base.leaf) : base.leaf);
     12         let out = base.leaf;
     13         for (let i = bits.length - 1; i >= 0; i--)
     14             out = base.fork(bits[i], out);
     15         return out;
     16     };
     17     return { ...base, natural, text(value) {
     18             let out = base.leaf;
     19             const chars = Array.from(value);
     20             for (let i = chars.length - 1; i >= 0; i--)
     21                 out = base.fork(natural(BigInt(chars[i].codePointAt(0))), out);
     22             return out;
     23         } };
     24 }
     25 export async function runPrivate(tree, action, identity, sweep) {
     26     const engine = new Core(tree, identity, action, [null, null, null], {
     27         request: (core, _scope, request) => () => core.wire.result(false, core.wire.problem('unsupported', `${request.group}/${request.operation}`)),
     28         release: () => { throw new Error('unexpected owned backend in private core probe'); }
     29     });
     30     sweep(engine.roots());
     31     for (let turns = 0; !engine.result; turns++) {
     32         const progress = engine.advance();
     33         sweep(engine.roots());
     34         if (!progress) {
     35             if (!engine.work.counts.pending)
     36                 throw new Error('private interpreter stalled');
     37             await engine.wait();
     38         }
     39         if (turns % 32 === 0)
     40             await new Promise(resolve => setTimeout(resolve, 0));
     41     }
     42     if (engine.hasFault)
     43         throw engine.fault;
     44     const out = engine.result;
     45     // Terminal diagnostics stay opaque, including when the test requests a number.
     46     const value = out.kind === 'completed' ? canonicalNat(tree, out.value, 64)?.toString() ?? null : null;
     47     return { kind: out.kind, value, cleanup: out.cleanup?.items.length ?? 0,
     48         tasks: engine.lifecycle.tasks.counts, resources: engine.lifecycle.resources.counts, host: engine.work.counts };
     49 }