gdp-wired 0.31.1 → 0.33.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 (84) hide show
  1. package/README.md +95 -6
  2. package/dist/core/c/reader.d.ts +86 -0
  3. package/dist/core/c/reader.js +860 -0
  4. package/dist/core/check.js +20 -6
  5. package/dist/core/cli.d.ts +76 -0
  6. package/dist/core/cli.js +636 -0
  7. package/dist/core/dsl.d.ts +6 -4
  8. package/dist/core/dsl.js +30 -16
  9. package/dist/core/effect.d.ts +6 -4
  10. package/dist/core/effect.js +48 -10
  11. package/dist/core/ex/harness.exs +177 -0
  12. package/dist/core/ex/json.exs +46 -0
  13. package/dist/core/ex/reader.exs +462 -0
  14. package/dist/core/exists.d.ts +3 -0
  15. package/dist/core/exists.js +19 -5
  16. package/dist/core/extract-c.d.ts +35 -0
  17. package/dist/core/extract-c.js +424 -0
  18. package/dist/core/extract-check.js +27 -6
  19. package/dist/core/extract-ex.d.ts +16 -0
  20. package/dist/core/extract-ex.js +33 -0
  21. package/dist/core/extract-go-check.d.ts +28 -0
  22. package/dist/core/extract-go-check.js +639 -0
  23. package/dist/core/extract-go.d.ts +231 -0
  24. package/dist/core/extract-go.js +1166 -0
  25. package/dist/core/extract-jvm.d.ts +23 -0
  26. package/dist/core/extract-jvm.js +220 -0
  27. package/dist/core/extract-print.js +17 -7
  28. package/dist/core/extract-py.d.ts +15 -0
  29. package/dist/core/extract-py.js +31 -0
  30. package/dist/core/extract-rb.d.ts +17 -0
  31. package/dist/core/extract-rb.js +31 -0
  32. package/dist/core/extract-read.d.ts +20 -0
  33. package/dist/core/extract-read.js +46 -6
  34. package/dist/core/extract-rs.d.ts +12 -0
  35. package/dist/core/extract-rs.js +306 -0
  36. package/dist/core/extract-shapes.d.ts +2 -0
  37. package/dist/core/extract-shapes.js +6 -5
  38. package/dist/core/extract-step.d.ts +806 -0
  39. package/dist/core/extract-step.js +4141 -0
  40. package/dist/core/extract-swift.d.ts +27 -0
  41. package/dist/core/extract-swift.js +484 -0
  42. package/dist/core/extract-xstate.d.ts +10 -3
  43. package/dist/core/extract-xstate.js +50 -4
  44. package/dist/core/extract.d.ts +22 -3
  45. package/dist/core/extract.js +107 -18
  46. package/dist/core/go/go.mod +3 -0
  47. package/dist/core/go/reader.go +901 -0
  48. package/dist/core/infer.d.ts +4 -0
  49. package/dist/core/infer.js +1838 -69
  50. package/dist/core/jvm/Harness.java +361 -0
  51. package/dist/core/jvm/JavaReader.java +825 -0
  52. package/dist/core/jvm/Jvm.java +332 -0
  53. package/dist/core/jvm/KtReader.java +960 -0
  54. package/dist/core/jvm/Rt.java +10 -0
  55. package/dist/core/laws.d.ts +83 -0
  56. package/dist/core/laws.js +623 -0
  57. package/dist/core/machine.d.ts +2 -0
  58. package/dist/core/machine.js +87 -0
  59. package/dist/core/py/harness.py +328 -0
  60. package/dist/core/py/reader.py +447 -0
  61. package/dist/core/rb/harness.rb +233 -0
  62. package/dist/core/rb/reader.rb +375 -0
  63. package/dist/core/relational.d.ts +49 -0
  64. package/dist/core/relational.js +345 -0
  65. package/dist/core/rs/Cargo.lock +108 -0
  66. package/dist/core/rs/Cargo.toml +14 -0
  67. package/dist/core/rs/src/main.rs +681 -0
  68. package/dist/core/swift/Harness.swift +124 -0
  69. package/dist/core/swift/Main.swift +34 -0
  70. package/dist/core/swift/Package.swift +13 -0
  71. package/dist/core/swift/Sources/gdp-swiftreader/main.swift +1341 -0
  72. package/dist/interchange/check.d.ts +16 -0
  73. package/dist/interchange/check.js +111 -0
  74. package/dist/interchange/format.d.ts +150 -0
  75. package/dist/interchange/format.js +678 -0
  76. package/dist/kernel/epr.d.ts +40 -0
  77. package/dist/kernel/epr.js +1882 -0
  78. package/dist/kernel/kernel.d.ts +45 -1
  79. package/dist/kernel/kernel.js +138 -13
  80. package/dist/kernel/prove.d.ts +45 -0
  81. package/dist/kernel/prove.js +658 -51
  82. package/dist/lean-kernel/emit.d.ts +17 -2
  83. package/dist/lean-kernel/emit.js +87 -7
  84. package/package.json +57 -2
