gdp-wired 0.23.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 (40) hide show
  1. package/README.md +12 -2
  2. package/dist/core/bmc.d.ts +13 -2
  3. package/dist/core/bmc.js +390 -18
  4. package/dist/core/cycles.d.ts +23 -0
  5. package/dist/core/cycles.js +104 -54
  6. package/dist/core/data.d.ts +9 -0
  7. package/dist/core/data.js +352 -121
  8. package/dist/core/discover.js +8 -3
  9. package/dist/core/dsl.d.ts +7 -2
  10. package/dist/core/dsl.js +47 -9
  11. package/dist/core/extract-check.d.ts +77 -0
  12. package/dist/core/extract-check.js +785 -0
  13. package/dist/core/extract-ir.d.ts +139 -0
  14. package/dist/core/extract-ir.js +198 -0
  15. package/dist/core/extract-print.d.ts +30 -0
  16. package/dist/core/extract-print.js +426 -0
  17. package/dist/core/extract-read.d.ts +298 -0
  18. package/dist/core/extract-read.js +1298 -0
  19. package/dist/core/extract-shapes.d.ts +13 -0
  20. package/dist/core/extract-shapes.js +993 -0
  21. package/dist/core/extract-xstate.d.ts +34 -0
  22. package/dist/core/extract-xstate.js +320 -0
  23. package/dist/core/extract.d.ts +31 -0
  24. package/dist/core/extract.js +249 -0
  25. package/dist/core/kind.d.ts +30 -0
  26. package/dist/core/kind.js +81 -0
  27. package/dist/core/relation.js +7 -4
  28. package/dist/core/xstate.d.ts +6 -0
  29. package/dist/core/xstate.js +70 -12
  30. package/dist/kernel/cdcl.d.ts +10 -0
  31. package/dist/kernel/cdcl.js +291 -241
  32. package/dist/kernel/kernel.d.ts +15 -0
  33. package/dist/kernel/kernel.js +32 -0
  34. package/dist/kernel/prove.js +14 -3
  35. package/dist/kernel/reader.d.ts +14 -0
  36. package/dist/kernel/reader.js +102 -14
  37. package/dist/lean-kernel/emit.d.ts +28 -1
  38. package/dist/lean-kernel/emit.js +56 -15
  39. package/dist/lean-kernel/library.js +2 -1
  40. package/package.json +12 -3
package/dist/core/data.js CHANGED
@@ -2,7 +2,7 @@ import { substC, substE } from "../kernel/kernel.js";
2
2
  import { proveCyclic } from "./cyclic.js";
3
3
  import { clock, counted, pairedKeys, withDeadline } from "../kernel/prove.js";
4
4
  import { work } from "./solver.js";
5
- import { ranksOfRuns } from "./cycles.js";
5
+ import { rankOfPaths, ranksOfCalls } from "./cycles.js";
6
6
  import { proveThrough, transferPlan } from "./transfer.js";
7
7
  // --- sorts and the AST ------------------------------------------------------------------------------------------------
8
8
  export const self = { self: true };
@@ -405,15 +405,15 @@ function recursion(fn) {
405
405
  }
406
406
  return undefined;
407
407
  };
408
- const got = fn.stated ? undefined : choose(0, []);
408
+ const got = members.some(f => f.stated) ? undefined : choose(0, []);
409
+ const names = members.map(f => f.name);
409
410
  if (!got) {
410
- const why = `${fn.name}: not structural recursion (no parameter whose field every recursive call passes${members.length > 1 ? `, in its ring ${members.map(f => f.name).join(', ')}` : ''}${fn.stated ? '; a measure is given' : ''})`;
411
- if (members.length > 1)
412
- throw new Error(`${why}, and a ring of functions is taken by structural recursion only`);
413
- const t = termination(fn, why);
414
- return { ring: [fn.name], measure: t.measure, termination: t };
411
+ const why = `${fn.name}: not structural recursion (no parameter whose field every recursive call passes${members.length > 1 ? `, in its ring ${names.join(', ')}` : ''}${members.some(f => f.stated) ? '; a measure is given' : ''})`;
412
+ // (each of the ring given its own measure and proofs: Data.lean's wf_fix_unique_ring)
413
+ const ts = termination(members, why);
414
+ members.forEach((f, a) => { f.rec = { ring: names, measure: ts[a].measure, termination: ts[a] }; });
415
+ return { ring: names, measure: ts[0].measure, termination: ts[0] };
415
416
  }
416
- const names = members.map(f => f.name);
417
417
  members.forEach((f, a) => { f.rec = { decreases: got[a], ring: names }; });
418
418
  return { decreases: got[0], ring: names };
419
419
  }
@@ -449,7 +449,14 @@ export function measureX(f, c, args) {
449
449
  return neg.length ? { op: 'sub', a: sum(pos), b: sum(neg) } : sum(pos);
450
450
  }
451
451
  const lexY = (as, bs) => (as.length === 1 ? { op: '<', a: as[0], b: bs[0] } : { op: 'or', xs: [{ op: '<', a: as[0], b: bs[0] }, { op: 'and', xs: [{ op: '=', a: as[0], b: bs[0] }, lexY(as.slice(1), bs.slice(1))] }] });
