@fraczak/k 8.3.0 → 8.4.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.
@@ -35,38 +35,7 @@ export function loadLibraryFromPath(libPath) {
35
35
  return loadLibrary(decodeObject(fs.readFileSync(libPath)));
36
36
  }
37
37
  if (ext === ".k") {
38
- let depLibs = [];
39
- const baseName = path.basename(libPath);
40
- if (baseName === "poly.k") {
41
- const dir = path.dirname(libPath);
42
- const arithPath = path.join(dir, "arithmetics.k");
43
- if (fs.existsSync(arithPath)) {
44
- const arithLib = loadLibrary(
45
- compileLibrary(fs.readFileSync(arithPath, "utf8"), {
46
- source: arithPath
47
- })
48
- );
49
- depLibs.push(arithLib);
50
- }
51
- }
52
38
  const rawSource = fs.readFileSync(libPath, "utf8");
53
- if (depLibs.length > 0) {
54
- const neededExports = [
55
- "0", "int", "inc", "dec", "nat", "zero_int?", "neg?", "GT"
56
- ];
57
- const preamble = buildExportPreamble(neededExports, depLibs);
58
- const compiled = compileLibrary(preamble + rawSource, {
59
- source: libPath,
60
- libraries: depLibs
61
- });
62
- const mergedLib = loadLibrary(compiled);
63
- for (const dep of depLibs) {
64
- for (const [k, v] of Object.entries(dep.relAlias || {})) {
65
- if (!mergedLib.relAlias[k]) mergedLib.relAlias[k] = v;
66
- }
67
- }
68
- return mergedLib;
69
- }
70
39
  return loadLibrary(compileLibrary(rawSource, { source: libPath }));
71
40
  }
72
41
  throw new Error(`Unsupported library extension: ${ext}`);
@@ -8,6 +8,77 @@ import { exportPatternGraph } from "./codecs/runtime/codec.mjs";
8
8
  import { closedPatternToCodeHash } from "./repl-codecs.mjs";
9
9
  import { expandFilter } from "./named-patterns.mjs";
10
10
 
