@fraczak/k 8.5.0 → 8.6.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 +35 -0
- package/DOCS/CODECS.md +54 -0
- package/DOCS/REPL.md +1 -0
- package/Examples/djson.k +443 -328
- package/Examples/ieee-arithmetics.k +7183 -0
- package/Examples/ieee.k +895 -7374
- package/Examples/poly.k +1 -1
- package/README.md +3 -2
- package/backends/llvm/src/kvm2llvm.mjs +5 -4
- package/backends/llvm/src/llvm.mjs +2 -1
- package/backends/llvm/tests/integration.sh +7 -0
- package/backends/llvm/tests/test-llvm.mjs +20 -0
- package/backends/wasm/src/kvm2wasm.mjs +64 -18
- package/backends/wasm/tests/integration.sh +7 -1
- package/backends/wasm/tests/test-wasm.mjs +86 -2
- package/browser/shims/fs.mjs +1 -0
- package/canonical-pattern.mjs +231 -2
- package/object.mjs +18 -9
- package/package.json +1 -1
- package/repl.mjs +91 -9
- package/scripts/benchmark-idempotency.mjs +20 -5
- package/scripts/benchmark.mjs +42 -10
- package/scripts/build-repl-html.mjs +4 -0
- package/scripts/perf-ieee.mjs +9 -16
- package/scripts/render-benchmark.mjs +1 -1
- package/scripts/run-tests.mjs +2 -0
- package/tests/README.md +2 -0
- package/tests/integration.sh +2 -1
- package/tests/test-djson-methods.mjs +11 -1
- package/tests/test-ieee-arithmetic.mjs +3 -1
- package/tests/test-ieee-text.mjs +59 -0
- package/tests/test-k-object.mjs +9 -0
- package/tests/test-parse-json.mjs +96 -0
- package/tests/test-repl-html.mjs +21 -8
- package/tests/test-repl.mjs +105 -2
package/Examples/poly.k
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
-- Examples/poly.k: Polymorphic list functions in k
|
|
2
|
-
-- Uses arbitrary-precision integers from Examples/arithmetics.k.
|
|
3
2
|
|
|
3
|
+
-- Defined in 'arithmetics.k':
|
|
4
4
|
int[] = @Nws3vysWqC9PznraTP4kWPp44Rd77NAqrx9dgbtHAjGA[];
|
|
5
5
|
dec = @yfy9ReCFtxn6HsW2qsER58PXQY8ptEdiH69pfi6rifeh;
|
|
6
6
|
nat = @74wj62GF7Bp6kN6TgCZ4WVkT6XmppzBQUaYLTzyuMFwc;
|
package/README.md
CHANGED
|
@@ -68,8 +68,9 @@ relations, libraries, and codecs.
|
|
|
68
68
|
| [Examples/list.k](Examples/list.k) | Small generic list example |
|
|
69
69
|
| [Examples/arithmetics.k](Examples/arithmetics.k) | Arbitrary-precision integer and rational arithmetic |
|
|
70
70
|
| [Examples/poly.k](Examples/poly.k) | Polymorphic list operations; load arithmetics.k first |
|
|
71
|
-
| [Examples/djson.k](Examples/djson.k) |
|
|
72
|
-
| [Examples/ieee.k](Examples/ieee.k) | Binary64
|
|
71
|
+
| [Examples/djson.k](Examples/djson.k) | JSON text parsing and dynamic JSON operations; load `core.k` and `Examples/ieee.k` first |
|
|
72
|
+
| [Examples/ieee.k](Examples/ieee.k) | Binary64 types and `parseFloat64` / `printFloat64`; load `core.k` first |
|
|
73
|
+
| [Examples/ieee-arithmetics.k](Examples/ieee-arithmetics.k) | Binary64 arithmetic returning `{result, flags}`; load `core.k`, then `Examples/ieee.k` first |
|
|
73
74
|
| [Examples/karatsuba-mult.k](Examples/karatsuba-mult.k) | Alternative integer multiplication algorithm |
|
|
74
75
|
|
|
75
76
|
Load libraries explicitly with `:load` in the REPL. The CLI uses `--lib` with
|
|
@@ -441,10 +441,11 @@ function hasSelfTailCall(insts, funcName, isTail = true) {
|
|
|
441
441
|
for (let i = 0; i < insts.length; i++) {
|
|
442
442
|
const inst = insts[i];
|
|
443
443
|
if (isTail && isSelfTailCall(insts, i, funcName)) return true;
|
|
444
|
-
if (inst.op === "union" && inst.branches) {
|
|
444
|
+
if (inst.op === "union" && inst.branches && inst.branches.length > 0) {
|
|
445
445
|
const unionIsTail = isTail && tailValueAfter(insts, i + 1, inst.dest);
|
|
446
|
-
|
|
447
|
-
|
|
446
|
+
if (unionIsTail) {
|
|
447
|
+
const lastBranch = inst.branches[inst.branches.length - 1];
|
|
448
|
+
if (hasSelfTailCall(lastBranch.body, funcName, true)) return true;
|
|
448
449
|
}
|
|
449
450
|
}
|
|
450
451
|
}
|
|
@@ -908,7 +909,7 @@ function lowerKVMFunction(kvmFunc, symbol, funcName, moduleCtx, linkage = "", op
|
|
|
908
909
|
outputPattern: kvmFunc.outputPattern,
|
|
909
910
|
body: branch.body
|
|
910
911
|
};
|
|
911
|
-
const armTailRef = tailValueAfter(insts, i + 1, inst.dest) ? tailRef : null;
|
|
912
|
+
const armTailRef = (isLast && tailValueAfter(insts, i + 1, inst.dest)) ? tailRef : null;
|
|
912
913
|
const armBody = lowerKVMFunction(armFunc, armName, armFunc.name, moduleCtx, "internal", { ...options, tailRef: armTailRef });
|
|
913
914
|
moduleCtx.syntheticFunctions.push(armBody);
|
|
914
915
|
|
|
@@ -505,7 +505,8 @@ function emitUnionFunctionBody(symbol, items, ctx, linkage = "", options = {}) {
|
|
|
505
505
|
unsupported(ctx);
|
|
506
506
|
} else {
|
|
507
507
|
items.forEach((item, index) => {
|
|
508
|
-
|
|
508
|
+
const isLast = index === items.length - 1;
|
|
509
|
+
unionBranch(ctx, ctx.addSyntheticFunction(item, options.tail === true && isLast), "%input", isLast);
|
|
509
510
|
});
|
|
510
511
|
}
|
|
511
512
|
const prefix = linkage ? `define ${linkage} %k_result` : "define %k_result";
|
|
@@ -134,6 +134,13 @@ printf '{"x":"left","y":"right"}' \
|
|
|
134
134
|
| node ../../codecs/k-print.mjs \
|
|
135
135
|
| grep -qx '"left"'
|
|
136
136
|
|
|
137
|
+
node ../../objects/compile.mjs 't[] = < {} a, T b > = T; f = ?t[] < /b f, /b {} |a > ?t[]; /b f' "$TMP_DIR/nonfinal-tail.ko"
|
|
138
|
+
printf '{"b":{"b":"a"}}\n' \
|
|
139
|
+
| node ../../codecs/k-parse.mjs --input-type '?< {} a, T b > = T' \
|
|
140
|
+
| node ./bin/k-llvm.mjs --cache-dir "$TMP_DIR/jit-cache" "$TMP_DIR/nonfinal-tail.ko" \
|
|
141
|
+
| node ../../codecs/k-print.mjs \
|
|
142
|
+
| grep -qx '"a"'
|
|
143
|
+
|
|
137
144
|
node --input-type=module -e "import { stdout } from 'node:process'; import { encodeToWire } from '../../codecs/runtime/prefix-codec.mjs'; import { Value } from '../../Value.mjs'; const pattern = [[\"open-union\",[[\"left\",1],[\"right\",1]]],[\"closed-product\",[]]]; stdout.write(encodeToWire(Value.variant(\"left\", Value.product({}), pattern), pattern));" \
|
|
138
145
|
| node ./bin/k-llvm.mjs --cache-dir "$TMP_DIR/jit-cache" "$TMP_DIR/id.ko" \
|
|
139
146
|
| node --input-type=module -e "import { stdin } from 'node:process'; import { decodeWire } from '../../codecs/runtime/prefix-codec.mjs'; const chunks = []; stdin.on('data', (chunk) => chunks.push(chunk)); stdin.on('end', () => console.log(JSON.stringify(decodeWire(Buffer.concat(chunks)).pattern)));" \
|
|
@@ -264,6 +264,26 @@ const { llvm: productRecurseLLVM } = compileObjectToLLVM(productRecurseObject, {
|
|
|
264
264
|
// Calls inside product fields must not return tail status (i32 2)
|
|
265
265
|
assert.doesNotMatch(productRecurseLLVM, /insertvalue %k_result undef, i32 2, 0/);
|
|
266
266
|
|
|
267
|
+
const unionNonFinalRecurseObject = decodeObject(compileObjectBuffer(`
|
|
268
|
+
t[] = < {} a, { T x } b > = T;
|
|
269
|
+
f = ?t[] <
|
|
270
|
+
/b .x f,
|
|
271
|
+
/b {} |a
|
|
272
|
+
> ?t[];
|
|
273
|
+
f
|
|
274
|
+
`, { source: "llvm-union-nonfinal-recurse.k" }));
|
|
275
|
+
const { llvm: unionNonFinalRecurseLLVM } = compileObjectToLLVM(unionNonFinalRecurseObject, {
|
|
276
|
+
relation: "f",
|
|
277
|
+
inputPattern: [
|
|
278
|
+
["closed-union", [["a", 1], ["b", 2]]],
|
|
279
|
+
["closed-product", []],
|
|
280
|
+
["closed-product", [["x", 0]]]
|
|
281
|
+
]
|
|
282
|
+
});
|
|
283
|
+
// Self-calls in non-final union branches must not be lowered as tail calls (status 2 or tail_loop)
|
|
284
|
+
assert.doesNotMatch(unionNonFinalRecurseLLVM, /insertvalue %k_result undef, i32 2, 0/);
|
|
285
|
+
assert.doesNotMatch(unionNonFinalRecurseLLVM, /tail_loop:/);
|
|
286
|
+
|
|
267
287
|
const kvmArtifact = objectToKVMArtifact(productObject, "__main__");
|
|
268
288
|
assert.equal(kvmArtifact.format, "k-vm");
|
|
269
289
|
const kvmLLVM = compileLLVMArtifactFromKVM(kvmArtifact, {
|
|
@@ -197,14 +197,34 @@ export function lowerToWasm(relDef, name, options = {}) {
|
|
|
197
197
|
return tailValueAfter(insts, index + 1, dest, inputMap, returnTarget, tailReturnTargets);
|
|
198
198
|
}
|
|
199
199
|
|
|
200
|
-
function
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
200
|
+
function feedsSelfTailCall(
|
|
201
|
+
insts,
|
|
202
|
+
startIndex,
|
|
203
|
+
valueReg,
|
|
204
|
+
inputMap,
|
|
205
|
+
returnTarget,
|
|
206
|
+
tailReturnTargets,
|
|
207
|
+
tailCallInputTargets
|
|
208
|
+
) {
|
|
209
|
+
if (options.trace || inputProductFields.length === 0) return false;
|
|
210
|
+
let current = valueReg;
|
|
211
|
+
for (let i = startIndex; i < insts.length; i++) {
|
|
212
|
+
const inst = insts[i];
|
|
213
|
+
if (inst.op === "guard_pattern" || inst.op === "guard_code" || inst.op === "id") {
|
|
214
|
+
if (mapsToReg(inst.src, inputMap) !== current) return false;
|
|
215
|
+
current = cleanReg(inst.dest);
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
if (inst.op === "call" && inst.func === name && mapsToReg(inst.src, inputMap) === current) {
|
|
219
|
+
const callDest = cleanReg(inst.dest);
|
|
220
|
+
return tailValueAfter(insts, i + 1, callDest, inputMap, returnTarget, tailReturnTargets);
|
|
221
|
+
}
|
|
222
|
+
if (inst.op === "return" && mapsToReg(inst.src, inputMap) === current) {
|
|
223
|
+
return Boolean(returnTarget && tailCallInputTargets.has(returnTarget));
|
|
224
|
+
}
|
|
225
|
+
return false;
|
|
226
|
+
}
|
|
227
|
+
return false;
|
|
208
228
|
}
|
|
209
229
|
|
|
210
230
|
function initInputProductLocals() {
|
|
@@ -252,7 +272,8 @@ export function lowerToWasm(relDef, name, options = {}) {
|
|
|
252
272
|
returnTarget = null,
|
|
253
273
|
failTarget = null,
|
|
254
274
|
tailReturnTargets = new Set(),
|
|
255
|
-
inputAliases = new Set(["in"])
|
|
275
|
+
inputAliases = new Set(["in"]),
|
|
276
|
+
tailCallInputTargets = new Set()
|
|
256
277
|
) {
|
|
257
278
|
const lines = [];
|
|
258
279
|
for (let index = 0; index < insts.length; index++) {
|
|
@@ -354,7 +375,15 @@ export function lowerToWasm(relDef, name, options = {}) {
|
|
|
354
375
|
const dest = cleanReg(inst.dest);
|
|
355
376
|
const rawSrc = cleanReg(inst.src);
|
|
356
377
|
const src = inputMap[rawSrc] || rawSrc;
|
|
357
|
-
const tailCall =
|
|
378
|
+
const tailCall = feedsSelfTailCall(
|
|
379
|
+
insts,
|
|
380
|
+
index + 1,
|
|
381
|
+
dest,
|
|
382
|
+
inputMap,
|
|
383
|
+
returnTarget,
|
|
384
|
+
tailReturnTargets,
|
|
385
|
+
tailCallInputTargets
|
|
386
|
+
);
|
|
358
387
|
const sortedBranches = [...inst.branches].sort((a, b) => {
|
|
359
388
|
if (a.label < b.label) return -1;
|
|
360
389
|
if (a.label > b.label) return 1;
|
|
@@ -382,8 +411,9 @@ export function lowerToWasm(relDef, name, options = {}) {
|
|
|
382
411
|
{ ...inputMap, "in": src },
|
|
383
412
|
fieldTmp,
|
|
384
413
|
failTarget,
|
|
385
|
-
|
|
386
|
-
new Set(inputAliases)
|
|
414
|
+
new Set(),
|
|
415
|
+
new Set(inputAliases),
|
|
416
|
+
new Set()
|
|
387
417
|
);
|
|
388
418
|
lines.push(branchWat);
|
|
389
419
|
}
|
|
@@ -430,8 +460,9 @@ export function lowerToWasm(relDef, name, options = {}) {
|
|
|
430
460
|
{ ...inputMap, "in": src },
|
|
431
461
|
fieldTmp,
|
|
432
462
|
failTarget,
|
|
433
|
-
|
|
434
|
-
new Set(inputAliases)
|
|
463
|
+
new Set(),
|
|
464
|
+
new Set(inputAliases),
|
|
465
|
+
new Set()
|
|
435
466
|
);
|
|
436
467
|
lines.push(branchWat);
|
|
437
468
|
}
|
|
@@ -549,9 +580,16 @@ export function lowerToWasm(relDef, name, options = {}) {
|
|
|
549
580
|
const rawSrc = cleanReg(inst.src);
|
|
550
581
|
const src = inputMap[rawSrc] || rawSrc;
|
|
551
582
|
const N = inst.branches.length;
|
|
552
|
-
const
|
|
553
|
-
|
|
554
|
-
|
|
583
|
+
const unionIsTail = tailValueAfter(insts, index + 1, dest, inputMap, returnTarget, tailReturnTargets);
|
|
584
|
+
const unionFeedsSelfTailCall = feedsSelfTailCall(
|
|
585
|
+
insts,
|
|
586
|
+
index + 1,
|
|
587
|
+
dest,
|
|
588
|
+
inputMap,
|
|
589
|
+
returnTarget,
|
|
590
|
+
tailReturnTargets,
|
|
591
|
+
tailCallInputTargets
|
|
592
|
+
);
|
|
555
593
|
|
|
556
594
|
const unionId = nextUnionId++;
|
|
557
595
|
const arenaMark = `union_mark_${unionId}`;
|
|
@@ -566,6 +604,13 @@ export function lowerToWasm(relDef, name, options = {}) {
|
|
|
566
604
|
|
|
567
605
|
for (let i = 0; i < N; i++) {
|
|
568
606
|
const branch = inst.branches[i];
|
|
607
|
+
const isLast = i === N - 1;
|
|
608
|
+
const branchTailReturnTargets = isLast && unionIsTail
|
|
609
|
+
? new Set([...tailReturnTargets, dest])
|
|
610
|
+
: new Set();
|
|
611
|
+
const branchTailCallInputTargets = unionFeedsSelfTailCall
|
|
612
|
+
? new Set([...tailCallInputTargets, dest])
|
|
613
|
+
: (isLast && unionIsTail ? tailCallInputTargets : new Set());
|
|
569
614
|
lines.push(` global.get $arena_free`);
|
|
570
615
|
lines.push(` local.set $${arenaMark}`);
|
|
571
616
|
const branchWat = compileInstructions(
|
|
@@ -574,7 +619,8 @@ export function lowerToWasm(relDef, name, options = {}) {
|
|
|
574
619
|
dest,
|
|
575
620
|
`$b${i}_try_${unionId}`,
|
|
576
621
|
branchTailReturnTargets,
|
|
577
|
-
new Set(inputAliases)
|
|
622
|
+
new Set(inputAliases),
|
|
623
|
+
branchTailCallInputTargets
|
|
578
624
|
);
|
|
579
625
|
lines.push(branchWat);
|
|
580
626
|
lines.push(` br $union_done_${unionId}`);
|
|
@@ -54,6 +54,11 @@ compare_json_envelope "projected JSON number" \
|
|
|
54
54
|
compare_json_envelope "closed product filter" \
|
|
55
55
|
'{"a":[1,2,"kupa"], "b": 123}' \
|
|
56
56
|
'?{X a, Y b}'
|
|
57
|
+
printf '{"b":{"b":"a"}}\n' |
|
|
58
|
+
node "$K_ROOT/codecs/k-parse.mjs" --input-type '?< {} a, T b > = T' |
|
|
59
|
+
node ./bin/k-wasm.mjs 't[] = < {} a, T b > = T; f = ?t[] < /b f, /b {} |a > ?t[]; /b f' |
|
|
60
|
+
node "$K_ROOT/codecs/k-print.mjs" |
|
|
61
|
+
grep -qx '"a"'
|
|
57
62
|
printf '{"a":[1,2,"kupa"], "b": 123}\n' |
|
|
58
63
|
node "$K_ROOT/codecs/json.mjs" --parse |
|
|
59
64
|
node ./bin/k-wasm.mjs '{ .a.2 word, .b number }' |
|
|
@@ -167,7 +172,8 @@ printf '{"x":{"a":{}},"y":{"b":{}}}\n' |
|
|
|
167
172
|
node "$K_ROOT/codecs/k-print.mjs" |
|
|
168
173
|
grep -qx '"b"'
|
|
169
174
|
|
|
170
|
-
node "$K_ROOT/objects/compile.mjs" "$K_ROOT/Examples/ieee.k" "$TMP_DIR/ieee.klib"
|
|
175
|
+
node "$K_ROOT/objects/compile.mjs" --lib "$K_ROOT/core.k" "$K_ROOT/Examples/ieee.k" "$TMP_DIR/ieee-types.klib"
|
|
176
|
+
node "$K_ROOT/objects/compile.mjs" --lib "$TMP_DIR/ieee-types.klib" "$K_ROOT/Examples/ieee-arithmetics.k" "$TMP_DIR/ieee.klib"
|
|
171
177
|
if node ./bin/k-wasm-compile.mjs --lib "$TMP_DIR/ieee.klib" --lib "$TMP_DIR/ieee.klib" --export mul:times "{()x,()y} times .result" "$TMP_DIR/repeated-lib.wasm" >/dev/null 2>&1; then
|
|
172
178
|
echo "--lib unexpectedly accepted more than once" >&2
|
|
173
179
|
exit 1
|
|
@@ -448,8 +448,8 @@ console.log("==> Running End-to-End Peano Addition & Serialization Tests");
|
|
|
448
448
|
inc = | +1 nat?;
|
|
449
449
|
dec = nat? / +1;
|
|
450
450
|
add = ?{ nat? x, nat? y } = X <
|
|
451
|
-
{ . x
|
|
452
|
-
. y
|
|
451
|
+
{ . x / 0 a, . y then } . then,
|
|
452
|
+
{ . x dec x, . y inc y } ?X add
|
|
453
453
|
>;
|
|
454
454
|
()
|
|
455
455
|
`;
|
|
@@ -625,4 +625,88 @@ console.log("==> Running End-to-End Peano Addition & Serialization Tests");
|
|
|
625
625
|
console.log("End-to-End Peano Addition & Serialization tests passed successfully!");
|
|
626
626
|
}
|
|
627
627
|
|
|
628
|
+
console.log("==> Running Union Non-Final Branch Recursion & Factored Tail-Call Tests (Issue #3)");
|
|
629
|
+
{
|
|
630
|
+
const runtimeWat = fs.readFileSync("runtime.wat", "utf8");
|
|
631
|
+
|
|
632
|
+
// 1. Issue #3: Self-call in a non-final union branch must NOT be tail-call optimized,
|
|
633
|
+
// because failure of the recursive call must backtrack to subsequent union branches
|
|
634
|
+
// with the original input.
|
|
635
|
+
const backtrackDefs = annotate(`
|
|
636
|
+
t[] = < {} a, { T x } b > = T;
|
|
637
|
+
f = ?t[] <
|
|
638
|
+
/b .x f,
|
|
639
|
+
/b {} |a
|
|
640
|
+
> ?t[];
|
|
641
|
+
main = ?t[] /b .x f;
|
|
642
|
+
()
|
|
643
|
+
`, { convergence: { strategy: "auto" } });
|
|
644
|
+
|
|
645
|
+
const fWat = lowerToWasm(backtrackDefs.rels.f, "f");
|
|
646
|
+
const mainWat = lowerToWasm(backtrackDefs.rels.main, "main");
|
|
647
|
+
assert.match(fWat, /\bcall \$f\b/, "Self-call in non-final union branch must emit a regular call");
|
|
648
|
+
assert.doesNotMatch(fWat, /\bbr \$tail_loop\b/, "Self-call in non-final union branch must not jump to $tail_loop");
|
|
649
|
+
|
|
650
|
+
const fullBacktrackWat = runtimeWat.trim().slice(0, -1) + "\n" + fWat + "\n" + mainWat + "\n)";
|
|
651
|
+
const binaryBacktrack = compileWat("union_backtrack.wat", fullBacktrackWat);
|
|
652
|
+
const exportsBacktrack = await instantiateWasm(binaryBacktrack);
|
|
653
|
+
|
|
654
|
+
function writeUnit(exports) {
|
|
655
|
+
const ptr = exports.alloc(8);
|
|
656
|
+
const view = new DataView(exports.memory.buffer);
|
|
657
|
+
view.setUint32(ptr, 8, true);
|
|
658
|
+
view.setUint32(ptr + 4, 0, true);
|
|
659
|
+
return ptr;
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
function writeVariant(exports, tag, payloadPtr) {
|
|
663
|
+
const ptr = exports.alloc(12);
|
|
664
|
+
const view = new DataView(exports.memory.buffer);
|
|
665
|
+
view.setUint32(ptr, 12, true);
|
|
666
|
+
view.setUint32(ptr + 4, getTagId(tag), true);
|
|
667
|
+
view.setUint32(ptr + 8, payloadPtr, true);
|
|
668
|
+
return ptr;
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
function writeSingleFieldProduct(exports, label, valPtr) {
|
|
672
|
+
const ptr = exports.alloc(16);
|
|
673
|
+
const view = new DataView(exports.memory.buffer);
|
|
674
|
+
view.setUint32(ptr, 16, true);
|
|
675
|
+
view.setUint32(ptr + 4, 1, true);
|
|
676
|
+
view.setUint32(ptr + 8, getTagId(label), true);
|
|
677
|
+
view.setUint32(ptr + 12, valPtr, true);
|
|
678
|
+
return ptr;
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
// Construct b(b(a)) = {{{} |a x} |b x} |b
|
|
682
|
+
const aPtr = writeVariant(exportsBacktrack, "a", writeUnit(exportsBacktrack));
|
|
683
|
+
const baPtr = writeVariant(exportsBacktrack, "b", writeSingleFieldProduct(exportsBacktrack, "x", aPtr));
|
|
684
|
+
const bbaPtr = writeVariant(exportsBacktrack, "b", writeSingleFieldProduct(exportsBacktrack, "x", baPtr));
|
|
685
|
+
|
|
686
|
+
const resBacktrack = exportsBacktrack.main(bbaPtr);
|
|
687
|
+
assert.equal(resBacktrack[1], 1, "main(b(b(a))) must succeed by backtracking to branch 2 of f(b(a))");
|
|
688
|
+
const viewBacktrack = new DataView(exportsBacktrack.memory.buffer);
|
|
689
|
+
assert.equal(viewBacktrack.getUint32(resBacktrack[0] + 4, true), getTagId("a"), "main(b(b(a))) must return variant |a");
|
|
690
|
+
|
|
691
|
+
// 2. Factored tail-recursive union `< { ... }, { ... } > self` in the final branch of a union
|
|
692
|
+
// must forward product fields directly into $tail_in_* locals without allocating a product.
|
|
693
|
+
const factoredDefs = annotate(`
|
|
694
|
+
bits[] = < {} _, B 0, B 1 > = B;
|
|
695
|
+
eat = ?{ bits[] x, bits[] y } <
|
|
696
|
+
{ .x /_ a, .y then } .then,
|
|
697
|
+
<
|
|
698
|
+
{ .x /0 x, .y |0 y },
|
|
699
|
+
{ .x /1 x, .y |1 y }
|
|
700
|
+
> eat
|
|
701
|
+
> ?bits[];
|
|
702
|
+
()
|
|
703
|
+
`, { convergence: { strategy: "auto" } });
|
|
704
|
+
|
|
705
|
+
const eatWat = lowerToWasm(factoredDefs.rels.eat, "eat");
|
|
706
|
+
assert.doesNotMatch(eatWat, /\bcall \$eat\b/, "Factored tail-recursive union must not emit a Wasm self-call");
|
|
707
|
+
assert.match(eatWat, /;; tail-call field x/, "Factored tail-recursive union branches must forward product fields directly to $tail_in_*");
|
|
708
|
+
|
|
709
|
+
console.log("Union Non-Final Branch Recursion & Factored Tail-Call tests passed successfully!");
|
|
710
|
+
}
|
|
711
|
+
|
|
628
712
|
console.log("==> Harness ready.");
|
package/browser/shims/fs.mjs
CHANGED
package/canonical-pattern.mjs
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// Canonical representation, hash resolution, and export helpers.
|
|
3
3
|
|
|
4
4
|
import { annotate } from "./index.mjs";
|
|
5
|
+
import { TypePatternGraph } from "./TypePatternGraph.mjs";
|
|
5
6
|
import { patternGraphToCanonical, prettyFilter } from "./pretty.mjs";
|
|
6
7
|
import { patternToPropertyList } from "./codecs/runtime/pattern-json.mjs";
|
|
7
8
|
import { exportPatternGraph } from "./codecs/runtime/codec.mjs";
|
|
@@ -200,7 +201,7 @@ export function resolvePatternCanonicalInfo(name, pat, options = {}) {
|
|
|
200
201
|
if (name && pat) allPatterns[name] = pat;
|
|
201
202
|
|
|
202
203
|
let pathMap = {};
|
|
203
|
-
if (formalCount > 0) {
|
|
204
|
+
if (formalCount > 0 && name) {
|
|
204
205
|
try {
|
|
205
206
|
const markerArgs = formalParams.map((_, i) => ({
|
|
206
207
|
type: "name",
|
|
@@ -434,8 +435,236 @@ export function buildExportPreamble(exports = [], libraries = []) {
|
|
|
434
435
|
return lines.join("\n") + "\n";
|
|
435
436
|
}
|
|
436
437
|
|
|
438
|
+
const DEFAULT_MAX_PAT_LENGTH = 30;
|
|
439
|
+
|
|
440
|
+
export function canonicalBoundaryFilterSources(
|
|
441
|
+
typePatternGraph,
|
|
442
|
+
patternIds,
|
|
443
|
+
options = {}
|
|
444
|
+
) {
|
|
445
|
+
const maxPatLength = options.maxPatLength ?? DEFAULT_MAX_PAT_LENGTH;
|
|
446
|
+
const leafOccurrences = [];
|
|
447
|
+
const knotEntries = [];
|
|
448
|
+
|
|
449
|
+
function buildSingleRootFilter(rawRootId) {
|
|
450
|
+
const subGraph = new TypePatternGraph(
|
|
451
|
+
typePatternGraph.registerCodeDef,
|
|
452
|
+
typePatternGraph.findCode
|
|
453
|
+
);
|
|
454
|
+
const renamed = typePatternGraph.clone([rawRootId], subGraph);
|
|
455
|
+
const rootId = subGraph.find(renamed[rawRootId]);
|
|
456
|
+
|
|
457
|
+
const origByNew = new Map();
|
|
458
|
+
for (const [origId, newId] of Object.entries(renamed)) {
|
|
459
|
+
origByNew.set(
|
|
460
|
+
subGraph.find(Number(newId)),
|
|
461
|
+
typePatternGraph.find(Number(origId))
|
|
462
|
+
);
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
const inDegree = subGraph.patterns.nodes.map(() => 0);
|
|
466
|
+
inDegree[rootId]++;
|
|
467
|
+
subGraph.edges.forEach((outEdges) =>
|
|
468
|
+
Object.values(outEdges).forEach((destMap) =>
|
|
469
|
+
Object.values(destMap).forEach((dst) => inDegree[dst]++)
|
|
470
|
+
)
|
|
471
|
+
);
|
|
472
|
+
|
|
473
|
+
function hasOpenDescendant(startId, seen = new Set()) {
|
|
474
|
+
if (seen.has(startId)) return false;
|
|
475
|
+
seen.add(startId);
|
|
476
|
+
const p = subGraph.get_pattern(startId);
|
|
477
|
+
if (
|
|
478
|
+
p.pattern === "(...)" ||
|
|
479
|
+
p.pattern === "{...}" ||
|
|
480
|
+
p.pattern === "<...>"
|
|
481
|
+
) {
|
|
482
|
+
return true;
|
|
483
|
+
}
|
|
484
|
+
const edges = subGraph.edges[startId] || {};
|
|
485
|
+
for (const key of Object.keys(edges)) {
|
|
486
|
+
const dst = Object.values(edges[key])[0];
|
|
487
|
+
if (hasOpenDescendant(dst, seen)) return true;
|
|
488
|
+
}
|
|
489
|
+
return false;
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
const dagKnots = new Map();
|
|
493
|
+
let nextKnot = 0;
|
|
494
|
+
|
|
495
|
+
function build(patternId, ancestorKnots) {
|
|
496
|
+
const pattern = subGraph.get_pattern(patternId);
|
|
497
|
+
if (pattern.pattern === "(...)") {
|
|
498
|
+
const origId = origByNew.get(patternId) ?? patternId;
|
|
499
|
+
const node = { type: null, open: true, fields: {} };
|
|
500
|
+
leafOccurrences.push({ origId, node });
|
|
501
|
+
return node;
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
if (ancestorKnots.has(patternId)) {
|
|
505
|
+
const knot = ancestorKnots.get(patternId);
|
|
506
|
+
knot.used = true;
|
|
507
|
+
const refNode = { type: "name", name: knot.name };
|
|
508
|
+
knot.refs.push(refNode);
|
|
509
|
+
return refNode;
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
const isOpenStruct =
|
|
513
|
+
pattern.pattern === "{...}" || pattern.pattern === "<...>";
|
|
514
|
+
const shareAcrossDag =
|
|
515
|
+
isOpenStruct || !hasOpenDescendant(patternId);
|
|
516
|
+
|
|
517
|
+
if (
|
|
518
|
+
shareAcrossDag &&
|
|
519
|
+
inDegree[patternId] > 1 &&
|
|
520
|
+
dagKnots.has(patternId)
|
|
521
|
+
) {
|
|
522
|
+
const knot = dagKnots.get(patternId);
|
|
523
|
+
knot.used = true;
|
|
524
|
+
const refNode = { type: "name", name: knot.name };
|
|
525
|
+
knot.refs.push(refNode);
|
|
526
|
+
return refNode;
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
const knotEntry = {
|
|
530
|
+
name: `K${nextKnot++}`,
|
|
531
|
+
used: false,
|
|
532
|
+
target: null,
|
|
533
|
+
refs: []
|
|
534
|
+
};
|
|
535
|
+
knotEntries.push(knotEntry);
|
|
536
|
+
const nextAncestors = new Map(ancestorKnots);
|
|
537
|
+
nextAncestors.set(patternId, knotEntry);
|
|
538
|
+
if (shareAcrossDag && inDegree[patternId] > 1) {
|
|
539
|
+
dagKnots.set(patternId, knotEntry);
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
const edges = subGraph.edges[patternId] || {};
|
|
543
|
+
const fields = () =>
|
|
544
|
+
Object.keys(edges)
|
|
545
|
+
.sort()
|
|
546
|
+
.reduce((acc, key) => {
|
|
547
|
+
acc[key] = build(
|
|
548
|
+
Object.values(edges[key])[0],
|
|
549
|
+
nextAncestors
|
|
550
|
+
);
|
|
551
|
+
return acc;
|
|
552
|
+
}, {});
|
|
553
|
+
|
|
554
|
+
let res;
|
|
555
|
+
switch (pattern.pattern) {
|
|
556
|
+
case "type": {
|
|
557
|
+
const code = subGraph.findCode(pattern.type);
|
|
558
|
+
if (code?.code === "product") {
|
|
559
|
+
res = { type: "product", fields: fields() };
|
|
560
|
+
} else if (code?.code === "union") {
|
|
561
|
+
res = { type: "union", fields: fields() };
|
|
562
|
+
} else {
|
|
563
|
+
res = { type: "code", code: pattern.type };
|
|
564
|
+
}
|
|
565
|
+
break;
|
|
566
|
+
}
|
|
567
|
+
case "{...}":
|
|
568
|
+
res = { type: "product", open: true, fields: fields() };
|
|
569
|
+
break;
|
|
570
|
+
case "<...>":
|
|
571
|
+
res = { type: "union", open: true, fields: fields() };
|
|
572
|
+
break;
|
|
573
|
+
case "{}":
|
|
574
|
+
res = { type: "product", fields: fields() };
|
|
575
|
+
break;
|
|
576
|
+
case "<>":
|
|
577
|
+
res = { type: "union", fields: fields() };
|
|
578
|
+
break;
|
|
579
|
+
}
|
|
580
|
+
knotEntry.target = res;
|
|
581
|
+
if (knotEntry.used) {
|
|
582
|
+
res.name = knotEntry.name;
|
|
583
|
+
}
|
|
584
|
+
return res;
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
const built = build(rootId, new Map());
|
|
588
|
+
for (const knot of dagKnots.values()) {
|
|
589
|
+
if (knot.used && knot.target) {
|
|
590
|
+
knot.target.name = knot.name;
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
return built;
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
const filters = patternIds.map((id) => buildSingleRootFilter(id));
|
|
597
|
+
|
|
598
|
+
const origCounts = new Map();
|
|
599
|
+
for (const { origId } of leafOccurrences) {
|
|
600
|
+
origCounts.set(origId, (origCounts.get(origId) || 0) + 1);
|
|
601
|
+
}
|
|
602
|
+
const sharedVarByOrig = new Map();
|
|
603
|
+
let nextVar = 0;
|
|
604
|
+
for (const { origId, node } of leafOccurrences) {
|
|
605
|
+
if ((origCounts.get(origId) || 0) > 1) {
|
|
606
|
+
if (!sharedVarByOrig.has(origId)) {
|
|
607
|
+
sharedVarByOrig.set(origId, `X${nextVar++}`);
|
|
608
|
+
}
|
|
609
|
+
node.type = "name";
|
|
610
|
+
node.name = sharedVarByOrig.get(origId);
|
|
611
|
+
delete node.fields;
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
const sharedVars = [...sharedVarByOrig.values()];
|
|
615
|
+
|
|
616
|
+
for (const knot of knotEntries) {
|
|
617
|
+
if (knot.used && knot.target) {
|
|
618
|
+
const knotName = `X${nextVar++}`;
|
|
619
|
+
knot.name = knotName;
|
|
620
|
+
knot.target.name = knotName;
|
|
621
|
+
for (const refNode of knot.refs) {
|
|
622
|
+
refNode.name = knotName;
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
return filters.map((filter) => {
|
|
628
|
+
const inlineStr = prettyFilter(filter);
|
|
629
|
+
if (
|
|
630
|
+
(filter.type === null &&
|
|
631
|
+
filter.open &&
|
|
632
|
+
Object.keys(filter.fields || {}).length === 0 &&
|
|
633
|
+
!filter.name) ||
|
|
634
|
+
(filter.type === "name" && filter.open) ||
|
|
635
|
+
inlineStr.length <= maxPatLength
|
|
636
|
+
) {
|
|
637
|
+
return `?${inlineStr}`;
|
|
638
|
+
}
|
|
639
|
+
const info = resolvePatternCanonicalInfo(
|
|
640
|
+
null,
|
|
641
|
+
{ params: sharedVars, filter },
|
|
642
|
+
options
|
|
643
|
+
);
|
|
644
|
+
if (
|
|
645
|
+
info.hash &&
|
|
646
|
+
options.registerPatterns &&
|
|
647
|
+
!options.registerPatterns[info.hash]
|
|
648
|
+
) {
|
|
649
|
+
options.registerPatterns[info.hash] = {
|
|
650
|
+
params: info.canonicalParams || info.params || [],
|
|
651
|
+
filter: info.canonicalFilterAst || filter,
|
|
652
|
+
_canonical: info.hash,
|
|
653
|
+
_canonicalDef: info.def,
|
|
654
|
+
_canonicalParams: info.canonicalParams,
|
|
655
|
+
_graphParams: info.canonicalParams,
|
|
656
|
+
_aliasArgs: info.aliasArgs,
|
|
657
|
+
_canonicalFilterAst: info.canonicalFilterAst
|
|
658
|
+
};
|
|
659
|
+
}
|
|
660
|
+
const args = (info.aliasArgs || []).join(", ");
|
|
661
|
+
return `?${info.hash}[${args}]`;
|
|
662
|
+
});
|
|
663
|
+
}
|
|
664
|
+
|
|
437
665
|
export default {
|
|
438
666
|
resolvePatternCanonicalInfo,
|
|
439
667
|
canonicalPatternHash,
|
|
440
|
-
buildExportPreamble
|
|
668
|
+
buildExportPreamble,
|
|
669
|
+
canonicalBoundaryFilterSources
|
|
441
670
|
};
|
package/object.mjs
CHANGED
|
@@ -5,7 +5,8 @@ import { TypePatternGraph } from "./TypePatternGraph.mjs";
|
|
|
5
5
|
import { patterns2filters, prettyRel } from "./pretty.mjs";
|
|
6
6
|
import {
|
|
7
7
|
resolvePatternCanonicalInfo,
|
|
8
|
-
buildExportPreamble
|
|
8
|
+
buildExportPreamble,
|
|
9
|
+
canonicalBoundaryFilterSources
|
|
9
10
|
} from "./canonical-pattern.mjs";
|
|
10
11
|
|
|
11
12
|
const OBJECT_MAGIC = Buffer.from("KOBJ\n");
|
|
@@ -842,12 +843,19 @@ function boundaryFilterSources(typePatternGraph, patternIds, aliases) {
|
|
|
842
843
|
}));
|
|
843
844
|
}
|
|
844
845
|
|
|
845
|
-
function prettyRelation(rel, aliases = {}, relAliases = {}) {
|
|
846
|
-
const
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
846
|
+
function prettyRelation(rel, aliases = {}, relAliases = {}, options = {}) {
|
|
847
|
+
const useCanonical = options.canonicalPatterns ?? true;
|
|
848
|
+
const [inputFilter, outputFilter] = useCanonical
|
|
849
|
+
? canonicalBoundaryFilterSources(
|
|
850
|
+
rel.typePatternGraph,
|
|
851
|
+
[rel.def.patterns[0], rel.def.patterns[1]],
|
|
852
|
+
options
|
|
853
|
+
)
|
|
854
|
+
: boundaryFilterSources(
|
|
855
|
+
rel.typePatternGraph,
|
|
856
|
+
[rel.def.patterns[0], rel.def.patterns[1]],
|
|
857
|
+
aliases
|
|
858
|
+
);
|
|
851
859
|
const body = rewriteRefsInExp(
|
|
852
860
|
stripRelationBoundaryFilters(stripDebugFieldsFromExp(rel.def), rel.typePatternGraph),
|
|
853
861
|
aliases,
|
|
@@ -866,7 +874,8 @@ function decompileObject(object) {
|
|
|
866
874
|
const relAliases = hydrated.relAlias || {};
|
|
867
875
|
const aliases = shortestUniqueAliases([
|
|
868
876
|
...Object.keys(hydrated.codes),
|
|
869
|
-
...Object.values(relAliases)
|
|
877
|
+
...Object.values(relAliases),
|
|
878
|
+
...Object.keys(rels).map((name) => relAliases[name] || name)
|
|
870
879
|
]);
|
|
871
880
|
|
|
872
881
|
const emittedRelAliases = new Set();
|
|
@@ -876,7 +885,7 @@ function decompileObject(object) {
|
|
|
876
885
|
const relName = relAliases[name] || name;
|
|
877
886
|
if (emittedRelAliases.has(relName)) return null;
|
|
878
887
|
emittedRelAliases.add(relName);
|
|
879
|
-
return `${aliases[relName] || relName} = ${prettyRelation(rel, aliases, relAliases)};`;
|
|
888
|
+
return `${aliases[relName] || relName} = ${prettyRelation(rel, aliases, relAliases, { canonicalPatterns: false })};`;
|
|
880
889
|
};
|
|
881
890
|
const compileStats = hydrated.compileStats;
|
|
882
891
|
const sccs = compileStats?.sccs || [];
|