everystate 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +111 -86
- package/bin/everystate.mjs +35 -0
- package/native/darwin-arm64/everystate +0 -0
- package/native/darwin-x64/everystate +0 -0
- package/native/linux-arm64/everystate +0 -0
- package/native/linux-x64/everystate +0 -0
- package/native/win32-x64/everystate.exe +0 -0
- package/package.json +23 -24
- package/wasm/cli.mjs +26 -0
- package/wasm/everystate.d.ts +33 -0
- package/wasm/everystate.mjs +112 -0
- package/wasm/everystate.wasm +0 -0
- package/CONFORMANCE.md +0 -64
- package/dist/bundled.d.ts +0 -1
- package/dist/bundled.js +0 -2
- package/dist/cfg.d.ts +0 -24
- package/dist/cfg.js +0 -252
- package/dist/checker.d.ts +0 -96
- package/dist/checker.js +0 -520
- package/dist/cli.d.ts +0 -2
- package/dist/cli.js +0 -4
- package/dist/community.d.ts +0 -17
- package/dist/community.js +0 -1381
- package/dist/entry.d.ts +0 -2
- package/dist/entry.js +0 -39
- package/dist/eval.d.ts +0 -119
- package/dist/eval.js +0 -1533
- package/dist/index.d.ts +0 -33
- package/dist/index.js +0 -24
- package/dist/java.d.ts +0 -2
- package/dist/java.js +0 -6
- package/dist/lexer.d.ts +0 -17
- package/dist/lexer.js +0 -255
- package/dist/liveness.d.ts +0 -80
- package/dist/liveness.js +0 -855
- package/dist/main.d.ts +0 -40
- package/dist/main.js +0 -494
- package/dist/model.d.ts +0 -56
- package/dist/model.js +0 -582
- package/dist/modules.d.ts +0 -91
- package/dist/modules.js +0 -649
- package/dist/node-host.d.ts +0 -2
- package/dist/node-host.js +0 -25
- package/dist/parser.d.ts +0 -30
- package/dist/parser.js +0 -1114
- package/dist/pprint.d.ts +0 -7
- package/dist/pprint.js +0 -647
- package/dist/stdlib.d.ts +0 -14
- package/dist/stdlib.js +0 -588
- package/dist/values.d.ts +0 -150
- package/dist/values.js +0 -822
package/dist/community.js
DELETED
|
@@ -1,1381 +0,0 @@
|
|
|
1
|
-
import { Lazy, LazyFcn } from "./eval.js";
|
|
2
|
-
import { fail, int, seq, set } from "./stdlib.js";
|
|
3
|
-
import { SetBase, SetV, IntervalV, LazySetV, RecSetV, TupleV, RecordV, FcnV, ModelValue, EMPTY_TUPLE, EMPTY_SET, valEq, compare, mkSet, makeFcnFromPairs, makeRecord, isFcn, domainElems, fcnValues, fmt, strId, bsearch, } from "./values.js";
|
|
4
|
-
// ---- shared helpers ----
|
|
5
|
-
const ORD = ['first', 'second', 'third', 'fourth', 'fifth'];
|
|
6
|
-
// TLC's EC.TLC_MODULE_ARGUMENT_ERROR / TLC_MODULE_ONE_ARGUMENT_ERROR / TLC_MODULE_ARGUMENT_NOT_IN_DOMAIN.
|
|
7
|
-
const argErr = (i, op, what, v) => fail(`The ${ORD[i]} argument of ${op} should be a ${what}, but instead it is:\n${fmt(v)}`);
|
|
8
|
-
const oneArgErr = (op, what, v) => fail(`The argument of ${op} should be a ${what}, but instead it is:\n${fmt(v)}`);
|
|
9
|
-
const notInDomain = (i, op, s, v) => fail(`The ${ORD[i]} argument of ${op} must be in the domain of its first argument:\n${fmt(s)}\n, but instead it is\n${fmt(v)}`);
|
|
10
|
-
const isInt = (v) => typeof v === 'number' && Number.isInteger(v);
|
|
11
|
-
const int32 = (n, what) => (n > 2147483647 || n < -2147483648 ? fail(`Overflow when computing ${what}`) : n);
|
|
12
|
-
const str = (v, op, i) => typeof v === 'string' ? v : argErr(i, op, 'string', v);
|
|
13
|
-
const bool = (v, i, op, what, test) => typeof v === 'boolean' ? v : argErr(i, op, what, test);
|
|
14
|
-
const key = (v) => fmt(v); // canonical values print identically iff they are equal
|
|
15
|
-
const tupleOf = (elems) => (elems.length ? new TupleV(elems) : EMPTY_TUPLE);
|
|
16
|
-
function io(ev) {
|
|
17
|
-
const h = ev.hooks.io;
|
|
18
|
-
return h ?? fail('File IO is not available in this environment (the host did not provide ev.hooks.io).');
|
|
19
|
-
}
|
|
20
|
-
function readText(ev, path) {
|
|
21
|
-
const h = io(ev);
|
|
22
|
-
if (!h.exists(path))
|
|
23
|
-
fail(`${path} (No such file or directory)`);
|
|
24
|
-
try {
|
|
25
|
-
return h.readFile(path);
|
|
26
|
-
}
|
|
27
|
-
catch (e) {
|
|
28
|
-
return fail(`${path} (${e.message})`);
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
function hostWrite(f, path) {
|
|
32
|
-
try {
|
|
33
|
-
f();
|
|
34
|
-
}
|
|
35
|
-
catch (e) {
|
|
36
|
-
fail(`${path} (${e.message})`);
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
// ---- folds ----
|
|
40
|
-
function foldFunctionOnSet(ev, op, base, fun, indices) {
|
|
41
|
-
if (!isFcn(fun) && !(fun instanceof LazyFcn))
|
|
42
|
-
argErr(2, 'FoldFunctionOnSet', 'function', fun);
|
|
43
|
-
if (!(indices instanceof SetBase))
|
|
44
|
-
argErr(3, 'FoldFunctionOnSet', 'set', indices);
|
|
45
|
-
let acc = base;
|
|
46
|
-
for (const d of indices.elems())
|
|
47
|
-
acc = ev.applyOp(op, [ev.applyFcn(fun, d), acc]);
|
|
48
|
-
return acc;
|
|
49
|
-
}
|
|
50
|
-
function foldFunction(ev, op, base, fun) {
|
|
51
|
-
if (!isFcn(fun))
|
|
52
|
-
argErr(2, 'FoldFunction', 'function', fun);
|
|
53
|
-
let acc = base;
|
|
54
|
-
for (const x of fcnValues(fun))
|
|
55
|
-
acc = ev.applyOp(op, [x, acc]); // values are stored in domain order
|
|
56
|
-
return acc;
|
|
57
|
-
}
|
|
58
|
-
// ---- sequences ----
|
|
59
|
-
function subSeqIndex(s, t, from) {
|
|
60
|
-
for (let i = from; i + s.length <= t.length; i++) {
|
|
61
|
-
let ok = true;
|
|
62
|
-
for (let j = 0; j < s.length; j++)
|
|
63
|
-
if (!valEq(t[i + j], s[j])) {
|
|
64
|
-
ok = false;
|
|
65
|
-
break;
|
|
66
|
-
}
|
|
67
|
-
if (ok)
|
|
68
|
-
return i;
|
|
69
|
-
}
|
|
70
|
-
return -1;
|
|
71
|
-
}
|
|
72
|
-
function selectIn(ev, a, opName, last, sub) {
|
|
73
|
-
const s = a[0] instanceof TupleV ? a[0].e : argErr(0, opName, 'sequence', a[0]);
|
|
74
|
-
const test = a[sub ? 3 : 1];
|
|
75
|
-
let from = 1, to = s.length;
|
|
76
|
-
if (sub) {
|
|
77
|
-
if (!isInt(a[1]))
|
|
78
|
-
argErr(1, opName, 'natural', a[1]);
|
|
79
|
-
if (!isInt(a[2]))
|
|
80
|
-
argErr(2, opName, 'natural', a[2]);
|
|
81
|
-
from = a[1];
|
|
82
|
-
to = a[2];
|
|
83
|
-
if (from > to)
|
|
84
|
-
return 0;
|
|
85
|
-
if (from < 1 || from > s.length)
|
|
86
|
-
notInDomain(1, opName, a[0], from);
|
|
87
|
-
if (to < 1 || to > s.length)
|
|
88
|
-
notInDomain(2, opName, a[0], to);
|
|
89
|
-
}
|
|
90
|
-
const what = last ? 'boolean-valued function' : 'boolean-valued operator';
|
|
91
|
-
const pos = sub ? 3 : 2; // TLC reports "third" for the two-argument variants
|
|
92
|
-
if (last) {
|
|
93
|
-
for (let i = to; i >= from; i--)
|
|
94
|
-
if (bool(ev.applyOp(test, [s[i - 1]]), pos, opName, what, test))
|
|
95
|
-
return i;
|
|
96
|
-
}
|
|
97
|
-
else {
|
|
98
|
-
for (let i = from; i <= to; i++)
|
|
99
|
-
if (bool(ev.applyOp(test, [s[i - 1]]), pos, opName, what, test))
|
|
100
|
-
return i;
|
|
101
|
-
}
|
|
102
|
-
return 0;
|
|
103
|
-
}
|
|
104
|
-
function permutations(s) {
|
|
105
|
-
const out = [];
|
|
106
|
-
const used = new Array(s.length).fill(false);
|
|
107
|
-
const cur = [];
|
|
108
|
-
const rec = () => {
|
|
109
|
-
if (cur.length === s.length) {
|
|
110
|
-
out.push(tupleOf(cur.slice()));
|
|
111
|
-
return;
|
|
112
|
-
}
|
|
113
|
-
for (let i = 0; i < s.length; i++) {
|
|
114
|
-
if (used[i])
|
|
115
|
-
continue;
|
|
116
|
-
used[i] = true;
|
|
117
|
-
cur.push(s[i]);
|
|
118
|
-
rec();
|
|
119
|
-
cur.pop();
|
|
120
|
-
used[i] = false;
|
|
121
|
-
}
|
|
122
|
-
};
|
|
123
|
-
rec();
|
|
124
|
-
return out;
|
|
125
|
-
}
|
|
126
|
-
const TUPLE_EDGE = e => (e instanceof TupleV && e.e.length === 2 ? [e.e[0], e.e[1]] : null);
|
|
127
|
-
const PAIR_EDGE = e => {
|
|
128
|
-
if (!(e instanceof SetBase) || !e.enumerable())
|
|
129
|
-
return null;
|
|
130
|
-
const x = e.elems();
|
|
131
|
-
if (x.length === 0 || x.length > 2)
|
|
132
|
-
return null;
|
|
133
|
-
return [x[0], x.length === 2 ? x[1] : x[0]];
|
|
134
|
-
};
|
|
135
|
-
function toGraph(op, pos, kind, v) {
|
|
136
|
-
if (!(v instanceof RecordV))
|
|
137
|
-
argErr(pos, op, `${kind} record with a node and an edge field`, v);
|
|
138
|
-
const node = v.get('node'), edge = v.get('edge');
|
|
139
|
-
if (!(node instanceof SetBase))
|
|
140
|
-
argErr(pos, op, `${kind} record whose node field is a set`, v);
|
|
141
|
-
if (!(edge instanceof SetBase))
|
|
142
|
-
argErr(pos, op, `${kind} record whose edge field is a set`, v);
|
|
143
|
-
node.elems();
|
|
144
|
-
return { nodes: node, edges: edge.elems() };
|
|
145
|
-
}
|
|
146
|
-
function adjacency(g, parse, mode) {
|
|
147
|
-
const adj = new Map();
|
|
148
|
-
const add = (from, to) => {
|
|
149
|
-
const k = key(from);
|
|
150
|
-
const l = adj.get(k);
|
|
151
|
-
if (l)
|
|
152
|
-
l.push(to);
|
|
153
|
-
else
|
|
154
|
-
adj.set(k, [to]);
|
|
155
|
-
};
|
|
156
|
-
for (const e of g.edges) {
|
|
157
|
-
const p = parse(e);
|
|
158
|
-
if (!p)
|
|
159
|
-
continue;
|
|
160
|
-
let [from, to] = p;
|
|
161
|
-
if (!g.nodes.contains(from) || !g.nodes.contains(to))
|
|
162
|
-
continue;
|
|
163
|
-
if (mode === 'transpose')
|
|
164
|
-
[from, to] = [to, from];
|
|
165
|
-
add(from, to);
|
|
166
|
-
if (mode === 'symmetric' && !valEq(from, to))
|
|
167
|
-
add(to, from);
|
|
168
|
-
}
|
|
169
|
-
return adj;
|
|
170
|
-
}
|
|
171
|
-
function reachable(source, adj) {
|
|
172
|
-
const visited = new Set([key(source)]);
|
|
173
|
-
const frontier = [source];
|
|
174
|
-
for (let i = 0; i < frontier.length; i++) {
|
|
175
|
-
for (const succ of adj.get(key(frontier[i])) ?? []) {
|
|
176
|
-
const k = key(succ);
|
|
177
|
-
if (!visited.has(k)) {
|
|
178
|
-
visited.add(k);
|
|
179
|
-
frontier.push(succ);
|
|
180
|
-
}
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
return visited;
|
|
184
|
-
}
|
|
185
|
-
function simplePath(kind, parse, mode, graph) {
|
|
186
|
-
const g = toGraph('SimplePath', 0, kind, graph);
|
|
187
|
-
const adj = adjacency(g, parse, mode);
|
|
188
|
-
const paths = [];
|
|
189
|
-
const path = [];
|
|
190
|
-
const visited = new Set();
|
|
191
|
-
const extend = (cur) => {
|
|
192
|
-
paths.push(new TupleV(path.slice()));
|
|
193
|
-
for (const succ of adj.get(key(cur)) ?? []) {
|
|
194
|
-
const k = key(succ);
|
|
195
|
-
if (visited.has(k))
|
|
196
|
-
continue;
|
|
197
|
-
visited.add(k);
|
|
198
|
-
path.push(succ);
|
|
199
|
-
extend(succ);
|
|
200
|
-
path.pop();
|
|
201
|
-
visited.delete(k);
|
|
202
|
-
}
|
|
203
|
-
};
|
|
204
|
-
for (const start of g.nodes.elems()) {
|
|
205
|
-
path.push(start);
|
|
206
|
-
visited.add(key(start));
|
|
207
|
-
extend(start);
|
|
208
|
-
visited.delete(key(start));
|
|
209
|
-
path.pop();
|
|
210
|
-
}
|
|
211
|
-
return mkSet(paths);
|
|
212
|
-
}
|
|
213
|
-
function areConnectedIn(kind, parse, mode, m, n, graph) {
|
|
214
|
-
const g = toGraph('AreConnectedIn', 2, kind, graph);
|
|
215
|
-
if (!g.nodes.contains(m) || !g.nodes.contains(n))
|
|
216
|
-
return false;
|
|
217
|
-
if (valEq(m, n))
|
|
218
|
-
return true;
|
|
219
|
-
return reachable(m, adjacency(g, parse, mode)).has(key(n));
|
|
220
|
-
}
|
|
221
|
-
// ---- JSON (Json.java, which uses Gson) ----
|
|
222
|
-
function jsonStr(s) {
|
|
223
|
-
let o = '"';
|
|
224
|
-
for (let i = 0; i < s.length; i++) {
|
|
225
|
-
const c = s.charCodeAt(i);
|
|
226
|
-
if (c === 0x22)
|
|
227
|
-
o += '\\"';
|
|
228
|
-
else if (c === 0x5c)
|
|
229
|
-
o += '\\\\';
|
|
230
|
-
else if (c === 0x09)
|
|
231
|
-
o += '\\t';
|
|
232
|
-
else if (c === 0x08)
|
|
233
|
-
o += '\\b';
|
|
234
|
-
else if (c === 0x0a)
|
|
235
|
-
o += '\\n';
|
|
236
|
-
else if (c === 0x0d)
|
|
237
|
-
o += '\\r';
|
|
238
|
-
else if (c === 0x0c)
|
|
239
|
-
o += '\\f';
|
|
240
|
-
else if (c < 0x20 || c === 0x2028 || c === 0x2029)
|
|
241
|
-
o += '\\u' + c.toString(16).padStart(4, '0');
|
|
242
|
-
else
|
|
243
|
-
o += s[i];
|
|
244
|
-
}
|
|
245
|
-
return o + '"';
|
|
246
|
-
}
|
|
247
|
-
const jsonUnsupported = (v) => fail(`Cannot convert value: unsupported value type (${fmt(v)})`);
|
|
248
|
-
const jsonArr = (xs) => '[' + xs.map(jsonNode).join(',') + ']';
|
|
249
|
-
function jsonObj(keys, vals) {
|
|
250
|
-
const m = new Map(); // Gson's JsonObject: a repeated key keeps its position, the last value wins
|
|
251
|
-
for (let i = 0; i < keys.length; i++)
|
|
252
|
-
m.set(typeof keys[i] === 'string' ? keys[i] : fmt(keys[i]), jsonNode(vals[i]));
|
|
253
|
-
return '{' + [...m].map(([k, v]) => jsonStr(k) + ':' + v).join(',') + '}';
|
|
254
|
-
}
|
|
255
|
-
function jsonNode(v) {
|
|
256
|
-
switch (typeof v) {
|
|
257
|
-
case 'string': return jsonStr(v);
|
|
258
|
-
case 'number': return String(v);
|
|
259
|
-
case 'boolean': return v ? 'true' : 'false';
|
|
260
|
-
}
|
|
261
|
-
if (v instanceof TupleV)
|
|
262
|
-
return jsonArr(v.e);
|
|
263
|
-
if (v instanceof RecordV)
|
|
264
|
-
return jsonObj(v.names, v.vals);
|
|
265
|
-
if (v instanceof FcnV)
|
|
266
|
-
return jsonObj(v.dom, v.vals);
|
|
267
|
-
if (v instanceof ModelValue)
|
|
268
|
-
return jsonStr(v.name);
|
|
269
|
-
if (v instanceof LazyFcn)
|
|
270
|
-
return jsonNode(v.force());
|
|
271
|
-
if (v instanceof SetBase && v.enumerable())
|
|
272
|
-
return jsonArr(v.elems());
|
|
273
|
-
return jsonUnsupported(v);
|
|
274
|
-
}
|
|
275
|
-
function jsonArrayNode(v) {
|
|
276
|
-
if (v instanceof LazyFcn)
|
|
277
|
-
v = v.force();
|
|
278
|
-
if (v instanceof TupleV || v instanceof RecordV || v instanceof FcnV || (v instanceof SetBase && v.enumerable()))
|
|
279
|
-
return jsonNode(v);
|
|
280
|
-
return jsonUnsupported(v);
|
|
281
|
-
}
|
|
282
|
-
function jsonObjectNode(v) {
|
|
283
|
-
if (v instanceof LazyFcn)
|
|
284
|
-
v = v.force();
|
|
285
|
-
// TLC prints a tuple *literal* as {"0":..,"1":..} here but a function with domain 1..n as an array; the two are
|
|
286
|
-
// the same value (and indistinguishable for us), so the array form is used for every non-empty sequence.
|
|
287
|
-
if (v instanceof TupleV)
|
|
288
|
-
return v.e.length === 0 ? '{}' : jsonArr(v.e);
|
|
289
|
-
if (v instanceof RecordV || v instanceof FcnV)
|
|
290
|
-
return jsonNode(v);
|
|
291
|
-
return jsonUnsupported(v);
|
|
292
|
-
}
|
|
293
|
-
// A JSON reader that keeps object members in document order and interns strings in the order Gson + Json.java
|
|
294
|
-
// create them (member name, then its value), because TLC orders strings by first use.
|
|
295
|
-
class JsonReader {
|
|
296
|
-
s;
|
|
297
|
-
i = 0;
|
|
298
|
-
constructor(s) { this.s = s; }
|
|
299
|
-
err(msg) { return fail(`Malformed JSON: ${msg} at offset ${this.i}`); }
|
|
300
|
-
ws() { while (this.i < this.s.length && ' \t\n\r'.includes(this.s[this.i]))
|
|
301
|
-
this.i++; }
|
|
302
|
-
document() {
|
|
303
|
-
const v = this.value();
|
|
304
|
-
this.ws();
|
|
305
|
-
if (this.i < this.s.length)
|
|
306
|
-
this.err('unexpected trailing characters');
|
|
307
|
-
return v;
|
|
308
|
-
}
|
|
309
|
-
value() {
|
|
310
|
-
this.ws();
|
|
311
|
-
const c = this.s[this.i];
|
|
312
|
-
if (c === undefined)
|
|
313
|
-
return this.err('unexpected end of input');
|
|
314
|
-
if (c === '[') {
|
|
315
|
-
this.i++;
|
|
316
|
-
const out = [];
|
|
317
|
-
this.ws();
|
|
318
|
-
if (this.s[this.i] === ']') {
|
|
319
|
-
this.i++;
|
|
320
|
-
return EMPTY_TUPLE;
|
|
321
|
-
}
|
|
322
|
-
for (;;) {
|
|
323
|
-
out.push(this.value());
|
|
324
|
-
this.ws();
|
|
325
|
-
const d = this.s[this.i++];
|
|
326
|
-
if (d === ']')
|
|
327
|
-
return new TupleV(out);
|
|
328
|
-
if (d !== ',')
|
|
329
|
-
this.err("expected ',' or ']'");
|
|
330
|
-
}
|
|
331
|
-
}
|
|
332
|
-
if (c === '{') {
|
|
333
|
-
this.i++;
|
|
334
|
-
const m = new Map();
|
|
335
|
-
this.ws();
|
|
336
|
-
if (this.s[this.i] === '}') {
|
|
337
|
-
this.i++;
|
|
338
|
-
return EMPTY_TUPLE;
|
|
339
|
-
}
|
|
340
|
-
for (;;) {
|
|
341
|
-
this.ws();
|
|
342
|
-
if (this.s[this.i] !== '"')
|
|
343
|
-
this.err('expected a member name');
|
|
344
|
-
const name = this.string();
|
|
345
|
-
this.ws();
|
|
346
|
-
if (this.s[this.i++] !== ':')
|
|
347
|
-
this.err("expected ':'");
|
|
348
|
-
strId(name);
|
|
349
|
-
m.set(name, this.value());
|
|
350
|
-
this.ws();
|
|
351
|
-
const d = this.s[this.i++];
|
|
352
|
-
if (d === '}')
|
|
353
|
-
return makeRecord([...m.keys()], [...m.values()]);
|
|
354
|
-
if (d !== ',')
|
|
355
|
-
this.err("expected ',' or '}'");
|
|
356
|
-
}
|
|
357
|
-
}
|
|
358
|
-
if (c === '"') {
|
|
359
|
-
const v = this.string();
|
|
360
|
-
strId(v);
|
|
361
|
-
return v;
|
|
362
|
-
}
|
|
363
|
-
const rest = this.s.slice(this.i);
|
|
364
|
-
const kw = /^(true|false|null)(?![A-Za-z0-9_])/.exec(rest);
|
|
365
|
-
if (kw) {
|
|
366
|
-
this.i += kw[0].length;
|
|
367
|
-
if (kw[0] === 'null')
|
|
368
|
-
fail('Cannot convert value: unsupported JSON value null');
|
|
369
|
-
return kw[0] === 'true';
|
|
370
|
-
}
|
|
371
|
-
const num = /^-?(0|[1-9]\d*)(\.\d+)?([eE][+-]?\d+)?/.exec(rest);
|
|
372
|
-
if (!num)
|
|
373
|
-
return this.err(`unexpected character '${c}'`);
|
|
374
|
-
this.i += num[0].length;
|
|
375
|
-
// Gson's getAsInt(): integers wrap to 32 bits, fractions are truncated.
|
|
376
|
-
if (!num[2] && !num[3])
|
|
377
|
-
return Number(BigInt.asIntN(32, BigInt(num[0])));
|
|
378
|
-
const x = Math.trunc(Number(num[0]));
|
|
379
|
-
return Number.isFinite(x) ? Number(BigInt.asIntN(32, BigInt(x))) : 0;
|
|
380
|
-
}
|
|
381
|
-
string() {
|
|
382
|
-
let o = '';
|
|
383
|
-
this.i++;
|
|
384
|
-
for (;;) {
|
|
385
|
-
const c = this.s[this.i++];
|
|
386
|
-
if (c === undefined)
|
|
387
|
-
return this.err('unterminated string');
|
|
388
|
-
if (c === '"')
|
|
389
|
-
return o;
|
|
390
|
-
if (c !== '\\') {
|
|
391
|
-
o += c;
|
|
392
|
-
continue;
|
|
393
|
-
}
|
|
394
|
-
const e = this.s[this.i++];
|
|
395
|
-
switch (e) {
|
|
396
|
-
case 'n':
|
|
397
|
-
o += '\n';
|
|
398
|
-
break;
|
|
399
|
-
case 't':
|
|
400
|
-
o += '\t';
|
|
401
|
-
break;
|
|
402
|
-
case 'r':
|
|
403
|
-
o += '\r';
|
|
404
|
-
break;
|
|
405
|
-
case 'b':
|
|
406
|
-
o += '\b';
|
|
407
|
-
break;
|
|
408
|
-
case 'f':
|
|
409
|
-
o += '\f';
|
|
410
|
-
break;
|
|
411
|
-
case 'u': {
|
|
412
|
-
const h = this.s.slice(this.i, this.i + 4);
|
|
413
|
-
if (!/^[0-9a-fA-F]{4}$/.test(h))
|
|
414
|
-
this.err('bad \\u escape');
|
|
415
|
-
o += String.fromCharCode(parseInt(h, 16));
|
|
416
|
-
this.i += 4;
|
|
417
|
-
break;
|
|
418
|
-
}
|
|
419
|
-
case '"':
|
|
420
|
-
case '\\':
|
|
421
|
-
case '/':
|
|
422
|
-
case "'":
|
|
423
|
-
o += e;
|
|
424
|
-
break;
|
|
425
|
-
default: this.err('bad escape sequence');
|
|
426
|
-
}
|
|
427
|
-
}
|
|
428
|
-
}
|
|
429
|
-
}
|
|
430
|
-
const splitLines = (text) => {
|
|
431
|
-
const lines = text.split(/\r\n|\n|\r/);
|
|
432
|
-
if (lines.length && lines[lines.length - 1] === '')
|
|
433
|
-
lines.pop();
|
|
434
|
-
return lines;
|
|
435
|
-
};
|
|
436
|
-
// java.lang.String.format for the conversions that make sense with string arguments.
|
|
437
|
-
function javaFormat(template, params) {
|
|
438
|
-
let next = 0;
|
|
439
|
-
return template.replace(/%(\d+\$)?([-#+ 0,(<]*)(\d+)?(\.\d+)?([a-zA-Z%])/g, (all, idx, flags, width, prec, conv) => {
|
|
440
|
-
if (conv === 'n')
|
|
441
|
-
return '\n';
|
|
442
|
-
if (conv === '%')
|
|
443
|
-
return '%';
|
|
444
|
-
if (conv !== 's' && conv !== 'S')
|
|
445
|
-
return fail(`Unsupported format conversion ${all} (only %s, %n and %% are supported).`);
|
|
446
|
-
const k = idx ? parseInt(idx, 10) - 1 : flags.includes('<') ? next - 1 : next++;
|
|
447
|
-
if (k < 0 || k >= params.length)
|
|
448
|
-
return fail(`Format specifier '${all}' has no matching argument.`);
|
|
449
|
-
let v = params[k];
|
|
450
|
-
if (prec)
|
|
451
|
-
v = v.slice(0, parseInt(prec.slice(1), 10));
|
|
452
|
-
if (conv === 'S')
|
|
453
|
-
v = v.toUpperCase();
|
|
454
|
-
if (width)
|
|
455
|
-
v = flags.includes('-') ? v.padEnd(parseInt(width, 10)) : v.padStart(parseInt(width, 10));
|
|
456
|
-
return v;
|
|
457
|
-
});
|
|
458
|
-
}
|
|
459
|
-
// ---- TLC's binary value format (tlc2.value.ValueOutputStream / ValueInputStream), uncompressed ----
|
|
460
|
-
const K_BOOL = 0, K_INT = 1, K_STRING = 3, K_RECORD = 4, K_SETENUM = 5, K_TUPLE = 7, K_FCNRCD = 9, K_MODEL = 21, K_INTERVAL = 23, K_DUMMY = 26;
|
|
461
|
-
function encodeValue(v) {
|
|
462
|
-
const out = [];
|
|
463
|
-
const i32 = (x) => { out.push((x >>> 24) & 255, (x >>> 16) & 255, (x >>> 8) & 255, x & 255); };
|
|
464
|
-
const nat = (x) => { if (x > 0x7fff)
|
|
465
|
-
i32(-x);
|
|
466
|
-
else
|
|
467
|
-
out.push((x >>> 8) & 255, x & 255); };
|
|
468
|
-
const ustr = (s) => {
|
|
469
|
-
out.push(K_STRING);
|
|
470
|
-
i32(0);
|
|
471
|
-
i32(-1);
|
|
472
|
-
i32(s.length);
|
|
473
|
-
for (let i = 0; i < s.length; i++)
|
|
474
|
-
out.push(s.charCodeAt(i) & 255);
|
|
475
|
-
};
|
|
476
|
-
const w = (x) => {
|
|
477
|
-
if (typeof x === 'boolean')
|
|
478
|
-
out.push(K_BOOL, x ? 1 : 0);
|
|
479
|
-
else if (typeof x === 'number') {
|
|
480
|
-
out.push(K_INT);
|
|
481
|
-
i32(x);
|
|
482
|
-
}
|
|
483
|
-
else if (typeof x === 'string')
|
|
484
|
-
ustr(x);
|
|
485
|
-
else if (x instanceof TupleV) {
|
|
486
|
-
out.push(K_TUPLE);
|
|
487
|
-
nat(x.e.length);
|
|
488
|
-
x.e.forEach(w);
|
|
489
|
-
}
|
|
490
|
-
else if (x instanceof RecordV) {
|
|
491
|
-
// written as "not normalized" (negative length): TLC's field order depends on its own string table
|
|
492
|
-
out.push(K_RECORD);
|
|
493
|
-
i32(-x.names.length);
|
|
494
|
-
x.names.forEach((n, i) => { ustr(n); w(x.vals[i]); });
|
|
495
|
-
}
|
|
496
|
-
else if (x instanceof FcnV) {
|
|
497
|
-
out.push(K_FCNRCD);
|
|
498
|
-
nat(x.dom.length);
|
|
499
|
-
out.push(2);
|
|
500
|
-
x.dom.forEach((d, i) => { w(d); w(x.vals[i]); });
|
|
501
|
-
}
|
|
502
|
-
else if (x instanceof IntervalV) {
|
|
503
|
-
out.push(K_INTERVAL);
|
|
504
|
-
i32(x.lo);
|
|
505
|
-
i32(x.hi);
|
|
506
|
-
}
|
|
507
|
-
else if (x instanceof SetBase && x.enumerable()) {
|
|
508
|
-
const e = x.elems();
|
|
509
|
-
out.push(K_SETENUM);
|
|
510
|
-
i32(-e.length);
|
|
511
|
-
e.forEach(w);
|
|
512
|
-
}
|
|
513
|
-
else if (x instanceof LazyFcn)
|
|
514
|
-
w(x.force());
|
|
515
|
-
else
|
|
516
|
-
fail(`IOSerialize cannot serialize the value:\n${fmt(x)}`);
|
|
517
|
-
};
|
|
518
|
-
w(v);
|
|
519
|
-
return Uint8Array.from(out);
|
|
520
|
-
}
|
|
521
|
-
function decodeValue(b) {
|
|
522
|
-
let p = 0;
|
|
523
|
-
const handles = [];
|
|
524
|
-
const need = (n) => { if (p + n > b.length)
|
|
525
|
-
fail('IODeserialize: unexpected end of file.'); };
|
|
526
|
-
const u8 = () => { need(1); return b[p++]; };
|
|
527
|
-
const i16 = () => { need(2); const x = (b[p] << 8) | b[p + 1]; p += 2; return (x << 16) >> 16; };
|
|
528
|
-
const i32 = () => { need(4); const x = (b[p] << 24) | (b[p + 1] << 16) | (b[p + 2] << 8) | b[p + 3]; p += 4; return x; };
|
|
529
|
-
const nat = () => { const r = i16(); return r >= 0 ? r : -((r << 16) | (i16() & 0xffff)); };
|
|
530
|
-
const ustr = () => {
|
|
531
|
-
i32();
|
|
532
|
-
i32();
|
|
533
|
-
const n = i32();
|
|
534
|
-
need(n);
|
|
535
|
-
let s = '';
|
|
536
|
-
for (let i = 0; i < n; i++)
|
|
537
|
-
s += String.fromCharCode(b[p++]);
|
|
538
|
-
strId(s);
|
|
539
|
-
return s;
|
|
540
|
-
};
|
|
541
|
-
const r = () => {
|
|
542
|
-
const kind = u8();
|
|
543
|
-
switch (kind) {
|
|
544
|
-
case K_BOOL: return u8() !== 0;
|
|
545
|
-
case K_INT: return i32();
|
|
546
|
-
case K_STRING: {
|
|
547
|
-
const s = ustr();
|
|
548
|
-
handles.push(s);
|
|
549
|
-
return s;
|
|
550
|
-
}
|
|
551
|
-
case K_INTERVAL: {
|
|
552
|
-
const lo = i32(), hi = i32();
|
|
553
|
-
return new IntervalV(lo, hi);
|
|
554
|
-
}
|
|
555
|
-
case K_DUMMY: {
|
|
556
|
-
const idx = nat();
|
|
557
|
-
if (idx >= handles.length || handles[idx] === undefined)
|
|
558
|
-
fail('IODeserialize: dangling back reference.');
|
|
559
|
-
return handles[idx];
|
|
560
|
-
}
|
|
561
|
-
case K_MODEL: return fail('IODeserialize: model values cannot be deserialized.');
|
|
562
|
-
case K_TUPLE: {
|
|
563
|
-
const h = handles.push(undefined) - 1;
|
|
564
|
-
const n = nat(), e = [];
|
|
565
|
-
for (let i = 0; i < n; i++)
|
|
566
|
-
e.push(r());
|
|
567
|
-
return (handles[h] = tupleOf(e));
|
|
568
|
-
}
|
|
569
|
-
case K_SETENUM: {
|
|
570
|
-
const h = handles.push(undefined) - 1;
|
|
571
|
-
const n = Math.abs(i32()), e = [];
|
|
572
|
-
for (let i = 0; i < n; i++)
|
|
573
|
-
e.push(r());
|
|
574
|
-
return (handles[h] = mkSet(e));
|
|
575
|
-
}
|
|
576
|
-
case K_RECORD: {
|
|
577
|
-
const h = handles.push(undefined) - 1;
|
|
578
|
-
const n = Math.abs(i32());
|
|
579
|
-
const pairs = [];
|
|
580
|
-
for (let i = 0; i < n; i++) {
|
|
581
|
-
let name;
|
|
582
|
-
if (u8() === K_DUMMY)
|
|
583
|
-
name = handles[nat()];
|
|
584
|
-
else {
|
|
585
|
-
name = ustr();
|
|
586
|
-
handles.push(name);
|
|
587
|
-
}
|
|
588
|
-
pairs.push([name, r()]);
|
|
589
|
-
}
|
|
590
|
-
return (handles[h] = makeFcnFromPairs(pairs));
|
|
591
|
-
}
|
|
592
|
-
case K_FCNRCD: {
|
|
593
|
-
const h = handles.push(undefined) - 1;
|
|
594
|
-
const n = nat(), info = u8();
|
|
595
|
-
const pairs = [];
|
|
596
|
-
if (info === 0) {
|
|
597
|
-
const lo = i32();
|
|
598
|
-
i32();
|
|
599
|
-
for (let i = 0; i < n; i++)
|
|
600
|
-
pairs.push([lo + i, r()]);
|
|
601
|
-
}
|
|
602
|
-
else {
|
|
603
|
-
for (let i = 0; i < n; i++) {
|
|
604
|
-
const d = r();
|
|
605
|
-
pairs.push([d, r()]);
|
|
606
|
-
}
|
|
607
|
-
}
|
|
608
|
-
return (handles[h] = makeFcnFromPairs(pairs));
|
|
609
|
-
}
|
|
610
|
-
default: return fail(`ValueInputStream: Can not unpickle a value of kind ${kind}`);
|
|
611
|
-
}
|
|
612
|
-
};
|
|
613
|
-
return r();
|
|
614
|
-
}
|
|
615
|
-
// ---- statistics: chi-square goodness of fit (Apache Commons Math ChiSquareTest) ----
|
|
616
|
-
function logGamma(x) {
|
|
617
|
-
const c = [76.18009172947146, -86.50532032941677, 24.01409824083091, -1.231739572450155, 0.1208650973866179e-2, -0.5395239384953e-5];
|
|
618
|
-
let y = x, tmp = x + 5.5;
|
|
619
|
-
tmp -= (x + 0.5) * Math.log(tmp);
|
|
620
|
-
let ser = 1.000000000190015;
|
|
621
|
-
for (const cj of c)
|
|
622
|
-
ser += cj / ++y;
|
|
623
|
-
return -tmp + Math.log(2.5066282746310005 * ser / x);
|
|
624
|
-
}
|
|
625
|
-
function regularizedGammaP(a, x) {
|
|
626
|
-
if (x <= 0)
|
|
627
|
-
return 0;
|
|
628
|
-
if (x < a + 1) {
|
|
629
|
-
let sum = 1 / a, del = sum, ap = a;
|
|
630
|
-
for (let n = 0; n < 10000; n++) {
|
|
631
|
-
ap += 1;
|
|
632
|
-
del *= x / ap;
|
|
633
|
-
sum += del;
|
|
634
|
-
if (Math.abs(del) < Math.abs(sum) * 1e-15)
|
|
635
|
-
break;
|
|
636
|
-
}
|
|
637
|
-
return sum * Math.exp(-x + a * Math.log(x) - logGamma(a));
|
|
638
|
-
}
|
|
639
|
-
const tiny = 1e-300;
|
|
640
|
-
let bb = x + 1 - a, c = 1 / tiny, d = 1 / bb, h = d;
|
|
641
|
-
for (let i = 1; i < 10000; i++) {
|
|
642
|
-
const an = -i * (i - a);
|
|
643
|
-
bb += 2;
|
|
644
|
-
d = an * d + bb;
|
|
645
|
-
if (Math.abs(d) < tiny)
|
|
646
|
-
d = tiny;
|
|
647
|
-
c = bb + an / c;
|
|
648
|
-
if (Math.abs(c) < tiny)
|
|
649
|
-
c = tiny;
|
|
650
|
-
d = 1 / d;
|
|
651
|
-
const del = d * c;
|
|
652
|
-
h *= del;
|
|
653
|
-
if (Math.abs(del - 1) < 1e-15)
|
|
654
|
-
break;
|
|
655
|
-
}
|
|
656
|
-
return 1 - Math.exp(-x + a * Math.log(x) - logGamma(a)) * h;
|
|
657
|
-
}
|
|
658
|
-
const EXEC_NAMES = ['exitValue', 'stdout', 'stderr'];
|
|
659
|
-
const execResult = (exitValue, stdout, stderr) => makeRecord(EXEC_NAMES.slice(), [exitValue, stdout, stderr]);
|
|
660
|
-
function runProcess(ev, op, command, env) {
|
|
661
|
-
const h = io(ev);
|
|
662
|
-
if (!h.exec)
|
|
663
|
-
fail(`${op} is not supported: this host cannot spawn external processes.`);
|
|
664
|
-
const r = h.exec(command, env);
|
|
665
|
-
return execResult(r.exitValue, r.stdout, r.stderr);
|
|
666
|
-
}
|
|
667
|
-
const cmdStrings = (v, op) => {
|
|
668
|
-
if (!(v instanceof TupleV))
|
|
669
|
-
oneArgErr(op, 'sequence', v);
|
|
670
|
-
return v.e.map(x => (typeof x === 'string' ? x : oneArgErr('IOExec', 'sequence', x)));
|
|
671
|
-
};
|
|
672
|
-
const envRecord = (v, op) => {
|
|
673
|
-
if (!(v instanceof RecordV))
|
|
674
|
-
oneArgErr(op, 'record', v);
|
|
675
|
-
const out = {};
|
|
676
|
-
v.names.forEach((n, i) => { const x = v.vals[i]; out[n] = typeof x === 'string' ? x : fmt(x); });
|
|
677
|
-
return out;
|
|
678
|
-
};
|
|
679
|
-
const NO_CHOICE = 'Attempted to compute the value of an expression of form\nCHOOSE x \\in S: P, but no element of S satisfied P.';
|
|
680
|
-
export const OVERRIDES = {
|
|
681
|
-
FiniteSetsExt: {
|
|
682
|
-
// FoldSet(op, base, set): op(element, accumulator), elements in normalized order.
|
|
683
|
-
FoldSet: [(ev, a) => {
|
|
684
|
-
let acc = a[1];
|
|
685
|
-
for (const x of set(a[2], 'FoldSet', 2).elems())
|
|
686
|
-
acc = ev.applyOp(a[0], [x, acc]);
|
|
687
|
-
return acc;
|
|
688
|
-
}, { ops: [0] }],
|
|
689
|
-
Quantify: [(ev, a) => {
|
|
690
|
-
if (!(a[0] instanceof SetBase))
|
|
691
|
-
argErr(0, 'Quantify', 'set', a[0]);
|
|
692
|
-
let n = 0;
|
|
693
|
-
for (const x of a[0].elems())
|
|
694
|
-
if (bool(ev.applyOp(a[1], [x]), 1, 'Quantify', 'boolean-valued operator', a[1]))
|
|
695
|
-
n++;
|
|
696
|
-
return n;
|
|
697
|
-
}, { ops: [1] }],
|
|
698
|
-
SumSet: [(_, a) => set(a[0], 'SumSet', 0).elems().reduce((x, y) => int32(x + int(y, '+', 0), `${y} + ${x}`), 0)],
|
|
699
|
-
ProductSet: [(_, a) => set(a[0], 'ProductSet', 0).elems().reduce((x, y) => int32(x * int(y, '*', 0), `${y} * ${x}`), 1)],
|
|
700
|
-
Max: [(_, a) => { const e = set(a[0], 'Max', 0).elems(); if (!e.length)
|
|
701
|
-
fail(NO_CHOICE); return e.reduce((x, y) => (int(y, '>=', 0) > x ? y : x), int(e[0], '>=', 0)); }],
|
|
702
|
-
Min: [(_, a) => { const e = set(a[0], 'Min', 0).elems(); if (!e.length)
|
|
703
|
-
fail(NO_CHOICE); return e.reduce((x, y) => (int(y, '=<', 0) < x ? y : x), int(e[0], '=<', 0)); }],
|
|
704
|
-
kSubset: [(_, a) => {
|
|
705
|
-
if (!isInt(a[0]))
|
|
706
|
-
argErr(0, 'kSubset', 'natural number', a[0]);
|
|
707
|
-
if (!(a[1] instanceof SetBase))
|
|
708
|
-
argErr(1, 'kSubset', 'set', a[1]);
|
|
709
|
-
const k = a[0], base = a[1];
|
|
710
|
-
if (k < 0)
|
|
711
|
-
return EMPTY_SET;
|
|
712
|
-
if (k === 0)
|
|
713
|
-
return new SetV([EMPTY_SET]);
|
|
714
|
-
if (!base.enumerable()) {
|
|
715
|
-
return new LazySetV(`kSubset(${k}, ${fmt(base)})`, v => {
|
|
716
|
-
if (!(v instanceof SetBase))
|
|
717
|
-
return fail(`Attempted to check if the non-set value:\n${fmt(v)}\nis in kSubset(${k}, ${fmt(base)})`);
|
|
718
|
-
if (!v.enumerable())
|
|
719
|
-
return false;
|
|
720
|
-
const e = v.elems();
|
|
721
|
-
return e.length === k && e.every(x => base.contains(x));
|
|
722
|
-
});
|
|
723
|
-
}
|
|
724
|
-
const b = base.elems();
|
|
725
|
-
if (k > b.length)
|
|
726
|
-
return EMPTY_SET;
|
|
727
|
-
const out = [];
|
|
728
|
-
const idx = [];
|
|
729
|
-
const rec = (start, left) => {
|
|
730
|
-
if (left === 0) {
|
|
731
|
-
out.push(new SetV(idx.map(i => b[i])));
|
|
732
|
-
return;
|
|
733
|
-
}
|
|
734
|
-
for (let i = start; i <= b.length - left; i++) {
|
|
735
|
-
idx.push(i);
|
|
736
|
-
rec(i + 1, left - 1);
|
|
737
|
-
idx.pop();
|
|
738
|
-
}
|
|
739
|
-
};
|
|
740
|
-
rec(0, k);
|
|
741
|
-
return new SetV(out); // same-size subsets enumerated lexicographically are in normalized order
|
|
742
|
-
}],
|
|
743
|
-
},
|
|
744
|
-
Functions: {
|
|
745
|
-
Range: [(_, a) => mkSet(fcnValues(a[0] instanceof LazyFcn ? a[0].force() : a[0]).slice())],
|
|
746
|
-
// Lazy only because TLC also accepts a set-of-records expression such as [a: 1, b: 2] here (it never looks at
|
|
747
|
-
// the fields as sets, only compares them); everything else is evaluated normally.
|
|
748
|
-
IsInjective: [(ev, a) => {
|
|
749
|
-
let vals;
|
|
750
|
-
const t = a[0];
|
|
751
|
-
if (t instanceof Lazy && t.e.k === 'recset')
|
|
752
|
-
vals = t.e.fields.map(f => ev.eval(f.e, t.ctx));
|
|
753
|
-
else {
|
|
754
|
-
const f0 = ev.unthunk(t);
|
|
755
|
-
const f = f0 instanceof LazyFcn ? f0.force() : f0;
|
|
756
|
-
if (f instanceof RecSetV)
|
|
757
|
-
vals = f.sets;
|
|
758
|
-
else if (isFcn(f))
|
|
759
|
-
vals = fcnValues(f);
|
|
760
|
-
else
|
|
761
|
-
return oneArgErr('IsInjective', 'function', f);
|
|
762
|
-
}
|
|
763
|
-
for (let i = 0; i < vals.length; i++)
|
|
764
|
-
for (let j = i + 1; j < vals.length; j++)
|
|
765
|
-
if (valEq(vals[i], vals[j]))
|
|
766
|
-
return false;
|
|
767
|
-
return true;
|
|
768
|
-
}, { lazy: true }],
|
|
769
|
-
// AntiFunction(f) == [t \in Range(f) |-> CHOOSE s \in DOMAIN f : f[s] = t]: the first s in domain order.
|
|
770
|
-
AntiFunction: [(_, a) => {
|
|
771
|
-
const f = a[0] instanceof LazyFcn ? a[0].force() : a[0];
|
|
772
|
-
if (!isFcn(f))
|
|
773
|
-
oneArgErr('AntiFunction', 'functions', f);
|
|
774
|
-
const dom = domainElems(f), vals = fcnValues(f);
|
|
775
|
-
return makeFcnFromPairs(vals.map((v, i) => [v, dom[i]])); // stable: the first of equal keys is kept
|
|
776
|
-
}],
|
|
777
|
-
// FoldFunction(op, base, fun): op(fun[x], accumulator), x in normalized domain order.
|
|
778
|
-
FoldFunction: [(ev, a) => foldFunction(ev, a[0], a[1], a[2] instanceof LazyFcn ? a[2].force() : a[2]), { ops: [0] }],
|
|
779
|
-
FoldFunctionOnSet: [(ev, a) => foldFunctionOnSet(ev, a[0], a[1], a[2], a[3]), { ops: [0] }],
|
|
780
|
-
},
|
|
781
|
-
Folds: {
|
|
782
|
-
// MapThenFoldSet(op, base, f, choose, S) == iter[S] where iter[s] == op(f(x), iter[s \ {x}]) with x == choose(s):
|
|
783
|
-
// the element chosen first is combined last. (No Java override exists; this follows the TLA+ definition.)
|
|
784
|
-
MapThenFoldSet: [(ev, a) => {
|
|
785
|
-
if (!(a[4] instanceof SetBase))
|
|
786
|
-
fail(`Attempted to check if the non-enumerable value\n${fmt(a[4])}\nis element of\nSUBSET ${fmt(a[4])}`);
|
|
787
|
-
let rest = a[4].elems();
|
|
788
|
-
const picked = [];
|
|
789
|
-
while (rest.length > 0) {
|
|
790
|
-
const x = ev.applyOp(a[3], [new SetV(rest)]);
|
|
791
|
-
const i = bsearch(rest, x);
|
|
792
|
-
if (i < 0)
|
|
793
|
-
fail(`The choose operator of MapThenFoldSet returned\n${fmt(x)}\nwhich is not an element of the set it was applied to.`);
|
|
794
|
-
picked.push(rest[i]);
|
|
795
|
-
rest = rest.slice(0, i).concat(rest.slice(i + 1));
|
|
796
|
-
}
|
|
797
|
-
let acc = a[1];
|
|
798
|
-
for (let i = picked.length - 1; i >= 0; i--)
|
|
799
|
-
acc = ev.applyOp(a[0], [ev.applyOp(a[2], [picked[i]]), acc]);
|
|
800
|
-
return acc;
|
|
801
|
-
}, { ops: [0, 2, 3] }],
|
|
802
|
-
},
|
|
803
|
-
BagsExt: {
|
|
804
|
-
// FoldBag(op, base, bag): op(accumulator, element), once per copy, elements in normalized domain order.
|
|
805
|
-
FoldBag: [(ev, a) => {
|
|
806
|
-
const bag = a[2] instanceof LazyFcn ? a[2].force() : a[2];
|
|
807
|
-
if (!isFcn(bag))
|
|
808
|
-
argErr(2, 'FoldBag', 'bag', bag);
|
|
809
|
-
const dom = domainElems(bag), vals = fcnValues(bag);
|
|
810
|
-
let acc = a[1];
|
|
811
|
-
for (let i = 0; i < dom.length; i++) {
|
|
812
|
-
const n = vals[i];
|
|
813
|
-
if (!isInt(n) || n <= 0) {
|
|
814
|
-
fail(`Applying FoldBag to the following value,\nwhich is not an element of Nat:\n${fmt(n)} (in: ${fmt(dom[i])}:>${fmt(n)})`);
|
|
815
|
-
}
|
|
816
|
-
for (let j = 0; j < n; j++)
|
|
817
|
-
acc = ev.applyOp(a[0], [acc, dom[i]]);
|
|
818
|
-
}
|
|
819
|
-
return acc;
|
|
820
|
-
}, { ops: [0] }],
|
|
821
|
-
},
|
|
822
|
-
SequencesExt: {
|
|
823
|
-
// FoldSeq(op, base, seq) == FoldFunction(op, base, seq): op(element, accumulator), left to right.
|
|
824
|
-
FoldSeq: [(ev, a) => foldFunction(ev, a[0], a[1], a[2]), { ops: [0] }],
|
|
825
|
-
// FoldLeft(op, base, seq): op(accumulator, element), left to right.
|
|
826
|
-
FoldLeft: [(ev, a) => {
|
|
827
|
-
if (!(a[2] instanceof TupleV))
|
|
828
|
-
argErr(2, 'FoldLeft', 'sequence', a[2]);
|
|
829
|
-
let acc = a[1];
|
|
830
|
-
for (const x of a[2].e)
|
|
831
|
-
acc = ev.applyOp(a[0], [acc, x]);
|
|
832
|
-
return acc;
|
|
833
|
-
}, { ops: [0] }],
|
|
834
|
-
// FoldRight(op, seq, base): op(element, accumulator), right to left.
|
|
835
|
-
FoldRight: [(ev, a) => {
|
|
836
|
-
if (!(a[1] instanceof TupleV))
|
|
837
|
-
argErr(1, 'FoldRight', 'sequence', a[1]);
|
|
838
|
-
let acc = a[2];
|
|
839
|
-
const s = a[1].e;
|
|
840
|
-
for (let i = s.length - 1; i >= 0; i--)
|
|
841
|
-
acc = ev.applyOp(a[0], [s[i], acc]);
|
|
842
|
-
return acc;
|
|
843
|
-
}, { ops: [0] }],
|
|
844
|
-
FoldLeftDomain: [(ev, a) => {
|
|
845
|
-
if (!(a[2] instanceof TupleV))
|
|
846
|
-
argErr(2, 'FoldLeftDomain', 'sequence', a[2]);
|
|
847
|
-
let acc = a[1];
|
|
848
|
-
for (let i = 1; i <= a[2].e.length; i++)
|
|
849
|
-
acc = ev.applyOp(a[0], [acc, i]);
|
|
850
|
-
return acc;
|
|
851
|
-
}, { ops: [0] }],
|
|
852
|
-
FoldRightDomain: [(ev, a) => {
|
|
853
|
-
if (!(a[1] instanceof TupleV))
|
|
854
|
-
argErr(1, 'FoldRightDomain', 'sequence', a[1]);
|
|
855
|
-
let acc = a[2];
|
|
856
|
-
for (let i = a[1].e.length; i >= 1; i--)
|
|
857
|
-
acc = ev.applyOp(a[0], [i, acc]);
|
|
858
|
-
return acc;
|
|
859
|
-
}, { ops: [0] }],
|
|
860
|
-
ToSet: [(_, a) => mkSet(fcnValues(a[0] instanceof LazyFcn ? a[0].force() : a[0]).slice())],
|
|
861
|
-
Reverse: [(_, a) => tupleOf(seq(a[0], 'Reverse', 0).slice().reverse())],
|
|
862
|
-
Cons: [(_, a) => new TupleV([a[0], ...seq(a[1], 'Cons', 1)])],
|
|
863
|
-
Front: [(_, a) => (typeof a[0] === 'string' ? a[0].slice(0, -1) : tupleOf(seq(a[0], 'Front', 0).slice(0, -1)))],
|
|
864
|
-
Last: [(ev, a) => { const s = seq(a[0], 'Last', 0); return s.length ? s[s.length - 1] : ev.applyFcn(a[0], 0); }],
|
|
865
|
-
IsSuffix: [(_, a) => { const s = seq(a[0], 'IsSuffix', 0), t = seq(a[1], 'IsSuffix', 1); const o = t.length - s.length; return o >= 0 && s.every((x, i) => valEq(x, t[o + i])); }],
|
|
866
|
-
Contains: [(_, a) => {
|
|
867
|
-
if (!(a[0] instanceof TupleV))
|
|
868
|
-
oneArgErr('Contains', 'sequence', a[0]);
|
|
869
|
-
for (const x of a[0].e)
|
|
870
|
-
if (valEq(x, a[1]))
|
|
871
|
-
return true;
|
|
872
|
-
return false;
|
|
873
|
-
}],
|
|
874
|
-
IsPrefix: [(_, a) => {
|
|
875
|
-
if (typeof a[0] === 'string' && typeof a[1] === 'string')
|
|
876
|
-
return a[1].startsWith(a[0]);
|
|
877
|
-
const s = seq(a[0], 'IsPrefix', 0), t = seq(a[1], 'IsPrefix', 1);
|
|
878
|
-
if (s.length > t.length)
|
|
879
|
-
return false;
|
|
880
|
-
for (let i = 0; i < s.length; i++)
|
|
881
|
-
if (!valEq(s[i], t[i]))
|
|
882
|
-
return false;
|
|
883
|
-
return true;
|
|
884
|
-
}],
|
|
885
|
-
SetToSeq: [(_, a) => tupleOf(set(a[0], 'SetToSeq', 0).elems().slice())],
|
|
886
|
-
SetToSeqs: [(_, a) => {
|
|
887
|
-
if (!(a[0] instanceof SetBase) || !a[0].enumerable())
|
|
888
|
-
fail(`Applying SetToSeqs to the following value,\nwhich is not a finite set:\n${fmt(a[0])}`);
|
|
889
|
-
return mkSet(permutations(a[0].elems()));
|
|
890
|
-
}],
|
|
891
|
-
LongestCommonPrefix: [(_, a) => {
|
|
892
|
-
if (!(a[0] instanceof SetBase))
|
|
893
|
-
oneArgErr('LongestCommonPrefix', 'non-empty set', a[0]);
|
|
894
|
-
const e = a[0].elems();
|
|
895
|
-
if (e.length === 0)
|
|
896
|
-
oneArgErr('LongestCommonPrefix', 'non-empty set', a[0]);
|
|
897
|
-
if (typeof e[0] === 'string') {
|
|
898
|
-
let prefix = e[0];
|
|
899
|
-
for (const o of e) {
|
|
900
|
-
if (typeof o !== 'string')
|
|
901
|
-
oneArgErr('LongestCommonPrefix', 'sequence', a[0]);
|
|
902
|
-
let n = 0;
|
|
903
|
-
while (n < prefix.length && n < o.length && prefix[n] === o[n])
|
|
904
|
-
n++;
|
|
905
|
-
prefix = prefix.slice(0, n);
|
|
906
|
-
}
|
|
907
|
-
return prefix;
|
|
908
|
-
}
|
|
909
|
-
if (!(e[0] instanceof TupleV))
|
|
910
|
-
oneArgErr('LongestCommonPrefix', 'sequence', a[0]);
|
|
911
|
-
const first = e[0].e;
|
|
912
|
-
let upper = first.length;
|
|
913
|
-
for (const o of e) {
|
|
914
|
-
if (!(o instanceof TupleV))
|
|
915
|
-
oneArgErr('LongestCommonPrefix', 'sequence', a[0]);
|
|
916
|
-
let n = 0;
|
|
917
|
-
while (n < upper && n < o.e.length && valEq(first[n], o.e[n]))
|
|
918
|
-
n++;
|
|
919
|
-
upper = n;
|
|
920
|
-
}
|
|
921
|
-
return tupleOf(first.slice(0, upper));
|
|
922
|
-
}],
|
|
923
|
-
SelectInSeq: [(ev, a) => selectIn(ev, a, 'SelectInSeq', false, false), { ops: [1] }],
|
|
924
|
-
SelectInSubSeq: [(ev, a) => selectIn(ev, a, 'SelectInSubSeq', false, true), { ops: [3] }],
|
|
925
|
-
SelectLastInSeq: [(ev, a) => selectIn(ev, a, 'SelectLastInSeq', true, false), { ops: [1] }],
|
|
926
|
-
SelectLastInSubSeq: [(ev, a) => selectIn(ev, a, 'SelectLastInSubSeq', true, true), { ops: [3] }],
|
|
927
|
-
RemoveFirst: [(_, a) => {
|
|
928
|
-
if (!(a[0] instanceof TupleV))
|
|
929
|
-
argErr(0, 'RemoveFirst', 'sequence', a[0]);
|
|
930
|
-
const s = a[0].e;
|
|
931
|
-
const i = s.findIndex(x => valEq(x, a[1]));
|
|
932
|
-
return i < 0 ? a[0] : tupleOf(s.slice(0, i).concat(s.slice(i + 1)));
|
|
933
|
-
}],
|
|
934
|
-
RemoveFirstMatch: [(ev, a) => {
|
|
935
|
-
if (!(a[0] instanceof TupleV))
|
|
936
|
-
argErr(0, 'RemoveFirstMatch', 'sequence', a[0]);
|
|
937
|
-
const s = a[0].e;
|
|
938
|
-
const i = s.findIndex(x => bool(ev.applyOp(a[1], [x]), 1, 'RemoveFirstMatch', 'boolean-valued function', a[1]));
|
|
939
|
-
return i < 0 ? a[0] : tupleOf(s.slice(0, i).concat(s.slice(i + 1)));
|
|
940
|
-
}, { ops: [1] }],
|
|
941
|
-
Suffixes: [(_, a) => {
|
|
942
|
-
if (!(a[0] instanceof TupleV))
|
|
943
|
-
oneArgErr('Suffixes', 'sequence', a[0]);
|
|
944
|
-
const s = a[0].e;
|
|
945
|
-
const out = [EMPTY_TUPLE];
|
|
946
|
-
for (let i = s.length - 1; i >= 0; i--)
|
|
947
|
-
out.push(new TupleV(s.slice(i)));
|
|
948
|
-
return mkSet(out);
|
|
949
|
-
}],
|
|
950
|
-
AllSubSeqs: [(_, a) => {
|
|
951
|
-
if (!(a[0] instanceof TupleV))
|
|
952
|
-
oneArgErr('AllSubSeqs', 'sequence', a[0]);
|
|
953
|
-
const s = a[0].e;
|
|
954
|
-
if (s.length > 26)
|
|
955
|
-
fail(`Attempted to enumerate AllSubSeqs of a sequence with ${s.length} elements; this is too large.`);
|
|
956
|
-
const out = [];
|
|
957
|
-
for (let m = 0; m < 2 ** s.length; m++)
|
|
958
|
-
out.push(tupleOf(s.filter((_x, j) => (m & (1 << j)) !== 0)));
|
|
959
|
-
return mkSet(out);
|
|
960
|
-
}],
|
|
961
|
-
// ReplaceFirstSubSeq(r, s, t): replace the first occurrence of the subsequence s in t by r. TLC overrides the
|
|
962
|
-
// string case only; the sequence case is the same computation as the TLA+ definition.
|
|
963
|
-
ReplaceFirstSubSeq: [(_, a) => {
|
|
964
|
-
const [r, s, t] = a;
|
|
965
|
-
if (typeof r === 'string' && typeof s === 'string' && typeof t === 'string') {
|
|
966
|
-
const i = t.indexOf(s);
|
|
967
|
-
return s === '' ? r + t : i < 0 ? t : t.slice(0, i) + r + t.slice(i + s.length);
|
|
968
|
-
}
|
|
969
|
-
const rs = seq(r, 'ReplaceFirstSubSeq', 0), ss = seq(s, 'ReplaceFirstSubSeq', 1), ts = seq(t, 'ReplaceFirstSubSeq', 2);
|
|
970
|
-
const i = subSeqIndex(ss, ts, 0);
|
|
971
|
-
return i < 0 ? t : tupleOf(ts.slice(0, i).concat(rs, ts.slice(i + ss.length)));
|
|
972
|
-
}],
|
|
973
|
-
// ReplaceAllSubSeqs(r, s, t): replace all (non-overlapping, leftmost first) occurrences of s in t by r.
|
|
974
|
-
ReplaceAllSubSeqs: [(_, a) => {
|
|
975
|
-
const [r, s, t] = a;
|
|
976
|
-
if (typeof r === 'string' && typeof s === 'string' && typeof t === 'string') {
|
|
977
|
-
if (s === '')
|
|
978
|
-
return r + t.split('').join(r);
|
|
979
|
-
return t.split(s).join(r);
|
|
980
|
-
}
|
|
981
|
-
const rs = seq(r, 'ReplaceAllSubSeqs', 0), ss = seq(s, 'ReplaceAllSubSeqs', 1), ts = seq(t, 'ReplaceAllSubSeqs', 2);
|
|
982
|
-
if (valEq(s, t))
|
|
983
|
-
return r;
|
|
984
|
-
if (valEq(r, s))
|
|
985
|
-
return t;
|
|
986
|
-
const out = [];
|
|
987
|
-
if (ss.length === 0) {
|
|
988
|
-
for (const x of ts) {
|
|
989
|
-
out.push(...rs);
|
|
990
|
-
out.push(x);
|
|
991
|
-
}
|
|
992
|
-
return tupleOf(out);
|
|
993
|
-
}
|
|
994
|
-
let i = 0, hit = false;
|
|
995
|
-
while (i < ts.length) {
|
|
996
|
-
if (subSeqIndex(ss, ts, i) === i) {
|
|
997
|
-
out.push(...rs);
|
|
998
|
-
i += ss.length;
|
|
999
|
-
hit = true;
|
|
1000
|
-
}
|
|
1001
|
-
else
|
|
1002
|
-
out.push(ts[i++]);
|
|
1003
|
-
}
|
|
1004
|
-
return hit ? tupleOf(out) : t;
|
|
1005
|
-
}],
|
|
1006
|
-
},
|
|
1007
|
-
Combinatorics: {
|
|
1008
|
-
// (TLC's `factorial` override is never reached for the function definition factorial[n]; its TLA+ definition is used.)
|
|
1009
|
-
choose: [(_, a) => {
|
|
1010
|
-
const [n, k] = a;
|
|
1011
|
-
if (!isInt(n) || n < 0)
|
|
1012
|
-
argErr(0, 'choose', 'natural number', n);
|
|
1013
|
-
if (!isInt(k) || k < 0)
|
|
1014
|
-
argErr(1, 'choose', 'natural number', k);
|
|
1015
|
-
if (k === 0 || k === n)
|
|
1016
|
-
return 1;
|
|
1017
|
-
if (k === 1 || k === n - 1)
|
|
1018
|
-
return n;
|
|
1019
|
-
if (n === 0 || k > n)
|
|
1020
|
-
return 0;
|
|
1021
|
-
let r = 1n;
|
|
1022
|
-
for (let i = 1n, j = BigInt(n); i <= BigInt(Math.min(k, n - k)); i++, j--)
|
|
1023
|
-
r = (r * j) / i;
|
|
1024
|
-
if (r > 2147483647n)
|
|
1025
|
-
fail(`Overflow when computing ${n}choose${k}`);
|
|
1026
|
-
return Number(r);
|
|
1027
|
-
}],
|
|
1028
|
-
},
|
|
1029
|
-
Bitwise: {
|
|
1030
|
-
And: [(_, a) => int(a[0], 'And', 0) & int(a[1], 'And', 1)],
|
|
1031
|
-
Or: [(_, a) => int(a[0], 'Or', 0) | int(a[1], 'Or', 1)],
|
|
1032
|
-
Xor: [(_, a) => int(a[0], 'Xor', 0) ^ int(a[1], 'Xor', 1)],
|
|
1033
|
-
// Flips only the bits below the highest set bit (the TLA+ definition has no word size to work with).
|
|
1034
|
-
Not: [(_, a) => { const x = int(a[0], 'Not', 0); return ~x & (2147483647 >> (Math.clz32(x) - 1)); }],
|
|
1035
|
-
shiftR: [(_, a) => (int(a[0], 'shiftR', 0) >>> int(a[1], 'shiftR', 1)) | 0],
|
|
1036
|
-
},
|
|
1037
|
-
DyadicRationals: {
|
|
1038
|
-
Reduce: [(_, a) => {
|
|
1039
|
-
const p = a[0];
|
|
1040
|
-
if (!(p instanceof RecordV))
|
|
1041
|
-
oneArgErr('Half', 'record', p);
|
|
1042
|
-
const num = int(p.get('num'), 'Reduce', 0), den = int(p.get('den'), 'Reduce', 0);
|
|
1043
|
-
let x = Math.abs(num), y = Math.abs(den);
|
|
1044
|
-
while (y)
|
|
1045
|
-
[x, y] = [y, x % y];
|
|
1046
|
-
if (x === 1)
|
|
1047
|
-
return p;
|
|
1048
|
-
if (x === 0)
|
|
1049
|
-
fail('The second argument of \\div is 0.');
|
|
1050
|
-
return makeRecord(['den', 'num'], [Math.trunc(den / x), Math.trunc(num / x)]);
|
|
1051
|
-
}],
|
|
1052
|
-
},
|
|
1053
|
-
VectorClocks: {
|
|
1054
|
-
// CausalOrder(log, clock(_), node(_), domain(_)): a topological sort of the log by its vector clocks.
|
|
1055
|
-
CausalOrder: [(ev, a) => {
|
|
1056
|
-
if (!(a[0] instanceof TupleV))
|
|
1057
|
-
argErr(0, 'CausalOrder', 'sequence', a[0]);
|
|
1058
|
-
const log = a[0].e;
|
|
1059
|
-
const n2l = new Map();
|
|
1060
|
-
for (const value of log) {
|
|
1061
|
-
const nodeId = ev.applyOp(a[2], [value]);
|
|
1062
|
-
const clock = ev.applyOp(a[1], [value]);
|
|
1063
|
-
const time = ev.applyFcn(clock, nodeId);
|
|
1064
|
-
const hosts = set(ev.applyOp(a[3], [clock]), 'CausalOrder', 3).elems();
|
|
1065
|
-
const k = key(nodeId);
|
|
1066
|
-
let list = n2l.get(k);
|
|
1067
|
-
if (!list)
|
|
1068
|
-
n2l.set(k, (list = []));
|
|
1069
|
-
list.push({ value, clock, time, hosts, parents: new Set(), children: new Set() });
|
|
1070
|
-
}
|
|
1071
|
-
// A node's own clock component totally orders its events.
|
|
1072
|
-
for (const list of n2l.values())
|
|
1073
|
-
list.sort((x, y) => compare(x.time, y.time));
|
|
1074
|
-
// Merge the per-node logs into a DAG: an event depends on the latest event of every other node it has seen.
|
|
1075
|
-
for (const [host, list] of n2l) {
|
|
1076
|
-
const global = new Map();
|
|
1077
|
-
for (const h of n2l.keys())
|
|
1078
|
-
global.set(h, 0);
|
|
1079
|
-
for (const gn of list) {
|
|
1080
|
-
global.set(host, gn.time);
|
|
1081
|
-
for (const other of gn.hosts) {
|
|
1082
|
-
const ok = key(other), seen = global.get(ok);
|
|
1083
|
-
const time = ev.applyFcn(gn.clock, other);
|
|
1084
|
-
if (seen === undefined) {
|
|
1085
|
-
// a node without events of its own; it cannot precede anything unless the clock says it did something
|
|
1086
|
-
if (compare(0, time) < 0)
|
|
1087
|
-
fail(`CausalOrder: the log has no events of node ${fmt(other)}, but a vector clock refers to its event ${fmt(time)}.`);
|
|
1088
|
-
continue;
|
|
1089
|
-
}
|
|
1090
|
-
if (compare(seen, time) < 0) {
|
|
1091
|
-
global.set(ok, time);
|
|
1092
|
-
const parent = n2l.get(ok)[int(time, 'CausalOrder', 0) - 1];
|
|
1093
|
-
if (!parent)
|
|
1094
|
-
fail(`CausalOrder: the log lacks event ${fmt(time)} of node ${fmt(other)} (vector clocks must be continuous).`);
|
|
1095
|
-
gn.parents.add(parent);
|
|
1096
|
-
parent.children.add(gn);
|
|
1097
|
-
}
|
|
1098
|
-
}
|
|
1099
|
-
}
|
|
1100
|
-
}
|
|
1101
|
-
// Repeatedly pop the heads that have no pending predecessor.
|
|
1102
|
-
const sorted = [];
|
|
1103
|
-
const heads = new Map();
|
|
1104
|
-
for (let round = 0; round < log.length && sorted.length < log.length; round++) {
|
|
1105
|
-
for (const [host, list] of n2l) {
|
|
1106
|
-
const i = heads.get(host) ?? 0;
|
|
1107
|
-
if (i >= list.length || list[i].parents.size > 0)
|
|
1108
|
-
continue;
|
|
1109
|
-
heads.set(host, i + 1);
|
|
1110
|
-
for (const c of list[i].children)
|
|
1111
|
-
c.parents.delete(list[i]);
|
|
1112
|
-
sorted.push(list[i].value);
|
|
1113
|
-
}
|
|
1114
|
-
}
|
|
1115
|
-
return tupleOf(sorted);
|
|
1116
|
-
}, { ops: [1, 2, 3] }],
|
|
1117
|
-
},
|
|
1118
|
-
Statistics: {
|
|
1119
|
-
// TRUE iff the chi-square goodness-of-fit test does NOT reject, at significance alpha, that `actual` follows `expected`.
|
|
1120
|
-
ChiSquare: [(_, a) => {
|
|
1121
|
-
if (!isFcn(a[0]))
|
|
1122
|
-
argErr(0, 'ChiSquare', 'function', a[0]);
|
|
1123
|
-
if (!isFcn(a[1]))
|
|
1124
|
-
argErr(1, 'ChiSquare', 'function', a[1]);
|
|
1125
|
-
if (typeof a[2] !== 'string')
|
|
1126
|
-
argErr(2, 'ChiSquare', 'StringValue representing a double in (0, .5]', a[2]);
|
|
1127
|
-
const exp = fcnValues(a[0]).map(v => int(v, 'ChiSquare', 0)), act = fcnValues(a[1]).map(v => int(v, 'ChiSquare', 1));
|
|
1128
|
-
const alpha = Number(a[2]);
|
|
1129
|
-
if (!(alpha > 0 && alpha <= 0.5))
|
|
1130
|
-
fail(`out of bounds significance level (${a[2]}), must be between 0 and 0.5`);
|
|
1131
|
-
if (exp.length < 2)
|
|
1132
|
-
fail(`${exp.length} is smaller than the minimum (2)`);
|
|
1133
|
-
if (exp.length !== act.length)
|
|
1134
|
-
fail(`${exp.length} != ${act.length}`);
|
|
1135
|
-
for (const e of exp)
|
|
1136
|
-
if (e <= 0)
|
|
1137
|
-
fail(`element is not strictly positive: ${e}`);
|
|
1138
|
-
for (const o of act)
|
|
1139
|
-
if (o < 0)
|
|
1140
|
-
fail(`element is negative: ${o}`);
|
|
1141
|
-
const sumE = exp.reduce((x, y) => x + y, 0), sumO = act.reduce((x, y) => x + y, 0);
|
|
1142
|
-
const rescale = Math.abs(sumE - sumO) > 10e-6, ratio = rescale ? sumO / sumE : 1;
|
|
1143
|
-
let chi = 0;
|
|
1144
|
-
for (let i = 0; i < exp.length; i++) {
|
|
1145
|
-
const e = rescale ? ratio * exp[i] : exp[i], dev = act[i] - e;
|
|
1146
|
-
chi += dev * dev / e;
|
|
1147
|
-
}
|
|
1148
|
-
const p = 1 - regularizedGammaP((exp.length - 1) / 2, chi / 2);
|
|
1149
|
-
return !(p < alpha);
|
|
1150
|
-
}],
|
|
1151
|
-
},
|
|
1152
|
-
Graphs: {
|
|
1153
|
-
SimplePath: [(_, a) => simplePath('graph', TUPLE_EDGE, 'forward', a[0])],
|
|
1154
|
-
AreConnectedIn: [(_, a) => areConnectedIn('graph', TUPLE_EDGE, 'forward', a[0], a[1], a[2])],
|
|
1155
|
-
IsStronglyConnected: [(_, a) => {
|
|
1156
|
-
const g = toGraph('IsStronglyConnected', 0, 'graph', a[0]);
|
|
1157
|
-
const nodes = g.nodes.elems();
|
|
1158
|
-
if (nodes.length === 0)
|
|
1159
|
-
return true;
|
|
1160
|
-
return reachable(nodes[0], adjacency(g, TUPLE_EDGE, 'forward')).size === nodes.length
|
|
1161
|
-
&& reachable(nodes[0], adjacency(g, TUPLE_EDGE, 'transpose')).size === nodes.length;
|
|
1162
|
-
}],
|
|
1163
|
-
},
|
|
1164
|
-
UndirectedGraphs: {
|
|
1165
|
-
SimplePath: [(_, a) => simplePath('undirected graph', PAIR_EDGE, 'symmetric', a[0])],
|
|
1166
|
-
AreConnectedIn: [(_, a) => areConnectedIn('undirected graph', PAIR_EDGE, 'symmetric', a[0], a[1], a[2])],
|
|
1167
|
-
ConnectedComponents: [(_, a) => {
|
|
1168
|
-
const g = toGraph('ConnectedComponents', 0, 'undirected graph', a[0]);
|
|
1169
|
-
const nodes = g.nodes.elems();
|
|
1170
|
-
const parent = new Map();
|
|
1171
|
-
for (const n of nodes)
|
|
1172
|
-
parent.set(key(n), key(n));
|
|
1173
|
-
const find = (k) => {
|
|
1174
|
-
let root = k;
|
|
1175
|
-
while (parent.get(root) !== root)
|
|
1176
|
-
root = parent.get(root);
|
|
1177
|
-
while (k !== root) {
|
|
1178
|
-
const next = parent.get(k);
|
|
1179
|
-
parent.set(k, root);
|
|
1180
|
-
k = next;
|
|
1181
|
-
}
|
|
1182
|
-
return root;
|
|
1183
|
-
};
|
|
1184
|
-
for (const e of g.edges) {
|
|
1185
|
-
const p = PAIR_EDGE(e);
|
|
1186
|
-
if (!p || !g.nodes.contains(p[0]) || !g.nodes.contains(p[1]))
|
|
1187
|
-
continue;
|
|
1188
|
-
const x = find(key(p[0])), y = find(key(p[1]));
|
|
1189
|
-
if (x !== y)
|
|
1190
|
-
parent.set(y, x);
|
|
1191
|
-
}
|
|
1192
|
-
const comps = new Map();
|
|
1193
|
-
for (const n of nodes) {
|
|
1194
|
-
const rep = find(key(n));
|
|
1195
|
-
const c = comps.get(rep);
|
|
1196
|
-
if (c)
|
|
1197
|
-
c.push(n);
|
|
1198
|
-
else
|
|
1199
|
-
comps.set(rep, [n]);
|
|
1200
|
-
}
|
|
1201
|
-
return mkSet([...comps.values()].map(c => new SetV(c)));
|
|
1202
|
-
}],
|
|
1203
|
-
},
|
|
1204
|
-
Json: {
|
|
1205
|
-
ToJson: [(_, a) => jsonNode(a[0])],
|
|
1206
|
-
ToJsonArray: [(_, a) => jsonArrayNode(a[0])],
|
|
1207
|
-
ToJsonObject: [(_, a) => jsonObjectNode(a[0])],
|
|
1208
|
-
JsonSerialize: [(ev, a) => {
|
|
1209
|
-
const path = str(a[0], 'JsonSerialize', 0);
|
|
1210
|
-
if (!(a[1] instanceof TupleV) && !(a[1] instanceof RecordV))
|
|
1211
|
-
argErr(1, 'JsonSerialize', 'sequence or record', a[1]);
|
|
1212
|
-
const text = jsonNode(a[1]);
|
|
1213
|
-
hostWrite(() => io(ev).writeFile(path, text), path);
|
|
1214
|
-
return true;
|
|
1215
|
-
}],
|
|
1216
|
-
ndJsonSerialize: [(ev, a) => {
|
|
1217
|
-
const path = str(a[0], 'ndJsonSerialize', 0);
|
|
1218
|
-
if (!(a[1] instanceof TupleV))
|
|
1219
|
-
argErr(1, 'ndJsonSerialize', 'sequence', a[1]);
|
|
1220
|
-
const text = a[1].e.map(v => jsonNode(v) + '\n').join('');
|
|
1221
|
-
hostWrite(() => io(ev).writeFile(path, text), path);
|
|
1222
|
-
return true;
|
|
1223
|
-
}],
|
|
1224
|
-
JsonDeserialize: [(ev, a) => new JsonReader(readText(ev, str(a[0], 'JsonDeserialize', 0))).document()],
|
|
1225
|
-
ndJsonDeserialize: [(ev, a) => {
|
|
1226
|
-
const out = [];
|
|
1227
|
-
for (const line of readText(ev, str(a[0], 'ndJsonDeserialize', 0)).split(/\r\n|\n|\r/)) {
|
|
1228
|
-
const t = line.trim();
|
|
1229
|
-
if (t !== '')
|
|
1230
|
-
out.push(new JsonReader(t).document());
|
|
1231
|
-
}
|
|
1232
|
-
return tupleOf(out);
|
|
1233
|
-
}],
|
|
1234
|
-
},
|
|
1235
|
-
CSV: {
|
|
1236
|
-
// Appends the record's values (and, if `headers`, first its field names) joined by `delim`.
|
|
1237
|
-
CSVWriteRecord: [(ev, a) => {
|
|
1238
|
-
if (!(a[0] instanceof RecordV))
|
|
1239
|
-
oneArgErr('CSVWriteRecord', 'record', a[0]);
|
|
1240
|
-
const rec = a[0], delim = str(a[1], 'CSVWriteRecord', 1), path = str(a[3], 'CSVWriteRecord', 3);
|
|
1241
|
-
if (typeof a[2] !== 'boolean')
|
|
1242
|
-
argErr(2, 'CSVWriteRecord', 'boolean', a[2]);
|
|
1243
|
-
let text = '';
|
|
1244
|
-
if (a[2])
|
|
1245
|
-
text += rec.names.join(delim) + '\n';
|
|
1246
|
-
text += rec.vals.map(fmt).join(delim) + '\n';
|
|
1247
|
-
hostWrite(() => io(ev).appendFile(path, text), path);
|
|
1248
|
-
return true;
|
|
1249
|
-
}],
|
|
1250
|
-
// Appends String.format(template, values printed as TLA+ values) as one line.
|
|
1251
|
-
CSVWrite: [(ev, a) => {
|
|
1252
|
-
const template = str(a[0], 'CSVWrite', 0), path = str(a[2], 'CSVWrite', 2);
|
|
1253
|
-
if (!(a[1] instanceof TupleV))
|
|
1254
|
-
oneArgErr('CSVWrite', 'sequence', a[1]);
|
|
1255
|
-
const text = javaFormat(template, a[1].e.map(fmt)) + '\n';
|
|
1256
|
-
hostWrite(() => io(ev).appendFile(path, text), path);
|
|
1257
|
-
return true;
|
|
1258
|
-
}],
|
|
1259
|
-
CSVRead: [(ev, a) => {
|
|
1260
|
-
if (!(a[0] instanceof TupleV))
|
|
1261
|
-
oneArgErr('CSVRead', 'sequence', a[0]);
|
|
1262
|
-
const names = a[0].e.map((n, i) => (typeof n === 'string' ? n : fail(`Column name ${i + 1} of CSVRead should be a string, but instead it is:\n${fmt(n)}`)));
|
|
1263
|
-
const delim = str(a[1], 'CSVRead', 1), path = str(a[2], 'CSVRead', 2);
|
|
1264
|
-
if (!io(ev).exists(path))
|
|
1265
|
-
return EMPTY_TUPLE;
|
|
1266
|
-
let re;
|
|
1267
|
-
try {
|
|
1268
|
-
re = new RegExp(delim);
|
|
1269
|
-
}
|
|
1270
|
-
catch {
|
|
1271
|
-
re = new RegExp(delim.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
|
|
1272
|
-
}
|
|
1273
|
-
return tupleOf(splitLines(readText(ev, path)).map(line => {
|
|
1274
|
-
const cells = line.split(re); // Java's String.split: a regex, trailing empty strings removed
|
|
1275
|
-
while (cells.length > 1 && cells[cells.length - 1] === '')
|
|
1276
|
-
cells.pop();
|
|
1277
|
-
for (const c of cells)
|
|
1278
|
-
strId(c);
|
|
1279
|
-
// surplus fields are ignored; a short line yields a record without the trailing columns
|
|
1280
|
-
return makeFcnFromPairs(names.slice(0, cells.length).map((n, i) => [n, cells[i]]));
|
|
1281
|
-
}));
|
|
1282
|
-
}],
|
|
1283
|
-
CSVRecords: [(ev, a) => {
|
|
1284
|
-
const path = str(a[0], 'CSVRecords', 0);
|
|
1285
|
-
return io(ev).exists(path) ? splitLines(readText(ev, path)).length : 0;
|
|
1286
|
-
}],
|
|
1287
|
-
},
|
|
1288
|
-
IOUtils: {
|
|
1289
|
-
IOEnv: [ev => {
|
|
1290
|
-
const env = io(ev).env;
|
|
1291
|
-
const names = Object.keys(env);
|
|
1292
|
-
return names.length ? makeRecord(names, names.map(n => env[n])) : EMPTY_TUPLE;
|
|
1293
|
-
}],
|
|
1294
|
-
atoi: [(_, a) => {
|
|
1295
|
-
const s = a[0];
|
|
1296
|
-
if (typeof s === 'string' && /^[+-]?[0-9]+$/.test(s)) {
|
|
1297
|
-
const n = Number(s);
|
|
1298
|
-
if (n >= -2147483648 && n <= 2147483647)
|
|
1299
|
-
return n === 0 ? 0 : n;
|
|
1300
|
-
}
|
|
1301
|
-
return oneArgErr('atoi', 'string', s);
|
|
1302
|
-
}],
|
|
1303
|
-
// TLC's binary value format (uncompressed only).
|
|
1304
|
-
IOSerialize: [(ev, a) => {
|
|
1305
|
-
const path = str(a[1], 'IOSerialize', 1), h = io(ev);
|
|
1306
|
-
if (a[2] !== false)
|
|
1307
|
-
fail('IOSerialize: compressed (gzip) output is not supported; pass FALSE as the third argument.');
|
|
1308
|
-
if (!h.writeBytes)
|
|
1309
|
-
fail('IOSerialize is not supported: this host does not provide binary file output.');
|
|
1310
|
-
const bytes = encodeValue(a[0]);
|
|
1311
|
-
hostWrite(() => h.writeBytes(path, bytes), path);
|
|
1312
|
-
return true;
|
|
1313
|
-
}],
|
|
1314
|
-
IODeserialize: [(ev, a) => {
|
|
1315
|
-
const path = str(a[0], 'IODeserialize', 0), h = io(ev);
|
|
1316
|
-
if (a[1] !== false)
|
|
1317
|
-
fail('IODeserialize: compressed (gzip) input is not supported; pass FALSE as the second argument.');
|
|
1318
|
-
if (!h.readBytes)
|
|
1319
|
-
fail('IODeserialize is not supported: this host does not provide binary file input.');
|
|
1320
|
-
if (!h.exists(path))
|
|
1321
|
-
fail(`${path} (No such file or directory)`);
|
|
1322
|
-
return decodeValue(h.readBytes(path));
|
|
1323
|
-
}],
|
|
1324
|
-
// Serialize(value, dest, options) / Deserialize(src, options): only the plain-text format is implemented (as in TLC).
|
|
1325
|
-
Serialize: [(ev, a) => {
|
|
1326
|
-
const opts = a[2];
|
|
1327
|
-
if (!(opts instanceof RecordV) || opts.get('format') !== 'TXT')
|
|
1328
|
-
fail('Serialize: only [format |-> "TXT", charset |-> ..., openOptions |-> ...] is supported.');
|
|
1329
|
-
const oo = opts.get('openOptions'), cs = opts.get('charset');
|
|
1330
|
-
if (typeof a[0] !== 'string' || typeof a[1] !== 'string' || !(oo instanceof TupleV) || typeof cs !== 'string' || oo.e.some((x) => typeof x !== 'string')) {
|
|
1331
|
-
return execResult(1, '', 'Serialize error invalid parameters: payload and file must be strings, charset a string and openOptions a sequence of strings');
|
|
1332
|
-
}
|
|
1333
|
-
const h = io(ev), o = oo.e;
|
|
1334
|
-
try {
|
|
1335
|
-
const bad = o.find(x => !['READ', 'WRITE', 'APPEND', 'TRUNCATE_EXISTING', 'CREATE', 'CREATE_NEW', 'DELETE_ON_CLOSE', 'SPARSE', 'SYNC', 'DSYNC'].includes(x));
|
|
1336
|
-
if (bad !== undefined)
|
|
1337
|
-
throw new Error(`java.lang.IllegalArgumentException: No enum constant java.nio.file.StandardOpenOption.${bad}`);
|
|
1338
|
-
const exists = h.exists(a[1]);
|
|
1339
|
-
if (o.includes('CREATE_NEW') && exists)
|
|
1340
|
-
throw new Error(`java.nio.file.FileAlreadyExistsException: ${a[1]}`);
|
|
1341
|
-
if (o.length > 0 && !o.includes('CREATE') && !o.includes('CREATE_NEW') && !exists)
|
|
1342
|
-
throw new Error(`java.nio.file.NoSuchFileException: ${a[1]}`);
|
|
1343
|
-
if (o.includes('APPEND'))
|
|
1344
|
-
h.appendFile(a[1], a[0]);
|
|
1345
|
-
else
|
|
1346
|
-
h.writeFile(a[1], a[0]);
|
|
1347
|
-
return execResult(0, 'Finish writing to the file with success!', '');
|
|
1348
|
-
}
|
|
1349
|
-
catch (e) {
|
|
1350
|
-
return execResult(1, '', 'Serialize error writing to the file: ' + e.message);
|
|
1351
|
-
}
|
|
1352
|
-
}],
|
|
1353
|
-
Deserialize: [(ev, a) => {
|
|
1354
|
-
const opts = a[1];
|
|
1355
|
-
if (!(opts instanceof RecordV) || opts.get('format') !== 'TXT')
|
|
1356
|
-
fail('Deserialize: only [format |-> "TXT", charset |-> ...] is supported.');
|
|
1357
|
-
if (typeof a[0] !== 'string' || typeof opts.get('charset') !== 'string')
|
|
1358
|
-
return execResult(1, '', 'Deserialize error invalid parameters: file and charset must be strings');
|
|
1359
|
-
const h = io(ev);
|
|
1360
|
-
try {
|
|
1361
|
-
if (!h.exists(a[0]))
|
|
1362
|
-
throw new Error(`java.nio.file.NoSuchFileException: ${a[0]}`);
|
|
1363
|
-
return execResult(0, h.readFile(a[0]), '');
|
|
1364
|
-
}
|
|
1365
|
-
catch (e) {
|
|
1366
|
-
return execResult(1, '', 'Deserialize error reading from the file: ' + e.message);
|
|
1367
|
-
}
|
|
1368
|
-
}],
|
|
1369
|
-
IOExec: [(ev, a) => runProcess(ev, 'IOExec', cmdStrings(a[0], 'IOExec'))],
|
|
1370
|
-
IOEnvExec: [(ev, a) => { const env = envRecord(a[0], 'IOEnvExec'); return runProcess(ev, 'IOEnvExec', cmdStrings(a[1], 'IOEnvExec'), env); }],
|
|
1371
|
-
IOExecTemplate: [(ev, a) => {
|
|
1372
|
-
const cmd = cmdStrings(a[0], 'IOExecTemplate'), params = cmdStrings(a[1], 'IOExecTemplate');
|
|
1373
|
-
return runProcess(ev, 'IOExecTemplate', cmd.map(c => javaFormat(c, params)));
|
|
1374
|
-
}],
|
|
1375
|
-
IOEnvExecTemplate: [(ev, a) => {
|
|
1376
|
-
const env = envRecord(a[0], 'IOEnvExecTemplate');
|
|
1377
|
-
const cmd = cmdStrings(a[1], 'IOEnvExecTemplate'), params = cmdStrings(a[2], 'IOEnvExecTemplate');
|
|
1378
|
-
return runProcess(ev, 'IOEnvExecTemplate', cmd.map(c => javaFormat(c, params)), env);
|
|
1379
|
-
}],
|
|
1380
|
-
},
|
|
1381
|
-
};
|