@fraczak/k 8.6.0 → 8.7.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 (71) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/DOCS/CODECS.md +20 -14
  3. package/DOCS/FILE_FORMATS.md +79 -12
  4. package/DOCS/GETTING_STARTED.md +17 -8
  5. package/DOCS/PATTERNS.md +17 -0
  6. package/DOCS/REPL.md +15 -8
  7. package/Examples/arithmetics.k +81 -468
  8. package/Examples/ieee-arithmetics.k +37 -33
  9. package/Examples/poly.k +107 -104
  10. package/README.md +19 -11
  11. package/backend-api.mjs +3 -1
  12. package/backends/llvm/README.md +1 -1
  13. package/backends/llvm/bin/k-llvm-build.mjs +5 -5
  14. package/backends/llvm/bin/k-llvm-compile.mjs +4 -4
  15. package/backends/llvm/bin/k-llvm.mjs +6 -6
  16. package/backends/llvm/src/cli.mjs +17 -12
  17. package/backends/llvm/tests/integration.sh +4 -1
  18. package/backends/wasm/README.md +3 -3
  19. package/backends/wasm/bin/k-wasm-compile.mjs +4 -4
  20. package/backends/wasm/bin/k-wasm.mjs +4 -4
  21. package/backends/wasm/src/cli.mjs +12 -10
  22. package/backends/wasm/src/wasm.mjs +6 -2
  23. package/backends/wasm/tests/integration.sh +8 -3
  24. package/browser/shims/fs.mjs +19 -3
  25. package/canonical-pattern.mjs +351 -82
  26. package/core.k +2 -1
  27. package/harness/suites/poly.mjs +14 -30
  28. package/k.mjs +17 -13
  29. package/kvm.mjs +13 -9
  30. package/lib/arithmetics.k +287 -0
  31. package/lib/bit.k +68 -0
  32. package/lib/bits.k +221 -0
  33. package/lib/btrie.k +187 -0
  34. package/lib/djson.k +326 -0
  35. package/lib/ieee.k +709 -0
  36. package/lib/list.k +49 -0
  37. package/lib/string.k +588 -0
  38. package/named-patterns.mjs +2 -2
  39. package/object.mjs +52 -10
  40. package/objects/README.md +10 -3
  41. package/objects/compile.mjs +10 -8
  42. package/package.json +1 -1
  43. package/repl.mjs +227 -22
  44. package/scripts/benchmark-idempotency.mjs +22 -15
  45. package/scripts/benchmark.mjs +29 -10
  46. package/scripts/build-repl-html.mjs +49 -14
  47. package/scripts/perf-ieee.mjs +9 -1
  48. package/scripts/perf-int.mjs +10 -17
  49. package/scripts/perf-multiplication.mjs +9 -15
  50. package/scripts/perf-poly.mjs +16 -32
  51. package/scripts/run-tests.mjs +2 -2
  52. package/scripts/test-package.mjs +8 -2
  53. package/tests/helpers/cli.mjs +11 -3
  54. package/tests/integration.sh +9 -4
  55. package/tests/test-arithmetics.mjs +4 -2
  56. package/tests/test-djson-methods.mjs +16 -12
  57. package/tests/test-ieee-arithmetic.mjs +11 -3
  58. package/tests/test-ieee-text.mjs +15 -4
  59. package/tests/test-k-object.mjs +11 -3
  60. package/tests/test-karatsuba.mjs +1 -1
  61. package/tests/test-kvm-polymorphic.mjs +54 -34
  62. package/tests/test-lib.mjs +115 -0
  63. package/tests/test-named-patterns.mjs +12 -3
  64. package/tests/test-parse-json.mjs +33 -13
  65. package/tests/test-poly.mjs +10 -4
  66. package/tests/test-repl-html.mjs +18 -7
  67. package/tests/test-repl.mjs +154 -54
  68. package/Examples/djson.k +0 -894
  69. package/Examples/ieee.k +0 -969
  70. package/Examples/karatsuba-mult.k +0 -227
  71. package/Examples/list.k +0 -10
