@fraczak/k 8.9.0 → 9.1.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/CHANGELOG.md +28 -0
- package/DOCS/ARCHITECTURE.md +5 -4
- package/DOCS/DICTIONARY.md +2 -2
- package/DOCS/FILE_FORMATS.md +11 -9
- package/DOCS/KIR_V1.md +5 -1
- package/DOCS/KTVM_SPEC.md +907 -0
- package/DOCS/KVM_EXECUTION_MODEL.md +3 -2
- package/DOCS/KVM_VS_KTVM_COMPARATIVE_STUDY.md +127 -0
- package/DOCS/PROFILING_AND_TRACING.md +13 -4
- package/DOCS/README.md +3 -2
- package/DOCS/REPL.md +16 -12
- package/README.md +138 -2
- package/backend-api.mjs +31 -16
- package/backends/llvm/README.md +4 -5
- package/backends/llvm/bin/k-llvm-build.mjs +7 -19
- package/backends/llvm/bin/k-llvm-compile.mjs +6 -18
- package/backends/llvm/bin/k-llvm.mjs +11 -33
- package/backends/llvm/src/cli.mjs +2 -12
- package/backends/llvm/src/executable.mjs +7 -95
- package/backends/llvm/src/kvm2llvm.mjs +1 -7
- package/backends/llvm/src/llvm.mjs +4 -113
- package/backends/llvm/tests/k-llvm-run.mjs +1 -6
- package/backends/llvm/tests/perf-support.mjs +3 -5
- package/backends/llvm/tests/test-llvm.mjs +2 -16
- package/backends/wasm/README.md +7 -3
- package/backends/wasm/bin/k-wasm-compile.mjs +4 -7
- package/backends/wasm/bin/k-wasm.mjs +4 -6
- package/backends/wasm/src/cli.mjs +8 -24
- package/backends/wasm/src/wasm.mjs +60 -57
- package/backends/wasm/tests/test-wasm.mjs +41 -2
- package/browser/repl-browser.mjs +9 -8
- package/browser/shims/buffer.mjs +31 -2
- package/browser/shims/child_process.mjs +26 -0
- package/browser/shims/fs.mjs +3 -1
- package/codecs/runtime/prefix-codec.mjs +67 -1
- package/conformance/run.mjs +17 -2
- package/harness/adapters/ktvm-llvm.mjs +118 -0
- package/harness/adapters/ktvm-wasm.mjs +104 -0
- package/harness/adapters/ktvm.mjs +133 -0
- package/harness/registry.mjs +9 -0
- package/ktvm/ast.mjs +218 -0
- package/ktvm/bit-deque.mjs +497 -0
- package/ktvm/fixtures/integer-streaming.k +477 -0
- package/ktvm/index.mjs +130 -0
- package/ktvm/llvm/index.mjs +202 -0
- package/ktvm/llvm/lower-c.mjs +1258 -0
- package/ktvm/llvm/runtime.h +3542 -0
- package/ktvm/llvm/test-llvm.mjs +476 -0
- package/ktvm/lower-kir.mjs +2221 -0
- package/ktvm/optimize/fuse-kernel.mjs +2111 -0
- package/ktvm/optimize/index.mjs +116 -0
- package/ktvm/optimize/mwtr.mjs +283 -0
- package/ktvm/optimize/simplify-procs.mjs +5250 -0
- package/ktvm/optimize/synthesize-tables.mjs +1105 -0
- package/ktvm/parser.mjs +1101 -0
- package/ktvm/printer.mjs +281 -0
- package/ktvm/schema.mjs +1134 -0
- package/ktvm/specialize.mjs +538 -0
- package/ktvm/test-conformance.mjs +597 -0
- package/ktvm/test-ktvm.mjs +1805 -0
- package/ktvm/test-optimize.mjs +598 -0
- package/ktvm/validator.mjs +1280 -0
- package/ktvm/vm.mjs +2225 -0
- package/ktvm/wasm/index.mjs +331 -0
- package/ktvm/wasm/lower-wasm.mjs +1272 -0
- package/ktvm/wasm/runtime.wat +4404 -0
- package/ktvm/wasm/test-wasm.mjs +429 -0
- package/ktvm/wire.mjs +679 -0
- package/package.json +1 -9
- package/paper/Makefile +8 -5
- package/paper/k-transducer-compiler.pdf +0 -0
- package/paper/k-transducer-compiler.tex +658 -0
- package/paper/replay-diagnostic.mjs +63 -0
- package/repl.mjs +101 -20
- package/scripts/build-repl-html.mjs +40 -18
- package/scripts/perf-bigint-compare.mjs +12 -16
- package/scripts/perf-ieee.mjs +14 -232
- package/scripts/perf-int.mjs +16 -274
- package/scripts/perf-multiplication.mjs +116 -121
- package/scripts/perf-poly.mjs +9 -263
- package/scripts/run-tests.mjs +5 -2
- package/scripts/test-package.mjs +15 -3
- package/tests/README.md +3 -3
- package/tests/test-repl-html.mjs +72 -15
- package/tests/test-repl.mjs +24 -17
- package/DOCS/POLYMORPHIC_IR.md +0 -86
- package/access-table.mjs +0 -343
- package/pkir.mjs +0 -772
- package/tests/test-access-table.mjs +0 -213
- package/tests/test-pkir.mjs +0 -530
|
@@ -0,0 +1,538 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Boundary Envelope Compatibility & Shape Refinement (`kTVM-P` -> `kTVM`).
|
|
3
|
+
*
|
|
4
|
+
* Implements DOCS/KTVM_SPEC.md §4:
|
|
5
|
+
* 1. Unifies incoming closed `k-wire` envelope schema `S_in` against `@entry`'s
|
|
6
|
+
* contract (raising `KTVMSchemaError` on contradiction).
|
|
7
|
+
* 2. Propagates bound concrete schemas through reachable procedures, deriving
|
|
8
|
+
* concrete closed output schema(s) `S_out`.
|
|
9
|
+
* 3. Computes per-procedure access profiles: splits accessed concrete products
|
|
10
|
+
* while preserving uninspected opaque `$X` payloads as a single `BitDeque`.
|
|
11
|
+
* 4. Resolves union tag bit-widths, erases proven `guard`s, prunes dead
|
|
12
|
+
* `switch` arms, collapses Moore-equivalent `coerce` into `splice`.
|
|
13
|
+
* 5. Validates and caches the resulting 100% envelope-free `mono` module by
|
|
14
|
+
* `(moduleKey, entry, MooreKey(S_in))`.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { KTVMSchemaError, S, cloneAst, createModule } from "./ast.mjs";
|
|
18
|
+
import {
|
|
19
|
+
compareLabels,
|
|
20
|
+
compileSchemaExprToPlist,
|
|
21
|
+
intersectSchemas,
|
|
22
|
+
isClosedPlist,
|
|
23
|
+
mooreKey,
|
|
24
|
+
mooreMinimize,
|
|
25
|
+
plistToSchemaAst,
|
|
26
|
+
productFieldInfo,
|
|
27
|
+
productFields,
|
|
28
|
+
schemasEquivalent,
|
|
29
|
+
subPlist,
|
|
30
|
+
substituteSchemaExpr,
|
|
31
|
+
unionTagInfo,
|
|
32
|
+
unifyContractWithConcrete
|
|
33
|
+
} from "./schema.mjs";
|
|
34
|
+
import { validateModule } from "./validator.mjs";
|
|
35
|
+
import { printModule } from "./printer.mjs";
|
|
36
|
+
|
|
37
|
+
const SPECIALIZE_CACHE = new Map();
|
|
38
|
+
|
|
39
|
+
function sanitizeSuffix(str) {
|
|
40
|
+
return str.replace(/[^A-Za-z0-9_]/g, "_").replace(/^_+/, "").slice(0, 24) || "s";
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Compute which port indices / local channels have fields accessed (`demux`/`project`/`mux`)
|
|
45
|
+
* inside a procedure body. Used for access-profile port splitting.
|
|
46
|
+
*/
|
|
47
|
+
function analyzeProcAccesses(proc) {
|
|
48
|
+
const accessedVars = new Set();
|
|
49
|
+
function walk(stmts) {
|
|
50
|
+
for (const s of stmts) {
|
|
51
|
+
if (s.op === "demux" || s.op === "project") {
|
|
52
|
+
accessedVars.add(s.src);
|
|
53
|
+
} else if (s.op === "mux") {
|
|
54
|
+
accessedVars.add(s.dst);
|
|
55
|
+
} else if (s.op === "switch") {
|
|
56
|
+
for (const arm of s.arms) walk(arm.body);
|
|
57
|
+
if (s.defaultBody) walk(s.defaultBody);
|
|
58
|
+
} else if (s.op === "spec") {
|
|
59
|
+
for (const br of s.branches) walk(br.body);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
walk(proc.body);
|
|
64
|
+
return accessedVars;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Specialize a `kTVM-P` (or already `mono`) module for a concrete closed `k-wire`
|
|
69
|
+
* input envelope schema `inputPlist` (or array of `inputPlists` for multi-port entries).
|
|
70
|
+
*
|
|
71
|
+
* Returns `{ module, entry, inputPlists, outputPlists, cached, accessProfiles }`.
|
|
72
|
+
*/
|
|
73
|
+
export function specializeKTVM(mod, entryName, inputPlistOrList, { useCache = true, validate = true } = {}) {
|
|
74
|
+
const entry = entryName || mod.entry;
|
|
75
|
+
if (!entry) {
|
|
76
|
+
throw new KTVMSchemaError("specializeKTVM requires an entry procedure name");
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const inputPlists = Array.isArray(inputPlistOrList) && Array.isArray(inputPlistOrList[0]) && typeof inputPlistOrList[0][0] === "string"
|
|
80
|
+
? [inputPlistOrList]
|
|
81
|
+
: inputPlistOrList;
|
|
82
|
+
|
|
83
|
+
if (!Array.isArray(inputPlists) || inputPlists.length === 0) {
|
|
84
|
+
throw new KTVMSchemaError("specializeKTVM requires at least one concrete input envelope plist");
|
|
85
|
+
}
|
|
86
|
+
for (let i = 0; i < inputPlists.length; i++) {
|
|
87
|
+
if (!isClosedPlist(inputPlists[i])) {
|
|
88
|
+
throw new KTVMSchemaError(`Input envelope ${i} must be a closed k-wire property-list graph`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const normalizedInputs = inputPlists.map((p) => mooreMinimize(p, 0).plist);
|
|
93
|
+
const inputKeys = normalizedInputs.map((p) => mooreKey(p, 0));
|
|
94
|
+
|
|
95
|
+
// Fast cache check
|
|
96
|
+
let cacheKey = null;
|
|
97
|
+
if (useCache) {
|
|
98
|
+
const modKey = printModule(mod);
|
|
99
|
+
cacheKey = `${modKey}::${entry}::${inputKeys.join("|")}`;
|
|
100
|
+
if (SPECIALIZE_CACHE.has(cacheKey)) {
|
|
101
|
+
return { ...SPECIALIZE_CACHE.get(cacheKey), cached: true };
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const schemaDecls = new Map((mod.schemas || []).map((s) => [s.name, s]));
|
|
106
|
+
const procMap = new Map((mod.procs || []).map((p) => [p.name, p]));
|
|
107
|
+
const kernelMap = new Map((mod.kernels || []).map((k) => [k.name, k]));
|
|
108
|
+
|
|
109
|
+
// If already `mono`, just verify boundary compatibility and derive outputPlists!
|
|
110
|
+
if (mod.layer === "mono") {
|
|
111
|
+
const target = procMap.get(entry) || kernelMap.get(entry);
|
|
112
|
+
if (!target) throw new KTVMSchemaError(`Unknown entry '${entry}'`);
|
|
113
|
+
if (target.inputs.length !== normalizedInputs.length) {
|
|
114
|
+
throw new KTVMSchemaError(
|
|
115
|
+
`Entry '${entry}' expects ${target.inputs.length} input(s), got ${normalizedInputs.length}`
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
for (let i = 0; i < target.inputs.length; i++) {
|
|
119
|
+
const expected = compileSchemaExprToPlist(target.inputs[i].schema, schemaDecls, { allowOpen: false });
|
|
120
|
+
if (!schemasEquivalent(expected, 0, normalizedInputs[i], 0)) {
|
|
121
|
+
throw new KTVMSchemaError(`Input envelope ${i} does not match mono entry '${entry}' contract`);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
const outputPlists = target.outputs.map((o) =>
|
|
125
|
+
mooreMinimize(compileSchemaExprToPlist(o.schema, schemaDecls, { allowOpen: false }), 0).plist
|
|
126
|
+
);
|
|
127
|
+
const result = {
|
|
128
|
+
module: mod,
|
|
129
|
+
entry,
|
|
130
|
+
inputPlists: normalizedInputs,
|
|
131
|
+
outputPlists,
|
|
132
|
+
cached: false,
|
|
133
|
+
accessProfiles: {}
|
|
134
|
+
};
|
|
135
|
+
if (cacheKey) SPECIALIZE_CACHE.set(cacheKey, result);
|
|
136
|
+
return result;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// --- Poly `kTVM-P` -> Mono `kTVM` Specialization ---
|
|
140
|
+
const entryProc = procMap.get(entry);
|
|
141
|
+
if (!entryProc) {
|
|
142
|
+
throw new KTVMSchemaError(`Unknown entry procedure '${entry}'`);
|
|
143
|
+
}
|
|
144
|
+
if (entryProc.inputs.length !== normalizedInputs.length) {
|
|
145
|
+
throw new KTVMSchemaError(
|
|
146
|
+
`Entry '${entry}' expects ${entryProc.inputs.length} input(s), got ${normalizedInputs.length}`
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// Step 1: Unify every input envelope against entry's contract to bind `$X`
|
|
151
|
+
const entryBindings = new Map();
|
|
152
|
+
for (let i = 0; i < entryProc.inputs.length; i++) {
|
|
153
|
+
const b = unifyContractWithConcrete(
|
|
154
|
+
entryProc.inputs[i].schema,
|
|
155
|
+
schemaDecls,
|
|
156
|
+
entryProc.params || [],
|
|
157
|
+
normalizedInputs[i],
|
|
158
|
+
0
|
|
159
|
+
);
|
|
160
|
+
for (const [param, pl] of b.entries()) {
|
|
161
|
+
if (entryBindings.has(param)) {
|
|
162
|
+
const prev = entryBindings.get(param);
|
|
163
|
+
const inter = intersectSchemas(prev, pl);
|
|
164
|
+
if (mooreKey(prev, 0) !== mooreKey(pl, 0) || mooreKey(inter, 0) !== mooreKey(prev, 0)) {
|
|
165
|
+
throw new KTVMSchemaError(`Conflicting bindings for schema parameter '${param}' across inputs`);
|
|
166
|
+
}
|
|
167
|
+
} else {
|
|
168
|
+
entryBindings.set(param, pl);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
for (const param of entryProc.params || []) {
|
|
173
|
+
if (!entryBindings.has(param)) {
|
|
174
|
+
throw new KTVMSchemaError(`Entry schema parameter '${param}' could not be bound from input envelope`);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// Schema registry for the emitted concrete `mono` module (deduplicated by Moore key!)
|
|
179
|
+
const emittedSchemas = new Map(); // mooreKey -> { name, expr, plist }
|
|
180
|
+
const emittedSchemaDecls = [];
|
|
181
|
+
let schemaSeq = 0;
|
|
182
|
+
|
|
183
|
+
function internConcretePlist(plist, hint = "S") {
|
|
184
|
+
const min = mooreMinimize(plist, 0);
|
|
185
|
+
const [kind, edges] = min.plist[0];
|
|
186
|
+
if (kind === "closed-product" && edges.length === 0) {
|
|
187
|
+
return { expr: S.unit(), plist: min.plist };
|
|
188
|
+
}
|
|
189
|
+
if (emittedSchemas.has(min.key)) {
|
|
190
|
+
return emittedSchemas.get(min.key);
|
|
191
|
+
}
|
|
192
|
+
const prefix = `$${sanitizeSuffix(hint)}_${schemaSeq++}`;
|
|
193
|
+
const { decls, rootExpr } = plistToSchemaAst(min.plist, prefix);
|
|
194
|
+
for (const d of decls) emittedSchemaDecls.push(d);
|
|
195
|
+
const rec = { expr: rootExpr, plist: min.plist };
|
|
196
|
+
emittedSchemas.set(min.key, rec);
|
|
197
|
+
return rec;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// Compile a schema AST expression under `paramMap: Map<$X, concretePlist>` to concrete plist
|
|
201
|
+
function evalConcreteSchema(expr, paramMap, concreteFallback = null) {
|
|
202
|
+
// Replace each bound parameter `$X` with a synthetic named schema pointing to its concrete plist
|
|
203
|
+
const localDecls = new Map(schemaDecls);
|
|
204
|
+
const paramExprEnv = new Map();
|
|
205
|
+
for (const [pName, pPlist] of paramMap.entries()) {
|
|
206
|
+
const interned = internConcretePlist(pPlist, pName.slice(1));
|
|
207
|
+
for (const d of emittedSchemaDecls) localDecls.set(d.name, d);
|
|
208
|
+
paramExprEnv.set(pName, interned.expr);
|
|
209
|
+
}
|
|
210
|
+
const subst = substituteSchemaExpr(expr, paramExprEnv);
|
|
211
|
+
const pl = compileSchemaExprToPlist(subst, localDecls, { allowOpen: true });
|
|
212
|
+
if (isClosedPlist(pl)) {
|
|
213
|
+
return mooreMinimize(pl, 0).plist;
|
|
214
|
+
}
|
|
215
|
+
if (concreteFallback) {
|
|
216
|
+
const inter = intersectSchemas(pl, concreteFallback);
|
|
217
|
+
if (isClosedPlist(inter)) return mooreMinimize(inter, 0).plist;
|
|
218
|
+
}
|
|
219
|
+
throw new KTVMSchemaError(
|
|
220
|
+
`Schema could not be closed statically during boundary specialization (fallback to kVM required)`
|
|
221
|
+
);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// Memoize specialized procedures by `(procName, paramKeys, inputKeys)`
|
|
225
|
+
const specProcMemo = new Map();
|
|
226
|
+
const emittedProcs = [];
|
|
227
|
+
const accessProfiles = {};
|
|
228
|
+
let procSeq = 0;
|
|
229
|
+
let freshChanSeq = 0;
|
|
230
|
+
|
|
231
|
+
function freshVar(prefix) {
|
|
232
|
+
return `%_${prefix}_${freshChanSeq++}`;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function specializeProc(procName, paramBindings, actualInputPlists) {
|
|
236
|
+
const proc = procMap.get(procName);
|
|
237
|
+
if (!proc) throw new KTVMSchemaError(`Unknown procedure '${procName}'`);
|
|
238
|
+
const pKeys = (proc.params || []).map((p) => mooreKey(paramBindings.get(p), 0)).join(",");
|
|
239
|
+
const inKeys = actualInputPlists.map((p) => mooreKey(p, 0)).join(",");
|
|
240
|
+
const memoKey = `${procName}[${pKeys}](${inKeys})`;
|
|
241
|
+
if (specProcMemo.has(memoKey)) return specProcMemo.get(memoKey);
|
|
242
|
+
|
|
243
|
+
const specName = procSeq === 0 ? `${procName}__spec` : `${procName}__spec${procSeq}`;
|
|
244
|
+
procSeq++;
|
|
245
|
+
|
|
246
|
+
// Record access profile (which product inputs/locals are accessed vs kept opaque)
|
|
247
|
+
const accessedVars = analyzeProcAccesses(proc);
|
|
248
|
+
accessProfiles[specName] = {
|
|
249
|
+
sourceProc: procName,
|
|
250
|
+
accessedVars: [...accessedVars],
|
|
251
|
+
opaqueParams: (proc.params || []).filter((p) => {
|
|
252
|
+
const pl = paramBindings.get(p);
|
|
253
|
+
return pl && pl[0][0] === "closed-product" && pl[0][1].length > 0;
|
|
254
|
+
})
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
// Derive concrete input & output port schemas
|
|
258
|
+
const concreteInputs = proc.inputs.map((inp, idx) => {
|
|
259
|
+
const pl = evalConcreteSchema(inp.schema, paramBindings, actualInputPlists[idx]);
|
|
260
|
+
const inter = intersectSchemas(pl, actualInputPlists[idx]);
|
|
261
|
+
const rec = internConcretePlist(inter, inp.name.slice(1));
|
|
262
|
+
return { name: inp.name, schema: rec.expr, plist: rec.plist };
|
|
263
|
+
});
|
|
264
|
+
|
|
265
|
+
const concreteOutputs = proc.outputs.map((out) => {
|
|
266
|
+
const pl = evalConcreteSchema(out.schema, paramBindings);
|
|
267
|
+
const rec = internConcretePlist(pl, out.name.slice(1));
|
|
268
|
+
return { name: out.name, schema: rec.expr, plist: rec.plist };
|
|
269
|
+
});
|
|
270
|
+
|
|
271
|
+
const specRecord = {
|
|
272
|
+
name: specName,
|
|
273
|
+
inputs: concreteInputs,
|
|
274
|
+
outputs: concreteOutputs
|
|
275
|
+
};
|
|
276
|
+
specProcMemo.set(memoKey, specRecord);
|
|
277
|
+
|
|
278
|
+
// Channel plist environment for rewriting statements
|
|
279
|
+
const chanPlistMap = new Map();
|
|
280
|
+
for (const p of concreteInputs) chanPlistMap.set(p.name, p.plist);
|
|
281
|
+
for (const p of concreteOutputs) chanPlistMap.set(p.name, p.plist);
|
|
282
|
+
|
|
283
|
+
const newBody = rewriteBlock(proc.body, paramBindings, chanPlistMap);
|
|
284
|
+
|
|
285
|
+
emittedProcs.push({
|
|
286
|
+
name: specName,
|
|
287
|
+
params: [],
|
|
288
|
+
inputs: concreteInputs.map(({ name, schema }) => ({ name, schema })),
|
|
289
|
+
outputs: concreteOutputs.map(({ name, schema }) => ({ name, schema })),
|
|
290
|
+
attrs: [...(proc.attrs || [])],
|
|
291
|
+
body: newBody
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
return specRecord;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function rewriteBlock(stmts, paramBindings, outerChanPlists) {
|
|
298
|
+
const chanPlists = new Map(outerChanPlists);
|
|
299
|
+
const out = [];
|
|
300
|
+
|
|
301
|
+
for (const s of stmts) {
|
|
302
|
+
switch (s.op) {
|
|
303
|
+
case "chan": {
|
|
304
|
+
// Wait: if a local chan has an open/any schema, try direct eval; otherwise defer?
|
|
305
|
+
const pl = evalConcreteSchema(s.schema, paramBindings);
|
|
306
|
+
const rec = internConcretePlist(pl, s.name.slice(1));
|
|
307
|
+
chanPlists.set(s.name, rec.plist);
|
|
308
|
+
out.push({ op: "chan", name: s.name, schema: rec.expr });
|
|
309
|
+
break;
|
|
310
|
+
}
|
|
311
|
+
case "barrier":
|
|
312
|
+
case "gate":
|
|
313
|
+
case "splice":
|
|
314
|
+
case "const_unit":
|
|
315
|
+
case "tee":
|
|
316
|
+
case "wrap":
|
|
317
|
+
case "match":
|
|
318
|
+
out.push(cloneAst(s));
|
|
319
|
+
break;
|
|
320
|
+
case "drain": {
|
|
321
|
+
const srcPl = chanPlists.get(s.src);
|
|
322
|
+
const pl = evalConcreteSchema(s.schema, paramBindings, srcPl);
|
|
323
|
+
const rec = internConcretePlist(pl, "d");
|
|
324
|
+
out.push({ op: "drain", src: s.src, schema: rec.expr, barrier: s.barrier });
|
|
325
|
+
break;
|
|
326
|
+
}
|
|
327
|
+
case "coerce": {
|
|
328
|
+
const sPl = evalConcreteSchema(s.srcSchema, paramBindings, chanPlists.get(s.src));
|
|
329
|
+
const dPl = evalConcreteSchema(s.dstSchema, paramBindings, chanPlists.get(s.dst));
|
|
330
|
+
if (schemasEquivalent(sPl, 0, dPl, 0)) {
|
|
331
|
+
// Collapse Moore-equivalent coerce into zero-copy splice!
|
|
332
|
+
out.push({ op: "splice", src: s.src, dst: s.dst });
|
|
333
|
+
} else {
|
|
334
|
+
const sRec = internConcretePlist(sPl, "cs");
|
|
335
|
+
const dRec = internConcretePlist(dPl, "cd");
|
|
336
|
+
out.push({ op: "coerce", src: s.src, srcSchema: sRec.expr, dst: s.dst, dstSchema: dRec.expr });
|
|
337
|
+
}
|
|
338
|
+
break;
|
|
339
|
+
}
|
|
340
|
+
case "demux": {
|
|
341
|
+
const pPl = evalConcreteSchema(s.schema, paramBindings, chanPlists.get(s.src));
|
|
342
|
+
const rec = internConcretePlist(pPl, "p");
|
|
343
|
+
out.push({ op: "demux", src: s.src, schema: rec.expr, fields: cloneAst(s.fields) });
|
|
344
|
+
break;
|
|
345
|
+
}
|
|
346
|
+
case "mux": {
|
|
347
|
+
const pPl = evalConcreteSchema(s.schema, paramBindings, chanPlists.get(s.dst));
|
|
348
|
+
const rec = internConcretePlist(pPl, "p");
|
|
349
|
+
out.push({ op: "mux", fields: cloneAst(s.fields), dst: s.dst, schema: rec.expr });
|
|
350
|
+
break;
|
|
351
|
+
}
|
|
352
|
+
case "guard": {
|
|
353
|
+
// Verify concrete channel schema satisfies guard `?$P`, then erase to `splice`!
|
|
354
|
+
const srcPl = chanPlists.get(s.src);
|
|
355
|
+
const guardPl = compileSchemaExprToPlist(
|
|
356
|
+
substituteSchemaExpr(s.schema, buildParamExprMap(paramBindings)),
|
|
357
|
+
buildMergedDecls(),
|
|
358
|
+
{ allowOpen: true }
|
|
359
|
+
);
|
|
360
|
+
const inter = intersectSchemas(guardPl, srcPl);
|
|
361
|
+
if (!isClosedPlist(inter)) {
|
|
362
|
+
throw new KTVMSchemaError(`Guard on '${s.src}' did not yield a closed schema`);
|
|
363
|
+
}
|
|
364
|
+
const dstPl = chanPlists.get(s.dst);
|
|
365
|
+
if (dstPl && schemasEquivalent(srcPl, 0, dstPl, 0)) {
|
|
366
|
+
out.push({ op: "splice", src: s.src, dst: s.dst });
|
|
367
|
+
} else {
|
|
368
|
+
const sRec = internConcretePlist(srcPl, "gs");
|
|
369
|
+
const dRec = internConcretePlist(dstPl || inter, "gd");
|
|
370
|
+
out.push({ op: "coerce", src: s.src, srcSchema: sRec.expr, dst: s.dst, dstSchema: dRec.expr });
|
|
371
|
+
}
|
|
372
|
+
break;
|
|
373
|
+
}
|
|
374
|
+
case "project": {
|
|
375
|
+
// Lower polymorphic `project .f %src -> %dst` into `demux` + `drain` + `barrier` + `gate`!
|
|
376
|
+
const srcPl = chanPlists.get(s.src);
|
|
377
|
+
const pf = productFields(srcPl, 0);
|
|
378
|
+
if (!pf) {
|
|
379
|
+
throw new KTVMSchemaError(`project .${s.field} requires concrete product on '${s.src}'`);
|
|
380
|
+
}
|
|
381
|
+
const targetField = productFieldInfo(srcPl, 0, s.field);
|
|
382
|
+
if (!targetField) {
|
|
383
|
+
throw new KTVMSchemaError(`Product '${s.src}' has no field '${s.field}'`);
|
|
384
|
+
}
|
|
385
|
+
if (pf.length === 1) {
|
|
386
|
+
// Single-field product: demux directly to %dst!
|
|
387
|
+
const pRec = internConcretePlist(srcPl, "proj");
|
|
388
|
+
out.push({ op: "demux", src: s.src, schema: pRec.expr, fields: [{ label: s.field, name: s.dst }] });
|
|
389
|
+
} else {
|
|
390
|
+
const bar = freshVar("bar");
|
|
391
|
+
out.push({ op: "barrier", name: bar });
|
|
392
|
+
const demuxFields = [];
|
|
393
|
+
let chosenVar = null;
|
|
394
|
+
const drains = [];
|
|
395
|
+
for (const f of pf) {
|
|
396
|
+
const fSub = subPlist(srcPl, f.targetId);
|
|
397
|
+
const fRec = internConcretePlist(fSub, f.label);
|
|
398
|
+
const v = freshVar(f.label);
|
|
399
|
+
out.push({ op: "chan", name: v, schema: fRec.expr });
|
|
400
|
+
demuxFields.push({ label: f.label, name: v });
|
|
401
|
+
if (f.label === s.field) {
|
|
402
|
+
chosenVar = v;
|
|
403
|
+
} else {
|
|
404
|
+
drains.push({ op: "drain", src: v, schema: fRec.expr, barrier: bar });
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
const pRec = internConcretePlist(srcPl, "proj");
|
|
408
|
+
out.push({ op: "demux", src: s.src, schema: pRec.expr, fields: demuxFields });
|
|
409
|
+
for (const dr of drains) out.push(dr);
|
|
410
|
+
out.push({ op: "gate", barrier: bar, src: chosenVar, dst: s.dst });
|
|
411
|
+
}
|
|
412
|
+
break;
|
|
413
|
+
}
|
|
414
|
+
case "spawn": {
|
|
415
|
+
const targetProc = procMap.get(s.target);
|
|
416
|
+
if (!targetProc) throw new KTVMSchemaError(`Unknown proc '${s.target}'`);
|
|
417
|
+
const childBindings = new Map();
|
|
418
|
+
for (let i = 0; i < (targetProc.params || []).length; i++) {
|
|
419
|
+
const argPl = evalConcreteSchema(s.schemaArgs[i], paramBindings);
|
|
420
|
+
childBindings.set(targetProc.params[i], argPl);
|
|
421
|
+
}
|
|
422
|
+
const actualIns = s.inputs.map((v) => chanPlists.get(v));
|
|
423
|
+
const specTarget = specializeProc(s.target, childBindings, actualIns);
|
|
424
|
+
out.push({
|
|
425
|
+
op: "spawn",
|
|
426
|
+
target: specTarget.name,
|
|
427
|
+
schemaArgs: [],
|
|
428
|
+
inputs: [...s.inputs],
|
|
429
|
+
outputs: [...s.outputs],
|
|
430
|
+
after: s.after,
|
|
431
|
+
token: s.token
|
|
432
|
+
});
|
|
433
|
+
break;
|
|
434
|
+
}
|
|
435
|
+
case "exec":
|
|
436
|
+
out.push(cloneAst(s));
|
|
437
|
+
break;
|
|
438
|
+
case "switch": {
|
|
439
|
+
// Prune dead arms whose leading tag is absent from the concrete input union!
|
|
440
|
+
const liveArms = [];
|
|
441
|
+
for (const arm of s.arms) {
|
|
442
|
+
let reachable = true;
|
|
443
|
+
for (let j = 0; j < arm.patterns.length; j++) {
|
|
444
|
+
const pat = arm.patterns[j];
|
|
445
|
+
if (pat.kind === "tag") {
|
|
446
|
+
const pl = chanPlists.get(s.inputs[j]);
|
|
447
|
+
if (!unionTagInfo(pl, 0, pat.tag)) {
|
|
448
|
+
reachable = false;
|
|
449
|
+
break;
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
if (reachable) {
|
|
454
|
+
liveArms.push({
|
|
455
|
+
patterns: cloneAst(arm.patterns),
|
|
456
|
+
body: rewriteBlock(arm.body, paramBindings, chanPlists)
|
|
457
|
+
});
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
const newDefault = s.defaultBody
|
|
461
|
+
? rewriteBlock(s.defaultBody, paramBindings, chanPlists)
|
|
462
|
+
: null;
|
|
463
|
+
out.push({
|
|
464
|
+
op: "switch",
|
|
465
|
+
inputs: [...s.inputs],
|
|
466
|
+
arms: liveArms,
|
|
467
|
+
defaultBody: newDefault
|
|
468
|
+
});
|
|
469
|
+
break;
|
|
470
|
+
}
|
|
471
|
+
case "spec": {
|
|
472
|
+
const newBranches = s.branches.map((br) => ({
|
|
473
|
+
index: br.index,
|
|
474
|
+
body: rewriteBlock(br.body, paramBindings, chanPlists)
|
|
475
|
+
}));
|
|
476
|
+
out.push({
|
|
477
|
+
op: "spec",
|
|
478
|
+
inputs: [...s.inputs],
|
|
479
|
+
outputs: [...s.outputs],
|
|
480
|
+
branches: newBranches
|
|
481
|
+
});
|
|
482
|
+
break;
|
|
483
|
+
}
|
|
484
|
+
default:
|
|
485
|
+
out.push(cloneAst(s));
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
return out;
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
function buildParamExprMap(paramBindings) {
|
|
492
|
+
const env = new Map();
|
|
493
|
+
for (const [pName, pPlist] of paramBindings.entries()) {
|
|
494
|
+
env.set(pName, internConcretePlist(pPlist, pName.slice(1)).expr);
|
|
495
|
+
}
|
|
496
|
+
return env;
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
function buildMergedDecls() {
|
|
500
|
+
const m = new Map(schemaDecls);
|
|
501
|
+
for (const d of emittedSchemaDecls) m.set(d.name, d);
|
|
502
|
+
return m;
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
const rootSpec = specializeProc(entry, entryBindings, normalizedInputs);
|
|
506
|
+
|
|
507
|
+
const monoModule = createModule({
|
|
508
|
+
version: mod.version || "0.1",
|
|
509
|
+
layer: "mono",
|
|
510
|
+
entry: rootSpec.name,
|
|
511
|
+
schemas: emittedSchemaDecls,
|
|
512
|
+
procs: emittedProcs,
|
|
513
|
+
kernels: cloneAst(mod.kernels || []),
|
|
514
|
+
tables: cloneAst(mod.tables || [])
|
|
515
|
+
});
|
|
516
|
+
|
|
517
|
+
if (validate) {
|
|
518
|
+
validateModule(monoModule);
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
const result = {
|
|
522
|
+
module: monoModule,
|
|
523
|
+
entry: rootSpec.name,
|
|
524
|
+
inputPlists: rootSpec.inputs.map((i) => i.plist),
|
|
525
|
+
outputPlists: rootSpec.outputs.map((o) => o.plist),
|
|
526
|
+
cached: false,
|
|
527
|
+
accessProfiles
|
|
528
|
+
};
|
|
529
|
+
|
|
530
|
+
if (cacheKey) {
|
|
531
|
+
SPECIALIZE_CACHE.set(cacheKey, result);
|
|
532
|
+
}
|
|
533
|
+
return result;
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
export function clearSpecializationCache() {
|
|
537
|
+
SPECIALIZE_CACHE.clear();
|
|
538
|
+
}
|