gdp-wired 0.42.0 → 0.43.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.
@@ -29,6 +29,10 @@ import { Refusal, mergeOps, mergeWrites } from "./extract-read.js";
29
29
  import { fromModel } from "./extract.js";
30
30
  import { nonneg } from "./extract-print.js";
31
31
  import { Outside, constantsOf, draw, drive } from "./extract-check.js";
32
+ // A string that is one of a choice's literals on every path (a literal, or literals by a condition): the choice's.
33
+ const asChoice = (k, vs) => { if (k.op === 'slit')
34
+ return vs.includes(k.value) ? I.llit(k.value, vs) : undefined; if (k.op !== 'kite')
35
+ return undefined; const a = asChoice(k.a, vs), b = asChoice(k.b, vs); return a && b ? I.lite(k.c, a, b) : undefined; };
32
36
  const where = (x) => x.p || '?';
33
37
  const refuse = (x, what) => { throw new Refusal(typeof x === 'string' ? x : where(x), what); };
34
38
  const RESERVED = new Set(['rule', 'nat', 'int', 'bool', 'when', 'min', 'max', 'all', 'any', 'not', 'yes', 'no', 'lit', 'str', 'record', 'oneOf', 'intern', 'Int', 'forall']);
@@ -155,7 +159,7 @@ export class Stepper {
155
159
  if (t.k === 'list')
156
160
  return 'a list (lists are outside the Python subset)';
157
161
  if (t.k === 'map')
158
- return 'a dict';
162
+ return t.set ? 'a set' : 'a dict';
159
163
  return t.k;
160
164
  }
161
165
  // An input of a type: its variables, the value, and how the harness makes it.
