@fraczak/k 8.4.0 → 8.5.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.
Files changed (113) hide show
  1. package/CHANGELOG.md +59 -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 +156 -123
  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 -371
  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/cli.mjs +0 -31
  27. package/backends/wasm/README.md +88 -66
  28. package/backends/wasm/src/cli.mjs +0 -31
  29. package/canonical-pattern.mjs +69 -35
  30. package/codecs/README.md +23 -261
  31. package/codecs/WIRE_FORMAT.md +132 -0
  32. package/core.k +5 -15
  33. package/index.mjs +5 -1
  34. package/named-patterns.mjs +55 -7
  35. package/object.mjs +28 -6
  36. package/objects/README.md +24 -109
  37. package/package.json +8 -3
  38. package/paper/Makefile +17 -0
  39. package/paper/k-paper.pdf +0 -0
  40. package/paper/k-paper.tex +435 -0
  41. package/parser.jison +0 -10
  42. package/parser.mjs +32 -43
  43. package/repl.mjs +79 -101
  44. package/scripts/benchmark-idempotency.mjs +3 -3
  45. package/scripts/run-tests.mjs +1 -1
  46. package/scripts/test-package.mjs +64 -0
  47. package/tests/README.md +66 -46
  48. package/tests/code-derivation/core.mjs +61 -0
  49. package/tests/helpers/cli.mjs +45 -0
  50. package/tests/integration.sh +2 -3
  51. package/tests/test-arithmetics.mjs +47 -237
  52. package/tests/test-djson-methods.mjs +71 -275
  53. package/tests/test-hash-normalization.mjs +22 -1
  54. package/tests/test-karatsuba.mjs +18 -126
  55. package/tests/test-named-patterns.mjs +174 -606
  56. package/tests/test-paper-examples.mjs +90 -0
  57. package/tests/test-poly.mjs +2 -2
  58. package/tests/test-repl-html.mjs +2 -2
  59. package/tests/test-repl.mjs +89 -38
  60. package/tests/test.mjs +27 -68
  61. package/AGENTS.md +0 -35
  62. package/CLAUDE.md +0 -64
  63. package/DOCS/BIG_PICTURE.md +0 -439
  64. package/DOCS/BINARY_CODEC_STATUS_AND_TODO.md +0 -74
  65. package/DOCS/CANONICAL_PATTERNS.md +0 -349
  66. package/DOCS/CODEC_ARCHITECTURE.md +0 -257
  67. package/DOCS/CONVERGENCE.md +0 -123
  68. package/DOCS/DIVERGENCE_DETECTION.md +0 -23
  69. package/DOCS/JSON_APPROACHES_COMPARISON.md +0 -302
  70. package/DOCS/KIR_SPECIALIZATION_DESIGN.md +0 -472
  71. package/DOCS/Makefile +0 -99
  72. package/DOCS/NAMED_PATTERNS.md +0 -340
  73. package/DOCS/OBJECT_FILE_AND_PATTERN.md +0 -343
  74. package/DOCS/PATTERNS_AND_TYPED_VALUES.md +0 -665
  75. package/DOCS/WEB_REPL_REQUIREMENTS.md +0 -136
  76. package/DOCS/book/01-introduction.md +0 -48
  77. package/DOCS/book/02-syntax-and-values.md +0 -110
  78. package/DOCS/book/03-types-as-finite-automata.md +0 -155
  79. package/DOCS/book/04-partial-functions-and-composition.md +0 -145
  80. package/DOCS/book/05-typing-filters-and-normalization.md +0 -109
  81. package/DOCS/book/06-values-in-memory.md +0 -1085
  82. package/DOCS/book/07-the-partial-function-abi.md +0 -143
  83. package/DOCS/book/08-operational-semantics-and-execution.md +0 -196
  84. package/DOCS/book/09-compiler-architecture.md +0 -160
  85. package/DOCS/book/10-from-ast-to-intermediate-representation.md +0 -166
  86. package/DOCS/book/14-canonical-serialization.md +0 -176
  87. package/DOCS/book/appendix-b-incorporating-external-predefined-types-and-functions.md +0 -156
  88. package/DOCS/book/overview.txt +0 -68
  89. package/DOCS/book.md +0 -50
  90. package/Examples/bnat.k +0 -308
  91. package/Examples/buda.k +0 -66
  92. package/Examples/byte.k +0 -35
  93. package/Examples/code.k +0 -43
  94. package/Examples/vhdl_to_k.k +0 -67
  95. package/JOURNAL.md +0 -288
  96. package/TODO.md +0 -107
  97. package/backends/wasm/DOCS/USE-WEB-ASSEMBLY.md +0 -233
  98. package/backends/wasm/TECHNICAL-DEBT.md +0 -58
  99. package/backends/wasm/demo_ieee.mjs +0 -318
  100. package/browser/vfs-data.mjs +0 -21
  101. package/codecs/BINARY_FORMAT.md +0 -53
  102. package/codecs/POLYMORPHIC_BINARY_FORMAT.md +0 -303
  103. package/codecs/pandoc.css +0 -71
  104. package/tests/code-derivation/blowup.mjs +0 -25
  105. package/tests/code-derivation/bnat.mjs +0 -11
  106. package/tests/code-derivation/dot.mjs +0 -37
  107. package/tests/code-derivation/index.mjs +0 -20
  108. package/tests/code-derivation/loop.mjs +0 -17
  109. package/tests/code-derivation/nat.mjs +0 -10
  110. package/tests/code-derivation/not-not.mjs +0 -14
  111. package/tests/code-derivation/product.mjs +0 -22
  112. package/tests/code-derivation/rlz.mjs +0 -13
  113. package/tests/test-fingerprint.mjs +0 -38
