gdp-wired 0.28.0 → 0.30.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/cycles.js +30 -3
- package/dist/core/data.d.ts +4 -0
- package/dist/core/data.js +188 -24
- package/dist/core/dsl.d.ts +11 -1
- package/dist/core/dsl.js +106 -11
- package/dist/core/extract-read.d.ts +1 -1
- package/dist/core/extract-read.js +4 -3
- package/dist/core/extract-shapes.js +9 -4
- package/dist/core/extract-xstate.js +89 -10
- package/dist/core/fresh.js +16 -1
- package/dist/core/infer.js +819 -188
- package/dist/core/machine.d.ts +5 -0
- package/dist/core/machine.js +3 -3
- package/dist/kernel/cdcl.d.ts +34 -11
- package/dist/kernel/cdcl.js +601 -60
- package/dist/kernel/kernel.d.ts +17 -1
- package/dist/kernel/kernel.js +187 -11
- package/dist/kernel/prove.d.ts +5 -1
- package/dist/kernel/prove.js +200 -63
- package/dist/kernel/reader.d.ts +35 -1
- package/dist/kernel/reader.js +342 -7
- package/dist/kernel/simplex.d.ts +3 -0
- package/dist/kernel/simplex.js +52 -6
- package/dist/lean-kernel/emit.d.ts +12 -0
- package/dist/lean-kernel/emit.js +108 -14
- package/dist/lean-kernel/library.js +2 -1
- 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, substC } 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";
|
|
@@ -862,6 +862,31 @@ function pulledOut(cs, what, prefix) {
|
|
|
862
862
|
throw new Error(`${what}: ${stray[0]} is bound by an exists(...) whose condition was taken apart; keep it whole (and, or, not, implies)`);
|
|
863
863
|
return { cs: out, vars, bodies: bs.map(b => ({ vars: b.vars.map(n => (prefix === undefined ? n : ren[n].name)), body: r(b.body) })) };
|
|
864
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
|
+
};
|
|
865
890
|
// A map from naturals to naturals, every cell starting at `init`. One write per map per step.
|
|
866
891
|
export class MapRef {
|
|
867
892
|
name;
|
|
@@ -887,6 +912,8 @@ export class MapRef {
|
|
|
887
912
|
// carries), and the set's size, the sum of its cells there (exact, given `within`).
|
|
888
913
|
within(n) { naturalConst(n); return everyKey(k => k.atLeast(n).implies(this.at(k).eq(0))); }
|
|
889
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); }
|
|
890
917
|
}
|
|
891
918
|
export class ListRef {
|
|
892
919
|
name;
|
|
@@ -982,6 +1009,8 @@ export class CellsRef {
|
|
|
982
1009
|
each(f) {
|
|
983
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])])) };
|
|
984
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); }
|
|
985
1014
|
}
|
|
986
1015
|
const fromOf = (d, p) => (typeof d.from === 'number' ? d.from : d.from(p));
|
|
987
1016
|
// The keys a condition reads any of these maps at, as terms.
|
|
@@ -1669,6 +1698,28 @@ export class Rule {
|
|
|
1669
1698
|
}
|
|
1670
1699
|
return this.with({ fns: (this.spec.fns ?? []).map(([n, d]) => [n, fns[n] ?? d]), lists2: lists });
|
|
1671
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
|
+
}
|
|
1672
1723
|
params(kinds) { return this.with({ params: [...this.spec.params, ...Object.entries(kinds)] }); }
|
|
1673
1724
|
inputs(kinds) { return this.with({ inputs: [...this.spec.inputs, ...Object.entries(kinds)] }); }
|
|
1674
1725
|
// Each variable starts at a natural or at a term over the params, or is declared by a kind and starts where `from`
|
|
@@ -1846,8 +1897,13 @@ export class Rule {
|
|
|
1846
1897
|
return { ...law, some: vars, ...(Object.keys(witness).length ? { witness } : {}) };
|
|
1847
1898
|
}
|
|
1848
1899
|
// What a law, a step law or a decision divides by, noted so the machine declares it (Spec.arith).
|
|
1849
|
-
divides(x) {
|
|
1850
|
-
|
|
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
|
+
}
|
|
1851
1907
|
// Divide by these too (inferLaws' candidates): the machine declares div$k and mod$k for each.
|
|
1852
1908
|
dividesBy(...ks) { for (const k of ks)
|
|
1853
1909
|
(this.spec.arith ??= new Set()).add(divisor(k, 'dividesBy')); return this; }
|
|
@@ -1857,7 +1913,11 @@ export class Rule {
|
|
|
1857
1913
|
// a case in range, a presence bit 0 or 1), as laws: proveRule, proveSteps and proveLeadsTo prove them beside the laws
|
|
1858
1914
|
// they are given, so a law may lean on "the hold is idle, holding or released" without stating it; give them to
|
|
1859
1915
|
// toLean (or the kernel) with the rest.
|
|
1860
|
-
|
|
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() {
|
|
1861
1921
|
const out = [];
|
|
1862
1922
|
const of = (env, n) => env[n];
|
|
1863
1923
|
for (const [n, k] of this.spec.kinded ?? [])
|
|
@@ -1927,11 +1987,15 @@ export class Rule {
|
|
|
1927
1987
|
// batches.leadsTo('every batch is done', {from: () => yes, to: ({waiting, items}) => waiting.eq(0).and(items.eq(0)),
|
|
1928
1988
|
// rank: ({waiting, items}) => [waiting, items], helpful: [{when: ({items}) => items.gt(0), request: () => ({op: 1})}, {when: ({items}) => items.eq(0), request: () => ({op: 0})}]})
|
|
1929
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}]})
|
|
1930
1994
|
leadsTo(name, spec) {
|
|
1931
1995
|
const env = this.env({ flags: false, inputs: false, queries: false });
|
|
1932
1996
|
const req = (f) => Object.fromEntries(Object.entries(f(env)).map(([n, t]) => [n, termOf(t)]));
|
|
1933
1997
|
const r = spec.rank ? spec.rank(env) : [], rank = Array.isArray(r) ? r.map(termOf) : termOf(r);
|
|
1934
|
-
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 } : {}) };
|
|
1935
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) })) });
|
|
1936
2000
|
}
|
|
1937
2001
|
// A decision: whenever the params and the request meet `given`, `then` holds. Decisions don't read the state; the
|
|
@@ -2192,7 +2256,9 @@ export class Rule {
|
|
|
2192
2256
|
...(s.prune ? { prune: { order: pruneOrder[0], after: termOf(s.prune.after(pEnv)) } } : {}),
|
|
2193
2257
|
};
|
|
2194
2258
|
}
|
|
2195
|
-
|
|
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 ?? []);
|
|
2196
2262
|
}
|
|
2197
2263
|
// --- the builders checked ------------------------------------------------------------------------------------------
|
|
2198
2264
|
// The builders against what they built, on concrete runs: random params and requests by their kinds (`pre` and
|
|
@@ -2495,7 +2561,7 @@ const expandParts = (updates) => {
|
|
|
2495
2561
|
return updates;
|
|
2496
2562
|
};
|
|
2497
2563
|
const encode = (kinds, values) => Object.assign({}, ...kinds.map(([n, k]) => k.encode(n, values[n])));
|
|
2498
|
-
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() });
|
|
2499
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;
|
|
2500
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));
|
|
2501
2567
|
// The kind a result field is kept in.
|
|
@@ -2901,6 +2967,17 @@ function searched(r, laws, stepLaws, v, opts) {
|
|
|
2901
2967
|
return v;
|
|
2902
2968
|
const inf = inferLaws(rule, [...fresh.map(f => f.law), ...laws], stepLaws, { ms, ...(rule === r && !fresh.length ? { first: v } : {}) });
|
|
2903
2969
|
if (!(inf.proven && inf.checked)) {
|
|
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
|
+
}
|
|
2904
2981
|
// (a step law's ghost: at most 10 s of it, as its goals cost more than the laws')
|
|
2905
2982
|
const deep = bounded(Math.max(0, Math.min(until - clock(), ghosted && !laws.length ? 10_000 : Infinity)), Math.max(1, reached));
|
|
2906
2983
|
if (deep)
|
|
@@ -2917,15 +2994,33 @@ export function proveLeadsTo(r, laws, l, opts = {}) {
|
|
|
2917
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)`);
|
|
2918
2995
|
if (Array.isArray(l.rank) && !l.rank.length) {
|
|
2919
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) };
|
|
2920
|
-
|
|
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() });
|
|
2921
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.
|
|
2922
3003
|
if (!(f.proven && f.checked) && until - clock() > 500) {
|
|
2923
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() });
|
|
2924
3005
|
if (g.proven && g.checked)
|
|
2925
3006
|
f = g;
|
|
2926
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
|
+
}
|
|
2927
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 } : {}),
|
|
2928
|
-
...(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 }))] } : {}) } } : {}) };
|
|
2929
3024
|
}
|
|
2930
3025
|
const out = proveLiveness(r.machine, withKinds(r, laws), l);
|
|
2931
3026
|
return verdictOf(out);
|
|
@@ -270,7 +270,7 @@ export declare function program(code: string, file: string, extra?: Record<strin
|
|
|
270
270
|
checker: ts.TypeChecker;
|
|
271
271
|
};
|
|
272
272
|
export declare const scriptKind: (file: string) => ts.ScriptKind;
|
|
273
|
-
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;
|
|
274
274
|
type Callable = {
|
|
275
275
|
decl: ts.FunctionLikeDeclaration;
|
|
276
276
|
self?: string;
|
|
@@ -63,7 +63,8 @@ export function program(code, file, extra = {}) {
|
|
|
63
63
|
}
|
|
64
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);
|
|
65
65
|
// The shape a type has in the subset.
|
|
66
|
-
|
|
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) {
|
|
67
68
|
if (t.flags & (ts.TypeFlags.NumberLike))
|
|
68
69
|
return { k: 'num' };
|
|
69
70
|
if (t.flags & ts.TypeFlags.BooleanLike)
|
|
@@ -85,7 +86,7 @@ export function shapeOf(t, checker, at) {
|
|
|
85
86
|
return refuse(at, `${checker.typeToString(t)}: a union of other than string literals`);
|
|
86
87
|
}
|
|
87
88
|
if (t.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown))
|
|
88
|
-
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`);
|
|
89
90
|
if (t.flags & ts.TypeFlags.Object) {
|
|
90
91
|
const sym = t.getSymbol() ?? t.aliasSymbol, name = sym?.getName();
|
|
91
92
|
if (name === 'Map') {
|
|
@@ -121,7 +122,7 @@ export function shapeOf(t, checker, at) {
|
|
|
121
122
|
refuse(at, `the optional field ${p.getName()} (a value that may be missing)`);
|
|
122
123
|
if (p.flags & ts.SymbolFlags.Method)
|
|
123
124
|
refuse(at, `the method ${p.getName()} in a value`);
|
|
124
|
-
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())];
|
|
125
126
|
});
|
|
126
127
|
return { k: 'rec', fields };
|
|
127
128
|
}
|
|
@@ -701,6 +701,10 @@ function attempt(code, file, opts, written) {
|
|
|
701
701
|
// (core/extract-read.ts's fnFields). Its start is a function written there or the one the constructor is given.
|
|
702
702
|
const fnType = (t) => !(t.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) && s.checker.getSignaturesOfType(s.checker.getNonNullableType(t), ts.SignatureKind.Call).length > 0 && !s.checker.getPropertiesOfType(s.checker.getNonNullableType(t)).length;
|
|
703
703
|
s.fnFields = { outside: new Map(), names: new Set() };
|
|
704
|
+
// A field's type as the entry's object has it: a class it extends with type arguments (`extends Base<Ctx>`) has its
|
|
705
|
+
// fields of a type parameter at the types given (TypeScript's own instantiation of the chain).
|
|
706
|
+
const ct = s.checker.getTypeAtLocation(cls), inst = ts.isClassDeclaration(cls) ? ct : ct.getConstructSignatures()[0]?.getReturnType();
|
|
707
|
+
const typeOf = (name, node) => { const sym = inst && s.checker.getPropertyOfType(inst, name); return sym ? s.checker.getTypeOfSymbolAtLocation(sym, cls) : s.checker.getTypeAtLocation(node); };
|
|
704
708
|
const fnField = (name, at) => { if (s.fnFields.names.has(name))
|
|
705
709
|
refuse(at, `${name}: a field declared again in a class that extends one with it`); s.fnFields.names.add(name); };
|
|
706
710
|
for (const c of [...chain].reverse()) {
|
|
@@ -712,14 +716,15 @@ function attempt(code, file, opts, written) {
|
|
|
712
716
|
refuse(m, 'a static field (state shared by every object)');
|
|
713
717
|
if (has(m, ts.SyntaxKind.AbstractKeyword) || has(m, ts.SyntaxKind.DeclareKeyword))
|
|
714
718
|
continue;
|
|
715
|
-
|
|
719
|
+
const mt = typeOf(memberName(m.name), m);
|
|
720
|
+
if (fnType(mt)) {
|
|
716
721
|
const i = m.initializer && unparen(m.initializer);
|
|
717
722
|
if (i && !ts.isArrowFunction(i) && !ts.isFunctionExpression(i))
|
|
718
723
|
refuse(m, `${memberName(m.name)} starts as ${i.getText().slice(0, 40)} (a field holding a function starts as one written there, or the one the constructor is given)`);
|
|
719
724
|
fnField(memberName(m.name), m);
|
|
720
725
|
continue;
|
|
721
726
|
}
|
|
722
|
-
addField({ name: memberName(m.name), shape: shapeOf(
|
|
727
|
+
addField({ name: memberName(m.name), shape: shapeOf(mt, s.checker, m), node: m, ...(m.initializer ? { init: m.initializer } : {}), of: c });
|
|
723
728
|
}
|
|
724
729
|
else if (ts.isSetAccessorDeclaration(m))
|
|
725
730
|
refuse(m, 'a setter');
|
|
@@ -730,10 +735,10 @@ function attempt(code, file, opts, written) {
|
|
|
730
735
|
}
|
|
731
736
|
const k = ownCtor(c);
|
|
732
737
|
for (const p of k?.parameters ?? [])
|
|
733
|
-
if (ts.isParameterPropertyDeclaration(p, k) && fnType(
|
|
738
|
+
if (ts.isParameterPropertyDeclaration(p, k) && fnType(typeOf(p.name.text, p)))
|
|
734
739
|
fnField(p.name.text, p);
|
|
735
740
|
else if (ts.isParameterPropertyDeclaration(p, k))
|
|
736
|
-
addField({ name: p.name.text, shape: shapeOf(
|
|
741
|
+
addField({ name: p.name.text, shape: shapeOf(typeOf(p.name.text, p), s.checker, p), node: p, of: c });
|
|
737
742
|
}
|
|
738
743
|
const ex0 = new Exec(s);
|
|
739
744
|
const constant = (f) => !first && !written.has(f.name) && f.shape.k !== 'map' && f.shape.k !== 'list';
|
|
@@ -89,11 +89,28 @@ export function extractXState(code, opts) {
|
|
|
89
89
|
return p && (ts.isPropertyAssignment(p) ? p.initializer : ts.isShorthandPropertyAssignment(p) ? p.name : undefined);
|
|
90
90
|
};
|
|
91
91
|
const prop = (o, name) => { const x = propRaw(o, name); return x && strip(x); };
|
|
92
|
+
// What a name stands for, through the program: a const's value or a function declared, in the files read (an import,
|
|
93
|
+
// `export default X`, a const of a const), as TypeScript resolves the name; anything else as it is.
|
|
94
|
+
const valueOf = (e, depth = 0) => {
|
|
95
|
+
e = strip(e);
|
|
96
|
+
if (!ts.isIdentifier(e) || depth > 8)
|
|
97
|
+
return e;
|
|
98
|
+
let sym = ts.isShorthandPropertyAssignment(e.parent) && e.parent.name === e ? checker.getShorthandAssignmentValueSymbol(e.parent) : checker.getSymbolAtLocation(e);
|
|
99
|
+
if (sym && sym.flags & ts.SymbolFlags.Alias)
|
|
100
|
+
sym = checker.getAliasedSymbol(sym);
|
|
101
|
+
const d = sym?.valueDeclaration;
|
|
102
|
+
if (d && ts.isFunctionDeclaration(d) && d.body)
|
|
103
|
+
return d;
|
|
104
|
+
if (d && ts.isVariableDeclaration(d) && d.initializer && d.parent.flags & ts.NodeFlags.Const && !d.getSourceFile().isDeclarationFile)
|
|
105
|
+
return valueOf(d.initializer, depth + 1);
|
|
106
|
+
return e;
|
|
107
|
+
};
|
|
92
108
|
const objOf = (o, name) => {
|
|
93
|
-
const
|
|
94
|
-
if (
|
|
109
|
+
const v0 = prop(o, name);
|
|
110
|
+
if (v0 === undefined)
|
|
95
111
|
return undefined;
|
|
96
|
-
|
|
112
|
+
const v = valueOf(v0);
|
|
113
|
+
return ts.isObjectLiteralExpression(v) ? v : refuse(v0, `the ${name} given as other than an object of them`);
|
|
97
114
|
};
|
|
98
115
|
const args = [];
|
|
99
116
|
const ctxExpr = prop(config, 'context');
|
|
@@ -293,8 +310,8 @@ export function extractXState(code, opts) {
|
|
|
293
310
|
// One function of ({context, event}) (v4: (context, event)) at a time, with the context as variables and the event's
|
|
294
311
|
// fields as inputs.
|
|
295
312
|
const run = (f, what) => {
|
|
296
|
-
const fn =
|
|
297
|
-
if (!isFn(fn))
|
|
313
|
+
const fn = valueOf(f);
|
|
314
|
+
if (!isFn(fn) && !ts.isFunctionDeclaration(fn))
|
|
298
315
|
return refuse(f, `${what}: a reference to a function defined elsewhere`);
|
|
299
316
|
if (fn.parameters.length > (v === 4 ? 2 : 1))
|
|
300
317
|
refuse(fn, `${what} reads its params (guards and actions with params are not in the subset)`);
|
|
@@ -318,7 +335,14 @@ export function extractXState(code, opts) {
|
|
|
318
335
|
};
|
|
319
336
|
// A guard: a condition of ({context, event}), or stateIn.
|
|
320
337
|
const guardOf = (g, name) => {
|
|
321
|
-
|
|
338
|
+
const gv = valueOf(g);
|
|
339
|
+
if (ts.isFunctionDeclaration(gv)) {
|
|
340
|
+
const { v: out } = run(g, `the guard ${name}`);
|
|
341
|
+
if (out.t !== 'bool')
|
|
342
|
+
refuse(g, `the guard ${name} returns other than a boolean`);
|
|
343
|
+
return out.e;
|
|
344
|
+
}
|
|
345
|
+
g = gv;
|
|
322
346
|
if (ts.isCallExpression(g) && ts.isIdentifier(g.expression) && g.expression.text === 'stateIn') {
|
|
323
347
|
const a = g.arguments[0] && strip(g.arguments[0]);
|
|
324
348
|
const path = (o) => (ts.isStringLiteral(o) ? o.text : ts.isObjectLiteralExpression(o) && o.properties.length === 1 && ts.isPropertyAssignment(o.properties[0]) ? `${o.properties[0].name.getText()}.${path(strip(o.properties[0].initializer))}` : refuse(o, 'a stateIn of other than one state'));
|
|
@@ -338,7 +362,12 @@ export function extractXState(code, opts) {
|
|
|
338
362
|
throw e;
|
|
339
363
|
} };
|
|
340
364
|
const actionOf = (a, name) => {
|
|
341
|
-
|
|
365
|
+
const av = valueOf(a);
|
|
366
|
+
if (ts.isFunctionDeclaration(av)) {
|
|
367
|
+
notes.push(`the action ${name} writes no context (its effects outside the machine are left out)`);
|
|
368
|
+
return null;
|
|
369
|
+
}
|
|
370
|
+
a = av;
|
|
342
371
|
const fname = ts.isCallExpression(a) && ts.isIdentifier(a.expression) ? a.expression.text : undefined;
|
|
343
372
|
if (fname === 'assign' && ts.isCallExpression(a)) {
|
|
344
373
|
const arg = a.arguments[0] ? strip(a.arguments[0]) : refuse(a, 'assign()');
|
|
@@ -394,12 +423,62 @@ export function extractXState(code, opts) {
|
|
|
394
423
|
}
|
|
395
424
|
return refuse(a, `the action ${name}: an action the subset doesn't read`);
|
|
396
425
|
};
|
|
397
|
-
|
|
426
|
+
// An object's entries by name: `name: value`, `name` (the value its name stands for), `...other` (another
|
|
427
|
+
// object's entries, the later ones winning, as JavaScript spreads them).
|
|
428
|
+
const named = (o, out = new Map(), depth = 0) => {
|
|
429
|
+
for (const x of o?.properties ?? []) {
|
|
430
|
+
if (ts.isPropertyAssignment(x))
|
|
431
|
+
out.set(memberName(x.name), x.initializer);
|
|
432
|
+
else if (ts.isShorthandPropertyAssignment(x))
|
|
433
|
+
out.set(x.name.text, x.name);
|
|
434
|
+
else if (ts.isSpreadAssignment(x)) {
|
|
435
|
+
const w = valueOf(x.expression);
|
|
436
|
+
if (!ts.isObjectLiteralExpression(w) || depth > 4)
|
|
437
|
+
refuse(x, 'an entry spread from other than an object of them');
|
|
438
|
+
named(w, out, depth + 1);
|
|
439
|
+
}
|
|
440
|
+
else
|
|
441
|
+
refuse(x, 'an entry written other than name: value');
|
|
442
|
+
}
|
|
443
|
+
return out;
|
|
444
|
+
};
|
|
445
|
+
// Only the guards and actions the config names are read: XState runs no other (an object shared by several machines
|
|
446
|
+
// holds others').
|
|
447
|
+
const names = new Set();
|
|
448
|
+
const namesIn = (e, role) => {
|
|
449
|
+
e = strip(e);
|
|
450
|
+
if (role && ts.isStringLiteral(e)) {
|
|
451
|
+
names.add(e.text);
|
|
452
|
+
return;
|
|
453
|
+
}
|
|
454
|
+
if (ts.isArrayLiteralExpression(e)) {
|
|
455
|
+
e.elements.forEach(el => namesIn(el, role));
|
|
456
|
+
return;
|
|
457
|
+
}
|
|
458
|
+
if (ts.isCallExpression(e)) {
|
|
459
|
+
e.arguments.forEach(el => namesIn(el, role));
|
|
460
|
+
return;
|
|
461
|
+
}
|
|
462
|
+
if (!ts.isObjectLiteralExpression(e))
|
|
463
|
+
return;
|
|
464
|
+
for (const p of e.properties)
|
|
465
|
+
if (ts.isPropertyAssignment(p)) {
|
|
466
|
+
const k = ts.isIdentifier(p.name) || ts.isStringLiteral(p.name) ? p.name.text : '';
|
|
467
|
+
namesIn(p.initializer, ['guard', 'cond', 'actions', 'entry', 'exit'].includes(k) || (role === true && k === 'type'));
|
|
468
|
+
}
|
|
469
|
+
};
|
|
470
|
+
namesIn(config);
|
|
471
|
+
const implementations = (o, what) => {
|
|
472
|
+
const all = [...named(o)], used = all.filter(([n]) => names.has(n));
|
|
473
|
+
if (used.length < all.length)
|
|
474
|
+
notes.push(`${all.length - used.length} ${what} of the object the config never names, not read (XState runs only those it names)`);
|
|
475
|
+
return used;
|
|
476
|
+
};
|
|
398
477
|
const guards = [], actions = [];
|
|
399
478
|
const where0 = v === 5 ? setupArg : options;
|
|
400
|
-
for (const [n, g] of
|
|
479
|
+
for (const [n, g] of implementations(objOf(where0, 'guards'), 'guards'))
|
|
401
480
|
guards.push([n, guardOf(g, n)]);
|
|
402
|
-
for (const [n, a] of
|
|
481
|
+
for (const [n, a] of implementations(objOf(where0, 'actions'), 'actions'))
|
|
403
482
|
actions.push([n, actionOf(a, n)]);
|
|
404
483
|
if (v === 4 && setupArg)
|
|
405
484
|
refuse(setupArg, 'setup() with XState v4');
|
package/dist/core/fresh.js
CHANGED
|
@@ -19,6 +19,9 @@ export function freshLaws(m, kinds, draws, opts = {}) {
|
|
|
19
19
|
const until = clock() + (opts.ms ?? 5000), run = interpret(m), rand = seeded(53), bound = 4;
|
|
20
20
|
// the runs: their states, and the variables some step lowers
|
|
21
21
|
const states = [], lowered = new Set(), handed = new Set();
|
|
22
|
+
// a high-water mark: a variable every key a step writes some map at is at most, after the step (top = max(top, b),
|
|
23
|
+
// a cell written at b): each map no step wrote past it, and each it was seen bounding
|
|
24
|
+
const past = new Set(), bounds = new Set();
|
|
22
25
|
for (let trial = 0; trial < 60 && clock() < until; trial++) {
|
|
23
26
|
let ps, st;
|
|
24
27
|
try {
|
|
@@ -44,6 +47,13 @@ export function freshLaws(m, kinds, draws, opts = {}) {
|
|
|
44
47
|
else if (now > was && maps.some(([n, init]) => (st.maps[n]?.get(was) ?? init) !== (next.maps[n]?.get(was) ?? init)))
|
|
45
48
|
handed.add(x);
|
|
46
49
|
}
|
|
50
|
+
for (const [n, init] of maps)
|
|
51
|
+
for (const key of new Set([...(st.maps[n]?.keys() ?? []), ...(next.maps[n]?.keys() ?? [])])) {
|
|
52
|
+
if ((st.maps[n]?.get(key) ?? init) === (next.maps[n]?.get(key) ?? init))
|
|
53
|
+
continue;
|
|
54
|
+
for (const x of Object.keys(m.state))
|
|
55
|
+
(key <= next.scalars[x] ? bounds : past).add(`${x}\u0000${n}`);
|
|
56
|
+
}
|
|
47
57
|
st = next;
|
|
48
58
|
d++;
|
|
49
59
|
states.push({ ps, st });
|
|
@@ -52,7 +62,8 @@ export function freshLaws(m, kinds, draws, opts = {}) {
|
|
|
52
62
|
}
|
|
53
63
|
}
|
|
54
64
|
const counters = [...handed].filter(c => !lowered.has(c));
|
|
55
|
-
|
|
65
|
+
const highs = [...bounds].filter(p => !past.has(p) && !lowered.has(p.split('\u0000')[0]) && !counters.includes(p.split('\u0000')[0])).map(p => p.split('\u0000'));
|
|
66
|
+
if (!counters.length && !highs.length)
|
|
56
67
|
return [];
|
|
57
68
|
const key = 'k$fresh', record = (n) => n.slice(0, Math.max(0, n.indexOf('.')));
|
|
58
69
|
const cands = [];
|
|
@@ -66,6 +77,10 @@ export function freshLaws(m, kinds, draws, opts = {}) {
|
|
|
66
77
|
cands.push({ law: { name: `ids from ${c}: ${map} below them where ${g} is set`, holds: { op: 'or', xs: [{ op: '=', a: get(g, v(key)), b: { op: 'const', value: gi } }, { op: '<', a: at, b: v(c) }] }, forall: key }, text: `∀k. ${g}[k] ≠ ${gi} → ${map}[k] < ${c}` });
|
|
67
78
|
}
|
|
68
79
|
}
|
|
80
|
+
for (const [c, map] of highs) {
|
|
81
|
+
const init = m.maps[map];
|
|
82
|
+
cands.push({ law: { name: `keys up to ${c}: ${map} unset past it`, holds: { op: 'or', xs: [{ op: '<=', a: v(key), b: v(c) }, { op: '=', a: get(map, v(key)), b: { op: 'const', value: init } }] }, forall: key }, text: `∀k. ${c} < k → ${map}[k] = ${init}` });
|
|
83
|
+
}
|
|
69
84
|
let alive = cands.filter(f => states.every(({ ps, st }) => { try {
|
|
70
85
|
return watch(m, run, f.law, ps, bound).start(st);
|
|
71
86
|
}
|