gdp-wired 0.22.0 → 0.24.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.
Files changed (60) hide show
  1. package/README.md +27 -2
  2. package/dist/core/bmc.d.ts +49 -0
  3. package/dist/core/bmc.js +509 -0
  4. package/dist/core/check.d.ts +1 -1
  5. package/dist/core/check.js +19 -6
  6. package/dist/core/cycles.d.ts +38 -0
  7. package/dist/core/cycles.js +531 -43
  8. package/dist/core/data.d.ts +25 -1
  9. package/dist/core/data.js +984 -215
  10. package/dist/core/discover.js +8 -3
  11. package/dist/core/dsl.d.ts +17 -3
  12. package/dist/core/dsl.js +81 -15
  13. package/dist/core/extract-check.d.ts +77 -0
  14. package/dist/core/extract-check.js +785 -0
  15. package/dist/core/extract-ir.d.ts +139 -0
  16. package/dist/core/extract-ir.js +198 -0
  17. package/dist/core/extract-print.d.ts +30 -0
  18. package/dist/core/extract-print.js +426 -0
  19. package/dist/core/extract-read.d.ts +298 -0
  20. package/dist/core/extract-read.js +1298 -0
  21. package/dist/core/extract-shapes.d.ts +13 -0
  22. package/dist/core/extract-shapes.js +993 -0
  23. package/dist/core/extract-xstate.d.ts +34 -0
  24. package/dist/core/extract-xstate.js +320 -0
  25. package/dist/core/extract.d.ts +31 -0
  26. package/dist/core/extract.js +249 -0
  27. package/dist/core/infer.js +518 -5
  28. package/dist/core/kind.d.ts +30 -0
  29. package/dist/core/kind.js +81 -0
  30. package/dist/core/nonterm.d.ts +34 -0
  31. package/dist/core/nonterm.js +610 -0
  32. package/dist/core/q.d.ts +17 -0
  33. package/dist/core/q.js +52 -0
  34. package/dist/core/rationals.d.ts +112 -0
  35. package/dist/core/rationals.js +281 -0
  36. package/dist/core/relation.d.ts +28 -0
  37. package/dist/core/relation.js +483 -0
  38. package/dist/core/solver.d.ts +5 -2
  39. package/dist/core/solver.js +65 -20
  40. package/dist/core/transfer.d.ts +3 -3
  41. package/dist/core/transfer.js +69 -42
  42. package/dist/core/xstate.d.ts +6 -0
  43. package/dist/core/xstate.js +70 -12
  44. package/dist/kernel/cdcl.d.ts +13 -0
  45. package/dist/kernel/cdcl.js +307 -236
  46. package/dist/kernel/kernel.d.ts +106 -0
  47. package/dist/kernel/kernel.js +342 -0
  48. package/dist/kernel/prove.js +14 -3
  49. package/dist/kernel/qprove.d.ts +18 -0
  50. package/dist/kernel/qprove.js +157 -0
  51. package/dist/kernel/reader.d.ts +14 -0
  52. package/dist/kernel/reader.js +102 -14
  53. package/dist/kernel/simplex.d.ts +4 -0
  54. package/dist/kernel/simplex.js +38 -11
  55. package/dist/lean-kernel/emit.d.ts +46 -1
  56. package/dist/lean-kernel/emit.js +125 -16
  57. package/dist/lean-kernel/library.js +4 -1
  58. package/dist/lean-kernel/qlean.d.ts +26 -0
  59. package/dist/lean-kernel/qlean.js +105 -0
  60. package/package.json +16 -3
@@ -1,11 +1,16 @@
1
- // Linear arithmetic over the integers, inside the library. A conjunction of constraints `lin <= 0` is decided by
2
- // Fourier–Motzkin elimination with integer cuts, and every answer carries evidence that a small checker verifies:
1
+ // Linear arithmetic over the integers and over the rationals, inside the library. A conjunction of constraints
2
+ // `lin <= 0` (or `lin < 0`, strict) is decided by Fourier–Motzkin elimination with integer cuts, and every answer
3
+ // carries evidence that a small checker verifies:
3
4
  // refuted a derivation: input rows, positive combinations of two rows, and cuts (divide a row's variable
4
5
  // coefficients by their common divisor g and round the constant up), ending in `positive <= 0`
5
6
  // sat an integer witness, checked by evaluating every input constraint at it
6
7
  // unknown elimination was inexact for the integers and no witness was found (never a wrong answer)
7
8
  // Elimination of x is exact for the integers when every pair it combines has a coefficient ±1 on x (the Omega test's
8
9
  // exact shadow). Then a rational solution of the rest extends to an integer x, so back-substitution finds a witness.
10
+ // Over the rationals (`integral` false) the same elimination is exact with no cut at all (a combination of a strict
11
+ // row is strict), so the answer is refuted or sat, the witness exact (`rational`), the derivation one check.ts takes
12
+ // with no cut: the integers are this with the cut rule, and a strict row over them is lin + 1 <= 0.
13
+ import { Q0, Q1, q, qadd, qcmp, qdiv, qneg, qnum, qrow, qsub } from "./q.js";
9
14
  export const v = (name) => ({ [name]: 1 });
10
15
  export const k = (value) => (value === 0 ? {} : { 1: value });
11
16
  // (Plain loops, no intermediate arrays: these run millions of times in a proof. Each keeps the keys in the order they
@@ -58,13 +63,15 @@ const vars = (lin) => Object.keys(lin).filter(key => key !== '1');
58
63
  // five times as many before merging them, it gives up with `unknown`.
59
64
  // The rows the solver has read and made, which a counted search reads as its clock (kernel/prove.ts's `counted`).
60
65
  export const work = { n: 0 };