package/tests/README.md CHANGED
@@ -1,46 +1,66 @@
1
- # k Test Suite
2
-
3
- This directory contains automated tests, type-derivation validation
4
- cases, and integration test scripts for the `k` compiler and runtime.
5
-
6
- ## Running the Tests
7
-
8
- ### 1. Run Unit and Integration Test Suite
9
- To run all core unit tests, type-derivation checks, and integration tests:
10
- ```bash
11
- npm test
12
- ```
13
- This executes `node scripts/run-tests.mjs`, which discovers and runs the
14
- test scripts sequentially.
15
-
16
- ## Test Directory Structure
17
-
18
- ### Core Test Files
19
- - **[test.mjs](test.mjs)**: Verifies basic parser and runtime
20
- execution behavior.
21
- - **[test-kvm.mjs](test-kvm.mjs)**: Conformance testing for the kVM
22
- register compiler and interpreter in envelope-aware and envelope-free
23
- modes.
24
- - **[test-kvm-polymorphic.mjs](test-kvm-polymorphic.mjs)**: Tests for
25
- polymorphic `.kvm` templates (`layer: "KVM-P"`) and runtime input
26
- envelope specialization (`specializeKVM`).
27
- - **[test-ieee-arithmetic.mjs](test-ieee-arithmetic.mjs)**: Verifies
28
- IEEE-754 double precision float arithmetic (`Examples/ieee.k`).
29
- - **[test-repl.mjs](test-repl.mjs)**: Tests interactive REPL commands,
30
- state transitions, imports, `.klib` and `.ko` exports.
31
- - **[test-k-object.mjs](test-k-object.mjs)**: Tests serialization,
32
- compilation, and loading of `.ko` binary objects and `.klib` libraries.
33
- - **[test-fingerprint.mjs](test-fingerprint.mjs)**: Tests semantic
34
- expression and relation hashing/fingerprinting (`@hash`).
35
- - **[test-hash-normalization.mjs](test-hash-normalization.mjs)**:
36
- Verifies consistent normalization of type pattern graphs and hashes.
37
- - **[test-hash-fuzz.mjs](test-hash-fuzz.mjs)**: Fuzzes expression and
38
- relation hashing to guard against collisions.
39
-
40
- ### Type Derivation Suites
41
- - **[code-derivation/](code-derivation/)**: Individual files validating
42
- type-derivation convergence and pattern-envelope generation.
43
-
44
- ### Integration Scripts
45
- - **[integration.sh](integration.sh)**: Shell script checking boundary
46
- data pipelines (`k-parse`, `k-show`, `k-print`) against binary outputs.
1
+ # Tests
2
+
3
+ Run commands below from the repository root after `npm install`.
4
+ Use Node.js 22+ for development: browser verification uses the global WebSocket
5
+ client. The source parser and runtime can run without a browser.
6
+
7
+ ## Suite commands
8
+
9
+ | Command | Coverage |
10
+ | --- | --- |
11
+ | `npm test` | Registered runtime, patterns, paper examples, codecs, hashes, objects, REPL, browser, kVM, PKIR, library, and shell suites |
12
+ | `npm run conformance` | Shared source/object/KIR-P fixtures |
13
+ | `npm run test:wasm` | Wasm runtime/lowering and backend shell integration |
14
+ | `npm run test:llvm` | LLVM runtime/lowering, field-layout regression, shell integration, and shared fixtures |
15
+ | `npm run test:backends` | Both backend suites |
16
+ | `npm --prefix k-vscode test` | Editor grammar and expression-background tests |
17
+ | `node tests/test-paper-examples.mjs` | Publication examples, including canonical hashes and the half adder |
18
+ | `npm run test:package -- /path/to/installed/@fraczak/k` | Packed installation, API, command help, codec pipeline, objects, and Wasm |
19
+
20
+ The backend and editor suites are separate commands; `npm test` does not run
21
+ every suite in this table. The paper command is also available as a focused check.
22
+
23
+ The main runner executes suites sequentially, prints durations, and stops at
24
+ the first failure. Browser tests build `repl.html` and perform headless
25
+ verification if Chromium is found. Without Chromium, that browser execution
26
+ portion is skipped. LLVM execution checks require Clang; individual optional
27
+ checks report skips when their toolchain is unavailable.
28
+
29
+ ## Registration and organization
30
+
31
+ Root suites are explicitly registered in
32
+ [scripts/run-tests.mjs](../scripts/run-tests.mjs).
33
+ Files ending in `.mjs` under [code-derivation/](code-derivation/) are discovered
34
+ automatically. The compact `core.mjs` table groups the elementary derivation
35
+ cases; shared helpers live outside the discovered directory.
36
+
37
+ | Area | Representative suites |
38
+ | --- | --- |
39
+ | Templates and routing | `test-named-patterns.mjs` |
40
+ | Derivation and envelope propagation | `code-derivation/` |
41
+ | Canonical identities | `test-hash-normalization.mjs` (including code fingerprints), `test-hash-fuzz.mjs` |
42
+ | Wire values and codecs | `test-codecs.mjs`, `test-deep-wire-value.mjs`, `test-structural-values.mjs` |
43
+ | Objects and portable export | `test-k-object.mjs`, `test-kir.mjs`, `test-validate-object.mjs` |
44
+ | Interactive state and browser UI | `test-repl.mjs`, `test-repl-html.mjs`, `test-tree-view.mjs` |
45
+ | Execution layers | `test-kvm.mjs`, `test-kvm-polymorphic.mjs`, `test-access-table.mjs`, `test-pkir.mjs` |
46
+ | Libraries | Arithmetic, IEEE, list, Karatsuba, and dynamic JSON suites |
47
+
48
+ `test-hash-fuzz.mjs` uses a deterministic generator to check renaming and
49
+ definition-order invariance; it is not a general cryptographic collision test.
50
+
51
+ The [conformance fixtures](../conformance/) provide programs, input values,
52
+ expected values, and case descriptions reused by supported execution paths.
53
+ A rendered payload alone can hide envelope differences, so keep pattern
54
+ comparisons when checking structural correctness.
55
+
56
+ Arithmetic and Karatsuba tests share CLI setup in `helpers/cli.mjs`. They still
57
+ run the library through `k.mjs` and compare numerical results with BigInt;
58
+ codec modules prepare and decode the wire values in process. The dedicated
59
+ codec and shell suites cover the codec command-line boundary.
60
+
61
+ ## Adding coverage
62
+
63
+ Use assertions for expected values, schemas, and failures. Register a new
64
+ root suite explicitly, or add a derivation case in the discovered directory.
65
+ Run the main suite and the relevant backend/editor checks. Grammar edits also
66
+ require `npm run prepare`; generated parser files should not be hand-edited.
@@ -0,0 +1,61 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFileSync } from "node:fs";
3
+ import { annotate } from "../../index.mjs";
4
+ import hash from "../../hash.mjs";
5
+
6
+ const bool = "@GWnxJCupZr96BZfdpDsfQQKxKjCbjyDh7Qaur7y9enCY";
7
+ const bit = "@MjusyRWZnVj8TR4BhFCCcMRrQbdKp9gPtC29LT9nZvjg";
8
+ const unit = hash("$C0={};");
9
+ const cases = [
10
+ ["unit", "{}", { pattern: "(...)" }, { type: unit }],
11
+ ["product", `
12
+ ?<{} true, {} false> {() one, () two}
13
+ ?{<{} true, {} false> one, <{} true, {} false> two}
14
+ `, { type: bool }, { type: "@ZR2yff4pdXTVqZdMu9x3t9GG5rwmhEfQuenbAwFnD2Nk" }],
15
+ ["product projection", `
16
+ 1 = {} |1 ?<{} 0, {} 1>;
17
+ ?<{} true, {} false> {1 one, () two, () c} .one
18
+ `, { type: bool }, { type: bit }],
19
+ ["closed variant projection", "?< <{} 0, {} 1> true, <{} 0, {} 1> false> /true",
20
+ { pattern: "type" }, { type: bit }],
21
+ ["composed variant projection", `
22
+ x = /x; xy = x/y;
23
+ f = {{} |y |x xy i, {} |y |x xy b}; f .b
24
+ `, { pattern: "(...)" }, { type: unit }],
25
+ ["recursive open union", `
26
+ B = {}|u A;
27
+ A = ?X < /a, /b ?X A, /c |z ?X A, B >; A
28
+ `, { pattern: "<...>" }, { pattern: "(...)" }],
29
+ ["double negation", `
30
+ true = {} |true; false = {} |false;
31
+ not = ?<{} true, {} false> </true false, /false true> ?<{} true, {} false>;
32
+ not not
33
+ `, { type: bool }, { type: bool }],
34
+ ["leading zero normalization", `
35
+ zero = {}|_|0;
36
+ rlz = ?<X 0, X 1, {} _>=X </0/_ zero, /0 rlz, ()> ?X; rlz
37
+ `, { type: "@VtPHxGf5GNMzzyVFxtv7gegFfJRYapBGtCeyV56bs5Zb" },
38
+ { type: "@VtPHxGf5GNMzzyVFxtv7gegFfJRYapBGtCeyV56bs5Zb" }],
39
+ ["Peano arithmetic", readFileSync(new URL("../../Examples/nat.k", import.meta.url), "utf8"),
40
+ { type: "@e9WP6QX6URfgnd9hHYrrYUBhiL7UcvbWErVmyQJfFcr8" },
41
+ { type: "@e9WP6QX6URfgnd9hHYrrYUBhiL7UcvbWErVmyQJfFcr8" }]
42
+ ];
43
+
44
+ function boundaries(source) {
45
+ const { def, typePatternGraph: graph } = annotate(source).rels.__main__;
46
+ return def.patterns.map((id) => graph.get_pattern(id));
47
+ }
48
+ for (const [name, source, ...expected] of cases) {
49
+ const actual = boundaries(source);
50
+ expected.forEach((fields, side) => {
51
+ for (const [key, value] of Object.entries(fields)) {
52
+ assert.equal(actual[side][key], value, `${name}: boundary ${side} ${key}`);
53
+ }
54
+ });
55
+ }
56
+ for (const [source, pattern] of [["</a, ()>", "<...>"], ["<.a, ()>", "{...}"]]) {
57
+ const [input, output] = boundaries(source);
58
+ assert.equal(input.pattern, pattern);
59
+ assert.equal(output, input, source);
60
+ }
61
+ console.log("core derivation cases: ok");
@@ -0,0 +1,45 @@
1
+ import assert from "node:assert/strict";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { spawnSync } from "node:child_process";
6
+ import { fileURLToPath } from "node:url";
7
+ import { parse, print } from "../../codecs/int.mjs";
8
+ import { encodeToWire, decodeWire } from "../../codecs/runtime/prefix-codec.mjs";
9
+
10
+ const root = fileURLToPath(new URL("../../", import.meta.url));
11
+
12
+ export function node(args, input) {
13
+ const result = spawnSync(process.execPath, args, {
14
+ cwd: root, input, maxBuffer: 64 * 1024 * 1024
15
+ });
16
+ assert.ifError(result.error);
17
+ return result;
18
+ }
19
+
20
+ export function succeeds(result, label) {
21
+ assert.equal(result.status, 0,
22
+ `${label} failed\n${result.stderr}\n${result.stdout}`);
23
+ return result.stdout;
24
+ }
25
+
26
+ export function withCompiledLibrary(source, test) {
27
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "k-library-test-"));
28
+ const library = path.join(dir, "library.klib");
29
+ try {
30
+ succeeds(node(["objects/compile.mjs", source, library]), `compile ${source}`);
31
+ test(library);
32
+ } finally {
33
+ fs.rmSync(dir, { recursive: true, force: true });
34
+ }
35
+ }
36
+
37
+ export function runLibrary(library, aliases, source, input = "0") {
38
+ return node(["k.mjs", "--lib", library,
39
+ ...aliases.flatMap((alias) => ["--export", alias]), source],
40
+ encodeToWire(parse(input)));
41
+ }
42
+
43
+ export function integer(result, label) {
44
+ return print(decodeWire(succeeds(result, label)).value);
45
+ }
@@ -70,17 +70,16 @@ echo '-21' | node ./codecs/int.mjs --parse | node ./codecs/int.mjs --print | gre
70
70
  echo
