@dallaylaen/ski-interpreter 2.3.2 → 2.4.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.
@@ -1,2249 +1,2116 @@
1
- var __getOwnPropNames = Object.getOwnPropertyNames;
2
- var __commonJS = (cb, mod) => function __require() {
3
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
1
+ // src/internal.ts
2
+ var Tokenizer = class {
3
+ constructor(...terms) {
4
+ const src = "$|(\\s+)|" + terms.map((s) => "(?:" + s + ")").sort((a, b) => b.length - a.length).join("|");
5
+ this.rex = new RegExp(src, "gys");
6
+ }
7
+ /**
8
+ * @desc Split the given string into tokens according to the terms specified in the constructor.
9
+ * @param {string} str
10
+ * @return {string[]}
11
+ */
12
+ split(str) {
13
+ this.rex.lastIndex = 0;
14
+ const list = [...str.matchAll(this.rex)];
15
+ const eol = list.pop();
16
+ const last = eol?.index ?? 0;
17
+ if (last !== str.length) {
18
+ throw new Error("Unknown tokens at pos " + last + "/" + str.length + " starting with " + str.substring(last));
19
+ }
20
+ return list.filter((x) => x[1] === void 0).map((x) => x[0]);
21
+ }
4
22
  };
5
-
6
- // src/internal.js
7
- var require_internal = __commonJS({
8
- "src/internal.js"(exports, module) {
9
- var Tokenizer = class {
10
- /**
11
- * @desc Create a tokenizer that splits strings into tokens according to the given terms.
12
- * The terms are interpreted as regular expressions, and are sorted by length
13
- * to ensure that longer matches are preferred over shorter ones.
14
- * @param {...string|RegExp} terms
15
- */
16
- constructor(...terms) {
17
- const src = "$|(\\s+)|" + terms.map((s) => "(?:" + s + ")").sort((a, b) => b.length - a.length).join("|");
18
- this.rex = new RegExp(src, "gys");
19
- }
20
- /**
21
- * @desc Split the given string into tokens according to the terms specified in the constructor.
22
- * @param {string} str
23
- * @return {string[]}
24
- */
25
- split(str) {
26
- this.rex.lastIndex = 0;
27
- const list = [...str.matchAll(this.rex)];
28
- const eol = list.pop();
29
- const last = eol?.index ?? 0;
30
- if (last !== str.length) {
31
- throw new Error("Unknown tokens at pos " + last + "/" + str.length + " starting with " + str.substring(last));
32
- }
33
- return list.filter((x) => x[1] === void 0).map((x) => x[0]);
34
- }
35
- };
36
- var tokRestrict = new Tokenizer("[-=+]", "[A-Z]", "\\b[a-z_][a-z_0-9]*\\b");
37
- function restrict(set, spec) {
38
- if (!spec)
39
- return set;
40
- let out = /* @__PURE__ */ new Set([...set]);
41
- const act = {
42
- "=": (sym) => {
43
- out = /* @__PURE__ */ new Set([sym]);
44
- mode = "+";
45
- },
46
- "+": (sym) => {
47
- out.add(sym);
48
- },
49
- "-": (sym) => {
50
- out.delete(sym);
51
- }
52
- };
53
- let mode = "=";
54
- for (const sym of tokRestrict.split(spec)) {
55
- if (act[sym])
56
- mode = sym;
57
- else
58
- act[mode](sym);
59
- }
60
- return out;
23
+ var tokRestrict = new Tokenizer("[-=+]", "[A-Z]", "\\b[a-z_][a-z_0-9]*\\b");
24
+ function restrict(set, spec) {
25
+ if (!spec)
26
+ return set;
27
+ let out = /* @__PURE__ */ new Set([...set]);
28
+ const act = {
29
+ "=": (sym) => {
30
+ out = /* @__PURE__ */ new Set([sym]);
31
+ mode = "+";
32
+ },
33
+ "+": (sym) => {
34
+ out.add(sym);
35
+ },
36
+ "-": (sym) => {
37
+ out.delete(sym);
61
38
  }
62
- var TraverseControl = class {
63
- /**
64
- * @desc A wrapper for values returned by fold/traverse callbacks
65
- * which instructs the traversal to alter its behavior while
66
- * retaining the value in question.
67
- *
68
- * This class is instantiated internally be `SKI.control.*` functions,
69
- * and is not intended to be used directly by client code.
70
- *
71
- * @template T
72
- * @param {T} value
73
- * @param {function(T): TraverseControl<T>} decoration
74
- */
75
- constructor(value, decoration) {
76
- this.value = value;
77
- this.decoration = decoration;
39
+ };
40
+ let mode = "=";
41
+ for (const sym of tokRestrict.split(spec)) {
42
+ if (act[sym])
43
+ mode = sym;
44
+ else
45
+ act[mode](sym);
46
+ }
47
+ return out;
48
+ }
49
+ var TraverseControl = class {
50
+ constructor(value, decoration) {
51
+ this.value = value;
52
+ this.decoration = decoration;
53
+ }
54
+ };
55
+ function unwrap(value) {
56
+ if (value instanceof TraverseControl)
57
+ return [value.value ?? void 0, value.decoration];
58
+ return [value ?? void 0, void 0];
59
+ }
60
+ function prepareWrapper(label) {
61
+ const fun = (value) => new TraverseControl(value, fun);
62
+ fun.label = label;
63
+ fun.toString = () => "TraverseControl::" + label;
64
+ return fun;
65
+ }
66
+
67
+ // src/expr.ts
68
+ var DEFAULTS = {
69
+ max: 1e3,
70
+ maxArgs: 32
71
+ };
72
+ var ORDER = {
73
+ "leftmost-outermost": "LO",
74
+ "leftmost-innermost": "LI",
75
+ LO: "LO",
76
+ LI: "LI"
77
+ };
78
+ var control = {
79
+ descend: prepareWrapper("descend"),
80
+ prune: prepareWrapper("prune"),
81
+ redo: prepareWrapper("redo"),
82
+ stop: prepareWrapper("stop")
83
+ };
84
+ var native = {};
85
+ var Expr = class _Expr {
86
+ static {
87
+ this.control = control;
88
+ }
89
+ static {
90
+ this.native = native;
91
+ }
92
+ /**
93
+ *
94
+ * @desc Define properties of the term based on user supplied options and/or inference results.
95
+ * Typically useful for declaring Native and Alias terms.
96
+ * @private
97
+ * @param {Object} options
98
+ * @param {string} [options.note] - a brief description what the term does
99
+ * @param {number} [options.arity] - number of arguments the term is waiting for (if known)
100
+ * @param {string} [options.fancy] - how to display in html mode, e.g. &phi; instead of 'f'
101
+ * @param {boolean} [options.canonize] - whether to try to infer the properties
102
+ * @param {number} [options.max] - maximum number of steps for inference, if canonize is true
103
+ * @param {number} [options.maxArgs] - maximum number of arguments for inference, if canonize is true
104
+ * @return {this}
105
+ */
106
+ _setup(options = {}) {
107
+ if (options.fancy !== void 0 && this instanceof Named)
108
+ this.fancyName = options.fancy;
109
+ if (options.note !== void 0)
110
+ this.note = options.note;
111
+ if (options.arity !== void 0)
112
+ this.arity = options.arity;
113
+ if (options.canonize) {
114
+ const guess = this.infer(options);
115
+ if (guess.normal) {
116
+ this.arity = this.arity ?? guess.arity;
117
+ this.note = this.note ?? guess.expr.format({ html: true, lambda: ["", " &mapsto; ", ""] });
118
+ delete guess.steps;
119
+ this.props = guess;
78
120
  }
79
- };
80
- function unwrap(value) {
81
- if (value instanceof TraverseControl)
82
- return [value.value ?? void 0, value.decoration];
83
- return [value ?? void 0, void 0];
84
121
  }
85
- function prepareWrapper(label) {
86
- const fun = (value) => new TraverseControl(value, fun);
87
- fun.label = label;
88
- fun.toString = () => "TraverseControl::" + label;
89
- return fun;
122
+ return this;
123
+ }
124
+ /**
125
+ * @desc apply self to zero or more terms and return the resulting term,
126
+ * without performing any calculations whatsoever
127
+ * @param {Expr} args
128
+ * @return {Expr}
129
+ */
130
+ apply(...args) {
131
+ let expr = this;
132
+ for (const arg of args)
133
+ expr = new App(expr, arg);
134
+ return expr;
135
+ }
136
+ /**
137
+ * @desc Replace all aliases in the expression with their definitions, recursively.
138
+ * @return {Expr}
139
+ */
140
+ expand() {
141
+ return this.traverse((e) => {
142
+ if (e instanceof Alias)
143
+ return e.impl.expand();
144
+ }) ?? this;
145
+ }
146
+ /**
147
+ * @desc Traverse the expression tree, applying change() to each node.
148
+ * If change() returns an Expr, the node is replaced with that value.
149
+ * A null/undefined value is interpreted as
150
+ * "descend further if applicable, or leave the node unchanged".
151
+ *
152
+ * Returned values may be decorated:
153
+ *
154
+ * SKI.control.prune will suppress further descending even if nothing was returned
155
+ * SKI.control.stop will terminate further changes.
156
+ * SKI.control.redo will apply the callback to the returned subtree, recursively.
157
+ *
158
+ * Note that if redo was applied at least once to a subtree, a null return from the same subtree
159
+ * will be replaced by the last non-null value returned.
160
+ *
161
+ * The traversal order is leftmost-outermost, unless options.order = 'leftmost-innermost' is specified.
162
+ * Short aliases 'LO' and 'LI' (case-sensitive) are also accepted.
163
+ *
164
+ * Returns null if no changes were made, or the new expression otherwise.
165
+ *
166
+ * @param {{
167
+ * order?: 'LO' | 'LI' | 'leftmost-outermost' | 'leftmost-innermost',
168
+ * }} [options]
169
+ * @param {(e:Expr) => TraverseValue<Expr>} change
170
+ * @returns {Expr|null}
171
+ */
172
+ traverse(options, change) {
173
+ if (typeof options === "function") {
174
+ change = options;
175
+ options = {};
90
176
  }
91
- module.exports = { Tokenizer, restrict, unwrap, prepareWrapper };
177
+ const order = ORDER[options.order ?? "LO"];
178
+ if (order === void 0)
179
+ throw new Error("Unknown traversal order: " + options.order);
180
+ const [expr] = unwrap(this._traverse_redo({ order }, change));
181
+ return expr ?? null;
92
182
  }
93
- });
94
-
95
- // src/expr.js
96
- var require_expr = __commonJS({
97
- "src/expr.js"(exports, module) {
98
- "use strict";
99
- var { unwrap, prepareWrapper } = require_internal();
100
- var DEFAULTS = {
101
- max: 1e3,
102
- maxArgs: 32
103
- };
104
- var ORDER = {
105
- "leftmost-outermost": "LO",
106
- "leftmost-innermost": "LI",
107
- LO: "LO",
108
- LI: "LI"
109
- };
110
- var control = {
111
- descend: prepareWrapper("descend"),
112
- prune: prepareWrapper("prune"),
113
- redo: prepareWrapper("redo"),
114
- stop: prepareWrapper("stop")
115
- };
116
- var native = {};
117
- var Expr = class _Expr {
118
- /**
119
- * @descr A combinatory logic expression.
120
- *
121
- * Applications, variables, and other terms like combinators per se
122
- * are subclasses of this class.
123
- *
124
- * @abstract
125
- * @property {{
126
- * scope?: any,
127
- * env?: { [key: string]: Expr },
128
- * src?: string,
129
- * parser: object,
130
- * }} [context]
131
- * @property {number} [arity] - number of arguments the term is waiting for (if known)
132
- * @property {string} [note] - a brief description what the term does
133
- * @property {string} [fancyName] - how to display in html mode, e.g. &phi; instead of 'f'
134
- * Typically only applicable to descendants of Named.
135
- * @property {TermInfo} [props] - properties inferred from the term's behavior
136
- */
137
- /**
138
- *
139
- * @desc Define properties of the term based on user supplied options and/or inference results.
140
- * Typically useful for declaring Native and Alias terms.
141
- * @private
142
- * @param {Object} options
143
- * @param {string} [options.note] - a brief description what the term does
144
- * @param {number} [options.arity] - number of arguments the term is waiting for (if known)
145
- * @param {string} [options.fancy] - how to display in html mode, e.g. &phi; instead of 'f'
146
- * @param {boolean} [options.canonize] - whether to try to infer the properties
147
- * @param {number} [options.max] - maximum number of steps for inference, if canonize is true
148
- * @param {number} [options.maxArgs] - maximum number of arguments for inference, if canonize is true
149
- * @return {this}
150
- */
151
- _setup(options = {}) {
152
- if (options.fancy !== void 0)
153
- this.fancyName = options.fancyName;
154
- if (options.note !== void 0)
155
- this.note = options.note;
156
- if (options.arity !== void 0)
157
- this.arity = options.arity;
158
- if (options.canonize) {
159
- const guess = this.infer(options);
160
- if (guess.normal) {
161
- this.arity = this.arity ?? guess.arity;
162
- this.note = this.note ?? guess.expr.format({ html: true, lambda: ["", " &mapsto; ", ""] });
163
- delete guess.steps;
164
- this.props = guess;
165
- }
166
- }
167
- return this;
168
- }
169
- /**
170
- * @desc apply self to zero or more terms and return the resulting term,
171
- * without performing any calculations whatsoever
172
- * @param {Expr} args
173
- * @return {Expr}
174
- */
175
- apply(...args) {
176
- let expr = this;
177
- for (const arg of args)
178
- expr = new App(expr, arg);
179
- return expr;
180
- }
181
- /**
182
- * @desc Replace all aliases in the expression with their definitions, recursively.
183
- * @return {Expr}
184
- */
185
- expand() {
186
- return this.traverse((e) => {
187
- if (e instanceof Alias)
188
- return e.impl.expand();
189
- }) ?? this;
190
- }
191
- /**
192
- * @desc Returns true if the expression contains only free variables and applications, false otherwise.
193
- * @returns {boolean}
194
- */
195
- freeOnly() {
196
- return !this.any((e) => !(e instanceof FreeVar || e instanceof App));
197
- }
198
- /**
199
- * @desc Traverse the expression tree, applying change() to each node.
200
- * If change() returns an Expr, the node is replaced with that value.
201
- * A null/undefined value is interpreted as
202
- * "descend further if applicable, or leave the node unchanged".
203
- *
204
- * Returned values may be decorated:
205
- *
206
- * SKI.control.prune will suppress further descending even if nothing was returned
207
- * SKI.control.stop will terminate further changes.
208
- * SKI.control.redo will apply the callback to the returned subtree, recursively.
209
- *
210
- * Note that if redo was applied at least once to a subtree, a null return from the same subtree
211
- * will be replaced by the last non-null value returned.
212
- *
213
- * The traversal order is leftmost-outermost, unless options.order = 'leftmost-innermost' is specified.
214
- * Short aliases 'LO' and 'LI' (case-sensitive) are also accepted.
215
- *
216
- * Returns null if no changes were made, or the new expression otherwise.
217
- *
218
- * @param {{
219
- * order?: 'LO' | 'LI' | 'leftmost-outermost' | 'leftmost-innermost',
220
- * }} [options]
221
- * @param {(e:Expr) => TraverseValue<Expr>} change
222
- * @returns {Expr|null}
223
- */
224
- traverse(options, change) {
225
- if (typeof options === "function") {
226
- change = options;
227
- options = {};
183
+ /**
184
+ * @private
185
+ * @param {Object} options
186
+ * @param {(e:Expr) => TraverseValue<Expr>} change
187
+ * @returns {TraverseValue<Expr>}
188
+ */
189
+ _traverse_redo(options, change) {
190
+ let action;
191
+ let expr = this;
192
+ let prev;
193
+ do {
194
+ prev = expr;
195
+ const next = options.order === "LI" ? expr._traverse_descend(options, change) ?? change(expr) : change(expr) ?? expr._traverse_descend(options, change);
196
+ [expr, action] = unwrap(next);
197
+ } while (expr && action === control.redo);
198
+ if (!expr && prev !== this)
199
+ expr = prev;
200
+ return action ? action(expr) : expr;
201
+ }
202
+ /**
203
+ * @private
204
+ * @param {Object} options
205
+ * @param {(e:Expr) => TraverseValue<Expr>} change
206
+ * @returns {TraverseValue<Expr>}
207
+ */
208
+ _traverse_descend(options, change) {
209
+ return null;
210
+ }
211
+ /**
212
+ * @desc Returns true if predicate() is true for any subterm of the expression, false otherwise.
213
+ *
214
+ * @param {(e: Expr) => boolean} predicate
215
+ * @returns {boolean}
216
+ */
217
+ any(predicate) {
218
+ return predicate(this);
219
+ }
220
+ /**
221
+ * @desc Fold the expression into a single value by recursively applying combine() to its subterms.
222
+ * Nodes are traversed in leftmost-outermost order, i.e. the same order as reduction steps are taken.
223
+ *
224
+ * null or undefined return value from combine() means "keep current value and descend further".
225
+ *
226
+ * SKI.control provides primitives to control the folding flow:
227
+ * - SKI.control.prune(value) means "use value and don't descend further into this branch";
228
+ * - SKI.control.stop(value) means "stop folding immediately and return value".
229
+ * - SKI.control.descend(value) is the default behavior, meaning "use value and descend further".
230
+ *
231
+ * This method is experimental and may change in the future.
232
+ *
233
+ * @experimental
234
+ * @template T
235
+ * @param {T} initial
236
+ * @param {(acc: T, expr: Expr) => TraverseValue<T>} combine
237
+ * @returns {T}
238
+ */
239
+ fold(initial, combine) {
240
+ const [value] = unwrap(this._fold(initial, combine));
241
+ return value ?? initial;
242
+ }
243
+ _fold(initial, combine) {
244
+ return combine(initial, this);
245
+ }
246
+ /**
247
+ * @experimental
248
+ * @desc Fold an application tree bottom to top.
249
+ * For each subtree, the function is given the term in the root position and
250
+ * a list of the results of folding its arguments.
251
+ *
252
+ * E.g. fold('x y (z t)', f) results in f(x, [f(y, []), f(z, [f(t, [])])])
253
+ *
254
+ * @example expr.foldBottomUp((head, tail) => {
255
+ * if (head.arity && head.arity <= tail.length) {
256
+ * return '(<span class="redex">'
257
+ * + head + ' '
258
+ * + tail.slice(0, head.arity).join(' ')
259
+ * + '</span>'
260
+ * + tail.slice(head.arity).join(' ')
261
+ * + ')';
262
+ * } else {
263
+ * return '(' + head + ' ' + tail.join(' ') + ')';
264
+ * }
265
+ * });
266
+ * @template T
267
+ * @param {(head: Expr, tail: T[]) => T} fun
268
+ * @return {T}
269
+ */
270
+ foldBottomUp(fun) {
271
+ const [head, ...tail] = this.unroll();
272
+ return fun(head, tail.map((e) => e.foldBottomUp(fun)));
273
+ }
274
+ /**
275
+ * @desc Try to empirically find an equivalent lambda term for the expression,
276
+ * returning also the term's arity and some other properties.
277
+ *
278
+ * This is used internally when declaring a Native / Alias term,
279
+ * unless {canonize: false} is used.
280
+ *
281
+ * As of current it only recognizes terms that have a normal form,
282
+ * perhaps after adding some variables. This may change in the future.
283
+ *
284
+ * Use toLambda() if you want to get a lambda term in any case.
285
+ *
286
+ * @param {{max?: number, maxArgs?: number}} options
287
+ * @return {TermInfo}
288
+ */
289
+ infer(options = {}) {
290
+ const skipNames = {};
291
+ this.traverse((e) => {
292
+ if (e instanceof Named)
293
+ skipNames[e.name] = true;
294
+ return void 0;
295
+ });
296
+ return this._infer({
297
+ max: options.max ?? DEFAULTS.max,
298
+ maxArgs: options.maxArgs ?? DEFAULTS.maxArgs,
299
+ skipNames
300
+ }, 0);
301
+ }
302
+ /**
303
+ * @desc Internal method for infer(), which performs the actual inference.
304
+ * @param {{max: number, maxArgs: number}} options
305
+ * @param {number} nargs - var index to avoid name clashes
306
+ * @returns {TermInfo}
307
+ * @private
308
+ */
309
+ _infer(options, nargs) {
310
+ const probe = [];
311
+ let steps = 0;
312
+ let expr = this;
313
+ main: for (let i = 0; i < options.maxArgs; i++) {
314
+ const next = expr.run({ max: options.max - steps });
315
+ steps += next.steps;
316
+ if (!next.final)
317
+ break;
318
+ if (firstVar(next.expr)) {
319
+ expr = next.expr;
320
+ if (!expr.any((e) => !(e instanceof FreeVar || e instanceof App)))
321
+ return maybeLambda(probe, expr, { steps });
322
+ const list = expr.unroll();
323
+ let discard = false;
324
+ let duplicate = false;
325
+ const acc = [];
326
+ for (let j = 1; j < list.length; j++) {
327
+ const sub = list[j]._infer(
328
+ { maxArgs: options.maxArgs - nargs, max: options.max - steps, skipNames: options.skipNames },
329
+ // limit recursion
330
+ nargs + i
331
+ // avoid variable name clashes
332
+ );
333
+ steps += sub.steps ?? 0;
334
+ if (!sub.expr)
335
+ break main;
336
+ if (sub.discard)
337
+ discard = true;
338
+ if (sub.duplicate)
339
+ duplicate = true;
340
+ acc.push(sub.expr);
228
341
  }
229
- const order = ORDER[options.order ?? "LO"];
230
- if (order === void 0)
231
- throw new Error("Unknown traversal order: " + options.order);
232
- const [expr, _] = unwrap(this._traverse_redo({ order }, change));
233
- return expr;
342
+ return maybeLambda(probe, list[0].apply(...acc), { discard, duplicate, steps });
234
343
  }
235
- /**
236
- * @private
237
- * @param {Object} options
238
- * @param {(e:Expr) => TraverseValue<Expr>} change
239
- * @returns {TraverseValue<Expr>}
240
- */
241
- _traverse_redo(options, change) {
242
- let action;
243
- let expr = this;
244
- let prev;
245
- do {
246
- prev = expr;
247
- const next = options.order === "LI" ? expr._traverse_descend(options, change) ?? change(expr) : change(expr) ?? expr._traverse_descend(options, change);
248
- [expr, action] = unwrap(next);
249
- } while (expr && action === control.redo);
250
- if (!expr && prev !== this)
251
- expr = prev;
252
- return action ? action(expr) : expr;
253
- }
254
- /**
255
- * @private
256
- * @param {Object} options
257
- * @param {(e:Expr) => TraverseValue<Expr>} change
258
- * @returns {TraverseValue<Expr>}
259
- */
260
- _traverse_descend(options, change) {
344
+ while (options.skipNames[nthvar(nargs + i).name])
345
+ nargs++;
346
+ const push = nthvar(nargs + i);
347
+ probe.push(push);
348
+ expr = next.expr.apply(push);
349
+ }
350
+ return { normal: false, proper: false, steps };
351
+ }
352
+ /**
353
+ * @desc Expand an expression into a list of terms
354
+ * that give the initial expression when applied from left to right:
355
+ * ((a, b), (c, d)) => [a, b, (c, d)]
356
+ *
357
+ * This can be thought of as an opposite of apply:
358
+ * fun.apply(...arg).unroll() is exactly [fun, ...args]
359
+ * (even if ...arg is in fact empty).
360
+ *
361
+ * @returns {Expr[]}
362
+ */
363
+ unroll() {
364
+ return [this];
365
+ }
366
+ /**
367
+ * @desc Returns a series of lambda terms equivalent to the given expression,
368
+ * up to the provided computation steps limit.
369
+ *
370
+ * Unlike infer(), this method will always return something,
371
+ * even if the expression has no normal form.
372
+ *
373
+ * See also Expr.walk() and Expr.toSKI().
374
+ *
375
+ * @param {{
376
+ * max?: number,
377
+ * maxArgs?: number,
378
+ * varGen?: function(void): FreeVar,
379
+ * steps?: number,
380
+ * html?: boolean,
381
+ * latin?: number,
382
+ * }} options
383
+ * @return {IterableIterator<{expr: Expr, steps?: number, comment?: string}>}
384
+ */
385
+ *toLambda(options = {}) {
386
+ let expr = this.traverse((e) => {
387
+ if (e instanceof FreeVar || e instanceof App || e instanceof Lambda || e instanceof Alias)
261
388
  return null;
262
- }
263
- /**
264
- * @desc Returns true if predicate() is true for any subterm of the expression, false otherwise.
265
- *
266
- * @param {(e: Expr) => boolean} predicate
267
- * @returns {boolean}
268
- */
269
- any(predicate) {
270
- return predicate(this);
271
- }
272
- /**
273
- * @desc Fold the expression into a single value by recursively applying combine() to its subterms.
274
- * Nodes are traversed in leftmost-outermost order, i.e. the same order as reduction steps are taken.
275
- *
276
- * null or undefined return value from combine() means "keep current value and descend further".
277
- *
278
- * SKI.control provides primitives to control the folding flow:
279
- * - SKI.control.prune(value) means "use value and don't descend further into this branch";
280
- * - SKI.control.stop(value) means "stop folding immediately and return value".
281
- * - SKI.control.descend(value) is the default behavior, meaning "use value and descend further".
282
- *
283
- * This method is experimental and may change in the future.
284
- *
285
- * @experimental
286
- * @template T
287
- * @param {T} initial
288
- * @param {(acc: T, expr: Expr) => TraverseValue<T>} combine
289
- * @returns {T}
290
- */
291
- fold(initial, combine) {
292
- const [value, _] = unwrap(this._fold(initial, combine));
293
- return value ?? initial;
294
- }
295
- /**
296
- * @template T
297
- * @param {T} initial
298
- * @param {(acc: T, expr: Expr) => TraverseValue<T>} combine
299
- * @returns {TraverseValue<T>}
300
- * @private
301
- */
302
- _fold(initial, combine) {
303
- return combine(initial, this);
304
- }
305
- /**
306
- * @desc rough estimate of the term's complexity
307
- * @return {number}
308
- */
309
- weight() {
310
- return 1;
311
- }
312
- /**
313
- * @desc Try to empirically find an equivalent lambda term for the expression,
314
- * returning also the term's arity and some other properties.
315
- *
316
- * This is used internally when declaring a Native / Alias term,
317
- * unless {canonize: false} is used.
318
- *
319
- * As of current it only recognizes terms that have a normal form,
320
- * perhaps after adding some variables. This may change in the future.
321
- *
322
- * Use toLambda() if you want to get a lambda term in any case.
323
- *
324
- * @param {{max?: number, maxArgs?: number}} options
325
- * @return {TermInfo}
326
- */
327
- infer(options = {}) {
328
- return this._infer({
329
- max: options.max ?? DEFAULTS.max,
330
- maxArgs: options.maxArgs ?? DEFAULTS.maxArgs
331
- }, 0);
332
- }
333
- /**
334
- * @desc Internal method for infer(), which performs the actual inference.
335
- * @param {{max: number, maxArgs: number}} options
336
- * @param {number} nargs - var index to avoid name clashes
337
- * @returns {TermInfo}
338
- * @private
339
- */
340
- _infer(options, nargs) {
341
- const probe = [];
342
- let steps = 0;
343
- let expr = this;
344
- main: for (let i = 0; i < options.maxArgs; i++) {
345
- const next = expr.run({ max: options.max - steps });
346
- steps += next.steps;
347
- if (!next.final)
348
- break;
349
- if (firstVar(next.expr)) {
350
- expr = next.expr;
351
- if (!expr.any((e) => !(e instanceof FreeVar || e instanceof App)))
352
- return maybeLambda(probe, expr, { steps });
353
- const list = expr.unroll();
354
- let discard = false;
355
- let duplicate = false;
356
- const acc = [];
357
- for (let j = 1; j < list.length; j++) {
358
- const sub = list[j]._infer(
359
- { maxArgs: options.maxArgs - nargs, max: options.max - steps },
360
- // limit recursion
361
- nargs + i
362
- // avoid variable name clashes
363
- );
364
- steps += sub.steps;
365
- if (!sub.expr)
366
- break main;
367
- if (sub.discard)
368
- discard = true;
369
- if (sub.duplicate)
370
- duplicate = true;
371
- acc.push(sub.expr);
372
- }
373
- return maybeLambda(probe, list[0].apply(...acc), { discard, duplicate, steps });
374
- }
375
- const push = nthvar(nargs + i);
376
- probe.push(push);
377
- expr = next.expr.apply(push);
378
- }
379
- return { normal: false, proper: false, steps };
380
- }
381
- /**
382
- * @desc Expand an expression into a list of terms
383
- * that give the initial expression when applied from left to right:
384
- * ((a, b), (c, d)) => [a, b, (c, d)]
385
- *
386
- * This can be thought of as an opposite of apply:
387
- * fun.apply(...arg).unroll() is exactly [fun, ...args]
388
- * (even if ...arg is in fact empty).
389
- *
390
- * @returns {Expr[]}
391
- */
392
- unroll() {
393
- return [this];
394
- }
395
- /**
396
- * @desc Returns a series of lambda terms equivalent to the given expression,
397
- * up to the provided computation steps limit,
398
- * in decreasing weight order.
399
- *
400
- * Unlike infer(), this method will always return something,
401
- * even if the expression has no normal form.
402
- *
403
- * See also Expr.walk() and Expr.toSKI().
404
- *
405
- * @param {{
406
- * max?: number,
407
- * maxArgs?: number,
408
- * varGen?: function(void): FreeVar,
409
- * steps?: number,
410
- * html?: boolean,
411
- * latin?: number,
412
- * }} options
413
- * @param {number} [maxWeight] - maximum allowed weight of terms in the sequence
414
- * @return {IterableIterator<{expr: Expr, steps?: number, comment?: string}>}
415
- */
416
- *toLambda(options = {}) {
417
- let expr = this.traverse((e) => {
418
- if (e instanceof FreeVar || e instanceof App || e instanceof Lambda || e instanceof Alias)
419
- return null;
389
+ const guess = e.infer({ max: options.max, maxArgs: options.maxArgs });
390
+ if (!guess.normal)
391
+ throw new Error("Failed to infer an equivalent lambda term for " + e);
392
+ return guess.expr;
393
+ }) ?? this;
394
+ const seen = /* @__PURE__ */ new Set();
395
+ let steps = 0;
396
+ while (expr) {
397
+ const next = expr.traverse({ order: "LI" }, (e) => {
398
+ if (seen.has(e))
399
+ return null;
400
+ if (e instanceof App && e.fun instanceof Lambda) {
420
401
  const guess = e.infer({ max: options.max, maxArgs: options.maxArgs });
421
- if (!guess.normal)
422
- throw new Error("Failed to infer an equivalent lambda term for " + e);
423
- return guess.expr;
424
- }) ?? this;
425
- const seen = /* @__PURE__ */ new Set();
426
- let steps = 0;
427
- while (expr) {
428
- const next = expr.traverse({ order: "LI" }, (e) => {
429
- if (seen.has(e))
430
- return null;
431
- if (e instanceof App && e.fun instanceof Lambda) {
432
- const guess = e.infer({ max: options.max, maxArgs: options.maxArgs });
433
- steps += guess.steps;
434
- if (!guess.normal) {
435
- seen.add(e);
436
- return null;
437
- }
438
- return control.stop(guess.expr);
439
- }
440
- });
441
- yield { expr, steps };
442
- expr = next;
443
- }
444
- }
445
- /**
446
- * @desc Rewrite the expression into S, K, and I combinators step by step.
447
- * Returns an iterator yielding the intermediate expressions,
448
- * along with the number of steps taken to reach them.
449
- *
450
- * See also Expr.walk() and Expr.toLambda().
451
- *
452
- * @param {{max?: number}} [options]
453
- * @return {IterableIterator<{final: boolean, expr: Expr, steps: number}>}
454
- */
455
- *toSKI(options = {}) {
456
- let expr = this.traverse((e) => {
457
- if (e instanceof FreeVar || e instanceof App || e instanceof Lambda || e instanceof Alias)
402
+ steps += guess.steps ?? 0;
403
+ if (!guess.normal) {
404
+ seen.add(e);
458
405
  return null;
459
- return e.infer().expr;
460
- }) ?? this;
461
- let steps = 0;
462
- while (expr) {
463
- const next = expr.traverse({ order: "LI" }, (e) => {
464
- if (!(e instanceof Lambda) || e.impl instanceof Lambda)
465
- return null;
466
- if (e.impl === e.arg)
467
- return control.stop(native.I);
468
- if (!e.impl.any((t) => t === e.arg))
469
- return control.stop(native.K.apply(e.impl));
470
- if (!(e.impl instanceof App))
471
- throw new Error("toSKI: assert failed: lambda body is of unexpected type " + e.impl.constructor.name);
472
- if (e.impl.arg === e.arg && !e.impl.fun.any((t) => t === e.arg))
473
- return control.stop(e.impl.fun);
474
- return control.stop(native.S.apply(new Lambda(e.arg, e.impl.fun), new Lambda(e.arg, e.impl.arg)));
475
- });
476
- yield { expr, steps, final: !next };
477
- steps++;
478
- expr = next;
479
- }
480
- }
481
- /**
482
- * Replace all instances of plug in the expression with value and return the resulting expression,
483
- * or null if no changes could be made.
484
- * Lambda terms and applications will never match if used as plug
485
- * as they are impossible co compare without extensive computations.
486
- * Typically used on variables but can also be applied to other terms, e.g. aliases.
487
- * See also Expr.traverse().
488
- * @param {Expr} search
489
- * @param {Expr} replace
490
- * @return {Expr|null}
491
- */
492
- subst(search, replace) {
493
- return this === search ? replace : null;
494
- }
495
- /**
496
- * @desc Apply term reduction rules, if any, to the given argument.
497
- * A returned value of null means no reduction is possible.
498
- * A returned value of Expr means the reduction is complete and the application
499
- * of this and arg can be replaced with the result.
500
- * A returned value of a function means that further arguments are needed,
501
- * and can be cached for when they arrive.
502
- *
503
- * This method is between apply() which merely glues terms together,
504
- * and step() which reduces the whole expression.
505
- *
506
- * foo.invoke(bar) is what happens inside foo.apply(bar).step() before
507
- * reduction of either foo or bar is attempted.
508
- *
509
- * The name 'invoke' was chosen to avoid confusion with either 'apply' or 'reduce'.
510
- *
511
- * @param {Expr} arg
512
- * @returns {Partial | null}
513
- */
514
- invoke(arg) {
515
- return null;
516
- }
517
- /**
518
- * @desc iterate one step of a calculation.
519
- * @return {{expr: Expr, steps: number, changed: boolean}}
520
- */
521
- step() {
522
- return { expr: this, steps: 0, changed: false };
523
- }
524
- /**
525
- * @desc Run uninterrupted sequence of step() applications
526
- * until the expression is irreducible, or max number of steps is reached.
527
- * Default number of steps = 1000.
528
- * @param {{max?: number, steps?: number, throw?: boolean}|Expr} [opt]
529
- * @param {Expr} args
530
- * @return {{expr: Expr, steps: number, final: boolean}}
531
- */
532
- run(opt = {}, ...args) {
533
- if (opt instanceof _Expr) {
534
- args.unshift(opt);
535
- opt = {};
536
- }
537
- let expr = args ? this.apply(...args) : this;
538
- let steps = opt.steps ?? 0;
539
- const max = Math.max(opt.max ?? DEFAULTS.max, 1) + steps;
540
- let final = false;
541
- for (; steps < max; ) {
542
- const next = expr.step();
543
- if (!next.changed) {
544
- final = true;
545
- break;
546
406
  }
547
- steps += next.steps;
548
- expr = next.expr;
549
- }
550
- if (opt.throw && !final)
551
- throw new Error("Failed to compute expression in " + max + " steps");
552
- return { final, steps, expr };
553
- }
554
- /**
555
- * Execute step() while possible, yielding a brief description of events after each step.
556
- * Mnemonics: like run() but slower.
557
- * @param {{max?: number}} options
558
- * @return {IterableIterator<{final: boolean, expr: Expr, steps: number}>}
559
- */
560
- *walk(options = {}) {
561
- const max = options.max ?? Infinity;
562
- let steps = 0;
563
- let expr = this;
564
- let final = false;
565
- while (steps < max) {
566
- const next = expr.step();
567
- if (!next.changed)
568
- final = true;
569
- yield { expr, steps, final };
570
- if (final)
571
- break;
572
- steps += next.steps;
573
- expr = next.expr;
574
- }
575
- }
576
- /**
577
- * @desc True is the expressions are identical, false otherwise.
578
- * Aliases are expanded.
579
- * Bound variables in lambda terms are renamed consistently.
580
- * However, no reductions are attempted.
581
- *
582
- * E.g. a->b->a == x->y->x is true, but a->b->a == K is false.
583
- *
584
- * @param {Expr} other
585
- * @return {boolean}
586
- */
587
- equals(other) {
588
- return !this.diff(other);
589
- }
590
- /**
591
- * @desc Recursively compare two expressions and return a string
592
- * describing the first point of difference.
593
- * Returns null if expressions are identical.
594
- *
595
- * Aliases are expanded.
596
- * Bound variables in lambda terms are renamed consistently.
597
- * However, no reductions are attempted.
598
- *
599
- * Members of the FreeVar class are considered different
600
- * even if they have the same name, unless they are the same object.
601
- * To somewhat alleviate confusion, the output will include
602
- * the internal id of the variable in square brackets.
603
- *
604
- * @example "K(S != I)" is the result of comparing "KS" and "KI"
605
- * @example "S(K([x[13] != x[14]]))K"
606
- *
607
- * @param {Expr} other
608
- * @param {boolean} [swap] If true, the order of expressions is reversed in the output.
609
- * @returns {string|null}
610
- */
611
- diff(other, swap = false) {
612
- if (this === other)
613
- return null;
614
- if (other instanceof Alias)
615
- return other.impl.diff(this, !swap);
616
- return swap ? "[" + other + " != " + this + "]" : "[" + this + " != " + other + "]";
617
- }
618
- /**
619
- * @desc Assert expression equality. Can be used in tests.
620
- *
621
- * `this` is the expected value and the argument is the actual one.
622
- * Mnemonic: the expected value is always a combinator, the actual one may be anything.
623
- *
624
- * @param {Expr} actual
625
- * @param {string} comment
626
- */
627
- expect(actual, comment = "") {
628
- comment = comment ? comment + ": " : "";
629
- if (!(actual instanceof _Expr)) {
630
- throw new Error(comment + "Expected a combinator but found " + (actual?.constructor?.name ?? typeof actual));
631
- }
632
- const diff = this.diff(actual);
633
- if (!diff)
634
- return;
635
- const poorMans = new Error(comment + diff);
636
- poorMans.expected = this.diag();
637
- poorMans.actual = actual.diag();
638
- throw poorMans;
639
- }
640
- /**
641
- * @desc Returns string representation of the expression.
642
- * Same as format() without options.
643
- * @return {string}
644
- */
645
- toString() {
646
- return this.format();
647
- }
648
- /**
649
- * @desc Whether the expression needs parentheses when printed.
650
- * @param {boolean} [first] - whether this is the first term in a sequence
651
- * @return {boolean}
652
- */
653
- _braced(first) {
654
- return false;
655
- }
656
- /**
657
- * @desc Whether the expression can be printed without a space when followed by arg.
658
- * @param {Expr} arg
659
- * @returns {boolean}
660
- * @private
661
- */
662
- _unspaced(arg) {
663
- return this._braced(true);
664
- }
665
- /**
666
- * @desc Stringify the expression with fancy formatting options.
667
- * Said options mostly include wrappers around various constructs in form of ['(', ')'],
668
- * as well as terse and html flags that set up the defaults.
669
- * Format without options is equivalent to toString() and can be parsed back.
670
- *
671
- * @param {Object} [options] - formatting options
672
- * @param {boolean} [options.terse] - whether to use terse formatting (omitting unnecessary spaces and parentheses)
673
- * @param {boolean} [options.html] - whether to default to HTML tags & entities.
674
- * If a named term has fancyName property set, it will be used instead of name in this mode.
675
- * @param {[string, string]} [options.brackets] - wrappers for application arguments, typically ['(', ')']
676
- * @param {[string, string]} [options.var] - wrappers for variable names
677
- * (will default to &lt;var&gt; and &lt;/var&gt; in html mode).
678
- * @param {[string, string, string]} [options.lambda] - wrappers for lambda abstractions, e.g. ['&lambda;', '.', '']
679
- * where the middle string is placed between argument and body
680
- * default is ['', '->', ''] or ['', '-&gt;', ''] for html
681
- * @param {[string, string]} [options.around] - wrappers around (sub-)expressions.
682
- * individual applications will not be wrapped, i.e. (a b c) but not ((a b) c)
683
- * @param {[string, string]} [options.redex] - wrappers around the starting term(s) that have enough arguments to be reduced
684
- * @param {Object<string, Expr>} [options.inventory] - if given, output aliases in the set as their names
685
- * and any other aliases as the expansion of their definitions.
686
- * The default is a cryptic and fragile mechanism dependent on a hidden mutable property.
687
- * @returns {string}
688
- *
689
- * @example foo.format() // equivalent to foo.toString()
690
- * @example foo.format({terse: false}) // spell out all parentheses
691
- * @example foo.format({html: true}) // use HTML tags and entities
692
- * @example foo.format({ around: ['(', ')'], brackets: ['', ''], lambda: ['(', '->', ')'] }) // lisp style, still back-parsable
693
- * @exapmle foo.format({ lambda: ['&lambda;', '.', ''] }) // pretty-print for the math department
694
- * @example foo.format({ lambda: ['', '=>', ''], terse: false }) // make it javascript
695
- * @example foo.format({ inventory: { T } }) // use T as a named term, expand all others
696
- *
697
- */
698
- format(options = {}) {
699
- const fallback = options.html ? {
700
- brackets: ["(", ")"],
701
- space: " ",
702
- var: ["<var>", "</var>"],
703
- lambda: ["", "-&gt;", ""],
704
- around: ["", ""],
705
- redex: ["", ""]
706
- } : {
707
- brackets: ["(", ")"],
708
- space: " ",
709
- var: ["", ""],
710
- lambda: ["", "->", ""],
711
- around: ["", ""],
712
- redex: ["", ""]
713
- };
714
- return this._format({
715
- terse: options.terse ?? true,
716
- brackets: options.brackets ?? fallback.brackets,
717
- space: options.space ?? fallback.space,
718
- var: options.var ?? fallback.var,
719
- lambda: options.lambda ?? fallback.lambda,
720
- around: options.around ?? fallback.around,
721
- redex: options.redex ?? fallback.redex,
722
- inventory: options.inventory,
723
- // TODO better name
724
- html: options.html ?? false
725
- }, 0);
726
- }
727
- /**
728
- * @desc Internal method for format(), which performs the actual formatting.
729
- * @param {Object} options
730
- * @param {number} nargs
731
- * @returns {string}
732
- * @private
733
- */
734
- _format(options, nargs) {
735
- throw new Error("No _format() method defined in class " + this.constructor.name);
736
- }
737
- /**
738
- * @desc Returns a string representation of the expression tree, with indentation to show structure.
739
- *
740
- * Applications are flattened to avoid excessive nesting.
741
- * Variables include ids to distinguish different instances of the same variable name.
742
- *
743
- * May be useful for debugging.
744
- *
745
- * @returns {string}
746
- *
747
- * @example
748
- * > console.log(ski.parse('C 5 x (x->x x)').diag())
749
- * App:
750
- * Native: C
751
- * Church: 5
752
- * FreeVar: x[53]
753
- * Lambda (x[54]):
754
- * App:
755
- * FreeVar: x[54]
756
- * FreeVar: x[54]
757
- */
758
- diag() {
759
- const rec = (e, indent) => {
760
- if (e instanceof App)
761
- return [indent + "App:", ...e.unroll().flatMap((s) => rec(s, indent + " "))];
762
- if (e instanceof Lambda)
763
- return [`${indent}Lambda (${e.arg}[${e.arg.id}]):`, ...rec(e.impl, indent + " ")];
764
- if (e instanceof Alias)
765
- return [`${indent}Alias (${e.name}): \\`, ...rec(e.impl, indent)];
766
- if (e instanceof FreeVar)
767
- return [`${indent}FreeVar: ${e.name}[${e.id}]`];
768
- return [`${indent}${e.constructor.name}: ${e}`];
769
- };
770
- const out = rec(this, "");
771
- return out.join("\n");
772
- }
773
- /**
774
- * @desc Convert the expression to a JSON-serializable format.
775
- * @returns {string}
776
- */
777
- toJSON() {
778
- return this.format();
779
- }
780
- };
781
- var App = class _App extends Expr {
782
- /**
783
- * @desc Application of fun() to args.
784
- * Never ever use new App(fun, arg) directly, use fun.apply(...args) instead.
785
- * @param {Expr} fun
786
- * @param {Expr} arg
787
- */
788
- constructor(fun, arg) {
789
- super();
790
- this.arg = arg;
791
- this.fun = fun;
792
- }
793
- /** @property {boolean} [final] */
794
- weight() {
795
- return this.fun.weight() + this.arg.weight();
796
- }
797
- _traverse_descend(options, change) {
798
- const [fun, fAction] = unwrap(this.fun._traverse_redo(options, change));
799
- if (fAction === control.stop)
800
- return control.stop(fun ? fun.apply(this.arg) : null);
801
- const [arg, aAction] = unwrap(this.arg._traverse_redo(options, change));
802
- const final = fun || arg ? (fun ?? this.fun).apply(arg ?? this.arg) : null;
803
- if (aAction === control.stop)
804
- return control.stop(final);
805
- return final;
806
- }
807
- any(predicate) {
808
- return predicate(this) || this.fun.any(predicate) || this.arg.any(predicate);
809
- }
810
- _fold(initial, combine) {
811
- const [value = initial, action = "descend"] = unwrap(combine(initial, this));
812
- if (action === control.prune)
813
- return value;
814
- if (action === control.stop)
815
- return control.stop(value);
816
- const [fValue = value, fAction = "descend"] = unwrap(this.fun._fold(value, combine));
817
- if (fAction === control.stop)
818
- return control.stop(fValue);
819
- const [aValue = fValue, aAction = "descend"] = unwrap(this.arg._fold(fValue, combine));
820
- if (aAction === control.stop)
821
- return control.stop(aValue);
822
- return aValue;
823
- }
824
- subst(search, replace) {
825
- const fun = this.fun.subst(search, replace);
826
- const arg = this.arg.subst(search, replace);
827
- return fun || arg ? (fun ?? this.fun).apply(arg ?? this.arg) : null;
828
- }
829
- /**
830
- * @return {{expr: Expr, steps: number}}
831
- */
832
- step() {
833
- if (!this.final) {
834
- const partial = this.fun.invoke(this.arg);
835
- if (partial instanceof Expr)
836
- return { expr: partial, steps: 1, changed: true };
837
- else if (typeof partial === "function")
838
- this.invoke = partial;
839
- const fun = this.fun.step();
840
- if (fun.changed)
841
- return { expr: fun.expr.apply(this.arg), steps: fun.steps, changed: true };
842
- const arg = this.arg.step();
843
- if (arg.changed)
844
- return { expr: this.fun.apply(arg.expr), steps: arg.steps, changed: true };
845
- this.final = true;
846
- }
847
- return { expr: this, steps: 0, changed: false };
848
- }
849
- invoke(arg) {
850
- const partial = this.fun.invoke(this.arg);
851
- if (partial instanceof Expr)
852
- return partial.apply(arg);
853
- else if (typeof partial === "function") {
854
- this.invoke = partial;
855
- return partial(arg);
856
- } else {
857
- this.invoke = (_) => null;
858
- return null;
407
+ return control.stop(guess.expr);
859
408
  }
860
- }
861
- unroll() {
862
- return [...this.fun.unroll(), this.arg];
863
- }
864
- diff(other, swap = false) {
865
- if (!(other instanceof _App))
866
- return super.diff(other, swap);
867
- const fun = this.fun.diff(other.fun, swap);
868
- if (fun)
869
- return fun + "(...)";
870
- const arg = this.arg.diff(other.arg, swap);
871
- if (arg)
872
- return this.fun + "(" + arg + ")";
409
+ });
410
+ yield { expr, steps };
411
+ expr = next;
412
+ }
413
+ }
414
+ /**
415
+ * @desc Rewrite the expression into S, K, and I combinators step by step.
416
+ * Returns an iterator yielding the intermediate expressions,
417
+ * along with the number of steps taken to reach them.
418
+ *
419
+ * See also Expr.walk() and Expr.toLambda().
420
+ *
421
+ * @param {{max?: number}} [options]
422
+ * @return {IterableIterator<{final: boolean, expr: Expr, steps: number}>}
423
+ */
424
+ *toSKI(_options = {}) {
425
+ let expr = this.traverse((e) => {
426
+ if (e instanceof FreeVar || e instanceof App || e instanceof Lambda || e instanceof Alias)
873
427
  return null;
874
- }
875
- _braced(first) {
876
- return !first;
877
- }
878
- _format(options, nargs) {
879
- const fun = this.fun._format(options, nargs + 1);
880
- const arg = this.arg._format(options, 0);
881
- const wrap = nargs ? ["", ""] : options.around;
882
- if (options.terse && !this.arg._braced(false))
883
- return wrap[0] + fun + (this.fun._unspaced(this.arg) ? "" : options.space) + arg + wrap[1];
884
- else
885
- return wrap[0] + fun + options.brackets[0] + arg + options.brackets[1] + wrap[1];
886
- }
887
- _unspaced(arg) {
888
- return this.arg._braced(false) ? true : this.arg._unspaced(arg);
889
- }
890
- };
891
- var Named = class _Named extends Expr {
892
- /**
893
- * @desc An abstract class representing a term named 'name'.
894
- *
895
- * @param {String} name
896
- */
897
- constructor(name) {
898
- super();
899
- if (typeof name !== "string" || name.length === 0)
900
- throw new Error("Attempt to create a named term with improper name");
901
- this.name = name;
902
- }
903
- _unspaced(arg) {
904
- return !!(arg instanceof _Named && (this.name.match(/^[A-Z+]$/) && arg.name.match(/^[a-z+]/i) || this.name.match(/^[a-z+]/i) && arg.name.match(/^[A-Z+]$/)));
905
- }
906
- _format(options, nargs) {
907
- const name = options.html ? this.fancyName ?? this.name : this.name;
908
- return this.arity > 0 && this.arity <= nargs ? options.redex[0] + name + options.redex[1] : name;
909
- }
910
- };
911
- var freeId = 0;
912
- var FreeVar = class _FreeVar extends Named {
913
- /**
914
- * @desc A named variable.
915
- *
916
- * Given the functional nature of combinatory logic, variables are treated
917
- * as functions that we don't know how to evaluate just yet.
918
- *
919
- * By default, two different variables even with the same name are considered different.
920
- * They display it via a hidden id property.
921
- *
922
- * If a scope object is given, however, two variables with the same name and scope
923
- * are considered identical.
924
- *
925
- * By convention, FreeVar.global is a constant denoting a global unbound variable.
926
- *
927
- * @param {string} name - name of the variable
928
- * @param {any} scope - an object representing where the variable belongs to.
929
- */
930
- constructor(name, scope) {
931
- super(name);
932
- this.id = ++freeId;
933
- this.scope = scope === void 0 ? this : scope;
934
- }
935
- weight() {
936
- return 0;
937
- }
938
- diff(other, swap = false) {
939
- if (!(other instanceof _FreeVar))
940
- return super.diff(other, swap);
941
- if (this.name === other.name && this.scope === other.scope)
428
+ return e.infer().expr;
429
+ }) ?? this;
430
+ let steps = 0;
431
+ while (expr) {
432
+ const next = expr.traverse({ order: "LI" }, (e) => {
433
+ if (!(e instanceof Lambda) || e.impl instanceof Lambda)
942
434
  return null;
943
- const lhs = this.name + "[" + this.id + "]";
944
- const rhs = other.name + "[" + other.id + "]";
945
- return swap ? "[" + rhs + " != " + lhs + "]" : "[" + lhs + " != " + rhs + "]";
946
- }
947
- subst(search, replace) {
948
- if (search instanceof _FreeVar && search.name === this.name && search.scope === this.scope)
949
- return replace;
950
- return null;
951
- }
952
- _format(options, nargs) {
953
- const name = options.html ? this.fancyName ?? this.name : this.name;
954
- return options.var[0] + name + options.var[1];
955
- }
435
+ if (e.impl === e.arg)
436
+ return control.stop(native.I);
437
+ if (!e.impl.any((t) => t === e.arg))
438
+ return control.stop(native.K.apply(e.impl));
439
+ if (!(e.impl instanceof App))
440
+ throw new Error("toSKI: assert failed: lambda body is of unexpected type " + e.impl.constructor.name);
441
+ if (e.impl.arg === e.arg && !e.impl.fun.any((t) => t === e.arg))
442
+ return control.stop(e.impl.fun);
443
+ return control.stop(native.S.apply(new Lambda(e.arg, e.impl.fun), new Lambda(e.arg, e.impl.arg)));
444
+ });
445
+ yield { expr, steps, final: !next };
446
+ steps++;
447
+ expr = next;
448
+ }
449
+ }
450
+ /**
451
+ * Replace all instances of plug in the expression with value and return the resulting expression,
452
+ * or null if no changes could be made.
453
+ * Lambda terms and applications will never match if used as plug
454
+ * as they are impossible co compare without extensive computations.
455
+ * Typically used on variables but can also be applied to other terms, e.g. aliases.
456
+ * See also Expr.traverse().
457
+ * @param {Expr} search
458
+ * @param {Expr} replace
459
+ * @return {Expr|null}
460
+ */
461
+ subst(search2, replace) {
462
+ return this === search2 ? replace : null;
463
+ }
464
+ /**
465
+ * @desc Apply term reduction rules, if any, to the given argument.
466
+ * A returned value of null means no reduction is possible.
467
+ * A returned value of Expr means the reduction is complete and the application
468
+ * of this and arg can be replaced with the result.
469
+ * A returned value of a function means that further arguments are needed,
470
+ * and can be cached for when they arrive.
471
+ *
472
+ * This method is between apply() which merely glues terms together,
473
+ * and step() which reduces the whole expression.
474
+ *
475
+ * foo.invoke(bar) is what happens inside foo.apply(bar).step() before
476
+ * reduction of either foo or bar is attempted.
477
+ *
478
+ * The name 'invoke' was chosen to avoid confusion with either 'apply' or 'reduce'.
479
+ *
480
+ * @param {Expr} arg
481
+ * @returns {Partial | null}
482
+ */
483
+ invoke(arg) {
484
+ return null;
485
+ }
486
+ /**
487
+ * @desc iterate one step of a calculation.
488
+ * @return {{expr: Expr, steps: number, changed: boolean}}
489
+ */
490
+ step() {
491
+ return { expr: this, steps: 0, changed: false };
492
+ }
493
+ /**
494
+ * @desc Run uninterrupted sequence of step() applications
495
+ * until the expression is irreducible, or max number of steps is reached.
496
+ * Default number of steps = 1000.
497
+ * @param {{max?: number, steps?: number, throw?: boolean}|Expr} [opt]
498
+ * @param {Expr} args
499
+ * @return {{expr: Expr, steps: number, final: boolean}}
500
+ */
501
+ run(opt = {}, ...args) {
502
+ if (opt instanceof _Expr) {
503
+ args.unshift(opt);
504
+ opt = {};
505
+ }
506
+ let expr = args ? this.apply(...args) : this;
507
+ let steps = opt.steps ?? 0;
508
+ const max = Math.max(opt.max ?? DEFAULTS.max, 1) + steps;
509
+ let final = false;
510
+ for (; steps < max; ) {
511
+ const next = expr.step();
512
+ if (!next.changed) {
513
+ final = true;
514
+ break;
515
+ }
516
+ steps += next.steps;
517
+ expr = next.expr;
518
+ }
519
+ if (opt.throw && !final)
520
+ throw new Error("Failed to compute expression in " + max + " steps");
521
+ return { final, steps, expr };
522
+ }
523
+ /**
524
+ * Execute step() while possible, yielding a brief description of events after each step.
525
+ * Mnemonics: like run() but slower.
526
+ * @param {{max?: number}} options
527
+ * @return {IterableIterator<{final: boolean, expr: Expr, steps: number}>}
528
+ */
529
+ *walk(options = {}) {
530
+ const max = options.max ?? Infinity;
531
+ let steps = 0;
532
+ let expr = this;
533
+ let final = false;
534
+ while (steps < max) {
535
+ const next = expr.step();
536
+ if (!next.changed)
537
+ final = true;
538
+ yield { expr, steps, final };
539
+ if (final)
540
+ break;
541
+ steps += next.steps;
542
+ expr = next.expr;
543
+ }
544
+ }
545
+ /**
546
+ * @desc True is the expressions are identical, false otherwise.
547
+ * Aliases are expanded.
548
+ * Bound variables in lambda terms are renamed consistently.
549
+ * However, no reductions are attempted.
550
+ *
551
+ * E.g. a->b->a == x->y->x is true, but a->b->a == K is false.
552
+ *
553
+ * @param {Expr} other
554
+ * @return {boolean}
555
+ */
556
+ equals(other) {
557
+ return !this.diff(other);
558
+ }
559
+ /**
560
+ * @desc Recursively compare two expressions and return a string
561
+ * describing the first point of difference.
562
+ * Returns null if expressions are identical.
563
+ *
564
+ * Aliases are expanded.
565
+ * Bound variables in lambda terms are renamed consistently.
566
+ * However, no reductions are attempted.
567
+ *
568
+ * Members of the FreeVar class are considered different
569
+ * even if they have the same name, unless they are the same object.
570
+ * To somewhat alleviate confusion, the output will include
571
+ * the internal id of the variable in square brackets.
572
+ *
573
+ * @example "K(S != I)" is the result of comparing "KS" and "KI"
574
+ * @example "S(K([x[13] != x[14]]))K"
575
+ *
576
+ * @param {Expr} other
577
+ * @param {boolean} [swap] If true, the order of expressions is reversed in the output.
578
+ * @returns {string|null}
579
+ */
580
+ diff(other, swap = false) {
581
+ if (this === other)
582
+ return null;
583
+ if (other instanceof Alias)
584
+ return other.impl.diff(this, !swap);
585
+ return swap ? "[" + other + " != " + this + "]" : "[" + this + " != " + other + "]";
586
+ }
587
+ /**
588
+ * @desc Assert expression equality. Can be used in tests.
589
+ *
590
+ * `this` is the expected value and the argument is the actual one.
591
+ * Mnemonic: the expected value is always a combinator, the actual one may be anything.
592
+ *
593
+ * @param {Expr} actual
594
+ * @param {string} comment
595
+ */
596
+ expect(actual, comment = "") {
597
+ comment = comment ? comment + ": " : "";
598
+ if (!(actual instanceof _Expr)) {
599
+ throw new Error(comment + "Expected a combinator but found " + (actual?.constructor?.name ?? typeof actual));
600
+ }
601
+ const diff = this.diff(actual);
602
+ if (!diff)
603
+ return;
604
+ const poorMans = new Error(comment + diff);
605
+ poorMans.expected = this.diag();
606
+ poorMans.actual = actual.diag();
607
+ throw poorMans;
608
+ }
609
+ /**
610
+ * @desc Returns string representation of the expression.
611
+ * Same as format() without options.
612
+ * @return {string}
613
+ */
614
+ toString() {
615
+ return this.format();
616
+ }
617
+ /**
618
+ * @desc Whether the expression needs parentheses when printed.
619
+ * @param {boolean} [first] - whether this is the first term in a sequence
620
+ * @return {boolean}
621
+ */
622
+ _braced(_first) {
623
+ return false;
624
+ }
625
+ /**
626
+ * @desc Whether the expression can be printed without a space when followed by arg.
627
+ * @param {Expr} arg
628
+ * @returns {boolean}
629
+ * @private
630
+ */
631
+ _unspaced(arg) {
632
+ return this._braced(true);
633
+ }
634
+ /**
635
+ * @desc Stringify the expression with fancy formatting options.
636
+ * Said options mostly include wrappers around various constructs in form of ['(', ')'],
637
+ * as well as terse and html flags that set up the defaults.
638
+ * Format without options is equivalent to toString() and can be parsed back.
639
+ *
640
+ * @param {Object} [options] - formatting options
641
+ * @param {boolean} [options.terse] - whether to use terse formatting (omitting unnecessary spaces and parentheses)
642
+ * @param {boolean} [options.html] - whether to default to HTML tags & entities.
643
+ * If a named term has fancyName property set, it will be used instead of name in this mode.
644
+ * @param {[string, string]} [options.brackets] - wrappers for application arguments, typically ['(', ')']
645
+ * @param {[string, string]} [options.var] - wrappers for variable names
646
+ * (will default to &lt;var&gt; and &lt;/var&gt; in html mode).
647
+ * @param {[string, string, string]} [options.lambda] - wrappers for lambda abstractions, e.g. ['&lambda;', '.', '']
648
+ * where the middle string is placed between argument and body
649
+ * default is ['', '->', ''] or ['', '-&gt;', ''] for html
650
+ * @param {[string, string]} [options.around] - wrappers around (sub-)expressions.
651
+ * individual applications will not be wrapped, i.e. (a b c) but not ((a b) c)
652
+ * @param {[string, string]} [options.redex] - wrappers around the starting term(s) that have enough arguments to be reduced
653
+ * @param {Object<string, Expr>} [options.inventory] - if given, output aliases in the set as their names
654
+ * and any other aliases as the expansion of their definitions.
655
+ * The default is a cryptic and fragile mechanism dependent on a hidden mutable property.
656
+ * @returns {string}
657
+ *
658
+ * @example foo.format() // equivalent to foo.toString()
659
+ * @example foo.format({terse: false}) // spell out all parentheses
660
+ * @example foo.format({html: true}) // use HTML tags and entities
661
+ * @example foo.format({ around: ['(', ')'], brackets: ['', ''], lambda: ['(', '->', ')'] }) // lisp style, still back-parsable
662
+ * @exapmle foo.format({ lambda: ['&lambda;', '.', ''] }) // pretty-print for the math department
663
+ * @example foo.format({ lambda: ['', '=>', ''], terse: false }) // make it javascript
664
+ * @example foo.format({ inventory: { T } }) // use T as a named term, expand all others
665
+ *
666
+ */
667
+ format(options = {}) {
668
+ const fallback = options.html ? {
669
+ brackets: ["(", ")"],
670
+ space: " ",
671
+ var: ["<var>", "</var>"],
672
+ lambda: ["", "-&gt;", ""],
673
+ around: ["", ""],
674
+ redex: ["", ""]
675
+ } : {
676
+ brackets: ["(", ")"],
677
+ space: " ",
678
+ var: ["", ""],
679
+ lambda: ["", "->", ""],
680
+ around: ["", ""],
681
+ redex: ["", ""]
956
682
  };
957
- FreeVar.global = ["global"];
958
- var Native = class extends Named {
959
- /**
960
- * @desc A named term with a known rewriting rule.
961
- * 'impl' is a function with signature Expr => Expr => ... => Expr
962
- * (see typedef Partial).
963
- * This is how S, K, I, and company are implemented.
964
- *
965
- * Note that as of current something like a=>b=>b(a) is not possible,
966
- * use full form instead: a=>b=>b.apply(a).
967
- *
968
- * @example new Native('K', x => y => x); // constant
969
- * @example new Native('Y', function(f) { return f.apply(this.apply(f)); }); // self-application
970
- *
971
- * @param {String} name
972
- * @param {Partial} impl
973
- * @param {{note?: string, arity?: number, canonize?: boolean }} [opt]
974
- */
975
- constructor(name, impl, opt = {}) {
976
- super(name);
977
- this.invoke = impl;
978
- this._setup({ canonize: true, ...opt });
979
- }
683
+ return this._format({
684
+ terse: options.terse ?? true,
685
+ brackets: options.brackets ?? fallback.brackets,
686
+ space: options.space ?? fallback.space,
687
+ var: options.var ?? fallback.var,
688
+ lambda: options.lambda ?? fallback.lambda,
689
+ around: options.around ?? fallback.around,
690
+ redex: options.redex ?? fallback.redex,
691
+ inventory: options.inventory,
692
+ // TODO better name
693
+ html: options.html ?? false
694
+ }, 0);
695
+ }
696
+ /**
697
+ * @desc Internal method for format(), which performs the actual formatting.
698
+ * @param {Object} options
699
+ * @param {number} nargs
700
+ * @returns {string}
701
+ * @private
702
+ */
703
+ _format(options, nargs) {
704
+ throw new Error("No _format() method defined in class " + this.constructor.name);
705
+ }
706
+ /**
707
+ * @desc Returns a string representation of the expression tree, with indentation to show structure.
708
+ *
709
+ * Applications are flattened to avoid excessive nesting.
710
+ * Variables include ids to distinguish different instances of the same variable name.
711
+ *
712
+ * May be useful for debugging.
713
+ *
714
+ * @returns {string}
715
+ *
716
+ * @example
717
+ * > console.log(ski.parse('C 5 x (x->x x)').diag())
718
+ * App:
719
+ * Native: C
720
+ * Church: 5
721
+ * FreeVar: x[53]
722
+ * Lambda (x[54]):
723
+ * App:
724
+ * FreeVar: x[54]
725
+ * FreeVar: x[54]
726
+ */
727
+ diag() {
728
+ const rec = (e, indent) => {
729
+ if (e instanceof App)
730
+ return [indent + "App:", ...e.unroll().flatMap((s) => rec(s, indent + " "))];
731
+ if (e instanceof Lambda)
732
+ return [`${indent}Lambda (${e.arg}[${e.arg.id}]):`, ...rec(e.impl, indent + " ")];
733
+ if (e instanceof Alias)
734
+ return [`${indent}Alias (${e.name}): \\`, ...rec(e.impl, indent)];
735
+ if (e instanceof FreeVar)
736
+ return [`${indent}FreeVar: ${e.name}[${e.id}]`];
737
+ return [`${indent}${e.constructor.name}: ${e}`];
980
738
  };
981
- var Lambda = class _Lambda extends Expr {
982
- /**
983
- * @desc Lambda abstraction of arg over impl.
984
- * Upon evaluation, all occurrences of 'arg' within 'impl' will be replaced
985
- * with the provided argument.
986
- *
987
- * Note that 'arg' will be replaced by a localized placeholder, so the original
988
- * variable can be used elsewhere without interference.
989
- * Listing symbols contained in the lambda will omit such placeholder.
990
- *
991
- * Legacy ([FreeVar], impl) constructor is supported but deprecated.
992
- * It will create a nested lambda expression.
993
- *
994
- * @param {FreeVar} arg
995
- * @param {Expr} impl
996
- */
997
- constructor(arg, impl) {
998
- if (Array.isArray(arg)) {
999
- if (arg.length === 0)
1000
- throw new Error("empty argument list in lambda constructor");
1001
- const [my, ...tail] = arg;
1002
- const known = /* @__PURE__ */ new Set([my.name]);
1003
- while (tail.length > 0) {
1004
- const last = tail.pop();
1005
- if (known.has(last.name))
1006
- throw new Error("Duplicate free var name " + last + " in lambda expression");
1007
- known.add(last.name);
1008
- impl = new _Lambda(last, impl);
1009
- }
1010
- arg = my;
1011
- }
1012
- super();
1013
- const local = new FreeVar(arg.name, this);
1014
- this.arg = local;
1015
- this.impl = impl.subst(arg, local) ?? impl;
1016
- this.arity = 1;
1017
- }
1018
- weight() {
1019
- return this.impl.weight() + 1;
1020
- }
1021
- invoke(arg) {
1022
- return this.impl.subst(this.arg, arg) ?? this.impl;
1023
- }
1024
- _traverse_descend(options, change) {
1025
- const [impl, iAction] = unwrap(this.impl._traverse_redo(options, change));
1026
- const final = impl ? new _Lambda(this.arg, impl) : null;
1027
- return iAction === control.stop ? control.stop(final) : final;
1028
- }
1029
- any(predicate) {
1030
- return predicate(this) || this.impl.any(predicate);
1031
- }
1032
- _fold(initial, combine) {
1033
- const [value = initial, action = "descend"] = unwrap(combine(initial, this));
1034
- if (action === control.prune)
1035
- return value;
1036
- if (action === control.stop)
1037
- return control.stop(value);
1038
- const [iValue, iAction] = unwrap(this.impl._fold(value, combine));
1039
- if (iAction === control.stop)
1040
- return control.stop(iValue);
1041
- return iValue ?? value;
1042
- }
1043
- subst(search, replace) {
1044
- if (search === this.arg)
1045
- return null;
1046
- const change = this.impl.subst(search, replace);
1047
- return change ? new _Lambda(this.arg, change) : null;
1048
- }
1049
- diff(other, swap = false) {
1050
- if (!(other instanceof _Lambda))
1051
- return super.diff(other, swap);
1052
- const t = new FreeVar("t");
1053
- const diff = this.invoke(t).diff(other.invoke(t), swap);
1054
- if (diff)
1055
- return "(t->" + diff + ")";
1056
- return null;
1057
- }
1058
- _format(options, nargs) {
1059
- return (nargs > 0 ? options.brackets[0] : "") + options.lambda[0] + this.arg._format(options, 0) + options.lambda[1] + this.impl._format(options, 0) + options.lambda[2] + (nargs > 0 ? options.brackets[1] : "");
1060
- }
1061
- _braced(first) {
1062
- return true;
1063
- }
739
+ const out = rec(this, "");
740
+ return out.join("\n");
741
+ }
742
+ /**
743
+ * @desc Convert the expression to a JSON-serializable format.
744
+ * @returns {string}
745
+ */
746
+ toJSON() {
747
+ return this.format();
748
+ }
749
+ };
750
+ var App = class _App extends Expr {
751
+ constructor(fun, arg) {
752
+ super();
753
+ this.arg = arg;
754
+ this.fun = fun;
755
+ }
756
+ /** @property {boolean} [final] */
757
+ _traverse_descend(options, change) {
758
+ const [fun, fAction] = unwrap(this.fun._traverse_redo(options, change));
759
+ if (fAction === control.stop)
760
+ return control.stop(fun ? fun.apply(this.arg) : null);
761
+ const [arg, aAction] = unwrap(this.arg._traverse_redo(options, change));
762
+ const final = fun || arg ? (fun ?? this.fun).apply(arg ?? this.arg) : null;
763
+ if (aAction === control.stop)
764
+ return control.stop(final);
765
+ return final;
766
+ }
767
+ any(predicate) {
768
+ return predicate(this) || this.fun.any(predicate) || this.arg.any(predicate);
769
+ }
770
+ _fold(initial, combine) {
771
+ const [value = initial, action = "descend"] = unwrap(combine(initial, this));
772
+ if (action === control.prune)
773
+ return value;
774
+ if (action === control.stop)
775
+ return control.stop(value);
776
+ const [fValue = value, fAction = "descend"] = unwrap(this.fun._fold(value, combine));
777
+ if (fAction === control.stop)
778
+ return control.stop(fValue);
779
+ const [aValue = fValue, aAction = "descend"] = unwrap(this.arg._fold(fValue, combine));
780
+ if (aAction === control.stop)
781
+ return control.stop(aValue);
782
+ return aValue;
783
+ }
784
+ subst(search2, replace) {
785
+ const fun = this.fun.subst(search2, replace);
786
+ const arg = this.arg.subst(search2, replace);
787
+ return fun || arg ? (fun ?? this.fun).apply(arg ?? this.arg) : null;
788
+ }
789
+ /**
790
+ * @return {{expr: Expr, steps: number}}
791
+ */
792
+ step() {
793
+ if (!this.final) {
794
+ const partial = this.fun.invoke(this.arg);
795
+ if (partial instanceof Expr)
796
+ return { expr: partial, steps: 1, changed: true };
797
+ else if (typeof partial === "function")
798
+ this.invoke = partial;
799
+ const fun = this.fun.step();
800
+ if (fun.changed)
801
+ return { expr: fun.expr.apply(this.arg), steps: fun.steps, changed: true };
802
+ const arg = this.arg.step();
803
+ if (arg.changed)
804
+ return { expr: this.fun.apply(arg.expr), steps: arg.steps, changed: true };
805
+ this.final = true;
806
+ }
807
+ return { expr: this, steps: 0, changed: false };
808
+ }
809
+ invoke(arg) {
810
+ const partial = this.fun.invoke(this.arg);
811
+ if (partial instanceof Expr)
812
+ return partial.apply(arg);
813
+ else if (typeof partial === "function") {
814
+ this.invoke = partial;
815
+ return partial(arg);
816
+ } else {
817
+ this.invoke = (arg2) => null;
818
+ return null;
819
+ }
820
+ }
821
+ unroll() {
822
+ return [...this.fun.unroll(), this.arg];
823
+ }
824
+ diff(other, swap = false) {
825
+ if (!(other instanceof _App))
826
+ return super.diff(other, swap);
827
+ const fun = this.fun.diff(other.fun, swap);
828
+ if (fun)
829
+ return fun + "(...)";
830
+ const arg = this.arg.diff(other.arg, swap);
831
+ if (arg)
832
+ return this.fun + "(" + arg + ")";
833
+ return null;
834
+ }
835
+ _braced(first) {
836
+ return !first;
837
+ }
838
+ _format(options, nargs) {
839
+ const fun = this.fun._format(options, nargs + 1);
840
+ const arg = this.arg._format(options, 0);
841
+ const wrap = nargs ? ["", ""] : options.around;
842
+ if (options.terse && !this.arg._braced(false))
843
+ return wrap[0] + fun + (this.fun._unspaced(this.arg) ? "" : options.space) + arg + wrap[1];
844
+ else
845
+ return wrap[0] + fun + options.brackets[0] + arg + options.brackets[1] + wrap[1];
846
+ }
847
+ _unspaced(arg) {
848
+ return this.arg._braced(false) ? true : this.arg._unspaced(arg);
849
+ }
850
+ };
851
+ var Named = class _Named extends Expr {
852
+ constructor(name) {
853
+ super();
854
+ if (typeof name !== "string" || name.length === 0)
855
+ throw new Error("Attempt to create a named term with improper name");
856
+ this.name = name;
857
+ }
858
+ _unspaced(arg) {
859
+ return !!(arg instanceof _Named && (this.name.match(/^[A-Z+]$/) && arg.name.match(/^[a-z+]/i) || this.name.match(/^[a-z+]/i) && arg.name.match(/^[A-Z+]$/)));
860
+ }
861
+ _format(options, nargs) {
862
+ const name = options.html ? this.fancyName ?? this.name : this.name;
863
+ return this.arity !== void 0 && this.arity > 0 && this.arity <= nargs ? options.redex[0] + name + options.redex[1] : name;
864
+ }
865
+ };
866
+ var freeId = 0;
867
+ var FreeVar = class _FreeVar extends Named {
868
+ constructor(name, scope) {
869
+ super(name);
870
+ this.id = ++freeId;
871
+ this.scope = scope === void 0 ? this : scope;
872
+ }
873
+ diff(other, swap = false) {
874
+ if (!(other instanceof _FreeVar))
875
+ return super.diff(other, swap);
876
+ if (this.name === other.name && this.scope === other.scope)
877
+ return null;
878
+ const lhs = this.name + "[" + this.id + "]";
879
+ const rhs = other.name + "[" + other.id + "]";
880
+ return swap ? "[" + rhs + " != " + lhs + "]" : "[" + lhs + " != " + rhs + "]";
881
+ }
882
+ subst(search2, replace) {
883
+ if (search2 instanceof _FreeVar && search2.name === this.name && search2.scope === this.scope)
884
+ return replace;
885
+ return null;
886
+ }
887
+ _format(options, nargs) {
888
+ const name = options.html ? this.fancyName ?? this.name : this.name;
889
+ return options.var[0] + name + options.var[1];
890
+ }
891
+ static {
892
+ this.global = ["global"];
893
+ }
894
+ };
895
+ var Native = class extends Named {
896
+ /**
897
+ * @desc A named term with a known rewriting rule.
898
+ * 'impl' is a function with signature Expr => Expr => ... => Expr
899
+ * (see typedef Partial).
900
+ * This is how S, K, I, and company are implemented.
901
+ *
902
+ * Note that as of current something like a=>b=>b(a) is not possible,
903
+ * use full form instead: a=>b=>b.apply(a).
904
+ *
905
+ * @example new Native('K', x => y => x); // constant
906
+ * @example new Native('Y', function(f) { return f.apply(this.apply(f)); }); // self-application
907
+ *
908
+ * @param {String} name
909
+ * @param {Partial} impl
910
+ * @param {{note?: string, arity?: number, canonize?: boolean }} [opt]
911
+ */
912
+ constructor(name, impl, opt = {}) {
913
+ super(name);
914
+ this.invoke = impl;
915
+ this._setup({ canonize: true, ...opt });
916
+ }
917
+ };
918
+ var Lambda = class _Lambda extends Expr {
919
+ constructor(arg, impl) {
920
+ super();
921
+ if (!(arg instanceof FreeVar))
922
+ throw new Error("Lambda argument must be a FreeVar");
923
+ const local = new FreeVar(arg.name, this);
924
+ this.arg = local;
925
+ this.impl = impl.subst(arg, local) ?? impl;
926
+ this.arity = 1;
927
+ }
928
+ invoke(arg) {
929
+ return this.impl.subst(this.arg, arg) ?? this.impl;
930
+ }
931
+ _traverse_descend(options, change) {
932
+ const [impl, iAction] = unwrap(this.impl._traverse_redo(options, change));
933
+ const final = impl ? new _Lambda(this.arg, impl) : null;
934
+ return iAction === control.stop ? control.stop(final) : final;
935
+ }
936
+ any(predicate) {
937
+ return predicate(this) || this.impl.any(predicate);
938
+ }
939
+ _fold(initial, combine) {
940
+ const [value = initial, action = "descend"] = unwrap(combine(initial, this));
941
+ if (action === control.prune)
942
+ return value;
943
+ if (action === control.stop)
944
+ return control.stop(value);
945
+ const [iValue, iAction] = unwrap(this.impl._fold(value, combine));
946
+ if (iAction === control.stop)
947
+ return control.stop(iValue);
948
+ return iValue ?? value;
949
+ }
950
+ subst(search2, replace) {
951
+ if (search2 === this.arg)
952
+ return null;
953
+ const change = this.impl.subst(search2, replace);
954
+ return change ? new _Lambda(this.arg, change) : null;
955
+ }
956
+ diff(other, swap = false) {
957
+ if (!(other instanceof _Lambda))
958
+ return super.diff(other, swap);
959
+ const t = new FreeVar("t");
960
+ const diff = this.invoke(t).diff(other.invoke(t), swap);
961
+ if (diff)
962
+ return "(t->" + diff + ")";
963
+ return null;
964
+ }
965
+ _format(options, nargs) {
966
+ return (nargs > 0 ? options.brackets[0] : "") + options.lambda[0] + this.arg._format(options, 0) + options.lambda[1] + this.impl._format(options, 0) + options.lambda[2] + (nargs > 0 ? options.brackets[1] : "");
967
+ }
968
+ _braced(first) {
969
+ return true;
970
+ }
971
+ };
972
+ var Church = class _Church extends Expr {
973
+ constructor(n) {
974
+ n = Number.parseInt(String(n));
975
+ if (!(n >= 0))
976
+ throw new Error("Church number must be a non-negative integer");
977
+ super();
978
+ this.invoke = (x) => (y) => {
979
+ let expr = y;
980
+ for (let i = n; i-- > 0; )
981
+ expr = x.apply(expr);
982
+ return expr;
1064
983
  };
1065
- var Church = class _Church extends Expr {
1066
- /**
1067
- * @desc Church numeral representing non-negative integer n:
1068
- * n f x = f(f(...(f x)...)) with f applied n times.
1069
- * @param {number} n
1070
- */
1071
- constructor(n) {
1072
- n = Number.parseInt(n);
1073
- if (!(n >= 0))
1074
- throw new Error("Church number must be a non-negative integer");
1075
- super();
1076
- this.invoke = (x) => (y) => {
1077
- let expr = y;
1078
- for (let i = n; i-- > 0; )
1079
- expr = x.apply(expr);
1080
- return expr;
1081
- };
1082
- this.n = n;
1083
- this.arity = 2;
1084
- }
1085
- diff(other, swap = false) {
1086
- if (!(other instanceof _Church))
1087
- return super.diff(other, swap);
1088
- if (this.n === other.n)
1089
- return null;
1090
- return swap ? "[" + other.n + " != " + this.n + "]" : "[" + this.n + " != " + other.n + "]";
1091
- }
1092
- _unspaced(arg) {
1093
- return false;
1094
- }
1095
- _format(options, nargs) {
1096
- return nargs >= 2 ? options.redex[0] + this.n + options.redex[1] : this.n + "";
984
+ this.n = n;
985
+ this.arity = 2;
986
+ }
987
+ diff(other, swap = false) {
988
+ if (!(other instanceof _Church))
989
+ return super.diff(other, swap);
990
+ if (this.n === other.n)
991
+ return null;
992
+ return swap ? "[" + other.n + " != " + this.n + "]" : "[" + this.n + " != " + other.n + "]";
993
+ }
994
+ _unspaced(arg) {
995
+ return false;
996
+ }
997
+ _format(options, nargs) {
998
+ return nargs >= 2 ? options.redex[0] + this.n + options.redex[1] : this.n + "";
999
+ }
1000
+ };
1001
+ function waitn(expr, n) {
1002
+ return (arg) => n <= 1 ? expr.apply(arg) : waitn(expr.apply(arg), n - 1);
1003
+ }
1004
+ var Alias = class extends Named {
1005
+ constructor(name, impl, options = {}) {
1006
+ super(name);
1007
+ if (!(impl instanceof Expr))
1008
+ throw new Error("Attempt to create an alias for a non-expression: " + impl);
1009
+ this.impl = impl;
1010
+ this._setup(options);
1011
+ this.terminal = options.terminal ?? this.props?.proper;
1012
+ this.invoke = waitn(impl, this.arity ?? 0);
1013
+ }
1014
+ /**
1015
+ * @property {boolean} [outdated] - whether the alias is outdated
1016
+ * and should be replaced with its definition when encountered.
1017
+ * @property {boolean} [terminal] - whether the alias should behave like a standalone term
1018
+ * // TODO better name?
1019
+ * @property {boolean} [proper] - whether the alias is a proper combinator (i.e. contains no free variables or constants)
1020
+ * @property {number} [arity] - the number of arguments the alias waits for before expanding
1021
+ * @property {Expr} [canonical] - equivalent lambda term.
1022
+ */
1023
+ _traverse_descend(options, change) {
1024
+ return this.impl._traverse_redo(options, change);
1025
+ }
1026
+ any(predicate) {
1027
+ return predicate(this) || this.impl.any(predicate);
1028
+ }
1029
+ _fold(initial, combine) {
1030
+ const [value = initial, action] = unwrap(combine(initial, this));
1031
+ if (action === control.prune)
1032
+ return value;
1033
+ if (action === control.stop)
1034
+ return control.stop(value);
1035
+ const [iValue, iAction] = unwrap(this.impl._fold(value, combine));
1036
+ if (iAction === control.stop)
1037
+ return control.stop(iValue);
1038
+ return iValue ?? value;
1039
+ }
1040
+ subst(search2, replace) {
1041
+ if (this === search2)
1042
+ return replace;
1043
+ return this.impl.subst(search2, replace);
1044
+ }
1045
+ // DO NOT REMOVE TYPE or tsc chokes with
1046
+ // TS2527: The inferred type of 'Alias' references an inaccessible 'this' type.
1047
+ /**
1048
+ * @return {{expr: Expr, steps: number, changed: boolean}}
1049
+ */
1050
+ step() {
1051
+ if ((this.arity ?? 0) > 0)
1052
+ return { expr: this, steps: 0, changed: false };
1053
+ return { expr: this.impl, steps: 0, changed: true };
1054
+ }
1055
+ diff(other, swap = false) {
1056
+ if (this === other)
1057
+ return null;
1058
+ return other.diff(this.impl, !swap);
1059
+ }
1060
+ _braced(first) {
1061
+ return this.outdated ? this.impl._braced(first) : false;
1062
+ }
1063
+ _format(options, nargs) {
1064
+ const outdated = options.inventory ? options.inventory[this.name] !== this : this.outdated;
1065
+ return outdated ? this.impl._format(options, nargs) : super._format(options, nargs);
1066
+ }
1067
+ };
1068
+ function addNative(name, impl, opt = {}) {
1069
+ native[name] = new Native(name, impl, opt);
1070
+ }
1071
+ addNative("I", (x) => x);
1072
+ addNative("K", (x) => (_y) => x);
1073
+ addNative("S", (x) => (y) => (z) => x.apply(z, y.apply(z)));
1074
+ addNative("B", (x) => (y) => (z) => x.apply(y.apply(z)));
1075
+ addNative("C", (x) => (y) => (z) => x.apply(z).apply(y));
1076
+ addNative("W", (x) => (y) => x.apply(y).apply(y));
1077
+ addNative(
1078
+ "+",
1079
+ (n) => n instanceof Church ? new Church(n.n + 1) : (f) => (x) => f.apply(n.apply(f, x)),
1080
+ {
1081
+ note: "Increase a Church numeral argument by 1, otherwise n => f => x => f(n f x)"
1082
+ }
1083
+ );
1084
+ function firstVar(expr) {
1085
+ while (expr instanceof App)
1086
+ expr = expr.fun;
1087
+ return expr instanceof FreeVar;
1088
+ }
1089
+ function maybeLambda(args, expr, caps) {
1090
+ const count = new Array(args.length).fill(0);
1091
+ let proper = true;
1092
+ expr.traverse((e) => {
1093
+ if (e instanceof FreeVar) {
1094
+ const index = args.findIndex((a) => a.name === e.name);
1095
+ if (index >= 0) {
1096
+ count[index]++;
1097
+ return;
1097
1098
  }
1098
- };
1099
- function waitn(expr, n) {
1100
- return (arg) => n <= 1 ? expr.apply(arg) : waitn(expr.apply(arg), n - 1);
1101
1099
  }
1102
- var Alias = class extends Named {
1103
- /**
1104
- * @desc A named alias for an existing expression.
1105
- *
1106
- * Upon evaluation, the alias expands into the original expression,
1107
- * unless it has a known arity > 0 and is marked terminal,
1108
- * in which case it waits for enough arguments before expanding.
1109
- *
1110
- * A hidden mutable property 'outdated' is used to silently
1111
- * replace the alias with its definition in all contexts.
1112
- * This is used when declaring named terms in an interpreter,
1113
- * to avoid confusion between old and new terms with the same name.
1114
- *
1115
- * @param {String} name
1116
- * @param {Expr} impl
1117
- * @param {{canonize?: boolean, max?: number, maxArgs?: number, note?: string, terminal?: boolean}} [options]
1118
- */
1119
- constructor(name, impl, options = {}) {
1120
- super(name);
1121
- if (!(impl instanceof Expr))
1122
- throw new Error("Attempt to create an alias for a non-expression: " + impl);
1123
- this.impl = impl;
1124
- this._setup(options);
1125
- this.terminal = options.terminal ?? this.props?.proper;
1126
- this.invoke = waitn(impl, this.arity ?? 0);
1127
- }
1128
- /**
1129
- * @property {boolean} [outdated] - whether the alias is outdated
1130
- * and should be replaced with its definition when encountered.
1131
- * @property {boolean} [terminal] - whether the alias should behave like a standalone term
1132
- * // TODO better name?
1133
- * @property {boolean} [proper] - whether the alias is a proper combinator (i.e. contains no free variables or constants)
1134
- * @property {number} [arity] - the number of arguments the alias waits for before expanding
1135
- * @property {Expr} [canonical] - equivalent lambda term.
1136
- */
1137
- weight() {
1138
- return this.terminal ? 1 : this.impl.weight();
1139
- }
1140
- _traverse_descend(options, change) {
1141
- return this.impl._traverse_redo(options, change);
1142
- }
1143
- any(predicate) {
1144
- return predicate(this) || this.impl.any(predicate);
1145
- }
1146
- _fold(initial, combine) {
1147
- const [value = initial, action] = unwrap(combine(initial, this));
1148
- if (action === control.prune)
1149
- return value;
1150
- if (action === control.stop)
1151
- return control.stop(value);
1152
- const [iValue, iAction] = unwrap(this.impl._fold(value, combine));
1153
- if (iAction === control.stop)
1154
- return control.stop(iValue);
1155
- return iValue ?? value;
1156
- }
1157
- subst(search, replace) {
1158
- if (this === search)
1159
- return replace;
1160
- return this.impl.subst(search, replace);
1161
- }
1162
- // DO NOT REMOVE TYPE or tsc chokes with
1163
- // TS2527: The inferred type of 'Alias' references an inaccessible 'this' type.
1164
- /**
1165
- * @return {{expr: Expr, steps: number, changed: boolean}}
1166
- */
1167
- step() {
1168
- if (this.arity > 0)
1169
- return { expr: this, steps: 0, changed: false };
1170
- return { expr: this.impl, steps: 0, changed: true };
1171
- }
1172
- diff(other, swap = false) {
1173
- if (this === other)
1174
- return null;
1175
- return other.diff(this.impl, !swap);
1176
- }
1177
- _braced(first) {
1178
- return this.outdated ? this.impl._braced(first) : false;
1179
- }
1180
- _format(options, nargs) {
1181
- const outdated = options.inventory ? options.inventory[this.name] !== this : this.outdated;
1182
- return outdated ? this.impl._format(options, nargs) : super._format(options, nargs);
1183
- }
1184
- };
1185
- function addNative(name, impl, opt) {
1186
- native[name] = new Native(name, impl, opt);
1100
+ if (!(e instanceof App))
1101
+ proper = false;
1102
+ return void 0;
1103
+ });
1104
+ const skip = /* @__PURE__ */ new Set();
1105
+ const dup = /* @__PURE__ */ new Set();
1106
+ for (let i = 0; i < args.length; i++) {
1107
+ if (count[i] === 0)
1108
+ skip.add(i);
1109
+ else if (count[i] > 1)
1110
+ dup.add(i);
1111
+ }
1112
+ for (let i = args.length; i-- > 0; )
1113
+ expr = new Lambda(args[i], expr);
1114
+ return {
1115
+ normal: true,
1116
+ steps: caps.steps,
1117
+ expr,
1118
+ arity: args.length,
1119
+ ...skip.size ? { skip } : {},
1120
+ ...dup.size ? { dup } : {},
1121
+ duplicate: !!dup.size || caps.duplicate || false,
1122
+ discard: !!skip.size || caps.discard || false,
1123
+ proper
1124
+ };
1125
+ }
1126
+ function nthvar(n) {
1127
+ return new FreeVar("abcdefgh"[n] ?? "x" + n);
1128
+ }
1129
+ var classes = { Expr, App, Named, FreeVar, Native, Lambda, Church, Alias };
1130
+
1131
+ // src/toposort.ts
1132
+ function toposort(list, env) {
1133
+ if (list instanceof Expr)
1134
+ list = [list];
1135
+ if (env) {
1136
+ if (!list)
1137
+ list = Object.keys(env).sort().map((k) => env[k]);
1138
+ } else {
1139
+ if (!list)
1140
+ return { list: [], env: {} };
1141
+ env = {};
1142
+ for (const item of list) {
1143
+ if (!(item instanceof Named))
1144
+ continue;
1145
+ if (env[item.name])
1146
+ throw new Error("duplicate name " + item);
1147
+ env[item.name] = item;
1187
1148
  }
1188
- addNative("I", (x) => x);
1189
- addNative("K", (x) => (_) => x);
1190
- addNative("S", (x) => (y) => (z) => x.apply(z, y.apply(z)));
1191
- addNative("B", (x) => (y) => (z) => x.apply(y.apply(z)));
1192
- addNative("C", (x) => (y) => (z) => x.apply(z).apply(y));
1193
- addNative("W", (x) => (y) => x.apply(y).apply(y));
1194
- addNative(
1195
- "+",
1196
- (n) => n instanceof Church ? new Church(n.n + 1) : (f) => (x) => f.apply(n.apply(f, x)),
1197
- {
1198
- note: "Increase a Church numeral argument by 1, otherwise n => f => x => f(n f x)"
1149
+ }
1150
+ const out = [];
1151
+ const seen = /* @__PURE__ */ new Set();
1152
+ const rec = (term) => {
1153
+ if (seen.has(term))
1154
+ return;
1155
+ term.fold(false, (acc, e) => {
1156
+ if (e !== term && e instanceof Named && env[e.name] === e) {
1157
+ rec(e);
1158
+ return control.prune(false);
1159
+ }
1160
+ });
1161
+ out.push(term);
1162
+ seen.add(term);
1163
+ };
1164
+ for (const term of list)
1165
+ rec(term);
1166
+ return {
1167
+ list: out,
1168
+ env
1169
+ };
1170
+ }
1171
+
1172
+ // src/parser.ts
1173
+ var Empty = class extends Expr {
1174
+ apply(...args) {
1175
+ return args.length > 0 ? args.shift().apply(...args) : this;
1176
+ }
1177
+ postParse() {
1178
+ throw new Error("Attempt to use empty expression () as a term");
1179
+ }
1180
+ };
1181
+ var PartialLambda = class _PartialLambda extends Empty {
1182
+ // TODO mutable! rewrite ro when have time
1183
+ constructor(term, _known = {}) {
1184
+ super();
1185
+ this.impl = new Empty();
1186
+ if (term instanceof FreeVar)
1187
+ this.terms = [term];
1188
+ else if (term instanceof _PartialLambda) {
1189
+ if (!(term.impl instanceof FreeVar))
1190
+ throw new Error("Expected FreeVar->...->FreeVar->Expr");
1191
+ this.terms = [...term.terms, term.impl];
1192
+ } else
1193
+ throw new Error("Expected FreeVar or PartialLambda");
1194
+ }
1195
+ apply(term, ...tail) {
1196
+ if (term === null || tail.length !== 0)
1197
+ throw new Error("bad syntax in partial lambda expr");
1198
+ this.impl = this.impl.apply(term);
1199
+ return this;
1200
+ }
1201
+ postParse() {
1202
+ let expr = this.impl;
1203
+ for (let i = this.terms.length; i-- > 0; )
1204
+ expr = new Lambda(this.terms[i], expr);
1205
+ return expr;
1206
+ }
1207
+ // uncomment if debugging with prints
1208
+ /* toString () {
1209
+ return this.terms.join('->') + '->' + (this.impl ?? '???');
1210
+ } */
1211
+ };
1212
+ function postParse(expr) {
1213
+ return expr.postParse ? expr.postParse() : expr;
1214
+ }
1215
+ var combChars = new Tokenizer(
1216
+ "[()]",
1217
+ "[A-Z]",
1218
+ "[a-z_][a-z_0-9]*",
1219
+ "\\b[0-9]+\\b",
1220
+ "->",
1221
+ "\\+"
1222
+ );
1223
+ var Parser = class {
1224
+ constructor(options = {}) {
1225
+ this.annotate = !!options.annotate;
1226
+ this.known = { ...native };
1227
+ this.hasNumbers = true;
1228
+ this.hasLambdas = true;
1229
+ this.allow = new Set(Object.keys(this.known));
1230
+ if (Array.isArray(options.terms))
1231
+ this.bulkAdd(options.terms);
1232
+ else if (options.terms) {
1233
+ for (const name in options.terms) {
1234
+ if (typeof options.terms[name] !== "string" || !options.terms[name].match(/^Native:/))
1235
+ this.add(name, options.terms[name]);
1199
1236
  }
1200
- );
1201
- function firstVar(expr) {
1202
- while (expr instanceof App)
1203
- expr = expr.fun;
1204
- return expr instanceof FreeVar;
1205
1237
  }
1206
- function maybeLambda(args, expr, caps = {}) {
1207
- const count = new Array(args.length).fill(0);
1208
- let proper = true;
1209
- expr.traverse((e) => {
1210
- if (e instanceof FreeVar) {
1211
- const index = args.findIndex((a) => a.name === e.name);
1212
- if (index >= 0) {
1213
- count[index]++;
1214
- return;
1215
- }
1216
- }
1217
- if (!(e instanceof App))
1218
- proper = false;
1219
- });
1220
- const skip = /* @__PURE__ */ new Set();
1221
- const dup = /* @__PURE__ */ new Set();
1222
- for (let i = 0; i < args.length; i++) {
1223
- if (count[i] === 0)
1224
- skip.add(i);
1225
- else if (count[i] > 1)
1226
- dup.add(i);
1227
- }
1228
- return {
1229
- normal: true,
1230
- steps: caps.steps,
1231
- expr: args.length ? new Lambda(args, expr) : expr,
1232
- arity: args.length,
1233
- ...skip.size ? { skip } : {},
1234
- ...dup.size ? { dup } : {},
1235
- duplicate: !!dup.size || caps.duplicate || false,
1236
- discard: !!skip.size || caps.discard || false,
1237
- proper
1238
- };
1238
+ this.hasNumbers = options.numbers ?? true;
1239
+ this.hasLambdas = options.lambdas ?? true;
1240
+ if (options.allow)
1241
+ this.restrict(options.allow);
1242
+ }
1243
+ /**
1244
+ * @desc Declare a new term
1245
+ * If the first argument is an Alias, it is added as is.
1246
+ * Otherwise, a new Alias or Native term (depending on impl type) is created.
1247
+ * If note is not provided and this.annotate is true, an automatic note is generated.
1248
+ *
1249
+ * If impl is a function, it should have signature (Expr) => ... => Expr
1250
+ * (see typedef Partial at top of expr.js)
1251
+ *
1252
+ * @example ski.add('T', 'S(K(SI))K', 'swap combinator')
1253
+ * @example ski.add( ski.parse('T = S(K(SI))K') ) // ditto but one-arg form
1254
+ * @example ski.add('T', x => y => y.apply(x), 'swap combinator') // heavy artillery
1255
+ * @example ski.add('Y', function (f) { return f.apply(this.apply(f)); }, 'Y combinator')
1256
+ *
1257
+ * @param {Alias|String} term
1258
+ * @param {String|Expr|function(Expr):Partial} [impl]
1259
+ * @param {object|string} [options]
1260
+ * @param {string} [options.note] - optional annotation for the term, default is auto-generated if this.annotate is true
1261
+ * @param {boolean} [options.canonize] - whether to canonize the term's implementation, default is this.annotate
1262
+ * @param {boolean} [options.fancy] - alternative HTML-friendly name for the term
1263
+ * @param {number} [options.arity] - custom arity for the term, default is inferred from the implementation
1264
+ * @return {SKI} chainable
1265
+ */
1266
+ add(term, impl, options) {
1267
+ const named = this._named(term, impl);
1268
+ const opts = typeof options === "string" ? { note: options, canonize: false } : options ?? {};
1269
+ named._setup({ canonize: this.annotate, ...opts });
1270
+ if (this.known[named.name])
1271
+ this.known[named.name].outdated = true;
1272
+ this.known[named.name] = named;
1273
+ this.allow.add(named.name);
1274
+ return this;
1275
+ }
1276
+ /**
1277
+ * @desc Internal helper for add() that creates an Alias or Native term from the given arguments.
1278
+ * @param {Alias|string} term
1279
+ * @param {string|Expr|function(Expr):Partial} impl
1280
+ * @returns {Native|Alias}
1281
+ * @private
1282
+ */
1283
+ _named(term, impl) {
1284
+ if (term instanceof Alias)
1285
+ return new Alias(term.name, term.impl, { canonize: true });
1286
+ if (typeof term !== "string")
1287
+ throw new Error("add(): term must be an Alias or a string");
1288
+ if (impl === void 0)
1289
+ throw new Error("add(): impl must be provided when term is a string");
1290
+ if (typeof impl === "string")
1291
+ return new Alias(term, this.parse(impl), { canonize: true });
1292
+ if (impl instanceof Expr)
1293
+ return new Alias(term, impl, { canonize: true });
1294
+ if (typeof impl === "function")
1295
+ return new Native(term, impl);
1296
+ throw new Error("add(): impl must be an Expr, a string, or a function with a signature Expr => ... => Expr");
1297
+ }
1298
+ /**
1299
+ * @desc Declare a new term if it is not known, otherwise just allow it.
1300
+ * Currently only used by quests.
1301
+ * Use with caution, this function may change its signature, behavior, or even be removed in the future.
1302
+ *
1303
+ * @experimental
1304
+ * @param {string|Alias} name
1305
+ * @param {string|Expr|function(Expr):Partial} impl
1306
+ * @returns {SKI}
1307
+ */
1308
+ maybeAdd(name, impl) {
1309
+ if (this.known[name])
1310
+ this.allow.add(name);
1311
+ else
1312
+ this.add(name, impl);
1313
+ return this;
1314
+ }
1315
+ /**
1316
+ * @desc Declare and remove multiple terms at once
1317
+ * term=impl adds term
1318
+ * term= removes term
1319
+ * @param {string[]} list
1320
+ * @return {SKI} chainable
1321
+ */
1322
+ bulkAdd(list) {
1323
+ for (const item of list) {
1324
+ const m = item.match(/^([A-Z]|[a-z][a-z_0-9]*)\s*=\s*(.*)$/s);
1325
+ if (!m)
1326
+ throw new Error("bulkAdd: invalid declaration: " + item);
1327
+ if (m[2] === "")
1328
+ this.remove(m[1]);
1329
+ else
1330
+ this.add(m[1], this.parse(m[2]));
1239
1331
  }
1240
- function nthvar(n) {
1241
- return new FreeVar("abcdefgh"[n] ?? "x" + n);
1332
+ return this;
1333
+ }
1334
+ /**
1335
+ * Restrict the interpreter to given terms. Terms prepended with '+' will be added
1336
+ * and terms preceeded with '-' will be removed.
1337
+ * @example ski.restrict('SK') // use the basis
1338
+ * @example ski.restrict('+I') // allow I now
1339
+ * @example ski.restrict('-SKI +BCKW' ); // switch basis
1340
+ * @example ski.restrict('-foo -bar'); // forbid some user functions
1341
+ * @param {string} spec
1342
+ * @return {SKI} chainable
1343
+ */
1344
+ restrict(spec) {
1345
+ this.allow = restrict(this.allow, spec);
1346
+ return this;
1347
+ }
1348
+ /**
1349
+ *
1350
+ * @param {string} spec
1351
+ * @return {string}
1352
+ */
1353
+ showRestrict(spec = "+") {
1354
+ const out = [];
1355
+ let prevShort = true;
1356
+ for (const term of [...restrict(this.allow, spec)].sort()) {
1357
+ const nextShort = !!term.match(/^[A-Z]$/);
1358
+ if (out.length && !(prevShort && nextShort))
1359
+ out.push(" ");
1360
+ out.push(term);
1361
+ prevShort = nextShort;
1242
1362
  }
1243
- function toposort(list, env) {
1244
- if (list instanceof Expr)
1245
- list = [list];
1246
- if (env) {
1247
- if (!list)
1248
- list = Object.keys(env).sort().map((k) => env[k]);
1249
- } else {
1250
- if (!list)
1251
- return [];
1252
- if (!env) {
1253
- env = {};
1254
- for (const item of list) {
1255
- if (!(item instanceof Named))
1256
- continue;
1257
- if (env[item.name])
1258
- throw new Error("duplicate name " + item);
1259
- env[item.name] = item;
1260
- }
1261
- }
1262
- }
1263
- const out = [];
1264
- const seen = /* @__PURE__ */ new Set();
1265
- const rec = (term) => {
1266
- if (seen.has(term))
1267
- return;
1268
- term.fold(null, (acc, e) => {
1269
- if (e !== term && e instanceof Named && env[e.name] === e) {
1270
- rec(e);
1271
- return Expr.control.prune(null);
1272
- }
1273
- });
1274
- out.push(term);
1275
- seen.add(term);
1276
- };
1277
- for (const term of list)
1278
- rec(term);
1279
- return {
1280
- list: out,
1281
- env
1282
- };
1363
+ return out.join("");
1364
+ }
1365
+ /**
1366
+ *
1367
+ * @param {String} name
1368
+ * @return {SKI}
1369
+ */
1370
+ remove(name) {
1371
+ this.known[name].outdated = true;
1372
+ delete this.known[name];
1373
+ this.allow.delete(name);
1374
+ return this;
1375
+ }
1376
+ /**
1377
+ *
1378
+ * @return {{[key:string]: Native|Alias}}
1379
+ */
1380
+ getTerms() {
1381
+ const out = {};
1382
+ for (const name of Object.keys(this.known)) {
1383
+ if (this.allow.has(name))
1384
+ out[name] = this.known[name];
1283
1385
  }
1284
- Expr.native = native;
1285
- Expr.control = control;
1286
- Expr.extras = { toposort };
1287
- module.exports = { Expr, App, Named, FreeVar, Lambda, Native, Alias, Church };
1386
+ return out;
1288
1387
  }
1289
- });
1290
-
1291
- // src/parser.js
1292
- var require_parser = __commonJS({
1293
- "src/parser.js"(exports, module) {
1294
- "use strict";
1295
- var { Tokenizer, restrict } = require_internal();
1296
- var classes = require_expr();
1297
- var { Expr, Named, Native, Alias, FreeVar, Lambda, Church } = classes;
1298
- var { native } = Expr;
1299
- var Empty = class extends Expr {
1300
- apply(...args) {
1301
- return args.length ? args.shift().apply(...args) : this;
1302
- }
1303
- postParse() {
1304
- throw new Error("Attempt to use empty expression () as a term");
1305
- }
1306
- };
1307
- var PartialLambda = class _PartialLambda extends Empty {
1308
- // TODO mutable! rewrite ro when have time
1309
- constructor(term, known = {}) {
1310
- super();
1311
- this.impl = new Empty();
1312
- if (term instanceof FreeVar)
1313
- this.terms = [term];
1314
- else if (term instanceof _PartialLambda) {
1315
- if (!(term.impl instanceof FreeVar))
1316
- throw new Error("Expected FreeVar->...->FreeVar->Expr");
1317
- this.terms = [...term.terms, term.impl];
1318
- } else
1319
- throw new Error("Expected FreeVar or PartialLambda");
1320
- }
1321
- apply(term, ...tail) {
1322
- if (term === null || tail.length !== 0)
1323
- throw new Error("bad syntax in partial lambda expr");
1324
- this.impl = this.impl.apply(term);
1325
- return this;
1326
- }
1327
- postParse() {
1328
- return new Lambda(this.terms, this.impl);
1329
- }
1330
- // uncomment if debugging with prints
1331
- /* toString () {
1332
- return this.terms.join('->') + '->' + (this.impl ?? '???');
1333
- } */
1334
- };
1335
- function postParse(expr) {
1336
- return expr.postParse ? expr.postParse() : expr;
1388
+ /**
1389
+ * @desc Export term declarations for use in bulkAdd().
1390
+ * Currently only Alias terms are serialized.
1391
+ * @returns {string[]}
1392
+ */
1393
+ declare() {
1394
+ const env = {};
1395
+ for (const [name, term] of Object.entries(this.getTerms())) {
1396
+ if (term instanceof Alias)
1397
+ env[name] = term;
1337
1398
  }
1338
- var combChars = new Tokenizer(
1339
- "[()]",
1340
- "[A-Z]",
1341
- "[a-z_][a-z_0-9]*",
1342
- "\\b[0-9]+\\b",
1343
- "->",
1344
- "\\+"
1345
- );
1346
- var SKI = class {
1347
- /**
1348
- *
1349
- * @param {{
1350
- * allow?: string,
1351
- * numbers?: boolean,
1352
- * lambdas?: boolean,
1353
- * terms?: { [key: string]: Expr|string} | string[],
1354
- * annotate?: boolean,
1355
- * }} [options]
1356
- */
1357
- constructor(options = {}) {
1358
- this.annotate = options.annotate ?? false;
1359
- this.known = { ...native };
1360
- this.hasNumbers = true;
1361
- this.hasLambdas = true;
1362
- this.allow = new Set(Object.keys(this.known));
1363
- if (Array.isArray(options.terms))
1364
- this.bulkAdd(options.terms);
1365
- else if (options.terms) {
1366
- for (const name in options.terms) {
1367
- if (!options.terms[name].match(/^Native:/))
1368
- this.add(name, options.terms[name]);
1369
- }
1370
- }
1371
- this.hasNumbers = options.numbers ?? true;
1372
- this.hasLambdas = options.lambdas ?? true;
1373
- if (options.allow)
1374
- this.restrict(options.allow);
1375
- }
1376
- /**
1377
- * @desc Declare a new term
1378
- * If the first argument is an Alias, it is added as is.
1379
- * Otherwise, a new Alias or Native term (depending on impl type) is created.
1380
- * If note is not provided and this.annotate is true, an automatic note is generated.
1381
- *
1382
- * If impl is a function, it should have signature (Expr) => ... => Expr
1383
- * (see typedef Partial at top of expr.js)
1384
- *
1385
- * @example ski.add('T', 'S(K(SI))K', 'swap combinator')
1386
- * @example ski.add( ski.parse('T = S(K(SI))K') ) // ditto but one-arg form
1387
- * @example ski.add('T', x => y => y.apply(x), 'swap combinator') // heavy artillery
1388
- * @example ski.add('Y', function (f) { return f.apply(this.apply(f)); }, 'Y combinator')
1389
- *
1390
- * @param {Alias|String} term
1391
- * @param {String|Expr|function(Expr):Partial} [impl]
1392
- * @param {object|string} [options]
1393
- * @param {string} [options.note] - optional annotation for the term, default is auto-generated if this.annotate is true
1394
- * @param {boolean} [options.canonize] - whether to canonize the term's implementation, default is this.annotate
1395
- * @param {boolean} [options.fancy] - alternative HTML-friendly name for the term
1396
- * @param {number} [options.arity] - custom arity for the term, default is inferred from the implementation
1397
- * @return {SKI} chainable
1398
- */
1399
- add(term, impl, options) {
1400
- term = this._named(term, impl);
1401
- if (typeof options === "string")
1402
- options = { note: options, canonize: false };
1403
- term._setup({ canonize: this.annotate, ...options });
1404
- if (this.known[term.name])
1405
- this.known[term.name].outdated = true;
1406
- this.known[term.name] = term;
1407
- this.allow.add(term.name);
1408
- return this;
1409
- }
1410
- /**
1411
- * @desc Internal helper for add() that creates an Alias or Native term from the given arguments.
1412
- * @param {Alias|string} term
1413
- * @param {string|Expr|function(Expr):Partial} impl
1414
- * @returns {Native|Alias}
1415
- * @private
1416
- */
1417
- _named(term, impl) {
1418
- if (term instanceof Alias)
1419
- return new Alias(term.name, term.impl, { canonize: true });
1420
- if (typeof term !== "string")
1421
- throw new Error("add(): term must be an Alias or a string");
1422
- if (impl === void 0)
1423
- throw new Error("add(): impl must be provided when term is a string");
1424
- if (typeof impl === "string")
1425
- return new Alias(term, this.parse(impl), { canonize: true });
1426
- if (impl instanceof Expr)
1427
- return new Alias(term, impl, { canonize: true });
1428
- if (typeof impl === "function")
1429
- return new Native(term, impl);
1430
- throw new Error("add(): impl must be an Expr, a string, or a function with a signature Expr => ... => Expr");
1431
- }
1432
- /**
1433
- * @desc Declare a new term if it is not known, otherwise just allow it.
1434
- * Currently only used by quests.
1435
- * Use with caution, this function may change its signature, behavior, or even be removed in the future.
1436
- *
1437
- * @experimental
1438
- * @param {string|Alias} name
1439
- * @param {string|Expr|function(Expr):Partial} impl
1440
- * @returns {SKI}
1441
- */
1442
- maybeAdd(name, impl) {
1443
- if (this.known[name])
1444
- this.allow.add(name);
1445
- else
1446
- this.add(name, impl);
1447
- return this;
1448
- }
1449
- /**
1450
- * @desc Declare and remove multiple terms at once
1451
- * term=impl adds term
1452
- * term= removes term
1453
- * @param {string[]} list
1454
- * @return {SKI} chainable
1455
- */
1456
- bulkAdd(list) {
1457
- for (const item of list) {
1458
- const m = item.match(/^([A-Z]|[a-z][a-z_0-9]*)\s*=\s*(.*)$/s);
1459
- if (!m)
1460
- throw new Error("bulkAdd: invalid declaration: " + item);
1461
- if (m[2] === "")
1462
- this.remove(m[1]);
1463
- else
1464
- this.add(m[1], this.parse(m[2]));
1465
- }
1466
- return this;
1467
- }
1468
- /**
1469
- * Restrict the interpreter to given terms. Terms prepended with '+' will be added
1470
- * and terms preceeded with '-' will be removed.
1471
- * @example ski.restrict('SK') // use the basis
1472
- * @example ski.restrict('+I') // allow I now
1473
- * @example ski.restrict('-SKI +BCKW' ); // switch basis
1474
- * @example ski.restrict('-foo -bar'); // forbid some user functions
1475
- * @param {string} spec
1476
- * @return {SKI} chainable
1477
- */
1478
- restrict(spec) {
1479
- this.allow = restrict(this.allow, spec);
1480
- return this;
1481
- }
1482
- /**
1483
- *
1484
- * @param {string} spec
1485
- * @return {string}
1486
- */
1487
- showRestrict(spec = "+") {
1488
- const out = [];
1489
- let prevShort = true;
1490
- for (const term of [...restrict(this.allow, spec)].sort()) {
1491
- const nextShort = term.match(/^[A-Z]$/);
1492
- if (out.length && !(prevShort && nextShort))
1493
- out.push(" ");
1494
- out.push(term);
1495
- prevShort = nextShort;
1496
- }
1497
- return out.join("");
1498
- }
1499
- /**
1500
- *
1501
- * @param {String} name
1502
- * @return {SKI}
1503
- */
1504
- remove(name) {
1505
- this.known[name].outdated = true;
1506
- delete this.known[name];
1507
- this.allow.delete(name);
1508
- return this;
1509
- }
1510
- /**
1511
- *
1512
- * @return {{[key:string]: Native|Alias}}
1513
- */
1514
- getTerms() {
1515
- const out = {};
1516
- for (const name of Object.keys(this.known)) {
1517
- if (this.allow.has(name))
1518
- out[name] = this.known[name];
1519
- }
1520
- return out;
1521
- }
1522
- /**
1523
- * @desc Export term declarations for use in bulkAdd().
1524
- * Currently only Alias terms are serialized.
1525
- * @returns {string[]}
1526
- */
1527
- declare() {
1528
- const env = this.getTerms();
1529
- for (const name in env) {
1530
- if (!(env[name] instanceof Alias))
1531
- delete env[name];
1532
- }
1533
- const needDetour = {};
1534
- let i = 1;
1535
- for (const name in native) {
1536
- if (!(env[name] instanceof Alias))
1537
- continue;
1538
- while ("tmp" + i in env)
1539
- i++;
1540
- const temp = new Alias("tmp" + i, env[name]);
1541
- needDetour[temp] = env[name];
1542
- env[temp] = temp;
1543
- delete env[name];
1544
- }
1545
- const list = Expr.extras.toposort(void 0, env).list;
1546
- const detour = /* @__PURE__ */ new Map();
1547
- if (Object.keys(needDetour).length) {
1548
- const rework = (expr) => {
1549
- return expr.traverse((e) => {
1550
- if (!(e instanceof Alias))
1551
- return null;
1552
- const newAlias = detour.get(e);
1553
- if (newAlias)
1554
- return newAlias;
1555
- return new Alias(e.name, rework(e.impl));
1556
- }) ?? expr;
1557
- };
1558
- for (let i2 = 0; i2 < list.length; i2++) {
1559
- list[i2] = rework(list[i2], detour);
1560
- detour.set(needDetour[list[i2].name], list[i2]);
1561
- env[list[i2].name] = list[i2];
1562
- console.log(`list[${i2}] = ${list[i2].name}=${list[i2].impl};`);
1563
- }
1564
- console.log("detour:", detour);
1565
- }
1566
- const out = list.map(
1567
- (e) => needDetour[e] ? e.name + "=" + needDetour[e].name + "=" + e.impl.format({ inventory: env }) : e.name + "=" + e.impl.format({ inventory: env })
1568
- );
1569
- for (const [name, temp] of detour)
1570
- out.push(name + "=" + temp, temp + "=");
1571
- return out;
1572
- }
1573
- /**
1574
- * @template T
1575
- * @param {string} source
1576
- * @param {Object} [options]
1577
- * @param {{[keys: string]: Expr}} [options.env]
1578
- * @param {T} [options.scope]
1579
- * @param {boolean} [options.numbers]
1580
- * @param {boolean} [options.lambdas]
1581
- * @param {string} [options.allow]
1582
- * @return {Expr}
1583
- */
1584
- parse(source, options = {}) {
1585
- if (typeof source !== "string")
1586
- throw new Error("parse: source must be a string, got " + typeof source);
1587
- const lines = source.replace(/\/\/[^\n]*$/gm, " ").replace(/\/\*.*?\*\//gs, " ").trim().split(/\s*;[\s;]*/).filter((s) => s.match(/\S/));
1588
- const jar = { ...options.env };
1589
- let expr = new Empty();
1590
- for (const item of lines) {
1591
- if (expr instanceof Alias)
1592
- expr.outdated = true;
1593
- const def = item.match(/^([A-Z]|[a-z][a-z_0-9]*)\s*=(.*)$/s);
1594
- if (def && def[2] === "")
1595
- expr = new FreeVar(def[1], options.scope ?? FreeVar.global);
1596
- else
1597
- expr = this.parseLine(item, jar, options);
1598
- if (def) {
1599
- if (jar[def[1]] !== void 0)
1600
- throw new Error("Attempt to redefine a known term: " + def[1]);
1601
- jar[def[1]] = expr;
1602
- }
1603
- }
1604
- expr.context = {
1605
- env: { ...this.getTerms(), ...jar },
1606
- // also contains pre-parsed terms
1607
- scope: options.scope,
1608
- src: source,
1609
- parser: this
1610
- };
1611
- return expr;
1612
- }
1613
- /**
1614
- * @desc Parse a single line of source code, without splitting it into declarations.
1615
- * Internal, always use parse() instead.
1616
- * @template T
1617
- * @param {String} source S(KI)I
1618
- * @param {{[keys: string]: Expr}} env
1619
- * @param {Object} [options]
1620
- * @param {{[keys: string]: Expr}} [options.env] - unused, see 'env' argument
1621
- * @param {T} [options.scope]
1622
- * @param {boolean} [options.numbers]
1623
- * @param {boolean} [options.lambdas]
1624
- * @param {string} [options.allow]
1625
- * @return {Expr} parsed expression
1626
- */
1627
- parseLine(source, env = {}, options = {}) {
1628
- const aliased = source.match(/^\s*([A-Z]|[a-z][a-z_0-9]*)\s*=\s*(.*)$/s);
1629
- if (aliased)
1630
- return new Alias(aliased[1], this.parseLine(aliased[2], env, options));
1631
- const opt = {
1632
- numbers: options.numbers ?? this.hasNumbers,
1633
- lambdas: options.lambdas ?? this.hasLambdas,
1634
- allow: restrict(this.allow, options.allow)
1635
- };
1636
- opt.numbers ? opt.allow.add("+") : opt.allow.delete("+");
1637
- const tokens = combChars.split(source);
1638
- const empty = new Empty();
1639
- const stack = [empty];
1640
- const context = options.scope || FreeVar.global;
1641
- for (const c of tokens) {
1642
- if (c === "(")
1643
- stack.push(empty);
1644
- else if (c === ")") {
1645
- if (stack.length < 2)
1646
- throw new Error("unbalanced input: extra closing parenthesis" + source);
1647
- const x = postParse(stack.pop());
1648
- const f = stack.pop();
1649
- stack.push(f.apply(x));
1650
- } else if (c === "->") {
1651
- if (!opt.lambdas)
1652
- throw new Error("Lambdas not supported, allow them explicitly");
1653
- stack.push(new PartialLambda(stack.pop(), env));
1654
- } else if (c.match(/^[0-9]+$/)) {
1655
- if (!opt.numbers)
1656
- throw new Error("Church numbers not supported, allow them explicitly");
1657
- const f = stack.pop();
1658
- stack.push(f.apply(new Church(c)));
1659
- } else {
1660
- const f = stack.pop();
1661
- if (!env[c] && this.known[c] && !opt.allow.has(c)) {
1662
- throw new Error("Term '" + c + "' is not in the restricted set " + [...opt.allow].sort().join(" "));
1663
- }
1664
- const x = env[c] ?? this.known[c] ?? (env[c] = new FreeVar(c, context));
1665
- stack.push(f.apply(x));
1666
- }
1667
- }
1668
- if (stack.length !== 1) {
1669
- throw new Error("unbalanced input: missing " + (stack.length - 1) + " closing parenthesis:" + source);
1670
- }
1671
- return postParse(stack.pop());
1672
- }
1673
- toJSON() {
1674
- return {
1675
- version: "1.1.1",
1676
- // set to incremented package.json version whenever SKI serialization changes
1677
- allow: this.showRestrict("+"),
1678
- numbers: this.hasNumbers,
1679
- lambdas: this.hasLambdas,
1680
- annotate: this.annotate,
1681
- terms: this.declare()
1682
- };
1683
- }
1684
- };
1685
- SKI.vars = function(scope = {}) {
1686
- const cache = {};
1687
- return new Proxy({}, {
1688
- get: (target, name) => {
1689
- if (!(name in cache))
1690
- cache[name] = new FreeVar(name, scope);
1691
- return cache[name];
1692
- }
1693
- });
1694
- };
1695
- SKI.church = (n) => new Church(n);
1696
- for (const name in native)
1697
- SKI[name] = native[name];
1698
- SKI.classes = classes;
1699
- SKI.native = native;
1700
- SKI.control = Expr.control;
1701
- module.exports = { SKI };
1702
- }
1703
- });
1704
-
1705
- // src/quest.js
1706
- var require_quest = __commonJS({
1707
- "src/quest.js"(exports, module) {
1708
- var { SKI } = require_parser();
1709
- var { Expr, FreeVar, Alias, Lambda } = SKI.classes;
1710
- var Quest = class {
1711
- /**
1712
- * @description A combinator problem with a set of test cases for the proposed solution.
1713
- * @param {QuestSpec} options
1714
- * @example const quest = new Quest({
1715
- * input: 'identity',
1716
- * cases: [
1717
- * ['identity x', 'x'],
1718
- * ],
1719
- * allow: 'SK',
1720
- * intro: 'Find a combinator that behaves like the identity function.',
1721
- * });
1722
- * quest.check('S K K'); // { pass: true, details: [...], ... }
1723
- * quest.check('K S'); // { pass: false, details: [...], ... }
1724
- * quest.check('K x'); // fail! internal variable x is not equal to free variable x,
1725
- * // despite having the same name.
1726
- * quest.check('I'); // fail! I not in the allowed list.
1727
- */
1728
- constructor(options) {
1729
- const { input, cases, allow, numbers, lambdas, engine, engineFull, ...meta } = options;
1730
- const env = options.env ?? options.vars;
1731
- this.engine = engine ?? new SKI();
1732
- this.engineFull = engineFull ?? new SKI();
1733
- this.restrict = { allow, numbers: numbers ?? false, lambdas: lambdas ?? false };
1734
- this.env = {};
1735
- const jar = {};
1736
- for (const term of env ?? []) {
1737
- const expr = this.engineFull.parse(term, { env: jar, scope: this });
1738
- if (expr instanceof SKI.classes.Alias)
1739
- this.env[expr.name] = new Alias(expr.name, expr.impl, { terminal: true, canonize: false });
1740
- else if (expr instanceof SKI.classes.FreeVar)
1741
- this.env[expr.name] = expr;
1742
- else
1743
- throw new Error("Unsupported given variable type: " + term);
1744
- }
1745
- this.input = [];
1746
- for (const term of Array.isArray(input) ? input : [input])
1747
- this.addInput(term);
1748
- if (!this.input.length)
1749
- throw new Error("Quest needs at least one input placeholder");
1750
- this.envFull = { ...this.env, ...jar };
1751
- for (const term of this.input) {
1752
- if (term.name in this.envFull)
1753
- throw new Error("input placeholder name is duplicated or clashes with env: " + term.name);
1754
- this.envFull[term.name] = term.placeholder;
1755
- }
1756
- this.cases = [];
1757
- this.name = meta.name ?? meta.title;
1758
- meta.intro = list2str(meta.intro ?? meta.descr);
1759
- this.intro = meta.intro;
1760
- this.id = meta.id;
1761
- this.meta = meta;
1762
- for (const c of cases ?? [])
1763
- this.add(...c);
1764
- }
1765
- /**
1766
- * Display allowed terms based on what engine thinks of this.env + this.restrict.allow
1767
- * @return {string}
1768
- */
1769
- allowed() {
1770
- const allow = this.restrict.allow ?? "";
1771
- const env = Object.keys(this.env).sort();
1772
- return allow ? this.engine.showRestrict(allow + "+" + env.join(" ")) : env.map((s) => "+" + s).join(" ");
1773
- }
1774
- addInput(term) {
1775
- if (typeof term !== "object")
1776
- term = { name: term };
1777
- if (typeof term.name !== "string")
1778
- throw new Error("quest 'input' field must be a string or a {name: string, ...} object");
1779
- term.placeholder = new SKI.classes.FreeVar(term.name);
1780
- this.input.push(term);
1781
- }
1782
- /**
1783
- *
1784
- * @param {{} | string} opt
1785
- * @param {string} terms
1786
- * @return {Quest}
1787
- */
1788
- add(opt, ...terms) {
1789
- if (typeof opt === "string") {
1790
- terms.unshift(opt);
1791
- opt = {};
1792
- } else
1793
- opt = { ...opt };
1794
- opt.engine = opt.engine ?? this.engineFull;
1795
- opt.env = opt.env ?? this.envFull;
1796
- const input = this.input.map((t) => t.placeholder);
1797
- this.cases.push(
1798
- opt.caps ? new PropertyCase(input, opt, terms) : new ExprCase(input, opt, terms)
1799
- );
1800
- return this;
1801
- }
1802
- /**
1803
- * @description Statefully parse a list of strings into expressions or fancy aliases thereof.
1804
- * @param {string[]} input
1805
- * @return {{terms: Expr[], weight: number}}
1806
- */
1807
- prepare(...input) {
1808
- if (input.length !== this.input.length)
1809
- throw new Error("Solutions provided " + input.length + " terms where " + this.input.length + " are expected");
1810
- let weight = 0;
1811
- const prepared = [];
1812
- const jar = { ...this.env };
1813
- for (let i = 0; i < input.length; i++) {
1814
- const spec = this.input[i];
1815
- const impl = this.engine.parse(input[i], {
1816
- env: jar,
1817
- allow: spec.allow ?? this.restrict.allow,
1818
- numbers: spec.numbers ?? this.restrict.numbers,
1819
- lambdas: spec.lambdas ?? this.restrict.lambdas
1820
- });
1821
- const arsenal = { ...this.engine.getTerms(), ...jar };
1822
- weight += impl.fold(0, (a, e) => {
1823
- if (e instanceof SKI.classes.Named && arsenal[e.name] === e)
1824
- return SKI.control.prune(a + 1);
1825
- });
1826
- const expr = impl instanceof FreeVar ? impl : new Alias(spec.fancy ?? spec.name, impl, { terminal: true, canonize: false });
1827
- jar[spec.name] = expr;
1828
- prepared.push(expr);
1829
- }
1830
- return {
1831
- prepared,
1832
- weight
1833
- };
1834
- }
1835
- /**
1836
- *
1837
- * @param {string} input
1838
- * @return {QuestResult}
1839
- */
1840
- check(...input) {
1841
- try {
1842
- const { prepared, weight } = this.prepare(...input);
1843
- const details = this.cases.map((c) => c.check(...prepared));
1844
- const pass = details.reduce((acc, val) => acc && val.pass, true);
1845
- const steps = details.reduce((acc, val) => acc + val.steps, 0);
1846
- return {
1847
- expr: prepared[0],
1848
- input: prepared,
1849
- pass,
1850
- steps,
1851
- details,
1852
- weight
1853
- };
1854
- } catch (e) {
1855
- return { pass: false, details: [], exception: e, steps: 0, input };
1856
- }
1857
- }
1858
- verify(options) {
1859
- const findings = this.verifyMeta(options);
1860
- if (options.solutions) {
1861
- const solCheck = this.verifySolutions(options.solutions);
1862
- if (solCheck)
1863
- findings.solutions = solCheck;
1864
- }
1865
- if (options.seen) {
1866
- if (!this.id)
1867
- findings.seen = "No id in quest " + (this.name ?? "(unnamed)");
1868
- if (options.seen.has(this.id))
1869
- findings.seen = "Duplicate quest id " + this.id;
1870
- options.seen.add(this.id);
1871
- }
1872
- return Object.keys(findings).length ? findings : null;
1873
- }
1874
- /**
1875
- * @desc Verify that solutions that are expected to pass/fail do so.
1876
- * @param {SelfCheck|{[key: string]: SelfCheck}} dataset
1877
- * @return {{shouldPass: {input: string[], result: QuestResult}[], shouldFail: {input: string[], result: QuestResult}[]} | null}
1878
- */
1879
- verifySolutions(dataset) {
1880
- if (typeof dataset === "object" && !Array.isArray(dataset?.accepted) && !Array.isArray(dataset?.rejected)) {
1881
- if (!this.id || !dataset[this.id])
1399
+ const needDetour = {};
1400
+ let i = 1;
1401
+ for (const name in native) {
1402
+ if (!(env[name] instanceof Alias))
1403
+ continue;
1404
+ while ("tmp" + i in env)
1405
+ i++;
1406
+ const temp = new Alias("tmp" + i, env[name]);
1407
+ needDetour[temp.name] = env[name];
1408
+ env[temp.name] = temp;
1409
+ delete env[name];
1410
+ }
1411
+ const list = toposort(void 0, env).list;
1412
+ const detour = /* @__PURE__ */ new Map();
1413
+ if (Object.keys(needDetour).length) {
1414
+ const rework = (expr) => {
1415
+ return expr.traverse((e) => {
1416
+ if (!(e instanceof Alias))
1882
1417
  return null;
1883
- }
1884
- const { accepted = [], rejected = [] } = dataset[this.id] ?? dataset;
1885
- const ret = { shouldPass: [], shouldFail: [] };
1886
- for (const input of accepted) {
1887
- const result = this.check(...input);
1888
- if (!result.pass)
1889
- ret.shouldPass.push({ input, result });
1890
- }
1891
- for (const input of rejected) {
1892
- const result = this.check(...input);
1893
- if (result.pass)
1894
- ret.shouldFail.push({ input, result });
1895
- }
1896
- return ret.shouldFail.length + ret.shouldPass.length ? ret : null;
1897
- }
1898
- verifyMeta(options = {}) {
1899
- const findings = {};
1900
- for (const field of ["name", "intro"]) {
1901
- const found = checkHtml(this[field]);
1902
- if (found)
1903
- findings[field] = found;
1904
- }
1905
- if (options.date) {
1906
- const date = new Date(this.meta.created_at);
1907
- if (isNaN(date))
1908
- findings.date = "invalid date format: " + this.meta.created_at;
1909
- else if (date < /* @__PURE__ */ new Date("2024-07-15") || date > /* @__PURE__ */ new Date())
1910
- findings.date = "date out of range: " + this.meta.created_at;
1911
- }
1912
- return findings;
1913
- }
1914
- /**
1915
- *
1916
- * @return {TestCase[]}
1917
- */
1918
- show() {
1919
- return [...this.cases];
1920
- }
1921
- };
1922
- var Case = class {
1923
- /**
1924
- * @param {FreeVar[]} input
1925
- * @param {{
1926
- * max?: number,
1927
- * note?: string,
1928
- * env?: {[key:string]: Expr},
1929
- * engine: SKI
1930
- * }} options
1931
- */
1932
- constructor(input, options) {
1933
- this.max = options.max ?? 1e3;
1934
- this.note = options.note;
1935
- this.env = { ...options.env ?? {} };
1936
- this.input = input;
1937
- this.engine = options.engine;
1938
- }
1939
- parse(src) {
1940
- return new Subst(this.engine.parse(src, { env: this.env, scope: this }), this.input);
1941
- }
1942
- /**
1943
- * @param {Expr} expr
1944
- * @return {CaseResult}
1945
- */
1946
- check(...expr) {
1947
- throw new Error("not implemented");
1948
- }
1949
- };
1950
- var ExprCase = class extends Case {
1951
- /**
1952
- * @param {FreeVar[]} input
1953
- * @param {{
1954
- * max?: number,
1955
- * note?: string,
1956
- * env?: {string: Expr},
1957
- * engine?: SKI
1958
- * }} options
1959
- * @param {[e1: string, e2: string]} terms
1960
- */
1961
- constructor(input, options, terms) {
1962
- if (terms.length !== 2)
1963
- throw new Error("Case accepts exactly 2 strings");
1964
- super(input, options);
1965
- [this.e1, this.e2] = terms.map((s) => this.parse(s));
1418
+ const newAlias = detour.get(e);
1419
+ if (newAlias)
1420
+ return newAlias;
1421
+ return new Alias(e.name, rework(e.impl));
1422
+ }) ?? expr;
1423
+ };
1424
+ for (let j = 0; j < list.length; j++) {
1425
+ list[j] = rework(list[j]);
1426
+ detour.set(needDetour[list[j].name], list[j]);
1427
+ env[list[j].name] = list[j];
1428
+ console.log(`list[${j}] = ${list[j].name}=${list[j].impl};`);
1966
1429
  }
1967
- check(...args) {
1968
- const e1 = this.e1.apply(args);
1969
- const r1 = e1.run({ max: this.max });
1970
- const e2 = this.e2.apply(args);
1971
- const r2 = e2.run({ max: this.max });
1972
- let reason = null;
1973
- if (!r1.final || !r2.final)
1974
- reason = "failed to reach normal form in " + this.max + " steps";
1975
- else
1976
- reason = r1.expr.diff(r2.expr);
1977
- return {
1978
- pass: !reason,
1979
- reason,
1980
- steps: r1.steps,
1981
- start: e1,
1982
- found: r1.expr,
1983
- expected: r2.expr,
1984
- note: this.note,
1985
- args,
1986
- case: this
1987
- };
1430
+ console.log("detour:", detour);
1431
+ }
1432
+ const out = list.map(
1433
+ (e) => needDetour[e.name] ? e.name + "=" + needDetour[e.name].name + "=" + e.impl.format({ inventory: env }) : e.name + "=" + e.impl.format({ inventory: env })
1434
+ );
1435
+ for (const [name, temp] of detour)
1436
+ out.push(name.name + "=" + temp, temp + "=");
1437
+ return out;
1438
+ }
1439
+ /**
1440
+ * @template T
1441
+ * @param {string} source
1442
+ * @param {Object} [options]
1443
+ * @param {{[keys: string]: Expr}} [options.env]
1444
+ * @param {T} [options.scope]
1445
+ * @param {boolean} [options.numbers]
1446
+ * @param {boolean} [options.lambdas]
1447
+ * @param {string} [options.allow]
1448
+ * @return {Expr}
1449
+ */
1450
+ parse(source, options = {}) {
1451
+ if (typeof source !== "string")
1452
+ throw new Error("parse: source must be a string, got " + typeof source);
1453
+ const lines = source.replace(/\/\/[^\n]*$/gm, " ").replace(/\/\*.*?\*\//gs, " ").trim().split(/\s*;[\s;]*/).filter((s) => s.match(/\S/));
1454
+ const jar = { ...options.env };
1455
+ let expr = new Empty();
1456
+ for (const item of lines) {
1457
+ if (expr instanceof Alias)
1458
+ expr.outdated = true;
1459
+ const def = item.match(/^([A-Z]|[a-z][a-z_0-9]*)\s*=(.*)$/s);
1460
+ if (def && def[2] === "")
1461
+ expr = new FreeVar(def[1], options.scope ?? FreeVar.global);
1462
+ else
1463
+ expr = this.parseLine(item, jar, options);
1464
+ if (def) {
1465
+ if (jar[def[1]] !== void 0)
1466
+ throw new Error("Attempt to redefine a known term: " + def[1]);
1467
+ jar[def[1]] = expr;
1988
1468
  }
1469
+ }
1470
+ expr.context = {
1471
+ env: { ...this.getTerms(), ...jar },
1472
+ // also contains pre-parsed terms
1473
+ scope: options.scope,
1474
+ src: source,
1475
+ parser: this
1989
1476
  };
1990
- var knownCaps = {
1991
- normal: true,
1992
- proper: true,
1993
- discard: true,
1994
- duplicate: true,
1995
- linear: true,
1996
- affine: true,
1997
- arity: true
1477
+ return expr;
1478
+ }
1479
+ /**
1480
+ * @desc Parse a single line of source code, without splitting it into declarations.
1481
+ * Internal, always use parse() instead.
1482
+ * @template T
1483
+ * @param {String} source S(KI)I
1484
+ * @param {{[keys: string]: Expr}} env
1485
+ * @param {Object} [options]
1486
+ * @param {{[keys: string]: Expr}} [options.env] - unused, see 'env' argument
1487
+ * @param {T} [options.scope]
1488
+ * @param {boolean} [options.numbers]
1489
+ * @param {boolean} [options.lambdas]
1490
+ * @param {string} [options.allow]
1491
+ * @return {Expr} parsed expression
1492
+ */
1493
+ parseLine(source, env = {}, options = {}) {
1494
+ const aliased = source.match(/^\s*([A-Z]|[a-z][a-z_0-9]*)\s*=\s*(.*)$/s);
1495
+ if (aliased)
1496
+ return new Alias(aliased[1], this.parseLine(aliased[2], env, options));
1497
+ const opt = {
1498
+ numbers: options.numbers ?? this.hasNumbers,
1499
+ lambdas: options.lambdas ?? this.hasLambdas,
1500
+ allow: restrict(this.allow, options.allow)
1998
1501
  };
1999
- var PropertyCase = class extends Case {
2000
- // test that an expression uses all of its inputs exactly once
2001
- constructor(input, options, terms) {
2002
- super(input, options);
2003
- if (terms.length > 1)
2004
- throw new Error("PropertyCase accepts exactly 1 string");
2005
- if (!options.caps || typeof options.caps !== "object" || !Object.keys(options.caps).length)
2006
- throw new Error("PropertyCase requires a caps object with at least one capability");
2007
- const unknown = Object.keys(options.caps).filter((c) => !knownCaps[c]);
2008
- if (unknown.length)
2009
- throw new Error("PropertyCase: don't know how to test these capabilities: " + unknown.join(", "));
2010
- this.expr = this.parse(terms[0]);
2011
- this.caps = options.caps;
2012
- if (this.caps.linear) {
2013
- delete this.caps.linear;
2014
- this.caps.duplicate = false;
2015
- this.caps.discard = false;
2016
- this.caps.normal = true;
2017
- }
2018
- if (this.caps.affine) {
2019
- delete this.caps.affine;
2020
- this.caps.normal = true;
2021
- this.caps.duplicate = false;
2022
- }
2023
- }
2024
- check(...expr) {
2025
- const start = this.expr.apply(expr);
2026
- const r = start.run({ max: this.max });
2027
- const guess = r.expr.infer({ max: this.max });
2028
- const reason = [];
2029
- for (const cap in this.caps) {
2030
- if (guess[cap] !== this.caps[cap])
2031
- reason.push("expected property " + cap + " to be " + this.caps[cap] + ", found " + guess[cap]);
1502
+ if (opt.numbers) opt.allow.add("+");
1503
+ else opt.allow.delete("+");
1504
+ const tokens = combChars.split(source);
1505
+ const empty = new Empty();
1506
+ const stack = [empty];
1507
+ const context = options.scope || FreeVar.global;
1508
+ for (const c of tokens) {
1509
+ if (c === "(")
1510
+ stack.push(empty);
1511
+ else if (c === ")") {
1512
+ if (stack.length < 2)
1513
+ throw new Error("unbalanced input: extra closing parenthesis" + source);
1514
+ const x = postParse(stack.pop());
1515
+ const f = stack.pop();
1516
+ stack.push(f.apply(x));
1517
+ } else if (c === "->") {
1518
+ if (!opt.lambdas)
1519
+ throw new Error("Lambdas not supported, allow them explicitly");
1520
+ stack.push(new PartialLambda(stack.pop()));
1521
+ } else if (c.match(/^[0-9]+$/)) {
1522
+ if (!opt.numbers)
1523
+ throw new Error("Church numbers not supported, allow them explicitly");
1524
+ const f = stack.pop();
1525
+ stack.push(f.apply(new Church(Number.parseInt(c))));
1526
+ } else {
1527
+ const f = stack.pop();
1528
+ if (!env[c] && this.known[c] && !opt.allow.has(c)) {
1529
+ throw new Error("Term '" + c + "' is not in the restricted set " + [...opt.allow].sort().join(" "));
2032
1530
  }
2033
- return {
2034
- pass: !reason.length,
2035
- reason: reason ? reason.join("\n") : null,
2036
- steps: r.steps,
2037
- start,
2038
- found: r.expr,
2039
- case: this,
2040
- note: this.note,
2041
- args: expr
2042
- };
1531
+ const x = env[c] ?? this.known[c] ?? (env[c] = new FreeVar(c, context));
1532
+ stack.push(f.apply(x));
2043
1533
  }
1534
+ }
1535
+ if (stack.length !== 1) {
1536
+ throw new Error("unbalanced input: missing " + (stack.length - 1) + " closing parenthesis:" + source);
1537
+ }
1538
+ return postParse(stack.pop());
1539
+ }
1540
+ toJSON() {
1541
+ return {
1542
+ version: "1.1.1",
1543
+ // set to incremented package.json version whenever SKI serialization changes
1544
+ allow: this.showRestrict("+"),
1545
+ numbers: this.hasNumbers,
1546
+ lambdas: this.hasLambdas,
1547
+ annotate: this.annotate,
1548
+ terms: this.declare()
2044
1549
  };
2045
- var Subst = class {
2046
- /**
2047
- * @descr A placeholder object with exactly n free variables to be substituted later.
2048
- * @param {Expr} expr
2049
- * @param {FreeVar[]} env
2050
- */
2051
- constructor(expr, env) {
2052
- this.expr = expr;
2053
- this.env = env;
2054
- }
2055
- apply(list) {
2056
- if (list.length !== this.env.length)
2057
- throw new Error("Subst: expected " + this.env.length + " terms, got " + list.length);
2058
- let expr = this.expr;
2059
- for (let i = 0; i < this.env.length; i++)
2060
- expr = expr.subst(this.env[i], list[i]) ?? expr;
2061
- return expr;
2062
- }
1550
+ }
1551
+ /**
1552
+ * Public static shortcuts to common functions (see also ./extras.js)
1553
+ */
1554
+ /**
1555
+ * @desc Create a proxy object that generates variables on demand,
1556
+ * with names corresponding to the property accessed.
1557
+ * Different invocations will return distinct variables,
1558
+ * even if with the same name.
1559
+ *
1560
+ *
1561
+ * @example const {x, y, z} = SKI.vars();
1562
+ * x.name; // 'x'
1563
+ * x instanceof FreeVar; // true
1564
+ * x.apply(y).apply(z); // x(y)(z)
1565
+ *
1566
+ * @template T
1567
+ * @param {T} [scope] - optional context to bind the generated variables to
1568
+ * @return {{[key: string]: FreeVar}}
1569
+ */
1570
+ };
1571
+
1572
+ // src/quest.ts
1573
+ var Quest = class {
1574
+ constructor(options) {
1575
+ const { input, cases, allow, numbers, lambdas, engine, engineFull, ...meta } = options;
1576
+ const env = options.env ?? [];
1577
+ this.engineFull = engineFull ?? new Parser();
1578
+ this.engine = engine ?? this.engineFull;
1579
+ this.restrict = { allow, numbers: numbers ?? false, lambdas: lambdas ?? false };
1580
+ this.env = {};
1581
+ const jar = {};
1582
+ for (const term of env ?? []) {
1583
+ const expr = this.engineFull.parse(term, { env: jar, scope: this });
1584
+ if (expr instanceof Alias)
1585
+ this.env[expr.name] = new Alias(expr.name, expr.impl, { terminal: true, canonize: false });
1586
+ else if (expr instanceof FreeVar)
1587
+ this.env[expr.name] = expr;
1588
+ else
1589
+ throw new Error("Unsupported given variable type: " + term);
1590
+ }
1591
+ this.input = [];
1592
+ for (const term of Array.isArray(input) ? input : [input])
1593
+ this.addInput(term);
1594
+ if (!this.input.length)
1595
+ throw new Error("Quest needs at least one input placeholder");
1596
+ this.envFull = { ...this.env, ...jar };
1597
+ for (const term of this.input) {
1598
+ if (term.name in this.envFull)
1599
+ throw new Error("input placeholder name is duplicated or clashes with env: " + term.name);
1600
+ this.envFull[term.name] = term.placeholder;
1601
+ }
1602
+ this.cases = [];
1603
+ this.name = meta.name ?? meta.title;
1604
+ meta.intro = list2str(meta.intro ?? meta.descr);
1605
+ this.intro = meta.intro;
1606
+ this.id = meta.id;
1607
+ this.meta = meta;
1608
+ for (const c of cases ?? [])
1609
+ this.add(...c);
1610
+ }
1611
+ /**
1612
+ * Display allowed terms based on what engine thinks of this.env + this.restrict.allow
1613
+ * @return {string}
1614
+ */
1615
+ allowed() {
1616
+ const allow = this.restrict.allow ?? "";
1617
+ const env = Object.keys(this.env).sort();
1618
+ return allow ? this.engine.showRestrict(allow + "+" + env.join(" ")) : env.map((s) => "+" + s).join(" ");
1619
+ }
1620
+ addInput(term) {
1621
+ if (typeof term !== "object")
1622
+ term = { name: term };
1623
+ if (typeof term.name !== "string")
1624
+ throw new Error("quest 'input' field must be a string or a {name: string, ...} object");
1625
+ const full = term;
1626
+ full.placeholder = new FreeVar(term.name);
1627
+ this.input.push(full);
1628
+ }
1629
+ /**
1630
+ *
1631
+ * @param {{} | string} opt
1632
+ * @param {string} terms
1633
+ * @return {Quest}
1634
+ */
1635
+ add(opt, ...terms) {
1636
+ let o;
1637
+ if (typeof opt === "string") {
1638
+ terms.unshift(opt);
1639
+ o = {};
1640
+ } else
1641
+ o = { ...opt };
1642
+ o.engine = o.engine ?? this.engineFull;
1643
+ o.env = o.env ?? this.envFull;
1644
+ const input = this.input.map((t) => t.placeholder);
1645
+ this.cases.push(
1646
+ o.caps ? new PropertyCase(input, o, terms) : new ExprCase(input, o, terms)
1647
+ );
1648
+ return this;
1649
+ }
1650
+ /**
1651
+ * @description Statefully parse a list of strings into expressions or fancy aliases thereof.
1652
+ * @param {string[]} input
1653
+ * @return {{terms: Expr[], weight: number}}
1654
+ */
1655
+ prepare(...input) {
1656
+ if (input.length !== this.input.length)
1657
+ throw new Error("Solutions provided " + input.length + " terms where " + this.input.length + " are expected");
1658
+ let weight = 0;
1659
+ const prepared = [];
1660
+ const jar = { ...this.env };
1661
+ for (let i = 0; i < input.length; i++) {
1662
+ const spec = this.input[i];
1663
+ const impl = this.engine.parse(input[i], {
1664
+ env: jar,
1665
+ allow: spec.allow ?? this.restrict.allow,
1666
+ numbers: spec.numbers ?? this.restrict.numbers,
1667
+ lambdas: spec.lambdas ?? this.restrict.lambdas
1668
+ });
1669
+ const arsenal = { ...this.engine.getTerms(), ...jar };
1670
+ weight += impl.fold(0, (a, e) => {
1671
+ if (e instanceof Named && arsenal[e.name] === e)
1672
+ return control.prune(a + 1);
1673
+ });
1674
+ const expr = impl instanceof FreeVar ? impl : new Alias(spec.fancy ?? spec.name, impl, { terminal: true, canonize: false });
1675
+ jar[spec.name] = expr;
1676
+ prepared.push(expr);
1677
+ }
1678
+ return {
1679
+ prepared,
1680
+ weight
2063
1681
  };
2064
- var Group = class {
2065
- constructor(options) {
2066
- this.name = options.name;
2067
- this.intro = list2str(options.intro);
2068
- this.id = options.id;
2069
- if (options.content)
2070
- this.content = options.content.map((c) => c instanceof Quest ? c : new Quest(c));
2071
- }
2072
- verify(options) {
2073
- const findings = {};
2074
- const id = checkId(this.id, options.seen);
2075
- if (id)
2076
- findings[this.id] = id;
2077
- for (const field of ["name", "intro"]) {
2078
- const found = checkHtml(this[field]);
2079
- if (found)
2080
- findings[field] = found;
2081
- }
2082
- findings.content = this.content.map((q) => q.verify(options));
2083
- return findings;
2084
- }
1682
+ }
1683
+ /**
1684
+ *
1685
+ * @param {string} input
1686
+ * @return {QuestResult}
1687
+ */
1688
+ check(...input) {
1689
+ try {
1690
+ const { prepared, weight } = this.prepare(...input);
1691
+ const details = this.cases.map((c) => c.check(...prepared));
1692
+ const pass = details.reduce((acc, val) => acc && val.pass, true);
1693
+ const steps = details.reduce((acc, val) => acc + val.steps, 0);
1694
+ return {
1695
+ expr: prepared[0],
1696
+ input: prepared,
1697
+ pass,
1698
+ steps,
1699
+ details,
1700
+ weight
1701
+ };
1702
+ } catch (e) {
1703
+ return { pass: false, details: [], exception: e, steps: 0, input };
1704
+ }
1705
+ }
1706
+ verify(options) {
1707
+ const findings = this.verifyMeta(options);
1708
+ if (options.solutions) {
1709
+ const solCheck = this.verifySolutions(options.solutions);
1710
+ if (solCheck)
1711
+ findings.solutions = solCheck;
1712
+ }
1713
+ if (options.seen) {
1714
+ if (!this.id)
1715
+ findings.seen = "No id in quest " + (this.name ?? "(unnamed)");
1716
+ if (options.seen.has(this.id))
1717
+ findings.seen = "Duplicate quest id " + this.id;
1718
+ options.seen.add(this.id);
1719
+ }
1720
+ return Object.keys(findings).length ? findings : null;
1721
+ }
1722
+ /**
1723
+ * @desc Verify that solutions that are expected to pass/fail do so.
1724
+ * @param {SelfCheck|{[key: string]: SelfCheck}} dataset
1725
+ * @return {{shouldPass: {input: string[], result: QuestResult}[], shouldFail: {input: string[], result: QuestResult}[]} | null}
1726
+ */
1727
+ verifySolutions(dataset) {
1728
+ if (typeof dataset === "object" && !Array.isArray(dataset.accepted) && !Array.isArray(dataset.rejected)) {
1729
+ if (!this.id || !dataset[this.id])
1730
+ return null;
1731
+ }
1732
+ const byId = this.id !== void 0 ? dataset[this.id] : void 0;
1733
+ const { accepted = [], rejected = [] } = byId ?? dataset;
1734
+ const ret = { shouldPass: [], shouldFail: [] };
1735
+ for (const input of accepted) {
1736
+ const result = this.check(...input);
1737
+ if (!result.pass)
1738
+ ret.shouldPass.push({ input, result });
1739
+ }
1740
+ for (const input of rejected) {
1741
+ const result = this.check(...input);
1742
+ if (result.pass)
1743
+ ret.shouldFail.push({ input, result });
1744
+ }
1745
+ return ret.shouldFail.length + ret.shouldPass.length ? ret : null;
1746
+ }
1747
+ verifyMeta(options = {}) {
1748
+ const findings = {};
1749
+ for (const field of ["name", "intro"]) {
1750
+ const found = checkHtml(this[field]);
1751
+ if (found)
1752
+ findings[field] = found;
1753
+ }
1754
+ if (options.date) {
1755
+ const date = new Date(this.meta?.created_at);
1756
+ if (isNaN(date.getTime()))
1757
+ findings.date = "invalid date format: " + this.meta?.created_at;
1758
+ else if (date.getTime() < (/* @__PURE__ */ new Date("2024-07-15")).getTime() || date.getTime() > (/* @__PURE__ */ new Date()).getTime())
1759
+ findings.date = "date out of range: " + this.meta?.created_at;
1760
+ }
1761
+ return findings;
1762
+ }
1763
+ /**
1764
+ *
1765
+ * @return {TestCase[]}
1766
+ */
1767
+ show() {
1768
+ return [...this.cases];
1769
+ }
1770
+ };
1771
+ var Case = class {
1772
+ constructor(input, options) {
1773
+ this.max = options.max ?? 1e3;
1774
+ this.note = options.note;
1775
+ this.env = { ...options.env ?? {} };
1776
+ this.input = input;
1777
+ this.engine = options.engine;
1778
+ }
1779
+ parse(src) {
1780
+ return new Subst(this.engine.parse(src, { env: this.env, scope: this }), this.input);
1781
+ }
1782
+ /**
1783
+ * @param {Expr} expr
1784
+ * @return {CaseResult}
1785
+ */
1786
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1787
+ check(..._expr) {
1788
+ throw new Error("not implemented");
1789
+ }
1790
+ };
1791
+ var ExprCase = class extends Case {
1792
+ /**
1793
+ * @param {FreeVar[]} input
1794
+ * @param {{
1795
+ * max?: number,
1796
+ * note?: string,
1797
+ * env?: {string: Expr},
1798
+ * engine?: Parser
1799
+ * }} options
1800
+ * @param {[e1: string, e2: string]} terms
1801
+ */
1802
+ constructor(input, options, terms) {
1803
+ if (terms.length !== 2)
1804
+ throw new Error("Case accepts exactly 2 strings");
1805
+ super(input, options);
1806
+ [this.e1, this.e2] = terms.map((s) => this.parse(s));
1807
+ }
1808
+ check(...args) {
1809
+ const e1 = this.e1.apply(args);
1810
+ const r1 = e1.run({ max: this.max });
1811
+ const e2 = this.e2.apply(args);
1812
+ const r2 = e2.run({ max: this.max });
1813
+ let reason = null;
1814
+ if (!r1.final || !r2.final)
1815
+ reason = "failed to reach normal form in " + this.max + " steps";
1816
+ else
1817
+ reason = r1.expr.diff(r2.expr);
1818
+ return {
1819
+ pass: !reason,
1820
+ reason: reason ?? void 0,
1821
+ steps: r1.steps,
1822
+ start: e1,
1823
+ found: r1.expr,
1824
+ expected: r2.expr,
1825
+ note: this.note,
1826
+ args,
1827
+ case: this
2085
1828
  };
2086
- function list2str(str) {
2087
- if (str === void 0 || typeof str === "string")
2088
- return str;
2089
- return Array.isArray(str) ? str.join(" ") : "" + str;
1829
+ }
1830
+ };
1831
+ var knownCaps = {
1832
+ normal: true,
1833
+ proper: true,
1834
+ discard: true,
1835
+ duplicate: true,
1836
+ linear: true,
1837
+ affine: true,
1838
+ arity: true
1839
+ };
1840
+ var PropertyCase = class extends Case {
1841
+ // test that an expression uses all of its inputs exactly once
1842
+ constructor(input, options, terms) {
1843
+ super(input, options);
1844
+ if (terms.length > 1)
1845
+ throw new Error("PropertyCase accepts exactly 1 string");
1846
+ if (!options.caps || typeof options.caps !== "object" || !Object.keys(options.caps).length)
1847
+ throw new Error("PropertyCase requires a caps object with at least one capability");
1848
+ const unknown = Object.keys(options.caps).filter((c) => !knownCaps[c]);
1849
+ if (unknown.length)
1850
+ throw new Error("PropertyCase: don't know how to test these capabilities: " + unknown.join(", "));
1851
+ this.expr = this.parse(terms[0]);
1852
+ this.caps = { ...options.caps };
1853
+ if (this.caps.linear) {
1854
+ delete this.caps.linear;
1855
+ this.caps.duplicate = false;
1856
+ this.caps.discard = false;
1857
+ this.caps.normal = true;
2090
1858
  }
2091
- function checkId(id, seen) {
2092
- if (id === void 0)
2093
- return "missing";
2094
- if (typeof id !== "string" && typeof id !== "number")
2095
- return "is a " + typeof id;
2096
- if (seen) {
2097
- if (seen.has(id))
2098
- return "duplicate id " + id;
2099
- seen.add(id);
2100
- }
1859
+ if (this.caps.affine) {
1860
+ delete this.caps.affine;
1861
+ this.caps.normal = true;
1862
+ this.caps.duplicate = false;
2101
1863
  }
2102
- function checkHtml(str) {
2103
- if (str === void 0)
2104
- return "missing";
2105
- if (typeof str !== "string")
2106
- return "not a string but " + typeof str;
2107
- const tagStack = [];
2108
- const tagRegex = /<\/?([a-z]+)(?:\s[^>]*)?>/gi;
2109
- let match;
2110
- while ((match = tagRegex.exec(str)) !== null) {
2111
- const [fullTag, tagName] = match;
2112
- if (fullTag.startsWith("</")) {
2113
- if (tagStack.length === 0 || tagStack.pop() !== tagName)
2114
- return `Unmatched closing tag: </${tagName}>`;
2115
- } else {
2116
- tagStack.push(tagName);
2117
- }
2118
- }
2119
- if (tagStack.length > 0)
2120
- return `Unclosed tags: ${tagStack.join(", ")}`;
2121
- return null;
1864
+ }
1865
+ check(...expr) {
1866
+ const start = this.expr.apply(expr);
1867
+ const r = start.run({ max: this.max });
1868
+ const guess = r.expr.infer({ max: this.max });
1869
+ const reason = [];
1870
+ for (const cap in this.caps) {
1871
+ if (guess[cap] !== this.caps[cap])
1872
+ reason.push("expected property " + cap + " to be " + this.caps[cap] + ", found " + guess[cap]);
1873
+ }
1874
+ return {
1875
+ pass: !reason.length,
1876
+ reason: reason.length ? reason.join("\n") : void 0,
1877
+ steps: r.steps,
1878
+ start,
1879
+ found: r.expr,
1880
+ case: this,
1881
+ note: this.note,
1882
+ args: expr
1883
+ };
1884
+ }
1885
+ };
1886
+ var Subst = class {
1887
+ constructor(expr, env) {
1888
+ this.expr = expr;
1889
+ this.env = env;
1890
+ }
1891
+ apply(list) {
1892
+ if (list.length !== this.env.length)
1893
+ throw new Error("Subst: expected " + this.env.length + " terms, got " + list.length);
1894
+ let expr = this.expr;
1895
+ for (let i = 0; i < this.env.length; i++)
1896
+ expr = expr.subst(this.env[i], list[i]) ?? expr;
1897
+ return expr;
1898
+ }
1899
+ };
1900
+ var Group = class {
1901
+ constructor(options) {
1902
+ this.name = options.name;
1903
+ this.intro = list2str(options.intro);
1904
+ this.id = options.id;
1905
+ if (options.content)
1906
+ this.content = options.content.map((c) => c instanceof Quest ? c : new Quest(c));
1907
+ }
1908
+ verify(options) {
1909
+ const findings = {};
1910
+ const id = checkId(this.id, options.seen);
1911
+ if (id)
1912
+ findings.id = id;
1913
+ for (const field of ["name", "intro"]) {
1914
+ const found = checkHtml(this[field]);
1915
+ if (found)
1916
+ findings[field] = found;
1917
+ }
1918
+ findings.content = this.content.map((q) => q.verify(options));
1919
+ return findings;
1920
+ }
1921
+ };
1922
+ function list2str(str) {
1923
+ if (str === void 0 || typeof str === "string")
1924
+ return str;
1925
+ return Array.isArray(str) ? str.join(" ") : "" + str;
1926
+ }
1927
+ function checkId(id, seen) {
1928
+ if (id === void 0)
1929
+ return "missing";
1930
+ if (typeof id !== "string" && typeof id !== "number")
1931
+ return "is a " + typeof id;
1932
+ if (seen) {
1933
+ if (seen.has(id))
1934
+ return "duplicate id " + id;
1935
+ seen.add(id);
1936
+ }
1937
+ }
1938
+ function checkHtml(str) {
1939
+ if (str === void 0)
1940
+ return "missing";
1941
+ if (typeof str !== "string")
1942
+ return "not a string but " + typeof str;
1943
+ const tagStack = [];
1944
+ const tagRegex = /<\/?([a-z]+)(?:\s[^>]*)?>/gi;
1945
+ let match;
1946
+ while ((match = tagRegex.exec(str)) !== null) {
1947
+ const [fullTag, tagName] = match;
1948
+ if (fullTag.startsWith("</")) {
1949
+ if (tagStack.length === 0 || tagStack.pop() !== tagName)
1950
+ return `Unmatched closing tag: </${tagName}>`;
1951
+ } else {
1952
+ tagStack.push(tagName);
2122
1953
  }
2123
- Quest.Group = Group;
2124
- Quest.Case = Case;
2125
- module.exports = { Quest };
2126
1954
  }
2127
- });
1955
+ if (tagStack.length > 0)
1956
+ return `Unclosed tags: ${tagStack.join(", ")}`;
1957
+ return null;
1958
+ }
1959
+ Quest.Group = Group;
1960
+ Quest.Case = Case;
2128
1961
 
2129
- // src/extras.js
2130
- var require_extras = __commonJS({
2131
- "src/extras.js"(exports, module) {
2132
- "use strict";
2133
- var { Expr, Alias, FreeVar } = require_expr();
2134
- var { Quest } = require_quest();
2135
- function search(seed, options, predicate) {
2136
- const {
2137
- depth = 16,
2138
- infer = true,
2139
- progressInterval = 1e3
2140
- } = options;
2141
- const hasSeen = infer && !options.noskip;
2142
- const cache = [[]];
2143
- let total = 0;
2144
- let probed = 0;
2145
- const seen = {};
2146
- const maybeProbe = (term) => {
2147
- total++;
2148
- const props = infer ? term.infer({ max: options.max, maxArgs: options.maxArgs }) : null;
2149
- if (hasSeen && props.expr) {
2150
- if (seen[props.expr])
2151
- return { res: -1 };
2152
- seen[props.expr] = true;
2153
- }
2154
- probed++;
2155
- const res = predicate(term, props);
2156
- return { res, props };
2157
- };
2158
- for (const term of seed) {
2159
- const { res } = maybeProbe(term);
2160
- if (res > 0)
2161
- return { expr: term, total, probed, gen: 1 };
2162
- else if (res < 0)
2163
- continue;
2164
- cache[0].push(term);
2165
- }
2166
- let lastProgress;
2167
- for (let gen = 1; gen < depth; gen++) {
2168
- if (options.progress) {
2169
- options.progress({ gen, total, probed, step: true });
2170
- lastProgress = total;
2171
- }
2172
- for (let i = 0; i < gen; i++) {
2173
- for (const a of cache[gen - i - 1] || []) {
2174
- for (const b of cache[i] || []) {
2175
- if (total >= options.tries)
2176
- return { total, probed, gen, ...options.retain ? { cache } : {} };
2177
- if (options.progress && total - lastProgress >= progressInterval) {
2178
- options.progress({ gen, total, probed, step: false });
2179
- lastProgress = total;
2180
- }
2181
- const term = a.apply(b);
2182
- const { res, props } = maybeProbe(term);
2183
- if (res > 0)
2184
- return { expr: term, total, probed, gen, ...options.retain ? { cache } : {} };
2185
- else if (res < 0)
2186
- continue;
2187
- const offset = infer ? (props.expr ? 0 : 3) + (props.dup ? 1 : 0) + (props.proper ? 0 : 1) : 0;
2188
- if (!cache[gen + offset])
2189
- cache[gen + offset] = [];
2190
- cache[gen + offset].push(term);
2191
- }
1962
+ // src/extras.ts
1963
+ function search(seed, options, predicate) {
1964
+ const {
1965
+ depth = 16,
1966
+ infer = true,
1967
+ progressInterval = 1e3
1968
+ } = options;
1969
+ const hasSeen = infer && !options.noskip;
1970
+ const cache = [[]];
1971
+ let total = 0;
1972
+ let probed = 0;
1973
+ const seen = {};
1974
+ const maybeProbe = (term) => {
1975
+ total++;
1976
+ const props = infer ? term.infer({ max: options.max, maxArgs: options.maxArgs }) : null;
1977
+ if (hasSeen && props && props.expr) {
1978
+ const key = String(props.expr);
1979
+ if (seen[key])
1980
+ return { res: -1, props };
1981
+ seen[key] = true;
1982
+ }
1983
+ probed++;
1984
+ const res = predicate(term, props);
1985
+ return { res, props };
1986
+ };
1987
+ for (const term of seed) {
1988
+ const { res = 0 } = maybeProbe(term);
1989
+ if (res > 0)
1990
+ return { expr: term, total, probed, gen: 1 };
1991
+ else if (res < 0)
1992
+ continue;
1993
+ cache[0].push(term);
1994
+ }
1995
+ let lastProgress = 0;
1996
+ for (let gen = 1; gen < depth; gen++) {
1997
+ if (options.progress) {
1998
+ options.progress({ gen, total, probed, step: true });
1999
+ lastProgress = total;
2000
+ }
2001
+ for (let i = 0; i < gen; i++) {
2002
+ for (const a of cache[gen - i - 1] || []) {
2003
+ for (const b of cache[i] || []) {
2004
+ if (total >= (options.tries ?? Infinity))
2005
+ return { total, probed, gen, ...options.retain ? { cache } : {} };
2006
+ if (options.progress && total - lastProgress >= progressInterval) {
2007
+ options.progress({ gen, total, probed, step: false });
2008
+ lastProgress = total;
2192
2009
  }
2010
+ const term = a.apply(b);
2011
+ const { res, props } = maybeProbe(term);
2012
+ if ((res ?? 0) > 0)
2013
+ return { expr: term, total, probed, gen, ...options.retain ? { cache } : {} };
2014
+ else if ((res ?? 0) < 0)
2015
+ continue;
2016
+ const offset = infer && props ? (props.expr ? 0 : 3) + (props.dup ? 1 : 0) + (props.proper ? 0 : 1) : 0;
2017
+ if (!cache[gen + offset])
2018
+ cache[gen + offset] = [];
2019
+ cache[gen + offset].push(term);
2193
2020
  }
2194
2021
  }
2195
- return { total, probed, gen: depth, ...options.retain ? { cache } : {} };
2196
- }
2197
- function deepFormat(obj, options = {}) {
2198
- if (obj instanceof Expr)
2199
- return obj.format(options);
2200
- if (obj instanceof Quest)
2201
- return "Quest(" + obj.name + ")";
2202
- if (obj instanceof Quest.Case)
2203
- return "Quest.Case";
2204
- if (Array.isArray(obj))
2205
- return obj.map(deepFormat);
2206
- if (typeof obj !== "object" || obj === null || obj.constructor !== Object)
2207
- return obj;
2208
- const out = {};
2209
- for (const key in obj)
2210
- out[key] = deepFormat(obj[key]);
2211
- return out;
2212
- }
2213
- function declare(expr, env) {
2214
- const res = Expr.extras.toposort([expr], env);
2215
- return res.list.map((s) => {
2216
- if (s instanceof Alias)
2217
- return s.name + "=" + s.impl.format({ inventory: res.env });
2218
- if (s instanceof FreeVar)
2219
- return s.name + "=";
2220
- return s.format({ inventory: res.env });
2221
- }).join("; ");
2222
2022
  }
2223
- function foldr(expr, fun) {
2224
- const [head, ...tail] = expr.unroll();
2225
- return fun(head, tail.map((e) => foldr(e, fun)));
2226
- }
2227
- module.exports = { search, deepFormat, declare, foldr };
2228
2023
  }
2229
- });
2024
+ return { total, probed, gen: depth, ...options.retain ? { cache } : {} };
2025
+ }
2026
+ function deepFormat(obj, options = {}) {
2027
+ if (obj instanceof Expr)
2028
+ return obj.format(options);
2029
+ if (obj instanceof Quest)
2030
+ return "Quest(" + obj.name + ")";
2031
+ if (obj instanceof Quest.Case)
2032
+ return "Quest.Case";
2033
+ if (Array.isArray(obj))
2034
+ return obj.map((item) => deepFormat(item, options));
2035
+ if (typeof obj !== "object" || obj === null || obj.constructor !== Object)
2036
+ return obj;
2037
+ const out = {};
2038
+ for (const key in obj)
2039
+ out[key] = deepFormat(obj[key], options);
2040
+ return out;
2041
+ }
2042
+ function declare(expr, env = {}) {
2043
+ const res = toposort([expr], env);
2044
+ return res.list.map((s) => {
2045
+ if (s instanceof Alias)
2046
+ return s.name + "=" + s.impl.format({ inventory: res.env });
2047
+ if (s instanceof FreeVar)
2048
+ return s.name + "=";
2049
+ return s.format({ inventory: res.env });
2050
+ }).join("; ");
2051
+ }
2052
+ var extras = { search, deepFormat, declare, toposort };
2230
2053
 
2231
- // index.js
2232
- var require_index = __commonJS({
2233
- "index.js"(exports, module) {
2234
- var { SKI } = require_parser();
2235
- var { Quest } = require_quest();
2236
- var extras = require_extras();
2237
- SKI.Quest = Quest;
2238
- SKI.extras = { ...extras, ...SKI.classes.Expr.extras };
2239
- if (typeof process === "object" && process.env.SKI_REPL && typeof global !== "undefined") {
2240
- global.SKI = SKI;
2241
- console.log("SKI_REPL activated, try `new SKI();`");
2242
- }
2243
- if (typeof window !== "undefined")
2244
- window.SKI = SKI;
2245
- module.exports = { SKI, Quest };
2054
+ // src/index.ts
2055
+ extras.toposort = toposort;
2056
+ var SKI = class extends Parser {
2057
+ static {
2058
+ this.native = native;
2059
+ }
2060
+ static {
2061
+ this.control = control;
2246
2062
  }
2247
- });
2248
- export default require_index();
2063
+ static {
2064
+ this.classes = classes;
2065
+ }
2066
+ static {
2067
+ // TODO declare in a loop?
2068
+ this.B = native.B;
2069
+ }
2070
+ static {
2071
+ this.C = native.C;
2072
+ }
2073
+ static {
2074
+ this.I = native.I;
2075
+ }
2076
+ static {
2077
+ this.K = native.K;
2078
+ }
2079
+ static {
2080
+ this.S = native.S;
2081
+ }
2082
+ static {
2083
+ this.W = native.W;
2084
+ }
2085
+ // variable generator shortcut
2086
+ static vars(scope = {}) {
2087
+ const vars = {};
2088
+ return new Proxy(vars, {
2089
+ get(target, prop) {
2090
+ if (!(prop in target))
2091
+ target[prop] = new FreeVar(prop, scope);
2092
+ return target[prop];
2093
+ }
2094
+ });
2095
+ }
2096
+ static church(n) {
2097
+ return new Church(n);
2098
+ }
2099
+ static {
2100
+ this.extras = extras;
2101
+ }
2102
+ static {
2103
+ this.Quest = Quest;
2104
+ }
2105
+ };
2106
+ var g = globalThis;
2107
+ if (g.process?.env.SKI_REPL) {
2108
+ g.SKI = SKI;
2109
+ console.log("SKI_REPL activated, try `new SKI();`");
2110
+ }
2111
+ if (typeof window !== "undefined")
2112
+ window.SKI = SKI;
2113
+ export {
2114
+ SKI
2115
+ };
2249
2116
  //# sourceMappingURL=ski-interpreter.esm.js.map