@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.
- package/CHANGELOG.md +32 -0
- package/DOCS/ARCHITECTURE.md +83 -0
- package/DOCS/CODECS.md +93 -204
- package/DOCS/DICTIONARY.md +42 -1241
- package/DOCS/FILE_FORMATS.md +170 -625
- package/DOCS/GETTING_STARTED.md +164 -0
- package/DOCS/KIR_V1.md +22 -33
- package/DOCS/KVM_EXECUTION_MODEL.md +88 -481
- package/DOCS/PATTERNS.md +155 -138
- package/DOCS/POLYMORPHIC_IR.md +83 -101
- package/DOCS/PROFILING_AND_TRACING.md +52 -166
- package/DOCS/README.md +35 -0
- package/DOCS/REPL.md +100 -377
- package/DOCS/TEXTUAL_VALUES.md +53 -81
- package/DOCS/TYPE_DERIVATION.md +95 -234
- package/DOCS/book-combined.md +3786 -0
- package/Examples/arithmetics.k +45 -59
- package/Examples/djson.k +102 -112
- package/Examples/karatsuba-mult.k +2 -3
- package/Examples/list.k +6 -7
- package/Examples/nat.k +6 -6
- package/Examples/poly.k +45 -45
- package/LICENSE +15 -0
- package/README.md +72 -410
- package/backends/llvm/README.md +75 -97
- 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/README.md +88 -66
- package/backends/wasm/src/kvm2wasm.mjs +64 -18
- package/backends/wasm/tests/integration.sh +5 -0
- package/backends/wasm/tests/test-wasm.mjs +86 -2
- package/canonical-pattern.mjs +7 -3
- package/codecs/README.md +23 -261
- package/codecs/WIRE_FORMAT.md +132 -0
- package/core.k +5 -15
- package/named-patterns.mjs +19 -7
- package/objects/README.md +24 -109
- package/package.json +8 -3
- package/paper/Makefile +17 -0
- package/paper/k-paper.pdf +0 -0
- package/paper/k-paper.tex +435 -0
- package/parser.jison +0 -10
- package/parser.mjs +32 -43
- package/repl.mjs +74 -29
- package/scripts/benchmark-idempotency.mjs +3 -3
- package/scripts/run-tests.mjs +1 -1
- package/scripts/test-package.mjs +64 -0
- package/tests/README.md +66 -46
- package/tests/code-derivation/core.mjs +61 -0
- package/tests/helpers/cli.mjs +45 -0
- package/tests/integration.sh +2 -3
- package/tests/test-arithmetics.mjs +47 -237
- package/tests/test-djson-methods.mjs +71 -275
- package/tests/test-hash-normalization.mjs +22 -1
- package/tests/test-karatsuba.mjs +18 -126
- package/tests/test-named-patterns.mjs +174 -621
- package/tests/test-paper-examples.mjs +90 -0
- package/tests/test-poly.mjs +2 -2
- package/tests/test-repl-html.mjs +22 -10
- package/tests/test-repl.mjs +49 -41
- package/tests/test.mjs +27 -68
- package/AGENTS.md +0 -35
- package/CLAUDE.md +0 -64
- package/DOCS/BIG_PICTURE.md +0 -439
- package/DOCS/BINARY_CODEC_STATUS_AND_TODO.md +0 -74
- package/DOCS/CANONICAL_PATTERNS.md +0 -362
- package/DOCS/CODEC_ARCHITECTURE.md +0 -257
- package/DOCS/CONVERGENCE.md +0 -123
- package/DOCS/DIVERGENCE_DETECTION.md +0 -23
- package/DOCS/JSON_APPROACHES_COMPARISON.md +0 -302
- package/DOCS/KIR_SPECIALIZATION_DESIGN.md +0 -472
- package/DOCS/Makefile +0 -99
- package/DOCS/NAMED_PATTERNS.md +0 -361
- package/DOCS/OBJECT_FILE_AND_PATTERN.md +0 -343
- package/DOCS/PATTERNS_AND_TYPED_VALUES.md +0 -665
- package/DOCS/WEB_REPL_REQUIREMENTS.md +0 -134
- package/DOCS/book/01-introduction.md +0 -48
- package/DOCS/book/02-syntax-and-values.md +0 -110
- package/DOCS/book/03-types-as-finite-automata.md +0 -155
- package/DOCS/book/04-partial-functions-and-composition.md +0 -145
- package/DOCS/book/05-typing-filters-and-normalization.md +0 -109
- package/DOCS/book/06-values-in-memory.md +0 -1085
- package/DOCS/book/07-the-partial-function-abi.md +0 -143
- package/DOCS/book/08-operational-semantics-and-execution.md +0 -196
- package/DOCS/book/09-compiler-architecture.md +0 -160
- package/DOCS/book/10-from-ast-to-intermediate-representation.md +0 -166
- package/DOCS/book/14-canonical-serialization.md +0 -176
- package/DOCS/book/appendix-b-incorporating-external-predefined-types-and-functions.md +0 -156
- package/DOCS/book/overview.txt +0 -68
- package/DOCS/book.md +0 -50
- package/Examples/bnat.k +0 -308
- package/Examples/buda.k +0 -66
- package/Examples/byte.k +0 -35
- package/Examples/code.k +0 -43
- package/Examples/vhdl_to_k.k +0 -67
- package/JOURNAL.md +0 -288
- package/TODO.md +0 -107
- package/backends/wasm/DOCS/USE-WEB-ASSEMBLY.md +0 -233
- package/backends/wasm/TECHNICAL-DEBT.md +0 -58
- package/backends/wasm/demo_ieee.mjs +0 -318
- package/browser/vfs-data.mjs +0 -21
- package/codecs/BINARY_FORMAT.md +0 -53
- package/codecs/POLYMORPHIC_BINARY_FORMAT.md +0 -303
- package/codecs/pandoc.css +0 -71
- package/tests/code-derivation/blowup.mjs +0 -25
- package/tests/code-derivation/bnat.mjs +0 -11
- package/tests/code-derivation/dot.mjs +0 -37
- package/tests/code-derivation/index.mjs +0 -20
- package/tests/code-derivation/loop.mjs +0 -17
- package/tests/code-derivation/nat.mjs +0 -10
- package/tests/code-derivation/not-not.mjs +0 -14
- package/tests/code-derivation/product.mjs +0 -22
- package/tests/code-derivation/rlz.mjs +0 -13
- package/tests/test-fingerprint.mjs +0 -38
package/backends/llvm/README.md
CHANGED
|
@@ -1,127 +1,87 @@
|
|
|
1
|
-
#
|
|
1
|
+
# LLVM backend
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The experimental LLVM backend lowers k programs to LLVM IR and links them with
|
|
4
|
+
the C runtime. It supports source/object execution, compiled native executables,
|
|
5
|
+
kVM input, and the experimental PKIR path.
|
|
4
6
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
`.ko` objects:
|
|
8
|
-
|
|
9
|
-
```text
|
|
10
|
-
.k source -> .ko -> envelope-specialized KIR-P -> LLVM IR prototype
|
|
11
|
-
```
|
|
12
|
-
|
|
13
|
-
The first milestone is not performance. It is a stable backend pipeline that
|
|
14
|
-
can load an object, specialize it through KIR-P, and produce an inspectable
|
|
15
|
-
LLVM module.
|
|
16
|
-
|
|
17
|
-
## Quick Start
|
|
18
|
-
|
|
19
|
-
From the monorepo root, install the workspace dependencies, then run the
|
|
20
|
-
backend from `backends/llvm`:
|
|
7
|
+
Commands belong to the root package. Install dependencies from the repository
|
|
8
|
+
root and ensure Clang is available:
|
|
21
9
|
|
|
22
10
|
```sh
|
|
23
11
|
npm install
|
|
24
|
-
|
|
25
|
-
node ../../objects/compile.mjs '()' /tmp/id.ko
|
|
26
|
-
node ./bin/k-llvm-compile.mjs /tmp/id.ko /tmp/id.ll
|
|
12
|
+
clang --version
|
|
27
13
|
```
|
|
28
14
|
|
|
29
|
-
|
|
30
|
-
|
|
15
|
+
`CLANG` or `CC` can select the compiler binary. `npm link` at the root exposes
|
|
16
|
+
`k-llvm`, `k-llvm-compile`, and `k-llvm-build`.
|
|
31
17
|
|
|
32
|
-
|
|
33
|
-
%k_result = type { i32, ptr }
|
|
18
|
+
## Compile and run
|
|
34
19
|
|
|
35
|
-
|
|
36
|
-
```
|
|
20
|
+
Build a program with a closed unit input and a constant result:
|
|
37
21
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
status in `k_result`. These operations can compose through KIR `comp`.
|
|
22
|
+
```sh
|
|
23
|
+
node backends/llvm/bin/k-llvm-build.mjs '?{} {} |ok' /tmp/k-ok.exe
|
|
24
|
+
node codecs/unit.mjs --parse | /tmp/k-ok.exe | node codecs/k-print.mjs
|
|
25
|
+
```
|
|
43
26
|
|
|
44
|
-
|
|
27
|
+
This prints `"ok"`. To compile and run directly over an input envelope:
|
|
45
28
|
|
|
46
29
|
```sh
|
|
47
|
-
|
|
48
|
-
k-llvm
|
|
49
|
-
k-
|
|
30
|
+
node codecs/unit.mjs --parse |
|
|
31
|
+
node backends/llvm/bin/k-llvm.mjs '|ok' |
|
|
32
|
+
node codecs/k-print.mjs
|
|
50
33
|
```
|
|
51
34
|
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
- `-o, --output path`: specify output file path explicitly.
|
|
55
|
-
- `--lib file`: load one `.klib` or `.k` dependency before compiling.
|
|
56
|
-
- `--export spec`: export a library alias into scope. Repeatable.
|
|
57
|
-
- `--pkir`: lower via Polymorphic K IR (PKIR).
|
|
58
|
-
- `--retype rel`: relation to specialize (defaults to object main).
|
|
59
|
-
- `--opt flag`: Clang optimization flag (-O0, -O1, -O2, -O3).
|
|
60
|
-
- `-h, --help`: show usage.
|
|
61
|
-
|
|
62
|
-
The compile commands follow the unified k CLI input convention: pass
|
|
63
|
-
inline source, an existing `.k` source file, or a `.ko`/`.klib` object.
|
|
64
|
-
Reads UTF-8 source from stdin when input is omitted. Output paths can be
|
|
65
|
-
specified as a positional argument or explicitly with `-o, --output`.
|
|
66
|
-
`k-llvm-build` emits a native executable that reads and writes the binary
|
|
67
|
-
k pattern+value envelope used by `codecs/k-parse.mjs` and
|
|
68
|
-
`codecs/k-print.mjs`. The executable checks the stdin envelope pattern
|
|
69
|
-
against the compiled input pattern and encodes stdout with the compiled
|
|
70
|
-
output pattern.
|
|
71
|
-
`k-llvm` reads the binary wire envelope, specializes the relation to
|
|
72
|
-
that input pattern, caches the compiled native executable, and writes
|
|
73
|
-
the compiled output envelope to stdout.
|
|
74
|
-
The native envelope codec supports the k Unicode string encoding used
|
|
75
|
-
for labels and tags.
|
|
76
|
-
|
|
77
|
-
## Tests
|
|
35
|
+
To inspect generated LLVM IR:
|
|
78
36
|
|
|
79
37
|
```sh
|
|
80
|
-
|
|
81
|
-
node ./scripts/conformance.mjs
|
|
82
|
-
npm run perf:int
|
|
83
|
-
npm run perf:ieee
|
|
38
|
+
node backends/llvm/bin/k-llvm-compile.mjs '?{} {} |ok' /tmp/k-ok.ll
|
|
84
39
|
```
|
|
85
40
|
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
41
|
+
## Commands and options
|
|
42
|
+
|
|
43
|
+
| Command | Result |
|
|
44
|
+
| --- | --- |
|
|
45
|
+
| `k-llvm` | Compile, cache, and execute a native program for an input envelope |
|
|
46
|
+
| `k-llvm-compile` | Emit textual LLVM IR |
|
|
47
|
+
| `k-llvm-build` | Link a standalone executable that reads/writes k wire values |
|
|
89
48
|
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
cases fail the process. The LLVM lane uses persistent executables by default;
|
|
96
|
-
set `LLVM_PIPELINE=1` to measure parallel request pipelining or
|
|
97
|
-
`LLVM_SPAWN_PER_CALL=1` to reproduce the older spawn-per-operation timing.
|
|
49
|
+
Compile/build commands accept inline source or a source, `.ko`, `.kvm`, or
|
|
50
|
+
`.pkir` input. A `.klib` needs a selected relation, supplied through the
|
|
51
|
+
tool's `--retype` option or linked into source with a terminal expression.
|
|
52
|
+
Source is read from stdin when omitted. The execution command instead requires
|
|
53
|
+
a program argument and reads binary input from stdin or an optional filename.
|
|
98
54
|
|
|
99
|
-
|
|
55
|
+
Common compile options:
|
|
100
56
|
|
|
101
|
-
|
|
57
|
+
- `-o` / `--output path`: output path instead of a positional output.
|
|
58
|
+
- `--lib file`: one `.k` or `.klib` dependency.
|
|
59
|
+
- `--export name` or `--export libraryName:localName`: repeatable alias imports.
|
|
60
|
+
- `--pkir`: compile source through PKIR.
|
|
61
|
+
- `--retype relation`: select the relation for envelope specialization.
|
|
62
|
+
- `--opt flag`: Clang optimization flag.
|
|
102
63
|
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
- KIR `comp` lowering for sequencing supported operations;
|
|
109
|
-
- KIR `empty` failure and ordered `union` branch selection;
|
|
110
|
-
- KIR `ref` lowering to internal `%k_result` relation functions;
|
|
111
|
-
- a tiny C runtime under `runtime/`.
|
|
64
|
+
Build/compile tools accept `--input-pattern` as JSON or a pattern file when
|
|
65
|
+
an explicit specialization input is needed. `k-llvm` derives the envelope
|
|
66
|
+
from its wire input; `--no-cache` disables reuse, and `--cache-dir` selects
|
|
67
|
+
the executable cache. Each command's `--help` lists its supported options
|
|
68
|
+
and defaults.
|
|
112
69
|
|
|
113
|
-
|
|
70
|
+
Existing program paths are read as files; recognized missing filenames are
|
|
71
|
+
errors. See [file formats](../../DOCS/FILE_FORMATS.md) for shared linking rules.
|
|
114
72
|
|
|
115
|
-
|
|
73
|
+
## Runtime contract
|
|
116
74
|
|
|
117
|
-
|
|
75
|
+
Compiled programs retain input/output patterns for wire boundaries. A native
|
|
76
|
+
runner checks incoming schemas against the compiled contract and serializes
|
|
77
|
+
the result with its output pattern. Partial failure is distinct from malformed
|
|
78
|
+
input, type errors, or compiler failures.
|
|
118
79
|
|
|
119
|
-
The C
|
|
80
|
+
The boxed C ABI is:
|
|
120
81
|
|
|
121
82
|
```c
|
|
122
83
|
typedef struct k_rt k_rt;
|
|
123
84
|
typedef struct k_value k_value;
|
|
124
|
-
|
|
125
85
|
typedef struct {
|
|
126
86
|
int32_t status;
|
|
127
87
|
k_value *value;
|
|
@@ -130,7 +90,25 @@ typedef struct {
|
|
|
130
90
|
k_result k_main(k_rt *rt, k_value *input);
|
|
131
91
|
```
|
|
132
92
|
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
93
|
+
[runtime/krt.h](runtime/krt.h) defines helpers and ownership through the runtime;
|
|
94
|
+
[runtime/krt.c](runtime/krt.c) implements values, arenas, and wire support.
|
|
95
|
+
[kvm2llvm.mjs](src/kvm2llvm.mjs) lowers kVM functions;
|
|
96
|
+
[llvm.mjs](src/llvm.mjs) coordinates object and PKIR paths.
|
|
97
|
+
|
|
98
|
+
Unsupported operations must produce diagnostics rather than silently change
|
|
99
|
+
semantics. Backend coverage and artifact formats remain experimental.
|
|
100
|
+
|
|
101
|
+
## Verification and profiling
|
|
102
|
+
|
|
103
|
+
From the repository root:
|
|
104
|
+
|
|
105
|
+
```sh
|
|
106
|
+
npm run test:llvm
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
This includes native execution, the open-product field-alignment regression,
|
|
110
|
+
shell integration, and shared conformance fixtures.
|
|
111
|
+
|
|
112
|
+
`npm run perf:int`, `npm run perf:ieee`, and `npm run perf:poly:trace`
|
|
113
|
+
compare execution lanes. See the [profiling guide](../../DOCS/PROFILING_AND_TRACING.md)
|
|
114
|
+
for measurement boundaries and target selection.
|
|
@@ -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, {
|
package/backends/wasm/README.md
CHANGED
|
@@ -1,97 +1,119 @@
|
|
|
1
|
-
#
|
|
1
|
+
# WebAssembly backend
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
a Node.js runner for the binary `pattern + value` streams used by the k codec
|
|
7
|
-
toolchain.
|
|
3
|
+
The experimental Wasm backend compiles k relations to standard WebAssembly
|
|
4
|
+
modules using kVM and WABT. The terminal and browser REPLs also use its
|
|
5
|
+
in-process execution path.
|
|
8
6
|
|
|
9
|
-
|
|
7
|
+
Commands are provided by the root package. From the repository root:
|
|
10
8
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
```bash
|
|
9
|
+
```sh
|
|
14
10
|
npm install
|
|
15
11
|
```
|
|
16
12
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
```bash
|
|
20
|
-
npm link
|
|
21
|
-
```
|
|
13
|
+
Run the modules directly as below, or use `npm link` at the root to expose
|
|
14
|
+
`k-wasm`, `k-wasm-compile`, and `k-wasm-run`.
|
|
22
15
|
|
|
23
|
-
##
|
|
16
|
+
## Compile and run
|
|
24
17
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
node
|
|
18
|
+
```sh
|
|
19
|
+
node backends/wasm/bin/k-wasm-compile.mjs '?{} {} |ok' /tmp/k-ok.wasm
|
|
20
|
+
node codecs/unit.mjs --parse |
|
|
21
|
+
node backends/wasm/bin/k-wasm-run.mjs /tmp/k-ok.wasm |
|
|
22
|
+
node codecs/k-print.mjs
|
|
29
23
|
```
|
|
30
24
|
|
|
31
|
-
|
|
25
|
+
This prints `"ok"`. Compilation and execution in one step:
|
|
32
26
|
|
|
33
|
-
```
|
|
34
|
-
node
|
|
35
|
-
node
|
|
36
|
-
node
|
|
27
|
+
```sh
|
|
28
|
+
node codecs/unit.mjs --parse |
|
|
29
|
+
node backends/wasm/bin/k-wasm.mjs '|ok' |
|
|
30
|
+
node codecs/k-print.mjs
|
|
37
31
|
```
|
|
38
32
|
|
|
39
|
-
|
|
33
|
+
## Inputs and libraries
|
|
40
34
|
|
|
41
|
-
|
|
42
|
-
|
|
35
|
+
| Command | Purpose |
|
|
36
|
+
| --- | --- |
|
|
37
|
+
| `k-wasm` | Compile and execute a source expression/file, `.ko`, `.kvm`, or `.pkir` |
|
|
38
|
+
| `k-wasm-compile` | Produce a `.wasm` artifact from those program forms |
|
|
39
|
+
| `k-wasm-run` | Execute a previously compiled `.wasm` artifact |
|
|
40
|
+
|
|
41
|
+
The runners read binary schema+payload data from stdin or an optional input
|
|
42
|
+
filename. Compile tools read source from stdin when the program is omitted.
|
|
43
|
+
Source files need a terminal expression; a `.klib` alone is not an executable
|
|
44
|
+
input.
|
|
45
|
+
|
|
46
|
+
Compile commands accept one `--lib file` and repeated `--export alias` or
|
|
47
|
+
`--export libraryAlias:localAlias` options before the program. Libraries can
|
|
48
|
+
be `.k` source or `.klib` objects. `--pkir` chooses the experimental PKIR
|
|
49
|
+
lowering path; `-o` / `--output` selects an output path.
|
|
50
|
+
|
|
51
|
+
Existing paths are read as files. Recognized missing filenames are errors;
|
|
52
|
+
other program arguments are treated as inline source.
|
|
53
|
+
|
|
54
|
+
For a library example using only a small definition:
|
|
55
|
+
|
|
56
|
+
```sh
|
|
57
|
+
node objects/compile.mjs 'greet = {} |hello;' /tmp/k-demo.klib
|
|
58
|
+
node backends/wasm/bin/k-wasm-compile.mjs --lib /tmp/k-demo.klib --export greet '?{} greet' /tmp/k-greet.wasm
|
|
59
|
+
node codecs/unit.mjs --parse |
|
|
60
|
+
node backends/wasm/bin/k-wasm-run.mjs /tmp/k-greet.wasm |
|
|
61
|
+
node codecs/k-print.mjs
|
|
43
62
|
```
|
|
44
63
|
|
|
45
|
-
|
|
46
|
-
|
|
64
|
+
The result is `"hello"`. The library is required at compilation time; the
|
|
65
|
+
module can subsequently run without the original source/library files.
|
|
47
66
|
|
|
48
|
-
|
|
49
|
-
k-wasm-compile '|ok' /tmp/ok.wasm
|
|
50
|
-
k-unit --parse | k-wasm-run /tmp/ok.wasm | k-print
|
|
51
|
-
```
|
|
67
|
+
## Artifact and execution contract
|
|
52
68
|
|
|
53
|
-
|
|
69
|
+
A module contains the reachable functions, the arena runtime from
|
|
70
|
+
[runtime.wat](runtime.wat), and one `k.metadata` custom section.
|
|
54
71
|
|
|
55
|
-
|
|
|
72
|
+
| Metadata field | Meaning |
|
|
56
73
|
| --- | --- |
|
|
57
|
-
| `
|
|
58
|
-
| `
|
|
59
|
-
| `
|
|
74
|
+
| `format` / `version` | `"k-wasm"` / `1` |
|
|
75
|
+
| `abi` | `"arena-v1"` |
|
|
76
|
+
| `entry` | Exported function called by the runner |
|
|
77
|
+
| `inputPattern` / `outputPattern` | Patterns used by the arena adapters |
|
|
78
|
+
| `tags` | Statically known variant tags and their IDs |
|
|
60
79
|
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
or a `.kvm` program. They also accept one `--lib` option for a `.klib`
|
|
64
|
-
dependency and repeated `--export` options to bring library aliases into the
|
|
65
|
-
source scope. Existing paths are treated as files; non-existing names with
|
|
66
|
-
`.k`, `.ko`, `.kvm`, `.klib`, or `.wasm` extensions are treated as missing
|
|
67
|
-
files; other arguments are treated as inline source. The runners read a binary
|
|
68
|
-
input stream from standard input unless an input file is given.
|
|
80
|
+
The entry ABI is `(input_pointer i32) -> (output_pointer i32, ok i32)`.
|
|
81
|
+
`ok = 1` means a defined result; `ok = 0` means ordinary partial failure.
|
|
69
82
|
|
|
70
|
-
|
|
83
|
+
The host decodes a wire value, writes it into linear memory, invokes the
|
|
84
|
+
entry, reads the result under its output pattern, and writes a wire value.
|
|
85
|
+
`instantiateWasmArtifact` also exposes `executeValue` for in-memory `Value`
|
|
86
|
+
input/output and optional phase tracing.
|
|
71
87
|
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
source, object, kVM, or `.klib` files.
|
|
88
|
+
`k-wasm` can use the arriving input envelope while compiling. A precompiled
|
|
89
|
+
module runs with its stored metadata; `k-wasm-run` does not rerun derivation
|
|
90
|
+
on the original relation graph. Use one-step compilation when an input-specific
|
|
91
|
+
contract is needed.
|
|
77
92
|
|
|
78
|
-
|
|
79
|
-
WebAssembly linear memory and k binary streams.
|
|
93
|
+
## Limits and implementation
|
|
80
94
|
|
|
81
|
-
|
|
95
|
+
A `.wasm` file still needs a host that understands the arena ABI and metadata.
|
|
96
|
+
The CLI host is Node.js; the browser REPL bundles its own in-process adapter.
|
|
82
97
|
|
|
83
|
-
|
|
98
|
+
Allocation uses a bump arena. Runners reset it between completed runs; selected
|
|
99
|
+
tail-loop paths also compact live state. Temporary allocation within successful
|
|
100
|
+
non-tail calls can still increase peak memory. The host translates exported
|
|
101
|
+
out-of-memory flags into diagnostics.
|
|
84
102
|
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
103
|
+
The implementation lives in [src/wasm.mjs](src/wasm.mjs) and
|
|
104
|
+
[src/kvm2wasm.mjs](src/kvm2wasm.mjs). See
|
|
105
|
+
[compiler architecture](../../DOCS/ARCHITECTURE.md) and
|
|
106
|
+
[kVM](../../DOCS/KVM_EXECUTION_MODEL.md) for shared layers.
|
|
107
|
+
|
|
108
|
+
## Verification and profiling
|
|
88
109
|
|
|
89
|
-
|
|
110
|
+
From the repository root:
|
|
90
111
|
|
|
91
|
-
```
|
|
92
|
-
npm run
|
|
112
|
+
```sh
|
|
113
|
+
npm run test:wasm
|
|
114
|
+
npm run build:repl-html
|
|
93
115
|
```
|
|
94
116
|
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
117
|
+
For performance measurements, use `npm run perf:ieee` or
|
|
118
|
+
`npm run perf:poly:trace`. The [profiling guide](../../DOCS/PROFILING_AND_TRACING.md)
|
|
119
|
+
explains execution lanes and boundary costs.
|
|
@@ -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 }' |
|