@fraczak/k 8.1.0 → 8.3.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/object.mjs CHANGED
@@ -3,6 +3,10 @@ import run, { run_rel, run_converged } from "./run.mjs";
3
3
  import codes from "./codes.mjs";
4
4
  import { TypePatternGraph } from "./TypePatternGraph.mjs";
5
5
  import { patterns2filters, prettyRel } from "./pretty.mjs";
6
+ import {
7
+ resolvePatternCanonicalInfo,
8
+ buildExportPreamble
9
+ } from "./canonical-pattern.mjs";
6
10
 
7
11
  const OBJECT_MAGIC = Buffer.from("KOBJ\n");
8
12
 
@@ -65,17 +69,32 @@ function isSourceName(name) {
65
69
 
66
70
  function addOrigin(meta, hash, type, origin) {
67
71
  if (!hash) return;
72
+ origin.type = type;
68
73
  if (!meta[hash]) {
69
74
  meta[hash] = { type, origins: [] };
70
75
  } else if (meta[hash].type == null) {
71
76
  meta[hash].type = type;
72
77
  } else if (meta[hash].type !== type) {
73
- throw new Error(`Metadata type conflict for ${hash}: ${meta[hash].type} vs ${type}`);
78
+ if (
79
+ (meta[hash].type === "rel" && type === "pattern") ||
80
+ (meta[hash].type === "pattern" && type === "rel")
81
+ ) {
82
+ if (type === "rel") meta[hash].type = "rel";
83
+ } else {
84
+ throw new Error(
85
+ `Metadata type conflict for ${hash}: ` +
86
+ `${meta[hash].type} vs ${type}`
87
+ );
88
+ }
89
+ }
90
+ if (type === "pattern" && origin.params) {
91
+ meta[hash].params = origin.params;
74
92
  }
75
93
  if (meta[hash].origins.some((existing) =>
76
94
  existing.source === origin.source &&
77
95
  existing.name === origin.name &&
78
- existing.compiledAt === origin.compiledAt
96
+ existing.compiledAt === origin.compiledAt &&
97
+ (existing.type || meta[hash].type) === type
79
98
  )) {
80
99
  return;
81
100
  }
@@ -288,7 +307,13 @@ function mergeMetaEntries(...metas) {
288
307
  for (const meta of metas) {
289
308
  for (const [hash, entry] of Object.entries(meta || {})) {
290
309
  const type = entry?.type;
291
- if (type !== "code" && type !== "rel") continue;
310
+ if (
311
+ type !== "code" &&
312
+ type !== "rel" &&
313
+ type !== "pattern"
314
+ ) {
315
+ continue;
316
+ }
292
317
  for (const origin of entry.origins || []) {
293
318
  if (!origin?.name) continue;
294
319
  addOrigin(merged, hash, type, { ...origin });
@@ -298,6 +323,19 @@ function mergeMetaEntries(...metas) {
298
323
  return merged;
299
324
  }
300
325
 
326
+ function patternOrigin(source, name, compiledAt, pat, info) {
327
+ const node = pat?.filter;
328
+ return {
329
+ source,
330
+ name,
331
+ params: pat?.params || [],
332
+ aliasArgs: info?.aliasArgs || pat?.params || [],
333
+ compiledAt,
334
+ ...(node?.start ? { start: node.start } : {}),
335
+ ...(node?.end ? { end: node.end } : {})
336
+ };
337
+ }
338
+
301
339
  function buildMeta(annotated, source) {
302
340
  const meta = {};
303
341
  const representatives = annotated.representatives || {};
@@ -321,6 +359,23 @@ function buildMeta(annotated, source) {
321
359
  addOrigin(meta, hash, "rel", relationOrigin(source, name, now, rel));
322
360
  }
323
361
  }
362
+
363
+ const patterns = annotated.sourceDefs?.patterns || {};
364
+ for (const [name, pat] of Object.entries(patterns)) {
365
+ if (!isSourceName(name)) continue;
366
+ const info = resolvePatternCanonicalInfo(name, pat, {
367
+ patterns,
368
+ libraries: annotated.libraries || []
369
+ });
370
+ if (info.hash) {
371
+ addOrigin(
372
+ meta,
373
+ info.hash,
374
+ "pattern",
375
+ patternOrigin(source, name, now, pat, info)
376
+ );
377
+ }
378
+ }
324
379
  return meta;
325
380
  }
326
381
 
@@ -481,15 +536,8 @@ function compileLibrary(script, options = {}) {
481
536
  def: rewriteRefsToCanonical(rel.def, relAlias)
482
537
  };
483
538
  }
484
- const libraryMetaHashes = new Set([
485
- ...Object.keys(allCodes),
486
- ...Object.keys(libRels)
487
- ]);
488
- const libMeta = Object.fromEntries(
489
- Object.entries(meta).filter(([hash]) => libraryMetaHashes.has(hash))
490
- );
491
-
492
539
  const libPatterns = {};
540
+ const patternAlias = {};
493
541
  if (options.libraries) {
494
542
  for (const lib of options.libraries) {
495
543
  const lp =
@@ -498,6 +546,7 @@ function compileLibrary(script, options = {}) {
498
546
  lib.sourceDefs?.patterns ||
499
547
  {};
500
548
  Object.assign(libPatterns, lp);
549
+ Object.assign(patternAlias, lib.patternAlias || {});
501
550
  }
502
551
  }
503
552
  if (options.patterns) {
@@ -507,11 +556,43 @@ function compileLibrary(script, options = {}) {
507
556
  Object.assign(libPatterns, annotated.sourceDefs.patterns);
508
557
  }
509
558
 
559
+ for (const [name, pat] of Object.entries(libPatterns)) {
560
+ if (name.startsWith("@")) continue;
561
+ const info = resolvePatternCanonicalInfo(name, pat, {
562
+ patterns: libPatterns,
563
+ libraries: options.libraries || []
564
+ });
565
+ if (info.hash) {
566
+ patternAlias[name] = info.hash;
567
+ if (!libPatterns[info.hash]) {
568
+ libPatterns[info.hash] = {
569
+ params:
570
+ info.canonicalParams ||
571
+ info.params ||
572
+ pat.params ||
573
+ [],
574
+ filter: info.canonicalFilterAst || pat.filter
575
+ };
576
+ }
577
+ }
578
+ }
579
+
580
+ const libraryMetaHashes = new Set([
581
+ ...Object.keys(allCodes),
582
+ ...Object.keys(libRels),
583
+ ...Object.values(patternAlias),
584
+ ...Object.keys(libPatterns).filter((k) => k.startsWith("@"))
585
+ ]);
586
+ const libMeta = Object.fromEntries(
587
+ Object.entries(meta).filter(([hash]) => libraryMetaHashes.has(hash))
588
+ );
589
+
510
590
  return {
511
591
  format: "k-object",
512
592
  codes: allCodes,
513
593
  rels: libRels,
514
594
  relAlias: serialized.relAlias,
595
+ patternAlias,
515
596
  compileStats: serialized.compileStats,
516
597
  meta: libMeta,
517
598
  patterns: libPatterns,
@@ -533,7 +614,8 @@ function hydrateObject(object) {
533
614
  return {
534
615
  ...object,
535
616
  rels: hydratedRels,
536
- patterns: object.patterns || {}
617
+ patterns: object.patterns || {},
618
+ patternAlias: object.patternAlias || {}
537
619
  };
538
620
  }
539
621
 
@@ -856,10 +938,15 @@ function extractAliasesFromObject(object) {
856
938
  const entries = [];
857
939
 
858
940
  for (const [hash, entry] of Object.entries(hydrated.meta || {})) {
859
- const type = entry?.type;
860
- if (type !== "code" && type !== "rel") continue;
861
- const typeOrder = type === "code" ? 0 : 1;
862
941
  for (const origin of entry.origins || []) {
942
+ const type = origin.type || entry?.type;
943
+ if (
944
+ type !== "code" &&
945
+ type !== "rel" &&
946
+ type !== "pattern"
947
+ ) continue;
948
+ const typeOrder =
949
+ type === "code" ? 0 : (type === "pattern" ? 1 : 2);
863
950
  if (origin?.name === "__main__") continue;
864
951
  if (!origin?.name || !isSourceName(origin.name)) continue;
865
952
  entries.push({
@@ -867,6 +954,12 @@ function extractAliasesFromObject(object) {
867
954
  typeOrder,
868
955
  hash,
869
956
  name: origin.name,
957
+ params: origin.params || entry.params || [],
958
+ aliasArgs:
959
+ origin.aliasArgs ||
960
+ entry.aliasArgs ||
961
+ origin.params ||
962
+ [],
870
963
  source: origin.source || "",
871
964
  compiledAt: origin.compiledAt,
872
965
  comment: originComment(origin)
@@ -879,7 +972,11 @@ function extractAliasesFromObject(object) {
879
972
  const activeEntries = new Set();
880
973
  for (let i = 0; i < entries.length; i++) {
881
974
  const next = entries[i + 1];
882
- if (!next || next.type !== entries[i].type || next.name !== entries[i].name) {
975
+ if (
976
+ !next ||
977
+ next.type !== entries[i].type ||
978
+ next.name !== entries[i].name
979
+ ) {
883
980
  activeEntries.add(entries[i]);
884
981
  }
885
982
  }
@@ -889,8 +986,26 @@ function extractAliasesFromObject(object) {
889
986
  for (const entry of entries) {
890
987
  if (lastType != null && lastType !== entry.type) lines.push("");
891
988
  lastType = entry.type;
892
- const prefix = entry.type === "code" ? "$ " : "";
893
- const line = `${prefix}${entry.name} = @${hashBody(entry.hash)}; # ${entry.comment}`;
989
+ let line;
990
+ const body = hashBody(entry.hash);
991
+ if (entry.type === "code") {
992
+ line = `$ ${entry.name} = @${body}; # ${entry.comment}`;
993
+ } else if (entry.type === "pattern") {
994
+ const paramStr =
995
+ entry.params && entry.params.length > 0
996
+ ? `[${entry.params.join(", ")}]`
997
+ : "[]";
998
+ const args = entry.aliasArgs || entry.params;
999
+ const argStr =
1000
+ args && args.length > 0
1001
+ ? `[${args.join(", ")}]`
1002
+ : paramStr;
1003
+ line =
1004
+ `${entry.name}${paramStr} = @${body}${argStr}; ` +
1005
+ `# ${entry.comment}`;
1006
+ } else {
1007
+ line = `${entry.name} = @${body}; # ${entry.comment}`;
1008
+ }
894
1009
  lines.push(activeEntries.has(entry) ? line : `# ${line}`);
895
1010
  }
896
1011
 
@@ -920,7 +1035,8 @@ export {
920
1035
  decompileObject,
921
1036
  decompileObjectBuffer,
922
1037
  extractAliasesFromObject,
923
- extractAliasesFromObjectBuffer
1038
+ extractAliasesFromObjectBuffer,
1039
+ buildExportPreamble
924
1040
  };
925
1041
 
926
1042
  export default {
@@ -942,5 +1058,6 @@ export default {
942
1058
  decompileObject,
943
1059
  decompileObjectBuffer,
944
1060
  extractAliasesFromObject,
945
- extractAliasesFromObjectBuffer
1061
+ extractAliasesFromObjectBuffer,
1062
+ buildExportPreamble
946
1063
  };
@@ -8,7 +8,8 @@ import {
8
8
  compileLibrary,
9
9
  compileLibraryBuffer,
10
10
  decodeObject,
11
- loadLibrary
11
+ loadLibrary,
12
+ buildExportPreamble
12
13
  } from "../object.mjs";
13
14
  import { objectToKVMArtifact } from "../kvm.mjs";
14
15
 
@@ -108,34 +109,6 @@ function resolveInput(inputArg) {
108
109
  };
109
110
  }
110
111
 
111
- function buildExportPreamble(exports, libraries) {
112
- if (exports.length === 0) return "";
113
- // Build a combined alias map from all libraries: name -> @hash
114
- const aliasMap = {};
115
- for (const lib of libraries) {
116
- for (const [name, hash] of Object.entries(lib.relAlias || {})) {
117
- if (name !== "__main__") aliasMap[name] = hash;
118
- }
119
- for (const [hash, entry] of Object.entries(lib.meta || {})) {
120
- if (entry?.type !== "rel") continue;
121
- for (const origin of entry?.origins || []) {
122
- if (origin?.name && origin.name !== "__main__") {
123
- aliasMap[origin.name] = hash;
124
- }
125
- }
126
- }
127
- }
128
- const lines = [];
129
- for (const spec of exports) {
130
- const [libName, localName] = spec.includes(":") ? spec.split(":", 2) : [spec, spec];
131
- const hash = aliasMap[libName];
132
- if (!hash) throw new Error(`--export: '${libName}' not found in loaded libraries`);
133
- const body = hash.startsWith("@") ? hash.slice(1) : hash;
134
- lines.push(`${localName} = @${body};`);
135
- }
136
- return lines.join("\n") + "\n";
137
- }
138
-
139
112
  function objectToKVM(object) {
140
113
  return JSON.stringify(objectToKVMArtifact(object), null, 2) + "\n";
141
114
  }
@@ -185,6 +185,7 @@ export function validateObjectPayload(object) {
185
185
  assertObject(object.codes || {}, "object.codes");
186
186
  assertObject(object.rels || {}, "object.rels");
187
187
  assertObject(object.relAlias || {}, "object.relAlias");
188
+ assertObject(object.patternAlias || {}, "object.patternAlias");
188
189
  assertObject(object.meta || {}, "object.meta");
189
190
  assertObject(object.compileStats || {}, "object.compileStats");
190
191
 
@@ -204,6 +205,11 @@ export function validateObjectPayload(object) {
204
205
  }
205
206
  }
206
207
 
208
+ for (const [name, hash] of Object.entries(object.patternAlias || {})) {
209
+ assertString(name, `object.patternAlias key ${name}`);
210
+ assertString(hash, `object.patternAlias.${name}`);
211
+ }
212
+
207
213
  for (const [name, rel] of Object.entries(object.rels || {})) {
208
214
  assertObject(rel, `object.rels.${name}`);
209
215
  validateObjectExp(rel.def, `object.rels.${name}.def`, relNames, codeNames);
@@ -214,7 +220,13 @@ export function validateObjectPayload(object) {
214
220
 
215
221
  for (const [hash, entry] of Object.entries(object.meta || {})) {
216
222
  assertObject(entry, `object.meta.${hash}`);
217
- if (entry.type !== "code" && entry.type !== "rel") fail(`object.meta.${hash}.type must be code or rel`);
223
+ if (
224
+ entry.type !== "code" &&
225
+ entry.type !== "rel" &&
226
+ entry.type !== "pattern"
227
+ ) {
228
+ fail(`object.meta.${hash}.type must be code, rel, or pattern`);
229
+ }
218
230
  assertArray(entry.origins || [], `object.meta.${hash}.origins`);
219
231
  }
220
232
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fraczak/k",
3
- "version": "8.1.0",
3
+ "version": "8.3.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/parser.jison CHANGED
@@ -7,6 +7,52 @@ function anError(pos,msg) {
7
7
  throw new Error(`Parse Error (lines ${pos.first_line}:${pos.first_column}...${pos.last_line}:${pos.last_column}): ${msg}`);
8
8
  }
9
9
 
10
+ function collectFilterKnots(filter) {
11
+ const knots = new Set();
12
+ function walk(node) {
13
+ if (!node || typeof node !== "object") return;
14
+ if (node.name && node.type !== "name") {
15
+ knots.add(node.name);
16
+ }
17
+ if (node.fields) {
18
+ for (const child of Object.values(node.fields)) {
19
+ walk(child);
20
+ }
21
+ }
22
+ if (node.args) {
23
+ for (const arg of node.args) {
24
+ walk(arg);
25
+ }
26
+ }
27
+ }
28
+ walk(filter);
29
+ return knots;
30
+ }
31
+
32
+ function validatePatternParams(params, name, loc, filter) {
33
+ const seen = new Set();
34
+ for (const p of params) {
35
+ if (seen.has(p)) {
36
+ const msg =
37
+ `Duplicate parameter '${p}' in pattern '${name}'.`;
38
+ anError(loc, msg);
39
+ }
40
+ seen.add(p);
41
+ }
42
+ if (filter) {
43
+ const knots = collectFilterKnots(filter);
44
+ for (const p of params) {
45
+ if (knots.has(p)) {
46
+ const msg =
47
+ `Pattern parameter '${p}' in pattern '${name}' ` +
48
+ `conflicts with knot '${p}'. ` +
49
+ `Knot variables cannot be pattern parameters.`;
50
+ anError(loc, msg);
51
+ }
52
+ }
53
+ }
54
+ }
55
+
10
56
  function getToken(yytext,yy,lstack) {
11
57
  const yylloc = yy.lexer.yylloc;
12
58
  const loc = lstack[lstack.length - 1]; // { first_line: 5, last_line: 5, first_column: 2, last_column: 3 };
@@ -124,18 +170,14 @@ defs: { }
124
170
  | defs name eq comp sc { s.add_rel($2.value,$4); }
125
171
  | defs name lb pattern_params rb eq filter sc
126
172
  {
127
- const seen = new Set();
128
- for (const p of $4) {
129
- if (seen.has(p)) {
130
- const msg =
131
- `Duplicate parameter '${p}' ` +
132
- `in pattern '${$2.value}'.`;
133
- anError(@4, msg);
134
- }
135
- seen.add(p);
136
- }
173
+ validatePatternParams($4, $2.value, @4, $7);
137
174
  s.add_pattern($2.value, $4, $7);
138
175
  }
176
+ | defs at name lb pattern_params rb eq filter sc
177
+ {
178
+ validatePatternParams($5, "@" + $3.value, @5, $8);
179
+ s.add_pattern("@" + $3.value, $5, $8);
180
+ }
139
181
  ;
140
182
 
141
183
  pattern_params
@@ -163,6 +205,26 @@ filter_
163
205
  end: $4.end
164
206
  };
165
207
  }
208
+ | at name lb pattern_args rb
209
+ {
210
+ $$ = {
211
+ type: "pattern_apply",
212
+ pattern: "@" + $2.value,
213
+ args: $4,
214
+ start: $1.start,
215
+ end: $5.end
216
+ };
217
+ }
218
+ | at name
219
+ {
220
+ $$ = {
221
+ type: "pattern_apply",
222
+ pattern: "@" + $2.value,
223
+ args: [],
224
+ start: $1.start,
225
+ end: $2.end
226
+ };
227
+ }
166
228
  ;
167
229
 
168
230
  pattern_args