gdp-wired 0.27.0 → 0.29.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 +5 -0
- package/dist/core/accel.js +24 -16
- package/dist/core/cycles.d.ts +2 -0
- package/dist/core/cycles.js +31 -4
- package/dist/core/data.d.ts +5 -0
- package/dist/core/data.js +259 -40
- package/dist/core/dsl.d.ts +11 -1
- package/dist/core/dsl.js +205 -21
- package/dist/core/extract-check.js +17 -5
- package/dist/core/extract-read.d.ts +13 -1
- package/dist/core/extract-read.js +47 -7
- package/dist/core/extract-shapes.js +100 -19
- package/dist/core/extract-xstate.js +105 -13
- package/dist/core/extract.js +6 -3
- package/dist/core/fresh.d.ts +9 -0
- package/dist/core/fresh.js +106 -0
- package/dist/core/infer.js +829 -188
- package/dist/core/live.d.ts +15 -0
- package/dist/core/live.js +317 -0
- package/dist/core/machine.d.ts +5 -0
- package/dist/core/machine.js +3 -3
- package/dist/core/nonterm.d.ts +3 -1
- package/dist/core/nonterm.js +76 -18
- package/dist/kernel/cdcl.d.ts +18 -1
- package/dist/kernel/cdcl.js +13 -8
- package/dist/kernel/kernel.d.ts +34 -2
- package/dist/kernel/kernel.js +345 -13
- package/dist/kernel/prove.d.ts +5 -1
- package/dist/kernel/prove.js +200 -63
- package/dist/kernel/reader.d.ts +2 -0
- package/dist/kernel/reader.js +7 -4
- package/dist/lean-kernel/emit.d.ts +27 -3
- package/dist/lean-kernel/emit.js +251 -25
- package/dist/lean-kernel/library.js +3 -2
- package/package.json +3 -2
package/dist/core/dsl.js
CHANGED
|
@@ -15,10 +15,10 @@
|
|
|
15
15
|
//
|
|
16
16
|
// A step returns its updates as one object: every right-hand side reads the state before the step, as the kernel and
|
|
17
17
|
// both runtimes do.
|
|
18
|
-
import { argsKey, carriedView, compileFunction, divName, divisor, divisorsIn, evalC, evalE, interpret, isArithmetic, loadJs, modName, numbersOf, pairedArgs, seeded, withArithmetic } from "./machine.js";
|
|
18
|
+
import { argsKey, machineTerms, carriedView, compileFunction, divName, divisor, divisorsIn, evalC, evalE, interpret, isArithmetic, loadJs, modName, numbersOf, pairedArgs, seeded, withArithmetic } from "./machine.js";
|
|
19
19
|
import { allowed, keysOf, requestEnv, watch } from "./watch.js";
|
|
20
|
-
import { someHolds, substVars } from "./exists.js";
|
|
21
|
-
import { check, checkRecur, foldObligations, loopObligations } from "../kernel/kernel.js";
|
|
20
|
+
import { someHolds, substVars, substVarsE } from "./exists.js";
|
|
21
|
+
import { check, checkRecur, foldObligations, loopObligations, substC, sumMachine } from "../kernel/kernel.js";
|
|
22
22
|
import { certLoop, clock, counted, factsFor, fullRate, grow, proveLaws, proveLiveness, proveStepLaws, usualProof, withDeadline } from "../kernel/prove.js";
|
|
23
23
|
import { certCyclic, certOn, crossCyclic, cyclicOn, foldNodes, proveCyclic, quietly, recurNodes, translatedProof, uncovered } from "./cyclic.js";
|
|
24
24
|
import { discover } from "./discover.js";
|
|
@@ -27,6 +27,8 @@ import { findBoundedRun } from "./bmc.js";
|
|
|
27
27
|
import { conjunction, proveKInduction } from "./kind.js";
|
|
28
28
|
import { cycleLemmas, findLeadsTo, findRank } from "./cycles.js";
|
|
29
29
|
import { findNeverEnds } from "./nonterm.js";
|
|
30
|
+
import { leadsByTerms } from "./live.js";
|
|
31
|
+
import { freshLaws } from "./fresh.js";
|
|
30
32
|
// --- terms and conditions -------------------------------------------------------------------------------------------
|
|
31
33
|
const naturalConst = (v) => {
|
|
32
34
|
if (!Number.isSafeInteger(v) || v < 0)
|
|
@@ -860,6 +862,31 @@ function pulledOut(cs, what, prefix) {
|
|
|
860
862
|
throw new Error(`${what}: ${stray[0]} is bound by an exists(...) whose condition was taken apart; keep it whole (and, or, not, implies)`);
|
|
861
863
|
return { cs: out, vars, bodies: bs.map(b => ({ vars: b.vars.map(n => (prefix === undefined ? n : ren[n].name)), body: r(b.body) })) };
|
|
862
864
|
}
|
|
865
|
+
// --- sums over a map's keys ------------------------------------------------------------------------------------------
|
|
866
|
+
// M.sum() is the sum of M's cells over every key; M.sum(cell => ...) the sum of a term of the cell (a count where a
|
|
867
|
+
// condition holds: when(c, 1, 0); a record map's field where another field says so). It reads as a state variable
|
|
868
|
+
// (sum$M, or sum$M$<id> for a term) that the kernel keeps exact (kernel.ts's sumMachine, Sums.lean): every map the term
|
|
869
|
+
// reads starts where the term is 0, so the sum starts at 0 and each step moves it by the term's change at the keys it
|
|
870
|
+
// writes. The name is the sum's: the same term over the same map is the same variable in every rule.
|
|
871
|
+
const sumDecls = new Map();
|
|
872
|
+
export const declaredSum = (name) => sumDecls.get(name);
|
|
873
|
+
const fnv = (text) => { let h = 0x811c9dc5; for (let i = 0; i < text.length; i++)
|
|
874
|
+
h = Math.imul(h ^ text.charCodeAt(i), 0x01000193) >>> 0; return h.toString(36); };
|
|
875
|
+
function sumOver(map, at, plain) {
|
|
876
|
+
const probe = termOf(at(v('k$sum$'))), id = plain ? `sum$${map}` : `sum$${map}$${fnv(JSON.stringify(probe))}`, key = `${id}$k`;
|
|
877
|
+
const term = substVarsE(probe, { 'k$sum$': { op: 'var', name: key } }), had = sumDecls.get(id);
|
|
878
|
+
if (had && JSON.stringify(had.term) !== JSON.stringify(term))
|
|
879
|
+
throw new Error(`${id}: two sums by one name`);
|
|
880
|
+
sumDecls.set(id, { key, term });
|
|
881
|
+
return v(id);
|
|
882
|
+
}
|
|
883
|
+
// The sums a set of terms reads (by name), declared.
|
|
884
|
+
export const sumsIn = (ts, more = []) => {
|
|
885
|
+
if (!sumDecls.size)
|
|
886
|
+
return undefined;
|
|
887
|
+
const names = new Set([...more, ...[...JSON.stringify(ts).matchAll(/"op":"var","name":"(sum\$[^"]+)"/g)].map(x2 => x2[1])].filter(n => sumDecls.has(n)));
|
|
888
|
+
return names.size ? Object.fromEntries([...names].sort().map(n => [n, sumDecls.get(n)])) : undefined;
|
|
889
|
+
};
|
|
863
890
|
// A map from naturals to naturals, every cell starting at `init`. One write per map per step.
|
|
864
891
|
export class MapRef {
|
|
865
892
|
name;
|
|
@@ -885,6 +912,8 @@ export class MapRef {
|
|
|
885
912
|
// carries), and the set's size, the sum of its cells there (exact, given `within`).
|
|
886
913
|
within(n) { naturalConst(n); return everyKey(k => k.atLeast(n).implies(this.at(k).eq(0))); }
|
|
887
914
|
sizeBelow(n) { naturalConst(n); return sum(0, ...Array.from({ length: n }, (_, key) => this.at(key))); }
|
|
915
|
+
// The sum over every key of the cells, or of a term of the cell (the map starts where it is 0): exact, unbounded.
|
|
916
|
+
sum(of) { return sumOver(this.name, key => (of ? of(this.at(key)) : this.at(key)), !of); }
|
|
888
917
|
}
|
|
889
918
|
export class ListRef {
|
|
890
919
|
name;
|
|
@@ -980,6 +1009,8 @@ export class CellsRef {
|
|
|
980
1009
|
each(f) {
|
|
981
1010
|
return { parts: Object.fromEntries(this.kind.vars(this.name).map(part => [part, this.map(part).each(k => partsOf(this.kind, this.name, f(k))[part])])) };
|
|
982
1011
|
}
|
|
1012
|
+
// The sum over every key of a term of the value there (the start value's term is 0): Refunds.sum(r => when(r.ok, r.amount, 0)).
|
|
1013
|
+
sum(of) { return sumOver(this.name, key => of(this.at(key)), false); }
|
|
983
1014
|
}
|
|
984
1015
|
const fromOf = (d, p) => (typeof d.from === 'number' ? d.from : d.from(p));
|
|
985
1016
|
// The keys a condition reads any of these maps at, as terms.
|
|
@@ -1667,6 +1698,28 @@ export class Rule {
|
|
|
1667
1698
|
}
|
|
1668
1699
|
return this.with({ fns: (this.spec.fns ?? []).map(([n, d]) => [n, fns[n] ?? d]), lists2: lists });
|
|
1669
1700
|
}
|
|
1701
|
+
// The same rule with the sum of every map its step writes (each a map of the state starting at 0 everywhere, whose sum
|
|
1702
|
+
// the kernel keeps exact: kernel.ts's sumMachine), beside the sums it reads: what the search proposes laws over where
|
|
1703
|
+
// a law is about the cells of a map against a total (a balance at most the supply). Undefined where there is none.
|
|
1704
|
+
withMapSums() {
|
|
1705
|
+
const m = this.machine;
|
|
1706
|
+
if (m.history)
|
|
1707
|
+
return undefined;
|
|
1708
|
+
const have = new Set(Object.keys(m.sums ?? {})), more = new Set(this.spec.sumsRead ?? []);
|
|
1709
|
+
for (const [map, init] of Object.entries(m.maps ?? {})) {
|
|
1710
|
+
if (init !== 0 || !m.step.maps?.[map] || (m.inputMaps ?? []).includes(map))
|
|
1711
|
+
continue;
|
|
1712
|
+
const name = new MapRef(map, 0).sum().e.name;
|
|
1713
|
+
if (have.has(name))
|
|
1714
|
+
continue;
|
|
1715
|
+
try {
|
|
1716
|
+
sumMachine({ ...m, sums: { ...m.sums, ...sumsIn([], [name]) } });
|
|
1717
|
+
more.add(name);
|
|
1718
|
+
}
|
|
1719
|
+
catch { /* a sum the kernel takes no cover of */ }
|
|
1720
|
+
}
|
|
1721
|
+
return more.size > (this.spec.sumsRead?.size ?? 0) ? this.with({ sumsRead: more }) : undefined;
|
|
1722
|
+
}
|
|
1670
1723
|
params(kinds) { return this.with({ params: [...this.spec.params, ...Object.entries(kinds)] }); }
|
|
1671
1724
|
inputs(kinds) { return this.with({ inputs: [...this.spec.inputs, ...Object.entries(kinds)] }); }
|
|
1672
1725
|
// Each variable starts at a natural or at a term over the params, or is declared by a kind and starts where `from`
|
|
@@ -1844,8 +1897,13 @@ export class Rule {
|
|
|
1844
1897
|
return { ...law, some: vars, ...(Object.keys(witness).length ? { witness } : {}) };
|
|
1845
1898
|
}
|
|
1846
1899
|
// What a law, a step law or a decision divides by, noted so the machine declares it (Spec.arith).
|
|
1847
|
-
divides(x) {
|
|
1848
|
-
|
|
1900
|
+
divides(x) {
|
|
1901
|
+
if (this.spec.arith)
|
|
1902
|
+
divisorsIn([x], this.spec.arith);
|
|
1903
|
+
for (const n of Object.keys(sumsIn([x]) ?? {}))
|
|
1904
|
+
(this.spec.sumsRead ??= new Set()).add(n);
|
|
1905
|
+
return x;
|
|
1906
|
+
}
|
|
1849
1907
|
// Divide by these too (inferLaws' candidates): the machine declares div$k and mod$k for each.
|
|
1850
1908
|
dividesBy(...ks) { for (const k of ks)
|
|
1851
1909
|
(this.spec.arith ??= new Set()).add(divisor(k, 'dividesBy')); return this; }
|
|
@@ -1855,7 +1913,11 @@ export class Rule {
|
|
|
1855
1913
|
// a case in range, a presence bit 0 or 1), as laws: proveRule, proveSteps and proveLeadsTo prove them beside the laws
|
|
1856
1914
|
// they are given, so a law may lean on "the hold is idle, holding or released" without stating it; give them to
|
|
1857
1915
|
// toLean (or the kernel) with the rest.
|
|
1858
|
-
|
|
1916
|
+
// (the same laws each time, their keys' names too: a goal built from them again is the same goal, whose tree
|
|
1917
|
+
// kernel/prove.ts's withTrees keeps)
|
|
1918
|
+
kinds;
|
|
1919
|
+
kindLaws() { return [...(this.kinds ??= this.kindLawsOf())]; }
|
|
1920
|
+
kindLawsOf() {
|
|
1859
1921
|
const out = [];
|
|
1860
1922
|
const of = (env, n) => env[n];
|
|
1861
1923
|
for (const [n, k] of this.spec.kinded ?? [])
|
|
@@ -1925,11 +1987,15 @@ export class Rule {
|
|
|
1925
1987
|
// batches.leadsTo('every batch is done', {from: () => yes, to: ({waiting, items}) => waiting.eq(0).and(items.eq(0)),
|
|
1926
1988
|
// rank: ({waiting, items}) => [waiting, items], helpful: [{when: ({items}) => items.gt(0), request: () => ({op: 1})}, {when: ({items}) => items.eq(0), request: () => ({op: 0})}]})
|
|
1927
1989
|
// With no rank, proveLeadsTo finds one from the rule's runs (core/cycles.ts's findLeadsTo).
|
|
1990
|
+
// `fairness: 'strong'`: each helpful request taken in its region infinitely often wherever it is allowed there
|
|
1991
|
+
// infinitely often (an event that keeps coming back is taken). Its regions need not stay; a helpful request may move to
|
|
1992
|
+
// the region of one of a higher `levels` (found where left out) instead of reaching `to` or lowering the rank:
|
|
1993
|
+
// job.leadsTo('every job ends', {..., fairness: 'strong', helpful: [{when: waiting, request: fetch}, {when: active, request: fail}]})
|
|
1928
1994
|
leadsTo(name, spec) {
|
|
1929
1995
|
const env = this.env({ flags: false, inputs: false, queries: false });
|
|
1930
1996
|
const req = (f) => Object.fromEntries(Object.entries(f(env)).map(([n, t]) => [n, termOf(t)]));
|
|
1931
1997
|
const r = spec.rank ? spec.rank(env) : [], rank = Array.isArray(r) ? r.map(termOf) : termOf(r);
|
|
1932
|
-
const base = { name, from: spec.from(env).c, to: spec.to(env).c, rank };
|
|
1998
|
+
const base = { name, from: spec.from(env).c, to: spec.to(env).c, rank, ...(spec.fairness === 'strong' ? { fairness: 'strong' } : {}), ...(spec.levels ? { levels: spec.levels } : {}) };
|
|
1933
1999
|
return this.divides(typeof spec.helpful === 'function' ? { ...base, request: req(spec.helpful) } : { ...base, helpful: spec.helpful.map(h => ({ ...(h.when ? { when: h.when(env).c } : {}), request: req(h.request) })) });
|
|
1934
2000
|
}
|
|
1935
2001
|
// A decision: whenever the params and the request meet `given`, `then` holds. Decisions don't read the state; the
|
|
@@ -2190,7 +2256,9 @@ export class Rule {
|
|
|
2190
2256
|
...(s.prune ? { prune: { order: pruneOrder[0], after: termOf(s.prune.after(pEnv)) } } : {}),
|
|
2191
2257
|
};
|
|
2192
2258
|
}
|
|
2193
|
-
|
|
2259
|
+
// (each sum a state variable from 0 the step never sets: sumMachine sets it, exact)
|
|
2260
|
+
const sums = sumsIn(machineTerms(m), s.sumsRead ?? []);
|
|
2261
|
+
return withArithmetic(sums ? { ...m, state: { ...m.state, ...Object.fromEntries(Object.keys(sums).map(n => [n, { op: 'const', value: 0 }])) }, sums } : m, [], s.arith ?? []);
|
|
2194
2262
|
}
|
|
2195
2263
|
// --- the builders checked ------------------------------------------------------------------------------------------
|
|
2196
2264
|
// The builders against what they built, on concrete runs: random params and requests by their kinds (`pre` and
|
|
@@ -2493,7 +2561,7 @@ const expandParts = (updates) => {
|
|
|
2493
2561
|
return updates;
|
|
2494
2562
|
};
|
|
2495
2563
|
const encode = (kinds, values) => Object.assign({}, ...kinds.map(([n, k]) => k.encode(n, values[n])));
|
|
2496
|
-
export const rule = (name) => new Rule({ name, params: [], inputs: [], state: [], maps: [], flags: [], pre: [], assume: [], sums: [], queries: [], arith: new Set() });
|
|
2564
|
+
export const rule = (name) => new Rule({ name, params: [], inputs: [], state: [], maps: [], flags: [], pre: [], assume: [], sums: [], queries: [], arith: new Set(), sumsRead: new Set() });
|
|
2497
2565
|
const quantifiedE = (e) => e.op === 'if' ? quantifiedIn(e.c) || quantifiedE(e.then) || quantifiedE(e.else) : 'a' in e && typeof e.a === 'object' ? quantifiedE(e.a) || ('b' in e && typeof e.b === 'object' && quantifiedE(e.b)) : false;
|
|
2498
2566
|
const quantifiedIn = (c) => c.op === 'all' || (c.op === 'not' ? quantifiedIn(c.x) : c.op === 'and' || c.op === 'or' ? c.xs.some(quantifiedIn) : c.op === 'flag' ? false : quantifiedE(c.a) || quantifiedE(c.b));
|
|
2499
2567
|
// The kind a result field is kept in.
|
|
@@ -2660,9 +2728,27 @@ const refuteBudget = { trials: 60, depth: 6, bound: 3 };
|
|
|
2660
2728
|
const shownRequest = (input) => Object.fromEntries(Object.entries(input).map(([n, x]) => [n, typeof x === 'number' ? x : Object.fromEntries(x)]));
|
|
2661
2729
|
// The search's own runs, before it looks for what the laws need: deeper and wider, from another seed.
|
|
2662
2730
|
const deeperBudget = { trials: 600, depth: 24, bound: 8, seed: 29 };
|
|
2731
|
+
const conjuncts = (c) => (!c ? [] : c.op === 'and' ? c.xs.flatMap(conjuncts) : [c]);
|
|
2732
|
+
function guidesOf(m) {
|
|
2733
|
+
const isInput = (e) => e.op === 'var' && m.inputs.includes(e.name);
|
|
2734
|
+
const free = (e) => !namesIn(e).some(n => m.inputs.includes(n));
|
|
2735
|
+
return conjuncts(m.assume).flatMap(c => {
|
|
2736
|
+
if (c.op !== '=' && c.op !== '<=' && c.op !== '<')
|
|
2737
|
+
return [];
|
|
2738
|
+
const [x, t, up] = isInput(c.a) && free(c.b) && c.op === '=' ? [c.a, c.b, false] : isInput(c.b) && free(c.a) ? [c.b, c.a, c.op !== '='] : [undefined, undefined, false];
|
|
2739
|
+
if (!x || !t)
|
|
2740
|
+
return [];
|
|
2741
|
+
return [(env, st, rand, bound) => { try {
|
|
2742
|
+
return [x.name, evalE(t, env, st, m) + (up ? (c.op === '<' ? 1 : 0) + rand(bound + 1) : 0)];
|
|
2743
|
+
}
|
|
2744
|
+
catch {
|
|
2745
|
+
return undefined;
|
|
2746
|
+
} }];
|
|
2747
|
+
});
|
|
2748
|
+
}
|
|
2663
2749
|
function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget) {
|
|
2664
2750
|
const m = r.machine;
|
|
2665
|
-
const run = interpret(m), rand = seeded(budget.seed ?? 13), bound = budget.bound, shown = shownRequest;
|
|
2751
|
+
const run = interpret(m), rand = seeded(budget.seed ?? 13), bound = budget.bound, shown = shownRequest, guides = budget.mixed ? guidesOf(m) : [];
|
|
2666
2752
|
// (Division by a constant is a function too, its facts Euclid's, which its JavaScript meets: not checked.)
|
|
2667
2753
|
const facts = (m.facts ?? []).filter(f => !isArithmetic(f.name.slice(0, f.name.indexOf(':'))));
|
|
2668
2754
|
const holds = (f, params) => {
|
|
@@ -2683,7 +2769,13 @@ function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget) {
|
|
|
2683
2769
|
&& facts.filter(readsParams).every(f => holds(f, params));
|
|
2684
2770
|
try {
|
|
2685
2771
|
for (let trial = 0; trial < budget.trials; trial++) {
|
|
2772
|
+
// (`mixed`: the trials in turn at bounds 1 to 4, every fourth near)
|
|
2773
|
+
const bound = budget.mixed ? 1 + trial % 4 : budget.bound, guided = guides, near = budget.mixed && trial % 4 ? undefined : budget.near;
|
|
2686
2774
|
const params = r.randomParams(rand, bound);
|
|
2775
|
+
if (near)
|
|
2776
|
+
for (const p of m.params)
|
|
2777
|
+
if (near[p] !== undefined && rand(2))
|
|
2778
|
+
params[p] = near[p];
|
|
2687
2779
|
if (m.pre && !evalC(m.pre, params, { scalars: {}, maps: {} }, m) || !factsHold(params))
|
|
2688
2780
|
continue;
|
|
2689
2781
|
const watching = [...laws, ...stepLaws].map(w => ({ w, on: watch(m, run, w, params, bound) }));
|
|
@@ -2696,6 +2788,15 @@ function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget) {
|
|
|
2696
2788
|
return broken(w, '@start', st);
|
|
2697
2789
|
for (let d = 0, tries = 0; d < budget.depth && tries < 40; tries++) {
|
|
2698
2790
|
const input = r.randomInput(rand, bound, params);
|
|
2791
|
+
if (near)
|
|
2792
|
+
for (const x of m.inputs)
|
|
2793
|
+
if (near[x] !== undefined && typeof input[x] === 'number' && rand(2))
|
|
2794
|
+
input[x] = near[x];
|
|
2795
|
+
for (const g of guided) {
|
|
2796
|
+
const set = g({ ...params, ...st.scalars }, st, rand, bound);
|
|
2797
|
+
if (set && typeof input[set[0]] === 'number')
|
|
2798
|
+
input[set[0]] = set[1];
|
|
2799
|
+
}
|
|
2699
2800
|
if (!allowed(m, run, params, st, input))
|
|
2700
2801
|
continue;
|
|
2701
2802
|
d++;
|
|
@@ -2714,7 +2815,7 @@ function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget) {
|
|
|
2714
2815
|
// variable of a kind is drawn as its kind draws (33 yes/nos drawn from 0..7 almost never make a lawful state).
|
|
2715
2816
|
const steps1 = stepLaws.filter(sl => (sl.steps ?? 1) === 1), given = withKinds(r, laws);
|
|
2716
2817
|
const wide = Object.keys(m.state).length + m.inputs.length >= 32, lawsHere = wide ? given : [], kinded = wide ? r.kindsOfState() : [];
|
|
2717
|
-
for (let trial = 0; !m.history && (steps1.length || lawsHere.length) && trial < budget.trials * 4; trial++) {
|
|
2818
|
+
for (let trial = 0; budget.states !== false && !m.history && (steps1.length || lawsHere.length) && trial < budget.trials * 4; trial++) {
|
|
2718
2819
|
const params = r.randomParams(rand, bound);
|
|
2719
2820
|
if (m.pre && !evalC(m.pre, params, { scalars: {}, maps: {} }, m) || !factsHold(params))
|
|
2720
2821
|
continue;
|
|
@@ -2763,21 +2864,52 @@ export function proveRule(r, laws, opts = {}) {
|
|
|
2763
2864
|
export function proveSteps(r, laws, stepLaws, opts = {}) {
|
|
2764
2865
|
noting(r, laws, stepLaws);
|
|
2765
2866
|
const refuted = refuteByRuns(r, laws, stepLaws);
|
|
2867
|
+
// (a step law broken from a state the laws allow, with no run to it: the laws may need an invariant there, or the run
|
|
2868
|
+
// be further than these runs go; the search goes on from it, as from the kernel's)
|
|
2766
2869
|
if (refuted)
|
|
2767
|
-
return refutedVerdict(refuted);
|
|
2870
|
+
return refuted.run ? refutedVerdict(refuted) : searched(r, laws, stepLaws, refutedVerdict(refuted), opts);
|
|
2768
2871
|
const out = proveStepLaws(r.machine, withKinds(r, laws), stepLaws);
|
|
2769
2872
|
const v = verdictOf(out);
|
|
2770
2873
|
return searched(r, laws, stepLaws, v, opts);
|
|
2771
2874
|
}
|
|
2875
|
+
// The one-step laws as laws the bounded runs read (core/bmc.ts takes laws alone): a ghost per step law, set once a step
|
|
2876
|
+
// it is about breaks it (`then` read with each primed name the step's update), and the law that it is never set. Only a
|
|
2877
|
+
// machine bmc takes (no maps, no history) and a step law over no key; the ghost changes no run of the machine.
|
|
2878
|
+
function stepGhosts(m, stepLaws) {
|
|
2879
|
+
const plain = stepLaws.filter(sl => (sl.steps ?? 1) === 1 && !sl.forall && !sl.keys?.length);
|
|
2880
|
+
if (!plain.length || Object.keys(m.maps ?? {}).length || m.history || m.inputMaps?.length)
|
|
2881
|
+
return undefined;
|
|
2882
|
+
const flags = Object.fromEntries(Object.keys(m.step.flags ?? {}).map(f => [f, { op: 'flag', name: f }]));
|
|
2883
|
+
const after = { vars: Object.fromEntries(Object.keys(m.state).map(n => [`${n}'`, m.step.state?.[n] ?? { op: 'var', name: n }])), maps: {}, flags };
|
|
2884
|
+
const ghosts = {}, out = [];
|
|
2885
|
+
for (const [i, sl] of plain.entries()) {
|
|
2886
|
+
const name = `broken$${i}`, whens = sl.when === undefined ? [] : Array.isArray(sl.when) ? sl.when : [sl.when];
|
|
2887
|
+
if (name in m.state)
|
|
2888
|
+
return undefined;
|
|
2889
|
+
ghosts[name] = { op: 'if', c: { op: 'and', xs: [...whens, { op: 'not', x: substC(sl.then, after) }] }, then: { op: 'const', value: 1 }, else: { op: 'var', name } };
|
|
2890
|
+
out.push({ name: sl.name, holds: { op: '<=', a: { op: 'var', name }, b: { op: 'const', value: 0 } } });
|
|
2891
|
+
}
|
|
2892
|
+
// (as core/compose.ts's `ghost`: each starts at 0, nothing of the machine reads it)
|
|
2893
|
+
try {
|
|
2894
|
+
return { machine: { ...m, state: { ...m.state, ...Object.fromEntries(Object.keys(ghosts).map(n => [n, { op: 'const', value: 0 }])) }, step: { ...m.step, state: { ...m.step.state, ...ghosts } } }, laws: out };
|
|
2895
|
+
}
|
|
2896
|
+
catch {
|
|
2897
|
+
return undefined;
|
|
2898
|
+
}
|
|
2899
|
+
}
|
|
2772
2900
|
// The search, where the prover alone didn't prove the laws and nothing refuted them: the lemmas first where the rule has
|
|
2773
2901
|
// recurrences or carried lists (the rule made again with them), then invariants over what it then is. The verdict is the
|
|
2774
2902
|
// prover's on the laws with what was found; when nothing is found, the prover's own (with why).
|
|
2775
2903
|
function searched(r, laws, stepLaws, v, opts) {
|
|
2776
2904
|
if ((v.proven && v.checked) || opts.search === false || v.run || v.stuck === 'sat' && !/@step|@\d+ steps/.test(v.goal ?? ''))
|
|
2777
2905
|
return v;
|
|
2778
|
-
|
|
2779
|
-
|
|
2780
|
-
|
|
2906
|
+
// The deeper runs; then runs over small values (keys that meet, small params), whose requests meet their
|
|
2907
|
+
// assumption's equalities and clocks, or near the counterexample the verdict ends at.
|
|
2908
|
+
for (const b of [deeperBudget, { ...deeperBudget, bound: 1, seed: 31, states: false }, { ...deeperBudget, trials: 1200, seed: 41, states: false, mixed: true, ...(v.witness ? { near: v.witness } : {}) }]) {
|
|
2909
|
+
const deeper = refuteByRuns(r, laws, stepLaws, b);
|
|
2910
|
+
if (deeper?.run)
|
|
2911
|
+
return refutedVerdict(deeper);
|
|
2912
|
+
}
|
|
2781
2913
|
const until = clock() + (typeof opts.search === 'object' && opts.search.ms !== undefined ? opts.search.ms : 10_000);
|
|
2782
2914
|
// Bounded runs (core/bmc.ts): a law broken k steps from the start, a model of the kernel's k-step goal, the run taken
|
|
2783
2915
|
// by the interpreter. The shallow depths first, within a fortieth of the search's budget (at most 250 ms, counted in
|
|
@@ -2786,7 +2918,10 @@ function searched(r, laws, stepLaws, v, opts) {
|
|
|
2786
2918
|
// shallow depths.
|
|
2787
2919
|
const total = until - clock(), tail = Math.min(1000, total / 10);
|
|
2788
2920
|
let reached = 0;
|
|
2789
|
-
const
|
|
2921
|
+
const ghosted = stepGhosts(r.machine, stepLaws);
|
|
2922
|
+
// (with the step laws' ghosts, a wall stop too, at the budget: their goals cost the cost model more than its clock
|
|
2923
|
+
// counts, a wide rule's past twice its wall time)
|
|
2924
|
+
const bounded = (ms, from) => counted(fullRate, () => findBoundedRun(ghosted?.machine ?? r.machine, [...laws, ...(ghosted?.laws ?? [])], { ms, from, steps: true, ...(ghosted ? { wall: performance.now() + ms } : {}), progress: k => { reached = k; } }), true);
|
|
2790
2925
|
const refutedBy = (b) => refutedVerdict({ goal: `${b.law} @step (a run of ${b.depth} steps from the start)`, witness: b.witness, run: { params: b.params, trace: b.trace.map(shownRequest) } });
|
|
2791
2926
|
const shallow = bounded(Math.min(250, total / 40), 1);
|
|
2792
2927
|
if (shallow)
|
|
@@ -2815,28 +2950,77 @@ function searched(r, laws, stepLaws, v, opts) {
|
|
|
2815
2950
|
if (c.proven && c.checked)
|
|
2816
2951
|
return { proven: true, checked: true, found: { ...(lemmas ? { lemmas } : {}), facts: c.found.map(f => f.text) } };
|
|
2817
2952
|
}
|
|
2953
|
+
// Laws about the ids a counter hands out (core/fresh.ts), within a tenth of what is left: the laws with them, then
|
|
2954
|
+
// the invariant search with them given.
|
|
2955
|
+
let fresh = [];
|
|
2956
|
+
if (Object.keys(rule.machine.maps ?? {}).length && until - clock() - tail > 1000) {
|
|
2957
|
+
const fm = rule.machine, share = (until - clock() - tail) / 10;
|
|
2958
|
+
fresh = withDeadline(clock() + share, () => freshLaws(fm, rule.kindLaws(), { params: (rand, bound) => rule.randomParams(rand, bound), input: (rand, bound, ps) => rule.randomInput(rand, bound, ps) }, { ms: share }));
|
|
2959
|
+
if (fresh.length) {
|
|
2960
|
+
const given = [...withKinds(rule, laws), ...fresh.map(f => f.law)], out = withDeadline(clock() + share, () => (stepLaws.length ? proveStepLaws(fm, given, stepLaws) : proveLaws(fm, given)));
|
|
2961
|
+
if (out.proven && out.checked)
|
|
2962
|
+
return { proven: true, checked: true, found: { laws: fresh, ...(lemmas ? { lemmas } : {}) } };
|
|
2963
|
+
}
|
|
2964
|
+
}
|
|
2818
2965
|
const ms = until - clock() - tail;
|
|
2819
2966
|
if (ms < 500)
|
|
2820
2967
|
return v;
|
|
2821
|
-
const inf = inferLaws(rule, laws, stepLaws, { ms, ...(rule === r ? { first: v } : {}) });
|
|
2968
|
+
const inf = inferLaws(rule, [...fresh.map(f => f.law), ...laws], stepLaws, { ms, ...(rule === r && !fresh.length ? { first: v } : {}) });
|
|
2822
2969
|
if (!(inf.proven && inf.checked)) {
|
|
2823
|
-
|
|
2970
|
+
// The sum of each map the step writes (withMapSums): the search again over the rule with them, within half of what
|
|
2971
|
+
// is left (at most 20 s), where a law of cells against a total needs one (no ERC20 balance past the supply).
|
|
2972
|
+
const summed = rule.withMapSums();
|
|
2973
|
+
if (summed && until - clock() - tail > 1000) {
|
|
2974
|
+
const inf2 = inferLaws(summed, [...fresh.map(f => f.law), ...laws], stepLaws, { ms: Math.min(20_000, (until - clock() - tail) / 2) });
|
|
2975
|
+
if (inf2.proven && inf2.checked) {
|
|
2976
|
+
const { found, stats: _s2, ...verdict } = inf2;
|
|
2977
|
+
void _s2;
|
|
2978
|
+
return { ...verdict, found: { laws: [...fresh, ...found], ...(lemmas ? { lemmas } : {}) } };
|
|
2979
|
+
}
|
|
2980
|
+
}
|
|
2981
|
+
// (a step law's ghost: at most 10 s of it, as its goals cost more than the laws')
|
|
2982
|
+
const deep = bounded(Math.max(0, Math.min(until - clock(), ghosted && !laws.length ? 10_000 : Infinity)), Math.max(1, reached));
|
|
2824
2983
|
if (deep)
|
|
2825
2984
|
return refutedBy(deep);
|
|
2826
2985
|
return { ...v, why: [v.why, `the search found nothing that proves it in ${Math.round(inf.stats.ms)} ms`].filter(Boolean).join('; ') };
|
|
2827
2986
|
}
|
|
2828
2987
|
const { found, stats: _stats, ...verdict } = inf;
|
|
2829
2988
|
void _stats;
|
|
2830
|
-
return { ...verdict, found: { laws: found, ...(lemmas ? { lemmas } : {}) } };
|
|
2989
|
+
return { ...verdict, found: { laws: [...fresh, ...found], ...(lemmas ? { lemmas } : {}) } };
|
|
2831
2990
|
}
|
|
2832
2991
|
export function proveLeadsTo(r, laws, l, opts = {}) {
|
|
2833
2992
|
noting(r, laws, l);
|
|
2834
2993
|
if (laws.some(law => law.some?.length))
|
|
2835
2994
|
throw new Error(`${r.machine.name}: a law with "there exists" goes to proveRule or proveSteps; a liveness takes plain laws (the ones its proof printed, Verdict.witnesses)`);
|
|
2836
2995
|
if (Array.isArray(l.rank) && !l.rank.length) {
|
|
2837
|
-
const
|
|
2996
|
+
const until = clock() + (opts.ms ?? 10_000), draws = { params: (rand, bound) => r.randomParams(rand, bound), input: (rand, bound, ps) => r.randomInput(rand, bound, ps) };
|
|
2997
|
+
// (the laws about the keys a counter hands out or a high-water mark bounds, core/fresh.ts, within a twentieth: given
|
|
2998
|
+
// to both searches, each proven again with the rank)
|
|
2999
|
+
const share = (until - clock()) / 20, fresh = Object.keys(r.machine.maps ?? {}).length ? withDeadline(clock() + share, () => freshLaws(r.machine, r.kindLaws(), draws, { ms: share })) : [];
|
|
3000
|
+
laws = [...laws, ...fresh.map(x => x.law)];
|
|
3001
|
+
let f = findLeadsTo(r.machine, withKinds(r, laws), l, { ...draws, rule: r }, { ms: until - clock() });
|
|
3002
|
+
// Where the rank fitted to the runs isn't the one: a rank of the rule's own terms (core/live.ts), in the time left.
|
|
3003
|
+
if (!(f.proven && f.checked) && until - clock() > 500) {
|
|
3004
|
+
const g = leadsByTerms(r.machine, withKinds(r, laws), l, { ...draws, rule: r, state: (rand, bound) => Object.assign({}, ...r.kindsOfState().map(([n, kd]) => kd.random(n, rand, bound))) }, { ms: until - clock() });
|
|
3005
|
+
if (g.proven && g.checked)
|
|
3006
|
+
f = g;
|
|
3007
|
+
}
|
|
3008
|
+
// The sum of each map the step writes (withMapSums), where neither found a rank: both again over the rule with them,
|
|
3009
|
+
// in the time left (a refund that needs the escrow's balance to cover every deposit).
|
|
3010
|
+
const summed = !(f.proven && f.checked) && until - clock() > 1000 ? r.withMapSums() : undefined;
|
|
3011
|
+
if (summed) {
|
|
3012
|
+
const sd = { params: (rand, bound) => summed.randomParams(rand, bound), input: (rand, bound, ps) => summed.randomInput(rand, bound, ps) };
|
|
3013
|
+
const f2 = findLeadsTo(summed.machine, withKinds(summed, laws), l, { ...sd, rule: summed }, { ms: until - clock() });
|
|
3014
|
+
if (f2.proven && f2.checked)
|
|
3015
|
+
f = f2;
|
|
3016
|
+
else if (until - clock() > 500) {
|
|
3017
|
+
const g2 = leadsByTerms(summed.machine, withKinds(summed, laws), l, { ...sd, rule: summed, state: (rand, bound) => Object.assign({}, ...summed.kindsOfState().map(([n, kd]) => kd.random(n, rand, bound))) }, { ms: until - clock() });
|
|
3018
|
+
if (g2.proven && g2.checked)
|
|
3019
|
+
f = g2;
|
|
3020
|
+
}
|
|
3021
|
+
}
|
|
2838
3022
|
return { proven: f.proven, checked: f.checked, ...(f.goal ? { goal: f.goal, stuck: f.stuck } : {}), ...(f.witness ? { witness: f.witness } : {}), ...(f.why ? { why: f.why } : {}),
|
|
2839
|
-
...(f.found ? { found: { rank: f.found.rank, ...(f.laws?.length ? { laws: f.laws.map((law, i) => ({ law, text: f.found.laws[i] ?? law.name })) } : {}) } } : {}) };
|
|
3023
|
+
...(f.found ? { found: { rank: f.found.rank, ...(f.laws?.length || fresh.length ? { laws: [...fresh, ...(f.laws ?? []).map((law, i) => ({ law, text: f.found.laws[i] ?? law.name }))] } : {}) } } : {}) };
|
|
2840
3024
|
}
|
|
2841
3025
|
const out = proveLiveness(r.machine, withKinds(r, laws), l);
|
|
2842
3026
|
return verdictOf(out);
|
|
@@ -160,7 +160,8 @@ function snapOf(v, layout, m, consts, out = { leaves: {}, maps: {} }, path = 'st
|
|
|
160
160
|
case 'rec': {
|
|
161
161
|
if (typeof v !== 'object' || v === null)
|
|
162
162
|
throw new Error(`${path} is ${JSON.stringify(v)}, not an object`);
|
|
163
|
-
|
|
163
|
+
// (a class's fields holding a function are no state: the object's own, left out where they hold one)
|
|
164
|
+
const own = Object.keys(v).filter(k => !(path === 'state' && m.fnFields?.includes(k) && typeof v[k] === 'function')), want = layout.fields.map(([f]) => f).filter(f => !f.endsWith('()'));
|
|
164
165
|
for (const k of own)
|
|
165
166
|
if (!want.includes(k))
|
|
166
167
|
throw new Error(`${path} has a field ${k} the rule doesn't`);
|
|
@@ -376,18 +377,28 @@ export function check(code, file, m, r, sorts, opts = {}) {
|
|
|
376
377
|
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
378
|
if (m.factory)
|
|
378
379
|
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
|
-
|
|
380
|
+
// A class's fields holding a function: each answers the request's input (set on the object before each call; a
|
|
381
|
+
// function given to the constructor is one such too).
|
|
382
|
+
let answers = {};
|
|
383
|
+
const answering = (f) => () => { const n = Object.keys(m.answers ?? {}).find(k => m.answers[k] === f); return n === undefined ? undefined : answers[n]; };
|
|
384
|
+
const fnArg = () => () => { throw new Error('a function given to the constructor called while the object is made'); };
|
|
385
|
+
const ctorValue = (n, params) => (n === '$fn' ? fnArg() : n.startsWith('$map:') ? vmOf().runInContext(n === '$map:Map' ? 'new Map()' : '({})', box.ctx) : params[n]);
|
|
386
|
+
const ctorValues = (params) => (m.ctorArgs ?? []).filter(n => !m.params.find(v => v.name === n)?.note?.startsWith('Date.now()')).map(n => ctorValue(n, params));
|
|
380
387
|
const side = {
|
|
381
388
|
make: params => {
|
|
382
389
|
const now0 = m.params.find(v => v.note?.startsWith('Date.now()'));
|
|
383
390
|
if (now0)
|
|
384
391
|
box.setNow(params[now0.name]);
|
|
385
392
|
// 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
|
|
393
|
+
return box.call('$new', undefined, (m.ctorArgs ?? []).filter(n => n !== now0?.name).map(n => ctorValue(n, params)));
|
|
387
394
|
},
|
|
388
395
|
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
396
|
snapOf: (self, params) => snapOf(stateOf(self), m.layout, m, evalAt(params)),
|
|
390
|
-
call: (self, e, args) =>
|
|
397
|
+
call: (self, e, args) => {
|
|
398
|
+
for (const f of new Set(Object.values(m.answers ?? {})))
|
|
399
|
+
self[f] = answering(f);
|
|
400
|
+
return box.call('$method', self, [e.call, args]);
|
|
401
|
+
},
|
|
391
402
|
reduce: (snap, e, args, params) => {
|
|
392
403
|
const input = valueOf(snap, m.layout, m, evalAt(params), box.ctx), before = JSON.stringify(input, mapReplacer);
|
|
393
404
|
const res = box.call(e.call, undefined, [input, ...args.slice(1)]);
|
|
@@ -396,6 +407,7 @@ export function check(code, file, m, r, sorts, opts = {}) {
|
|
|
396
407
|
return res.ok ? { snap: snapOf(res.value, m.layout, m, evalAt(params)) } : { refused: res.error };
|
|
397
408
|
},
|
|
398
409
|
args: (inputs, e) => {
|
|
410
|
+
answers = inputs;
|
|
399
411
|
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
412
|
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
413
|
? 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]]))
|
|
@@ -473,7 +485,7 @@ export function drive(m, r, sorts, code, opts = {}) {
|
|
|
473
485
|
used.add(v.name); };
|
|
474
486
|
e.args.forEach(walk);
|
|
475
487
|
for (const v of m.inputs)
|
|
476
|
-
if (v.note?.startsWith('Date.now()'))
|
|
488
|
+
if (v.note?.startsWith('Date.now()') || m.answers?.[v.name])
|
|
477
489
|
used.add(v.name);
|
|
478
490
|
// An input the event doesn't bring: its kind's first value (the rule reads it only under another event).
|
|
479
491
|
return Object.fromEntries(m.inputs.map(v => [v.name, v.name in e.select ? e.select[v.name] : used.has(v.name) ? inputs[v.name] : v.sort.k === 'num' ? 0 : v.sort.k === 'bool' ? false : v.sort.k === 'choice' ? v.sort.values[0] : '']));
|
|
@@ -173,6 +173,8 @@ export type Model = {
|
|
|
173
173
|
null: boolean;
|
|
174
174
|
}>;
|
|
175
175
|
laws?: string[];
|
|
176
|
+
answers?: Record<string, string>;
|
|
177
|
+
fnFields?: string[];
|
|
176
178
|
};
|
|
177
179
|
type V = {
|
|
178
180
|
t: 'num';
|
|
@@ -253,12 +255,14 @@ type Path = {
|
|
|
253
255
|
heap: Heap;
|
|
254
256
|
wrote: string[];
|
|
255
257
|
nows: number;
|
|
258
|
+
outs?: string[];
|
|
256
259
|
};
|
|
257
260
|
type Flow = {
|
|
258
261
|
live?: Path;
|
|
259
262
|
rets: [Path, V][];
|
|
260
263
|
breaks: Path[];
|
|
261
264
|
};
|
|
265
|
+
export declare const unparen: (x: ts.Expression) => ts.Expression;
|
|
262
266
|
export declare const normalize: (path: string) => string;
|
|
263
267
|
export declare const resolveIn: (files: Record<string, string>, from: string, spec: string) => string | undefined;
|
|
264
268
|
export declare function program(code: string, file: string, extra?: Record<string, string>): {
|
|
@@ -266,7 +270,7 @@ export declare function program(code: string, file: string, extra?: Record<strin
|
|
|
266
270
|
checker: ts.TypeChecker;
|
|
267
271
|
};
|
|
268
272
|
export declare const scriptKind: (file: string) => ts.ScriptKind;
|
|
269
|
-
export declare function shapeOf(t: ts.Type, checker: ts.TypeChecker, at: ts.Node): Shape;
|
|
273
|
+
export declare function shapeOf(t: ts.Type, checker: ts.TypeChecker, at: ts.Node, inner?: string): Shape;
|
|
270
274
|
type Callable = {
|
|
271
275
|
decl: ts.FunctionLikeDeclaration;
|
|
272
276
|
self?: string;
|
|
@@ -299,6 +303,13 @@ export type Setup = {
|
|
|
299
303
|
sort: Sort;
|
|
300
304
|
}>;
|
|
301
305
|
};
|
|
306
|
+
fnFields?: {
|
|
307
|
+
outside: Map<string, {
|
|
308
|
+
path: string;
|
|
309
|
+
sort: Sort;
|
|
310
|
+
}>;
|
|
311
|
+
names: Set<string>;
|
|
312
|
+
};
|
|
302
313
|
};
|
|
303
314
|
export declare class Exec {
|
|
304
315
|
readonly s: Setup;
|
|
@@ -364,6 +375,7 @@ export declare class Exec {
|
|
|
364
375
|
resolved(e: ts.Node): ts.Symbol | undefined;
|
|
365
376
|
private args;
|
|
366
377
|
private call;
|
|
378
|
+
fnField(x: ts.Expression): boolean;
|
|
367
379
|
private outside;
|
|
368
380
|
private listLen;
|
|
369
381
|
private listOp;
|
|
@@ -26,6 +26,7 @@ export class Retype extends Error {
|
|
|
26
26
|
this.sort = sort;
|
|
27
27
|
}
|
|
28
28
|
}
|
|
29
|
+
export const unparen = (x) => (ts.isParenthesizedExpression(x) ? unparen(x.expression) : x);
|
|
29
30
|
const where = (n) => {
|
|
30
31
|
const sf = n.getSourceFile(), { line, character } = sf.getLineAndCharacterOfPosition(n.getStart());
|
|
31
32
|
return `${sf.fileName.split('/').pop()}:${line + 1}:${character + 1}`;
|
|
@@ -62,7 +63,8 @@ export function program(code, file, extra = {}) {
|
|
|
62
63
|
}
|
|
63
64
|
export const scriptKind = (file) => (/\.jsx$/.test(file) ? ts.ScriptKind.JSX : /\.tsx$/.test(file) ? ts.ScriptKind.TSX : /\.[cm]?js$/.test(file) ? ts.ScriptKind.JS : ts.ScriptKind.TS);
|
|
64
65
|
// The shape a type has in the subset.
|
|
65
|
-
|
|
66
|
+
// (`inner`: the field path inside the value at `at` that t is the type of, for where a refusal says it is)
|
|
67
|
+
export function shapeOf(t, checker, at, inner) {
|
|
66
68
|
if (t.flags & (ts.TypeFlags.NumberLike))
|
|
67
69
|
return { k: 'num' };
|
|
68
70
|
if (t.flags & ts.TypeFlags.BooleanLike)
|
|
@@ -84,7 +86,7 @@ export function shapeOf(t, checker, at) {
|
|
|
84
86
|
return refuse(at, `${checker.typeToString(t)}: a union of other than string literals`);
|
|
85
87
|
}
|
|
86
88
|
if (t.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown))
|
|
87
|
-
return refuse(at, `${text(at)} has no type the subset reads (any or unknown): annotate it`);
|
|
89
|
+
return refuse(at, inner ? `${(ts.isPropertyDeclaration(at) || ts.isParameter(at) || ts.isPropertySignature(at)) && ts.isIdentifier(at.name) ? at.name.text : text(at)}.${inner} has no type the subset reads (any or unknown${t.flags & ts.TypeFlags.Any ? ': a type not among the files read, say' : ''})` : `${text(at)} has no type the subset reads (any or unknown): annotate it`);
|
|
88
90
|
if (t.flags & ts.TypeFlags.Object) {
|
|
89
91
|
const sym = t.getSymbol() ?? t.aliasSymbol, name = sym?.getName();
|
|
90
92
|
if (name === 'Map') {
|
|
@@ -120,7 +122,7 @@ export function shapeOf(t, checker, at) {
|
|
|
120
122
|
refuse(at, `the optional field ${p.getName()} (a value that may be missing)`);
|
|
121
123
|
if (p.flags & ts.SymbolFlags.Method)
|
|
122
124
|
refuse(at, `the method ${p.getName()} in a value`);
|
|
123
|
-
return [p.getName(), shapeOf(checker.getTypeOfSymbolAtLocation(p, at), checker, at)];
|
|
125
|
+
return [p.getName(), shapeOf(checker.getTypeOfSymbolAtLocation(p, at), checker, at, inner ? `${inner}.${p.getName()}` : p.getName())];
|
|
124
126
|
});
|
|
125
127
|
return { k: 'rec', fields };
|
|
126
128
|
}
|
|
@@ -213,7 +215,8 @@ export class Exec {
|
|
|
213
215
|
const oa = a.heap.get(id), ob = b.heap.get(id);
|
|
214
216
|
heap.set(id, !oa ? ob : !ob ? oa : this.mergeObj(c, oa, ob, a, b, heap, pairs, at));
|
|
215
217
|
}
|
|
216
|
-
|
|
218
|
+
const outs = [...new Set([...(a.outs ?? []), ...(b.outs ?? [])])];
|
|
219
|
+
return { pc, locals, heap, wrote: [...new Set([...a.wrote, ...b.wrote])], nows: Math.max(a.nows, b.nows), ...(outs.length ? { outs } : {}) };
|
|
217
220
|
}
|
|
218
221
|
deref(p, v) {
|
|
219
222
|
while (v.t === 'ref') {
|
|
@@ -496,10 +499,13 @@ export class Exec {
|
|
|
496
499
|
case 'choice': return v.values.includes('') ? I.not(I.is(v.e, '')) : I.T;
|
|
497
500
|
// A string is truthy where it isn't empty.
|
|
498
501
|
case 'str': return v.e.op === 'slit' ? (v.e.value ? I.T : I.F) : I.not(I.keq(v.e, { op: 'slit', value: '' }));
|
|
502
|
+
case 'outside':
|
|
503
|
+
if (v.path.startsWith('new? '))
|
|
504
|
+
return refuse(at, `${text(at)}: whether a function was given to the constructor, read (the check gives one: the claim would be only for calls that do)`);
|
|
505
|
+
return I.T;
|
|
499
506
|
case 'ref':
|
|
500
507
|
case 'cell':
|
|
501
|
-
case 'phi':
|
|
502
|
-
case 'outside': return I.T;
|
|
508
|
+
case 'phi': return I.T;
|
|
503
509
|
case 'opt': return I.and(v.has, this.truthy(v.v, at));
|
|
504
510
|
case 'undef': return I.F;
|
|
505
511
|
case 'opaque': return refuse(at, `${text(at)} read as a condition: ${v.what}`);
|
|
@@ -689,6 +695,15 @@ export class Exec {
|
|
|
689
695
|
}
|
|
690
696
|
binary(e, p) {
|
|
691
697
|
const op = e.operatorToken.kind, S = ts.SyntaxKind;
|
|
698
|
+
if (op === S.EqualsToken && this.fnField(e.left)) {
|
|
699
|
+
// A function field set while the object is made, to the function given or one written there: nothing the rule keeps.
|
|
700
|
+
const r = unparen(e.right), given = ts.isIdentifier(r) && p.locals.get(r.text)?.t === 'outside';
|
|
701
|
+
if (!this.s.ctor)
|
|
702
|
+
return refuse(e, `${text(e.left)}: a field holding a function, set by a method (its calls would answer by another function from then on)`);
|
|
703
|
+
if (!given && !ts.isArrowFunction(r) && !ts.isFunctionExpression(r))
|
|
704
|
+
return refuse(e, `${text(e.left)} set to ${text(r)} (a field holding a function is set to the function given or one written there)`);
|
|
705
|
+
return [{ t: 'undef' }, p];
|
|
706
|
+
}
|
|
692
707
|
if (op === S.EqualsToken) {
|
|
693
708
|
const [v, q] = this.ev(e.right, p);
|
|
694
709
|
return [v, this.assign(e.left, v, q)];
|
|
@@ -1234,6 +1249,11 @@ export class Exec {
|
|
|
1234
1249
|
// A function the factory is given: its answer is an input of the step (any value of its type), read once.
|
|
1235
1250
|
if (ts.isIdentifier(obj) && p.locals.get(obj.text)?.t === 'outside')
|
|
1236
1251
|
return this.outside(e, `${p.locals.get(obj.text).path}.${m}`, p);
|
|
1252
|
+
if (this.fnField(callee)) {
|
|
1253
|
+
if (this.s.ctor)
|
|
1254
|
+
return refuse(e, `${text(callee)}() called while the object is made`);
|
|
1255
|
+
return this.outside(e, `this.${m}`, p);
|
|
1256
|
+
}
|
|
1237
1257
|
if (obj.kind === ts.SyntaxKind.ThisKeyword && this.s.cls) {
|
|
1238
1258
|
const member = this.member(m);
|
|
1239
1259
|
if (member && ts.isMethodDeclaration(member)) {
|
|
@@ -1321,8 +1341,14 @@ export class Exec {
|
|
|
1321
1341
|
}
|
|
1322
1342
|
return refuse(e, 'a call the subset doesn\'t read');
|
|
1323
1343
|
}
|
|
1344
|
+
// this.f, where f is a field holding a function.
|
|
1345
|
+
fnField(x) {
|
|
1346
|
+
const t = unparen(x);
|
|
1347
|
+
return !!this.s.fnFields && ts.isPropertyAccessExpression(t) && t.expression.kind === ts.SyntaxKind.ThisKeyword && this.s.fnFields.names.has(memberName(t.name));
|
|
1348
|
+
}
|
|
1324
1349
|
outside(e, path, p) {
|
|
1325
|
-
const
|
|
1350
|
+
const own = this.s.fnFields;
|
|
1351
|
+
const x = this.s.xstate ?? own ?? refuse(e, `${path}: a function from outside`);
|
|
1326
1352
|
if (e.arguments.some(impure))
|
|
1327
1353
|
refuse(e, `${path}(...) with arguments that have effects`);
|
|
1328
1354
|
const [, q] = this.args(e.arguments, p);
|
|
@@ -1336,6 +1362,20 @@ export class Exec {
|
|
|
1336
1362
|
const sh = shapeOf(t, this.s.checker, e);
|
|
1337
1363
|
if (sh.k !== 'num' && sh.k !== 'bool' && sh.k !== 'choice' && sh.k !== 'str')
|
|
1338
1364
|
return refuse(e, `${path}() returns a compound value`);
|
|
1365
|
+
if (own) {
|
|
1366
|
+
// A class's: one answer a step (a second call may answer differently), the same input in each method.
|
|
1367
|
+
if (q.outs?.includes(path))
|
|
1368
|
+
return refuse(e, `${path}() called twice in one step (each call may answer differently: call it once into a local)`);
|
|
1369
|
+
const had = [...own.outside].find(([, o]) => o.path === path);
|
|
1370
|
+
if (had && had[1].sort.k !== sh.k)
|
|
1371
|
+
return refuse(e, `${path}() read as two sorts`);
|
|
1372
|
+
const v = had ? this.s.vars.get(had[0]) : this.newVar(path.split('.').pop(), sh, 'input', `${path}(): the answer of the function the field holds (any value of its type: the claim is for every such function that leaves the object alone)`);
|
|
1373
|
+
if (!had) {
|
|
1374
|
+
own.outside.set(v.name, { path, sort: sh });
|
|
1375
|
+
this.s.notes.add(`${path}(): the answer of the function the field holds, an input (any value of its type: the claim is for every such function that leaves the object alone)`);
|
|
1376
|
+
}
|
|
1377
|
+
return [Exec.valueOf(v), { ...q, outs: [...(q.outs ?? []), path] }];
|
|
1378
|
+
}
|
|
1339
1379
|
if ([...x.outside.values()].some(o => o.path === path))
|
|
1340
1380
|
return refuse(e, `${path}() read in two places (each call may answer differently)`);
|
|
1341
1381
|
const v = this.newVar(path.split('.').pop(), sh, 'input', `${path}(): the answer of a function the machine is given (any value of its type)`);
|