@fraczak/k 8.2.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.
@@ -0,0 +1,350 @@
1
+ // canonical-pattern.mjs
2
+ // Canonical representation, hash resolution, and export helpers.
3
+
4
+ import { annotate } from "./index.mjs";
5
+ import { patternGraphToCanonical, prettyFilter } from "./pretty.mjs";
6
+ import { patternToPropertyList } from "./codecs/runtime/pattern-json.mjs";
7
+ import { exportPatternGraph } from "./codecs/runtime/codec.mjs";
8
+ import { closedPatternToCodeHash } from "./repl-codecs.mjs";
9
+ import { expandFilter } from "./named-patterns.mjs";
10
+
11
+ function collectParamPaths(filter) {
12
+ const map = {};
13
+ function walk(node, path) {
14
+ if (!node || typeof node !== "object") return;
15
+ if (node.type === "name" && typeof node.name === "string") {
16
+ const m = node.name.match(/^__PARAM_(\d+)__$/);
17
+ if (m) {
18
+ const idx = Number(m[1]);
19
+ if (!map[idx]) map[idx] = [];
20
+ map[idx].push(path);
21
+ }
22
+ }
23
+ if (node.fields) {
24
+ for (const k of Object.keys(node.fields).sort()) {
25
+ walk(node.fields[k], [...path, k]);
26
+ }
27
+ }
28
+ }
29
+ walk(filter, []);
30
+ return map;
31
+ }
32
+
33
+ function findVarAtPath(filter, path) {
34
+ let curr = filter;
35
+ for (let i = 0; i < path.length; i++) {
36
+ const key = path[i];
37
+ if (!curr?.fields?.[key]) return null;
38
+ curr = curr.fields[key];
39
+ }
40
+ return curr?.name || (curr?.type === "name" ? curr.name : null);
41
+ }
42
+
43
+ function collectCanonicalVarPaths(canonicalFilter) {
44
+ const paths = {};
45
+ function walk(node, path) {
46
+ if (!node || typeof node !== "object") return;
47
+ const name =
48
+ node.name || (node.type === "name" ? node.name : null);
49
+ if (name && /^X\d+$/.test(name) && !paths[name]) {
50
+ paths[name] = path;
51
+ }
52
+ if (node.fields) {
53
+ for (const k of Object.keys(node.fields).sort()) {
54
+ walk(node.fields[k], [...path, k]);
55
+ }
56
+ }
57
+ }
58
+ walk(canonicalFilter, []);
59
+ return paths;
60
+ }
61
+
62
+ function toAstFilter(node) {
63
+ if (!node || typeof node !== "object") return node;
64
+ 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;
72
+ }
73
+ if (res.fields) {
74
+ res.fields = {};
75
+ for (const [k, v] of Object.entries(node.fields)) {
76
+ res.fields[k] = toAstFilter(v);
77
+ }
78
+ }
79
+ return res;
80
+ }
81
+
82
+ export function resolvePatternCanonicalInfo(name, pat, options = {}) {
83
+ if (!pat) return { hash: null, def: null, params: null };
84
+ if (
85
+ pat._canonical &&
86
+ pat._canonicalDef &&
87
+ pat._canonicalParams &&
88
+ pat._aliasArgs
89
+ ) {
90
+ return {
91
+ hash: pat._canonical,
92
+ def: pat._canonicalDef,
93
+ params: pat._canonicalParams,
94
+ aliasArgs: pat._aliasArgs,
95
+ canonicalParams: pat._graphParams || [],
96
+ canonicalFilterAst: pat._canonicalFilterAst || null
97
+ };
98
+ }
99
+ if (typeof name === "string" && name.startsWith("@")) {
100
+ pat._canonical = name;
101
+ }
102
+ const formalParams = pat.params || [];
103
+ const formalCount = formalParams.length;
104
+ const allPatterns = { ...(options.patterns || {}) };
105
+ if (name && pat) allPatterns[name] = pat;
106
+
107
+ let pathMap = {};
108
+ if (formalCount > 0) {
109
+ try {
110
+ const markerArgs = formalParams.map((_, i) => ({
111
+ type: "name",
112
+ name: `__PARAM_${i}__`
113
+ }));
114
+ const expanded = expandFilter(
115
+ { type: "pattern_apply", pattern: name, args: markerArgs },
116
+ allPatterns
117
+ );
118
+ pathMap = collectParamPaths(expanded);
119
+ } catch {
120
+ pathMap = {};
121
+ }
122
+ }
123
+
124
+ const dummyParams = formalParams.map((_, i) => `P${i}`);
125
+ const source = `? ${name}[${dummyParams.join(", ")}]`;
126
+ try {
127
+ const annotated = annotate(source, {
128
+ libraries: options.libraries || [],
129
+ patterns: allPatterns
130
+ });
131
+ const mainRel = annotated.rels.__main__;
132
+ let canonicalFilter = null;
133
+ let graphParams = null;
134
+ if (
135
+ mainRel?.typePatternGraph &&
136
+ mainRel?.def?.patterns?.[0] != null
137
+ ) {
138
+ const rootId = mainRel.typePatternGraph.find(
139
+ mainRel.def.patterns[0]
140
+ );
141
+ const paramLimit = null;
142
+ const res = patternGraphToCanonical(
143
+ mainRel.typePatternGraph,
144
+ rootId,
145
+ paramLimit
146
+ );
147
+ canonicalFilter = res.filter;
148
+ graphParams = res.canonicalParams;
149
+
150
+ const propList = patternToPropertyList(
151
+ exportPatternGraph(mainRel.typePatternGraph, rootId)
152
+ );
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
+ }
170
+ }
171
+
172
+ if (canonicalFilter) {
173
+ pat._canonicalDef = prettyFilter(canonicalFilter);
174
+ }
175
+
176
+ let expandedFilter = null;
177
+ try {
178
+ expandedFilter = expandFilter(pat.filter, allPatterns);
179
+ } catch {
180
+ expandedFilter = pat.filter;
181
+ }
182
+
183
+ const varPaths = collectCanonicalVarPaths(canonicalFilter);
184
+ const aliasArgs = (graphParams || []).map((cVar) => {
185
+ const path = varPaths[cVar];
186
+ const origVar = path
187
+ ? findVarAtPath(expandedFilter, path)
188
+ : null;
189
+ if (origVar && formalParams.includes(origVar)) {
190
+ return origVar;
191
+ }
192
+ return "(...)";
193
+ });
194
+
195
+ const selectedParams = formalParams.map((_, i) => {
196
+ const paths = pathMap[i] || [];
197
+ for (const p of paths) {
198
+ const v = findVarAtPath(canonicalFilter, p);
199
+ if (v) return v;
200
+ }
201
+ return graphParams?.[i] || `X${i}`;
202
+ });
203
+
204
+ pat._canonicalParams =
205
+ formalCount > 0 ? selectedParams : [];
206
+ pat._graphParams = graphParams || [];
207
+ pat._aliasArgs = aliasArgs;
208
+ pat._canonicalFilterAst = toAstFilter(canonicalFilter);
209
+
210
+ const relHash = annotated.relAlias?.__main__ || null;
211
+ if (relHash) {
212
+ pat._canonical = relHash;
213
+ return {
214
+ hash: relHash,
215
+ def: pat._canonicalDef || null,
216
+ params: pat._canonicalParams,
217
+ aliasArgs: pat._aliasArgs,
218
+ canonicalParams: pat._graphParams,
219
+ canonicalFilterAst: pat._canonicalFilterAst
220
+ };
221
+ }
222
+ } catch {
223
+ return {
224
+ hash: pat._canonical || null,
225
+ def: pat._canonicalDef || null,
226
+ params: pat._canonicalParams || null
227
+ };
228
+ }
229
+ return {
230
+ hash: pat._canonical || null,
231
+ def: pat._canonicalDef || null,
232
+ params: pat._canonicalParams || null
233
+ };
234
+ }
235
+
236
+ export function canonicalPatternHash(name, pat, options = {}) {
237
+ return resolvePatternCanonicalInfo(name, pat, options).hash;
238
+ }
239
+
240
+ export function buildExportPreamble(exports = [], libraries = []) {
241
+ if (exports.length === 0) return "";
242
+ const relMap = {};
243
+ const patMap = {};
244
+ for (const lib of libraries) {
245
+ for (const [name, hash] of Object.entries(lib.relAlias || {})) {
246
+ if (name !== "__main__") relMap[name] = { hash };
247
+ }
248
+ for (const [name, hash] of Object.entries(lib.patternAlias || {})) {
249
+ patMap[name] = {
250
+ hash,
251
+ params:
252
+ lib.patterns?.[name]?.params ||
253
+ lib.patterns?.[name]?._canonicalParams ||
254
+ lib.patterns?.[hash]?.params ||
255
+ [],
256
+ aliasArgs:
257
+ lib.patterns?.[name]?._aliasArgs ||
258
+ lib.meta?.[hash]?.origins?.find((o) => o.name === name)
259
+ ?.aliasArgs ||
260
+ lib.patterns?.[name]?.params ||
261
+ []
262
+ };
263
+ }
264
+ for (const [name, pat] of Object.entries(lib.patterns || {})) {
265
+ if (!patMap[name]) {
266
+ patMap[name] = {
267
+ hash: pat._canonical || lib.patternAlias?.[name] || name,
268
+ params: pat.params || [],
269
+ aliasArgs: pat._aliasArgs || pat.params || []
270
+ };
271
+ }
272
+ }
273
+ for (const [hash, entry] of Object.entries(lib.meta || {})) {
274
+ for (const origin of entry?.origins || []) {
275
+ const type = origin?.type || entry?.type;
276
+ if (type === "rel") {
277
+ if (origin?.name && origin.name !== "__main__") {
278
+ relMap[origin.name] = { hash };
279
+ }
280
+ } else if (type === "pattern") {
281
+ if (origin?.name) {
282
+ patMap[origin.name] = {
283
+ hash,
284
+ params: origin.params || entry.params || [],
285
+ aliasArgs:
286
+ origin.aliasArgs ||
287
+ entry.aliasArgs ||
288
+ origin.params ||
289
+ []
290
+ };
291
+ }
292
+ }
293
+ }
294
+ }
295
+ }
296
+
297
+ const lines = [];
298
+ for (const spec of exports) {
299
+ const [rawLib, rawLocal] = spec.includes(":")
300
+ ? spec.split(":", 2)
301
+ : [spec, spec];
302
+ const isExplicitPattern =
303
+ rawLib.includes("[") || rawLocal.includes("[");
304
+ const libName = rawLib.replace(/\[.*\]$/, "").trim();
305
+ const localName = rawLocal.replace(/\[.*\]$/, "").trim();
306
+
307
+ let emitted = false;
308
+ if (!isExplicitPattern && relMap[libName]) {
309
+ const target = relMap[libName];
310
+ const body = target.hash.startsWith("@")
311
+ ? target.hash.slice(1)
312
+ : target.hash;
313
+ lines.push(`${localName} = @${body};`);
314
+ emitted = true;
315
+ }
316
+ if (patMap[libName]) {
317
+ if (isExplicitPattern || !emitted || relMap[libName]) {
318
+ const target = patMap[libName];
319
+ const body = target.hash.startsWith("@")
320
+ ? target.hash.slice(1)
321
+ : target.hash;
322
+ const paramStr =
323
+ target.params && target.params.length > 0
324
+ ? `[${target.params.join(", ")}]`
325
+ : "[]";
326
+ const args = target.aliasArgs || target.params;
327
+ const argStr =
328
+ args && args.length > 0
329
+ ? `[${args.join(", ")}]`
330
+ : paramStr;
331
+ lines.push(
332
+ `${localName}${paramStr} = @${body}${argStr};`
333
+ );
334
+ emitted = true;
335
+ }
336
+ }
337
+ if (!emitted) {
338
+ throw new Error(
339
+ `--export: '${rawLib}' not found in loaded libraries`
340
+ );
341
+ }
342
+ }
343
+ return lines.join("\n") + "\n";
344
+ }
345
+
346
+ export default {
347
+ resolvePatternCanonicalInfo,
348
+ canonicalPatternHash,
349
+ buildExportPreamble
350
+ };
package/k.mjs CHANGED
@@ -12,7 +12,8 @@ import {
12
12
  compileLibrary,
13
13
  decodeObject,
14
14
  objectToFunction,
15
- loadLibrary
15
+ loadLibrary,
16
+ buildExportPreamble
16
17
  } from "./object.mjs";
