gdp-wired 0.42.0 → 0.44.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 +14 -3
- package/dist/core/cli.d.ts +8 -1
- package/dist/core/cli.js +271 -30
- package/dist/core/counts.d.ts +8 -1
- package/dist/core/counts.js +171 -302
- package/dist/core/data.js +2 -2
- package/dist/core/dsl.js +26 -30
- package/dist/core/effect-prims.d.ts +60 -0
- package/dist/core/effect-prims.js +625 -0
- package/dist/core/effect-schedule.d.ts +103 -0
- package/dist/core/effect-schedule.js +817 -0
- package/dist/core/effect.d.ts +36 -1
- package/dist/core/effect.js +656 -29
- package/dist/core/ex/harness.exs +2 -0
- package/dist/core/exists.d.ts +5 -0
- package/dist/core/exists.js +98 -34
- package/dist/core/extract-c.d.ts +2 -0
- package/dist/core/extract-c.js +5 -3
- package/dist/core/extract-check.d.ts +2 -0
- package/dist/core/extract-check.js +45 -4
- package/dist/core/extract-ex.js +2 -2
- package/dist/core/extract-go-check.js +4 -6
- package/dist/core/extract-go.d.ts +3 -0
- package/dist/core/extract-go.js +4 -4
- package/dist/core/extract-jvm.js +6 -3
- package/dist/core/extract-print.js +9 -2
- package/dist/core/extract-py.js +2 -2
- package/dist/core/extract-rb.js +2 -2
- package/dist/core/extract-read.js +2 -1
- package/dist/core/extract-rs.js +12 -7
- package/dist/core/extract-sol.js +4 -4
- package/dist/core/extract-step.d.ts +18 -0
- package/dist/core/extract-step.js +135 -31
- package/dist/core/extract-swift.js +3 -3
- package/dist/core/extract.d.ts +8 -0
- package/dist/core/extract.js +13 -1
- package/dist/core/infer.d.ts +1 -0
- package/dist/core/infer.js +10 -7
- package/dist/core/jvm/Harness.java +8 -1
- package/dist/core/jvm/Jvm.java +1 -1
- package/dist/core/jvm/KtReader.java +3 -0
- package/dist/core/laws.d.ts +4 -0
- package/dist/core/laws.js +176 -9
- package/dist/core/machine.d.ts +3 -0
- package/dist/core/machine.js +17 -3
- package/dist/core/py/harness.py +64 -19
- package/dist/core/py/reader.py +51 -1
- package/dist/core/sol/Replay.sol +52 -0
- package/dist/core/sol/harness.py +508 -0
- package/dist/core/system.d.ts +44 -0
- package/dist/core/system.js +435 -0
- package/dist/interchange/check.d.ts +18 -1
- package/dist/interchange/check.js +9 -2
- package/dist/interchange/cli.d.ts +2 -0
- package/dist/interchange/cli.js +45 -0
- package/dist/interchange/format.d.ts +1 -1
- package/dist/interchange/format.js +15 -7
- package/dist/kernel/cdcl.js +32 -12
- package/dist/kernel/kernel.js +3 -2
- package/dist/kernel/prove.d.ts +1 -0
- package/dist/kernel/prove.js +69 -8
- package/dist/kernel/reader.js +3 -2
- package/dist/lean-kernel/emit.js +3 -3
- package/dist/lean-kernel/lean-terms.d.ts +1 -0
- package/dist/lean-kernel/lean-terms.js +8 -4
- package/package.json +12 -3
|
@@ -0,0 +1,625 @@
|
|
|
1
|
+
// Effect's concurrency primitives, modelled once (core/effect.ts reads a service through this): a Queue (bounded,
|
|
2
|
+
// dropping, sliding, unbounded) and a Semaphore of any number of permits, made by the service's make effect, are written
|
|
3
|
+
// again as what Effect's own hold, in transactions over TxRefs (4.x) or TRefs (3.x), and the service read as any:
|
|
4
|
+
// a queue `q` q_items (a map from position to item), q_head (the items that left: taken, polled, slid out or shut
|
|
5
|
+
// down), q_tail (the items that came in) and q_open; it holds the items at q_head .. q_tail - 1, oldest
|
|
6
|
+
// first. offer appends at the tail (a full bounded queue waits, a dropping one answers false, a sliding
|
|
7
|
+
// one lets its oldest go), take answers the oldest (an empty queue waits), poll an Option of it, size the
|
|
8
|
+
// count, shutdown drops what it holds.
|
|
9
|
+
// a semaphore s_taken, the permits taken (Effect's own field), and s_held, those the calling fiber holds (its takes
|
|
10
|
+
// less its releases; under many fibers one a fiber, summing to s_taken, so a release past what was taken
|
|
11
|
+
// is a fiber's own): take(n) waits until n are free, release(n) gives n back (unchecked, as Effect does), withPermits(n)(body) is take, the body's
|
|
12
|
+
// statements, release (a failure in the body releasing first, as its ensuring does).
|
|
13
|
+
// Each operation is one transaction, so one atomic step (as the operation is on Effect's runtime), a wait its guard; a
|
|
14
|
+
// method of several is several steps, the fibers interleaving them (core/effect.ts's fibered). The model's own laws
|
|
15
|
+
// (bounded, nothing lost, FIFO, the permits) are proven once on the canonical service's rule (primitiveRule) and run
|
|
16
|
+
// beside the real primitive on random operations and fibers (primitiveConforms); a service's instances carry the laws
|
|
17
|
+
// that hold of every use (the queue's bound, at most the permits taken) as invariants, and the one that depends on the
|
|
18
|
+
// use (a semaphore never released past what was taken) as a law to prove of it.
|
|
19
|
+
import ts from 'typescript';
|
|
20
|
+
import * as dsl from "./dsl.js";
|
|
21
|
+
import { interpret, searchSeeded } from "./machine.js";
|
|
22
|
+
import { allowed } from "./watch.js";
|
|
23
|
+
import { bare as strip, memberName, refuse, text } from "./extract-read.js";
|
|
24
|
+
import { extractEffect } from "./effect.js";
|
|
25
|
+
const QUEUES = { 'Queue.bounded': 'bounded', 'Queue.dropping': 'dropping', 'Queue.sliding': 'sliding', 'Queue.unbounded': 'unbounded', 'Queue.make': 'bounded' };
|
|
26
|
+
const SEMS = new Set(['Semaphore.make', 'Effect.makeSemaphore', 'Semaphore.makeUnsafe', 'Effect.unsafeMakeSemaphore']);
|
|
27
|
+
// What each version's queue answers on its operations (3.x interrupts every one on a shut-down queue; 4.x only take).
|
|
28
|
+
const QOPS4 = ['offer', 'take', 'poll', 'size', 'isFull', 'shutdown'], QOPS3 = ['offer', 'take', 'poll', 'shutdown', 'isShutdown'];
|
|
29
|
+
const FAILS = /^(Effect|STM)\.(fail|failSync|failCause|failCauseSync|die|dieSync|dieMessage|interrupt)$/;
|
|
30
|
+
export const WAITS_FOREVER = 'an operation that interrupts its fiber on a shut-down queue (every one on Effect 3, take on Effect 4) is read as a wait that never ends: the fiber takes no step after it, which is what an interrupted one does';
|
|
31
|
+
// The service's make effect `make` written again with its primitives modelled; undefined where it makes none (or only
|
|
32
|
+
// Semaphores of 1 used as locks, read as before: core/effect.ts's lock).
|
|
33
|
+
export function rewritePrims(s, made, api, v4, opts = {}) {
|
|
34
|
+
const make = made.fn;
|
|
35
|
+
const sf = s.sf, body = make.body && ts.isBlock(make.body) ? make.body : undefined;
|
|
36
|
+
if (!body || !/\b(Queue|Semaphore|makeSemaphore|unsafeMakeSemaphore)\b/.test(sf.text))
|
|
37
|
+
return undefined;
|
|
38
|
+
const insts = [], params = new Set(made.params.flatMap(p => (ts.isIdentifier(p.name) ? [p.name.text] : [])));
|
|
39
|
+
const whole = (e, what, at, min) => {
|
|
40
|
+
const x = e && strip(e);
|
|
41
|
+
if (x && ts.isNumericLiteral(x) && Number.isInteger(Number(x.text)) && Number(x.text) >= min)
|
|
42
|
+
return Number(x.text);
|
|
43
|
+
if (x && ts.isIdentifier(x) && params.has(x.text) && (opts.params || what === 'permits'))
|
|
44
|
+
return x.text;
|
|
45
|
+
return refuse(e ?? at, `${what} of other than a whole number${min ? ` from ${min}` : ''} written here${what === 'permits' ? ' (or a parameter of the make)' : ''}`);
|
|
46
|
+
};
|
|
47
|
+
for (const st of body.statements) {
|
|
48
|
+
if (!ts.isVariableStatement(st))
|
|
49
|
+
continue;
|
|
50
|
+
for (const d of st.declarationList.declarations) {
|
|
51
|
+
const init = d.initializer && strip(d.initializer), call = init && ts.isYieldExpression(init) && init.expression ? strip(init.expression) : init;
|
|
52
|
+
const a = call && ts.isCallExpression(call) ? api(call.expression) : undefined;
|
|
53
|
+
if (!a || !(a in QUEUES || SEMS.has(a)))
|
|
54
|
+
continue;
|
|
55
|
+
const c = call;
|
|
56
|
+
if (!ts.isIdentifier(d.name))
|
|
57
|
+
refuse(d, `${text(d)}: a ${a.split('.')[0]} bound to a pattern (one name is read)`);
|
|
58
|
+
if (st.declarationList.declarations.length > 1)
|
|
59
|
+
refuse(st, `${text(st)}: a primitive declared beside others (one declaration a statement)`);
|
|
60
|
+
const name = d.name.text, unsafe = /Unsafe|unsafe/.test(a);
|
|
61
|
+
if (!unsafe && !(init && ts.isYieldExpression(init) && init.asteriskToken))
|
|
62
|
+
refuse(d, `${text(d)}: ${a} not yielded where the service is made`);
|
|
63
|
+
if (SEMS.has(a)) {
|
|
64
|
+
insts.push({ name, kind: 'semaphore', permits: whole(c.arguments[0], 'permits', c, 0), fields: [`${name}_taken`, `${name}_held`], decl: d, stmt: st });
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
let strategy = QUEUES[a], cap = c.arguments[0];
|
|
68
|
+
if (a === 'Queue.make') {
|
|
69
|
+
// (4.x: make({capacity, strategy}); no capacity is an unbounded queue)
|
|
70
|
+
const o = c.arguments[0] && strip(c.arguments[0]);
|
|
71
|
+
if (o && !ts.isObjectLiteralExpression(o))
|
|
72
|
+
refuse(o, 'Queue.make of other than {capacity, strategy} written here');
|
|
73
|
+
const props = new Map(o?.properties.map(p => (ts.isPropertyAssignment(p) ? [memberName(p.name), p.initializer] : refuse(p, `Queue.make's ${text(p)} (capacity and strategy are read)`))) ?? []);
|
|
74
|
+
for (const k of props.keys())
|
|
75
|
+
if (k !== 'capacity' && k !== 'strategy')
|
|
76
|
+
refuse(o, `Queue.make's ${k} (capacity and strategy are read)`);
|
|
77
|
+
const sv = props.get('strategy') && strip(props.get('strategy'));
|
|
78
|
+
if (sv && !ts.isStringLiteral(sv))
|
|
79
|
+
refuse(sv, 'a strategy other than a string written here');
|
|
80
|
+
strategy = !props.has('capacity') ? 'unbounded' : sv?.text === 'dropping' ? 'dropping' : sv?.text === 'sliding' ? 'sliding' : 'bounded';
|
|
81
|
+
cap = props.get('capacity');
|
|
82
|
+
}
|
|
83
|
+
const capacity = strategy === 'unbounded' ? undefined : whole(cap, 'a capacity', c, 1);
|
|
84
|
+
// (the item's type: the queue's first type argument)
|
|
85
|
+
const t = s.checker.getTypeAtLocation(d.name), args = t.aliasTypeArguments ?? (t.flags & ts.TypeFlags.Object ? s.checker.getTypeArguments(t) : undefined);
|
|
86
|
+
const it = args?.[0] ?? refuse(d, `${name}: no type for the queue's items`);
|
|
87
|
+
const written = c.typeArguments?.[0]?.getText();
|
|
88
|
+
insts.push({ name, kind: 'queue', strategy, ...(capacity !== undefined ? { capacity } : {}), fields: ['items', 'head', 'tail', 'open'].map(f => `${name}_${f}`), decl: d, stmt: st, item: written ?? s.checker.typeToString(it, d, ts.TypeFormatFlags.NoTruncation), zero: zeroOf(s, it, d) });
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
if (!insts.length)
|
|
92
|
+
return undefined;
|
|
93
|
+
// (the names the model gives: none of the code's own)
|
|
94
|
+
// (the code's identifiers, not its comments: a law there names the model's fields)
|
|
95
|
+
const ids = new Set(), idsOf = (n) => { if (ts.isIdentifier(n))
|
|
96
|
+
ids.add(n.text); ts.forEachChild(n, idsOf); };
|
|
97
|
+
idsOf(sf);
|
|
98
|
+
for (const i of insts)
|
|
99
|
+
for (const n of i.fields)
|
|
100
|
+
if (ids.has(n))
|
|
101
|
+
refuse(i.decl, `${n} is a name of the code's, and one the model of ${i.name} gives`);
|
|
102
|
+
for (const n of ids)
|
|
103
|
+
if (/^gdp\$/.test(n) || insts.some(i => n.startsWith(`${i.name}$`)))
|
|
104
|
+
refuse(sf.statements[0] ?? sf, `${n}: a name of the code's like those the model of the primitives is written with (gdp$..., <primitive>$...)`);
|
|
105
|
+
const ofDecl = new Map(insts.map(i => [i.decl, i]));
|
|
106
|
+
const instOf = (x) => { const e = x && strip(x); const d = e && ts.isIdentifier(e) ? s.checker.getSymbolAtLocation(e)?.valueDeclaration : undefined; return d ? ofDecl.get(d) : undefined; };
|
|
107
|
+
// Every reference to each primitive (each the operation it is called with), seen first without refusing: a service
|
|
108
|
+
// whose only primitives are Semaphores of 1 used as locks is read as before, and a queue it shuts down is known.
|
|
109
|
+
const refs = [];
|
|
110
|
+
const scan = (n) => {
|
|
111
|
+
if (ts.isIdentifier(n) && !(ts.isVariableDeclaration(n.parent) && n.parent.name === n)) {
|
|
112
|
+
const i = instOf(n);
|
|
113
|
+
if (i)
|
|
114
|
+
refs.push([i, n]);
|
|
115
|
+
}
|
|
116
|
+
ts.forEachChild(n, scan);
|
|
117
|
+
};
|
|
118
|
+
scan(sf);
|
|
119
|
+
const opOf = (id) => {
|
|
120
|
+
const p = id.parent;
|
|
121
|
+
if (ts.isCallExpression(p) && p.arguments[0] === id)
|
|
122
|
+
return (api(p.expression) ?? '').split('.')[1] ?? '';
|
|
123
|
+
return ts.isPropertyAccessExpression(p) && p.expression === id ? memberName(p.name) : '';
|
|
124
|
+
};
|
|
125
|
+
const isLock = (id) => {
|
|
126
|
+
const p = id.parent, op = opOf(id);
|
|
127
|
+
if (op === 'withPermit')
|
|
128
|
+
return true;
|
|
129
|
+
const n = op !== 'withPermits' ? undefined : ts.isCallExpression(p) ? p.arguments[1] : ts.isCallExpression(p.parent) ? p.parent.arguments[0] : undefined;
|
|
130
|
+
return !!n && ts.isNumericLiteral(strip(n)) && strip(n).text === '1';
|
|
131
|
+
};
|
|
132
|
+
if (insts.every(i => i.kind === 'semaphore' && i.permits === 1) && refs.every(([, id]) => isLock(id)))
|
|
133
|
+
return undefined;
|
|
134
|
+
for (const [i, id] of refs)
|
|
135
|
+
if (i.kind === 'queue' && opOf(id) === 'shutdown')
|
|
136
|
+
i.shuts = true;
|
|
137
|
+
// Every use of each primitive, an edit: an operation a call of the model's, withPermits statements of the method's.
|
|
138
|
+
const edits = new Map(), lock = new Set();
|
|
139
|
+
const count = (e, at) => whole(e, 'a permit count', at, 1);
|
|
140
|
+
const classify = (i, id) => {
|
|
141
|
+
const p = id.parent, gp = p.parent;
|
|
142
|
+
// Queue.op(q, ...), Semaphore.op(s, ...)
|
|
143
|
+
if (ts.isCallExpression(p) && p.arguments[0] === id) {
|
|
144
|
+
const a = api(p.expression) ?? '', [m = '', op = ''] = a.split('.');
|
|
145
|
+
if (m === 'Queue' && i.kind === 'queue')
|
|
146
|
+
return queueOp(i, op, p, p.arguments.slice(1));
|
|
147
|
+
if (m === 'Semaphore' && i.kind === 'semaphore')
|
|
148
|
+
return semOp(i, op, p, p.arguments.slice(1), true);
|
|
149
|
+
}
|
|
150
|
+
// q.op(...), q.op (3.x's members), s.op(...), s.op
|
|
151
|
+
if (ts.isPropertyAccessExpression(p) && p.expression === id) {
|
|
152
|
+
const op = memberName(p.name), call = ts.isCallExpression(gp) && gp.expression === p ? gp : undefined;
|
|
153
|
+
if (i.kind === 'queue') {
|
|
154
|
+
if (v4)
|
|
155
|
+
refuse(p, `${text(p)}: a queue's member (Queue.${op}(${i.name}, ...) is read)`);
|
|
156
|
+
if (op === 'offer' && call)
|
|
157
|
+
return queueOp(i, op, call, call.arguments);
|
|
158
|
+
if (op === 'capacity' && call)
|
|
159
|
+
return queueOp(i, op, call, []);
|
|
160
|
+
if (op !== 'offer' && op !== 'capacity' && !call)
|
|
161
|
+
return queueOp(i, op, p, []);
|
|
162
|
+
return void refuse(p, `${text(p)} (a queue's ${QOPS3.join(', ')} are read)`);
|
|
163
|
+
}
|
|
164
|
+
return semOp(i, op, call ?? p, call?.arguments ?? [], false);
|
|
165
|
+
}
|
|
166
|
+
refuse(id, `${i.name} used other than by its operations (a ${i.kind} the make effect makes is read where its operations are called on it, not passed or kept)`);
|
|
167
|
+
};
|
|
168
|
+
const queueOp = (i, op, call, args) => {
|
|
169
|
+
const ops = v4 ? QOPS4 : QOPS3;
|
|
170
|
+
if (op === 'capacity' && !v4) {
|
|
171
|
+
edits.set(call, () => String(i.capacity ?? Number.MAX_SAFE_INTEGER));
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
if (!ops.includes(op)) {
|
|
175
|
+
const why = !v4 && ['size', 'isEmpty', 'isFull'].includes(op) ? ': Effect 3\'s size counts the fibers waiting on the queue (takers below zero, back-pressured offers past the capacity), which the rule doesn\'t hold (a waiting request is one not yet taken)' : '';
|
|
176
|
+
refuse(call, `Queue.${op}${why} (${ops.join(', ')} are read${v4 ? '' : ', and capacity'})`);
|
|
177
|
+
}
|
|
178
|
+
if (args.length !== (op === 'offer' ? 1 : 0))
|
|
179
|
+
refuse(call, `Queue.${op} with ${args.length} arguments`);
|
|
180
|
+
edits.set(call, () => `${i.name}$${op}(${args.map(render).join(', ')})`);
|
|
181
|
+
};
|
|
182
|
+
const semOp = (i, op, call, args, fn) => {
|
|
183
|
+
if (op === 'take' || op === 'release') {
|
|
184
|
+
if (args.length !== 1 || !ts.isCallExpression(call))
|
|
185
|
+
refuse(call, `${text(call)}: ${op} of one count`);
|
|
186
|
+
count(args[0], call);
|
|
187
|
+
edits.set(call, () => `${i.name}$${op}(${render(args[0])})`);
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
if (op === 'releaseAll') {
|
|
191
|
+
if (fn ? args.length : ts.isCallExpression(call))
|
|
192
|
+
refuse(call, `${text(call)}: releaseAll is an effect`);
|
|
193
|
+
edits.set(call, () => `${i.name}$releaseAll()`);
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
if (op === 'withPermits' || op === 'withPermit') {
|
|
197
|
+
// (the count and the effect: s.withPermits(n)(e), s.withPermit(e), Semaphore.withPermits(s, n)(e) or (s, n, e),
|
|
198
|
+
// Semaphore.withPermit(s)(e) or (s, e))
|
|
199
|
+
const k = op === 'withPermit' ? 1 : count(args[0], call), rest = op === 'withPermit' ? args : args.slice(1);
|
|
200
|
+
let outer = call, eff = rest[0];
|
|
201
|
+
if (!eff) {
|
|
202
|
+
const o = call.parent;
|
|
203
|
+
if (!ts.isCallExpression(o) || o.expression !== call || o.arguments.length !== 1)
|
|
204
|
+
return void refuse(call, `${text(call)} other than applied to an effect here`);
|
|
205
|
+
outer = o;
|
|
206
|
+
eff = o.arguments[0];
|
|
207
|
+
}
|
|
208
|
+
if (rest.length > 1)
|
|
209
|
+
refuse(call, `${text(call)} with more arguments than the effect`);
|
|
210
|
+
lock.add(i);
|
|
211
|
+
return withPermits(i, k, outer, eff);
|
|
212
|
+
}
|
|
213
|
+
refuse(call, `${text(call)} (a semaphore's take, release, releaseAll, withPermits and withPermit are read${op === 'resize' ? '; resize changes its permits, which the model holds fixed' : ''})`);
|
|
214
|
+
};
|
|
215
|
+
// withPermits(n)(e), yielded as a statement of a generator's body: take, e's statements (or e), release. A failure in
|
|
216
|
+
// e's body releases first (withPermits releases on any exit); one e may fail with elsewhere (a helper, a transaction,
|
|
217
|
+
// a queue's interrupt) is refused, since the release would be skipped.
|
|
218
|
+
let tmp = 0;
|
|
219
|
+
const withPermits = (i, k, w, eff) => {
|
|
220
|
+
const y = w.parent, st = y && ts.isYieldExpression(y) && y.asteriskToken && y.expression === w ? stmtOf(y) : undefined;
|
|
221
|
+
if (!st)
|
|
222
|
+
return void refuse(w, `${text(w)} other than yielded as a statement of a generator's body (\`yield* ${i.name}.withPermits(n)(...)\`, \`const x = yield* ...\` or \`return yield* ...\`): its body's steps and the release are written as the method's own steps${ts.isArrowFunction(w.parent) ? ' (write the method as Effect.fn(\'name\')(function* () { ... }))' : ''}`);
|
|
223
|
+
const take = `yield* ${i.name}$take(${k}); `, release = `yield* ${i.name}$release(${k})`;
|
|
224
|
+
if (ts.isVariableStatement(st) && (st.declarationList.declarations.length !== 1 || !ts.isIdentifier(st.declarationList.declarations[0].name)))
|
|
225
|
+
refuse(st, `${text(st)}: one name declared`);
|
|
226
|
+
const into = ts.isVariableStatement(st) ? st.declarationList.declarations[0].name.text : undefined;
|
|
227
|
+
const kw = ts.isVariableStatement(st) && !(st.declarationList.flags & ts.NodeFlags.Const) ? 'let' : 'const', r = `gdp$v${tmp++}`;
|
|
228
|
+
const g = genBody(eff);
|
|
229
|
+
if (!g) {
|
|
230
|
+
if (canFail(eff))
|
|
231
|
+
refuse(eff, `${text(eff)} inside withPermits may fail (or be interrupted) other than by a statement of the body written here: withPermits releases its permits on any exit, which the steps hold only for a failure written in the body (write it as Effect.gen(function* () { ... }) with the failure there)`);
|
|
232
|
+
edits.set(st, () => (ts.isExpressionStatement(st) ? `${take}yield* ${render(eff)}; ${release}` : into ? `${take}${kw} ${into} = yield* ${render(eff)}; ${release}` : `${take}const ${r} = yield* ${render(eff)}; ${release}; return ${r}`));
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
// (the body's names must not meet the method's: they are declared beside them)
|
|
236
|
+
const outerNames = new Set(), innerNames = new Set();
|
|
237
|
+
const names = (n, to) => { const go = (x) => { if ((ts.isVariableDeclaration(x) || ts.isParameter(x)) && ts.isIdentifier(x.name))
|
|
238
|
+
to.add(x.name.text); if (!ts.isFunctionLike(x))
|
|
239
|
+
ts.forEachChild(x, go); }; go(n); };
|
|
240
|
+
for (const other of st.parent.statements)
|
|
241
|
+
if (other !== st)
|
|
242
|
+
names(other, outerNames);
|
|
243
|
+
let fnHost = st.parent;
|
|
244
|
+
while (fnHost && !ts.isFunctionLike(fnHost))
|
|
245
|
+
fnHost = fnHost.parent;
|
|
246
|
+
for (const p of fnHost?.parameters ?? [])
|
|
247
|
+
if (ts.isIdentifier(p.name))
|
|
248
|
+
outerNames.add(p.name.text);
|
|
249
|
+
for (const b of g.statements)
|
|
250
|
+
names(b, innerNames);
|
|
251
|
+
for (const n of innerNames)
|
|
252
|
+
if (outerNames.has(n))
|
|
253
|
+
refuse(eff, `${n} is declared inside withPermits' body and around it (the body's statements are written beside the method's: rename one)`);
|
|
254
|
+
const last = g.statements.at(-1), value = last && ts.isReturnStatement(last) && !failing(last.expression) ? last : undefined;
|
|
255
|
+
const stmts = value ? g.statements.slice(0, -1) : g.statements;
|
|
256
|
+
// (each failing statement of the body releases first; every other may fail nowhere)
|
|
257
|
+
const walk = (b) => {
|
|
258
|
+
if ((ts.isExpressionStatement(b) || ts.isReturnStatement(b)) && failing(b.expression)) {
|
|
259
|
+
edits.set(b, () => `{ ${release}; ${render0(b)} }`);
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
if (ts.isReturnStatement(b))
|
|
263
|
+
return void refuse(b, `${text(b)}: a return inside withPermits' body before its end (the body's statements are written in the method's: return at its end)`);
|
|
264
|
+
if (ts.isIfStatement(b)) {
|
|
265
|
+
if (canFail(b.expression))
|
|
266
|
+
refuse(b.expression, `${text(b.expression)} inside withPermits may fail other than by a statement of its body`);
|
|
267
|
+
walk(b.thenStatement);
|
|
268
|
+
if (b.elseStatement)
|
|
269
|
+
walk(b.elseStatement);
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
if (ts.isBlock(b))
|
|
273
|
+
return b.statements.forEach(walk);
|
|
274
|
+
if (canFail(b))
|
|
275
|
+
refuse(b, `${text(b)} inside withPermits may fail (or be interrupted) other than by a statement of its body written here (a helper's or a transaction's failure, an operation on a queue the service shuts down): withPermits releases its permits on any exit, which the steps hold only there`);
|
|
276
|
+
};
|
|
277
|
+
stmts.forEach(walk);
|
|
278
|
+
if (value?.expression && canFail(value.expression))
|
|
279
|
+
refuse(value, `${text(value)} inside withPermits may fail other than by a statement of its body`);
|
|
280
|
+
edits.set(st, () => {
|
|
281
|
+
// (the body's statements with the lines between them, so the code keeps its place)
|
|
282
|
+
let out = take, at = g.getStart(sf) + 1;
|
|
283
|
+
for (const b of stmts) {
|
|
284
|
+
out += gap(at, b.getStart(sf)) + render(b);
|
|
285
|
+
at = b.end;
|
|
286
|
+
}
|
|
287
|
+
const v = value?.expression ? render(value.expression) : 'undefined';
|
|
288
|
+
const tail = ts.isExpressionStatement(st) ? `${value?.expression && /\byield\b/.test(v) ? `${v}; ` : ''}${release}` : into ? `${kw} ${into} = ${v}; ${release}` : `const ${r} = ${v}; ${release}; return ${r}`;
|
|
289
|
+
return `${out}${gap(at, value ? value.getStart(sf) : g.end)} ${tail}`;
|
|
290
|
+
});
|
|
291
|
+
};
|
|
292
|
+
const gap = (a, b) => '\n'.repeat((sf.text.slice(a, Math.max(a, b)).match(/\n/g) ?? []).length) || ' ';
|
|
293
|
+
const failing = (e) => {
|
|
294
|
+
const y = e && strip(e);
|
|
295
|
+
if (!y || !ts.isYieldExpression(y) || !y.expression)
|
|
296
|
+
return false;
|
|
297
|
+
const x = strip(y.expression);
|
|
298
|
+
return ts.isNewExpression(x) || FAILS.test((ts.isCallExpression(x) ? api(x.expression) : api(x)) ?? '');
|
|
299
|
+
};
|
|
300
|
+
// Whether running n may fail: a failure in it, in a helper it calls, or an operation that interrupts on a queue the
|
|
301
|
+
// service shuts down.
|
|
302
|
+
const memo = new Map();
|
|
303
|
+
const canFail = (n) => {
|
|
304
|
+
let hit = false;
|
|
305
|
+
const go = (x) => {
|
|
306
|
+
if (hit)
|
|
307
|
+
return;
|
|
308
|
+
if (ts.isYieldExpression(x) && x.expression && ts.isNewExpression(strip(x.expression))) {
|
|
309
|
+
hit = true;
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
if (ts.isCallExpression(x) || ts.isPropertyAccessExpression(x)) {
|
|
313
|
+
const a = api(ts.isCallExpression(x) ? x.expression : x) ?? '';
|
|
314
|
+
if (FAILS.test(a)) {
|
|
315
|
+
hit = true;
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
const q = ts.isCallExpression(x) ? instOf(x.arguments[0]) : instOf(x.expression);
|
|
319
|
+
if (q?.kind === 'queue' && q.shuts && (!v4 || a === 'Queue.take')) {
|
|
320
|
+
hit = true;
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
if (ts.isIdentifier(x) && ts.isCallExpression(x.parent) && x.parent.expression === x) {
|
|
325
|
+
const d = s.checker.getSymbolAtLocation(x)?.valueDeclaration;
|
|
326
|
+
if (d && ts.isVariableDeclaration(d) && d.initializer && d.getSourceFile() === sf) {
|
|
327
|
+
if (!memo.has(d)) {
|
|
328
|
+
memo.set(d, false);
|
|
329
|
+
memo.set(d, canFail(d.initializer));
|
|
330
|
+
}
|
|
331
|
+
if (memo.get(d)) {
|
|
332
|
+
hit = true;
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
ts.forEachChild(x, go);
|
|
338
|
+
};
|
|
339
|
+
go(n);
|
|
340
|
+
return hit;
|
|
341
|
+
};
|
|
342
|
+
for (const [i, id] of refs)
|
|
343
|
+
classify(i, id);
|
|
344
|
+
for (const i of insts)
|
|
345
|
+
edits.set(i.stmt, () => model(i, v4));
|
|
346
|
+
const out = `${imports(v4)}${render(sf)}`;
|
|
347
|
+
const notes = insts.map(i => (i.kind === 'queue'
|
|
348
|
+
? `${i.name} is an Effect ${v4 ? 4 : 3} Queue (${i.strategy}${i.capacity !== undefined ? `, ${i.capacity} items` : ''}), modelled: ${i.fields.join(', ')}; it holds the items at ${i.name}_head .. ${i.name}_tail - 1, oldest first${i.strategy === 'bounded' ? '; an offer to it full waits' : i.strategy === 'dropping' ? '; an offer to it full answers false' : i.strategy === 'sliding' ? '; an offer to it full lets its oldest item go' : ''}; a take from it empty waits${i.shuts ? `; shut down, it drops what it holds (${WAITS_FOREVER})` : ''}`
|
|
349
|
+
: `${i.name} is an Effect ${v4 ? 4 : 3} Semaphore of ${i.permits} permits, modelled: ${i.name}_taken, the permits taken, and ${i.name}_held, those the calling fiber holds (its takes less its releases; under many fibers each fiber's, summing to ${i.name}_taken); a take waits until they are free, a release gives them back unchecked (as Effect does)${lock.has(i) ? '; withPermits is the take, its body\'s statements, the release (a failure in the body releasing first)' : ''}`));
|
|
350
|
+
return { code: out, prims: insts.map(({ decl: _d, stmt: _s, item: _i, zero: _z, shuts: _h, ...p }) => p), notes };
|
|
351
|
+
// The code with every edit made: a node edited is its edit, else its text with its children's edits. (Each edit keeps
|
|
352
|
+
// its lines: the code after it is where it was, so a refusal's place is the file's.)
|
|
353
|
+
function render(n) {
|
|
354
|
+
const e = edits.get(n);
|
|
355
|
+
if (!e)
|
|
356
|
+
return render0(n);
|
|
357
|
+
const out = e(), lines = n.getText(sf).split('\n').length - out.split('\n').length;
|
|
358
|
+
return lines > 0 ? out + '\n'.repeat(lines) : out;
|
|
359
|
+
}
|
|
360
|
+
function render0(n) {
|
|
361
|
+
const start = ts.isSourceFile(n) ? 0 : n.getStart(sf);
|
|
362
|
+
if (![...edits.keys()].some(k => k !== n && k.pos >= n.pos && k.end <= n.end))
|
|
363
|
+
return sf.text.slice(start, n.end);
|
|
364
|
+
let out = '', pos = start;
|
|
365
|
+
for (const c of n.getChildren(sf)) {
|
|
366
|
+
if (ts.isJSDoc(c))
|
|
367
|
+
continue;
|
|
368
|
+
out += sf.text.slice(pos, Math.max(pos, c.getStart(sf))) + render(c);
|
|
369
|
+
pos = c.end;
|
|
370
|
+
}
|
|
371
|
+
return out + sf.text.slice(pos, n.end);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
// The statement a yield* is the whole of: `yield* x;`, `const v = yield* x`, `return yield* x`.
|
|
375
|
+
function stmtOf(y) {
|
|
376
|
+
let p = y.parent;
|
|
377
|
+
while (ts.isParenthesizedExpression(p))
|
|
378
|
+
p = p.parent;
|
|
379
|
+
if (ts.isExpressionStatement(p) || ts.isReturnStatement(p))
|
|
380
|
+
return ts.isBlock(p.parent) ? p : undefined;
|
|
381
|
+
if (ts.isVariableDeclaration(p) && ts.isVariableDeclarationList(p.parent) && ts.isVariableStatement(p.parent.parent) && ts.isBlock(p.parent.parent.parent))
|
|
382
|
+
return p.parent.parent;
|
|
383
|
+
return undefined;
|
|
384
|
+
}
|
|
385
|
+
// Effect.gen(function* () {...})'s body.
|
|
386
|
+
function genBody(e) {
|
|
387
|
+
const x = strip(e);
|
|
388
|
+
if (!ts.isCallExpression(x) || !ts.isPropertyAccessExpression(x.expression) || memberName(x.expression.name) !== 'gen' || x.arguments.length !== 1)
|
|
389
|
+
return undefined;
|
|
390
|
+
const f = strip(x.arguments[0]);
|
|
391
|
+
return ts.isFunctionExpression(f) && f.asteriskToken && ts.isBlock(f.body) ? f.body : undefined;
|
|
392
|
+
}
|
|
393
|
+
// An item's zero, for the model's read at the queue's head (never read where the queue holds an item): a number's 0, a
|
|
394
|
+
// boolean's false. (A record's would make the read one object or another by the path, a string's a value no union holds:
|
|
395
|
+
// refused.)
|
|
396
|
+
function zeroOf(s, t, at) {
|
|
397
|
+
if (t.flags & ts.TypeFlags.NumberLike)
|
|
398
|
+
return '0';
|
|
399
|
+
if (t.flags & ts.TypeFlags.BooleanLike || (t.isUnion() && t.types.every(u => u.flags & ts.TypeFlags.BooleanLiteral)))
|
|
400
|
+
return 'false';
|
|
401
|
+
return refuse(at, `a queue of ${s.checker.typeToString(t)} (numbers and booleans are read: queue an id, the item in a Ref's map)`);
|
|
402
|
+
}
|
|
403
|
+
// --- the model -------------------------------------------------------------------------------------------------------
|
|
404
|
+
const imports = (v4) => (v4 ? "import {Effect as gdp$Effect, TxRef as gdp$TxRef, Option as gdp$Option} from 'effect'; " : "import {STM as gdp$STM, TRef as gdp$TRef, Option as gdp$Option} from 'effect'; ");
|
|
405
|
+
// The declarations a primitive is written as: its fields' TxRefs (TRefs) and one function an operation, each one
|
|
406
|
+
// transaction (on one line, so the code after it keeps its place).
|
|
407
|
+
function model(i, v4) {
|
|
408
|
+
const R = v4 ? 'gdp$TxRef' : 'gdp$TRef', tx = (b) => (v4 ? `gdp$Effect.tx(gdp$Effect.gen(function* () { ${b} }))` : `gdp$STM.commit(gdp$STM.gen(function* () { ${b} }))`);
|
|
409
|
+
const wait = v4 ? 'return yield* gdp$Effect.txRetry' : 'return yield* gdp$STM.retry', get = (r) => `(yield* ${R}.get(${r}))`, set = (r, v) => `yield* ${R}.set(${r}, ${v});`;
|
|
410
|
+
const mk = (n, t, v) => `const ${n} = yield* ${R}.make<${t}>(${v});`;
|
|
411
|
+
const fn = (op, ps, b) => `const ${i.name}$${op} = (${ps}) => ${tx(b)};`;
|
|
412
|
+
if (i.kind === 'semaphore') {
|
|
413
|
+
const n = i.name, P = String(i.permits);
|
|
414
|
+
// (and the permits the calling fiber holds, its takes less its releases: the taken are every fiber's, summed)
|
|
415
|
+
const own = (d) => `const o = ${get(`${n}_held`)}; ${set(`${n}_held`, `o + ${d}`)}`;
|
|
416
|
+
return [mk(`${n}_taken`, 'number', '0'), mk(`${n}_held`, 'number', '0'),
|
|
417
|
+
fn('take', 'n: number', `const t = ${get(`${n}_taken`)}; if (${P} - t < n) ${wait}; ${set(`${n}_taken`, 't + n')} ${own('n')} return n`),
|
|
418
|
+
fn('release', 'n: number', `const t = ${get(`${n}_taken`)}; ${set(`${n}_taken`, 't - n')} ${own('-n')} return ${P} - (t - n)`),
|
|
419
|
+
fn('releaseAll', '', `const t = ${get(`${n}_taken`)}; ${set(`${n}_taken`, '0')} ${own('-t')} return ${P}`)].join(' ');
|
|
420
|
+
}
|
|
421
|
+
const q = i.name, A = i.item, Z = i.zero, C = i.capacity, closed = (v) => `if (!${get(`${q}_open`)}) ${v4 ? `return ${v}` : wait};`;
|
|
422
|
+
const full = C === undefined ? '' : `if (t - h >= ${C}) ${i.strategy === 'bounded' ? `${wait};` : i.strategy === 'dropping' ? 'return false;' : `{ ${set(`${q}_head`, 'h + 1')} }`}`;
|
|
423
|
+
const front = `const h = ${get(`${q}_head`)}; const t = ${get(`${q}_tail`)};`;
|
|
424
|
+
return [mk(`${q}_items`, `ReadonlyMap<number, ${A}>`, 'new Map()'), mk(`${q}_head`, 'number', '0'), mk(`${q}_tail`, 'number', '0'), mk(`${q}_open`, 'boolean', 'true'),
|
|
425
|
+
fn('offer', `x: ${A}`, `${closed('false')} ${front} ${full} yield* ${R}.update(${q}_items, m => new Map(m).set(t, x)); ${set(`${q}_tail`, 't + 1')} return true`),
|
|
426
|
+
// (4.x's take fails on a shut-down queue as 3.x's interrupts: a wait that never ends, as the notes say)
|
|
427
|
+
fn('take', '', `if (!${get(`${q}_open`)}) ${wait}; ${front} if (t <= h) ${wait}; const m = ${get(`${q}_items`)}; ${set(`${q}_head`, 'h + 1')} return m.get(h) ?? ${Z}`),
|
|
428
|
+
fn('poll', '', `${closed('gdp$Option.none()')} ${front} if (t <= h) return gdp$Option.none(); const m = ${get(`${q}_items`)}; ${set(`${q}_head`, 'h + 1')} return gdp$Option.some(m.get(h) ?? ${Z})`),
|
|
429
|
+
fn('size', '', `${closed('0')} return ${get(`${q}_tail`)} - ${get(`${q}_head`)}`),
|
|
430
|
+
fn('isFull', '', C === undefined ? 'return false' : `${closed('false')} return ${get(`${q}_tail`)} - ${get(`${q}_head`)} === ${C}`),
|
|
431
|
+
fn('isShutdown', '', `return !${get(`${q}_open`)}`),
|
|
432
|
+
fn('shutdown', '', `if (!${get(`${q}_open`)}) return ${v4 ? 'false' : 'undefined'}; ${set(`${q}_head`, get(`${q}_tail`))} ${set(`${q}_open`, 'false')} return ${v4 ? 'true' : 'undefined'}`)].join(' ');
|
|
433
|
+
}
|
|
434
|
+
const QUEUE_OPS = (v4) => (v4 ? ['offer', 'take', 'poll', 'size', 'isFull', 'shutdown'] : ['offer', 'take', 'poll', 'isShutdown', 'shutdown']);
|
|
435
|
+
const SEM_OPS = ['take1', 'take2', 'release1', 'release2', 'releaseAll'];
|
|
436
|
+
function canonical(spec, v4) {
|
|
437
|
+
const m = (n, b) => ` const ${n} = Effect.fn('${n}')(function* (${n === 'offer' ? 'x: number' : ''}) { ${b} })`;
|
|
438
|
+
if (spec.kind === 'semaphore')
|
|
439
|
+
return `import {Effect${v4 ? ', Semaphore' : ''}} from 'effect'
|
|
440
|
+
export const make = (permits: number) => Effect.gen(function* () {
|
|
441
|
+
const s = yield* ${v4 ? 'Semaphore.make' : 'Effect.makeSemaphore'}(permits)
|
|
442
|
+
${[1, 2].flatMap(n => [m(`take${n}`, `return yield* s.take(${n})`), m(`release${n}`, `return yield* s.release(${n})`)]).join('\n')}
|
|
443
|
+
${m('releaseAll', 'return yield* s.releaseAll')}
|
|
444
|
+
return {${SEM_OPS.join(', ')}}
|
|
445
|
+
})
|
|
446
|
+
`;
|
|
447
|
+
const ops = QUEUE_OPS(v4), body = {
|
|
448
|
+
offer: 'return yield* Queue.offer(q, x)', take: 'return yield* Queue.take(q)', size: 'return yield* Queue.size(q)', isFull: 'return yield* Queue.isFull(q)', isShutdown: 'return yield* Queue.isShutdown(q)',
|
|
449
|
+
poll: 'const o = yield* Queue.poll(q); return Option.isSome(o) ? Option.getOrElse(o, () => 0) : -1', shutdown: v4 ? 'return yield* Queue.shutdown(q)' : 'yield* Queue.shutdown(q)'
|
|
450
|
+
};
|
|
451
|
+
return `import {Effect, Option, Queue} from 'effect'
|
|
452
|
+
export const make = (${spec.strategy === 'unbounded' ? '' : 'capacity: number'}) => Effect.gen(function* () {
|
|
453
|
+
const q = yield* Queue.${spec.strategy}<number>(${spec.strategy === 'unbounded' ? '' : 'capacity'})
|
|
454
|
+
${ops.map(o => m(o, body[o])).join('\n')}
|
|
455
|
+
return {${ops.join(', ')}}
|
|
456
|
+
})
|
|
457
|
+
`;
|
|
458
|
+
}
|
|
459
|
+
// The canonical service's rule (an Extraction of core/effect.ts's): a queue of numbers of a strategy, every capacity (a
|
|
460
|
+
// natural) its parameter; a semaphore, every number of permits.
|
|
461
|
+
// (`file`: where the code is read as if it were, so its imports resolve to that `effect`'s types: by default beside the
|
|
462
|
+
// working directory)
|
|
463
|
+
export function primitiveRule(spec, effect, opts = {}) {
|
|
464
|
+
const v4 = 'TxRef' in effect, name = spec.kind === 'queue' ? `queue-${spec.strategy}` : 'semaphore';
|
|
465
|
+
return extractEffect({ code: canonical(spec, v4), file: opts.file ?? `${name}.ts` }, { entry: 'make', effect, fibers: false, capacityParam: true, domains: { capacity: 'nat', permits: 'nat' }, check: { runs: opts.runs ?? 40 } });
|
|
466
|
+
}
|
|
467
|
+
// Its laws: the invariants (a queue's bound; at most the permits taken) and what each operation does to it, as step laws
|
|
468
|
+
// (nothing is lost: what comes in comes by an offer, at the tail; what leaves is the oldest, to the take or poll whose
|
|
469
|
+
// answer it is, to a slide or to a shutdown; what is held stays where it is). The semaphore's use law (never released
|
|
470
|
+
// past what was taken) is no law of Effect's own (a release is unchecked): it is a law of a service's use, refuted here.
|
|
471
|
+
export function primitiveLaws(x, spec) {
|
|
472
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
473
|
+
const r = x.rule, inv = x.invariants ?? [], is = (b, ...ms) => dsl.any(...ms.map(m => b.method.is(m)));
|
|
474
|
+
if (spec.kind === 'semaphore') {
|
|
475
|
+
return { laws: inv, refuted: x.primitives?.flatMap(p => p.laws) ?? [], stepLaws: [
|
|
476
|
+
r.stepLaw('a take of n waits until n are free, then takes them', (b, a) => dsl.any(a.s_taken.eq(b.s_taken), a.s_taken.eq(b.s_taken.plus(dsl.when(is(b, 'take2'), 2, 1))).and(a.s_taken.atMost(b.permits))), (b) => is(b, 'take1', 'take2')),
|
|
477
|
+
r.stepLaw('a release of n gives back n, unchecked', (b, a) => a.s_taken.eq(b.s_taken.minus(dsl.when(is(b, 'release2'), 2, 1))), (b) => is(b, 'release1', 'release2')),
|
|
478
|
+
r.stepLaw('only a take waits', (b, a) => a.s_taken.eq(b.s_taken).implies(is(b, 'take1', 'take2').or(b.method.is('releaseAll').and(b.s_taken.eq(0)))), (b) => is(b, 'take1', 'take2', 'release1', 'release2', 'releaseAll').and(dsl.not(is(b, 'take1', 'take2')))),
|
|
479
|
+
] };
|
|
480
|
+
}
|
|
481
|
+
const st = spec.strategy, cap = (b) => (st === 'unbounded' ? undefined : b.capacity), full = (b) => (cap(b) ? b.q_tail.minus(b.q_head).atLeast(cap(b)) : dsl.no);
|
|
482
|
+
const item = (s, k) => s.q_items.at(k).value, same = (b, a) => a.q_head.eq(b.q_head).and(a.q_tail.eq(b.q_tail));
|
|
483
|
+
const appended = (b, a) => a.q_tail.eq(b.q_tail.plus(1)).and(dsl.same(item(a, b.q_tail), b.offer_x));
|
|
484
|
+
return { laws: inv, refuted: [], stepLaws: [
|
|
485
|
+
r.stepLaw(st === 'bounded' ? 'an offer appends its item at the tail (full, it waits)' : st === 'dropping' ? 'an offer appends its item at the tail; full, it answers false and changes nothing' : st === 'sliding' ? 'an offer appends its item at the tail; full, the oldest item leaves to make room' : 'an offer appends its item at the tail', (b, a) => dsl.any(same(b, a), appended(b, a).and(st === 'sliding' ? dsl.when(full(b), a.q_head.eq(b.q_head.plus(1)), a.q_head.eq(b.q_head)) : a.q_head.eq(b.q_head).and(dsl.not(full(b))))).and(st === 'dropping' ? full(b).implies(same(b, a)) : dsl.yes), (b) => b.method.is('offer')),
|
|
486
|
+
r.stepLaw('a take or a poll answers the oldest item, which leaves', (b, a) => a.q_head.eq(b.q_head).or(a.q_head.eq(b.q_head.plus(1)).and(dsl.same(dsl.when(b.method.is('take'), a.take_result, a.poll_result), item(b, b.q_head)))), (b) => is(b, 'take', 'poll')),
|
|
487
|
+
r.stepLaw('only the oldest item leaves, to a take, a poll, a slide or a shutdown', (b, a) => dsl.any(a.q_head.eq(b.q_head), a.q_head.eq(b.q_head.plus(1)).and(is(b, 'take', 'poll', ...(st === 'sliding' ? ['offer'] : []))), b.method.is('shutdown').and(a.q_head.eq(b.q_tail)))),
|
|
488
|
+
r.stepLaw('nothing comes in but an offer, at the tail', (b, a) => a.q_tail.eq(b.q_tail).or(b.method.is('offer').and(a.q_tail.eq(b.q_tail.plus(1))))),
|
|
489
|
+
r.stepLaw('the items held stay where they are', (b, a) => dsl.forall((k) => k.atLeast(a.q_head).and(k.lt(b.q_tail)).implies(dsl.same(item(a, k), item(b, k))))),
|
|
490
|
+
] };
|
|
491
|
+
}
|
|
492
|
+
// The rule beside Effect's own primitive: `runs` runs of `depth` operations (a capacity from 1 to 4, or 0 to 3 permits),
|
|
493
|
+
// each started on a fiber of its own; after each, the runtime runs until nothing more moves, every operation that
|
|
494
|
+
// completed is a step the rule takes with its answer (in an order the rule allows), every one still waiting one the rule
|
|
495
|
+
// refuses, and what the primitive holds is the rule's (a queue's size, a semaphore's taken; at the end of a run, a queue's
|
|
496
|
+
// items in order). An operation that interrupts its fiber on a shut-down queue is one the rule refuses (WAITS_FOREVER).
|
|
497
|
+
// (checked: the completions stepped; blocked: the operations found waiting after an operation, each refused by the rule;
|
|
498
|
+
// waited: those ended by a shut-down queue; interrupted: the waiting ones interrupted)
|
|
499
|
+
export async function primitiveConforms(spec, effect, opts = {}) {
|
|
500
|
+
const E = effect, v4 = 'TxRef' in E, x = opts.x ?? primitiveRule(spec, E, opts.file ? { file: opts.file } : {});
|
|
501
|
+
if (!x.ok || !x.rule)
|
|
502
|
+
return { checked: 0, waited: 0, blocked: 0, interrupted: 0, failure: `the rule: ${x.refusals.map(f => f.what).join('; ')}` };
|
|
503
|
+
const r = x.rule, g = r.compiled(), interp = interpret(r.machine), rand = searchSeeded(opts.seed ?? 1);
|
|
504
|
+
const inputs = r.parts.inputs.map(([n]) => n).filter(n => n !== 'method');
|
|
505
|
+
const ops = spec.kind === 'queue' ? QUEUE_OPS(v4) : SEM_OPS;
|
|
506
|
+
const tick = () => new Promise(res => setTimeout(res, 0));
|
|
507
|
+
let checked = 0, waited = 0, blocked = 0, interrupted = 0;
|
|
508
|
+
for (let run = 0; run < (opts.runs ?? 100); run++) {
|
|
509
|
+
const n = spec.kind === 'queue' ? 1 + rand(4) : rand(4), params = spec.kind === 'queue' ? (spec.strategy === 'unbounded' ? {} : { capacity: n }) : { permits: n };
|
|
510
|
+
const ps = r.encodeParams(params);
|
|
511
|
+
const prim = E.Effect.runSync(spec.kind === 'semaphore' ? (v4 ? E.Semaphore.make(n) : E.Effect.makeSemaphore(n)) : spec.strategy === 'unbounded' ? E.Queue.unbounded() : E.Queue[spec.strategy](n));
|
|
512
|
+
const effOf = (op, arg) => {
|
|
513
|
+
if (spec.kind === 'semaphore')
|
|
514
|
+
return op === 'releaseAll' ? prim.releaseAll : prim[op.slice(0, -1)](Number(op.slice(-1)));
|
|
515
|
+
if (op === 'offer')
|
|
516
|
+
return E.Queue.offer(prim, arg);
|
|
517
|
+
if (op === 'poll')
|
|
518
|
+
return E.Effect.map(E.Queue.poll(prim), (o) => (E.Option.isSome(o) ? o.value : -1));
|
|
519
|
+
return E.Queue[op](prim);
|
|
520
|
+
};
|
|
521
|
+
const live = [], sent = [], done = [];
|
|
522
|
+
let st = g.init(ps), order = 0;
|
|
523
|
+
const request = (o) => r.encodeInput({ method: o.op, ...Object.fromEntries(inputs.map(i => [i, 0])), ...(o.op === 'offer' ? { offer_x: o.arg } : {}) }, params);
|
|
524
|
+
const takes = (s, o) => { try {
|
|
525
|
+
return allowed(r.machine, interp, ps, s, request(o));
|
|
526
|
+
}
|
|
527
|
+
catch {
|
|
528
|
+
return false;
|
|
529
|
+
} };
|
|
530
|
+
const at = () => `${JSON.stringify(params)}, after ${sent.join(', ')}`;
|
|
531
|
+
const fail = (what) => ({ checked, waited, blocked, interrupted, failure: `${at()}: ${what}` });
|
|
532
|
+
for (let d = 0; d < (opts.depth ?? 16); d++) {
|
|
533
|
+
// (an operation, or now and then a waiting one interrupted, or a queue shut down)
|
|
534
|
+
const pick = rand(12);
|
|
535
|
+
if (pick === 0 && live.length) {
|
|
536
|
+
const o = live[rand(live.length)];
|
|
537
|
+
o.killed = true;
|
|
538
|
+
sent.push(`interrupt #${o.id}`);
|
|
539
|
+
interrupted++;
|
|
540
|
+
E.Effect.runFork(E.Fiber.interrupt(o.fiber));
|
|
541
|
+
}
|
|
542
|
+
else {
|
|
543
|
+
const op = ops.filter(o => o !== 'shutdown' || pick === 1)[rand(ops.length - (ops.includes('shutdown') && pick !== 1 ? 1 : 0))], arg = rand(10);
|
|
544
|
+
const o = { id: d, op, arg, fiber: undefined };
|
|
545
|
+
sent.push(`#${d} ${op}${op === 'offer' ? `(${arg})` : ''}`);
|
|
546
|
+
o.fiber = E.Effect.runFork(effOf(op, arg));
|
|
547
|
+
o.fiber.addObserver((exit) => { o.exit = exit; o.at = order++; });
|
|
548
|
+
live.push(o);
|
|
549
|
+
}
|
|
550
|
+
for (let i = 0; i < 4; i++)
|
|
551
|
+
await tick();
|
|
552
|
+
// (what completed since, in the order it did; each a step the rule takes, in some order it allows)
|
|
553
|
+
const now = live.filter(o => o.exit).sort((a, b) => a.at - b.at);
|
|
554
|
+
for (const o of now)
|
|
555
|
+
live.splice(live.indexOf(o), 1);
|
|
556
|
+
const pending = now.filter(o => !o.killed);
|
|
557
|
+
for (const o of [...pending])
|
|
558
|
+
if (!E.Exit.isSuccess(o.exit)) {
|
|
559
|
+
// (an operation on a shut-down queue that interrupts its fiber: one the rule refuses, as a wait)
|
|
560
|
+
if (takes(st, o))
|
|
561
|
+
return fail(`#${o.id} ${o.op} ends its fiber (${String(E.Cause.pretty(o.exit.cause)).split('\n')[0]}), the rule takes it`);
|
|
562
|
+
pending.splice(pending.indexOf(o), 1);
|
|
563
|
+
waited++;
|
|
564
|
+
}
|
|
565
|
+
while (pending.length) {
|
|
566
|
+
const i = pending.findIndex(o => {
|
|
567
|
+
if (!takes(st, o))
|
|
568
|
+
return false;
|
|
569
|
+
const s2 = g.step(ps, g.fork(st), request(o)), want = r.decode(s2)[`${o.op}_result`], got = o.exit.value;
|
|
570
|
+
return typeof got === 'object' || got === undefined || JSON.stringify(want) === JSON.stringify(typeof got === 'boolean' ? got : got);
|
|
571
|
+
});
|
|
572
|
+
if (i < 0) {
|
|
573
|
+
const o = pending[0], s2 = takes(st, o) ? r.decode(g.step(ps, g.fork(st), request(o))) : undefined;
|
|
574
|
+
return fail(`#${o.id} ${o.op} completes with ${JSON.stringify(o.exit.value)}, the rule ${s2 ? `answers ${JSON.stringify(s2[`${o.op}_result`])}` : 'refuses it (it would wait)'}`);
|
|
575
|
+
}
|
|
576
|
+
const o = pending.splice(i, 1)[0];
|
|
577
|
+
st = g.step(ps, st, request(o));
|
|
578
|
+
done.push(o);
|
|
579
|
+
checked++;
|
|
580
|
+
}
|
|
581
|
+
// (what still waits, the rule refuses; what the primitive holds, the rule holds)
|
|
582
|
+
for (const o of live) {
|
|
583
|
+
if (!o.killed && takes(st, o))
|
|
584
|
+
return fail(`#${o.id} ${o.op} waits, the rule takes it`);
|
|
585
|
+
if (!o.killed)
|
|
586
|
+
blocked++;
|
|
587
|
+
}
|
|
588
|
+
const mine = r.decode(st);
|
|
589
|
+
if (spec.kind === 'semaphore') {
|
|
590
|
+
if (prim.taken !== mine.s_taken)
|
|
591
|
+
return fail(`the semaphore has ${prim.taken} taken, the rule ${mine.s_taken}`);
|
|
592
|
+
}
|
|
593
|
+
else {
|
|
594
|
+
const open = v4 ? prim.state._tag !== 'Done' : !prim.shutdownFlag.current;
|
|
595
|
+
const size = v4 ? E.Queue.sizeUnsafe(prim) : open ? prim.queue.length() : 0;
|
|
596
|
+
if (open !== (mine.q_open ?? true))
|
|
597
|
+
return fail(`the queue is ${open ? 'open' : 'shut down'}, the rule's ${open ? 'shut down' : 'open'}`);
|
|
598
|
+
if (open && size !== Number(mine.q_tail) - Number(mine.q_head))
|
|
599
|
+
return fail(`the queue holds ${size}, the rule ${Number(mine.q_tail) - Number(mine.q_head)}`);
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
// (the end of a run: every waiting fiber interrupted; a queue's items, polled one by one, are the rule's in order)
|
|
603
|
+
for (const o of live)
|
|
604
|
+
E.Effect.runFork(E.Fiber.interrupt(o.fiber));
|
|
605
|
+
for (let i = 0; i < 4; i++)
|
|
606
|
+
await tick();
|
|
607
|
+
if (spec.kind === 'queue') {
|
|
608
|
+
const mine = r.decode(st), open = v4 ? prim.state._tag !== 'Done' : !prim.shutdownFlag.current;
|
|
609
|
+
if (open) {
|
|
610
|
+
const items = mine.q_items, held = [], got = [];
|
|
611
|
+
for (let k = Number(mine.q_head); k < Number(mine.q_tail); k++)
|
|
612
|
+
held.push(Number((items instanceof Map ? items.get(k) : items[k])?.value));
|
|
613
|
+
for (let k = 0; k < 64; k++) {
|
|
614
|
+
const o = E.Effect.runSync(E.Queue.poll(prim));
|
|
615
|
+
if (!E.Option.isSome(o))
|
|
616
|
+
break;
|
|
617
|
+
got.push(o.value);
|
|
618
|
+
}
|
|
619
|
+
if (JSON.stringify(held) !== JSON.stringify(got))
|
|
620
|
+
return fail(`the queue holds ${JSON.stringify(got)}, the rule ${JSON.stringify(held)}`);
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
return { checked, waited, blocked, interrupted };
|
|
625
|
+
}
|