@dallaylaen/ski-interpreter 2.3.2 → 2.4.0

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