@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.
- package/CHANGELOG.md +26 -0
- package/README.md +9 -2
- package/bin/ski.js +10 -7
- package/lib/ski-interpreter.cjs.js +2082 -2187
- package/lib/ski-interpreter.cjs.js.map +4 -4
- package/lib/ski-interpreter.esm.js +2065 -2198
- package/lib/ski-interpreter.esm.js.map +4 -4
- package/lib/ski-interpreter.min.js +3 -3
- package/lib/ski-interpreter.min.js.map +4 -4
- package/lib/ski-quest.min.js +3 -3
- package/lib/ski-quest.min.js.map +4 -4
- package/{types/src → lib/types}/expr.d.ts +238 -248
- package/{types/src → lib/types}/extras.d.ts +24 -23
- package/lib/types/index.d.ts +68 -0
- package/{types/src → lib/types}/internal.d.ts +27 -23
- package/{types/src → lib/types}/parser.d.ts +40 -83
- package/lib/types/quest.d.ts +232 -0
- package/lib/types/toposort.d.ts +30 -0
- package/package.json +13 -12
- package/types/index.d.ts +0 -3
- package/types/src/quest.d.ts +0 -257
|
@@ -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
|
|
3
|
-
|
|
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/
|
|
7
|
-
var
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
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
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
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
|
-
|
|
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.
|
|
96
|
-
var
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
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: ["", " ↦ ", ""] });
|
|
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. φ 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: ["", " ↦ ", ""] });
|
|
144
|
+
delete guess.steps;
|
|
145
|
+
this.props = guess;
|
|
197
146
|
}
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
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
|
-
|
|
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
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
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
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
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
|
-
|
|
422
|
-
|
|
423
|
-
|
|
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
|
-
|
|
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 <var> and </var> in html mode).
|
|
678
|
-
* @param {[string, string, string]} [options.lambda] - wrappers for lambda abstractions, e.g. ['λ', '.', '']
|
|
679
|
-
* where the middle string is placed between argument and body
|
|
680
|
-
* default is ['', '->', ''] or ['', '->', ''] 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: ['λ', '.', ''] }) // 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: ["", "->", ""],
|
|
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
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
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
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
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
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
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 <var> and </var> in html mode).
|
|
673
|
+
* @param {[string, string, string]} [options.lambda] - wrappers for lambda abstractions, e.g. ['λ', '.', '']
|
|
674
|
+
* where the middle string is placed between argument and body
|
|
675
|
+
* default is ['', '->', ''] or ['', '->', ''] 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: ['λ', '.', ''] }) // 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: ["", "->", ""],
|
|
699
|
+
around: ["", ""],
|
|
700
|
+
redex: ["", ""]
|
|
701
|
+
} : {
|
|
702
|
+
brackets: ["(", ")"],
|
|
703
|
+
space: " ",
|
|
704
|
+
var: ["", ""],
|
|
705
|
+
lambda: ["", "->", ""],
|
|
706
|
+
around: ["", ""],
|
|
707
|
+
redex: ["", ""]
|
|
956
708
|
};
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
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
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
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
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
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
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
}
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
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
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
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
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
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
|
-
|
|
1241
|
-
|
|
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
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
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
|
-
|
|
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
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
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
|
-
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
|
|
1997
|
-
|
|
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
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
|
|
2015
|
-
|
|
2016
|
-
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
}
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
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
|
-
|
|
2034
|
-
|
|
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
|
-
|
|
2046
|
-
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
|
|
2061
|
-
|
|
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
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
|
|
2078
|
-
|
|
2079
|
-
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
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
|
-
|
|
2087
|
-
|
|
2088
|
-
|
|
2089
|
-
|
|
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
|
-
|
|
2092
|
-
|
|
2093
|
-
|
|
2094
|
-
|
|
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
|
-
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
|
|
2108
|
-
|
|
2109
|
-
|
|
2110
|
-
|
|
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
|
-
|
|
2124
|
-
|
|
2125
|
-
|
|
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.
|
|
2130
|
-
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
|
|
2134
|
-
|
|
2135
|
-
|
|
2136
|
-
|
|
2137
|
-
|
|
2138
|
-
|
|
2139
|
-
|
|
2140
|
-
|
|
2141
|
-
|
|
2142
|
-
|
|
2143
|
-
|
|
2144
|
-
|
|
2145
|
-
const
|
|
2146
|
-
|
|
2147
|
-
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
|
|
2153
|
-
|
|
2154
|
-
|
|
2155
|
-
|
|
2156
|
-
|
|
2157
|
-
};
|
|
2158
|
-
|
|
2159
|
-
|
|
2160
|
-
|
|
2161
|
-
|
|
2162
|
-
|
|
2163
|
-
|
|
2164
|
-
|
|
2165
|
-
}
|
|
2166
|
-
|
|
2167
|
-
|
|
2168
|
-
|
|
2169
|
-
|
|
2170
|
-
|
|
2171
|
-
|
|
2172
|
-
|
|
2173
|
-
|
|
2174
|
-
|
|
2175
|
-
|
|
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.
|
|
2232
|
-
|
|
2233
|
-
var
|
|
2234
|
-
|
|
2235
|
-
|
|
2236
|
-
|
|
2237
|
-
|
|
2238
|
-
|
|
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
|