@fraczak/k 8.8.0 → 9.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.
- 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 +902 -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 +6 -4
- package/DOCS/README.md +3 -2
- package/DOCS/REPL.md +16 -12
- package/README.md +132 -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 -5
- package/backends/llvm/src/llvm.mjs +4 -111
- 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 +0 -16
- package/backends/wasm/README.md +2 -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 +10 -56
- 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/djson.mjs +2 -3
- package/codecs/int.mjs +66 -14
- 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 +482 -0
- package/ktvm/fixtures/integer-streaming.k +477 -0
- package/ktvm/index.mjs +119 -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 +543 -0
- package/ktvm/specialize.mjs +538 -0
- package/ktvm/test-conformance.mjs +597 -0
- package/ktvm/test-ktvm.mjs +1376 -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 +4413 -0
- package/ktvm/wasm/test-wasm.mjs +426 -0
- package/ktvm/wire.mjs +489 -0
- package/lib/djson.k +175 -173
- package/lib/generic.k +82 -97
- package/lib/ieee.k +110 -115
- package/lib/integer.k +25 -31
- package/package.json +1 -9
- package/repl.mjs +101 -20
- package/scripts/build-repl-html.mjs +40 -18
- package/scripts/perf-bigint-compare.mjs +275 -0
- package/scripts/perf-ieee.mjs +9 -229
- package/scripts/perf-int.mjs +14 -272
- package/scripts/perf-multiplication.mjs +8 -54
- 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-djson-methods.mjs +0 -1
- package/tests/test-djson.mjs +0 -1
- package/tests/test-generic.mjs +5 -7
- package/tests/test-repl-html.mjs +72 -15
- package/tests/test-repl.mjs +27 -20
- package/tests/test-structural-values.mjs +1 -1
- 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
package/ktvm/schema.mjs
ADDED
|
@@ -0,0 +1,543 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* kTVM Schema & Wire Type System.
|
|
3
|
+
*
|
|
4
|
+
* Compiles kTVM schema AST expressions to canonical k-wire property-list graphs
|
|
5
|
+
* (`plist`), computes Moore minimal bisimulation quotients for zero-copy splice
|
|
6
|
+
* equivalence (`S1 ≡ S2`), derives prefix derivatives, and unifies polymorphic
|
|
7
|
+
* `kTVM-P` contracts against concrete `k-wire` envelopes using K's
|
|
8
|
+
* `intersectPropertyListPatterns`.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { intersectPropertyListPatterns } from "../codecs/runtime/codec.mjs";
|
|
12
|
+
import { choiceWidth } from "../codecs/runtime/prefix-codec.mjs";
|
|
13
|
+
import { KTVMSchemaError, S } from "./ast.mjs";
|
|
14
|
+
|
|
15
|
+
export function compareLabels(a, b) {
|
|
16
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function isClosedSchemaKind(kind) {
|
|
20
|
+
return kind === "closed-product" || kind === "closed-union";
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function isClosedPlist(plist) {
|
|
24
|
+
if (!Array.isArray(plist) || plist.length === 0) return false;
|
|
25
|
+
for (const node of plist) {
|
|
26
|
+
if (!Array.isArray(node) || node.length !== 2) return false;
|
|
27
|
+
if (!isClosedSchemaKind(node[0])) return false;
|
|
28
|
+
}
|
|
29
|
+
return true;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Substitute schema parameters `$X -> schemaExpr` inside a schema AST expression.
|
|
34
|
+
*/
|
|
35
|
+
export function substituteSchemaExpr(expr, env) {
|
|
36
|
+
if (!expr) return expr;
|
|
37
|
+
switch (expr.kind) {
|
|
38
|
+
case "unit":
|
|
39
|
+
case "any":
|
|
40
|
+
return expr;
|
|
41
|
+
case "ref": {
|
|
42
|
+
if ((!expr.args || expr.args.length === 0) && env.has(expr.name)) {
|
|
43
|
+
return env.get(expr.name);
|
|
44
|
+
}
|
|
45
|
+
return S.ref(expr.name, (expr.args || []).map((a) => substituteSchemaExpr(a, env)));
|
|
46
|
+
}
|
|
47
|
+
case "product":
|
|
48
|
+
return S.product(expr.fields.map((f) => ({ label: f.label, schema: substituteSchemaExpr(f.schema, env) })));
|
|
49
|
+
case "open_product":
|
|
50
|
+
return S.openProduct(expr.fields.map((f) => ({ label: f.label, schema: substituteSchemaExpr(f.schema, env) })));
|
|
51
|
+
case "union":
|
|
52
|
+
return S.union(expr.fields.map((f) => ({ label: f.label, schema: substituteSchemaExpr(f.schema, env) })));
|
|
53
|
+
case "open_union":
|
|
54
|
+
return S.openUnion(expr.fields.map((f) => ({ label: f.label, schema: substituteSchemaExpr(f.schema, env) })));
|
|
55
|
+
default:
|
|
56
|
+
throw new Error(`Unknown schema expr kind: ${expr.kind}`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function exprStructuralKey(expr) {
|
|
61
|
+
switch (expr.kind) {
|
|
62
|
+
case "unit": return "U";
|
|
63
|
+
case "any": return "A";
|
|
64
|
+
case "ref":
|
|
65
|
+
return expr.args && expr.args.length > 0
|
|
66
|
+
? `R(${expr.name}[${expr.args.map(exprStructuralKey).join(",")}])`
|
|
67
|
+
: `R(${expr.name})`;
|
|
68
|
+
case "product":
|
|
69
|
+
case "open_product":
|
|
70
|
+
case "union":
|
|
71
|
+
case "open_union": {
|
|
72
|
+
const sorted = [...expr.fields].sort((a, b) => compareLabels(a.label, b.label));
|
|
73
|
+
return `${expr.kind}(${sorted.map((f) => `${JSON.stringify(f.label)}:${exprStructuralKey(f.schema)}`).join(",")})`;
|
|
74
|
+
}
|
|
75
|
+
default:
|
|
76
|
+
throw new Error(`Unknown schema expr kind: ${expr.kind}`);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Compile a closed (or open, if allowOpen=true) kTVM schema expression against
|
|
82
|
+
* a map of schema declarations into a canonical k-wire property-list graph.
|
|
83
|
+
*/
|
|
84
|
+
export function compileSchemaExprToPlist(expr, schemaDecls, { paramBindings = new Map(), allowOpen = false } = {}) {
|
|
85
|
+
const declMap = schemaDecls instanceof Map
|
|
86
|
+
? schemaDecls
|
|
87
|
+
: new Map((schemaDecls || []).map((d) => [d.name, d]));
|
|
88
|
+
|
|
89
|
+
const nodes = [];
|
|
90
|
+
const memo = new Map();
|
|
91
|
+
|
|
92
|
+
function visit(curExpr, env, expandingRefs = new Set()) {
|
|
93
|
+
const resolved = substituteSchemaExpr(curExpr, env);
|
|
94
|
+
if (resolved.kind === "ref") {
|
|
95
|
+
const decl = declMap.get(resolved.name);
|
|
96
|
+
if (!decl) {
|
|
97
|
+
if (allowOpen) {
|
|
98
|
+
const id = nodes.length;
|
|
99
|
+
nodes.push(["any", []]);
|
|
100
|
+
return id;
|
|
101
|
+
}
|
|
102
|
+
throw new KTVMSchemaError(`Unresolved schema reference '${resolved.name}'`);
|
|
103
|
+
}
|
|
104
|
+
const args = resolved.args || [];
|
|
105
|
+
if (args.length !== (decl.params || []).length) {
|
|
106
|
+
throw new KTVMSchemaError(
|
|
107
|
+
`Schema '${resolved.name}' expects ${(decl.params || []).length} args, got ${args.length}`
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
const key = `${resolved.name}[${args.map(exprStructuralKey).join(",")}]`;
|
|
111
|
+
if (memo.has(key)) return memo.get(key);
|
|
112
|
+
if (expandingRefs.has(key)) {
|
|
113
|
+
throw new KTVMSchemaError(`Unguarded direct schema cycle on '${resolved.name}'`);
|
|
114
|
+
}
|
|
115
|
+
const nextEnv = new Map();
|
|
116
|
+
for (let i = 0; i < args.length; i++) {
|
|
117
|
+
nextEnv.set(decl.params[i], args[i]);
|
|
118
|
+
}
|
|
119
|
+
const nextExpanding = new Set(expandingRefs);
|
|
120
|
+
nextExpanding.add(key);
|
|
121
|
+
|
|
122
|
+
// Peek body kind; reserve node slot BEFORE descending into edges to tie recursive knots.
|
|
123
|
+
const body = substituteSchemaExpr(decl.expr, nextEnv);
|
|
124
|
+
if (body.kind === "ref") {
|
|
125
|
+
const id = visit(body, nextEnv, nextExpanding);
|
|
126
|
+
memo.set(key, id);
|
|
127
|
+
return id;
|
|
128
|
+
}
|
|
129
|
+
const id = nodes.length;
|
|
130
|
+
memo.set(key, id);
|
|
131
|
+
nodes.push(null);
|
|
132
|
+
nodes[id] = buildComposite(body, nextEnv);
|
|
133
|
+
return id;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const id = nodes.length;
|
|
137
|
+
nodes.push(null);
|
|
138
|
+
nodes[id] = buildComposite(resolved, env);
|
|
139
|
+
return id;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function buildComposite(resolved, env) {
|
|
143
|
+
switch (resolved.kind) {
|
|
144
|
+
case "unit":
|
|
145
|
+
return ["closed-product", []];
|
|
146
|
+
case "any":
|
|
147
|
+
if (!allowOpen) throw new KTVMSchemaError("Schema 'any' is not allowed in concrete mono kTVM");
|
|
148
|
+
return ["any", []];
|
|
149
|
+
case "product":
|
|
150
|
+
case "union": {
|
|
151
|
+
const kind = resolved.kind === "product" ? "closed-product" : "closed-union";
|
|
152
|
+
const sorted = [...resolved.fields].sort((a, b) => compareLabels(a.label, b.label));
|
|
153
|
+
const edges = sorted.map((f) => [f.label, visit(f.schema, env)]);
|
|
154
|
+
return [kind, edges];
|
|
155
|
+
}
|
|
156
|
+
case "open_product":
|
|
157
|
+
case "open_union": {
|
|
158
|
+
if (!allowOpen) {
|
|
159
|
+
throw new KTVMSchemaError(`Open schema '${resolved.kind}' is not allowed in concrete mono kTVM`);
|
|
160
|
+
}
|
|
161
|
+
const kind = resolved.kind === "open_product" ? "open-product" : "open-union";
|
|
162
|
+
const sorted = [...resolved.fields].sort((a, b) => compareLabels(a.label, b.label));
|
|
163
|
+
const edges = sorted.map((f) => [f.label, visit(f.schema, env)]);
|
|
164
|
+
return [kind, edges];
|
|
165
|
+
}
|
|
166
|
+
default:
|
|
167
|
+
throw new KTVMSchemaError(`Unsupported schema kind '${resolved.kind}'`);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
visit(expr, paramBindings);
|
|
172
|
+
return canonicalizePlistOrder(nodes, 0);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Re-index a property-list graph in canonical DFS discovery order from `rootId`
|
|
177
|
+
* with edges sorted in canonical label order.
|
|
178
|
+
*/
|
|
179
|
+
export function canonicalizePlistOrder(plist, rootId = 0) {
|
|
180
|
+
const idMap = new Map();
|
|
181
|
+
const out = [];
|
|
182
|
+
|
|
183
|
+
function dfs(oldId) {
|
|
184
|
+
if (idMap.has(oldId)) return idMap.get(oldId);
|
|
185
|
+
const newId = out.length;
|
|
186
|
+
idMap.set(oldId, newId);
|
|
187
|
+
const [kind, edges] = plist[oldId];
|
|
188
|
+
const sortedEdges = [...edges].sort((a, b) => compareLabels(a[0], b[0]));
|
|
189
|
+
const slot = [kind, []];
|
|
190
|
+
out.push(slot);
|
|
191
|
+
slot[1] = sortedEdges.map(([label, target]) => [label, dfs(target)]);
|
|
192
|
+
return newId;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
dfs(rootId);
|
|
196
|
+
return out;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Extract the reachable subgraph rooted at `rootId` as a standalone property-list.
|
|
201
|
+
*/
|
|
202
|
+
export function subPlist(plist, rootId = 0) {
|
|
203
|
+
return canonicalizePlistOrder(plist, rootId);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Compute the Moore minimal bisimulation quotient of a property-list graph
|
|
208
|
+
* rooted at `rootId`, returning both the minimized plist and a unique canonical
|
|
209
|
+
* string key (`S1 ≡ S2 <=> mooreKey(S1) === mooreKey(S2)`).
|
|
210
|
+
*/
|
|
211
|
+
export function mooreMinimize(plist, rootId = 0) {
|
|
212
|
+
const sub = canonicalizePlistOrder(plist, rootId);
|
|
213
|
+
const n = sub.length;
|
|
214
|
+
|
|
215
|
+
// Initial partition by (kind, ordered label list)
|
|
216
|
+
let cls = new Int32Array(n);
|
|
217
|
+
const initSigs = new Map();
|
|
218
|
+
let numClasses = 0;
|
|
219
|
+
for (let i = 0; i < n; i++) {
|
|
220
|
+
const [kind, edges] = sub[i];
|
|
221
|
+
const sig = `${kind}|${edges.map(([l]) => JSON.stringify(l)).join(",")}`;
|
|
222
|
+
let c = initSigs.get(sig);
|
|
223
|
+
if (c === undefined) {
|
|
224
|
+
c = numClasses++;
|
|
225
|
+
initSigs.set(sig, c);
|
|
226
|
+
}
|
|
227
|
+
cls[i] = c;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// Refine partition to fixed point
|
|
231
|
+
while (true) {
|
|
232
|
+
const nextCls = new Int32Array(n);
|
|
233
|
+
const sigMap = new Map();
|
|
234
|
+
let nextNum = 0;
|
|
235
|
+
for (let i = 0; i < n; i++) {
|
|
236
|
+
const edges = sub[i][1];
|
|
237
|
+
const sig = `${cls[i]}:${edges.map(([, t]) => cls[t]).join(",")}`;
|
|
238
|
+
let c = sigMap.get(sig);
|
|
239
|
+
if (c === undefined) {
|
|
240
|
+
c = nextNum++;
|
|
241
|
+
sigMap.set(sig, c);
|
|
242
|
+
}
|
|
243
|
+
nextCls[i] = c;
|
|
244
|
+
}
|
|
245
|
+
cls = nextCls;
|
|
246
|
+
if (nextNum === numClasses) break;
|
|
247
|
+
numClasses = nextNum;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// Build representative graph over classes and re-order canonically from root's class
|
|
251
|
+
const repOfClass = new Int32Array(numClasses).fill(-1);
|
|
252
|
+
for (let i = 0; i < n; i++) {
|
|
253
|
+
if (repOfClass[cls[i]] === -1) repOfClass[cls[i]] = i;
|
|
254
|
+
}
|
|
255
|
+
const quotient = [];
|
|
256
|
+
for (let c = 0; c < numClasses; c++) {
|
|
257
|
+
const [kind, edges] = sub[repOfClass[c]];
|
|
258
|
+
quotient.push([kind, edges.map(([l, t]) => [l, cls[t]])]);
|
|
259
|
+
}
|
|
260
|
+
const canonical = canonicalizePlistOrder(quotient, cls[0]);
|
|
261
|
+
return { plist: canonical, key: JSON.stringify(canonical) };
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
const MOORE_KEY_CACHE = new WeakMap();
|
|
265
|
+
|
|
266
|
+
export function mooreKey(plist, rootId = 0) {
|
|
267
|
+
let byRoot = MOORE_KEY_CACHE.get(plist);
|
|
268
|
+
if (!byRoot) {
|
|
269
|
+
byRoot = new Map();
|
|
270
|
+
MOORE_KEY_CACHE.set(plist, byRoot);
|
|
271
|
+
}
|
|
272
|
+
let key = byRoot.get(rootId);
|
|
273
|
+
if (key === undefined) {
|
|
274
|
+
key = mooreMinimize(plist, rootId).key;
|
|
275
|
+
byRoot.set(rootId, key);
|
|
276
|
+
}
|
|
277
|
+
return key;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
export function schemasEquivalent(p1, r1, p2, r2) {
|
|
281
|
+
if (p1 === p2 && r1 === r2) return true;
|
|
282
|
+
return mooreKey(p1, r1) === mooreKey(p2, r2);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// --- Wire Layout Helpers ---
|
|
286
|
+
|
|
287
|
+
export function isUnitSchema(plist, nodeId = 0) {
|
|
288
|
+
const node = plist[nodeId];
|
|
289
|
+
return node[0] === "closed-product" && node[1].length === 0;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
export function unionTagInfo(plist, nodeId, label) {
|
|
293
|
+
const node = plist[nodeId];
|
|
294
|
+
if (!node || (node[0] !== "closed-union" && node[0] !== "open-union")) return null;
|
|
295
|
+
const edges = node[1];
|
|
296
|
+
const ordinal = edges.findIndex(([l]) => l === label);
|
|
297
|
+
if (ordinal < 0) return null;
|
|
298
|
+
return {
|
|
299
|
+
ordinal,
|
|
300
|
+
width: choiceWidth(edges.length),
|
|
301
|
+
targetId: edges[ordinal][1],
|
|
302
|
+
tagCount: edges.length
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
export function unionOrdinalInfo(plist, nodeId, ordinal) {
|
|
307
|
+
const node = plist[nodeId];
|
|
308
|
+
if (!node || (node[0] !== "closed-union" && node[0] !== "open-union")) return null;
|
|
309
|
+
const edges = node[1];
|
|
310
|
+
if (ordinal < 0 || ordinal >= edges.length) return null;
|
|
311
|
+
return {
|
|
312
|
+
label: edges[ordinal][0],
|
|
313
|
+
targetId: edges[ordinal][1],
|
|
314
|
+
width: choiceWidth(edges.length),
|
|
315
|
+
tagCount: edges.length
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
export function productFields(plist, nodeId = 0) {
|
|
320
|
+
const node = plist[nodeId];
|
|
321
|
+
if (!node || (node[0] !== "closed-product" && node[0] !== "open-product")) return null;
|
|
322
|
+
return node[1].map(([label, targetId]) => ({ label, targetId }));
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
export function productFieldInfo(plist, nodeId, label) {
|
|
326
|
+
const fields = productFields(plist, nodeId);
|
|
327
|
+
if (!fields) return null;
|
|
328
|
+
const idx = fields.findIndex((f) => f.label === label);
|
|
329
|
+
if (idx < 0) return null;
|
|
330
|
+
return { index: idx, label, targetId: fields[idx].targetId, fields };
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/**
|
|
334
|
+
* Convert a concrete closed property-list graph back into clean kTVM schema
|
|
335
|
+
* declarations (`$prefix_0`, ...) plus a root schema expression.
|
|
336
|
+
*/
|
|
337
|
+
export function plistToSchemaAst(plist, namePrefix = "$S") {
|
|
338
|
+
const min = mooreMinimize(plist, 0).plist;
|
|
339
|
+
// Detect which nodes are referenced recursively (or multiple times) so we emit clean named decls.
|
|
340
|
+
const inDegree = new Int32Array(min.length);
|
|
341
|
+
const isCycleTarget = new Uint8Array(min.length);
|
|
342
|
+
const state = new Int8Array(min.length);
|
|
343
|
+
|
|
344
|
+
function mark(u) {
|
|
345
|
+
state[u] = 1;
|
|
346
|
+
for (const [, v] of min[u][1]) {
|
|
347
|
+
inDegree[v]++;
|
|
348
|
+
if (state[v] === 1) isCycleTarget[v] = 1;
|
|
349
|
+
else if (state[v] === 0) mark(v);
|
|
350
|
+
}
|
|
351
|
+
state[u] = 2;
|
|
352
|
+
}
|
|
353
|
+
mark(0);
|
|
354
|
+
|
|
355
|
+
const decls = [];
|
|
356
|
+
const nameOf = new Map();
|
|
357
|
+
let seq = 0;
|
|
358
|
+
for (let i = 0; i < min.length; i++) {
|
|
359
|
+
const [kind, edges] = min[i];
|
|
360
|
+
if (kind === "closed-product" && edges.length === 0) continue; // inline `unit`
|
|
361
|
+
if (isCycleTarget[i] || inDegree[i] > 1 || i === 0) {
|
|
362
|
+
nameOf.set(i, seq === 0 ? namePrefix : `${namePrefix}_${seq}`);
|
|
363
|
+
seq++;
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
function buildExpr(i, inlineSelf) {
|
|
368
|
+
const [kind, edges] = min[i];
|
|
369
|
+
if (kind === "closed-product" && edges.length === 0) return S.unit();
|
|
370
|
+
if (!inlineSelf && nameOf.has(i)) return S.ref(nameOf.get(i));
|
|
371
|
+
const fields = edges.map(([label, t]) => ({ label, schema: buildExpr(t, false) }));
|
|
372
|
+
if (kind === "closed-product") return S.product(fields);
|
|
373
|
+
if (kind === "closed-union") return S.union(fields);
|
|
374
|
+
if (kind === "open-product") return S.openProduct(fields);
|
|
375
|
+
if (kind === "open-union") return S.openUnion(fields);
|
|
376
|
+
return S.any();
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
for (const [nodeId, name] of nameOf.entries()) {
|
|
380
|
+
decls.push({ name, params: [], expr: buildExpr(nodeId, true) });
|
|
381
|
+
}
|
|
382
|
+
const rootExpr = nameOf.has(0) ? S.ref(nameOf.get(0)) : buildExpr(0, true);
|
|
383
|
+
return { decls, rootExpr, plist: min };
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/**
|
|
387
|
+
* Unify a polymorphic kTVM-P contract expression against a concrete closed
|
|
388
|
+
* k-wire property-list graph `concretePlist`.
|
|
389
|
+
*
|
|
390
|
+
* Returns `Map<paramName, concreteSubPlist>` binding every schema parameter
|
|
391
|
+
* `$X` in `paramSet`, or throws `KTVMSchemaError` on any structural contradiction.
|
|
392
|
+
*/
|
|
393
|
+
export function unifyContractWithConcrete(contractExpr, schemaDecls, paramNames, concretePlist, concreteRootId = 0) {
|
|
394
|
+
if (!isClosedPlist(concretePlist)) {
|
|
395
|
+
throw new KTVMSchemaError("Input envelope schema must be a closed concrete k-wire pattern graph");
|
|
396
|
+
}
|
|
397
|
+
const declMap = schemaDecls instanceof Map
|
|
398
|
+
? schemaDecls
|
|
399
|
+
: new Map((schemaDecls || []).map((d) => [d.name, d]));
|
|
400
|
+
const paramSet = new Set(paramNames || []);
|
|
401
|
+
const bindings = new Map(); // $X -> minimized concrete subPlist
|
|
402
|
+
const visited = new Set();
|
|
403
|
+
|
|
404
|
+
function unify(cExpr, localEnv, nodeId) {
|
|
405
|
+
const resolved = substituteSchemaExpr(cExpr, localEnv);
|
|
406
|
+
const cNode = concretePlist[nodeId];
|
|
407
|
+
if (!cNode) throw new KTVMSchemaError(`Invalid concrete schema node ${nodeId}`);
|
|
408
|
+
const [cKind, cEdges] = cNode;
|
|
409
|
+
|
|
410
|
+
// Schema parameter `$X`
|
|
411
|
+
if (resolved.kind === "ref" && (!resolved.args || resolved.args.length === 0) && paramSet.has(resolved.name)) {
|
|
412
|
+
const candidate = mooreMinimize(concretePlist, nodeId).plist;
|
|
413
|
+
if (bindings.has(resolved.name)) {
|
|
414
|
+
const prev = bindings.get(resolved.name);
|
|
415
|
+
// Verify compatibility via K's pattern intersection and Moore equivalence
|
|
416
|
+
try {
|
|
417
|
+
const inter = intersectPropertyListPatterns(prev, candidate);
|
|
418
|
+
const mPrev = mooreKey(prev, 0);
|
|
419
|
+
const mCand = mooreKey(candidate, 0);
|
|
420
|
+
const mInter = mooreKey(inter, 0);
|
|
421
|
+
if (mPrev !== mCand || mInter !== mPrev) {
|
|
422
|
+
throw new KTVMSchemaError(
|
|
423
|
+
`Conflicting bindings for schema parameter '${resolved.name}'`
|
|
424
|
+
);
|
|
425
|
+
}
|
|
426
|
+
} catch (err) {
|
|
427
|
+
if (err instanceof KTVMSchemaError) throw err;
|
|
428
|
+
throw new KTVMSchemaError(
|
|
429
|
+
`Incompatible bindings for schema parameter '${resolved.name}': ${err.message}`
|
|
430
|
+
);
|
|
431
|
+
}
|
|
432
|
+
} else {
|
|
433
|
+
bindings.set(resolved.name, candidate);
|
|
434
|
+
}
|
|
435
|
+
return;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
if (resolved.kind === "any") {
|
|
439
|
+
return;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
if (resolved.kind === "unit") {
|
|
443
|
+
if (cKind !== "closed-product" || cEdges.length !== 0) {
|
|
444
|
+
throw new KTVMSchemaError(`Expected 'unit', got '${cKind}' with ${cEdges.length} edges`);
|
|
445
|
+
}
|
|
446
|
+
return;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
// Named schema reference (possibly recursive & parameterized)
|
|
450
|
+
if (resolved.kind === "ref") {
|
|
451
|
+
const decl = declMap.get(resolved.name);
|
|
452
|
+
if (!decl) {
|
|
453
|
+
throw new KTVMSchemaError(`Unknown schema '${resolved.name}'`);
|
|
454
|
+
}
|
|
455
|
+
const args = resolved.args || [];
|
|
456
|
+
if (args.length !== (decl.params || []).length) {
|
|
457
|
+
throw new KTVMSchemaError(
|
|
458
|
+
`Schema '${resolved.name}' expects ${(decl.params || []).length} args, got ${args.length}`
|
|
459
|
+
);
|
|
460
|
+
}
|
|
461
|
+
const visitKey = `${exprStructuralKey(resolved)}@${nodeId}`;
|
|
462
|
+
if (visited.has(visitKey)) return;
|
|
463
|
+
visited.add(visitKey);
|
|
464
|
+
|
|
465
|
+
const nextEnv = new Map();
|
|
466
|
+
for (let i = 0; i < args.length; i++) {
|
|
467
|
+
nextEnv.set(decl.params[i], args[i]);
|
|
468
|
+
}
|
|
469
|
+
unify(decl.expr, nextEnv, nodeId);
|
|
470
|
+
return;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
// Products
|
|
474
|
+
if (resolved.kind === "product" || resolved.kind === "open_product") {
|
|
475
|
+
if (cKind !== "closed-product") {
|
|
476
|
+
throw new KTVMSchemaError(`Expected product schema, got '${cKind}'`);
|
|
477
|
+
}
|
|
478
|
+
const cMap = new Map(cEdges);
|
|
479
|
+
const reqFields = resolved.fields || [];
|
|
480
|
+
if (resolved.kind === "product" && reqFields.length !== cEdges.length) {
|
|
481
|
+
throw new KTVMSchemaError(
|
|
482
|
+
`Closed product arity mismatch: contract has ${reqFields.length} fields, input has ${cEdges.length}`
|
|
483
|
+
);
|
|
484
|
+
}
|
|
485
|
+
for (const f of reqFields) {
|
|
486
|
+
if (!cMap.has(f.label)) {
|
|
487
|
+
throw new KTVMSchemaError(`Input product is missing required field '${f.label}'`);
|
|
488
|
+
}
|
|
489
|
+
unify(f.schema, localEnv, cMap.get(f.label));
|
|
490
|
+
}
|
|
491
|
+
return;
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
// Unions
|
|
495
|
+
if (resolved.kind === "union" || resolved.kind === "open_union") {
|
|
496
|
+
if (cKind !== "closed-union") {
|
|
497
|
+
throw new KTVMSchemaError(`Expected union schema, got '${cKind}'`);
|
|
498
|
+
}
|
|
499
|
+
const cMap = new Map(cEdges);
|
|
500
|
+
const contractMap = new Map((resolved.fields || []).map((f) => [f.label, f.schema]));
|
|
501
|
+
if (resolved.kind === "union") {
|
|
502
|
+
// Every tag in input must be accepted by closed union contract; for exact closed-union
|
|
503
|
+
// contract, check exact tag set match (consistent with k-wire closed union).
|
|
504
|
+
for (const [label] of cEdges) {
|
|
505
|
+
if (!contractMap.has(label)) {
|
|
506
|
+
throw new KTVMSchemaError(`Input union carries unhandled tag '${label}'`);
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
if (contractMap.size !== cEdges.length) {
|
|
510
|
+
throw new KTVMSchemaError(
|
|
511
|
+
`Closed union tag set mismatch: contract expects [${[...contractMap.keys()].join(", ")}], input has [${cEdges.map(([l]) => l).join(", ")}]`
|
|
512
|
+
);
|
|
513
|
+
}
|
|
514
|
+
} else {
|
|
515
|
+
// open_union: contract tags present in input must unify; intersection must be non-empty
|
|
516
|
+
// if contract has tags, at least compatible kinds.
|
|
517
|
+
}
|
|
518
|
+
for (const [label, targetId] of cEdges) {
|
|
519
|
+
if (contractMap.has(label)) {
|
|
520
|
+
unify(contractMap.get(label), localEnv, targetId);
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
return;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
throw new KTVMSchemaError(`Unsupported contract kind '${resolved.kind}'`);
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
unify(contractExpr, new Map(), concreteRootId);
|
|
530
|
+
return bindings;
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
/**
|
|
534
|
+
* Intersect two concrete or open property-list patterns using K's canonical
|
|
535
|
+
* `intersectPropertyListPatterns`, converting errors into `KTVMSchemaError`.
|
|
536
|
+
*/
|
|
537
|
+
export function intersectSchemas(leftPlist, rightPlist) {
|
|
538
|
+
try {
|
|
539
|
+
return canonicalizePlistOrder(intersectPropertyListPatterns(leftPlist, rightPlist), 0);
|
|
540
|
+
} catch (err) {
|
|
541
|
+
throw new KTVMSchemaError(err.message);
|
|
542
|
+
}
|
|
543
|
+
}
|