71
71
  node ./codecs/unit.mjs --parse | node ./codecs/unit.mjs --print | grep -qx '{}'
72
72
  echo
73
- if ./k.mjs -k Examples/byte.k > "$TMP_DIR/dash-k.out" 2> "$TMP_DIR/dash-k.err"; then
73
+ if ./k.mjs -k Examples/nat.k > "$TMP_DIR/dash-k.out" 2> "$TMP_DIR/dash-k.err"; then
74
74
  echo "expected -k to fail" >&2
75
75
  exit 1
76
76
  fi
77
77
  grep -q -- '-k is no longer supported' "$TMP_DIR/dash-k.err"
78
- if ./kvm.mjs -k Examples/byte.k > "$TMP_DIR/dash-k-kvm.out" 2> "$TMP_DIR/dash-k-kvm.err"; then
78
+ if ./kvm.mjs -k Examples/nat.k > "$TMP_DIR/dash-k-kvm.out" 2> "$TMP_DIR/dash-k-kvm.err"; then
79
79
  echo "expected k-vm -k to fail" >&2
80
80
  exit 1
81
81
  fi
82
82
  grep -q -- '-k is no longer supported' "$TMP_DIR/dash-k-kvm.err"
83
- printf 'A🙂\nBé~\t' | ./codecs/utf8.mjs --parse | ./k.mjs Examples/byte.k |./codecs/utf8.mjs --print
84
83
  echo
