@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/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,7 +2,12 @@
2
2
  // Canonical representation, hash resolution, and export helpers.
3
3
 
4
4
  import { annotate } from "./index.mjs";
5
- import { patternGraphToCanonical, prettyFilter } from "./pretty.mjs";
5
+ import { TypePatternGraph } from "./TypePatternGraph.mjs";
6
+ import {
7
+ patternGraphToCanonical,
8
+ patterns2filters,
9
+ prettyFilter
10
+ } from "./pretty.mjs";
6
11
  import { patternToPropertyList } from "./codecs/runtime/pattern-json.mjs";
7
12
  import { exportPatternGraph } from "./codecs/runtime/codec.mjs";
8
13
  import { closedPatternToCodeHash } from "./repl-codecs.mjs";
@@ -162,6 +167,88 @@ function toAstFilter(node, canonicalParams = []) {
162
167
  return res;
163
168
  }
164
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
+
165
252
  export function resolvePatternCanonicalInfo(name, pat, options = {}) {
166
253
  if (!pat) return { hash: null, def: null, params: null };
167
254
  if (
@@ -200,7 +287,7 @@ export function resolvePatternCanonicalInfo(name, pat, options = {}) {
200
287
  if (name && pat) allPatterns[name] = pat;
201
288
 
202
289
  let pathMap = {};
203
- if (formalCount > 0) {
290
+ if (formalCount > 0 && name) {
204
291
  try {
205
292
  const markerArgs = formalParams.map((_, i) => ({
206
293
  type: "name",
@@ -434,8 +521,259 @@ export function buildExportPreamble(exports = [], libraries = []) {
434
521
  return lines.join("\n") + "\n";
435
522
  }
436
523
 
524
+ const DEFAULT_MAX_PAT_LENGTH = 45;
525
+
526
+ export function canonicalBoundaryFilterSources(
527
+ typePatternGraph,
528
+ patternIds,
529
+ options = {}
530
+ ) {
531
+ const maxPatLength = options.maxPatLength ?? DEFAULT_MAX_PAT_LENGTH;
532
+ const leafOccurrences = [];
533
+
534
+ function buildSingleRootFilter(rawRootId) {
535
+ const filterKnots = [];
536
+ const subGraph = new TypePatternGraph(
537
+ typePatternGraph.registerCodeDef,
538
+ typePatternGraph.findCode
539
+ );
540
+ const renamed = typePatternGraph.clone([rawRootId], subGraph);
541
+ const rootId = subGraph.find(renamed[rawRootId]);
542
+
543
+ const origByNew = new Map();
544
+ for (const [origId, newId] of Object.entries(renamed)) {
545
+ origByNew.set(
546
+ subGraph.find(Number(newId)),
547
+ typePatternGraph.find(Number(origId))
548
+ );
549
+ }
550
+
551
+ const inDegree = subGraph.patterns.nodes.map(() => 0);
552
+ inDegree[rootId]++;
553
+ subGraph.edges.forEach((outEdges) =>
554
+ Object.values(outEdges).forEach((destMap) =>
555
+ Object.values(destMap).forEach((dst) => inDegree[dst]++)
556
+ )
557
+ );
558
+
559
+ function hasOpenDescendant(startId, seen = new Set()) {
560
+ if (seen.has(startId)) return false;
561
+ seen.add(startId);
562
+ const p = subGraph.get_pattern(startId);
563
+ if (
564
+ p.pattern === "(...)" ||
565
+ p.pattern === "{...}" ||
566
+ p.pattern === "<...>"
567
+ ) {
568
+ return true;
569
+ }
570
+ const edges = subGraph.edges[startId] || {};
571
+ for (const key of Object.keys(edges)) {
572
+ const dst = Object.values(edges[key])[0];
573
+ if (hasOpenDescendant(dst, seen)) return true;
574
+ }
575
+ return false;
576
+ }
577
+
578
+ const dagKnots = new Map();
579
+ let nextKnot = 0;
580
+
581
+ function build(patternId, ancestorKnots) {
582
+ const pattern = subGraph.get_pattern(patternId);
583
+ if (pattern.pattern === "(...)") {
584
+ const origId = origByNew.get(patternId) ?? patternId;
585
+ const node = { type: null, open: true, fields: {} };
586
+ leafOccurrences.push({ origId, node });
587
+ return node;
588
+ }
589
+
590
+ if (ancestorKnots.has(patternId)) {
591
+ const knot = ancestorKnots.get(patternId);
592
+ knot.used = true;
593
+ const refNode = { type: "name", name: knot.name };
594
+ knot.refs.push(refNode);
595
+ return refNode;
596
+ }
597
+
598
+ const isOpenStruct =
599
+ pattern.pattern === "{...}" || pattern.pattern === "<...>";
600
+ const shareAcrossDag =
601
+ isOpenStruct || !hasOpenDescendant(patternId);
602
+
603
+ if (
604
+ shareAcrossDag &&
605
+ inDegree[patternId] > 1 &&
606
+ dagKnots.has(patternId)
607
+ ) {
608
+ const knot = dagKnots.get(patternId);
609
+ knot.used = true;
610
+ const refNode = { type: "name", name: knot.name };
611
+ knot.refs.push(refNode);
612
+ return refNode;
613
+ }
614
+
615
+ const knotEntry = {
616
+ name: `K${nextKnot++}`,
617
+ used: false,
618
+ target: null,
619
+ refs: []
620
+ };
621
+ filterKnots.push(knotEntry);
622
+ const nextAncestors = new Map(ancestorKnots);
623
+ nextAncestors.set(patternId, knotEntry);
624
+ if (shareAcrossDag && inDegree[patternId] > 1) {
625
+ dagKnots.set(patternId, knotEntry);
626
+ }
627
+
628
+ const edges = subGraph.edges[patternId] || {};
629
+ const fields = () =>
630
+ Object.keys(edges)
631
+ .sort()
632
+ .reduce((acc, key) => {
633
+ acc[key] = build(
634
+ Object.values(edges[key])[0],
635
+ nextAncestors
636
+ );
637
+ return acc;
638
+ }, {});
639
+
640
+ let res;
641
+ switch (pattern.pattern) {
642
+ case "type": {
643
+ const code = subGraph.findCode(pattern.type);
644
+ if (code?.code === "product") {
645
+ res = { type: "product", fields: fields() };
646
+ } else if (code?.code === "union") {
647
+ res = { type: "union", fields: fields() };
648
+ } else {
649
+ res = { type: "code", code: pattern.type };
650
+ }
651
+ break;
652
+ }
653
+ case "{...}":
654
+ res = { type: "product", open: true, fields: fields() };
655
+ break;
656
+ case "<...>":
657
+ res = { type: "union", open: true, fields: fields() };
658
+ break;
659
+ case "{}":
660
+ res = { type: "product", fields: fields() };
661
+ break;
662
+ case "<>":
663
+ res = { type: "union", fields: fields() };
664
+ break;
665
+ }
666
+ knotEntry.target = res;
667
+ if (knotEntry.used) {
668
+ res.name = knotEntry.name;
669
+ }
670
+ return res;
671
+ }
672
+
673
+ const built = build(rootId, new Map());
674
+ for (const knot of dagKnots.values()) {
675
+ if (knot.used && knot.target) {
676
+ knot.target.name = knot.name;
677
+ }
678
+ }
679
+ return { filter: built, filterKnots };
680
+ }
681
+
682
+ const builtFilters = patternIds.map((id) => buildSingleRootFilter(id));
683
+ const filters = builtFilters.map((b) => b.filter);
684
+
685
+ const origCounts = new Map();
686
+ for (const { origId } of leafOccurrences) {
687
+ origCounts.set(origId, (origCounts.get(origId) || 0) + 1);
688
+ }
689
+ const sharedVarByOrig = new Map();
690
+ let nextVar = 0;
691
+ for (const { origId, node } of leafOccurrences) {
692
+ if ((origCounts.get(origId) || 0) > 1) {
693
+ if (!sharedVarByOrig.has(origId)) {
694
+ sharedVarByOrig.set(origId, `X${nextVar++}`);
695
+ }
696
+ node.type = "name";
697
+ node.name = sharedVarByOrig.get(origId);
698
+ delete node.fields;
699
+ }
700
+ }
701
+ const sharedVars = [...sharedVarByOrig.values()];
702
+
703
+ for (const { filterKnots } of builtFilters) {
704
+ let knotVar = sharedVars.length;
705
+ for (const knot of filterKnots) {
706
+ if (knot.used && knot.target) {
707
+ const knotName = `X${knotVar++}`;
708
+ knot.name = knotName;
709
+ knot.target.name = knotName;
710
+ for (const refNode of knot.refs) {
711
+ refNode.name = knotName;
712
+ }
713
+ }
714
+ }
715
+ }
716
+
717
+ const useCanonicalNames = filters.some(
718
+ (filter) => prettyFilter(filter).length > maxPatLength
719
+ );
720
+
721
+ const resolvedByInline = new Map();
722
+ const canonicalSources = filters.map((filter) => {
723
+ const inlineStr = prettyFilter(filter);
724
+ const isBareWildcard =
725
+ (filter.type === null &&
726
+ filter.open &&
727
+ Object.keys(filter.fields || {}).length === 0 &&
728
+ !filter.name) ||
729
+ (filter.type === "name" && filter.open);
730
+ if (isBareWildcard) {
731
+ return `?${inlineStr}`;
732
+ }
733
+ if (!useCanonicalNames && !options.registerPatterns) {
734
+ return `?${inlineStr}`;
735
+ }
736
+ let info = resolvedByInline.get(inlineStr);
737
+ if (!info) {
738
+ info = resolvePatternCanonicalInfo(
739
+ null,
740
+ { params: sharedVars, filter },
741
+ options
742
+ );
743
+ resolvedByInline.set(inlineStr, info);
744
+ }
745
+ if (
746
+ info.hash &&
747
+ options.registerPatterns &&
748
+ !options.registerPatterns[info.hash]
749
+ ) {
750
+ options.registerPatterns[info.hash] = {
751
+ params: info.canonicalParams || info.params || [],
752
+ filter: info.canonicalFilterAst || filter,
753
+ _canonical: info.hash,
754
+ _canonicalDef: info.def,
755
+ _canonicalParams: info.canonicalParams,
756
+ _graphParams: info.canonicalParams,
757
+ _aliasArgs: info.canonicalParams || [],
758
+ _canonicalFilterAst: info.canonicalFilterAst
759
+ };
760
+ }
761
+ const args = (info.aliasArgs || []).join(", ");
762
+ return `?${info.hash}[${args}]`;
763
+ });
764
+
765
+ if (!useCanonicalNames) {
766
+ return patterns2filters(typePatternGraph, ...patternIds).map(
767
+ (f) => `?${prettyFilter(f)}`
768
+ );
769
+ }
770
+ return canonicalSources;
771
+ }
772
+
437
773
  export default {
438
774
  resolvePatternCanonicalInfo,
439
775
  canonicalPatternHash,
440
- buildExportPreamble
776
+ buildExportPreamble,
777
+ canonicalBoundaryFilterSources,
778
+ instantiateCanonicalFilter
441
779
  };
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");
@@ -592,7 +593,7 @@ function compileLibrary(script, options = {}) {
592
593
  _canonicalDef: info.def,
593
594
  _canonicalParams: info.canonicalParams,
594
595
  _graphParams: info.canonicalParams,
595
- _aliasArgs: info.aliasArgs,
596
+ _aliasArgs: info.canonicalParams || [],
596
597
  _canonicalFilterAst: info.canonicalFilterAst
597
598
  };
598
599
  }
@@ -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.1",
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"