gdp-wired 0.24.0 → 0.26.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 (52) hide show
  1. package/README.md +14 -9
  2. package/dist/core/accel.d.ts +44 -0
  3. package/dist/core/accel.js +955 -0
  4. package/dist/core/bmc.d.ts +8 -0
  5. package/dist/core/bmc.js +263 -97
  6. package/dist/core/cycles.d.ts +2 -3
  7. package/dist/core/cycles.js +409 -174
  8. package/dist/core/cyclic.d.ts +4 -1
  9. package/dist/core/cyclic.js +86 -64
  10. package/dist/core/data.d.ts +9 -1
  11. package/dist/core/data.js +872 -168
  12. package/dist/core/discover.js +2 -3
  13. package/dist/core/dsl.d.ts +3 -2
  14. package/dist/core/dsl.js +21 -18
  15. package/dist/core/exists.js +7 -14
  16. package/dist/core/extract-check.d.ts +3 -2
  17. package/dist/core/extract-check.js +137 -50
  18. package/dist/core/extract-print.d.ts +1 -0
  19. package/dist/core/extract-print.js +26 -3
  20. package/dist/core/extract-read.d.ts +85 -4
  21. package/dist/core/extract-read.js +295 -34
  22. package/dist/core/extract-shapes.d.ts +14 -0
  23. package/dist/core/extract-shapes.js +608 -78
  24. package/dist/core/extract-xstate.d.ts +5 -1
  25. package/dist/core/extract-xstate.js +618 -184
  26. package/dist/core/extract.js +73 -27
  27. package/dist/core/infer.d.ts +1 -0
  28. package/dist/core/infer.js +364 -40
  29. package/dist/core/machine.d.ts +6 -0
  30. package/dist/core/machine.js +35 -3
  31. package/dist/core/nonterm.d.ts +9 -2
  32. package/dist/core/nonterm.js +173 -9
  33. package/dist/core/q.d.ts +1 -0
  34. package/dist/core/q.js +2 -2
  35. package/dist/core/relation.d.ts +1 -0
  36. package/dist/core/relation.js +95 -39
  37. package/dist/core/solver.d.ts +12 -0
  38. package/dist/core/solver.js +76 -30
  39. package/dist/core/transfer.js +23 -14
  40. package/dist/core/translate.d.ts +1 -1
  41. package/dist/core/translate.js +22 -49
  42. package/dist/core/xstate.d.ts +6 -1
  43. package/dist/core/xstate.js +336 -55
  44. package/dist/kernel/cdcl.d.ts +5 -0
  45. package/dist/kernel/cdcl.js +44 -8
  46. package/dist/kernel/prove.d.ts +6 -1
  47. package/dist/kernel/prove.js +101 -85
  48. package/dist/kernel/reader.d.ts +1 -0
  49. package/dist/kernel/reader.js +4 -3
  50. package/dist/kernel/simplex.d.ts +1 -1
  51. package/dist/kernel/simplex.js +13 -1
  52. package/package.json +3 -2
@@ -1,6 +1,7 @@
1
1
  // Rules read from the code that ships (`gdp-wired/extract`): `extract(code, {entry})` reads a TypeScript or JavaScript
2
- // step function (a reducer `(state, action) => state`, `useReducer`'s, functions over one record) or a class whose
3
- // methods write its fields (a rate limiter's `tryRemove(n)`, a wallet's `debit(x)`), and returns the rule that steps the
2
+ // step function (a reducer `(state, action) => state`, `useReducer`'s, functions over one record), a class whose
3
+ // methods write its fields (a rate limiter's `tryRemove(n)`, a wallet's `debit(x)`), with the classes it extends, or
4
+ // the object of functions a factory returns (its state what they close over), and returns the rule that steps the
4
5
  // same way, as a builder value and as the source that makes it (`toSource`), for a user to read and keep:
5
6
  //
6
7
  // const x = extract(readFileSync('bucket.ts', 'utf8'), {file: 'bucket.ts', entry: 'TokenBucket'})
@@ -10,26 +11,34 @@
10
11
  //
11
12
  // The extractor is untrusted. The rule is checked against the original code by running both (core/extract-check.ts):
12
13
  // requests from the start, steps from drawn states, and steps from the prover's counterexamples, every state, map cell,
13
- // result and refusal compared, and the code's branches counted. Any difference refuses the extraction with the
14
+ // list, result and refusal compared, and the code's branches counted. Any difference refuses the extraction with the
14
15
  // difference; nothing is adopted that the check didn't run. What the subset doesn't read is refused where it is, with
15
16
  // the reason, never approximated. XState machines go through `fromXState` (core/xstate.ts), their guards and actions
16
- // read the same way (`extractXState`).
17
+ // read the same way (`extractXState`, a machine or a function that makes one, its actors, timers and eventless
18
+ // transitions included).
17
19
  //
