gdp-wired 0.35.0 → 0.36.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.
@@ -86,6 +86,13 @@ export class Stepper {
86
86
  arms = new Set();
87
87
  hints = new WeakMap();
88
88
  lazy = new Map();
89
+ // The lists the request carries (maps by place), those a step reads, and the loops over lists read as folds.
90
+ seqs = [];
91
+ used = new Set();
92
+ folds = [];
93
+ // (inside a fold's pass: the tries outside it, hidden, and how deep)
94
+ hidden = 0;
95
+ inFold = 0;
89
96
  initHeap = new Map();
90
97
  storeMaps = new Map();
91
98
  // The least keys the step reads (an ordered collection's first or last item, its min or max by a key), each once.
@@ -108,7 +115,7 @@ export class Stepper {
108
115
  this.inf = inf;
109
116
  }
110
117
  rec(name, at) { return this.mod.recs[name] ?? refuse(at, `${name}: a type the reader didn't read`); }
111
- newVar(name, sort, role, note) {
118
+ newVar(name, sort, role, note, own = true) {
112
119
  let n = name.replace(/^[_@]+/, '').replace(/\?/g, '_p').replace(/!/g, '').replace(/[^\w$]/g, '_') || 'x';
113
120
  if (/^\d/.test(n))
114
121
  n = `_${n}`;
@@ -118,6 +125,11 @@ export class Stepper {
118
125
  while (this.vars.has(n) || RESERVED.has(n))
119
126
  n = `${n}_`;
120
127
  const v = { name: n, sort, role, ...(note ? { note } : {}) };
128
+ // (not own: a name the rule's builders declare, a carried list's, kept from the others)
129
+ if (!own) {
130
+ this.vars.set(n, v);
131
+ return v;
132
+ }
121
133
  this.vars.set(n, v);
122
134
  if (role === 'input')
123
135
  this.inputs.push(v);
@@ -167,6 +179,18 @@ export class Stepper {
167
179
  }
168
180
  if (t.k === 'none')
169
181
  return [{ t: 'none' }, { k: 'dflt' }];
182
+ // A list the request carries, of any length: a map by place (as a list of the state is), each place below its
183
+ // length holding an item, of the scalar fields of its records (or its one value).
184
+ if (t.k === 'list' && role === 'input' && this.mod.lists && (this.scalar(t.of) || t.of.k === 'rec')) {
185
+ const n = this.newVar(name, { k: 'num' }, 'input', undefined, false).name, id = `in:${n}`, sc = this.scalar(t.of);
186
+ this.newVar(`${n}_len`, { k: 'num' }, 'input', `the length of ${name}`, false);
187
+ const fs = sc ? [{ name: 'value', t: t.of }] : this.rec(t.of.name, at).fields.filter(x => this.scalar(x.t));
188
+ const decl = { name: n, key: 'num', fields: fs.map(x => ({ name: x.name, sort: this.scalar(x.t), role: 'input' })), scalar: !!sc, js: 'Map', carried: true };
189
+ this.seqs.push(decl);
190
+ p.heap.set(id, { k: 'map', decl, val: t.of, origin: 'input' });
191
+ const arg = (x) => ({ k: 'in', name: x.name, ...(x.t.k === 'float' ? { float: true } : {}) });
192
+ return [{ t: 'ref', id }, { k: 'list', name: n, item: sc ? arg(fs[0]) : { k: 'rec', cls: t.of.name, f: fs.map(x => [x.name, arg(x)]) } }];
193
+ }
170
194
  if (t.k === 'rec' && role === 'input') {
171
195
  // An object the caller gives: its fields read are inputs, each made where it is first read.
172
196
  const id = `in:${name}:${this.fresh++}`, args = [];
@@ -217,15 +241,22 @@ export class Stepper {
217
241
  return [{ t: 'num', e: I.nvar(this.now.name) }, { ...p, called: [...p.called, '$now'] }];
218
242
  }
219
243
  // --- paths ----------------------------------------------------------------------------------------------------------
220
- cond(p) { return I.and(...p.pc); }
244
+ // (inside a try, every path is also outside the raises its handlers caught before it: no path goes on past a raise)
245
+ cond(p) { return this.tries.length ? I.and(...p.pc, ...this.tries.flatMap(t => t.ws.map(I.not))) : I.and(...p.pc); }
221
246
  // (a negated disjunction as its negated parts, so a later test of one of them is decided)
222
247
  assume(p, c) { if (this.mod.split === false)
223
248
  return c.op === 'const' && c.v ? p : { ...p, pc: [...p.pc, c] }; const cs = c.op === 'not' && c.x.op === 'or' ? c.x.xs.map(I.not) : c.op === 'and' ? c.xs : [c]; const kept = cs.filter(x => !(x.op === 'const' && x.v)); return kept.length ? { ...p, pc: [...p.pc, ...kept] } : p; }
224
249
  // A failure of the code where c holds on this path (an exception raised): the step's refusal, or its result.
225
- fail(p, c, at, what) {
250
+ // (kind: the class raised and its bases, where it isn't the executor's own named in `what`, "(a KeyError)")
251
+ fail(p, c, at, what, kind = this.kindOf(what, at)) {
226
252
  const w = I.and(this.cond(p), c);
227
253
  if (w.op === 'const' && !w.v)
228
254
  return;
255
+ if (this.tries.length) {
256
+ const h = this.catcher(kind, at);
257
+ if (h)
258
+ return this.raise(p, c, w, h, kind, at);
259
+ }
229
260
  if (this.init) {
230
261
  this.fails.push(w);
231
262
  return;
@@ -237,7 +268,7 @@ export class Stepper {
237
268
  if (this.opts.failures === 'kept' && this.opts.onError !== 'discard') {
238
269
  if (crash && this.changed(p))
239
270
  refuse(at, `${what} after the state is written: a crash, after which the state is as it was (onError: 'discard' says so of every failure)`);
240
- this.failPaths.push(this.assume(p, c));
271
+ this.failPaths.push(this.assume(p, this.tries.length ? w : c));
241
272
  this.fails.push(w);
242
273
  this.notes.add(`${this.method}: ${what} (${at.p}) is the step's failure, kept as its result (with what the step wrote before it)`);
243
274
  return;
@@ -248,6 +279,315 @@ export class Stepper {
248
279
  this.notes.add(`${this.method}: ${what} (${at.p}) is ${this.opts.failures === 'kept' ? 'the step\'s failure, kept as its result' : 'the step\'s refusal'}`);
249
280
  }
250
281
  // A failure after the step wrote the state: refused, but where the caller drops what a failed call wrote.
282
+ // --- exceptions caught ---------------------------------------------------------------------------------------------
283
+ // The tries the path is in (innermost last): each one's handlers, the paths raised to each (with the raise's kind),
284
+ // and the conditions they were raised under; `handling`, the kinds each handler being run caught (a bare re-raise's).
285
+ tries = [];
286
+ handling = [];
287
+ // (the tries around each context manager of other code entered, taken as transparent)
288
+ cms = [];
289
+ kindOf(what, at) {
290
+ if (at.crash || /\(a panic\)$/.test(what))
291
+ return null;
292
+ const m = /\(an? ([A-Z]\w*)\)$/.exec(what), b = m && this.mod.kinds?.[m[1]];
293
+ return b ? { mro: b } : undefined;
294
+ }
295
+ // The handler a raise of this kind goes to, the innermost try's first that names one of its classes (or any), or none
296
+ // (the step's failure); one that may or may not (a kind of bases unknown, or none named) is refused, unless `loose`.
297
+ catcher(k, at, loose = false) {
298
+ if (k === null)
299
+ return undefined;
300
+ for (let j = this.tries.length - 1; j >= 0; j--) {
301
+ for (const [i, h] of this.tries[j].hs.entries()) {
302
+ if (h.any || (k && h.names.some(n => k.mro.includes(n))))
303
+ return [this.tries[j], i];
304
+ if ((!k || k.open) && !loose)
305
+ refuse(at, `${k ? `a raise of ${k.mro[0]}, whose bases the reader doesn't know` : 'a failure the reader names no class for'}, inside a try whose handler names ${h.names.join(', ')}`);
306
+ }
307
+ }
308
+ return undefined;
309
+ }
310
+ // A raise (where c holds; w on this path) caught: its path goes to the handler, and no path of the try goes on past it.
311
+ // (through a context manager of other code taken as transparent, which may suppress it: refused)
312
+ raise(p, c, w, [t, i], k, at) {
313
+ if (this.cms.some(b => this.tries.indexOf(t) < b))
314
+ refuse(at, 'a raise through a context manager of other code (which may suppress it) to a handler around it');
315
+ t.to.push([{ ...this.assume(p, c), pc: [...p.pc, ...this.tries.flatMap(x => x.ws.map(I.not)), c] }, i, k]);
316
+ t.ws.push(w);
317
+ }
318
+ tryStmt(s, p) {
319
+ const hs = s.handlers, fin = s.fin ?? [], t = { hs, to: [], ws: [] }, f0 = this.fails.length, outer = this.tries.map(x => x.ws.length);
320
+ this.tries.push(t);
321
+ let body;
322
+ try {
323
+ body = this.block(s.body, p);
324
+ }
325
+ finally {
326
+ this.tries.pop();
327
+ }
328
+ // (every way out of the body is past the raises its handlers caught)
329
+ const out = (q) => (t.ws.length ? this.assume(q, I.not(I.or(...t.ws))) : q);
330
+ const rets = body.rets.map(([q, v]) => [out(q), v]), brk = (body.brk ?? []).map(out), lives = [];
331
+ const add = (f) => { rets.push(...f.rets); brk.push(...(f.brk ?? [])); if (f.live)
332
+ lives.push(f.live); };
333
+ for (const [i, h] of hs.entries()) {
334
+ const to = t.to.filter(x => x[1] === i);
335
+ if (!to.length)
336
+ continue;
337
+ this.arm(h.body);
338
+ const q = this.joinSome(to.map(x => x[0]), s);
339
+ this.handling.push(to.map(x => x[2]));
340
+ try {
341
+ add(this.block(h.body, h.as ? { ...q, locals: new Map(q.locals).set(h.as, { t: 'opaque', why: `${h.as}: the exception caught` }) } : q));
342
+ }
343
+ finally {
344
+ this.handling.pop();
345
+ }
346
+ }
347
+ if (body.live)
348
+ add(this.block(s.els ?? [], out(body.live)));
349
+ let live = this.join(lives, s);
350
+ if (fin.length) {
351
+ // (finally on every way out: run where the try ends and on each return; a failure's way out through it is refused)
352
+ if (deep(fin, o => o.s === 'ret' || o.s === 'fail' || o.s === 'break' || o.s === 'try'))
353
+ refuse(s, 'a finally that returns, raises or breaks');
354
+ // (a raise an outer handler catches, from the body or a handler, goes out through it too)
355
+ const past = this.tries.some((x, j) => x.ws.length > outer[j]);
356
+ if (this.fails.length > f0 || brk.length || past)
357
+ refuse(s, `finally on ${brk.length ? 'a break' : past ? 'a raise' : 'a failure'}'s way out of its try`);
358
+ const fl = (q) => { const f = this.block(fin, q); return f.live; };
359
+ if (live)
360
+ live = fl(live);
361
+ for (const r of rets)
362
+ r[0] = fl(r[0]) ?? r[0];
363
+ }
364
+ return { ...(live ? { live } : {}), rets, ...(brk.length ? { brk } : {}) };
365
+ }
366
+ // --- loops over a list the request carries, read as folds -----------------------------------------------------------
367
+ // The body runs once, at a pass i$: the item there (its fields cells of the list's carried maps), and each local the
368
+ // body sets that is set before it a running value (a cell of the loop's own list, at i$). Its step is what the pass
369
+ // makes of them: each running value at i$ + 1, and whether the pass ended the loop (a return, a break, a failure or a
370
+ // refusal of the step), with what it returned. Every request is assumed to carry the running values its items make
371
+ // (Model's folds: the start at 0, the step at every i$ below the length), so after the loop each one is its cell at
372
+ // the length: exact for every length, no pass unrolled. A pass that writes the state, reads an answer (one a pass) or
373
+ // raises out of the loop to a try around it is refused.
374
+ // A list a loop may run over: one the request carries (every place below its length held) or one of the state (its
375
+ // places up to its last, each where it holds an item: its least key's, read in the state before the step).
376
+ // (carried: only one the request carries, whose length is an input: its len() and its truth)
377
+ listOf(v, p, at, carried = false) {
378
+ const o = v.t === 'ref' ? p.heap.get(v.id) : undefined;
379
+ if (o?.k !== 'map' || !(o.decl.carried || (!carried && o.decl.ordered && o.origin === 'state')))
380
+ return undefined;
381
+ this.used.add(o.decl.name);
382
+ if (o.decl.carried)
383
+ return { id: v.id, o, len: I.nvar(`${o.decl.name}_len`), held: () => I.T };
384
+ const last = this.least(o, at, k => this.baseCell(o.decl, k).has, k => [{ e: k.e, desc: true }]);
385
+ return { id: v.id, o, len: I.nite(last.some, I.add(last.key, I.num(1)), I.num(0)), held: k => this.baseCell(o.decl, k).has };
386
+ }
387
+ forStmt(s, p) {
388
+ const why = (w) => refuse(s, `a loop over ${s.over.text ?? 'a value'}: ${w} (the subset reads a loop over a list the request carries, as a fold)`);
389
+ let ov, q0;
390
+ try {
391
+ [ov, q0] = this.ev(s.over, p);
392
+ }
393
+ catch (e) {
394
+ if (e instanceof Refusal) {
395
+ try {
396
+ why(`${e.where}: ${e.what}`);
397
+ }
398
+ catch (r) {
399
+ r.frames = e.frames;
400
+ throw r;
401
+ }
402
+ }
403
+ throw e;
404
+ }
405
+ const ls = this.listOf(ov, q0, s.over) ?? why(ov.t === 'opaque' ? ov.why : `a ${ov.t}`);
406
+ if (s.els?.length)
407
+ return refuse(s, 'a loop\'s else');
408
+ if (this.inFold)
409
+ return refuse(s, 'a loop inside a loop\'s pass (one fold at a time)');
410
+ const d = ls.o.decl, run = this.newVar(`${d.name}$${this.folds.length}`, { k: 'num' }, 'input', undefined, false).name, i = I.nvar(PASS), ik = { op: 'num', e: i };
411
+ const own = assigned(s.body), tv = s.to;
412
+ if (deep(tv, o => o.e === 'var' && q0.locals.has(String(o.n))))
413
+ return refuse(s, 'a loop whose variable is a local set before it (after the loop it would hold the last item)');
414
+ // The running values: the locals the body sets that are set before it.
415
+ const fields = [], init = {}, locals = new Map(q0.locals);
416
+ for (const n of [...own].filter(x => q0.locals.has(x))) {
417
+ if (FLAGS.includes(n))
418
+ refuse(s, `${n}: a local the loop carries named as a fold's own values are`);
419
+ const v0 = q0.locals.get(n), srt = sortOfV(v0) ?? refuse(s, `${n}: ${v0.t === 'opaque' ? v0.why : `a ${v0.t}`}, carried by the loop (the subset reads a loop's numbers, booleans and choices)`);
420
+ fields.push({ name: n, sort: srt, role: 'state' });
421
+ init[n] = termOfV(v0, s);
422
+ locals.set(n, cellV(run, i, n, srt, v0.t === 'num' ? v0.ty : undefined));
423
+ }
424
+ // The item at the pass: its place's cell (its one value, for a list of scalars), where the place holds one.
425
+ const held = ls.held(ik);
426
+ let b0 = { ...q0, pc: held.op === 'const' ? [] : [held], locals, cont: undefined };
427
+ b0 = this.assign(tv, d.scalar ? this.baseCell(d, ik).vals.get('value') : { t: 'cell', map: ls.id, key: ik }, s, b0);
428
+ // One pass: the tries around the loop hidden (a raise out of a pass is the loop's), its failures and refusals its own.
429
+ const saved = { tries: this.tries, fails: this.fails, failPaths: this.failPaths, refusals: this.refusals.length, edges: this.edges.length };
430
+ this.hidden += this.tries.length;
431
+ this.tries = [];
432
+ this.fails = [];
433
+ this.failPaths = [];
434
+ this.inFold++;
435
+ let f;
436
+ try {
437
+ f = this.block(s.body, b0);
438
+ }
439
+ finally {
440
+ this.tries = saved.tries;
441
+ this.hidden -= saved.tries.length;
442
+ this.inFold--;
443
+ }
444
+ const F = I.or(...this.fails), Rf = I.or(...this.refusals.splice(saved.refusals));
445
+ this.fails = saved.fails;
446
+ this.failPaths = saved.failPaths;
447
+ if (this.edges.length > saved.edges)
448
+ refuse(s, 'a loop whose passes reach the edge of a fixed-width type');
449
+ const brks = (f.brk ?? []).filter(x => !x.cont), on = this.join([...(f.brk ?? []).filter(x => x.cont), ...(f.live ? [f.live] : [])], s), brk = this.join(brks, s);
450
+ for (const e of [...(on ? [on] : []), ...(brk ? [brk] : []), ...f.rets.map(r => r[0])])
451
+ if (this.changedFrom(e, q0))
452
+ refuse(s, `a loop whose passes write the state (the subset reads a loop over a list as a fold of its locals)`);
453
+ const pc = (x) => I.and(...x.pc), R = I.or(...f.rets.map(([x]) => pc(x))), Br = I.or(...brks.map(pc));
454
+ const no = (c) => c.op === 'const' && !c.v, ends = !(no(R) && no(Br) && no(F) && no(Rf));
455
+ const at = (n, x = i) => cellV(run, x, n, fields.find(v => v.name === n).sort);
456
+ const flag = (n, c) => { fields.push({ name: n, sort: { k: 'bool' }, role: 'state' }); init[n] = { s: 'bool', e: I.F }; return c; };
457
+ const step = {}, done = ends ? flag('__done', I.or(R, Br, F, Rf)) : I.F;
458
+ const doneAt = ends ? at('__done').e : I.F, idle = I.or(doneAt, I.not(held));
459
+ for (const v of fields.filter(x => !FLAGS.includes(x.name))) {
460
+ const val = (x) => x?.locals.get(v.name);
461
+ const nx = brk && on ? this.ite(Br, val(brk), val(on), s) : val(brk) ?? val(on) ?? locals.get(v.name);
462
+ if (sortOfV(nx)?.k !== v.sort.k)
463
+ refuse(s, `${v.name}: ${nx.t === 'opaque' ? nx.why : `a ${nx.t}`} after a pass of the loop`);
464
+ step[v.name] = iteTerm(idle, termOfV(locals.get(v.name), s), termOfV(nx, s));
465
+ }
466
+ if (ends)
467
+ step.__done = { s: 'bool', e: I.or(doneAt, I.and(held, done)) };
468
+ // (what a pass returned, where one did: kept, and the loop's value after it)
469
+ let retV;
470
+ if (!no(R)) {
471
+ retV = this.join(f.rets.map(([r, v]) => ({ ...r, locals: new Map([['__ret', v]]) })), s).locals.get('__ret');
472
+ const srt = sortOfV(retV) ?? refuse(s, `a loop that returns ${retV.t === 'opaque' ? retV.why : `a ${retV.t}`} (the subset reads a loop's return of a number, a boolean or a choice)`);
473
+ flag('__returned', R);
474
+ step.__returned = { s: 'bool', e: I.or(at('__returned').e, I.and(I.not(idle), R)) };
475
+ fields.push({ name: '__ret', sort: srt, role: 'state' });
476
+ init.__ret = termOfV(zeroOf(srt), s);
477
+ step.__ret = iteTerm(I.and(I.not(idle), R), termOfV(retV, s), termOfV(at('__ret'), s));
478
+ }
479
+ if (!no(F)) {
480
+ flag('__failed', F);
481
+ step.__failed = { s: 'bool', e: I.or(at('__failed').e, I.and(I.not(idle), F)) };
482
+ }
483
+ if (!no(Rf)) {
484
+ flag('__refused', Rf);
485
+ step.__refused = { s: 'bool', e: I.or(at('__refused').e, I.and(I.not(idle), Rf)) };
486
+ }
487
+ this.folds.push({ list: d.name, run, fields, init, step, len: ls.len, ...(d.carried ? {} : { state: true }) });
488
+ // After the loop: each running value its cell at the length.
489
+ const end = (n) => at(n, ls.len);
490
+ let q = { ...q0, locals: new Map(q0.locals), called: [...new Set([q0.called, ...f.rets.map(r => r[0].called), ...(on ? [on.called] : []), ...(brk ? [brk.called] : [])].flat())] };
491
+ for (const v of fields)
492
+ if (!FLAGS.includes(v.name))
493
+ q.locals.set(v.name, end(v.name));
494
+ // (a pass that failed or refused: the loop's, and no path goes on past it)
495
+ if (!no(F)) {
496
+ if (this.tries.length)
497
+ refuse(s, 'a failure in a loop inside a try');
498
+ this.fail(q, end('__failed').e, s, `a failure in a pass of the loop over ${d.name}`, null);
499
+ q = this.assume(q, I.not(end('__failed').e));
500
+ }
501
+ if (!no(Rf)) {
502
+ this.refuseWhere(q, end('__refused').e, s, `a refusal in a pass of the loop over ${d.name}`);
503
+ q = this.assume(q, I.not(end('__refused').e));
504
+ }
505
+ if (no(R))
506
+ return { live: q, rets: [] };
507
+ const ret = q;
508
+ q = this.assume(q, I.not(end('__returned').e));
509
+ return { live: q, rets: [[{ ...ret, pc: [...q0.pc, end('__returned').e] }, end('__ret')]] };
510
+ }
511
+ // any, all or sum of a generator: the loop it is, its value an accumulator's (any: true at the first that is; all:
512
+ // false at the first that isn't; sum: each added), the fold above.
513
+ foldExpr(x, p) {
514
+ const acc = `__fold${this.fresh++}`, at = x.p, n = () => ({ e: 'var', n: acc, p: at }), set = (y) => ({ s: 'set', p: at, to: n(), x: y });
515
+ const k = (v) => ({ e: 'bool', v, p: at }), f = String(x.f), y = x.x;
516
+ const body = f === 'any' ? [{ s: 'if', p: at, c: y, then: [set(k(true)), { s: 'break', p: at }], else: [] }] : f === 'all' ? [{ s: 'if', p: at, c: y, then: [], else: [set(k(false)), { s: 'break', p: at }] }]
517
+ : [set({ e: 'bin', op: '+', x: n(), y, p: at, text: x.text })];
518
+ const ifs = x.ifs, init = f === 'sum' ? { t: 'num', e: I.num(0) } : { t: 'bool', e: f === 'all' ? I.T : I.F };
519
+ const fl = this.forStmt({ s: 'for', p: at, to: x.to, over: x.over, body: ifs.length ? [{ s: 'if', p: at, c: ifs.length > 1 ? { e: 'and', xs: ifs, p: at } : ifs[0], then: body, else: [] }] : body }, { ...p, locals: new Map(p.locals).set(acc, init) });
520
+ const q = fl.live, out = q.locals.get(acc), locals = new Map(q.locals);
521
+ locals.delete(acc);
522
+ return [out, { ...q, locals }];
523
+ }
524
+ changedFrom(e, p) {
525
+ for (const [id, o] of e.heap) {
526
+ const b = p.heap.get(id);
527
+ if (b && b !== o && 'origin' in o && o.origin === 'state' && keyV(o) !== keyV(b))
528
+ return true;
529
+ }
530
+ return false;
531
+ }
532
+ // Paths that don't cover where they started (the raises to one handler) joined, keeping that one of them was taken.
533
+ joinSome(ps, at) {
534
+ const j = this.join(ps, at);
535
+ if (!j || ps.length < 2)
536
+ return j;
537
+ const k = j.pc.length, d = I.or(...ps.map(q => I.and(...q.pc.slice(k))));
538
+ return d.op === 'const' && d.v ? j : { ...j, pc: [...j.pc, d] };
539
+ }
540
+ // A call of other code inside a try that catches what it may raise: it returns, or raises what one handler of the
541
+ // tries it is in catches (the innermost's first, up to one catching every exception other code raises), an input of
542
+ // the request saying which (`<callee>_raises`), its stub raising the handler's class there.
543
+ mayRaise(a, name, at, p) {
544
+ if (!this.tries.length)
545
+ return p;
546
+ const exc = this.mod.exc;
547
+ const outs = [];
548
+ for (let j = this.tries.length - 1, done = false; j >= 0 && !done; j--) {
549
+ for (const [i, h] of this.tries[j].hs.entries()) {
550
+ const k = h.any ? (exc ? { mro: exc.mro } : null) : h.mro ? { mro: h.mro, ...(h.open ? { open: true } : {}) } : null;
551
+ if (!k || (h.any ? !exc : h.raise === undefined))
552
+ return refuse(at, `${at.text ?? name}: other code called inside a try whose handler ${h.any ? 'catches every exception' : `names ${h.names.join(', ')}`}, which the ${LANG[this.mod.lang] ?? this.mod.lang} check can't raise`);
553
+ // (its class caught by an earlier handler: that one's outcome)
554
+ const c = this.catcher(k, at, true);
555
+ if (c && (c[0] !== this.tries[j] || c[1] !== i))
556
+ continue;
557
+ outs.push({ t: this.tries[j], i, k, raise: h.any ? exc.raise : h.raise, n: (h.any ? exc.mro[0] : h.names[0]).split('.').pop() });
558
+ // (one catching the class other code raises catches every exception it raises: the last outcome)
559
+ if (h.any || h.names.some(n => exc?.mro.includes(n))) {
560
+ done = true;
561
+ break;
562
+ }
563
+ }
564
+ }
565
+ if (!outs.length)
566
+ return p;
567
+ if (this.init)
568
+ return refuse(at, `${at.text ?? name}: other code called inside a try in the constructor (whether it raises would be a param)`);
569
+ if (p.called.includes(`${a.key}$raises`))
570
+ return refuse(at, `${at.text ?? name}: ${a.key} called twice in one step inside a try (whether it raises is one input a step)`);
571
+ if (!a.patch && !a.at?.length)
572
+ return refuse(at, `${at.text ?? name}: may raise inside a try that catches it, and the check can't stub it`);
573
+ const short = a.key.split(/\.|::/).pop(), vals = ['none', ...outs.map((o, i) => (outs.findIndex(x => x.n === o.n) === i ? o.n : `${o.n}_${i}`))];
574
+ // (one input a method: each method's tries may catch it differently)
575
+ let r = a.raises?.find(x => x.m === this.method);
576
+ if (!r) {
577
+ const v = this.newVar(a.raises?.length ? `${this.method}_${short}_raises` : `${short}_raises`, outs.length === 1 ? { k: 'bool' } : { k: 'choice', values: vals }, 'input', `whether ${name} raises${outs.length > 1 ? ', and what (the class each handler catches)' : ''}: other code called inside a try that catches it (assumed: it returns, or raises what a handler of the try catches)`);
578
+ (a.raises ??= []).push(r = { name: v.name, cls: outs.map(o => o.raise), m: this.method });
579
+ this.notes.add(`${name} (${at.p}): may raise inside a try that catches it (assumed: it returns, or raises ${outs.map(o => o.n).join(' or ')}); whether it raises is an input of the request, ${v.name}`);
580
+ }
581
+ else if (JSON.stringify(r.cls) !== JSON.stringify(outs.map(o => o.raise)))
582
+ return refuse(at, `${at.text ?? name}: ${a.key} called inside tries that catch differently in one method`);
583
+ const v = this.vars.get(r.name);
584
+ for (const [i, o] of outs.entries()) {
585
+ const c = v.sort.k === 'bool' ? I.bvar(v.name) : I.is({ op: 'var', name: v.name, values: vals }, vals[i + 1]), w = I.and(this.cond(p), c);
586
+ if (!(w.op === 'const' && !w.v))
587
+ this.raise(p, c, w, [o.t, o.i], o.k, at);
588
+ }
589
+ return { ...p, called: [...p.called, `${a.key}$raises`] };
590
+ }
251
591
  unwritten(p, at, what) { if (this.opts.onError !== 'discard' && this.changed(p))
252
592
  refuse(at, `${what} after the state is written (the caller would see the object changed and the call failed; with onError: 'discard' the caller is taken to drop what a failed call wrote)`); }
253
593
  changed(p) {
@@ -371,6 +711,9 @@ export class Stepper {
371
711
  }
372
712
  if (a.t === 'tuple' && b.t === 'tuple' && a.xs.length === b.xs.length)
373
713
  return { t: 'tuple', xs: a.xs.map((x, i) => this.ite(c, x, b.xs[i], at)) };
714
+ // (a list the request carries on one path, another value on another: kept only where nothing reads it)
715
+ if ([a, b].some(x => x.t === 'ref' && this.seqs.some(d => x.id === `in:${d.name}`)))
716
+ return { t: 'opaque', why: 'a list the request carries on one path, another value on another' };
374
717
  if (a.t === 'ref' && b.t === 'ref')
375
718
  return refuse(at, 'one of two objects by a condition');
376
719
  return refuse(at, `a value that is a ${a.t} on one path and a ${b.t} on another`);
@@ -402,7 +745,7 @@ export class Stepper {
402
745
  return refuse(at, `a value that is a ${a.t} on one path and a ${b.t} on another`);
403
746
  }
404
747
  baseCell(d, key) {
405
- const vals = new Map(d.fields.map(f => [f.name, f.sort.k === 'num' ? { t: 'num', e: { op: 'cell', map: d.name, key, field: f.name } } : f.sort.k === 'choice' ? { t: 'choice', e: { op: 'cell', map: d.name, key, field: f.name, values: f.sort.values } } : { t: 'bool', e: { op: 'cell', map: d.name, key, field: f.name } }]));
748
+ const vals = new Map(d.fields.map(f => [f.name, f.sort.k === 'num' ? { t: 'num', e: { op: 'cell', map: d.name, key, field: f.name } } : f.sort.k === 'str' ? { t: 'str', e: { op: 'cell', map: d.name, key, field: f.name } } : f.sort.k === 'choice' ? { t: 'choice', e: { op: 'cell', map: d.name, key, field: f.name, values: f.sort.values } } : { t: 'bool', e: { op: 'cell', map: d.name, key, field: f.name } }]));
406
749
  return { has: { op: 'cell', map: d.name, key, field: 'has' }, vals };
407
750
  }
408
751
  // A value that may be None, read where the path has decided which (after `if x is None: return`).
@@ -429,6 +772,10 @@ export class Stepper {
429
772
  case 'none': return I.F;
430
773
  case 'opt': return I.and(v.has, this.truthy(v.v, at, p));
431
774
  case 'ref': {
775
+ // (a list the request carries: whether it has an item)
776
+ const cl = p && this.listOf(v, p, at, true);
777
+ if (cl)
778
+ return I.cmp('<', I.num(0), cl.len);
432
779
  // An object is true unless its class (or a base) defines __bool__ or __len__; a dict's truth is whether it is
433
780
  // empty, which the subset doesn't read.
434
781
  const o = (p?.heap ?? this.initHeap).get(v.id);
@@ -560,8 +907,13 @@ export class Stepper {
560
907
  const rets = [...flow.rets, ...(flow.live ? [[flow.live, { t: 'none' }]] : [])];
561
908
  if (!rets.length)
562
909
  return [{ t: 'none' }, { ...q, pc: [...q.pc, I.F], locals: saved }];
563
- const joined = this.join(rets.map(([r, v]) => ({ ...r, locals: new Map([['$ret', v]]) })), at);
564
- return [joined.locals.get('$ret'), { ...joined, locals: saved }];
910
+ const joined = this.join(rets.map(([r, v]) => ({ ...r, locals: new Map([['$ret', v]]) })), at), out = joined.locals.get('$ret');
911
+ // (other code's value left out, returned: where it is read and can't be answered, the innermost function that
912
+ // returned it is what is cut)
913
+ const o = out.t === 'opt' ? out.v : out;
914
+ if (this.inf && o.t === 'opaque' && o.ask && !this.returnedBy.has(o.why))
915
+ this.returnedBy.set(o.why, { id: f.id, roots: [...locals].filter(([, v]) => this.stateRef(v, q)).map(([n]) => n) });
916
+ return [out, { ...joined, locals: saved }];
565
917
  }
566
918
  // A branch arm the step runs: its first statement's line, counted by the harness's line events.
567
919
  arm(ss) { const s0 = ss.find(x => x.s !== 'import' && !/:0:\d+$/.test(x.p)); if (s0) {
@@ -649,29 +1001,57 @@ export class Stepper {
649
1001
  const [v, q] = this.ev(s.x, p);
650
1002
  return { rets: [[q, v]] };
651
1003
  }
652
- case 'fail':
653
- this.fail(p, I.T, s, String(s.why));
1004
+ case 'fail': {
1005
+ // (a class raised, with its bases; a bare re-raise, what its handler caught: one outer handler for all of it)
1006
+ let k = s.cls ? { mro: s.cls, ...(s.open ? { open: true } : {}) } : this.kindOf(String(s.why), s);
1007
+ if (s.reraise && this.tries.length) {
1008
+ const ks = this.handling.at(-1) ?? refuse(s, 'a bare raise outside a handler'), hs = ks.map(x => this.catcher(x, s));
1009
+ if (hs.some(h => h?.[0] !== hs[0]?.[0] || h?.[1] !== hs[0]?.[1]))
1010
+ refuse(s, 'a re-raise of exceptions outer handlers tell apart');
1011
+ k = ks[0];
1012
+ }
1013
+ // (inside a try, the exception's arguments are evaluated first: a failure there is raised instead)
1014
+ let q = p;
1015
+ const x = s.x;
1016
+ if (this.tries.length && x?.e === 'call' && !s.reraise)
1017
+ for (const a of [...x.args, ...x.kw.map(([, y]) => y)])
1018
+ q = this.ev(a, q)[1];
1019
+ this.fail(q, I.T, s, String(s.why), k);
654
1020
  return { rets: [] };
1021
+ }
1022
+ case 'try': return this.tryStmt(s, p);
655
1023
  case 'with': {
656
- let q = p;
1024
+ // (a context manager of other code, taken as transparent: a raise inside it may be suppressed by it, so none
1025
+ // goes through it to a handler around it)
1026
+ let q = p, other = false;
657
1027
  for (const it of s.items) {
658
1028
  if (it.as)
659
1029
  refuse(s, 'with ... as (a context manager\'s value)');
660
1030
  if (it.x.e === 'call' && this.skipped(this.calleeNames(it.x))) {
661
1031
  this.notes.add(`with ${it.x.text} (${it.x.p}): a context manager taken as transparent (skip)`);
1032
+ other = true;
662
1033
  continue;
663
1034
  }
664
1035
  const [v, q2] = this.ev(it.x, q);
665
1036
  q = q2;
666
1037
  if (v.t === 'opaque' && v.ask) {
667
1038
  this.notes.add(`with ${it.x.text} (${it.x.p}): a context manager of other code taken as transparent (inferred: the check runs it)`);
1039
+ other = true;
668
1040
  continue;
669
1041
  }
670
1042
  if (v.t !== 'lock')
671
1043
  refuse(it.x, `with ${it.x.text}: a context manager (the subset reads a lock's, which makes the step atomic)`);
672
1044
  this.notes.add(`${this.method}: the lock held (${it.x.p}): the step is atomic`);
673
1045
  }
674
- return this.block(s.body, q);
1046
+ if (!other)
1047
+ return this.block(s.body, q);
1048
+ this.cms.push(this.tries.length);
1049
+ try {
1050
+ return this.block(s.body, q);
1051
+ }
1052
+ finally {
1053
+ this.cms.pop();
1054
+ }
675
1055
  }
676
1056
  case 'del': {
677
1057
  const t = s.x;
@@ -711,6 +1091,8 @@ export class Stepper {
711
1091
  case 'assign': return { live: this.assignGo(s, p), rets: [] };
712
1092
  case 'switch': return this.switchGo(s, p);
713
1093
  case 'break': return { rets: [], brk: [p] };
1094
+ case 'continue': return { rets: [], brk: [{ ...p, cont: true }] };
1095
+ case 'for': return this.forStmt(s, p);
714
1096
  case 'defer': {
715
1097
  const key = this.lockKey(s.pl, p);
716
1098
  if (!p.locks.includes(key))
@@ -1211,6 +1593,9 @@ export class Stepper {
1211
1593
  given(all.filter(v => v !== keyV && v !== valV));
1212
1594
  const { tpl, k, kn } = this.storeKey(keyV, at);
1213
1595
  const [id, o] = this.storeMap(store, tpl, kn, at, p);
1596
+ // (inside a try that may catch it: the store's operation may raise, as other code's may, before it acts)
1597
+ if (this.tries.length)
1598
+ p = this.passing(`${store}.${m}`, `${store}.${m}`, { store, path: [m] }, at, p, awaited);
1214
1599
  if (kind === 'get')
1215
1600
  return this.mapGet({ t: 'ref', id }, k, at, p, 'none');
1216
1601
  if (kind === 'delete')
@@ -1245,6 +1630,8 @@ export class Stepper {
1245
1630
  // A call answered by the request: its result an input (one a step), the check stubbing the callee with it. Its type
1246
1631
  // is the caller's (a type string), a tag's, or the callee's declared one (inferred: `how` says which).
1247
1632
  answer(key, names, patch, at, p, awaited, type = this.opts.answers[key], how = 'stated') {
1633
+ if (this.inFold)
1634
+ return refuse(at, `${at.text ?? names[0]}: other code's value read in a loop's pass (it may differ each pass)`);
1248
1635
  if (!patch && !at.end)
1249
1636
  return refuse(at, `${at.text}: an answered call the check can't stub`);
1250
1637
  if (this.mod.stubs === false)
@@ -1277,7 +1664,24 @@ export class Stepper {
1277
1664
  if (!a.at.some(x => x.p === site.p))
1278
1665
  a.at.push(site);
1279
1666
  const vv = this.valueOf(this.vars.get(a.inputs.name));
1280
- return [a.inputs.none ? { t: 'opt', has: I.not(I.bvar(a.inputs.none)), v: vv } : vv, q];
1667
+ return [a.inputs.none ? { t: 'opt', has: I.not(I.bvar(a.inputs.none)), v: vv } : vv, this.mayRaise(a, names[0], at, q)];
1668
+ }
1669
+ // A call left out inside a try (its value unread): stubbed only to raise where the request says, else run as it is.
1670
+ passing(key, name, patch, at, p, awaited) {
1671
+ if (this.hidden)
1672
+ return refuse(at, `${at.text ?? name}: other code called in a loop inside a try (whether it raises would be one input a pass)`);
1673
+ if (!this.tries.length)
1674
+ return p;
1675
+ if (!patch && !at.end)
1676
+ return refuse(at, `${at.text ?? name}: other code left out inside a try that may catch what it raises, and the check can't stub it`);
1677
+ let a = this.answers.get(key);
1678
+ if (!a)
1679
+ this.answers.set(key, a = { key, patch: patch ?? {}, async: awaited, inputs: { name: '' }, sort: '', pass: true, at: [] });
1680
+ if (!a.pass)
1681
+ return refuse(at, `${at.text ?? name}: ${key} answered at one call and left out at another`);
1682
+ if (!a.at.some(x => x.p === at.p))
1683
+ a.at.push({ p: at.p, ...(at.end ? { end: at.end } : {}), ...(at.span ? { span: at.span } : {}) });
1684
+ return this.mayRaise(a, name, at, p);
1281
1685
  }
1282
1686
  // --- the boundary inferred ---------------------------------------------------------------------------------------
1283
1687
  // A call of code the subset doesn't read (another module's, an injected dependency's, or the module's own function
@@ -1285,6 +1689,7 @@ export class Stepper {
1285
1689
  // other code may change it: refused unless the caller states it. Its value read (a run refused where it is): the next
1286
1690
  // run answers it by the request, over its declared type; else it is left out, kept only where nothing reads it.
1287
1691
  pend = new Map();
1692
+ returnedBy = new Map();
1288
1693
  entryIds = new Set();
1289
1694
  boundary(x, b, p, awaited) {
1290
1695
  const tag = this.tagAt(x.p) ?? b.tag;
@@ -1301,7 +1706,7 @@ export class Stepper {
1301
1706
  const why = `${x.text ?? b.name}: the value of ${b.name}, other code left out`;
1302
1707
  this.pend.set(why, { ...b, why, at: x.p, ...(x.end ? { end: x.end } : {}) });
1303
1708
  this.notes.add(`${b.name} (${x.p}): left out (${tag ? 'tagged: gdp: skip' : 'inferred: nothing the rule keeps reads its value'}), run as it is by the check`);
1304
- return [{ t: 'opaque', why, ask: b.key }, q];
1709
+ return [{ t: 'opaque', why, ask: b.key }, this.passing(b.key, b.name, b.patch, x, q, awaited)];
1305
1710
  }
1306
1711
  argVals(x, p) {
1307
1712
  let q = p;
@@ -1453,6 +1858,12 @@ export class Stepper {
1453
1858
  this.notes.add(`${fn.name}: the module's own code, outside the subset (${why}), and writing none of the rule's state: taken as other code where it is called (inferred)`);
1454
1859
  return { key: fn.id, name: fn.name, patch: this.ownPatch(fn, self), ret: fn.ret, own: fn.id, recv: self, tag, refusal: `${x.text}: ${fn.name}` };
1455
1860
  }
1861
+ // The module's own function that returned other code's value (the innermost), where it may be cut: not cut yet, not
1862
+ // an entry, not strict, writing none of the state its call gave it.
1863
+ cuttable(why) {
1864
+ const own = this.returnedBy.get(why), fn = own ? this.mod.funcs[own.id] : undefined;
1865
+ return fn && !this.inf.cut.has(fn.id) && !this.entryIds.has(fn.id) && this.fnTag(fn)?.k !== 'strict' && !this.writesState(fn.id, new Set(own.roots)) ? fn : undefined;
1866
+ }
1456
1867
  // A refused run: what the next one infers, or the refusal (with the statement that would accept it). A value of
1457
1868
  // other code read is answered by its declared type (where the check can stub it); else the module's own function the
1458
1869
  // refusal is in (the innermost but the entries) is cut where it writes none of the rule's state.
@@ -1478,6 +1889,13 @@ export class Stepper {
1478
1889
  this.inf.cut.set(id.id, `${e.where}: ${e.what}`);
1479
1890
  return undefined;
1480
1891
  }
1892
+ // (last: a value returned by the module's own function, writing none of the state: that function cut, answered by
1893
+ // its declared type)
1894
+ const fn = best && this.cuttable(best.why);
1895
+ if (fn) {
1896
+ this.inf.cut.set(fn.id, `${e.where}: ${e.what}`);
1897
+ return undefined;
1898
+ }
1481
1899
  return hint ? new Refusal(e.where, `${e.what}; ${hint}`) : e;
1482
1900
  }
1483
1901
  // --- expressions ----------------------------------------------------------------------------------------------------
@@ -1601,7 +2019,7 @@ export class Stepper {
1601
2019
  return this.answer(ans, names, patch, x, x.args ? this.argsRead(x, p) : p, false);
1602
2020
  if (this.skipped(names)) {
1603
2021
  this.notes.add(`${names[0]} (${x.p}): left out (stated: skip), run as it is by the check`);
1604
- return [{ t: 'opaque', why: `${names[0]}: the value of a call left out (skip)` }, x.args ? this.argsRead(x, p) : p];
2022
+ return [{ t: 'opaque', why: `${names[0]}: the value of a call left out (skip)` }, this.passing(names[0], names[0], patch, x, x.args ? this.argsRead(x, p) : p, false)];
1605
2023
  }
1606
2024
  let q = p, recv;
1607
2025
  if (x.recv && this.inf)
@@ -1862,6 +2280,7 @@ export class Stepper {
1862
2280
  case 'list': return x.xs.length ? refuse(x, 'a list literal with items (the subset keeps a list of the state, made empty)') : [{ t: 'opaque', why: '[] (an empty list, a collection only where a field declares its type)' }, p];
1863
2281
  case 'lambda': return refuse(x, `${x.text}: a lambda (a closure; read only as min's or max's key over a collection of the state)`);
1864
2282
  case 'call': return this.call(x, p, awaited);
2283
+ case 'fold': return this.foldExpr(x, p);
1865
2284
  }
1866
2285
  return refuse(x, `${x.text ?? x.e}: an expression the subset doesn't read`);
1867
2286
  }
@@ -2180,6 +2599,16 @@ export class Stepper {
2180
2599
  const e = b.t === 'none' ? isNone(a) : isNone(b);
2181
2600
  return out(op === 'is' ? e : I.not(e));
2182
2601
  }
2602
+ if ((op === 'in' || op === 'not in') && this.listOf(b, q2, x)) {
2603
+ // (an item of a list, the request's or the state's: any(item == a for item in it), the fold)
2604
+ if (!callFree(x.y))
2605
+ return refuse(x, `${x.text}: in a list made by a call`);
2606
+ const tmp = `__in${this.fresh++}`, it = `__item${this.fresh++}`, at = x.p, vr = (n) => ({ e: 'var', n, p: at });
2607
+ const [v, q3] = this.foldExpr({ e: 'fold', f: 'any', p: at, text: x.text, to: vr(it), over: x.y, x: { e: 'cmp', op: '==', x: vr(it), y: vr(tmp), p: at, text: x.text }, ifs: [] }, { ...q2, locals: new Map(q2.locals).set(tmp, a) });
2608
+ const locals = new Map(q3.locals);
2609
+ locals.delete(tmp);
2610
+ return [{ t: 'bool', e: op === 'in' ? v.e : I.not(v.e) }, { ...q3, locals }];
2611
+ }
2183
2612
  if (op === 'in' || op === 'not in') {
2184
2613
  let e;
2185
2614
  if (b.t === 'tuple')
@@ -2275,10 +2704,11 @@ export class Stepper {
2275
2704
  call(x, p, awaited) {
2276
2705
  const fx = x.f, names = this.calleeNames(x), args0 = x.args, kw0 = x.kw;
2277
2706
  // The boundary first: an answered call, then a skipped one (neither's arguments read).
2278
- const ans = this.match(Object.keys(this.opts.answers ?? {}), names);
2279
- if (ans) {
2707
+ const ans = this.match(Object.keys(this.opts.answers ?? {}), names), skip = !ans && this.skipped(names);
2708
+ if (ans || skip) {
2280
2709
  let patch;
2281
- if (fx.e === 'fn')
2710
+ if (!ans && !this.tries.length) { } // (left out outside a try: run as it is, no stub)
2711
+ else if (fx.e === 'fn')
2282
2712
  patch = { mod: this.mod.module, path: [String(fx.id)] };
2283
2713
  else if (fx.e === 'get' && fx.x.e === 'var' && fx.x.n === 'self')
2284
2714
  patch = { self: String(fx.f) };
@@ -2300,11 +2730,10 @@ export class Stepper {
2300
2730
  if (o.t === 'ext' || o.t === 'cls')
2301
2731
  patch = o.patch;
2302
2732
  }
2303
- return this.answer(ans, names, patch, x, this.argsRead(x, p), awaited);
2304
- }
2305
- if (this.skipped(names)) {
2733
+ if (ans)
2734
+ return this.answer(ans, names, patch, x, this.argsRead(x, p), awaited);
2306
2735
  this.notes.add(`${names[0]} (${x.p}): left out (stated: skip), run as it is by the check`);
2307
- return [{ t: 'opaque', why: `${x.text}: the value of a call left out (skip)` }, this.argsRead(x, p)];
2736
+ return [{ t: 'opaque', why: `${x.text}: the value of a call left out (skip)` }, this.passing(names[0], names[0], patch, x, this.argsRead(x, p), awaited)];
2308
2737
  }
2309
2738
  // The callee and its object.
2310
2739
  let f, q = p;
@@ -2479,6 +2908,10 @@ export class Stepper {
2479
2908
  return [{ t: 'opaque', why: `${x.text}: of a value outside the subset${ask ? ` (${ask.why})` : ''}`, ...(ask ? { ask: ask.ask } : {}) }, q];
2480
2909
  }
2481
2910
  const v = args[0];
2911
+ // (a list the request carries: its length, an input)
2912
+ const cl = v && this.listOf(v, q, x, true);
2913
+ if (n === 'len' && cl)
2914
+ return [{ t: 'num', e: cl.len }, q];
2482
2915
  switch (n) {
2483
2916
  case 'min':
2484
2917
  case 'max': {
@@ -3359,7 +3792,7 @@ export class Stepper {
3359
3792
  const di = cases.findIndex(c => c.default);
3360
3793
  if (di >= 0)
3361
3794
  conds[di] = none;
3362
- const lives = [], rets = [];
3795
+ const lives = [], rets = [], conts = [];
3363
3796
  let carried;
3364
3797
  cases.forEach((c, i) => {
3365
3798
  const entry = conds[i].op === 'const' && !conds[i].v ? undefined : this.assume(q, conds[i]);
@@ -3378,8 +3811,10 @@ export class Stepper {
3378
3811
  if (f.live)
3379
3812
  lives.push(f.live);
3380
3813
  rets.push(...f.rets);
3381
- if (f.brk?.length)
3382
- lives.push(this.join(f.brk, c));
3814
+ const bs = (f.brk ?? []).filter(x => !x.cont);
3815
+ if (bs.length)
3816
+ lives.push(this.join(bs, c));
3817
+ conts.push(...(f.brk ?? []).filter(x => x.cont));
3383
3818
  if (f.ft) {
3384
3819
  if (i === cases.length - 1)
3385
3820
  refuse(c, 'fallthrough out of the last case');
@@ -3389,9 +3824,29 @@ export class Stepper {
3389
3824
  if (di < 0)
3390
3825
  lives.push(this.assume(q, none));
3391
3826
  const live = this.join(lives, s);
3392
- return { ...(live ? { live } : {}), rets };
3827
+ return { ...(live ? { live } : {}), rets, ...(conts.length ? { brk: conts } : {}) };
3393
3828
  }
3394
3829
  }
3830
+ // --- folds' helpers --------------------------------------------------------------------------------------------------
3831
+ // A cell of a carried list at a pass; a fold's own values (whether a pass ended it, returned, failed, refused).
3832
+ const PASS = I.PASS, FLAGS = ['__done', '__returned', '__ret', '__failed', '__refused'];
3833
+ const cellV = (map, i, f, s, ty) => {
3834
+ const c = { op: 'cell', map, key: { op: 'num', e: i }, field: f };
3835
+ return s.k === 'num' ? { t: 'num', e: c, ...(ty ? { ty } : {}) } : s.k === 'bool' ? { t: 'bool', e: c } : s.k === 'str' ? { t: 'str', e: c } : { t: 'choice', e: { ...c, values: s.k === 'choice' ? s.values : [] } };
3836
+ };
3837
+ const sortOfV = (v) => (v.t === 'num' ? { k: 'num' } : v.t === 'bool' ? { k: 'bool' } : v.t === 'choice' ? { k: 'choice', values: lvalues(v.e) } : v.t === 'str' ? { k: 'str' } : undefined);
3838
+ const termOfV = (v, at) => (v.t === 'num' ? { s: 'num', e: v.e } : v.t === 'bool' ? { s: 'bool', e: v.e } : v.t === 'choice' ? { s: 'choice', e: v.e } : v.t === 'str' ? { s: 'str', e: v.e } : refuse(at, `a ${v.t} where a fold keeps a number, a boolean, a string or a choice`));
3839
+ // The locals a body sets (each statement's targets), by name.
3840
+ const assigned = (ss) => {
3841
+ const out = new Set(), tv = (t) => { if (t?.e === 'var')
3842
+ out.add(String(t.n));
3843
+ else if (t?.e === 'tuple')
3844
+ t.xs.forEach(tv); };
3845
+ deep(ss, o => { if (o.s === 'set' || o.s === 'incdec' || o.s === 'opset' || o.s === 'for')
3846
+ tv(o.to); if (o.s === 'assign')
3847
+ (o.to ?? []).forEach(tv); return false; });
3848
+ return out;
3849
+ };
3395
3850
  // A pointer by a condition (one case where both are the same).
3396
3851
  export const phiP = (c, a, b) => (c.op === 'const' ? (c.v ? a : b) : JSON.stringify(a) === JSON.stringify(b) ? a : { k: 'phi', c, a, b });
3397
3852
  // The values a merge keeps exact (Go's): refused, not made opaque, where two paths make them different.
@@ -3423,7 +3878,13 @@ const split = (t) => { const i = t.indexOf('{}'); return i < 0 ? [t, t] : [t.sli
3423
3878
  export function assumed(x, request) {
3424
3879
  const out = [];
3425
3880
  for (const a of x.read?.answers ?? []) {
3426
- if (!a.how || !request || !(a.inputs.name in request))
3881
+ // (a call that raises inside a try: the request says it does, and which handler's class)
3882
+ for (const rs of a.raises ?? []) {
3883
+ const r = request?.[rs.name];
3884
+ if (r !== undefined && r !== false && r !== 0 && r !== 'none')
3885
+ out.push(`assumes \`${a.key.split('.').pop()}\` may raise${typeof r === 'string' ? ` ${r}` : ''} (inside a try that catches it)`);
3886
+ }
3887
+ if (!a.how || a.pass || !request || !(a.inputs.name in request))
3427
3888
  continue;
3428
3889
  // (an integer of the prover's is a pair: x − x$neg; a boolean 0 or 1)
3429
3890
  const none = a.inputs.none && (request[a.inputs.none] === true || request[a.inputs.none] === 1), v = request[a.inputs.name], neg = request[`${a.inputs.name}$neg`];
@@ -3923,7 +4384,10 @@ function readOnce(mod, opts, g) {
3923
4384
  let kind = 'none', rv, rn;
3924
4385
  // (a result of other code left out by inference: the step's result is kept, so its value is read)
3925
4386
  const asked = out.t === 'opaque' ? out : out.t === 'opt' && out.v.t === 'opaque' ? out.v : undefined;
3926
- if (asked?.ask)
4387
+ // (other code's value returned: answered or cut by the next reading where it can be; an object of other code's
4388
+ // class, not kept, as any other value of no scalar kind)
4389
+ const pd = asked?.ask ? [...g.pend.values()].find(x => x.why === asked.why) : undefined;
4390
+ if (asked?.ask && (pd?.ret?.k !== 'rec' || g.cuttable(asked.why)))
3927
4391
  refuse(fn, `${fn.name} returns ${asked.why} (a result the rule keeps)`);
3928
4392
  if (out.t === 'num' || out.t === 'bool' || out.t === 'str' || out.t === 'choice' || out.t === 'opt') {
3929
4393
  const inner = out.t === 'opt' ? out.v : out;
@@ -4011,9 +4475,13 @@ function readOnce(mod, opts, g) {
4011
4475
  a.f.forEach(([, x]) => walk(x)); };
4012
4476
  argsOf[fn.name].forEach(([, a]) => walk(a));
4013
4477
  for (const a of g.answers.values()) {
4014
- used.add(a.inputs.name);
4478
+ if (!a.pass)
4479
+ used.add(a.inputs.name);
4015
4480
  if (a.inputs.none)
4016
4481
  used.add(a.inputs.none);
4482
+ for (const r of a.raises ?? [])
4483
+ if (r.m === fn.name)
4484
+ used.add(r.name);
4017
4485
  }
4018
4486
  if (g.now)
4019
4487
  used.add(g.now.name);
@@ -4049,6 +4517,9 @@ function readOnce(mod, opts, g) {
4049
4517
  }
4050
4518
  mention(refuseB);
4051
4519
  mention(pre);
4520
+ for (const fd of g.folds)
4521
+ for (const t of [...Object.values(fd.init), ...Object.values(fd.step)])
4522
+ mention(t.e);
4052
4523
  const unread = g.inputs.filter(v => !read.has(v.name) && v.name !== ev?.name);
4053
4524
  if (unread.length)
4054
4525
  g.notes.add(`read by the code but by no term of the rule (given their sort's zero, or None, by the check): ${unread.map(v => v.name).join(', ')}`);
@@ -4095,6 +4566,7 @@ function readOnce(mod, opts, g) {
4095
4566
  params: g.params, inputs, state, maps, init, writes, mapWrites, outputs,
4096
4567
  refuse: refuseB, pre, layout, events, notes: [...g.notes], hints: g.hints, ...(ev ? { event: ev.name } : {}), results, laws,
4097
4568
  ...(g.leasts.length ? { leasts: g.leasts } : {}),
4569
+ ...(g.used.size ? { seqs: g.seqs.filter(d => g.used.has(d.name)), folds: g.folds } : {}),
4098
4570
  };
4099
4571
  return { ints: Object.fromEntries(g.ints), ...(g.madeAt ? { madeAt: g.madeAt.name } : {}), model, leaves, args: argsOf, answers: [...g.answers.values()], ctor, kept, arms: [...g.arms].map(a => { const i = a.lastIndexOf(':'); return [a.slice(0, i), Number(a.slice(i + 1))]; }), ...(cls ? { cls } : {}), stores, results: resultKinds, ...(g.injectedFields.length ? { inject: g.injectedFields } : {}) };
4100
4572
  }
@@ -4204,18 +4676,21 @@ export function checkStep(h, read, r, sorts, opts) {
4204
4676
  };
4205
4677
  const j = (x) => (typeof x === 'number' ? String(x) : x);
4206
4678
  const snapJson = (s) => ({ ...Object.fromEntries(Object.entries(s.leaves).map(([k, v]) => [k, j(v)])), ...Object.fromEntries(Object.entries(s.maps).map(([k, cells]) => [k, Object.fromEntries(Object.entries(cells).map(([key, c]) => [key, Object.fromEntries(Object.entries(c).map(([f, x]) => [f, j(x)]))]))])) });
4207
- const build = (a, inputs) => (a.k === 'in' ? { in: inputs[a.name] ?? a.z ?? 0, ...(a.float ? { float: true } : {}), ...(a.sym ? { sym: true } : {}) } : a.k === 'opt' ? (inputs[a.none] === true ? { none: true } : build(a.v, inputs)) : a.k === 'rec' ? (a.f.length ? { rec: a.cls, f: Object.fromEntries(a.f.map(([f, x]) => [f, build(x, inputs)])) } : { inert: true }) : a.k === 'inert' ? { inert: true } : a.k === 'store' ? { store: a.name } : { dflt: true });
4679
+ const build = (a, inputs) => (a.k === 'in' ? { in: inputs[a.name] ?? a.z ?? 0, ...(a.float ? { float: true } : {}), ...(a.sym ? { sym: true } : {}) } : a.k === 'opt' ? (inputs[a.none] === true ? { none: true } : build(a.v, inputs)) : a.k === 'rec' ? (a.f.length ? { rec: a.cls, f: Object.fromEntries(a.f.map(([f, x]) => [f, build(x, inputs)])) } : { inert: true }) : a.k === 'inert' ? { inert: true } : a.k === 'store' ? { store: a.name }
4680
+ : a.k === 'list' ? { list: (inputs[a.name] ?? []).map(it => build(a.item, it)) } : { dflt: true });
4208
4681
  const ctorArgs = (params) => read.ctor.map(([n, a]) => [n, build(a, params)]);
4209
4682
  let now = 0, inputsNow = {};
4210
4683
  // (an answer outside its type is no value the callee returns: the request is outside what the check compares)
4211
- const answersOf = () => Object.fromEntries(read.answers.map(a => {
4684
+ const answersOf = (call) => Object.fromEntries(read.answers.map(a => {
4212
4685
  const v = inputsNow[a.inputs.name] ?? 0, ty = read.ints[a.inputs.name], n = Number(v);
4213
4686
  if (a.fit && ty && !(a.inputs.none && inputsNow[a.inputs.none] === true)) {
4214
4687
  const [lo, hi] = rangeOf(ty);
4215
4688
  if (n < lo || n > hi)
4216
4689
  throw new Outside(`${a.key} answers ${String(v)}, outside its type`);
4217
4690
  }
4218
- return [a.key, a.inputs.none && inputsNow[a.inputs.none] === true ? { none: true } : { in: v, ...(a.inputs.float ? { float: true } : {}) }];
4691
+ // (a call that may raise: the class of the handler the request says, by its index; a call left out runs as it is)
4692
+ const rs = a.raises?.find(x => x.m === call), r = rs && inputsNow[rs.name], raise = r === true ? 0 : typeof r === 'string' && r !== 'none' ? rs.cls.findIndex((_, i) => (g0r(read.model, rs.name, i + 1)) === r) : -1;
4693
+ return [a.key, { ...(a.pass ? { pass: true } : a.inputs.none && inputsNow[a.inputs.none] === true ? { none: true } : { in: v, ...(a.inputs.float ? { float: true } : {}) }), ...(raise >= 0 ? { raise: rs.cls[raise] } : {}) }];
4219
4694
  }));
4220
4695
  let coverage;
4221
4696
  const r0 = performance.now();
@@ -4225,7 +4700,7 @@ export function checkStep(h, read, r, sorts, opts) {
4225
4700
  snapOf: self => { const res = ask({ op: 'get', id: self }); if (res.error)
4226
4701
  throw new Error(JSON.stringify(res.error)); return toSnap(res.state); },
4227
4702
  call: (self, e, args) => {
4228
- const res = ask({ op: 'call', id: self, m: e.call, a: args, now, answers: answersOf() });
4703
+ const res = ask({ op: 'call', id: self, m: e.call, a: args, now, answers: answersOf(e.call) });
4229
4704
  if (res.frame)
4230
4705
  throw new Error(`the code changes ${res.frame}, a field the rule leaves out`);
4231
4706
  if (res.bad !== undefined)
@@ -4328,6 +4803,8 @@ export function checkStep(h, read, r, sorts, opts) {
4328
4803
  catch { /* gone */ }
4329
4804
  }
4330
4805
  }
4806
+ // The i-th value of a choice input (a raise's handler by its index after 'none').
4807
+ const g0r = (m, name, i) => { const v = m.inputs.find(x => x.name === name); return v?.sort.k === 'choice' ? v.sort.values[i] : undefined; };
4331
4808
  // The value a None leaf holds in the rule (its sort's zero).
4332
4809
  const g0 = (m, name) => { const v = m.state.find(x => x.name === name); return v?.sort.k === 'num' ? 0 : v?.sort.k === 'bool' ? false : v?.sort.k === 'choice' ? v.sort.values[0] : ''; };
4333
4810
  // A front end's whole run: the module read, the model printed and built, the code run beside it.
@@ -4385,8 +4862,12 @@ export function stepNames(read) {
4385
4862
  for (const [method, as] of Object.entries(read.args))
4386
4863
  for (const [code, a] of as)
4387
4864
  arg(a, code, 'input', method);
4388
- for (const a of read.answers)
4389
- out.push({ code: a.key, rule: a.inputs.name, role: 'answer', ...(a.inputs.none ? { none: a.inputs.none } : {}) });
4865
+ for (const a of read.answers) {
4866
+ if (!a.pass)
4867
+ out.push({ code: a.key, rule: a.inputs.name, role: 'answer', ...(a.inputs.none ? { none: a.inputs.none } : {}) });
4868
+ for (const r of a.raises ?? [])
4869
+ out.push({ code: `${a.key} raises`, rule: r.name, role: 'answer', method: r.m });
4870
+ }
4390
4871
  const vars = new Set([...m.state, ...m.inputs].map(v => v.name));
4391
4872
  for (const [method, k] of Object.entries(read.results))
4392
4873
  if (k !== 'none')