gdp-wired 0.33.1 → 0.35.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.
@@ -13,6 +13,7 @@ export declare function sortsOf(m: Model, given?: Record<string, 'nat' | 'int'>)
13
13
  sorts: Sorts;
14
14
  notes: string[];
15
15
  };
16
+ export declare const leastName: (m: Model, n: string) => string;
16
17
  export type Printer = {
17
18
  sorts: Sorts;
18
19
  m: Model;
@@ -229,6 +229,11 @@ export function sortsOf(m, given = {}) {
229
229
  const cellNums = m.maps.flatMap(d => d.fields.filter(f => f.sort.k === 'num').map(f => `${d.name}.${f.name}`));
230
230
  for (const v of nums(m.state))
231
231
  sorts.set(v.name, given[v.name] ?? 'nat');
232
+ // (a least key, and the key its order is read at: naturals, a map's keys)
233
+ for (const l of m.leasts ?? []) {
234
+ sorts.set(l.name, 'nat');
235
+ sorts.set(l.key, 'nat');
236
+ }
232
237
  for (const c of cellNums)
233
238
  sorts.set(c, given[c] ?? 'nat');
234
239
  // A list's length is a natural; its items naturals until one written may be below 0.
@@ -289,6 +294,12 @@ function refusedBelowZero(m, x, ctx) {
289
294
  return refutes([...linCond(I.not(own[0]), ctx), ...lt(lv(x), lk(0))]);
290
295
  }));
291
296
  }