18
20
  // The subset: numbers (integers: a literal that isn't one is refused; division only as Math.floor or Math.ceil of
19
- // x / k for a constant k; % by a constant of a natural), booleans, string-literal unions, records and nested records
20
- // (spreads, shorthand), Map and Record state keyed by numbers or strings (get, set, has, delete, [k], ?? a default),
21
- // conditionals, ternaries, && || ?? (their right side's effects on its own path), early returns, switch on a tag
22
- // (fall-through, default), Math.min, Math.max, Math.abs, Date.now() (an input; once a step), throws (the rule's
23
- // refusals: its assumption, or its precondition for a constructor), helper functions and methods of the same file
24
- // (inlined), getters. Refused: loops, arrays, strings beyond keys and literals, floats, async, try/catch, writes to the
25
- // state a reducer is given, a throw after a method wrote a field, two keys of one map written in one step, a map
26
- // replaced whole, a reference into a map held across a set, aliasing that depends on the path, other modules' code.
21
+ // x / k for a constant k, a fraction being a binary float the code rounds; % by a constant of a natural), booleans,
22
+ // string-literal unions, strings (set, compared, truthy where not empty), null and undefined where a value may be
23
+ // missing, records and nested records (spreads, shorthand), Map and Record state keyed by numbers or strings (get,
24
+ // set, has, delete, [k], ?? a default; a Map given to a constructor starts empty), arrays of numbers, booleans and
25
+ // string unions as lists (length, [i], push, pop, [i] = x within the array, [...xs], [...xs, x]), Dates as their time
26
+ // (new Date(), getTime(), setTime() where the Date is held), conditionals, ternaries, && || ?? (their right side's
27
+ // effects on its own path), early returns, switch on a tag (fall-through, default), Math.min, Math.max, Math.abs,
28
+ // Boolean(x), Date.now() (an input; once a step), throws (the rule's refusals: its assumption, or its precondition
29
+ // for a constructor), helper functions and methods of the same files (inlined), getters, single inheritance (each
30
+ // member resolved statically: this.m() the nearest the object has, super.m() the nearest above the class it is in),
31
+ // results kept (a value, a record of values, a value that may be missing). Refused: loops, strings beyond keys and
32
+ // literals, floats, async, try/catch, writes to the state a reducer is given, a throw after a method wrote a field, two
33
+ // keys of one map or two writes of one list in one step, a map or a list replaced whole, a reference into a map held
34
+ // across a set, one object (an array, a Map, a Date) in two places, aliasing that depends on the path, mixins, other
35
+ // modules' code.
27
36
  import * as dsl from "./dsl.js";
28
- import { compileFunction } from "./machine.js";
37
+ import { compileFunction, walk } from "./machine.js";
29
38
  import * as I from "./extract-ir.js";
30
39
  import { Refusal } from "./extract-read.js";
31
- import { isSlice, readClass, readFunctions, readSlice } from "./extract-shapes.js";
32
- import { kindOf, mapEmpty, mapKind, natOK, pb, pk, pterm, sortsOf } from "./extract-print.js";
40
+ import { isFactory, isSlice, readClass, readFactory, readFunctions, readSlice } from "./extract-shapes.js";
41
+ import { kindOf, mapEmpty, mapKind, natOK, pb, pidx, pk, pterm, sortsOf } from "./extract-print.js";
33
42
  import { check } from "./extract-check.js";
34
43
  export function extract(code, opts) {
35
44
  const file = opts.file ?? 'input.ts', notes = [];
@@ -38,7 +47,7 @@ export function extract(code, opts) {
38
47
  const isClass = opts.shape ? opts.shape === 'class' : new RegExp(`\\bclass\\s+${opts.entry}\\b|\\b${opts.entry}\\s*=\\s*class\\b`).test(code);
39
48
  // The file sits in the working directory, so its imports (xstate, say) resolve as the project's do.
40
49
  const cwd = globalThis.process?.cwd?.() ?? '.', at = `${cwd}/${file}`;
41
- model = isClass ? readClass(code, at, opts) : isSlice(code, opts.entry) ? readSlice(code, at, opts) : readFunctions(code, at, opts);
50
+ 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);
42
51
  model.file = file;
43
52
  }