17
18
 
18
19
  let kScript, inputStream;
@@ -106,42 +107,24 @@ function compileFile(filePath, libraries, preamble) {
106
107
  }
107
108
  }
108
109
 
109
- function buildExportPreamble() {
110
- if (exports.length === 0) return "";
111
- const aliasMap = {};
112
- for (const lib of libraries) {
113
- for (const [name, hash] of Object.entries(lib.relAlias || {})) {
114
- if (name !== "__main__") aliasMap[name] = hash;
115
- }
116
- for (const [hash, entry] of Object.entries(lib.meta || {})) {
117
- if (entry?.type !== "rel") continue;
118
- for (const origin of entry?.origins || []) {
119
- if (origin?.name && origin.name !== "__main__") aliasMap[origin.name] = hash;
120
- }
121
- }
122
- }
123
- const lines = [];
124
- for (const spec of exports) {
125
- const [libName, localName] = spec.includes(":") ? spec.split(":", 2) : [spec, spec];
126
- const hash = aliasMap[libName];
127
- if (!hash) throw new Error(`--export: '${libName}' not found in loaded libraries`);
128
- const body = hash.startsWith("@") ? hash.slice(1) : hash;
129
- lines.push(`${localName} = @${body};`);
130
- }
131
- return lines.join("\n") + "\n";
132
- }
110
+ const preamble = buildExportPreamble(exports, libraries);
133
111
 
