gdp-wired 0.23.0 → 0.25.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.
- package/README.md +12 -2
- package/dist/core/accel.d.ts +44 -0
- package/dist/core/accel.js +720 -0
- package/dist/core/bmc.d.ts +13 -2
- package/dist/core/bmc.js +390 -18
- package/dist/core/cycles.d.ts +23 -0
- package/dist/core/cycles.js +527 -146
- package/dist/core/data.d.ts +17 -0
- package/dist/core/data.js +1177 -213
- package/dist/core/discover.js +8 -3
- package/dist/core/dsl.d.ts +7 -2
- package/dist/core/dsl.js +47 -9
- package/dist/core/extract-check.d.ts +77 -0
- package/dist/core/extract-check.js +785 -0
- package/dist/core/extract-ir.d.ts +139 -0
- package/dist/core/extract-ir.js +198 -0
- package/dist/core/extract-print.d.ts +30 -0
- package/dist/core/extract-print.js +426 -0
- package/dist/core/extract-read.d.ts +298 -0
- package/dist/core/extract-read.js +1298 -0
- package/dist/core/extract-shapes.d.ts +13 -0
- package/dist/core/extract-shapes.js +993 -0
- package/dist/core/extract-xstate.d.ts +34 -0
- package/dist/core/extract-xstate.js +320 -0
- package/dist/core/extract.d.ts +31 -0
- package/dist/core/extract.js +249 -0
- package/dist/core/infer.d.ts +1 -0
- package/dist/core/infer.js +298 -28
- package/dist/core/kind.d.ts +30 -0
- package/dist/core/kind.js +81 -0
- package/dist/core/nonterm.d.ts +4 -1
- package/dist/core/nonterm.js +98 -2
- package/dist/core/relation.js +82 -7
- package/dist/core/transfer.js +1 -1
- package/dist/core/xstate.d.ts +6 -0
- package/dist/core/xstate.js +70 -12
- package/dist/kernel/cdcl.d.ts +15 -0
- package/dist/kernel/cdcl.js +331 -244
- package/dist/kernel/kernel.d.ts +15 -0
- package/dist/kernel/kernel.js +32 -0
- package/dist/kernel/prove.js +20 -7
- package/dist/kernel/reader.d.ts +14 -0
- package/dist/kernel/reader.js +102 -14
- package/dist/lean-kernel/emit.d.ts +28 -1
- package/dist/lean-kernel/emit.js +56 -15
- package/dist/lean-kernel/library.js +2 -1
- package/package.json +12 -3
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { type Coverage } from './extract-check.js';
|
|
2
|
+
import { fromXState } from './xstate.js';
|
|
3
|
+
export type XStateOptions = {
|
|
4
|
+
file?: string;
|
|
5
|
+
entry: string;
|
|
6
|
+
xstate: {
|
|
7
|
+
createActor: (m: never) => {
|
|
8
|
+
start: () => unknown;
|
|
9
|
+
};
|
|
10
|
+
} & Record<string, unknown>;
|
|
11
|
+
check?: {
|
|
12
|
+
runs?: number;
|
|
13
|
+
depth?: number;
|
|
14
|
+
seed?: number;
|
|
15
|
+
};
|
|
16
|
+
};
|
|
17
|
+
export type XStateExtraction = {
|
|
18
|
+
ok: boolean;
|
|
19
|
+
source?: string;
|
|
20
|
+
chart?: ReturnType<typeof fromXState>;
|
|
21
|
+
refusals: {
|
|
22
|
+
where: string;
|
|
23
|
+
what: string;
|
|
24
|
+
}[];
|
|
25
|
+
notes: string[];
|
|
26
|
+
evidence?: {
|
|
27
|
+
runs: number;
|
|
28
|
+
events: number;
|
|
29
|
+
coverage: Coverage;
|
|
30
|
+
ms: number;
|
|
31
|
+
mismatch?: string;
|
|
32
|
+
};
|
|
33
|
+
};
|
|
34
|
+
export declare function extractXState(code: string, opts: XStateOptions): XStateExtraction;
|
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
// XState machines read from the code (core/extract.ts's `extractXState`): the machine as XState builds it (the file
|
|
2
|
+
// loaded in the check's VM, with the real xstate), its states and transitions read by `fromXState` (core/xstate.ts), and
|
|
3
|
+
// each guard and action `setup({guards, actions})` names read from its source by the extractor's executor, printed as
|
|
4
|
+
// the bridge fromXState takes: a guard as its condition, an `assign` as the context it writes. The chart is then run
|
|
5
|
+
// beside XState's own actor (`conforms`) on random events with payloads, every state and context compared, the code's
|
|
6
|
+
// branches counted; any difference refuses it. Refused besides what fromXState refuses: v4 `cond` (the machines read are
|
|
7
|
+
// v5's, and XState v5 ignores a `cond`, taking the transition unguarded), a machine made by a function, guards and actions with params, actions that
|
|
8
|
+
// raise, send or spawn.
|
|
9
|
+
import ts from 'typescript';
|
|
10
|
+
import * as dsl from "./dsl.js";
|
|
11
|
+
import { compileFunction } from "./machine.js";
|
|
12
|
+
import * as I from "./extract-ir.js";
|
|
13
|
+
import { Exec, Refusal, program } from "./extract-read.js";
|
|
14
|
+
import { kindOf, pb, pterm, sortsOf } from "./extract-print.js";
|
|
15
|
+
import { sandbox } from "./extract-check.js";
|
|
16
|
+
import { conforms, fromXState } from "./xstate.js";
|
|
17
|
+
const where = (n) => { const sf = n.getSourceFile(), { line, character } = sf.getLineAndCharacterOfPosition(n.getStart()); return `${sf.fileName.split('/').pop()}:${line + 1}:${character + 1}`; };
|
|
18
|
+
const refuse = (n, what) => { throw new Refusal(where(n), what); };
|
|
19
|
+
const strip = (e) => (ts.isParenthesizedExpression(e) || ts.isAsExpression(e) || ts.isSatisfiesExpression(e) ? strip(e.expression) : e);
|
|
20
|
+
export function extractXState(code, opts) {
|
|
21
|
+
const file = opts.file ?? 'machine.ts', t0 = performance.now(), notes = [];
|
|
22
|
+
try {
|
|
23
|
+
const cwd = globalThis.process?.cwd?.() ?? '.';
|
|
24
|
+
const { sf, checker } = program(code, `${cwd}/${file}`);
|
|
25
|
+
// The machine's expression: setup({...}).createMachine({...}) or createMachine({...}), bound to the entry.
|
|
26
|
+
let init;
|
|
27
|
+
for (const st of sf.statements)
|
|
28
|
+
if (ts.isVariableStatement(st))
|
|
29
|
+
for (const d of st.declarationList.declarations)
|
|
30
|
+
if (ts.isIdentifier(d.name) && d.name.text === opts.entry)
|
|
31
|
+
init = d.initializer;
|
|
32
|
+
if (!init) {
|
|
33
|
+
const fn = sf.statements.find((st) => ts.isFunctionDeclaration(st) && st.name?.text === opts.entry);
|
|
34
|
+
if (fn)
|
|
35
|
+
refuse(fn, `${opts.entry} makes the machine when called (a machine made by a function: export the machine itself)`);
|
|
36
|
+
return { ok: false, refusals: [{ where: file, what: `no machine ${opts.entry} in the file` }], notes };
|
|
37
|
+
}
|
|
38
|
+
const call = strip(init);
|
|
39
|
+
if (!ts.isCallExpression(call) || !ts.isPropertyAccessExpression(call.expression) && !ts.isIdentifier(call.expression))
|
|
40
|
+
refuse(init, 'a machine not made by setup(...).createMachine or createMachine');
|
|
41
|
+
const c = call;
|
|
42
|
+
const callee = c.expression, made = ts.isPropertyAccessExpression(callee) ? callee.name.text : callee.text;
|
|
43
|
+
if (made !== 'createMachine')
|
|
44
|
+
refuse(c, 'a machine not made by createMachine');
|
|
45
|
+
const setupArg = ts.isPropertyAccessExpression(callee) && ts.isCallExpression(callee.expression) && ts.isIdentifier(callee.expression.expression) && callee.expression.expression.text === 'setup' ? callee.expression.arguments[0] : undefined;
|
|
46
|
+
const props = (o, name) => {
|
|
47
|
+
if (!o || !ts.isObjectLiteralExpression(o))
|
|
48
|
+
return undefined;
|
|
49
|
+
const p = o.properties.find(x => ts.isPropertyAssignment(x) && x.name.getText() === name);
|
|
50
|
+
if (!p)
|
|
51
|
+
return undefined;
|
|
52
|
+
const v = strip(p.initializer);
|
|
53
|
+
return ts.isObjectLiteralExpression(v) ? v : refuse(v, `setup's ${name} as other than an object of them`);
|
|
54
|
+
};
|
|
55
|
+
// v4's `cond` (XState v5 ignores it): refused where it is, not dropped.
|
|
56
|
+
const config = c.arguments[0];
|
|
57
|
+
const visit = (n) => { if (ts.isPropertyAssignment(n) && n.name.getText() === 'cond')
|
|
58
|
+
refuse(n, 'a v4 `cond` (XState v5 reads `guard` and takes this transition unguarded: name the guard in `guard`)'); ts.forEachChild(n, visit); };
|
|
59
|
+
if (config)
|
|
60
|
+
visit(config);
|
|
61
|
+
// The machine as XState builds it, from the code loaded with the real xstate.
|
|
62
|
+
const box = sandbox(code, file, [opts.entry], { xstate: opts.xstate });
|
|
63
|
+
const machine = box.get(opts.entry);
|
|
64
|
+
const ctx0 = machine.config.context;
|
|
65
|
+
if (ctx0 !== undefined && (typeof ctx0 !== 'object' || ctx0 === null))
|
|
66
|
+
refuse(config ?? c, 'a context computed by a function');
|
|
67
|
+
// The context's variables and the payload's inputs, in one setup the guards and actions are read with.
|
|
68
|
+
const s = { ours: f => f === sf, checker, sf, names: new Set(), vars: new Map(), maps: new Map(), lazySorts: new Map(), nowRole: 'input', hints: new WeakMap(), notes: new Set(), lazy: new Map() };
|
|
69
|
+
const ex = new Exec(s), ctxVars = new Map(), init0 = {};
|
|
70
|
+
for (const [k, v] of Object.entries(ctx0 ?? {})) {
|
|
71
|
+
if (typeof v === 'number' && Number.isSafeInteger(v)) {
|
|
72
|
+
const x = ex.newVar(k, { k: 'num' }, 'state');
|
|
73
|
+
ctxVars.set(k, x);
|
|
74
|
+
init0[x.name] = { s: 'num', e: I.num(v) };
|
|
75
|
+
}
|
|
76
|
+
else if (typeof v === 'boolean') {
|
|
77
|
+
const x = ex.newVar(k, { k: 'bool' }, 'state');
|
|
78
|
+
ctxVars.set(k, x);
|
|
79
|
+
init0[x.name] = { s: 'bool', e: v ? I.T : I.F };
|
|
80
|
+
}
|
|
81
|
+
else
|
|
82
|
+
refuse(config ?? c, `the context's ${k} (${JSON.stringify(v)}): numbers and booleans are the context the subset reads`);
|
|
83
|
+
if (ctxVars.get(k).name !== k)
|
|
84
|
+
refuse(config ?? c, `the context's ${k} shares a name with the builders'`);
|
|
85
|
+
}
|
|
86
|
+
// One function of ({context, event}) at a time, with the context as variables and the event's fields as inputs.
|
|
87
|
+
const run = (f, what) => {
|
|
88
|
+
const fn = strip(f);
|
|
89
|
+
if (!ts.isArrowFunction(fn) && !ts.isFunctionExpression(fn))
|
|
90
|
+
return refuse(f, `${what}: a reference to a function defined elsewhere`);
|
|
91
|
+
if (fn.parameters.length > 1)
|
|
92
|
+
refuse(fn, `${what} reads its params (named guards and actions with params are not in the subset)`);
|
|
93
|
+
const heap = new Map();
|
|
94
|
+
heap.set('xs.context', { k: 'rec', fields: new Map([...ctxVars].map(([k, x]) => [k, Exec.valueOf(x)])), origin: 'input' });
|
|
95
|
+
heap.set('xs.event', { k: 'rec', fields: new Map(), origin: 'input', lazy: { prefix: '' } });
|
|
96
|
+
heap.set('xs.arg', { k: 'rec', fields: new Map([['context', { t: 'ref', id: 'xs.context' }], ['event', { t: 'ref', id: 'xs.event' }]]), origin: 'input' });
|
|
97
|
+
let p = { pc: [], locals: new Map(), heap: heap, wrote: [], nows: 0 };
|
|
98
|
+
if (fn.parameters[0])
|
|
99
|
+
p = ex.bind(fn.parameters[0].name, { t: 'ref', id: 'xs.arg' }, p);
|
|
100
|
+
if (!ts.isBlock(fn.body)) {
|
|
101
|
+
const [v, q] = ex.ev(fn.body, p);
|
|
102
|
+
return { v, p: q };
|
|
103
|
+
}
|
|
104
|
+
const flow = ex.block(fn.body.statements, p);
|
|
105
|
+
if (flow.live || flow.rets.length !== 1 || ex.throws.length)
|
|
106
|
+
refuse(fn, `${what}: one return, no throw (a function by cases is written with ?: in the subset)`);
|
|
107
|
+
return { v: flow.rets[0][1], p: flow.rets[0][0] };
|
|
108
|
+
};
|
|
109
|
+
// A guard: a condition of ({context, event}), or stateIn.
|
|
110
|
+
const guardOf = (v, name) => {
|
|
111
|
+
v = strip(v);
|
|
112
|
+
// stateIn({a: 'b'}) or stateIn('#id.a.b'): whether the machine is in that state.
|
|
113
|
+
if (ts.isCallExpression(v) && ts.isIdentifier(v.expression) && v.expression.text === 'stateIn') {
|
|
114
|
+
const a = v.arguments[0] && strip(v.arguments[0]);
|
|
115
|
+
const path = (o) => (ts.isStringLiteral(o) ? o.text : ts.isObjectLiteralExpression(o) && o.properties.length === 1 && ts.isPropertyAssignment(o.properties[0]) ? `${o.properties[0].name.getText()}.${path(strip(o.properties[0].initializer))}` : refuse(o, 'a stateIn of other than one state'));
|
|
116
|
+
return { in: a ? path(a).replace(/^#[^.]*\./, '') : refuse(v, 'stateIn()') };
|
|
117
|
+
}
|
|
118
|
+
const { v: out } = run(v, `the guard ${name}`);
|
|
119
|
+
if (out.t !== 'bool')
|
|
120
|
+
refuse(v, `the guard ${name} returns other than a boolean`);
|
|
121
|
+
return out.e;
|
|
122
|
+
};
|
|
123
|
+
// An action: the context an assign writes, null for one that writes none; refused for one that sends or spawns.
|
|
124
|
+
const actionOf = (v, name) => {
|
|
125
|
+
v = strip(v);
|
|
126
|
+
if (ts.isCallExpression(v) && ts.isIdentifier(v.expression) && v.expression.text === 'assign') {
|
|
127
|
+
const arg = v.arguments[0] ? strip(v.arguments[0]) : refuse(v, 'assign()');
|
|
128
|
+
const writes = {};
|
|
129
|
+
const put = (k, x, at) => {
|
|
130
|
+
const cv = ctxVars.get(k) ?? refuse(at, `assigns ${k}, not in the context`);
|
|
131
|
+
if (cv.sort.k === 'num' && x.t === 'num')
|
|
132
|
+
writes[k] = { s: 'num', e: x.e };
|
|
133
|
+
else if (cv.sort.k === 'bool' && x.t === 'bool')
|
|
134
|
+
writes[k] = { s: 'bool', e: x.e };
|
|
135
|
+
else
|
|
136
|
+
refuse(at, `assigns ${k} a ${x.t}`);
|
|
137
|
+
};
|
|
138
|
+
if (ts.isObjectLiteralExpression(arg)) {
|
|
139
|
+
for (const p of arg.properties) {
|
|
140
|
+
if (!ts.isPropertyAssignment(p)) {
|
|
141
|
+
refuse(p, 'an assign entry other than key: value');
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
const k = p.name.getText(), init1 = strip(p.initializer);
|
|
145
|
+
if (ts.isArrowFunction(init1) || ts.isFunctionExpression(init1))
|
|
146
|
+
put(k, run(init1, `the action ${name}'s ${k}`).v, p);
|
|
147
|
+
else {
|
|
148
|
+
const [x] = ex.ev(init1, { pc: [], locals: new Map(), heap: new Map(), wrote: [], nows: 0 });
|
|
149
|
+
put(k, x, p);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
else {
|
|
154
|
+
const { v: out, p } = run(arg, `the action ${name}`);
|
|
155
|
+
const o = out.t === 'ref' ? p.heap.get(out.id) : undefined;
|
|
156
|
+
if (o?.k !== 'rec')
|
|
157
|
+
refuse(arg, `the action ${name} returns other than an object of context fields`);
|
|
158
|
+
for (const [k, x] of o.fields)
|
|
159
|
+
put(k, x, arg);
|
|
160
|
+
}
|
|
161
|
+
return writes;
|
|
162
|
+
}
|
|
163
|
+
if (ts.isCallExpression(v) && ts.isIdentifier(v.expression) && ['raise', 'sendTo', 'sendParent', 'emit', 'enqueueActions', 'spawnChild', 'stopChild', 'forwardTo', 'cancel'].includes(v.expression.text))
|
|
164
|
+
return refuse(v, `the action ${name}: ${v.expression.text} (an action that sends or spawns is not in the subset)`);
|
|
165
|
+
if (ts.isCallExpression(v) && ts.isIdentifier(v.expression) && v.expression.text === 'log')
|
|
166
|
+
return null;
|
|
167
|
+
// A plain function: it writes no context (XState's actions write it through assign only); its effects are
|
|
168
|
+
// outside the machine, left out.
|
|
169
|
+
if (ts.isArrowFunction(v) || ts.isFunctionExpression(v)) {
|
|
170
|
+
notes.push(`the action ${name} writes no context (its effects outside the machine are left out)`);
|
|
171
|
+
return null;
|
|
172
|
+
}
|
|
173
|
+
return refuse(v, `the action ${name}: an action the subset doesn't read`);
|
|
174
|
+
};
|
|
175
|
+
const guards = [];
|
|
176
|
+
for (const g of props(setupArg, 'guards')?.properties ?? []) {
|
|
177
|
+
if (!ts.isPropertyAssignment(g))
|
|
178
|
+
refuse(g, 'a guard written other than name: function');
|
|
179
|
+
guards.push([g.name.getText(), guardOf(g.initializer, g.name.getText())]);
|
|
180
|
+
}
|
|
181
|
+
const actions = [];
|
|
182
|
+
for (const a of props(setupArg, 'actions')?.properties ?? []) {
|
|
183
|
+
if (!ts.isPropertyAssignment(a))
|
|
184
|
+
refuse(a, 'an action written other than name: action');
|
|
185
|
+
actions.push([a.name.getText(), actionOf(a.initializer, a.name.getText())]);
|
|
186
|
+
}
|
|
187
|
+
// Inline guards and actions: the config's source and the machine's own config walked together, each function the
|
|
188
|
+
// config holds named by its path in it (what fromXState's `inline` takes).
|
|
189
|
+
const inlineGuards = [], inlineActions = [];
|
|
190
|
+
const key = (k) => (/^[A-Za-z_$][\w$]*$/.test(k) ? `.${k}` : `[${JSON.stringify(k)}]`);
|
|
191
|
+
// Each transition's actions with its guard (an action runs only where the guard holds: a write's sign is proven there).
|
|
192
|
+
const uses = [];
|
|
193
|
+
const keyOf = (e, path) => (ts.isStringLiteral(strip(e)) ? `named:${strip(e).text}` : path);
|
|
194
|
+
const walk = (ast, rt, path, role) => {
|
|
195
|
+
ast = strip(ast);
|
|
196
|
+
if (!role && ts.isObjectLiteralExpression(ast)) {
|
|
197
|
+
const get = (k) => ast.properties.find((x) => ts.isPropertyAssignment(x) && x.name.getText() === k);
|
|
198
|
+
const a = get('actions'), g = get('guard');
|
|
199
|
+
if (a) {
|
|
200
|
+
const gk = g ? keyOf(g.initializer, `${path}.guard`) : undefined, av = strip(a.initializer);
|
|
201
|
+
const aks = ts.isArrayLiteralExpression(av) ? av.elements.map((el, i) => keyOf(el, `${path}.actions[${i}]`)) : [keyOf(av, `${path}.actions`)];
|
|
202
|
+
for (const ak of aks)
|
|
203
|
+
uses.push({ action: ak, ...(gk ? { guard: gk } : {}) });
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
if (role === 'actions' && !ts.isArrayLiteralExpression(ast)) {
|
|
207
|
+
if (typeof rt === 'function' && !ts.isStringLiteral(ast))
|
|
208
|
+
inlineActions.push([path, actionOf(ast, path)]);
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
if (role === 'guard') {
|
|
212
|
+
if (typeof rt === 'function')
|
|
213
|
+
inlineGuards.push([path, guardOf(ast, path)]);
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
if (ts.isObjectLiteralExpression(ast) && rt && typeof rt === 'object') {
|
|
217
|
+
for (const p of ast.properties) {
|
|
218
|
+
if (!ts.isPropertyAssignment(p))
|
|
219
|
+
continue;
|
|
220
|
+
const k = ts.isIdentifier(p.name) || ts.isStringLiteral(p.name) ? p.name.text : p.name.getText(), sub = rt[k];
|
|
221
|
+
if (sub === undefined || k === 'context' || k === 'types')
|
|
222
|
+
continue;
|
|
223
|
+
walk(p.initializer, sub, `${path}${key(k)}`, k === 'actions' || k === 'entry' || k === 'exit' ? 'actions' : k === 'guard' ? 'guard' : undefined);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
else if (ts.isArrayLiteralExpression(ast) && Array.isArray(rt))
|
|
227
|
+
ast.elements.forEach((el, i) => walk(el, rt[i], `${path}[${i}]`, role));
|
|
228
|
+
};
|
|
229
|
+
if (config)
|
|
230
|
+
walk(config, machine.config, `${opts.entry}.config`);
|
|
231
|
+
if (inlineActions.length || inlineGuards.length)
|
|
232
|
+
notes.push(`${inlineActions.length} inline actions and ${inlineGuards.length} inline guards, each given by its place in the config`);
|
|
233
|
+
for (const [p, ws] of inlineActions)
|
|
234
|
+
actions.push([`(inline)${p}`, ws]);
|
|
235
|
+
// Which context numbers are naturals: as a rule's state, each written by every use of an action that writes it,
|
|
236
|
+
// under its transition's guard (an action no transition names, or one named elsewhere, without one).
|
|
237
|
+
const writesOf = new Map(actions.map(([n, ws]) => [n.startsWith('(inline)') ? n.slice(8) : `named:${n}`, ws]));
|
|
238
|
+
const guardOfKey = new Map([...guards.map(([n, g]) => [`named:${n}`, g]), ...inlineGuards]);
|
|
239
|
+
const used = new Set(uses.map(u => u.action));
|
|
240
|
+
const all = [...uses, ...[...writesOf.keys()].filter(k => !used.has(k)).map(action => ({ action }))];
|
|
241
|
+
const writes = {};
|
|
242
|
+
for (const [k, x] of ctxVars) {
|
|
243
|
+
let w;
|
|
244
|
+
all.forEach((u, i) => {
|
|
245
|
+
const t = writesOf.get(u.action)?.[k], g = u.guard ? guardOfKey.get(u.guard) : undefined;
|
|
246
|
+
if (!t || t.s !== 'num')
|
|
247
|
+
return;
|
|
248
|
+
const under = g && !('in' in g) ? I.nite(g, t.e, I.nvar(x.name)) : t.e;
|
|
249
|
+
w = { s: 'num', e: I.nite(I.bvar(`$use${i}`), under, w && w.s === 'num' ? w.e : I.nvar(x.name)) };
|
|
250
|
+
});
|
|
251
|
+
if (w)
|
|
252
|
+
writes[x.name] = w;
|
|
253
|
+
}
|
|
254
|
+
const vars = [...s.vars.values()];
|
|
255
|
+
const model = { name: opts.entry, shape: 'reducer', file, entry: opts.entry, params: [], inputs: vars.filter(x => x.role === 'input'), state: vars.filter(x => x.role === 'state'), maps: [],
|
|
256
|
+
init: init0, writes, mapWrites: {}, outputs: [], refuse: I.F, pre: I.T, layout: { k: 'rec', fields: [] }, events: [], notes: [], hints: s.hints };
|
|
257
|
+
const { sorts, notes: sn } = sortsOf(model);
|
|
258
|
+
notes.push(...sn);
|
|
259
|
+
const P = { sorts, m: model, hoisted: new Map(), choiceVars: new Map() };
|
|
260
|
+
const cx = () => ({ m: model, sorts, atoms: [] });
|
|
261
|
+
const envOf = (...xs) => { const vs = new Set(); for (const x of xs)
|
|
262
|
+
I.varsOf(x, vs); return `{${[...vs].join(', ')}}`; };
|
|
263
|
+
const parts = [];
|
|
264
|
+
if (model.inputs.length)
|
|
265
|
+
parts.push(`inputs: {${model.inputs.map(x => `${x.name}: ${kindOf(x, sorts)}`).join(', ')}}`);
|
|
266
|
+
const ints = model.state.filter(x => x.sort.k === 'num' && sorts.get(x.name) === 'int');
|
|
267
|
+
if (ints.length)
|
|
268
|
+
parts.push(`context: {${ints.map(x => `${x.name}: int.from(${init0[x.name].e.v})`).join(', ')}}`);
|
|
269
|
+
if (guards.length)
|
|
270
|
+
parts.push(`guards: {${guards.map(([n, g]) => `${JSON.stringify(n)}: ${'in' in g ? `env => env.in(${JSON.stringify(g.in)})` : `(${envOf(g)}) => ${pb(g, P, cx())}`}`).join(', ')}}`);
|
|
271
|
+
const namedActions = actions.filter(([n]) => !n.startsWith('(inline)'));
|
|
272
|
+
if (namedActions.length)
|
|
273
|
+
parts.push(`actions: {${namedActions.map(([n, ws]) => `${JSON.stringify(n)}: ${ws ? `(${envOf(...Object.values(ws).map(t => t.e))}) => ({${Object.entries(ws).map(([k, t]) => `${k}: ${pterm(t, P, cx(), k)}`).join(', ')}})` : 'null'}`).join(', ')}}`);
|
|
274
|
+
const named = actions.filter(([n]) => !n.startsWith('(inline)'));
|
|
275
|
+
const guardSrc = (g) => ('in' in g ? `env => env.in(${JSON.stringify(g.in)})` : `(${envOf(g)}) => ${pb(g, P, cx())}`);
|
|
276
|
+
const actionSrc = (ws) => (ws ? `(${envOf(...Object.values(ws).map(t => t.e))}) => ({${Object.entries(ws).map(([k, t]) => `${k}: ${pterm(t, P, cx(), k)}`).join(', ')}})` : 'null');
|
|
277
|
+
if (inlineGuards.length || inlineActions.length)
|
|
278
|
+
parts.push(`inline: {${[inlineGuards.length ? `guards: new Map([${inlineGuards.map(([p, g]) => `[${p}, ${guardSrc(g)}]`).join(', ')}])` : '', inlineActions.length ? `actions: new Map([${inlineActions.map(([p, ws]) => `[${p}, ${actionSrc(ws)}]`).join(', ')}])` : ''].filter(Boolean).join(', ')}}`);
|
|
279
|
+
const bridge = `{${parts.join(', ')}}`;
|
|
280
|
+
const source = [
|
|
281
|
+
`// Extracted by gdp-wired/extract from ${file} (${opts.entry}, an XState machine): its guards and actions read from setup().`,
|
|
282
|
+
`// Checked against XState's own actor; read again with extractXState() after the code changes.`,
|
|
283
|
+
`import {fromXState} from 'gdp-wired/xstate'`,
|
|
284
|
+
...(/\b(int|nat|bool|oneOf|str)\b/.test(bridge) ? [`import {${['bool', 'int', 'nat', 'oneOf', 'str', 'when', 'all', 'any', 'not', 'min', 'max', 'lit', 'Int', 'yes', 'no'].filter(n => new RegExp(`\\b${n}\\b`).test(bridge.replace(/'[^']*'|"[^"]*"/g, ''))).join(', ')}} from 'gdp-wired'`] : []),
|
|
285
|
+
`import {${opts.entry}} from './${file.replace(/\.(ts|js)$/, '')}'`,
|
|
286
|
+
'',
|
|
287
|
+
`export const ${opts.entry}Chart = fromXState(${opts.entry}, ${bridge})`,
|
|
288
|
+
'',
|
|
289
|
+
].join('\n');
|
|
290
|
+
const NAMES = ['nat', 'int', 'bool', 'oneOf', 'str', 'when', 'min', 'max', 'all', 'any', 'not', 'yes', 'no', 'lit', 'Int'];
|
|
291
|
+
void named;
|
|
292
|
+
const chart = compileFunction([...NAMES, 'fromXState', opts.entry], `return fromXState(${opts.entry}, ${bridge})`)(...NAMES.map(n => dsl[n]), fromXState, machine);
|
|
293
|
+
// The check: XState's actor and the chart's compiled rule on the same events, payloads drawn for every input read.
|
|
294
|
+
let x = opts.check?.seed ?? 3;
|
|
295
|
+
const rand = (k) => { x = (x * 1103515245 + 12345) % 2 ** 31; return Math.floor(x / 2 ** 31 * k); };
|
|
296
|
+
const draw = (v) => (v.sort.k === 'bool' ? rand(2) === 1 : v.sort.k === 'choice' ? v.sort.values[rand(v.sort.values.length)] : v.sort.k === 'str' ? ['a', 'b', ''][rand(3)] : sorts.get(v.name) === 'nat' ? rand(12) : rand(25) - 12);
|
|
297
|
+
const runs = opts.check?.runs ?? 200, depth = opts.check?.depth ?? 16;
|
|
298
|
+
let result;
|
|
299
|
+
try {
|
|
300
|
+
result = conforms(chart, machine, opts.xstate.createActor, { runs, depth, seed: opts.check?.seed ?? 3, payload: () => Object.fromEntries(model.inputs.map(v => [v.name, draw(v)])) });
|
|
301
|
+
}
|
|
302
|
+
catch (e) {
|
|
303
|
+
result = { checked: 0, failure: `the chart's run throws: ${e.message}` };
|
|
304
|
+
}
|
|
305
|
+
const coverage = { arms: box.arms.length, hit: box.counts.filter(n => n > 0).length, missed: box.arms.filter((_, i) => box.counts[i] === 0).map(a => `${a.label} at ${a.where}`) };
|
|
306
|
+
const evidence = { runs, events: result.checked, coverage, ms: Math.round(performance.now() - t0), ...(result.failure ? { mismatch: result.failure } : {}) };
|
|
307
|
+
if (result.failure)
|
|
308
|
+
return { ok: false, source, evidence, notes, refusals: [{ where: file, what: `the chart and XState differ: ${result.failure}` }] };
|
|
309
|
+
return { ok: true, source, chart, evidence, notes, refusals: [] };
|
|
310
|
+
}
|
|
311
|
+
catch (e) {
|
|
312
|
+
if (e instanceof Refusal)
|
|
313
|
+
return { ok: false, refusals: [{ where: e.where, what: e.what }], notes };
|
|
314
|
+
// fromXState's own refusals (`always`, `after`, `invoke`, ...), with its reason.
|
|
315
|
+
const msg = e.message;
|
|
316
|
+
if (/has no chart counterpart|refus|inline|give its|a parallel state|several targets|wildcard|shallow history|both write|forbidden event|entry actions|exit actions|no state/.test(msg))
|
|
317
|
+
return { ok: false, refusals: [{ where: file, what: `fromXState: ${msg}` }], notes };
|
|
318
|
+
throw e;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { Rule } from './dsl.js';
|
|
2
|
+
import type { Law } from './machine.js';
|
|
3
|
+
import { type Model, Refusal, type Term } from './extract-read.js';
|
|
4
|
+
import { type ReadOptions } from './extract-shapes.js';
|
|
5
|
+
import { type Sorts } from './extract-print.js';
|
|
6
|
+
import { type CheckOptions, type Evidence } from './extract-check.js';
|
|
7
|
+
export type ExtractOptions = ReadOptions & {
|
|
8
|
+
file?: string;
|
|
9
|
+
shape?: 'class' | 'functions';
|
|
10
|
+
domains?: Record<string, 'nat' | 'int'>;
|
|
11
|
+
check?: CheckOptions;
|
|
12
|
+
};
|
|
13
|
+
export type Extraction = {
|
|
14
|
+
ok: boolean;
|
|
15
|
+
rule?: Rule;
|
|
16
|
+
invariants?: Law[];
|
|
17
|
+
source?: string;
|
|
18
|
+
model?: Model;
|
|
19
|
+
sorts?: Sorts;
|
|
20
|
+
refusals: {
|
|
21
|
+
where: string;
|
|
22
|
+
what: string;
|
|
23
|
+
}[];
|
|
24
|
+
evidence?: Evidence;
|
|
25
|
+
notes: string[];
|
|
26
|
+
};
|
|
27
|
+
export declare function extract(code: string, opts: ExtractOptions): Extraction;
|
|
28
|
+
export declare const toSource: (x: Extraction) => string;
|
|
29
|
+
export type { Evidence, Model, Term };
|
|
30
|
+
export { Refusal };
|
|
31
|
+
export { extractXState, type XStateExtraction, type XStateOptions } from './extract-xstate.js';
|
|
@@ -0,0 +1,249 @@
|
|
|
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
|
|
4
|
+
// same way, as a builder value and as the source that makes it (`toSource`), for a user to read and keep:
|
|
5
|
+
//
|
|
6
|
+
// const x = extract(readFileSync('bucket.ts', 'utf8'), {file: 'bucket.ts', entry: 'TokenBucket'})
|
|
7
|
+
// if (!x.ok) console.log(x.refusals) // where and why
|
|
8
|
+
// proveRule(x.rule, [x.rule.law('within capacity', ({tokens, capacity}) => tokens.atMost(capacity))])
|
|
9
|
+
// writeFileSync('bucket.rule.ts', toSource(x))
|
|
10
|
+
//
|
|
11
|
+
// The extractor is untrusted. The rule is checked against the original code by running both (core/extract-check.ts):
|
|
12
|
+
// 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
|
+
// difference; nothing is adopted that the check didn't run. What the subset doesn't read is refused where it is, with
|
|
15
|
+
// the reason, never approximated. XState machines go through `fromXState` (core/xstate.ts), their guards and actions
|
|
16
|
+
// read the same way (`extractXState`).
|
|
17
|
+
//
|
|
18
|
+
// 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.
|
|
27
|
+
import * as dsl from "./dsl.js";
|
|
28
|
+
import { compileFunction } from "./machine.js";
|
|
29
|
+
import * as I from "./extract-ir.js";
|
|
30
|
+
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";
|
|
33
|
+
import { check } from "./extract-check.js";
|
|
34
|
+
export function extract(code, opts) {
|
|
35
|
+
const file = opts.file ?? 'input.ts', notes = [];
|
|
36
|
+
let model;
|
|
37
|
+
try {
|
|
38
|
+
const isClass = opts.shape ? opts.shape === 'class' : new RegExp(`\\bclass\\s+${opts.entry}\\b|\\b${opts.entry}\\s*=\\s*class\\b`).test(code);
|
|
39
|
+
// The file sits in the working directory, so its imports (xstate, say) resolve as the project's do.
|
|
40
|
+
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);
|
|
42
|
+
model.file = file;
|
|
43
|
+
}
|
|
44
|
+
catch (e) {
|
|
45
|
+
if (e instanceof Refusal)
|
|
46
|
+
return { ok: false, refusals: [{ where: e.where, what: e.what }], notes };
|
|
47
|
+
throw e;
|
|
48
|
+
}
|
|
49
|
+
let source, body, sorts;
|
|
50
|
+
try {
|
|
51
|
+
const s = sortsOf(model, opts.domains);
|
|
52
|
+
sorts = s.sorts;
|
|
53
|
+
notes.push(...model.notes, ...s.notes);
|
|
54
|
+
body = builderOf(model, sorts);
|
|
55
|
+
source = moduleOf(model, body, file);
|
|
56
|
+
}
|
|
57
|
+
catch (e) {
|
|
58
|
+
if (e instanceof Refusal)
|
|
59
|
+
return { ok: false, refusals: [{ where: e.where, what: e.what }], notes, model };
|
|
60
|
+
throw e;
|
|
61
|
+
}
|
|
62
|
+
let rule, invariants;
|
|
63
|
+
try {
|
|
64
|
+
rule = evaluate(body);
|
|
65
|
+
invariants = evaluateLaws(rule, invariantsOf(model, sorts));
|
|
66
|
+
}
|
|
67
|
+
catch (e) {
|
|
68
|
+
return { ok: false, source, model, sorts, refusals: [{ where: file, what: `the rule printed doesn't build: ${e.message}` }], notes };
|
|
69
|
+
}
|
|
70
|
+
if (invariants.length)
|
|
71
|
+
source = `${source}\n// What every state of the code is: a law about every state is about the code's with these beside it.\nexport const ${identOf(model)}Invariants = [${invariantsOf(model, sorts).map(x => x.replace(/^r\./, `${identOf(model)}Rule.`)).join(', ')}]\n`;
|
|
72
|
+
const evidence = check(code, file, model, rule, sorts, { ...opts.check, ...(opts.files ? { files: opts.files } : {}), ...(opts.domains ? { given: opts.domains } : {}) });
|
|
73
|
+
if (evidence.mismatch)
|
|
74
|
+
return { ok: false, source, model, sorts, evidence, refusals: [{ where: file, what: `the rule and the code differ: ${evidence.mismatch}` }], notes };
|
|
75
|
+
return { ok: true, rule, ...(invariants.length ? { invariants } : {}), source, model, sorts, evidence, refusals: [], notes };
|
|
76
|
+
}
|
|
77
|
+
// The module a user keeps: the rule, with what it was read from and how it was checked.
|
|
78
|
+
export const toSource = (x) => x.source ?? '';
|
|
79
|
+
// The source is the rule: it is evaluated with the builders, so what is checked is what is printed.
|
|
80
|
+
const NAMES = ['rule', 'nat', 'int', 'bool', 'oneOf', 'str', 'record', 'when', 'min', 'max', 'all', 'any', 'not', 'yes', 'no', 'lit', 'intern', 'Int'];
|
|
81
|
+
function evaluate(body) {
|
|
82
|
+
const f = compileFunction([...NAMES], `return ${body}`);
|
|
83
|
+
const r = f(...NAMES.map(n => dsl[n]));
|
|
84
|
+
void r.machine;
|
|
85
|
+
return r;
|
|
86
|
+
}
|
|
87
|
+
// A map's representation: each key it doesn't hold holds the defaults (as no object of the code holds a value there).
|
|
88
|
+
function invariantsOf(m, sorts) {
|
|
89
|
+
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
|
+
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(', ')}))))`);
|
|
92
|
+
}
|
|
93
|
+
function evaluateLaws(r, xs) {
|
|
94
|
+
if (!xs.length)
|
|
95
|
+
return [];
|
|
96
|
+
const f = compileFunction(['r', 'forall', 'any', 'all'], `return [${xs.join(', ')}]`);
|
|
97
|
+
return f(r, dsl.forall, dsl.any, dsl.all);
|
|
98
|
+
}
|
|
99
|
+
const identOf = (m) => (/^[A-Za-z_$][\w$]*$/.test(m.name) ? m.name.charAt(0).toLowerCase() + m.name.slice(1) : 'extracted');
|
|
100
|
+
function moduleOf(m, body, file) {
|
|
101
|
+
const used = NAMES.filter(n => new RegExp(`(^|[^.\\w$])${n}\\(|(^|[^.\\w$])${n}\\b(?!\\s*:)`).test(body.replace(/'[^']*'/g, "''")) || (n === 'rule'));
|
|
102
|
+
const ident = identOf(m);
|
|
103
|
+
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'}).`,
|
|
105
|
+
`// Checked against the code it was read from; read again with extract() after the code changes.`,
|
|
106
|
+
`import {${[...new Set([...used, ...(m.maps.length ? ['all', 'any', 'forall'] : [])])].sort((a, b) => a.localeCompare(b)).join(', ')}} from 'gdp-wired'`,
|
|
107
|
+
'',
|
|
108
|
+
`export const ${ident}Rule = ${body}`,
|
|
109
|
+
'',
|
|
110
|
+
].join('\n');
|
|
111
|
+
}
|
|
112
|
+
// --- the builder calls ----------------------------------------------------------------------------------------------
|
|
113
|
+
function builderOf(m, sorts) {
|
|
114
|
+
const P = { sorts, m, hoisted: new Map(), choiceVars: new Map() };
|
|
115
|
+
for (const v of [...m.state, ...m.inputs, ...m.params])
|
|
116
|
+
if (v.sort.k === 'choice' && !P.choiceVars.has(v.sort.values.join('\u0000')))
|
|
117
|
+
P.choiceVars.set(v.sort.values.join('\u0000'), v.name);
|
|
118
|
+
const ctx = () => ({ m, sorts, atoms: [] });
|
|
119
|
+
const lines = [`rule(${JSON.stringify(m.name)})`];
|
|
120
|
+
const kinds = (vs) => vs.map(v => `${v.name}: ${kindOf(v, sorts)}`).join(', ');
|
|
121
|
+
if (m.params.length)
|
|
122
|
+
lines.push(` .params({${kinds(m.params)}})`);
|
|
123
|
+
if (m.inputs.length)
|
|
124
|
+
lines.push(` .inputs({${kinds(m.inputs)}})`);
|
|
125
|
+
// The state: each variable from its start (a term over the params where the constructor makes it one).
|
|
126
|
+
const params = (t) => [...I.varsOf(t).vars].filter(n => m.params.some(p => p.name === n));
|
|
127
|
+
const start = (v) => {
|
|
128
|
+
const t = m.init[v.name], ps = params(t.e), fn = (x) => (ps.length ? `({${ps.join(', ')}}) => ${x}` : x);
|
|
129
|
+
const at = pterm(t, P, ctx(), v.name);
|
|
130
|
+
if (v.sort.k === 'num')
|
|
131
|
+
return sorts.get(v.name) === 'nat' ? (ps.length ? fn(at) : at) : `int.from(${ps.length ? fn(at) : at})`;
|
|
132
|
+
if (v.sort.k === 'bool')
|
|
133
|
+
return `bool.from(${ps.length ? fn(at) : at === 'yes' ? 'true' : at === 'no' ? 'false' : at})`;
|
|
134
|
+
if (v.sort.k === 'str')
|
|
135
|
+
return `str().from(${ps.length ? fn(at) : at})`;
|
|
136
|
+
return `${kindOf(v, sorts)}.from(${ps.length ? fn(at) : at})`;
|
|
137
|
+
};
|
|
138
|
+
if (m.state.length)
|
|
139
|
+
lines.push(` .state({${m.state.map(v => `${v.name}: ${start(v)}`).join(', ')}})`);
|
|
140
|
+
if (m.maps.length)
|
|
141
|
+
lines.push(` .maps({${m.maps.map((d) => `${d.name}: ${mapKind(d, sorts)}.from(${mapEmpty(d)})`).join(', ')}})`);
|
|
142
|
+
const envOf = (...xs) => {
|
|
143
|
+
const vars = new Set(), maps = new Set();
|
|
144
|
+
for (const x of xs)
|
|
145
|
+
I.varsOf(x, vars, maps);
|
|
146
|
+
return `{${[...vars, ...maps].join(', ')}}`;
|
|
147
|
+
};
|
|
148
|
+
if (!(m.pre.op === 'const' && m.pre.v))
|
|
149
|
+
lines.push(` .pre((${envOf(m.pre)}) => ${pb(m.pre, P, ctx())})`);
|
|
150
|
+
const allowed = I.not(m.refuse);
|
|
151
|
+
if (!(allowed.op === 'const' && allowed.v)) {
|
|
152
|
+
// The choices a printed literal is named by are read in the callback too.
|
|
153
|
+
const text = pb(allowed, P, ctx());
|
|
154
|
+
lines.push(` .assume((${withChoices(envOf(allowed), text, P)}) => ${text})`);
|
|
155
|
+
}
|
|
156
|
+
// The step: a const for each term written more than once (by the code's own local's name where it has one).
|
|
157
|
+
const outs = [];
|
|
158
|
+
const writes = Object.entries(m.writes), mw = Object.entries(m.mapWrites);
|
|
159
|
+
hoist(m, P, [...writes.map(([, t]) => t.e), ...mw.flatMap(([, w]) => [w.has, ...Object.values(w.vals).map(t => t.e), w.key])]);
|
|
160
|
+
const consts = [...P.hoisted.entries()];
|
|
161
|
+
P.hoisted = new Map();
|
|
162
|
+
const defs = [];
|
|
163
|
+
for (const [key, name] of consts) {
|
|
164
|
+
const node = hoistNodes.get(key);
|
|
165
|
+
defs.push(`const ${name} = ${'rel' in node || isBool(node) ? pb(node, P, ctx()) : pterm({ s: 'num', e: node }, P, ctx())}`);
|
|
166
|
+
P.hoisted.set(key, name);
|
|
167
|
+
}
|
|
168
|
+
for (const [n, t] of writes)
|
|
169
|
+
outs.push([n, pterm(t, P, ctx(), n)]);
|
|
170
|
+
for (const [n, w] of mw) {
|
|
171
|
+
const d = m.maps.find(x => x.name === n);
|
|
172
|
+
const vals = d.fields.map(f => `${f.name}: ${pterm(w.vals[f.name], P, { m, sorts, atoms: [w.has] }, `${n}.${f.name}`)}`);
|
|
173
|
+
outs.push([n, `${n}.set(${pk(w.key, P, ctx())}, {has: ${pb(w.has, P, ctx())}, ${vals.join(', ')}})`]);
|
|
174
|
+
}
|
|
175
|
+
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(', ')}}`;
|
|
178
|
+
lines.push(defs.length ? ` .step((${env}) => {\n${defs.map(d => ` ${d}`).join('\n')}\n return ${ret}\n })` : ` .step((${env}) => (${ret}))`);
|
|
179
|
+
return lines.join('\n');
|
|
180
|
+
}
|
|
181
|
+
const isBool = (x) => ['cmp', 'and', 'or', 'not', 'is', 'leq', 'keq'].includes(x.op) || (x.op === 'const' && typeof x.v === 'boolean');
|
|
182
|
+
// The env's names: those the terms read, the choices a literal is printed through, and the maps written.
|
|
183
|
+
function withChoices(env, text, P, extra = []) {
|
|
184
|
+
const names = new Set(env.slice(1, -1).split(', ').filter(Boolean));
|
|
185
|
+
for (const w of P.choiceVars.values())
|
|
186
|
+
if (new RegExp(`\\b${w}\\.of\\(`).test(text))
|
|
187
|
+
names.add(w);
|
|
188
|
+
for (const n of P.hoisted.values())
|
|
189
|
+
names.delete(n);
|
|
190
|
+
for (const n of extra)
|
|
191
|
+
names.add(n);
|
|
192
|
+
return `{${[...names].join(', ')}}`;
|
|
193
|
+
}
|
|
194
|
+
// Terms written more than once, hoisted as consts (inner ones first). A number is hoisted only where its printing
|
|
195
|
+
// doesn't depend on the branch it is read under (a natural everywhere, or an integer everywhere).
|
|
196
|
+
const hoistNodes = new Map();
|
|
197
|
+
function hoist(m, P, roots) {
|
|
198
|
+
const count = new Map(), order = [];
|
|
199
|
+
const visit = (x) => {
|
|
200
|
+
if (!x || typeof x !== 'object')
|
|
201
|
+
return;
|
|
202
|
+
const o = x;
|
|
203
|
+
if (o.op && !['var', 'const', 'lit', 'svar', 'slit', 'num'].includes(o.op)) {
|
|
204
|
+
const k = I.keyOf(o);
|
|
205
|
+
count.set(k, (count.get(k) ?? 0) + 1);
|
|
206
|
+
if (!hoistNodes.has(k))
|
|
207
|
+
hoistNodes.set(k, o);
|
|
208
|
+
if ((count.get(k) ?? 0) > 1)
|
|
209
|
+
return;
|
|
210
|
+
Object.values(o).forEach(visit);
|
|
211
|
+
if (!order.includes(k))
|
|
212
|
+
order.push(k);
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
if (Array.isArray(x))
|
|
216
|
+
x.forEach(visit);
|
|
217
|
+
else
|
|
218
|
+
Object.values(o).forEach(visit);
|
|
219
|
+
};
|
|
220
|
+
roots.forEach(visit);
|
|
221
|
+
let i = 0;
|
|
222
|
+
const names = new Set([...m.params, ...m.inputs, ...m.state].map(v => v.name).concat(m.maps.map(d => d.name)));
|
|
223
|
+
for (const k of order) {
|
|
224
|
+
const node = hoistNodes.get(k), size = k.length;
|
|
225
|
+
if ((count.get(k) ?? 0) < 2 || size < 60)
|
|
226
|
+
continue;
|
|
227
|
+
if (!isBool(node)) {
|
|
228
|
+
const ctx = { m, sorts: P.sorts, atoms: [] }, free = natOK(node, ctx);
|
|
229
|
+
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);
|
|
237
|
+
const hasInt = [...I.varsOf(node).vars].some(n => P.sorts.get(n) === 'int') || cells.some(c => P.sorts.get(c) === 'int');
|
|
238
|
+
if (!free && !hasInt)
|
|
239
|
+
continue;
|
|
240
|
+
}
|
|
241
|
+
let name = m.hints.get(node) ?? `t${++i}`;
|
|
242
|
+
while (names.has(name))
|
|
243
|
+
name = `${name}_`;
|
|
244
|
+
names.add(name);
|
|
245
|
+
P.hoisted.set(k, name);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
export { Refusal };
|
|
249
|
+
export { extractXState } from "./extract-xstate.js";
|
package/dist/core/infer.d.ts
CHANGED