452
- function callSites(fn) {
452
+ // The measures of a ring, each padded to the longest with components 0 (Data.lean's `lexLt` compares tuples of one length).
453
+ const padded = (ring, ms) => {
454
+ const w = Math.max(...ms.map(m => m.comps.length));
455
+ return ms.map((m, i) => ({ comps: [...m.comps, ...Array.from({ length: w - m.comps.length }, () => ({ coef: ring[i].params.map(() => 0), c: 0 }))] }));
456
+ };
457
+ const ringText = (ring, ms) => (ring.length === 1 ? showMeasure(ring[0], ms[0]) : ring.map((f, i) => `${f.name} ${showMeasure(f, ms[i])}`).join(', '));
458
+ const callSites = (ring) => ring.flatMap((f, from) => sitesOf(f, ring.map(g => g.name)).map(s => ({ ...s, from })));
459
+ function sitesOf(fn, names) {
453
460
  const out = [], yesX = { op: 'bool', c: yes.y };
454
461
  const at = (sh, name) => { let t = sh.get(name); while (t && t.op === 'var' && sh.has(t.name))
455
462
  t = sh.get(t.name); return t; };
@@ -517,8 +524,8 @@ function callSites(fn) {
517
524
  return;
518
525
  case 'call':
519
526
  x.args.forEach(a => goX(a, w));
520
- if (x.fn === fn.name)
521
- out.push({ args: x.args, ...w });
527
+ if (names.includes(x.fn))
528
+ out.push({ to: names.indexOf(x.fn), args: x.args, ...w });
522
529
  return;
523
530
  case 'if':
524
531
  goY(x.c, w);
@@ -561,25 +568,30 @@ function callSites(fn) {
561
568
  goX(fn.body(), { wrap: y => y, shape: new Map(), vars: fn.params.map(q => ({ name: `${fn.name}.${q.name}`, sort: q.sort })) });
562
569
  return out;
563
570
  }
564
- // The obligation of a call: under its path, the measure at its arguments below the measure at the parameters, a law over
565
- // the path's variables (the parameters not matched, the fields of the cases taken).
566
- function obligation(fn, m, s, i) {
567
- const own = fn.params.map(q => ({ op: 'var', name: `${fn.name}.${q.name}` }));
568
- const shaped = (t) => (Array.isArray(t) ? t.map(shaped) : t && typeof t === 'object' ? (t.op === 'var' && s.shape.has(t.name) ? shaped(s.shape.get(t.name)) : Object.fromEntries(Object.entries(t).map(([key, v]) => [key, shaped(v)]))) : t);
569
- const holds = shaped(s.wrap(lexY(m.comps.map(c => measureX(fn, c, s.args)), m.comps.map(c => measureX(fn, c, own)))));
570
- return { name: `${fn.name}'s call ${i + 1} lowers ${showMeasure(fn, m)}`, vars: s.vars.filter(v => !s.shape.has(v.name)), holds, params: [...new Set(paramsIn(holds))] };
571
+ // A term (or a law) with the site's shape put in: each matched variable its constructor's value.
572
+ const shapedBy = (s) => {
573
+ const go = (t) => (Array.isArray(t) ? t.map(go) : t && typeof t === 'object' ? (t.op === 'var' && s.shape.has(t.name) ? go(s.shape.get(t.name)) : Object.fromEntries(Object.entries(t).map(([key, v]) => [key, go(v)]))) : t);
574
+ return go;
575
+ };
576
+ const ownArgs = (f) => f.params.map(q => ({ op: 'var', name: `${f.name}.${q.name}` }));
577
+ // The obligation of a call: under its path, the callee's measure at its arguments below the caller's at its parameters,
578
+ // a law over the path's variables (the parameters not matched, the fields of the cases taken). `i`: the call's place
579
+ // among its caller's.
580
+ function obligation(ring, ms, s, i) {
581
+ const fn = ring[s.from], to = ring[s.to];
582
+ const holds = shapedBy(s)(s.wrap(lexY(ms[s.to].comps.map(c => measureX(to, c, s.args)), ms[s.from].comps.map(c => measureX(fn, c, ownArgs(fn))))));
583
+ const name = ring.length === 1 ? `${fn.name}'s call ${i + 1} lowers ${showMeasure(fn, ms[0])}` : `${fn.name}'s call ${i + 1}, of ${to.name}, lowers ${showMeasure(to, ms[s.to])} below ${showMeasure(fn, ms[s.from])}`;
584
+ return { name, vars: s.vars.filter(v => !s.shape.has(v.name)), holds, params: [...new Set(paramsIn(holds))] };
571
585
  }
572
- // The calls the function's runs make, each from its parameters' sizes to its arguments' (random arguments, up to 2,000
573
- // calls a run: a run past that is cut, its calls kept).
574
586
  let tracing;
575
- function runEdges(fn) {
587
+ const featOf = (f, vs) => f.params.map((p, i) => (p.sort === 'nat' ? vs[i] : p.sort instanceof Data ? sizeOf(p.sort, vs[i]) : 0));
588
+ function runEdges(ring) {
576
589
  const rand = rng(17), edges = new Map();
577
- const feat = (vs) => fn.params.map((p, i) => (p.sort === 'nat' ? vs[i] : p.sort instanceof Data ? sizeOf(p.sort, vs[i]) : 0));
578
590
  const tables = new Map();
579
591
  const params = new Proxy({}, { get: (_, key) => tables.get(key) ?? (tables.set(key, randomFn(rand)), tables.get(key)) });
580
- for (let i = 0; i < 120 && edges.size < 400; i++) {
581
- const vals = fn.params.map(p => randomValue(p.sort, rand, 1 + (i % 7)));
582
- tracing = { fn: fn.name, stack: [], fuel: 2000, edge: (a, b) => { const e = { s: feat(a), t: feat(b) }; edges.set(JSON.stringify(e), e); } };
592
+ for (let i = 0; i < 120 * ring.length && edges.size < 400 * ring.length; i++) {
593
+ const fn = ring[i % ring.length], vals = fn.params.map(p => randomValue(p.sort, rand, 1 + (Math.floor(i / ring.length) % 7)));
594
+ tracing = { fns: new Map(ring.map((g, j) => [g.name, j])), stack: [], fuel: 2000, edge: (a, b) => { const e = { from: a.at, to: b.at, s: featOf(ring[a.at], a.vals), t: featOf(ring[b.at], b.vals) }; edges.set(JSON.stringify(e), e); } };
583
595
  try {
584
596
  evalX({ op: 'call', fn: fn.name, args: vals.map((_, j) => ({ op: 'var', name: `$a${j}` })) }, new Map(vals.map((v, j) => [`$a${j}`, v])), params);
585
597
  }
@@ -591,46 +603,191 @@ function runEdges(fn) {
591
603
  return [...edges.values()];
592
604
  }
593
605
  const valueOf = (c, xs) => Math.max(0, c.coef.reduce((a, k, i) => a + k * xs[i], c.c));
594
- const lowers = (m, e) => {
595
- for (const c of m.comps) {
596
- const a = valueOf(c, e.t), b = valueOf(c, e.s);
597
- if (a < b)
606
+ const lowers = (ms, e) => {
607
+ const a = ms[e.to], b = ms[e.from];
608
+ for (const [j, c] of a.comps.entries()) {
609
+ const x = valueOf(c, e.t), y = valueOf(b.comps[j], e.s);
610
+ if (x < y)
598
611
  return true;
599
- if (a > b)
612
+ if (x > y)
600
613
  return false;
601
614
  }
602
615
  return false;
603
616
  };
604
- function candidates(fn, edges) {
605
- if (fn.stated)
606
- return [fn.stated];
607
- const ix = fn.params.flatMap((p, i) => (measurable(p.sort) ? [i] : [])), n = fn.params.length;
608
- const one = (i) => ({ coef: fn.params.map((_, j) => (j === i ? 1 : 0)), c: 0 }), sum = (is) => ({ coef: fn.params.map((_, j) => (is.includes(j) ? 1 : 0)), c: 0 });
609
- const out = ix.map(i => ({ comps: [one(i)] }));
610
- for (const i of ix)
611
- for (const j of ix)
612
- if (i !== j)
613
- out.push({ comps: [one(i), one(j)] });
614
- for (const [a, i] of ix.entries())
615
- for (const j of ix.slice(a + 1))
616
- out.push({ comps: [sum([i, j])] });
617
- if (ix.length <= 4)
618
- for (const i of ix)
619
- for (const j of ix)
620
- for (const k of ix)
621
- if (i !== j && j !== k && i !== k)
622
- out.push({ comps: [one(i), one(j), one(k)] });
623
- if (ix.length > 2)
624
- out.push({ comps: [sum(ix)] });
625
- // The LP's rank over the runs (coefficients and constants), where the runs give edges.
626
- if (edges.length) {
627
- const vars = ix.map(i => `p${i}`), env = (xs) => Object.fromEntries(ix.map(i => [`p${i}`, xs[i]]));
628
- const r = ranksOfRuns(vars, edges.flatMap(e => [env(e.s), env(e.t)]), edges.map(e => ({ s: env(e.s), t: env(e.t) })));
629
- if (!r.left && r.comps.length)
630
- out.push({ comps: r.comps.map(c => ({ coef: Array.from({ length: n }, (_, j) => c.coef[`p${j}`] ?? 0), c: c.c })) });
617
+ const sizeOfValue = (s, v) => (s === 'nat' ? v : s instanceof Data ? sizeOf(s, v) : 0);
618
+ function sizeBounds(t, sort, vars, envs, coef = 1) {
619
+ const ms = vars.flatMap((v, i) => (measurable(v.sort) ? [i] : [])), at = [];
620
+ for (const s of envs) {
621
+ try {
622
+ at.push({ t: coef * sizeOfValue(sort, evalX(t, s.env, s.params)), v: vars.map(v => sizeOfValue(v.sort, s.env.get(v.name))) });
623
+ }
624
+ catch { /* past the bounds */ }
625
+ }
626
+ if (at.length < 12)
627
+ return [];
628
+ const sets = [...ms.map(i => [i]), ...ms.flatMap((i, a) => ms.slice(a + 1).map(j => [i, j]))];
629
+ return sets.map(of => { const d = at.map(p => p.t - of.reduce((s, i) => s + p.v[i], 0)); return { of, lo: Math.min(...d), hi: Math.max(...d), coef }; });
630
+ }
631
+ // The upper bounds worth stating: an equation where there is one (its fewest variables), else each set's whose bound is
632
+ // small, none another of fewer variables implies (each size is at least 0).
633
+ const upperBounds = (bs, most = 3) => {
634
+ const exact = bs.filter(b => b.lo === b.hi).sort((a, b) => a.of.length - b.of.length);
635
+ if (exact.length)
636
+ return [exact[0]];
637
+ const ok = bs.filter(b => b.hi <= 2).sort((a, b) => a.of.length - b.of.length || a.hi - b.hi);
638
+ return ok.filter(b => !ok.some(c => c !== b && c.of.length < b.of.length && c.of.every(i => b.of.includes(i)) && c.hi <= b.hi)).slice(0, most);
639
+ };
640
+ // The values of a law's variables where its path holds (`cond`: false where it doesn't).
641
+ // (naturals up to 40: a guard n ≥ 12 is met)
642
+ const pathSamples = (vars, params, cond, n = 240, seed = 19) => {
643
+ const rand = rng(seed), out = [];
644
+ for (let i = 0; i < n; i++) {
645
+ const s = { env: new Map(vars.map(v => [v.name, randomValue(v.sort, rand, 1 + (i % 7), i % 2 ? 40 : 5)])), params: Object.fromEntries(params.map(p => [p, randomFn(rand)])) };
646
+ try {
647
+ if (cond(s))
648
+ out.push(s);
649
+ }
650
+ catch { /* past the bounds */ }
651
+ }
652
+ return out;
653
+ };
654
+ // Size laws about the functions a law reads (not the ring's): for each, S(g(y…)) + a ≤ Σ S(yᵢ) + b over one or two of
655
+ // its arguments, the bound the values give (an equation where they give one difference), 2·g(n) ≤ n + b for a natural
656
+ // of one natural, those its values refute dropped; each a lemma for proveData to prove by induction and use.
657
+ function sizeLaws(l, ring) {
658
+ const seen = new Set(), helpers = [];
659
+ walk(l.holds, o => { if (o.op === 'call' && !ring.includes(o.fn) && !seen.has(o.fn)) {
660
+ seen.add(o.fn);
661
+ const g = fnOf(o.fn);
662
+ if (measurable(g.ret))
663
+ helpers.push(g);
664
+ } });
665
+ const out = [];
666
+ const nat = (n) => ({ op: 'nat', value: n }), add = (a, b) => (b.op === 'nat' && b.value === 0 ? a : { op: 'add', a, b });
667
+ for (const g of helpers.slice(0, 4)) {
668
+ const vars = g.params.map((q, i) => ({ name: `${q.name}${i}`, sort: q.sort }));
669
+ if (!vars.some(v => measurable(v.sort)))
670
+ continue;
671
+ const call = { op: 'call', fn: g.name, args: vars.map(v => ({ op: 'var', name: v.name })) }, envs = samples(vars, [], 160, 23);
672
+ const twice = g.ret === 'nat' && vars.length === 1 && vars[0].sort === 'nat' ? upperBounds(sizeBounds(call, g.ret, vars, envs, 2), 1).filter(b => b.lo !== b.hi) : [];
673
+ for (const b of [...upperBounds(sizeBounds(call, g.ret, vars, envs)), ...twice]) {
674
+ const lhs0 = b.coef === 1 ? sizeX(g.ret, call) : { op: 'mul', k: b.coef, a: sizeX(g.ret, call) };
675
+ const sum = b.of.map(i => sizeX(vars[i].sort, { op: 'var', name: vars[i].name })).reduce((a, c) => ({ op: 'add', a, b: c }));
676
+ const lhs = add(lhs0, nat(Math.max(0, -b.hi))), rhs = add(sum, nat(Math.max(0, b.hi)));
677
+ // (an upper bound is what a decrease reads: an equation's other half is a proof's cost for nothing)
678
+ const holds = { op: '<=', a: lhs, b: rhs };
679
+ out.push({ name: `size law: ${showY(holds)}`, vars, holds, params: [] });
680
+ }
631
681
  }
632
682
  return out;
633
683
  }
684
+ // The calls' relation (core/relation.ts's form): a location per function of the ring, its parameters' sizes the state
685
+ // (`s<i>_<k>`), a path per call: the caller's parameters' sizes and the callee's arguments' (`a<k>`, the turn's
686
+ // inputs) bounded by the sizes of the path's variables (`v<j>`) where its values give a bound (`sizeBounds`).
687
+ function callRelation(ring, sites) {
688
+ const slot = (i, k) => `s${i}_${k}`;
689
+ const state = ring.flatMap((f, i) => f.params.flatMap((q, k) => (measurable(q.sort) ? [slot(i, k)] : [])));
690
+ const paths = [], nats = new Set(state), from = [], to = [];
691
+ for (const s of sites) {
692
+ const caller = ring[s.from], callee = ring[s.to], shaped = shapedBy(s);
693
+ const vars = s.vars.filter(v => !s.shape.has(v.name)), names = vars.map((_, j) => `v${j}`);
694
+ const cond = shaped(s.wrap(no.y));
695
+ const envs = pathSamples(vars, [...new Set(paramsIn([cond, s.args]))], sm => !evalY(cond, sm.env, sm.params));
696
+ if (envs.length < 12)
697
+ continue;
698
+ const rows = vars.flatMap((v, j) => (v.sort instanceof Data ? [{ [names[j]]: -1, 1: 1 }] : []));
699
+ const bounded = (x, t, sort) => {
700
+ const bs = sizeBounds(shaped(t), sort, vars, envs), exact = bs.filter(b => b.lo === b.hi).sort((a, b) => a.of.length - b.of.length)[0];
701
+ const lin = (b, c) => { const o = { [x]: 1 }; for (const i of b.of)
702
+ o[names[i]] = (o[names[i]] ?? 0) - 1; if (c)
703
+ o['1'] = -c; return o; };
704
+ if (exact) {
705
+ rows.push(lin(exact, exact.hi), Object.fromEntries(Object.entries(lin(exact, exact.hi)).map(([y, c]) => [y, -c])));
706
+ return;
707
+ }
708
+ for (const b of upperBounds(bs))
709
+ rows.push(lin(b, b.hi));
710
+ };
711
+ caller.params.forEach((q, k) => { if (measurable(q.sort))
712
+ bounded(slot(s.from, k), ownArgs(caller)[k], q.sort); });
713
+ const post = {};
714
+ callee.params.forEach((q, k) => { if (!measurable(q.sort))
715
+ return; const a = `a${k}`; nats.add(a); bounded(a, s.args[k], q.sort); post[slot(s.to, k)] = { [a]: 1 }; });
716
+ names.forEach(x => nats.add(x));
717
+ paths.push({ rows, pins: { $fn: s.from }, post });
718
+ from.push(s.from);
719
+ to.push(s.to);
720
+ }
721
+ if (!paths.length)
722
+ return undefined;
723
+ return { paths, ints: new Map(), nats: [...nats], state, params: [], loc: '$fn', from, to, exact: false };
724
+ }
725
+ function candidates(ring, edges, sites, until) {
726
+ if (ring.some(f => f.stated))
727
+ return [ring.map(f => f.stated ?? { comps: [{ coef: f.params.map(() => 0), c: 0 }] })];
728
+ const out = [];
729
+ if (ring.length === 1) {
730
+ const fn = ring[0], ix = fn.params.flatMap((p, i) => (measurable(p.sort) ? [i] : []));
731
+ const one = (i) => ({ coef: fn.params.map((_, j) => (j === i ? 1 : 0)), c: 0 }), sum = (is) => ({ coef: fn.params.map((_, j) => (is.includes(j) ? 1 : 0)), c: 0 });
732
+ const ms = ix.map(i => ({ comps: [one(i)] }));
733
+ for (const i of ix)
734
+ for (const j of ix)
735
+ if (i !== j)
736
+ ms.push({ comps: [one(i), one(j)] });
737
+ for (const [a, i] of ix.entries())
738
+ for (const j of ix.slice(a + 1))
739
+ ms.push({ comps: [sum([i, j])] });
740
+ if (ix.length <= 4)
741
+ for (const i of ix)
742
+ for (const j of ix)
743
+ for (const k2 of ix)
744
+ if (i !== j && j !== k2 && i !== k2)
745
+ ms.push({ comps: [one(i), one(j), one(k2)] });
746
+ if (ix.length > 2)
747
+ ms.push({ comps: [sum(ix)] });
748
+ out.push(...ms.map(m => [m]));
749
+ }
750
+ // The LP's rank over the runs (coefficients and constants), a node per function, where the runs give edges; for a ring,
751
+ // after the relation's.
752
+ const fromRuns = () => {
753
+ if (!edges.length)
754
+ return undefined;
755
+ const vars = ring.map((f, i) => f.params.flatMap((q, j) => (measurable(q.sort) ? [`p${i}_${j}`] : [])));
756
+ const env = (i, xs) => Object.fromEntries(vars[i].map(x => [x, xs[Number(x.split('_')[1])]]));
757
+ const r = ranksOfCalls(vars, edges.flatMap(e => [{ node: e.from, env: env(e.from, e.s) }, { node: e.to, env: env(e.to, e.t) }]), edges.map(e => ({ from: e.from, to: e.to, s: env(e.from, e.s), t: env(e.to, e.t) })));
758
+ if (r.left || !r.comps.length)
759
+ return undefined;
760
+ return ring.map((f, i) => ({ comps: r.comps.map(c => ({ coef: f.params.map((_, j) => c[i].coef[`p${i}_${j}`] ?? 0), c: c[i].c })) }));
761
+ };
762
+ // The relation's rank: per location (each function), its components' forms over the function's parameters' sizes.
763
+ const fromRelation = () => {
764
+ const rel = callRelation(ring, sites);
765
+ if (!rel)
766
+ return undefined;
767
+ const r = rankOfPaths(ring.map(f => f.name).join(', '), rel, Math.min(until, clock() + 2000));
768
+ if (!('forms' in r) || !r.forms.length)
769
+ return undefined;
770
+ const ms = ring.map((f, i) => {
771
+ const n = r.values.indexOf(i);
772
+ return n < 0 ? { comps: r.forms.map(() => ({ coef: f.params.map(() => 0), c: 0 })) } : { comps: r.forms.map(col => ({ coef: f.params.map((_, k) => col[n][`s${i}_${k}`] ?? 0), c: col[n]['1'] ?? 0 })) };
773
+ });
774
+ // (a form that reads another function's parameters isn't a measure of this one's)
775
+ return r.forms.every(col => col.every((l, n) => Object.keys(l).every(x => x === '1' || x.startsWith(`s${r.values[n]}_`)))) ? ms : undefined;
776
+ };
777
+ const runs = ring.length === 1 ? fromRuns() : undefined;
778
+ if (runs)
779
+ out.push(runs);
780
+ const rel = fromRelation();
781
+ if (rel)
782
+ out.push(rel);
783
+ const runs2 = ring.length > 1 ? fromRuns() : undefined;
784
+ if (runs2)
785
+ out.push(runs2);
786
+ // (a ring's last: each function the sum of its parameters' sizes)
787
+ if (ring.length > 1)
788
+ out.push(ring.map(f => ({ comps: [{ coef: f.params.map(q => (measurable(q.sort) ? 1 : 0)), c: 0 }] })));
789
+ return out.map(ms => padded(ring, ms));
790
+ }
634
791
  // An obligation as one node of a cyclic proof (no use, no models): its conclusion, each definition it reads unfolded
635
792
  // once, the constructors' facts at the values built, the shape at each size it reads and at its variables of a
636
793
  // datatype, the congruences 16 random models' explanations use. The kernel checks it as any cyclic proof; undefined where it isn't proven.
@@ -651,70 +808,104 @@ function directly(law, ms) {
651
808
  pairedKeys.skip = was;
652
809
  }
653
810
  }
654
- function termination(fn, why) {
811
+ // Each call's obligation under measures given, proven (`obligations`, each function's) or the first that isn't (`failed`).
812
+ function proveMeasures(ring, sites, ms, until) {
813
+ const names = ring.map(f => f.name), text = ringText(ring, ms);
814
+ const nth = sites.map((s, i) => sites.slice(0, i).filter(r => r.from === s.from).length);
815
+ const obligations = ring.map(() => []);
816
+ for (const [i, site] of sites.entries()) {
817
+ const law = obligation(ring, ms, site, nth[i]), call = `${ring.length > 1 ? `${names[site.from]}'s ` : ''}call ${nth[i] + 1}`;
818
+ // (no call of the ring in it: refused before)
819
+ walk(law.holds, o => { if (o.op === 'call' && names.includes(o.fn))
820
+ throw new Error(`${law.name} reads the ring`); });
821
+ // First one node, the definitions unfolded once (most calls lower the measure by their cases alone); then, where its
822
+ // call is on a function of the argument, size laws about those functions proven by induction and used; else, or
823
+ // then, proveData: by induction where the obligation has a scheme (a call on a filter of the tail: the filter's own
824
+ // recursion), else, or then, the definitions unfolded alone.
825
+ const left = () => Math.max(1, until - clock()), cex = refute(law, 200);
826
+ if (cex)
827
+ return { failed: `${text}: its ${call} doesn't lower it at ${JSON.stringify(cex)}` };
828
+ const direct = directly(law, Math.min(2000, left()));
829
+ if (direct) {
830
+ obligations[site.from].push({ law, proof: direct, lemmas: [] });
831
+ continue;
832
+ }
833
+ // (the size laws first, each proven once and used, within 60% of the time left; then proveData without conjectured
834
+ // lemmas, whose making isn't counted in the budget: by induction, then the definitions unfolded alone)
835
+ const inductive = schemes(programOf([law]), law).length > 0, lemmas = sizeLaws(law, names);
836
+ if (dataTrace && lemmas.length)
837
+ console.error(`[data] ${law.name}: ${lemmas.map(c => c.name).join('; ')}`);
838
+ let v = lemmas.length ? proveData(law, { lemmas, lemmasFirst: true, ms: Math.min(8000, 0.6 * left()) }) : undefined;
839
+ if (!v?.proven && !v?.counterexample && inductive && clock() < until)
840
+ v = proveData(law, { ms: Math.min(12_000, left()), lemmas: false });
841
+ if (!v?.proven && !v?.counterexample && clock() < until)
842
+ v = proveData(law, { induction: false, ms: Math.min(4000, left()) });
843
+ if (!v || !(v.proven && v.checked))
844
+ return { failed: `${text}: its ${call} ${v?.counterexample ? `doesn't lower it at ${JSON.stringify(v.counterexample)}` : 'not proven to lower it'}` };
845
+ const used = v;
846
+ obligations[site.from].push({ law, proof: used.proof, scheme: used.scheme, lemmas: used.lemmas, lemmaLaws: lemmas.filter(c => used.lemmas.includes(c.name)) });
847
+ }
848
+ return { obligations };
849
+ }
850
+ // A ring's calls, refused where one is nested in another's argument or condition (its obligation would read a function
851
+ // being taken).
852
+ function ringSites(ring, why) {
853
+ const names = ring.map(f => f.name), sites = callSites(ring);
854
+ for (const st of sites) {
855
+ let nested = false;
856
+ walk([st.args, st.wrap(no.y)], o => { if (o.op === 'call' && names.includes(o.fn))
857
+ nested = true; });
858
+ if (nested)
859
+ throw new Error(`${why}, and a call to ${ring.length > 1 ? 'its ring' : 'itself'} is nested in the argument or the condition of another (nested recursion isn't taken)`);
860
+ }
861
+ return sites;
862
+ }
863
+ // Measures given to a ring (or a function) checked as `termination` checks the one it takes: each call's obligation
864
+ // proven by the kernel, within the counted budget; nothing is taken (core/conformance.ts: tampered measures refused).
865
+ export function checkMeasures(fns, ms, budget = terminationMs.ms) {
655
866
  return counted(dataRate, () => {
867
+ const r = proveMeasures(fns, ringSites(fns, fns.map(f => f.name).join(', ')), padded(fns, ms), clock() + budget);
868
+ return 'failed' in r ? { proven: false, why: r.failed } : { proven: true, obligations: r.obligations };
869
+ });
870
+ }
871
+ // The ring's measures and each call's proof, or a refusal with the measures tried. A ring of one is a function.
872
+ function termination(ring, why) {
873
+ return counted(dataRate, () => {
874
+ const names = ring.map(f => f.name);
656
875
  if (dataTrace)
657
- console.error(`[data] termination of ${fn.name}`);
658
- const t0 = performance.now(), sites = callSites(fn);
659
- if (!fn.params.some(p => measurable(p.sort)))
660
- throw new Error(`${why}, and it has no parameter a measure reads (a natural or a datatype value)`);
876
+ console.error(`[data] termination of ${names.join(', ')}`);
877
+ const t0 = performance.now();
878
+ if (!ring.some(f => f.params.some(p => measurable(p.sort))))
879
+ throw new Error(`${why}, and ${ring.length === 1 ? 'it has' : 'its ring has'} no parameter a measure reads (a natural or a datatype value)`);
880
+ const sites = ringSites(ring, why);
661
881
  if (dataTrace)
662
882
  console.error(`[data] ${sites.length} calls`);
663
- const edges = runEdges(fn), until = clock() + terminationMs.ms, tried = [], seen = new Set();
883
+ const edges = runEdges(ring), until = clock() + terminationMs.ms * ring.length, tried = [], seen = new Set();
664
884
  if (dataTrace)
665
885
  console.error(`[data] its runs: ${edges.length} calls at ${Math.round(performance.now() - t0)} ms`);
666
- for (const m of candidates(fn, edges)) {
886
+ for (const ms of candidates(ring, edges, sites, until)) {
887
+ const text = ringText(ring, ms);
667
888
  if (dataTrace)
668
- console.error(`[data] ${showMeasure(fn, m)} at ${Math.round(performance.now() - t0)} ms`);
889
+ console.error(`[data] ${text} at ${Math.round(performance.now() - t0)} ms`);
669
890
  if (clock() > until) {
670
891
  tried.push('out of time');
671
892
  break;
672
893
  }
673
- const text = showMeasure(fn, m), bad = edges.find(e => !lowers(m, e));
894
+ const bad = edges.find(e => !lowers(ms, e));
674
895
  if (seen.has(text))
675
896
  continue;
676
897
  seen.add(text);
677
898
  if (bad) {
678
- if (fn.stated || !tried.length)
679
- tried.push(`${text}: a call of its runs doesn't lower it (from ${JSON.stringify(bad.s)} to ${JSON.stringify(bad.t)}, the parameters' sizes)`);
899
+ if (ring.some(f => f.stated) || !tried.length)
900
+ tried.push(`${text}: a call of its runs doesn't lower it (from ${JSON.stringify(bad.s)} to ${JSON.stringify(bad.t)}, the parameters' sizes${ring.length > 1 ? `, ${names[bad.from]} to ${names[bad.to]}` : ''})`);
680
901
  continue;
681
902
  }
682
- const obligations = [];
683
- let failed;
684
- for (const [i, site] of sites.entries()) {
685
- const law = obligation(fn, m, site, i);
686
- // A call nested in its own argument or condition: the obligation would read the function being taken.
687
- if (programOf([law]).fns.some(g => g.name === fn.name))
688
- throw new Error(`${why}, and a call to itself is nested in the argument or the condition of another (nested recursion isn't taken)`);
689
- // First one node, the definitions unfolded once (most calls lower the measure by their cases alone); else
690
- // proveData: by induction where the obligation has a scheme (a call on a filter of the tail: the filter's own
691
- // recursion), else, or then, the definitions unfolded alone.
692
- const left = () => Math.max(1, until - clock()), cex = refute(law, 200);
693
- if (cex) {
694
- failed = `${text}: its call ${i + 1} doesn't lower it at ${JSON.stringify(cex)}`;
695
- break;
696
- }
697
- const direct = directly(law, Math.min(2000, left()));
698
- if (direct) {
699
- obligations.push({ law, proof: direct, lemmas: [] });
700
- continue;
701
- }
702
- const inductive = schemes(programOf([law]), law).length > 0;
703
- // (no conjectured lemmas: their making isn't counted in the budget, and a call's decrease mostly needs none)
704
- let v = proveData(law, inductive ? { ms: Math.min(12_000, left()), lemmas: false } : { induction: false, ms: Math.min(4000, left()) });
705
- if (inductive && !(v.proven && v.checked) && !v.counterexample && clock() < until)
706
- v = proveData(law, { induction: false, ms: Math.min(4000, left()) });
707
- if (!(v.proven && v.checked)) {
708
- failed = `${text}: its call ${i + 1} ${v.counterexample ? `doesn't lower it at ${JSON.stringify(v.counterexample)}` : 'not proven to lower it'}`;
709
- break;
710
- }
711
- obligations.push({ law, proof: v.proof, scheme: v.scheme, lemmas: v.lemmas });
712
- }
713
- if (!failed)
714
- return { measure: m, text, obligations, ms: Math.round(performance.now() - t0) };
715
- tried.push(failed);
903
+ const r = proveMeasures(ring, sites, ms, until);
904
+ if ('obligations' in r)
905
+ return ring.map((f, i) => ({ measure: ms[i], text: showMeasure(f, ms[i]), obligations: r.obligations[i], ms: Math.round(performance.now() - t0) }));
906
+ tried.push(r.failed);
716
907
  }
717
- throw new Error(`${why}, and no measure is proven to fall at every call${tried.length ? ` (${tried.slice(0, 3).join('; ')})` : ''}`);
908
+ throw new Error(`${why}, and no measure is proven to fall at every call${ring.length > 1 ? ' within the ring' : ''}${tried.length ? ` (${tried.slice(0, 3).join('; ')})` : ' (no measure found to try)'}`);
718
909
  });
719
910
  }
720
911
  export function law(name, vars, holds) {
@@ -794,16 +985,17 @@ export function evalX(x, env, params, d = 0) {
794
985
  if (d >= evalBounds.depth || ++evalCalls > evalBounds.calls)
795
986
  throw new EvalLimit(`${f.name}: past the evaluation's bounds`);
796
987
  }
797
- if (tracing?.fn !== f.name)
988
+ const at = tracing?.fns.get(f.name);
989
+ if (at === undefined)
798
990
  return evalX(body, e2, params, d + 1);
799
- // A run of a function whose termination is being proven: each call recorded, the run cut past its fuel.
991
+ // A run of a ring whose termination is being proven: each call within it recorded, the run cut past its fuel.
800
992
  const t = tracing;
801
993
  if (--t.fuel < 0)
802
994
  throw new RangeError('out of fuel');
803
- const top = t.stack.at(-1);
995
+ const top = t.stack.at(-1), frame = { at, vals };
804
996
  if (top)
805
- t.edge(top, vals);
806
- t.stack.push(vals);
997
+ t.edge(top, frame);
998
+ t.stack.push(frame);
807
999
  try {
808
1000
  return evalX(body, e2, params, d + 1);
809
1001
  }
@@ -1523,34 +1715,42 @@ function schemes(p, l) {
1523
1715
  const d = f.params[f.decreases ?? 0].sort;
1524
1716
  const formal = new Map(f.params.map((q, i) => [`${f.name}.${q.name}`, args[i].op === 'var' && l.vars.some(v => v.name === args[i].name) ? ev(args[i].name) : undefined]));
1525
1717
  const uses = [];
1526
- const go = (x, env, guard) => {
1718
+ // (`through`: the functions of f's ring whose bodies are read in place of their calls, once each: evens through
1719
+ // odds, which call each other, is recursion of evens at the tail's tail)
1720
+ const go = (x, env, guard, through = new Set()) => {
1527
1721
  if (!x || typeof x !== 'object')
1528
1722
  return;
1529
1723
  if (Array.isArray(x)) {
1530
- x.forEach(y => go(y, env, guard));
1724
+ x.forEach(y => go(y, env, guard, through));
1531
1725
  return;
1532
1726
  }
1533
1727
  const t = x;
1728
+ if (t.op === 'call' && t.fn !== f.name && f.ring.includes(t.fn) && !through.has(t.fn)) {
1729
+ const g = fnOf(t.fn);
1730
+ go(t.args, env, guard, through);
1731
+ go(g.body(), new Map([...env, ...g.params.map((q, i) => [`${g.name}.${q.name}`, encX(p, t.args[i], env)])]), guard, new Set([...through, t.fn]));
1732
+ return;
1733
+ }
1534
1734
  if (t.op === 'match') {
1535
- go(t.of, env, guard);
1735
+ go(t.of, env, guard, through);
1536
1736
  const dd = dataOf(p, t.data), of = encX(p, t.of, env);
1537
- t.cases.forEach((c, j) => { const e2 = new Map(env); c.binds.forEach((b, i) => e2.set(b, get(fieldMap(dd, j, i), of))); go(c.body, e2, [...guard, eqC(get(tagMap(dd.name), of), k(j))]); });
1737
+ t.cases.forEach((c, j) => { const e2 = new Map(env); c.binds.forEach((b, i) => e2.set(b, get(fieldMap(dd, j, i), of))); go(c.body, e2, [...guard, eqC(get(tagMap(dd.name), of), k(j))], through); });
1538
1738
  return;
1539
1739
  }
1540
1740
  if (t.op === 'natmatch') {
1541
- go(t.of, env, guard);
1741
+ go(t.of, env, guard, through);
1542
1742
  const of = encX(p, t.of, env), e2 = new Map(env);
1543
- go(t.zero, env, [...guard, eqC(of, k(0))]);
1743
+ go(t.zero, env, [...guard, eqC(of, k(0))], through);
1544
1744
  e2.set(t.pred, { op: 'sub', a: of, b: k(1) });
1545
- go(t.succ, e2, [...guard, { op: 'not', x: eqC(of, k(0)) }]);
1745
+ go(t.succ, e2, [...guard, { op: 'not', x: eqC(of, k(0)) }], through);
1546
1746
  return;
1547
1747
  }
1548
1748
  // (a well-founded call's descent may need its if's condition: x − y below x where y ≤ x)
1549
1749
  if (m && t.op === 'if') {
1550
1750
  const c = encY(p, t.c, env);
1551
- go(t.c, env, guard);
1552
- go(t.then, env, [...guard, c]);
1553
- go(t.else, env, [...guard, { op: 'not', x: c }]);
1751
+ go(t.c, env, guard, through);
1752
+ go(t.then, env, [...guard, c], through);
1753
+ go(t.else, env, [...guard, { op: 'not', x: c }], through);
1554
1754
  return;
1555
1755
  }
1556
1756
  if (t.op === 'call' && t.fn === f.name) {
@@ -1570,7 +1770,7 @@ function schemes(p, l) {
1570
1770
  uses.push({ subst, guard: andC(yesC, ...guard) });
1571
1771
  }
1572
1772
  for (const v of Object.values(t))
1573
- go(v, env, guard);
1773
+ go(v, env, guard, through);
1574
1774
  };
1575
1775
  const env = new Map([...formal].flatMap(([key, e]) => (e ? [[key, e]] : [])));
1576
1776
  go(f.body(), env, []);
@@ -1859,6 +2059,28 @@ function instancesOf(p, fs, w) {
1859
2059
  for (const d of p.datas)
1860
2060
  if (r.map === sizeMap(d.name))
1861
2061
  shape(r.key, d);
2062
+ // Where it does, the sizes those shapes read in turn (a field's, a value built's), `depth` rounds: size(x) is 1 plus
2063
+ // its tail's, and the tail's size is its own shape's (a size law of a recursion two fields deep).
2064
+ {
2065
+ const sizeOf = (r) => p.datas.find(d => r.map === sizeMap(d.name));
2066
+ let todo = reads([w.roots, w.others]).filter(r => sizeOf(r)).map(r => r.key);
2067
+ const shaped = new Set(todo.map(t => sid(t)));
2068
+ for (let round = 0; round < w.depth && todo.length; round++) {
2069
+ const next = [];
2070
+ for (const t of todo) {
2071
+ const d = sizeOf({ map: (reads([w.roots, w.others]).find(r => sid(r.key) === sid(t) && sizeOf(r)) ?? { map: '' }).map }) ?? dataOfTerm(t);
2072
+ if (!d)
2073
+ continue;
2074
+ for (const r of reads(holdsAt(`shape ${d.name}`, [t])))
2075
+ if (sizeOf(r) && !shaped.has(sid(r.key))) {
2076
+ shaped.add(sid(r.key));
2077
+ shape(r.key, sizeOf(r));
2078
+ next.push(r.key);
2079
+ }
2080
+ }
2081
+ todo = next;
2082
+ }
2083
+ }
1862
2084
  if (w.depth >= 2)
1863
2085
  for (const r of [...all])
1864
2086
  for (const d of p.datas)
@@ -2552,7 +2774,12 @@ function lemmaUsesFor(p, fs, lemmas, from, insts, models = []) {
2552
2774
  const vars = new Set(lm.law.vars.map(v => v.name)), sides = [];
2553
2775
  walk(encY(p, lm.law.holds, new Map()), o => { if (o.op === 'get')
2554
2776
  sides.push(o); });
2555
- const tops = sides.filter(a => !sides.some(b => b !== a && JSON.stringify(b).includes(JSON.stringify(a))));
2777
+ const tops0 = sides.filter(a => !sides.some(b => b !== a && JSON.stringify(b).includes(JSON.stringify(a))));
2778
+ // (a read of a function where the lemma has one: a size law about a filter is used at the filter's reads, not at
2779
+ // every size the goal reads)
2780
+ const callsFn = (t) => { let yes = false; walk(t, o => { if (o.op === 'get' && fs.arity.has(o.map) && p.fns.some(f => f.name === o.map))
2781
+ yes = true; }); return yes; };
2782
+ const tops = tops0.some(callsFn) ? tops0.filter(callsFn) : tops0;
2556
2783
  for (const top of tops) {
2557
2784
  const n = fs.arity.get(top.map) ?? 1, pats = argsOf(top.key, n);
2558
2785
  // A pattern's match at a term alone, once (a match given others' bindings is it, where it agrees with them).
@@ -3163,7 +3390,7 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
3163
3390
  if (c)
3164
3391
  return c;
3165
3392
  }
3166
- const first = phase === 'rest' ? undefined : proveWith(p, fs, l, base, lv + 1, opts, until, 6000, [1], 'plain');
3393
+ const first = phase === 'rest' || (opts.lemmasFirst && Array.isArray(opts.lemmas)) ? undefined : proveWith(p, fs, l, base, lv + 1, opts, until, 6000, [1], 'plain');
3167
3394
  const one = first && ok(first, base);
3168
3395
  if (one)
3169
3396
  return one;
@@ -3277,6 +3504,10 @@ export function searchIn(l, opts, until, ctx, phase = 'all') {
3277
3504
  // No induction: the law by the cases of a variable (or none), its definitions unfolded.
3278
3505
  () => ok(proveWith(p, fs, l, base, lv + 1, opts, until, 3000, [1, 2], 'cases'), base),
3279
3506
  ];
3507
+ // Lemmas first (a call's decrease from size laws): those the goal reads, the others, each proven and the law tried
3508
+ // again after it; then the law with every lemma proven, at two unfoldings.
3509
+ if (opts.lemmasFirst && Array.isArray(opts.lemmas))
3510
+ steps.splice(0, steps.length, () => lemmaPass('hits', 8, share(0.6), 6000, [1]), () => lemmaPass('others', 8, share(0.8), 6000, [1, 2]), () => ok(proveWith(p2, fs2, l, proven, level(), opts, until, 12000, [1, 2], 'first'), proven, p2));
3280
3511
  for (const [i, step] of steps.entries()) {
3281
3512
  if (clock() > until)
3282
3513
  break;