@fraczak/k 8.5.0 → 8.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,96 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFileSync, mkdtempSync, rmSync } from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { spawnSync } from "node:child_process";
6
+ import k from "../index.mjs";
7
+ import { compileLibrary, loadLibrary } from "../object.mjs";
8
+ import { compileWasmArtifact, instantiateWasmArtifact } from "../backends/wasm/src/wasm.mjs";
9
+ import { fromJsonValue } from "../codecs/djson.mjs";
10
+ import { textToStringValue } from "../codecs/runtime/unicode-string.mjs";
11
+ import { parse as utf8 } from "../codecs/utf8.mjs";
12
+ import { encodeToWire, decodeWire } from "../codecs/runtime/codec-sdk.mjs";
13
+
14
+ const core = loadLibrary(compileLibrary(readFileSync(new URL("../core.k", import.meta.url), "utf8")));
15
+ const ieee = loadLibrary(compileLibrary(readFileSync(new URL("../Examples/ieee.k", import.meta.url), "utf8"), {
16
+ libraries: [core]
17
+ }));
18
+ const library = loadLibrary(compileLibrary(readFileSync(new URL("../Examples/djson.k", import.meta.url), "utf8"), {
19
+ libraries: [ieee]
20
+ }));
21
+ const wasm = await instantiateWasmArtifact(await compileWasmArtifact(library.relAlias.parseJson, { libraries: [library] }));
22
+ const fast = text => wasm.executeValue(textToStringValue(text));
23
+ const parse = k.compile(library.relAlias.parseJson, { libraries: [library] });
24
+ const payload = value => JSON.parse(JSON.stringify(value));
25
+ function check(text, evaluate = text => parse(textToStringValue(text))) {
26
+ const actual = evaluate(text);
27
+ assert.ok(actual, text);
28
+ assert.deepEqual(payload(actual), payload(fromJsonValue(JSON.parse(text))), text);
29
+ }
30
+
31
+ for (const text of [
32
+ " \t\r\n null \t", "true", "false", '""', "[ \t ]", "{ \r\n }",
33
+ '[[],{},null,true,false,[1,-2,3.14]]',
34
+ '{"a":1,"a":{"new":"type"},"":0,"__proto__":{"safe":true},"emoji😀":[1,2]}',
35
+ String.raw`"\"\\\/\b\f\n\r\t"`,
36
+ String.raw`"\uD834\uDD1E\uFAbC"`,
37
+ "0", "-0", "-42", "0.1", "1.25", "12E-2", "1e+20",
38
+ "0e999999999999999999", "-0.00e-999999999999999999", "-1e-999999999999999999"
39
+ ]) check(text);
40
+
41
+ // Exercise every Unicode encoding partition, including surrogate pairs.
42
+ const scalars = [
43
+ 0, 0x1f, 0x7f, 0x80, 0x7ff, 0x800, 0xfff, 0x1000, 0x7fff,
44
+ 0x8000, 0xcfff, 0xd000, 0xd7ff, 0xe000, 0xefff, 0xf000, 0xf7ff,
45
+ 0xf800, 0xf8ff, 0xf900, 0xf9ff, 0xfa00, 0xfbff, 0xfc00, 0xfdff,
46
+ 0xfe00, 0xffff, 0x10000, 0x1ffff, 0x20000, 0x3ffff, 0x40000,
47
+ 0x7ffff, 0x80000, 0xfffff, 0x100000, 0x10ffff
48
+ ];
49
+ for (const scalar of scalars) {
50
+ const text = JSON.stringify(String.fromCodePoint(scalar));
51
+ check(text);
52
+ check(text.replace(/[\u007f-\uffff]/g, char => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`));
53
+ }
54
+ for (const text of [
55
+ "", " ", "nil", "True", "+1", "01", "-01", ".1", "1.", "1e", "1e+", "--1", "0x10",
56
+ "NaN", "Infinity", "1e999999999999999999", "[1,]", "[,1]", "[1 2]", "[",
57
+ '{"x":1,}', "{x:1}", '{"x" 1}', "{", "null true", '"x"x', '"unterminated',
58
+ String.raw`"\x20"`, String.raw`"\u123"`, String.raw`"\uZZZZ"`,
59
+ String.raw`"\uD800"`, String.raw`"\uDC00"`, String.raw`"\uD800\u0041"`,
60
+ String.raw`"\uDC00\uD800"`, '"line\nfeed"', "\u00a0null"
61
+ ]) assert.equal(parse(textToStringValue(text)), undefined, JSON.stringify(text));
62
+
63
+ // Use compiled Wasm for the expensive exact-rational boundary cases.
64
+ for (const text of [
65
+ "9007199254740993", "9007199254740995", "1.9999999999999999", "9.9999999999999999",
66
+ "1.00000000000000011102230246251565404236316680908203125",
67
+ "1.00000000000000011102230246251565404236316680908203126",
68
+ "5e-324", "2e-324", "2.2250738585072014e-308", "1.7976931348623157e308"
69
+ ]) check(text, fast);
70
+ for (const text of ["1e309", "-1.8e308"]) assert.equal(fast(text), undefined, text);
71
+
72
+ const text = '{"answer":42,"ok":true}';
73
+ const scratch = mkdtempSync(path.join(os.tmpdir(), "k-json-test-"));
74
+ try {
75
+ const artifact = path.join(scratch, "djson.klib");
76
+ const ieeeArtifact = path.join(scratch, "ieee.klib");
77
+ for (const args of [
78
+ ["--lib", "core.k", "Examples/ieee.k", ieeeArtifact],
79
+ ["--lib", ieeeArtifact, "Examples/djson.k", artifact]
80
+ ]) {
81
+ const built = spawnSync(process.execPath, ["objects/compile.mjs", ...args], {
82
+ cwd: new URL("..", import.meta.url)
83
+ });
84
+ assert.ifError(built.error);
85
+ assert.equal(built.status, 0, built.stderr.toString());
86
+ }
87
+ const cli = spawnSync(process.execPath, ["k.mjs", "--lib", artifact, "--export", "parseJson", "parseJson"], {
88
+ cwd: new URL("..", import.meta.url), input: encodeToWire(utf8(text))
89
+ });
90
+ assert.ifError(cli.error);
91
+ assert.equal(cli.status, 0, cli.stderr.toString());
92
+ assert.deepEqual(payload(decodeWire(cli.stdout).value), payload(fromJsonValue(JSON.parse(text))));
93
+ } finally {
94
+ rmSync(scratch, { recursive: true, force: true });
95
+ }
96
+ console.log("JSON text parser: grammar, Unicode, binary64 rounding, Wasm and CLI passed");
@@ -1,5 +1,6 @@
1
1
  import assert from "node:assert";
2
2
  import fs from "node:fs";
3
+ import os from "node:os";
3
4
  import path from "node:path";
4
5
  import { spawn, spawnSync } from "node:child_process";
5
6
  import { fileURLToPath } from "node:url";
@@ -50,25 +51,36 @@ const chromiumBin = ["google-chrome", "chromium-browser", "chromium"].find(bin =
50
51
 
51
52
  if (chromiumBin) {
52
53
  console.log(`3. Running browser verification with ${chromiumBin}...`);
53
- const tmpDir = `/tmp/chrome-test-${Date.now()}`;
54
- fs.mkdirSync(tmpDir, { recursive: true });
54
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "k-browser-test-"));
55
55
 
56
- const cdpPort = 9333 + Math.floor(Math.random() * 500);
57
56
  const chrome = spawn(chromiumBin, [
58
57
  "--headless=new",
59
58
  "--disable-gpu",
60
- `--remote-debugging-port=${cdpPort}`,
59
+ "--remote-debugging-port=0",
61
60
  "--no-sandbox",
62
61
  "--disable-extensions",
63
62
  `--user-data-dir=${tmpDir}`,
64
63
  `file://${replHtmlPath}`
65
- ]);
64
+ ], { stdio: ["ignore", "ignore", "pipe"] });
65
+ let launchError;
66
+ let diagnostics = "";
67
+ chrome.on("error", error => { launchError = error; });
68
+ chrome.stderr.setEncoding("utf8");
69
+ chrome.stderr.on("data", chunk => { diagnostics = (diagnostics + chunk).slice(-16384); });
66
70
 
