@fraczak/k 8.7.0 → 8.7.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.
@@ -0,0 +1,381 @@
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
+ import k from "../index.mjs";
9
+ import { Value } from "../Value.mjs";
10
+ import {
11
+ compileObject,
12
+ compileObjectBuffer,
13
+ compileLibrary,
14
+ compileLibraryBuffer,
15
+ loadLibrary,
16
+ decodeObject,
17
+ objectToFunction
18
+ } from "../object.mjs";
19
+ import { createState, evaluateInput } from "../repl.mjs";
20
+
21
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
22
+ const node = process.execPath;
23
+ const compileMjs = path.join(root, "objects/compile.mjs");
24
+ const kMjs = path.join(root, "k.mjs");
25
+ const kPrintMjs = path.join(root, "codecs/k-print.mjs");
26
+ const unitParseMjs = path.join(root, "codecs/unit.mjs");
27
+
28
+ function runCommand(cmd, args, options = {}) {
29
+ const encoding = options.encoding !== undefined ? options.encoding : "utf8";
30
+ const result = spawnSync(cmd, args, {
31
+ cwd: root,
32
+ ...options,
33
+ encoding
34
+ });
35
+ return result;
36
+ }
37
+
38
+ console.log("==> Starting Library Isolation & Scope Binding Tests");
39
+
40
+ // -----------------------------------------------------------------------------
41
+ // §1. Relation Content-Addressable Isolation & Explicit Scope Binding
42
+ // -----------------------------------------------------------------------------
43
+ console.log("--> Test 1: Relations - Content-Addressable Isolation and --use");
44
+ {
45
+ const libSource = `
46
+ greet = {} |hello;
47
+ secret = {} |classified;
48
+ `;
49
+ const libObject = compileLibrary(libSource, { source: "test-lib1.k" });
50
+ const library = loadLibrary(libObject);
51
+
52
+ const greetHash = library.relAlias.greet;
53
+ const secretHash = library.relAlias.secret;
54
+ assert.ok(greetHash && greetHash.startsWith("@"), `Expected @hash for greet, got ${greetHash}`);
55
+ assert.ok(secretHash && secretHash.startsWith("@"), `Expected @hash for secret, got ${secretHash}`);
56
+
57
+ // 1.1 Without --use / useSpecs: friendly name 'greet' is NOT in scope
58
+ assert.throws(
59
+ () => compileObject("greet", { libraries: [library] }),
60
+ /No definition found for 'greet'/,
61
+ "Expected friendly name 'greet' to be inaccessible without --use"
62
+ );
63
+
64
+ // 1.2 Without --use / useSpecs: friendly name 'secret' is NOT in scope
65
+ assert.throws(
66
+ () => compileObject("secret", { libraries: [library] }),
67
+ /No definition found for 'secret'/,
68
+ "Expected friendly name 'secret' to be inaccessible without --use"
69
+ );
70
+
71
+ // 1.3 Without --use / useSpecs: accessing @greetHash directly by hash SUCCEEDS
72
+ const objByHash = compileObject(greetHash, { libraries: [library] });
73
+ const resByHash = objectToFunction(objByHash)(Value.product({}));
74
+ assert.equal(resByHash.tag, "hello", "Accessing library relation by @hash must succeed");
75
+
76
+ // 1.4 Accessing @secretHash directly by hash SUCCEEDS
77
+ const objSecretHash = compileObject(secretHash, { libraries: [library] });
78
+ const resSecret = objectToFunction(objSecretHash)(Value.product({}));
79
+ assert.equal(resSecret.tag, "classified", "Accessing secret relation by @hash must succeed");
80
+
81
+ // 1.5 With explicit useSpecs: ["greet"]:
82
+ // 'greet' is in scope, but 'secret' remains isolated
83
+ const objWithGreet = compileObject("greet", {
84
+ libraries: [library],
85
+ useSpecs: ["greet"]
86
+ });
87
+ const resGreet = objectToFunction(objWithGreet)(Value.product({}));
88
+ assert.equal(resGreet.tag, "hello", "'greet' must be in scope when specified via useSpecs");
89
+
90
+ assert.throws(
91
+ () => compileObject("secret", { libraries: [library], useSpecs: ["greet"] }),
92
+ /No definition found for 'secret'/,
93
+ "'secret' must NOT be in scope when only 'greet' was requested"
94
+ );
95
+
96
+ // 1.6 With aliasing useSpecs: ["greet:custom_hello"]:
97
+ // 'custom_hello' is in scope; 'greet' is NOT
98
+ const objAliased = compileObject("custom_hello", {
99
+ libraries: [library],
100
+ useSpecs: ["greet:custom_hello"]
101
+ });
102
+ const resAliased = objectToFunction(objAliased)(Value.product({}));
103
+ assert.equal(resAliased.tag, "hello", "Aliased name 'custom_hello' must resolve");
104
+
105
+ assert.throws(
106
+ () => compileObject("greet", { libraries: [library], useSpecs: ["greet:custom_hello"] }),
107
+ /No definition found for 'greet'/,
108
+ "Original name 'greet' must NOT be in scope when aliased to 'custom_hello'"
109
+ );
110
+ }
111
+ console.log(" Passed: Relation isolation and explicit scope binding verified.");
112
+
113
+ // -----------------------------------------------------------------------------
114
+ // §2. Pattern Template Content-Addressable Isolation & Explicit Scope Binding
115
+ // -----------------------------------------------------------------------------
116
+ console.log("--> Test 2: Pattern Templates - Content-Addressable Isolation and --use");
117
+ {
118
+ const libSource = `
119
+ pair[A, B] = { A first, B second };
120
+ triple[A, B, C] = { A first, B second, C third };
121
+ `;
122
+ const libObject = compileLibrary(libSource, { source: "test-patterns.k" });
123
+ const library = loadLibrary(libObject);
124
+
125
+ const pairHash = library.patternAlias.pair;
126
+ const tripleHash = library.patternAlias.triple;
127
+ assert.ok(pairHash && pairHash.startsWith("@"), `Expected @hash for pair, got ${pairHash}`);
128
+ assert.ok(tripleHash && tripleHash.startsWith("@"), `Expected @hash for triple, got ${tripleHash}`);
129
+
130
+ // 2.1 Without useSpecs: 'pair[]' is NOT in scope
131
+ assert.throws(
132
+ () => compileObject("is_pair = ?pair[{}, {}]; ()", { libraries: [library] }),
133
+ /Unknown pattern template 'pair\[\]'/,
134
+ "Expected pattern template 'pair[]' to be inaccessible without --use"
135
+ );
136
+
137
+ // 2.2 Without useSpecs: 'triple[]' is NOT in scope
138
+ assert.throws(
139
+ () => compileObject("is_triple = ?triple[{}, {}, {}]; ()", { libraries: [library] }),
140
+ /Unknown pattern template 'triple\[\]'/,
141
+ "Expected pattern template 'triple[]' to be inaccessible without --use"
142
+ );
143
+
144
+ // 2.3 Accessing @pairHash directly by hash SUCCEEDS
145
+ const objPairHash = compileObject(`
146
+ is_pair = ?${pairHash}[{}, {}];
147
+ {{} first, {} second} is_pair
148
+ `, { libraries: [library] });
149
+ const resPair = objectToFunction(objPairHash)(Value.product({}));
150
+ assert.equal(resPair.type, "{}");
151
+
152
+ // 2.4 With explicit useSpecs: ["pair"]:
153
+ // 'pair[]' is in scope; 'triple[]' remains isolated
154
+ const objPairUse = compileObject(`
155
+ is_pair = ?pair[{}, {}];
156
+ {{} first, {} second} is_pair
157
+ `, {
158
+ libraries: [library],
159
+ useSpecs: ["pair"]
160
+ });
161
+ const resPairUse = objectToFunction(objPairUse)(Value.product({}));
162
+ assert.equal(resPairUse.type, "{}");
163
+
164
+ assert.throws(
165
+ () => compileObject("is_triple = ?triple[{}, {}, {}]; ()", {
166
+ libraries: [library],
167
+ useSpecs: ["pair"]
168
+ }),
169
+ /Unknown pattern template 'triple\[\]'/,
170
+ "'triple[]' must NOT be in scope when only 'pair' was requested"
171
+ );
172
+
173
+ // 2.5 With aliasing useSpecs: ["pair:two_tuple"]:
174
+ const objPairAliased = compileObject(`
175
+ is_two = ?two_tuple[{}, {}];
176
+ {{} first, {} second} is_two
177
+ `, {
178
+ libraries: [library],
179
+ useSpecs: ["pair:two_tuple"]
180
+ });
181
+ const resPairAliased = objectToFunction(objPairAliased)(Value.product({}));
182
+ assert.equal(resPairAliased.type, "{}");
183
+
184
+ assert.throws(
185
+ () => compileObject("is_pair = ?pair[{}, {}]; ()", {
186
+ libraries: [library],
187
+ useSpecs: ["pair:two_tuple"]
188
+ }),
189
+ /Unknown pattern template 'pair\[\]'/
190
+ );
191
+ }
192
+ console.log(" Passed: Pattern template isolation and explicit scope binding verified.");
193
+
194
+ // -----------------------------------------------------------------------------
195
+ // §3. Local Definitions vs Unused Library Definitions (No Shadowing Ambiguity)
196
+ // -----------------------------------------------------------------------------
197
+ console.log("--> Test 3: Local definitions and unused library symbols");
198
+ {
199
+ const libSource = `
200
+ foo = {} |library_foo;
201
+ `;
202
+ const library = loadLibrary(compileLibrary(libSource, { source: "lib-foo.k" }));
203
+ const fooHash = library.relAlias.foo;
204
+
205
+ // Local file defines its own 'foo' without --use foo.
206
+ // The local 'foo' evaluates to local_foo.
207
+ // The library foo is only accessible via @fooHash.
208
+ const source = `
209
+ foo = {} |local_foo;
210
+ call_local = foo;
211
+ call_lib = ${fooHash};
212
+ { call_local local, call_lib lib }
213
+ `;
214
+ const compiled = compileObject(source, { libraries: [library] });
215
+ const result = objectToFunction(compiled)(Value.product({}));
216
+ assert.equal(result.product.local.tag, "local_foo");
217
+ assert.equal(result.product.lib.tag, "library_foo");
218
+ }
219
+ console.log(" Passed: Local definitions and library symbols do not clash without --use.");
220
+
221
+ // -----------------------------------------------------------------------------
222
+ // §4. CLI Invocations (compile.mjs and k.mjs)
223
+ // -----------------------------------------------------------------------------
224
+ console.log("--> Test 4: CLI enforcement of isolation and --use");
225
+ {
226
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "k-test-isolation-"));
227
+ try {
228
+ const libPath = path.join(tmpDir, "sample.klib");
229
+ const libSource = "greeting = {} |welcome; secret = {} |hidden;";
230
+ fs.writeFileSync(path.join(tmpDir, "sample.k"), libSource, "utf8");
231
+
232
+ // Build sample.klib
233
+ const buildLib = runCommand(node, [compileMjs, path.join(tmpDir, "sample.k"), libPath]);
234
+ assert.equal(buildLib.status, 0, buildLib.stderr);
235
+
236
+ const libObj = decodeObject(fs.readFileSync(libPath));
237
+ const greetingHash = libObj.relAlias.greeting;
238
+ assert.ok(greetingHash && greetingHash.startsWith("@"));
239
+
240
+ // 4.1 CLI compile.mjs without --use: referencing 'greeting' fails
241
+ const failCompile = runCommand(node, [
242
+ compileMjs,
243
+ "--lib", libPath,
244
+ "greeting",
245
+ path.join(tmpDir, "fail.ko")
246
+ ]);
247
+ assert.notEqual(failCompile.status, 0);
248
+ assert.match(failCompile.stderr, /No definition found for 'greeting'/);
249
+
250
+ // 4.2 CLI compile.mjs referencing @greetingHash succeeds
251
+ const hashKo = path.join(tmpDir, "hash.ko");
252
+ const passHashCompile = runCommand(node, [
253
+ compileMjs,
254
+ "--lib", libPath,
255
+ greetingHash,
256
+ hashKo
257
+ ]);
258
+ assert.equal(passHashCompile.status, 0, passHashCompile.stderr);
259
+ assert.ok(fs.existsSync(hashKo));
260
+
261
+ // 4.3 CLI compile.mjs with --use greeting succeeds
262
+ const greetKo = path.join(tmpDir, "greet.ko");
263
+ const passUseCompile = runCommand(node, [
264
+ compileMjs,
265
+ "--lib", libPath,
266
+ "--use", "greeting",
267
+ "greeting",
268
+ greetKo
269
+ ]);
270
+ assert.equal(passUseCompile.status, 0, passUseCompile.stderr);
271
+ assert.ok(fs.existsSync(greetKo));
272
+
273
+ // 4.4 CLI compile.mjs with --use greeting:my_hello succeeds
274
+ const aliasKo = path.join(tmpDir, "alias.ko");
275
+ const passAliasCompile = runCommand(node, [
276
+ compileMjs,
277
+ "--lib", libPath,
278
+ "--use", "greeting:my_hello",
279
+ "my_hello",
280
+ aliasKo
281
+ ]);
282
+ assert.equal(passAliasCompile.status, 0, passAliasCompile.stderr);
283
+
284
+ // 4.5 CLI k.mjs without --use fails
285
+ const unitBytes = runCommand(node, [unitParseMjs, "--parse"], { encoding: null }).stdout;
286
+ const failRun = runCommand(node, [kMjs, "--lib", libPath, "greeting"], {
287
+ input: unitBytes
288
+ });
289
+ assert.notEqual(failRun.status, 0);
290
+ assert.match(failRun.stderr, /No definition found for 'greeting'/);
291
+
292
+ // 4.6 CLI k.mjs with @greetingHash succeeds
293
+ const passHashRun = runCommand(node, [kMjs, "--lib", libPath, greetingHash], {
294
+ input: unitBytes,
295
+ encoding: null
296
+ });
297
+ assert.equal(passHashRun.status, 0, passHashRun.stderr?.toString());
298
+ const printHash = runCommand(node, [kPrintMjs], {
299
+ input: passHashRun.stdout,
300
+ encoding: "utf8"
301
+ });
302
+ assert.equal(printHash.stdout.trim(), '"welcome"');
303
+
304
+ // 4.7 CLI k.mjs with --use greeting succeeds
305
+ const passUseRun = runCommand(node, [kMjs, "--lib", libPath, "--use", "greeting", "greeting"], {
306
+ input: unitBytes,
307
+ encoding: null
308
+ });
309
+ assert.equal(passUseRun.status, 0, passUseRun.stderr?.toString());
310
+ const printUse = runCommand(node, [kPrintMjs], {
311
+ input: passUseRun.stdout,
312
+ encoding: "utf8"
313
+ });
314
+ assert.equal(printUse.stdout.trim(), '"welcome"');
315
+ } finally {
316
+ fs.rmSync(tmpDir, { recursive: true, force: true });
317
+ }
318
+ }
319
+ console.log(" Passed: CLI isolation and --use flags verified.");
320
+
321
+ // -----------------------------------------------------------------------------
322
+ // §5. Exact Line Number Preservation (No text synthesis or line offset)
323
+ // -----------------------------------------------------------------------------
324
+ console.log("--> Test 5: Exact 1-to-1 source line numbers in diagnostics");
325
+ {
326
+ const sourceWithComment = [
327
+ "# --lib lib/dummy.klib --use hello world",
328
+ "-- Comment line 2",
329
+ "-- Comment line 3",
330
+ "bad_definition = undefined_symbol;",
331
+ "()"
332
+ ].join("\n");
333
+
334
+ try {
335
+ compileObject(sourceWithComment, { source: "test-lines.k" });
336
+ assert.fail("Compilation should fail on undefined_symbol");
337
+ } catch (error) {
338
+ // line 4 must be reported exactly, not shifted by any synthesized preamble
339
+ assert.match(
340
+ error.message,
341
+ /lines 4:18\.\.\.4:34/,
342
+ `Error line must be line 4, got: ${error.message}`
343
+ );
344
+ }
345
+ }
346
+ console.log(" Passed: Exact line numbers preserved without offset.");
347
+
348
+ // -----------------------------------------------------------------------------
349
+ // §6. REPL Sequential :load of Standard Libraries (No Renaming Magic)
350
+ // -----------------------------------------------------------------------------
351
+ console.log("--> Test 6: REPL sequential :load of standard libraries");
352
+ {
353
+ const state = createState();
354
+ const libSequence = [
355
+ "lib/bit.k",
356
+ "lib/bits.k",
357
+ "lib/list.k",
358
+ "lib/btrie.k",
359
+ "lib/string.k",
360
+ "lib/ieee.k",
361
+ "lib/djson.k",
362
+ "lib/arithmetics.k"
363
+ ];
364
+
365
+ for (const libFile of libSequence) {
366
+ await evaluateInput(`:load ${libFile}`, state);
367
+ }
368
+
369
+ // Verify that symbols are accessible in REPL under their exact canonical names
370
+ assert.ok(state.relAliases.inc, "Expected 'inc' in REPL");
371
+ assert.ok(state.relAliases.inc_bits, "Expected 'inc_bits' in REPL");
372
+ assert.ok(state.relAliases.list_size, "Expected 'list_size' in REPL");
373
+ assert.ok(state.relAliases.reverse, "Expected 'reverse' in REPL");
374
+ assert.ok(state.patternAliases.bit, "Expected 'bit[]' in REPL");
375
+ assert.ok(state.patternAliases.list, "Expected 'list[T]' in REPL");
376
+ assert.ok(state.patternAliases.btrie, "Expected 'btrie[V]' in REPL");
377
+ assert.ok(state.patternAliases.unicode, "Expected 'unicode[]' in REPL");
378
+ }
379
+ console.log(" Passed: All standard libraries load cleanly in REPL without renaming.");
380
+
381
+ console.log("==> All Library Isolation & Scope Binding Tests Passed Successfully!");
@@ -132,21 +132,30 @@ assert.equal(evaluate(`
132
132
  my_list[T] = ${LIST}[T];
133
133
  {{}|0 car, {}|nil cdr}|cons ?my_list[my_bit[]]
134
134
  `, { libraries: [library] }).tag, "cons");
