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.
Files changed (66) hide show
  1. package/README.md +14 -3
  2. package/dist/core/cli.d.ts +8 -1
  3. package/dist/core/cli.js +271 -30
  4. package/dist/core/counts.d.ts +8 -1
  5. package/dist/core/counts.js +171 -302
  6. package/dist/core/data.js +2 -2
  7. package/dist/core/dsl.js +26 -30
  8. package/dist/core/effect-prims.d.ts +60 -0
  9. package/dist/core/effect-prims.js +625 -0
  10. package/dist/core/effect-schedule.d.ts +103 -0
  11. package/dist/core/effect-schedule.js +817 -0
  12. package/dist/core/effect.d.ts +36 -1
  13. package/dist/core/effect.js +656 -29
  14. package/dist/core/ex/harness.exs +2 -0
  15. package/dist/core/exists.d.ts +5 -0
  16. package/dist/core/exists.js +98 -34
  17. package/dist/core/extract-c.d.ts +2 -0
  18. package/dist/core/extract-c.js +5 -3
  19. package/dist/core/extract-check.d.ts +2 -0
  20. package/dist/core/extract-check.js +45 -4
  21. package/dist/core/extract-ex.js +2 -2
  22. package/dist/core/extract-go-check.js +4 -6
  23. package/dist/core/extract-go.d.ts +3 -0
  24. package/dist/core/extract-go.js +4 -4
  25. package/dist/core/extract-jvm.js +6 -3
  26. package/dist/core/extract-print.js +9 -2
  27. package/dist/core/extract-py.js +2 -2
  28. package/dist/core/extract-rb.js +2 -2
  29. package/dist/core/extract-read.js +2 -1
  30. package/dist/core/extract-rs.js +12 -7
  31. package/dist/core/extract-sol.js +4 -4
  32. package/dist/core/extract-step.d.ts +18 -0
  33. package/dist/core/extract-step.js +135 -31
  34. package/dist/core/extract-swift.js +3 -3
  35. package/dist/core/extract.d.ts +8 -0
  36. package/dist/core/extract.js +13 -1
  37. package/dist/core/infer.d.ts +1 -0
  38. package/dist/core/infer.js +10 -7
  39. package/dist/core/jvm/Harness.java +8 -1
  40. package/dist/core/jvm/Jvm.java +1 -1
  41. package/dist/core/jvm/KtReader.java +3 -0
  42. package/dist/core/laws.d.ts +4 -0
  43. package/dist/core/laws.js +176 -9
  44. package/dist/core/machine.d.ts +3 -0
  45. package/dist/core/machine.js +17 -3
  46. package/dist/core/py/harness.py +64 -19
  47. package/dist/core/py/reader.py +51 -1
  48. package/dist/core/sol/Replay.sol +52 -0
  49. package/dist/core/sol/harness.py +508 -0
  50. package/dist/core/system.d.ts +44 -0
  51. package/dist/core/system.js +435 -0
  52. package/dist/interchange/check.d.ts +18 -1
  53. package/dist/interchange/check.js +9 -2
  54. package/dist/interchange/cli.d.ts +2 -0
  55. package/dist/interchange/cli.js +45 -0
  56. package/dist/interchange/format.d.ts +1 -1
  57. package/dist/interchange/format.js +15 -7
  58. package/dist/kernel/cdcl.js +32 -12
  59. package/dist/kernel/kernel.js +3 -2
  60. package/dist/kernel/prove.d.ts +1 -0
  61. package/dist/kernel/prove.js +69 -8
  62. package/dist/kernel/reader.js +3 -2
  63. package/dist/lean-kernel/emit.js +3 -3
  64. package/dist/lean-kernel/lean-terms.d.ts +1 -0
  65. package/dist/lean-kernel/lean-terms.js +8 -4
  66. package/package.json +12 -3
@@ -16,19 +16,35 @@
16
16
  // a Schema's kind.
17
17
  import ts from 'typescript';
18
18
  import * as dsl from "./dsl.js";
19
- import { interpret, seeded } from "./machine.js";
19
+ import { interpret, lcg, seeded } from "./machine.js";
20
20
  import { allowed } from "./watch.js";
21
21
  import * as I from "./extract-ir.js";
22
- import { Refusal, bare as strip, beside, impure, memberName, placed, refuse, shapeOf, sourceOf, text } from "./extract-read.js";
22
+ import { Refusal, bare as strip, beside, impure, memberName, normalize, placed, refuse, shapeOf, sourceOf, text, where } from "./extract-read.js";
23
23
  import { readFactory, setupOf } from "./extract-shapes.js";
24
24
  import { fromModel, namesOf } from "./extract.js";
25
- import { check } from "./extract-check.js";
25
+ import { check, sandbox } from "./extract-check.js";
26
+ import { Parts, readSchedule, replaySchedule, scheduleConforms, scheduleRule } from "./effect-schedule.js";
27
+ import { asRule, lift } from "./system.js";
28
+ import { rewritePrims } from "./effect-prims.js";
26
29
  export { proveRule, proveSteps } from "./dsl.js";
27
- const REFS = new Set(['Ref', 'SynchronizedRef', 'SubscriptionRef', 'TxRef']), MAKES = ['make', 'makeUnsafe', 'unsafeMake'];
28
- const STM = (api) => `${api}: STM (v3) is not read (a Ref, SynchronizedRef, or v4's TxRef is)`, MATCH = (x) => `${x}: a matcher (write the dispatch as a switch on _tag, or ifs)`;
30
+ export { jitterRun, replaySchedule, scheduleConforms, stepper } from "./effect-schedule.js";
31
+ export { primitiveConforms, primitiveLaws, primitiveRule } from "./effect-prims.js";
32
+ const REFS = new Set(['Ref', 'SynchronizedRef', 'SubscriptionRef', 'TxRef', 'TRef']), MAKES = ['make', 'makeUnsafe', 'unsafeMake'];
33
+ // (Effect's RateLimiter: 3.x's gives its permits back on a fiber of its own, forked into the make effect's scope, on
34
+ // timers; 4.x's (effect/persistence) keeps its counters in a store every user of it shares)
35
+ const RATE = 'a RateLimiter (not modelled: 3.x\'s gives its permits back on timers of a fiber forked into the scope, 4.x\'s keeps its counters in a store shared by its every user): write the window in Refs read with Clock.currentTimeMillis, or a rule by hand beside it (conforms)';
36
+ const STM = (api) => `${api} (of STM: gen, commit, succeed, sync, void, fail, die, check and retry are read)`, MATCH = (x) => `${x}: a matcher (write the dispatch as a switch on _tag, or ifs)`;
37
+ // The Effect line the file is read for (4.x unless the project's effect is 3.x), and the policies its methods retry or
38
+ // repeat with, each read into its schedule's rule.
39
+ let V4 = true;
40
+ let found = [];
41
+ const SLEPT = '$slept';
29
42
  // Where on a path the step has changed a Ref so far (a condition in the heap, so merges and helpers carry it).
30
43
  const CHANGED = '$changed';
31
- const changedOn = (p) => { const o = p.heap.get(CHANGED); return o?.k === 'alias' && o.to.t === 'bool' ? o.to.e : I.F; };
44
+ const changedOn = (p, k = CHANGED) => { const o = p.heap.get(k); return o?.k === 'alias' && o.to.t === 'bool' ? o.to.e : I.F; };
45
+ // Inside a transaction (STM.gen, STM.commit, 4.x's Effect.tx), the writes made before it: what a failure there keeps
46
+ // (the transaction's own are rolled back).
47
+ const OUTER = '$outer', flagged = (b) => ({ k: 'alias', to: { t: 'bool', e: b } });
32
48
  const changedOf = (v, c) => (v.t === 'phi' ? I.bite(v.c, changedOf(v.a, c), changedOf(v.b, c)) : v.t === 'ref' && c.t === 'ref' && v.id === c.id ? I.F
33
49
  : (v.t === 'num' || v.t === 'bool' || v.t === 'str' || v.t === 'choice') && v.t === c.t && I.same(v.e, c.e) ? I.F : I.T);
34
50
  // --- the reader -----------------------------------------------------------------------------------------------------
@@ -69,13 +85,13 @@ function fnOf(s, e) {
69
85
  refuse(e.arguments[1], `${head} with combinators after its body (their effects aren't read)`);
70
86
  return g;
71
87
  }