61
- export function solve(constraints, maxRows = 20_000) {
66
+ export function solve(constraints, maxRows = 20_000, integral = true) {
62
67
  work.n += constraints.length;
63
68
  const steps = [];
64
- const lins = [];
65
- const push = (step, lin) => (steps.push(step), lins.push(lin), lins.length - 1);
66
- // A row after its cut, if its variables share a divisor.
69
+ const lins = [], stricts = [];
70
+ const push = (step, lin, strict = false) => (steps.push(step), lins.push(lin), stricts.push(strict), lins.length - 1);
71
+ // A row after its cut, if its variables share a divisor (over the integers only).
67
72
  const tighten = (index) => {
73
+ if (!integral)
74
+ return index;
68
75
  const lin = lins[index];
69
76
  let g = 0;
70
77
  for (const key in lin)
@@ -82,10 +89,15 @@ export function solve(constraints, maxRows = 20_000) {
82
89
  const constant = Math.ceil((lin['1'] ?? 0) / g);
83
90
  return push({ kind: 'cut', of: index, g }, add(cut, k(constant)));
84
91
  };
85
- let rows = constraints.map((c, index) => tighten(push({ kind: 'input', index }, c.lin)));
86
- // A row with no variable and a positive constant (kept per row: a row never changes once pushed).
92
+ let rows = constraints.map((c, index) => tighten(push({ kind: 'input', index }, c.lin, !integral && c.strict === true)));
93
+ // A row with no variable and a positive constant, or a strict one with a constant >= 0 (kept per row: a row never
94
+ // changes once pushed).
87
95
  const contra = [];
88
- const isContra = (r) => (contra[r] ??= (lins[r]['1'] ?? 0) > 0 && Object.keys(lins[r]).every(key => key === '1'));
96
+ const isContra = (r) => (contra[r] ??= ((lins[r]['1'] ?? 0) > 0 || (stricts[r] && (lins[r]['1'] ?? 0) >= 0)) && Object.keys(lins[r]).every(key => key === '1'));
97
+ // Over the rationals every coefficient must stay a safe integer (none is rounded); past that, unknown.
98
+ let inexact = false;
99
+ const pushExact = (step, lin, strict) => { if (!integral && !Object.values(lin).every(c => Number.isSafeInteger(c)))
100
+ inexact = true; return push(step, lin, strict); };
89
101
  const contradiction = () => rows.find(isContra);
90
102
  const eliminated = [];
91
103
  let exact = true;
@@ -101,7 +113,7 @@ export function solve(constraints, maxRows = 20_000) {
101
113
  const byKey = new Map(rows.map(r => [key(r), r]));
102
114
  for (const r of rows) {
103
115
  const neg = byKey.get(negKey(r));
104
- if (neg === undefined || neg === r)
116
+ if (neg === undefined || neg === r || stricts[r] || stricts[neg])
105
117
  continue;
106
118
  let x;
107
119
  for (const name in lins[r])
@@ -121,7 +133,7 @@ export function solve(constraints, maxRows = 20_000) {
121
133
  if (c === 0)
122
134
  next.push(o);
123
135
  else
124
- next.push(tighten(push({ kind: 'combine', a: o, b: c > 0 ? down : up, ma: 1, mb: Math.abs(c) }, add(lins[o], scale(lins[c > 0 ? down : up], Math.abs(c))))));
136
+ next.push(tighten(pushExact({ kind: 'combine', a: o, b: c > 0 ? down : up, ma: 1, mb: Math.abs(c) }, add(lins[o], scale(lins[c > 0 ? down : up], Math.abs(c))), stricts[o])));
125
137
  }
126
138
  eliminated.push({ x, rows: [up, down] });
127
139
  rows = next;
@@ -183,27 +195,29 @@ export function solve(constraints, maxRows = 20_000) {
183
195
  for (const p of choice.pos)
184
196
  for (const n of choice.neg) {
185
197
  const a = lins[p][choice.x], b = -lins[n][choice.x];
186
- const combined = push({ kind: 'combine', a: p, b: n, ma: b / gcd(a, b), mb: a / gcd(a, b) }, add(scale(lins[p], b / gcd(a, b)), scale(lins[n], a / gcd(a, b))));
198
+ const combined = pushExact({ kind: 'combine', a: p, b: n, ma: b / gcd(a, b), mb: a / gcd(a, b) }, add(scale(lins[p], b / gcd(a, b)), scale(lins[n], a / gcd(a, b))), stricts[p] || stricts[n]);
187
199
  next.push(tighten(combined));
188
200
  }
189
- // Rows with the same variable part: only the tightest (largest constant) matters; rows with no variables that hold
190
- // say nothing.
201
+ // Rows with the same variable part: only the tightest (largest constant, strict before not at the same) matters;
202
+ // rows with no variables that hold say nothing.
191
203
  const best = new Map();
192
204
  for (const r of next) {
193
205
  const lin = lins[r], sig = sigOf(r);
194
- if (sig === '[]' && (lin['1'] ?? 0) <= 0)
206
+ if (sig === '[]' && !isContra(r))
195
207
  continue;
196
208
  const seen = best.get(sig);
197
- if (seen === undefined || (lins[seen]['1'] ?? 0) < (lin['1'] ?? 0))
209
+ if (seen === undefined || (lins[seen]['1'] ?? 0) < (lin['1'] ?? 0) || (stricts[r] && !stricts[seen] && (lins[seen]['1'] ?? 0) === (lin['1'] ?? 0)))
198
210
  best.set(sig, r);
199
211
  }
200
212
  rows = [...best.values()];
201
- if (rows.length > maxRows)
213
+ if (rows.length > maxRows || inexact)
202
214
  return { kind: 'unknown' };
203
215
  }
204
216
  const found = contradiction();
205
217
  if (found !== undefined)
206
- return { kind: 'refuted', steps: prune(steps, found) };
218
+ return inexact ? { kind: 'unknown' } : { kind: 'refuted', steps: prune(steps, found) };
219
+ if (!integral)
220
+ return inexact ? { kind: 'unknown' } : satOverQ(constraints, eliminated, lins, stricts);
207
221
  // A rational solution the same way (cuts only remove non-integer points, so bounds never cross): where to split.
208
222
  const rational = {};
209
223
  for (const { x, rows: bounds } of [...eliminated].reverse()) {
@@ -240,6 +254,35 @@ export function solve(constraints, maxRows = 20_000) {
240
254
  void exact;
241
255
  return holds ? { kind: 'sat', witness: point } : { kind: 'unknown', point: rational };
242
256
  }
257
+ // Over the rationals elimination is exact: back-substitution, last eliminated first, gives each variable an exact value
258
+ // within its bounds (strict ones kept strict): 0 where it may be, else the integer nearest its bounds that fits, else
259
+ // the midpoint. The witness is checked on every input exactly; a miss (none should happen) is unknown, never sat.
260
+ function satOverQ(constraints, eliminated, lins, stricts) {
261
+ const at = {};
262
+ for (const { x, rows: bounds } of [...eliminated].reverse()) {
263
+ let lo, hi;
264
+ for (const r of bounds) {
265
+ const lin = lins[r], a = lin[x];
266
+ // a·x + rest (<|<=) 0: x (<|<=) −rest/a when a > 0, x (>|>=) −rest/a when a < 0.
267
+ const rest = qrow(Object.fromEntries(Object.entries(lin).filter(([key]) => key !== x)), at), b = qdiv(qneg(rest), q(a)), strict = stricts[r];
268
+ if (a > 0) {
269
+ if (!hi || qcmp(b, hi.v) < 0 || (qcmp(b, hi.v) === 0 && strict))
270
+ hi = { v: b, strict };
271
+ }
272
+ else if (!lo || qcmp(b, lo.v) > 0 || (qcmp(b, lo.v) === 0 && strict))
273
+ lo = { v: b, strict };
274
+ }
275
+ const fits = (v) => (!lo || qcmp(v, lo.v) > 0 || (!lo.strict && qcmp(v, lo.v) === 0)) && (!hi || qcmp(v, hi.v) < 0 || (!hi.strict && qcmp(v, hi.v) === 0));
276
+ const floor = (v) => q(v.num >= 0n ? v.num / v.den : -((-v.num + v.den - 1n) / v.den));
277
+ const tries = [Q0, ...(lo ? [floor(lo.v), qadd(floor(lo.v), Q1)] : []), ...(hi ? [floor(hi.v), qsub(floor(hi.v), Q1)] : [])];
278
+ at[x] = tries.find(fits) ?? (lo && hi ? qdiv(qadd(lo.v, hi.v), q(2)) : lo ? qadd(lo.v, Q1) : qsub(hi.v, Q1));
279
+ }
280
+ for (const c of constraints)
281
+ for (const key of vars(c.lin))
282
+ at[key] ??= Q0;
283
+ const holds = constraints.every(c => { const s = qcmp(qrow(c.lin, at), Q0); return c.strict ? s < 0 : s <= 0; });
284
+ return holds ? { kind: 'sat', witness: Object.fromEntries(Object.entries(at).map(([key, v]) => [key, qnum(v)])), rational: at } : { kind: 'unknown' };
285
+ }
243
286
  // Only the steps the contradiction depends on, renumbered.
244
287
  function prune(steps, last) {
245
288
  const keep = new Set();
@@ -267,7 +310,9 @@ function prune(steps, last) {
267
310
  // derivation, renumbered to the whole system's rows. Floating point only picks the rows: the derivation is exact, and
268
311
  // the checker sees nothing else. Undefined when no λ turns up (a system with a rational solution, or one the floats
269
312
  // misjudge): the caller goes on as without it.
270
- export function refuteFast(constraints, maxRows = 2_000) {
313
+ // (Over the rationals, `integral` false, the elimination on the support has no cut; a refutation that needs a strict
314
+ // row's strictness, Σ λ·c = 0, isn't looked for here: the caller's own elimination finds it.)
315
+ export function refuteFast(constraints, maxRows = 2_000, integral = true) {
271
316
  const m = constraints.length;
272
317
  if (m === 0)
273
318
  return undefined;
@@ -348,7 +393,7 @@ export function refuteFast(constraints, maxRows = 2_000) {
348
393
  support.push(basis[r]);
349
394
  if (!support.length)
350
395
  return undefined;
351
- const sub = solve(support.sort((a, b) => a - b).map(i => constraints[i]));
396
+ const sub = solve(support.sort((a, b) => a - b).map(i => constraints[i]), 20_000, integral);
352
397
  if (sub.kind !== 'refuted')
353
398
  return undefined;
354
399
  return { kind: 'refuted', steps: sub.steps.map(st => (st.kind === 'input' ? { ...st, index: support[st.index] } : st)) };
@@ -1,10 +1,10 @@
1
1
  import { type DataLaw, type DataVerdict, type Options, type X } from './data.js';
2
2
  type Op = {
3
3
  name: string;
4
- args: 1 | 2;
4
+ args: number;
5
5
  ret: 'nat' | 'bool';
6
- x: (a: X, b: X) => X;
7
- at: (a: number, b: number) => number;
6
+ x: (as: X[]) => X;
7
+ at: (ns: number[]) => number;
8
8
  };
9
9
  export type Plan = {
10
10
  bridges: Map<string, Op>;
@@ -1,48 +1,72 @@
1
- import { Bool, Integer, Nat, Val, argsOf, bindName, define, encX, encY, evalX, factsOf, fnNamed, programOf, schemesOf, searchIn } from "./data.js";
1
+ import { Bool, Integer, Nat, Val, argsOf, bindName, define, encX, encY, evalX, factsOf, fnNamed, programOf, rankWidth, schemesOf, searchIn } from "./data.js";
2
2
  import { proveCyclic } from "./cyclic.js";
3
3
  import { clock, pairedKeys, withDeadline } from "../kernel/prove.js";
4
4
  import { substE } from "../kernel/kernel.js";
5
5
  const nat = (value) => ({ op: 'nat', value });
6
6
  const cond = (c) => ({ op: 'bool', c });
7
7
  const OPS = [
8
- { name: '+', args: 2, ret: 'nat', x: (a, b) => ({ op: 'add', a, b }), at: (a, b) => a + b },
9
- { name: '∸', args: 2, ret: 'nat', x: (a, b) => ({ op: 'sub', a, b }), at: (a, b) => Math.max(0, a - b) },
10
- { name: 'min', args: 2, ret: 'nat', x: (a, b) => ({ op: 'min', a, b }), at: Math.min },
11
- { name: 'max', args: 2, ret: 'nat', x: (a, b) => ({ op: 'max', a, b }), at: Math.max },
12
- { name: '≤', args: 2, ret: 'bool', x: (a, b) => cond({ op: '<=', a, b }), at: (a, b) => +(a <= b) },
13
- { name: '<', args: 2, ret: 'bool', x: (a, b) => cond({ op: '<', a, b }), at: (a, b) => +(a < b) },
14
- { name: '=', args: 2, ret: 'bool', x: (a, b) => cond({ op: '=', a, b }), at: (a, b) => +(a === b) },
15
- { name: '≥', args: 2, ret: 'bool', x: (a, b) => cond({ op: '<=', a: b, b: a }), at: (a, b) => +(a >= b) },
16
- { name: '>', args: 2, ret: 'bool', x: (a, b) => cond({ op: '<', a: b, b: a }), at: (a, b) => +(a > b) },
17
- { name: '≠', args: 2, ret: 'bool', x: (a, b) => cond({ op: 'not', x: { op: '=', a, b } }), at: (a, b) => +(a !== b) },
18
- { name: 'x + 1', args: 1, ret: 'nat', x: a => ({ op: 'add', a, b: nat(1) }), at: a => a + 1 },
19
- { name: 'x ∸ 1', args: 1, ret: 'nat', x: a => ({ op: 'sub', a, b: nat(1) }), at: a => Math.max(0, a - 1) },
20
- { name: '2·x', args: 1, ret: 'nat', x: a => ({ op: 'mul', k: 2, a }), at: a => 2 * a },
21
- { name: 'x = 0', args: 1, ret: 'bool', x: a => cond({ op: '=', a, b: nat(0) }), at: a => +(a === 0) },
8
+ { name: '+', args: 2, ret: 'nat', x: ([a, b]) => ({ op: 'add', a: a, b: b }), at: ([a, b]) => a + b },
9
+ { name: '∸', args: 2, ret: 'nat', x: ([a, b]) => ({ op: 'sub', a: a, b: b }), at: ([a, b]) => Math.max(0, a - b) },
10
+ { name: 'min', args: 2, ret: 'nat', x: ([a, b]) => ({ op: 'min', a: a, b: b }), at: ([a, b]) => Math.min(a, b) },
11
+ { name: 'max', args: 2, ret: 'nat', x: ([a, b]) => ({ op: 'max', a: a, b: b }), at: ([a, b]) => Math.max(a, b) },
12
+ { name: '≤', args: 2, ret: 'bool', x: ([a, b]) => cond({ op: '<=', a: a, b: b }), at: ([a, b]) => +(a <= b) },
13
+ { name: '<', args: 2, ret: 'bool', x: ([a, b]) => cond({ op: '<', a: a, b: b }), at: ([a, b]) => +(a < b) },
14
+ { name: '=', args: 2, ret: 'bool', x: ([a, b]) => cond({ op: '=', a: a, b: b }), at: ([a, b]) => +(a === b) },
15
+ { name: '≥', args: 2, ret: 'bool', x: ([a, b]) => cond({ op: '<=', a: b, b: a }), at: ([a, b]) => +(a >= b) },
16
+ { name: '>', args: 2, ret: 'bool', x: ([a, b]) => cond({ op: '<', a: b, b: a }), at: ([a, b]) => +(a > b) },
17
+ { name: '≠', args: 2, ret: 'bool', x: ([a, b]) => cond({ op: 'not', x: { op: '=', a: a, b: b } }), at: ([a, b]) => +(a !== b) },
18
+ { name: 'x + 1', args: 1, ret: 'nat', x: ([a]) => ({ op: 'add', a: a, b: nat(1) }), at: ([a]) => a + 1 },
19
+ { name: 'x ∸ 1', args: 1, ret: 'nat', x: ([a]) => ({ op: 'sub', a: a, b: nat(1) }), at: ([a]) => Math.max(0, a - 1) },
20
+ { name: '2·x', args: 1, ret: 'nat', x: ([a]) => ({ op: 'mul', k: 2, a: a }), at: ([a]) => 2 * a },
21
+ { name: 'x = 0', args: 1, ret: 'bool', x: ([a]) => cond({ op: '=', a: a, b: nat(0) }), at: ([a]) => +(a === 0) },
22
22
  ];
23
+ // A sum Σ cᵢ·xᵢ + c₀ of naturals (cᵢ, c₀ ≥ 0): the built-in of a function of three or four naturals (add3, add3acc), or
24
+ // of one or two that none of OPS is.
25
+ const linear = (cs, c0) => {
26
+ const names = ['x', 'y', 'z', 'w'], name = [...cs.flatMap((c, i) => (c ? [`${c === 1 ? '' : `${c}·`}${names[i]}`] : [])), ...(c0 || cs.every(c => !c) ? [String(c0)] : [])].join(' + ');
27
+ const term = (a, c) => (c === 1 ? a : { op: 'mul', k: c, a });
28
+ return { name, args: cs.length, ret: 'nat', at: ns => cs.reduce((t, c, i) => t + c * ns[i], c0),
29
+ x: as => { const parts = [...cs.flatMap((c, i) => (c ? [term(as[i], c)] : [])), ...(c0 || cs.every(c => !c) ? [nat(c0)] : [])]; return parts.slice(1).reduce((t, x) => ({ op: 'add', a: t, b: x }), parts[0]); } };
30
+ };
23
31
  const fnOf = (name) => { const f = fnNamed(name); if (!f)
24
32
  throw new Error(`no function ${name}`); return f; };
25
33
  const recursive = (f) => f.decreases !== undefined;
26
- // The built-in a recursive function of naturals computes at every argument up to 6 (one argument: up to 12), if one.
34
+ // Recursive at all (structural, or well-founded): never unfolded at a call.
35
+ const taken = (f) => recursive(f) || f.measure !== undefined;
36
+ // The built-in a recursive function of naturals (structural, or well-founded: its termination proven) computes at every
37
+ // argument up to 6 (one argument: up to 12; three: up to 5; four: up to 3), if one.
27
38
  function builtinOf(f) {
28
- if (!recursive(f) || f.paramFns.length || !(f.ret === 'nat' || f.ret === 'bool') || !f.params.every(q => q.sort === 'nat'))
39
+ if (!taken(f) || f.paramFns.length || !(f.ret === 'nat' || f.ret === 'bool') || !f.params.every(q => q.sort === 'nat'))
29
40
  return undefined;
30
41
  const n = f.params.length;
31
- return OPS.find(op => {
32
- if (op.args !== n || op.ret !== f.ret)
33
- return false;
34
- try {
35
- for (let a = 0; a <= (n === 1 ? 12 : 6); a++)
36
- for (let b = 0; b <= (n === 1 ? 0 : 6); b++) {
37
- if (evalX({ op: 'call', fn: f.name, args: [nat(a), nat(b)].slice(0, n) }, new Map(), {}) !== op.at(a, b))
38
- return false;
39
- }
40
- }
41
- catch {
42
- return false;
42
+ if (n < 1 || n > 4)
43
+ return undefined;
44
+ const top = [12, 6, 5, 3][n - 1], points = [[]];
45
+ for (let i = 0; i < n; i++)
46
+ points.splice(0, points.length, ...points.flatMap(p => Array.from({ length: top + 1 }, (_, a) => [...p, a])));
47
+ const values = new Map();
48
+ const at = (ns) => {
49
+ const key = ns.join(',');
50
+ if (!values.has(key)) {
51
+ try {
52
+ values.set(key, evalX({ op: 'call', fn: f.name, args: ns.map(nat) }, new Map(), {}));
53
+ }
54
+ catch {
55
+ return undefined;
56
+ }
43
57
  }
44
- return true;
45
- });
58
+ return values.get(key);
59
+ };
60
+ const agrees = (op) => points.every(ns => at(ns) === op.at(ns));
61
+ const named = OPS.find(op => op.args === n && op.ret === f.ret && agrees(op));
62
+ if (named || f.ret !== 'nat')
63
+ return named;
64
+ // (its value at zero and at each unit point, then checked at every point)
65
+ const c0 = at(Array(n).fill(0)), cs = Array.from({ length: n }, (_, i) => { const e = Array(n).fill(0); e[i] = 1; const v = at(e); return v === undefined || c0 === undefined ? -1 : v - c0; });
66
+ if (c0 === undefined || cs.some(c => c < 0))
67
+ return undefined;
68
+ const op = linear(cs, c0);
69
+ return agrees(op) ? op : undefined;
46
70
  }
47
71
  // Whether `y` is f's bridge law: f at distinct variables equal (either side) to the built-in at them.
48
72
  function isBridge(y, f, op) {
@@ -50,7 +74,7 @@ function isBridge(y, f, op) {
50
74
  return false;
51
75
  const sides = [[y.a, y.b], [y.b, y.a]];
52
76
  return sides.some(([c, x]) => c.op === 'call' && c.fn === f.name && c.args.every(a => a.op === 'var') && new Set(c.args.map(a => JSON.stringify(a))).size === c.args.length
53
- && JSON.stringify(x) === JSON.stringify(op.x(c.args[0], c.args[1] ?? nat(0))));
77
+ && JSON.stringify(x) === JSON.stringify(op.x(c.args)));
54
78
  }
55
79
  const callsOf = (t) => { const out = []; walkO(t, o => { if (o.op === 'call')
56
80
  out.push(o.fn); }); return out; };
@@ -72,7 +96,7 @@ export function transferPlan(l) {
72
96
  if (op && !isBridge(l.holds, f, op))
73
97
  bridges.set(f.name, op);
74
98
  }
75
- const unfolds = p.fns.some(f => !recursive(f));
99
+ const unfolds = p.fns.some(f => !taken(f));
76
100
  return bridges.size || unfolds ? { bridges, unfolds } : undefined;
77
101
  }
78
102
  // --- the law said another way ------------------------------------------------------------------------------------------
@@ -136,8 +160,8 @@ function rewriter(bridges, copies, unfold, ren = new Map()) {
136
160
  case 'call': {
137
161
  const op = bridges.get(x.fn);
138
162
  if (op)
139
- return op.x(rx(x.args[0]), x.args[1] ? rx(x.args[1]) : nat(0));
140
- if (unfold && !recursive(fnOf(x.fn))) {
163
+ return op.x(x.args.map(rx));
164
+ if (unfold && !taken(fnOf(x.fn))) {
141
165
  if (++unfolded > 400)
142
166
  throw new RangeError('unfolded past 400 calls');
143
167
  return rx(instantiate(fnOf(x.fn), x.args));
@@ -175,7 +199,7 @@ const freshName = (base) => { let n = base; for (let i = 2; fnNamed(n); i++)
175
199
  function build(l, bridged, unfold) {
176
200
  // Copied: a function that calls a bridged one, or (unfolding) one that isn't recursive, or a copied one; a function
177
201
  // that isn't recursive is unfolded where it is called instead.
178
- const p0 = programOf([l]), reach = new Set(), unfolded = (n) => unfold && !recursive(fnOf(n));
202
+ const p0 = programOf([l]), reach = new Set(), unfolded = (n) => unfold && !taken(fnOf(n));
179
203
  for (let changed = true; changed;) {
180
204
  changed = false;
181
205
  for (const f of p0.fns)
@@ -236,7 +260,7 @@ function build(l, bridged, unfold) {
236
260
  const p1 = programOf([lstar]), back = new Map([...copies].map(([a, b]) => [b, a]));
237
261
  const bridges = [...bridged].map(([f, op]) => {
238
262
  const fn = fnOf(f), vs = fn.params.map(q => q.name);
239
- return { fn, op, law: { name: `${f} is ${op.name}`, vars: fn.params.map(q => ({ name: q.name, sort: q.sort })), holds: { op: '=', a: { op: 'call', fn: f, args: vs.map(v) }, b: op.x(v(vs[0]), vs[1] ? v(vs[1]) : nat(0)) }, params: [] } };
263
+ return { fn, op, law: { name: `${f} is ${op.name}`, vars: fn.params.map(q => ({ name: q.name, sort: q.sort })), holds: { op: '=', a: { op: 'call', fn: f, args: vs.map(v) }, b: op.x(vs.map(v)) }, params: [] } };
240
264
  });
241
265
  const equivs = p1.fns.filter(f => back.has(f.name)).map(c => {
242
266
  const fn = fnOf(back.get(c.name)), vs = fn.params.map(q => q.name), params = [...new Set(fn.paramFns)];
@@ -332,7 +356,7 @@ export function proveThrough(l, plan, opts, until) {
332
356
  const v = verify(fs, specs, Math.max(until, clock() + 3000));
333
357
  if (!v.proven || !v.checked)
334
358
  return undefined;
335
- const through = [...b.bridges.map(x => `${x.fn.name} is ${x.op.name}`), ...b.equivs.map(x => x.law.name), ...(b.unfolded ? [`unfolded: ${programOf([l]).fns.filter(f => !recursive(f)).map(f => f.name).join(', ')}`] : [])];
359
+ const through = [...b.bridges.map(x => `${x.fn.name} is ${x.op.name}`), ...b.equivs.map(x => x.law.name), ...(b.unfolded ? [`unfolded: ${programOf([l]).fns.filter(f => !taken(f)).map(f => f.name).join(', ')}`] : [])];
336
360
  return { law: l.name, proven: true, checked: true, proof: v, lemmas: [...b.bridges.map(x => x.law.name), ...b.equivs.map(x => x.law.name), ...r.verdict.lemmas], scheme: `${r.verdict.scheme ?? 'no induction'}, through the law ${b.lstar.name}`, tried, program: b.p, node: specs.length - 1, ms: Math.round(performance.now() - t0), through };
337
361
  }
338
362
  }
@@ -367,9 +391,9 @@ function walker(b, fs, nodeOf, own) {
367
391
  if (br) {
368
392
  if (!use(br.law.name, Object.fromEntries(f.params.map((q, i) => [q.name, as[i]]))))
369
393
  return undefined;
370
- return substE(encX(p, br.op.x({ op: 'var', name: 'a$' }, { op: 'var', name: 'b$' }), new Map()), { vars: { 'a$': as[0], 'b$': as[1] ?? k(0) }, maps: {}, flags: {} });
394
+ return substE(encX(p, br.op.x(as.map((_, i) => ({ op: 'var', name: `a$${i}` }))), new Map()), { vars: Object.fromEntries(as.map((a, i) => [`a$${i}`, a])), maps: {}, flags: {} });
371
395
  }
372
- if (!recursive(f) && b.unfolded)
396
+ if (!taken(f) && b.unfolded)
373
397
  return inst(`fn ${f.name}`, as) ? factBody(f, as) : undefined;
374
398
  const copy = b.copies.get(f.name);
375
399
  if (!copy)
@@ -447,12 +471,15 @@ function walker(b, fs, nodeOf, own) {
447
471
  };
448
472
  return { walkC, walkE, insts, uses, inst };
449
473
  }
474
+ // A node's rank is (level, the measure's place, 0 or 1), the measure's place as wide as the program's widest measure
475
+ // (core/data.ts's attempt): the zeros after the `n` components given, so every node's rank has one length.
476
+ const pad = (p, n) => Array.from({ length: rankWidth(p) - n }, () => k(0));
450
477
  // The law's node: its conclusion, using the law said through the bridges (at its own variables) and the walk's reasons.
451
478
  function lawNode(l, b, fs, nodeOf, lnode, level) {
452
479
  const w = walker(b, fs, nodeOf), concl = encY(b.p, l.holds, new Map());
453
480
  if (!w.walkC(concl, encY(b.p, b.lstar.holds, new Map())))
454
481
  return undefined;
455
- return { name: `${l.name} (through ${b.lstar.name})`, hyps: [], concl, rank: [k(level), k(0), k(0)], insts: w.insts, uses: [{ node: lnode, subst: {}, guard: yes }, ...w.uses] };
482
+ return { name: `${l.name} (through ${b.lstar.name})`, hyps: [], concl, rank: [k(level), ...pad(b.p, 0), k(0)], insts: w.insts, uses: [{ node: lnode, subst: {}, guard: yes }, ...w.uses] };
456
483
  }
457
484
  // A copy's law, f(xs) = f'(xs), as one node at index `self`: both definitions' facts at xs, their bodies walked together
458
485
  // (f's own recursive calls its copy's by the node itself, at the uses of f's recursion scheme), the shape of the argument
@@ -471,6 +498,6 @@ function copyNode(x, b, fs, nodeOf, self, level) {
471
498
  const on = scheme?.on, size = !on ? k(0) : on.d === 'nat' ? { op: 'var', name: on.v } : { op: 'get', map: `${on.d.name}.size`, key: { op: 'var', name: on.v } };
472
499
  if (on && on.d !== 'nat')
473
500
  w.inst(`shape ${on.d.name}`, [{ op: 'var', name: on.v }]);
474
- return { name: `${x.law.name} (its copy, made)`, hyps: [], concl: encY(b.p, x.law.holds, new Map()), rank: [k(level), size, k(0)], insts: w.insts,
501
+ return { name: `${x.law.name} (its copy, made)`, hyps: [], concl: encY(b.p, x.law.holds, new Map()), rank: [k(level), size, ...pad(b.p, 1), k(0)], insts: w.insts,
475
502
  uses: [...(scheme?.uses ?? []).map(u => ({ node: self, subst: u.subst, guard: u.guard })), ...w.uses] };
476
503
  }
@@ -8,9 +8,11 @@ type XAction = string | {
8
8
  type XTransition = string | {
9
9
  target?: string | string[];
10
10
  guard?: unknown;
11
+ cond?: unknown;
11
12
  actions?: XAction | XAction[];
12
13
  reenter?: boolean;
13
14
  description?: string;
15
+ [k: string]: unknown;
14
16
  };
15
17
  export type XNode = {
16
18
  id?: string;
@@ -41,6 +43,10 @@ export type Bridge = {
41
43
  guards?: Record<string, Guard>;
42
44
  actions?: Record<string, Action>;
43
45
  events?: string[];
46
+ inline?: {
47
+ guards?: ReadonlyMap<unknown, Guard>;
48
+ actions?: ReadonlyMap<unknown, Action>;
49
+ };
44
50
  };
45
51
  export type MachineLike = object;
46
52
  export declare function fromXState(machine: MachineLike, opts?: Bridge): Chart<Obj, Obj, Obj>;
@@ -18,22 +18,57 @@
18
18
  // root, eventless (`always`) and delayed (`after`) transitions, invoked actors and done events, wildcard events, several
19
19
  // targets at once, inline guards and actions, entry and exit actions that write the context, two regions writing the
20
20
  // context on one event (XState runs their actions one after another; a chart's regions write in one step), and a
21
- // shallow history over nested states.
21
+ // shallow history over nested states. So is every key it doesn't read, rather than dropped: a node or transition key
22
+ // outside the lists below (KEYS), an initial transition with actions, an event XState raises itself (done, error, init).
23
+ // An XState v4 machine reads the same, its `cond` the guard v5 calls `guard` (a name, or {type, ...params}); v4's
24
+ // `in`, `strict`, `activities` and eventless `''` are refused with the rest. Each XState ignores the other's guard key,
25
+ // so a v5 machine with `cond` or a v4 one with `guard` is refused (a plain config is read by the key it uses).
22
26
  import { Choice, bool, int } from "./dsl.js";
23
27
  import { chart } from "./chart.js";
28
+ // The keys read, and those that change nothing a run shows (descriptions, metadata, types, a final state's output, v4's
29
+ // action-order flags, which order no write to the context: those a transition makes run in order either way; v5's
30
+ // `reenter` and v4's `internal`, which change only which entry and exit actions run, and those write no context here).
31
+ // Any other is refused, by name, rather than dropped; some with the reason.
32
+ const KEYS = {
33
+ node: new Set(['id', 'type', 'history', 'initial', 'target', 'states', 'on', 'entry', 'exit', 'description', 'meta', 'tags', 'output', 'data']),
34
+ root: new Set(['context', 'version', 'types', 'schemas', 'schema', 'tsTypes', 'predictableActionArguments', 'preserveActionOrder']),
35
+ transition: new Set(['target', 'guard', 'cond', 'actions', 'reenter', 'internal', 'description', 'meta']),
36
+ };
37
+ const WHY = {
38
+ always: '`always` has no chart counterpart', after: '`after` has no chart counterpart', invoke: '`invoke` has no chart counterpart', onDone: '`onDone` has no chart counterpart',
39
+ onError: '`onError` has no chart counterpart', activities: "v4's `activities` have no chart counterpart", strict: "v4's `strict` (an event no state takes throws) has no chart counterpart",
40
+ delimiter: 'a state path delimiter other than "."', onEntry: "v4's `onEntry`: write it as `entry`", onExit: "v4's `onExit`: write it as `exit`",
41
+ in: "v4's `in` guard: write it as a named guard reading env.in(...)",
42
+ };
43
+ const keyCheck = (o, allowed, refuse, also) => {
44
+ for (const k of Object.keys(o))
45
+ if (!allowed.has(k) && !also?.has(k) && o[k] !== undefined)
46
+ refuse(WHY[k] ?? `\`${k}\`, a key fromXState doesn't read (it would be dropped)`);
47
+ };
48
+ // Events XState raises itself (a done state or actor, an error, the start): a chart's events are only those sent.
49
+ const raised = (e) => e === '' || /^(xstate\.|done\.(state|invoke)\.|error\.(platform|execution|communication))/.test(e);
24
50
  const list = (x) => (x === undefined ? [] : Array.isArray(x) ? x : [x]);
25
51
  const configOf = (machine) => ('config' in machine && machine.config && typeof machine.config === 'object' ? machine.config : machine);
52
+ // The XState a machine is of: v5's machines have getInitialSnapshot, v4's withConfig; a plain config says neither.
53
+ const versionOf = (machine) => {
54
+ const m = machine;
55
+ return typeof m.getInitialSnapshot === 'function' ? 5 : typeof m.withConfig === 'function' ? 4 : undefined;
56
+ };
26
57
  export function fromXState(machine, opts = {}) {
27
- const root = configOf(machine), name = root.id ?? 'machine', parallel = root.type === 'parallel';
58
+ const root = configOf(machine), name = root.id ?? 'machine', parallel = root.type === 'parallel', version = versionOf(machine);
28
59
  const refuse = (where, what) => { throw new Error(`${name}: ${where || 'the machine'}: ${what}`); };
29
60
  const infos = [], ids = new Map();
30
61
  const walk = (node, segs, parent) => {
31
62
  const info = { node, segs, parent }, where = segs.join('.');
32
63
  infos.push(info);
33
64
  ids.set(node.id ?? (segs.length ? `${name}.${where}` : name), info);
34
- for (const k of ['always', 'after', 'invoke', 'onDone'])
35
- if (node[k] !== undefined)
36
- refuse(where, `\`${k}\` has no chart counterpart`);
65
+ keyCheck(node, KEYS.node, what => refuse(where, what), segs.length ? undefined : KEYS.root);
66
+ if (node.type !== undefined && !['atomic', 'compound', 'parallel', 'final', 'history'].includes(node.type))
67
+ refuse(where, `the state type ${JSON.stringify(node.type)}`);
68
+ if (node.initial !== undefined && typeof node.initial !== 'string')
69
+ refuse(where, 'an initial transition given as an object (its actions have no chart counterpart): name the initial state');
70
+ if (node.type !== 'history' && (node.history !== undefined || node.target !== undefined))
71
+ refuse(where, '`history` or `target` on a state that is not a history node');
37
72
  if (node.type === 'parallel' && segs.length)
38
73
  refuse(where, 'a parallel state below the root (a chart runs regions only at the top)');
39
74
  for (const [k, kid] of Object.entries(node.states ?? {}))
@@ -75,16 +110,25 @@ export function fromXState(machine, opts = {}) {
75
110
  return at.node.type === 'history' ? { to: at.parent, viaHistory: true } : { to: at, viaHistory: false };
76
111
  };
77
112
  // Guards and actions, named and given again.
78
- const guardOf = (where, g) => {
113
+ // v5's guard: a name or {type, params}; v4's cond: a name or {type, ...params}, its params the object's other keys.
114
+ const guardOf = (where, g, v4 = false) => {
79
115
  if (g === undefined)
80
116
  return undefined;
81
- const [n, params] = typeof g === 'string' ? [g, undefined] : typeof g === 'object' && g && typeof g.type === 'string' ? [g.type, g.params] : [undefined, undefined];
117
+ const given = opts.inline?.guards?.get(g);
118
+ if (given)
119
+ return env => given(env);
120
+ const v4params = (o) => { const { type: _t, ...rest } = o; void _t; return Object.keys(rest).length ? rest : undefined; };
121
+ const [n, params] = typeof g === 'string' ? [g, undefined] : typeof g === 'object' && g && typeof g.type === 'string' ? [g.type, v4 ? v4params(g) : g.params] : [undefined, undefined];
82
122
  if (n === undefined)
83
123
  return refuse(where, `an inline guard${typeof g === 'function' && g.type ? ` (${g.type})` : ''}: name it in setup({guards}) and give its condition in guards`);
84
124
  const f = opts.guards?.[n] ?? refuse(where, `the guard ${n}: give its condition in guards`);
85
125
  return env => f(env, params);
86
126
  };
87
127
  const actionsOf = (where, as) => as.flatMap(a => {
128
+ if (opts.inline?.actions?.has(a)) {
129
+ const f = opts.inline.actions.get(a);
130
+ return f ? [(env) => f(env)] : [];
131
+ }
88
132
  const [n, params] = typeof a === 'string' ? [a, undefined] : typeof a === 'object' && a && typeof a.type === 'string' ? [a.type, a.params] : [undefined, undefined];
89
133
  if (n === undefined)
90
134
  return refuse(where, `an inline action${typeof a === 'function' && a.type ? ` (${a.type})` : ''}: name it in setup({actions}) and give the context it writes in actions`);
@@ -124,7 +168,7 @@ export function fromXState(machine, opts = {}) {
124
168
  c = c.regions(Object.fromEntries(top.map(r => [r.segs[0], nodeOf(r)])));
125
169
  }
126
170
  else
127
- c = c.states(nodeOf(infos[0]).states ?? refuse('', 'no states'), root.initial ? { initial: root.initial } : {});
171
+ c = c.states(nodeOf(infos[0]).states ?? { [STATELESS]: {} }, root.initial ? { initial: root.initial } : {});
128
172
  if (opts.events)
129
173
  c = c.events(...opts.events);
130
174
  // The transitions, in document order (the chart takes the most specific source first, then the first declared, as
@@ -132,20 +176,32 @@ export function fromXState(machine, opts = {}) {
132
176
  const writers = new Map();
133
177
  for (const i of infos)
134
178
  for (const [event, spec] of Object.entries(i.node.on ?? {})) {
135
- const where = `${pathOf(i) || 'the root'} on ${event}`;
179
+ const where = `${pathOf(i) || 'the root'} on ${event || '""'}`;
136
180
  if (event.includes('*'))
137
181
  refuse(where, 'a wildcard event');
182
+ if (raised(event))
183
+ refuse(where, event ? 'an event XState raises itself (a done, error or init event)' : "v4's eventless transition (`''`)");
138
184
  if (spec === undefined)
139
185
  refuse(where, 'a forbidden event (an undefined transition)');
140
186
  for (const t of list(spec)) {
187
+ if (t === null || (typeof t !== 'string' && typeof t !== 'object'))
188
+ refuse(where, `a transition given as ${typeof t === 'function' ? 'a function' : JSON.stringify(t)}`);
141
189
  const o = typeof t === 'string' ? { target: t } : t, targets = list(o.target);
190
+ keyCheck(o, KEYS.transition, what => refuse(where, what));
191
+ if (o.guard !== undefined && o.cond !== undefined)
192
+ refuse(where, 'both `guard` and v4\'s `cond`');
193
+ // (each XState reads its own and takes a transition with the other's unguarded: refused, not taken so)
194
+ if (o.cond !== undefined && version === 5)
195
+ refuse(where, 'v4\'s `cond` in an XState v5 machine, which doesn\'t read it (it takes this transition unguarded): name the guard in `guard`');
196
+ if (o.guard !== undefined && version === 4)
197
+ refuse(where, 'v5\'s `guard` in an XState v4 machine, which doesn\'t read it (it takes this transition unguarded): name the guard in `cond`');
142
198
  if (targets.length > 1)
143
199
  refuse(where, 'several targets at once');
144
200
  const to = targets[0] === undefined ? undefined : resolve(i, targets[0]);
145
- const set = composed(actionsOf(where, list(o.actions))), when = guardOf(where, o.guard);
201
+ const set = composed(actionsOf(where, list(o.actions))), when = o.cond !== undefined ? guardOf(where, o.cond, true) : guardOf(where, o.guard);
146
202
  // Where it applies: its state; for the root, every top state but a final one (XState stops there), or in a
147
203
  // parallel machine the region its target is in (the first region, for one with no target).
148
- const from = i.segs.length ? pathOf(i) : parallel ? (to ? to.to.segs[0] : top[0].segs[0]) : top.filter(x => x.node.type !== 'final' && x.node.type !== 'history').map(pathOf);
204
+ const from = i.segs.length ? pathOf(i) : parallel ? (to ? to.to.segs[0] : top[0].segs[0]) : top.length ? top.filter(x => x.node.type !== 'final' && x.node.type !== 'history').map(pathOf) : STATELESS;
149
205
  if (set) {
150
206
  const region = parallel ? String(list(from)[0]).split('.')[0] : 'state';
151
207
  writers.set(event, (writers.get(event) ?? new Set()).add(region));
@@ -158,6 +214,8 @@ export function fromXState(machine, opts = {}) {
158
214
  refuse(`on ${event}`, `regions ${[...regions].join(' and ')} both write the context (XState runs their actions one after another)`);
159
215
  return c;
160
216
  }
217
+ // A machine with no states (its root's transitions only): one state of the chart's, XState's value {} there.
218
+ const STATELESS = '(machine)';
161
219
  function contextOf(root, given, refuse) {
162
220
  const out = {};
163
221
  if (root.context !== undefined && typeof root.context !== 'object') {
@@ -192,7 +250,7 @@ export function conforms(c, machine, createActor, opts = {}) {
192
250
  const nest = (path) => path.split('.').reduceRight((acc, seg) => (acc === undefined ? seg : { [seg]: acc }), undefined);
193
251
  if (root.type === 'parallel')
194
252
  return Object.fromEntries(Object.keys(root.states ?? {}).filter(k => root.states[k].type !== 'history').map(k => [k, nest(String(d[k]))]));
195
- return nest(String(d.state));
253
+ return d.state === STATELESS ? {} : nest(String(d.state));
196
254
  };
197
255
  const contextKeys = Object.keys((root.context && typeof root.context === 'object' ? root.context : {}));
198
256
  let checked = 0;
@@ -1,3 +1,4 @@
1
+ import { type Lin } from '../core/solver.js';
1
2
  import { type Goal, type Path } from './kernel.js';
2
3
  import { type Outcome } from './prove.js';
3
4
  export declare const cdclStats: {
@@ -32,9 +33,21 @@ export declare const cdclStats: {
32
33
  nodes: number;
33
34
  boundRounds: number;
34
35
  };
36
+ export declare const REFUTED = "refuted, not unfolded";
35
37
  export declare function growCdcl(goal: Goal, root: Path, budget: {
36
38
  nodes: number;
37
39
  until?: number;
38
40
  }, opts?: {
39
41
  maxLeaves?: number;
42
+ model?: boolean;
43
+ wall?: number;
40
44
  }): Outcome;
45
+ export declare function cdclSession(goal: Goal, root: Path, opts?: {
46
+ maxLeaves?: number;
47
+ model?: boolean;
48
+ }): {
49
+ run: (b: {
50
+ nodes: number;
51
+ until?: number;
52
+ }, w?: number, assume?: Lin) => Outcome;
53
+ };