@fraczak/k 8.4.1 → 8.5.1

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.
Files changed (116) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/DOCS/ARCHITECTURE.md +83 -0
  3. package/DOCS/CODECS.md +93 -204
  4. package/DOCS/DICTIONARY.md +42 -1241
  5. package/DOCS/FILE_FORMATS.md +170 -625
  6. package/DOCS/GETTING_STARTED.md +164 -0
  7. package/DOCS/KIR_V1.md +22 -33
  8. package/DOCS/KVM_EXECUTION_MODEL.md +88 -481
  9. package/DOCS/PATTERNS.md +155 -138
  10. package/DOCS/POLYMORPHIC_IR.md +83 -101
  11. package/DOCS/PROFILING_AND_TRACING.md +52 -166
  12. package/DOCS/README.md +35 -0
  13. package/DOCS/REPL.md +100 -377
  14. package/DOCS/TEXTUAL_VALUES.md +53 -81
  15. package/DOCS/TYPE_DERIVATION.md +95 -234
  16. package/DOCS/book-combined.md +3786 -0
  17. package/Examples/arithmetics.k +45 -59
  18. package/Examples/djson.k +102 -112
  19. package/Examples/karatsuba-mult.k +2 -3
  20. package/Examples/list.k +6 -7
  21. package/Examples/nat.k +6 -6
  22. package/Examples/poly.k +45 -45
  23. package/LICENSE +15 -0
  24. package/README.md +72 -410
  25. package/backends/llvm/README.md +75 -97
  26. package/backends/llvm/src/kvm2llvm.mjs +5 -4
  27. package/backends/llvm/src/llvm.mjs +2 -1
  28. package/backends/llvm/tests/integration.sh +7 -0
  29. package/backends/llvm/tests/test-llvm.mjs +20 -0
  30. package/backends/wasm/README.md +88 -66
  31. package/backends/wasm/src/kvm2wasm.mjs +64 -18
  32. package/backends/wasm/tests/integration.sh +5 -0
  33. package/backends/wasm/tests/test-wasm.mjs +86 -2
  34. package/canonical-pattern.mjs +7 -3
  35. package/codecs/README.md +23 -261
  36. package/codecs/WIRE_FORMAT.md +132 -0
  37. package/core.k +5 -15
  38. package/named-patterns.mjs +19 -7
  39. package/objects/README.md +24 -109
  40. package/package.json +8 -3
  41. package/paper/Makefile +17 -0
  42. package/paper/k-paper.pdf +0 -0
  43. package/paper/k-paper.tex +435 -0
  44. package/parser.jison +0 -10
  45. package/parser.mjs +32 -43
  46. package/repl.mjs +74 -29
  47. package/scripts/benchmark-idempotency.mjs +3 -3
  48. package/scripts/run-tests.mjs +1 -1
  49. package/scripts/test-package.mjs +64 -0
  50. package/tests/README.md +66 -46
  51. package/tests/code-derivation/core.mjs +61 -0
  52. package/tests/helpers/cli.mjs +45 -0
  53. package/tests/integration.sh +2 -3
  54. package/tests/test-arithmetics.mjs +47 -237
  55. package/tests/test-djson-methods.mjs +71 -275
  56. package/tests/test-hash-normalization.mjs +22 -1
  57. package/tests/test-karatsuba.mjs +18 -126
  58. package/tests/test-named-patterns.mjs +174 -621
  59. package/tests/test-paper-examples.mjs +90 -0
  60. package/tests/test-poly.mjs +2 -2
  61. package/tests/test-repl-html.mjs +22 -10
  62. package/tests/test-repl.mjs +49 -41
  63. package/tests/test.mjs +27 -68
  64. package/AGENTS.md +0 -35
  65. package/CLAUDE.md +0 -64
  66. package/DOCS/BIG_PICTURE.md +0 -439
  67. package/DOCS/BINARY_CODEC_STATUS_AND_TODO.md +0 -74
  68. package/DOCS/CANONICAL_PATTERNS.md +0 -362
  69. package/DOCS/CODEC_ARCHITECTURE.md +0 -257
  70. package/DOCS/CONVERGENCE.md +0 -123
  71. package/DOCS/DIVERGENCE_DETECTION.md +0 -23
  72. package/DOCS/JSON_APPROACHES_COMPARISON.md +0 -302
  73. package/DOCS/KIR_SPECIALIZATION_DESIGN.md +0 -472
  74. package/DOCS/Makefile +0 -99
  75. package/DOCS/NAMED_PATTERNS.md +0 -361
  76. package/DOCS/OBJECT_FILE_AND_PATTERN.md +0 -343
  77. package/DOCS/PATTERNS_AND_TYPED_VALUES.md +0 -665
  78. package/DOCS/WEB_REPL_REQUIREMENTS.md +0 -134
  79. package/DOCS/book/01-introduction.md +0 -48
  80. package/DOCS/book/02-syntax-and-values.md +0 -110
  81. package/DOCS/book/03-types-as-finite-automata.md +0 -155
  82. package/DOCS/book/04-partial-functions-and-composition.md +0 -145
  83. package/DOCS/book/05-typing-filters-and-normalization.md +0 -109
  84. package/DOCS/book/06-values-in-memory.md +0 -1085
  85. package/DOCS/book/07-the-partial-function-abi.md +0 -143
  86. package/DOCS/book/08-operational-semantics-and-execution.md +0 -196
  87. package/DOCS/book/09-compiler-architecture.md +0 -160
  88. package/DOCS/book/10-from-ast-to-intermediate-representation.md +0 -166
  89. package/DOCS/book/14-canonical-serialization.md +0 -176
  90. package/DOCS/book/appendix-b-incorporating-external-predefined-types-and-functions.md +0 -156
  91. package/DOCS/book/overview.txt +0 -68
  92. package/DOCS/book.md +0 -50
  93. package/Examples/bnat.k +0 -308
  94. package/Examples/buda.k +0 -66
  95. package/Examples/byte.k +0 -35
  96. package/Examples/code.k +0 -43
  97. package/Examples/vhdl_to_k.k +0 -67
  98. package/JOURNAL.md +0 -288
  99. package/TODO.md +0 -107
  100. package/backends/wasm/DOCS/USE-WEB-ASSEMBLY.md +0 -233
  101. package/backends/wasm/TECHNICAL-DEBT.md +0 -58
  102. package/backends/wasm/demo_ieee.mjs +0 -318
  103. package/browser/vfs-data.mjs +0 -21
  104. package/codecs/BINARY_FORMAT.md +0 -53
  105. package/codecs/POLYMORPHIC_BINARY_FORMAT.md +0 -303
  106. package/codecs/pandoc.css +0 -71
  107. package/tests/code-derivation/blowup.mjs +0 -25
  108. package/tests/code-derivation/bnat.mjs +0 -11
  109. package/tests/code-derivation/dot.mjs +0 -37
  110. package/tests/code-derivation/index.mjs +0 -20
  111. package/tests/code-derivation/loop.mjs +0 -17
  112. package/tests/code-derivation/nat.mjs +0 -10
  113. package/tests/code-derivation/not-not.mjs +0 -14
  114. package/tests/code-derivation/product.mjs +0 -22
  115. package/tests/code-derivation/rlz.mjs +0 -13
  116. package/tests/test-fingerprint.mjs +0 -38
