@fraczak/k 8.5.1 → 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.
package/Examples/poly.k CHANGED
@@ -1,6 +1,6 @@
1
1
  -- Examples/poly.k: Polymorphic list functions in k
2
- -- Uses arbitrary-precision integers from Examples/arithmetics.k.
3
2
 
3
+ -- Defined in 'arithmetics.k':
4
4
  int[] = @Nws3vysWqC9PznraTP4kWPp44Rd77NAqrx9dgbtHAjGA[];
5
5
  dec = @yfy9ReCFtxn6HsW2qsER58PXQY8ptEdiH69pfi6rifeh;
6
6
  nat = @74wj62GF7Bp6kN6TgCZ4WVkT6XmppzBQUaYLTzyuMFwc;
package/README.md CHANGED
@@ -68,8 +68,9 @@ relations, libraries, and codecs.
68
68
  | [Examples/list.k](Examples/list.k) | Small generic list example |
69
69
  | [Examples/arithmetics.k](Examples/arithmetics.k) | Arbitrary-precision integer and rational arithmetic |
70
70
  | [Examples/poly.k](Examples/poly.k) | Polymorphic list operations; load arithmetics.k first |
71
- | [Examples/djson.k](Examples/djson.k) | Dynamic JSON operations over binary tries |
72
- | [Examples/ieee.k](Examples/ieee.k) | Binary64 floating-point operations returning `{result, flags}` |
71
+ | [Examples/djson.k](Examples/djson.k) | JSON text parsing and dynamic JSON operations; load `core.k` and `Examples/ieee.k` first |
72
+ | [Examples/ieee.k](Examples/ieee.k) | Binary64 types and `parseFloat64` / `printFloat64`; load `core.k` first |
73
+ | [Examples/ieee-arithmetics.k](Examples/ieee-arithmetics.k) | Binary64 arithmetic returning `{result, flags}`; load `core.k`, then `Examples/ieee.k` first |
73
74
  | [Examples/karatsuba-mult.k](Examples/karatsuba-mult.k) | Alternative integer multiplication algorithm |
74
75
 
75
76
  Load libraries explicitly with `:load` in the REPL. The CLI uses `--lib` with
@@ -172,7 +172,8 @@ printf '{"x":{"a":{}},"y":{"b":{}}}\n' |
172
172
  node "$K_ROOT/codecs/k-print.mjs" |
173
173
  grep -qx '"b"'
174
174
 
175
- node "$K_ROOT/objects/compile.mjs" "$K_ROOT/Examples/ieee.k" "$TMP_DIR/ieee.klib"
175
+ node "$K_ROOT/objects/compile.mjs" --lib "$K_ROOT/core.k" "$K_ROOT/Examples/ieee.k" "$TMP_DIR/ieee-types.klib"
176
+ node "$K_ROOT/objects/compile.mjs" --lib "$TMP_DIR/ieee-types.klib" "$K_ROOT/Examples/ieee-arithmetics.k" "$TMP_DIR/ieee.klib"
176
177
  if node ./bin/k-wasm-compile.mjs --lib "$TMP_DIR/ieee.klib" --lib "$TMP_DIR/ieee.klib" --export mul:times "{()x,()y} times .result" "$TMP_DIR/repeated-lib.wasm" >/dev/null 2>&1; then
177
178
  echo "--lib unexpectedly accepted more than once" >&2
178
179
  exit 1