@@ -3,7 +3,11 @@
3
3
 
4
4
  import { annotate } from "./index.mjs";
5
5
  import { TypePatternGraph } from "./TypePatternGraph.mjs";
6
- import { patternGraphToCanonical, prettyFilter } from "./pretty.mjs";
6
+ import {
7
+ patternGraphToCanonical,
8
+ patterns2filters,
9
+ prettyFilter
10
+ } from "./pretty.mjs";
7
11
  import { patternToPropertyList } from "./codecs/runtime/pattern-json.mjs";
8
12
  import { exportPatternGraph } from "./codecs/runtime/codec.mjs";
9
13
  import { closedPatternToCodeHash } from "./repl-codecs.mjs";
@@ -163,6 +167,88 @@ function toAstFilter(node, canonicalParams = []) {
163
167
  return res;
164
168
  }
165
169
 
170
+ export function instantiateCanonicalFilter(
171
+ canonicalFilterAst,
172
+ canonicalParams = [],
173
+ aliasArgs = []
174
+ ) {
175
+ if (!canonicalFilterAst) return canonicalFilterAst;
176
+ const paramMap = new Map();
177
+ for (let i = 0; i < canonicalParams.length; i++) {
178
+ paramMap.set(
179
+ canonicalParams[i],
180
+ aliasArgs[i] ?? canonicalParams[i]
181
+ );
182
+ }
183
+ const usedArgNames = new Set(
184
+ aliasArgs.filter((a) => a && a !== "(...)")
185
+ );
186
+ const knotNames = new Set();
187
+ function collectKnots(node) {
188
+ if (!node || typeof node !== "object") return;
189
+ if (
190
+ node.name &&
191
+ node.type !== "name" &&
192
+ !paramMap.has(node.name)
193
+ ) {
194
+ knotNames.add(node.name);
195
+ }
196
+ if (node.fields) {
197
+ for (const child of Object.values(node.fields)) {
198
+ collectKnots(child);
199
+ }
200
+ }
201
+ }
202
+ collectKnots(canonicalFilterAst);
203
+
204
+ const knotRename = new Map();
205
+ let nextIdx = 0;
206
+ for (const k of knotNames) {
207
+ if (usedArgNames.has(k)) {
208
+ while (
209
+ usedArgNames.has(`X${nextIdx}`) ||
210
+ knotNames.has(`X${nextIdx}`)
211
+ ) {
212
+ nextIdx++;
213
+ }
214
+ knotRename.set(k, `X${nextIdx++}`);
215
+ }
216
+ }
217
+
218
+ function walk(node) {
219
+ if (!node || typeof node !== "object") return node;
220
+ if (
221
+ (node.type === "name" || node.type === null) &&
222
+ paramMap.has(node.name)
223
+ ) {
224
+ const arg = paramMap.get(node.name);
225
+ if (arg === "(...)") {
226
+ return { type: null, open: true, fields: {} };
227
+ }
228
+ return { type: "name", name: arg, open: true };
229
+ }
230
+ if (
231
+ (node.type === "name" || node.type === null) &&
232
+ knotRename.has(node.name)
233
+ ) {
234
+ return { ...node, name: knotRename.get(node.name) };
235
+ }
236
+ const res = { ...node };
237
+ if (res.name && knotRename.has(res.name)) {
238
+ res.name = knotRename.get(res.name);
239
+ }
240
+ if (res.fields) {
241
+ res.fields = {};
242
+ for (const [k, v] of Object.entries(node.fields)) {
243
+ res.fields[k] = walk(v);
244
+ }
245
+ }
246
+ return res;
247
+ }
248
+
249
+ return walk(canonicalFilterAst);
250
+ }
251
+
166
252
  export function resolvePatternCanonicalInfo(name, pat, options = {}) {
167
253
  if (!pat) return { hash: null, def: null, params: null };
168
254
  if (
@@ -329,55 +415,144 @@ export function canonicalPatternHash(name, pat, options = {}) {
329
415
  return resolvePatternCanonicalInfo(name, pat, options).hash;
330
416
  }
331
417
 
332
- export function buildExportPreamble(exports = [], libraries = []) {
333
- if (exports.length === 0) return "";
418
+ export function parseHeaderDirectives(source) {
419
+ if (!source || typeof source !== "string") return [];
420
+ const directives = [];
421
+ const lines = source.split(/\r?\n/);
422
+ for (const line of lines) {
423
+ const trimmed = line.trim();
424
+ if (!trimmed || trimmed.startsWith("--") || trimmed.startsWith("//") || trimmed.startsWith("%")) {
425
+ continue;
426
+ }
427
+ if (trimmed.startsWith("#")) {
428
+ const match = trimmed.match(/^#\s*--?lib\s+(\S+)\s+--use\s+(.+)$/);
429
+ if (match) {
430
+ directives.push({ lib: match[1], use: match[2].trim() });
431
+ }
432
+ continue;
433
+ }
434
+ if (trimmed.match(/^[a-zA-Z0-9_?!+-]+(?:\[[^\]]*\])?\s*=\s*@[a-zA-Z0-9_-]+(?:\[[^\]]*\])?\s*;/)) {
435
+ continue;
436
+ }
437
+ break;
438
+ }
439
+ return directives;
440
+ }
441
+
442
+ export function parseHeaderUses(source) {
443
+ return parseHeaderDirectives(source);
444
+ }
445
+
446
+ function buildMapsForLibrary(lib) {
334
447
  const relMap = {};
335
448
  const patMap = {};
336
- for (const lib of libraries) {
337
- for (const [name, hash] of Object.entries(lib.relAlias || {})) {
338
- if (name !== "__main__") relMap[name] = { hash };
339
- }
340
- for (const [name, hash] of Object.entries(lib.patternAlias || {})) {
449
+ for (const [name, hash] of Object.entries(lib.relAlias || {})) {
450
+ if (name !== "__main__") relMap[name] = { hash };
451
+ }
452
+ for (const [name, hash] of Object.entries(lib.patternAlias || {})) {
453
+ patMap[name] = {
454
+ hash,
455
+ params:
456
+ lib.patterns?.[name]?.params ||
457
+ lib.patterns?.[name]?._canonicalParams ||
458
+ lib.patterns?.[hash]?.params ||
459
+ [],
460
+ aliasArgs:
461
+ lib.patterns?.[name]?._aliasArgs ||
462
+ lib.meta?.[hash]?.origins?.find((o) => o.name === name)
463
+ ?.aliasArgs ||
464
+ lib.patterns?.[name]?.params ||
465
+ []
466
+ };
467
+ }
468
+ for (const [name, pat] of Object.entries(lib.patterns || {})) {
469
+ if (!patMap[name]) {
341
470
  patMap[name] = {
342
- hash,
343
- params:
344
- lib.patterns?.[name]?.params ||
345
- lib.patterns?.[name]?._canonicalParams ||
346
- lib.patterns?.[hash]?.params ||
347
- [],
348
- aliasArgs:
349
- lib.patterns?.[name]?._aliasArgs ||
350
- lib.meta?.[hash]?.origins?.find((o) => o.name === name)
351
- ?.aliasArgs ||
352
- lib.patterns?.[name]?.params ||
353
- []
471
+ hash: pat._canonical || lib.patternAlias?.[name] || name,
472
+ params: pat.params || [],
473
+ aliasArgs: pat._aliasArgs || pat.params || []
354
474
  };
355
475
  }
356
- for (const [name, pat] of Object.entries(lib.patterns || {})) {
357
- if (!patMap[name]) {
358
- patMap[name] = {
359
- hash: pat._canonical || lib.patternAlias?.[name] || name,
360
- params: pat.params || [],
361
- aliasArgs: pat._aliasArgs || pat.params || []
362
- };
476
+ }
477
+ for (const [hash, entry] of Object.entries(lib.meta || {})) {
478
+ for (const origin of entry?.origins || []) {
479
+ const type = origin?.type || entry?.type;
480
+ if (type === "rel") {
481
+ if (origin?.name && origin.name !== "__main__") {
482
+ relMap[origin.name] = { hash };
483
+ }
484
+ } else if (type === "pattern") {
485
+ if (origin?.name) {
486
+ patMap[origin.name] = {
487
+ hash,
488
+ params: origin.params || entry.params || [],
489
+ aliasArgs:
490
+ origin.aliasArgs ||
491
+ entry.aliasArgs ||
492
+ origin.params ||
493
+ []
494
+ };
495
+ }
363
496
  }
364
497
  }
365
- for (const [hash, entry] of Object.entries(lib.meta || {})) {
366
- for (const origin of entry?.origins || []) {
367
- const type = origin?.type || entry?.type;
368
- if (type === "rel") {
369
- if (origin?.name && origin.name !== "__main__") {
370
- relMap[origin.name] = { hash };
498
+ }
499
+ return { relMap, patMap };
500
+ }
501
+
502
+ function findMatchingLibrary(libPath, libraries) {
503
+ if (!libPath || !libraries || libraries.length === 0) return null;
504
+ const baseName = libPath.split("/").pop();
505
+ for (const lib of libraries) {
506
+ if (lib.source) {
507
+ if (
508
+ lib.source === libPath ||
509
+ lib.source.endsWith("/" + libPath) ||
510
+ lib.source.split("/").pop() === baseName
511
+ ) {
512
+ return lib;
513
+ }
514
+ }
515
+ if (lib.meta) {
516
+ for (const entry of Object.values(lib.meta)) {
517
+ for (const origin of entry?.origins || []) {
518
+ if (
519
+ origin.source &&
520
+ (origin.source === libPath ||
521
+ origin.source.split("/").pop() === baseName)
522
+ ) {
523
+ return lib;
371
524
  }
372
- } else if (type === "pattern") {
373
- if (origin?.name) {
374
- patMap[origin.name] = {
525
+ }
526
+ }
527
+ }
528
+ }
529
+ return null;
530
+ }
531
+
532
+ function matchesSource(actualSource, requestedSource) {
533
+ if (!actualSource || !requestedSource) return false;
534
+ if (actualSource === requestedSource) return true;
535
+ const reqBase = requestedSource.split("/").pop();
536
+ const actBase = actualSource.split("/").pop();
537
+ return reqBase === actBase;
538
+ }
539
+
540
+ function findFromMeta(libPath, name, type, libraries) {
541
+ for (const lib of libraries) {
542
+ if (!lib.meta) continue;
543
+ for (const [hash, entry] of Object.entries(lib.meta)) {
544
+ if (entry?.type !== type && entry?.type !== "any") continue;
545
+ for (const origin of entry?.origins || []) {
546
+ if (origin?.name === name && (origin.type == null || origin.type === type)) {
547
+ if (!libPath || matchesSource(origin.source, libPath)) {
548
+ return {
375
549
  hash,
376
550
  params: origin.params || entry.params || [],
377
551
  aliasArgs:
378
552
  origin.aliasArgs ||
379
553
  entry.aliasArgs ||
380
554
  origin.params ||
555
+ entry.params ||
381
556
  []
382
557
  };
383
558
  }
@@ -385,9 +560,45 @@ export function buildExportPreamble(exports = [], libraries = []) {
385
560
  }
386
561
  }
387
562
  }
563
+ return null;
564
+ }
565
+
566
+ export function buildUsePreamble(exports = [], libraries = []) {
567
+ if (exports.length === 0) return "";
568
+ const globalRelMap = {};
569
+ const globalPatMap = {};
570
+ const libMap = new Map();
571
+
572
+ for (const lib of libraries) {
573
+ const maps = buildMapsForLibrary(lib);
574
+ libMap.set(lib, maps);
575
+ Object.assign(globalRelMap, maps.relMap);
576
+ Object.assign(globalPatMap, maps.patMap);
577
+ }
578
+
579
+ const flatItems = [];
580
+ for (const entry of exports) {
581
+ if (!entry) continue;
582
+ if (typeof entry === "string") {
583
+ const trimmed = entry.trim();
584
+ if (!trimmed) continue;
585
+ for (const spec of trimmed.split(/[\s,]+/).filter(Boolean)) {
586
+ flatItems.push({ lib: null, spec });
587
+ }
588
+ } else if (typeof entry === "object" && entry.use) {
589
+ const trimmed = entry.use.trim();
590
+ if (!trimmed) continue;
591
+ for (const spec of trimmed.split(/[\s,]+/).filter(Boolean)) {
592
+ flatItems.push({ lib: entry.lib || null, spec });
593
+ }
594
+ }
595
+ }
388
596
 
389
597
  const lines = [];
390
- for (const spec of exports) {
598
+ const seenRel = new Set();
599
+ const seenPat = new Set();
600
+ for (const item of flatItems) {
601
+ const spec = item.spec;
391
602
  const [rawLib, rawLocal] = spec.includes(":")
392
603
  ? spec.split(":", 2)
393
604
  : [spec, spec];
@@ -396,46 +607,79 @@ export function buildExportPreamble(exports = [], libraries = []) {
396
607
  const libName = rawLib.replace(/\[.*\]$/, "").trim();
397
608
  const localName = rawLocal.replace(/\[.*\]$/, "").trim();
398
609
 
610
+ let relTarget = null;
611
+ let patTarget = null;
612
+
613
+ if (!isExplicitPattern) {
614
+ if (item.lib) {
615
+ relTarget = findFromMeta(item.lib, libName, "rel", libraries);
616
+ }
617
+ if (!relTarget) {
618
+ const matchedLib = item.lib ? findMatchingLibrary(item.lib, libraries) : null;
619
+ if (matchedLib && libMap.get(matchedLib)?.relMap[libName]) {
620
+ relTarget = libMap.get(matchedLib).relMap[libName];
621
+ } else if (globalRelMap[libName]) {
622
+ relTarget = globalRelMap[libName];
623
+ }
624
+ }
625
+ }
626
+
627
+ if (item.lib) {
628
+ patTarget = findFromMeta(item.lib, libName, "pattern", libraries);
629
+ }
630
+ if (!patTarget) {
631
+ const matchedLib = item.lib ? findMatchingLibrary(item.lib, libraries) : null;
632
+ if (matchedLib && libMap.get(matchedLib)?.patMap[libName]) {
633
+ patTarget = libMap.get(matchedLib).patMap[libName];
634
+ } else if (globalPatMap[libName]) {
635
+ patTarget = globalPatMap[libName];
636
+ }
637
+ }
638
+
399
639
  let emitted = false;
400
- if (!isExplicitPattern && relMap[libName]) {
401
- const target = relMap[libName];
402
- const body = target.hash.startsWith("@")
403
- ? target.hash.slice(1)
404
- : target.hash;
405
- lines.push(`${localName} = @${body};`);
640
+ if (!isExplicitPattern && relTarget) {
641
+ const body = relTarget.hash.startsWith("@")
642
+ ? relTarget.hash.slice(1)
643
+ : relTarget.hash;
644
+ if (!seenRel.has(localName)) {
645
+ lines.push(`${localName} = @${body};`);
646
+ seenRel.add(localName);
647
+ }
406
648
  emitted = true;
407
649
  }
408
- if (patMap[libName]) {
409
- if (isExplicitPattern || !emitted || relMap[libName]) {
410
- const target = patMap[libName];
411
- const body = target.hash.startsWith("@")
412
- ? target.hash.slice(1)
413
- : target.hash;
650
+ if (patTarget) {
651
+ if (isExplicitPattern || !emitted || relTarget) {
652
+ const body = patTarget.hash.startsWith("@")
653
+ ? patTarget.hash.slice(1)
654
+ : patTarget.hash;
414
655
  const paramStr =
415
- target.params && target.params.length > 0
416
- ? `[${target.params.join(", ")}]`
656
+ patTarget.params && patTarget.params.length > 0
657
+ ? `[${patTarget.params.join(", ")}]`
417
658
  : "[]";
418
- const args = target.aliasArgs || target.params;
659
+ const args = patTarget.aliasArgs || patTarget.params;
419
660
  const argStr =
420
661
  args && args.length > 0
421
662
  ? `[${args.join(", ")}]`
422
663
  : paramStr;
423
- lines.push(
424
- `${localName}${paramStr} = @${body}${argStr};`
425
- );
664
+ if (!seenPat.has(localName)) {
665
+ lines.push(
666
+ `${localName}${paramStr} = @${body}${argStr};`
667
+ );
668
+ seenPat.add(localName);
669
+ }
426
670
  emitted = true;
427
671
  }
428
672
  }
429
673
  if (!emitted) {
430
674
  throw new Error(
431
- `--export: '${rawLib}' not found in loaded libraries`
675
+ `--use: '${rawLib}' not found in loaded libraries`
432
676
  );
433
677
  }
434
678
  }
435
- return lines.join("\n") + "\n";
679
+ return lines.length > 0 ? lines.join("\n") + "\n" : "";
436
680
  }
437
681
 
438
- const DEFAULT_MAX_PAT_LENGTH = 30;
682
+ const DEFAULT_MAX_PAT_LENGTH = 45;
439
683
 
440
684
  export function canonicalBoundaryFilterSources(
441
685
  typePatternGraph,
@@ -444,9 +688,9 @@ export function canonicalBoundaryFilterSources(
444
688
  ) {
445
689
  const maxPatLength = options.maxPatLength ?? DEFAULT_MAX_PAT_LENGTH;
446
690
  const leafOccurrences = [];
447
- const knotEntries = [];
448
691
 
449
692
  function buildSingleRootFilter(rawRootId) {
693
+ const filterKnots = [];
450
694
  const subGraph = new TypePatternGraph(
451
695
  typePatternGraph.registerCodeDef,
452
696
  typePatternGraph.findCode
@@ -532,7 +776,7 @@ export function canonicalBoundaryFilterSources(
532
776
  target: null,
533
777
  refs: []
534
778
  };
535
- knotEntries.push(knotEntry);
779
+ filterKnots.push(knotEntry);
536
780
  const nextAncestors = new Map(ancestorKnots);
537
781
  nextAncestors.set(patternId, knotEntry);
538
782
  if (shareAcrossDag && inDegree[patternId] > 1) {
@@ -590,10 +834,11 @@ export function canonicalBoundaryFilterSources(
590
834
  knot.target.name = knot.name;
591
835
  }
592
836
  }
593
- return built;
837
+ return { filter: built, filterKnots };
594
838
  }
595
839
 
596
- const filters = patternIds.map((id) => buildSingleRootFilter(id));
840
+ const builtFilters = patternIds.map((id) => buildSingleRootFilter(id));
841
+ const filters = builtFilters.map((b) => b.filter);
597
842
 
598
843
  const origCounts = new Map();
599
844
  for (const { origId } of leafOccurrences) {
@@ -613,34 +858,48 @@ export function canonicalBoundaryFilterSources(
613
858
  }
614
859
  const sharedVars = [...sharedVarByOrig.values()];
615
860
 
616
- for (const knot of knotEntries) {
617
- if (knot.used && knot.target) {
618
- const knotName = `X${nextVar++}`;
619
- knot.name = knotName;
620
- knot.target.name = knotName;
621
- for (const refNode of knot.refs) {
622
- refNode.name = knotName;
861
+ for (const { filterKnots } of builtFilters) {
862
+ let knotVar = sharedVars.length;
863
+ for (const knot of filterKnots) {
864
+ if (knot.used && knot.target) {
865
+ const knotName = `X${knotVar++}`;
866
+ knot.name = knotName;
867
+ knot.target.name = knotName;
868
+ for (const refNode of knot.refs) {
869
+ refNode.name = knotName;
870
+ }
623
871
  }
624
872
  }
625
873
  }
626
874
 
627
- return filters.map((filter) => {
875
+ const useCanonicalNames = filters.some(
876
+ (filter) => prettyFilter(filter).length > maxPatLength
877
+ );
878
+
879
+ const resolvedByInline = new Map();
880
+ const canonicalSources = filters.map((filter) => {
628
881
  const inlineStr = prettyFilter(filter);
629
- if (
882
+ const isBareWildcard =
630
883
  (filter.type === null &&
631
884
  filter.open &&
632
885
  Object.keys(filter.fields || {}).length === 0 &&
633
886
  !filter.name) ||
634
- (filter.type === "name" && filter.open) ||
635
- inlineStr.length <= maxPatLength
636
- ) {
887
+ (filter.type === "name" && filter.open);
888
+ if (isBareWildcard) {
637
889
  return `?${inlineStr}`;
638
890
  }
639
- const info = resolvePatternCanonicalInfo(
640
- null,
641
- { params: sharedVars, filter },
642
- options
643
- );
891
+ if (!useCanonicalNames && !options.registerPatterns) {
892
+ return `?${inlineStr}`;
893
+ }
894
+ let info = resolvedByInline.get(inlineStr);
895
+ if (!info) {
896
+ info = resolvePatternCanonicalInfo(
897
+ null,
898
+ { params: sharedVars, filter },
899
+ options
900
+ );
901
+ resolvedByInline.set(inlineStr, info);
902
+ }
644
903
  if (
645
904
  info.hash &&
646
905
  options.registerPatterns &&
@@ -653,18 +912,28 @@ export function canonicalBoundaryFilterSources(
653
912
  _canonicalDef: info.def,
654
913
  _canonicalParams: info.canonicalParams,
655
914
  _graphParams: info.canonicalParams,
656
- _aliasArgs: info.aliasArgs,
915
+ _aliasArgs: info.canonicalParams || [],
657
916
  _canonicalFilterAst: info.canonicalFilterAst
658
917
  };
659
918
  }
660
919
  const args = (info.aliasArgs || []).join(", ");
661
920
  return `?${info.hash}[${args}]`;
662
921
  });
922
+
923
+ if (!useCanonicalNames) {
924
+ return patterns2filters(typePatternGraph, ...patternIds).map(
925
+ (f) => `?${prettyFilter(f)}`
926
+ );
927
+ }
928
+ return canonicalSources;
663
929
  }
664
930
 
665
931
  export default {
666
932
  resolvePatternCanonicalInfo,
667
933
  canonicalPatternHash,
668
- buildExportPreamble,
669
- canonicalBoundaryFilterSources
934
+ buildUsePreamble,
935
+ parseHeaderDirectives,
936
+ parseHeaderUses,
937
+ canonicalBoundaryFilterSources,
938
+ instantiateCanonicalFilter
670
939
  };
package/core.k CHANGED
@@ -11,6 +11,7 @@
11
11
 
12
12
  bit[] = < {} 0, {} 1 >;
13
13
  bits[] = < {} _, B 0, B 1 > = B;
14
+ list[X] = < {} nil, {X car, L cdr} cons> = L;
14
15
 
15
16
  ---------------------------------------------------------------
16
17
  -- §2. Unicode and String
@@ -73,7 +74,7 @@ unicode[] = <
73
74
  >;
74
75
 
75
76
  -- Linked-list string: nil or (unicode car, string cdr).
76
- string[] = < {} nil, { unicode[] car, S cdr } cons > = S;
77
+ string[] = list[unicode[]];
77
78
 
78
79
  ---------------------------------------------------------------
79
80
  -- §3. Pattern
@@ -23,47 +23,31 @@ export async function createPolySuite({ listLength = 40, cacheDir = null } = {})
23
23
  const ops = ["reverse", "concat", "split_by", "get_nth", "length"];
24
24
  const benchNames = Object.fromEntries(ops.map(op => [op, `bench_${op}`]));
25
25
 
26
- const arithmeticsPath = fileURLToPath(import.meta.resolve("../../Examples/arithmetics.k"));
27
- const arithmeticsSource = fs.readFileSync(arithmeticsPath, "utf8");
28
- const arithmeticsLib = loadLibrary(compileLibrary(arithmeticsSource, { source: arithmeticsPath }));
26
+ let depLib = null;
27
+ for (const relPath of ["../../lib/bit.k", "../../lib/bits.k", "../../lib/arithmetics.k", "../../lib/list.k"]) {
28
+ const filePath = fileURLToPath(import.meta.resolve(relPath));
29
+ depLib = loadLibrary(compileLibrary(fs.readFileSync(filePath, "utf8"), {
30
+ source: filePath,
31
+ libraries: depLib ? [depLib] : []
32
+ }));
33
+ }
29
34
 
30
35
  const polyPath = fileURLToPath(import.meta.resolve("../../Examples/poly.k"));
31
36
  const polySource = fs.readFileSync(polyPath, "utf8");
32
-
33
- function buildExportPreamble(exports, libraries) {
34
- const aliasMap = {};
35
- for (const lib of libraries) {
36
- for (const [name, hash] of Object.entries(lib.relAlias || {})) {
37
- if (name !== "__main__") aliasMap[name] = hash;
38
- }
39
- }
40
- const lines = [];
41
- for (const spec of exports) {
42
- const [libName, localName] = spec.includes(":") ? spec.split(":", 2) : [spec, spec];
43
- const hash = aliasMap[libName];
44
- if (!hash) throw new Error(`--export: '${libName}' not found in loaded libraries`);
45
- const body = hash.startsWith("@") ? hash.slice(1) : hash;
46
- lines.push(`${localName} = @${body};`);
47
- }
48
- return lines.join("\n") + "\n";
49
- }
50
-
51
- const neededExports = ["0", "int", "inc", "dec", "nat", "zero_int?"];
52
- const exportPreamble = buildExportPreamble(neededExports, [arithmeticsLib]);
53
- const polyLib = loadLibrary(compileLibrary(exportPreamble + polySource, {
37
+ const polyLib = loadLibrary(compileLibrary(polySource, {
54
38
  source: polyPath,
55
- libraries: [arithmeticsLib]
39
+ libraries: [depLib]
56
40
  }));
57
41
 
58
42
  const state = {
59
- codes: { ...arithmeticsLib.codes, ...polyLib.codes },
60
- rels: { ...arithmeticsLib.rels, ...polyLib.rels },
43
+ codes: { ...depLib.codes, ...polyLib.codes },
44
+ rels: { ...depLib.rels, ...polyLib.rels },
61
45
  typeAliases: {},
62
46
  relAliases: { ...polyLib.relAlias },
63
- meta: { ...arithmeticsLib.meta, ...polyLib.meta }
47
+ meta: { ...depLib.meta, ...polyLib.meta }
64
48
  };
65
49
 
66
- for (const [hash, entry] of Object.entries(arithmeticsLib.meta)) {
50
+ for (const [hash, entry] of Object.entries(depLib.meta)) {
67
51
  if (entry.type === "code") {
68
52
  for (const origin of entry.origins || []) {
69
53
  if (origin.name) state.typeAliases[origin.name] = hash;