@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/tests/test-repl-html.mjs
CHANGED
|
@@ -35,6 +35,7 @@ assert(html.includes("<style>"), "repl.html must contain inlined CSS styles");
|
|
|
35
35
|
assert(html.includes('<script type="module">'), "repl.html must contain inlined module script");
|
|
36
36
|
assert(!html.includes('<script src="http'), "repl.html must NOT contain external remote scripts");
|
|
37
37
|
assert(html.includes("wasm-in-process"), "repl.html must mention wasm-in-process engine");
|
|
38
|
+
assert(html.includes("ktvm-wasm"), "repl.html must mention ktvm-wasm engine");
|
|
38
39
|
assert(html.includes("nat.k"), "repl.html must embed standard examples");
|
|
39
40
|
assert(html.includes("btn-codecs"), "repl.html must contain Codecs button");
|
|
40
41
|
assert(html.includes("codecs-modal"), "repl.html must contain Codecs modal");
|
|
@@ -685,35 +686,78 @@ if (chromiumBin) {
|
|
|
685
686
|
assert.strictEqual(narrowNavbarCheck.hasTiming, false, "Help modal should not contain :timing");
|
|
686
687
|
assert.strictEqual(narrowNavbarCheck.hasCodecDefine, false, "Help modal should not contain :codec define");
|
|
687
688
|
|
|
688
|
-
// 6. Test 3-way engine switching in browser (wasm ->
|
|
689
|
+
// 6. Test 3-way engine switching in browser (wasm -> ktvm -> js -> wasm) and kTVM execution
|
|
689
690
|
const engineCheck = await evaluateAsync(`(async () => {
|
|
691
|
+
const badge = document.getElementById("engine-badge");
|
|
692
|
+
const badgeTag = badge?.tagName;
|
|
690
693
|
const initialEngine = window.kRepl.getEngine();
|
|
691
|
-
await window.kRepl.executeCommand(":engine
|
|
692
|
-
const
|
|
693
|
-
const
|
|
694
|
+
await window.kRepl.executeCommand(":engine ktvm");
|
|
695
|
+
const ktvmEngine = window.kRepl.getEngine();
|
|
696
|
+
const badgeKtvmText = badge?.textContent;
|
|
697
|
+
const badgeKtvmClass = badge?.classList.contains("ktvm-mode");
|
|
698
|
+
|
|
699
|
+
// Execute K expressions on ktvm-wasm directly in the browser!
|
|
700
|
+
await window.kRepl.executeCommand("{} | ok");
|
|
701
|
+
const ktvmSimpleLines = Array.from(document.querySelectorAll(".entry-line")).map(el => el.textContent);
|
|
702
|
+
const ktvmSimpleOut = ktvmSimpleLines[ktvmSimpleLines.length - 1];
|
|
703
|
+
|
|
704
|
+
await window.kRepl.executeCommand("{{}|_|0|1|0|1 nat x, {}|_|1|0|1 nat y} plus");
|
|
705
|
+
const ktvmPlusLines = Array.from(document.querySelectorAll(".entry-line")).map(el => el.textContent);
|
|
706
|
+
const ktvmPlusOut = ktvmPlusLines[ktvmPlusLines.length - 1];
|
|
707
|
+
|
|
708
|
+
await window.kRepl.executeCommand("{}|_|0|1|0|1 nat (gen_list sort)");
|
|
709
|
+
const ktvmSortLines = Array.from(document.querySelectorAll(".entry-line")).map(el => el.textContent);
|
|
710
|
+
const ktvmSortOut = ktvmSortLines[ktvmSortLines.length - 1];
|
|
711
|
+
|
|
694
712
|
await window.kRepl.executeCommand(":engine js");
|
|
695
713
|
const jsEngine = window.kRepl.getEngine();
|
|
696
|
-
const badgeJsText =
|
|
714
|
+
const badgeJsText = badge?.textContent;
|
|
697
715
|
await window.kRepl.executeCommand("() | ok");
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
716
|
+
// Verify switching from js (open-union state.value) -> ktvm works cleanly
|
|
717
|
+
await window.kRepl.executeCommand(":ktvm");
|
|
718
|
+
await window.kRepl.executeCommand("/ok");
|
|
719
|
+
const ktvmFromJsLines = Array.from(document.querySelectorAll(".entry-line")).map(el => el.textContent);
|
|
720
|
+
const ktvmFromJsOut = ktvmFromJsLines[ktvmFromJsLines.length - 1];
|
|
721
|
+
|
|
722
|
+
// Verify badge click cycles ktvm -> js -> wasm -> ktvm -> ...
|
|
723
|
+
badge.click();
|
|
724
|
+
await new Promise(r => setTimeout(r, 80));
|
|
725
|
+
const clickedToJs = window.kRepl.getEngine();
|
|
726
|
+
badge.click();
|
|
727
|
+
await new Promise(r => setTimeout(r, 80));
|
|
728
|
+
const clickedToWasm = window.kRepl.getEngine();
|
|
729
|
+
const badgeWasmText = badge?.textContent;
|
|
701
730
|
return {
|
|
731
|
+
badgeTag,
|
|
702
732
|
initialEngine,
|
|
703
|
-
|
|
733
|
+
ktvmEngine,
|
|
704
734
|
jsEngine,
|
|
705
|
-
|
|
706
|
-
|
|
735
|
+
clickedToJs,
|
|
736
|
+
clickedToWasm,
|
|
737
|
+
badgeKtvmText,
|
|
738
|
+
badgeKtvmClass,
|
|
707
739
|
badgeJsText,
|
|
708
|
-
badgeWasmText
|
|
740
|
+
badgeWasmText,
|
|
741
|
+
ktvmSimpleOut,
|
|
742
|
+
ktvmPlusOut,
|
|
743
|
+
ktvmSortOut,
|
|
744
|
+
ktvmFromJsOut
|
|
709
745
|
};
|
|
710
746
|
})()`);
|
|
747
|
+
assert.strictEqual(engineCheck.badgeTag, "BUTTON", "#engine-badge should be a native <button>");
|
|
711
748
|
assert.strictEqual(engineCheck.initialEngine, "wasm");
|
|
712
|
-
assert.strictEqual(engineCheck.
|
|
713
|
-
assert.strictEqual(engineCheck.
|
|
749
|
+
assert.strictEqual(engineCheck.ktvmEngine, "ktvm");
|
|
750
|
+
assert.strictEqual(engineCheck.badgeKtvmText, "ktvm-wasm");
|
|
751
|
+
assert.strictEqual(engineCheck.badgeKtvmClass, true, "#engine-badge should have .ktvm-mode class");
|
|
752
|
+
assert(engineCheck.ktvmSimpleOut.includes("{}|ok"), `Expected {}|ok from ktvm in browser, got: ${engineCheck.ktvmSimpleOut}`);
|
|
753
|
+
assert(engineCheck.ktvmPlusOut.includes("int.mjs: 15"), `Expected int.mjs: 15 from ktvm plus in browser, got: ${engineCheck.ktvmPlusOut}`);
|
|
754
|
+
assert(engineCheck.ktvmSortOut.includes("int.mjs: [0,1,2,3,4,5,6,7,8,9,10]"), `Expected sorted list from ktvm in browser, got: ${engineCheck.ktvmSortOut}`);
|
|
714
755
|
assert.strictEqual(engineCheck.jsEngine, "js");
|
|
715
756
|
assert.strictEqual(engineCheck.badgeJsText, "js-in-process");
|
|
716
|
-
assert
|
|
757
|
+
assert(engineCheck.ktvmFromJsOut.includes("{}"), `Expected {} after switching js -> ktvm on /ok, got: ${engineCheck.ktvmFromJsOut}`);
|
|
758
|
+
assert.strictEqual(engineCheck.clickedToJs, "js");
|
|
759
|
+
assert.strictEqual(engineCheck.clickedToWasm, "wasm");
|
|
760
|
+
assert.strictEqual(engineCheck.badgeWasmText, "wasm-in-process");
|
|
717
761
|
// 7. Test uploading a file (adds to VFS without auto-loading)
|
|
718
762
|
const uploadCheck = await evaluateAsync(`(async () => {
|
|
719
763
|
const codecCode = \`export default {
|
|
@@ -805,6 +849,19 @@ if (chromiumBin) {
|
|
|
805
849
|
`Expected 'int.mjs: 3' from wasm execution, got: ${wasmLenCheck}`
|
|
806
850
|
);
|
|
807
851
|
|
|
852
|
+
// Test kTVM-Wasm engine with polymorphic/open list len
|
|
853
|
+
const ktvmLenCheck = await evaluateAsync(`(async () => {
|
|
854
|
+
await window.kRepl.executeCommand(":engine ktvm");
|
|
855
|
+
await window.kRepl.executeCommand(":input int.mjs [1,2,3]");
|
|
856
|
+
await window.kRepl.executeCommand("len");
|
|
857
|
+
const lines = Array.from(document.querySelectorAll(".entry-line")).map(el => el.textContent);
|
|
858
|
+
return lines[lines.length - 1];
|
|
859
|
+
})()`);
|
|
860
|
+
assert(
|
|
861
|
+
ktvmLenCheck.includes("int.mjs: 3"),
|
|
862
|
+
`Expected 'int.mjs: 3' from ktvm execution, got: ${ktvmLenCheck}`
|
|
863
|
+
);
|
|
864
|
+
|
|
808
865
|
ws.close();
|
|
809
866
|
console.log(" Browser execution verified successfully!");
|
|
810
867
|
} finally {
|
package/tests/test-repl.mjs
CHANGED
|
@@ -525,14 +525,14 @@ assert.equal(output[0], "{} ?{}");
|
|
|
525
525
|
assert.match(output[1], /\/\* comp: .*, exec: .* \(js\) \*\//);
|
|
526
526
|
assert.equal(timingState.lastTiming.engine, "js");
|
|
527
527
|
|
|
528
|
-
// Verify shortcuts :wasm and :js
|
|
528
|
+
// Verify shortcuts :wasm, :ktvm, and :js
|
|
529
529
|
output = await evaluateInput(":wasm", timingState);
|
|
530
530
|
assert.equal(output[0], "engine set to wasm");
|
|
531
531
|
assert.equal(timingState.engine, "wasm");
|
|
532
532
|
|
|
533
|
-
output = await evaluateInput(":
|
|
534
|
-
assert.equal(output[0], "engine set to
|
|
535
|
-
assert.equal(timingState.engine, "
|
|
533
|
+
output = await evaluateInput(":ktvm", timingState);
|
|
534
|
+
assert.equal(output[0], "engine set to ktvm");
|
|
535
|
+
assert.equal(timingState.engine, "ktvm");
|
|
536
536
|
|
|
537
537
|
output = await evaluateInput(":js", timingState);
|
|
538
538
|
assert.equal(output[0], "engine set to js");
|
|
@@ -546,13 +546,13 @@ assert.equal(timingState.engine, "js");
|
|
|
546
546
|
// Verify invalid engine error
|
|
547
547
|
await assert.rejects(
|
|
548
548
|
() => evaluateInput(":engine invalid", timingState),
|
|
549
|
-
/Invalid engine 'invalid'\. Valid engines: wasm,
|
|
549
|
+
/Invalid engine 'invalid'\. Valid engines: wasm, ktvm, js/
|
|
550
550
|
);
|
|
551
551
|
|
|
552
552
|
// Verify autocompletion for :engine
|
|
553
553
|
completions = completeInput(":engine ", timingState)[0];
|
|
554
554
|
assert(completions.includes(":engine wasm"));
|
|
555
|
-
assert(completions.includes(":engine
|
|
555
|
+
assert(completions.includes(":engine ktvm"));
|
|
556
556
|
assert(completions.includes(":engine js"));
|
|
557
557
|
|
|
558
558
|
// Verify evaluating expressions in JS engine
|
|
@@ -574,30 +574,37 @@ output = await evaluateInput("{ {}|_|0|1|0|1 nat x, {}|_|1|0|1 nat y } plus", js
|
|
|
574
574
|
assert.match(output[0], /^\{\}\|_\|1\|1\|1\|1\|\+/);
|
|
575
575
|
assert.match(output[1], /\(js\)/);
|
|
576
576
|
|
|
577
|
-
// Verify evaluating expressions in
|
|
578
|
-
const
|
|
579
|
-
assert.equal(
|
|
577
|
+
// Verify evaluating expressions in kTVM-Wasm engine
|
|
578
|
+
const ktvmState = createState({ engine: "ktvm" });
|
|
579
|
+
assert.equal(ktvmState.engine, "ktvm");
|
|
580
580
|
|
|
581
581
|
output = await evaluateInput(
|
|
582
582
|
"succ = | succ;\n{} | zero succ succ",
|
|
583
|
-
|
|
583
|
+
ktvmState
|
|
584
584
|
);
|
|
585
585
|
assert.match(output[0], /^\{\}\|zero\|succ\|succ/);
|
|
586
|
-
assert.match(output[1], /\(
|
|
586
|
+
assert.match(output[1], /\(ktvm\)/);
|
|
587
587
|
|
|
588
588
|
output = await evaluateInput(
|
|
589
589
|
"not = </true | false, /false | true >;\n{} | true not",
|
|
590
|
-
|
|
590
|
+
ktvmState
|
|
591
591
|
);
|
|
592
592
|
assert.match(output[0], /^\{\}\|false/);
|
|
593
|
-
assert.match(output[1], /\(
|
|
593
|
+
assert.match(output[1], /\(ktvm\)/);
|
|
594
594
|
|
|
595
|
-
await evaluateInput(":load core.k",
|
|
596
|
-
output = await evaluateInput(":load lib/integer.k",
|
|
595
|
+
await evaluateInput(":load core.k", ktvmState);
|
|
596
|
+
output = await evaluateInput(":load lib/integer.k", ktvmState);
|
|
597
597
|
assert.equal(output[0], "loaded lib/integer.k");
|
|
598
|
-
output = await evaluateInput("{ {}|_|0|1|0|1 nat x, {}|_|1|0|1 nat y } plus",
|
|
598
|
+
output = await evaluateInput("{ {}|_|0|1|0|1 nat x, {}|_|1|0|1 nat y } plus", ktvmState);
|
|
599
599
|
assert.match(output[0], /^\{\}\|_\|1\|1\|1\|1\|\+/);
|
|
600
|
-
assert.match(output[1], /\(
|
|
600
|
+
assert.match(output[1], /\(ktvm\)/);
|
|
601
|
+
|
|
602
|
+
await evaluateInput(":codec load codecs/int.mjs", ktvmState);
|
|
603
|
+
await evaluateInput("len = {()list,0 int len} len_; len_ = ?X <{.list/nil if, .len then} .then, {.list/cons.cdr list, .len inc len} ?X len_ >;", ktvmState);
|
|
604
|
+
await evaluateInput(":input int.mjs [3,3,3]", ktvmState);
|
|
605
|
+
output = await evaluateInput("len", ktvmState);
|
|
606
|
+
assert.match(output[0], /int\.mjs:\s*3/);
|
|
607
|
+
assert.match(output[1], /\(ktvm\)/);
|
|
601
608
|
|
|
602
609
|
// Verify open product projection in wasm engine
|
|
603
610
|
const wasmListState = createState({ engine: "wasm" });
|
|
@@ -645,7 +652,7 @@ await evaluateInput(
|
|
|
645
652
|
djsonKState
|
|
646
653
|
);
|
|
647
654
|
output = await evaluateInput(
|
|
648
|
-
"{{{}|_
|
|
655
|
+
"{{{}|_ index, () json} nth /string key, " +
|
|
649
656
|
"{{}|_|1 index, () json} nth json} get",
|
|
650
657
|
djsonKState
|
|
651
658
|
);
|
|
@@ -656,7 +663,7 @@ await evaluateInput(
|
|
|
656
663
|
djsonKState
|
|
657
664
|
);
|
|
658
665
|
output = await evaluateInput(
|
|
659
|
-
"{{{}|_
|
|
666
|
+
"{{{}|_ index, () json} nth /string key, " +
|
|
660
667
|
"{{}|_|1 index, () json} nth json} del",
|
|
661
668
|
djsonKState
|
|
662
669
|
);
|
|
@@ -1015,7 +1022,7 @@ assert.equal(
|
|
|
1015
1022
|
"?@Pt3MwQwzUPxQKu58zXR3qUBHWTzfycx5bSZGzcK6EZQK[] " +
|
|
1016
1023
|
"dj_json_value {.rest dj_ws /nil _, .value value} .value " +
|
|
1017
1024
|
"?@P5C7TQKTSPnFUkYkYzTudJamxAQ3T3fHbvZNqwWMfAA2[]; " +
|
|
1018
|
-
"-- @
|
|
1025
|
+
"-- @3dPQGT29U9k4zMc8WizAimZtrhb6BHtY3UZEHtq7FPwN"
|
|
1019
1026
|
);
|
|
1020
1027
|
const shortThresholdState = createState();
|
|
1021
1028
|
output = await evaluateInput(":max-pat-length", shortThresholdState);
|
|
@@ -34,7 +34,7 @@ const listWire = encodeToWire(parsedList, INT_LIST_PATTERN);
|
|
|
34
34
|
const decodedList = decodeWire(listWire).value;
|
|
35
35
|
assert.equal(
|
|
36
36
|
valueWithEnvelopeToK(decodedList),
|
|
37
|
-
"{{}|_
|
|
37
|
+
"{{}|_|+ car, {{}|_|1|+ car, {{}|_|0|1|+ car, {}|nil cdr}|cons cdr}|cons cdr}|cons ?<{<<X1 0, X1 1, {}=X2 _>=X1 +, X1 -> car, X0 cdr} cons, X2 nil>=X0"
|
|
38
38
|
);
|
|
39
39
|
assert.equal(printInt(decodedList), "[0,1,2]");
|
|
40
40
|
|
package/DOCS/POLYMORPHIC_IR.md
DELETED
|
@@ -1,86 +0,0 @@
|
|
|
1
|
-
# Polymorphic IR (PKIR)
|
|
2
|
-
|
|
3
|
-
PKIR is an experimental execution representation in [pkir.mjs](../pkir.mjs).
|
|
4
|
-
It uses schema states and structural access profiles to navigate values through
|
|
5
|
-
layout witnesses.
|
|
6
|
-
|
|
7
|
-
It is separate from [KIR-P](KIR_V1.md), the portable object export, and from
|
|
8
|
-
[kVM](KVM_EXECUTION_MODEL.md), the register execution representation used by
|
|
9
|
-
the backends.
|
|
10
|
-
|
|
11
|
-
## Relation artifact
|
|
12
|
-
|
|
13
|
-
`compileRelationToPKIR(relDef, name)` creates:
|
|
14
|
-
|
|
15
|
-
```text
|
|
16
|
-
format: "pk-ir"
|
|
17
|
-
version: 1
|
|
18
|
-
name
|
|
19
|
-
inputReg / outputReg
|
|
20
|
-
inputPattern / outputPattern
|
|
21
|
-
patternGraph
|
|
22
|
-
accessProfile
|
|
23
|
-
instructions
|
|
24
|
-
```
|
|
25
|
-
|
|
26
|
-
The pattern graph supplies relation constraints; the access profile records
|
|
27
|
-
which fields and variants each state uses. `.pkir` is the JSON artifact
|
|
28
|
-
extension accepted by target tools.
|
|
29
|
-
|
|
30
|
-
## Access tables and values
|
|
31
|
-
|
|
32
|
-
`buildAccessTable(schema, pattern)` in
|
|
33
|
-
[access-table.mjs](../access-table.mjs) connects an input schema to the relation's
|
|
34
|
-
pattern graph. Descriptors map structural accesses to physical slots, child
|
|
35
|
-
states, tag identities, and offsets.
|
|
36
|
-
|
|
37
|
-
The JavaScript adapter `valueToKVal` creates materialized records with
|
|
38
|
-
`repr`, `state`, `tag`, and `words`; product records also retain field names.
|
|
39
|
-
`kvalToValue` converts these records back to `Value`. The execution code also
|
|
40
|
-
has support for serialized representations; use the adapter/codec contracts
|
|
41
|
-
rather than assuming that every PKIR value is a native pointer.
|
|
42
|
-
|
|
43
|
-
## Current instructions
|
|
44
|
-
|
|
45
|
-
| Instruction | Role |
|
|
46
|
-
| --- | --- |
|
|
47
|
-
| `id` | Forward a register |
|
|
48
|
-
| `fail` | Partial failure |
|
|
49
|
-
| `project_slot` | Project a product field through schema/layout information |
|
|
50
|
-
| `match_variant` | Extract a matching variant payload |
|
|
51
|
-
| `make_variant` | Construct a tagged value |
|
|
52
|
-
| `product` | Construct fields through nested instruction streams |
|
|
53
|
-
| `union` | Ordered branch selection |
|
|
54
|
-
| `call_rel` | Relation call, including recursion |
|
|
55
|
-
| `project_offset` | Specialized product access with a resolved offset |
|
|
56
|
-
| `match_tag_imm` | Specialized tag match with resolved discriminator information |
|
|
57
|
-
|
|
58
|
-
Instruction records retain labels/tags where needed for generic adapters.
|
|
59
|
-
Do not assume that generic execution universally eliminates string operations.
|
|
60
|
-
|
|
61
|
-
## Specialization and target lowering
|
|
62
|
-
|
|
63
|
-
`specializePKIR(pkir, table)` resolves product accesses to `project_offset`,
|
|
64
|
-
resolves variant matches to `match_tag_imm`, and removes branches whose
|
|
65
|
-
leading operation is known to fail. It returns an artifact with
|
|
66
|
-
`isSpecialized: true`.
|
|
67
|
-
|
|
68
|
-
`executePKIR` interprets generic or specialized instructions with the required
|
|
69
|
-
access table and relation context. `lowerPKIRToKVM` adapts instructions for
|
|
70
|
-
backend lowering. The shared [backend API](../backend-api.mjs) exports these
|
|
71
|
-
functions plus `compileWasmArtifactFromPKIR` and
|
|
72
|
-
`compileLLVMArtifactFromPKIR`.
|
|
73
|
-
|
|
74
|
-
The target CLIs accept `.pkir` files or `--pkir` for compiling source through
|
|
75
|
-
this path. See [WebAssembly](../backends/wasm/README.md) and
|
|
76
|
-
[LLVM](../backends/llvm/README.md).
|
|
77
|
-
|
|
78
|
-
Performance depends on the workload, adapter, and execution target. Use the
|
|
79
|
-
[benchmark guide](PROFILING_AND_TRACING.md) for measurements rather than
|
|
80
|
-
treating historical timings as interface guarantees.
|
|
81
|
-
|
|
82
|
-
## Verification
|
|
83
|
-
|
|
84
|
-
`tests/test-access-table.mjs` exercises descriptors and layout mapping.
|
|
85
|
-
`tests/test-pkir.mjs` checks execution, specialization, opaque payloads,
|
|
86
|
-
partial failure, and target integration. Both are registered in `npm test`.
|
package/access-table.mjs
DELETED
|
@@ -1,343 +0,0 @@
|
|
|
1
|
-
// access-table.mjs: State-Indexed Access Table for Polymorphic Execution
|
|
2
|
-
// Translates an input schema S into a compact, indexable navigation table
|
|
3
|
-
// allowing function instructions to access payload fields and variants
|
|
4
|
-
// without runtime string comparisons or dynamic dictionary lookups.
|
|
5
|
-
|
|
6
|
-
import { patternToPropertyList } from "./codecs/runtime/pattern-json.mjs";
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* Node descriptor for a single state in schema S.
|
|
10
|
-
*/
|
|
11
|
-
export class NodeDescriptor {
|
|
12
|
-
constructor(state, kind) {
|
|
13
|
-
this.state = state;
|
|
14
|
-
this.kind = kind; // 'product', 'union', or 'any'
|
|
15
|
-
}
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
/**
|
|
19
|
-
* AccessTable encapsulates the complete navigation structure for a
|
|
20
|
-
* schema S with respect to a function's structural access profile P.
|
|
21
|
-
*/
|
|
22
|
-
export class AccessTable {
|
|
23
|
-
constructor(descriptors, rootState = 0, wordSize = 8) {
|
|
24
|
-
this.descriptors = descriptors;
|
|
25
|
-
this.rootState = rootState;
|
|
26
|
-
this.wordSize = wordSize;
|
|
27
|
-
this.stateCount = descriptors.length;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
getDescriptor(stateId) {
|
|
31
|
-
const desc = this.descriptors[stateId];
|
|
32
|
-
if (!desc) {
|
|
33
|
-
throw new Error(`AccessTable has no descriptor for state ${stateId}`);
|
|
34
|
-
}
|
|
35
|
-
return desc;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
/**
|
|
39
|
-
* Resolves physical byte offset and child state for a logical
|
|
40
|
-
* field access.
|
|
41
|
-
*/
|
|
42
|
-
resolveField(stateId, fieldNameOrSlot) {
|
|
43
|
-
const desc = this.getDescriptor(stateId);
|
|
44
|
-
if (desc.kind !== "product") {
|
|
45
|
-
throw new Error(`State ${stateId} is not a product (is ${desc.kind})`);
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
if (typeof fieldNameOrSlot === "string") {
|
|
49
|
-
const fieldMeta = desc.fields[fieldNameOrSlot];
|
|
50
|
-
if (!fieldMeta) {
|
|
51
|
-
throw new Error(
|
|
52
|
-
`Field '${fieldNameOrSlot}' not found in state ${stateId}`
|
|
53
|
-
);
|
|
54
|
-
}
|
|
55
|
-
return fieldMeta;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
const slot = fieldNameOrSlot;
|
|
59
|
-
return {
|
|
60
|
-
byteOffset: desc.slotToByteOffset[slot],
|
|
61
|
-
childState: desc.slotToChildState[slot],
|
|
62
|
-
skipCount: desc.slotToSkipCount[slot]
|
|
63
|
-
};
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
/**
|
|
67
|
-
* Resolves branch index and child state for a variant discriminator.
|
|
68
|
-
*/
|
|
69
|
-
resolveVariant(stateId, tagOrId) {
|
|
70
|
-
const desc = this.getDescriptor(stateId);
|
|
71
|
-
if (desc.kind !== "union") {
|
|
72
|
-
throw new Error(`State ${stateId} is not a union (is ${desc.kind})`);
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
if (typeof tagOrId === "string") {
|
|
76
|
-
const tagMeta = desc.tags[tagOrId];
|
|
77
|
-
if (!tagMeta) {
|
|
78
|
-
throw new Error(`Variant '${tagOrId}' not found in state ${stateId}`);
|
|
79
|
-
}
|
|
80
|
-
return tagMeta;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
const tagId = tagOrId;
|
|
84
|
-
return {
|
|
85
|
-
branchId: desc.branchMap[tagId],
|
|
86
|
-
childState: desc.childStateMap[tagId]
|
|
87
|
-
};
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
toJSON() {
|
|
91
|
-
return {
|
|
92
|
-
rootState: this.rootState,
|
|
93
|
-
wordSize: this.wordSize,
|
|
94
|
-
stateCount: this.stateCount,
|
|
95
|
-
descriptors: this.descriptors
|
|
96
|
-
};
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
/**
|
|
101
|
-
* Normalizes a pattern, pattern graph, or property list into
|
|
102
|
-
* a canonical property list format.
|
|
103
|
-
*/
|
|
104
|
-
function toPropertyList(patternOrGraph) {
|
|
105
|
-
if (Array.isArray(patternOrGraph)) {
|
|
106
|
-
return patternOrGraph;
|
|
107
|
-
}
|
|
108
|
-
if (patternOrGraph && Array.isArray(patternOrGraph.nodes)) {
|
|
109
|
-
return patternToPropertyList(patternOrGraph);
|
|
110
|
-
}
|
|
111
|
-
if (patternOrGraph?.patterns?.nodes) {
|
|
112
|
-
// TypePatternGraph from KIR / KVM
|
|
113
|
-
return patternOrGraph.patterns.nodes.map((node, nodeIdx) => {
|
|
114
|
-
let kind = "any";
|
|
115
|
-
if (node.pattern === "{}") kind = "closed-product";
|
|
116
|
-
else if (node.pattern === "{...}") kind = "open-product";
|
|
117
|
-
else if (node.pattern === "<>") kind = "closed-union";
|
|
118
|
-
else if (node.pattern === "<...>") kind = "open-union";
|
|
119
|
-
const edgeMap = patternOrGraph.edges?.[nodeIdx] || {};
|
|
120
|
-
const edges = (node.fields || []).map((f) => {
|
|
121
|
-
const dest = edgeMap[f];
|
|
122
|
-
const target = Array.isArray(dest)
|
|
123
|
-
? dest[0]
|
|
124
|
-
: typeof dest === "object" && dest !== null
|
|
125
|
-
? Object.values(dest)[0]
|
|
126
|
-
: (dest ?? 0);
|
|
127
|
-
return [f, target];
|
|
128
|
-
});
|
|
129
|
-
return [kind, edges];
|
|
130
|
-
});
|
|
131
|
-
}
|
|
132
|
-
throw new Error("Invalid pattern representation for access table generation");
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
/**
|
|
136
|
-
* Builds an Access Table bridging an Input Schema S to Function
|
|
137
|
-
* Pattern P.
|
|
138
|
-
*
|
|
139
|
-
* @param {Array|Object} schema - Concrete input value schema S
|
|
140
|
-
* @param {Array|Object} pattern - Function's input pattern graph P
|
|
141
|
-
* @param {Object} [options]
|
|
142
|
-
* @param {number} [options.wordSize=8] - Word size in bytes (default: 8)
|
|
143
|
-
* @returns {AccessTable}
|
|
144
|
-
*/
|
|
145
|
-
export function buildAccessTable(schema, pattern, options = {}) {
|
|
146
|
-
const wordSize = options.wordSize ?? 8;
|
|
147
|
-
const sList = toPropertyList(schema);
|
|
148
|
-
const pList = toPropertyList(pattern);
|
|
149
|
-
|
|
150
|
-
const stateCount = sList.length;
|
|
151
|
-
const descriptors = new Array(stateCount);
|
|
152
|
-
|
|
153
|
-
const schemaRoot = options.schemaRoot ?? 0;
|
|
154
|
-
const patternRoot = options.patternRoot ?? 0;
|
|
155
|
-
|
|
156
|
-
// Simulation worklist: pairs of [stateInS, stateInP]
|
|
157
|
-
const visited = new Set();
|
|
158
|
-
const worklist = [[schemaRoot, patternRoot]];
|
|
159
|
-
|
|
160
|
-
while (worklist.length > 0) {
|
|
161
|
-
const [sId, pId] = worklist.shift();
|
|
162
|
-
const key = `${sId}:${pId}`;
|
|
163
|
-
if (visited.has(key)) continue;
|
|
164
|
-
visited.add(key);
|
|
165
|
-
|
|
166
|
-
const sNode = sList[sId];
|
|
167
|
-
const pNode = pList[pId];
|
|
168
|
-
if (!sNode || !pNode) continue;
|
|
169
|
-
|
|
170
|
-
const [sKind, sEdges] = sNode;
|
|
171
|
-
const [pKind, pEdges] = pNode;
|
|
172
|
-
|
|
173
|
-
const sIsUnion = sKind.includes("union");
|
|
174
|
-
const pIsUnion = pKind.includes("union");
|
|
175
|
-
|
|
176
|
-
if (sIsUnion !== pIsUnion && sKind !== "any" && pKind !== "any") {
|
|
177
|
-
throw new Error(
|
|
178
|
-
`Structural mismatch at S[${sId}] (${sKind}) vs P[${pId}] (${pKind})`
|
|
179
|
-
);
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
if (sIsUnion) {
|
|
183
|
-
// Sort variant tags in S alphabetically to define physical tag IDs
|
|
184
|
-
const sortedSEdges = [...sEdges].sort((a, b) =>
|
|
185
|
-
a[0].localeCompare(b[0])
|
|
186
|
-
);
|
|
187
|
-
const pEdgeMap = new Map(
|
|
188
|
-
pEdges.map(([label, target], idx) => [
|
|
189
|
-
label,
|
|
190
|
-
{ target, branchIdx: idx }
|
|
191
|
-
])
|
|
192
|
-
);
|
|
193
|
-
|
|
194
|
-
const tags = {};
|
|
195
|
-
const branchMap = [];
|
|
196
|
-
const childStateMap = [];
|
|
197
|
-
|
|
198
|
-
sortedSEdges.forEach(([tag, sTarget], tagId) => {
|
|
199
|
-
const pMatch = pEdgeMap.get(tag);
|
|
200
|
-
const branchId = pMatch ? pMatch.branchIdx : -1;
|
|
201
|
-
const pTarget = pMatch ? pMatch.target : null;
|
|
202
|
-
|
|
203
|
-
tags[tag] = {
|
|
204
|
-
tagId,
|
|
205
|
-
branchId,
|
|
206
|
-
childState: sTarget,
|
|
207
|
-
childPatternState: pTarget
|
|
208
|
-
};
|
|
209
|
-
branchMap[tagId] = branchId;
|
|
210
|
-
childStateMap[tagId] = sTarget;
|
|
211
|
-
|
|
212
|
-
if (pTarget != null && pTarget < pList.length) {
|
|
213
|
-
worklist.push([sTarget, pTarget]);
|
|
214
|
-
}
|
|
215
|
-
});
|
|
216
|
-
|
|
217
|
-
descriptors[sId] = {
|
|
218
|
-
state: sId,
|
|
219
|
-
kind: "union",
|
|
220
|
-
isOpen: sKind.startsWith("open"),
|
|
221
|
-
variantCount: sortedSEdges.length,
|
|
222
|
-
tags,
|
|
223
|
-
branchMap,
|
|
224
|
-
childStateMap
|
|
225
|
-
};
|
|
226
|
-
} else if (sKind.includes("product")) {
|
|
227
|
-
// Physical layout of fields in S: sorted by label
|
|
228
|
-
const sortedSEdges = [...sEdges].sort((a, b) =>
|
|
229
|
-
a[0].localeCompare(b[0])
|
|
230
|
-
);
|
|
231
|
-
const sFieldMap = new Map(
|
|
232
|
-
sortedSEdges.map(([label, target], idx) => [
|
|
233
|
-
label,
|
|
234
|
-
{ target, physicalSlot: idx }
|
|
235
|
-
])
|
|
236
|
-
);
|
|
237
|
-
|
|
238
|
-
const fields = {};
|
|
239
|
-
const slotToByteOffset = [];
|
|
240
|
-
const slotToChildState = [];
|
|
241
|
-
const slotToSkipCount = [];
|
|
242
|
-
|
|
243
|
-
pEdges.forEach(([field, pTarget], logicalSlot) => {
|
|
244
|
-
const sMatch = sFieldMap.get(field);
|
|
245
|
-
if (!sMatch) {
|
|
246
|
-
if (!pKind.startsWith("open")) {
|
|
247
|
-
throw new Error(`Required field '${field}' missing in S[${sId}]`);
|
|
248
|
-
}
|
|
249
|
-
return;
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
const physicalSlot = sMatch.physicalSlot;
|
|
253
|
-
const sTarget = sMatch.target;
|
|
254
|
-
const byteOffset = physicalSlot * wordSize;
|
|
255
|
-
const skipCount = physicalSlot;
|
|
256
|
-
|
|
257
|
-
fields[field] = {
|
|
258
|
-
logicalSlot,
|
|
259
|
-
physicalSlot,
|
|
260
|
-
byteOffset,
|
|
261
|
-
skipCount,
|
|
262
|
-
childState: sTarget,
|
|
263
|
-
childPatternState: pTarget
|
|
264
|
-
};
|
|
265
|
-
|
|
266
|
-
slotToByteOffset[logicalSlot] = byteOffset;
|
|
267
|
-
slotToChildState[logicalSlot] = sTarget;
|
|
268
|
-
slotToSkipCount[logicalSlot] = skipCount;
|
|
269
|
-
|
|
270
|
-
if (pTarget < pList.length) {
|
|
271
|
-
worklist.push([sTarget, pTarget]);
|
|
272
|
-
}
|
|
273
|
-
});
|
|
274
|
-
|
|
275
|
-
descriptors[sId] = {
|
|
276
|
-
state: sId,
|
|
277
|
-
kind: "product",
|
|
278
|
-
isOpen: sKind.startsWith("open"),
|
|
279
|
-
fieldCount: sortedSEdges.length,
|
|
280
|
-
fields,
|
|
281
|
-
slotToByteOffset,
|
|
282
|
-
slotToChildState,
|
|
283
|
-
slotToSkipCount
|
|
284
|
-
};
|
|
285
|
-
} else {
|
|
286
|
-
descriptors[sId] = {
|
|
287
|
-
state: sId,
|
|
288
|
-
kind: "any"
|
|
289
|
-
};
|
|
290
|
-
}
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
// Populate any unreached states in S as self-contained descriptors
|
|
294
|
-
for (let sId = 0; sId < stateCount; sId++) {
|
|
295
|
-
if (!descriptors[sId]) {
|
|
296
|
-
const [sKind, sEdges] = sList[sId];
|
|
297
|
-
if (sKind.includes("union")) {
|
|
298
|
-
const sorted = [...sEdges].sort((a, b) => a[0].localeCompare(b[0]));
|
|
299
|
-
descriptors[sId] = {
|
|
300
|
-
state: sId,
|
|
301
|
-
kind: "union",
|
|
302
|
-
isOpen: sKind.startsWith("open"),
|
|
303
|
-
variantCount: sorted.length,
|
|
304
|
-
tags: Object.fromEntries(
|
|
305
|
-
sorted.map(([t, target], i) => [
|
|
306
|
-
t,
|
|
307
|
-
{ tagId: i, branchId: i, childState: target }
|
|
308
|
-
])
|
|
309
|
-
),
|
|
310
|
-
branchMap: sorted.map((_, i) => i),
|
|
311
|
-
childStateMap: sorted.map(([_, target]) => target)
|
|
312
|
-
};
|
|
313
|
-
} else if (sKind.includes("product")) {
|
|
314
|
-
const sorted = [...sEdges].sort((a, b) => a[0].localeCompare(b[0]));
|
|
315
|
-
descriptors[sId] = {
|
|
316
|
-
state: sId,
|
|
317
|
-
kind: "product",
|
|
318
|
-
isOpen: sKind.startsWith("open"),
|
|
319
|
-
fieldCount: sorted.length,
|
|
320
|
-
fields: Object.fromEntries(
|
|
321
|
-
sorted.map(([f, target], i) => [
|
|
322
|
-
f,
|
|
323
|
-
{
|
|
324
|
-
logicalSlot: i,
|
|
325
|
-
physicalSlot: i,
|
|
326
|
-
byteOffset: i * wordSize,
|
|
327
|
-
skipCount: i,
|
|
328
|
-
childState: target
|
|
329
|
-
}
|
|
330
|
-
])
|
|
331
|
-
),
|
|
332
|
-
slotToByteOffset: sorted.map((_, i) => i * wordSize),
|
|
333
|
-
slotToChildState: sorted.map(([_, target]) => target),
|
|
334
|
-
slotToSkipCount: sorted.map((_, i) => i)
|
|
335
|
-
};
|
|
336
|
-
} else {
|
|
337
|
-
descriptors[sId] = { state: sId, kind: "any" };
|
|
338
|
-
}
|
|
339
|
-
}
|
|
340
|
-
}
|
|
341
|
-
|
|
342
|
-
return new AccessTable(descriptors, schemaRoot, wordSize);
|
|
343
|
-
}
|