@dallaylaen/ski-interpreter 2.3.3 → 2.4.1

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