297
+ // --- printing -------------------------------------------------------------------------------------------------------
298
+ // A least key's names as the printed rule reads them: the key `<name>.inner`, whether there is one `<name>.isSome`.
299
+ export const leastName = (m, n) => {
300
+ const l = m.leasts?.find(x => x.name === n || x.some === n);
301
+ return !l ? n : l.name === n ? `${n}.inner` : `${l.name}.isSome`;
302
+ };
292
303
  const q = (s) => `'${s.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
293
304
  function pn(e, P, ctx, mode, recv = false) {
294
305
  const h = P.hoisted.get(I.keyOf(e));
@@ -297,7 +308,10 @@ function pn(e, P, ctx, mode, recv = false) {
297
308
  const nat = mode === 'nat';
298
309
  const R = (x, c = ctx) => pn(x, P, c, nat ? 'nat' : 'int', true), A = (x, c = ctx) => pn(x, P, c, nat || natOK(x, c) ? 'nat' : 'int');
299
310
  switch (e.op) {
300
- case 'var': return !nat && recv && P.sorts.get(e.name) === 'nat' ? `Int.of(${e.name})` : e.name;
311
+ case 'var': {
312
+ const n = leastName(P.m, e.name);
313
+ return !nat && recv && P.sorts.get(e.name) === 'nat' ? `Int.of(${n})` : n;
314
+ }
301
315
  case 'const': return recv ? (nat ? `lit(${e.v})` : `Int.of(${e.v})`) : String(e.v);
302
316
  case 'add': return e.a.op === 'const' ? `${R(e.b)}.plus(${A(e.a)})` : `${R(e.a)}.plus(${A(e.b)})`;
303
317
  case 'sub': return `${R(e.a)}.minus(${A(e.b)})`;
@@ -354,7 +368,7 @@ export function pb(c, P, ctx) {
354
368
  return h;
355
369
  switch (c.op) {
356
370
  case 'const': return c.v ? 'yes' : 'no';
357
- case 'var': return c.name;
371
+ case 'var': return leastName(P.m, c.name);
358
372
  case 'cmp': return pcmp(c.rel, c.a, c.b, P, ctx);
359
373
  case 'and': return `all(${c.xs.map(x => pb(x, P, ctx)).join(', ')})`;
360
374
  case 'or': return `any(${c.xs.map(x => pb(x, P, ctx)).join(', ')})`;
@@ -47,6 +47,18 @@ export type MapDecl = {
47
47
  js: 'Map' | 'record' | 'Set';
48
48
  untyped?: boolean;
49
49
  len?: number;
50
+ ordered?: true;
51
+ };
52
+ export type LeastRead = {
53
+ name: string;
54
+ some: string;
55
+ map: string;
56
+ key: string;
57
+ where: B;
58
+ by: {
59
+ e: N;
60
+ desc?: boolean;
61
+ }[];
50
62
  };
51
63
  export type Layout = {
52
64
  k: 'scalar';
@@ -181,6 +193,7 @@ export type Model = {
181
193
  fnFields?: string[];
182
194
  imports?: string[];
183
195
  kind?: string;
196
+ leasts?: LeastRead[];
184
197
  };
185
198
  type V = {
186
199
  t: 'num';
@@ -1,6 +1,6 @@
1
1
  import * as I from './extract-ir.js';
2
2
  import type { B, K, L, N } from './extract-ir.js';
3
- import { type MapDecl, type Model, Refusal, type Term, type Var } from './extract-read.js';
3
+ import { type LeastRead, type MapDecl, type Model, Refusal, type Term, type Var } from './extract-read.js';
4
4
  import { type Extraction, type Name } from './extract.js';
5
5
  import type { Rule } from './dsl.js';
6
6
  import { type Sorts } from './extract-print.js';
@@ -374,10 +374,12 @@ export type Leaf = {
374
374
  fields?: {
375
375
  name: string;
376
376
  float?: boolean;
377
+ choice?: boolean;
377
378
  }[];
378
379
  key?: 'num' | 'str';
379
380
  store?: string;
380
381
  tpl?: string;
382
+ ordered?: boolean;
381
383
  };
382
384
  export type PArg = {
383
385
  k: 'in';
@@ -487,6 +489,7 @@ export declare class Stepper {
487
489
  id: string;
488
490
  decl: MapDecl;
489
491
  }>;
492
+ readonly leasts: LeastRead[];
490
493
  frames: string[];
491
494
  fieldNames: Set<string>;
492
495
  readonly frozen: Set<string>;
@@ -580,6 +583,46 @@ export declare class Stepper {
580
583
  mapDeclOf(name: string, t: SType, at: {
581
584
  p: string;
582
585
  }): MapDecl;
586
+ literalsOf(r: SRec, field: string): string[] | undefined;
587
+ least(o: Extract<Obj, {
588
+ k: 'map';
589
+ }>, at: SX, where: (k: K) => B, by: (k: K) => {
590
+ e: N;
591
+ desc?: boolean;
592
+ }[]): {
593
+ key: N;
594
+ some: B;
595
+ held: B;
596
+ where: (k: K) => B;
597
+ };
598
+ holds(p: Path, c: B): boolean;
599
+ orderedObj(m: V, p: Path): [string, Extract<Obj, {
600
+ k: 'map';
601
+ }>] | undefined;
602
+ item(id: string, o: Extract<Obj, {
603
+ k: 'map';
604
+ }>, at: SX, last: boolean, by?: (k: K) => {
605
+ e: N;
606
+ desc?: boolean;
607
+ }[]): {
608
+ key: K;
609
+ some: B;
610
+ held: B;
611
+ v: V;
612
+ };
613
+ listCall(id: string, o0: Extract<Obj, {
614
+ k: 'map';
615
+ }>, name: string, x: SX, p: Path): [V, Path];
616
+ listDel(id: string, o: Extract<Obj, {
617
+ k: 'map';
618
+ }>, key: K, at: SX, p: Path): Path;
619
+ recOf(d: MapDecl, at: SX): SRec;
620
+ fieldOf(v: V, f: string, at: SX, p: Path): V;
621
+ minMax(n: 'min' | 'max', x: SX, p: Path): [V, Path] | undefined;
622
+ emptyOr(n: string, v: V, l: {
623
+ some: B;
624
+ held: B;
625
+ }, d: V | undefined, x: SX, p: Path): [V, Path];
583
626
  storeMap(store: string, tpl: string, kn: boolean, at: SX, p: Path): [string, Extract<Obj, {
584
627
  k: 'map';
585
628
  }>];
@@ -648,7 +691,7 @@ export declare class Stepper {
648
691
  dictCall(m: V, name: string, x: SX, p: Path): [V, Path];
649
692
  construct(rec: string, args: V[], kw: [string, V][], x: SX, p: Path): [V, Path];
650
693
  builtin(n: string, x: SX, p: Path): [V, Path];
651
- quotient(d: SX, p: Path, round: 'floor' | 'ceil' | 'trunc'): [V, Path];
694
+ quotient(d: SX, p: Path, round: 'floor' | 'ceil' | 'trunc' | 'even'): [V, Path];
652
695
  lib(q0: string, x: SX, p: Path): [V, Path];
653
696
  readonly edges: B[];
654
697
  readonly lists: MapDecl[];
@@ -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;