@@ -164,7 +168,7 @@ export class Stepper {
164
168
  if (s) {
165
169
  const v = this.newVar(name, s, role);
166
170
  this.typed(v, t, role);
167
- return [this.valueOf(v), { k: 'in', name: v.name, z: zeroRaw(s), ...(t.k === 'float' ? { float: true } : {}), ...(t.k === 'choice' && t.sym ? { sym: true } : {}) }];
171
+ return [this.valueOf(v), { k: 'in', name: v.name, z: zeroRaw(s), ...(t.k === 'float' ? { float: true } : {}), ...(t.k === 'choice' && t.sym ? { sym: true } : {}), ...(t.k === 'str' && t.bytes ? { bytes: true } : {}) }];
168
172
  }
169
173
  if (t.k === 'opt') {
170
174
  if (t.of.k === 'rec') {
@@ -177,7 +181,7 @@ export class Stepper {
177
181
  return refuse(at, `${name}: an optional ${this.why(t.of)}`);
178
182
  const v = this.newVar(name, inner, role, `0 where ${name} is None`), none = this.newVar(`${name}_none`, { k: 'bool' }, role, `whether ${name} is None`);
179
183
  this.typed(v, t.of, role);
180
- return [{ t: 'opt', has: I.not(I.bvar(none.name)), v: this.valueOf(v) }, { k: 'opt', none: none.name, v: { k: 'in', name: v.name, z: zeroRaw(inner), ...(t.of.k === 'float' ? { float: true } : {}) } }];
184
+ return [{ t: 'opt', has: I.not(I.bvar(none.name)), v: this.valueOf(v) }, { k: 'opt', none: none.name, v: { k: 'in', name: v.name, z: zeroRaw(inner), ...(t.of.k === 'float' ? { float: true } : {}), ...(t.of.k === 'str' && t.of.bytes ? { bytes: true } : {}) } }];
181
185
  }
182
186
  if (t.k === 'none')
183
187
  return [{ t: 'none' }, { k: 'dflt' }];
@@ -207,7 +211,13 @@ export class Stepper {
207
211
  // A fixed-width integer variable: its type, and (for a request) a value outside it refused: the claim is for the
208
212
  // type's values.
209
213
  intTy(t) { return t.k === 'int' && t.bits !== undefined ? { bits: t.bits, signed: t.signed ?? true, ...(t.mod ? { mod: t.mod } : {}) } : undefined; }
214
+ // (bytes: a string of the rule's that is never equal to a str, as Python's b"x" != "x")
215
+ bytesVars = new Set();
216
+ // (the request's arguments kept though no term reads them: opts.keep)
217
+ kept = new Set();
210
218
  typed(v, t, role, sel = this.sel) {
219
+ if ('k' in t && t.k === 'str' && t.bytes)
220
+ this.bytesVars.add(v.name);
211
221
  const ty = 'k' in t ? this.intTy(t) : t;
212
222
  if (!ty)
213
223
  return;
@@ -949,7 +959,10 @@ export class Stepper {
949
959
  this.frames.pop();
950
960
  this.frameLocals.pop();
951
961
  }
952
- const rets = [...flow.rets, ...(flow.live ? [[flow.live, { t: 'none' }]] : [])];
962
+ // (a literal returned where the function declares a choice of literals, `-> Literal["a", "b"]`: the choice's)
963
+ const rt = f.ret?.k === 'opt' ? f.ret.of : f.ret;
964
+ const asDeclared = (v) => { const l = rt?.k === 'choice' && v.t === 'str' ? asChoice(v.e, rt.values) : undefined; return l ? { t: 'choice', e: l } : v; };
965
+ const rets = [...flow.rets, ...(flow.live ? [[flow.live, { t: 'none' }]] : [])].map(([r, v]) => [r, asDeclared(v)]);
953
966
  if (!rets.length)
954
967
  return [{ t: 'none' }, { ...q, pc: [...q.pc, I.F], locals: saved }];
955
968
  const joined = this.join(rets.map(([r, v]) => ({ ...r, locals: new Map([['$ret', v]]) })), at), out = joined.locals.get('$ret');
@@ -1256,8 +1269,11 @@ export class Stepper {
1256
1269
  this.declared.set(`${o.id}.${f}`, t);
1257
1270
  // (a literal written to a field of a choice is the choice's)
1258
1271
  const ft = this.declared.get(`${o.id}.${f}`) ?? this.mod.recs[obj.ty]?.fields.find(x => x.name === f)?.t, ct = ft?.k === 'opt' ? ft.of : ft;
1259
- if (ct?.k === 'choice' && v.t === 'str' && v.e.op === 'slit' && ct.values.includes(v.e.value))
1260
- v = { t: 'choice', e: I.llit(v.e.value, ct.values) };
1272
+ if (ct?.k === 'choice' && v.t === 'str') {
1273
+ const l = asChoice(v.e, ct.values);
1274
+ if (l)
1275
+ v = { t: 'choice', e: l };
1276
+ }
1261
1277
  const heap = new Map(p.heap).set(o.id, { ...obj, f: new Map(obj.f).set(f, v) });
1262
1278
  return { ...p, heap };
1263
1279
  }
@@ -1271,10 +1287,7 @@ export class Stepper {
1271
1287
  }
1272
1288
  // (a string that is a literal of the choice on every path)
1273
1289
  if (f.sort.k === 'choice' && v.t === 'str') {
1274
- const vs = f.sort.values, conv = (k) => { if (k.op === 'slit')
1275
- return vs.includes(k.value) ? I.llit(k.value, vs) : undefined; if (k.op !== 'kite')
1276
- return undefined; const a = conv(k.a), b = conv(k.b); return a && b ? I.lite(k.c, a, b) : undefined; };
1277
- const l = conv(v.e);
1290
+ const l = asChoice(v.e, f.sort.values);
1278
1291
  if (l)
1279
1292
  return { t: 'choice', e: l };
1280
1293
  }
@@ -1372,7 +1385,12 @@ export class Stepper {
1372
1385
  this.notes.add(`${r.short}.${f.name}: a string the module only sets to ${vs.map(x => JSON.stringify(x)).join(' or ')} (read as a choice of those)`);
1373
1386
  return { k: 'choice', values: vs };
1374
1387
  };
1375
- if (t.val.k === 'rec') {
1388
+ // (a set: its keys alone, a cell held or not, as the TypeScript front end's Set)
1389
+ if (t.set) {
1390
+ fields = [];
1391
+ scalar = false;
1392
+ }
1393
+ else if (t.val.k === 'rec') {
1376
1394
  const r = this.rec(t.val.name, at);
1377
1395
  fields = r.fields.map(f => cell(f.name, lits(r, f)));
1378
1396
  scalar = false;
@@ -1380,7 +1398,7 @@ export class Stepper {
1380
1398
  else
1381
1399
  fields = [cell('value', t.val)];
1382
1400
  const v = this.newVar(name, { k: 'num' }, 'state');
1383
- const d = { name: v.name, key, fields, scalar, js: 'Map' };
1401
+ const d = { name: v.name, key, fields, scalar, js: t.set ? 'Set' : 'Map' };
1384
1402
  this.maps.push(d);
1385
1403
  return d;
1386
1404
  }
@@ -3009,8 +3027,10 @@ export class Stepper {
3009
3027
  return I.cmp('=', a.e, b.e);
3010
3028
  if (a.t === 'bool' && b.t === 'bool')
3011
3029
  return I.bite(a.e, b.e, I.not(b.e));
3012
- if (a.t === 'str' && b.t === 'str')
3013
- return I.keq(a.e, b.e);
3030
+ if (a.t === 'str' && b.t === 'str') {
3031
+ const isB = (k) => (k.op === 'svar' ? this.bytesVars.has(k.name) : k.op === 'slit' ? false : undefined), x = isB(a.e), y = isB(b.e);
3032
+ return x !== undefined && y !== undefined && x !== y ? I.F : I.keq(a.e, b.e);
3033
+ }
3014
3034
  if (a.t === 'choice' && b.t === 'choice')
3015
3035
  return I.leq(a.e, b.e);
3016
3036
  if (a.t === 'choice' && b.t === 'str' && b.e.op === 'slit')
@@ -3236,6 +3256,8 @@ export class Stepper {
3236
3256
  return k(args, kw, q);
3237
3257
  }
3238
3258
  dictCall(m, name, x, p) {
3259
+ if (this.mapObj(m, x, p)[1].decl.js === 'Set')
3260
+ return this.setCall(m, name, x, p);
3239
3261
  return this.evArgs(x, p, (args, kw, q) => {
3240
3262
  if (kw.length)
3241
3263
  return refuse(x, `${x.text}: a dict's method given keywords`);
@@ -3266,6 +3288,19 @@ export class Stepper {
3266
3288
  return refuse(x, `${x.text}: dict.${name} (the subset reads get, pop, [k], in and del)`);
3267
3289
  });
3268
3290
  }
3291
+ // A set's methods: add, discard and remove (a KeyError where the key isn't held), each a write of one key.
3292
+ setCall(m, name, x, p) {
3293
+ return this.evArgs(x, p, (args, kw, q) => {
3294
+ if (kw.length || args.length !== 1)
3295
+ return refuse(x, `${x.text}: a set's method given other than one key`);
3296
+ const [id, o] = this.mapObj(m, x, q), k = this.keyOf(args[0], x.args[0]);
3297
+ if (name === 'add')
3298
+ return [{ t: 'none' }, this.writeCell(id, o, k, I.T, new Map(), x, q)];
3299
+ if (name === 'discard' || name === 'remove')
3300
+ return [{ t: 'none' }, this.mapDel(m, k, x, q, name === 'remove')];
3301
+ return refuse(x, `${x.text}: set.${name} (the subset reads add, discard, remove and in)`);
3302
+ });
3303
+ }
3269
3304
  construct(rec, args, kw, x, p) {
3270
3305
  const r = this.rec(rec, x);
3271
3306
  // (a plain class of the repository whose __init__ the reader read: made by running it on a fresh object)
@@ -3313,6 +3348,9 @@ export class Stepper {
3313
3348
  const [c, q] = this.truth(a0, p);
3314
3349
  return [{ t: 'bool', e: c }, q];
3315
3350
  }
3351
+ // (set(), dict(), list(): an empty collection, as {} and [] are, a collection only where a field declares its type)
3352
+ if ((n === 'set' || n === 'frozenset' || n === 'dict' || n === 'list') && !x.args.length && !x.kw.length)
3353
+ return [{ t: 'opaque', why: n === 'list' ? `${n}() [] (an empty list, a collection only where a field declares its type)` : `${n}() {} (an empty ${n === 'dict' ? 'dict' : 'set'}, a collection only where a field declares its type)` }, p];
3316
3354
  return this.evArgs(x, p, (args, kw, q) => {
3317
3355
  if (kw.length)
3318
3356
  return refuse(x, `${x.text}: ${n} given keywords`);
@@ -4558,9 +4596,13 @@ function readOnce(mod, opts, g) {
4558
4596
  continue;
4559
4597
  }
4560
4598
  const [v, a] = g.input(pa.name, pa.t, fn, p, 'param');
4599
+ // (an argument of no kind the rule holds, a dict of no stated types say: the constructor and the methods may
4600
+ // keep it, and are refused wherever the rule would read it, as a method's argument of that type is; the check
4601
+ // gives an inert one)
4561
4602
  if (a.k === 'inert')
4562
- refuse(fn, `${r.short}(${pa.name}): a constructor argument of ${g.why(pa.t)} (state it as a store, or give it a default)`);
4563
- give(pa, v);
4603
+ g.notes.add(`${r.short}(${pa.name}): ${g.why(pa.t)}, read nowhere the rule keeps (the check gives an inert one)`);
4604
+ // (where the rule would read it, refused there, saying how: a store, or a default)
4605
+ give(pa, a.k === 'inert' && v.t === 'opaque' ? { ...v, why: `${v.why} (a constructor argument: state it as a store, or give it a default)` } : v);
4564
4606
  ctor.push([pa.name, a]);
4565
4607
  }
4566
4608
  const [, p2] = g.callFunc(fn, { t: 'ref', id: 'this' }, args, kw, { e: 'call', p: fn.p, text: `${r.short}()` }, p, false);
@@ -4706,11 +4748,14 @@ function readOnce(mod, opts, g) {
4706
4748
  g.notes.add(`${path.join('.')}: a list, read as its items in order (each item's place a key that only grows as items are added)`);
4707
4749
  return;
4708
4750
  }
4709
- if (v.t === 'opaque' && decl?.k === 'map' && /\{\}/.test(v.why)) {
4751
+ // (a dict whose cells the rule can hold: keyed by integers or strings, of sets' keys, records, or numbers, booleans
4752
+ // and literals; another, of threading.Event say, is a field outside the subset, left out like any other)
4753
+ const cellable = (t) => (t.key.k === 'int' || t.key.k === 'str') && (!!t.set || t.val.k === 'rec' || (!!g.scalar(t.val) && g.scalar(t.val).k !== 'str'));
4754
+ if (v.t === 'opaque' && decl?.k === 'map' && /\{\}/.test(v.why) && !!decl.set === /^(set|frozenset)\(\)/.test(v.why) && cellable(decl)) {
4710
4755
  const d = g.mapDeclOf(name, decl, at), id = `state:${path.join('.')}`;
4711
4756
  const vt = decl.val;
4712
4757
  heap.set(id, { k: 'map', decl: d, val: vt, origin: 'state' });
4713
- leaves.push({ name: d.name, path, kind: 'map', key: d.key, ...(vt.k === 'rec' ? { cls: vt.name, fields: d.fields.map(x => ({ name: x.name, ...(g.mod.recs[vt.name].fields.find(y => y.name === x.name)?.t.k === 'float' ? { float: true } : {}), ...(x.sort.k === 'choice' ? { choice: true } : {}) })) } : vt.k === 'float' ? { float: true } : {}) });
4758
+ leaves.push({ name: d.name, path, kind: 'map', key: d.key, ...(decl.set ? { set: true } : {}), ...(vt.k === 'rec' ? { cls: vt.name, fields: d.fields.map(x => ({ name: x.name, ...(g.mod.recs[vt.name].fields.find(y => y.name === x.name)?.t.k === 'float' ? { float: true } : {}), ...(x.sort.k === 'choice' ? { choice: true } : {}) })) } : vt.k === 'float' ? { float: true } : {}) });
4714
4759
  into.set(f, { t: 'ref', id });
4715
4760
  return;
4716
4761
  }
@@ -4784,6 +4829,15 @@ function readOnce(mod, opts, g) {
4784
4829
  continue;
4785
4830
  }
4786
4831
  const [v, a] = g.input(nm, pa.t, fn, p);
4832
+ if (opts.keep?.includes(pa.name)) {
4833
+ const keepOf = (x) => { if (x.k === 'in')
4834
+ g.kept.add(x.name);
4835
+ else if (x.k === 'opt') {
4836
+ g.kept.add(x.none);
4837
+ keepOf(x.v);
4838
+ } };
4839
+ keepOf(a);
4840
+ }
4787
4841
  if (at)
4788
4842
  g.shared.set(`${ty} ${k}`, [v, a]);
4789
4843
  args.push(v);
@@ -4905,7 +4959,18 @@ function readOnce(mod, opts, g) {
4905
4959
  const pd = asked?.ask ? [...g.pend.values()].find(x => x.why === asked.why) : undefined;
4906
4960
  if (asked?.ask && (pd?.ret?.k !== 'rec' || g.cuttable(asked.why)))
4907
4961
  refuse(fn, `${fn.name} returns ${asked.why} (a result the rule keeps)`);
4908
- if (out.t === 'num' || out.t === 'bool' || out.t === 'str' || out.t === 'choice' || out.t === 'opt') {
4962
+ // (a string result that is one of the method's literals on every path, `return "adopt"` / `return "stop"`: a choice
4963
+ // of them, as a Literal result is; a string kept by cases is otherwise of two strings the rule holds)
4964
+ const strLits = (k) => (k.op === 'slit' ? [k.value] : k.op === 'kite' ? ((a, b) => (a && b ? [...new Set([...a, ...b])] : undefined))(strLits(k.a), strLits(k.b)) : undefined);
4965
+ const lits = out.t === 'str' && out.e.op === 'kite' ? strLits(out.e) : undefined;
4966
+ if (lits) {
4967
+ const l = asChoice(out.e, lits);
4968
+ f.out = { t: 'choice', e: l };
4969
+ g.notes.add(`${fn.name} returns ${lits.map(x => JSON.stringify(x)).join(' or ')}: kept as a choice of them`);
4970
+ }
4971
+ const out1 = f.out;
4972
+ if (out1.t === 'num' || out1.t === 'bool' || out1.t === 'str' || out1.t === 'choice' || out1.t === 'opt') {
4973
+ const out = out1;
4909
4974
  const inner = out.t === 'opt' ? out.v : out;
4910
4975
  if (inner.t === 'num' || inner.t === 'bool' || inner.t === 'str' || inner.t === 'choice') {
4911
4976
  const sort = inner.t === 'num' ? { k: 'num' } : inner.t === 'bool' ? { k: 'bool' } : inner.t === 'str' ? { k: 'str' } : { k: 'choice', values: lvalues(inner.e) };
@@ -5044,7 +5109,7 @@ function readOnce(mod, opts, g) {
5044
5109
  for (const fd of g.folds)
5045
5110
  for (const t of [...Object.values(fd.init), ...Object.values(fd.step)])
5046
5111
  mention(t.e);
5047
- const unread = g.inputs.filter(v => !read.has(v.name) && v.name !== ev?.name);
5112
+ const unread = g.inputs.filter(v => !read.has(v.name) && v.name !== ev?.name && !g.kept.has(v.name));
5048
5113
  if (unread.length)
5049
5114
  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(', ')}`);
5050
5115
  const inputs = g.inputs.filter(v => !unread.includes(v));
@@ -5210,7 +5275,7 @@ export function checkStep(h, read, r, sorts, opts) {
5210
5275
  };
5211
5276
  const j = (x) => (typeof x === 'number' ? String(x) : x);
5212
5277
  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)]))]))])) });
5213
- 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.dict ? { dict: true } : {}) } : a.k === 'store' ? { store: a.name }
5278
+ const build = (a, inputs) => (a.k === 'in' ? { in: inputs[a.name] ?? a.z ?? 0, ...(a.float ? { float: true } : {}), ...(a.sym ? { sym: true } : {}), ...(a.bytes ? { bytes: 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.dict ? { dict: true } : {}) } : a.k === 'store' ? { store: a.name }
5214
5279
  : a.k === 'list' ? { list: (inputs[a.name] ?? []).map(it => build(a.item, it)) } : { dflt: true });
5215
5280
  const ctorArgs = (params) => read.ctor.map(([n, a]) => [n, build(a, params)]);
5216
5281
  let now = 0, inputsNow = {};
@@ -5360,7 +5425,7 @@ export function extractStep(mod, h, opts) {
5360
5425
  }
5361
5426
  const unsigned = Object.fromEntries([...read.model.inputs, ...read.model.params].filter(v => read.ints[v.name] && !read.ints[v.name].signed).map(v => [v.name, 'nat']));
5362
5427
  const x = fromModel(read.model, mod.file, { ...unsigned, ...opts.domains }, notes, (rule, sorts) => checkStep(h(read), read, rule, sorts, opts));
5363
- return { ...x, read, names: stepNames(read) };
5428
+ return { ...x, read, names: stepNames(read), ...(mod.consts ? { consts: mod.consts } : {}) };
5364
5429
  }
5365
5430
  // The names of a reading: each leaf of the state by its path, the constructor's and each method's arguments (an object
5366
5431
  // the caller gives by its fields), each answer by its callee's qualified name, each method's result, the failure.
@@ -36,6 +36,14 @@ export type Extraction = {
36
36
  evidence?: Evidence;
37
37
  notes: string[];
38
38
  names?: Name[];
39
+ schedule?: unknown;
40
+ schedules?: unknown[];
41
+ fibers?: {
42
+ name: string;
43
+ steps: number;
44
+ base: number;
45
+ }[];
46
+ consts?: Record<string, number | string | boolean>;
39
47
  };
40
48
  export type Name = {
41
49
  code: string;
@@ -369,6 +369,11 @@ const isBool = (x, m) => {
369
369
  return o.field === 'has' || [...m.maps, ...(m.seqs ?? []), ...(m.folds ?? []).map(d => ({ name: d.run, fields: d.fields }))].some(d => d.name === o.map && d.fields.some(f => f.name === o.field && f.sort.k === 'bool'));
370
370
  return false;
371
371
  };
372
+ // (a choice by cases, `when(c, 'a', 'b')`: printed where it is read, through its variable, never hoisted as a number)
373
+ const isChoice = (x) => {
374
+ const o = x;
375
+ return o.op === 'lit' || (o.op === 'var' && Array.isArray(o.values)) || (o.op === 'ite' && (isChoice(o.a) || isChoice(o.b)));
376
+ };
372
377
  // The env's names: those the terms read, the choices a literal is printed through, and the maps written.
373
378
  function withChoices(env, text, P, extra = []) {
374
379
  const names = new Set(env.slice(1, -1).split(', ').filter(Boolean));
@@ -412,7 +417,14 @@ function hoist(m, P, roots) {
412
417
  const names = new Set([...m.params, ...m.inputs, ...m.state].map(v => v.name).concat(m.maps.map(d => d.name)));
413
418
  for (const k of order) {
414
419
  const node = hoistNodes.get(k), size = k.length;
415
- if ((count.get(k) ?? 0) < 2 || size < 60)
420
+ if ((count.get(k) ?? 0) < 2 || size < 60 || isChoice(node))
421
+ continue;
422
+ // (a product of integers kept at 0 or above only by the conditions the path is under: printed where it is read,
423
+ // under them, never hoisted out of them)
424
+ let guarded = false;
425
+ walk(node, o => { if (o.op === 'mul' && !(natOK(o.a, { m, sorts: P.sorts, atoms: [] }) && natOK(o.b, { m, sorts: P.sorts, atoms: [] })))
426
+ guarded = true; });
427
+ if (guarded)
416
428
  continue;
417
429
  if (!isBool(node, m)) {
418
430
  const ctx = { m, sorts: P.sorts, atoms: [] }, free = natOK(node, ctx);
@@ -20,6 +20,7 @@ export type InferOptions = {
20
20
  params: Record<string, number>;
21
21
  st: State;
22
22
  }[];
23
+ wall?: number;
23
24
  };
24
25
  export type Found = {
25
26
  law: Law;
@@ -161,6 +161,9 @@ function constantsOf(m, laws) {
161
161
  }
162
162
  // A key's linear form over the names `ok` admits, into `out` (`1` the constant); false where it is none.
163
163
  const conj = (c) => (c.op === 'and' ? c.xs.flatMap(conj) : [c]);
164
+ // A few values: at most four, none past 8: a mode's, and a view's cell reads each of them as a literal (as it does any
165
+ // three: a program counter's four phases are a mode, and were no literal of a view)
166
+ const few = (vals) => vals.length <= 4 && vals.every(x => x <= 8);
164
167
  function pairingOf(m) {
165
168
  const inputs = new Set(m.inputs), input = (v) => inputs.has(v);
166
169
  let found;
@@ -695,13 +698,13 @@ function comparisons(m, laws, atoms, coords, more = []) {
695
698
  return [...found.values()];
696
699
  }
697
700
  export function inferLaws(target, laws, stepLaws = [], opts = {}) {
698
- return quietly(() => withDeadline(clock() + (opts.ms ?? 20000), () => inferLawsSearch(target, laws, stepLaws, opts)));
701
+ return quietly(() => withDeadline(clock() + (opts.wall === undefined ? opts.ms ?? 20000 : Math.max(0, opts.wall - performance.now())), () => inferLawsSearch(target, laws, stepLaws, opts)));
699
702
  }
700
703
  function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
701
704
  // (GDP_INFER_TRACE=2: each phase's progress too, to stderr)
702
705
  if (env.GDP_INFER_TRACE === '2' && !opts.progress)
703
706
  opts = { ...opts, progress: (phase, info) => globalThis.process.stderr.write(`[infer ${phase}] ${JSON.stringify(info)}\n`) };
704
- const t0 = performance.now(), ms = opts.ms ?? 20000, wallUntil = t0 + ms, rule = isRule(target) ? target.withSumsOf(laws, stepLaws) : undefined;
707
+ const t0 = performance.now(), ms = opts.ms ?? 20000, wallUntil = opts.wall ?? t0 + ms, rule = isRule(target) ? target.withSumsOf(laws, stepLaws) : undefined;
705
708
  // The clock the budgets read (counted milliseconds since the start, or wall time where `timed`), and the stop.
706
709
  const timed = !!opts.timed, w0 = work.n, used = { tries: 0, rows: 0, evals: 0, watched: 0, erows: 0, etries: 0 };
707
710
  const now = () => (timed ? performance.now() - t0
@@ -957,7 +960,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
957
960
  modes.push({ atom: i, values: [0, 1], bool: true });
958
961
  else if (typeof decoded === 'string' && values)
959
962
  modes.push({ atom: i, values: values.map((_, j) => j), choice: values });
960
- else if (!k && seenValues.length && seenValues.length <= 4 && seenValues.every(v => v <= 8))
963
+ else if (!k && seenValues.length && few(seenValues))
961
964
  modes.push({ atom: i, values: seenValues });
962
965
  });
963
966
  const modeOf = (i) => modes.find(mo => mo.atom === i);
@@ -3014,7 +3017,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
3014
3017
  for (const i of [...v.atoms.filter(j => !atoms[j].int && !atoms[j].term), ...modes.filter(mo => !atoms[mo.atom].cell && !atoms[mo.atom].param).map(mo => mo.atom)]) {
3015
3018
  const vals = [...new Set(R.map(r => r[i]))].sort((a, b) => a - b);
3016
3019
  // (a value of a key's sort: 0 alone, an order literal below)
3017
- for (const value of valued(i) ? vals.filter(q => q === 0) : vals.length <= 3 ? vals : []) {
3020
+ for (const value of valued(i) ? vals.filter(q => q === 0) : vals.length <= 3 || few(vals) ? vals : []) {
3018
3021
  const top = value > 0 && value === vals.at(-1);
3019
3022
  add(top ? { lin: { coef: [[i, -1]], d: -value } } : { at: { atom: i, value } }, `${i}`, ren => `${term(i, ren)}=${value}`, reads(i), r => (top ? r[i] >= value : r[i] === value));
3020
3023
  }
@@ -80,4 +80,8 @@ export type Cite = {
80
80
  export declare function citesIn(text: string, where?: string): Cite[];
81
81
  export declare const isTwoRuns: (expr: string) => boolean;
82
82
  export declare function buildTwoRuns(x: Extraction, l: LawText, others?: Record<string, Extraction>): TwoRunLaw;
83
+ export declare const isLeadsTo: (expr: string) => boolean;
84
+ export declare function buildLeadsTo(x: Extraction, l: LawText, opts?: {
85
+ clock?: number;
86
+ }): unknown;
83
87
  export {};
package/dist/core/laws.js CHANGED
@@ -249,7 +249,7 @@ export function buildLaw(x, l, opts = {}) {
249
249
  throw new LawError(`${l.name}: a law is stated as <name>: <expr>`);
250
250
  const e = parse(l.expr);
251
251
  // A first reading finds what the law reads: a request, a result, the failure or the state before make it a step law.
252
- const probe = { b: {}, a: {}, step: true, method: l.method, keys: new Map(), roles: new Set(), methods: new Set(), clock: opts.clock };
252
+ const probe = { consts: x.consts, b: {}, a: {}, step: true, method: l.method, keys: new Map(), roles: new Set(), methods: new Set(), clock: opts.clock };
253
253
  read(e, probe, names, true);
254
254
  // (a law on a method, the line above it, is a law of its step: the state after it, old(x) before)
255
255
  const step = !!l.method || ['input', 'answer', 'result', 'failed', 'clock', 'method', 'old'].some(k => probe.roles.has(k));
@@ -257,7 +257,7 @@ export function buildLaw(x, l, opts = {}) {
257
257
  if (probe.methods.size > 1)
258
258
  throw new LawError(`it reads the arguments of ${[...probe.methods].join(' and ')}: a law of one step is about one method`);
259
259
  const gate = step && method && names.some(n => n.role === 'method') ? method : undefined;
260
- const body = (b, a) => read(e, { b, a, step, method, keys: new Map(), roles: new Set(), methods: new Set(), clock: opts.clock }, names, false);
260
+ const body = (b, a) => read(e, { consts: x.consts, b, a, step, method, keys: new Map(), roles: new Set(), methods: new Set(), clock: opts.clock }, names, false);
261
261
  if (!step)
262
262
  return { kind: 'law', law: r.law(l.name, (env) => (x.quiet ? env[x.quiet].eq(0).implies(body(env, env)) : body(env, env))) };
263
263
  const mname = names.find(n => n.role === 'method')?.rule;
@@ -353,8 +353,24 @@ function val(e, c, names, dry) {
353
353
  throw new LawError(`sum(${m.n.code}): its cells have ${fs.join(', ')} (the sum is of a map of numbers)`);
354
354
  if (dry)
355
355
  return DRY;
356
- const map = (c.a[m.n.rule] ?? c.b[m.n.rule]);
357
- return { t: 'num', v: Int.of(map.sum(cell => cell[fs[0]])) };
356
+ const map = ((m.env ?? c.a)[m.n.rule] ?? c.b[m.n.rule]);
357
+ try {
358
+ // (a map of integers: the sum of its cells' positive parts less the sum of their negative parts, each a sum of
359
+ // naturals the kernel keeps exact)
360
+ const one = map.at(new Term({ op: 'const', value: 0 }))[fs[0]];
361
+ if (one instanceof Int) {
362
+ // (after the step: the sums over the map before it, as the state after it holds them, primed)
363
+ const after = (m.env ?? c.a) === c.a && c.step && c.a !== c.b, src = (after ? c.b[m.n.rule] : map);
364
+ const sumOf = (part) => { const t = src.sum(cell => cell[fs[0]][part]); return after && t.e.op === 'var' ? new Term({ op: 'var', name: `${t.e.name}'` }) : t; };
365
+ return { t: 'num', v: new Int(sumOf('pos'), sumOf('neg')) };
366
+ }
367
+ return { t: 'num', v: Int.of(map.sum(cell => cell[fs[0]])) };
368
+ }
369
+ catch (x) {
370
+ if (x instanceof TypeError)
371
+ throw new LawError(`sum(${m.n.code}): a sum is of naturals, and ${m.n.code}'s cells are integers (a cell the code may set below 0): state them as naturals (domains, in gdp.toml) where the code never does`);
372
+ throw x;
373
+ }
358
374
  }
359
375
  const xs = e.xs.map(go);
360
376
  if (dry)
@@ -370,6 +386,20 @@ function val(e, c, names, dry) {
370
386
  return e.op === '-' ? { t: 'num', v: num(v).negate() } : { t: 'cond', v: not(cond(v)) };
371
387
  }
372
388
  case 'bin': {
389
+ // (a comparison with x // k on one side, k a positive constant: the same comparison without the division, exact
390
+ // over the integers (a <= x // k is k·a <= x; a < x // k is k·(a + 1) <= x), so it needs no function, which a law
391
+ // of one step can't read)
392
+ const flip = { '<': '>', '<=': '>=', '>': '<', '>=': '<=', '==': '==', '!=': '!=' };
393
+ const divk = (x) => (x.k === 'bin' && x.op === '//' && (constOf(x.b) ?? 0) >= 1 ? x : undefined);
394
+ if (flip[e.op] && (divk(e.b) || divk(e.a))) {
395
+ const [op, lhs, d] = divk(e.b) ? [e.op, e.a, divk(e.b)] : [flip[e.op], e.b, divk(e.a)];
396
+ const k = constOf(d.b), ka = { k: 'bin', op: '*', a: { k: 'num', v: k }, b: lhs }, ka1 = { k: 'bin', op: '*', a: { k: 'num', v: k }, b: { k: 'bin', op: '+', a: lhs, b: { k: 'num', v: 1 } } };
397
+ const le = (a, b) => ({ k: 'bin', op: '<=', a, b }), lt = (a, b) => ({ k: 'bin', op: '<', a, b });
398
+ // a ⋈ ⌊x/k⌋: <= : k·a <= x; < : k·(a+1) <= x; >= : x < k·(a+1); > : x < k·a; == : both; != : not both
399
+ const x = d.a, eq = { k: 'bin', op: '&&', a: le(ka, x), b: lt(x, ka1) };
400
+ const out = op === '<=' ? le(ka, x) : op === '<' ? le(ka1, x) : op === '>=' ? lt(x, ka1) : op === '>' ? lt(x, ka) : op === '==' ? eq : { k: 'un', op: 'not', x: eq };
401
+ return go(out);
402
+ }
373
403
  if (e.op === 'in') {
374
404
  const m = go(e.b);
375
405
  if (m.t !== 'map')
@@ -455,7 +485,7 @@ const show = (x) => (x.k === 'path' ? [x.head, ...x.segs.map(s => ('f' in s ? `.
455
485
  // A map's key as the rule holds it: a string's id, a natural.
456
486
  const key = (k) => (k.t === 'opt' && k.v ? key(k.v) : k.t === 'key' ? k.v : k.t === 'str' ? k.v.id : k.t === 'lit' ? fail('a literal key (the rule keys a map by the request\'s values)') : (() => { const n = num(k); return n.neg.e.op === 'const' && n.neg.e.value === 0 ? n.pos : n.clamped; })());
457
487
  function cellOf(m, k, c) {
458
- const map = (c.a[m.n.rule] ?? c.b[m.n.rule]);
488
+ const map = ((m.env ?? c.a)[m.n.rule] ?? c.b[m.n.rule]);
459
489
  return { rec: map.at(k), fields: m.n.map.fields };
460
490
  }
461
491
  // A path: the longest prefix of it the code names (in the law's method first: its arguments shadow the fields, as in the
@@ -469,7 +499,9 @@ function path(e, c, names, dry) {
469
499
  return dry ? DRY : rest(e.segs, { t: 'cell', rec: item.map, fields: item.fields }, c, names, dry, e);
470
500
  if (c.keys.has(e.head) && dry)
471
501
  return DRY;
472
- if (e.head === 'result' || e.head === 'failed') {
502
+ // (result and failed are the step's, unless the code has a name of its own so: a field named failed, read bare, is
503
+ // that field, as self.failed always is)
504
+ if ((e.head === 'result' || e.head === 'failed') && !names.some(n => n.code === e.head && n.role !== 'failed' && n.role !== 'result')) {
473
505
  const n = e.head === 'failed' ? names.find(x => x.role === 'failed') : results(names, c);
474
506
  if (!n)
475
507
  throw new LawError(e.head === 'failed' ? 'the rule keeps no failure (with failures: \'kept\' it does: `failures = "kept"` in gdp.toml or --failures kept)' : 'the method returns nothing the rule keeps');
@@ -478,7 +510,8 @@ function path(e, c, names, dry) {
478
510
  c.methods.add(n.method);
479
511
  return rest(e.segs, leaf(n, c, dry), c, names, dry, e);
480
512
  }
481
- const explicit = ['self', 'this', 'state', 's'].includes(e.head) || e.head.startsWith('@');
513
+ // (self.x, this.x, state.x, @x: the state's x; a bare `state` or `s` is a name of the code's, a field named so)
514
+ const explicit = (['self', 'this', 'state', 's'].includes(e.head) && e.segs.length > 0) || e.head.startsWith('@');
482
515
  const parts = [e.head.replace(/^@/, ''), ...e.segs.map(s => ('f' in s ? s.f : undefined))];
483
516
  const heads = explicit && !e.head.startsWith('@') ? [parts.slice(1)] : [parts, ...(parts.length > 1 && parts[1] !== undefined ? [parts.slice(1)] : [])];
484
517
  for (const [hi, p] of heads.entries()) {
@@ -500,11 +533,16 @@ function path(e, c, names, dry) {
500
533
  if (hit.role === 'answer' && next && 'call' in next && next.args)
501
534
  throw new LawError(`${code}(${next.args}): an answered call's value is the request's, one a step: write it ${code}(...)`);
502
535
  const segs = e.segs.slice(skip + n - 1 + (hit.role === 'answer' && next && 'call' in next ? 1 : 0));
503
- return rest(segs, hit.map ? { t: 'map', n: hit, maps: names.filter(x => x.map && x.code === hit.code) } : leaf(hit, c, dry), c, names, dry, e);
536
+ // (a map read where it is named: old(m) is the map before the step wherever its cells are read, `k in old(m)`)
537
+ return rest(segs, hit.map ? { t: 'map', n: hit, maps: names.filter(x => x.map && x.code === hit.code), env: c.a } : leaf(hit, c, dry), c, names, dry, e);
504
538
  }
505
539
  }
506
540
  }
507
541
  // A method's argument by its method's name (charge.user), where several methods take one of that name.
542
+ // A constant of the module bound to a literal, by its name.
543
+ const k = c.consts?.[e.head];
544
+ if (k !== undefined && !e.segs.length)
545
+ return typeof k === 'number' ? { t: 'num', v: Int.of(k) } : typeof k === 'boolean' ? { t: 'cond', v: k ? yes : no } : { t: 'lit', v: k };
508
546
  const m = names.find(n => n.role === 'input' && n.method === e.head && e.segs[0] && 'f' in e.segs[0] && n.code === e.segs[0].f);
509
547
  if (m) {
510
548
  c.roles.add('input');
@@ -524,6 +562,10 @@ function find(code, names, c, stateOnly, called) {
524
562
  const here = inputs.filter(n => n.method === c.method);
525
563
  if (here.length)
526
564
  return here[0];
565
+ // (a field of that name: the field, never another method's argument)
566
+ const field = names.find(n => n.role === 'state' && at(n));
567
+ if (field)
568
+ return field;
527
569
  if (new Set(inputs.map(n => n.method)).size === 1)
528
570
  return inputs[0];
529
571
  throw new LawError(`${code} is an argument of ${inputs.map(n => n.method).join(', ')}: write the law on the method it is about (the line above it), or as <method>.${code}`);
@@ -610,7 +652,7 @@ function storeKey(m, k, c, names, dry) {
610
652
  const hit = m.maps.find(x => x.map.tpl === tpl) ?? (holes.length === 1 && tpl === '{}' && m.maps.length === 1 ? m.maps[0] : undefined);
611
653
  if (!hit || holes.length !== 1)
612
654
  throw new LawError(`${m.n.code}[${tpl}]: its keys are ${m.maps.map(x => JSON.stringify(x.map.tpl.replace('{}', '<key>'))).join(', ')}`);
613
- return [{ t: 'map', n: hit, maps: [hit] }, val(holes[0], c, names, dry)];
655
+ return [{ t: 'map', n: hit, maps: [hit], ...(m.env ? { env: m.env } : {}) }, val(holes[0], c, names, dry)];
614
656
  }
615
657
  const CITE = /(?:#|\/\/|--|%|\/\*|^\s*\*)\s*gdp:\s*cite\s+([^:]+?)\s*:\s*(.+?)\s*(?:\*\/)?\s*$/;
616
658
  export function citesIn(text, where = '') {
@@ -668,3 +710,128 @@ export function buildTwoRuns(x, l, others = {}) {
668
710
  }
669
711
  throw new LawError('not a law about two runs');
670
712
  }
713
+ // --- liveness: "whenever <from>, later <to>" ---------------------------------------------------------------------------
714
+ // `<from> leads to <to> by <rank>[, <rank>...] via <helpful>[; <helpful>...] [strongly]`, each helpful request
715
+ // `[<cond> ->] <method>(<arg> = <value>, ...)`: in every run that takes each helpful request (where its condition holds)
716
+ // infinitely often, a state where `from` holds is followed by one where `to` does (core/dsl.ts's leadsTo, proven by
717
+ // proveLeadsTo: no step raises the rank (in order) while `from` holds and `to` doesn't, except into `to`, and each helpful
718
+ // request lowers it or reaches `to`). `strongly`: strong fairness (a request taken wherever, infinitely often, it is
719
+ // allowed). The conditions and the rank read the state and the params; a helpful request's values are literals (true,
720
+ // false, a number, one of a choice's values) or terms of the state.
721
+ const LEADS = /^(.*?)\s+leads\s+to\s+(.*?)(?:\s+by\s+(.*?))?\s+via\s+(.*?)(\s+strongly)?\s*$/s;
722
+ export const isLeadsTo = (expr) => LEADS.test(expr.trim());
723
+ export function buildLeadsTo(x, l, opts = {}) {
724
+ const m = LEADS.exec(l.expr.trim());
725
+ if (!m)
726
+ throw new LawError(`${l.name}: <from> leads to <to> [by <rank>] via <method>(<arg> = <value>, ...)`);
727
+ const names = namesWithClock(x), r = x.rule;
728
+ const model = x.model;
729
+ const sorts = x.sorts;
730
+ const ctxOf = (env) => ({ consts: x.consts, b: env, a: env, step: false, keys: new Map(), roles: new Set(), methods: new Set(), clock: opts.clock });
731
+ const stateOnly = (text, what) => {
732
+ const e = parse(text), probe = ctxOf({});
733
+ if (e.k === 'forall')
734
+ read(e, probe, names, true);
735
+ else
736
+ val(e, probe, names, true); // (what it reads: a bare yes/no field reads as one)
737
+ if ([...probe.roles].some(k => ['input', 'answer', 'result', 'failed', 'old', 'method'].includes(k)))
738
+ throw new LawError(`${what} reads the request or the step: it reads the state and the params`);
739
+ return e;
740
+ };
741
+ const from = stateOnly(m[1], 'its from'), to = stateOnly(m[2], 'its to');
742
+ const ranks = (m[3] ? split(m[3], ',') : []).map(t => { const e = parse(t); val(e, ctxOf({}), names, true); return e; });
743
+ const mname = names.find(n => n.role === 'method')?.rule;
744
+ const helpful = split(m[4], ';').map(h => {
745
+ const arrow = topIndex(h, '->');
746
+ const when = arrow >= 0 ? stateOnly(h.slice(0, arrow), 'a helpful request\'s condition') : undefined;
747
+ const call = /^\s*(\w+)\s*\((.*)\)\s*$/s.exec(arrow >= 0 ? h.slice(arrow + 2) : h);
748
+ if (!call)
749
+ throw new LawError(`a helpful request is <method>(<arg> = <value>, ...): ${h.trim()}`);
750
+ const method = call[1], args = call[2].trim() ? split(call[2], ',').map(a => { const eq = a.indexOf('='); if (eq < 0)
751
+ throw new LawError(`${method}(${a.trim()}): <arg> = <value>`); return [a.slice(0, eq).trim(), a.slice(eq + 1).trim()]; }) : [];
752
+ const ins = names.filter(n => n.role === 'input' && (n.method === method || !n.method));
753
+ if (mname && !names.some(n => n.method === method)) {
754
+ const ev = model?.inputs.find(v => v.name === mname);
755
+ if (!ev?.sort.values?.includes(method))
756
+ throw new LawError(`no method ${method} (its methods: ${ev?.sort.values?.join(', ') ?? 'none'})`);
757
+ }
758
+ const vals = args.map(([a, v]) => {
759
+ const n = ins.find(y => y.code === a) ?? (() => { throw new LawError(`${method}(${a}): no such argument (its arguments: ${ins.filter(y => y.method === method).map(y => y.code).join(', ')})`); })();
760
+ if (!n.rule)
761
+ throw new LawError(`${method}(${a}): an argument the rule doesn't keep`);
762
+ return [n.rule, v, model?.inputs.find(y => y.name === n.rule)?.sort, sorts?.get(n.rule)];
763
+ });
764
+ return { when, method, vals };
765
+ });
766
+ const strongly = !!m[5];
767
+ const term = (e, env) => { const v = val(e, ctxOf(env), names, false); const n = num(v); return n.clamped; };
768
+ const request = (h) => (env) => {
769
+ const out = {};
770
+ if (mname) {
771
+ const ev = model.inputs.find(v => v.name === mname);
772
+ out[mname] = ev.sort.values.indexOf(h.method);
773
+ }
774
+ for (const [rule, text, sort, dom] of h.vals) {
775
+ const lit = text.replace(/^["']|["']$/g, '');
776
+ if (sort?.k === 'bool') {
777
+ if (!['true', 'false', 'True', 'False'].includes(text))
778
+ throw new LawError(`${h.method}: ${rule} is a yes/no: true or false`);
779
+ out[rule] = /^t/i.test(text) ? 1 : 0;
780
+ }
781
+ else if (sort?.k === 'choice') {
782
+ const i = sort.values.indexOf(lit);
783
+ if (i < 0)
784
+ throw new LawError(`${text} isn't one of ${sort.values.join(', ')}`);
785
+ out[rule] = i;
786
+ }
787
+ else if (sort?.k === 'num' && dom !== 'int')
788
+ out[rule] = /^\d+$/.test(text) ? Number(text) : term(parse(text), env);
789
+ // (an integer: its two parts, the natural above 0 and the one below)
790
+ else if (sort?.k === 'num') {
791
+ const n = num(val(parse(text), ctxOf(env), names, false));
792
+ out[rule] = n.pos;
793
+ out[`${rule}$neg`] = n.neg;
794
+ }
795
+ else
796
+ throw new LawError(`${h.method}: ${rule}, a ${sort?.k ?? 'value'}, isn't given in a helpful request (numbers, yes/no and choices are)`);
797
+ }
798
+ return out;
799
+ };
800
+ return r.leadsTo(l.name, {
801
+ from: (env) => read(from, ctxOf(env), names, false),
802
+ to: (env) => read(to, ctxOf(env), names, false),
803
+ ...(ranks.length ? { rank: (env) => ranks.map(e => term(e, env)) } : {}),
804
+ helpful: helpful.map(h => ({ ...(h.when ? { when: (env) => read(h.when, ctxOf(env), names, false) } : {}), request: request(h) })),
805
+ ...(strongly ? { fairness: 'strong' } : {}),
806
+ });
807
+ }
808
+ // (the index of `tok` outside parentheses and quotes, or -1; a text split there)
809
+ function topIndex(s, tok) {
810
+ let depth = 0, q = '';
811
+ for (let i = 0; i < s.length; i++) {
812
+ const ch = s[i];
813
+ if (q) {
814
+ if (ch === q)
815
+ q = '';
816
+ continue;
817
+ }
818
+ if (ch === '"' || ch === "'")
819
+ q = ch;
820
+ else if (ch === '(' || ch === '[')
821
+ depth++;
822
+ else if (ch === ')' || ch === ']')
823
+ depth--;
824
+ else if (depth === 0 && s.startsWith(tok, i))
825
+ return i;
826
+ }
827
+ return -1;
828
+ }
829
+ function split(s, sep) {
830
+ const out = [];
831
+ let rest = s;
832
+ for (let i = topIndex(rest, sep); i >= 0; i = topIndex(rest, sep)) {
833
+ out.push(rest.slice(0, i));
834
+ rest = rest.slice(i + sep.length);
835
+ }
836
+ return [...out, rest].map(t => t.trim()).filter(Boolean);
837
+ }