11
+ function collectFilterKnots(filter) {
12
+ const knots = new Set();
13
+ function walk(node) {
14
+ if (!node || typeof node !== "object") return;
15
+ if (node.name && node.type !== "name") {
16
+ knots.add(node.name);
17
+ }
18
+ if (node.fields) {
19
+ for (const child of Object.values(node.fields)) {
20
+ walk(child);
21
+ }
22
+ }
23
+ if (node.args) {
24
+ for (const arg of node.args) {
25
+ walk(arg);
26
+ }
27
+ }
28
+ }
29
+ walk(filter);
30
+ return knots;
31
+ }
32
+
33
+ function skeletonizeFilter(filter, knots) {
34
+ let leafIdx = 0;
35
+ function walk(node) {
36
+ if (!node || typeof node !== "object") return node;
37
+ if (node.type === "name" && knots.has(node.name)) {
38
+ return { ...node };
39
+ }
40
+ if (node.name && node.type !== "name") {
41
+ const knotName = node.name;
42
+ if (node.fields) {
43
+ const newFields = {};
44
+ for (const [k, v] of Object.entries(node.fields)) {
45
+ newFields[k] = walk(v);
46
+ }
47
+ return { ...node, name: knotName, fields: newFields };
48
+ }
49
+ return { ...node };
50
+ }
51
+ if (node.type === "product" || node.type === "union") {
52
+ const newFields = {};
53
+ for (const [k, v] of Object.entries(node.fields || {})) {
54
+ newFields[k] = walk(v);
55
+ }
56
+ return { ...node, fields: newFields };
57
+ }
58
+ if (node.type === "code") {
59
+ return { ...node };
60
+ }
61
+ if (node.type === "pattern_apply") {
62
+ const pos = node.start
63
+ ? ` (lines ${node.start.line}:${node.start.column})`
64
+ : "";
65
+ const suffix = node.pattern?.startsWith("@") ? "" : "[]";
66
+ throw new Error(
67
+ `Unknown pattern template '${node.pattern}${suffix}'${pos}`
68
+ );
69
+ }
70
+ if (node.type === "name" || node.type === null) {
71
+ return {
72
+ type: "name",
73
+ name: `__LEAF_${leafIdx++}__`,
74
+ open: true
75
+ };
76
+ }
77
+ return node;
78
+ }
79
+ return walk(filter);
80
+ }
81
+
11
82
  function collectParamPaths(filter) {
12
83
  const map = {};
13
84
  function walk(node, path) {
@@ -59,21 +130,29 @@ function collectCanonicalVarPaths(canonicalFilter) {
59
130
  return paths;
60
131
  }
61
132
 
62
- function toAstFilter(node) {
133
+ function toAstFilter(node, canonicalParams = []) {
63
134
  if (!node || typeof node !== "object") return node;
64
135
  const res = { ...node };
65
- if (
66
- res.name &&
67
- /^X\d+$/.test(res.name) &&
68
- (!res.fields || Object.keys(res.fields).length === 0)
69
- ) {
70
- res.type = "name";
71
- res.open = true;
136
+ if (res.type === null) {
137
+ return {
138
+ type: "name",
139
+ name: res.name,
140
+ open: true
141
+ };
142
+ }
143
+ if (res.type === "name") {
144
+ return {
145
+ type: "name",
146
+ name: res.name,
147
+ ...(canonicalParams.includes(res.name)
148
+ ? { open: true }
149
+ : {})
150
+ };
72
151
  }
73
152
  if (res.fields) {
74
153
  res.fields = {};
75
154
  for (const [k, v] of Object.entries(node.fields)) {
76
- res.fields[k] = toAstFilter(v);
155
+ res.fields[k] = toAstFilter(v, canonicalParams);
77
156
  }
78
157
  }
79
158
  return res;
@@ -96,12 +175,24 @@ export function resolvePatternCanonicalInfo(name, pat, options = {}) {
96
175
  canonicalFilterAst: pat._canonicalFilterAst || null
97
176
  };
98
177
  }
99
- if (typeof name === "string" && name.startsWith("@")) {
178
+ const isDirectCanonical =
179
+ typeof name === "string" && name.startsWith("@");
180
+ if (isDirectCanonical) {
100
181
  pat._canonical = name;
101
182
  }
102
183
  const formalParams = pat.params || [];
103
184
  const formalCount = formalParams.length;
104
185
  const allPatterns = { ...(options.patterns || {}) };
186
+ if (options.libraries) {
187
+ for (const lib of options.libraries) {
188
+ const lp =
189
+ lib.patterns ||
190
+ lib.defs?.patterns ||
191
+ lib.sourceDefs?.patterns ||
192
+ {};
193
+ Object.assign(allPatterns, lp);
194
+ }
195
+ }
105
196
  if (name && pat) allPatterns[name] = pat;
106
197
 
107
198
  let pathMap = {};
@@ -121,8 +212,21 @@ export function resolvePatternCanonicalInfo(name, pat, options = {}) {
121
212
  }
122
213
  }
123
214
 
124
- const dummyParams = formalParams.map((_, i) => `P${i}`);
125
- const source = `? ${name}[${dummyParams.join(", ")}]`;
215
+ if (!pat.filter) {
216
+ return {
217
+ hash: pat._canonical || null,
218
+ def: null,
219
+ params: formalParams
220
+ };
221
+ }
222
+
223
+ const expandedFilter = expandFilter(pat.filter, allPatterns);
224
+
225
+ const knots = collectFilterKnots(expandedFilter);
226
+ const skeletonFilter = isDirectCanonical
227
+ ? expandedFilter
228
+ : skeletonizeFilter(expandedFilter, knots);
229
+ const source = `? ${prettyFilter(skeletonFilter)}`;
126
230
  try {
127
231
  const annotated = annotate(source, {
128
232
  libraries: options.libraries || [],
@@ -131,6 +235,7 @@ export function resolvePatternCanonicalInfo(name, pat, options = {}) {
131
235
  const mainRel = annotated.rels.__main__;
132
236
  let canonicalFilter = null;
133
237
  let graphParams = null;
238
+ let codeHash = null;
134
239
  if (
135
240
  mainRel?.typePatternGraph &&
136
241
  mainRel?.def?.patterns?.[0] != null
@@ -138,11 +243,10 @@ export function resolvePatternCanonicalInfo(name, pat, options = {}) {
138
243
  const rootId = mainRel.typePatternGraph.find(
139
244
  mainRel.def.patterns[0]
140
245
  );
141
- const paramLimit = null;
142
246
  const res = patternGraphToCanonical(
143
247
  mainRel.typePatternGraph,
144
248
  rootId,
145
- paramLimit
249
+ null
146
250
  );
147
251
  canonicalFilter = res.filter;
148
252
  graphParams = res.canonicalParams;
@@ -150,45 +254,26 @@ export function resolvePatternCanonicalInfo(name, pat, options = {}) {
150
254
  const propList = patternToPropertyList(
151
255
  exportPatternGraph(mainRel.typePatternGraph, rootId)
152
256
  );
153
- const codeHash = closedPatternToCodeHash(propList);
154
- if (codeHash) {
155
- pat._canonical = codeHash;
156
- pat._canonicalDef = prettyFilter(canonicalFilter);
157
- pat._canonicalParams = graphParams;
158
- pat._aliasArgs = [];
159
- pat._graphParams = graphParams;
160
- pat._canonicalFilterAst = toAstFilter(canonicalFilter);
161
- return {
162
- hash: codeHash,
163
- def: pat._canonicalDef,
164
- params: pat._canonicalParams,
165
- aliasArgs: pat._aliasArgs,
166
- canonicalParams: graphParams,
167
- canonicalFilterAst: pat._canonicalFilterAst
168
- };
169
- }
257
+ codeHash = closedPatternToCodeHash(propList);
170
258
  }
171
259
 
172
260
  if (canonicalFilter) {
173
261
  pat._canonicalDef = prettyFilter(canonicalFilter);
174
262
  }
175
263
 
176
- let expandedFilter = null;
177
- try {
178
- expandedFilter = expandFilter(pat.filter, allPatterns);
179
- } catch {
180
- expandedFilter = pat.filter;
181
- }
182
-
183
264
  const varPaths = collectCanonicalVarPaths(canonicalFilter);
184
- const aliasArgs = (graphParams || []).map((cVar) => {
265
+ const tokens = (graphParams || []).map((cVar) => {
185
266
  const path = varPaths[cVar];
186
- const origVar = path
187
- ? findVarAtPath(expandedFilter, path)
188
- : null;
189
- if (origVar && formalParams.includes(origVar)) {
190
- return origVar;
191
- }
267
+ return path ? findVarAtPath(expandedFilter, path) : null;
268
+ });
269
+ const tokenCounts = {};
270
+ for (const t of tokens) {
271
+ if (t) tokenCounts[t] = (tokenCounts[t] || 0) + 1;
272
+ }
273
+ const aliasArgs = tokens.map((t) => {
274
+ if (!t) return "(...)";
275
+ if (formalParams.includes(t)) return t;
276
+ if (tokenCounts[t] > 1) return t;
192
277
  return "(...)";
193
278
  });
194
279
 
@@ -201,36 +286,38 @@ export function resolvePatternCanonicalInfo(name, pat, options = {}) {
201
286
  return graphParams?.[i] || `X${i}`;
202
287
  });
203
288
 
289
+ const relHash = annotated.relAlias?.__main__ || null;
290
+ const finalHash =
291
+ codeHash || relHash || pat._canonical || null;
292
+
293
+ pat._canonical = finalHash;
204
294
  pat._canonicalParams =
205
295
  formalCount > 0 ? selectedParams : [];
206
296
  pat._graphParams = graphParams || [];
207
297
  pat._aliasArgs = aliasArgs;
208
- pat._canonicalFilterAst = toAstFilter(canonicalFilter);
298
+ pat._canonicalFilterAst = toAstFilter(
299
+ canonicalFilter,
300
+ graphParams || []
301
+ );
209
302
 
210
- const relHash = annotated.relAlias?.__main__ || null;
211
- if (relHash) {
212
- pat._canonical = relHash;
303
+ return {
304
+ hash: pat._canonical,
305
+ def: pat._canonicalDef || null,
306
+ params: pat._canonicalParams,
307
+ aliasArgs: pat._aliasArgs,
308
+ canonicalParams: pat._graphParams,
309
+ canonicalFilterAst: pat._canonicalFilterAst
310
+ };
311
+ } catch (err) {
312
+ if (isDirectCanonical) {
213
313
  return {
214
- hash: relHash,
314
+ hash: pat._canonical || null,
215
315
  def: pat._canonicalDef || null,
216
- params: pat._canonicalParams,
217
- aliasArgs: pat._aliasArgs,
218
- canonicalParams: pat._graphParams,
219
- canonicalFilterAst: pat._canonicalFilterAst
316
+ params: pat._canonicalParams || null
220
317
  };
221
318
  }
222
- } catch {
223
- return {
224
- hash: pat._canonical || null,
225
- def: pat._canonicalDef || null,
226
- params: pat._canonicalParams || null
227
- };
319
+ throw err;
228
320
  }
229
- return {
230
- hash: pat._canonical || null,
231
- def: pat._canonicalDef || null,
232
- params: pat._canonicalParams || null
233
- };
234
321
  }
235
322
 
236
323
  export function canonicalPatternHash(name, pat, options = {}) {
package/index.mjs CHANGED
@@ -2,7 +2,10 @@ import { parse } from "./parser.mjs";
2
2
  import { fromObject, isValue } from "./Value.mjs";
3
3
  import { parseValue } from "./valueIO.mjs";
4
4
  import { compileTypes } from "./compiler.mjs";
5
- import { expandPatternsInRels } from "./named-patterns.mjs";
5
+ import {
6
+ expandPatternsInRels,
7
+ validatePatternDefinitions
8
+ } from "./named-patterns.mjs";
6
9
  import run from "./run.mjs";
7
10
  import codes from "./codes.mjs";
8
11
 
@@ -38,6 +41,7 @@ function annotate(script, options = {}) {
38
41
  const representatives = codes.register(defs.codes);
39
42
  const rels = {...defs.rels, "__main__": {def: exp}};
40
43
 
44
+ validatePatternDefinitions(defs.patterns || {}, options);
41
45
  expandPatternsInRels(rels, defs.patterns || {}, options);
42
46
 
43
47
  // Inject library relations into the rels table so @hash refs resolve
@@ -293,8 +293,44 @@ export function expandPatternsInRels(rels, patterns = {}, options = {}) {
293
293
  return rels;
294
294
  }
295
295
 
296
+ export function validatePatternDefinitions(
297
+ patterns = {},
298
+ options = {}
299
+ ) {
300
+ const allPatterns = { ...(options.patterns || {}), ...patterns };
301
+ if (options.libraries) {
302
+ for (const lib of options.libraries) {
303
+ const libPatterns =
304
+ lib.patterns ||
305
+ lib.defs?.patterns ||
306
+ lib.sourceDefs?.patterns ||
307
+ {};
308
+ for (const [name, pat] of Object.entries(libPatterns)) {
309
+ if (!(name in allPatterns)) {
310
+ allPatterns[name] = pat;
311
+ }
312
+ }
313
+ for (const [name, hash] of Object.entries(
314
+ lib.patternAlias || {}
315
+ )) {
316
+ if (libPatterns[name] && !(hash in allPatterns)) {
317
+ allPatterns[hash] = libPatterns[name];
318
+ }
319
+ }
320
+ }
321
+ }
322
+
323
+ for (const [name, pat] of Object.entries(patterns)) {
324
+ if (name.startsWith("@")) continue;
325
+ if (pat?.filter) {
326
+ expandFilter(pat.filter, allPatterns, new Set([name]));
327
+ }
328
+ }
329
+ }
330
+
296
331
  export default {
297
332
  expandFilter,
298
333
  expandExp,
299
334
  expandPatternsInRels,
335
+ validatePatternDefinitions,
300
336
  };
package/object.mjs CHANGED
@@ -336,7 +336,7 @@ function patternOrigin(source, name, compiledAt, pat, info) {
336
336
  };
337
337
  }
338
338
 
339
- function buildMeta(annotated, source) {
339
+ function buildMeta(annotated, source, options = {}) {
340
340
  const meta = {};
341
341
  const representatives = annotated.representatives || {};
342
342
  const relAlias = annotated.relAlias || {};
@@ -361,11 +361,27 @@ function buildMeta(annotated, source) {
361
361
  }
362
362
 
363
363
  const patterns = annotated.sourceDefs?.patterns || {};
364
+ const allPatterns = {};
365
+ if (options.libraries) {
366
+ for (const lib of options.libraries) {
367
+ const lp =
368
+ lib.patterns ||
369
+ lib.defs?.patterns ||
370
+ lib.sourceDefs?.patterns ||
371
+ {};
372
+ Object.assign(allPatterns, lp);
373
+ }
374
+ }
375
+ if (options.patterns) {
376
+ Object.assign(allPatterns, options.patterns);
377
+ }
378
+ Object.assign(allPatterns, patterns);
379
+
364
380
  for (const [name, pat] of Object.entries(patterns)) {
365
381
  if (!isSourceName(name)) continue;
366
382
  const info = resolvePatternCanonicalInfo(name, pat, {
367
- patterns,
368
- libraries: annotated.libraries || []
383
+ patterns: allPatterns,
384
+ libraries: options.libraries || []
369
385
  });
370
386
  if (info.hash) {
371
387
  addOrigin(
@@ -464,7 +480,7 @@ function compileObject(script, options = {}) {
464
480
  const serialized = serializeAnnotated(annotated);
465
481
  const meta = mergeMetaEntries(
466
482
  importedLibraryMeta(options.libraries),
467
- buildMeta(annotated, options.source || null)
483
+ buildMeta(annotated, options.source || null, options)
468
484
  );
469
485
 
470
486
  // Prune to reachable from main
@@ -521,7 +537,7 @@ function compileLibrary(script, options = {}) {
521
537
  const serialized = serializeAnnotated(annotated);
522
538
  const meta = mergeMetaEntries(
523
539
  importedLibraryMeta(options.libraries),
524
- buildMeta(annotated, options.source || null)
540
+ buildMeta(annotated, options.source || null, options)
525
541
  );
526
542
  const relAlias = serialized.relAlias || {};
527
543
 
@@ -571,7 +587,13 @@ function compileLibrary(script, options = {}) {
571
587
  info.params ||
572
588
  pat.params ||
573
589
  [],
574
- filter: info.canonicalFilterAst || pat.filter
590
+ filter: info.canonicalFilterAst || pat.filter,
591
+ _canonical: info.hash,
592
+ _canonicalDef: info.def,
593
+ _canonicalParams: info.canonicalParams,
594
+ _graphParams: info.canonicalParams,
595
+ _aliasArgs: info.aliasArgs,
596
+ _canonicalFilterAst: info.canonicalFilterAst
575
597
  };
576
598
  }
577
599
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fraczak/k",
3
- "version": "8.3.0",
3
+ "version": "8.4.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"
package/repl.mjs CHANGED
@@ -1153,15 +1153,6 @@ function loadSourceOrKlib(state, targetPath, options = {}) {
1153
1153
  const normKey = normalizeFilePath(targetPath);
1154
1154
  if (!state.loadedFiles) state.loadedFiles = new Set();
1155
1155
 
1156
- // If loading poly.k, auto-load arithmetics.k first if not already loaded
1157
- if (normKey === "Examples/poly.k" || normKey.endsWith("/poly.k") || normKey === "poly.k") {
1158
- const arithKey = "arithmetics.k";
1159
- const alreadyHasArith = Array.from(state.loadedFiles).some(f => path.basename(f) === "arithmetics.k");
1160
- if (!alreadyHasArith) {
1161
- loadSourceOrKlib(state, arithKey, { loadAliases });
1162
- }
1163
- }
1164
-
1165
1156
  const loadPath = resolveKFilePath(targetPath);
1166
1157
  if (loadPath.endsWith(".klib")) {
1167
1158
  const lib = loadLibrary(decodeLibrary(fs.readFileSync(loadPath)));
@@ -1184,45 +1175,13 @@ function loadSourceOrKlib(state, targetPath, options = {}) {
1184
1175
  lib,
1185
1176
  compileOptions
1186
1177
  );
1187
- const { patternNames } = userDefinedNames(source);
1188
- let parsedSource;
1189
- try {
1190
- parsedSource = parse(source);
1191
- } catch {
1192
- parsedSource = parse(`${source}\n()`);
1193
- }
1194
- const filePatterns = {};
1195
- for (const name of patternNames) {
1196
- const pat = parsedSource.defs?.patterns?.[name];
1197
- if (pat) {
1198
- filePatterns[name] = pat;
1199
- if (patternAlias[name]) {
1200
- const info = resolvePatternCanonicalInfo(state, name, pat);
1201
- filePatterns[patternAlias[name]] = {
1202
- params:
1203
- info.canonicalParams ||
1204
- info.params ||
1205
- pat.params ||
1206
- [],
1207
- filter: info.canonicalFilterAst || pat.filter,
1208
- _canonical: patternAlias[name],
1209
- _canonicalDef: info.def,
1210
- _canonicalParams: info.canonicalParams,
1211
- _graphParams: info.canonicalParams,
1212
- _aliasArgs: info.canonicalParams,
1213
- _canonicalFilterAst: info.canonicalFilterAst
1214
- };
1215
- }
1216
- }
1217
- }
1218
1178
  mergeLibrary(
1219
1179
  state,
1220
1180
  {
1221
1181
  ...lib,
1222
1182
  relAlias,
1223
1183
  patternAlias,
1224
- meta,
1225
- patterns: filePatterns
1184
+ meta
1226
1185
  },
1227
1186
  targetPath,
1228
1187
  { loadAliases }
@@ -1298,36 +1257,10 @@ function compileSnippetArtifacts(source, state, sourceName = "<repl>") {
1298
1257
  );
1299
1258
  const annotated = annotateWithOptionalIdentity(fullSource, options);
1300
1259
  const { patternNames } = userDefinedNames(source);
1301
- let parsedSnippet;
1302
- try {
1303
- parsedSnippet = parse(source);
1304
- } catch {
1305
- parsedSnippet = parse(`${source}\n()`);
1306
- }
1307
- const patterns = { ...(state.patterns || {}) };
1308
- for (const name of patternNames) {
1309
- const pat = parsedSnippet.defs?.patterns?.[name];
1310
- if (pat) {
1311
- patterns[name] = pat;
1312
- if (patternAlias[name]) {
1313
- const info = resolvePatternCanonicalInfo(state, name, pat);
1314
- patterns[patternAlias[name]] = {
1315
- params:
1316
- info.canonicalParams ||
1317
- info.params ||
1318
- pat.params ||
1319
- [],
1320
- filter: info.canonicalFilterAst || pat.filter,
1321
- _canonical: patternAlias[name],
1322
- _canonicalDef: info.def,
1323
- _canonicalParams: info.canonicalParams,
1324
- _graphParams: info.canonicalParams,
1325
- _aliasArgs: info.canonicalParams,
1326
- _canonicalFilterAst: info.canonicalFilterAst
1327
- };
1328
- }
1329
- }
1330
- }
1260
+ const patterns = {
1261
+ ...(state.patterns || {}),
1262
+ ...(lib.patterns || {})
1263
+ };
1331
1264
  return {
1332
1265
  annotated,
1333
1266
  lib: {