@@ -1,318 +0,0 @@
1
- import fs from "node:fs";
2
- import assert from "node:assert/strict";
3
- import wabtFactory from "wabt";
4
- import {
5
- codes,
6
- createState,
7
- evaluateInput,
8
- executeKVM,
9
- exportPatternGraph,
10
- fromObject,
11
- isProduct,
12
- isVariant,
13
- lowerToKVM,
14
- parseFloat64,
15
- patternToPropertyList,
16
- printFloat64,
17
- propertyListToPattern,
18
- valueForCode,
19
- Value
20
- } from "@fraczak/k/backend-api.mjs";
21
- import { lowerToWasm, getTagId, getTagFromId, getFuncNameFromId } from "./src/kvm2wasm.mjs";
22
-
23
- console.log("==> Starting Wasm IEEE-754 Square Demo");
24
-
25
- // Initialize WABT
26
- const wabtInstance = await wabtFactory();
27
-
28
- function compileWat(filename, watText) {
29
- const watModule = wabtInstance.parseWat(filename, watText, {
30
- mutable_globals: true,
31
- sat_float_to_int: true,
32
- sign_extension: true,
33
- multi_value: true,
34
- bulk_memory: true,
35
- reference_types: true
36
- });
37
- watModule.resolveNames();
38
- watModule.validate();
39
- const binary = watModule.toBinary({
40
- log: false,
41
- canonicalize_lebs: true,
42
- relocatable: false,
43
- write_debug_names: true
44
- });
45
- return binary.buffer;
46
- }
47
-
48
- // 1. Create REPL state and load ieee.k library
49
- console.log("Loading IEEE-754 arithmetic library (@fraczak/k/Examples/ieee.k)...");
50
- const state = createState();
51
- const ieeePath = fileURLToPath(import.meta.resolve("@fraczak/k/Examples/ieee.k"));
52
- await evaluateInput(`:load ${ieeePath}`, state);
53
-
54
- // 2. Define the squaring relation: square = { () x, () y } mul;
55
- console.log("Defining relation: square = { () x, () y } mul;");
56
- await evaluateInput("square = { () x, () y } mul;", state);
57
- await evaluateInput("get_sign = $float64 .sign;", state);
58
-
59
- // 3. Compile and Link relations recursively starting from square
60
- console.log("Compiling and linking Wasm module...");
61
-
62
- const cleanName = (h) => "rel_" + h.replace(/[^a-zA-Z0-9_]/g, "_");
63
-
64
- function compileModule(mainRelHash) {
65
- const compiled = new Set();
66
- const queue = [mainRelHash];
67
- const wats = [];
68
-
69
- while (queue.length > 0) {
70
- const hash = queue.shift();
71
- if (compiled.has(hash)) continue;
72
- compiled.add(hash);
73
-
74
- const relDef = state.rels[hash];
75
- if (!relDef) {
76
- throw new Error(`Relation hash ${hash} not found`);
77
- }
78
-
79
- const kvmFunc = lowerToKVM(relDef, hash);
80
- kvmFunc.typePatternGraph = relDef.typePatternGraph;
81
-
82
- // Scan for call dependencies using raw hashes
83
- for (const inst of kvmFunc.body) {
84
- if (inst.op === "call") {
85
- if (!compiled.has(inst.func) && !queue.includes(inst.func)) {
86
- queue.push(inst.func);
87
- }
88
- }
89
- if (inst.op === "call_intrinsic") {
90
- console.log(`FOUND INTRINSIC: ${inst.symbol} in relation ${hash}`);
91
- }
92
- if (inst.branches) {
93
- const scan = (insts) => {
94
- for (const sub of insts) {
95
- if (sub.op === "call") {
96
- if (!compiled.has(sub.func) && !queue.includes(sub.func)) {
97
- queue.push(sub.func);
98
- }
99
- }
100
- if (sub.op === "call_intrinsic") {
101
- console.log(`FOUND INTRINSIC: ${sub.symbol} in relation ${hash}`);
102
- }
103
- if (sub.branches) {
104
- for (const br of sub.branches) {
105
- scan(br.body);
106
- }
107
- }
108
- }
109
- };
110
- for (const br of inst.branches) {
111
- scan(br.body);
112
- }
113
- }
114
- }
115
-
116
- // Rename functions in KVM IR to valid Wasm identifiers
117
- kvmFunc.name = cleanName(hash);
118
- const cleanInsts = (insts) => {
119
- for (const inst of insts) {
120
- if (inst.op === "call") {
121
- inst.func = cleanName(inst.func);
122
- }
123
- if (inst.branches) {
124
- for (const br of inst.branches) {
125
- cleanInsts(br.body);
126
- }
127
- }
128
- }
129
- };
130
- cleanInsts(kvmFunc.body);
131
-
132
- const wat = lowerToWasm(kvmFunc, kvmFunc.name, { trace: true });
133
- if (hash === squareHash) {
134
- console.log("==> KVM IR for square:", JSON.stringify(kvmFunc.body, null, 2));
135
- console.log("==> Compiled WAT for square:\n", wat);
136
- }
137
- wats.push(wat);
138
- }
139
-
140
- return wats.join("\n\n");
141
- }
142
-
143
- const squareHash = state.relAliases["square"];
144
- const getSignHash = state.relAliases["get_sign"];
145
- const moduleWatBody = compileModule(squareHash);
146
- const getSignWat = lowerToWasm(state.rels[getSignHash], "get_sign", { trace: true });
147
- console.log("==> Compiled WAT for get_sign:\n", getSignWat);
148
- const runtimeWat = fs.readFileSync("runtime.wat", "utf8");
149
-
150
- // Combine Wasm runtime and compiled relations
151
- const declarations = `
152
- (import "env" "log_call" (func $log_call (param i32 i32)))
153
- (import "env" "log_ret" (func $log_ret (param i32 i32 i32)))
154
- `;
155
- const runtimeWatWithImports = runtimeWat.replace("(module", "(module\n" + declarations);
156
- const fullWat = runtimeWatWithImports.trim().slice(0, -1) + "\n" + moduleWatBody + "\n" + getSignWat + "\n)";
157
- fs.writeFileSync("debug_full.wat", fullWat);
158
- const binary = compileWat("square_demo.wat", fullWat);
159
- const module = await WebAssembly.compile(binary);
160
- const imports = {
161
- env: {
162
- log_call: (funcId, ptrIn) => {
163
- const funcName = getFuncNameFromId(funcId);
164
- console.log(`[Wasm Trace] Calling ${funcName} with input ptr ${ptrIn}`);
165
- },
166
- log_ret: (funcId, ptrOut, ok) => {
167
- const funcName = getFuncNameFromId(funcId);
168
- console.log(`[Wasm Trace] Returned from ${funcName} -> ptr ${ptrOut}, ok ${ok}`);
169
- }
170
- }
171
- };
172
- const instance = await WebAssembly.instantiate(module, imports);
173
- const exports = instance.exports;
174
-
175
- // JS Arena helpers
176
- function readArenaValue(exports, ptr, pattern, patternNodeId) {
177
- const patternNode = pattern.nodes[patternNodeId];
178
- const view = new DataView(exports.memory.buffer);
179
-
180
- if (patternNode.kind === 1 || patternNode.kind === 3) {
181
- const size = view.getUint32(ptr, true);
182
- const N = view.getUint32(ptr + 4, true);
183
- const productObj = {};
184
-
185
- for (let i = 0; i < N; i++) {
186
- const edge = patternNode.edges[i];
187
- const childPtr = view.getUint32(ptr + 8 + 4 * N + 4 * i, true);
188
- productObj[edge.label] = readArenaValue(exports, childPtr, pattern, edge.target);
189
- }
190
- return Value.product(productObj, pattern);
191
- } else if (patternNode.kind === 2 || patternNode.kind === 4) {
192
- const size = view.getUint32(ptr, true);
193
- const tagId = view.getUint32(ptr + 4, true);
194
- const payloadPtr = view.getUint32(ptr + 8, true);
195
-
196
- const tag = getTagFromId(tagId);
197
- console.log(`[Debug Arena] Read Variant at ptr=${ptr}: size=${size}, tagId=${tagId}, tag=${tag}`);
198
- const edge = patternNode.edges.find(e => e.label === tag);
199
- if (!edge) {
200
- throw new Error(`Variant tag '${tag}' not found in pattern edges`);
201
- }
202
- const payloadVal = readArenaValue(exports, payloadPtr, pattern, edge.target);
203
- return Value.variant(tag, payloadVal, pattern);
204
- }
205
- throw new Error(`Unsupported pattern kind: ${patternNode.kind}`);
206
- }
207
-
208
- function writeValueToArena(value, pattern, patternNodeId) {
209
- const patternNode = pattern.nodes[patternNodeId];
210
-
211
- if (isProduct(value)) {
212
- const keys = Object.keys(value.product).sort();
213
- const N = keys.length;
214
- const totalSize = 8 + 8 * N;
215
-
216
- // Evaluate and allocate all children first
217
- const childPtrs = [];
218
- for (let i = 0; i < N; i++) {
219
- const label = keys[i];
220
- const edge = patternNode.edges.find(e => e.label === label);
221
- const childPtr = writeValueToArena(value.product[label], pattern, edge.target);
222
- childPtrs.push(childPtr);
223
- }
224
-
225
- const ptr = exports.alloc(totalSize);
226
- const view = new DataView(exports.memory.buffer);
227
-
228
- view.setUint32(ptr, totalSize, true);
229
- view.setUint32(ptr + 4, N, true);
230
-
231
- for (let i = 0; i < N; i++) {
232
- const offsetVal = 8 + 4 * N + 4 * i;
233
- view.setUint32(ptr + 8 + 4 * i, getTagId(keys[i]), true);
234
- view.setUint32(ptr + offsetVal, childPtrs[i], true);
235
- }
236
- return ptr;
237
- } else if (isVariant(value)) {
238
- const tagId = getTagId(value.tag);
239
- const edge = patternNode.edges.find(e => e.label === value.tag);
240
- const childPtr = writeValueToArena(value.value, pattern, edge.target);
241
-
242
- const ptr = exports.alloc(12);
243
- const view = new DataView(exports.memory.buffer);
244
-
245
- view.setUint32(ptr, 12, true);
246
- view.setUint32(ptr + 4, tagId, true);
247
- view.setUint32(ptr + 8, childPtr, true);
248
- console.log(`[Debug Arena] Wrote Variant at ptr=${ptr}: tag=${value.tag}, tagId=${tagId}`);
249
- return ptr;
250
- }
251
- throw new Error(`Unsupported value type: ${value}`);
252
- }
253
-
254
- function getPattern(graph, patternId) {
255
- const nodeId = graph.find(patternId);
256
- return propertyListToPattern(patternToPropertyList(exportPatternGraph(graph, nodeId)));
257
- }
258
-
259
- // 4. Run on an input
260
- const inputValStr = "1.5";
261
- console.log(`\nInput float64 value: ${inputValStr}`);
262
-
263
- // Convert input string to IEEE float64 tree
264
- const float64Hash = state.typeAliases.float64;
265
- const parsedFloatVal = valueForCode(parseFloat64(inputValStr), float64Hash, codes.find);
266
-
267
- // Resolve patterns
268
- const squareRel = state.rels[squareHash];
269
- const graph = squareRel.typePatternGraph;
270
- const inputPattern = getPattern(graph, squareRel.def.patterns[0]);
271
- const outputPattern = getPattern(graph, squareRel.def.patterns[1]);
272
-
273
- // Run the JS interpreter first to check
274
- const kvmFuncSquare = lowerToKVM(squareRel, squareHash);
275
- const context = { rels: state.rels, findCode: codes.find, options: { envelopeFree: true, trace: false } };
276
- const jsRes = executeKVM(kvmFuncSquare, parsedFloatVal, context);
277
- console.log("JS Interpreter result:", jsRes ? printFloat64(jsRes.product.result) : "failed");
278
-
279
- // Print keys and patterns for debugging
280
- console.log("==> parsedFloatVal keys:", Object.keys(parsedFloatVal.product));
281
- console.log("==> inputPattern node 0:", JSON.stringify(inputPattern.nodes[0], null, 2));
282
- console.log("==> outputPattern node 0:", JSON.stringify(outputPattern.nodes[0], null, 2));
283
-
284
- // Write input to the arena
285
- const ptrIn = writeValueToArena(parsedFloatVal, inputPattern, 0);
286
-
287
- // Call get_sign to test basic projection
288
- console.log("Calling Wasm function 'get_sign'...");
289
- const getSignRes = exports.get_sign(ptrIn);
290
- if (getSignRes[1] === 1) {
291
- const getSignRel = state.rels[getSignHash];
292
- const getSignPattern = getPattern(getSignRel.typePatternGraph, getSignRel.def.patterns[1]);
293
- const getSignVal = readArenaValue(exports, getSignRes[0], getSignPattern, 0);
294
- console.log("get_sign output tag:", getSignVal.tag);
295
- } else {
296
- console.log("get_sign failed!");
297
- }
298
-
299
- // Run the Wasm function
300
- console.log("Calling Wasm function 'square'...");
301
- const mainFuncName = cleanName(squareHash);
302
- const result = exports[mainFuncName](ptrIn);
303
-
304
- if (result[1] !== 1) {
305
- console.error("Wasm execution failed!");
306
- process.exit(1);
307
- }
308
-
309
- // Read and decode output from the arena
310
- const outputVal = readArenaValue(exports, result[0], outputPattern, 0);
311
-
312
- // Print the result using ieee print float64 codec helper
313
- const outputResultFloat = outputVal.product.result;
314
- const printResult = printFloat64(outputResultFloat);
315
-
316
- console.log(`Result of (${inputValStr} * ${inputValStr}): ${printResult}`);
317
- console.log("Flags:", outputVal.product.flags.tag);
318
- console.log("==> Demo finished successfully!");