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
@@ -80,9 +80,11 @@ function linearCands(target, forms, samples, show) {
80
80
  c.name = nameOf(c, show, target);
81
81
  c.target = target;
82
82
  }
83
- return dedupe(out.filter(c => samples.every(s => holds(c, s))));
83
+ return dedupe(out.filter(c => exact(c) && samples.every(s => holds(c, s))));
84
84
  }
85
85
  const dedupe = (cs) => [...new Map(cs.map(c => [c.name, c])).values()];
86
+ // A statement whose coefficients are naturals a term can hold (a fit to values near 2^53 can make one that isn't).
87
+ const exact = (c) => Object.values(c.lin).every(Number.isSafeInteger);
86
88
  // A polynomial in x of degree 3 at most, exact over the rationals, as d·f = a·x·x·x + b·x·x + c·x + e with whole
87
89
  // numbers: fitted to four points (Newton's differences), kept when every sample meets it.
88
90
  function closedForm(samples, show) {
@@ -99,7 +101,7 @@ function closedForm(samples, show) {
99
101
  const g = Object.values(lin).reduce((p, q) => gcd(p, Math.abs(q)), 0);
100
102
  const c = { name: '', rel: '=', lin: Object.fromEntries(Object.entries(lin).map(([a, k]) => [a, k / g]).filter(([, k]) => k !== 0)) };
101
103
  c.name = nameOf(c, show, 'f');
102
- return samples.every(s => holds(c, s)) ? [c] : [];
104
+ return exact(c) && samples.every(s => holds(c, s)) ? [c] : [];
103
105
  };
104
106
  // f = a x² + b x + c: c = f0, a = (f2 - 2 f1 + f0) / 2, b = f1 - f0 - a; times 2 to keep whole numbers.
105
107
  const A = f2 - 2 * f1 + f0, B = 2 * (f1 - f0) - A, C = 2 * f0;
@@ -136,6 +138,9 @@ function recurSamples(d, args) {
136
138
  break;
137
139
  throw e;
138
140
  }
141
+ // (past 2^53 a value isn't exact, and no statement a lemma makes may hold its constants: the run stops there too)
142
+ if (!Number.isSafeInteger(y) || y < 0)
143
+ break;
139
144
  out.push({ x, f: y, xx: x * x, xxx: x * x * x, ...Object.fromEntries(args.map((a, i) => [a, t[i]])) });
140
145
  }
141
146
  return out;
@@ -170,7 +175,7 @@ function recurCands(samples, args) {
170
175
  { name: '', rel: '<=', lin: { f: 1, g: -1 } },
171
176
  { name: '', rel: '<=', lin: { g: 1, f: -1 } },
172
177
  ...(steepest ? [{ name: '', rel: '<=', lin: { g: 1, x: steepest, f: -1, y: -steepest } }] : []),
173
- ].filter(c => pairs.every(p => holds(c, p)));
178
+ ].filter(c => exact(c) && pairs.every(p => holds(c, p)));
174
179
  for (const c of between)
175
180
  c.name = nameOf(c, showRecur, 'g');
176
181
  return { lemmas, between };