72
- const genOf = (s, e) => {
73
- if (callOf(s, e) !== 'Effect.gen')
88
+ const genOf = (s, e, which = 'Effect.gen') => {
89
+ if (callOf(s, e) !== which)
74
90
  return undefined;
75
91
  const args = strip(e).arguments, g = args.at(-1);
76
92
  if (args.length !== 1)
77
- refuse(e, 'Effect.gen with a this (a generator of one function is read)');
78
- return g && ts.isFunctionExpression(g) && g.asteriskToken ? g : refuse(e, 'Effect.gen of other than a function*');
93
+ refuse(e, `${which} with a this (a generator of one function is read)`);
94
+ return g && ts.isFunctionExpression(g) && g.asteriskToken ? g : refuse(e, `${which} of other than a function*`);
79
95
  };
80
96
  // A type's type argument: Ref<A>'s A, Effect<A, E, R>'s A, Generator<Y, R, N>'s R.
81
97
  const argOf = (s, t, i) => (t.aliasTypeArguments ?? (t.flags & ts.TypeFlags.Object ? s.checker.getTypeArguments(t) : undefined))?.[i];
@@ -158,8 +174,10 @@ function factoryOf(s, entry) {
158
174
  refs.set(id, m);
159
175
  return { shape: shapeOf(t, s.checker, d), init: start };
160
176
  }
161
- if (m === 'TRef' || m === 'STM')
177
+ if (m === 'STM')
162
178
  return refuse(d, STM(api));
179
+ if (m === 'RateLimiter' || /\bRateLimiter\b/.test(call.getText()))
180
+ return refuse(d, RATE);
163
181
  if (m === 'Semaphore' || /^Effect\.(unsafeM|m)akeSemaphore$/.test(api)) {
164
182
  const n = call.arguments[0];
165
183
  if (!n || !ts.isNumericLiteral(n) || n.text !== '1')
@@ -199,11 +217,29 @@ function hook(s, refs, locks, effects) {
199
217
  // An error made of pure values: `new E({...})` of a class (an error class has no effects), or a plain value.
200
218
  const effectful = (x) => (x = strip(x), ts.isNewExpression(x) && ts.isIdentifier(x.expression) ? (x.arguments ?? []).some(impure) : impure(x));
201
219
  // A failure: the step refused where it is reached; where a Ref has been changed on the path, the Ref keeps it.
202
- const fail = (ex, at, q) => {
203
- if (!ex.known(q, I.not(changedOn(q))))
204
- refuse(at, `fails after writing ${q.wrote.join(', ')}: a Ref keeps what was written (a rule's refusal leaves the state as it was)`);
205
- ex.throws.push({ pc: q.pc });
206
- return [undef, { ...q, pc: [...q.pc, I.F] }];
220
+ const fail = (ex, at, q, when = I.T) => {
221
+ const kept = q.heap.has(OUTER) ? changedOn(q, OUTER) : changedOn(q), at2 = { ...q, pc: [...q.pc, when] };
222
+ if (!ex.known(at2, I.not(kept)))
223
+ refuse(at, `fails after writing ${q.wrote.join(', ')}${q.heap.has(OUTER) ? ' before the transaction' : ''}: a Ref keeps what was written (a rule's refusal leaves the state as it was)`);
224
+ ex.throws.push({ pc: at2.pc });
225
+ return [undef, { ...q, pc: [...q.pc, I.not(when)] }];
226
+ };
227
+ // A transaction: its writes kept where it succeeds, rolled back where it fails or waits (one inside another joins it).
228
+ const tx = (inner, at) => (inner.t !== 'eff' ? refuse(at, `${text(at)}: a transaction of other than an effect`) : eff(q => {
229
+ if (q.heap.has(OUTER))
230
+ return inner.run(q);
231
+ const [v, q2] = inner.run({ ...q, heap: new Map(q.heap).set(OUTER, flagged(changedOn(q))).set(CHANGED, flagged(I.F)) });
232
+ const heap = new Map(q2.heap).set(CHANGED, flagged(I.or(changedOn(q2, OUTER), changedOn(q2))));
233
+ heap.delete(OUTER);
234
+ return [v, { ...q2, heap }];
235
+ }));
236
+ // A transaction that waits (STM.check of false, STM.retry, 4.x's Effect.txRetry): the request isn't taken until a TRef it
237
+ // read changes, a refusal in the rule.
238
+ const waits = (ex, at, q, when = I.T) => {
239
+ if (!q.heap.has(OUTER))
240
+ refuse(at, `${text(at)} outside a transaction`);
241
+ s.notes.add('a transaction that waits (STM.check, STM.retry, Effect.txRetry) is not taken until a TRef it read changes: the rule refuses the request (it is taken later as a new one)');
242
+ return fail(ex, at, q, when);
207
243
  };
208
244
  // A function's body run on a path, with the locals where it was made.
209
245
  const body = (ex, f, at, locals, args = []) => eff(q => ex.inline({ decl: f }, args, at, q, locals));
@@ -227,12 +263,18 @@ function hook(s, refs, locks, effects) {
227
263
  }
228
264
  if (ts.isPropertyAccessExpression(e)) {
229
265
  const api = apiOf(s, e);
230
- if (api === 'Effect.void' || api === 'Effect.unit')
266
+ if (api === 'Effect.void' || api === 'Effect.unit' || api === 'STM.void' || api === 'STM.unit')
267
+ return [eff(q => [undef, q]), p];
268
+ if (api === 'Effect.txRetry' || api === 'STM.retry')
269
+ return [eff(q => waits(ex, e, q)), p];
270
+ if (api === 'Effect.yieldNow')
231
271
  return [eff(q => [undef, q]), p];
232
272
  if (api === 'Clock.currentTimeMillis')
233
- return [eff(q => ex.now(e, q)), p];
273
+ return [eff(q => (q.heap.has(SLEPT) ? refuse(e, 'the clock read after a repeat that waits (the time has moved on by its delays)') : ex.now(e, q))), p];
234
274
  if (api?.startsWith('Clock.'))
235
275
  return refuse(e, `${api} (Clock.currentTimeMillis is read, as an input)`);
276
+ if (!api && ['_tag', 'value'].includes(memberName(e.name)) && /^Option<|^(Some|None)</.test(s.checker.typeToString(s.checker.getTypeAtLocation(e.expression))))
277
+ return refuse(e, `${text(e)}: an Option's ${memberName(e.name)} (Option.isSome, isNone, getOrElse and getOrUndefined are read)`);
236
278
  if (api && /^(Random|DateTime|Crypto|Console|Config|FileSystem)\./.test(api) && ts.isYieldExpression(e.parent))
237
279
  return refuse(e, `${api}: an answer from outside the Refs read (Clock.currentTimeMillis is the one read, as an input)`);
238
280
  return undefined;
@@ -252,12 +294,24 @@ function hook(s, refs, locks, effects) {
252
294
  // x.pipe(...): only annotations (a span, a log annotation) are read through.
253
295
  if (ts.isPropertyAccessExpression(callee) && memberName(callee.name) === 'pipe' && !api) {
254
296
  const head = strip(callee.expression);
297
+ if (e.arguments.length === 1 && apiOf(s, e.arguments[0]) === 'STM.commit') {
298
+ const [v, q] = ex.ev(head, p);
299
+ return [tx(v, head), q];
300
+ }
255
301
  if (callOf(s, head)?.startsWith('Match.'))
256
302
  return refuse(head, MATCH(text(head)));
257
- for (const a of e.arguments)
258
- if (!ANNOTATIONS.has(callOf(s, a) ?? ''))
259
- return refuse(a, `${text(a)} in a pipe (a combinator's effect isn't read: write the step in Effect.gen)`);
260
- return ex.ev(callee.expression, p);
303
+ let [v, q] = ex.ev(callee.expression, p);
304
+ for (const a of e.arguments) {
305
+ const c = callOf(s, a) ?? '';
306
+ if (ANNOTATIONS.has(c))
307
+ continue;
308
+ if ((c === 'Effect.retry' || c === 'Effect.repeat') && strip(a).arguments.length === 1) {
309
+ v = scheduled(ex, c, v, strip(a).arguments[0], e);
310
+ continue;
311
+ }
312
+ return refuse(a, `${text(a)} in a pipe (a combinator's effect isn't read: write the step in Effect.gen)`);
313
+ }
314
+ return [v, q];
261
315
  }
262
316
  // A helper of the same files written with Effect.fn: its body run where it is yielded.
263
317
  if (ts.isIdentifier(callee)) {
@@ -270,7 +324,27 @@ function hook(s, refs, locks, effects) {
270
324
  }
271
325
  if (REFS.has(m))
272
326
  return refOp(ex, e, m, op, p);
273
- if (m === 'Effect') {
327
+ if ((api === 'Effect.retry' || api === 'Effect.repeat') && e.arguments.length === 2) {
328
+ const [v, q] = ex.ev(one, p);
329
+ return [scheduled(ex, api, v, e.arguments[1], e), q];
330
+ }
331
+ if (api === 'Effect.tx' || api === 'STM.commit') {
332
+ const [v, q] = ex.ev(one ?? refuse(e, `${api}()`), p);
333
+ return [tx(v, e), q];
334
+ }
335
+ if (m === 'STM') {
336
+ if (op === 'gen')
337
+ return [tx(body(ex, genOf(s, e, 'STM.gen'), e, p.locals), e), p];
338
+ if (op === 'check') {
339
+ const f = one && fnOf(s, one);
340
+ if (!f || f.parameters.length || ts.isBlock(f.body))
341
+ return refuse(e, 'STM.check of other than () => condition written here');
342
+ return [eff(q => { const [c, q1] = ex.ev(f.body, q); return c.t === 'bool' ? waits(ex, e, q1, I.not(c.e)) : refuse(e, `STM.check of other than a condition (${c.t})`); }), p];
343
+ }
344
+ if (!['succeed', 'sync', 'fail', 'failSync', 'die', 'dieMessage'].includes(op))
345
+ return refuse(e, STM(api));
346
+ }
347
+ if (m === 'Effect' || m === 'STM') {
274
348
  if (op === 'gen')
275
349
  return [body(ex, genOf(s, e), e, p.locals), p];
276
350
  if (op === 'succeed') {
@@ -281,22 +355,165 @@ function hook(s, refs, locks, effects) {
281
355
  return [body(ex, fnOf(s, one ?? refuse(e, 'Effect.sync()')) ?? refuse(e, 'Effect.sync of other than a function written here'), e, p.locals), p];
282
356
  if (FAILS.has(op))
283
357
  return e.arguments.some(effectful) ? refuse(e, `Effect.${op} of a value that has effects`) : [eff(q => fail(ex, e, q)), p];
358
+ if (op === 'sleep') {
359
+ if (e.arguments.some(impure))
360
+ return refuse(e, 'Effect.sleep of a value that has effects');
361
+ return [eff(q => [undef, { ...q, heap: new Map(q.heap).set(SLEPT, flagged(I.T)) }]), p];
362
+ }
284
363
  if (LOGS.has(op)) {
285
364
  if (e.arguments.some(impure))
286
365
  return refuse(e, `Effect.${op} of values that have effects`);
287
366
  s.notes.add('Effect.log and span annotations are left out (they write nothing the rule keeps)');
288
367
  return [eff(q => [undef, q]), p];
289
368
  }
369
+ if (m === 'STM')
370
+ return refuse(e, STM(api));
290
371
  return refuse(e, op === 'fn' || op === 'fnUntraced' ? `Effect.${op} as a value inside a step (a method or a helper of the service is read)` : `Effect.${op} (Effect.gen, Effect.fn bodies, succeed, sync, fail, die, void and log are read; the effect of ${op} isn't)`);
291
372
  }
292
373
  if (m === 'Match')
293
374
  return refuse(e, MATCH(api));
294
- if (m === 'STM' || m === 'TRef')
295
- return refuse(e, STM(api));
375
+ if (m === 'Option')
376
+ return option(ex, e, op, p);
377
+ if (m === 'RateLimiter')
378
+ return refuse(e, RATE);
379
+ if (m === 'Queue')
380
+ return refuse(e, `${api}: a Queue other than one the service's make effect makes (yield* Queue.bounded(n), dropping, sliding, unbounded or make, read as its model)`);
381
+ if (m === 'TRef')
382
+ return refuse(e, `${api} (a TRef the service's make effect makes is read: get, set, update, modify and their variants)`);
296
383
  if (m === 'Semaphore')
297
384
  return refuse(e, `${api} (a Semaphore of 1 made by the service, as a lock, is read)`);
298
385
  return undefined;
299
386
  };
387
+ // Effect.retry / Effect.repeat of an effect read here, with a schedule (or {times, schedule, while, until}). The
388
+ // policy is read into its schedule's rule (its laws proven on their own: x.schedules). The effect is what the service
389
+ // does to its Refs, so each attempt of a retry fails as the first did (a failure leaves the Refs as they were, and the
390
+ // attempts read nothing else that moves): the step is the effect's, the policy's delays passing only on the way to the
391
+ // failure. A repeat runs it again as many times as the policy goes on, counted by running the policy's rule.
392
+ function scheduled(ex, api, v, policy, at) {
393
+ const use = api === 'Effect.retry' ? 'retry' : 'repeat', pol = strip(policy);
394
+ if (v.t !== 'eff')
395
+ return refuse(at, `${api} of other than an effect`);
396
+ let sched, times;
397
+ if (ts.isObjectLiteralExpression(pol)) {
398
+ for (const pr of pol.properties) {
399
+ const k = ts.isPropertyAssignment(pr) ? memberName(pr.name) : '';
400
+ if (k === 'schedule')
401
+ sched = pr.initializer;
402
+ else if (k === 'times') {
403
+ const n = strip(pr.initializer);
404
+ times = ts.isNumericLiteral(n) ? Number(n.text) : refuse(n, `${use}'s times of other than a number written here`);
405
+ }
406
+ else if ((k === 'while' || k === 'until') && use === 'retry')
407
+ s.notes.add(`${use}'s ${k} reads the error: each attempt fails with the same one, so it decides only how many attempts are made`);
408
+ else
409
+ return refuse(pr, `${use}'s ${text(pr)} (schedule, times${use === 'retry' ? ', while and until' : ''} are read)`);
410
+ }
411
+ }
412
+ else
413
+ sched = pol;
414
+ const outer = (n) => refuse(n, `${text(n)}: a ${use} policy reading the service's params (one written with literals and consts is read: the check runs it)`);
415
+ const P = new Parts(), base = sched ? readSchedule(sched, { api: x => apiOf(s, x), checker: s.checker, v4: V4, params: new Map(), sf: s.sf, outer }, P) : undefined;
416
+ let frag = base?.frag;
417
+ if (times !== undefined) {
418
+ const lim = (frag ?? { step: () => ({ cont: dsl.yes, delay: dsl.lit(0), next: {} }), names: [] }), n = times;
419
+ frag = { ...lim, step: (env, get, c) => { const x = lim.step(env, get, c); return { ...x, cont: x.cont.and(c.attempt.lt(n)) }; } };
420
+ }
421
+ if (!frag)
422
+ return refuse(at, `${use} with no schedule and no times (it would go on forever)`);
423
+ const sr = scheduleRule(frag, P, `${use} policy`, V4);
424
+ // (a method may be read more than once: one entry a place)
425
+ if (!found.some(f => f.at === where(at)))
426
+ found.push({ at: where(at), use, source: sched ? sched.getText() : `{times: ${times}}`, rule: sr });
427
+ // The policy run as Effect drives it, each attempt taking no time: how many times it goes on (for every input it
428
+ // may be fed, drawn), and how long it waits in all.
429
+ const g = sr.rule.compiled(), ps = sr.rule.encodeParams({}), rand = (() => { let x = 7; return (n) => (x = lcg(x)) % Math.max(1, n); })();
430
+ const runOnce = (draw) => {
431
+ let st = g.init(ps), n = 0, waited = 0;
432
+ for (; n < 1000; n++) {
433
+ const inp = { took: 0 };
434
+ for (const [f, k] of sr.fields)
435
+ inp[f === '_tag' ? 'input__tag' : f === 'input' ? 'input' : `input_${f}`] = k.sample(draw ? rand : () => 0, 3);
436
+ for (const j of sr.jitters)
437
+ inp[j.name] = 0;
438
+ try {
439
+ st = g.step(ps, st, sr.rule.encodeInput(inp));
440
+ }
441
+ catch {
442
+ return { stops: true, n, waited };
443
+ }
444
+ const d = sr.rule.decode(st);
445
+ if (d.done)
446
+ return { stops: true, n, waited };
447
+ waited += Number(d.delay);
448
+ }
449
+ return { stops: false, n, waited };
450
+ };
451
+ const runs = [runOnce(false), ...(sr.fields.size ? Array.from({ length: 8 }, () => runOnce(true)) : [])];
452
+ if (runs.some(r => !r.stops))
453
+ return refuse(policy, `a ${use} whose policy goes on past 1000 attempts${use === 'retry' ? ' around an effect read here, which fails the same way each time: the call would never return' : ''} (bound it: recurs, upTo, times)`);
454
+ if (sr.jitters.length)
455
+ s.notes.add(`the ${use} policy's jitter is left to its rule (x.schedules): it moves only the time the step waits`);
456
+ if (use === 'retry') {
457
+ s.notes.add(`${text(at)}: retried with ${sched ? text(sched) : `{times: ${times}}`}; each attempt fails as the first did (the effect reads only the Refs, which a failure leaves as they were), so the step is the effect's; the policy's own laws are proven on its rule (x.schedules)`);
458
+ return eff(q => withoutClock(ex, 'the clock read in an effect that is retried (each attempt reads a later time: a loop the step doesn\'t unroll)', () => v.run(q)));
459
+ }
460
+ if (sr.fields.size)
461
+ return refuse(sched, 'a repeat whose policy reads the effect\'s result (a loop the step doesn\'t unroll)');
462
+ const n = runs[0].n, waited = runs[0].waited;
463
+ if (n > 16)
464
+ return refuse(policy, `a repeat that runs the effect ${n + 1} times (up to 17 are unrolled)`);
465
+ let host = at;
466
+ while (host.parent && (ts.isCallExpression(host.parent) || ts.isParenthesizedExpression(host.parent) || ts.isPropertyAccessExpression(host.parent)))
467
+ host = host.parent;
468
+ if (!ts.isYieldExpression(host.parent) || !ts.isExpressionStatement(host.parent.parent))
469
+ return refuse(at, 'the value of a repeat (its policy\'s output): yield* it as a statement');
470
+ s.notes.add(`${text(at)}: the effect runs ${n + 1} times in the step (its policy goes on ${n} times)${waited ? `, waiting ${waited} ms in all` : ''}`);
471
+ return eff(q => {
472
+ let r = [undef, q];
473
+ withoutClock(ex, 'the clock read in an effect that is repeated (each run reads a later time)', () => { for (let i = 0; i <= n; i++)
474
+ r = v.run(r[1]); });
475
+ return [undef, waited ? { ...r[1], heap: new Map(r[1].heap).set(SLEPT, flagged(I.T)) } : r[1]];
476
+ });
477
+ }
478
+ // f run with the clock refused where it is read (an effect run again later in the step reads a later time).
479
+ function withoutClock(ex, why, f) {
480
+ const own = Object.getOwnPropertyDescriptor(ex, 'now');
481
+ Object.defineProperty(ex, 'now', { value: (n) => refuse(n, why), configurable: true, writable: true });
482
+ try {
483
+ return f();
484
+ }
485
+ finally {
486
+ if (own)
487
+ Object.defineProperty(ex, 'now', own);
488
+ else
489
+ delete ex.now;
490
+ }
491
+ }
492
+ // Option's constructors and reads, over a value that may be missing (Queue.poll's answer): some, none, isSome, isNone,
493
+ // getOrElse (of a default written here) and getOrUndefined.
494
+ function option(ex, e, op, p) {
495
+ const [a, b] = e.arguments, has = (v) => (v.t === 'opt' ? v.has : v.t === 'undef' ? I.F : I.T), n = e.arguments.length;
496
+ if (op === 'none' && !n)
497
+ return [{ t: 'undef' }, p];
498
+ if (op === 'some' && n === 1) {
499
+ const [v, q] = ex.ev(a, p);
500
+ return [{ t: 'opt', has: I.T, v }, q];
501
+ }
502
+ if ((op === 'isSome' || op === 'isNone') && n === 1) {
503
+ const [v, q] = ex.ev(a, p);
504
+ return [{ t: 'bool', e: op === 'isSome' ? has(v) : I.not(has(v)) }, q];
505
+ }
506
+ if (op === 'getOrUndefined' && n === 1)
507
+ return ex.ev(a, p);
508
+ if (op === 'getOrElse' && n === 2) {
509
+ const f = fnOf(s, b);
510
+ if (!f || f.parameters.length || ts.isBlock(f.body) || impure(f.body))
511
+ return refuse(b, 'Option.getOrElse of other than () => a value written here');
512
+ const [v, q] = ex.ev(a, p), [d, q2] = ex.ev(f.body, q);
513
+ return [v.t === 'opt' ? ex.phiV(v.has, v.v, d, e) : v.t === 'undef' ? d : v, q2];
514
+ }
515
+ return refuse(e, `Option.${op} (some, none, isSome, isNone, getOrElse and getOrUndefined are read)`);
516
+ }
300
517
  // Ref.op(ref, ...): the ref a Ref the service made (by its name), its value the state's field.
301
518
  function refOp(ex, e, m, op, p) {
302
519
  const r = e.arguments[0] && strip(e.arguments[0]), base = op.replace(/Effect$/, ''), answer = ANSWERS[base], f = e.arguments[1];
@@ -344,13 +561,40 @@ export function runner(E) {
344
561
  let now = 0;
345
562
  // A Clock at `now`: 4.x names its unsafe reads currentTime<X>Unsafe, 3.x unsafeCurrentTime<X>.
346
563
  const unsafe = (x) => (v4 ? `currentTime${x}Unsafe` : `unsafeCurrentTime${x}`), ns = () => BigInt(now) * 1000000n;
347
- const clock = Object.create(Effect.runSync(v4 ? Effect.clockWith((c) => Effect.succeed(c)) : Effect.clock), { [unsafe('Millis')]: { value: () => now }, currentTimeMillis: { value: Effect.sync(() => now) }, [unsafe('Nanos')]: { value: ns }, currentTimeNanos: { value: Effect.sync(ns) } });
564
+ // (a sleep, a retry's or a repeat's, passes at once: the clock moves on by its duration)
565
+ const clock = Object.create(Effect.runSync(v4 ? Effect.clockWith((c) => Effect.succeed(c)) : Effect.clock), { [unsafe('Millis')]: { value: () => now }, currentTimeMillis: { value: Effect.sync(() => now) }, [unsafe('Nanos')]: { value: ns }, currentTimeNanos: { value: Effect.sync(ns) },
566
+ sleep: { value: (d) => Effect.sync(() => { now += E.Duration.toMillis(d); }) } });
348
567
  const exit = (eff, t) => {
349
568
  if (!Effect.isEffect(eff))
350
569
  return { ok: false, error: `not an effect: ${String(eff).slice(0, 60)}` };
351
570
  now = t;
352
- const x = Effect.runSyncExit(v4 ? Effect.provideService(eff, Clock.Clock, clock) : Effect.withClock(eff, clock));
353
- return Exit.isSuccess(x) ? { ok: true, value: x.value } : { ok: false, error: String(Cause.pretty(x.cause)).split('\n')[0] };
571
+ // (3.x on a scheduler of its own, so a fiber left waiting, a transaction that retries, is interrupted at once: it
572
+ // would otherwise wake and commit inside a later request)
573
+ let x, waiting;
574
+ if (v4) {
575
+ x = Effect.runSyncExit(Effect.provideService(eff, Clock.Clock, clock));
576
+ waiting = Exit.isSuccess(x) ? undefined : (x.cause.reasons ?? []).map((r) => r.defect).find((d) => d && typeof d === 'object' && 'fiber' in d);
577
+ waiting?.fiber.interruptUnsafe();
578
+ }
579
+ else {
580
+ // (on a scheduler of its own: what yields to it (a SynchronizedRef's lock) runs on when it is flushed; a fiber still
581
+ // waiting then is interrupted there)
582
+ const sch = new E.Scheduler.SyncScheduler();
583
+ x = Effect.runSyncExit(Effect.withScheduler(Effect.withClock(eff, clock), sch));
584
+ const fiber = Exit.isSuccess(x) ? undefined : x.cause.defect?.fiber;
585
+ if (fiber) {
586
+ for (let i = 0; i < 64 && !(x = fiber.unsafePoll()); i++)
587
+ sch.flush();
588
+ if (!x) {
589
+ waiting = { fiber };
590
+ fiber.unsafeInterruptAsFork(E.FiberId.none);
591
+ sch.flush();
592
+ }
593
+ }
594
+ }
595
+ if (x && Exit.isSuccess(x))
596
+ return { ok: true, value: x.value };
597
+ return { ok: false, error: waiting ? 'it waits (an effect that suspends: a transaction that retries, a fiber it waits for)' : String(Cause.pretty(x.cause)).split('\n')[0] };
354
598
  };
355
599
  const run = (eff, t = now) => { const x = exit(eff, t); if (!x.ok)
356
600
  throw new Error(x.error); return x.value; };
@@ -364,7 +608,20 @@ export function extractEffect(at, opts = {}) {
364
608
  E = opts.effect ?? beside(file, 'effect');
365
609
  if (!E)
366
610
  throw new Refusal(file, 'no effect package resolves from the file (install it in its project, or give it: {effect: await import(\'effect\')})');
611
+ V4 = 'TxRef' in E;
612
+ found = [];
613
+ const sch = scheduleEntry(code, file, opts);
614
+ if (sch)
615
+ return fromScheduleEntry(code, file, sch, E, opts);
367
616
  const entry = opts.entry ?? serviceOf(code, file, opts);
617
+ const pr = modelled(code, file, entry, E, opts);
618
+ if (pr)
619
+ return pr;
620
+ if (opts.fibers !== false) {
621
+ const f = fibered(code, file, entry, E, opts);
622
+ if (f)
623
+ return f;
624
+ }
368
625
  m = readFactory(code, placed(file), { ...opts, entry }, s => factoryOf(s, entry));
369
626
  m.file = file;
370
627
  if (!opts.entry)
@@ -377,7 +634,377 @@ export function extractEffect(at, opts = {}) {
377
634
  }
378
635
  // The modules the code imports, by specifier (effect, effect/<Module>), and the check's runner.
379
636
  const model = m, modules = { effect: E, ...Object.fromEntries(Object.entries(E).map(([k, x]) => [`effect/${k}`, x])), 'gdp-wired:effect': runner(E), ...opts.modules };
380
- return { ...fromModel(model, file, opts.domains, [], (rule, sorts) => check(code, file, model, rule, sorts, { ...opts.check, modules, ...(opts.files ? { files: opts.files } : {}), ...(opts.domains ? { given: opts.domains } : {}) })), names: namesOf(model) };
637
+ const schedules = found;
638
+ return { ...fromModel(model, file, opts.domains, [], (rule, sorts) => check(code, file, model, rule, sorts, { ...opts.check, modules, ...(opts.files ? { files: opts.files } : {}), ...(opts.domains ? { given: opts.domains } : {}) })), names: namesOf(model), ...(schedules.length ? { schedules } : {}) };
639
+ }
640
+ function modelled(code, file, entry, E, opts) {
641
+ if (!/\b(Queue|Semaphore|makeSemaphore|unsafeMakeSemaphore)\b/.test(code))
642
+ return undefined;
643
+ const s = setupOf(code, placed(file), {}, opts.files), w = rewritePrims(s, factoryOf(s, entry), x => apiOf(s, x), V4, { params: !!opts.capacityParam });
644
+ if (!w)
645
+ return undefined;
646
+ const x = extractEffect(w.code, { ...opts, capacityParam: false, file: normalize(placed(file)), entry, effect: E, perFiber: w.prims.flatMap(p => (p.kind === 'semaphore' ? [`${p.name}_held`] : [])) });
647
+ if (!x.ok || !x.rule)
648
+ return { ...x, notes: [...w.notes, ...x.notes] };
649
+ const r = x.rule;
650
+ // (a field's value: under fibers an integer is the machine's two naturals, x and x$neg)
651
+ const maps = new Set(Object.keys(x.rule.machine.maps ?? {}));
652
+ const val = (st, n) => (st[n] instanceof dsl.Int ? st[n] : `${n}$neg` in st ? new dsl.Int(st[n], st[`${n}$neg`]) : dsl.Int.of(st[n]));
653
+ const prims = w.prims.map(p => {
654
+ const f = (n) => `${p.name}_${n}`;
655
+ if (p.kind === 'queue')
656
+ return { ...p, laws: [], invariants: [r.law(p.capacity === undefined ? `${p.name} never gives more than it was given` : `${p.name} holds at most ${p.capacity} items`, st => {
657
+ const h = val(st, f('head')), t = val(st, f('tail'));
658
+ return p.capacity === undefined ? h.atMost(t) : h.atMost(t).and(t.atMost(h.plus(typeof p.capacity === 'number' ? p.capacity : val(st, p.capacity))));
659
+ })] };
660
+ const total = (st) => (typeof p.permits === 'number' ? p.permits : val(st, p.permits));
661
+ // (what the fibers hold sums to what is taken: one fiber's own, or under many fibers the sum of each's)
662
+ const held = (st) => (maps.has(f('held')) ? new dsl.Int(st[f('held')].sum(), maps.has(`${f('held')}$neg`) ? st[`${f('held')}$neg`].sum() : dsl.lit(0)) : val(st, f('held')));
663
+ // (under many fibers, the lemmas the use law rests on where each fiber gives back only what it took, withPermits':
664
+ // no fiber's own below nothing, and so not their sum)
665
+ const neg = `${f('held')}$neg`, lemmas = maps.has(neg) ? [r.law(`${p.name}: no fiber gives back more permits than it took`, st => dsl.forall(k => st[neg].at(k).eq(0))),
666
+ r.law(`${p.name}: what its fibers hold is never below nothing`, st => st[neg].sum().eq(0))] : [];
667
+ return { ...p, invariants: [r.law(`${p.name} never has more permits taken than ${typeof p.permits === 'number' ? `its ${p.permits}` : p.permits}`, st => val(st, f('taken')).atMost(total(st))), r.law(`${p.name}'s permits taken are those its fibers hold`, st => val(st, f('taken')).eq(held(st)))],
668
+ laws: [r.law(`${p.name} is never released past what was taken`, st => val(st, f('taken')).atLeast(0))], lemmas };
669
+ });
670
+ const lemmas = prims.flatMap(p => p.lemmas ?? []);
671
+ return { ...x, invariants: [...x.invariants ?? [], ...prims.flatMap(p => p.invariants)], notes: [...w.notes, ...x.notes], primitives: prims, ...(lemmas.length ? { lemmas } : {}) };
672
+ }
673
+ // The extraction with its lemmas (laws that hold where the code uses its primitives as they are meant to be, a
674
+ // semaphore's permits given back by the fiber that took them) proven first, each with the invariants and those proven
675
+ // before it: the proven ones, with what their search found, join the invariants every law is proven beside; the others
676
+ // are left out (a lemma is no claim: the laws stated are).
677
+ export function withLemmas(x, opts = {}) {
678
+ const lemmas = x.lemmas ?? [], inv = [...x.invariants ?? []], proven = [], unproven = [];
679
+ if (!x.rule)
680
+ return { x, proven, unproven };
681
+ for (const l of lemmas) {
682
+ let v;
683
+ try {
684
+ v = dsl.proveRule(x.rule, [...inv, l], { search: { ms: opts.ms ?? 30_000 } });
685
+ }
686
+ catch {
687
+ v = undefined;
688
+ }
689
+ if (v?.proven && v.checked) {
690
+ inv.push(l, ...(v.found?.laws ?? []).map(f => f.law));
691
+ proven.push(l.name);
692
+ }
693
+ else
694
+ unproven.push(l.name);
695
+ }
696
+ return { x: { ...x, invariants: inv }, proven, unproven };
697
+ }
698
+ // --- many fibers: a method that is several steps ---------------------------------------------------------------------
699
+ // A method's atomic units: the statements of its body that run an effect on the service's state (a transaction, a Ref
700
+ // operation, a helper's), each a step another fiber's may come between. A failure, a log, a sleep or a wait runs no
701
+ // such effect. A method of two or more is read as its steps: the service written again with one fiber's place in it
702
+ // (`__gdp_pc`) and what it carries from one step to the next (its arguments, its locals) in Refs of its own, read and
703
+ // checked as any service; then lift (core/system.ts) makes those Refs every fiber's at once (maps keyed by `fiber`, an
704
+ // input), the service's own Refs shared, and each request one fiber's next step.
705
+ const QUIET = new Set(['Effect.fail', 'Effect.failSync', 'Effect.die', 'Effect.dieMessage', 'Effect.void', 'Effect.sleep', 'Effect.yieldNow', 'Effect.txRetry', 'STM.fail', 'STM.die', 'STM.retry', ...[...LOGS].map(l => `Effect.${l}`)]);
706
+ const TX = /\b(TRef|TxRef|STM)\.|Effect\.tx\b/, WAITS = new Set(['Effect.txRetry', 'STM.retry']);
707
+ function fibered(code, file, entry, E, opts) {
708
+ const s = setupOf(code, placed(file), {}, opts.files), f = factoryOf(s, entry);
709
+ const failing = (y) => { const x = y.expression && strip(y.expression); return !!x && (ts.isNewExpression(x) || /^(Effect|STM)\.(fail|failSync|die|dieMessage)$/.test((ts.isCallExpression(x) ? callOf(s, x) : '') ?? '')); };
710
+ // How many effects on the state a piece of a method runs one after another, each a point another fiber's step may
711
+ // come between: a Ref or TRef operation, a transaction or a lock's body one each; an Effect.gen's or a helper's body
712
+ // counted through; a branch its larger side; a repeat several; a failure, a log, a sleep or a wait none.
713
+ const TXS = new Set(['Effect.tx', 'STM.gen', 'STM.commit']);
714
+ const units = (n) => {
715
+ if (ts.isFunctionLike(n))
716
+ return 0;
717
+ if (ts.isIfStatement(n))
718
+ return units(n.expression) + Math.max(units(n.thenStatement), n.elseStatement ? units(n.elseStatement) : 0);
719
+ if (ts.isConditionalExpression(n))
720
+ return units(n.condition) + Math.max(units(n.whenTrue), units(n.whenFalse));
721
+ // (a yield inside the effect's arguments runs before it: its own points first)
722
+ if (ts.isYieldExpression(n)) {
723
+ let inner = 0;
724
+ if (n.expression)
725
+ ts.forEachChild(n.expression, c => { inner += units(c); });
726
+ return inner + (n.expression ? ran(n.expression) : 0);
727
+ }
728
+ let t = 0;
729
+ ts.forEachChild(n, c => { t += units(c); });
730
+ return t;
731
+ };
732
+ const helper = (x) => { const d = ts.isIdentifier(x) ? s.checker.getSymbolAtLocation(x)?.valueDeclaration : undefined; return d && ts.isVariableDeclaration(d) && d.initializer ? fnOf(s, d.initializer) ?? genOf(s, d.initializer) : undefined; };
733
+ const bodyUnits = (fn) => (!fn.body ? 0 : ts.isBlock(fn.body) ? units(fn.body) : ran(fn.body));
734
+ const ran = (e0) => {
735
+ const e = strip(e0);
736
+ if (ts.isNewExpression(e))
737
+ return 0;
738
+ const api = (ts.isCallExpression(e) ? callOf(s, e) : apiOf(s, e)) ?? '';
739
+ if (QUIET.has(api))
740
+ return 0;
741
+ if (TXS.has(api))
742
+ return 1;
743
+ if (ts.isCallExpression(e)) {
744
+ const callee = strip(e.expression);
745
+ if (ts.isPropertyAccessExpression(callee) && memberName(callee.name) === 'pipe' && !api) {
746
+ const fs = e.arguments.map(a => callOf(s, a) ?? apiOf(s, a) ?? ''), head = ran(callee.expression);
747
+ return fs.includes('STM.commit') ? 1 : fs.includes('Effect.repeat') && head ? 2 : head;
748
+ }
749
+ // (a lock's body: one at a time)
750
+ if (ts.isCallExpression(callee) && ts.isPropertyAccessExpression(strip(callee.expression)) && /^withPermits?$/.test(memberName(strip(callee.expression).name)))
751
+ return e.arguments[0] && ran(e.arguments[0]) ? 1 : 0;
752
+ if (api === 'Effect.gen') {
753
+ const g = genOf(s, e);
754
+ return g ? bodyUnits(g) : 1;
755
+ }
756
+ if (api === 'Effect.retry')
757
+ return ran(e.arguments[0]);
758
+ if (api === 'Effect.repeat')
759
+ return ran(e.arguments[0]) ? 2 : 0;
760
+ const h = helper(callee);
761
+ if (h)
762
+ return bodyUnits(h);
763
+ }
764
+ if (ts.isIdentifier(e)) {
765
+ const d = s.checker.getSymbolAtLocation(e)?.valueDeclaration;
766
+ if (d && ts.isVariableDeclaration(d) && d.initializer && !fnOf(s, d.initializer))
767
+ return ran(d.initializer);
768
+ }
769
+ return 1;
770
+ };
771
+ const methods = [], several = [];
772
+ for (const pr of f.obj.properties) {
773
+ const name = pr.name ? memberName(pr.name) : '';
774
+ let init = ts.isPropertyAssignment(pr) ? pr.initializer : ts.isShorthandPropertyAssignment(pr) ? pr.name : undefined;
775
+ if (init && ts.isIdentifier(strip(init))) {
776
+ const d = (ts.isShorthandPropertyAssignment(pr) ? s.checker.getShorthandAssignmentValueSymbol(pr) : s.checker.getSymbolAtLocation(strip(init)))?.valueDeclaration;
777
+ init = d && ts.isVariableDeclaration(d) ? d.initializer : init;
778
+ }
779
+ const fn = init && fnOf(s, init);
780
+ if (!fn?.body)
781
+ continue;
782
+ if (!ts.isFunctionExpression(fn) || !fn.asteriskToken || !ts.isBlock(fn.body)) {
783
+ const n = bodyUnits(fn);
784
+ if (n >= 2)
785
+ several.push([name, fn, n]);
786
+ continue;
787
+ }
788
+ const stmts = fn.body.statements, per = stmts.map(units), units0 = stmts.flatMap((_, i) => (per[i] > 0 ? [i] : []));
789
+ if (per.reduce((a, b) => a + b, 0) >= 2)
790
+ for (const [i, n] of per.entries())
791
+ if (n >= 2)
792
+ several.push([name, stmts[i], n]);
793
+ methods.push({ name, fn, at: init, units: units0, stmts });
794
+ }
795
+ const split = methods.filter(mt => mt.units.length >= 2 || several.some(([n]) => n === mt.name));
796
+ if ((!split.length && !several.length) || (opts.fibers === undefined && !TX.test(code))) {
797
+ if (split.length || several.length)
798
+ s.notes.add(`${[...new Set([...split.map(mt => mt.name), ...several.map(([n]) => n)])].join(', ')} run several Ref operations one after another: each method is read as one step, which holds where calls don't interleave (fibers: true reads them as interleaving steps)`);
799
+ return undefined;
800
+ }
801
+ // (each step of a method read for many fibers is one statement of its body, with one effect on the state at most)
802
+ for (const [name, at, n] of several)
803
+ refuse(at, `${name}: ${text(at)} runs ${n} effects on the state one after another${ts.isStatement(at) ? ' in one statement' : ''}, and another fiber's step may come between them: write the method as Effect.fn('${name}')(function* ...) with each in a statement of its own (each a step), or in one transaction`);
804
+ // Each split method's segments, the names each carries on, and the service written again.
805
+ if (/\b__gdp_/.test(code))
806
+ return refuse(s.sf.statements[0] ?? s.sf, 'a name of the code starts with __gdp_ (the names the fibers\' places and carried values are given)');
807
+ const edits = [], decls = [], resumes = [], made = new Set(['__gdp_pc']);
808
+ const tyOf = (n) => { const t = s.checker.getTypeAtLocation(n), str = s.checker.typeToString(s.checker.getBaseTypeOfLiteralType(t)); return t.flags & ts.TypeFlags.BooleanLike ? ['boolean', 'false'] : t.flags & ts.TypeFlags.NumberLike ? ['number', '0'] : t.isUnion() && t.types.every(u => u.isStringLiteral()) ? [s.checker.typeToString(t), JSON.stringify(t.types[0].value)] : t.flags & ts.TypeFlags.StringLike ? ['string', "''"] : refuse(n, `${text(n)} is carried from one step to the next, and is a ${str} (a number, a boolean or a string is carried)`); };
809
+ split.forEach((mt, mi) => {
810
+ const base = (mi + 1) * 100, K = mt.units.length, segs = [];
811
+ mt.units.forEach((u, k) => segs.push([...mt.stmts.slice(k === 0 ? 0 : mt.units[k - 1] + 1, u + 1), ...(k === K - 1 ? mt.stmts.slice(u + 1) : [])]));
812
+ for (const [k, seg] of segs.entries())
813
+ for (const st of seg) {
814
+ // (a later step's failing transaction: the call would end with the earlier steps' writes kept and this one's rolled
815
+ // back, which a refusal of this step leaves the fiber waiting on instead)
816
+ if (k > 0) {
817
+ const go = (x, inner) => { if (ts.isYieldExpression(x) && inner && failing(x))
818
+ refuse(x, `${mt.name}: a transaction that fails in a step after the first (the call ends there, its earlier steps' writes kept): fail in the first step, or wait (STM.check, Effect.txRetry) instead`); ts.forEachChild(x, c => go(c, inner || ts.isFunctionLike(x))); };
819
+ go(st, false);
820
+ }
821
+ }
822
+ // What a later step reads of an earlier one: the arguments and the locals declared at the top of a segment.
823
+ const carried = new Map();
824
+ for (const p of mt.fn.parameters)
825
+ if (ts.isIdentifier(p.name))
826
+ carried.set(p, p.name.text);
827
+ segs.forEach(seg => seg.forEach(st => { if (ts.isVariableStatement(st))
828
+ for (const d of st.declarationList.declarations)
829
+ carried.set(d, ts.isIdentifier(d.name) ? d.name.text : refuse(d, `${mt.name}: ${text(d)} (a name is carried, not a pattern)`)); }));
830
+ const usedIn = (seg) => { const u = new Set(); const go = (x) => { if (ts.isIdentifier(x)) {
831
+ const d = s.checker.getSymbolAtLocation(x)?.valueDeclaration;
832
+ if (d && carried.has(d))
833
+ u.add(d);
834
+ } ts.forEachChild(x, go); }; seg.forEach(go); return u; };
835
+ const later = segs.map((_, k) => { const u = new Set(); segs.slice(k + 1).forEach(sg => usedIn(sg).forEach(d => u.add(d))); return u; });
836
+ const ref = (d) => `__gdp_${mt.name}_${carried.get(d)}`;
837
+ const kept = new Set();
838
+ later.forEach(u => u.forEach(d => kept.add(d)));
839
+ for (const d of kept) {
840
+ const [t, zero] = tyOf(d);
841
+ decls.push(`const ${ref(d)} = yield* __gdp_Ref.make<${t}>(${zero})`);
842
+ made.add(ref(d));
843
+ }
844
+ // (where each carried name is defined: a parameter, or the segment that declares it)
845
+ const defined = (d, k) => (ts.isParameter(d) ? k === 0 : segs[k].some(st => st.pos <= d.pos && d.end <= st.end));
846
+ const body = (seg, k) => {
847
+ // (what it reads of earlier steps loaded first; what a later step reads stored last: defined here, or loaded here
848
+ // and perhaps assigned again)
849
+ const used = usedIn(seg);
850
+ const loads = k === 0 ? '' : [...used].filter(d => !defined(d, k)).map(d => `let ${carried.get(d)} = yield* __gdp_Ref.get(${ref(d)})\n`).join('');
851
+ const stores = [...later[k]].filter(d => defined(d, k) || used.has(d) || ts.isParameter(d) && k === 0).map(d => `yield* __gdp_Ref.set(${ref(d)}, ${carried.get(d)})\n`).join('');
852
+ // (a return ends the call, its value left out (under fibers a step's result is no part of the rule): what it
853
+ // returns is run, then the fiber goes back to where it starts. In a later step a failure outside a transaction ends
854
+ // the call too, as a return (the earlier steps' writes kept, as Effect keeps them); a wait, or a failure in the
855
+ // first step, leaves the fiber where it is)
856
+ const textOf = (st) => {
857
+ let t = st.getText();
858
+ const rs = [];
859
+ const go = (x) => { if (ts.isReturnStatement(x) || k > 0 && ts.isExpressionStatement(x) && ts.isYieldExpression(strip(x.expression)) && failing(strip(x.expression)))
860
+ rs.push(x); if (!ts.isFunctionLike(x))
861
+ ts.forEachChild(x, go); };
862
+ go(st);
863
+ for (const r of rs.reverse()) {
864
+ const y = ts.isReturnStatement(r) ? r.expression && strip(r.expression) : strip(r.expression), fails = !!y && ts.isYieldExpression(y) && failing(y);
865
+ // (a wait leaves the fiber where it is; so does a failure in the first step, which ends the call with nothing done)
866
+ if (y && ts.isYieldExpression(y) && (WAITS.has(apiOf(s, strip(y.expression)) ?? '') || fails && k === 0))
867
+ continue;
868
+ const run = fails || !y ? '' : `${ts.isYieldExpression(y) ? '' : 'void '}(${y.getText()}); `;
869
+ t = t.slice(0, r.getStart() - st.getStart()) + `{ ${run}${k > 0 ? 'yield* __gdp_Ref.set(__gdp_pc, 0); ' : ''}return }` + t.slice(r.end - st.getStart());
870
+ }
871
+ return t;
872
+ };
873
+ return `${loads}${seg.map(textOf).join('\n')}\n${stores}yield* __gdp_Ref.set(__gdp_pc, ${k === K - 1 ? 0 : base + k + 2})`;
874
+ };
875
+ resumes.push(...segs.slice(1).map((seg, j) => `if (__gdp_p === ${base + j + 2}) {\n${body(seg, j + 1)}\n}`));
876
+ const params = mt.fn.parameters.map(p => p.getText()).join(', ');
877
+ edits.push([mt.fn.getStart(), mt.fn.end, `function* (${params}) {\nconst __gdp_p = yield* __gdp_Ref.get(__gdp_pc)\nif (__gdp_p !== 0) return yield* __gdp_resume()\n${body(segs[0], 0)}\n}`]);
878
+ });
879
+ const ret = f.fn.body.statements.at(-1);
880
+ edits.push([ret.getStart(), ret.getStart(), `const __gdp_pc = yield* __gdp_Ref.make<number>(0)\n${decls.join('\n')}\nconst __gdp_resume = __gdp_Effect.fn('__gdp_resume')(function* () {\nconst __gdp_p = yield* __gdp_Ref.get(__gdp_pc)\n${resumes.join(' else ')}\n})\n`]);
881
+ let out = code;
882
+ for (const [a, b, t] of edits.sort((x, y) => y[0] - x[0]))
883
+ out = out.slice(0, a) + t + out.slice(b);
884
+ out = `import {Effect as __gdp_Effect, Ref as __gdp_Ref} from 'effect'\n${out}`;
885
+ // One fiber: the service written again, read and checked as any.
886
+ // (by its absolute path, `..` resolved: the checker reads the code written again there, not the file on disk)
887
+ const one = extractEffect(out, { ...opts, file: normalize(placed(file)), entry, effect: E, fibers: false });
888
+ if (!one.ok || !one.rule)
889
+ return { ...one, notes: [`read as one fiber's steps (${split.map(mt => `${mt.name}: ${mt.units.length}`).join(', ')}), the service written again:`, out, ...one.notes] };
890
+ const m0 = one.rule.machine, model = one.model;
891
+ // (an integer is two naturals, x and x$neg)
892
+ const local = (n0) => { const n = n0.replace(/\$neg$/, ''); return made.has(n) || !!opts.perFiber?.includes(n) || model.outputs.some(o => n === o || n.startsWith(`${o}_`)) || n === 'failed'; };
893
+ const shared = Object.keys(m0.state).filter(n => !local(n));
894
+ if (m0.inputs.includes('fiber'))
895
+ return { ok: false, refusals: [{ where: file, what: 'a method takes an argument named fiber (the name the fibers are told apart by)' }], notes: [] };
896
+ const lifted = lift(m0, 'fiber', shared);
897
+ const parts = one.rule.parts;
898
+ // (the kinds of the requests' choices kept; an integer is its two naturals, x and x$neg, as the machine has it)
899
+ const named = new Set([...lifted.params, ...lifted.inputs]), whole = ([n]) => named.has(n) && !named.has(`${n}$neg`);
900
+ // (and the shared integers' kinds: a law reads an integer of the service's as it does where the rule is one fiber's)
901
+ const one2 = one.rule;
902
+ const ints = [...one2.kindsOfState().filter(([n]) => shared.includes(n) && shared.includes(`${n}$neg`)), ...one2.kindsOfCells().filter(([n, k]) => k.vars(n).every(p => !local(p)))];
903
+ const rule = asRule({ ...lifted, name: `${m0.name}, every fiber` }, Object.fromEntries([...parts.params, ...parts.inputs].filter(whole).concat(ints)));
904
+ const names = (one.names ?? []).filter(n => !(n.role === 'state' && local(n.rule)) && n.role !== 'result' && !made.has(n.code));
905
+ const inv = (one.invariants ?? []).filter(l => ![...JSON.stringify(l.holds).matchAll(/"name":"([^"]*)"/g)].some(m => local(m[1])));
906
+ const steps = split.map((mt, mi) => ({ name: mt.name, steps: mt.units.length, base: (mi + 1) * 100 }));
907
+ return { ...one, rule, names: [...names, { code: 'fiber', rule: 'fiber', role: 'input' }], invariants: inv, fibers: steps, replay: undefined,
908
+ notes: [`calls from many fibers at once: ${split.map(mt => `${mt.name} is ${mt.units.length} steps`).join(', ')} (each transaction or Ref operation one), the fibers interleaving them: the rule is every fiber's (lift: each fiber's place and what it carries a map keyed by the input fiber, the service's Refs (${shared.filter(n => !n.endsWith('$neg')).join(', ')}) shared); each other method is one step. A request is one fiber's next step: a fiber in the middle of a call takes its next step whatever method the request names. A failure in a later step ends the call as a return does. A law reads the service's Refs`, ...one.notes],
909
+ source: out };
910
+ }
911
+ // A run of every fiber's rule as what each fiber does: starts a call (with its arguments), or takes the next step of the
912
+ // call it is in.
913
+ export function fiberRun(x, run) {
914
+ const fibers = x.fibers ?? [], r = x.rule;
915
+ const go = interpret(r.machine), ps = r.encodeParams(run.params), method = new Map(r.parts.inputs).get('method');
916
+ let st = go.init(ps);
917
+ return run.trace.map(q => {
918
+ const f = Number(q.fiber), pc = st.maps.__gdp_pc?.get(f) ?? 0, m = method ? method.decode('method', q) : x.model?.events[0]?.call ?? 'step';
919
+ st = go.step(ps, st, q);
920
+ if (pc === 0) {
921
+ const sp = fibers.find(s2 => s2.name === m), args = (x.names ?? []).filter(n => n.role === 'input' && n.method === m && n.rule in q).map(n => `${n.code.split('.').pop()} = ${String(q[n.rule])}`);
922
+ return `fiber ${f}: ${m}(${args.join(', ')})${sp ? `, its step 1 of ${sp.steps}` : ''}`;
923
+ }
924
+ const sp = fibers.find(s2 => pc > s2.base && pc <= s2.base + s2.steps);
925
+ return `fiber ${f}: ${sp.name}, its step ${pc - sp.base} of ${sp.steps}`;
926
+ });
927
+ }
928
+ const isSchedule = (s, e) => {
929
+ e = strip(e);
930
+ if (ts.isCallExpression(e) && ts.isPropertyAccessExpression(e.expression) && memberName(e.expression.name) === 'pipe' && !apiOf(s, e.expression))
931
+ return isSchedule(s, e.expression.expression);
932
+ return (ts.isCallExpression(e) ? apiOf(s, e.expression) : apiOf(s, e))?.startsWith('Schedule.') ?? false;
933
+ };
934
+ function scheduleEntry(code, file, opts) {
935
+ if (!/\bSchedule\b/.test(code))
936
+ return undefined;
937
+ const s = setupOf(code, placed(file), {}, opts.files), found = [];
938
+ for (const st of s.sf.statements) {
939
+ const decls = ts.isVariableStatement(st) ? st.declarationList.declarations.filter(d => ts.isIdentifier(d.name) && d.initializer).map(d => [d.name.text, d.initializer])
940
+ : ts.isFunctionDeclaration(st) && st.name ? [[st.name.text, st]] : [];
941
+ for (const [name, init] of decls) {
942
+ if (opts.entry && opts.entry !== name)
943
+ continue;
944
+ const f = ts.isFunctionDeclaration(init) ? init : ts.isArrowFunction(strip(init)) || ts.isFunctionExpression(strip(init)) ? strip(init) : undefined;
945
+ const body = f ? lastReturn(f.body) : init;
946
+ if (!body || !isSchedule(s, body) || (f && ts.isBlock(f.body) && f.body.statements.length > 1))
947
+ continue;
948
+ found.push({ name, expr: body, params: (f?.parameters ?? []).map(p => (ts.isIdentifier(p.name) ? p.name.text : refuse(p, `${text(p)}: a parameter other than a name`))), s });
949
+ }
950
+ }
951
+ if (opts.entry)
952
+ return found[0];
953
+ // (a file with a service reads the service; else its one schedule, the exported ones first)
954
+ if (found.length === 0)
955
+ return undefined;
956
+ try {
957
+ serviceOf(code, file, opts);
958
+ return undefined;
959
+ }
960
+ catch (e) {
961
+ if (!(e instanceof Refusal))
962
+ throw e;
963
+ }
964
+ const exported = found.filter(f => new RegExp(`export\\s+(?:const|function)\\s+${f.name}\\b`).test(code));
965
+ const pick = exported.length ? exported : found;
966
+ if (pick.length > 1)
967
+ throw new Refusal(file, `several schedules in the file (${pick.map(f => f.name).join(', ')}): name one (entry)`);
968
+ return pick[0];
969
+ }
970
+ // The schedule read into its rule, and checked by stepping the file's own schedule on Effect beside it.
971
+ function fromScheduleEntry(code, file, e, E, opts) {
972
+ const t0 = Date.now(), v4 = 'TxRef' in E, s = e.s;
973
+ const params = new Map();
974
+ const fnDecl = (() => { let n = e.expr; while (n && !ts.isFunctionLike(n))
975
+ n = n.parent; return n; })();
976
+ for (const p of fnDecl?.parameters ?? [])
977
+ if (ts.isIdentifier(p.name))
978
+ params.set(p, p.name.text);
979
+ const P = new Parts();
980
+ for (const n of e.params)
981
+ P.params.set(n, dsl.nat);
982
+ let sr;
983
+ try {
984
+ sr = scheduleRule(readSchedule(e.expr, { api: x => apiOf(s, x), checker: s.checker, v4, params, sf: s.sf }, P).frag, P, e.name, v4);
985
+ }
986
+ catch (x) {
987
+ if (x instanceof Refusal)
988
+ return { ok: false, refusals: [{ where: x.where, what: x.what }], notes: [] };
989
+ throw x;
990
+ }
991
+ const notes = [`${e.name} is an Effect ${v4 ? '4' : '3'} Schedule: each step is one of its decisions (go on after a delay, or stop), at the time the attempt before it ended; attempt, retries, delay, elapsed and done are the rule's own${e.params.length ? `; its parameters (${e.params.join(', ')}) are the rule's params, naturals` : ''}`, ...sr.notes];
992
+ const modules = { effect: E, ...Object.fromEntries(Object.entries(E).map(([k, x]) => [`effect/${k}`, x])), ...opts.modules };
993
+ const box = sandbox(code, file, [e.name], modules, undefined, opts.files);
994
+ const value = box.get(e.name), make = (p) => (typeof value === 'function' ? value(...e.params.map(n => p[n])) : value);
995
+ const runs = opts.check?.runs ?? 60, c = scheduleConforms(sr, make, E, { runs, depth: 14 });
996
+ const evidence = { runs, requests: c.checked, fromStates: 0, probes: { conditions: 0, witnesses: 0, steps: 0 }, refusedBoth: 0, outside: 0, edge: 0, compiledAgreed: c.checked, coverage: { arms: 0, hit: 0, missed: [] }, ms: Date.now() - t0, ...(c.failure ? { mismatch: c.failure } : {}) };
997
+ const source = `// ${e.name}: ${e.expr.getText().replace(/\s+/g, ' ')}\n${sr.rule.machine.name}: state ${Object.keys(sr.rule.machine.state).join(', ')}; inputs ${sr.rule.machine.inputs.join(', ')}${sr.rule.machine.params.length ? `; params ${sr.rule.machine.params.join(', ')}` : ''}`;
998
+ if (c.failure)
999
+ return { ok: false, rule: sr.rule, source, refusals: [{ where: file, what: `the rule and Effect's own schedule part: ${c.failure}` }], notes, names: sr.names, evidence };
1000
+ return { ok: true, rule: sr.rule, source, refusals: [], notes, names: sr.names, evidence, schedule: sr, replay: run => replaySchedule(sr, make(run.params), E, run) };
1001
+ }
1002
+ // A schedule written as source (an expression over Schedule and Duration, with `params` its free names) read into its
1003
+ // rule and checked against the schedule Effect makes of it: fromSchedule('Schedule.exponential("10 millis").pipe(Schedule.upTo({times: 5}))', {effect}).
1004
+ export function fromSchedule(source, opts) {
1005
+ const ps = opts.params ?? [], name = opts.name ?? 'schedule';
1006
+ const code = `import {Duration, Effect, Schedule} from 'effect'\nexport const ${name} = (${ps.map(p => `${p}: number`).join(', ')}) => ${source}\n`;
1007
+ return extractEffect(code, { file: 'schedule.ts', entry: name, effect: opts.effect, check: { runs: opts.runs ?? 60 } });
381
1008
  }
382
1009
  // The service a file has: of its declarations (the exported ones first), those whose make effect reads, one make effect
383
1010
  // however many names reach it (make, and a Layer of it).