135
- // Unexported pattern templates from a library do not leak into scope:
135
+
136
+ // Library patterns are known by hash only unless --use / useSpecs is specified.
136
137
  assert.throws(
137
138
  () => evaluate("is_bit = ?bit[]; ()", { libraries: [library] }),
138
139
  /Unknown pattern template 'bit\[\]'/
139
140
  );
140
141
 
141
- const preambleBoth = buildUsePreamble(["bit", "list"], [library]);
142
- assert.equal(evaluate(preambleBoth + `
142
+ assert.equal(evaluate(`
143
143
  is_bit = ?bit[];
144
144
  is_pair = ?${PAIR}[bit[],bit[]];
145
145
  is_pair_list = ?list[${PAIR}[bit[],bit[]]];
146
146
  b = {}|0 is_bit;
147
147
  p = {b first, {}|1 second} is_pair;
148
148
  {p car, {}|nil cdr}|cons is_pair_list
149
- `, { libraries: [library] }).tag, "cons");
149
+ `, { libraries: [library], useSpecs: ["bit", "list"] }).tag, "cons");
150
+
151
+ assert.equal(evaluate(`
152
+ is_bit = ?my_bit[];
153
+ is_pair = ?${PAIR}[my_bit[],my_bit[]];
154
+ is_pair_list = ?my_list[${PAIR}[my_bit[],my_bit[]]];
155
+ b = {}|0 is_bit;
156
+ p = {b first, {}|1 second} is_pair;
157
+ {p car, {}|nil cdr}|cons is_pair_list
158
+ `, { libraries: [library], useSpecs: ["bit:my_bit", "list:my_list"] }).tag, "cons");
150
159
  assert.ok(evaluate(`
151
160
  @A6vrY7TP9s34tvNgVZsk7N5m4Cr4ZJERYPBevgmqnK7P[X,Y] = {X x,Y y,Y z};
152
161
  {{} x,{} y,{} z} ?@A6vrY7TP9s34tvNgVZsk7N5m4Cr4ZJERYPBevgmqnK7P[{},{}]
@@ -5,6 +5,7 @@ import path from "node:path";
5
5
  import { spawnSync } from "node:child_process";
6
6
  import k from "../index.mjs";
7
7
  import { compileLibrary, loadLibrary } from "../object.mjs";
8
+ import { parseHeaderUses } from "../canonical-pattern.mjs";
8
9
  import { compileWasmArtifact, instantiateWasmArtifact } from "../backends/wasm/src/wasm.mjs";
9
10
  import { fromJsonValue } from "../codecs/djson.mjs";
10
11
  import { textToStringValue } from "../codecs/runtime/unicode-string.mjs";
@@ -20,14 +21,20 @@ for (const file of [
20
21
  "lib/string.k",
21
22
  "lib/ieee.k"
22
23
  ]) {
23
- ieee = loadLibrary(compileLibrary(readFileSync(new URL(`../${file}`, import.meta.url), "utf8"), {
24
+ const fileSource = readFileSync(new URL(`../${file}`, import.meta.url), "utf8");
25
+ const uses = parseHeaderUses(fileSource).map((u) => u.use);
26
+ ieee = loadLibrary(compileLibrary(fileSource, {
24
27
  source: file,
25
- libraries: ieee ? [ieee] : []
28
+ libraries: ieee ? [ieee] : [],
29
+ use: uses
26
30
  }));
27
31
  }
28
- const library = loadLibrary(compileLibrary(readFileSync(new URL("../lib/djson.k", import.meta.url), "utf8"), {
32
+ const djsonSource = readFileSync(new URL("../lib/djson.k", import.meta.url), "utf8");
33
+ const djsonUses = parseHeaderUses(djsonSource).map((u) => u.use);
34
+ const library = loadLibrary(compileLibrary(djsonSource, {
29
35
  source: "lib/djson.k",
30
- libraries: [ieee]
36
+ libraries: [ieee],
37
+ use: djsonUses
31
38
  }));
32
39
  const wasm = await instantiateWasmArtifact(await compileWasmArtifact(library.relAlias.parseJson, { libraries: [library] }));
33
40
  const fast = text => wasm.executeValue(textToStringValue(text));
@@ -95,7 +102,10 @@ try {
95
102
  let prev = null;
96
103
  for (let i = 0; i < chain.length; i++) {
97
104
  const out = path.join(scratch, `step-${i}.klib`);
98
- const args = ["objects/compile.mjs", ...(prev ? ["--lib", prev] : []), chain[i], out];
105
+ const fileSource = readFileSync(new URL(`../${chain[i]}`, import.meta.url), "utf8");
106
+ const uses = parseHeaderUses(fileSource).map((u) => u.use);
107
+ const useArgs = uses.flatMap((u) => ["--use", u]);
108
+ const args = ["objects/compile.mjs", ...(prev ? ["--lib", prev] : []), ...useArgs, chain[i], out];
99
109
  const built = spawnSync(process.execPath, args, {
100
110
  cwd: new URL("..", import.meta.url)
101
111
  });