44
53
  catch (e) {
@@ -50,6 +59,7 @@ export function extract(code, opts) {
50
59
  try {
51
60
  const s = sortsOf(model, opts.domains);
52
61
  sorts = s.sorts;
62
+ datesInRange(model, sorts);
53
63
  notes.push(...model.notes, ...s.notes);
54
64
  body = builderOf(model, sorts);
55
65
  source = moduleOf(model, body, file);
@@ -74,6 +84,34 @@ export function extract(code, opts) {
74
84
  return { ok: false, source, model, sorts, evidence, refusals: [{ where: file, what: `the rule and the code differ: ${evidence.mismatch}` }], notes };
75
85
  return { ok: true, rule, ...(invariants.length ? { invariants } : {}), source, model, sorts, evidence, refusals: [], notes };
76
86
  }
87
+ // A Date holds a time within ±8.64e15 ms; past it the code's Date is invalid (NaN). The rule refuses a step that would
88
+ // set one there (as it refuses a sum past 2^53), and a start there: its claim stops at the Date's range.
89
+ const DATE_MAX = 8_640_000_000_000_000;
90
+ function datesInRange(m, sorts) {
91
+ const out = (e, at) => (sorts.get(at) === 'nat' ? I.cmp('<', I.num(DATE_MAX), e) : I.or(I.cmp('<', I.num(DATE_MAX), e), I.cmp('<', e, I.num(-DATE_MAX))));
92
+ const dated = m.state.filter(v => v.sort.k === 'num' && v.sort.date);
93
+ const over = [];
94
+ for (const v of dated) {
95
+ const w = m.writes[v.name];
96
+ if (w?.s === 'num')
97
+ over.push(out(w.e, v.name));
98
+ }
99
+ for (const d of m.maps)
100
+ for (const f of d.fields)
101
+ if (f.sort.k === 'num' && f.sort.date) {
102
+ const w = m.mapWrites[d.name];
103
+ const t = w?.vals[f.name];
104
+ if (t?.s === 'num')
105
+ over.push(I.and(w.has, out(t.e, `${d.name}.${f.name}`)));
106
+ }
107
+ if (over.length)
108
+ m.refuse = I.or(m.refuse, ...over);
109
+ const starts = dated.filter(v => m.init[v.name]?.s === 'num').map(v => I.not(out(m.init[v.name].e, v.name)));
110
+ if (starts.length)
111
+ m.pre = I.and(m.pre, ...starts);
112
+ if (over.length || starts.length)
113
+ m.notes.push('a Date holds a time within ±8.64e15 ms: a step that would set one past it is refused (the code\'s Date would be invalid)');
114
+ }
77
115
  // The module a user keeps: the rule, with what it was read from and how it was checked.
78
116
  export const toSource = (x) => x.source ?? '';
79
117
  // The source is the rule: it is evaluated with the builders, so what is checked is what is printed.
@@ -88,7 +126,8 @@ function evaluate(body) {
88
126
  function invariantsOf(m, sorts) {
89
127
  const empty = (d, f) => (f.sort.k === 'num' ? `.eq(0)` : f.sort.k === 'bool' ? `.not()` : f.sort.k === 'choice' ? `.is(${JSON.stringify(f.sort.values[0])})` : `.eq('')`);
90
128
  void sorts;
91
- return m.maps.map(d => `r.law(${JSON.stringify(`${d.name}: a key it doesn't hold holds the defaults`)}, ({${d.name}}) => forall(k => any(${d.name}.at(k).has, all(${d.fields.map(f => `${d.name}.at(k).${f.name}${empty(d, f)}`).join(', ')}))))`);
129
+ return [...m.maps.map(d => `r.law(${JSON.stringify(`${d.name}: a key it doesn't hold holds the defaults`)}, ({${d.name}}) => forall(k => any(${d.name}.at(k).has, all(${d.fields.map(f => `${d.name}.at(k).${f.name}${empty(d, f)}`).join(', ')}))))`),
130
+ ...(m.lists ?? []).map(d => `r.law(${JSON.stringify(`${d.name}: nothing past its end`)}, ({${d.name}}) => ${d.name}.within())`)];
92
131
  }
93
132
  function evaluateLaws(r, xs) {
94
133
  if (!xs.length)
@@ -101,7 +140,7 @@ function moduleOf(m, body, file) {
101
140
  const used = NAMES.filter(n => new RegExp(`(^|[^.\\w$])${n}\\(|(^|[^.\\w$])${n}\\b(?!\\s*:)`).test(body.replace(/'[^']*'/g, "''")) || (n === 'rule'));
102
141
  const ident = identOf(m);
103
142
  return [
104
- `// Extracted by gdp-wired/extract from ${file} (${m.entry}, ${m.shape === 'class' ? 'a class' : m.shape === 'reducer' ? 'a step function' : 'functions over one record'}).`,
143
+ `// Extracted by gdp-wired/extract from ${file} (${m.entry}, ${m.factory ? 'a factory of an object of functions' : m.shape === 'class' ? 'a class' : m.shape === 'reducer' ? 'a step function' : 'functions over one record'}).`,
105
144
  `// Checked against the code it was read from; read again with extract() after the code changes.`,
106
145
  `import {${[...new Set([...used, ...(m.maps.length ? ['all', 'any', 'forall'] : [])])].sort((a, b) => a.localeCompare(b)).join(', ')}} from 'gdp-wired'`,
107
146
  '',
@@ -139,6 +178,8 @@ function builderOf(m, sorts) {
139
178
  lines.push(` .state({${m.state.map(v => `${v.name}: ${start(v)}`).join(', ')}})`);
140
179
  if (m.maps.length)
141
180
  lines.push(` .maps({${m.maps.map((d) => `${d.name}: ${mapKind(d, sorts)}.from(${mapEmpty(d)})`).join(', ')}})`);
181
+ if (m.lists?.length)
182
+ lines.push(` .items({${m.lists.map(d => `${d.name}: ${kindOf(d.fields[0], sorts, `${d.name}.$item`)}`).join(', ')}})`);
142
183
  const envOf = (...xs) => {
143
184
  const vars = new Set(), maps = new Set();
144
185
  for (const x of xs)
@@ -172,9 +213,19 @@ function builderOf(m, sorts) {
172
213
  const vals = d.fields.map(f => `${f.name}: ${pterm(w.vals[f.name], P, { m, sorts, atoms: [w.has] }, `${n}.${f.name}`)}`);
173
214
  outs.push([n, `${n}.set(${pk(w.key, P, ctx())}, {has: ${pb(w.has, P, ctx())}, ${vals.join(', ')}})`]);
174
215
  }
216
+ // A list's write: its apply over the operations by cases (each under its condition).
217
+ const lw = Object.entries(m.listWrites ?? {});
218
+ for (const [n, ops] of lw) {
219
+ const one = (o) => {
220
+ const at = { m, sorts, atoms: [o.when] }, when = pb(o.when, P, ctx());
221
+ return o.op === 'push' ? `${n}.push(${pterm(o.x, P, at, `${n}.$item`)}, ${when})` : o.op === 'pop' ? `${n}.pop(${when})` : `${n}.set(when(${when}, ${pidx(o.i, P, at)}, 0), ${pterm(o.x, P, at, `${n}.$item`)}, ${when})`;
222
+ };
223
+ outs.push([`...${n}`, `${n}.apply(${ops.map(one).join(', ')})`]);
224
+ }
175
225
  const all = [...defs, ...outs.map(([, x]) => x)].join('\n');
176
- const env = withChoices(envOf(...writes.map(([, t]) => t.e), ...mw.flatMap(([, w]) => [w.has, w.key, ...Object.values(w.vals).map(t => t.e)])), all, P, mw.map(([n]) => n));
177
- const ret = `{${outs.map(([n, x]) => `${n}: ${x}`).join(', ')}}`;
226
+ const lterms = lw.flatMap(([, ops]) => ops.flatMap(o => [o.when, ...(o.op === 'pop' ? [] : [o.x.e]), ...(o.op === 'set' ? [o.i] : [])]));
227
+ const env = withChoices(envOf(...writes.map(([, t]) => t.e), ...mw.flatMap(([, w]) => [w.has, w.key, ...Object.values(w.vals).map(t => t.e)]), ...lterms), all, P, [...mw.map(([n]) => n), ...lw.map(([n]) => n)]);
228
+ const ret = `{${outs.map(([n, x]) => (n.startsWith('...') ? `...${x}` : `${n}: ${x}`)).join(', ')}}`;
178
229
  lines.push(defs.length ? ` .step((${env}) => {\n${defs.map(d => ` ${d}`).join('\n')}\n return ${ret}\n })` : ` .step((${env}) => (${ret}))`);
179
230
  return lines.join('\n');
180
231
  }
@@ -227,13 +278,8 @@ function hoist(m, P, roots) {
227
278
  if (!isBool(node)) {
228
279
  const ctx = { m, sorts: P.sorts, atoms: [] }, free = natOK(node, ctx);
229
280
  const cells = [];
230
- const walk = (x) => { if (x && typeof x === 'object') {
231
- const o = x;
232
- if (o.op === 'cell')
233
- cells.push(`${o.map}.${o.field}`);
234
- Object.values(o).forEach(walk);
235
- } };
236
- walk(node);
281
+ walk(node, o => { if (o.op === 'cell')
282
+ cells.push(`${o.map}.${o.field}`); });
237
283
  const hasInt = [...I.varsOf(node).vars].some(n => P.sorts.get(n) === 'int') || cells.some(c => P.sorts.get(c) === 'int');
238
284
  if (!free && !hasInt)
239
285
  continue;
@@ -12,6 +12,7 @@ export type InferOptions = {
12
12
  first?: Verdict;
13
13
  progress?: (phase: string, info: Record<string, number | string>) => void;
14
14
  existentials?: boolean;
15
+ minimize?: boolean;
15
16
  remainders?: boolean;
16
17
  };
17
18
  export type Found = {