@fraczak/k 8.5.1 → 8.6.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.
package/repl.mjs CHANGED
@@ -28,6 +28,8 @@ import {
28
28
  prettyFilter
29
29
  } from "./pretty.mjs";
30
30
  import {
31
+ canonicalBoundaryFilterSources,
32
+ instantiateCanonicalFilter,
31
33
  resolvePatternCanonicalInfo as canonicalPatternInfo
32
34
  } from "./canonical-pattern.mjs";
33
35
  import {
@@ -61,8 +63,10 @@ import {
61
63
  const NAME_RE = /^[a-zA-Z0-9_+-][a-zA-Z0-9_?!+-]*$/;
62
64
  const COMMAND_NAMES = [
63
65
  "help", "rel", "pattern", "pat", "patterns", "pats",
66
+ "all-patterns", "all-pat",
64
67
  "codecs", "rels", "codec", "input", "reset", "klib", "ko", "load",
65
68
  "engine", "wasm", "pkir", "js", "limit",
69
+ "max-pat-length", "maxPatLength",
66
70
  "quit", "exit"
67
71
  ];
68
72
  const CODEC_COMMAND_NAMES = ["load", "unload", "list"];
@@ -110,7 +114,8 @@ function createState(options = {}) {
110
114
  lastMain: null,
111
115
  lastTiming: null,
112
116
  showTiming: true,
113
- printLimit: options.printLimit ?? Infinity
117
+ printLimit: options.printLimit ?? Infinity,
118
+ maxPatLength: options.maxPatLength ?? 45
114
119
  };
115
120
  }
116
121
 
@@ -283,6 +288,20 @@ function recoverAliasesFromMeta(state, lib) {
283
288
  state.typeAliases[origin.name] = hash;
284
289
  } else if (type === "pattern") {
285
290
  state.patternAliases[origin.name] = hash;
291
+ if (!state.patterns[origin.name] && state.patterns[hash]) {
292
+ const canonPat = state.patterns[hash];
293
+ state.patterns[origin.name] = {
294
+ params: origin.params || [],
295
+ filter: canonPat.filter,
296
+ _canonical: hash,
297
+ _canonicalDef: canonPat._canonicalDef,
298
+ _canonicalParams: origin.params || [],
299
+ _graphParams: entry.params || canonPat._graphParams || [],
300
+ _aliasArgs: origin.aliasArgs || origin.params || [],
301
+ _canonicalFilterAst:
302
+ canonPat._canonicalFilterAst || canonPat.filter
303
+ };
304
+ }
286
305
  } else if (type === "rel" || hash in state.rels) {
287
306
  state.relAliases[origin.name] = hash;
288
307
  }
@@ -502,10 +521,6 @@ function resolvePatternCanonicalName(state, name, pat) {
502
521
  function prettyPattern(name, pat, state = null) {
503
522
  const info = resolvePatternCanonicalInfo(state, name, pat);
504
523
  const isHash = typeof name === "string" && name.startsWith("@");
505
- const isDirectAlias =
506
- pat?.filter?.type === "pattern_apply" &&
507
- typeof pat.filter.pattern === "string" &&
508
- pat.filter.pattern.startsWith("@");
509
524
 
510
525
  const paramList =
511
526
  isHash && (info.canonicalParams || pat?.params)
@@ -513,18 +528,28 @@ function prettyPattern(name, pat, state = null) {
513
528
  : (pat?.params || info.params || []);
514
529
  const params = paramList.join(", ");
515
530
 
531
+ const aliasArgs = info.aliasArgs || pat?.params || [];
532
+ const canonicalAst =
533
+ info.canonicalFilterAst ||
534
+ (info.hash ? state?.patterns?.[info.hash]?._canonicalFilterAst : null);
535
+ const canonicalParams =
536
+ info.canonicalParams ||
537
+ (info.hash ? state?.patterns?.[info.hash]?._graphParams : null) ||
538
+ [];
539
+
516
540
  let filterStr;
517
541
  if (isHash) {
518
542
  filterStr =
519
543
  info.def || (pat?.filter ? prettyFilter(pat.filter) : "()");
520
- } else if (pat?.filter && !isDirectAlias) {
521
- filterStr = prettyFilter(pat.filter);
544
+ } else if (canonicalAst) {
545
+ filterStr = prettyFilter(
546
+ instantiateCanonicalFilter(canonicalAst, canonicalParams, aliasArgs)
547
+ );
522
548
  } else {
523
549
  filterStr =
524
550
  info.def || (pat?.filter ? prettyFilter(pat.filter) : "()");
525
551
  }
526
552
 
527
- const aliasArgs = info.aliasArgs || pat?.params || [];
528
553
  const argStr = aliasArgs.join(", ");
529
554
  const suffix =
530
555
  info.hash && !isHash ? ` -- ${info.hash}[${argStr}]` : "";
@@ -566,6 +591,142 @@ function listPatternAliases(state) {
566
591
  return aliases.join("\n");
567
592
  }
568
593
 
594
+ function collectRelFilterPairs(exp, pairs = []) {
595
+ if (!exp) return pairs;
596
+ switch (exp.op) {
597
+ case "filter":
598
+ if (exp.patterns?.length >= 2) {
599
+ pairs.push([exp.patterns[0], exp.patterns[1]]);
600
+ }
601
+ break;
602
+ case "comp":
603
+ exp.comp.forEach((child) => collectRelFilterPairs(child, pairs));
604
+ break;
605
+ case "union":
606
+ exp.union.forEach((child) => collectRelFilterPairs(child, pairs));
607
+ break;
608
+ case "product":
609
+ exp.product.forEach(({ exp: child }) =>
610
+ collectRelFilterPairs(child, pairs)
611
+ );
612
+ break;
613
+ }
614
+ return pairs;
615
+ }
616
+
617
+ function registerRelationPatterns(state) {
618
+ if (!state?.rels) return;
619
+ if (!state.patterns) state.patterns = {};
620
+ const rels = reachableRelations(
621
+ state.rels,
622
+ Object.values(state.relAliases || {})
623
+ );
624
+ let registeredAny = false;
625
+ for (const rel of Object.values(rels)) {
626
+ if (rel._patternsRegistered) continue;
627
+ if (rel.typePatternGraph && rel.def?.patterns?.length >= 2) {
628
+ const pairs = [
629
+ [rel.def.patterns[0], rel.def.patterns[1]],
630
+ ...collectRelFilterPairs(rel.def)
631
+ ];
632
+ for (const pair of pairs) {
633
+ canonicalBoundaryFilterSources(rel.typePatternGraph, pair, {
634
+ libraries: [stateLibrary(state)],
635
+ patterns: state.patterns,
636
+ registerPatterns: state.patterns,
637
+ maxPatLength: state.maxPatLength
638
+ });
639
+ }
640
+ registeredAny = true;
641
+ }
642
+ Object.defineProperty(rel, "_patternsRegistered", {
643
+ value: true,
644
+ configurable: true
645
+ });
646
+ }
647
+ if (registeredAny) {
648
+ state.codes = codes.dump();
649
+ }
650
+ }
651
+
652
+ function listAllPatterns(state) {
653
+ registerRelationPatterns(state);
654
+ const byHash = new Map();
655
+ const names = [
656
+ ...new Set([
657
+ ...Object.keys(state?.patternAliases || {}),
658
+ ...Object.keys(state?.patterns || {})
659
+ ])
660
+ ].filter((name) => !name.startsWith("@")).sort();
661
+
662
+ for (const name of names) {
663
+ const pat =
664
+ state?.patterns?.[name] ||
665
+ (state?.patternAliases?.[name]
666
+ ? state?.patterns?.[state.patternAliases[name]]
667
+ : null);
668
+ const info = resolvePatternCanonicalInfo(state, name, pat);
669
+ const hash =
670
+ info?.hash || state?.patternAliases?.[name] || null;
671
+ if (!hash) continue;
672
+ const canonicalPat = state?.patterns?.[hash];
673
+ if (!byHash.has(hash)) {
674
+ const canonicalParams =
675
+ info?.canonicalParams ||
676
+ canonicalPat?._graphParams ||
677
+ canonicalPat?.params ||
678
+ state?.meta?.[hash]?.params ||
679
+ [];
680
+ const def =
681
+ info?.def ||
682
+ canonicalPat?._canonicalDef ||
683
+ (canonicalPat?.filter ? prettyFilter(canonicalPat.filter) : "()");
684
+ byHash.set(hash, { canonicalParams, def, aliases: [] });
685
+ }
686
+ const formalParams = pat?.params || [];
687
+ const paramStr =
688
+ formalParams.length > 0
689
+ ? `[${formalParams.join(",")}]`
690
+ : "[]";
691
+ const args = info?.aliasArgs || formalParams;
692
+ const argStr =
693
+ args.length > 0
694
+ ? `[${args.join(",")}]`
695
+ : "[]";
696
+ byHash.get(hash).aliases.push(`${name}${paramStr} = @${argStr}`);
697
+ }
698
+
699
+ for (const [key, pat] of Object.entries(state?.patterns || {})) {
700
+ if (!key.startsWith("@") || byHash.has(key)) continue;
701
+ const info = resolvePatternCanonicalInfo(state, key, pat);
702
+ const canonicalParams =
703
+ info?.canonicalParams ||
704
+ pat?._graphParams ||
705
+ pat?.params ||
706
+ state?.meta?.[key]?.params ||
707
+ [];
708
+ const def =
709
+ info?.def ||
710
+ pat?._canonicalDef ||
711
+ (pat?.filter ? prettyFilter(pat.filter) : "()");
712
+ byHash.set(key, { canonicalParams, def, aliases: [] });
713
+ }
714
+
715
+ if (byHash.size === 0) return "(none)";
716
+ const lines = [];
717
+ for (const hash of [...byHash.keys()].sort()) {
718
+ const { canonicalParams, def, aliases } = byHash.get(hash);
719
+ const paramStr =
720
+ canonicalParams.length > 0
721
+ ? `[${canonicalParams.join(",")}]`
722
+ : "[]";
723
+ const suffix =
724
+ aliases.length > 0 ? ` -- ${aliases.join(", ")}` : "";
725
+ lines.push(`${hash}${paramStr} = ${def};${suffix}`);
726
+ }
727
+ return lines.join("\n");
728
+ }
729
+
569
730
  function listPatterns(stateOrPatterns) {
570
731
  if (
571
732
  stateOrPatterns &&
@@ -732,6 +893,7 @@ function canonicalNames(state) {
732
893
  return [...new Set([
733
894
  ...Object.keys(state.codes),
734
895
  ...Object.keys(state.rels),
896
+ ...Object.keys(state.patterns || {}),
735
897
  ...Object.values(state.typeAliases),
736
898
  ...Object.values(state.relAliases),
737
899
  ...Object.values(state.patternAliases || {})
@@ -1061,16 +1223,23 @@ function completeCommandArgument(line, state) {
1061
1223
 
1062
1224
  if (command === "pattern" || command === "pat") {
1063
1225
  const trimmed = arg.trimStart();
1226
+ const qMatch = trimmed.match(/^(\?\s*)(.*)$/);
1227
+ const qPrefix = qMatch ? qMatch[1] : "";
1228
+ const target = qMatch ? qMatch[2] : trimmed;
1064
1229
  const leadingWhitespace = arg.length - trimmed.length;
1065
- const prefix = line.slice(0, argStart + leadingWhitespace);
1230
+ const prefix = line.slice(0, argStart + leadingWhitespace) + qPrefix;
1066
1231
  const names = Object.keys(state.patterns || {}).sort();
1067
1232
  const matches = names
1068
- .filter((name) => name.startsWith(trimmed))
1233
+ .filter((name) => name.startsWith(target))
1069
1234
  .map((name) => `${prefix}${name}`);
1070
- if (trimmed.startsWith("@")) {
1235
+ if (target.startsWith("@")) {
1071
1236
  for (const [name, p] of Object.entries(state.patterns || {})) {
1072
1237
  const hash = resolvePatternCanonicalName(state, name, p);
1073
- if (hash && hash.startsWith(trimmed)) {
1238
+ if (
1239
+ hash &&
1240
+ hash.startsWith(target) &&
1241
+ !matches.includes(`${prefix}${hash}`)
1242
+ ) {
1074
1243
  matches.push(`${prefix}${hash}`);
1075
1244
  }
1076
1245
  }
@@ -1220,13 +1389,22 @@ function loadSourceOrKlib(state, targetPath, options = {}) {
1220
1389
  lib,
1221
1390
  compileOptions
1222
1391
  );
1392
+ const { patternNames } = userDefinedNames(source);
1393
+ const definedSet = new Set(patternNames);
1394
+ const patterns = { ...(state.patterns || {}) };
1395
+ for (const [k, v] of Object.entries(lib.patterns || {})) {
1396
+ if (k.startsWith("@") || definedSet.has(k) || !(k in patterns)) {
1397
+ patterns[k] = v;
1398
+ }
1399
+ }
1223
1400
  mergeLibrary(
1224
1401
  state,
1225
1402
  {
1226
1403
  ...lib,
1227
1404
  relAlias,
1228
1405
  patternAlias,
1229
- meta
1406
+ meta,
1407
+ patterns
1230
1408
  },
1231
1409
  targetPath,
1232
1410
  { loadAliases }
@@ -1302,10 +1480,13 @@ function compileSnippetArtifacts(source, state, sourceName = "<repl>") {
1302
1480
  );
1303
1481
  const annotated = annotateWithOptionalIdentity(fullSource, options);
1304
1482
  const { patternNames } = userDefinedNames(source);
1305
- const patterns = {
1306
- ...(state.patterns || {}),
1307
- ...(lib.patterns || {})
1308
- };
1483
+ const definedSet = new Set(patternNames);
1484
+ const patterns = { ...(state.patterns || {}) };
1485
+ for (const [k, v] of Object.entries(lib.patterns || {})) {
1486
+ if (k.startsWith("@") || definedSet.has(k) || !(k in patterns)) {
1487
+ patterns[k] = v;
1488
+ }
1489
+ }
1309
1490
  return {
1310
1491
  annotated,
1311
1492
  lib: {
@@ -1572,13 +1753,21 @@ async function evaluateCommand(line, state) {
1572
1753
  "Use :rel <name> to show a relation definition"
1573
1754
  );
1574
1755
  }
1756
+ restoreCodes(state);
1575
1757
  const { hash, rel } = resolveRel(state, arg);
1576
1758
  if (!rel) throw new Error(`Unknown relation '${arg}'`);
1577
1759
  const prettyRelStr = prettyRelation(
1578
1760
  rel,
1579
1761
  displayAliases(state),
1580
- state.relAliases
1762
+ state.relAliases,
1763
+ {
1764
+ libraries: [stateLibrary(state)],
1765
+ patterns: state.patterns,
1766
+ registerPatterns: state.patterns,
1767
+ maxPatLength: state.maxPatLength
1768
+ }
1581
1769
  );
1770
+ state.codes = codes.dump();
1582
1771
  return [`${arg} = ${prettyRelStr}; -- ${hash}`];
1583
1772
  }
1584
1773
  case "rels":
@@ -1588,8 +1777,15 @@ async function evaluateCommand(line, state) {
1588
1777
  if (!arg) {
1589
1778
  throw new Error(`${usagePrefix}pattern requires a pattern name`);
1590
1779
  }
1780
+ restoreCodes(state);
1591
1781
  const rawName = arg.trim();
1592
- let patternName = rawName.replace(/\[.*\]$/, "").trim();
1782
+ let patternName = rawName
1783
+ .replace(/^\?\s*/, "")
1784
+ .replace(/\[.*\]$/, "")
1785
+ .trim();
1786
+ if (!patternName) {
1787
+ throw new Error(`${usagePrefix}pattern requires a pattern name`);
1788
+ }
1593
1789
  let pat = null;
1594
1790
  if (patternName.startsWith("@")) {
1595
1791
  pat = state.patterns?.[patternName];
@@ -1616,6 +1812,10 @@ async function evaluateCommand(line, state) {
1616
1812
  }
1617
1813
  }
1618
1814
  }
1815
+ if (!pat) {
1816
+ registerRelationPatterns(state);
1817
+ pat = state.patterns?.[patternName];
1818
+ }
1619
1819
  } else {
1620
1820
  pat = state.patterns?.[patternName];
1621
1821
  if (!pat && state.patternAliases?.[patternName]) {
@@ -1629,7 +1829,13 @@ async function evaluateCommand(line, state) {
1629
1829
  }
1630
1830
  case "patterns":
1631
1831
  case "pats":
1832
+ restoreCodes(state);
1632
1833
  return [listPatternAliases(state)];
1834
+ case "all-patterns":
1835
+ case "all-pats":
1836
+ case "all-pat":
1837
+ restoreCodes(state);
1838
+ return [listAllPatterns(state)];
1633
1839
  case "codec":
1634
1840
  case "codecs":
1635
1841
  return loadCodec(arg, state);
@@ -1681,12 +1887,37 @@ async function evaluateCommand(line, state) {
1681
1887
  state.printLimit = n;
1682
1888
  return [`output limit set to ${n}`];
1683
1889
  }
1890
+ case "maxPatLength":
1891
+ case "max-pat-length": {
1892
+ const mode = (arg || "").trim().toLowerCase();
1893
+ if (!mode) {
1894
+ const current = Number.isFinite(state.maxPatLength)
1895
+ ? state.maxPatLength
1896
+ : "none";
1897
+ return [`Current max pattern length: ${current}`];
1898
+ }
1899
+ if (mode === "none" || mode === "infinity" || mode === "off") {
1900
+ state.maxPatLength = Infinity;
1901
+ return ["max pattern length disabled"];
1902
+ }
1903
+ const n = parseInt(mode, 10);
1904
+ if (Number.isNaN(n) || n < 0) {
1905
+ throw new Error(
1906
+ `Invalid max pattern length '${arg.trim()}'. ` +
1907
+ `Usage: :${command} [num|none]`
1908
+ );
1909
+ }
1910
+ state.maxPatLength = n;
1911
+ return [`max pattern length set to ${n}`];
1912
+ }
1684
1913
  case "reset": {
1685
1914
  const currentEngine = state.engine;
1686
1915
  const currentLimit = state.printLimit;
1916
+ const currentMaxPatLength = state.maxPatLength;
1687
1917
  const fresh = createState({
1688
1918
  engine: currentEngine,
1689
- printLimit: currentLimit
1919
+ printLimit: currentLimit,
1920
+ maxPatLength: currentMaxPatLength
1690
1921
  });
1691
1922
  Object.assign(state, fresh);
1692
1923
  return ["reset"];
@@ -1724,7 +1955,9 @@ function helpText() {
1724
1955
  ":rels list relation aliases",
1725
1956
  ":pattern name show named pattern definition (alias :pat)",
1726
1957
  ":patterns list pattern aliases (alias :pats)",
1958
+ ":all-patterns list canonical patterns and aliases (alias :all-pat)",
1727
1959
  ":limit [num|none] set maximum characters for value output",
1960
+ ":max-pat-length [n|none] max inline pattern length in :rel (default 45)",
1728
1961
  ":codec load file load a codec module from file",
1729
1962
  ":codec unload name unload a registered codec",
1730
1963
  ":codec list list loaded codecs (or simply :codecs)",
@@ -1762,6 +1995,8 @@ function cliUsage() {
1762
1995
  console.log(" --wasm Shortcut for --engine=wasm.");
1763
1996
  console.log(" --js Shortcut for --engine=js.");
1764
1997
  console.log(" --limit=<num> Set maximum characters for output.");
1998
+ console.log(" --max-pat-length=<num> Set max inline pattern length in :rel");
1999
+ console.log(" (default: 45).");
1765
2000
  console.log(" -h, --help Show this help.");
1766
2001
  }
1767
2002
 
@@ -1858,6 +2093,7 @@ if (isMainEntrypoint()) {
1858
2093
  const args = argv.slice(2);
1859
2094
  let engine = "wasm";
1860
2095
  let printLimit = Infinity;
2096
+ let maxPatLength = 30;
1861
2097
  for (let i = 0; i < args.length; i++) {
1862
2098
  const arg = args[i];
1863
2099
  if (arg === "-h" || arg === "--help") {
@@ -1905,13 +2141,41 @@ if (isMainEntrypoint()) {
1905
2141
  exit(1);
1906
2142
  }
1907
2143
  printLimit = val;
2144
+ } else if (
2145
+ arg.startsWith("--max-pat-length=") ||
2146
+ arg.startsWith("--maxPatLength=")
2147
+ ) {
2148
+ const raw = arg.slice(arg.indexOf("=") + 1).trim().toLowerCase();
2149
+ if (raw === "none" || raw === "infinity" || raw === "off") {
2150
+ maxPatLength = Infinity;
2151
+ } else {
2152
+ const val = parseInt(raw, 10);
2153
+ if (Number.isNaN(val) || val < 0) {
2154
+ console.error(`Invalid max pattern length '${raw}'.`);
2155
+ exit(1);
2156
+ }
2157
+ maxPatLength = val;
2158
+ }
2159
+ } else if (arg === "--max-pat-length" || arg === "--maxPatLength") {
2160
+ i++;
2161
+ const raw = (args[i] || "").trim().toLowerCase();
2162
+ if (raw === "none" || raw === "infinity" || raw === "off") {
2163
+ maxPatLength = Infinity;
2164
+ } else {
2165
+ const val = parseInt(raw, 10);
2166
+ if (Number.isNaN(val) || val < 0) {
2167
+ console.error(`Invalid max pattern length '${args[i]}'.`);
2168
+ exit(1);
2169
+ }
2170
+ maxPatLength = val;
2171
+ }
1908
2172
  } else {
1909
2173
  console.error(`Unknown option '${arg}'.`);
1910
2174
  cliUsage();
1911
2175
  exit(1);
1912
2176
  }
1913
2177
  }
1914
- startRepl({ engine, printLimit });
2178
+ startRepl({ engine, printLimit, maxPatLength });
1915
2179
  }
1916
2180
 
1917
2181
  export {
@@ -1949,5 +2213,6 @@ export {
1949
2213
  patternFromFilter,
1950
2214
  prettyPattern,
1951
2215
  resolvePatternCanonicalName,
1952
- listPatterns
2216
+ listPatterns,
2217
+ listAllPatterns
1953
2218
  };
@@ -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")]);
@@ -27,7 +27,10 @@ import {
27
27
  } from "../backend-api.mjs";
28
28
  import { parse as parseIntValue } from "../codecs/int.mjs";
29
29
  import { parse as parseFloatValue } from "../codecs/ieee.mjs";
30
+ import { composePattern, edgeSubpattern } from "../Value.mjs";
30
31
  import {
32
+ compileLibrary,
33
+ loadLibrary,
31
34
  compileObjectBuffer as compileBackendObjectBuffer,
32
35
  decodeObject as decodeBackendObject
33
36
  } from "../object.mjs";
@@ -45,7 +48,9 @@ const scriptPath = fileURLToPath(import.meta.url);
45
48
  const root = path.resolve(path.dirname(scriptPath), "..");
46
49
  const kRoot = root;
47
50
  const llvmRoot = path.join(root, "backends/llvm");
48
- const resultsPath = path.join(root, "benchmark-results.json");
51
+ const resultsPath = process.env.K_BENCHMARK_RESULT_PATH
52
+ ? path.resolve(process.env.K_BENCHMARK_RESULT_PATH)
53
+ : path.join(root, "benchmark-results.json");
49
54
 
50
55
  const bigA = "1234567890".repeat(22);
51
56
  const bigB = "9876543210".repeat(22);
@@ -146,11 +151,23 @@ function sha256() {
146
151
  }
147
152
 
148
153
  function suiteSourcePath(suite) {
149
- return path.join(kRoot, suite === "ieee" ? "Examples/ieee.k" : "Examples/arithmetics.k");
154
+ return path.join(kRoot, sourceNameForSuite(suite));
150
155
  }
151
156
 
152
157
  function sourceNameForSuite(suite) {
153
- return suite === "ieee" ? "Examples/ieee.k" : "Examples/arithmetics.k";
158
+ return suite === "ieee" ? "Examples/ieee-arithmetics.k" : "Examples/arithmetics.k";
159
+ }
160
+
161
+ let ieeeDependencies;
162
+ function dependenciesForSuite(suite) {
163
+ if (suite !== "ieee") return [];
164
+ if (!ieeeDependencies) {
165
+ const core = loadLibrary(compileLibrary(fs.readFileSync(path.join(kRoot, "core.k"), "utf8")));
166
+ ieeeDependencies = [loadLibrary(compileLibrary(fs.readFileSync(path.join(kRoot, "Examples/ieee.k"), "utf8"), {
167
+ libraries: [core]
168
+ }))];
169
+ }
170
+ return ieeeDependencies;
154
171
  }
155
172
 
156
173
  function stripTrailingUnitMain(source) {
@@ -174,7 +191,7 @@ function canonicalPattern(propertyList) {
174
191
  }
175
192
 
176
193
  function wireInput(inputVal, relDef) {
177
- const inputPattern = relationPattern(relDef, 0);
194
+ const inputPattern = inputVal.pattern || relationPattern(relDef, 0);
178
195
  const inputWire = encodeToWire(inputVal, inputPattern);
179
196
  return { inputPattern, inputWire };
180
197
  }
@@ -182,7 +199,8 @@ function wireInput(inputVal, relDef) {
182
199
  function backendObjectForCase(testCase) {
183
200
  const source = sourceForCase(testCase);
184
201
  return decodeBackendObject(compileBackendObjectBuffer(source, {
185
- source: `${sourceNameForSuite(testCase.suite)}#${testCase.rel}`
202
+ source: `${sourceNameForSuite(testCase.suite)}#${testCase.rel}`,
203
+ libraries: dependenciesForSuite(testCase.suite)
186
204
  }));
187
205
  }
188
206
 
@@ -454,33 +472,47 @@ async function prepareBackendRunner(job, relation, inputVal, state) {
454
472
 
455
473
  async function prepareState(suite) {
456
474
  const state = createState();
475
+ if (suite === "ieee") {
476
+ await evaluateInput(`:load ${path.join(kRoot, "core.k")}`, state);
477
+ await evaluateInput(`:load ${path.join(kRoot, "Examples/ieee.k")}`, state);
478
+ }
457
479
  await evaluateInput(`:load ${suiteSourcePath(suite)}`, state);
458
480
  return state;
459
481
  }
460
482
 
461
483
  function ieeeInput(testCase, state) {
462
- return Value.product({
484
+ return typedProduct({
463
485
  x: parseFloatValue(testCase.input.x),
464
486
  y: parseFloatValue(testCase.input.y)
465
487
  });
466
488
  }
467
489
 
490
+ function typedProduct(fields) {
491
+ return Value.product(fields, composePattern("closed-product",
492
+ Object.entries(fields).map(([label, value]) => [label, value.pattern])));
493
+ }
494
+
468
495
  function arithmeticInput(testCase) {
469
496
  const { shape } = testCase.input;
470
497
  if (shape === "int") {
471
498
  return parseIntValue(testCase.input.x);
472
499
  }
473
500
  if (shape === "int-pair") {
474
- return Value.product({
501
+ return typedProduct({
475
502
  x: parseIntValue(testCase.input.x),
476
503
  y: parseIntValue(testCase.input.y)
477
504
  });
478
505
  }
479
506
  if (shape === "bits-pair") {
507
+ const x = parseIntValue(testCase.input.x);
508
+ const y = parseIntValue(testCase.input.y);
480
509
  return Value.product({
481
- x: parseIntValue(testCase.input.x).value,
482
- y: parseIntValue(testCase.input.y).value
483
- });
510
+ x: x.value,
511
+ y: y.value
512
+ }, composePattern("closed-product", [
513
+ ["x", edgeSubpattern(x.pattern, x.tag)],
514
+ ["y", edgeSubpattern(y.pattern, y.tag)]
515
+ ]));
484
516
  }
485
517
  throw new Error(`Unknown arithmetic input shape '${shape}'`);
486
518
  }