67
71
  try {
68
72
  let wsUrl = null;
69
- for (let i = 0; i < 30; i++) {
73
+ const deadline = Date.now() + 30000;
74
+ while (Date.now() < deadline) {
75
+ if (launchError) throw launchError;
76
+ if (chrome.exitCode !== null || chrome.signalCode !== null) {
77
+ throw new Error(`Chrome exited before startup (${chrome.exitCode ?? chrome.signalCode})\n${diagnostics}`);
78
+ }
70
79
  try {
71
- const res = await fetch(`http://127.0.0.1:${cdpPort}/json/list`);
80
+ const cdpPort = fs.readFileSync(path.join(tmpDir, "DevToolsActivePort"), "utf8").split("\n")[0];
81
+ const res = await fetch(`http://127.0.0.1:${cdpPort}/json/list`, {
82
+ signal: AbortSignal.timeout(1000)
83
+ });
72
84
  const list = await res.json();
73
85
  const page = list.find(item => item.url && item.url.includes("repl.html"));
74
86
  if (page && page.webSocketDebuggerUrl) {
@@ -79,7 +91,7 @@ if (chromiumBin) {
79
91
  await new Promise(r => setTimeout(r, 200));
80
92
  }
81
93
 
82
- assert(wsUrl, `Could not connect to Chromium CDP on port ${cdpPort}`);
94
+ assert(wsUrl, `Chrome debugging connection was not ready within 30 seconds\n${diagnostics}`);
83
95
 
84
96
  const ws = new WebSocket(wsUrl);
85
97
  await new Promise(r => ws.onopen = r);
@@ -143,6 +155,7 @@ if (chromiumBin) {
143
155
  "djson.k",
144
156
  "djson.mjs",
145
157
  "ieee.k",
158
+ "ieee-arithmetics.k",
146
159
  "ieee.mjs",
147
160
  "int.mjs",
148
161
  "json.mjs",
@@ -26,11 +26,19 @@ const state = createState();
26
26
 
27
27
  let output = await evaluateInput("zero = {} | zero;", state);
28
28
  output = await evaluateInput(":rel zero", state);
29
- assert.match(output[0], /^zero = /);
29
+ assert.equal(
30
+ output[0],
31
+ "zero = ?(...) {} |zero ?<{} zero, ...>; " +
32
+ "-- @ZdauiYp7DqPGmHkUiG8yuWz4ZbEgvxZyNkBAmJ4ENhAX"
33
+ );
30
34
 
31
35
  output = await evaluateInput("succ = | succ;", state);
32
36
  output = await evaluateInput(":rel succ", state);
33
- assert.match(output[0], /^succ = /);
37
+ assert.equal(
38
+ output[0],
39
+ "succ = ?X0 |succ ?<X0 succ, ...>; " +
40
+ "-- @SwjzXdcxv8ZbpCkF4cXGtgKkqPTfYqGGP5erQE7DCCsj"
41
+ );
34
42
 
35
43
  output = await evaluateInput(":rels", state);
36
44
  assert.match(output[0], /^zero = @/m);
@@ -400,6 +408,7 @@ output = await evaluateInput("test utf8", utf8AutoState);
400
408
  assert.match(output[0], /utf8\.mjs: test utf8/);
401
409
 
402
410
  const ieeeAutoState = createState();
411
+ await evaluateInput(":load core.k", ieeeAutoState);
403
412
  await evaluateInput(":load Examples/ieee.k", ieeeAutoState);
404
413
  output = await evaluateInput(":codec load ./codecs/ieee.mjs", ieeeAutoState);
405
414
  assert.match(output[0], /^loaded codec ieee\.mjs/);
@@ -625,6 +634,8 @@ assert.equal(output[0], "Current output limit: none");
625
634
 
626
635
  // Verify Examples/djson.k (json?, get, nth, set, del)
627
636
  const djsonKState = createState({ engine: "wasm" });
637
+ await evaluateInput(":load core.k", djsonKState);
638
+ await evaluateInput(":load Examples/ieee.k", djsonKState);
628
639
  output = await evaluateInput(":load Examples/djson.k", djsonKState);
629
640
  assert.equal(output[0], "loaded Examples/djson.k");
630
641
  await evaluateInput(":codec load codecs/djson.mjs", djsonKState);
@@ -969,6 +980,98 @@ assert(
969
980
  )
970
981
  );
971
982
 
983
+ // Verify :rel prints canonical pattern names for input and output patterns
984
+ output = await evaluateInput(":rel car", polyExplicitState);
985
+ assert.equal(
986
+ output[0],
987
+ "car = ?@JagVexzgseRr4rVZRmVpsMbr2AKXDjzZnz6Qnf8a9SNe[X0] " +
988
+ "/cons .car ?X0; " +
989
+ "-- @zjRvxpKqktzNfR3VYSqq4bF9XLQTnCp4MpP82JLmysaP"
990
+ );
991
+ output = await evaluateInput(":rel reverse", polyExplicitState);
992
+ assert.equal(
993
+ output[0],
994
+ "reverse = ?@JagVexzgseRr4rVZRmVpsMbr2AKXDjzZnz6Qnf8a9SNe[X0] " +
995
+ "{() xs, nil acc} _reverse " +
996
+ "?@JagVexzgseRr4rVZRmVpsMbr2AKXDjzZnz6Qnf8a9SNe[X0]; " +
997
+ "-- @JbJ2aQugNct2GGeCJ65zKjN55Bf5YPyGHzsikTCjx82w"
998
+ );
999
+ output = await evaluateInput(":rel nil?", polyExplicitState);
1000
+ assert.equal(
1001
+ output[0],
1002
+ "nil? = ?@JagVexzgseRr4rVZRmVpsMbr2AKXDjzZnz6Qnf8a9SNe[(...)] " +
1003
+ "/nil nil " +
1004
+ "?@JagVexzgseRr4rVZRmVpsMbr2AKXDjzZnz6Qnf8a9SNe[(...)]; " +
1005
+ "-- @YHZEettEijtfW68ekdSKKiZRfiiEkqJjLDb9NNcJnwcg"
1006
+ );
1007
+ output = await evaluateInput(":rel parseJson", djsonKState);
1008
+ assert.equal(
1009
+ output[0],
1010
+ "parseJson = " +
1011
+ "?@Pt3MwQwzUPxQKu58zXR3qUBHWTzfycx5bSZGzcK6EZQK[] " +
1012
+ "json_value {.rest ws /nil end, .value value} .value " +
1013
+ "?@P5C7TQKTSPnFUkYkYzTudJamxAQ3T3fHbvZNqwWMfAA2[]; " +
1014
+ "-- @tWaZchv9AbbWxSHVk8nBpz8jVnjswiwDNhpFZeFwg6Pt"
1015
+ );
1016
+ const shortThresholdState = createState();
1017
+ output = await evaluateInput(":max-pat-length", shortThresholdState);
1018
+ assert.equal(output[0], "Current max pattern length: 30");
1019
+ output = await evaluateInput(":maxPatLength 10", shortThresholdState);
1020
+ assert.equal(output[0], "max pattern length set to 10");
1021
+ output = await evaluateInput(":max-pat-length", shortThresholdState);
1022
+ assert.equal(output[0], "Current max pattern length: 10");
1023
+ await evaluateInput("zero = {} | zero;", shortThresholdState);
1024
+ output = await evaluateInput(":rel zero", shortThresholdState);
1025
+ assert.equal(
1026
+ output[0],
1027
+ "zero = ?(...) {} |zero " +
1028
+ "?@92TYLAz9F3GXM3pwDZhN8rD8vKTRJhX9hS44HzS9WKdM[]; " +
1029
+ "-- @ZdauiYp7DqPGmHkUiG8yuWz4ZbEgvxZyNkBAmJ4ENhAX"
1030
+ );
1031
+ output = await evaluateInput(
1032
+ ":pat @92TYLAz9F3GXM3pwDZhN8rD8vKTRJhX9hS44HzS9WKdM",
1033
+ shortThresholdState
1034
+ );
1035
+ assert.equal(
1036
+ output[0],
1037
+ "@92TYLAz9F3GXM3pwDZhN8rD8vKTRJhX9hS44HzS9WKdM[] = <{} zero, ...>;"
1038
+ );
1039
+ output = await evaluateInput(
1040
+ ":pat ?@92TYLAz9F3GXM3pwDZhN8rD8vKTRJhX9hS44HzS9WKdM",
1041
+ shortThresholdState
1042
+ );
1043
+ assert.equal(
1044
+ output[0],
1045
+ "@92TYLAz9F3GXM3pwDZhN8rD8vKTRJhX9hS44HzS9WKdM[] = <{} zero, ...>;"
1046
+ );
1047
+ output = await evaluateInput(
1048
+ ":pat ?@92TYLAz9F3GXM3pwDZhN8rD8vKTRJhX9hS44HzS9WKdM[]",
1049
+ shortThresholdState
1050
+ );
1051
+ assert.equal(
1052
+ output[0],
1053
+ "@92TYLAz9F3GXM3pwDZhN8rD8vKTRJhX9hS44HzS9WKdM[] = <{} zero, ...>;"
1054
+ );
1055
+ completions = completeInput(":pat ?@92TY", shortThresholdState)[0];
1056
+ assert(
1057
+ completions.includes(
1058
+ ":pat ?@92TYLAz9F3GXM3pwDZhN8rD8vKTRJhX9hS44HzS9WKdM"
1059
+ )
1060
+ );
1061
+ output = await evaluateInput(":max-pat-length none", shortThresholdState);
1062
+ assert.equal(output[0], "max pattern length disabled");
1063
+ output = await evaluateInput(":maxPatLength", shortThresholdState);
1064
+ assert.equal(output[0], "Current max pattern length: none");
1065
+ output = await evaluateInput(":rel zero", shortThresholdState);
1066
+ assert.equal(
1067
+ output[0],
1068
+ "zero = ?(...) {} |zero ?<{} zero, ...>; " +
1069
+ "-- @ZdauiYp7DqPGmHkUiG8yuWz4ZbEgvxZyNkBAmJ4ENhAX"
1070
+ );
1071
+ completions = completeInput(":max", shortThresholdState)[0];
1072
+ assert(completions.includes(":max-pat-length"));
1073
+ assert(completions.includes(":maxPatLength"));
1074
+
972
1075
  fs.rmSync(tmpDir, { recursive: true, force: true });
973
1076
  fs.rmSync(symlinkPath, { force: true });
974
1077
  console.log("OK");