@@ -53,6 +53,7 @@ const CURATED_VFS_FILES = [
53
53
  "core.k",
54
54
  "arithmetics.k",
55
55
  "ieee.k",
56
+ "ieee-arithmetics.k",
56
57
  "poly.k",
57
58
  "karatsuba-mult.k",
58
59
  "json.mjs",
@@ -2,6 +2,7 @@
2
2
  // Canonical representation, hash resolution, and export helpers.
3
3
 
4
4
  import { annotate } from "./index.mjs";
5
+ import { TypePatternGraph } from "./TypePatternGraph.mjs";
5
6
  import { patternGraphToCanonical, prettyFilter } from "./pretty.mjs";
6
7
  import { patternToPropertyList } from "./codecs/runtime/pattern-json.mjs";
7
8
  import { exportPatternGraph } from "./codecs/runtime/codec.mjs";
@@ -200,7 +201,7 @@ export function resolvePatternCanonicalInfo(name, pat, options = {}) {
200
201
  if (name && pat) allPatterns[name] = pat;
201
202
 
202
203
  let pathMap = {};
203
- if (formalCount > 0) {
204
+ if (formalCount > 0 && name) {
204
205
  try {
205
206
  const markerArgs = formalParams.map((_, i) => ({
206
207
  type: "name",
@@ -434,8 +435,236 @@ export function buildExportPreamble(exports = [], libraries = []) {
434
435
  return lines.join("\n") + "\n";
435
436
  }
436
437
 
438
+ const DEFAULT_MAX_PAT_LENGTH = 30;
439
+
440
+ export function canonicalBoundaryFilterSources(
441
+ typePatternGraph,
442
+ patternIds,
443
+ options = {}
444
+ ) {
445
+ const maxPatLength = options.maxPatLength ?? DEFAULT_MAX_PAT_LENGTH;
446
+ const leafOccurrences = [];
447
+ const knotEntries = [];
448
+
449
+ function buildSingleRootFilter(rawRootId) {
450
+ const subGraph = new TypePatternGraph(
451
+ typePatternGraph.registerCodeDef,
452
+ typePatternGraph.findCode
453
+ );
454
+ const renamed = typePatternGraph.clone([rawRootId], subGraph);
455
+ const rootId = subGraph.find(renamed[rawRootId]);
456
+
457
+ const origByNew = new Map();
458
+ for (const [origId, newId] of Object.entries(renamed)) {
459
+ origByNew.set(
460
+ subGraph.find(Number(newId)),
461
+ typePatternGraph.find(Number(origId))
462
+ );
463
+ }
464
+
465
+ const inDegree = subGraph.patterns.nodes.map(() => 0);
466
+ inDegree[rootId]++;
467
+ subGraph.edges.forEach((outEdges) =>
468
+ Object.values(outEdges).forEach((destMap) =>
469
+ Object.values(destMap).forEach((dst) => inDegree[dst]++)
470
+ )
471
+ );
472
+
473
+ function hasOpenDescendant(startId, seen = new Set()) {
474
+ if (seen.has(startId)) return false;
475
+ seen.add(startId);
476
+ const p = subGraph.get_pattern(startId);
477
+ if (
478
+ p.pattern === "(...)" ||
479
+ p.pattern === "{...}" ||
480
+ p.pattern === "<...>"
481
+ ) {
482
+ return true;
483
+ }
484
+ const edges = subGraph.edges[startId] || {};
485
+ for (const key of Object.keys(edges)) {
486
+ const dst = Object.values(edges[key])[0];
487
+ if (hasOpenDescendant(dst, seen)) return true;
488
+ }
489
+ return false;
490
+ }
491
+
492
+ const dagKnots = new Map();
493
+ let nextKnot = 0;
494
+
495
+ function build(patternId, ancestorKnots) {
496
+ const pattern = subGraph.get_pattern(patternId);
497
+ if (pattern.pattern === "(...)") {
498
+ const origId = origByNew.get(patternId) ?? patternId;
499
+ const node = { type: null, open: true, fields: {} };
500
+ leafOccurrences.push({ origId, node });
501
+ return node;
502
+ }
503
+
504
+ if (ancestorKnots.has(patternId)) {
505
+ const knot = ancestorKnots.get(patternId);
506
+ knot.used = true;
507
+ const refNode = { type: "name", name: knot.name };
508
+ knot.refs.push(refNode);
509
+ return refNode;
510
+ }
511
+
512
+ const isOpenStruct =
513
+ pattern.pattern === "{...}" || pattern.pattern === "<...>";
514
+ const shareAcrossDag =
515
+ isOpenStruct || !hasOpenDescendant(patternId);
516
+
517
+ if (
518
+ shareAcrossDag &&
519
+ inDegree[patternId] > 1 &&
520
+ dagKnots.has(patternId)
521
+ ) {
522
+ const knot = dagKnots.get(patternId);
523
+ knot.used = true;
524
+ const refNode = { type: "name", name: knot.name };
525
+ knot.refs.push(refNode);
526
+ return refNode;
527
+ }
528
+
529
+ const knotEntry = {
530
+ name: `K${nextKnot++}`,
531
+ used: false,
532
+ target: null,
533
+ refs: []
534
+ };
535
+ knotEntries.push(knotEntry);
536
+ const nextAncestors = new Map(ancestorKnots);
537
+ nextAncestors.set(patternId, knotEntry);
538
+ if (shareAcrossDag && inDegree[patternId] > 1) {
539
+ dagKnots.set(patternId, knotEntry);
540
+ }
541
+
542
+ const edges = subGraph.edges[patternId] || {};
543
+ const fields = () =>
544
+ Object.keys(edges)
545
+ .sort()
546
+ .reduce((acc, key) => {
547
+ acc[key] = build(
548
+ Object.values(edges[key])[0],
549
+ nextAncestors
550
+ );
551
+ return acc;
552
+ }, {});
553
+
554
+ let res;
555
+ switch (pattern.pattern) {
556
+ case "type": {
557
+ const code = subGraph.findCode(pattern.type);
558
+ if (code?.code === "product") {
559
+ res = { type: "product", fields: fields() };
560
+ } else if (code?.code === "union") {
561
+ res = { type: "union", fields: fields() };
562
+ } else {
563
+ res = { type: "code", code: pattern.type };
564
+ }
565
+ break;
566
+ }
567
+ case "{...}":
568
+ res = { type: "product", open: true, fields: fields() };
569
+ break;
570
+ case "<...>":
571
+ res = { type: "union", open: true, fields: fields() };
572
+ break;
573
+ case "{}":
574
+ res = { type: "product", fields: fields() };
575
+ break;
576
+ case "<>":
577
+ res = { type: "union", fields: fields() };
578
+ break;
579
+ }
580
+ knotEntry.target = res;
581
+ if (knotEntry.used) {
582
+ res.name = knotEntry.name;
583
+ }
584
+ return res;
585
+ }
586
+
587
+ const built = build(rootId, new Map());
588
+ for (const knot of dagKnots.values()) {
589
+ if (knot.used && knot.target) {
590
+ knot.target.name = knot.name;
591
+ }
592
+ }
593
+ return built;
594
+ }
595
+
596
+ const filters = patternIds.map((id) => buildSingleRootFilter(id));
597
+
598
+ const origCounts = new Map();
599
+ for (const { origId } of leafOccurrences) {
600
+ origCounts.set(origId, (origCounts.get(origId) || 0) + 1);
601
+ }
602
+ const sharedVarByOrig = new Map();
603
+ let nextVar = 0;
604
+ for (const { origId, node } of leafOccurrences) {
605
+ if ((origCounts.get(origId) || 0) > 1) {
606
+ if (!sharedVarByOrig.has(origId)) {
607
+ sharedVarByOrig.set(origId, `X${nextVar++}`);
608
+ }
609
+ node.type = "name";
610
+ node.name = sharedVarByOrig.get(origId);
611
+ delete node.fields;
612
+ }
613
+ }
614
+ const sharedVars = [...sharedVarByOrig.values()];
615
+
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;
623
+ }
624
+ }
625
+ }
626
+
627
+ return filters.map((filter) => {
628
+ const inlineStr = prettyFilter(filter);
629
+ if (
630
+ (filter.type === null &&
631
+ filter.open &&
632
+ Object.keys(filter.fields || {}).length === 0 &&
633
+ !filter.name) ||
634
+ (filter.type === "name" && filter.open) ||
635
+ inlineStr.length <= maxPatLength
636
+ ) {
637
+ return `?${inlineStr}`;
638
+ }
639
+ const info = resolvePatternCanonicalInfo(
640
+ null,
641
+ { params: sharedVars, filter },
642
+ options
643
+ );
644
+ if (
645
+ info.hash &&
646
+ options.registerPatterns &&
647
+ !options.registerPatterns[info.hash]
648
+ ) {
649
+ options.registerPatterns[info.hash] = {
650
+ params: info.canonicalParams || info.params || [],
651
+ filter: info.canonicalFilterAst || filter,
652
+ _canonical: info.hash,
653
+ _canonicalDef: info.def,
654
+ _canonicalParams: info.canonicalParams,
655
+ _graphParams: info.canonicalParams,
656
+ _aliasArgs: info.aliasArgs,
657
+ _canonicalFilterAst: info.canonicalFilterAst
658
+ };
659
+ }
660
+ const args = (info.aliasArgs || []).join(", ");
661
+ return `?${info.hash}[${args}]`;
662
+ });
663
+ }
664
+
437
665
  export default {
438
666
  resolvePatternCanonicalInfo,
439
667
  canonicalPatternHash,
440
- buildExportPreamble
668
+ buildExportPreamble,
669
+ canonicalBoundaryFilterSources
441
670
  };
package/object.mjs CHANGED
@@ -5,7 +5,8 @@ import { TypePatternGraph } from "./TypePatternGraph.mjs";
5
5
  import { patterns2filters, prettyRel } from "./pretty.mjs";
6
6
  import {
7
7
  resolvePatternCanonicalInfo,
8
- buildExportPreamble
8
+ buildExportPreamble,
9
+ canonicalBoundaryFilterSources
9
10
  } from "./canonical-pattern.mjs";
10
11
 
11
12
  const OBJECT_MAGIC = Buffer.from("KOBJ\n");
@@ -842,12 +843,19 @@ function boundaryFilterSources(typePatternGraph, patternIds, aliases) {
842
843
  }));
843
844
  }
844
845
 
845
- function prettyRelation(rel, aliases = {}, relAliases = {}) {
846
- const [inputFilter, outputFilter] = boundaryFilterSources(
847
- rel.typePatternGraph,
848
- [rel.def.patterns[0], rel.def.patterns[1]],
849
- aliases
850
- );
846
+ function prettyRelation(rel, aliases = {}, relAliases = {}, options = {}) {
847
+ const useCanonical = options.canonicalPatterns ?? true;
848
+ const [inputFilter, outputFilter] = useCanonical
849
+ ? canonicalBoundaryFilterSources(
850
+ rel.typePatternGraph,
851
+ [rel.def.patterns[0], rel.def.patterns[1]],
852
+ options
853
+ )
854
+ : boundaryFilterSources(
855
+ rel.typePatternGraph,
856
+ [rel.def.patterns[0], rel.def.patterns[1]],
857
+ aliases
858
+ );
851
859
  const body = rewriteRefsInExp(
852
860
  stripRelationBoundaryFilters(stripDebugFieldsFromExp(rel.def), rel.typePatternGraph),
853
861
  aliases,
@@ -866,7 +874,8 @@ function decompileObject(object) {
866
874
  const relAliases = hydrated.relAlias || {};
867
875
  const aliases = shortestUniqueAliases([
868
876
  ...Object.keys(hydrated.codes),
869
- ...Object.values(relAliases)
877
+ ...Object.values(relAliases),
878
+ ...Object.keys(rels).map((name) => relAliases[name] || name)
870
879
  ]);
871
880
 
872
881
  const emittedRelAliases = new Set();
@@ -876,7 +885,7 @@ function decompileObject(object) {
876
885
  const relName = relAliases[name] || name;
877
886
  if (emittedRelAliases.has(relName)) return null;
878
887
  emittedRelAliases.add(relName);
879
- return `${aliases[relName] || relName} = ${prettyRelation(rel, aliases, relAliases)};`;
888
+ return `${aliases[relName] || relName} = ${prettyRelation(rel, aliases, relAliases, { canonicalPatterns: false })};`;
880
889
  };
881
890
  const compileStats = hydrated.compileStats;
882
891
  const sccs = compileStats?.sccs || [];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fraczak/k",
3
- "version": "8.5.1",
3
+ "version": "8.6.0",
4
4
  "description": "k — a language for content-addressable schemas and data transformations over algebraic data types (products and tagged unions); includes runtime, contract derivation, REPL, and codec toolchain",
5
5
  "publishConfig": {
6
6
  "access": "public"
package/repl.mjs CHANGED
@@ -63,6 +63,7 @@ const COMMAND_NAMES = [
63
63
  "help", "rel", "pattern", "pat", "patterns", "pats",
64
64
  "codecs", "rels", "codec", "input", "reset", "klib", "ko", "load",
65
65
  "engine", "wasm", "pkir", "js", "limit",
66
+ "max-pat-length", "maxPatLength",
66
67
  "quit", "exit"
67
68
  ];
68
69
  const CODEC_COMMAND_NAMES = ["load", "unload", "list"];
@@ -110,7 +111,8 @@ function createState(options = {}) {
110
111
  lastMain: null,
111
112
  lastTiming: null,
112
113
  showTiming: true,
113
- printLimit: options.printLimit ?? Infinity
114
+ printLimit: options.printLimit ?? Infinity,
115
+ maxPatLength: options.maxPatLength ?? 30
114
116
  };
115
117
  }
116
118
 
@@ -732,6 +734,7 @@ function canonicalNames(state) {
732
734
  return [...new Set([
733
735
  ...Object.keys(state.codes),
734
736
  ...Object.keys(state.rels),
737
+ ...Object.keys(state.patterns || {}),
735
738
  ...Object.values(state.typeAliases),
736
739
  ...Object.values(state.relAliases),
737
740
  ...Object.values(state.patternAliases || {})
@@ -1061,16 +1064,23 @@ function completeCommandArgument(line, state) {
1061
1064
 
1062
1065
  if (command === "pattern" || command === "pat") {
1063
1066
  const trimmed = arg.trimStart();
1067
+ const qMatch = trimmed.match(/^(\?\s*)(.*)$/);
1068
+ const qPrefix = qMatch ? qMatch[1] : "";
1069
+ const target = qMatch ? qMatch[2] : trimmed;
1064
1070
  const leadingWhitespace = arg.length - trimmed.length;
1065
- const prefix = line.slice(0, argStart + leadingWhitespace);
1071
+ const prefix = line.slice(0, argStart + leadingWhitespace) + qPrefix;
1066
1072
  const names = Object.keys(state.patterns || {}).sort();
1067
1073
  const matches = names
1068
- .filter((name) => name.startsWith(trimmed))
1074
+ .filter((name) => name.startsWith(target))
1069
1075
  .map((name) => `${prefix}${name}`);
1070
- if (trimmed.startsWith("@")) {
1076
+ if (target.startsWith("@")) {
1071
1077
  for (const [name, p] of Object.entries(state.patterns || {})) {
1072
1078
  const hash = resolvePatternCanonicalName(state, name, p);
1073
- if (hash && hash.startsWith(trimmed)) {
1079
+ if (
1080
+ hash &&
1081
+ hash.startsWith(target) &&
1082
+ !matches.includes(`${prefix}${hash}`)
1083
+ ) {
1074
1084
  matches.push(`${prefix}${hash}`);
1075
1085
  }
1076
1086
  }
@@ -1572,13 +1582,21 @@ async function evaluateCommand(line, state) {
1572
1582
  "Use :rel <name> to show a relation definition"
1573
1583
  );
1574
1584
  }
1585
+ restoreCodes(state);
1575
1586
  const { hash, rel } = resolveRel(state, arg);
1576
1587
  if (!rel) throw new Error(`Unknown relation '${arg}'`);
1577
1588
  const prettyRelStr = prettyRelation(
1578
1589
  rel,
1579
1590
  displayAliases(state),
1580
- state.relAliases
1591
+ state.relAliases,
1592
+ {
1593
+ libraries: [stateLibrary(state)],
1594
+ patterns: state.patterns,
1595
+ registerPatterns: state.patterns,
1596
+ maxPatLength: state.maxPatLength
1597
+ }
1581
1598
  );
1599
+ state.codes = codes.dump();
1582
1600
  return [`${arg} = ${prettyRelStr}; -- ${hash}`];
1583
1601
  }
1584
1602
  case "rels":
@@ -1588,8 +1606,15 @@ async function evaluateCommand(line, state) {
1588
1606
  if (!arg) {
1589
1607
  throw new Error(`${usagePrefix}pattern requires a pattern name`);
1590
1608
  }
1609
+ restoreCodes(state);
1591
1610
  const rawName = arg.trim();
1592
- let patternName = rawName.replace(/\[.*\]$/, "").trim();
1611
+ let patternName = rawName
1612
+ .replace(/^\?\s*/, "")
1613
+ .replace(/\[.*\]$/, "")
1614
+ .trim();
1615
+ if (!patternName) {
1616
+ throw new Error(`${usagePrefix}pattern requires a pattern name`);
1617
+ }
1593
1618
  let pat = null;
1594
1619
  if (patternName.startsWith("@")) {
1595
1620
  pat = state.patterns?.[patternName];
@@ -1681,12 +1706,37 @@ async function evaluateCommand(line, state) {
1681
1706
  state.printLimit = n;
1682
1707
  return [`output limit set to ${n}`];
1683
1708
  }
1709
+ case "maxPatLength":
1710
+ case "max-pat-length": {
1711
+ const mode = (arg || "").trim().toLowerCase();
1712
+ if (!mode) {
1713
+ const current = Number.isFinite(state.maxPatLength)
1714
+ ? state.maxPatLength
1715
+ : "none";
1716
+ return [`Current max pattern length: ${current}`];
1717
+ }
1718
+ if (mode === "none" || mode === "infinity" || mode === "off") {
1719
+ state.maxPatLength = Infinity;
1720
+ return ["max pattern length disabled"];
1721
+ }
1722
+ const n = parseInt(mode, 10);
1723
+ if (Number.isNaN(n) || n < 0) {
1724
+ throw new Error(
1725
+ `Invalid max pattern length '${arg.trim()}'. ` +
1726
+ `Usage: :${command} [num|none]`
1727
+ );
1728
+ }
1729
+ state.maxPatLength = n;
1730
+ return [`max pattern length set to ${n}`];
1731
+ }
1684
1732
  case "reset": {
1685
1733
  const currentEngine = state.engine;
1686
1734
  const currentLimit = state.printLimit;
1735
+ const currentMaxPatLength = state.maxPatLength;
1687
1736
  const fresh = createState({
1688
1737
  engine: currentEngine,
1689
- printLimit: currentLimit
1738
+ printLimit: currentLimit,
1739
+ maxPatLength: currentMaxPatLength
1690
1740
  });
1691
1741
  Object.assign(state, fresh);
1692
1742
  return ["reset"];
@@ -1725,6 +1775,7 @@ function helpText() {
1725
1775
  ":pattern name show named pattern definition (alias :pat)",
1726
1776
  ":patterns list pattern aliases (alias :pats)",
1727
1777
  ":limit [num|none] set maximum characters for value output",
1778
+ ":max-pat-length [n|none] max inline pattern length in :rel (default 30)",
1728
1779
  ":codec load file load a codec module from file",
1729
1780
  ":codec unload name unload a registered codec",
1730
1781
  ":codec list list loaded codecs (or simply :codecs)",
@@ -1762,6 +1813,8 @@ function cliUsage() {
1762
1813
  console.log(" --wasm Shortcut for --engine=wasm.");
1763
1814
  console.log(" --js Shortcut for --engine=js.");
1764
1815
  console.log(" --limit=<num> Set maximum characters for output.");
1816
+ console.log(" --max-pat-length=<num> Set max inline pattern length in :rel");
1817
+ console.log(" (default: 30).");
1765
1818
  console.log(" -h, --help Show this help.");
1766
1819
  }
1767
1820
 
@@ -1858,6 +1911,7 @@ if (isMainEntrypoint()) {
1858
1911
  const args = argv.slice(2);
1859
1912
  let engine = "wasm";
1860
1913
  let printLimit = Infinity;
1914
+ let maxPatLength = 30;
1861
1915
  for (let i = 0; i < args.length; i++) {
1862
1916
  const arg = args[i];
1863
1917
  if (arg === "-h" || arg === "--help") {
@@ -1905,13 +1959,41 @@ if (isMainEntrypoint()) {
1905
1959
  exit(1);
1906
1960
  }
1907
1961
  printLimit = val;
1962
+ } else if (
1963
+ arg.startsWith("--max-pat-length=") ||
1964
+ arg.startsWith("--maxPatLength=")
1965
+ ) {
1966
+ const raw = arg.slice(arg.indexOf("=") + 1).trim().toLowerCase();
1967
+ if (raw === "none" || raw === "infinity" || raw === "off") {
1968
+ maxPatLength = Infinity;
1969
+ } else {
1970
+ const val = parseInt(raw, 10);
1971
+ if (Number.isNaN(val) || val < 0) {
1972
+ console.error(`Invalid max pattern length '${raw}'.`);
1973
+ exit(1);
1974
+ }
1975
+ maxPatLength = val;
1976
+ }
1977
+ } else if (arg === "--max-pat-length" || arg === "--maxPatLength") {
1978
+ i++;
1979
+ const raw = (args[i] || "").trim().toLowerCase();
1980
+ if (raw === "none" || raw === "infinity" || raw === "off") {
1981
+ maxPatLength = Infinity;
1982
+ } else {
1983
+ const val = parseInt(raw, 10);
1984
+ if (Number.isNaN(val) || val < 0) {
1985
+ console.error(`Invalid max pattern length '${args[i]}'.`);
1986
+ exit(1);
1987
+ }
1988
+ maxPatLength = val;
1989
+ }
1908
1990
  } else {
1909
1991
  console.error(`Unknown option '${arg}'.`);
1910
1992
  cliUsage();
1911
1993
  exit(1);
1912
1994
  }
1913
1995
  }
1914
- startRepl({ engine, printLimit });
1996
+ startRepl({ engine, printLimit, maxPatLength });
1915
1997
  }
1916
1998
 
1917
1999
  export {
@@ -3,14 +3,15 @@
3
3
  import { spawnSync } from "node:child_process";
4
4
  import { mkdtempSync, rmSync, statSync } from "node:fs";
5
5
  import { tmpdir } from "node:os";
6
- import { join } from "node:path";
6
+ import { join, resolve } from "node:path";
7
7
  import { performance } from "node:perf_hooks";
8
8
 
9
9
  const DEFAULT_EXAMPLES = [
10
10
  "Examples/nat.k",
11
11
  "Examples/list.k",
12
12
  "Examples/arithmetics.k",
13
- "Examples/ieee.k"
13
+ "Examples/ieee.k",
14
+ "Examples/ieee-arithmetics.k"
14
15
  ];
15
16
 
16
17
  function printHelp() {
@@ -24,7 +25,8 @@ Arguments:
24
25
  example.k ...
25
26
  One or more .k source files to benchmark.
26
27
  (default: Examples/nat.k Examples/list.k
27
- Examples/arithmetics.k Examples/ieee.k)
28
+ Examples/arithmetics.k Examples/ieee.k
29
+ Examples/ieee-arithmetics.k)
28
30
 
29
31
  Options:
30
32
  -h, --help
@@ -52,7 +54,7 @@ function run(args) {
52
54
  });
53
55
  if (result.error) throw result.error;
54
56
  if (result.status !== 0) {
55
- throw new Error(`${args.join(" ")} failed\n${result.stderr || result.stdout}`);
57
+ throw new Error(`${args.join(" ")} failed (${result.status ?? result.signal})\n${result.stderr || result.stdout}`);
56
58
  }
57
59
  }
58
60
 
@@ -81,8 +83,21 @@ for (const example of benchmarkExamples) {
81
83
  for (let i = 0; i < iterations; i++) {
82
84
  const out = mkdtempSync(join(tmpdir(), `k-idempotency-bench-${example.replaceAll("/", "_")}-`));
83
85
  try {
86
+ const isIEEE = resolve(example) === resolve("Examples/ieee.k");
87
+ const isArithmetic = resolve(example) === resolve("Examples/ieee-arithmetics.k");
88
+ let dependency;
89
+ if (isIEEE || isArithmetic) {
90
+ dependency = join(out, "core.klib");
91
+ run(["objects/compile.mjs", "core.k", dependency]);
92
+ }
93
+ if (isArithmetic) {
94
+ const ieee = join(out, "ieee.klib");
95
+ run(["objects/compile.mjs", "--lib", dependency, "Examples/ieee.k", ieee]);
96
+ dependency = ieee;
97
+ }
98
+ const library = dependency ? ["--lib", dependency] : [];
84
99
  const t0 = performance.now();
85
- run(["objects/compile.mjs", example, join(out, "1.klib")]);
100
+ run(["objects/compile.mjs", ...library, example, join(out, "1.klib")]);
86
101
  run(["objects/decompile.mjs", join(out, "1.klib"), join(out, "1.k")]);
87
102
  run(["objects/compile.mjs", join(out, "1.k"), join(out, "2.klib")]);
88
103
  run(["objects/decompile.mjs", join(out, "2.klib"), join(out, "2.k")]);