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.
@@ -36,6 +36,8 @@ const keyV = (v) => JSON.stringify(v, (_, x) => (x instanceof Map ? [...x.entrie
36
36
  const LANG = { go: 'Go', rust: 'Rust', python: 'Python', c: 'C', cpp: 'C++', ruby: 'Ruby', elixir: 'Elixir', java: 'Java', kotlin: 'Kotlin' };
37
37
  const tyName = (ty) => (ty ? (ty.bits ? `${ty.signed ? 'i' : 'u'}${ty.bits}` : ty.signed ? 'an Instant' : 'a Duration') : 'the number');
38
38
  const constOf = (v) => (v.t === 'num' && v.e.op === 'const' ? v.e.v : undefined);
39
+ // The key a least key's where and by are read at (the printed rule's `.least`'s argument).
40
+ const LEAST_KEY = 'kl$';
39
41
  // The sorts a type string names (an answer's): int, float, bool, str, a choice of quoted strings, each `| None`.
40
42
  function sortOfText(s, at) {
41
43
  const parts = s.split('|').map(x => x.trim()).filter(Boolean), none = parts.includes('None'), rest = parts.filter(x => x !== 'None');
@@ -86,6 +88,8 @@ export class Stepper {
86
88
  lazy = new Map();
87
89
  initHeap = new Map();
88
90
  storeMaps = new Map();
91
+ // The least keys the step reads (an ordered collection's first or last item, its min or max by a key), each once.
92
+ leasts = [];
89
93
  frames = [];
90
94
  fieldNames = new Set();
91
95
  frozen = new Set();
@@ -432,6 +436,9 @@ export class Stepper {
432
436
  return I.T;
433
437
  if (o?.k === 'rec' && this.plainTruth(o.ty))
434
438
  return I.T;
439
+ // (a list or a dict of the state: whether it holds an item, its least key's)
440
+ if (o?.k === 'map' && o.origin === 'state')
441
+ return p ? this.least(o, at, k => this.baseCell(o.decl, k).has, () => []).some : refuse(at, `${at.text ?? ''}: the truth of a collection read with no step around it`);
435
442
  return refuse(at, `${at.text ?? ''}: the truth of ${o?.k === 'map' ? 'a dict (whether it is empty)' : 'an object whose class may define __bool__ or __len__'}`);
436
443
  }
437
444
  case 'cell':
@@ -797,6 +804,8 @@ export class Stepper {
797
804
  refuse(at, `${JSON.stringify(v.e.value)} is not one of ${f.name}'s literals`);
798
805
  return { t: 'choice', e: I.llit(v.e.value, f.sort.values) };
799
806
  }
807
+ if (f.sort.k === 'choice' && v.t !== 'choice')
808
+ return refuse(at, `${at.text}: a ${v.t === 'opaque' ? v.why : v.t} set where one of ${f.sort.values.map(x => JSON.stringify(x)).join(', ')} is held`);
800
809
  if (f.sort.k === 'num' && v.t !== 'num')
801
810
  return refuse(at, `${at.text}: a ${v.t === 'opaque' ? v.why : v.t} set where a number is held`);
802
811
  if (f.sort.k === 'bool' && v.t !== 'bool')
@@ -870,9 +879,19 @@ export class Stepper {
870
879
  const cell = (n, ft) => { const s = this.scalar(ft); if (!s || s.k === 'str')
871
880
  return refuse(at, `${name}: a dict of ${s?.k === 'str' ? 'strings' : this.why(ft)} (a cell holds integers, booleans and literals)`); return { name: n, sort: s, role: 'state' }; };
872
881
  let fields, scalar = true;
882
+ // (a record's string field the module only ever sets to literals: a choice of them, said in the notes)
883
+ const lits = (r, f) => {
884
+ if (f.t.k !== 'str')
885
+ return f.t;
886
+ const vs = this.literalsOf(r, f.name);
887
+ if (!vs)
888
+ return f.t;
889
+ 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)`);
890
+ return { k: 'choice', values: vs };
891
+ };
873
892
  if (t.val.k === 'rec') {
874
893
  const r = this.rec(t.val.name, at);
875
- fields = r.fields.map(f => cell(f.name, f.t));
894
+ fields = r.fields.map(f => cell(f.name, lits(r, f)));
876
895
  scalar = false;
877
896
  }
878
897
  else
@@ -882,6 +901,193 @@ export class Stepper {
882
901
  this.maps.push(d);
883
902
  return d;
884
903
  }
904
+ // The literals a record's field is made with, where every construction of it in the module gives one (its default
905
+ // too); undefined where one gives another value, or none is made.
906
+ literalsOf(r, field) {
907
+ const i = r.fields.findIndex(f => f.name === field), out = new Set();
908
+ let ok = true, made = 0;
909
+ const lit = (x) => { if (x?.e === 'str')
910
+ out.add(String(x.v));
911
+ else
912
+ ok = false; };
913
+ const visit = (o) => {
914
+ if (!ok || !o || typeof o !== 'object')
915
+ return;
916
+ if (Array.isArray(o)) {
917
+ o.forEach(visit);
918
+ return;
919
+ }
920
+ const x = o;
921
+ if (x.e === 'call' && x.f?.e === 'cls' && x.f.rec === Object.keys(this.mod.recs).find(k => this.mod.recs[k] === r)) {
922
+ made++;
923
+ const args = x.args, kw = x.kw;
924
+ lit(i < args.length ? args[i] : kw.find(([n]) => n === field)?.[1] ?? r.fields[i].dflt);
925
+ }
926
+ for (const v of Object.values(o))
927
+ visit(v);
928
+ };
929
+ visit(this.mod.funcs);
930
+ return ok && made && out.size ? [...out].sort() : undefined;
931
+ }
932
+ // --- ordered collections (core/dsl.ts's least) -----------------------------------------------------------------------
933
+ // The least key of a map of the state where `where` holds, least by `by` and then by the key itself (a list's order:
934
+ // the first of those that tie), as the rule's least key (Model.leasts): the rule's runtimes find it in the state
935
+ // before the step, so one read after the step wrote the map is refused. Each least read once, however often.
936
+ // (`held`: whether there is one, with `where` at its key, which it implies: what a path that takes it knows)
937
+ least(o, at, where, by) {
938
+ if (o.w)
939
+ return refuse(at, `${at.text}: the first, last, least or greatest item of a collection the step has written (the rule reads it in the state before the step)`);
940
+ const kk = { op: 'num', e: I.nvar(LEAST_KEY) }, w = where(kk), b = [...by(kk), { e: I.nvar(LEAST_KEY) }], sig = I.keyOf({ map: o.decl.name, w, b });
941
+ let l = this.leasts.find(x => I.keyOf({ map: x.map, w: x.where, b: x.by }) === sig);
942
+ if (!l) {
943
+ let name = `${o.decl.name}_least${this.leasts.length + 1}`;
944
+ while (this.vars.has(name))
945
+ name = `${name}_`;
946
+ // (whether there is one is the same for every order over the same keys: one condition, so a path that took one
947
+ // knows the others)
948
+ const same = this.leasts.find(x => x.map === o.decl.name && I.keyOf(x.where) === I.keyOf(w));
949
+ l = { name, some: same?.some ?? `${name}$some`, map: o.decl.name, key: LEAST_KEY, where: w, by: b };
950
+ this.leasts.push(l);
951
+ }
952
+ const key = I.nvar(l.name), some = I.bvar(l.some);
953
+ return { key, some, held: I.and(some, where({ op: 'num', e: key })), where };
954
+ }
955
+ // Whether the path already takes c: each of its conjuncts one of the path's conditions (or decided). A failure
956
+ // where c doesn't hold then never happens there (a least key's item is held where the path took it).
957
+ holds(p, c) {
958
+ if (c.op === 'not' && c.x.op === 'and')
959
+ return c.x.xs.some(x => this.holds(p, I.not(x)));
960
+ if (c.op === 'or')
961
+ return c.xs.some(x => this.holds(p, x));
962
+ const have = new Set(p.pc.flatMap(x => (x.op === 'and' ? x.xs : [x])).map(I.keyOf));
963
+ const parts = (x) => (x.op === 'and' ? x.xs.flatMap(parts) : x.op === 'not' && x.x.op === 'or' ? x.x.xs.map(I.not).flatMap(parts) : [x]);
964
+ return parts(c).every(x => (x.op === 'const' && x.v) || have.has(I.keyOf(x)));
965
+ }
966
+ orderedObj(m, p) {
967
+ const o = m.t === 'ref' ? p.heap.get(m.id) : undefined;
968
+ return o?.k === 'map' && o.decl.ordered && o.origin === 'state' ? [m.id, o] : undefined;
969
+ }
970
+ // A list of the state's item at its first or last place (xs[0], xs[-1], xs.pop(0), max(xs) and the like): the cell,
971
+ // and whether there is one.
972
+ item(id, o, at, last, by = () => []) {
973
+ const l = this.least(o, at, k => this.baseCell(o.decl, k).has, k => [...by(k), ...(last ? [{ e: k.e, desc: true }] : [])]);
974
+ const key = { op: 'num', e: l.key };
975
+ return { key, some: l.some, held: l.held, v: o.decl.scalar ? this.cellOf(o, key, undefined, at).vals.get('value') : { t: 'cell', map: id, key } };
976
+ }
977
+ // A list of the state's methods: append (at a place past every item), remove (the first item equal to the value),
978
+ // pop (the last, or the first), each a write of one place.
979
+ listCall(id, o0, name, x, p) {
980
+ let o = o0;
981
+ return this.evArgs(x, p, (args, kw, q) => {
982
+ const m = { t: 'ref', id };
983
+ // (the list as evaluating the arguments left it: a write there is one the least keys see, and refuse)
984
+ o = q.heap.get(id);
985
+ if (kw.length)
986
+ return refuse(x, `${x.text}: a list's method given keywords`);
987
+ if (name === 'append' && args.length === 1) {
988
+ const last = this.least(o, x, k => this.baseCell(o.decl, k).has, k => [{ e: k.e, desc: true }]);
989
+ return [{ t: 'none' }, this.mapSet(m, { op: 'num', e: I.nite(last.some, I.add(last.key, I.num(1)), I.num(0)) }, args[0], x, q)];
990
+ }
991
+ if (name === 'remove' && args.length === 1) {
992
+ const r = o.decl.scalar ? undefined : this.recOf(o.decl, x);
993
+ if (r && (!r.kinds.includes('dataclass') || r.kinds.includes('eq-identity') || r.methods.__eq__))
994
+ return refuse(x, `${x.text}: a list's remove of ${r.short}, whose equality isn't its fields' (a dataclass's)`);
995
+ const v = args[0], field = (f) => (o.decl.scalar ? v : this.fieldOf(v, f, x, q));
996
+ const hit = this.least(o, x, k => { const c = this.cellOf(o, k, q, x); return I.and(c.has, ...o.decl.fields.map(f => this.equal(c.vals.get(f.name), field(f.name), x, q))); }, () => []);
997
+ // (an item of this list itself: none equal to it only where it isn't held either)
998
+ // (an item of this list itself, at a least key the path took: equal to itself, so never missing)
999
+ const own = v.t === 'cell' && v.map === id ? this.leasts.find(l => l.map === o.decl.name && v.key.op === 'num' && v.key.e.op === 'var' && v.key.e.name === l.name) : undefined;
1000
+ const none = I.and(I.not(hit.some), ...(v.t === 'cell' && v.map === id ? [I.not(this.baseCell(o.decl, v.key).has)] : []));
1001
+ if (!this.holds(q, I.not(none)) && !(own && this.holds(q, I.bvar(own.some))))
1002
+ this.fail(q, none, x, `${x.text}: no item equal to it (a ValueError)`);
1003
+ return [{ t: 'none' }, this.listDel(id, o, { op: 'num', e: hit.key }, x, this.assume(q, hit.held))];
1004
+ }
1005
+ if (name === 'pop' && args.length <= 1) {
1006
+ const i = args[0] ? constOf(args[0]) : -1;
1007
+ if (i !== 0 && i !== -1)
1008
+ return refuse(x, `${x.text}: a list's pop at a place other than the first or the last`);
1009
+ const it = this.item(id, o, x, i === -1);
1010
+ if (!this.holds(q, it.some))
1011
+ this.fail(q, I.not(it.some), x, `${x.text}: pop from an empty list (an IndexError)`);
1012
+ return [it.v, this.listDel(id, o, it.key, x, this.assume(q, it.held))];
1013
+ }
1014
+ return refuse(x, `${x.text}: list.${name} (the subset reads append, remove, pop() and pop(0), xs[0] and xs[-1], min and max with a key, and whether it is empty)`);
1015
+ });
1016
+ }
1017
+ // An item taken out of a list: its place no longer held, its fields kept (a value read from it before is still the
1018
+ // object the code holds; a place past every item is where the next one goes).
1019
+ listDel(id, o, key, at, p) {
1020
+ const c = this.cellOf(o, key, p, at);
1021
+ return this.writeCell(id, o, key, I.F, c.vals, at, p);
1022
+ }
1023
+ recOf(d, at) {
1024
+ const id = [...this.initHeap].find(([, x]) => x.k === 'map' && x.decl === d)?.[1];
1025
+ const t = id?.val;
1026
+ return t?.k === 'rec' ? this.rec(t.name, at) : refuse(at, `${at.text}: a list of other than records`);
1027
+ }
1028
+ // A field of a record value: a cell's, a fresh record's.
1029
+ fieldOf(v, f, at, p) {
1030
+ if (v.t === 'cell') {
1031
+ const o = p.heap.get(v.map);
1032
+ if (o?.k === 'map')
1033
+ return this.cellOf(o, v.key, p, at).vals.get(f) ?? refuse(at, `${at.text}: no field ${f}`);
1034
+ }
1035
+ if (v.t === 'ref') {
1036
+ const o = p.heap.get(v.id);
1037
+ if (o?.k === 'rec')
1038
+ return o.f.get(f) ?? refuse(at, `${at.text}: no field ${f}`);
1039
+ }
1040
+ return refuse(at, `${at.text}: a ${v.t === 'opaque' ? v.why : v.t} compared with a list's items`);
1041
+ }
1042
+ // min or max of a list of the state (by a key function over its items, of one argument), or of a dict's keys.
1043
+ minMax(n, x, p) {
1044
+ const args = x.args, kw = x.kw;
1045
+ if (args.length !== 1 || kw.some(([k]) => k !== 'key' && k !== 'default'))
1046
+ return undefined;
1047
+ const [m, q] = this.ev(args[0], p), ord = this.orderedObj(m, q);
1048
+ const dict = !ord && m.t === 'ref' ? q.heap.get(m.id) : undefined;
1049
+ if (!ord && !(dict?.k === 'map' && dict.origin === 'state' && dict.decl.key === 'num'))
1050
+ return undefined;
1051
+ const keyFn = kw.find(([k]) => k === 'key')?.[1], dflt = kw.find(([k]) => k === 'default')?.[1];
1052
+ let q2 = q, d;
1053
+ if (dflt) {
1054
+ [d, q2] = this.ev(dflt, q2);
1055
+ }
1056
+ // (the collection as evaluating the default left it: a write there refuses the least key)
1057
+ const now = m.t === 'ref' ? q2.heap.get(m.id) : undefined;
1058
+ const desc = n === 'max';
1059
+ const partsOf = (v, at) => (v.t === 'tuple' ? v.xs.flatMap(y => partsOf(y, at)) : v.t === 'num' ? [v.e] : refuse(at, `${at.text}: a key of ${v.t === 'opaque' ? v.why : `a ${v.t}`} (the subset orders by numbers and tuples of them)`));
1060
+ // (a part negated: the part itself, ordered the other way)
1061
+ const signed = (e, d) => (e.op === 'neg' ? signed(e.a, !d) : e.op === 'mulk' && e.k === -1 ? signed(e.a, !d) : { e, ...(d ? { desc: true } : {}) });
1062
+ if (dict) {
1063
+ // (min(d), max(d): the least or greatest key the dict holds)
1064
+ if (keyFn)
1065
+ return refuse(x, `${x.text}: ${n} of a dict's keys by a key function`);
1066
+ const o = now, l = this.least(o, x, k => this.baseCell(o.decl, k).has, k => [{ e: k.e, desc }]);
1067
+ return this.emptyOr(n, { t: 'num', e: l.key }, l, d, x, q2);
1068
+ }
1069
+ const [id] = ord, o = now;
1070
+ let by;
1071
+ if (keyFn) {
1072
+ if (keyFn.e !== 'lambda')
1073
+ return refuse(x, `${x.text}: ${n}'s key other than a lambda of one argument`);
1074
+ const param = keyFn.params[0];
1075
+ by = k => { const [v] = this.ev(keyFn.x, { ...q2, locals: new Map(q2.locals).set(param, o.decl.scalar ? this.cellOf(o, k, q2, x).vals.get('value') : { t: 'cell', map: id, key: k }) }); return partsOf(v, keyFn.x).map(e => signed(e, desc)); };
1076
+ }
1077
+ else if (o.decl.scalar)
1078
+ by = k => [{ e: this.cellOf(o, k, q2, x).vals.get('value').e, desc }];
1079
+ else
1080
+ return refuse(x, `${x.text}: ${n} of records with no key (a TypeError: records aren't ordered)`);
1081
+ const l = this.least(o, x, k => this.baseCell(o.decl, k).has, by), key = { op: 'num', e: l.key };
1082
+ return this.emptyOr(n, o.decl.scalar ? this.cellOf(o, key, q2, x).vals.get('value') : { t: 'cell', map: id, key }, l, d, x, q2);
1083
+ }
1084
+ emptyOr(n, v, l, d, x, p) {
1085
+ if (d)
1086
+ return [d.t === 'none' ? { t: 'opt', has: l.held, v } : this.ite(l.held, v, d, x), p];
1087
+ if (!this.holds(p, l.some))
1088
+ this.fail(p, I.not(l.some), x, `${x.text}: ${n}() of an empty collection (a ValueError)`);
1089
+ return [v, this.assume(p, l.held)];
1090
+ }
885
1091
  // --- stores ---------------------------------------------------------------------------------------------------------
886
1092
  storeMap(store, tpl, kn, at, p) {
887
1093
  const key = `${store}\u0000${tpl}`;
@@ -1596,6 +1802,16 @@ export class Stepper {
1596
1802
  const [m, q] = this.ev(x.x, p), [k, q2] = this.ev(x.i, q);
1597
1803
  if (m.t === 'opaque')
1598
1804
  return [m, q2];
1805
+ const ord = this.orderedObj(m, q2);
1806
+ if (ord) {
1807
+ const i = constOf(k);
1808
+ if (i !== 0 && i !== -1)
1809
+ return refuse(x, `${x.text}: a list's item at a place other than the first or the last (xs[0], xs[-1])`);
1810
+ const it = this.item(ord[0], ord[1], x, i === -1);
1811
+ if (!this.holds(q2, it.some))
1812
+ this.fail(q2, I.not(it.some), x, `${x.text}: an item of an empty list (an IndexError)`);
1813
+ return [it.v, this.assume(q2, it.held)];
1814
+ }
1599
1815
  return this.mapGet(m, this.keyOf(k, x.i), x, q2, 'fail');
1600
1816
  }
1601
1817
  case 'neg': {
@@ -1642,7 +1858,9 @@ export class Stepper {
1642
1858
  return refuse(x, `${x.text ?? 'a dict literal'}: a dict literal with items (a record is made by its class)`);
1643
1859
  return [{ t: 'opaque', why: '{} (an empty dict, a map only where a field declares its type)' }, p];
1644
1860
  }
1645
- case 'list': return refuse(x, 'a list literal (lists are outside the Python subset)');
1861
+ // (an empty list: an ordered collection where a field of the state declares a list of records or numbers)
1862
+ 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
+ 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)`);
1646
1864
  case 'call': return this.call(x, p, awaited);
1647
1865
  }
1648
1866
  return refuse(x, `${x.text ?? x.e}: an expression the subset doesn't read`);
@@ -1834,9 +2052,16 @@ export class Stepper {
1834
2052
  const op = String(x.op);
1835
2053
  if (x.ovf)
1836
2054
  return this.fixed(x, p);
1837
- if (op === '/')
1838
- return refuse(x, `${x.text}: a true division (a float; the subset reads math.floor or math.ceil of x / k, int(x / k), or x // k)`);
1839
2055
  const [a, q] = this.ev(x.x, p), [b, q2] = this.ev(x.y, q);
2056
+ // A true division: a float, kept only where nothing the rule keeps reads it (refused there); its divisor 0 fails.
2057
+ if (op === '/') {
2058
+ if (b.t === 'num' || b.t === 'bool') {
2059
+ const nb = this.numOf(b, x, q2);
2060
+ this.fail(q2, I.cmp('=', nb, I.num(0)), x, `${x.text}: a division by zero (a ZeroDivisionError)`);
2061
+ return [{ t: 'opaque', why: `${x.text}: a true division (a float; the subset reads math.floor or math.ceil of x / k, int(x / k), or x // k)` }, this.assume(q2, I.not(I.cmp('=', nb, I.num(0))))];
2062
+ }
2063
+ return [{ t: 'opaque', why: `${x.text}: a true division (a float; the subset reads math.floor or math.ceil of x / k, int(x / k), or x // k)` }, q2];
2064
+ }
1840
2065
  if (a.t === 'opaque' || b.t === 'opaque')
1841
2066
  return [a.t === 'opaque' ? a : b, q2];
1842
2067
  if ((a.t === 'str' || a.t === 'fmt') && op === '+')
@@ -2086,6 +2311,9 @@ export class Stepper {
2086
2311
  if (fx.e === 'get') {
2087
2312
  const [o, q1] = this.ev(fx.x, q);
2088
2313
  q = q1;
2314
+ const ord = this.orderedObj(o, q);
2315
+ if (ord)
2316
+ return this.listCall(ord[0], ord[1], String(fx.f), x, q);
2089
2317
  if (o.t === 'ref' && q.heap.get(o.id)?.k === 'map')
2090
2318
  return this.dictCall(o, String(fx.f), x, q);
2091
2319
  if (o.t === 'ref' && q.heap.get(o.id)?.k === 'store')
@@ -2232,9 +2460,17 @@ export class Stepper {
2232
2460
  }
2233
2461
  builtin(n, x, p) {
2234
2462
  const a0 = x.args[0];
2235
- // int(x / k): truncated toward zero.
2463
+ // min or max of a collection of the state (a list's items by a key, a dict's keys): its least key.
2464
+ if ((n === 'min' || n === 'max') && (a0?.e === 'get' || a0?.e === 'var')) {
2465
+ const r = this.minMax(n, x, p);
2466
+ if (r)
2467
+ return r;
2468
+ }
2469
+ // int(x / k): truncated toward zero; round(x / k): to the nearest, a half to the even one (Python's round).
2236
2470
  if (n === 'int' && a0?.e === 'bin' && a0.op === '/')
2237
2471
  return this.quotient(a0, p, 'trunc');
2472
+ if (n === 'round' && a0?.e === 'bin' && a0.op === '/' && x.args.length === 1 && !x.kw.length)
2473
+ return this.quotient(a0, p, 'even');
2238
2474
  return this.evArgs(x, p, (args, kw, q) => {
2239
2475
  if (kw.length)
2240
2476
  return refuse(x, `${x.text}: ${n} given keywords`);
@@ -2256,6 +2492,11 @@ export class Stepper {
2256
2492
  const e = this.numOf(v, x, q);
2257
2493
  return [{ t: 'num', e: I.nite(I.cmp('<', e, I.num(0)), I.neg(e), e) }, q];
2258
2494
  }
2495
+ // (round of a whole number, an int or a float at a whole value: itself)
2496
+ case 'round':
2497
+ if (args.length === 1 && v?.t === 'num')
2498
+ return [v, q];
2499
+ break;
2259
2500
  case 'int':
2260
2501
  case 'float':
2261
2502
  if (v?.t === 'str')
@@ -2263,7 +2504,7 @@ export class Stepper {
2263
2504
  if (v?.t === 'bool')
2264
2505
  return [{ t: 'num', e: I.nite(v.e, I.num(1), I.num(0)) }, q];
2265
2506
  return [{ t: 'num', e: this.numOf(v ?? { t: 'num', e: I.num(0) }, x, q) }, q];
2266
- case 'bool': return [{ t: 'bool', e: v ? this.truthy(v, x) : I.F }, q];
2507
+ case 'bool': return [{ t: 'bool', e: v ? this.truthy(v, x, q) : I.F }, q];
2267
2508
  case 'str':
2268
2509
  if (v?.t === 'str')
2269
2510
  return [v, q];
@@ -2273,6 +2514,8 @@ export class Stepper {
2273
2514
  return refuse(x, `${x.text}: ${n}() (a builtin outside the subset)`);
2274
2515
  });
2275
2516
  }
2517
+ // (even: Python's round(a / k), the nearest whole number, a half to the even one: exact for |a| below 2^53, where the
2518
+ // float a / k is within half its last place of a / k, so it lands on a half only where a / k is one)
2276
2519
  quotient(d, p, round) {
2277
2520
  const [a, q] = this.ev(d.x, p), [b, q2] = this.ev(d.y, q), k = constOf(b);
2278
2521
  if (k === undefined)
@@ -2283,6 +2526,11 @@ export class Stepper {
2283
2526
  }
2284
2527
  const n = this.numOf(a, d, q2), fl = this.floorDiv(n, k), ce = I.neg(this.floorDiv(I.neg(n), k));
2285
2528
  const lt = k > 0 ? I.cmp('<', n, I.num(0)) : I.cmp('<', I.num(0), n);
2529
+ if (round === 'even') {
2530
+ // (r = a − k·⌊a/k⌋: below half of k the floor, past it one more, at it the even of the two)
2531
+ const r2 = I.mulk(2, I.sub(n, I.mulk(k, fl))), half = I.num(k), below = k > 0 ? I.cmp('<', r2, half) : I.cmp('<', half, r2), above = k > 0 ? I.cmp('<', half, r2) : I.cmp('<', r2, half);
2532
+ return [{ t: 'num', e: I.nite(below, fl, I.nite(above, I.add(fl, I.num(1)), I.add(fl, I.sub(fl, I.mulk(2, I.divk(2, fl)))))) }, q2];
2533
+ }
2286
2534
  return [{ t: 'num', e: round === 'floor' ? fl : round === 'ceil' ? ce : I.nite(lt, ce, fl) }, q2];
2287
2535
  }
2288
2536
  lib(q0, x, p) {
@@ -3501,11 +3749,22 @@ function readOnce(mod, opts, g) {
3501
3749
  return;
3502
3750
  }
3503
3751
  }
3752
+ // A list of records or numbers the constructor makes empty: an ordered collection, a map keyed by each item's place
3753
+ // in the list's order (MapDecl.ordered).
3754
+ if (v.t === 'opaque' && decl?.k === 'list' && /\[\]/.test(v.why) && (decl.of.k === 'rec' || g.scalar(decl.of)?.k === 'num')) {
3755
+ const vt = decl.of, d = g.mapDeclOf(name, { k: 'map', key: { k: 'int' }, val: vt }, at), id = `state:${path.join('.')}`;
3756
+ d.ordered = true;
3757
+ heap.set(id, { k: 'map', decl: d, val: vt, origin: 'state' });
3758
+ leaves.push({ name: d.name, path, kind: 'map', key: 'num', ordered: 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 } : {}) });
3759
+ into.set(f, { t: 'ref', id });
3760
+ 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)`);
3761
+ return;
3762
+ }
3504
3763
  if (v.t === 'opaque' && decl?.k === 'map' && /\{\}/.test(v.why)) {
3505
3764
  const d = g.mapDeclOf(name, decl, at), id = `state:${path.join('.')}`;
3506
3765
  const vt = decl.val;
3507
3766
  heap.set(id, { k: 'map', decl: d, val: vt, origin: 'state' });
3508
- 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 } : {}) })) } : vt.k === 'float' ? { float: true } : {}) });
3767
+ 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 } : {}) });
3509
3768
  into.set(f, { t: 'ref', id });
3510
3769
  return;
3511
3770
  }
@@ -3835,6 +4094,7 @@ function readOnce(mod, opts, g) {
3835
4094
  name: cls ? g.rec(cls, at).short : names.length === 1 ? names[0] : mod.module.split('.').pop(), shape: 'class', file: mod.file, entry: cls ? g.rec(cls, at).short : names.join(', '),
3836
4095
  params: g.params, inputs, state, maps, init, writes, mapWrites, outputs,
3837
4096
  refuse: refuseB, pre, layout, events, notes: [...g.notes], hints: g.hints, ...(ev ? { event: ev.name } : {}), results, laws,
4097
+ ...(g.leasts.length ? { leasts: g.leasts } : {}),
3838
4098
  };
3839
4099
  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 } : {}) };
3840
4100
  }
@@ -4093,7 +4353,7 @@ export function stepNames(read) {
4093
4353
  for (const l of read.leaves) {
4094
4354
  const code = l.path.join('.');
4095
4355
  if (l.kind === 'map')
4096
- out.push({ code: l.store ?? code, rule: l.name, role: 'state', map: { fields: m.maps.find(d => d.name === l.name)?.fields.map(f => f.name) ?? [], ...(l.store ? { store: l.store, tpl: l.tpl ?? '{}' } : {}) } });
4356
+ out.push({ code: l.store ?? code, rule: l.name, role: 'state', map: { fields: m.maps.find(d => d.name === l.name)?.fields.map(f => f.name) ?? [], ...(l.store ? { store: l.store, tpl: l.tpl ?? '{}' } : {}), ...(l.ordered ? { ordered: true } : {}) } });
4097
4357
  else if (l.kind === 'none') {
4098
4358
  const n = at(code);
4099
4359
  if (n)
@@ -40,6 +40,7 @@ export type Name = {
40
40
  fields: string[];
41
41
  store?: string;
42
42
  tpl?: string;
43
+ ordered?: boolean;
43
44
  };
44
45
  };
45
46
  export declare function namesOf(m: Model): Name[];
@@ -42,7 +42,7 @@ import { compileFunction, walk } from "./machine.js";
42
42
  import * as I from "./extract-ir.js";
43
43
  import { Refusal, placed, sourceOf } from "./extract-read.js";
44
44
  import { isFactory, isSlice, readClass, readFactory, readFunctions, readSlice } from "./extract-shapes.js";
45
- import { kindOf, mapEmpty, mapKind, natOK, pb, pidx, pk, pterm, sortsOf } from "./extract-print.js";
45
+ import { kindOf, mapEmpty, mapKind, natOK, pb, pidx, pk, pnum, pterm, sortsOf } from "./extract-print.js";
46
46
  import { check } from "./extract-check.js";
47
47
  // (a rule read is proven from the same import: proveRule(x.rule!, [x.rule!.law(...)]))
48
48
  export { proveRule, proveSteps } from "./dsl.js";
@@ -197,7 +197,7 @@ function datesInRange(m, sorts) {
197
197
  // The module a user keeps: the rule, with what it was read from and how it was checked.
198
198
  export const toSource = (x) => x.source ?? '';
199
199
  // The source is the rule: it is evaluated with the builders, so what is checked is what is printed.
200
- const NAMES = ['rule', 'nat', 'int', 'bool', 'oneOf', 'str', 'record', 'when', 'min', 'max', 'all', 'any', 'not', 'yes', 'no', 'lit', 'intern', 'Int'];
200
+ const NAMES = ['rule', 'nat', 'int', 'bool', 'oneOf', 'str', 'record', 'when', 'min', 'max', 'all', 'any', 'not', 'yes', 'no', 'lit', 'intern', 'Int', 'desc'];
201
201
  function evaluate(body) {
202
202
  const f = compileFunction([...NAMES], `return ${body}`);
203
203
  const r = f(...NAMES.map(n => dsl[n]));
@@ -209,7 +209,7 @@ function invariantsOf(m, sorts) {
209
209
  const empty = (d, f) => (f.sort.k === 'num' ? `.eq(0)` : f.sort.k === 'bool' ? `.not()` : f.sort.k === 'choice' ? `.is(${JSON.stringify(f.sort.values[0])})` : `.eq('')`);
210
210
  // (a signed field the printer reads as a natural keeps its range's top: a natural is at least 0 already)
211
211
  const nat = (l) => { const r = /^r\.law\(("\w+ within its type's range"), \(\{(\w+)\}\) => \2\.atMost\((\d+)\)\.and\(\2\.atLeast\(-\d+\)\)\)$/.exec(l); return r && sorts.get(r[2]) === 'nat' ? `r.law(${r[1]}, ({${r[2]}}) => ${r[2]}.atMost(${r[3]}))` : l; };
212
- return [...(m.laws ?? []).map(nat), ...m.maps.filter(d => d.fields.length).map(d => `r.law(${JSON.stringify(`${d.name}: a key it doesn't hold holds the defaults`)}, ({${d.name}}) => forall(k => any(${d.name}.at(k).has, all(${d.fields.map(f => `${d.name}.at(k).${f.name}${empty(d, f)}`).join(', ')}))))`),
212
+ return [...(m.laws ?? []).map(nat), ...m.maps.filter(d => d.fields.length && !d.ordered).map(d => `r.law(${JSON.stringify(`${d.name}: a key it doesn't hold holds the defaults`)}, ({${d.name}}) => forall(k => any(${d.name}.at(k).has, all(${d.fields.map(f => `${d.name}.at(k).${f.name}${empty(d, f)}`).join(', ')}))))`),
213
213
  ...(m.lists ?? []).map(d => `r.law(${JSON.stringify(`${d.name}: nothing past its end`)}, ({${d.name}}) => ${d.name}.within())`),
214
214
  ...(m.lists ?? []).filter(d => d.len !== undefined).map(d => `r.law(${JSON.stringify(`${d.name}: ${d.len} items, always`)}, ({${d.name}_len}) => ${d.name}_len.eq(${d.len}))`)];
215
215
  }
@@ -264,12 +264,19 @@ function builderOf(m, sorts) {
264
264
  lines.push(` .maps({${m.maps.map((d) => `${d.name}: ${mapKind(d, sorts)}.from(${mapEmpty(d)})`).join(', ')}})`);
265
265
  if (m.lists?.length)
266
266
  lines.push(` .items({${m.lists.map(d => `${d.name}: ${kindOf(d.fields[0], sorts, `${d.name}.$item`)}`).join(', ')}}${m.lists.some(d => d.len !== undefined) ? `, {${m.lists.filter(d => d.len !== undefined).map(d => `${d.name}: ${d.len}`).join(', ')}}` : ''})`);
267
+ // (a least key's two names are its one Maybe; the key its order is read at is bound by its own function)
268
+ const leastOf = (n) => m.leasts?.find(l => l.some === n)?.name ?? n;
267
269
  const envOf = (...xs) => {
268
270
  const vars = new Set(), maps = new Set();
269
271
  for (const x of xs)
270
272
  I.varsOf(x, vars, maps);
271
- return `{${[...vars, ...maps].join(', ')}}`;
273
+ return `{${[...new Set([...vars].filter(n => !m.leasts?.some(l => l.key === n)).map(leastOf)), ...maps].join(', ')}}`;
272
274
  };
275
+ // The least keys: each where it holds, by what, read at the state before the step.
276
+ if (m.leasts?.length) {
277
+ const c = ctx();
278
+ lines.push(` .least({${m.leasts.map(l => `${l.name}: (${envOf(l.where, ...l.by.map(b => b.e))}) => ({where: ${l.key} => ${pb(l.where, P, c)}, by: ${l.key} => [${l.by.map(b => (b.desc ? `desc(${pnum(b.e, P, c)})` : pnum(b.e, P, c))).join(', ')}]})`).join(', ')}})`);
279
+ }
273
280
  if (!(m.pre.op === 'const' && m.pre.v))
274
281
  lines.push(` .pre((${envOf(m.pre)}) => ${pb(m.pre, P, ctx())})`);
275
282
  const allowed = I.not(m.refuse);
@@ -321,7 +328,7 @@ const isBool = (x, m) => {
321
328
  if (o.op === 'ite')
322
329
  return isBool(o.a, m) || isBool(o.b, m);
323
330
  if (o.op === 'var' && m)
324
- return [...m.params, ...m.inputs, ...m.state].some(v => v.name === o.name && v.sort.k === 'bool');
331
+ return [...m.params, ...m.inputs, ...m.state].some(v => v.name === o.name && v.sort.k === 'bool') || !!m.leasts?.some(l => l.some === o.name);
325
332
  if (o.op === 'cell' && m)
326
333
  return o.field === 'has' || !!m.maps.find(d => d.name === o.map)?.fields.some(f => f.name === o.field && f.sort.k === 'bool');
327
334
  return false;
package/dist/core/laws.js CHANGED
@@ -22,6 +22,9 @@
22
22
  // counts[user] < limit, user in m a map at a key as the code reads it (m.get(k), k in m, m[k] is None)
23
23
  // cache["hits:" + s] <= limit a store at its key's template ("hits:" + s, f"hits:{s}")
24
24
  // forall k in budgets: budgets[k].spent <= budgets[k].limit every key the map holds (at the top of the law)
25
+ // forall o in old(asks): forall j in old(asks): o in asks or o.price <= j.price
26
+ // every item of a list (o.price its field; `o in asks` whether that item is still
27
+ // in it, the same item, not an equal one), at every two (or three) at once
25
28
  // mode == "closed", outcome == SLOW_ERROR, mode == :closed a choice by its value
26
29
  import { Choice, Int, Str, Term, all, any, forall, no, not, yes } from "./dsl.js";
27
30
  import { agreement, isolation, noninterference } from "./relational.js";
@@ -262,14 +265,38 @@ export function buildLaw(x, l, opts = {}) {
262
265
  // The expression read: its value (`dry`: only which names it reads, nothing built).
263
266
  function read(e, c, names, dry) {
264
267
  if (e.k === 'forall') {
265
- const over = val(e.over, c, names, dry);
266
- if (over.t !== 'map')
267
- throw new LawError(`forall ${e.v} in ...: over a map (a dict, a Map, a hash)`);
268
+ // (forall a in X: forall b in Y: ...: at every two keys at once, each held by its map)
269
+ const chain = [];
270
+ let body = e;
271
+ while (body.k === 'forall') {
272
+ chain.push(body);
273
+ body = body.body;
274
+ }
275
+ if (chain.length > 3)
276
+ throw new LawError('forall ... in ...: at most three at once');
277
+ c.items ??= new Map();
278
+ const overs = chain.map(f => {
279
+ const over = val(f.over, c, names, dry);
280
+ if (over.t !== 'map')
281
+ throw new LawError(`forall ${f.v} in ...: over a map (a dict, a Map, a hash) or a list`);
282
+ return { over, env: f.over.k === 'old' || !c.step ? c.b : c.a };
283
+ });
268
284
  if (dry) {
269
- c.keys.set(e.v, new Term({ op: 'const', value: 0 }));
270
- return cond(val(e.body, c, names, true));
285
+ for (const f of chain)
286
+ c.keys.set(f.v, new Term({ op: 'const', value: 0 }));
287
+ return cond(val(body, c, names, true));
271
288
  }
272
- return forall(k => { c.keys.set(e.v, k); const m = (c.step ? c.a : c.b)[over.n.rule]; return m.at(k).has.implies(cond(val(e.body, c, names, false))); });
289
+ const at = (ks) => {
290
+ const held = overs.map((o, i) => {
291
+ const m = o.env[o.over.n.rule];
292
+ c.keys.set(chain[i].v, ks[i]);
293
+ if (o.over.n.map?.ordered)
294
+ c.items.set(chain[i].v, { map: m.at(ks[i]), fields: o.over.n.map.fields });
295
+ return m.at(ks[i]).has;
296
+ });
297
+ return all(...held).implies(cond(val(body, c, names, false)));
298
+ };
299
+ return chain.length === 1 ? forall(k => at([k])) : chain.length === 2 ? forall((k, j) => at([k, j])) : forall((k, j, i) => at([k, j, i]));
273
300
  }
274
301
  return cond(val(e, c, names, dry));
275
302
  }
@@ -422,6 +449,12 @@ function cellOf(m, k, c) {
422
449
  function path(e, c, names, dry) {
423
450
  if (c.keys.has(e.head) && !e.segs.length)
424
451
  return { t: 'key', v: c.keys.get(e.head) };
452
+ // (an item of a list a forall is over: its fields)
453
+ const item = c.items?.get(e.head);
454
+ if (item && e.segs.length)
455
+ return dry ? DRY : rest(e.segs, { t: 'cell', rec: item.map, fields: item.fields }, c, names, dry, e);
456
+ if (c.keys.has(e.head) && dry)
457
+ return DRY;
425
458
  if (e.head === 'result' || e.head === 'failed') {
426
459
  const n = e.head === 'failed' ? names.find(x => x.role === 'failed') : results(names, c);
427
460
  if (!n)
@@ -1,4 +1,4 @@
1
- import { type Law, type Machine, type Rand, type Request } from './machine.js';
1
+ import { type C, type E, type Law, type Machine, type Rand, type Request } from './machine.js';
2
2
  import { type Liveness } from '../kernel/kernel.js';
3
3
  import { type LeadsVerdict } from './cycles.js';
4
4
  import { inferLaws } from './infer.js';
@@ -12,4 +12,25 @@ export type Draws = {
12
12
  export declare function leadsByTerms(m: Machine, laws: Law[], l: Liveness, draws: Draws, opts?: {
13
13
  ms?: number;
14
14
  }): LeadsVerdict;
15
+ export type Ring = {
16
+ params: Env;
17
+ stem: Request[];
18
+ sets: {
19
+ holds: C;
20
+ request: Record<string, E>;
21
+ }[];
22
+ };
23
+ export type Fairness = 'taken' | 'weak' | 'strong';
24
+ export type RingVerdict = {
25
+ refuted: boolean;
26
+ fair?: Fairness[];
27
+ why?: string;
28
+ };
29
+ export declare function refutedBy(m: Machine, laws: Law[], l: Liveness, ring: Ring): RingVerdict;
30
+ export declare function findRing(m: Machine, laws: Law[], l: Liveness, draws: Draws, opts?: {
31
+ ms?: number;
32
+ }): {
33
+ ring: Ring;
34
+ verdict: RingVerdict;
35
+ } | undefined;
15
36
  export {};