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,993 @@
|
|
|
1
|
+
// The shapes the extractor reads (core/extract.ts): step functions over a state (a reducer `(state, action) => state`,
|
|
2
|
+
// `useReducer`'s, or several functions over one record, each an event), and classes whose methods write their fields
|
|
3
|
+
// (each public method an event, its arguments the request, its result kept as `<method>_result`). Each is executed
|
|
4
|
+
// symbolically (core/extract-read.ts) into a Model: the state's variables, where each sits in the code's own values,
|
|
5
|
+
// the step's writes, what the code refuses (its throws) and how a request is made of the code.
|
|
6
|
+
import ts from 'typescript';
|
|
7
|
+
import * as I from "./extract-ir.js";
|
|
8
|
+
import { Exec, Refusal, Retype, memberName, normalize, program, shapeOf } from "./extract-read.js";
|
|
9
|
+
const at0 = (sf) => sf.statements[0] ?? sf;
|
|
10
|
+
const where = (n) => { const sf = n.getSourceFile(), { line, character } = sf.getLineAndCharacterOfPosition(n.getStart()); return `${sf.fileName.split('/').pop()}:${line + 1}:${character + 1}`; };
|
|
11
|
+
const refuse = (n, what) => { throw new Refusal(where(n), what); };
|
|
12
|
+
function setupOf(code, file, typed = {}, files = {}) {
|
|
13
|
+
const root = file.slice(0, file.length - (file.split('/').pop().length)), extra = Object.fromEntries(Object.entries(files).map(([p, c]) => [normalize(`${root}${p}`), c]));
|
|
14
|
+
const { sf, checker } = program(code, file, extra);
|
|
15
|
+
return { ours: f => f === sf || f.fileName in extra, checker, sf, names: new Set(), vars: new Map(), maps: new Map(), lazySorts: new Map(Object.entries(typed)), nowRole: 'input', hints: new WeakMap(), notes: new Set(), lazy: new Map() };
|
|
16
|
+
}
|
|
17
|
+
// The state's tree: a variable per scalar, a heap object per record, a map per keyed field.
|
|
18
|
+
function build(ex, shape, path, heap, origin, at) {
|
|
19
|
+
const name = path.join('_') || 'state';
|
|
20
|
+
switch (shape.k) {
|
|
21
|
+
case 'num':
|
|
22
|
+
case 'bool':
|
|
23
|
+
case 'choice': {
|
|
24
|
+
const x = ex.newVar(name, shape, 'state');
|
|
25
|
+
return { layout: { k: 'scalar', name: x.name }, v: Exec.valueOf(x) };
|
|
26
|
+
}
|
|
27
|
+
// A string: compared for equality and set (str(), interned), nothing else read of it.
|
|
28
|
+
case 'str': {
|
|
29
|
+
const x = ex.newVar(name, shape, 'state');
|
|
30
|
+
return { layout: { k: 'scalar', name: x.name }, v: Exec.valueOf(x) };
|
|
31
|
+
}
|
|
32
|
+
case 'rec': {
|
|
33
|
+
const fields = new Map(), layout = [];
|
|
34
|
+
for (const [f, s] of shape.fields) {
|
|
35
|
+
const r = build(ex, s, [...path, f], heap, origin, at);
|
|
36
|
+
fields.set(f, r.v);
|
|
37
|
+
layout.push([f, r.layout]);
|
|
38
|
+
}
|
|
39
|
+
const id = path.length ? `${origin}.${path.join('.')}` : origin === 'this' ? 'this' : 'state';
|
|
40
|
+
heap.set(id, { k: 'rec', fields, origin });
|
|
41
|
+
return { layout: { k: 'rec', fields: layout }, v: { t: 'ref', id } };
|
|
42
|
+
}
|
|
43
|
+
case 'map': {
|
|
44
|
+
const decl = mapDecl(ex, shape, name, at), id = `${origin}.${path.join('.')}`;
|
|
45
|
+
heap.set(id, { k: 'map', base: decl.name, decl, origin, gen: 0 });
|
|
46
|
+
return { layout: { k: 'map', name: decl.name }, v: { t: 'ref', id } };
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
function mapDecl(ex, shape, name, at) {
|
|
51
|
+
const scalar = shape.val.k !== 'rec';
|
|
52
|
+
const fields = shape.val.k === 'rec' ? shape.val.fields.map(([f, s]) => {
|
|
53
|
+
if (s.k !== 'num' && s.k !== 'bool' && s.k !== 'choice')
|
|
54
|
+
return refuse(at, `${name}: a map whose values hold ${s.k === 'str' ? 'a string' : 'a nested value'} in ${f}`);
|
|
55
|
+
if (f === 'has')
|
|
56
|
+
return refuse(at, `${name}: a map value with a field named has (the rule keeps whether a key is there under that name)`);
|
|
57
|
+
return { name: f, sort: s, role: 'state' };
|
|
58
|
+
}) : [{ name: 'value', sort: shape.val.k === 'num' || shape.val.k === 'bool' || shape.val.k === 'choice' ? shape.val : refuse(at, `${name}: a map of ${shape.val.k === 'str' ? 'strings' : 'maps'}`), role: 'state' }];
|
|
59
|
+
const decl = { name: ex.fresh(name), key: shape.key, fields, scalar, js: shape.js };
|
|
60
|
+
ex.s.maps.set(decl.name, decl);
|
|
61
|
+
return decl;
|
|
62
|
+
}
|
|
63
|
+
function materialize(ex, v, layout, p, at, out = { leaves: new Map(), maps: new Map() }) {
|
|
64
|
+
const deref = (x) => { while (x.t === 'ref') {
|
|
65
|
+
const o = p.heap.get(x.id);
|
|
66
|
+
if (o?.k !== 'alias')
|
|
67
|
+
break;
|
|
68
|
+
x = o.to;
|
|
69
|
+
} return x; };
|
|
70
|
+
v = deref(v);
|
|
71
|
+
if (v.t === 'phi' && layout.k !== 'scalar') {
|
|
72
|
+
// One of two objects by a condition: each side's state, by the condition.
|
|
73
|
+
const a = materialize(ex, v.a, layout, p, at), b = materialize(ex, v.b, layout, p, at), both = mergeVals(ex, v.c, a, b, at);
|
|
74
|
+
for (const [n, x] of both.leaves)
|
|
75
|
+
out.leaves.set(n, x);
|
|
76
|
+
for (const [n, w] of both.maps)
|
|
77
|
+
out.maps.set(n, w);
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
switch (layout.k) {
|
|
81
|
+
case 'scalar': {
|
|
82
|
+
const sort = ex.s.vars.get(layout.name).sort;
|
|
83
|
+
if (v.t === 'opt') {
|
|
84
|
+
if (!ex.known(p, v.has))
|
|
85
|
+
refuse(at, `${layout.name} may be set to undefined`);
|
|
86
|
+
v = v.v;
|
|
87
|
+
}
|
|
88
|
+
const ok = (sort.k === 'num' && v.t === 'num') || (sort.k === 'bool' && v.t === 'bool') || (sort.k === 'choice' && (v.t === 'choice' || v.t === 'str')) || (sort.k === 'str' && v.t === 'str');
|
|
89
|
+
if (!ok) {
|
|
90
|
+
// An untyped input written here: of this field's sort, and the step read again.
|
|
91
|
+
const e = v.t === 'num' || v.t === 'bool' ? v.e : v.t === 'str' ? v.e : undefined;
|
|
92
|
+
const name = e && (e.op === 'var' || e.op === 'svar') ? e.name : undefined, lz = name ? ex.s.lazy.get(name) : undefined;
|
|
93
|
+
if (lz && !ex.s.lazySorts.has(`${lz.prefix}${lz.field}`))
|
|
94
|
+
throw new Retype(`${lz.prefix}${lz.field}`, sort);
|
|
95
|
+
refuse(at, `${layout.name} is set to a ${v.t}`);
|
|
96
|
+
}
|
|
97
|
+
out.leaves.set(layout.name, sort.k === 'choice' ? { t: 'choice', e: ex.asChoice(v, sort.values, at), values: sort.values } : v);
|
|
98
|
+
return out;
|
|
99
|
+
}
|
|
100
|
+
case 'rec': {
|
|
101
|
+
if (v.t === 'cell')
|
|
102
|
+
return refuse(at, 'a state made of a map cell');
|
|
103
|
+
const o = v.t === 'ref' ? p.heap.get(v.id) : undefined;
|
|
104
|
+
if (o?.k !== 'rec')
|
|
105
|
+
return refuse(at, `returns ${v.t === 'undef' ? 'undefined' : 'other than the state\'s record'} on some path`);
|
|
106
|
+
for (const f of o.fields.keys())
|
|
107
|
+
if (!layout.fields.some(([g]) => g === f))
|
|
108
|
+
refuse(at, `returns a state with a field ${f} its type doesn't have`);
|
|
109
|
+
for (const [f, sub] of layout.fields)
|
|
110
|
+
materialize(ex, o.fields.get(f) ?? refuse(at, `returns a state without ${f}`), sub, p, at, out);
|
|
111
|
+
return out;
|
|
112
|
+
}
|
|
113
|
+
case 'map': {
|
|
114
|
+
const o = v.t === 'ref' ? p.heap.get(v.id) : undefined;
|
|
115
|
+
if (o?.k !== 'map' || o.base !== layout.name)
|
|
116
|
+
return refuse(at, `${layout.name} is set to other than a copy of itself (a map replaced whole is not in the subset)`);
|
|
117
|
+
out.maps.set(layout.name, o.w);
|
|
118
|
+
return out;
|
|
119
|
+
}
|
|
120
|
+
case 'const': return out;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
const strip = (p) => ({ pc: p.pc, locals: new Map(), heap: new Map(), wrote: [], nows: p.nows });
|
|
124
|
+
// The condition that tells two paths apart (as Exec.merge reads it).
|
|
125
|
+
function split(a, b) {
|
|
126
|
+
let i = 0;
|
|
127
|
+
while (i < a.pc.length && i < b.pc.length && a.pc[i] === b.pc[i])
|
|
128
|
+
i++;
|
|
129
|
+
const ra = a.pc.slice(i), rb = b.pc.slice(i);
|
|
130
|
+
return ra.length ? I.and(...ra) : I.not(I.and(...rb));
|
|
131
|
+
}
|
|
132
|
+
function mergeVals(ex, c, a, b, at) {
|
|
133
|
+
const leaves = new Map([...a.leaves].map(([n, v]) => [n, ex.mergeScalar(c, v, b.leaves.get(n), at)]));
|
|
134
|
+
const maps = new Map([...a.maps].map(([n, w]) => [n, ex.mergeWrites(c, ex.s.maps.get(n), w, b.maps.get(n), at)]));
|
|
135
|
+
return { leaves, maps };
|
|
136
|
+
}
|
|
137
|
+
// Every way a step ends (each a path and its state), as one state by cases.
|
|
138
|
+
function joinAll(ex, outs, at) {
|
|
139
|
+
if (!outs.length)
|
|
140
|
+
return refuse(at, 'no path through the step returns');
|
|
141
|
+
let [pa, acc] = outs.at(-1);
|
|
142
|
+
for (let i = outs.length - 2; i >= 0; i--) {
|
|
143
|
+
const [p, sv] = outs[i];
|
|
144
|
+
acc = mergeVals(ex, split(p, pa), sv, acc, at);
|
|
145
|
+
pa = ex.merge(strip(p), strip(pa), at);
|
|
146
|
+
}
|
|
147
|
+
return acc;
|
|
148
|
+
}
|
|
149
|
+
const termOf = (v) => (v.t === 'num' ? { s: 'num', e: v.e } : v.t === 'bool' ? { s: 'bool', e: v.e } : v.t === 'choice' ? { s: 'choice', e: v.e } : v.t === 'str' ? { s: 'str', e: v.e } : (() => { throw new Error(`a ${v.t} as a term`); })());
|
|
150
|
+
const sameTerm = (a, b) => (a.t === 'num' || a.t === 'bool' || a.t === 'choice' || a.t === 'str') && (b.t === 'num' || b.t === 'bool' || b.t === 'choice' || b.t === 'str') && I.same(a.e, b.e);
|
|
151
|
+
const refusalOf = (ex) => I.or(...ex.throws.map(t => I.and(...t.pc)));
|
|
152
|
+
const EMPTY = Symbol('an empty map');
|
|
153
|
+
function constValue(e, s) {
|
|
154
|
+
if (ts.isParenthesizedExpression(e) || ts.isAsExpression(e) || ts.isSatisfiesExpression(e))
|
|
155
|
+
return constValue(e.expression, s);
|
|
156
|
+
if (ts.isNumericLiteral(e)) {
|
|
157
|
+
const x = Number(e.text);
|
|
158
|
+
return Number.isSafeInteger(x) ? x : refuse(e, `${e.text}: not a safe integer`);
|
|
159
|
+
}
|
|
160
|
+
if (ts.isPrefixUnaryExpression(e) && e.operator === ts.SyntaxKind.MinusToken) {
|
|
161
|
+
const x = constValue(e.operand, s);
|
|
162
|
+
return typeof x === 'number' ? -x : refuse(e, 'a negated non-number');
|
|
163
|
+
}
|
|
164
|
+
if (ts.isStringLiteral(e) || ts.isNoSubstitutionTemplateLiteral(e))
|
|
165
|
+
return e.text;
|
|
166
|
+
if (e.kind === ts.SyntaxKind.TrueKeyword)
|
|
167
|
+
return true;
|
|
168
|
+
if (e.kind === ts.SyntaxKind.FalseKeyword)
|
|
169
|
+
return false;
|
|
170
|
+
if (ts.isNewExpression(e) && ts.isIdentifier(e.expression) && e.expression.text === 'Map' && !e.arguments?.length)
|
|
171
|
+
return EMPTY;
|
|
172
|
+
if (ts.isObjectLiteralExpression(e)) {
|
|
173
|
+
const out = {};
|
|
174
|
+
for (const p of e.properties) {
|
|
175
|
+
if (ts.isPropertyAssignment(p) && (ts.isIdentifier(p.name) || ts.isStringLiteral(p.name)))
|
|
176
|
+
out[p.name.text] = constValue(p.initializer, s);
|
|
177
|
+
else if (ts.isShorthandPropertyAssignment(p))
|
|
178
|
+
out[p.name.text] = constValue(p.name, s);
|
|
179
|
+
else if (ts.isSpreadAssignment(p)) {
|
|
180
|
+
const x = constValue(p.expression, s);
|
|
181
|
+
if (typeof x !== 'object')
|
|
182
|
+
refuse(p, 'a spread of other than an object');
|
|
183
|
+
Object.assign(out, x);
|
|
184
|
+
}
|
|
185
|
+
else
|
|
186
|
+
refuse(p, 'an initial state entry the subset doesn\'t read');
|
|
187
|
+
}
|
|
188
|
+
return out;
|
|
189
|
+
}
|
|
190
|
+
if (ts.isPropertyAccessExpression(e)) {
|
|
191
|
+
// A field of a const's object literal: that field's own initializer (the others aren't read).
|
|
192
|
+
const lit = literalOf(e.expression, s);
|
|
193
|
+
const prop = lit && ts.isObjectLiteralExpression(lit) ? lit.properties.find((x) => ts.isPropertyAssignment(x) && x.name.getText() === e.name.text) : undefined;
|
|
194
|
+
if (!prop)
|
|
195
|
+
return refuse(e, `${e.getText()}: an initial state the subset can't read (give it in init)`);
|
|
196
|
+
return constValue(prop.initializer, s);
|
|
197
|
+
}
|
|
198
|
+
if (ts.isArrayLiteralExpression(e))
|
|
199
|
+
return refuse(e, 'an array (lists are not in the subset yet)');
|
|
200
|
+
if (ts.isIdentifier(e)) {
|
|
201
|
+
const decl = aliased(s, e)?.valueDeclaration;
|
|
202
|
+
if (decl && ts.isVariableDeclaration(decl) && decl.initializer && decl.parent.flags & ts.NodeFlags.Const)
|
|
203
|
+
return constValue(decl.initializer, s);
|
|
204
|
+
return refuse(e, `${e.text}: an initial state the subset can't read (give it in init)`);
|
|
205
|
+
}
|
|
206
|
+
return refuse(e, 'an initial state the subset can\'t read (give it in init)');
|
|
207
|
+
}
|
|
208
|
+
const aliased = (s, e) => { const sym = s.checker.getSymbolAtLocation(e); return sym && sym.flags & ts.SymbolFlags.Alias ? s.checker.getAliasedSymbol(sym) : sym; };
|
|
209
|
+
// An expression's object literal, through consts.
|
|
210
|
+
function literalOf(e, s) {
|
|
211
|
+
if (ts.isParenthesizedExpression(e) || ts.isAsExpression(e) || ts.isSatisfiesExpression(e))
|
|
212
|
+
return literalOf(e.expression, s);
|
|
213
|
+
if (ts.isObjectLiteralExpression(e))
|
|
214
|
+
return e;
|
|
215
|
+
if (ts.isIdentifier(e)) {
|
|
216
|
+
const d = aliased(s, e)?.valueDeclaration;
|
|
217
|
+
return d && ts.isVariableDeclaration(d) && d.initializer && d.parent.flags & ts.NodeFlags.Const ? literalOf(d.initializer, s) : undefined;
|
|
218
|
+
}
|
|
219
|
+
if (ts.isPropertyAccessExpression(e)) {
|
|
220
|
+
const o = literalOf(e.expression, s);
|
|
221
|
+
const p = o && ts.isObjectLiteralExpression(o) ? o.properties.find((x) => ts.isPropertyAssignment(x) && x.name.getText() === e.name.text) : undefined;
|
|
222
|
+
return p && literalOf(p.initializer, s);
|
|
223
|
+
}
|
|
224
|
+
return undefined;
|
|
225
|
+
}
|
|
226
|
+
function initLeaves(raw, layout, s, at, out = {}) {
|
|
227
|
+
switch (layout.k) {
|
|
228
|
+
case 'scalar': {
|
|
229
|
+
const sort = s.vars.get(layout.name).sort;
|
|
230
|
+
if (sort.k === 'num' && typeof raw === 'number' && Number.isSafeInteger(raw))
|
|
231
|
+
out[layout.name] = { s: 'num', e: I.num(raw) };
|
|
232
|
+
else if (sort.k === 'bool' && typeof raw === 'boolean')
|
|
233
|
+
out[layout.name] = { s: 'bool', e: raw ? I.T : I.F };
|
|
234
|
+
else if (sort.k === 'choice' && typeof raw === 'string' && sort.values.includes(raw))
|
|
235
|
+
out[layout.name] = { s: 'choice', e: I.llit(raw, sort.values) };
|
|
236
|
+
else if (sort.k === 'str' && typeof raw === 'string')
|
|
237
|
+
out[layout.name] = { s: 'str', e: { op: 'slit', value: raw } };
|
|
238
|
+
else
|
|
239
|
+
refuse(at, `the initial ${layout.name} (${String(raw)}) is not of its type`);
|
|
240
|
+
return out;
|
|
241
|
+
}
|
|
242
|
+
case 'rec':
|
|
243
|
+
if (typeof raw !== 'object' || raw === null)
|
|
244
|
+
return refuse(at, 'an initial state of another shape');
|
|
245
|
+
for (const [f, sub] of layout.fields)
|
|
246
|
+
initLeaves(raw[f], sub, s, at, out);
|
|
247
|
+
return out;
|
|
248
|
+
case 'map':
|
|
249
|
+
if (raw !== EMPTY && !(typeof raw === 'object' && raw !== null && !Object.keys(raw).length) && !(raw instanceof Map && !raw.size))
|
|
250
|
+
refuse(at, `${layout.name} starts with entries (a map starts empty in the subset)`);
|
|
251
|
+
return out;
|
|
252
|
+
case 'const': return out;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
// An untyped state's shape from its initial value given (numbers, booleans, records of them).
|
|
256
|
+
function shapeOfRaw(raw, at, s) {
|
|
257
|
+
s.notes.add('the state is untyped: its type is the initial state\'s given');
|
|
258
|
+
if (typeof raw === 'number')
|
|
259
|
+
return { k: 'num' };
|
|
260
|
+
if (typeof raw === 'boolean')
|
|
261
|
+
return { k: 'bool' };
|
|
262
|
+
if (typeof raw === 'object' && raw !== null && !(raw instanceof Map) && Object.keys(raw).length)
|
|
263
|
+
return { k: 'rec', fields: Object.entries(raw).map(([f, x]) => [f, shapeOfRaw(x, at, s)]) };
|
|
264
|
+
return refuse(at, `an untyped state whose initial value (${JSON.stringify(raw)}) says no type: annotate it`);
|
|
265
|
+
}
|
|
266
|
+
// --- step functions -------------------------------------------------------------------------------------------------
|
|
267
|
+
function findFunction(sf, name) {
|
|
268
|
+
for (const st of sf.statements) {
|
|
269
|
+
if (ts.isFunctionDeclaration(st) && (st.name?.text === name || (name === 'default' && st.modifiers?.some(m => m.kind === ts.SyntaxKind.DefaultKeyword))))
|
|
270
|
+
return st;
|
|
271
|
+
if (ts.isVariableStatement(st))
|
|
272
|
+
for (const d of st.declarationList.declarations)
|
|
273
|
+
if (ts.isIdentifier(d.name) && d.name.text === name && d.initializer) {
|
|
274
|
+
const init = ts.isParenthesizedExpression(d.initializer) ? d.initializer.expression : d.initializer;
|
|
275
|
+
if (ts.isArrowFunction(init) || ts.isFunctionExpression(init))
|
|
276
|
+
return init;
|
|
277
|
+
}
|
|
278
|
+
if (name === 'default' && ts.isExportAssignment(st) && (ts.isArrowFunction(st.expression) || ts.isFunctionExpression(st.expression)))
|
|
279
|
+
return st.expression;
|
|
280
|
+
if (name === 'default' && ts.isExportAssignment(st) && ts.isIdentifier(st.expression))
|
|
281
|
+
return findFunction(sf, st.expression.text);
|
|
282
|
+
}
|
|
283
|
+
return refuse(at0(sf), `no function ${name} in the file`);
|
|
284
|
+
}
|
|
285
|
+
// The string literals the code compares a record's fields with (case labels, ===): those fields are choices.
|
|
286
|
+
function literalsOf(body, param, s) {
|
|
287
|
+
const out = new Map();
|
|
288
|
+
const pathOf = (e) => {
|
|
289
|
+
if (ts.isParenthesizedExpression(e))
|
|
290
|
+
return pathOf(e.expression);
|
|
291
|
+
if (ts.isPropertyAccessExpression(e)) {
|
|
292
|
+
if (ts.isIdentifier(e.expression) && e.expression.text === param)
|
|
293
|
+
return e.name.text;
|
|
294
|
+
const p = pathOf(e.expression);
|
|
295
|
+
return p && `${p}_${e.name.text}`;
|
|
296
|
+
}
|
|
297
|
+
return undefined;
|
|
298
|
+
};
|
|
299
|
+
// A literal, or a const naming one (an action type from a constants module).
|
|
300
|
+
const textOf = (lit) => {
|
|
301
|
+
if (ts.isStringLiteral(lit) || ts.isNoSubstitutionTemplateLiteral(lit))
|
|
302
|
+
return lit.text;
|
|
303
|
+
if (s && (ts.isIdentifier(lit) || ts.isPropertyAccessExpression(lit))) {
|
|
304
|
+
try {
|
|
305
|
+
const v = constValue(lit, s);
|
|
306
|
+
return typeof v === 'string' ? v : undefined;
|
|
307
|
+
}
|
|
308
|
+
catch {
|
|
309
|
+
return undefined;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
return undefined;
|
|
313
|
+
};
|
|
314
|
+
const add = (path, lit) => { const t = textOf(lit); if (path && t !== undefined) {
|
|
315
|
+
const xs = out.get(path) ?? [];
|
|
316
|
+
if (!xs.includes(t))
|
|
317
|
+
xs.push(t);
|
|
318
|
+
out.set(path, xs);
|
|
319
|
+
} };
|
|
320
|
+
const visit = (n) => {
|
|
321
|
+
if (ts.isBinaryExpression(n) && [ts.SyntaxKind.EqualsEqualsEqualsToken, ts.SyntaxKind.ExclamationEqualsEqualsToken, ts.SyntaxKind.EqualsEqualsToken, ts.SyntaxKind.ExclamationEqualsToken].includes(n.operatorToken.kind)) {
|
|
322
|
+
add(pathOf(n.left), n.right);
|
|
323
|
+
add(pathOf(n.right), n.left);
|
|
324
|
+
}
|
|
325
|
+
if (ts.isSwitchStatement(n))
|
|
326
|
+
for (const cl of n.caseBlock.clauses)
|
|
327
|
+
if (ts.isCaseClause(cl))
|
|
328
|
+
add(pathOf(n.expression), cl.expression);
|
|
329
|
+
ts.forEachChild(n, visit);
|
|
330
|
+
};
|
|
331
|
+
visit(body);
|
|
332
|
+
return out;
|
|
333
|
+
}
|
|
334
|
+
const OTHER = '@@other';
|
|
335
|
+
function argOf(ex, param, prefix, body) {
|
|
336
|
+
const s = ex.s, t = s.checker.getTypeAtLocation(param), pname = ts.isIdentifier(param.name) ? param.name.text : 'arg';
|
|
337
|
+
const lits = ts.isIdentifier(param.name) ? literalsOf(body, param.name.text, s) : new Map();
|
|
338
|
+
// Untyped (JavaScript): its fields as the code reads them, numbers unless compared with string literals.
|
|
339
|
+
if (t.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) {
|
|
340
|
+
for (const [path, xs] of lits)
|
|
341
|
+
if (!s.lazySorts.has(`${prefix}${path}`))
|
|
342
|
+
s.lazySorts.set(`${prefix}${path}`, { k: 'choice', values: [...xs, OTHER] });
|
|
343
|
+
const id = `input.${prefix}${pname}`;
|
|
344
|
+
s.notes.add(`${pname} is untyped: its fields are inputs as the code reads them (numbers, or a choice among the literals it is compared with and ${OTHER})`);
|
|
345
|
+
const disc = [...lits.keys()].find(k => !k.includes('_'));
|
|
346
|
+
const arg = { k: 'lazy', prefix };
|
|
347
|
+
const events = disc ? [...lits.get(disc), OTHER].map(value => ({ select: { [`$lazy:${prefix}${disc}`]: value }, arg })) : [{ select: {}, arg }];
|
|
348
|
+
return { v: { t: 'ref', id }, events, heap: [[id, { k: 'rec', fields: new Map(), origin: 'input', lazy: { prefix } }]] };
|
|
349
|
+
}
|
|
350
|
+
const members = t.isUnion() && t.types.every(m => m.flags & ts.TypeFlags.Object) ? t.types : [t];
|
|
351
|
+
if (members.length === 1 && !(t.flags & ts.TypeFlags.Object)) {
|
|
352
|
+
const sh = shapeOf(t, s.checker, param);
|
|
353
|
+
if (sh.k === 'map' || sh.k === 'rec')
|
|
354
|
+
throw new Error('unreachable');
|
|
355
|
+
const x = ex.newVar(`${prefix}${pname}`, sortOf(sh, lits.get('') ?? []), 'input');
|
|
356
|
+
return { v: Exec.valueOf(x), events: [{ select: {}, arg: { k: 'input', name: x.name } }], heap: [] };
|
|
357
|
+
}
|
|
358
|
+
// The fields of every member, by name; the discriminant: a field each member gives as one string literal.
|
|
359
|
+
const fieldsOf = (m) => s.checker.getPropertiesOfType(m).map(p => [p.getName(), s.checker.getTypeOfSymbolAtLocation(p, param)]);
|
|
360
|
+
const all = new Map();
|
|
361
|
+
for (const m of members)
|
|
362
|
+
for (const [f, ft] of fieldsOf(m)) {
|
|
363
|
+
const lit = ft.flags & ts.TypeFlags.StringLiteral;
|
|
364
|
+
const sh = lit ? { k: 'choice', values: [ft.value] } : shapeOf(ft, s.checker, param);
|
|
365
|
+
const seen = all.get(f);
|
|
366
|
+
if (!seen)
|
|
367
|
+
all.set(f, sh);
|
|
368
|
+
else if (seen.k === 'choice' && sh.k === 'choice')
|
|
369
|
+
all.set(f, { k: 'choice', values: [...new Set([...seen.values, ...sh.values])] });
|
|
370
|
+
else if (JSON.stringify(seen) !== JSON.stringify(sh))
|
|
371
|
+
refuse(param, `${pname}.${f} is of two types across the union (name them apart)`);
|
|
372
|
+
}
|
|
373
|
+
const disc = members.length > 1 ? [...all.keys()].find(f => members.every(m => { const ft = fieldsOf(m).find(([g]) => g === f)?.[1]; return ft && ft.flags & ts.TypeFlags.StringLiteral; })) : undefined;
|
|
374
|
+
const heap = [], vars = new Map();
|
|
375
|
+
const make = (sh, path, id) => {
|
|
376
|
+
if (sh.k === 'rec') {
|
|
377
|
+
const fields = new Map(sh.fields.map(([f, fs]) => [f, make(fs, [...path, f], `${id}.${f}`)]));
|
|
378
|
+
heap.push([id, { k: 'rec', fields, origin: 'input' }]);
|
|
379
|
+
return { t: 'ref', id };
|
|
380
|
+
}
|
|
381
|
+
if (sh.k === 'map')
|
|
382
|
+
return refuse(param, `${pname}.${path.join('.')}: a map in a request`);
|
|
383
|
+
const key = path.join('_');
|
|
384
|
+
let sort = sh;
|
|
385
|
+
// A string field compared with literals (an action's `type: string`): a choice among them, and any other.
|
|
386
|
+
if (sh.k === 'str' && lits.get(key)?.length)
|
|
387
|
+
sort = { k: 'choice', values: [...lits.get(key), OTHER] };
|
|
388
|
+
const x = ex.newVar(s.names.has(`${prefix}${key}`) ? `${prefix}${pname}_${key}` : `${prefix}${key}`, sort, 'input');
|
|
389
|
+
vars.set(key, x);
|
|
390
|
+
return Exec.valueOf(x);
|
|
391
|
+
};
|
|
392
|
+
const id = `input.${prefix}${pname}`, v = make({ k: 'rec', fields: [...all] }, [], id);
|
|
393
|
+
const template = (m) => {
|
|
394
|
+
const of = (sh, path, present) => (sh.k === 'rec'
|
|
395
|
+
? { k: 'rec', fields: sh.fields.filter(([f]) => path.length || present(f)).map(([f, fs]) => [f, of(fs, [...path, f], present)]) }
|
|
396
|
+
: { k: 'input', name: vars.get(path.join('_')).name });
|
|
397
|
+
return of({ k: 'rec', fields: [...all] }, [], f => !m || fieldsOf(m).some(([g]) => g === f));
|
|
398
|
+
};
|
|
399
|
+
const dv = disc && vars.get(disc);
|
|
400
|
+
const events = dv && dv.sort.k === 'choice' ? members.map(m => {
|
|
401
|
+
const lit = s.checker.getTypeOfSymbolAtLocation(m.getProperty(disc), param).value;
|
|
402
|
+
return { select: { [dv.name]: lit }, arg: template(m) };
|
|
403
|
+
}) : (() => {
|
|
404
|
+
// A string discriminant (`type: string`): each literal it is compared with, and another.
|
|
405
|
+
const sv = [...vars.values()].find(x => x.sort.k === 'choice' && x.sort.values.includes(OTHER));
|
|
406
|
+
return sv && sv.sort.k === 'choice' ? sv.sort.values.map(value => ({ select: { [sv.name]: value }, arg: template(undefined) })) : [{ select: {}, arg: template(undefined) }];
|
|
407
|
+
})();
|
|
408
|
+
return { v, events, heap };
|
|
409
|
+
}
|
|
410
|
+
const sortOf = (sh, lits) => (sh.k === 'str' && lits.length ? { k: 'choice', values: [...lits, OTHER] } : sh.k === 'num' || sh.k === 'bool' || sh.k === 'choice' || sh.k === 'str' ? sh : (() => { throw new Error('a compound sort'); })());
|
|
411
|
+
export function readFunctions(code, file, opts) {
|
|
412
|
+
// Read again while an untyped input turns out to be of another sort than a number.
|
|
413
|
+
for (let typed = { ...opts.typed };;) {
|
|
414
|
+
try {
|
|
415
|
+
return readFunctionsOnce(code, file, { ...opts, typed });
|
|
416
|
+
}
|
|
417
|
+
catch (e) {
|
|
418
|
+
if (!(e instanceof Retype) || e.path in typed)
|
|
419
|
+
throw e;
|
|
420
|
+
typed = { ...typed, [e.path]: e.sort };
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
function readFunctionsOnce(code, file, opts) {
|
|
425
|
+
const s = setupOf(code, file, opts.typed, opts.files), names = opts.functions ?? [opts.entry], fns = names.map(n => findFunction(s.sf, n));
|
|
426
|
+
const first = fns[0], sp = first.parameters[0] ?? refuse(first, 'a step function takes the state first');
|
|
427
|
+
// The initial state: given, a default parameter, useReducer's second argument, or `initialState`.
|
|
428
|
+
let raw = opts.init, initSource, initExpr;
|
|
429
|
+
if (raw === undefined) {
|
|
430
|
+
initExpr = sp.initializer;
|
|
431
|
+
if (!initExpr) {
|
|
432
|
+
const visit = (n) => { if (!initExpr && ts.isCallExpression(n) && ts.isIdentifier(n.expression) && n.expression.text === 'useReducer' && n.arguments[0] && ts.isIdentifier(n.arguments[0]) && names.includes(n.arguments[0].text)) {
|
|
433
|
+
if (n.arguments.length > 2)
|
|
434
|
+
refuse(n, 'useReducer with an init function');
|
|
435
|
+
initExpr = n.arguments[1];
|
|
436
|
+
} ts.forEachChild(n, visit); };
|
|
437
|
+
visit(s.sf);
|
|
438
|
+
}
|
|
439
|
+
if (!initExpr)
|
|
440
|
+
for (const stmt of s.sf.statements)
|
|
441
|
+
if (ts.isVariableStatement(stmt))
|
|
442
|
+
for (const d of stmt.declarationList.declarations)
|
|
443
|
+
if (ts.isIdentifier(d.name) && d.name.text === 'initialState' && d.initializer)
|
|
444
|
+
initExpr = d.initializer;
|
|
445
|
+
if (!initExpr)
|
|
446
|
+
refuse(sp, 'no initial state: a default parameter, useReducer(reducer, initial), a const initialState, or init');
|
|
447
|
+
raw = constValue(initExpr, s);
|
|
448
|
+
initSource = initExpr.getText();
|
|
449
|
+
}
|
|
450
|
+
// The state's type: its own, or (untyped JavaScript) the initial state's.
|
|
451
|
+
let st = s.checker.getTypeAtLocation(sp);
|
|
452
|
+
if (st.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) {
|
|
453
|
+
if (initExpr) {
|
|
454
|
+
st = s.checker.getBaseTypeOfLiteralType(s.checker.getTypeAtLocation(initExpr));
|
|
455
|
+
s.notes.add(`the state is untyped: its type is the initial state's (${s.checker.typeToString(st)})`);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
let shape = st.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown) && raw !== undefined ? shapeOfRaw(raw, sp, s) : shapeOf(st, s.checker, sp), untypedMap = false;
|
|
459
|
+
// Untyped and starting as {}: a record keyed by strings, of numbers (what [key] writes; the check runs it).
|
|
460
|
+
if (shape.k === 'rec' && !shape.fields.length && typeof raw === 'object' && raw !== null && !Object.keys(raw).length) {
|
|
461
|
+
const byNum = opts.typed?.['$key:state']?.k === 'num';
|
|
462
|
+
shape = { k: 'map', key: byNum ? 'num' : 'str', val: { k: 'num' }, js: 'record' };
|
|
463
|
+
s.notes.add(`the state starts as {} with no fields of its own: read as a record of numbers keyed by ${byNum ? 'numbers (as the step reads it)' : 'strings'}`);
|
|
464
|
+
untypedMap = true;
|
|
465
|
+
}
|
|
466
|
+
for (const [i, f] of fns.entries()) {
|
|
467
|
+
const p0 = f.parameters[0] ?? refuse(f, `${names[i]} takes no state`);
|
|
468
|
+
if (i > 0 && s.checker.typeToString(s.checker.getTypeAtLocation(p0)) !== s.checker.typeToString(s.checker.getTypeAtLocation(sp)))
|
|
469
|
+
refuse(p0, `${names[i]} takes another state than ${names[0]}`);
|
|
470
|
+
}
|
|
471
|
+
const ex0 = new Exec(s), heap = new Map(), { layout, v: stateV } = build(ex0, shape, [], heap, 'input', sp);
|
|
472
|
+
if (untypedMap)
|
|
473
|
+
for (const d of s.maps.values())
|
|
474
|
+
d.untyped = true;
|
|
475
|
+
const init = initLeaves(raw, layout, s, sp);
|
|
476
|
+
const multi = fns.length > 1, ev = multi ? ex0.newVar('fn', { k: 'choice', values: names }, 'input') : undefined;
|
|
477
|
+
const outs = [], throws = [], events = [];
|
|
478
|
+
for (const f of fns)
|
|
479
|
+
(s.spans ??= []).push([f.getStart(), f.end]);
|
|
480
|
+
fns.forEach((f, i) => {
|
|
481
|
+
const ex = new Exec(s), sel = ev ? I.is({ op: 'var', name: ev.name, values: names }, names[i]) : I.T;
|
|
482
|
+
const h = new Map(heap);
|
|
483
|
+
let p = { pc: sel.op === 'const' ? [] : [sel], locals: new Map(), heap: h, wrote: [], nows: 0 };
|
|
484
|
+
p = ex.bind(f.parameters[0].name, stateV, p);
|
|
485
|
+
const combos = [{ select: ev ? { [ev.name]: names[i] } : {}, args: [{ k: 'state' }] }];
|
|
486
|
+
for (const param of f.parameters.slice(1)) {
|
|
487
|
+
if (param.dotDotDotToken)
|
|
488
|
+
refuse(param, 'a rest parameter');
|
|
489
|
+
const a = argOf(ex, param, multi ? `${names[i]}_` : '', f.body ?? f);
|
|
490
|
+
for (const [id, o] of a.heap)
|
|
491
|
+
p.heap.set(id, o);
|
|
492
|
+
p = ex.bind(param.name, a.v, p);
|
|
493
|
+
const next = combos.flatMap(c => a.events.map(e => ({ select: { ...c.select, ...e.select }, args: [...c.args, e.arg] })));
|
|
494
|
+
combos.splice(0, combos.length, ...next);
|
|
495
|
+
}
|
|
496
|
+
if (!f.body)
|
|
497
|
+
refuse(f, 'a function without a body');
|
|
498
|
+
let returned;
|
|
499
|
+
if (ts.isBlock(f.body)) {
|
|
500
|
+
const flow = ex.block(f.body.statements, p);
|
|
501
|
+
if (flow.live)
|
|
502
|
+
refuse(f, `${names[i]} returns nothing on some path`);
|
|
503
|
+
returned = flow.rets;
|
|
504
|
+
}
|
|
505
|
+
else {
|
|
506
|
+
const [v, q] = ex.ev(f.body, p);
|
|
507
|
+
returned = [[q, v]];
|
|
508
|
+
}
|
|
509
|
+
for (const [rp, rv] of returned)
|
|
510
|
+
outs.push([rp, materialize(ex, rv, layout, rp, f)]);
|
|
511
|
+
throws.push(refusalOf(ex));
|
|
512
|
+
for (const c of combos)
|
|
513
|
+
events.push({ select: c.select, call: names[i], args: c.args });
|
|
514
|
+
});
|
|
515
|
+
// An untyped record's discriminant, chosen by name now that the variable is made.
|
|
516
|
+
for (const e of events)
|
|
517
|
+
for (const [k, value] of Object.entries(e.select))
|
|
518
|
+
if (k.startsWith('$lazy:')) {
|
|
519
|
+
delete e.select[k];
|
|
520
|
+
const v = [...s.lazy].find(([, l]) => `$lazy:${l.prefix}${l.field}` === k);
|
|
521
|
+
if (v)
|
|
522
|
+
e.select[v[0]] = value;
|
|
523
|
+
}
|
|
524
|
+
const final = joinAll(ex0, outs, first);
|
|
525
|
+
// A default export by its function's own name.
|
|
526
|
+
const own = ts.isFunctionDeclaration(first) ? first.name?.text : ts.isVariableDeclaration(first.parent) && ts.isIdentifier(first.parent.name) ? first.parent.name.text : undefined;
|
|
527
|
+
return finish(s, { name: names[0] === 'default' ? own ?? 'reducer' : names[0], shape: multi ? 'functions' : 'reducer', file, entry: names.join(','), layout, init, final,
|
|
528
|
+
refuse: I.or(...throws), pre: I.T, events, outputs: [], ...(ev ? { event: ev.name } : {}), ...(initSource ? { initSource } : {}) });
|
|
529
|
+
}
|
|
530
|
+
function finish(s, m) {
|
|
531
|
+
const vars = [...s.vars.values()];
|
|
532
|
+
const writes = {};
|
|
533
|
+
for (const [n, v] of m.final.leaves)
|
|
534
|
+
if (!sameTerm(v, Exec.valueOf(s.vars.get(n))))
|
|
535
|
+
writes[n] = termOf(v);
|
|
536
|
+
const mapWrites = {};
|
|
537
|
+
for (const [n, w] of m.final.maps)
|
|
538
|
+
if (w)
|
|
539
|
+
mapWrites[n] = { key: w.key, has: w.has, vals: Object.fromEntries([...w.vals].map(([f, v]) => [f, termOf(v)])) };
|
|
540
|
+
return { name: m.name, shape: m.shape, file: m.file, entry: m.entry, params: vars.filter(v => v.role === 'param'), inputs: vars.filter(v => v.role === 'input'), state: vars.filter(v => v.role === 'state'),
|
|
541
|
+
maps: [...s.maps.values()], init: m.init, writes, mapWrites, outputs: m.outputs, refuse: m.refuse, pre: m.pre, layout: m.layout, events: m.events, notes: [...s.notes], hints: s.hints,
|
|
542
|
+
...(m.event ? { event: m.event } : {}), ...(m.ctorArgs ? { ctorArgs: m.ctorArgs } : {}), ...(s.lazy.size ? { lazy: s.lazy } : {}), ...(m.initSource ? { initSource: m.initSource } : {}), ...(s.spans ? { spans: s.spans } : {}) };
|
|
543
|
+
}
|
|
544
|
+
// --- classes --------------------------------------------------------------------------------------------------------
|
|
545
|
+
function findClass(sf, name) {
|
|
546
|
+
for (const st of sf.statements) {
|
|
547
|
+
if (ts.isClassDeclaration(st) && (st.name?.text === name || (name === 'default' && st.modifiers?.some(m => m.kind === ts.SyntaxKind.DefaultKeyword))))
|
|
548
|
+
return st;
|
|
549
|
+
if (ts.isVariableStatement(st))
|
|
550
|
+
for (const d of st.declarationList.declarations)
|
|
551
|
+
if (ts.isIdentifier(d.name) && d.name.text === name && d.initializer && ts.isClassExpression(d.initializer))
|
|
552
|
+
return d.initializer;
|
|
553
|
+
}
|
|
554
|
+
return refuse(at0(sf), `no class ${name} in the file`);
|
|
555
|
+
}
|
|
556
|
+
const has = (n, k) => !!(ts.canHaveModifiers(n) && ts.getModifiers(n)?.some(m => m.kind === k));
|
|
557
|
+
const isMapInit = (e) => !!e && ((ts.isNewExpression(e) && ts.isIdentifier(e.expression) && e.expression.text === 'Map' && !e.arguments?.length) || (ts.isObjectLiteralExpression(e) && !e.properties.length) || ((ts.isAsExpression(e) || ts.isParenthesizedExpression(e)) && isMapInit(e.expression)));
|
|
558
|
+
export function readClass(code, file, opts) {
|
|
559
|
+
// Read twice: first with every field a state variable, to see which the methods write; then with the others as the
|
|
560
|
+
// constants the constructor makes them.
|
|
561
|
+
const written = attempt(code, file, opts, new Set()).written;
|
|
562
|
+
return attempt(code, file, opts, written).model;
|
|
563
|
+
}
|
|
564
|
+
function attempt(code, file, opts, written) {
|
|
565
|
+
const s = setupOf(code, file, {}, opts.files), cls = findClass(s.sf, opts.entry), first = written.size === 0;
|
|
566
|
+
s.cls = cls;
|
|
567
|
+
// `implements` is a type's only (nothing at run time); `extends` brings another class's fields and methods.
|
|
568
|
+
if (cls.heritageClauses?.some(h => h.token === ts.SyntaxKind.ExtendsKeyword))
|
|
569
|
+
refuse(cls, 'a class that extends another');
|
|
570
|
+
const ctor = cls.members.find(ts.isConstructorDeclaration);
|
|
571
|
+
if (ctor)
|
|
572
|
+
(s.spans ??= []).push([ctor.getStart(), ctor.end]);
|
|
573
|
+
const fields = [];
|
|
574
|
+
for (const m of cls.members) {
|
|
575
|
+
if (ts.isPropertyDeclaration(m)) {
|
|
576
|
+
if (ts.isPrivateIdentifier(m.name))
|
|
577
|
+
refuse(m, `${m.name.text}: a #private field (the check reads the object's fields; \`private\` is in the subset)`);
|
|
578
|
+
if (has(m, ts.SyntaxKind.StaticKeyword))
|
|
579
|
+
refuse(m, 'a static field (state shared by every object)');
|
|
580
|
+
fields.push({ name: memberName(m.name), shape: shapeOf(s.checker.getTypeAtLocation(m), s.checker, m), node: m, ...(m.initializer ? { init: m.initializer } : {}) });
|
|
581
|
+
}
|
|
582
|
+
else if (ts.isSetAccessorDeclaration(m))
|
|
583
|
+
refuse(m, 'a setter');
|
|
584
|
+
else if (ts.isMethodDeclaration(m) && ts.isPrivateIdentifier(m.name))
|
|
585
|
+
refuse(m, 'a #private method');
|
|
586
|
+
else if (ts.isIndexSignatureDeclaration(m) || ts.isClassStaticBlockDeclaration(m))
|
|
587
|
+
refuse(m, 'a static block or index signature');
|
|
588
|
+
}
|
|
589
|
+
for (const p of ctor?.parameters ?? [])
|
|
590
|
+
if (ts.isParameterPropertyDeclaration(p, ctor))
|
|
591
|
+
fields.push({ name: p.name.text, shape: shapeOf(s.checker.getTypeAtLocation(p), s.checker, p), node: p });
|
|
592
|
+
const ex0 = new Exec(s);
|
|
593
|
+
const constant = (f) => !first && !written.has(f.name) && f.shape.k !== 'map';
|
|
594
|
+
// The state's variables first (so they keep the fields' names), then the params.
|
|
595
|
+
const stateHeap = new Map(), thisFields = new Map(), layout = [], stateLayout = [];
|
|
596
|
+
for (const f of fields)
|
|
597
|
+
if (!constant(f)) {
|
|
598
|
+
const r = build(ex0, f.shape, [f.name], stateHeap, 'this', f.node);
|
|
599
|
+
thisFields.set(f.name, r.v);
|
|
600
|
+
layout.push([f.name, r.layout]);
|
|
601
|
+
stateLayout.push([f.name, r.layout]);
|
|
602
|
+
}
|
|
603
|
+
// The constructor, run over its arguments (the params): what each field starts at, and what it refuses (the pre).
|
|
604
|
+
s.nowRole = 'param';
|
|
605
|
+
const ctorArgs = [], ctorHeap = new Map(), ctorFields = new Map(fields.map(f => [f.name, { t: 'undef' }]));
|
|
606
|
+
ctorHeap.set('this', { k: 'rec', fields: ctorFields, origin: 'fresh' });
|
|
607
|
+
let cp = { pc: [], locals: new Map(), heap: ctorHeap, wrote: [], nows: 0 };
|
|
608
|
+
const exC = new Exec(s);
|
|
609
|
+
s.ctor = true;
|
|
610
|
+
for (const p of ctor?.parameters ?? []) {
|
|
611
|
+
if (!ts.isIdentifier(p.name))
|
|
612
|
+
refuse(p, 'a destructured constructor argument');
|
|
613
|
+
const sh = shapeOf(s.checker.getTypeAtLocation(p), s.checker, p);
|
|
614
|
+
if (sh.k !== 'num' && sh.k !== 'bool' && sh.k !== 'choice')
|
|
615
|
+
refuse(p, `${p.name.getText()}: a constructor argument that isn't a number, a boolean or a union of literals`);
|
|
616
|
+
const x = exC.newVar(p.name.getText(), sh, 'param', 'a constructor argument');
|
|
617
|
+
ctorArgs.push(x.name);
|
|
618
|
+
cp = exC.bind(p.name, Exec.valueOf(x), cp);
|
|
619
|
+
if (ts.isParameterPropertyDeclaration(p, ctor)) {
|
|
620
|
+
const o = cp.heap.get('this');
|
|
621
|
+
cp = { ...cp, heap: new Map(cp.heap).set('this', { ...o, fields: new Map(o.fields).set(p.name.text, Exec.valueOf(x)) }) };
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
const empty = new Set();
|
|
625
|
+
for (const f of fields)
|
|
626
|
+
if (f.init) {
|
|
627
|
+
if (f.shape.k === 'map') {
|
|
628
|
+
if (!isMapInit(f.init))
|
|
629
|
+
refuse(f.init, `${f.name} starts with entries (a map starts empty in the subset)`);
|
|
630
|
+
empty.add(f.name);
|
|
631
|
+
continue;
|
|
632
|
+
}
|
|
633
|
+
const [v, q] = exC.ev(f.init, cp);
|
|
634
|
+
cp = q;
|
|
635
|
+
const o = cp.heap.get('this');
|
|
636
|
+
cp = { ...cp, heap: new Map(cp.heap).set('this', { ...o, fields: new Map(o.fields).set(f.name, v) }) };
|
|
637
|
+
}
|
|
638
|
+
const body = (ctor?.body?.statements ?? []).filter(st => {
|
|
639
|
+
if (!ts.isExpressionStatement(st) || !ts.isBinaryExpression(st.expression) || st.expression.operatorToken.kind !== ts.SyntaxKind.EqualsToken)
|
|
640
|
+
return true;
|
|
641
|
+
const l = st.expression.left;
|
|
642
|
+
if (!ts.isPropertyAccessExpression(l) || l.expression.kind !== ts.SyntaxKind.ThisKeyword)
|
|
643
|
+
return true;
|
|
644
|
+
const f = fields.find(x => x.name === memberName(l.name));
|
|
645
|
+
if (f?.shape.k !== 'map')
|
|
646
|
+
return true;
|
|
647
|
+
if (!isMapInit(st.expression.right))
|
|
648
|
+
refuse(st, `${f.name} starts with entries (a map starts empty in the subset)`);
|
|
649
|
+
empty.add(f.name);
|
|
650
|
+
return false;
|
|
651
|
+
});
|
|
652
|
+
const cflow = exC.block(body, cp);
|
|
653
|
+
if (cflow.rets.some(([, v]) => v.t !== 'undef'))
|
|
654
|
+
refuse(ctor, 'a constructor that returns a value');
|
|
655
|
+
const ends = [...cflow.rets.map(([p]) => p), ...(cflow.live ? [cflow.live] : [])];
|
|
656
|
+
const cend = ends.reduceRight((acc, x) => exC.merge(x, acc, ctor ?? cls), undefined) ?? refuse(ctor ?? cls, 'a constructor that always throws');
|
|
657
|
+
s.ctor = false;
|
|
658
|
+
const pre = I.not(refusalOf(exC));
|
|
659
|
+
const made = cend.heap.get('this').fields;
|
|
660
|
+
for (const f of fields)
|
|
661
|
+
if (f.shape.k === 'map' && !empty.has(f.name))
|
|
662
|
+
refuse(f.node, `${f.name}: a map field must start as new Map() or {}`);
|
|
663
|
+
// Each field's start, over the params: a state variable's init, or a constant field's value in every method.
|
|
664
|
+
const init = {};
|
|
665
|
+
const startOf = (v, lay, at) => {
|
|
666
|
+
const sv = materialize(exC, v, lay, cend, at);
|
|
667
|
+
for (const [n, x] of sv.leaves)
|
|
668
|
+
init[n] = termOf(x);
|
|
669
|
+
};
|
|
670
|
+
for (const [fname, lay] of layout)
|
|
671
|
+
if (lay.k !== 'map')
|
|
672
|
+
startOf(made.get(fname), lay, fields.find(f => f.name === fname).node);
|
|
673
|
+
for (const f of fields)
|
|
674
|
+
if (constant(f)) {
|
|
675
|
+
const v = made.get(f.name);
|
|
676
|
+
if (v.t === 'undef' || v.t === 'opt')
|
|
677
|
+
refuse(f.node, `${f.name} starts undefined`);
|
|
678
|
+
if (v.t === 'ref') {
|
|
679
|
+
// A constant object (a config): copied into each method's heap, each field a term over the params.
|
|
680
|
+
const copy = (id) => { const o = cend.heap.get(id); if (o?.k === 'rec') {
|
|
681
|
+
stateHeap.set(id, { ...o, origin: 'this' });
|
|
682
|
+
for (const x of o.fields.values())
|
|
683
|
+
if (x.t === 'ref')
|
|
684
|
+
copy(x.id);
|
|
685
|
+
}
|
|
686
|
+
else
|
|
687
|
+
refuse(f.node, `${f.name}: a constant map`); };
|
|
688
|
+
copy(v.id);
|
|
689
|
+
}
|
|
690
|
+
thisFields.set(f.name, v);
|
|
691
|
+
layout.push([f.name, constLayout(v, cend, f.node)]);
|
|
692
|
+
}
|
|
693
|
+
s.now = undefined;
|
|
694
|
+
s.nowRole = 'input';
|
|
695
|
+
stateHeap.set('this', { k: 'rec', fields: thisFields, origin: 'this' });
|
|
696
|
+
// The methods: each public one an event, run from the state as variables.
|
|
697
|
+
const methods = cls.members.filter((m) => ts.isMethodDeclaration(m) && !has(m, ts.SyntaxKind.StaticKeyword) && !has(m, ts.SyntaxKind.PrivateKeyword) && !has(m, ts.SyntaxKind.ProtectedKeyword))
|
|
698
|
+
.filter(m => !opts.methods || opts.methods.includes(memberName(m.name)));
|
|
699
|
+
if (opts.methods)
|
|
700
|
+
for (const n of opts.methods)
|
|
701
|
+
if (!methods.some(m => memberName(m.name) === n))
|
|
702
|
+
refuse(cls, `no public method ${n}`);
|
|
703
|
+
if (!methods.length)
|
|
704
|
+
refuse(cls, 'a class with no public methods (no events)');
|
|
705
|
+
const mnames = methods.map(m => memberName(m.name)), ev = ex0.newVar('method', { k: 'choice', values: mnames }, 'input'), evL = { op: 'var', name: ev.name, values: mnames };
|
|
706
|
+
const outputs = [], perMethod = [], events = [];
|
|
707
|
+
const outVars = new Map();
|
|
708
|
+
for (const m of methods) {
|
|
709
|
+
const name = memberName(m.name), sig = s.checker.getSignatureFromDeclaration(m), rt = s.checker.getReturnTypeOfSignature(sig);
|
|
710
|
+
if (has(m, ts.SyntaxKind.AsyncKeyword) || m.asteriskToken)
|
|
711
|
+
refuse(m, `${name}: an async or generator method (its steps interleave with others)`);
|
|
712
|
+
if (!(rt.flags & (ts.TypeFlags.Void | ts.TypeFlags.Undefined))) {
|
|
713
|
+
const sh = shapeOf(rt, s.checker, m);
|
|
714
|
+
if (sh.k !== 'num' && sh.k !== 'bool' && sh.k !== 'choice')
|
|
715
|
+
refuse(m, `${name} returns ${sh.k === 'str' ? 'a string' : 'a compound value'} (a result kept is a number, a boolean or a union of literals)`);
|
|
716
|
+
const x = ex0.newVar(`${name}_result`, sh, 'state', `what ${name} returned, at the step that called it (its default at others)`);
|
|
717
|
+
outVars.set(name, x);
|
|
718
|
+
outputs.push(x.name);
|
|
719
|
+
layout.push([`${name}()`, { k: 'scalar', name: x.name }]);
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
for (const m of methods)
|
|
723
|
+
(s.spans ??= []).push([m.getStart(), m.end]);
|
|
724
|
+
for (const m of methods) {
|
|
725
|
+
const name = memberName(m.name), ex = new Exec(s), sel = I.is(evL, name);
|
|
726
|
+
let p = { pc: [sel], locals: new Map(), heap: new Map(stateHeap), wrote: [], nows: 0 };
|
|
727
|
+
const args = [];
|
|
728
|
+
for (const param of m.parameters) {
|
|
729
|
+
if (param.dotDotDotToken || !ts.isIdentifier(param.name))
|
|
730
|
+
refuse(param, 'a rest or destructured argument');
|
|
731
|
+
const a = argOf(ex, param, `${name}_`, m.body ?? m);
|
|
732
|
+
if (a.events.length !== 1)
|
|
733
|
+
refuse(param, 'an argument that is a union of records');
|
|
734
|
+
for (const [id, o] of a.heap)
|
|
735
|
+
p.heap.set(id, o);
|
|
736
|
+
p = ex.bind(param.name, a.v, p);
|
|
737
|
+
args.push(a.events[0].arg);
|
|
738
|
+
}
|
|
739
|
+
if (!m.body)
|
|
740
|
+
refuse(m, `${name} has no body`);
|
|
741
|
+
const flow = ex.block(m.body.statements, p);
|
|
742
|
+
const outs = [...flow.rets, ...(flow.live ? [[flow.live, { t: 'undef' }]] : [])].map(([rp, rv]) => {
|
|
743
|
+
const self = rp.heap.get('this'), sv = { leaves: new Map(), maps: new Map() };
|
|
744
|
+
for (const [f, lay] of stateLayout)
|
|
745
|
+
materialize(ex, self.fields.get(f), lay, rp, m, sv);
|
|
746
|
+
for (const [mn, x] of outVars)
|
|
747
|
+
sv.leaves.set(x.name, mn === name ? (rv.t === 'undef' ? refuse(m, `${name} returns nothing on some path`) : outValue(ex, rv, x, rp, m)) : Exec.defaultOf(x.sort));
|
|
748
|
+
return [rp, sv];
|
|
749
|
+
});
|
|
750
|
+
perMethod.push({ sel, sv: joinAll(ex, outs, m), refuse: refusalOf(ex) });
|
|
751
|
+
events.push({ select: { [ev.name]: name }, call: name, args });
|
|
752
|
+
}
|
|
753
|
+
// The methods together: each variable by the method called.
|
|
754
|
+
let final = perMethod.at(-1).sv;
|
|
755
|
+
for (let i = perMethod.length - 2; i >= 0; i--)
|
|
756
|
+
final = mergeVals(ex0, perMethod[i].sel, perMethod[i].sv, final, cls);
|
|
757
|
+
for (const x of outVars.values())
|
|
758
|
+
init[x.name] = termOf(Exec.defaultOf(x.sort));
|
|
759
|
+
const wrote = new Set();
|
|
760
|
+
for (const [f, lay] of layout) {
|
|
761
|
+
const leaves = [];
|
|
762
|
+
const walk = (l) => { if (l.k === 'scalar')
|
|
763
|
+
leaves.push(l.name);
|
|
764
|
+
else if (l.k === 'rec')
|
|
765
|
+
l.fields.forEach(([, x]) => walk(x));
|
|
766
|
+
else if (l.k === 'map')
|
|
767
|
+
leaves.push(`map:${l.name}`); };
|
|
768
|
+
walk(lay);
|
|
769
|
+
if (leaves.some(n => (n.startsWith('map:') ? final.maps.get(n.slice(4)) !== undefined : !sameTerm(final.leaves.get(n), Exec.valueOf(s.vars.get(n))))))
|
|
770
|
+
wrote.add(f);
|
|
771
|
+
}
|
|
772
|
+
const model = finish(s, { name: opts.entry, shape: 'class', file, entry: opts.entry, layout: { k: 'rec', fields: layout }, init, final, refuse: I.or(...perMethod.map(x => I.and(x.sel, x.refuse))), pre, events, outputs, event: ev.name, ctorArgs });
|
|
773
|
+
return { model, written: wrote };
|
|
774
|
+
}
|
|
775
|
+
function constLayout(v, p, at) {
|
|
776
|
+
if (v.t === 'num')
|
|
777
|
+
return { k: 'const', value: { s: 'num', e: v.e } };
|
|
778
|
+
if (v.t === 'bool')
|
|
779
|
+
return { k: 'const', value: { s: 'bool', e: v.e } };
|
|
780
|
+
if (v.t === 'choice')
|
|
781
|
+
return { k: 'const', value: { s: 'choice', e: v.e } };
|
|
782
|
+
if (v.t === 'ref') {
|
|
783
|
+
const o = p.heap.get(v.id);
|
|
784
|
+
if (o?.k === 'rec')
|
|
785
|
+
return { k: 'rec', fields: [...o.fields].map(([f, x]) => [f, constLayout(x, p, at)]) };
|
|
786
|
+
}
|
|
787
|
+
return refuse(at, `a constant field holding a ${v.t}`);
|
|
788
|
+
}
|
|
789
|
+
function outValue(ex, v, x, p, at) {
|
|
790
|
+
if (v.t === 'opt') {
|
|
791
|
+
if (!ex.known(p, v.has))
|
|
792
|
+
refuse(at, `${x.name} may be undefined`);
|
|
793
|
+
v = v.v;
|
|
794
|
+
}
|
|
795
|
+
if (x.sort.k === 'num' && v.t === 'num')
|
|
796
|
+
return v;
|
|
797
|
+
if (x.sort.k === 'bool' && v.t === 'bool')
|
|
798
|
+
return v;
|
|
799
|
+
if (x.sort.k === 'choice' && (v.t === 'choice' || v.t === 'str'))
|
|
800
|
+
return { t: 'choice', e: ex.asChoice(v, x.sort.values, at), values: x.sort.values };
|
|
801
|
+
return refuse(at, `returns a ${v.t} where its type says ${x.sort.k}`);
|
|
802
|
+
}
|
|
803
|
+
// --- Redux Toolkit slices -------------------------------------------------------------------------------------------
|
|
804
|
+
// createSlice({name, initialState, reducers, extraReducers}): each case reducer (and each builder.addCase of
|
|
805
|
+
// extraReducers) an event of its action type; it runs on a copy of the state (immer's draft, written in place), and the
|
|
806
|
+
// state after is the draft, or the value it returns. Writing the draft and returning another value is refused (immer
|
|
807
|
+
// throws there). The check runs the slice's own reducer (Redux Toolkit itself, in the check's modules).
|
|
808
|
+
const sliceOf = (sf, name) => {
|
|
809
|
+
for (const st of sf.statements)
|
|
810
|
+
if (ts.isVariableStatement(st))
|
|
811
|
+
for (const d of st.declarationList.declarations) {
|
|
812
|
+
if (!ts.isIdentifier(d.name) || d.name.text !== name || !d.initializer)
|
|
813
|
+
continue;
|
|
814
|
+
const c = d.initializer;
|
|
815
|
+
if (ts.isCallExpression(c) && ts.isIdentifier(c.expression) && c.expression.text === 'createSlice' && c.arguments[0] && ts.isObjectLiteralExpression(c.arguments[0]))
|
|
816
|
+
return c.arguments[0];
|
|
817
|
+
}
|
|
818
|
+
return undefined;
|
|
819
|
+
};
|
|
820
|
+
export const isSlice = (code, entry) => new RegExp(`\\b${entry}\\s*=\\s*createSlice\\s*\\(`).test(code);
|
|
821
|
+
export function readSlice(code, file, opts) {
|
|
822
|
+
for (let typed = { ...opts.typed };;) {
|
|
823
|
+
try {
|
|
824
|
+
return readSliceOnce(code, file, { ...opts, typed });
|
|
825
|
+
}
|
|
826
|
+
catch (e) {
|
|
827
|
+
if (!(e instanceof Retype) || e.path in typed)
|
|
828
|
+
throw e;
|
|
829
|
+
typed = { ...typed, [e.path]: e.sort };
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
function readSliceOnce(code, file, opts) {
|
|
834
|
+
const s = setupOf(code, file, opts.typed, opts.files), cfg = sliceOf(s.sf, opts.entry) ?? refuse(at0(s.sf), `no createSlice ${opts.entry} in the file`);
|
|
835
|
+
const prop = (k) => cfg.properties.find((p) => (ts.isPropertyAssignment(p) || ts.isShorthandPropertyAssignment(p)) && p.name.getText() === k);
|
|
836
|
+
// A shorthand entry's value: the variable it names (its initializer, for a const).
|
|
837
|
+
const valueOf = (p) => {
|
|
838
|
+
if (ts.isPropertyAssignment(p))
|
|
839
|
+
return p.initializer;
|
|
840
|
+
const d = s.checker.getShorthandAssignmentValueSymbol(p)?.valueDeclaration;
|
|
841
|
+
return d && ts.isVariableDeclaration(d) && d.initializer && d.parent.flags & ts.NodeFlags.Const ? d.initializer : p.name;
|
|
842
|
+
};
|
|
843
|
+
const nameP = prop('name'), initP = prop('initialState');
|
|
844
|
+
if (!nameP || !initP)
|
|
845
|
+
return refuse(cfg, 'a slice without a name or an initialState');
|
|
846
|
+
const sliceName = constValue(valueOf(nameP), s);
|
|
847
|
+
if (typeof sliceName !== 'string')
|
|
848
|
+
return refuse(nameP, 'a slice name that is not a string');
|
|
849
|
+
// Its value from the initializer; its type as written there (a declared CounterState, not its literals' types).
|
|
850
|
+
const initExpr = valueOf(initP), raw = opts.init ?? constValue(initExpr, s);
|
|
851
|
+
let st = s.checker.getTypeAtLocation(ts.isPropertyAssignment(initP) ? initP.initializer : initP.name);
|
|
852
|
+
if (st.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown))
|
|
853
|
+
st = s.checker.getBaseTypeOfLiteralType(st);
|
|
854
|
+
const shape = st.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown) ? shapeOfRaw(raw, initExpr, s) : shapeOf(s.checker.getBaseTypeOfLiteralType(st), s.checker, initExpr);
|
|
855
|
+
const ex0 = new Exec(s), heap = new Map(), { layout, v: stateV } = build(ex0, shape, [], heap, 'input', initExpr);
|
|
856
|
+
const init = initLeaves(raw, layout, s, initExpr);
|
|
857
|
+
// The cases: each reducer `key: (state, action) => ...` of type `name/key`; each addCase(creator, reducer).
|
|
858
|
+
const cases = [];
|
|
859
|
+
const reducers = prop('reducers');
|
|
860
|
+
const rv = reducers && valueOf(reducers);
|
|
861
|
+
if (rv && !ts.isObjectLiteralExpression(rv))
|
|
862
|
+
refuse(rv, 'reducers given other than as an object of them');
|
|
863
|
+
for (const p of rv?.properties ?? []) {
|
|
864
|
+
if (ts.isMethodDeclaration(p)) {
|
|
865
|
+
cases.push([`${sliceName}/${p.name.getText()}`, p]);
|
|
866
|
+
continue;
|
|
867
|
+
}
|
|
868
|
+
if (!ts.isPropertyAssignment(p)) {
|
|
869
|
+
refuse(p, 'a case reducer written other than key: function');
|
|
870
|
+
continue;
|
|
871
|
+
}
|
|
872
|
+
const f = p.initializer;
|
|
873
|
+
if (!ts.isArrowFunction(f) && !ts.isFunctionExpression(f))
|
|
874
|
+
refuse(f, 'a case reducer with a prepare callback, or not a function');
|
|
875
|
+
cases.push([`${sliceName}/${p.name.getText()}`, f]);
|
|
876
|
+
}
|
|
877
|
+
const extra = prop('extraReducers');
|
|
878
|
+
if (extra) {
|
|
879
|
+
const fn = valueOf(extra);
|
|
880
|
+
if (!ts.isArrowFunction(fn) && !ts.isFunctionExpression(fn))
|
|
881
|
+
return refuse(fn, 'extraReducers other than a builder callback');
|
|
882
|
+
const builder = fn.parameters[0]?.name.getText() ?? '';
|
|
883
|
+
// The action creator's type: a thunk's pending, fulfilled or rejected (createAsyncThunk's prefix), or createAction's.
|
|
884
|
+
const typeOf = (a) => {
|
|
885
|
+
if (ts.isPropertyAccessExpression(a) && ['pending', 'fulfilled', 'rejected'].includes(a.name.text) && ts.isIdentifier(a.expression)) {
|
|
886
|
+
const d = s.checker.getSymbolAtLocation(a.expression)?.valueDeclaration;
|
|
887
|
+
const c = d && ts.isVariableDeclaration(d) ? d.initializer : undefined;
|
|
888
|
+
if (c && ts.isCallExpression(c) && ts.isIdentifier(c.expression) && c.expression.text === 'createAsyncThunk' && c.arguments[0]) {
|
|
889
|
+
const pre = constValue(c.arguments[0], s);
|
|
890
|
+
if (typeof pre === 'string')
|
|
891
|
+
return `${pre}/${a.name.text}`;
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
if (ts.isIdentifier(a)) {
|
|
895
|
+
const d = s.checker.getSymbolAtLocation(a)?.valueDeclaration, c = d && ts.isVariableDeclaration(d) ? d.initializer : undefined;
|
|
896
|
+
if (c && ts.isCallExpression(c) && ts.isIdentifier(c.expression) && c.expression.text === 'createAction' && c.arguments[0]) {
|
|
897
|
+
const t = constValue(c.arguments[0], s);
|
|
898
|
+
if (typeof t === 'string')
|
|
899
|
+
return t;
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
const t = constValue(a, s);
|
|
903
|
+
return typeof t === 'string' ? t : refuse(a, 'an addCase of an action creator the subset can\'t name');
|
|
904
|
+
};
|
|
905
|
+
const chain = (e) => {
|
|
906
|
+
e = ts.isParenthesizedExpression(e) ? e.expression : e;
|
|
907
|
+
if (ts.isIdentifier(e) && e.text === builder)
|
|
908
|
+
return;
|
|
909
|
+
if (!ts.isCallExpression(e) || !ts.isPropertyAccessExpression(e.expression))
|
|
910
|
+
return void refuse(e, 'extraReducers other than builder.addCase(...) calls');
|
|
911
|
+
const m = e.expression.name.text;
|
|
912
|
+
if (m !== 'addCase')
|
|
913
|
+
return void refuse(e, `builder.${m} (addCase is in the subset)`);
|
|
914
|
+
chain(e.expression.expression);
|
|
915
|
+
cases.push([typeOf(e.arguments[0]), e.arguments[1]]);
|
|
916
|
+
};
|
|
917
|
+
const body = fn.body;
|
|
918
|
+
if (ts.isBlock(body))
|
|
919
|
+
for (const stmt of body.statements) {
|
|
920
|
+
if (!ts.isExpressionStatement(stmt))
|
|
921
|
+
refuse(stmt, 'extraReducers other than builder calls');
|
|
922
|
+
else
|
|
923
|
+
chain(stmt.expression);
|
|
924
|
+
}
|
|
925
|
+
else
|
|
926
|
+
chain(body);
|
|
927
|
+
}
|
|
928
|
+
if (!cases.length)
|
|
929
|
+
return refuse(cfg, 'a slice with no case reducers');
|
|
930
|
+
const types = [...new Set(cases.map(([t]) => t)), OTHER];
|
|
931
|
+
const ev = ex0.newVar('type', { k: 'choice', values: types }, 'input'), evL = { op: 'var', name: ev.name, values: types };
|
|
932
|
+
const outs = [], refusals = [];
|
|
933
|
+
// The draft: a copy of the state's objects, written in place.
|
|
934
|
+
const draftOf = (h) => {
|
|
935
|
+
const ids = new Map(), out = new Map(h);
|
|
936
|
+
const copy = (x) => {
|
|
937
|
+
if (x.t !== 'ref')
|
|
938
|
+
return x;
|
|
939
|
+
const known = ids.get(x.id);
|
|
940
|
+
if (known)
|
|
941
|
+
return { t: 'ref', id: known };
|
|
942
|
+
const o = h.get(x.id), id = `draft.${x.id}`;
|
|
943
|
+
ids.set(x.id, id);
|
|
944
|
+
out.set(id, o.k === 'rec' ? { ...o, origin: 'fresh', fields: new Map([...o.fields].map(([f, y]) => [f, copy(y)])) } : o.k === 'map' ? { ...o, origin: 'fresh' } : o);
|
|
945
|
+
return { t: 'ref', id };
|
|
946
|
+
};
|
|
947
|
+
return { heap: out, v: copy(stateV) };
|
|
948
|
+
};
|
|
949
|
+
for (const [, f] of cases)
|
|
950
|
+
(s.spans ??= []).push([f.getStart(), f.end]);
|
|
951
|
+
for (const [type, f] of cases) {
|
|
952
|
+
const ex = new Exec(s), sel = I.is(evL, type);
|
|
953
|
+
const fn = f;
|
|
954
|
+
if (!ts.isArrowFunction(fn) && !ts.isFunctionExpression(fn) && !ts.isMethodDeclaration(fn)) {
|
|
955
|
+
refuse(f, 'a case reducer that is not a function');
|
|
956
|
+
continue;
|
|
957
|
+
}
|
|
958
|
+
const d = draftOf(heap), actionId = 'input.action';
|
|
959
|
+
let p = { pc: [sel], locals: new Map(), heap: new Map([...d.heap, [actionId, { k: 'rec', fields: new Map(), origin: 'input', lazy: { prefix: '' } }]]), wrote: [], nows: 0 };
|
|
960
|
+
if (fn.parameters[0])
|
|
961
|
+
p = ex.bind(fn.parameters[0].name, d.v, p);
|
|
962
|
+
if (fn.parameters[1])
|
|
963
|
+
p = ex.bind(fn.parameters[1].name, { t: 'ref', id: actionId }, p);
|
|
964
|
+
const ends = [];
|
|
965
|
+
if (fn.body && !ts.isBlock(fn.body)) {
|
|
966
|
+
const [v, q] = ex.ev(fn.body, p);
|
|
967
|
+
ends.push([q, v]);
|
|
968
|
+
}
|
|
969
|
+
else {
|
|
970
|
+
const flow = ex.block(fn.body.statements, p);
|
|
971
|
+
ends.push(...flow.rets, ...(flow.live ? [[flow.live, { t: 'undef' }]] : []));
|
|
972
|
+
}
|
|
973
|
+
const written = (q) => [...d.heap.keys()].some(id => id.startsWith('draft.') && q.heap.get(id) !== d.heap.get(id));
|
|
974
|
+
const states = ends.map(([q, v]) => {
|
|
975
|
+
const self = v.t === 'ref' && v.id === d.v.id;
|
|
976
|
+
if (v.t !== 'undef' && !self && written(q))
|
|
977
|
+
refuse(fn, `the case reducer for ${type} writes the draft and returns another value (immer throws there)`);
|
|
978
|
+
return [q, materialize(ex, v.t === 'undef' || self ? d.v : v, layout, q, fn)];
|
|
979
|
+
});
|
|
980
|
+
outs.push([sel, joinAll(ex, states, fn)]);
|
|
981
|
+
refusals.push(refusalOf(ex));
|
|
982
|
+
}
|
|
983
|
+
// Any other action: the state as it was (a slice's reducer passes it through).
|
|
984
|
+
const same = materialize(ex0, stateV, layout, { pc: [], locals: new Map(), heap, wrote: [], nows: 0 }, cfg);
|
|
985
|
+
let final = same;
|
|
986
|
+
for (let i = outs.length - 1; i >= 0; i--)
|
|
987
|
+
final = mergeVals(ex0, outs[i][0], outs[i][1], final, cfg);
|
|
988
|
+
// A request: {type, ...the fields the case reducers read of the action}.
|
|
989
|
+
const fields = [...s.lazy].filter(([, l]) => l.prefix === '').map(([n, l]) => [l.field, { k: 'input', name: n }]);
|
|
990
|
+
const events = types.map(t => ({ select: { [ev.name]: t }, call: `${opts.entry}.reducer`, args: [{ k: 'state' }, { k: 'rec', fields: [['type', { k: 'lit', value: t }], ...fields.filter(([f]) => f !== 'type')] }] }));
|
|
991
|
+
s.notes.add(`a Redux Toolkit slice: ${cases.length} case reducers on immer's draft, any other action passing the state through`);
|
|
992
|
+
return finish(s, { name: opts.entry, shape: 'reducer', file, entry: opts.entry, layout, init, final, refuse: I.or(...refusals), pre: I.T, events, outputs: [], event: ev.name, initSource: initExpr.getText() });
|
|
993
|
+
}
|