85
84
  ./objects/compile.mjs Examples/ieee.k "$TMP_DIR/ieee.klib"
86
85
  MUL=`./objects/extract-aliases.mjs "$TMP_DIR/ieee.klib" | grep '^mul = @' | sed 's/^mul = \(@[^;]*\);.*$/\1/'`
@@ -1,245 +1,55 @@
1
1
  import assert from "node:assert/strict";
2
- import fs from "node:fs";
3
- import os from "node:os";
4
- import path from "node:path";
5
- import { spawnSync } from "node:child_process";
6
- import { fileURLToPath } from "node:url";
7
-
8
- const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
9
- const node = process.execPath;
10
- const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "k-arithmetics-"));
11
- const libPath = path.join(tmpDir, "arithmetics.klib");
12
- const program = "{inc x, () y} o";
13
-
14
- const smallInput = "11111112222223333334444444555555666666777777788888899999900000011111122222233333344444455555";
15
-
16
- function run(command, args, options = {}) {
17
- const result = spawnSync(command, args, {
18
- cwd: root,
19
- input: options.input,
20
- encoding: options.encoding ?? null,
21
- maxBuffer: 64 * 1024 * 1024
22
- });
23
- if (result.error && result.status == null) throw result.error;
24
- return result;
25
- }
26
-
27
- function assertOk(result, label) {
28
- if (result.status !== 0) {
29
- const stderr = Buffer.isBuffer(result.stderr) ? result.stderr.toString("utf8") : String(result.stderr ?? "");
30
- const stdout = Buffer.isBuffer(result.stdout) ? result.stdout.toString("utf8") : String(result.stdout ?? "");
31
- assert.fail(`${label} failed with status ${result.status}\nSTDERR:\n${stderr}\nSTDOUT:\n${stdout}`);
2
+ import { withCompiledLibrary, runLibrary, integer, succeeds } from "./helpers/cli.mjs";
3
+
4
+ const large = "11111112222223333334444444555555666666777777788888899999900000011111122222233333344444455555";
5
+
6
+ withCompiledLibrary("Examples/arithmetics.k", (library) => {
7
+ const run = (aliases, source, input) => runLibrary(library, aliases, source, input);
8
+ const n = BigInt(large);
9
+ for (const [op, expected] of [
10
+ ["plus", n + n + 1n], ["minus", 1n], ["times", n * (n + 1n)]
11
+ ]) {
12
+ assert.equal(integer(run([`${op}:o`, "inc"], "{inc x, () y} o", large), op),
13
+ String(expected), op);
32
14
  }
33
- }
34
-
35
- function parseIntWire(text) {
36
- const result = run(node, ["codecs/int.mjs", "--parse"], {
37
- input: `${text}\n`
38
- });
39
- assertOk(result, `parse int ${text}`);
40
- return result.stdout;
41
- }
42
-
43
- function printIntWire(wire, label) {
44
- const result = run(node, ["codecs/int.mjs", "--print"], {
45
- input: wire,
46
- encoding: "utf8"
47
- });
48
- assertOk(result, `${label} print`);
49
- return result.stdout.trim();
50
- }
51
15
 
52
- function runnerArgs(operation) {
53
- return [
54
- "--lib", libPath,
55
- "--export", `${operation}:o`,
56
- "--export", "inc",
57
- program
58
- ];
59
- }
60
-
61
- function runNative(operation, inputText) {
62
- const wire = parseIntWire(inputText);
63
- const result = run(node, ["k.mjs", ...runnerArgs(operation)], {
64
- input: wire
65
- });
66
- assertOk(result, `native ${operation}(${inputText})`);
67
- return printIntWire(result.stdout, `native ${operation}`);
68
- }
69
-
70
- function expected(operation, inputText) {
71
- const n = BigInt(inputText);
72
- if (operation === "plus") return (n + n + 1n).toString();
73
- if (operation === "minus") return "1";
74
- if (operation === "times") return (n * (n + 1n)).toString();
75
- throw new Error(`Unknown operation: ${operation}`);
76
- }
77
-
78
- try {
79
- assertOk(
80
- run(node, ["objects/compile.mjs", "Examples/arithmetics.k", libPath], { encoding: "utf8" }),
81
- "compile Examples/arithmetics.k"
82
- );
83
-
84
- for (const operation of ["plus", "minus", "times"]) {
85
- assert.equal(
86
- runNative(operation, smallInput),
87
- expected(operation, smallInput),
88
- `native ${operation} should match BigInt oracle`
89
- );
16
+ succeeds(run(["dec", "zero_int?"], "dec dec zero_int?", "2"),
17
+ "decrement normalization");
18
+ for (const [x, divisor] of [
19
+ ["0", "7"], ["3", "7"], ["4", "1"], ["10", "2"], ["12", "3"],
20
+ ["11", "3"], ["12", "12"], ["100", "7"], ["-100", "7"], ["1000", "10"]
21
+ ]) {
22
+ const a = BigInt(x), b = BigInt(divisor);
23
+ const aliases = ["div", "int", `${divisor}:divisor`];
24
+ for (const [projection, expected] of [
25
+ [".div", a / b], [".rem int", (a < 0n ? -a : a) % b]
26
+ ]) {
27
+ const source = `{() x, divisor int y} div ${projection}`;
28
+ assert.equal(integer(run(aliases, source, x), source), String(expected),
29
+ `div(${x}, ${divisor}) ${projection}`);
30
+ }
90
31
  }
91
32
 
92
- // Regression tests for inc/dec normalization and div
93
- const resDec = run(node, [
94
- "k.mjs",
95
- "--lib", libPath,
96
- "--export", "dec:dec",
97
- "--export", "zero_int?:zero_int?",
98
- "dec dec zero_int?"
99
- ], { input: parseIntWire("2") });
100
- assertOk(resDec, "2 int dec dec zero_int? should succeed");
101
-
102
- const divTestCases = [
103
- { x: "0", yAlias: "7", yVal: 7n },
104
- { x: "3", yAlias: "7", yVal: 7n },
105
- { x: "4", yAlias: "1", yVal: 1n },
106
- { x: "10", yAlias: "2", yVal: 2n },
107
- { x: "12", yAlias: "3", yVal: 3n },
108
- { x: "11", yAlias: "3", yVal: 3n },
109
- { x: "12", yAlias: "12", yVal: 12n },
110
- { x: "100", yAlias: "7", yVal: 7n },
111
- { x: "-100", yAlias: "7", yVal: 7n },
112
- { x: "1000", yAlias: "10", yVal: 10n }
113
- ];
114
-
115
- for (const { x, yAlias, yVal } of divTestCases) {
116
- const xBig = BigInt(x);
117
- const expectedDiv = (xBig / yVal).toString();
118
- const xAbs = xBig < 0n ? -xBig : xBig;
119
- const yAbs = yVal < 0n ? -yVal : yVal;
120
- const expectedRem = (xAbs % yAbs).toString();
121
-
122
- const wire = parseIntWire(x);
123
-
124
- const resDiv = run(node, [
125
- "k.mjs",
126
- "--lib", libPath,
127
- "--export", "div:div",
128
- "--export", "int:int",
129
- "--export", `${yAlias}:divisor`,
130
- "{() x, divisor int y} div .div"
131
- ], { input: wire });
132
- assertOk(resDiv, `native div(${x}, ${yAlias}) quotient`);
133
- const divOut = printIntWire(resDiv.stdout, `div quotient`);
134
- assert.equal(divOut, expectedDiv, `div(${x}, ${yAlias}) quotient should match BigInt oracle`);
135
-
136
- const resRem = run(node, [
137
- "k.mjs",
138
- "--lib", libPath,
139
- "--export", "div:div",
140
- "--export", "int:int",
141
- "--export", `${yAlias}:divisor`,
142
- "{() x, divisor int y} div .rem int"
143
- ], { input: wire });
144
- assertOk(resRem, `native div(${x}, ${yAlias}) remainder`);
145
- const remOut = printIntWire(resRem.stdout, `div remainder`);
146
- assert.equal(remOut, expectedRem, `div(${x}, ${yAlias}) remainder should match BigInt oracle`);
33
+ for (const [aliases, source] of [
34
+ [["EQ", "int", "2:two"], "{two x, two y} EQ .x int"],
35
+ [["pos?", "int", "2:two"], "two int pos?"]
36
+ ]) succeeds(run(aliases, source), source);
37
+
38
+ for (const [aliases, source] of [
39
+ [["EQ", "int", "2:two", "3:three"], "{two x, three y} EQ .x int"],
40
+ [["pos?", "int", "0:zero"], "zero int pos?"]
41
+ ]) {
42
+ const result = run(aliases, source);
43
+ assert.notEqual(result.status, 0, source);
44
+ assert.match(result.stderr.toString(), /undefined/, source);
147
45
  }
148
46
 
149
- // Regression tests for EQ
150
- const dummyWire = parseIntWire("0");
151
- const resEqTrue = run(node, [
152
- "k.mjs",
153
- "--lib", libPath,
154
- "--export", "EQ:EQ",
155
- "--export", "int:int",
156
- "--export", "2:two",
157
- "{two x, two y} EQ .x int"
158
- ], { input: dummyWire });
159
- assertOk(resEqTrue, "{2, 2} EQ should succeed");
160
-
161
- const resEqFalse = run(node, [
162
- "k.mjs",
163
- "--lib", libPath,
164
- "--export", "EQ:EQ",
165
- "--export", "int:int",
166
- "--export", "2:two",
167
- "--export", "3:three",
168
- "{two x, three y} EQ .x int"
169
- ], { input: dummyWire });
170
- assert.notEqual(resEqFalse.status, 0, "{2, 3} EQ should fail");
171
-
172
- // Regression tests for pos?
173
- const resPosTrue = run(node, [
174
- "k.mjs",
175
- "--lib", libPath,
176
- "--export", "pos?:pos?",
177
- "--export", "int:int",
178
- "--export", "2:two",
179
- "two int pos?"
180
- ], { input: dummyWire });
181
- assertOk(resPosTrue, "2 int pos? should succeed");
182
-
183
- const resPosZero = run(node, [
184
- "k.mjs",
185
- "--lib", libPath,
186
- "--export", "pos?:pos?",
187
- "--export", "int:int",
188
- "--export", "0:zero",
189
- "zero int pos?"
190
- ], { input: dummyWire });
191
- assert.notEqual(resPosZero.status, 0, "0 int pos? should fail");
192
-
193
- // Regression tests for mod, gcd, lcm
194
- const resMod = run(node, [
195
- "k.mjs",
196
- "--lib", libPath,
197
- "--export", "mod:mod",
198
- "--export", "int:int",
199
- "--export", "10:ten",
200
- "--export", "3:three",
201
- "{ten x, three y} mod int"
202
- ], { input: dummyWire });
203
- assertOk(resMod, "10 % 3 mod");
204
- assert.equal(printIntWire(resMod.stdout, "mod"), "1");
205
-
206
- const resGcd = run(node, [
207
- "k.mjs",
208
- "--lib", libPath,
209
- "--export", "gcd:gcd",
210
- "--export", "int:int",
211
- "--export", "12:twelve",
212
- "--export", "8:eight",
213
- "{twelve x, eight y} gcd int"
214
- ], { input: dummyWire });
215
- assertOk(resGcd, "gcd(12, 8)");
216
- assert.equal(printIntWire(resGcd.stdout, "gcd"), "4");
217
-
218
- const resGcdZero = run(node, [
219
- "k.mjs",
220
- "--lib", libPath,
221
- "--export", "gcd:gcd",
222
- "--export", "int:int",
223
- "--export", "4:four",
224
- "--export", "0b:zero_b",
225
- "{four x, zero_b y} gcd int"
226
- ], { input: dummyWire });
227
- assertOk(resGcdZero, "gcd(4, 0b)");
228
- assert.equal(printIntWire(resGcdZero.stdout, "gcd 0b"), "4");
229
-
230
- const resLcm = run(node, [
231
- "k.mjs",
232
- "--lib", libPath,
233
- "--export", "lcm:lcm",
234
- "--export", "int:int",
235
- "--export", "4:four",
236
- "--export", "6:six",
237
- "{four x, six y} lcm int"
238
- ], { input: dummyWire });
239
- assertOk(resLcm, "lcm(4, 6)");
240
- assert.equal(printIntWire(resLcm.stdout, "lcm"), "12");
47
+ for (const [aliases, source, expected] of [
48
+ [["mod", "int", "10:ten", "3:three"], "{ten x, three y} mod int", "1"],
49
+ [["gcd", "int", "12:twelve", "8:eight"], "{twelve x, eight y} gcd int", "4"],
50
+ [["gcd", "int", "4:four", "_:zero_b"], "{four x, zero_b y} gcd int", "4"],
51
+ [["lcm", "int", "4:four", "6:six"], "{four x, six y} lcm int", "12"]
52
+ ]) assert.equal(integer(run(aliases, source), source), expected, source);
53
+ });
241
54
 
242
- console.log("OK");
243
- } finally {
244
- fs.rmSync(tmpDir, { recursive: true, force: true });
245
- }
55
+ console.log("arithmetic CLI and BigInt oracles: ok");