gdp-wired 0.24.0 → 0.26.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 +14 -9
- package/dist/core/accel.d.ts +44 -0
- package/dist/core/accel.js +955 -0
- package/dist/core/bmc.d.ts +8 -0
- package/dist/core/bmc.js +263 -97
- package/dist/core/cycles.d.ts +2 -3
- package/dist/core/cycles.js +409 -174
- package/dist/core/cyclic.d.ts +4 -1
- package/dist/core/cyclic.js +86 -64
- package/dist/core/data.d.ts +9 -1
- package/dist/core/data.js +872 -168
- package/dist/core/discover.js +2 -3
- package/dist/core/dsl.d.ts +3 -2
- package/dist/core/dsl.js +21 -18
- package/dist/core/exists.js +7 -14
- package/dist/core/extract-check.d.ts +3 -2
- package/dist/core/extract-check.js +137 -50
- package/dist/core/extract-print.d.ts +1 -0
- package/dist/core/extract-print.js +26 -3
- package/dist/core/extract-read.d.ts +85 -4
- package/dist/core/extract-read.js +295 -34
- package/dist/core/extract-shapes.d.ts +14 -0
- package/dist/core/extract-shapes.js +608 -78
- package/dist/core/extract-xstate.d.ts +5 -1
- package/dist/core/extract-xstate.js +618 -184
- package/dist/core/extract.js +73 -27
- package/dist/core/infer.d.ts +1 -0
- package/dist/core/infer.js +364 -40
- package/dist/core/machine.d.ts +6 -0
- package/dist/core/machine.js +35 -3
- package/dist/core/nonterm.d.ts +9 -2
- package/dist/core/nonterm.js +173 -9
- package/dist/core/q.d.ts +1 -0
- package/dist/core/q.js +2 -2
- package/dist/core/relation.d.ts +1 -0
- package/dist/core/relation.js +95 -39
- package/dist/core/solver.d.ts +12 -0
- package/dist/core/solver.js +76 -30
- package/dist/core/transfer.js +23 -14
- package/dist/core/translate.d.ts +1 -1
- package/dist/core/translate.js +22 -49
- package/dist/core/xstate.d.ts +6 -1
- package/dist/core/xstate.js +336 -55
- package/dist/kernel/cdcl.d.ts +5 -0
- package/dist/kernel/cdcl.js +44 -8
- package/dist/kernel/prove.d.ts +6 -1
- package/dist/kernel/prove.js +101 -85
- package/dist/kernel/reader.d.ts +1 -0
- package/dist/kernel/reader.js +4 -3
- package/dist/kernel/simplex.d.ts +1 -1
- package/dist/kernel/simplex.js +13 -1
- package/package.json +3 -2
|
@@ -18,11 +18,12 @@ const proc = globalThis.process;
|
|
|
18
18
|
const vmOf = () => { const m = proc?.getBuiltinModule?.('node:vm'); if (!m)
|
|
19
19
|
throw new Error('the check runs the code in node:vm (Node 20.16 or later, or Bun)'); return m; };
|
|
20
20
|
import { Int, Term, bool, int, intern, interned, nat, no, oneOf, str, proveSteps } from "./dsl.js";
|
|
21
|
+
import { seeded, walk } from "./machine.js";
|
|
21
22
|
import { allowed } from "./watch.js";
|
|
22
23
|
import { normalize, resolveIn, scriptKind } from "./extract-read.js";
|
|
23
24
|
import * as I from "./extract-ir.js";
|
|
24
25
|
// --- the code, instrumented and loaded ------------------------------------------------------------------------------
|
|
25
|
-
export function instrument(code, file, tail = '') {
|
|
26
|
+
export function instrument(code, file, tail = '', extra = []) {
|
|
26
27
|
const sf = ts.createSourceFile(file, code, ts.ScriptTarget.ES2022, true, scriptKind(file));
|
|
27
28
|
const arms = [], edits = [];
|
|
28
29
|
const loc = (n) => { const { line, character } = sf.getLineAndCharacterOfPosition(n.getStart()); return `${file.split('/').pop()}:${line + 1}:${character + 1}`; };
|
|
@@ -58,6 +59,7 @@ export function instrument(code, file, tail = '') {
|
|
|
58
59
|
ts.forEachChild(n, visit);
|
|
59
60
|
};
|
|
60
61
|
visit(sf);
|
|
62
|
+
edits.push(...extra);
|
|
61
63
|
// Later positions first; at one position, in the order made reversed (a closing paren before the next opening one).
|
|
62
64
|
const order = edits.map((e, i) => [...e, i]).sort((a, b) => b[0] - a[0] || b[2] - a[2]);
|
|
63
65
|
let out = code;
|
|
@@ -67,22 +69,23 @@ export function instrument(code, file, tail = '') {
|
|
|
67
69
|
const js = ts.transpileModule(out, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022, esModuleInterop: true, jsx: ts.JsxEmit.React }, fileName: file.replace(/\.js$/, '.ts').replace(/\.jsx$/, '.tsx') }).outputText;
|
|
68
70
|
return { js, arms };
|
|
69
71
|
}
|
|
70
|
-
export function sandbox(code, file, expose, modules = {}, init, files = {}) {
|
|
72
|
+
export function sandbox(code, file, expose, modules = {}, init, files = {}, extra = []) {
|
|
71
73
|
const vm = vmOf();
|
|
72
|
-
const { js, arms } = instrument(code, file, init ? `\n;(globalThis as any).__gdpInit = () => (${init});\n` : '');
|
|
74
|
+
const { js, arms } = instrument(code, file, init ? `\n;(globalThis as any).__gdpInit = () => (${init});\n` : '', extra);
|
|
73
75
|
const counts = arms.map(() => 0);
|
|
74
76
|
let now = 0;
|
|
77
|
+
const stub = (name) => new Proxy({}, {
|
|
78
|
+
get: (_, k) => { if (k === '__esModule' || typeof k === 'symbol')
|
|
79
|
+
return undefined; throw new Error(`the check loads no module ${name} (its ${String(k)} was read)`); },
|
|
80
|
+
ownKeys: () => [],
|
|
81
|
+
});
|
|
75
82
|
const module = { exports: {} };
|
|
76
83
|
const ctx = vm.createContext({
|
|
77
84
|
__cov: (i) => { counts[i]++; }, __now: () => now, module, exports: module.exports,
|
|
78
85
|
// A relative import among the files given: loaded in this VM (not counted: the branches are the entry's). A module
|
|
79
86
|
// the step doesn't name (React, for the component beside a reducer): a stub that throws when read, so a step that
|
|
80
87
|
// reads it fails the check rather than running without it.
|
|
81
|
-
require: (name) => (name in modules ? modules[name] : name.startsWith('.') && Object.keys(files).length ? load(ENTRY, name) :
|
|
82
|
-
get: (_, k) => { if (k === '__esModule' || typeof k === 'symbol')
|
|
83
|
-
return undefined; throw new Error(`the check loads no module ${name} (its ${String(k)} was read)`); },
|
|
84
|
-
ownKeys: () => [],
|
|
85
|
-
})),
|
|
88
|
+
require: (name) => (name in modules ? modules[name] : name.startsWith('.') && Object.keys(files).length ? load(ENTRY, name) : stub(name)),
|
|
86
89
|
console: { log() { }, warn() { }, error() { }, info() { }, debug() { } },
|
|
87
90
|
});
|
|
88
91
|
// The files given, by their place beside the entry's; each loaded once.
|
|
@@ -96,12 +99,22 @@ export function sandbox(code, file, expose, modules = {}, init, files = {}) {
|
|
|
96
99
|
const m = { exports: {} };
|
|
97
100
|
loaded.set(at, m.exports);
|
|
98
101
|
const js = ts.transpileModule(abs[at], { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022, esModuleInterop: true, jsx: ts.JsxEmit.React }, fileName: at.replace(/\.js$/, '.ts').replace(/\.jsx$/, '.tsx') }).outputText;
|
|
99
|
-
|
|
100
|
-
|
|
102
|
+
// A file that doesn't load here (it reads import.meta, a browser's globals): a stub that throws when read, so a step
|
|
103
|
+
// that reads it fails the check rather than running without it.
|
|
104
|
+
try {
|
|
105
|
+
const f = vm.runInContext(`(function (module, exports, require) {${js}\n})`, ctx);
|
|
106
|
+
f(m, m.exports, (s2) => (s2 in modules ? modules[s2] : s2.startsWith('.') ? load(at, s2) : stub(s2)));
|
|
107
|
+
}
|
|
108
|
+
catch (e) {
|
|
109
|
+
const st = stub(`${spec} (${e.message})`);
|
|
110
|
+
loaded.set(at, st);
|
|
111
|
+
return st;
|
|
112
|
+
}
|
|
101
113
|
loaded.set(at, m.exports);
|
|
102
114
|
return m.exports;
|
|
103
115
|
};
|
|
104
|
-
|
|
116
|
+
// The clock is the request's: Date.now() and new Date() read it.
|
|
117
|
+
vm.runInContext('globalThis.Date = new Proxy(Date, {construct: (D, a) => (a.length ? new D(...a) : new D(__now())), get: (D, k) => (k === "now" ? () => __now() : D[k])}); Math.random = () => { throw new Error("Math.random in a step") }', ctx);
|
|
105
118
|
vm.runInContext(`${js}\n;globalThis.__gdp = {${expose.map(n => { if (n === 'default')
|
|
106
119
|
return 'default: module.exports.default'; const [h, ...rest] = n.split('.'); return `${JSON.stringify(n)}: (typeof ${h} !== 'undefined' ? ${h} : module.exports.${h})${rest.map(x => `.${x}`).join('')}`; }).join(', ')}};`, ctx, { timeout: 2000, filename: file });
|
|
107
120
|
const script = new vm.Script('globalThis.__r = (() => { try { return {ok: true, value: __gdp[__f].apply(__self, __args)} } catch (e) { return {ok: false, error: String(e && e.message || e)} } })()');
|
|
@@ -122,6 +135,14 @@ function snapOf(v, layout, m, consts, out = { leaves: {}, maps: {} }, path = 'st
|
|
|
122
135
|
switch (layout.k) {
|
|
123
136
|
case 'scalar': {
|
|
124
137
|
const sort = m.state.find(x => x.name === layout.name)?.sort;
|
|
138
|
+
// A Date: its time.
|
|
139
|
+
if (sort?.k === 'num' && sort.date) {
|
|
140
|
+
if (!isDateValue(v))
|
|
141
|
+
throw new Error(`${path} is ${JSON.stringify(v)}, not a Date`);
|
|
142
|
+
v = v.getTime();
|
|
143
|
+
if (Number.isNaN(v))
|
|
144
|
+
throw new Outside(`${path} is an invalid Date (past ±8.64e15 ms)`);
|
|
145
|
+
}
|
|
125
146
|
if (sort?.k === 'num' && !(typeof v === 'number' && Number.isSafeInteger(v))) {
|
|
126
147
|
if (typeof v === 'number')
|
|
127
148
|
throw new Outside(`${path} is ${v}`);
|
|
@@ -173,6 +194,16 @@ function snapOf(v, layout, m, consts, out = { leaves: {}, maps: {} }, path = 'st
|
|
|
173
194
|
out.maps[d.name] = cells;
|
|
174
195
|
return out;
|
|
175
196
|
}
|
|
197
|
+
case 'list': {
|
|
198
|
+
const d = m.lists.find(x => x.name === layout.name);
|
|
199
|
+
if (!Array.isArray(v))
|
|
200
|
+
throw new Error(`${path} is ${JSON.stringify(v)}, not an array`);
|
|
201
|
+
// Every index an item (an array with holes, or more than its own indices, is not a list).
|
|
202
|
+
if (Object.keys(v).length !== v.length)
|
|
203
|
+
throw new Error(`${path} has holes or fields beside its items`);
|
|
204
|
+
(out.lists ??= {})[d.name] = v.map((x, i) => checkCell(x, d.fields[0], `${path}[${i}]`));
|
|
205
|
+
return out;
|
|
206
|
+
}
|
|
176
207
|
case 'const': {
|
|
177
208
|
const want = layout.value.s === 'str' ? (layout.value.e.op === 'slit' ? layout.value.e.value : undefined) : consts(layout.value.e);
|
|
178
209
|
if (v !== want)
|
|
@@ -181,7 +212,15 @@ function snapOf(v, layout, m, consts, out = { leaves: {}, maps: {} }, path = 'st
|
|
|
181
212
|
}
|
|
182
213
|
}
|
|
183
214
|
}
|
|
215
|
+
const isDateValue = (x) => Object.prototype.toString.call(x) === '[object Date]';
|
|
184
216
|
function checkCell(x, f, path) {
|
|
217
|
+
if (f.sort.k === 'num' && f.sort.date) {
|
|
218
|
+
if (!isDateValue(x))
|
|
219
|
+
throw new Error(`${path} is ${JSON.stringify(x)}, not a Date`);
|
|
220
|
+
x = x.getTime();
|
|
221
|
+
if (Number.isNaN(x))
|
|
222
|
+
throw new Outside(`${path} is an invalid Date (past ±8.64e15 ms)`);
|
|
223
|
+
}
|
|
185
224
|
if (f.sort.k === 'num') {
|
|
186
225
|
if (typeof x === 'number' && Number.isSafeInteger(x))
|
|
187
226
|
return x;
|
|
@@ -205,20 +244,25 @@ function checkCell(x, f, path) {
|
|
|
205
244
|
function valueOf(s, layout, m, consts, ctx) {
|
|
206
245
|
const tree = (l) => {
|
|
207
246
|
switch (l.k) {
|
|
208
|
-
case 'scalar':
|
|
247
|
+
case 'scalar': {
|
|
248
|
+
const sort = m.state.find(x => x.name === l.name)?.sort;
|
|
249
|
+
return sort?.k === 'num' && sort.date ? { $date: s.leaves[l.name] } : s.leaves[l.name];
|
|
250
|
+
}
|
|
209
251
|
case 'rec': return Object.fromEntries(l.fields.filter(([f]) => !f.endsWith('()')).map(([f, sub]) => [f, tree(sub)]));
|
|
210
252
|
case 'map': {
|
|
211
253
|
const d = m.maps.find(x => x.name === l.name);
|
|
212
|
-
const
|
|
254
|
+
const dated = (f, x) => (f.sort.k === 'num' && f.sort.date ? { $date: x } : x);
|
|
255
|
+
const entries = Object.entries(s.maps[d.name] ?? {}).map(([k, c]) => [d.key === 'num' ? Number(k) : k, d.scalar ? dated(d.fields[0], c.value) : Object.fromEntries(d.fields.map(f => [f.name, dated(f, c[f.name])]))]);
|
|
213
256
|
return { $map: d.js, entries };
|
|
214
257
|
}
|
|
258
|
+
case 'list': return s.lists?.[l.name] ?? [];
|
|
215
259
|
case 'const': return l.value.s === 'str' ? (l.value.e.op === 'slit' ? l.value.e.value : undefined) : consts(l.value.e);
|
|
216
260
|
}
|
|
217
261
|
};
|
|
218
262
|
ctx.__in = JSON.stringify(tree(layout));
|
|
219
|
-
return vmOf().runInContext('JSON.parse(__in, (k, v) => v && typeof v === "object" && v.$map ? (v.$map === "Map" ? new Map(v.entries) : Object.fromEntries(v.entries)) : v)', ctx);
|
|
263
|
+
return vmOf().runInContext('JSON.parse(__in, (k, v) => v && typeof v === "object" && v.$map ? (v.$map === "Map" ? new Map(v.entries) : Object.fromEntries(v.entries)) : v && typeof v === "object" && "$date" in v ? new Date(v.$date) : v)', ctx);
|
|
220
264
|
}
|
|
221
|
-
const showSnap = (s) => JSON.stringify({ ...s.leaves, ...Object.fromEntries(Object.entries(s.maps).map(([k, v]) => [k, v])) });
|
|
265
|
+
const showSnap = (s) => JSON.stringify({ ...s.leaves, ...Object.fromEntries(Object.entries(s.maps).map(([k, v]) => [k, v])), ...(s.lists ?? {}) });
|
|
222
266
|
const sameSnap = (a, b) => {
|
|
223
267
|
for (const k of new Set([...Object.keys(a.leaves), ...Object.keys(b.leaves)]))
|
|
224
268
|
if (a.leaves[k] !== b.leaves[k])
|
|
@@ -229,6 +273,9 @@ const sameSnap = (a, b) => {
|
|
|
229
273
|
if (JSON.stringify(x[key]) !== JSON.stringify(y[key]))
|
|
230
274
|
return `${k}[${key}] is ${JSON.stringify(x[key])} in the code, ${JSON.stringify(y[key])} in the rule`;
|
|
231
275
|
}
|
|
276
|
+
for (const k of new Set([...Object.keys(a.lists ?? {}), ...Object.keys(b.lists ?? {})]))
|
|
277
|
+
if (JSON.stringify(a.lists?.[k] ?? []) !== JSON.stringify(b.lists?.[k] ?? []))
|
|
278
|
+
return `${k} is ${JSON.stringify(a.lists?.[k] ?? [])} in the code, ${JSON.stringify(b.lists?.[k] ?? [])} in the rule`;
|
|
232
279
|
return undefined;
|
|
233
280
|
};
|
|
234
281
|
// --- the rule's side ------------------------------------------------------------------------------------------------
|
|
@@ -249,8 +296,11 @@ function ruleSnap(r, m, st, sorts) {
|
|
|
249
296
|
}
|
|
250
297
|
maps[md.name] = cells;
|
|
251
298
|
}
|
|
299
|
+
const lists = {};
|
|
300
|
+
for (const ld of m.lists ?? [])
|
|
301
|
+
lists[ld.name] = (d[ld.name] ?? []);
|
|
252
302
|
void sorts;
|
|
253
|
-
return { leaves, maps };
|
|
303
|
+
return { leaves, maps, ...(m.lists?.length ? { lists } : {}) };
|
|
254
304
|
}
|
|
255
305
|
// A snapshot as a state of the rule (each variable and cell by its kind).
|
|
256
306
|
function ruleState(base, s, m, sorts) {
|
|
@@ -267,23 +317,25 @@ function ruleState(base, s, m, sorts) {
|
|
|
267
317
|
(maps[part] ??= new Map()).set(key, x);
|
|
268
318
|
}
|
|
269
319
|
}
|
|
320
|
+
// A list: its items at their indices, its length.
|
|
321
|
+
for (const d of m.lists ?? []) {
|
|
322
|
+
const kind = kindOfVar(d.fields[0], sorts, `${d.name}.$item`), xs = s.lists?.[d.name] ?? [];
|
|
323
|
+
scalars[`${d.name}_len`] = xs.length;
|
|
324
|
+
xs.forEach((x, i) => { for (const [part, y] of Object.entries(kind.encode(d.name, x)))
|
|
325
|
+
if (y !== 0)
|
|
326
|
+
(maps[part] ??= new Map()).set(i, y); });
|
|
327
|
+
}
|
|
270
328
|
return { ...base, scalars, maps };
|
|
271
329
|
}
|
|
272
330
|
import { record } from "./dsl.js";
|
|
273
331
|
const cellKind = (d, sorts) => record({ has: bool, ...Object.fromEntries(d.fields.map(f => [f.name, kindOfVar(f, sorts, `${d.name}.${f.name}`)])) });
|
|
274
|
-
|
|
332
|
+
// --- values to draw -------------------------------------------------------------------------------------------------
|
|
275
333
|
const BIG = [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER - 1, 2 ** 31, 2 ** 32];
|
|
276
334
|
function constantsOf(m) {
|
|
277
335
|
const out = new Set([0, 1]);
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
out.add(o.v);
|
|
282
|
-
if (typeof o.k === 'number')
|
|
283
|
-
out.add(o.k);
|
|
284
|
-
Object.values(o).forEach(go);
|
|
285
|
-
} };
|
|
286
|
-
go([m.writes, m.mapWrites, m.refuse, m.pre, m.init]);
|
|
336
|
+
walk([m.writes, m.mapWrites, m.refuse, m.pre, m.init], o => { if (o.op === 'const' && typeof o.v === 'number')
|
|
337
|
+
out.add(o.v); if (typeof o.k === 'number')
|
|
338
|
+
out.add(o.k); });
|
|
287
339
|
return [...out];
|
|
288
340
|
}
|
|
289
341
|
function draw(sort, sorts, name, rand, near, bound, strs) {
|
|
@@ -310,9 +362,12 @@ function draw(sort, sorts, name, rand, near, bound, strs) {
|
|
|
310
362
|
}
|
|
311
363
|
}
|
|
312
364
|
export function check(code, file, m, r, sorts, opts = {}) {
|
|
313
|
-
const t0 = performance.now(), rand = seeded(opts.seed ?? 7), bound = opts.bound ?? 12;
|
|
365
|
+
const t0 = performance.now(), rand = seeded((opts.seed ?? 7) >>> 0 || 1), bound = opts.bound ?? 12;
|
|
314
366
|
const isClass = m.shape === 'class', fns = m.shape === 'class' ? [m.entry] : [...new Set(m.events.map(e => e.call))];
|
|
315
|
-
const box = sandbox(code, file, fns, opts.modules, m.initSource, opts.files);
|
|
367
|
+
const box = sandbox(code, file, fns, opts.modules, m.initSource, opts.files, m.factory ? [[m.factory.at, m.factory.text]] : []);
|
|
368
|
+
// An object a factory makes: its state is what its functions close over, read and set through the two functions the
|
|
369
|
+
// check added to it.
|
|
370
|
+
const stateOf = (self) => (m.factory ? box.call('$get', self, []).value : self);
|
|
316
371
|
const interp = r.interpreter(), gen = r.compiled(), machine = r.machine;
|
|
317
372
|
const ev = { runs: 0, requests: 0, fromStates: 0, probes: { conditions: 0, witnesses: 0, steps: 0 }, refusedBoth: 0, outside: 0, edge: 0, compiledAgreed: 0, coverage: { arms: box.arms.length, hit: 0, missed: [] }, ms: 0 };
|
|
318
373
|
const consts = constantsOf(m), strs = ['a', 'b', 'c', ''];
|
|
@@ -331,7 +386,8 @@ export function check(code, file, m, r, sorts, opts = {}) {
|
|
|
331
386
|
return ev;
|
|
332
387
|
};
|
|
333
388
|
const request = (params, inputs, e) => {
|
|
334
|
-
const
|
|
389
|
+
const dateIn = (n) => { const x = m.inputs.find(v => v.name === n); return x?.sort.k === 'num' && x.sort.date ? vmOf().runInContext(`new Date(${Number(inputs[n])})`, box.ctx) : inputs[n]; };
|
|
390
|
+
const build = (a) => (a.k === 'input' ? dateIn(a.name) : a.k === 'lit' ? a.value : a.k === 'rec' ? Object.fromEntries(a.fields.map(([f, x]) => [f, build(x)])) : a.k === 'lazy'
|
|
335
391
|
? Object.fromEntries([...m.inputs].filter(v => m.lazy?.get(v.name)?.prefix === a.prefix).map(v => [m.lazy.get(v.name).field, inputs[v.name]]))
|
|
336
392
|
: undefined);
|
|
337
393
|
void params;
|
|
@@ -391,7 +447,7 @@ export function check(code, file, m, r, sorts, opts = {}) {
|
|
|
391
447
|
if (!res.ok)
|
|
392
448
|
code = { refused: res.error };
|
|
393
449
|
else
|
|
394
|
-
code = { snap: snapOf(self, m.layout, m, evalAt(params)), out: res.value, self };
|
|
450
|
+
code = { snap: snapOf(stateOf(self), m.layout, m, evalAt(params)), out: res.value, self };
|
|
395
451
|
}
|
|
396
452
|
else {
|
|
397
453
|
const input = valueOf(side.snap, m.layout, m, evalAt(params), box.ctx), before = JSON.stringify(input, mapReplacer);
|
|
@@ -456,7 +512,7 @@ export function check(code, file, m, r, sorts, opts = {}) {
|
|
|
456
512
|
// A refusal leaves the state as it was: the object the code threw from must be as it was too.
|
|
457
513
|
if (isClass) {
|
|
458
514
|
try {
|
|
459
|
-
const after = snapOf(side.self, m.layout, m, evalAt(params)), d = sameSnap(after, side.snap);
|
|
515
|
+
const after = snapOf(stateOf(side.self), m.layout, m, evalAt(params)), d = sameSnap(after, side.snap);
|
|
460
516
|
if (d)
|
|
461
517
|
return `${where}: ${req} ${from}: the code throws (${code.refused}) after changing the object: ${d}`;
|
|
462
518
|
}
|
|
@@ -474,19 +530,40 @@ export function check(code, file, m, r, sorts, opts = {}) {
|
|
|
474
530
|
const ruleSide = ruleSnap(r, m, rule.st, sorts), diff = sameSnap(code.snap, ruleSide);
|
|
475
531
|
if (diff)
|
|
476
532
|
return `${where}: ${req} ${from}: ${diff}`;
|
|
477
|
-
if (isClass
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
533
|
+
if (isClass) {
|
|
534
|
+
// The method's result, as the rule keeps it: a value, a record's fields, or a value and whether it is missing.
|
|
535
|
+
const res = m.results?.[e.call], d = r.decode(rule.st);
|
|
536
|
+
const bad = (what) => `${where}: ${req} ${from}: ${e.call} returns ${JSON.stringify(code.out)}, ${what}`;
|
|
537
|
+
if (res?.k === 'scalar' && d[res.name] !== code.out)
|
|
538
|
+
return bad(`the rule's ${res.name} is ${JSON.stringify(d[res.name])}`);
|
|
539
|
+
if (res?.k === 'rec') {
|
|
540
|
+
const o = code.out;
|
|
541
|
+
if (typeof o !== 'object' || o === null || Object.keys(o).length !== res.fields.length)
|
|
542
|
+
return bad('not a record of the fields the rule keeps');
|
|
543
|
+
for (const [f, n] of res.fields)
|
|
544
|
+
if (o[f] !== d[n])
|
|
545
|
+
return bad(`the rule's ${n} is ${JSON.stringify(d[n])}`);
|
|
546
|
+
}
|
|
547
|
+
if (res?.k === 'maybe') {
|
|
548
|
+
const gone = code.out === (res.null ? null : undefined);
|
|
549
|
+
if (gone !== d[res.missing])
|
|
550
|
+
return bad(`the rule's ${res.missing} is ${JSON.stringify(d[res.missing])}`);
|
|
551
|
+
if (!gone && d[res.name] !== code.out)
|
|
552
|
+
return bad(`the rule's ${res.name} is ${JSON.stringify(d[res.name])}`);
|
|
553
|
+
}
|
|
481
554
|
}
|
|
482
555
|
next.side = { snap: code.snap, ...(code.self ? { self: code.self } : {}) };
|
|
483
556
|
next.st = rule.st;
|
|
484
557
|
return undefined;
|
|
485
558
|
};
|
|
486
559
|
// A class's object: made by its constructor, or set to a snapshot.
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
560
|
+
const E = JSON.stringify(m.entry);
|
|
561
|
+
if (isClass && !m.factory)
|
|
562
|
+
vmOf().runInContext(`__gdp.$method = function (name, args) { return this[name](...args) }; __gdp.$new = function (...args) { return new __gdp[${E}](...args) }; __gdp.$at = function (fields) { return Object.assign(Object.create(__gdp[${E}].prototype), fields) }`, box.ctx);
|
|
563
|
+
if (m.factory)
|
|
564
|
+
vmOf().runInContext(`__gdp.$method = function (name, args) { return this[name](...args) }; __gdp.$new = function (...args) { return __gdp[${E}](...args) }; __gdp.$get = function () { return this.__gdpGet() }; __gdp.$at = function (fields, args) { const o = __gdp[${E}](...args); o.__gdpSet(fields); return o }`, box.ctx);
|
|
565
|
+
const ctorValues = (params) => (m.ctorArgs ?? []).filter(n => !m.params.find(v => v.name === n)?.note?.startsWith('Date.now()')).map(n => (n.startsWith('$map:') ? vmOf().runInContext(n === '$map:Map' ? 'new Map()' : '({})', box.ctx) : params[n]));
|
|
566
|
+
const objectAt = (snap, params) => box.call('$at', undefined, [valueOf(snap, m.layout, m, evalAt(params), box.ctx), ctorValues(params)]).ok ? box.ctx.__r.value : (() => { throw new Error(`could not make the object: ${box.ctx.__r.error}`); })();
|
|
490
567
|
const drawParams = () => Object.fromEntries(m.params.map(v => [v.name, v.note?.startsWith('Date.now()') ? rand(10_000) : draw(v.sort, sorts, v.name, rand, consts, bound, strs)]));
|
|
491
568
|
const start = (params) => {
|
|
492
569
|
const ctorRefuses = (() => { const pre = evalTerm(m.pre, params); return pre !== true; })();
|
|
@@ -501,7 +578,8 @@ export function check(code, file, m, r, sorts, opts = {}) {
|
|
|
501
578
|
const now0 = m.params.find(v => v.note?.startsWith('Date.now()'));
|
|
502
579
|
if (now0)
|
|
503
580
|
box.setNow(params[now0.name]);
|
|
504
|
-
|
|
581
|
+
// A Map the constructor is given: an empty one, made in the code's realm.
|
|
582
|
+
const made = box.call('$new', undefined, (m.ctorArgs ?? []).filter(n => n !== now0?.name).map(n => (n.startsWith('$map:') ? vmOf().runInContext(n === '$map:Map' ? 'new Map()' : '({})', box.ctx) : params[n])));
|
|
505
583
|
const ruleRefuses = ps === undefined || ctorRefuses;
|
|
506
584
|
if (!made.ok)
|
|
507
585
|
return ruleRefuses ? {} : { problem: `new ${m.entry}(${JSON.stringify(params)}) throws (${made.error}), the rule's precondition holds` };
|
|
@@ -509,7 +587,7 @@ export function check(code, file, m, r, sorts, opts = {}) {
|
|
|
509
587
|
return { problem: `new ${m.entry}(${JSON.stringify(params)}) is made, the rule's ${ps === undefined ? 'param kinds refuse' : 'precondition refuses'} it` };
|
|
510
588
|
const st = interp.init(ps);
|
|
511
589
|
try {
|
|
512
|
-
const snap = snapOf(made.value, m.layout, m, evalAt(params));
|
|
590
|
+
const snap = snapOf(stateOf(made.value), m.layout, m, evalAt(params));
|
|
513
591
|
const diff = sameSnap(snap, ruleSnap(r, m, st, sorts));
|
|
514
592
|
if (diff)
|
|
515
593
|
return { problem: `new ${m.entry}(${JSON.stringify(params)}): ${diff}` };
|
|
@@ -578,10 +656,26 @@ export function check(code, file, m, r, sorts, opts = {}) {
|
|
|
578
656
|
}
|
|
579
657
|
maps[d.name] = cells;
|
|
580
658
|
}
|
|
659
|
+
const lists = {};
|
|
660
|
+
for (const d of m.lists ?? []) {
|
|
661
|
+
const f = d.fields[0];
|
|
662
|
+
lists[d.name] = Array.from({ length: rand(4) }, () => { let x = draw(f.sort, sorts, `${d.name}.$item`, rand, consts, bound, strs); if (typeof x === 'number' && sorts.get(`${d.name}.$item`) === 'nat')
|
|
663
|
+
x = Math.abs(x); return x; });
|
|
664
|
+
}
|
|
581
665
|
for (const v of m.state)
|
|
582
666
|
if (v.name in leaves && v.sort.k === 'num' && Math.abs(leaves[v.name]) > Number.MAX_SAFE_INTEGER / 4)
|
|
583
667
|
leaves[v.name] = rand(bound);
|
|
584
|
-
|
|
668
|
+
// A Date's time within its range (a Date past it is invalid in the code: no state of the code holds one).
|
|
669
|
+
for (const v of m.state)
|
|
670
|
+
if (v.name in leaves && v.sort.k === 'num' && v.sort.date && Math.abs(leaves[v.name]) > 8.64e15)
|
|
671
|
+
leaves[v.name] = rand(bound);
|
|
672
|
+
for (const d of m.maps)
|
|
673
|
+
for (const f of d.fields)
|
|
674
|
+
if (f.sort.k === 'num' && f.sort.date)
|
|
675
|
+
for (const c of Object.values(maps[d.name] ?? {}))
|
|
676
|
+
if (Math.abs(c[f.name]) > 8.64e15)
|
|
677
|
+
c[f.name] = rand(bound);
|
|
678
|
+
return { leaves, maps, ...(m.lists?.length ? { lists } : {}) };
|
|
585
679
|
};
|
|
586
680
|
const fromState = (params, snap, inputs, e, where) => {
|
|
587
681
|
let ps;
|
|
@@ -655,15 +749,8 @@ function conditionsOf(m) {
|
|
|
655
749
|
seen.add(k);
|
|
656
750
|
out.push(c, I.not(c));
|
|
657
751
|
} };
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
return;
|
|
661
|
-
const o = x;
|
|
662
|
-
if ((o.op === 'ite' || o.op === 'kite') && o.c)
|
|
663
|
-
add(o.c);
|
|
664
|
-
Object.values(o).forEach(go);
|
|
665
|
-
};
|
|
666
|
-
go([m.writes, m.mapWrites]);
|
|
752
|
+
walk([m.writes, m.mapWrites], o => { if ((o.op === 'ite' || o.op === 'kite') && o.c)
|
|
753
|
+
add(o.c); });
|
|
667
754
|
for (const d of m.refuse.op === 'or' ? m.refuse.xs : [m.refuse])
|
|
668
755
|
add(d);
|
|
669
756
|
return out.slice(0, 48);
|
|
@@ -21,6 +21,7 @@ export type Printer = {
|
|
|
21
21
|
};
|
|
22
22
|
export declare const pnum: (e: N, P: Printer, ctx: Ctx, recv?: boolean) => string;
|
|
23
23
|
export declare function pb(c: B, P: Printer, ctx: Ctx): string;
|
|
24
|
+
export declare const pidx: (i: N, P: Printer, ctx: Ctx) => string;
|
|
24
25
|
export declare function pl(l: L, P: Printer, ctx: Ctx, bare?: boolean): string;
|
|
25
26
|
export declare function pk(k: K, P: Printer, ctx: Ctx): string;
|
|
26
27
|
export declare function pterm(t: Term, P: Printer, ctx: Ctx, target?: string): string;
|
|
@@ -221,6 +221,12 @@ export function sortsOf(m, given = {}) {
|
|
|
221
221
|
sorts.set(v.name, given[v.name] ?? 'nat');
|
|
222
222
|
for (const c of cellNums)
|
|
223
223
|
sorts.set(c, given[c] ?? 'nat');
|
|
224
|
+
// A list's length is a natural; its items naturals until one written may be below 0.
|
|
225
|
+
for (const d of m.lists ?? []) {
|
|
226
|
+
sorts.set(`${d.name}_len`, 'nat');
|
|
227
|
+
if (d.fields[0].sort.k === 'num')
|
|
228
|
+
sorts.set(`${d.name}.$item`, given[`${d.name}.$item`] ?? 'nat');
|
|
229
|
+
}
|
|
224
230
|
for (let changed = true; changed;) {
|
|
225
231
|
changed = false;
|
|
226
232
|
for (const v of nums(m.state)) {
|
|
@@ -242,6 +248,15 @@ export function sortsOf(m, given = {}) {
|
|
|
242
248
|
changed = true;
|
|
243
249
|
}
|
|
244
250
|
}
|
|
251
|
+
for (const d of m.lists ?? []) {
|
|
252
|
+
const n = `${d.name}.$item`;
|
|
253
|
+
if (d.fields[0].sort.k !== 'num' || sorts.get(n) === 'int' || given[n])
|
|
254
|
+
continue;
|
|
255
|
+
if ((m.listWrites?.[d.name] ?? []).some(o => o.op !== 'pop' && o.x.s === 'num' && !natOK(o.x.e, withAtom(ctx0(), o.when)))) {
|
|
256
|
+
sorts.set(n, 'int');
|
|
257
|
+
changed = true;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
245
260
|
}
|
|
246
261
|
for (const v of nums(m.state))
|
|
247
262
|
if (sorts.get(v.name) === 'int')
|
|
@@ -310,7 +325,7 @@ function pn(e, P, ctx, mode, recv = false) {
|
|
|
310
325
|
return `when(${pb(e.c, P, ctx)}, ${side(e.a, ca)}, ${side(e.b, cb)})`;
|
|
311
326
|
}
|
|
312
327
|
case 'cell': {
|
|
313
|
-
const v =
|
|
328
|
+
const v = cellText(e, P, ctx);
|
|
314
329
|
return !nat && recv && P.sorts.get(`${e.map}.${e.field}`) === 'nat' ? `Int.of(${v})` : v;
|
|
315
330
|
}
|
|
316
331
|
}
|
|
@@ -355,9 +370,17 @@ export function pb(c, P, ctx) {
|
|
|
355
370
|
const s = (k) => (k.op === 'svar' ? k.name : k.op === 'slit' ? q(k.value) : pk(k, P, ctx));
|
|
356
371
|
return c.a.op === 'svar' ? `${c.a.name}.eq(${s(c.b)})` : c.b.op === 'svar' ? `${c.b.name}.eq(${s(c.a)})` : `${pk(c.a, P, ctx)}.eq(${pk(c.b, P, ctx)})`;
|
|
357
372
|
}
|
|
358
|
-
case 'cell': return
|
|
373
|
+
case 'cell': return cellText(c, P, ctx);
|
|
359
374
|
}
|
|
360
375
|
}
|
|
376
|
+
// A map's cell field, or a list's item (read where the index is within it: an integer index is at least 0 there).
|
|
377
|
+
function cellText(c, P, ctx) {
|
|
378
|
+
if (c.field !== '$item')
|
|
379
|
+
return `${c.map}.at(${pk(c.key, P, ctx)}).${c.field}`;
|
|
380
|
+
return `${c.map}.at(${c.key.op === 'num' ? pidx(c.key.e, P, ctx) : pk(c.key, P, ctx)})`;
|
|
381
|
+
}
|
|
382
|
+
// A list's index, where it is read or set within the list: a natural, or an integer clamped at 0 (the same there).
|
|
383
|
+
export const pidx = (i, P, ctx) => (natOK(i, ctx) ? pn(i, P, ctx, 'nat') : `${pn(i, P, ctx, 'int', true)}.clamped`);
|
|
361
384
|
// A choice: a literal is written as the choice's own value where nothing else gives the choice (`status.of('open')`).
|
|
362
385
|
export function pl(l, P, ctx, bare = false) {
|
|
363
386
|
switch (l.op) {
|
|
@@ -371,7 +394,7 @@ export function pl(l, P, ctx, bare = false) {
|
|
|
371
394
|
return `${w}.of(${q(l.value)})`;
|
|
372
395
|
}
|
|
373
396
|
case 'ite': return `when(${pb(l.c, P, ctx)}, ${pl(l.a, P, ctx, l.b.op !== 'lit')}, ${pl(l.b, P, ctx, l.a.op !== 'lit' || l.b.op !== 'lit' ? l.a.op !== 'lit' : false)})`;
|
|
374
|
-
case 'cell': return
|
|
397
|
+
case 'cell': return cellText(l, P, ctx);
|
|
375
398
|
}
|
|
376
399
|
}
|
|
377
400
|
export function pk(k, P, ctx) {
|
|
@@ -12,6 +12,7 @@ export declare class Retype extends Error {
|
|
|
12
12
|
}
|
|
13
13
|
export type Sort = {
|
|
14
14
|
k: 'num';
|
|
15
|
+
date?: true;
|
|
15
16
|
} | {
|
|
16
17
|
k: 'bool';
|
|
17
18
|
} | {
|
|
@@ -28,6 +29,9 @@ export type Shape = Sort | {
|
|
|
28
29
|
key: 'num' | 'str';
|
|
29
30
|
val: Shape;
|
|
30
31
|
js: 'Map' | 'record';
|
|
32
|
+
} | {
|
|
33
|
+
k: 'list';
|
|
34
|
+
of: Sort;
|
|
31
35
|
};
|
|
32
36
|
export type Var = {
|
|
33
37
|
name: string;
|
|
@@ -52,6 +56,9 @@ export type Layout = {
|
|
|
52
56
|
} | {
|
|
53
57
|
k: 'map';
|
|
54
58
|
name: string;
|
|
59
|
+
} | {
|
|
60
|
+
k: 'list';
|
|
61
|
+
name: string;
|
|
55
62
|
} | {
|
|
56
63
|
k: 'const';
|
|
57
64
|
value: Term;
|
|
@@ -94,6 +101,32 @@ export type MapWrite = {
|
|
|
94
101
|
has: B;
|
|
95
102
|
vals: Record<string, Term>;
|
|
96
103
|
};
|
|
104
|
+
export type ListOp = {
|
|
105
|
+
op: 'push';
|
|
106
|
+
x: V;
|
|
107
|
+
when: B;
|
|
108
|
+
} | {
|
|
109
|
+
op: 'pop';
|
|
110
|
+
when: B;
|
|
111
|
+
} | {
|
|
112
|
+
op: 'set';
|
|
113
|
+
i: N;
|
|
114
|
+
x: V;
|
|
115
|
+
when: B;
|
|
116
|
+
};
|
|
117
|
+
export type ListWrite = ({
|
|
118
|
+
op: 'push';
|
|
119
|
+
x: Term;
|
|
120
|
+
when: B;
|
|
121
|
+
} | {
|
|
122
|
+
op: 'pop';
|
|
123
|
+
when: B;
|
|
124
|
+
} | {
|
|
125
|
+
op: 'set';
|
|
126
|
+
i: N;
|
|
127
|
+
x: Term;
|
|
128
|
+
when: B;
|
|
129
|
+
})[];
|
|
97
130
|
export type Model = {
|
|
98
131
|
name: string;
|
|
99
132
|
shape: 'reducer' | 'functions' | 'class';
|
|
@@ -108,6 +141,8 @@ export type Model = {
|
|
|
108
141
|
writes: Record<string, Term>;
|
|
109
142
|
mapWrites: Record<string, MapWrite>;
|
|
110
143
|
outputs: string[];
|
|
144
|
+
lists?: MapDecl[];
|
|
145
|
+
listWrites?: Record<string, ListWrite>;
|
|
111
146
|
refuse: B;
|
|
112
147
|
pre: B;
|
|
113
148
|
layout: Layout;
|
|
@@ -121,6 +156,22 @@ export type Model = {
|
|
|
121
156
|
}>;
|
|
122
157
|
initSource?: string;
|
|
123
158
|
spans?: [number, number][];
|
|
159
|
+
factory?: {
|
|
160
|
+
at: number;
|
|
161
|
+
text: string;
|
|
162
|
+
};
|
|
163
|
+
results?: Record<string, {
|
|
164
|
+
k: 'scalar';
|
|
165
|
+
name: string;
|
|
166
|
+
} | {
|
|
167
|
+
k: 'rec';
|
|
168
|
+
fields: [string, string][];
|
|
169
|
+
} | {
|
|
170
|
+
k: 'maybe';
|
|
171
|
+
name: string;
|
|
172
|
+
missing: string;
|
|
173
|
+
null: boolean;
|
|
174
|
+
}>;
|
|
124
175
|
};
|
|
125
176
|
type V = {
|
|
126
177
|
t: 'num';
|
|
@@ -147,8 +198,16 @@ type V = {
|
|
|
147
198
|
t: 'opt';
|
|
148
199
|
has: B;
|
|
149
200
|
v: V;
|
|
201
|
+
null?: true;
|
|
150
202
|
} | {
|
|
151
203
|
t: 'undef';
|
|
204
|
+
null?: true;
|
|
205
|
+
} | {
|
|
206
|
+
t: 'outside';
|
|
207
|
+
path: string;
|
|
208
|
+
} | {
|
|
209
|
+
t: 'opaque';
|
|
210
|
+
what: string;
|
|
152
211
|
} | {
|
|
153
212
|
t: 'phi';
|
|
154
213
|
c: B;
|
|
@@ -175,7 +234,14 @@ type MapObj = {
|
|
|
175
234
|
origin: 'fresh' | 'input' | 'this' | 'shared';
|
|
176
235
|
gen: number;
|
|
177
236
|
};
|
|
178
|
-
type
|
|
237
|
+
type ListObj = {
|
|
238
|
+
k: 'list';
|
|
239
|
+
base: string;
|
|
240
|
+
decl: MapDecl;
|
|
241
|
+
ops: ListOp[];
|
|
242
|
+
origin: 'fresh' | 'input' | 'this' | 'shared';
|
|
243
|
+
};
|
|
244
|
+
type Obj = Rec | MapObj | ListObj | {
|
|
179
245
|
k: 'alias';
|
|
180
246
|
to: V;
|
|
181
247
|
};
|
|
@@ -210,8 +276,11 @@ export type Setup = {
|
|
|
210
276
|
names: Set<string>;
|
|
211
277
|
vars: Map<string, Var>;
|
|
212
278
|
maps: Map<string, MapDecl>;
|
|
279
|
+
lists?: Map<string, MapDecl>;
|
|
213
280
|
lazySorts: Map<string, Sort>;
|
|
214
281
|
cls?: ts.ClassLikeDeclaration;
|
|
282
|
+
chain?: ts.ClassLikeDeclaration[];
|
|
283
|
+
closure?: Set<ts.Node>;
|
|
215
284
|
now?: string;
|
|
216
285
|
nowRole: 'input' | 'param';
|
|
217
286
|
hints: WeakMap<object, string>;
|
|
@@ -223,6 +292,12 @@ export type Setup = {
|
|
|
223
292
|
ctor?: boolean;
|
|
224
293
|
ours: (sf: ts.SourceFile) => boolean;
|
|
225
294
|
spans?: [number, number][];
|
|
295
|
+
xstate?: {
|
|
296
|
+
outside: Map<string, {
|
|
297
|
+
path: string;
|
|
298
|
+
sort: Sort;
|
|
299
|
+
}>;
|
|
300
|
+
};
|
|
226
301
|
};
|
|
227
302
|
export declare class Exec {
|
|
228
303
|
readonly s: Setup;
|
|
@@ -262,7 +337,7 @@ export declare class Exec {
|
|
|
262
337
|
truthy(v: V, at: ts.Node): B;
|
|
263
338
|
num(v: V, at: ts.Node, p: Path): N;
|
|
264
339
|
private bool;
|
|
265
|
-
equal(a: V, b: V, at: ts.Node): B;
|
|
340
|
+
equal(a: V, b: V, at: ts.Node, loose?: boolean): B;
|
|
266
341
|
ev(e: ts.Expression, p: Path): [V, Path];
|
|
267
342
|
private joinValues;
|
|
268
343
|
private name;
|
|
@@ -283,16 +358,22 @@ export declare class Exec {
|
|
|
283
358
|
private mapId;
|
|
284
359
|
mapSet(id: string, key: K, v: V | undefined, at: ts.Node, p: Path, track?: boolean): Path;
|
|
285
360
|
private cellValue;
|
|
286
|
-
assign(target: ts.Expression, v: V, p: Path): Path;
|
|
361
|
+
assign(target: ts.Expression, v: V, p: Path, setTime?: boolean): Path;
|
|
287
362
|
private writeField;
|
|
288
363
|
resolved(e: ts.Node): ts.Symbol | undefined;
|
|
289
364
|
private args;
|
|
290
365
|
private call;
|
|
366
|
+
private outside;
|
|
367
|
+
private listLen;
|
|
368
|
+
private listOp;
|
|
369
|
+
private array;
|
|
370
|
+
member(name: string, from?: number): ts.ClassElement | undefined;
|
|
291
371
|
private math;
|
|
292
372
|
private now;
|
|
293
373
|
private newExpr;
|
|
294
374
|
inline(f: Callable, args: V[], at: ts.Node, p: Path): [V, Path];
|
|
295
375
|
}
|
|
376
|
+
export declare const isDate: (t: ts.Type) => boolean;
|
|
296
377
|
export declare const memberName: (n: ts.PropertyName | ts.MemberName) => string;
|
|
297
378
|
export declare function impure(e: ts.Node): boolean;
|
|
298
|
-
export type { V, Path, Rec, MapObj, Heap, Flow };
|
|
379
|
+
export type { V, Path, Rec, MapObj, ListObj, Heap, Flow };
|