gdp-wired 0.33.1 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/core/live.js CHANGED
@@ -13,8 +13,8 @@
13
13
  // chosen in order, each one no step raises that lowers the most of those left. The rank is then the kernel's
14
14
  // (proveLiveness), with the invariants inferLaws finds where its goals need some. Nothing new is trusted.
15
15
  import { evalC, evalE, interpret, seeded, walk } from "./machine.js";
16
- import { livenessHelpful, livenessParts, substE } from "../kernel/kernel.js";
17
- import { clock, proveLiveness, withDeadline } from "../kernel/prove.js";
16
+ import { falseC, livenessHelpful, livenessParts, substC, substE } from "../kernel/kernel.js";
17
+ import { clock, proveLiveness, proveProgress, proveStepLaws, withDeadline } from "../kernel/prove.js";
18
18
  import { allowed, watch } from "./watch.js";
19
19
  import { showE } from "./cycles.js";
20
20
  import { inferLaws } from "./infer.js";
@@ -58,16 +58,18 @@ function distances(m, l) {
58
58
  }
59
59
  // A variable's values ranked by the steps between them: each strongly connected set one level, a level above every one
60
60
  // a step goes to from it (Tarjan's components, then the longest path down).
61
- function controlRank(x, steps) {
61
+ function controlRank(x, value, steps) {
62
62
  const graph = new Map();
63
63
  const node = (a) => graph.get(a) ?? (graph.set(a, new Set()), graph.get(a));
64
64
  for (const st of steps) {
65
- const a = st.s.scalars[x], b = st.t.scalars[x];
65
+ const a = value(x, st, false), b = value(x, st, true);
66
+ if (Number.isNaN(a) || Number.isNaN(b))
67
+ return undefined;
66
68
  node(b);
67
69
  if (a !== b)
68
70
  node(a).add(b);
69
71
  }
70
- if (graph.size < 2)
72
+ if (graph.size < 2 || graph.size > 16)
71
73
  return undefined;
72
74
  const index = new Map(), low = new Map(), comp = new Map(), stack = [];
73
75
  let n = 0, c = 0;
@@ -109,7 +111,7 @@ function controlRank(x, steps) {
109
111
  const values = [...graph.keys()].sort((p, q) => p - q).map(a => [a, level.get(comp.get(a))]);
110
112
  if (values.every(([, lv]) => lv === 0))
111
113
  return undefined;
112
- return values.slice(0, -1).reduceRight((rest, [a, lv]) => ({ op: 'if', c: { op: '=', a: v(x), b: k(a) }, then: k(lv), else: rest }), k(values.at(-1)[1]));
114
+ return values.slice(0, -1).reduceRight((rest, [a, lv]) => ({ op: 'if', c: { op: '=', a: x, b: k(a) }, then: k(lv), else: rest }), k(values.at(-1)[1]));
113
115
  }
114
116
  // The variables a kind law bounds by a small constant (x < c, x <= c).
115
117
  const bounded = (m, laws) => {
@@ -243,14 +245,22 @@ export function leadsByTerms(m, laws, l, draws, opts = {}) {
243
245
  return NaN;
244
246
  } };
245
247
  const fixed = distances(m, l), text = (rank) => `(${rank.map(showE).join(', ')})`, tried = new Set();
248
+ // the control: the variables a kind law bounds, and the cells `from` and `to` read at a key of the params (a liveness
249
+ // about every key reads its key's cells: a status per key)
250
+ const cells = new Map();
251
+ walk([l.from, l.to], o => { if (o.op === 'get' && !reads(o.key, [...m.inputs, ...Object.keys(m.state)]) && !id(o.key).includes('"op":"get"'))
252
+ cells.set(id(o), o); });
253
+ const controls = [...bounded(m, laws).map(v), ...cells.values()];
246
254
  let last, best;
247
- for (let round = 0; round < 6 && until - clock() > 200; round++) {
248
- const cands = [...bounded(m, laws).map(x => controlRank(x, steps)).filter((e) => !!e), ...fixed];
255
+ // (the ranks alone until two thirds of the time are spent: the rest for the invariants the first one needs)
256
+ const ranksUntil = until - (until - clock()) / 3;
257
+ for (let round = 0; round < 6 && ranksUntil - clock() > 200; round++) {
258
+ const cands = [...controls.map(x => controlRank(x, (e, st, after) => value(e, st.ps, after ? st.t : st.s), steps)).filter((e) => !!e), ...fixed];
249
259
  const vals = cands.map(e => steps.map(st => [value(e, st.ps, st.s), value(e, st.ps, st.t)]));
250
260
  const build = (banned) => {
251
261
  let left = steps.map((_, i) => i);
252
262
  const rank = [];
253
- for (let turn = 0; turn < 3 && left.some(i => steps[i].lower); turn++) {
263
+ for (let turn = 0; turn < 4 && left.some(i => steps[i].lower); turn++) {
254
264
  let pick = -1, most = 0;
255
265
  for (let c = 0; c < cands.length; c++) {
256
266
  if (banned.has(c) || rank.includes(c))
@@ -285,7 +295,7 @@ export function leadsByTerms(m, laws, l, draws, opts = {}) {
285
295
  break;
286
296
  let learnt = false;
287
297
  for (const rank of fresh) {
288
- const ms = until - clock();
298
+ const ms = ranksUntil - clock();
289
299
  if (ms < 200)
290
300
  break;
291
301
  tried.add(id(rank));
@@ -305,7 +315,7 @@ export function leadsByTerms(m, laws, l, draws, opts = {}) {
305
315
  const rank = best, lv = { ...l, rank }, ms = until - clock();
306
316
  if (ms > 300) {
307
317
  const { stay, cover, helps } = livenessParts(m, lv), inf = inferLaws(draws.rule ?? m, laws, [stay, cover, ...helps], { ms });
308
- const kept = inf.found.filter(f => !f.law.forall && !f.law.keys?.length), more = kept.map(f => f.law);
318
+ const kept = inf.found.filter(f => !f.law.some?.length), more = kept.map(f => f.law);
309
319
  if (inf.proven && more.length) {
310
320
  const again = withDeadline(until + 5000, () => proveLiveness(m, [...laws, ...more], lv));
311
321
  if (again.proven && again.checked)
@@ -315,3 +325,146 @@ export function leadsByTerms(m, laws, l, draws, opts = {}) {
315
325
  const failed = last?.failed ? { goal: last.failed.goal, stuck: last.failed.stuck, ...(last.failed.witness ? { witness: last.failed.witness } : {}) } : {};
316
326
  return { proven: false, checked: false, rank, found: { rank: text(rank), laws: [] }, ...failed, why: `rank ${text(rank)} of the rule's terms, from ${steps.length} steps sampled; the kernel's goals not proven with it` };
317
327
  }
328
+ export function refutedBy(m, laws, l, ring) {
329
+ const run = interpret(m), helpful = livenessHelpful(l), n = ring.sets.length;
330
+ if (!n)
331
+ return { refuted: false, why: 'no set' };
332
+ if (m.pre && !evalC(m.pre, ring.params, { scalars: {}, maps: {} }, m))
333
+ return { refuted: false, why: 'the params break the precondition' };
334
+ let st = run.init(ring.params);
335
+ for (const [i, req] of ring.stem.entries()) {
336
+ if (!allowed(m, run, ring.params, st, req))
337
+ return { refuted: false, why: `the stem's request ${i + 1} is not allowed` };
338
+ st = run.step(ring.params, st, req);
339
+ }
340
+ const at = (c) => evalC(c, { ...ring.params, ...st.scalars }, st, m);
341
+ if (!at(l.from) || at(l.to) || !at(ring.sets[0].holds))
342
+ return { refuted: false, why: 'the stem ends where `from` doesn\'t hold, `to` does, or outside the first set' };
343
+ const after = { vars: Object.fromEntries(Object.keys(m.state).map(x => [x, v(`${x}'`)])), maps: Object.fromEntries(Object.keys(m.maps ?? {}).map(map => [map, (key) => ({ op: 'get', map: `${map}'`, key })])), flags: {} };
344
+ const full = (r) => Object.fromEntries(m.inputs.map(i => [i, r[i] ?? k(0)]));
345
+ for (const [j, set] of ring.sets.entries()) {
346
+ const next = ring.sets[(j + 1) % n].holds, then = { op: 'and', xs: [substC(next, after), substC(l.from, after), { op: 'not', x: substC(l.to, after) }] };
347
+ const p = proveProgress(m, laws, { name: `${l.name}: ring ${j + 1}`, when: set.holds, then, request: full(set.request) });
348
+ if (!p.proven || !p.checked)
349
+ return { refuted: false, why: `ring ${j + 1}: its request not proven allowed and into the next set${p.failed ? ` (${p.failed.goal})` : ''}` };
350
+ }
351
+ // "no allowed request from a state of R_j meets these": a step law whose `then` is false
352
+ const never = (what, ...cs) => { const r = proveStepLaws(m, laws, [{ name: `${l.name}: ${what}`, when: { op: 'and', xs: cs }, then: falseC }]); return r.proven && r.checked; };
353
+ const named = (req) => Object.entries(req).map(([x, t]) => ({ op: '=', a: v(x), b: t }));
354
+ const fair = new Set(['taken', 'weak', 'strong']);
355
+ for (const [i, h] of helpful.entries()) {
356
+ const takes = ring.sets.map(set => Object.entries(h.request).every(([x, t]) => id(full(set.request)[x]) === id(t)));
357
+ if (!takes.some(Boolean))
358
+ fair.delete('taken');
359
+ if (!takes.some(Boolean) && !ring.sets.some(set => never(`helpful request ${i + 1} not allowed`, set.holds, ...named(h.request))))
360
+ fair.delete('weak');
361
+ if (!ring.sets.some((set, j) => takes[j] && never(`helpful request ${i + 1} taken in its region`, set.holds, { op: 'not', x: h.when }, ...named(full(set.request))))
362
+ && !ring.sets.every(set => never(`helpful request ${i + 1} not allowed in its region`, set.holds, h.when, ...named(h.request))))
363
+ fair.delete('strong');
364
+ if (!fair.size)
365
+ return { refuted: false, fair: [], why: `helpful request ${i + 1}: the run is fair to it under no notion` };
366
+ }
367
+ const want = l.fairness === 'strong' ? 'strong' : 'weak', out = [...fair];
368
+ return { refuted: fair.has(want), fair: out, ...(fair.has(want) ? {} : { why: `the run is not ${want}ly fair` }) };
369
+ }
370
+ // A ring of one set, found: a state the runs reach where `from` holds and `to` doesn't and the helpful requests taken in
371
+ // turn keep it so; the set, the literals of the rule's comparisons (its guards and steps, also as each helpful request
372
+ // meets them, `from`, `to`, the regions) true there, the ring's requests the helpful requests allowed there. Literals a
373
+ // request doesn't keep are dropped (each kept literal proven by the kernel after each request, as Houdini drops them)
374
+ // until the rest are kept; then refutedBy checks the ring. Undefined where none is found.
375
+ export function findRing(m, laws, l, draws, opts = {}) {
376
+ const until = clock() + (opts.ms ?? 10_000), rand = seeded(17), run = interpret(m), helpful = livenessHelpful(l);
377
+ const env = (ps, st) => ({ ...ps, ...st.scalars });
378
+ const holds = (c, ps, st) => { try {
379
+ return evalC(c, env(ps, st), st, m);
380
+ }
381
+ catch {
382
+ return undefined;
383
+ } };
384
+ const pending = (ps, st) => holds(l.from, ps, st) === true && holds(l.to, ps, st) === false;
385
+ const full = (r) => Object.fromEntries(m.inputs.map(i => [i, r[i] ?? k(0)]));
386
+ const concrete = (r, ps, st) => Object.fromEntries(Object.entries(full(r)).map(([i, t]) => [i, evalE(t, env(ps, st), st, m)]));
387
+ // A state where `from` holds and `to` doesn't, then the helpful requests allowed taken in turn, up to 3,000 steps (the
388
+ // time passing in them, every deadline small params allow passed), never reaching `to`: the state they end at.
389
+ let found;
390
+ const allowedAt = (ps, st) => helpful.flatMap((h, i) => { try {
391
+ return allowed(m, run, ps, st, concrete(h.request, ps, st)) ? [i] : [];
392
+ }
393
+ catch {
394
+ return [];
395
+ } });
396
+ for (let trial = 0; trial < 400 && !found && clock() < until; trial++) {
397
+ let ps, st;
398
+ try {
399
+ ps = draws.params(rand, 2 + (trial % 3) * 2);
400
+ if (m.pre && !evalC(m.pre, ps, { scalars: {}, maps: {} }, m))
401
+ continue;
402
+ st = run.init(ps);
403
+ }
404
+ catch {
405
+ continue;
406
+ }
407
+ const stem = [];
408
+ for (let turn = 0; turn < 40; turn++) {
409
+ if (turn > 0 && pending(ps, st)) {
410
+ let s2 = st;
411
+ const laps = [];
412
+ for (let lap = 0; lap < 1000 && s2 && laps.length < 3000; lap++)
413
+ for (const i of allowedAt(ps, s2)) {
414
+ if (!s2)
415
+ break;
416
+ const req = concrete(helpful[i].request, ps, s2);
417
+ if (!allowed(m, run, ps, s2, req))
418
+ continue;
419
+ s2 = run.step(ps, s2, req);
420
+ laps.push(req);
421
+ if (!pending(ps, s2))
422
+ s2 = undefined;
423
+ }
424
+ const hs = s2 ? allowedAt(ps, s2) : [];
425
+ if (s2 && hs.length) {
426
+ found = { ps, stem: [...stem, ...laps], st: s2, hs };
427
+ break;
428
+ }
429
+ }
430
+ try {
431
+ const req = draws.input(rand, 4, ps);
432
+ if (!allowed(m, run, ps, st, req))
433
+ continue;
434
+ st = run.step(ps, st, req);
435
+ stem.push(req);
436
+ }
437
+ catch { /* refused: another */ }
438
+ }
439
+ }
440
+ if (!found)
441
+ return undefined;
442
+ // the literals there
443
+ const atoms = new Map();
444
+ const add = (t) => walk(t, o => { if ((o.op === '<' || o.op === '<=' || o.op === '=') && typeof o.a === 'object' && typeof o.b === 'object') {
445
+ const c = o;
446
+ if (!readsC(c, m.inputs) && !id(c).includes('"op":"flag"'))
447
+ atoms.set(id(c), c);
448
+ } });
449
+ add([l.from, l.to, helpful.map(h => h.when), m.assume, m.step]);
450
+ for (const h of helpful) {
451
+ const sb = { vars: full(h.request), maps: {}, flags: {} };
452
+ if (m.assume)
453
+ add(substC(m.assume, sb));
454
+ for (const e of Object.values(m.step.state ?? {}))
455
+ add(substE(e, sb));
456
+ }
457
+ let lits = [...atoms.values()].flatMap(c => { const b = holds(c, found.ps, found.st); return b === undefined ? [] : [b ? c : { op: 'not', x: c }]; });
458
+ const after = { vars: Object.fromEntries(Object.keys(m.state).map(x => [x, v(`${x}'`)])), maps: Object.fromEntries(Object.keys(m.maps ?? {}).map(map => [map, (key) => ({ op: 'get', map: `${map}'`, key })])), flags: {} };
459
+ for (let round = 0; round < 8 && clock() < until; round++) {
460
+ const R = { op: 'and', xs: lits };
461
+ const kept = lits.filter(c => found.hs.every(i => { const p = withDeadline(Math.min(until, clock() + 2000), () => proveProgress(m, laws, { name: 'kept', when: R, then: substC(c, after), request: full(helpful[i].request) })); return p.proven && p.checked; }));
462
+ if (kept.length === lits.length)
463
+ break;
464
+ lits = kept;
465
+ }
466
+ const ring = { params: found.ps, stem: found.stem, sets: found.hs.map(i => ({ holds: { op: 'and', xs: lits }, request: helpful[i].request })) };
467
+ return { ring, verdict: refutedBy(m, laws, l, ring) };
468
+ }
469
+ const readsC = (c, names) => { let hit = false; walk(c, o => { if (o.op === 'var' && names.includes(o.name))
470
+ hit = true; }); return hit; };
@@ -72,6 +72,17 @@ export type Machine = {
72
72
  sums?: Record<string, Sum>;
73
73
  fns?: Record<string, Fn>;
74
74
  facts?: Law[];
75
+ leasts?: Record<string, Least>;
76
+ };
77
+ export type Least = {
78
+ some: string;
79
+ key: string;
80
+ where: C;
81
+ by: {
82
+ e: E;
83
+ neg?: E;
84
+ desc?: boolean;
85
+ }[];
75
86
  };
76
87
  export type Fn = {
77
88
  js: string;
@@ -207,6 +218,7 @@ export declare function pairedArgs(key: E, n: number): E[] | undefined;
207
218
  export declare function evalC(c: C, env: Env, st: State, m: Machine): boolean;
208
219
  export declare function compileE(e: E, m: Machine): (env: Env, st: State) => number;
209
220
  export declare function compileC(c: C, m: Machine): (env: Env, st: State) => boolean;
221
+ export declare function leastsIn(m: Machine, env: Env, st: State): Env;
210
222
  export declare function carriedView(m: Machine, st: State, input: Request, rename?: (map: string) => string): State;
211
223
  export declare const numbersOf: (input: Request) => Record<string, number>;
212
224
  export declare function interpret(m: Machine): {
@@ -420,8 +420,31 @@ function runnable(m) {
420
420
  const plain = h ? historyMachine(m).machine : sumRuntime(m);
421
421
  if (!h)
422
422
  scope(plain);
423
- const queries = h ? Object.keys(h.queries) : [];
424
- return { h, plain, queries, carried: m.inputs.filter(i => !queries.includes(i)) };
423
+ const queries = h ? Object.keys(h.queries) : [], found = Object.entries(m.leasts ?? {}).flatMap(([n, l]) => [n, l.some]);
424
+ return { h, plain, queries, carried: m.inputs.filter(i => !queries.includes(i) && !found.includes(i)) };
425
+ }
426
+ // The least keys (Machine.leasts) in a state: the candidates are the keys the maps `where` and `by` read hold a cell at;
427
+ // where `where` holds past them all too (at every key no map holds), there is no least, and the request is refused.
428
+ export function leastsIn(m, env, st) {
429
+ const out = {};
430
+ for (const [name, l] of Object.entries(m.leasts ?? {})) {
431
+ const keys = keysAt(st, mapsIn({ op: 'and', xs: [l.where, ...l.by.flatMap(b => [b.e, ...(b.neg ? [b.neg] : [])].map(e => ({ op: '=', a: e, b: e })))] }).filter(mp => !m.fns?.[mp])), past = keys.pop();
432
+ const at = (key) => ({ ...env, ...out, [l.key]: key });
433
+ if (evalC(l.where, at(past), st, m))
434
+ throw new RangeError(`${m.name}: ${name} has no least (its condition holds at every key past the cells)`);
435
+ let best;
436
+ for (const key of keys.sort((a, b) => a - b)) {
437
+ if (!evalC(l.where, at(key), st, m))
438
+ continue;
439
+ const by = l.by.map(b => evalE(b.e, at(key), st, m) - (b.neg ? evalE(b.neg, at(key), st, m) : 0));
440
+ const first = best && by.findIndex((x, i) => x !== best.by[i]);
441
+ if (!best || (first !== -1 && (l.by[first].desc ? by[first] > best.by[first] : by[first] < best.by[first])))
442
+ best = { key, by };
443
+ }
444
+ out[name] = best?.key ?? 0;
445
+ out[l.some] = best ? 1 : 0;
446
+ }
447
+ return out;
425
448
  }
426
449
  const empty = { scalars: {}, maps: {} };
427
450
  // The state as a step reads it: with the maps the request carries (cells past them read 0), each checked natural.
@@ -499,11 +522,12 @@ export function interpret(m) {
499
522
  },
500
523
  // The queries a request would read (none without a history).
501
524
  queries: (params, st, input) => {
502
- if (!h)
503
- return {};
504
525
  const env = args(params, input);
526
+ if (!h)
527
+ return m.leasts ? leastsIn(m, env, viewed(st, input)) : {};
505
528
  ordered(env, st);
506
- return queriesOf(env, live(env, st));
529
+ const qs = queriesOf(env, live(env, st));
530
+ return m.leasts ? { ...qs, ...leastsIn(m, { ...env, ...qs }, viewed(st, input)) } : qs;
507
531
  },
508
532
  step: (params, given, input) => {
509
533
  const env = args(params, input), st = viewed(given, input);
@@ -513,6 +537,8 @@ export function interpret(m) {
513
537
  records = live(env, st);
514
538
  Object.assign(env, queriesOf(env, records));
515
539
  }
540
+ if (m.leasts)
541
+ Object.assign(env, leastsIn(m, env, st));
516
542
  for (const [name, c] of Object.entries(plain.step.flags ?? {}))
517
543
  env[`?${name}`] = evalC(c, env, st, plain) ? 1 : 0;
518
544
  if (m.assume && !evalC(m.assume, env, st, plain))
@@ -669,6 +695,16 @@ export function compileJs(m) {
669
695
  }
670
696
  lines.push(`let ${queries.map((_, i) => `q${i} = 0`).join(', ')};`, `for (let i = head; i < records.length; i++) { const r = records[i]; ${queries.map((q, i) => `q${i} = $x(q${i} + ${ex(h.queries[q])});`).join(' ')} }`, ...queries.map((q, i) => `env[${id(q)}] = q${i};`));
671
697
  }
698
+ // The least keys (leastsIn): a scan of the keys the maps read hold, smaller keys first.
699
+ for (const [name, l] of Object.entries(m.leasts ?? {})) {
700
+ const outer = bound;
701
+ bound = { ...bound, [l.key]: 'lk' };
702
+ const where = cx(l.where), by = l.by.map(b => (b.neg ? `(${ex(b.e)} - ${ex(b.neg)})` : ex(b.e)));
703
+ bound = outer;
704
+ const ms = mapsIn({ op: 'and', xs: [l.where, ...l.by.flatMap(b => [b.e, ...(b.neg ? [b.neg] : [])].map(e => ({ op: '=', a: e, b: e })))] }).filter(mp => !fns.includes(mp));
705
+ const better = l.by.map((b, i) => `by[${i}] !== bb[${i}] ? by[${i}] ${b.desc ? '>' : '<'} bb[${i}] : `).join('') + 'false';
706
+ lines.push(`{ const ks = $keys(maps, ${JSON.stringify(ms)}), past = ks.pop(); let lk = past; if (${where}) throw new RangeError(${id(`${m.name}: ${name} has no least (its condition holds at every key past the cells)`)}); let bk, bb; for (lk of ks.sort((a, b) => a - b)) { if (!(${where})) continue; const by = [${by.join(', ')}]; if (bk === undefined || (${better})) { bk = lk; bb = by; } } env[${id(name)}] = bk ?? 0; env[${id(l.some)}] = bk === undefined ? 0 : 1; }`);
707
+ }
672
708
  lines.push(...flags.map((name, i) => `const flag${i} = ${cx(plain.step.flags[name])};`),
673
709
  // The rule's own assumption, as `allowed` (core/watch.ts) reads it (a history's machine assumes more: its relations).
674
710
  ...(m.assume ? [`if (!${cx(m.assume)}) throw new RangeError(${id(refused(m))});`] : []), `const scalars = {...s, ${Object.entries(plain.step.state ?? {}).map(([name, e]) => `${id(name)}: ${ex(e)}`).join(', ')}};`, ...writes.map(([, w], i) => ('each' in w ? `const write${i} = ${every(w)};` : `const key${i} = ${ex(w.key)}, value${i} = ${ex(w.value)};`)));
@@ -149,8 +149,9 @@ def state_of(obj, stores):
149
149
  elif k == 'bool': s[l['name']] = False if v is None else v
150
150
  elif k == 'map':
151
151
  cells = {}
152
- for key, x in (v or {}).items():
153
- if l.get('fields'): cells[str(key)] = {f['name']: (enc_num(x[f['name']] if isinstance(x, dict) else getattr(x, f['name']))) for f in l['fields']}
152
+ # (a list: its items by their places, 0 first)
153
+ for key, x in (enumerate(v or []) if l.get('ordered') else (v or {}).items()):
154
+ if l.get('fields'): cells[str(key)] = {f['name']: (lambda y: y if f.get('choice') else enc_num(y))(x[f['name']] if isinstance(x, dict) else getattr(x, f['name'])) for f in l['fields']}
154
155
  else: cells[str(key)] = {'value': enc_num(x)}
155
156
  s[l['name']] = cells
156
157
  # A store's key no template names: the code keeps state the rule has no place for.
@@ -181,9 +182,9 @@ def set_state(obj, stores, state):
181
182
  for key, c in (v or {}).items():
182
183
  kk = int(key) if l.get('key') == 'num' else key
183
184
  if l.get('fields'):
184
- d[kk] = make_rec(resolve(l['cls']), {f['name']: (num_in(c[f['name']], f.get('float')) if isinstance(c[f['name']], str) else c[f['name']]) for f in l['fields']})
185
+ d[kk] = make_rec(resolve(l['cls']), {f['name']: (num_in(c[f['name']], f.get('float')) if isinstance(c[f['name']], str) and not f.get('choice') else c[f['name']]) for f in l['fields']})
185
186
  else: d[kk] = num_in(c['value'], l.get('float')) if isinstance(c['value'], str) else c['value']
186
- put(obj, l['path'], d)
187
+ put(obj, l['path'], [d[kk] for kk in sorted(d)] if l.get('ordered') else d)
187
188
  for l in S['leaves']:
188
189
  if l['kind'] == 'none' and state.get(l['name']) is True: put(obj, l['path'], None)
189
190
 
@@ -147,6 +147,8 @@ class Reader:
147
147
  elif bn: kinds.add('outside-base:' + bn)
148
148
  dataclass = any((dotted(d.func if isinstance(d, ast.Call) else d) or '').split('.')[-1] == 'dataclass' for d in cdef.decorator_list)
149
149
  frozen = any(isinstance(d, ast.Call) and any(k.arg == 'frozen' and isinstance(k.value, ast.Constant) and k.value.value for k in d.keywords) for d in cdef.decorator_list)
150
+ # (a dataclass whose == is its fields' unless eq=False says it is identity)
151
+ if any(isinstance(d, ast.Call) and any(k.arg == 'eq' and not (isinstance(k.value, ast.Constant) and k.value.value is True) for k in d.keywords) for d in cdef.decorator_list): kinds.add('eq-identity')
150
152
  total = not any(k.arg == 'total' and isinstance(k.value, ast.Constant) and k.value.value is False for k in cdef.keywords)
151
153
  # The fields its __init__ sets: annotated there, or set from an annotated argument (a class of another module whose
152
154
  # fields aren't declared on the class).
@@ -419,7 +421,15 @@ class Reader:
419
421
  return {'e': 'fstr', 'parts': parts, 'p': p, 'text': text(x)}
420
422
  if isinstance(x, ast.List): return {'e': 'list', 'xs': [E(v) for v in x.elts], 'p': p}
421
423
  if isinstance(x, (ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp)): return {'e': 'no', 'why': f"{text(x)}: a comprehension (a loop)", 'p': p}
422
- if isinstance(x, ast.Lambda): return {'e': 'no', 'why': f"{text(x)}: a lambda (a closure)", 'p': p}
424
+ if isinstance(x, ast.Lambda):
425
+ # (read as a key function where one is taken, min/max(xs, key=lambda o: ...); anywhere else refused, a closure)
426
+ a = x.args
427
+ if a.vararg or a.kwarg or a.kwonlyargs or a.defaults or a.posonlyargs or len(a.args) != 1: return {'e': 'no', 'why': f"{text(x)}: a lambda (a closure)", 'p': p}
428
+ ps = [y.arg for y in a.args]
429
+ self.local_stack.append((self.local_stack[-1] if self.local_stack else set()) | set(ps))
430
+ try: body = E(x.body)
431
+ finally: self.local_stack.pop()
432
+ return {'e': 'lambda', 'params': ps, 'x': body, 'p': p, 'text': text(x)}
423
433
  return {'e': 'no', 'why': f"{text(x)}: {type(x).__name__} (outside the subset)", 'p': p}
424
434
 
425
435
  def main():
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gdp-wired",
3
- "version": "0.33.1",
3
+ "version": "0.34.0",
4
4
  "description": "An automatic prover for stateful rules (budgets, caps, windows, workflows, policies): laws proven with no proof to write, checked again in Lean, counterexamples found on the GPU, the rule shipped as code",
5
5
  "keywords": [
6
6
  "verification",