134
112
  let kScriptStr = (function (arg) {
135
113
  if (arg == null) {
136
114
  throw new Error("Missing script argument");
137
115
  }
138
116
  if (arg === "-k") {
139
- throw new Error("-k is no longer supported; pass the source/object file path directly");
117
+ throw new Error(
118
+ "-k is no longer supported; " +
119
+ "pass the source/object file path directly"
120
+ );
140
121
  }
141
- if (isFile(arg)) return compileFile(arg, libraries, buildExportPreamble());
142
- return buildExportPreamble() + arg;
122
+ if (isFile(arg)) return compileFile(arg, libraries, preamble);
123
+ return preamble + arg;
143
124
  })(args.shift());
144
- let kScript = typeof kScriptStr === "function" ? kScriptStr : k.compile(kScriptStr, { libraries });
125
+ let kScript = typeof kScriptStr === "function"
126
+ ? kScriptStr
127
+ : k.compile(kScriptStr, { libraries });
145
128
  inputStream = (function (arg) {
146
129
  if (arg == null) {
147
130
  return stdin;
package/kvm.mjs CHANGED
@@ -13,7 +13,8 @@ import {
13
13
  compileLibrary,
14
14
  compileObjectBuffer,
15
15
  decodeObject,
16
- loadLibrary
16
+ loadLibrary,
17
+ buildExportPreamble
17
18
  } from "./object.mjs";
18
19
  import codes from "./codes.mjs";
19
20
  import { isMainEntrypoint } from "./codecs/runtime/cli-entry.mjs";
@@ -41,33 +42,6 @@ function isFile(filePath) {
41
42
  }
42
43
  }
43
44
 
44
- function buildExportPreamble(exports, libraries) {
45
- if (exports.length === 0) return "";
46
- const aliasMap = {};
47
- for (const lib of libraries) {
48
- for (const [name, hash] of Object.entries(lib.relAlias || {})) {
49
- if (name !== "__main__") aliasMap[name] = hash;
50
- }
51
- for (const [hash, entry] of Object.entries(lib.meta || {})) {
52
- if (entry?.type !== "rel") continue;
53
- for (const origin of entry?.origins || []) {
54
- if (origin?.name && origin.name !== "__main__") {
55
- aliasMap[origin.name] = hash;
56
- }
57
- }
58
- }
59
- }
60
- const lines = [];
61
- for (const spec of exports) {
62
- const [libName, localName] = spec.includes(":") ? spec.split(":", 2) : [spec, spec];
63
- const hash = aliasMap[libName];
64
- if (!hash) throw new Error(`--export: '${libName}' not found in loaded libraries`);
65
- const body = hash.startsWith("@") ? hash.slice(1) : hash;
66
- lines.push(`${localName} = @${body};`);
67
- }
68
- return lines.join("\n") + "\n";
69
- }
70
-
71
45
  function kirFindCode(kir) {
72
46
  return (hash) => kir.codes?.[hash] || codes.find(hash);
73
47
  }
@@ -26,13 +26,20 @@ export function expandFilter(
26
26
 
27
27
  if (filter.type === "pattern_apply") {
28
28
  const patternName = filter.pattern;
29
- const template = patterns[patternName];
29
+ let template = patterns[patternName];
30
+ if (!template && patternName.startsWith("@")) {
31
+ template = patterns[patternName.slice(1)];
32
+ }
33
+ if (!template && !patternName.startsWith("@")) {
34
+ template = patterns["@" + patternName];
35
+ }
30
36
  if (!template) {
31
37
  const pos = filter.start
32
38
  ? ` (lines ${filter.start.line}:${filter.start.column})`
33
39
  : "";
40
+ const suffix = patternName.startsWith("@") ? "" : "[]";
34
41
  throw new Error(
35
- `Unknown pattern template '${patternName}[]'${pos}`
42
+ `Unknown pattern template '${patternName}${suffix}'${pos}`
36
43
  );
37
44
  }
38
45
 
@@ -92,12 +99,33 @@ export function expandFilter(
92
99
  const nextStack = new Set(stack);
93
100
  nextStack.add(patternName);
94
101
 
102
+ const paramWildcardVars = {};
103
+ for (let i = 0; i < expandedArgs.length; i++) {
104
+ const arg = expandedArgs[i];
105
+ if (
106
+ arg &&
107
+ arg.type === null &&
108
+ arg.open === true &&
109
+ (!arg.fields || Object.keys(arg.fields).length === 0) &&
110
+ !arg.name
111
+ ) {
112
+ paramWildcardVars[i] = `_wildcard_np${++uniqueIdRef.val}`;
113
+ }
114
+ }
115
+
95
116
  function substitute(node) {
96
117
  if (!node || typeof node !== "object") return node;
97
118
 
98
119
  if (node.type === "name") {
99
120
  const paramIdx = template.params.indexOf(node.name);
100
121
  if (paramIdx !== -1) {
122
+ if (paramWildcardVars[paramIdx]) {
123
+ return {
124
+ type: "name",
125
+ name: paramWildcardVars[paramIdx],
126
+ open: true
127
+ };
128
+ }
101
129
  const clonedArg = cloneFilter(expandedArgs[paramIdx]);
102
130
  if (node.name && node.name !== template.params[paramIdx]) {
103
131
  clonedArg.name = varSubst[node.name] || node.name;
@@ -246,6 +274,11 @@ export function expandPatternsInRels(rels, patterns = {}, options = {}) {
246
274
  allPatterns[name] = pat;
247
275
  }
248
276
  }
277
+ for (const [name, hash] of Object.entries(lib.patternAlias || {})) {
278
+ if (libPatterns[name] && !(hash in allPatterns)) {
279
+ allPatterns[hash] = libPatterns[name];
280
+ }
281
+ }
249
282
  }
250
283
  }
251
284