gdp-wired 0.29.0 → 0.30.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -87,7 +87,10 @@ All of these are proven automatically, and each proof is also a Lean theorem:
87
87
  and no run breaks them, it looks for lemmas about the rule's recurrences and lists (`discover`), lemmas about the
88
88
  functions it knows by their facts (`cycleLemmas`, each proven by a cyclic proof) and then invariants (`inferLaws`),
89
89
  within 10 s (`{search: {ms}}`; `{search: false}`, the prover alone); the verdict's `found` holds what
90
- proved them, as laws and lemmas with the source to paste.
90
+ proved them, as laws and lemmas with the source to paste. Each invariant found holds in the states reachable from the
91
+ start, so a proof that needs one holds there and the verdict says so (`assumes: {states: 'reachable', laws}`). Code that
92
+ steps the rule from states it is handed proves with `{from: 'any'}`: every step law then holds from every state the
93
+ laws allow, reachable or not, and the search never adds an invariant.
91
94
  - **Invariants nobody wrote** (`gdp-wired/infer`): `inferLaws(rule, laws)` proves a law that holds but isn't inductive
92
95
  alone, with the laws it finds (bounds, sums and differences over the state, the same where a flag or a choice holds
93
96
  one value, remainders of a value or of a sum or difference of two, x mod 2 = 0 for a counter stepping by 2, and laws
@@ -1,4 +1,4 @@
1
- import { type Kind, type Rule, type TermLike, type Verdict, Choice, Cond, Term } from './dsl.js';
1
+ import { type Kind, type ProveOptions, type Rule, type TermLike, type Verdict, Choice, Cond, Term } from './dsl.js';
2
2
  import { type Law } from './machine.js';
3
3
  import type { StepLaw } from '../kernel/kernel.js';
4
4
  export type StateNode = {
@@ -78,7 +78,7 @@ export declare class Chart<P extends Obj = {}, I extends Obj = {}, X extends Obj
78
78
  law(name: string, f: (env: After<P & X>) => Cond): Law;
79
79
  stepLaw(name: string, then: (before: Env<P, I, X>, after: After<X>) => Cond, when?: (before: Env<P, I, X>) => Cond): StepLaw;
80
80
  chartLaws(): Law[];
81
- prove(laws?: Law[], stepLaws?: StepLaw[]): Verdict;
81
+ prove(laws?: Law[], stepLaws?: StepLaw[], opts?: ProveOptions): Verdict;
82
82
  check(opts?: {
83
83
  params?: Obj;
84
84
  bound?: number;
@@ -201,7 +201,7 @@ export class Chart {
201
201
  const { rule: r, regions } = this.build();
202
202
  return regions.flatMap(reg => [...reg.compounds].filter(([c, { history }]) => history && c).map(([c]) => r.law(`${reg.name === 'state' ? '' : `${reg.name}.`}${c} remembers one of its own states`, (env) => any(...reg.leaves.filter(l => l.startsWith(`${c}.`)).map(l => env[`${reg.field}.last.${c}`].is(l))))));
203
203
  }
204
- prove(laws = [], stepLaws = []) { const given = [...this.chartLaws(), ...laws]; return stepLaws.length ? proveSteps(this.rule, given, stepLaws) : proveRule(this.rule, given); }
204
+ prove(laws = [], stepLaws = [], opts = {}) { const given = [...this.chartLaws(), ...laws]; return stepLaws.length ? proveSteps(this.rule, given, stepLaws, opts) : proveRule(this.rule, given, opts); }
205
205
  // --- the checks a chart's author expects -------------------------------------------------------------------------
206
206
  // reached: each state, with the first run from the start that reaches it (a breadth-first walk of the compiled rule
207
207
  // over every event and small payloads, `bound` the largest natural tried, under `params`), or `unreachable` where the
@@ -149,14 +149,15 @@ export declare function translatedProof(key: () => string, build: (reused: boole
149
149
  why?: string;
150
150
  };
151
151
  export declare const routeOf: () => string;
152
- export declare const translateMs: (usualMs?: number) => number;
152
+ export declare const translateMs: (usualMs?: number, floor?: number) => number;
153
+ export declare const stepCertFloor: () => number;
153
154
  export declare function crossCyclic(kind: string, name: string, usual: boolean, run0: (() => CyclicVerdict) | undefined, usualMs?: number, translated?: Translated): void;
154
155
  export declare const certMode: () => boolean;
155
156
  export declare const certOn: () => boolean;
156
157
  export declare const certSearch: () => boolean;
157
158
  export declare const certMs: () => number;
158
159
  export declare const uncovered: (kind: string, name: string, why: string) => void;
159
- export declare function certCyclic(kind: string, name: string, translated: Translated | undefined, run0: (() => CyclicVerdict) | undefined, usualMs?: number): {
160
+ export declare function certCyclic(kind: string, name: string, translated: Translated | undefined, run0: (() => CyclicVerdict) | undefined, usualMs?: number, floor?: number): {
160
161
  checked: boolean;
161
162
  proof?: Cyclic;
162
163
  why: string;
@@ -1376,11 +1376,18 @@ const none = () => ({ proven: false, checked: false, node: '', goal: 'no instanc
1376
1376
  // translated) searched, within `until` where it is given; with why the translation wasn't proven.
1377
1377
  // A translation within the certificate's budget (GDP_CERT_MS) or four times the usual proof's time, whichever is longer
1378
1378
  // (`translateMs`): one that will fail is cut there, not at its goals' own bounds.
1379
- export const translateMs = (usualMs = 0) => Math.max(certMs(), 4 * usualMs);
1380
- function cyclicOf(translated, run, st, until, usualMs) {
1379
+ // `floor`: the least a translation is given (a step law's certificate passes its own, stepCertFloor).
1380
+ export const translateMs = (usualMs = 0, floor = certMs()) => Math.max(floor, 4 * usualMs);
1381
+ // A step law's: four times its usual proof's time, at least a quarter second (GDP_CERT_STEP_MS). Its usual trees are
1382
+ // the certificate where the translation isn't made, checked by kernel.ts as every certificate is, so a translation that
1383
+ // will fail costs at most that. (With GDP_CERT_MS's 10 s as the floor, from 0.19.0, every step law whose translation
1384
+ // fails waited it out, and twice from 0.20.0, together and then alone: a statechart's 19 step laws, proven in 0.35 s,
1385
+ // took 55 s to certify, every one of the failed laws' certificates its usual trees in the end.)
1386
+ export const stepCertFloor = () => Number(env.GDP_CERT_STEP_MS ?? 250);
1387
+ function cyclicOf(translated, run, st, until, usualMs, floor) {
1381
1388
  let how = 'searched', why;
1382
1389
  if (translated) {
1383
- const r = withDeadline(clock() + translateMs(usualMs), () => translated(st));
1390
+ const r = withDeadline(clock() + translateMs(usualMs, floor), () => translated(st));
1384
1391
  if (r.verdict?.proven && r.verdict.checked)
1385
1392
  return { out: r.verdict, how: 'translated' };
1386
1393
  how = 'fallback';
@@ -1429,11 +1436,11 @@ export const certMs = () => Number(env.GDP_CERT_MS ?? 10_000);
1429
1436
  // A proof of a kind no cyclic instance covers, or whose cyclic proof wasn't made, counted (`cyclic: {..., uncovered:
1430
1437
  // true, why}`): its certificate the usual trees.
1431
1438
  export const uncovered = (kind, name, why) => cycLog({ kind, name, uncovered: true, why });
1432
- export function certCyclic(kind, name, translated, run0, usualMs) {
1439
+ export function certCyclic(kind, name, translated, run0, usualMs, floor) {
1433
1440
  for (const key of Object.keys(cyclicProf))
1434
1441
  delete cyclicProf[key];
1435
1442
  const st = tstats(), t0 = performance.now(), until = clock() + certMs();
1436
- const { out, how, why } = cyclicOf(translated, (translated && !certSearch() ? undefined : run0) ?? none, st, until, usualMs);
1443
+ const { out, how, why } = cyclicOf(translated, (translated && !certSearch() ? undefined : run0) ?? none, st, until, usualMs, floor);
1437
1444
  const checked = out.proven && out.checked;
1438
1445
  cycLog({ kind, name, cert: true, usual: true, cyclic: checked, ms: Math.round(performance.now() - t0), ...(usualMs === undefined ? {} : { usualMs: Math.round(usualMs) }), route: how, ...(how !== 'searched' ? st : {}), ...(why ? { fellBack: why } : {}), ...profLine() });
1439
1446
  const late = clock() > until ? ` within ${certMs()} ms` : '';
@@ -313,6 +313,7 @@ function houdiniList(r, part, cands, params) {
313
313
  // is proven first, then each dropped in turn while the laws stay proven without it.
314
314
  // `first`: the laws' verdict on r alone, when the caller has it.
315
315
  export function discover(r, laws, stepLaws = [], first) {
316
+ r = r.withSumsOf(laws, stepLaws);
316
317
  return quietly(() => discoverSearch(r, laws, stepLaws, first ?? proveSteps(r, laws, stepLaws, { search: false })));
317
318
  }
318
319
  function discoverSearch(r, laws, stepLaws, first) {
@@ -618,6 +618,7 @@ export declare class Rule<P extends Obj = {}, I extends Obj = {}, S extends Obj
618
618
  private lawOf;
619
619
  private someOf;
620
620
  private divides;
621
+ withSumsOf(...xs: unknown[]): this;
621
622
  dividesBy(...ks: number[]): this;
622
623
  withDivisors(...ks: number[]): this;
623
624
  private kinds?;
@@ -839,6 +840,11 @@ export type Verdict = {
839
840
  found?: Found;
840
841
  witnesses?: Record<string, string>;
841
842
  k?: number;
843
+ assumes?: Assumes;
844
+ };
845
+ export type Assumes = {
846
+ states: 'reachable';
847
+ laws: string[];
842
848
  };
843
849
  export type Found = {
844
850
  laws?: {
@@ -858,6 +864,7 @@ export type ProveOptions = {
858
864
  ms?: number;
859
865
  cycles?: boolean;
860
866
  };
867
+ from?: 'reachable' | 'any';
861
868
  };
862
869
  export declare class Unproven extends Error {
863
870
  readonly verdict: Verdict;
package/dist/core/dsl.js CHANGED
@@ -1900,10 +1900,14 @@ export class Rule {
1900
1900
  divides(x) {
1901
1901
  if (this.spec.arith)
1902
1902
  divisorsIn([x], this.spec.arith);
1903
- for (const n of Object.keys(sumsIn([x]) ?? {}))
1904
- (this.spec.sumsRead ??= new Set()).add(n);
1905
1903
  return x;
1906
1904
  }
1905
+ // The same rule declaring every sum over a map's keys these read (laws, step laws, a liveness, a decision's goal), as
1906
+ // each prover entry takes it; this rule itself unchanged. The rule where they read none it doesn't already declare.
1907
+ withSumsOf(...xs) {
1908
+ const had = this.spec.sumsRead ?? new Set(), names = Object.keys(sumsIn(xs) ?? {}).filter(n => !had.has(n));
1909
+ return names.length ? this.with({ sumsRead: new Set([...had, ...names]) }) : this;
1910
+ }
1907
1911
  // Divide by these too (inferLaws' candidates): the machine declares div$k and mod$k for each.
1908
1912
  dividesBy(...ks) { for (const k of ks)
1909
1913
  (this.spec.arith ??= new Set()).add(divisor(k, 'dividesBy')); return this; }
@@ -2011,7 +2015,7 @@ export class Rule {
2011
2015
  const listed = lists.flatMap(l => l.equationsAt(uniqueTerms([l.len, l.len.minus(1), ...keysRead([...hyps, t], l.maps)])).map(c => c.c));
2012
2016
  const goal = this.divides({ name, hyps: [...listed, ...hyps, { op: 'not', x: t }] });
2013
2017
  const facts = this.spec.fns?.length || this.spec.facts?.length || this.spec.arith?.size ? factsFor(this.machine, goal) : [];
2014
- const d = { name, rule: this, given: hyps, then: t, goal: { name, hyps: [...facts, ...goal.hyps] } };
2018
+ const d = { name, rule: this.withSumsOf(goal), given: hyps, then: t, goal: { name, hyps: [...facts, ...goal.hyps] } };
2015
2019
  if ([...(Array.isArray(g) ? g : [g]).map(c => c.c), t].some(quantifiedIn)) {
2016
2020
  const conds = (e) => { const own = given(e); return { given$: all(...(Array.isArray(own) ? own : [own])), then$: then(e) }; };
2017
2021
  const r = (this.spec.step ? this : this.step(() => ({}))).flags(conds);
@@ -2267,6 +2271,9 @@ export class Rule {
2267
2271
  // interpreter evaluates (core/watch.ts's verdicts, over the same keys). A law that says something other than its
2268
2272
  // callback, or a step that writes something other than it means, is reported with the state it shows at.
2269
2273
  crossCheck(laws, stepLaws = [], opts = {}) {
2274
+ const summed = this.withSumsOf(laws, stepLaws);
2275
+ if (summed !== this)
2276
+ return summed.crossCheck(laws, stepLaws, opts);
2270
2277
  const s = this.spec, m = this.machine, run = interpret(m), bound = opts.bound ?? 4, rand = opts.rand ?? seeded(7);
2271
2278
  let checked = 0;
2272
2279
  const at = (what, params, st, input) => `${what}: params ${JSON.stringify(params)}, state ${JSON.stringify(this.decode(st))}${input ? `, request ${JSON.stringify(numbersOf(input))}` : ''}`;
@@ -2355,6 +2362,9 @@ export class Rule {
2355
2362
  Object.assign(written, k.store(n, updates[n]));
2356
2363
  } });
2357
2364
  for (const n of Object.keys(st.scalars)) {
2365
+ // (a sum over a map's keys: no callback writes it; the runtimes keep it exact, kernel.ts's sumMachine)
2366
+ if (m.sums && n in m.sums)
2367
+ continue;
2358
2368
  const u = written[n], got = next.scalars[n], want = u === undefined ? st.scalars[n] : valOf(u);
2359
2369
  if (want === undefined)
2360
2370
  continue;
@@ -2850,6 +2860,7 @@ const refutedVerdict = (out) => ({ proven: false, checked: false, goal: out.goal
2850
2860
  const noting = (r, ...xs) => { const ks = divisorsIn(xs); if (ks.size)
2851
2861
  r.dividesBy(...ks); return r; };
2852
2862
  export function proveRule(r, laws, opts = {}) {
2863
+ r = r.withSumsOf(laws);
2853
2864
  noting(r, laws);
2854
2865
  const refuted = refuteByRuns(r, laws);
2855
2866
  // A state the laws allow whose step breaks one, with no run to it (a wide rule's: what the kernel's step goal would end
@@ -2862,6 +2873,7 @@ export function proveRule(r, laws, opts = {}) {
2862
2873
  return searched(r, laws, [], v, opts);
2863
2874
  }
2864
2875
  export function proveSteps(r, laws, stepLaws, opts = {}) {
2876
+ r = r.withSumsOf(laws, stepLaws);
2865
2877
  noting(r, laws, stepLaws);
2866
2878
  const refuted = refuteByRuns(r, laws, stepLaws);
2867
2879
  // (a step law broken from a state the laws allow, with no run to it: the laws may need an invariant there, or the run
@@ -2901,7 +2913,8 @@ function stepGhosts(m, stepLaws) {
2901
2913
  // recurrences or carried lists (the rule made again with them), then invariants over what it then is. The verdict is the
2902
2914
  // prover's on the laws with what was found; when nothing is found, the prover's own (with why).
2903
2915
  function searched(r, laws, stepLaws, v, opts) {
2904
- if ((v.proven && v.checked) || opts.search === false || v.run || v.stuck === 'sat' && !/@step|@\d+ steps/.test(v.goal ?? ''))
2916
+ const any = opts.from === 'any';
2917
+ if ((v.proven && v.checked) || opts.search === false || v.run || v.stuck === 'sat' && (any || !/@step|@\d+ steps/.test(v.goal ?? '')))
2905
2918
  return v;
2906
2919
  // The deeper runs; then runs over small values (keys that meet, small params), whose requests meet their
2907
2920
  // assumption's equalities and clocks, or near the counterexample the verdict ends at.
@@ -2928,11 +2941,11 @@ function searched(r, laws, stepLaws, v, opts) {
2928
2941
  return refutedBy(shallow);
2929
2942
  // k-induction (core/kind.ts): the plain laws as one, over k = 2, 3, ... steps in a row, the rule's kinds assumed;
2930
2943
  // within a twentieth of the budget (at most 500 ms, counted so too).
2931
- if (!stepLaws.length && laws.every(l => !l.forall && !l.keys?.length && !l.some?.length)) {
2944
+ if (!any && !stepLaws.length && laws.every(l => !l.forall && !l.keys?.length && !l.some?.length)) {
2932
2945
  const ms = Math.min(500, total / 20), kinds = withKinds(r, []).filter(k => !laws.some(l => l.name === k.name));
2933
2946
  const kd = counted(fullRate, () => proveKInduction(r.machine, kinds, conjunction(laws), { ms }), true);
2934
2947
  if (kd.proven && kd.checked)
2935
- return { proven: true, checked: true, k: kd.k };
2948
+ return { proven: true, checked: true, k: kd.k, assumes: { states: 'reachable', laws: [] } };
2936
2949
  }
2937
2950
  let rule = r, lemmas;
2938
2951
  const { fns, lists } = r.parts;
@@ -2952,6 +2965,9 @@ function searched(r, laws, stepLaws, v, opts) {
2952
2965
  }
2953
2966
  // Laws about the ids a counter hands out (core/fresh.ts), within a tenth of what is left: the laws with them, then
2954
2967
  // the invariant search with them given.
2968
+ // (each found invariant proven from init: none where the step laws hold from any state)
2969
+ if (any)
2970
+ return { ...v, why: [v.why, 'no invariant searched for: {from: \'any\'}'].filter(Boolean).join('; ') };
2955
2971
  let fresh = [];
2956
2972
  if (Object.keys(rule.machine.maps ?? {}).length && until - clock() - tail > 1000) {
2957
2973
  const fm = rule.machine, share = (until - clock() - tail) / 10;
@@ -2959,7 +2975,7 @@ function searched(r, laws, stepLaws, v, opts) {
2959
2975
  if (fresh.length) {
2960
2976
  const given = [...withKinds(rule, laws), ...fresh.map(f => f.law)], out = withDeadline(clock() + share, () => (stepLaws.length ? proveStepLaws(fm, given, stepLaws) : proveLaws(fm, given)));
2961
2977
  if (out.proven && out.checked)
2962
- return { proven: true, checked: true, found: { laws: fresh, ...(lemmas ? { lemmas } : {}) } };
2978
+ return { proven: true, checked: true, found: { laws: fresh, ...(lemmas ? { lemmas } : {}) }, assumes: reachableBy(fresh) };
2963
2979
  }
2964
2980
  }
2965
2981
  const ms = until - clock() - tail;
@@ -2975,7 +2991,7 @@ function searched(r, laws, stepLaws, v, opts) {
2975
2991
  if (inf2.proven && inf2.checked) {
2976
2992
  const { found, stats: _s2, ...verdict } = inf2;
2977
2993
  void _s2;
2978
- return { ...verdict, found: { laws: [...fresh, ...found], ...(lemmas ? { lemmas } : {}) } };
2994
+ return { ...verdict, found: { laws: [...fresh, ...found], ...(lemmas ? { lemmas } : {}) }, ...withAssumes([...fresh, ...found]) };
2979
2995
  }
2980
2996
  }
2981
2997
  // (a step law's ghost: at most 10 s of it, as its goals cost more than the laws')
@@ -2986,9 +3002,13 @@ function searched(r, laws, stepLaws, v, opts) {
2986
3002
  }
2987
3003
  const { found, stats: _stats, ...verdict } = inf;
2988
3004
  void _stats;
2989
- return { ...verdict, found: { laws: [...fresh, ...found], ...(lemmas ? { lemmas } : {}) } };
3005
+ return { ...verdict, found: { laws: [...fresh, ...found], ...(lemmas ? { lemmas } : {}) }, ...withAssumes([...fresh, ...found]) };
2990
3006
  }
3007
+ // What a verdict proven with these found laws rests on: the states reachable from init (each found law is proven so).
3008
+ const reachableBy = (found) => ({ states: 'reachable', laws: found.map(f => f.text) });
3009
+ const withAssumes = (found) => (found.length ? { assumes: reachableBy(found) } : {});
2991
3010
  export function proveLeadsTo(r, laws, l, opts = {}) {
3011
+ r = r.withSumsOf(laws, l);
2992
3012
  noting(r, laws, l);
2993
3013
  if (laws.some(law => law.some?.length))
2994
3014
  throw new Error(`${r.machine.name}: a law with "there exists" goes to proveRule or proveSteps; a liveness takes plain laws (the ones its proof printed, Verdict.witnesses)`);
@@ -3019,8 +3039,9 @@ export function proveLeadsTo(r, laws, l, opts = {}) {
3019
3039
  f = g2;
3020
3040
  }
3021
3041
  }
3042
+ const helpers = [...fresh, ...(f.laws ?? []).map((law, i) => ({ law, text: f.found?.laws[i] ?? law.name }))];
3022
3043
  return { proven: f.proven, checked: f.checked, ...(f.goal ? { goal: f.goal, stuck: f.stuck } : {}), ...(f.witness ? { witness: f.witness } : {}), ...(f.why ? { why: f.why } : {}),
3023
- ...(f.found ? { found: { rank: f.found.rank, ...(f.laws?.length || fresh.length ? { laws: [...fresh, ...(f.laws ?? []).map((law, i) => ({ law, text: f.found.laws[i] ?? law.name }))] } : {}) } } : {}) };
3044
+ ...(f.found ? { found: { rank: f.found.rank, ...(helpers.length ? { laws: helpers } : {}) } } : {}), ...(f.proven ? withAssumes(helpers) : {}) };
3024
3045
  }
3025
3046
  const out = proveLiveness(r.machine, withKinds(r, laws), l);
3026
3047
  return verdictOf(out);
@@ -269,6 +269,7 @@ export declare function program(code: string, file: string, extra?: Record<strin
269
269
  sf: ts.SourceFile;
270
270
  checker: ts.TypeChecker;
271
271
  };
272
+ export declare function placed(file: string): string;
272
273
  export declare const scriptKind: (file: string) => ts.ScriptKind;
273
274
  export declare function shapeOf(t: ts.Type, checker: ts.TypeChecker, at: ts.Node, inner?: string): Shape;
274
275
  type Callable = {
@@ -56,11 +56,17 @@ export function program(code, file, extra = {}) {
56
56
  host.getSourceFile = (name, lang, ...rest) => (name === file ? ts.createSourceFile(name, code, lang, true, scriptKind(file)) : name in extra ? ts.createSourceFile(name, extra[name], lang, true, scriptKind(name)) : getSourceFile(name, lang, ...rest));
57
57
  host.readFile = name => (name === file ? code : name in extra ? extra[name] : readFile(name));
58
58
  host.fileExists = name => name === file || name in extra || fileExists(name);
59
- const dirExists = host.directoryExists?.bind(host), dirs = new Set(Object.keys(extra).flatMap(f => f.split('/').slice(1, -1).map((_, i, a) => `/${a.slice(0, i + 1).join('/')}`)));
59
+ const dirExists = host.directoryExists?.bind(host), dirs = new Set(Object.keys(extra).flatMap(f => { const p = f.split('/'); return p.slice(1, -1).map((_, i) => p.slice(0, i + 2).join('/')); }));
60
60
  host.directoryExists = d => dirs.has(d.replace(/\/$/, '')) || (dirExists ? dirExists(d) : true);
61
61
  const p = ts.createProgram([file], options, host);
62
62
  return { sf: p.getSourceFile(file), checker: p.getTypeChecker() };
63
63
  }
64
+ // Where the file sits: an absolute path as given (backslashes as slashes), a relative one in the working directory, so its
65
+ // imports (xstate, say) resolve as the project's do.
66
+ export function placed(file) {
67
+ const cwd = globalThis.process?.cwd?.() ?? '.';
68
+ return (/^([A-Za-z]:)?[\\/]/.test(file) ? file : `${cwd}/${file}`).replace(/\\/g, '/');
69
+ }
64
70
  export const scriptKind = (file) => (/\.jsx$/.test(file) ? ts.ScriptKind.JSX : /\.tsx$/.test(file) ? ts.ScriptKind.TSX : /\.[cm]?js$/.test(file) ? ts.ScriptKind.JS : ts.ScriptKind.TS);
65
71
  // The shape a type has in the subset.
66
72
  // (`inner`: the field path inside the value at `at` that t is the type of, for where a refusal says it is)
@@ -24,7 +24,7 @@ import ts from 'typescript';
24
24
  import * as dsl from "./dsl.js";
25
25
  import { compileFunction, seeded } from "./machine.js";
26
26
  import * as I from "./extract-ir.js";
27
- import { Exec, Refusal, memberName, normalize, program, shapeOf } from "./extract-read.js";
27
+ import { Exec, Refusal, memberName, normalize, placed, program, shapeOf } from "./extract-read.js";
28
28
  import { kindOf, pb, pterm, sortsOf } from "./extract-print.js";
29
29
  import { sandbox } from "./extract-check.js";
30
30
  import { conforms, eventsOf, fromXState } from "./xstate.js";
@@ -35,8 +35,7 @@ const isFn = (e) => ts.isArrowFunction(e) || ts.isFunctionExpression(e);
35
35
  export function extractXState(code, opts) {
36
36
  const file = opts.file ?? 'machine.ts', t0 = performance.now(), notes = [];
37
37
  try {
38
- const cwd = globalThis.process?.cwd?.() ?? '.';
39
- const at = `${cwd}/${file}`, root = at.slice(0, at.length - file.split('/').pop().length);
38
+ const at = placed(file), root = at.slice(0, at.length - file.split('/').pop().length);
40
39
  const extra = Object.fromEntries(Object.entries(opts.files ?? {}).map(([p, c]) => [normalize(`${root}${p}`), c]));
41
40
  const { sf, checker } = program(code, at, extra);
42
41
  // The entry: a machine (setup(...).createMachine(...), createMachine(...)) or a function that returns one.
@@ -39,7 +39,7 @@
39
39
  import * as dsl from "./dsl.js";
40
40
  import { compileFunction, walk } from "./machine.js";
41
41
  import * as I from "./extract-ir.js";
42
- import { Refusal } from "./extract-read.js";
42
+ import { Refusal, placed } from "./extract-read.js";
43
43
  import { isFactory, isSlice, readClass, readFactory, readFunctions, readSlice } from "./extract-shapes.js";
44
44
  import { kindOf, mapEmpty, mapKind, natOK, pb, pidx, pk, pterm, sortsOf } from "./extract-print.js";
45
45
  import { check } from "./extract-check.js";
@@ -48,8 +48,7 @@ export function extract(code, opts) {
48
48
  let model;
49
49
  try {
50
50
  const isClass = opts.shape ? opts.shape === 'class' : new RegExp(`\\bclass\\s+${opts.entry}\\b|\\b${opts.entry}\\s*=\\s*class\\b`).test(code);
51
- // The file sits in the working directory, so its imports (xstate, say) resolve as the project's do.
52
- const cwd = globalThis.process?.cwd?.() ?? '.', at = `${cwd}/${file}`;
51
+ const at = placed(file);
53
52
  model = isClass ? readClass(code, at, opts) : isSlice(code, opts.entry) ? readSlice(code, at, opts) : isFactory(code, file, opts.entry) ? readFactory(code, at, opts) : readFunctions(code, at, opts);
54
53
  model.file = file;
55
54
  }
@@ -538,7 +538,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
538
538
  // (GDP_INFER_TRACE=2: each phase's progress too, to stderr)
539
539
  if (env.GDP_INFER_TRACE === '2' && !opts.progress)
540
540
  opts = { ...opts, progress: (phase, info) => globalThis.process.stderr.write(`[infer ${phase}] ${JSON.stringify(info)}\n`) };
541
- const t0 = performance.now(), ms = opts.ms ?? 20000, wallUntil = t0 + ms, rule = isRule(target) ? target : undefined;
541
+ const t0 = performance.now(), ms = opts.ms ?? 20000, wallUntil = t0 + ms, rule = isRule(target) ? target.withSumsOf(laws, stepLaws) : undefined;
542
542
  // The clock the budgets read (counted milliseconds since the start, or wall time where `timed`), and the stop.
543
543
  const timed = !!opts.timed, w0 = work.n, used = { tries: 0, rows: 0, evals: 0, watched: 0 };
544
544
  const now = () => (timed ? performance.now() - t0
@@ -19,7 +19,7 @@ export type TStats = {
19
19
  cached: number;
20
20
  };
21
21
  export declare const tstats: () => TStats;
22
- export declare function translate(part: Goal, whole: Goal, tree: Tree, ren0: Renamer, st: TStats, until: number, pp?: Path, wp?: Path, swaps?: [string, string][]): Tree | undefined;
22
+ export declare function translate(part: Goal, whole: Goal, tree: Tree, ren0: Renamer, st: TStats, until0: number, pp?: Path, wp?: Path, swaps?: [string, string][]): Tree | undefined;
23
23
  export type Reads = {
24
24
  k: E;
25
25
  w: E;
@@ -27,4 +27,4 @@ export type Reads = {
27
27
  export declare function readsFirst(whole: Goal, reads: Reads, ren: Renamer, inner: (wp: Path, swaps: [string, string][]) => Tree | undefined, st: TStats, until: number, wp?: Path, swaps?: [string, string][]): Tree | undefined;
28
28
  export declare function decide(whole: Goal, conds: C[], inner: (wp: Path) => Tree | undefined, st: TStats, until: number, wp?: Path): Tree | undefined;
29
29
  export declare function close(g: Goal, wp: Path, st: TStats, until: number): Tree | undefined;
30
- export declare function carry(g: Goal, nFacts: number, nUses: number, st: TStats, until: number): Tree | undefined;
30
+ export declare function carry(g: Goal, nFacts: number, nUses: number, st: TStats, until0: number): Tree | undefined;
@@ -13,7 +13,7 @@ import { walk } from "./machine.js";
13
13
  import { add, costs, env, refuteFast, scale, solve } from "./solver.js";
14
14
  import { checkRefutation } from "./check.js";
15
15
  import { canon, canonFlip, columnTerm, factorsOf, isCell, isMonomial, leafConstraints, leafConstraintsReusing, linear, substE, truth, withProducts } from "../kernel/kernel.js";
16
- import { cellProducts, clock, grow, leafRowsOf, parseKey } from "../kernel/prove.js";
16
+ import { cellProducts, clock, grow, leafRowsOf, parseKey, withinDeadline } from "../kernel/prove.js";
17
17
  import { Reader, times } from "../kernel/reader.js";
18
18
  const omega = 'O$';
19
19
  const debugOn = () => !!env.GDP_CYCLIC_DEBUG;
@@ -145,7 +145,9 @@ function regrow(whole, wp, until) {
145
145
  // key W equal to a key K the node's conclusion reads its map at, that conclusion reads at K what the usual one reads at
146
146
  // W (a write's reads at its key read at the key read, as the step's facts have them), so the usual cells at W are read
147
147
  // as the cells at K (`readsFirst` decides the two equal or apart first).
148
- export function translate(part, whole, tree, ren0, st, until, pp = new Map(), wp = new Map(), swaps = []) {
148
+ export function translate(part, whole, tree, ren0, st, until0, pp = new Map(), wp = new Map(), swaps = []) {
149
+ // (within the deadline it runs in too: a certificate's translation, core/cyclic.ts's translateMs)
150
+ const until = withinDeadline(until0);
149
151
  const ren = swaps.length ? (lin, p) => {
150
152
  const out = {};
151
153
  for (const key in lin) {
@@ -492,7 +494,8 @@ export function close(g, wp, st, until) {
492
494
  // one where both are decided by whichever of the two hypotheses is then false. A case none of that refutes is grown on
493
495
  // the goal at its path.
494
496
  // `nUses`: the uses' hypotheses, just before the conclusion refuted (mainGoal's order).
495
- export function carry(g, nFacts, nUses, st, until) {
497
+ export function carry(g, nFacts, nUses, st, until0) {
498
+ const until = withinDeadline(until0);
496
499
  const last = g.hyps.length - 1, uses = g.hyps.slice(last - nUses, last), facts = g.hyps.slice(last - nUses - nFacts, last - nUses);
497
500
  const law = g.hyps[last].x;
498
501
  const parts = uses.map(u => (u.op === 'or' && u.xs.length === 2 && u.xs[0].op === 'not' ? { guard: u.xs[0].x, concl: u.xs[1] } : { guard: undefined, concl: u }));
@@ -9,10 +9,14 @@ type DagNode = {
9
9
  } | {
10
10
  res: [number, number];
11
11
  on: Lin;
12
+ } | {
13
+ hyp: number;
14
+ lits: [Lin, boolean][];
12
15
  };
13
16
  export type Dag = {
14
17
  nodes: DagNode[];
15
18
  top: number;
19
+ clausal?: boolean;
16
20
  };
17
21
  export declare const cdclStats: {
18
22
  on: boolean;
@@ -50,26 +54,28 @@ export declare const REFUTED = "refuted, not unfolded";
50
54
  export type Refuted = Outcome & {
51
55
  core?: number[];
52
56
  dag?: Dag;
57
+ assumed?: number[];
53
58
  };
54
- export declare function growCdcl(goal: Goal, root: Path, budget: {
55
- nodes: number;
56
- until?: number;
57
- }, opts?: {
59
+ export type CdclOptions = {
58
60
  maxLeaves?: number;
59
61
  model?: boolean;
60
- wall?: number;
61
62
  core?: boolean;
62
63
  dag?: boolean;
64
+ clausal?: boolean;
65
+ sideOf?: (hyp: number) => number;
66
+ quiet?: (name: string) => boolean;
67
+ };
68
+ export declare function growCdcl(goal: Goal, root: Path, budget: {
69
+ nodes: number;
70
+ until?: number;
71
+ }, opts?: CdclOptions & {
72
+ wall?: number;
63
73
  }): Outcome;
64
- export declare function cdclSession(goal: Goal, root: Path, opts?: {
65
- maxLeaves?: number;
66
- model?: boolean;
67
- core?: boolean;
68
- dag?: boolean;
69
- }): {
74
+ export declare function cdclSession(goal: Goal, root: Path, opts?: CdclOptions): {
70
75
  run: (b: {
71
76
  nodes: number;
72
77
  until?: number;
73
- }, w?: number, assume?: Lin) => Outcome;
78
+ }, w?: number, assume?: Lin | Lin[]) => Outcome;
79
+ retire: (hyp: number) => void;
74
80
  };
75
81
  export {};