gdp-wired 0.26.0 → 0.27.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/dist/core/accel.d.ts +19 -0
- package/dist/core/accel.js +547 -205
- package/dist/core/bmc.d.ts +4 -1
- package/dist/core/bmc.js +18 -15
- package/dist/core/cyclic.js +17 -10
- package/dist/core/discover.js +64 -25
- package/dist/core/dsl.js +8 -7
- package/dist/core/extract-check.d.ts +52 -2
- package/dist/core/extract-check.js +141 -102
- package/dist/core/extract-read.d.ts +13 -0
- package/dist/core/extract-read.js +12 -10
- package/dist/core/extract-shapes.js +2 -2
- package/dist/core/extract.d.ts +1 -0
- package/dist/core/extract.js +10 -5
- package/dist/core/infer.d.ts +1 -0
- package/dist/core/infer.js +54 -46
- package/dist/core/machine.js +0 -1
- package/dist/core/nonterm.js +27 -7
- package/dist/core/solver.d.ts +21 -0
- package/dist/core/solver.js +8 -0
- package/dist/core/translate.js +69 -19
- package/dist/kernel/cdcl.js +212 -78
- package/dist/kernel/prove.d.ts +30 -4
- package/dist/kernel/prove.js +119 -25
- package/dist/kernel/reader.d.ts +74 -5
- package/dist/kernel/reader.js +531 -75
- package/dist/kernel/simplex.d.ts +26 -1
- package/dist/kernel/simplex.js +148 -14
- package/package.json +1 -1
|
@@ -126,9 +126,9 @@ export function sandbox(code, file, expose, modules = {}, init, files = {}, extr
|
|
|
126
126
|
return { ctx, counts, arms, call, setNow: n => { now = n; }, get: name => vm.runInContext(`__gdp[${JSON.stringify(name)}]`, ctx) };
|
|
127
127
|
}
|
|
128
128
|
const isMap = (x) => Object.prototype.toString.call(x) === '[object Map]';
|
|
129
|
-
class Outside extends Error {
|
|
129
|
+
export class Outside extends Error {
|
|
130
130
|
}
|
|
131
|
-
class Refused extends Error {
|
|
131
|
+
export class Refused extends Error {
|
|
132
132
|
}
|
|
133
133
|
// The code's value as a snapshot, by the layout; what the rule has no place for is a difference.
|
|
134
134
|
function snapOf(v, layout, m, consts, out = { leaves: {}, maps: {} }, path = 'state') {
|
|
@@ -262,8 +262,8 @@ function valueOf(s, layout, m, consts, ctx) {
|
|
|
262
262
|
ctx.__in = JSON.stringify(tree(layout));
|
|
263
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);
|
|
264
264
|
}
|
|
265
|
-
const showSnap = (s) => JSON.stringify({ ...s.leaves, ...Object.fromEntries(Object.entries(s.maps).map(([k, v]) => [k, v])), ...(s.lists ?? {}) });
|
|
266
|
-
const sameSnap = (a, b) => {
|
|
265
|
+
export const showSnap = (s) => JSON.stringify({ ...s.leaves, ...Object.fromEntries(Object.entries(s.maps).map(([k, v]) => [k, v])), ...(s.lists ?? {}) });
|
|
266
|
+
export const sameSnap = (a, b) => {
|
|
267
267
|
for (const k of new Set([...Object.keys(a.leaves), ...Object.keys(b.leaves)]))
|
|
268
268
|
if (a.leaves[k] !== b.leaves[k])
|
|
269
269
|
return `${k} is ${JSON.stringify(a.leaves[k])} in the code, ${JSON.stringify(b.leaves[k])} in the rule`;
|
|
@@ -281,7 +281,7 @@ const sameSnap = (a, b) => {
|
|
|
281
281
|
// --- the rule's side ------------------------------------------------------------------------------------------------
|
|
282
282
|
export const kindOfVar = (v, sorts, at = v.name) => (v.sort.k === 'num' ? (sorts.get(at) === 'nat' ? nat : int) : v.sort.k === 'bool' ? bool : v.sort.k === 'choice' ? oneOf(...v.sort.values) : str());
|
|
283
283
|
const idText = (id) => interned().find(([, n]) => n === id)?.[0];
|
|
284
|
-
function ruleSnap(r, m, st, sorts) {
|
|
284
|
+
export function ruleSnap(r, m, st, sorts) {
|
|
285
285
|
const d = r.decode(st), leaves = {}, maps = {};
|
|
286
286
|
for (const v of m.state)
|
|
287
287
|
if (!m.outputs.includes(v.name))
|
|
@@ -303,7 +303,7 @@ function ruleSnap(r, m, st, sorts) {
|
|
|
303
303
|
return { leaves, maps, ...(m.lists?.length ? { lists } : {}) };
|
|
304
304
|
}
|
|
305
305
|
// A snapshot as a state of the rule (each variable and cell by its kind).
|
|
306
|
-
function ruleState(base, s, m, sorts) {
|
|
306
|
+
export function ruleState(base, s, m, sorts) {
|
|
307
307
|
const scalars = { ...base.scalars }, maps = Object.fromEntries(Object.entries(base.maps).map(([k]) => [k, new Map()]));
|
|
308
308
|
for (const v of m.state)
|
|
309
309
|
if (v.name in s.leaves)
|
|
@@ -331,14 +331,14 @@ import { record } from "./dsl.js";
|
|
|
331
331
|
const cellKind = (d, sorts) => record({ has: bool, ...Object.fromEntries(d.fields.map(f => [f.name, kindOfVar(f, sorts, `${d.name}.${f.name}`)])) });
|
|
332
332
|
// --- values to draw -------------------------------------------------------------------------------------------------
|
|
333
333
|
const BIG = [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER - 1, 2 ** 31, 2 ** 32];
|
|
334
|
-
function constantsOf(m) {
|
|
334
|
+
export function constantsOf(m) {
|
|
335
335
|
const out = new Set([0, 1]);
|
|
336
336
|
walk([m.writes, m.mapWrites, m.refuse, m.pre, m.init], o => { if (o.op === 'const' && typeof o.v === 'number')
|
|
337
337
|
out.add(o.v); if (typeof o.k === 'number')
|
|
338
338
|
out.add(o.k); });
|
|
339
339
|
return [...out];
|
|
340
340
|
}
|
|
341
|
-
function draw(sort, sorts, name, rand, near, bound, strs) {
|
|
341
|
+
export function draw(sort, sorts, name, rand, near, bound, strs) {
|
|
342
342
|
switch (sort.k) {
|
|
343
343
|
case 'bool': return rand(2) === 1;
|
|
344
344
|
case 'choice': return sort.values[rand(sort.values.length)];
|
|
@@ -362,37 +362,83 @@ function draw(sort, sorts, name, rand, near, bound, strs) {
|
|
|
362
362
|
}
|
|
363
363
|
}
|
|
364
364
|
export function check(code, file, m, r, sorts, opts = {}) {
|
|
365
|
-
const t0 = performance.now(), rand = seeded((opts.seed ?? 7) >>> 0 || 1), bound = opts.bound ?? 12;
|
|
366
365
|
const isClass = m.shape === 'class', fns = m.shape === 'class' ? [m.entry] : [...new Set(m.events.map(e => e.call))];
|
|
367
366
|
const box = sandbox(code, file, fns, opts.modules, m.initSource, opts.files, m.factory ? [[m.factory.at, m.factory.text]] : []);
|
|
368
367
|
// An object a factory makes: its state is what its functions close over, read and set through the two functions the
|
|
369
368
|
// check added to it.
|
|
370
369
|
const stateOf = (self) => (m.factory ? box.call('$get', self, []).value : self);
|
|
371
|
-
const interp = r.interpreter(), gen = r.compiled(), machine = r.machine;
|
|
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 };
|
|
373
|
-
const consts = constantsOf(m), strs = ['a', 'b', 'c', ''];
|
|
374
|
-
const paramKinds = m.params.map(v => [v, kindOfVar(v, sorts)]), inputKinds = m.inputs.map(v => [v, kindOfVar(v, sorts)]);
|
|
375
|
-
// A term over the params at their values (a constant field, a start).
|
|
376
370
|
const evalAt = (env) => (t) => evalTerm(t, env);
|
|
377
|
-
const fail = (what) => { ev.mismatch = what; return finish(); };
|
|
378
371
|
// The arms of the code the step reads (the entry, its methods, the functions it inlines; a class's constructor too).
|
|
379
372
|
const inSpan = (a) => !m.spans || m.spans.some(([s0, e0]) => a.pos >= s0 && a.pos < e0);
|
|
380
373
|
const counted = box.arms.map((a, i) => [a, i]).filter(([a]) => inSpan(a));
|
|
381
|
-
|
|
374
|
+
const E = JSON.stringify(m.entry);
|
|
375
|
+
if (isClass && !m.factory)
|
|
376
|
+
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);
|
|
377
|
+
if (m.factory)
|
|
378
|
+
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);
|
|
379
|
+
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]));
|
|
380
|
+
const side = {
|
|
381
|
+
make: params => {
|
|
382
|
+
const now0 = m.params.find(v => v.note?.startsWith('Date.now()'));
|
|
383
|
+
if (now0)
|
|
384
|
+
box.setNow(params[now0.name]);
|
|
385
|
+
// A Map the constructor is given: an empty one, made in the code's realm.
|
|
386
|
+
return 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])));
|
|
387
|
+
},
|
|
388
|
+
at: (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}`); })()),
|
|
389
|
+
snapOf: (self, params) => snapOf(stateOf(self), m.layout, m, evalAt(params)),
|
|
390
|
+
call: (self, e, args) => box.call('$method', self, [e.call, args]),
|
|
391
|
+
reduce: (snap, e, args, params) => {
|
|
392
|
+
const input = valueOf(snap, m.layout, m, evalAt(params), box.ctx), before = JSON.stringify(input, mapReplacer);
|
|
393
|
+
const res = box.call(e.call, undefined, [input, ...args.slice(1)]);
|
|
394
|
+
if (JSON.stringify(input, mapReplacer) !== before)
|
|
395
|
+
return { problem: `${e.call} changed the state it was given` };
|
|
396
|
+
return res.ok ? { snap: snapOf(res.value, m.layout, m, evalAt(params)) } : { refused: res.error };
|
|
397
|
+
},
|
|
398
|
+
args: (inputs, e) => {
|
|
399
|
+
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]; };
|
|
400
|
+
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'
|
|
401
|
+
? 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]]))
|
|
402
|
+
: undefined);
|
|
403
|
+
return e.args.map(build);
|
|
404
|
+
},
|
|
405
|
+
setNow: n => box.setNow(n),
|
|
406
|
+
// The code's own initial state (where the code gives it), against the rule's.
|
|
407
|
+
init: (snap, params) => {
|
|
408
|
+
if (!m.initSource)
|
|
409
|
+
return undefined;
|
|
410
|
+
const made = vmOf().runInContext('(() => { try { return {ok: true, value: __gdpInit()} } catch (e) { return {ok: false, error: String(e)} } })()', box.ctx);
|
|
411
|
+
if (!made.ok)
|
|
412
|
+
return `the initial state throws (${made.error})`;
|
|
413
|
+
try {
|
|
414
|
+
const diff = sameSnap(snapOf(made.value, m.layout, m, evalAt(params)), snap);
|
|
415
|
+
if (diff)
|
|
416
|
+
return `the initial state: ${diff}`;
|
|
417
|
+
}
|
|
418
|
+
catch (x) {
|
|
419
|
+
return `the initial state: ${x.message}`;
|
|
420
|
+
}
|
|
421
|
+
return undefined;
|
|
422
|
+
},
|
|
423
|
+
coverage: () => ({ arms: counted.length, hit: counted.filter(([, i]) => box.counts[i] > 0).length, missed: counted.filter(([, i]) => box.counts[i] === 0).map(([a]) => `${a.label} at ${a.where}`) }),
|
|
424
|
+
};
|
|
425
|
+
return drive(m, r, sorts, side, opts);
|
|
426
|
+
}
|
|
427
|
+
// The check: requests from the start, from drawn states and from the prover's witnesses, each made of the code
|
|
428
|
+
// (through its side) and of the rule, and compared.
|
|
429
|
+
export function drive(m, r, sorts, code, opts = {}) {
|
|
430
|
+
const t0 = performance.now(), rand = seeded((opts.seed ?? 7) >>> 0 || 1), bound = opts.bound ?? 12;
|
|
431
|
+
const isClass = m.shape === 'class';
|
|
432
|
+
const interp = r.interpreter(), gen = r.compiled(), machine = r.machine;
|
|
433
|
+
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: 0, hit: 0, missed: [] }, ms: 0 };
|
|
434
|
+
const consts = constantsOf(m), strs = ['a', 'b', 'c', ''];
|
|
435
|
+
const paramKinds = m.params.map(v => [v, kindOfVar(v, sorts)]), inputKinds = m.inputs.map(v => [v, kindOfVar(v, sorts)]);
|
|
436
|
+
const fail = (what) => { ev.mismatch = what; return finish(); };
|
|
382
437
|
const finish = () => {
|
|
383
|
-
ev.coverage
|
|
384
|
-
ev.coverage.missed = counted.filter(([, i]) => box.counts[i] === 0).map(([a]) => `${a.label} at ${a.where}`);
|
|
438
|
+
ev.coverage = code.coverage();
|
|
385
439
|
ev.ms = Math.round(performance.now() - t0);
|
|
386
440
|
return ev;
|
|
387
441
|
};
|
|
388
|
-
const request = (params, inputs, e) => {
|
|
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'
|
|
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]]))
|
|
392
|
-
: undefined);
|
|
393
|
-
void params;
|
|
394
|
-
return e.args.map(build);
|
|
395
|
-
};
|
|
396
442
|
const draws = (st, params) => [...consts, ...Object.values(st.leaves).filter((x) => typeof x === 'number'), ...Object.values(params).filter((x) => typeof x === 'number')];
|
|
397
443
|
let lastNow = 1_000;
|
|
398
444
|
const drawRequest = (st, params) => {
|
|
@@ -411,7 +457,7 @@ export function check(code, file, m, r, sorts, opts = {}) {
|
|
|
411
457
|
const keys = Object.values(st.maps).flatMap(c => Object.keys(c));
|
|
412
458
|
// An input given as a natural (domains) is drawn as one: the claim is for those, as the user said.
|
|
413
459
|
const x = draw(v.sort, sorts, v.name, rand, near, bound, [...strs, ...keys]);
|
|
414
|
-
inputs[v.name] = opts.given?.[v.name] === 'nat' && typeof x === 'number' ? Math.abs(x) : x;
|
|
460
|
+
inputs[v.name] = code.input ? code.input(v, x, rand) : opts.given?.[v.name] === 'nat' && typeof x === 'number' ? Math.abs(x) : x;
|
|
415
461
|
}
|
|
416
462
|
return { e, inputs };
|
|
417
463
|
};
|
|
@@ -435,31 +481,30 @@ export function check(code, file, m, r, sorts, opts = {}) {
|
|
|
435
481
|
// Steps the code and the rule from one state; undefined when they agree (the next state on both sides is returned
|
|
436
482
|
// through `next`), else the difference.
|
|
437
483
|
const step = (params, ps, side, st, inputs, e, next, where) => {
|
|
438
|
-
const args =
|
|
484
|
+
const args = code.args(inputs, e), raw = ruleInputs(inputs, e);
|
|
439
485
|
const nowVar = m.inputs.find(v => v.note?.startsWith('Date.now()'));
|
|
440
486
|
if (nowVar)
|
|
441
|
-
|
|
487
|
+
code.setNow(inputs[nowVar.name]);
|
|
442
488
|
// The code.
|
|
443
|
-
let
|
|
489
|
+
let res;
|
|
444
490
|
try {
|
|
445
491
|
if (isClass) {
|
|
446
|
-
const self = side.self,
|
|
447
|
-
if (!
|
|
448
|
-
|
|
492
|
+
const self = side.self, c = code.call(self, e, args);
|
|
493
|
+
if (!c.ok)
|
|
494
|
+
res = { refused: c.error };
|
|
449
495
|
else
|
|
450
|
-
|
|
496
|
+
res = { snap: code.snapOf(self, params), out: c.value, self };
|
|
451
497
|
}
|
|
452
498
|
else {
|
|
453
|
-
const
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
code = res.ok ? { snap: snapOf(res.value, m.layout, m, evalAt(params)) } : { refused: res.error };
|
|
499
|
+
const c = code.reduce(side.snap, e, args, params);
|
|
500
|
+
if ('problem' in c)
|
|
501
|
+
return `${where}: ${c.problem}`;
|
|
502
|
+
res = c;
|
|
458
503
|
}
|
|
459
504
|
}
|
|
460
505
|
catch (x) {
|
|
461
506
|
if (x instanceof Outside)
|
|
462
|
-
|
|
507
|
+
res = { outside: x.message };
|
|
463
508
|
else
|
|
464
509
|
return `${where}: the code's state after the request: ${x.message}`;
|
|
465
510
|
}
|
|
@@ -486,19 +531,22 @@ export function check(code, file, m, r, sorts, opts = {}) {
|
|
|
486
531
|
catch (x) {
|
|
487
532
|
rule = x instanceof Refused ? { refused: x.message } : /2\^53|safe integer/.test(x.message) ? { outside: x.message } : { refused: x.message };
|
|
488
533
|
}
|
|
534
|
+
// Where Go goes on past a type the rule refuses at (a uint64 below 0): the edge the rule's claim stops at.
|
|
535
|
+
if ('refused' in rule && code.edge?.(side.snap, raw))
|
|
536
|
+
rule = { outside: `${rule.refused}: past the rule's numbers` };
|
|
489
537
|
}
|
|
490
538
|
const req = `${e.call}(${JSON.stringify(args).slice(1, -1)})${nowVar ? ` at ${inputs[nowVar.name]}` : ''}`;
|
|
491
539
|
const from = `from ${showSnap(side.snap)}${m.params.length ? ` with ${JSON.stringify(params)}` : ''}`;
|
|
492
|
-
if ('outside' in
|
|
540
|
+
if ('outside' in res || 'outside' in rule) {
|
|
493
541
|
// The code past the safe integers: the rule's runtime must refuse there too (it never rounds).
|
|
494
542
|
next.stop = true;
|
|
495
|
-
if ('outside' in
|
|
543
|
+
if ('outside' in res) {
|
|
496
544
|
if ('st' in rule)
|
|
497
|
-
return `${where}: ${req} ${from}: the code leaves the safe integers (${
|
|
545
|
+
return `${where}: ${req} ${from}: the code leaves the safe integers (${res.outside}) where the rule takes the step`;
|
|
498
546
|
ev.outside++;
|
|
499
547
|
return undefined;
|
|
500
548
|
}
|
|
501
|
-
if ('refused' in
|
|
549
|
+
if ('refused' in res) {
|
|
502
550
|
ev.refusedBoth++;
|
|
503
551
|
return undefined;
|
|
504
552
|
}
|
|
@@ -508,13 +556,13 @@ export function check(code, file, m, r, sorts, opts = {}) {
|
|
|
508
556
|
ev.edgeSample ??= `${req} ${from}`;
|
|
509
557
|
return undefined;
|
|
510
558
|
}
|
|
511
|
-
if ('refused' in
|
|
559
|
+
if ('refused' in res && 'refused' in rule) {
|
|
512
560
|
// A refusal leaves the state as it was: the object the code threw from must be as it was too.
|
|
513
561
|
if (isClass) {
|
|
514
562
|
try {
|
|
515
|
-
const after = snapOf(
|
|
563
|
+
const after = code.snapOf(side.self, params), d = sameSnap(after, side.snap);
|
|
516
564
|
if (d)
|
|
517
|
-
return `${where}: ${req} ${from}: the code throws (${
|
|
565
|
+
return `${where}: ${req} ${from}: the code throws (${res.refused}) after changing the object: ${d}`;
|
|
518
566
|
}
|
|
519
567
|
catch (x) {
|
|
520
568
|
return `${where}: ${req} ${from}: the code throws after changing the object (${x.message})`;
|
|
@@ -523,47 +571,40 @@ export function check(code, file, m, r, sorts, opts = {}) {
|
|
|
523
571
|
ev.refusedBoth++;
|
|
524
572
|
return undefined;
|
|
525
573
|
}
|
|
526
|
-
if ('refused' in
|
|
527
|
-
return `${where}: ${req} ${from}: the code throws (${
|
|
574
|
+
if ('refused' in res)
|
|
575
|
+
return `${where}: ${req} ${from}: the code throws (${res.refused}), the rule takes the step`;
|
|
528
576
|
if ('refused' in rule)
|
|
529
577
|
return `${where}: ${req} ${from}: the rule refuses it (${rule.refused}), the code doesn't`;
|
|
530
|
-
const ruleSide = ruleSnap(r, m, rule.st, sorts), diff = sameSnap(
|
|
578
|
+
const ruleSide = ruleSnap(r, m, rule.st, sorts), diff = sameSnap(res.snap, ruleSide);
|
|
531
579
|
if (diff)
|
|
532
580
|
return `${where}: ${req} ${from}: ${diff}`;
|
|
533
581
|
if (isClass) {
|
|
534
582
|
// 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
|
|
536
|
-
const bad = (what) => `${where}: ${req} ${from}: ${e.call} returns ${JSON.stringify(
|
|
537
|
-
if (
|
|
538
|
-
return bad(`the rule's ${
|
|
539
|
-
if (
|
|
540
|
-
const o =
|
|
541
|
-
if (typeof o !== 'object' || o === null || Object.keys(o).length !==
|
|
583
|
+
const rk = m.results?.[e.call], d = r.decode(rule.st);
|
|
584
|
+
const bad = (what) => `${where}: ${req} ${from}: ${e.call} returns ${JSON.stringify(res.out)}, ${what}`;
|
|
585
|
+
if (rk?.k === 'scalar' && d[rk.name] !== res.out)
|
|
586
|
+
return bad(`the rule's ${rk.name} is ${JSON.stringify(d[rk.name])}`);
|
|
587
|
+
if (rk?.k === 'rec') {
|
|
588
|
+
const o = res.out;
|
|
589
|
+
if (typeof o !== 'object' || o === null || Object.keys(o).length !== rk.fields.length)
|
|
542
590
|
return bad('not a record of the fields the rule keeps');
|
|
543
|
-
for (const [f, n] of
|
|
591
|
+
for (const [f, n] of rk.fields)
|
|
544
592
|
if (o[f] !== d[n])
|
|
545
593
|
return bad(`the rule's ${n} is ${JSON.stringify(d[n])}`);
|
|
546
594
|
}
|
|
547
|
-
if (
|
|
548
|
-
const gone =
|
|
549
|
-
if (gone !== d[
|
|
550
|
-
return bad(`the rule's ${
|
|
551
|
-
if (!gone && d[
|
|
552
|
-
return bad(`the rule's ${
|
|
595
|
+
if (rk?.k === 'maybe') {
|
|
596
|
+
const gone = res.out === (rk.null ? null : undefined);
|
|
597
|
+
if (gone !== d[rk.missing])
|
|
598
|
+
return bad(`the rule's ${rk.missing} is ${JSON.stringify(d[rk.missing])}`);
|
|
599
|
+
if (!gone && d[rk.name] !== res.out)
|
|
600
|
+
return bad(`the rule's ${rk.name} is ${JSON.stringify(d[rk.name])}`);
|
|
553
601
|
}
|
|
554
602
|
}
|
|
555
|
-
next.side = { snap:
|
|
603
|
+
next.side = { snap: res.snap, ...(res.self ? { self: res.self } : {}) };
|
|
556
604
|
next.st = rule.st;
|
|
557
605
|
return undefined;
|
|
558
606
|
};
|
|
559
607
|
// A class's object: made by its constructor, or set to a snapshot.
|
|
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}`); })();
|
|
567
608
|
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)]));
|
|
568
609
|
const start = (params) => {
|
|
569
610
|
const ctorRefuses = (() => { const pre = evalTerm(m.pre, params); return pre !== true; })();
|
|
@@ -575,11 +616,7 @@ export function check(code, file, m, r, sorts, opts = {}) {
|
|
|
575
616
|
ps = undefined;
|
|
576
617
|
}
|
|
577
618
|
if (isClass) {
|
|
578
|
-
const
|
|
579
|
-
if (now0)
|
|
580
|
-
box.setNow(params[now0.name]);
|
|
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])));
|
|
619
|
+
const made = code.make(params);
|
|
583
620
|
const ruleRefuses = ps === undefined || ctorRefuses;
|
|
584
621
|
if (!made.ok)
|
|
585
622
|
return ruleRefuses ? {} : { problem: `new ${m.entry}(${JSON.stringify(params)}) throws (${made.error}), the rule's precondition holds` };
|
|
@@ -587,7 +624,7 @@ export function check(code, file, m, r, sorts, opts = {}) {
|
|
|
587
624
|
return { problem: `new ${m.entry}(${JSON.stringify(params)}) is made, the rule's ${ps === undefined ? 'param kinds refuse' : 'precondition refuses'} it` };
|
|
588
625
|
const st = interp.init(ps);
|
|
589
626
|
try {
|
|
590
|
-
const snap = snapOf(
|
|
627
|
+
const snap = code.snapOf(made.value, params);
|
|
591
628
|
const diff = sameSnap(snap, ruleSnap(r, m, st, sorts));
|
|
592
629
|
if (diff)
|
|
593
630
|
return { problem: `new ${m.entry}(${JSON.stringify(params)}): ${diff}` };
|
|
@@ -598,20 +635,9 @@ export function check(code, file, m, r, sorts, opts = {}) {
|
|
|
598
635
|
}
|
|
599
636
|
}
|
|
600
637
|
const st = interp.init(ps ?? {}), snap = ruleSnap(r, m, st, sorts);
|
|
601
|
-
|
|
602
|
-
if (
|
|
603
|
-
|
|
604
|
-
if (!made.ok)
|
|
605
|
-
return { problem: `the initial state throws (${made.error})` };
|
|
606
|
-
try {
|
|
607
|
-
const diff = sameSnap(snapOf(made.value, m.layout, m, evalAt(params)), snap);
|
|
608
|
-
if (diff)
|
|
609
|
-
return { problem: `the initial state: ${diff}` };
|
|
610
|
-
}
|
|
611
|
-
catch (x) {
|
|
612
|
-
return { problem: `the initial state: ${x.message}` };
|
|
613
|
-
}
|
|
614
|
-
}
|
|
638
|
+
const problem = code.init?.(snap, params);
|
|
639
|
+
if (problem)
|
|
640
|
+
return { problem };
|
|
615
641
|
return { side: { snap }, st, ps: ps ?? {} };
|
|
616
642
|
};
|
|
617
643
|
const runs = opts.runs ?? 200, depth = opts.depth ?? 12;
|
|
@@ -640,6 +666,8 @@ export function check(code, file, m, r, sorts, opts = {}) {
|
|
|
640
666
|
}
|
|
641
667
|
// Steps from drawn states.
|
|
642
668
|
const drawSnap = (params) => {
|
|
669
|
+
if (code.drawSnap)
|
|
670
|
+
return code.drawSnap(rand);
|
|
643
671
|
const leaves = {}, maps = {};
|
|
644
672
|
for (const v of m.state)
|
|
645
673
|
if (!m.outputs.includes(v.name))
|
|
@@ -688,7 +716,11 @@ export function check(code, file, m, r, sorts, opts = {}) {
|
|
|
688
716
|
if (evalTerm(m.pre, params) !== true)
|
|
689
717
|
return undefined;
|
|
690
718
|
const st = ruleState(interp.init(ps), snap, m, sorts);
|
|
691
|
-
|
|
719
|
+
// A state the code can't hold (a value outside its type, Go's): no state of the code is that one.
|
|
720
|
+
const self = isClass ? code.at(snap, params) : undefined;
|
|
721
|
+
if (isClass && self === undefined)
|
|
722
|
+
return undefined;
|
|
723
|
+
const side = { snap, ...(isClass ? { self: self } : {}) };
|
|
692
724
|
return step(params, ps, side, st, inputs, e, {}, where);
|
|
693
725
|
};
|
|
694
726
|
for (let i = 0; i < (opts.states ?? 400); i++) {
|
|
@@ -732,7 +764,8 @@ export function check(code, file, m, r, sorts, opts = {}) {
|
|
|
732
764
|
if (!ok)
|
|
733
765
|
continue;
|
|
734
766
|
const e = m.events.find(x => Object.entries(x.select).every(([n, val]) => inputs[n] === val)) ?? m.events[0];
|
|
735
|
-
const
|
|
767
|
+
const snap = { leaves, maps: Object.fromEntries(m.maps.map(d => [d.name, {}])) };
|
|
768
|
+
const diff = fromState(params, code.normalize ? code.normalize(snap) : snap, inputs, e, `the prover's witness for ${showCond(c)}`);
|
|
736
769
|
ev.probes.steps++;
|
|
737
770
|
if (diff)
|
|
738
771
|
return fail(diff);
|
|
@@ -742,7 +775,7 @@ export function check(code, file, m, r, sorts, opts = {}) {
|
|
|
742
775
|
}
|
|
743
776
|
const mapReplacer = (_, v) => (isMap(v) ? { $map: [...v.entries()] } : v);
|
|
744
777
|
// The conditions a step reads (each branch's, each refusal's), as a probe asks the prover to reach.
|
|
745
|
-
function conditionsOf(m) {
|
|
778
|
+
export function conditionsOf(m) {
|
|
746
779
|
const out = [], seen = new Set();
|
|
747
780
|
const add = (c) => { if (c.op === 'const')
|
|
748
781
|
return; const k = I.keyOf(c); if (!seen.has(k) && !hasCell(c)) {
|
|
@@ -758,7 +791,7 @@ function conditionsOf(m) {
|
|
|
758
791
|
const hasCell = (c) => I.varsOf(c).maps.size > 0;
|
|
759
792
|
const showCond = (c) => JSON.stringify(c).replace(/"op":/g, '').slice(0, 120);
|
|
760
793
|
// A condition over the rule's env (the step law's `when`): the builders' own values, read from the env by name.
|
|
761
|
-
function condAt(c, env) {
|
|
794
|
+
export function condAt(c, env) {
|
|
762
795
|
const n = (e) => {
|
|
763
796
|
switch (e.op) {
|
|
764
797
|
case 'var': return Int.of(env[e.name]);
|
|
@@ -823,8 +856,11 @@ function condAt(c, env) {
|
|
|
823
856
|
}
|
|
824
857
|
import { yes as yesC, no as noC, when as whenDsl } from "./dsl.js";
|
|
825
858
|
const whenInt = (c, a, b) => whenDsl(c, a, b);
|
|
826
|
-
// A term at concrete values (a constant field over the params, a start, the precondition
|
|
827
|
-
|
|
859
|
+
// A term at concrete values (a constant field over the params, a start, the precondition; with `cell`, a state's
|
|
860
|
+
// map cells and list items too).
|
|
861
|
+
export function evalTerm(t, env, cell) {
|
|
862
|
+
const at = (map, k, field) => (cell ?? (() => { throw new Error('a map cell at the start'); }))(map, key(k), field);
|
|
863
|
+
const key = (k) => (k.op === 'num' ? n(k.e) : k.op === 'svar' ? env[k.name] : k.op === 'slit' ? k.value : b(k.c) ? key(k.a) : key(k.b));
|
|
828
864
|
const n = (e) => {
|
|
829
865
|
switch (e.op) {
|
|
830
866
|
case 'var': return env[e.name];
|
|
@@ -839,7 +875,7 @@ export function evalTerm(t, env) {
|
|
|
839
875
|
case 'divk': return Math.floor(n(e.a) / e.k);
|
|
840
876
|
case 'modk': return ((n(e.a) % e.k) + e.k) % e.k;
|
|
841
877
|
case 'ite': return b(e.c) ? n(e.a) : n(e.b);
|
|
842
|
-
case 'cell':
|
|
878
|
+
case 'cell': return at(e.map, e.key, e.field);
|
|
843
879
|
}
|
|
844
880
|
};
|
|
845
881
|
const l = (x) => (x.op === 'var' ? env[x.name] : x.op === 'lit' ? x.value : x.op === 'ite' ? (b(x.c) ? l(x.a) : l(x.b)) : (() => { throw new Error('a map cell'); })());
|
|
@@ -854,8 +890,11 @@ export function evalTerm(t, env) {
|
|
|
854
890
|
case 'ite': return b(x.c) ? b(x.a) : b(x.b);
|
|
855
891
|
case 'is': return l(x.l) === x.value;
|
|
856
892
|
case 'leq': return l(x.a) === l(x.b);
|
|
857
|
-
case 'keq':
|
|
858
|
-
|
|
893
|
+
case 'keq':
|
|
894
|
+
if (!cell)
|
|
895
|
+
throw new Error('a key at the start');
|
|
896
|
+
return key(x.a) === key(x.b);
|
|
897
|
+
case 'cell': return at(x.map, x.key, x.field);
|
|
859
898
|
}
|
|
860
899
|
};
|
|
861
900
|
if (t.op === 'var')
|
|
@@ -865,7 +904,7 @@ export function evalTerm(t, env) {
|
|
|
865
904
|
if (t.op === 'lit')
|
|
866
905
|
return t.value;
|
|
867
906
|
if (t.op === 'ite')
|
|
868
|
-
return b(t.c) ? evalTerm(t.a, env) : evalTerm(t.b, env);
|
|
907
|
+
return b(t.c) ? evalTerm(t.a, env, cell) : evalTerm(t.b, env, cell);
|
|
869
908
|
if (['add', 'sub', 'neg', 'mulk', 'mul', 'min', 'max', 'divk', 'modk', 'cell'].includes(t.op))
|
|
870
909
|
return n(t);
|
|
871
910
|
return b(t);
|
|
@@ -172,6 +172,7 @@ export type Model = {
|
|
|
172
172
|
missing: string;
|
|
173
173
|
null: boolean;
|
|
174
174
|
}>;
|
|
175
|
+
laws?: string[];
|
|
175
176
|
};
|
|
176
177
|
type V = {
|
|
177
178
|
t: 'num';
|
|
@@ -374,6 +375,18 @@ export declare class Exec {
|
|
|
374
375
|
inline(f: Callable, args: V[], at: ts.Node, p: Path): [V, Path];
|
|
375
376
|
}
|
|
376
377
|
export declare const isDate: (t: ts.Type) => boolean;
|
|
378
|
+
export declare function mergeWrites<V>(c: B, wa: Write<V> | undefined, wb: Write<V> | undefined, base: (key: K) => {
|
|
379
|
+
has: B;
|
|
380
|
+
vals: Map<string, V>;
|
|
381
|
+
}, scalar: (c: B, a: V, b: V) => V): Write<V> | undefined;
|
|
382
|
+
type Write<V> = {
|
|
383
|
+
key: K;
|
|
384
|
+
has: B;
|
|
385
|
+
vals: Map<string, V>;
|
|
386
|
+
};
|
|
387
|
+
export declare const mergeOps: <O extends {
|
|
388
|
+
when: B;
|
|
389
|
+
}>(c: B, a: O[], b: O[]) => O[];
|
|
377
390
|
export declare const memberName: (n: ts.PropertyName | ts.MemberName) => string;
|
|
378
391
|
export declare function impure(e: ts.Node): boolean;
|
|
379
392
|
export type { V, Path, Rec, MapObj, ListObj, Heap, Flow };
|
|
@@ -280,7 +280,7 @@ export class Exec {
|
|
|
280
280
|
if (oa.base !== ob.base)
|
|
281
281
|
return refuse(at, 'one of two lists by the path taken');
|
|
282
282
|
const origin = oa.origin === 'input' || ob.origin === 'input' ? 'input' : oa.origin;
|
|
283
|
-
return { ...oa, origin, ops:
|
|
283
|
+
return { ...oa, origin, ops: mergeOps(c, oa.ops, ob.ops) };
|
|
284
284
|
}
|
|
285
285
|
if (oa.k === 'map' && ob.k === 'map') {
|
|
286
286
|
if (oa.base !== ob.base)
|
|
@@ -292,15 +292,7 @@ export class Exec {
|
|
|
292
292
|
return refuse(at, 'an object that is of another kind by the path taken');
|
|
293
293
|
}
|
|
294
294
|
mergeW(c, oa, ob, at) { return this.mergeWrites(c, oa.decl, oa.w, ob.w, at); }
|
|
295
|
-
mergeWrites(c, decl, wa, wb, at) {
|
|
296
|
-
if (!wa && !wb)
|
|
297
|
-
return undefined;
|
|
298
|
-
const base = (key) => this.baseCell(decl, key);
|
|
299
|
-
const fill = (w, key) => w ?? { key, ...base(key) };
|
|
300
|
-
const xa = fill(wa, (wa ?? wb).key), xb = fill(wb, (wb ?? wa).key);
|
|
301
|
-
const vals = new Map([...xa.vals].map(([f, v]) => [f, this.mergeScalar(c, v, xb.vals.get(f), at)]));
|
|
302
|
-
return { key: I.kite(c, xa.key, xb.key), has: I.bite(c, xa.has, xb.has), vals };
|
|
303
|
-
}
|
|
295
|
+
mergeWrites(c, decl, wa, wb, at) { return mergeWrites(c, wa, wb, key => this.baseCell(decl, key), (c2, x, y) => this.mergeScalar(c2, x, y, at)); }
|
|
304
296
|
mergeScalar(c, a, b, at) {
|
|
305
297
|
if (a.t === 'num' && b.t === 'num')
|
|
306
298
|
return { t: 'num', e: I.nite(c, a.e, b.e) };
|
|
@@ -1525,6 +1517,16 @@ const nullOf = (at, a, b) => {
|
|
|
1525
1517
|
refuse(at, 'a value that may be null on one side and undefined on the other');
|
|
1526
1518
|
return ka === 'null' || kb === 'null' ? { null: true } : {};
|
|
1527
1519
|
};
|
|
1520
|
+
// A map's write and a list's operations by a condition (the Go reader's too).
|
|
1521
|
+
export function mergeWrites(c, wa, wb, base, scalar) {
|
|
1522
|
+
if (!wa && !wb)
|
|
1523
|
+
return undefined;
|
|
1524
|
+
const fill = (w, key) => w ?? { key, ...base(key) };
|
|
1525
|
+
const xa = fill(wa, (wa ?? wb).key), xb = fill(wb, (wb ?? wa).key);
|
|
1526
|
+
const vals = new Map([...xa.vals].map(([f, v]) => [f, scalar(c, v, xb.vals.get(f))]));
|
|
1527
|
+
return { key: I.kite(c, xa.key, xb.key), has: I.bite(c, xa.has, xb.has), vals };
|
|
1528
|
+
}
|
|
1529
|
+
export const mergeOps = (c, a, b) => [...a.map(o => ({ ...o, when: I.and(c, o.when) })), ...b.map(o => ({ ...o, when: I.and(I.not(c), o.when) }))];
|
|
1528
1530
|
const mergedGen = (a, b) => (a.gen === b.gen ? a.gen : Math.max(a.gen, b.gen) + 1);
|
|
1529
1531
|
// The module an import names, for a refusal.
|
|
1530
1532
|
const moduleOf = (d) => { let n = d; while (n && !ts.isImportDeclaration(n))
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
// the step's writes, what the code refuses (its throws) and how a request is made of the code.
|
|
6
6
|
import ts from 'typescript';
|
|
7
7
|
import * as I from "./extract-ir.js";
|
|
8
|
-
import { Exec, Refusal, Retype, memberName, normalize, program, shapeOf } from "./extract-read.js";
|
|
8
|
+
import { Exec, Refusal, Retype, memberName, mergeOps, normalize, program, shapeOf } from "./extract-read.js";
|
|
9
9
|
const at0 = (sf) => sf.statements[0] ?? sf;
|
|
10
10
|
const where = (n) => { const sf = n.getSourceFile(), { line, character } = sf.getLineAndCharacterOfPosition(n.getStart()); return `${sf.fileName.split('/').pop()}:${line + 1}:${character + 1}`; };
|
|
11
11
|
const refuse = (n, what) => { throw new Refusal(where(n), what); };
|
|
@@ -153,7 +153,7 @@ function mergeVals(ex, c, a, b, at) {
|
|
|
153
153
|
// A list's write by cases: each side's under its condition.
|
|
154
154
|
const lists = new Map();
|
|
155
155
|
for (const n of new Set([...(a.lists?.keys() ?? []), ...(b.lists?.keys() ?? [])]))
|
|
156
|
-
lists.set(n,
|
|
156
|
+
lists.set(n, mergeOps(c, a.lists?.get(n) ?? [], b.lists?.get(n) ?? []));
|
|
157
157
|
return { leaves, maps, ...(lists.size ? { lists } : {}) };
|
|
158
158
|
}
|
|
159
159
|
// Every way a step ends (each a path and its state), as one state by cases.
|
package/dist/core/extract.d.ts
CHANGED
|
@@ -25,6 +25,7 @@ export type Extraction = {
|
|
|
25
25
|
notes: string[];
|
|
26
26
|
};
|
|
27
27
|
export declare function extract(code: string, opts: ExtractOptions): Extraction;
|
|
28
|
+
export declare function fromModel(model: Model, file: string, domains: Record<string, 'nat' | 'int'> | undefined, notes: string[], run: (rule: Rule, sorts: Sorts) => Evidence): Extraction;
|
|
28
29
|
export declare const toSource: (x: Extraction) => string;
|
|
29
30
|
export type { Evidence, Model, Term };
|
|
30
31
|
export { Refusal };
|
package/dist/core/extract.js
CHANGED
|
@@ -55,9 +55,14 @@ export function extract(code, opts) {
|
|
|
55
55
|
return { ok: false, refusals: [{ where: e.where, what: e.what }], notes };
|
|
56
56
|
throw e;
|
|
57
57
|
}
|
|
58
|
+
return fromModel(model, file, opts.domains, notes, (rule, sorts) => check(code, file, model, rule, sorts, { ...opts.check, ...(opts.files ? { files: opts.files } : {}), ...(opts.domains ? { given: opts.domains } : {}) }));
|
|
59
|
+
}
|
|
60
|
+
// A model read by a front end (this file's TypeScript, or core/extract-go.ts's Go) printed as the rule, built, and
|
|
61
|
+
// checked against the code by the front end's own check: what both front ends share.
|
|
62
|
+
export function fromModel(model, file, domains, notes, run) {
|
|
58
63
|
let source, body, sorts;
|
|
59
64
|
try {
|
|
60
|
-
const s = sortsOf(model,
|
|
65
|
+
const s = sortsOf(model, domains);
|
|
61
66
|
sorts = s.sorts;
|
|
62
67
|
datesInRange(model, sorts);
|
|
63
68
|
notes.push(...model.notes, ...s.notes);
|
|
@@ -79,7 +84,7 @@ export function extract(code, opts) {
|
|
|
79
84
|
}
|
|
80
85
|
if (invariants.length)
|
|
81
86
|
source = `${source}\n// What every state of the code is: a law about every state is about the code's with these beside it.\nexport const ${identOf(model)}Invariants = [${invariantsOf(model, sorts).map(x => x.replace(/^r\./, `${identOf(model)}Rule.`)).join(', ')}]\n`;
|
|
82
|
-
const evidence =
|
|
87
|
+
const evidence = run(rule, sorts);
|
|
83
88
|
if (evidence.mismatch)
|
|
84
89
|
return { ok: false, source, model, sorts, evidence, refusals: [{ where: file, what: `the rule and the code differ: ${evidence.mismatch}` }], notes };
|
|
85
90
|
return { ok: true, rule, ...(invariants.length ? { invariants } : {}), source, model, sorts, evidence, refusals: [], notes };
|
|
@@ -126,7 +131,7 @@ function evaluate(body) {
|
|
|
126
131
|
function invariantsOf(m, sorts) {
|
|
127
132
|
const empty = (d, f) => (f.sort.k === 'num' ? `.eq(0)` : f.sort.k === 'bool' ? `.not()` : f.sort.k === 'choice' ? `.is(${JSON.stringify(f.sort.values[0])})` : `.eq('')`);
|
|
128
133
|
void sorts;
|
|
129
|
-
return [...m.maps.map(d => `r.law(${JSON.stringify(`${d.name}: a key it doesn't hold holds the defaults`)}, ({${d.name}}) => forall(k => any(${d.name}.at(k).has, all(${d.fields.map(f => `${d.name}.at(k).${f.name}${empty(d, f)}`).join(', ')}))))`),
|
|
134
|
+
return [...(m.laws ?? []), ...m.maps.map(d => `r.law(${JSON.stringify(`${d.name}: a key it doesn't hold holds the defaults`)}, ({${d.name}}) => forall(k => any(${d.name}.at(k).has, all(${d.fields.map(f => `${d.name}.at(k).${f.name}${empty(d, f)}`).join(', ')}))))`),
|
|
130
135
|
...(m.lists ?? []).map(d => `r.law(${JSON.stringify(`${d.name}: nothing past its end`)}, ({${d.name}}) => ${d.name}.within())`)];
|
|
131
136
|
}
|
|
132
137
|
function evaluateLaws(r, xs) {
|
|
@@ -140,9 +145,9 @@ function moduleOf(m, body, file) {
|
|
|
140
145
|
const used = NAMES.filter(n => new RegExp(`(^|[^.\\w$])${n}\\(|(^|[^.\\w$])${n}\\b(?!\\s*:)`).test(body.replace(/'[^']*'/g, "''")) || (n === 'rule'));
|
|
141
146
|
const ident = identOf(m);
|
|
142
147
|
return [
|
|
143
|
-
`// Extracted by gdp-wired/extract from ${file} (${m.entry}, ${m.factory ? 'a factory of an object of functions' : m.shape === 'class' ? 'a class' : m.shape === 'reducer' ? 'a step function' : 'functions over one record'}).`,
|
|
148
|
+
`// Extracted by gdp-wired/extract from ${file} (${m.entry}, ${m.factory ? 'a factory of an object of functions' : m.shape === 'class' ? (/\.go$/.test(file) ? 'a struct and its methods' : 'a class') : m.shape === 'reducer' ? 'a step function' : 'functions over one record'}).`,
|
|
144
149
|
`// Checked against the code it was read from; read again with extract() after the code changes.`,
|
|
145
|
-
`import {${[...new Set([...used, ...(m.maps.length ? ['all', 'any', 'forall'] : [])])].sort((a, b) => a.localeCompare(b)).join(', ')}} from 'gdp-wired'`,
|
|
150
|
+
`import {${[...new Set([...used, ...(m.maps.length ? ['all', 'any', 'forall'] : []), ...['all', 'any', 'forall'].filter(n => (m.laws ?? []).some(l => l.includes(`${n}(`)))])].sort((a, b) => a.localeCompare(b)).join(', ')}} from 'gdp-wired'`,
|
|
146
151
|
'',
|
|
147
152
|
`export const ${ident}Rule = ${body}`,
|
|
148
153
|
'',
|