@@ -1,10 +1,14 @@
1
1
  import type { Rule } from './dsl.js';
2
2
  import type { Law } from './machine.js';
3
- import { type Model, Refusal, type Term } from './extract-read.js';
3
+ import { type Model, Refusal, type Source, type Term } from './extract-read.js';
4
4
  import { type ReadOptions } from './extract-shapes.js';
5
5
  import { type Sorts } from './extract-print.js';
6
6
  import { type CheckOptions, type Evidence } from './extract-check.js';
7
- export type ExtractOptions = ReadOptions & {
7
+ export { proveRule, proveSteps } from './dsl.js';
8
+ export type ExtractOptions = Omit<ReadOptions, 'entry' | 'functions'> & {
9
+ entry?: string | string[];
10
+ /** @deprecated entry: [...] (the same: several functions over one record, the entry the first) */
11
+ functions?: string[];
8
12
  file?: string;
9
13
  shape?: 'class' | 'functions';
10
14
  domains?: Record<string, 'nat' | 'int'>;
@@ -23,8 +27,23 @@ export type Extraction = {
23
27
  }[];
24
28
  evidence?: Evidence;
25
29
  notes: string[];
30
+ names?: Name[];
26
31
  };
27
- export declare function extract(code: string, opts: ExtractOptions): Extraction;
32
+ export type Name = {
33
+ code: string;
34
+ rule: string;
35
+ role: 'state' | 'param' | 'input' | 'answer' | 'result' | 'failed' | 'method' | 'clock' | 'const';
36
+ method?: string;
37
+ none?: string;
38
+ value?: number;
39
+ map?: {
40
+ fields: string[];
41
+ store?: string;
42
+ tpl?: string;
43
+ };
44
+ };
45
+ export declare function namesOf(m: Model): Name[];
46
+ export declare function extract(at: Source, opts?: ExtractOptions): Extraction;
28
47
  export declare function fromModel(model: Model, file: string, domains: Record<string, 'nat' | 'int'> | undefined, notes: string[], run: (rule: Rule, sorts: Sorts) => Evidence): Extraction;
29
48
  export declare const toSource: (x: Extraction) => string;
30
49
  export type { Evidence, Model, Term };
@@ -4,11 +4,12 @@
4
4
  // the object of functions a factory returns (its state what they close over), and returns the rule that steps the
5
5
  // same way, as a builder value and as the source that makes it (`toSource`), for a user to read and keep:
6
6
  //
7
- // const x = extract(readFileSync('bucket.ts', 'utf8'), {file: 'bucket.ts', entry: 'TokenBucket'})
7
+ // const x = extract('./bucket.ts') // a path or a URL; the entry inferred (or {entry: 'TokenBucket'})
8
8
  // if (!x.ok) console.log(x.refusals) // where and why
9
- // proveRule(x.rule, [x.rule.law('within capacity', ({tokens, capacity}) => tokens.atMost(capacity))])
9
+ // proveRule(x.rule!, [x.rule!.law('within capacity', ({tokens, capacity}) => tokens.atMost(capacity))])
10
10
  // writeFileSync('bucket.rule.ts', toSource(x))
11
11
  //
12
+ // Code in memory is read as {code, file}; the code-first form, extract(code, {file, entry}), stays.
12
13
  // The extractor is untrusted. The rule is checked against the original code by running both (core/extract-check.ts):
13
14
  // requests from the start, steps from drawn states, and steps from the prover's counterexamples, every state, map cell,
14
15
  // list, result and refusal compared, and the code's branches counted. Any difference refuses the extraction with the
@@ -39,17 +40,65 @@
39
40
  import * as dsl from "./dsl.js";
40
41
  import { compileFunction, walk } from "./machine.js";
41
42
  import * as I from "./extract-ir.js";
42
- import { Refusal, placed } from "./extract-read.js";
43
+ import { Refusal, placed, sourceOf } from "./extract-read.js";
43
44
  import { isFactory, isSlice, readClass, readFactory, readFunctions, readSlice } from "./extract-shapes.js";
44
45
  import { kindOf, mapEmpty, mapKind, natOK, pb, pidx, pk, pterm, sortsOf } from "./extract-print.js";
45
46
  import { check } from "./extract-check.js";
46
- export function extract(code, opts) {
47
- const file = opts.file ?? 'input.ts', notes = [];
48
- let model;
47
+ // (a rule read is proven from the same import: proveRule(x.rule!, [x.rule!.law(...)]))
48
+ export { proveRule, proveSteps } from "./dsl.js";
49
+ // The names of a model read from TypeScript (the state's layout, each request's arguments, each method's result).
50
+ export function namesOf(m) {
51
+ const out = [], fields = (n) => m.maps.find(d => d.name === n)?.fields.map(f => f.name) ?? [];
52
+ const lay = (l, at) => {
53
+ if (l.k === 'scalar')
54
+ out.push({ code: at, rule: l.name, role: 'state' });
55
+ else if (l.k === 'map')
56
+ out.push({ code: at, rule: l.name, role: 'state', map: { fields: fields(l.name) } });
57
+ else if (l.k === 'const') {
58
+ const e = l.value.e;
59
+ if (e.op === 'var')
60
+ out.push({ code: at, rule: e.name, role: 'param' });
61
+ else if (e.op === 'const')
62
+ out.push({ code: at, rule: '', role: 'const', value: e.v });
63
+ }
64
+ else if (l.k === 'rec')
65
+ for (const [f, x] of l.fields)
66
+ if (!f.endsWith('()'))
67
+ lay(x, at ? `${at}.${f}` : f);
68
+ };
69
+ lay(m.layout, '');
70
+ const arg = (a, at, method) => {
71
+ if (a.k === 'input')
72
+ out.push({ code: at, rule: a.name, role: 'input', method });
73
+ else if (a.k === 'rec')
74
+ for (const [f, x] of a.fields)
75
+ arg(x, `${at}.${f}`, method);
76
+ };
77
+ for (const e of m.events)
78
+ e.args.forEach((a, i) => { const n = e.names?.[i]; if (n)
79
+ arg(a, n, e.call); });
80
+ for (const [method, r] of Object.entries(m.results ?? {})) {
81
+ if (r.k === 'scalar')
82
+ out.push({ code: 'result', rule: r.name, role: 'result', method });
83
+ else if (r.k === 'maybe')
84
+ out.push({ code: 'result', rule: r.name, role: 'result', method, none: r.missing });
85
+ else
86
+ for (const [f, n] of r.fields)
87
+ out.push(f === 'failed' ? { code: 'failed', rule: n, role: 'failed' } : { code: f === 'value' ? 'result' : `result.${f}`, rule: n, role: 'result', method });
88
+ }
89
+ if (m.event)
90
+ out.push({ code: 'method', rule: m.event, role: 'method' });
91
+ return out;
92
+ }
93
+ export function extract(at, opts = {}) {
94
+ const notes = [];
95
+ let model, code, file;
49
96
  try {
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
- const at = placed(file);
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);
97
+ ;
98
+ ({ code, file } = sourceOf(at, opts.file, 'input.ts'));
99
+ const fns = Array.isArray(opts.entry) ? opts.entry : opts.functions;
100
+ const o = { ...opts, entry: (Array.isArray(opts.entry) ? opts.entry[0] : opts.entry) ?? fns?.[0] ?? '', ...(fns ? { functions: fns } : {}) };
101
+ model = o.entry ? readModel(code, file, o, opts.shape) : inferred(code, file, o, opts.shape);
53
102
  model.file = file;
54
103
  }
55
104
  catch (e) {
@@ -57,7 +106,33 @@ export function extract(code, opts) {
57
106
  return { ok: false, refusals: [{ where: e.where, what: e.what }], notes };
58
107
  throw e;
59
108
  }
60
- return fromModel(model, file, opts.domains, notes, (rule, sorts) => check(code, file, model, rule, sorts, { ...opts.check, ...(opts.files ? { files: opts.files } : {}), ...(opts.domains ? { given: opts.domains } : {}) }));
109
+ return { ...fromModel(model, file, opts.domains, notes, (rule, sorts) => check(code, file, model, rule, sorts, { ...opts.check, ...(opts.files ? { files: opts.files } : {}), ...(opts.domains ? { given: opts.domains } : {}) })), names: namesOf(model) };
110
+ }
111
+ function readModel(code, file, opts, shape) {
112
+ const isClass = shape ? shape === 'class' : new RegExp(`\\bclass\\s+${opts.entry}\\b|\\b${opts.entry}\\s*=\\s*class\\b`).test(code), at = placed(file);
113
+ return 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);
114
+ }
115
+ // No entry named: each exported class and function tried, the one that reads taken.
116
+ function inferred(code, file, opts, shape) {
117
+ const names = [...new Set([...code.matchAll(/export\s+(?:default\s+)?(?:abstract\s+)?class\s+(\w+)|export\s+(?:const|function)\s+(\w+)/g)].map(m => (m[1] ?? m[2])))];
118
+ const read = [], why = [];
119
+ for (const entry of names) {
120
+ try {
121
+ read.push(readModel(code, file, { ...opts, entry }, shape));
122
+ }
123
+ catch (e) {
124
+ if (e instanceof Refusal)
125
+ why.push(e);
126
+ else
127
+ throw e;
128
+ }
129
+ }
130
+ if (read.length > 1)
131
+ throw new Refusal(file, `several rules in the file (${read.map(m => m.entry).join(', ')}): name one (entry)`);
132
+ if (!read.length)
133
+ throw names.length === 1 ? why[0] : new Refusal(file, names.length ? `no exported class or function reads as a rule (${why.map(r => `${r.where}: ${r.what}`).join('; ')}): name the entry` : 'no exported class or function: name the entry');
134
+ read[0].notes.unshift(`the entry inferred: ${read[0].entry}, the one of the file's exports that reads as a rule`);
135
+ return read[0];
61
136
  }
62
137
  // A model read by a front end (this file's TypeScript, or core/extract-go.ts's Go) printed as the rule, built, and
63
138
  // checked against the code by the front end's own check: what both front ends share.
@@ -132,9 +207,11 @@ function evaluate(body) {
132
207
  // A map's representation: each key it doesn't hold holds the defaults (as no object of the code holds a value there).
133
208
  function invariantsOf(m, sorts) {
134
209
  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('')`);
135
- void sorts;
136
- return [...(m.laws ?? []), ...m.maps.filter(d => d.fields.length).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(', ')}))))`),
137
- ...(m.lists ?? []).map(d => `r.law(${JSON.stringify(`${d.name}: nothing past its end`)}, ({${d.name}}) => ${d.name}.within())`)];
210
+ // (a signed field the printer reads as a natural keeps its range's top: a natural is at least 0 already)
211
+ const nat = (l) => { const r = /^r\.law\(("\w+ within its type's range"), \(\{(\w+)\}\) => \2\.atMost\((\d+)\)\.and\(\2\.atLeast\(-\d+\)\)\)$/.exec(l); return r && sorts.get(r[2]) === 'nat' ? `r.law(${r[1]}, ({${r[2]}}) => ${r[2]}.atMost(${r[3]}))` : l; };
212
+ return [...(m.laws ?? []).map(nat), ...m.maps.filter(d => d.fields.length).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(', ')}))))`),
213
+ ...(m.lists ?? []).map(d => `r.law(${JSON.stringify(`${d.name}: nothing past its end`)}, ({${d.name}}) => ${d.name}.within())`),
214
+ ...(m.lists ?? []).filter(d => d.len !== undefined).map(d => `r.law(${JSON.stringify(`${d.name}: ${d.len} items, always`)}, ({${d.name}_len}) => ${d.name}_len.eq(${d.len}))`)];
138
215
  }
139
216
  function evaluateLaws(r, xs) {
140
217
  if (!xs.length)
@@ -147,7 +224,7 @@ function moduleOf(m, body, file) {
147
224
  const used = NAMES.filter(n => new RegExp(`(^|[^.\\w$])${n}\\(|(^|[^.\\w$])${n}\\b(?!\\s*:)`).test(body.replace(/'[^']*'/g, "''")) || (n === 'rule'));
148
225
  const ident = identOf(m);
149
226
  return [
150
- `// Extracted by gdp-wired/extract from ${file} (${m.entry}, ${m.factory?.calls ? 'an Effect service' : m.factory ? 'a factory of an object of functions' : m.shape === 'class' ? (/\.go$/.test(file) ? 'a struct and its methods' : 'a class') : m.shape === 'reducer' ? 'a step function' : 'functions over one record'}).`,
227
+ `// Extracted by gdp-wired/extract from ${file} (${m.entry}, ${m.kind ?? (m.factory?.calls ? 'an Effect service' : m.factory ? 'a factory of an object of functions' : m.shape === 'class' ? (/\.go$/.test(file) ? 'a struct and its methods' : 'a class') : m.shape === 'reducer' ? 'a step function' : 'functions over one record')}).`,
151
228
  `// Checked against the code it was read from; read again with extract() after the code changes.`,
152
229
  `import {${[...new Set([...used, ...(m.maps.length ? ['all', 'any', 'forall'] : []), ...['all', 'any', 'forall'].filter(n => (m.laws ?? []).some(l => l.includes(`${n}(`)))])].sort((a, b) => a.localeCompare(b)).join(', ')}} from 'gdp-wired'`,
153
230
  '',
@@ -186,7 +263,7 @@ function builderOf(m, sorts) {
186
263
  if (m.maps.length)
187
264
  lines.push(` .maps({${m.maps.map((d) => `${d.name}: ${mapKind(d, sorts)}.from(${mapEmpty(d)})`).join(', ')}})`);
188
265
  if (m.lists?.length)
189
- lines.push(` .items({${m.lists.map(d => `${d.name}: ${kindOf(d.fields[0], sorts, `${d.name}.$item`)}`).join(', ')}})`);
266
+ lines.push(` .items({${m.lists.map(d => `${d.name}: ${kindOf(d.fields[0], sorts, `${d.name}.$item`)}`).join(', ')}}${m.lists.some(d => d.len !== undefined) ? `, {${m.lists.filter(d => d.len !== undefined).map(d => `${d.name}: ${d.len}`).join(', ')}}` : ''})`);
190
267
  const envOf = (...xs) => {
191
268
  const vars = new Set(), maps = new Set();
192
269
  for (const x of xs)
@@ -210,7 +287,7 @@ function builderOf(m, sorts) {
210
287
  const defs = [];
211
288
  for (const [key, name] of consts) {
212
289
  const node = hoistNodes.get(key);
213
- defs.push(`const ${name} = ${'rel' in node || isBool(node) ? pb(node, P, ctx()) : pterm({ s: 'num', e: node }, P, ctx())}`);
290
+ defs.push(`const ${name} = ${'rel' in node || isBool(node, m) ? pb(node, P, ctx()) : pterm({ s: 'num', e: node }, P, ctx())}`);
214
291
  P.hoisted.set(key, name);
215
292
  }
216
293
  for (const [n, t] of writes)
@@ -236,7 +313,19 @@ function builderOf(m, sorts) {
236
313
  lines.push(defs.length ? ` .step((${env}) => {\n${defs.map(d => ` ${d}`).join('\n')}\n return ${ret}\n })` : ` .step((${env}) => (${ret}))`);
237
314
  return lines.join('\n');
238
315
  }
239
- const isBool = (x) => ['cmp', 'and', 'or', 'not', 'is', 'leq', 'keq'].includes(x.op) || (x.op === 'const' && typeof x.v === 'boolean');
316
+ // (a condition by cases is one where a branch is: an ite of conditions, or of a boolean variable or cell)
317
+ const isBool = (x, m) => {
318
+ const o = x;
319
+ if (['cmp', 'and', 'or', 'not', 'is', 'leq', 'keq'].includes(o.op) || (o.op === 'const' && typeof o.v === 'boolean'))
320
+ return true;
321
+ if (o.op === 'ite')
322
+ return isBool(o.a, m) || isBool(o.b, m);
323
+ if (o.op === 'var' && m)
324
+ return [...m.params, ...m.inputs, ...m.state].some(v => v.name === o.name && v.sort.k === 'bool');
325
+ if (o.op === 'cell' && m)
326
+ return o.field === 'has' || !!m.maps.find(d => d.name === o.map)?.fields.some(f => f.name === o.field && f.sort.k === 'bool');
327
+ return false;
328
+ };
240
329
  // The env's names: those the terms read, the choices a literal is printed through, and the maps written.
241
330
  function withChoices(env, text, P, extra = []) {
242
331
  const names = new Set(env.slice(1, -1).split(', ').filter(Boolean));
@@ -282,7 +371,7 @@ function hoist(m, P, roots) {
282
371
  const node = hoistNodes.get(k), size = k.length;
283
372
  if ((count.get(k) ?? 0) < 2 || size < 60)
284
373
  continue;
285
- if (!isBool(node)) {
374
+ if (!isBool(node, m)) {
286
375
  const ctx = { m, sorts: P.sorts, atoms: [] }, free = natOK(node, ctx);
287
376
  const cells = [];
288
377
  walk(node, o => { if (o.op === 'cell')
@@ -0,0 +1,3 @@
1
+ module gdpwired/goreader
2
+
3
+ go 1.22