@@ -44,7 +44,8 @@ export declare function when(c: Cond, then: Decimal | number, otherwise: Decimal
44
44
  export declare function when(c: Cond, then: IntLike, otherwise: IntLike): Int;
45
45
  export declare function when<K extends string>(c: Cond, then: Choice<K> | NoInfer<K>, otherwise: Choice<K>): Choice<K>;
46
46
  export declare function when<K extends string>(c: Cond, then: Choice<K>, otherwise: Choice<K> | NoInfer<K>): Choice<K>;
47
- export declare function when(c: Cond, then: Str, otherwise: Str): Str;
47
+ export declare function when(c: Cond, then: Str, otherwise: Str | string): Str;
48
+ export declare function when(c: Cond, then: string, otherwise: Str): Str;
48
49
  export declare function when<V>(c: Cond, then: Maybe<V>, otherwise: Maybe<V>): Maybe<V>;
49
50
  export declare function when(c: Cond, then: Cond, otherwise: Cond): Cond;
50
51
  export declare function when<C extends Cases, T extends string>(c: Cond, then: Variant<C, T>, otherwise: Variant<C, T>): Variant<C, T>;
@@ -236,6 +237,7 @@ export declare class Str {
236
237
  constructor(id: Term, length: Term, bits: ReadonlyMap<string, Term>);
237
238
  get patterns(): string[];
238
239
  choose(c: Cond, other: Str): Str;
240
+ literal(text: string): Str;
239
241
  like(pattern: string): Cond;
240
242
  get isEmpty(): Cond;
241
243
  bit(pattern: string): Term;
@@ -826,6 +828,7 @@ export type Verdict = {
826
828
  };
827
829
  found?: Found;
828
830
  witnesses?: Record<string, string>;
831
+ k?: number;
829
832
  };
830
833
  export type Found = {
831
834
  laws?: {
@@ -857,7 +860,9 @@ export type { Liveness };
857
860
  export declare function proveLeadsTo(r: Rule<Obj, Obj, Obj, Obj, Obj, Obj, Obj, Obj>, laws: Law[], l: Liveness, opts?: {
858
861
  ms?: number;
859
862
  }): Verdict;
860
- export declare const proveDecision: (d: Decision) => Verdict;
863
+ export declare const proveDecision: (d: Decision, opts?: {
864
+ ms?: number;
865
+ }) => Verdict;
861
866
  export declare function crossCheckDecision(d: Decision, opts?: {
862
867
  trials?: number;
863
868
  bound?: number;
package/dist/core/dsl.js CHANGED
@@ -19,11 +19,12 @@ import { carriedView, compileFunction, divName, divisor, divisorsIn, evalC, eval
19
19
  import { allowed, keysOf, requestEnv, watch } from "./watch.js";
20
20
  import { someHolds, substVars } from "./exists.js";
21
21
  import { check, checkRecur, foldObligations, loopObligations } from "../kernel/kernel.js";
22
- import { certLoop, factsFor, grow, proveLaws, proveLiveness, proveStepLaws, usualProof, withDeadline } from "../kernel/prove.js";
22
+ import { certLoop, clock, factsFor, 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";
25
25
  import { inferLaws } from "./infer.js";
26
26
  import { findBoundedRun } from "./bmc.js";
27
+ import { conjunction, proveKInduction } from "./kind.js";
27
28
  import { cycleLemmas, findLeadsTo, findRank } from "./cycles.js";
28
29
  import { findNeverEnds } from "./nonterm.js";
29
30
  // --- terms and conditions -------------------------------------------------------------------------------------------
@@ -120,6 +121,11 @@ export function when(c, then, otherwise) {
120
121
  return new Choice(when(c, then.n, otherwise.n), then.values);
121
122
  if (then instanceof Str && otherwise instanceof Str)
122
123
  return then.choose(c, otherwise);
124
+ // A string beside a string value is that string: when(claimed, who, '').
125
+ if (then instanceof Str && typeof otherwise === 'string')
126
+ return then.choose(c, then.literal(otherwise));
127
+ if (typeof then === 'string' && otherwise instanceof Str)
128
+ return otherwise.literal(then).choose(c, otherwise);
123
129
  if (then instanceof Maybe && otherwise instanceof Maybe)
124
130
  return new Maybe(when(c, then.present, otherwise.present), when(c, then.inner, otherwise.inner));
125
131
  return pickNumbers(c, then, otherwise);
@@ -700,6 +706,8 @@ export class Str {
700
706
  get patterns() { return [...this.bits.keys()]; }
701
707
  // This string where c holds, else `other` (the patterns both declare).
702
708
  choose(c, other) { return new Str(when(c, this.id, other.id), when(c, this.length, other.length), new Map([...this.bits].filter(([p]) => other.bits.has(p)).map(([p, b]) => [p, when(c, b, other.bits.get(p))]))); }
709
+ // A literal as a string value with this one's patterns (each bit as the literal matches it).
710
+ literal(text) { return new Str(lit(literal(text)), lit(text.length), new Map([...this.bits.keys()].map(p => [p, lit(globMatch(p, text) ? 1 : 0)]))); }
703
711
  // The string matches `pattern`, one the kind declared.
704
712
  like(pattern) {
705
713
  const b = this.bits.get(pattern);
@@ -2641,8 +2649,10 @@ const withKinds = (r, laws) => [...r.kindLaws().filter(k => !laws.some(l => l.na
2641
2649
  // A real run from the start that breaks a law or a step law, from a few random runs (each request drawn by its kinds,
2642
2650
  // those the rule's assumption refuses skipped): a false law is refused at once, with the run, where the symbolic search
2643
2651
  // would have to decide every case of its goal to reach one. Nothing here is trusted; a run it finds is a run the
2644
- // interpreter took. A rule that reads functions is skipped: the kernel knows them only by their facts (a recurrence's
2645
- // induction machine reads the function it proves things about), so a run computing them proves nothing about the goal.
2652
+ // interpreter took. A function the rule reads is computed by its JavaScript, as the runtimes compute it; the kernel
2653
+ // knows it only by its facts, which may also bound the params (a recurrence's induction machines take f(x) as a param
2654
+ // fx), so params are drawn only where every fact holds: a fact about the params alone exactly, one about every key at
2655
+ // each key (or tuple of keys) up to twice the bound. A rule whose function breaks its own facts there gets no run.
2646
2656
  const refuteBudget = { trials: 60, depth: 6, bound: 3, ms: 150 };
2647
2657
  // A request as a run's trace shows it: each map it carries as an object of its cells.
2648
2658
  const shownRequest = (input) => Object.fromEntries(Object.entries(input).map(([n, x]) => [n, typeof x === 'number' ? x : Object.fromEntries(x)]));
@@ -2650,14 +2660,29 @@ const shownRequest = (input) => Object.fromEntries(Object.entries(input).map(([n
2650
2660
  const deeperBudget = { trials: 600, depth: 24, bound: 8, ms: 1500, seed: 29 };
2651
2661
  function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget) {
2652
2662
  const m = r.machine;
2653
- // Division by a constant is a function too, but its facts fix its value, so a run computing it is a run of the rule.
2654
- if (Object.keys(m.fns ?? {}).some(f => !isArithmetic(f)) || m.facts?.some(f => !isArithmetic(f.name.slice(0, f.name.indexOf(':')))))
2655
- return undefined;
2656
2663
  const run = interpret(m), rand = seeded(budget.seed ?? 13), until = performance.now() + budget.ms, bound = budget.bound, shown = shownRequest;
2664
+ // (Division by a constant is a function too, its facts Euclid's, which its JavaScript meets: not checked.)
2665
+ const facts = (m.facts ?? []).filter(f => !isArithmetic(f.name.slice(0, f.name.indexOf(':'))));
2666
+ const holds = (f, params) => {
2667
+ const names = f.forall ? [f.forall, ...(f.keys ?? [])] : [], top = names.length > 1 ? bound : 2 * bound;
2668
+ const at = (env, i) => (i === names.length ? evalC(f.holds, env, { scalars: {}, maps: {} }, m)
2669
+ : Array.from({ length: top + 1 }, (_, key) => key).every(key => at({ ...env, [names[i]]: key }, i + 1)));
2670
+ try {
2671
+ return at(params, 0);
2672
+ }
2673
+ catch {
2674
+ return false;
2675
+ }
2676
+ };
2677
+ // (those that read no param once)
2678
+ const readsParams = (f) => m.params.some(p => JSON.stringify(f.holds).includes(`"name":${JSON.stringify(p)}`));
2679
+ let alone;
2680
+ const factsHold = (params) => (alone ??= facts.filter(f => !readsParams(f)).every(f => holds(f, params)))
2681
+ && facts.filter(readsParams).every(f => holds(f, params));
2657
2682
  try {
2658
2683
  for (let trial = 0; trial < budget.trials && performance.now() < until; trial++) {
2659
2684
  const params = r.randomParams(rand, bound);
2660
- if (m.pre && !evalC(m.pre, params, { scalars: {}, maps: {} }, m))
2685
+ if (m.pre && !evalC(m.pre, params, { scalars: {}, maps: {} }, m) || !factsHold(params))
2661
2686
  continue;
2662
2687
  const watching = [...laws, ...stepLaws].map(w => ({ w, on: watch(m, run, w, params, bound) }));
2663
2688
  let st = run.init(params);
@@ -2689,7 +2714,7 @@ function refuteByRuns(r, laws, stepLaws = [], budget = refuteBudget) {
2689
2714
  const wide = Object.keys(m.state).length + m.inputs.length >= 32, lawsHere = wide ? given : [], kinded = wide ? r.kindsOfState() : [];
2690
2715
  for (let trial = 0; !m.history && (steps1.length || lawsHere.length) && trial < budget.trials * 4 && performance.now() < until; trial++) {
2691
2716
  const params = r.randomParams(rand, bound);
2692
- if (m.pre && !evalC(m.pre, params, { scalars: {}, maps: {} }, m))
2717
+ if (m.pre && !evalC(m.pre, params, { scalars: {}, maps: {} }, m) || !factsHold(params))
2693
2718
  continue;
2694
2719
  const scalars = Object.fromEntries(Object.keys(m.state).map(n => [n, rand(8)]));
2695
2720
  for (const [n, k] of kinded)
@@ -2761,6 +2786,14 @@ function searched(r, laws, stepLaws, v, opts) {
2761
2786
  const shallow = bounded(Math.min(250, total / 40), 1);
2762
2787
  if (shallow)
2763
2788
  return refutedBy(shallow);
2789
+ // k-induction (core/kind.ts): the plain laws as one, over k = 2, 3, ... steps in a row, the rule's kinds assumed;
2790
+ // within a twentieth of the budget (at most 500 ms, counted and in wall time).
2791
+ if (!stepLaws.length && laws.every(l => !l.forall && !l.keys?.length && !l.some?.length)) {
2792
+ const ms = Math.min(500, total / 20), kinds = withKinds(r, []).filter(k => !laws.some(l => l.name === k.name));
2793
+ const kd = proveKInduction(r.machine, kinds, conjunction(laws), { ms, wall: performance.now() + ms });
2794
+ if (kd.proven && kd.checked)
2795
+ return { proven: true, checked: true, k: kd.k };
2796
+ }
2764
2797
  let rule = r, lemmas;
2765
2798
  const { fns, lists } = r.parts;
2766
2799
  if (lists.length || fns.some(([, d]) => recurOf(d))) {
@@ -2803,7 +2836,12 @@ export function proveLeadsTo(r, laws, l, opts = {}) {
2803
2836
  const out = proveLiveness(r.machine, withKinds(r, laws), l);
2804
2837
  return { proven: out.proven, checked: out.checked, ...(out.failed ? { goal: out.failed.goal, stuck: out.failed.stuck, ...(out.failed.witness ? { witness: out.failed.witness } : {}), ...(out.failed.why ? { why: out.failed.why } : {}) } : {}) };
2805
2838
  }
2806
- export const proveDecision = (d) => (d.steps ? proveSteps(d.steps.rule, [], [d.steps.law], { search: false }) : goalsVerdict([d.goal]));
2839
+ // `ms`: the budget (the prover's own per goal, 20 s or a second a hypothesis, where none is given), on the clock the
2840
+ // prover reads (the counted one inside a counted search): past it the verdict is unknown.
2841
+ export const proveDecision = (d, opts = {}) => {
2842
+ const go = () => (d.steps ? proveSteps(d.steps.rule, [], [d.steps.law], { search: false }) : goalsVerdict([d.goal]));
2843
+ return opts.ms === undefined ? go() : withDeadline(clock() + opts.ms, go);
2844
+ };
2807
2845
  const seeded = (seed) => { let x = seed; return k => { x = (x * 1103515245 + 12345) % 2 ** 31; return Math.floor(x / 2 ** 31 * k); }; };
2808
2846
  // A decision's callbacks against its condition, on random params and requests: `given` and `then` each run with every
2809
2847
  // value known, against what the interpreter evaluates of the decision built from them.
@@ -0,0 +1,77 @@
1
+ type Context = Record<string, unknown>;
2
+ import { type Kind, type Rule } from './dsl.js';
3
+ import { type Model, type Var } from './extract-read.js';
4
+ import * as I from './extract-ir.js';
5
+ import type { B, N } from './extract-ir.js';
6
+ import type { Sorts } from './extract-print.js';
7
+ type Raw = number | boolean | string;
8
+ export type Arm = {
9
+ label: string;
10
+ where: string;
11
+ pos: number;
12
+ };
13
+ export type Coverage = {
14
+ arms: number;
15
+ hit: number;
16
+ missed: string[];
17
+ };
18
+ export type Evidence = {
19
+ runs: number;
20
+ requests: number;
21
+ fromStates: number;
22
+ probes: {
23
+ conditions: number;
24
+ witnesses: number;
25
+ steps: number;
26
+ };
27
+ refusedBoth: number;
28
+ outside: number;
29
+ edge: number;
30
+ edgeSample?: string;
31
+ compiledAgreed: number;
32
+ coverage: Coverage;
33
+ ms: number;
34
+ mismatch?: string;
35
+ };
36
+ export declare function instrument(code: string, file: string, tail?: string): {
37
+ js: string;
38
+ arms: Arm[];
39
+ };
40
+ export type Sandbox = {
41
+ ctx: Context;
42
+ counts: number[];
43
+ call: (f: string, self: unknown, args: unknown[]) => {
44
+ ok: true;
45
+ value: unknown;
46
+ } | {
47
+ ok: false;
48
+ error: string;
49
+ };
50
+ setNow: (n: number) => void;
51
+ get: (name: string) => unknown;
52
+ };
53
+ export declare function sandbox(code: string, file: string, expose: string[], modules?: Record<string, unknown>, init?: string, files?: Record<string, string>): Sandbox & {
54
+ arms: Arm[];
55
+ };
56
+ type Cells = Record<string, Record<string, Raw>>;
57
+ export type Snap = {
58
+ leaves: Record<string, Raw>;
59
+ maps: Record<string, Cells>;
60
+ };
61
+ export declare const kindOfVar: (v: Var, sorts: Sorts, at?: string) => Kind<unknown>;
62
+ export type CheckOptions = {
63
+ runs?: number;
64
+ depth?: number;
65
+ states?: number;
66
+ seed?: number;
67
+ bound?: number;
68
+ probes?: boolean;
69
+ probeMs?: number;
70
+ modules?: Record<string, unknown>;
71
+ files?: Record<string, string>;
72
+ };
73
+ export declare function check(code: string, file: string, m: Model, r: Rule, sorts: Sorts, opts?: CheckOptions & {
74
+ given?: Record<string, 'nat' | 'int'>;
75
+ }): Evidence;
76
+ export declare function evalTerm(t: N | B | I.L, env: Record<string, Raw>): Raw;
77
+ export {};