gdp-wired 0.24.0 → 0.26.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.
Files changed (52) hide show
  1. package/README.md +14 -9
  2. package/dist/core/accel.d.ts +44 -0
  3. package/dist/core/accel.js +955 -0
  4. package/dist/core/bmc.d.ts +8 -0
  5. package/dist/core/bmc.js +263 -97
  6. package/dist/core/cycles.d.ts +2 -3
  7. package/dist/core/cycles.js +409 -174
  8. package/dist/core/cyclic.d.ts +4 -1
  9. package/dist/core/cyclic.js +86 -64
  10. package/dist/core/data.d.ts +9 -1
  11. package/dist/core/data.js +872 -168
  12. package/dist/core/discover.js +2 -3
  13. package/dist/core/dsl.d.ts +3 -2
  14. package/dist/core/dsl.js +21 -18
  15. package/dist/core/exists.js +7 -14
  16. package/dist/core/extract-check.d.ts +3 -2
  17. package/dist/core/extract-check.js +137 -50
  18. package/dist/core/extract-print.d.ts +1 -0
  19. package/dist/core/extract-print.js +26 -3
  20. package/dist/core/extract-read.d.ts +85 -4
  21. package/dist/core/extract-read.js +295 -34
  22. package/dist/core/extract-shapes.d.ts +14 -0
  23. package/dist/core/extract-shapes.js +608 -78
  24. package/dist/core/extract-xstate.d.ts +5 -1
  25. package/dist/core/extract-xstate.js +618 -184
  26. package/dist/core/extract.js +73 -27
  27. package/dist/core/infer.d.ts +1 -0
  28. package/dist/core/infer.js +364 -40
  29. package/dist/core/machine.d.ts +6 -0
  30. package/dist/core/machine.js +35 -3
  31. package/dist/core/nonterm.d.ts +9 -2
  32. package/dist/core/nonterm.js +173 -9
  33. package/dist/core/q.d.ts +1 -0
  34. package/dist/core/q.js +2 -2
  35. package/dist/core/relation.d.ts +1 -0
  36. package/dist/core/relation.js +95 -39
  37. package/dist/core/solver.d.ts +12 -0
  38. package/dist/core/solver.js +76 -30
  39. package/dist/core/transfer.js +23 -14
  40. package/dist/core/translate.d.ts +1 -1
  41. package/dist/core/translate.js +22 -49
  42. package/dist/core/xstate.d.ts +6 -1
  43. package/dist/core/xstate.js +336 -55
  44. package/dist/kernel/cdcl.d.ts +5 -0
  45. package/dist/kernel/cdcl.js +44 -8
  46. package/dist/kernel/prove.d.ts +6 -1
  47. package/dist/kernel/prove.js +101 -85
  48. package/dist/kernel/reader.d.ts +1 -0
  49. package/dist/kernel/reader.js +4 -3
  50. package/dist/kernel/simplex.d.ts +1 -1
  51. package/dist/kernel/simplex.js +13 -1
  52. package/package.json +3 -2
@@ -45,6 +45,15 @@ function build(ex, shape, path, heap, origin, at) {
45
45
  heap.set(id, { k: 'map', base: decl.name, decl, origin, gen: 0 });
46
46
  return { layout: { k: 'map', name: decl.name }, v: { t: 'ref', id } };
47
47
  }
48
+ case 'list': {
49
+ // An array: a list of its items (`<name>.$item`) and its length (`<name>_len`).
50
+ const decl = { name: ex.fresh(name), key: 'num', fields: [{ name: '$item', sort: shape.of, role: 'state' }], scalar: true, js: 'Map' };
51
+ ex.fresh(`${decl.name}_len`);
52
+ (ex.s.lists ??= new Map()).set(decl.name, decl);
53
+ const id = `${origin}.${path.join('.')}`;
54
+ heap.set(id, { k: 'list', base: decl.name, decl, ops: [], origin });
55
+ return { layout: { k: 'list', name: decl.name }, v: { t: 'ref', id } };
56
+ }
48
57
  }
49
58
  }
50
59
  function mapDecl(ex, shape, name, at) {
@@ -75,6 +84,8 @@ function materialize(ex, v, layout, p, at, out = { leaves: new Map(), maps: new
75
84
  out.leaves.set(n, x);
76
85
  for (const [n, w] of both.maps)
77
86
  out.maps.set(n, w);
87
+ for (const [n, w] of both.lists ?? [])
88
+ (out.lists ??= new Map()).set(n, w);
78
89
  return out;
79
90
  }
80
91
  switch (layout.k) {
@@ -117,6 +128,13 @@ function materialize(ex, v, layout, p, at, out = { leaves: new Map(), maps: new
117
128
  out.maps.set(layout.name, o.w);
118
129
  return out;
119
130
  }
131
+ case 'list': {
132
+ const o = v.t === 'ref' ? p.heap.get(v.id) : undefined;
133
+ if (o?.k !== 'list' || o.base !== layout.name)
134
+ return refuse(at, `${layout.name} is set to other than a copy of itself (an array replaced whole, or one array in two places)`);
135
+ (out.lists ??= new Map()).set(layout.name, o.ops);
136
+ return out;
137
+ }
120
138
  case 'const': return out;
121
139
  }
122
140
  }
@@ -132,7 +150,11 @@ function split(a, b) {
132
150
  function mergeVals(ex, c, a, b, at) {
133
151
  const leaves = new Map([...a.leaves].map(([n, v]) => [n, ex.mergeScalar(c, v, b.leaves.get(n), at)]));
134
152
  const maps = new Map([...a.maps].map(([n, w]) => [n, ex.mergeWrites(c, ex.s.maps.get(n), w, b.maps.get(n), at)]));
135
- return { leaves, maps };
153
+ // A list's write by cases: each side's under its condition.
154
+ const lists = new Map();
155
+ for (const n of new Set([...(a.lists?.keys() ?? []), ...(b.lists?.keys() ?? [])]))
156
+ lists.set(n, [...(a.lists?.get(n) ?? []).map(o => ({ ...o, when: I.and(c, o.when) })), ...(b.lists?.get(n) ?? []).map(o => ({ ...o, when: I.and(I.not(c), o.when) }))]);
157
+ return { leaves, maps, ...(lists.size ? { lists } : {}) };
136
158
  }
137
159
  // Every way a step ends (each a path and its state), as one state by cases.
138
160
  function joinAll(ex, outs, at) {
@@ -149,7 +171,7 @@ function joinAll(ex, outs, at) {
149
171
  const termOf = (v) => (v.t === 'num' ? { s: 'num', e: v.e } : v.t === 'bool' ? { s: 'bool', e: v.e } : v.t === 'choice' ? { s: 'choice', e: v.e } : v.t === 'str' ? { s: 'str', e: v.e } : (() => { throw new Error(`a ${v.t} as a term`); })());
150
172
  const sameTerm = (a, b) => (a.t === 'num' || a.t === 'bool' || a.t === 'choice' || a.t === 'str') && (b.t === 'num' || b.t === 'bool' || b.t === 'choice' || b.t === 'str') && I.same(a.e, b.e);
151
173
  const refusalOf = (ex) => I.or(...ex.throws.map(t => I.and(...t.pc)));
152
- const EMPTY = Symbol('an empty map');
174
+ const EMPTY = Symbol('an empty map'), EMPTY_LIST = Symbol('an empty array');
153
175
  function constValue(e, s) {
154
176
  if (ts.isParenthesizedExpression(e) || ts.isAsExpression(e) || ts.isSatisfiesExpression(e))
155
177
  return constValue(e.expression, s);
@@ -196,7 +218,7 @@ function constValue(e, s) {
196
218
  return constValue(prop.initializer, s);
197
219
  }
198
220
  if (ts.isArrayLiteralExpression(e))
199
- return refuse(e, 'an array (lists are not in the subset yet)');
221
+ return e.elements.length ? refuse(e, 'an array that starts with items (a list starts empty in the subset)') : EMPTY_LIST;
200
222
  if (ts.isIdentifier(e)) {
201
223
  const decl = aliased(s, e)?.valueDeclaration;
202
224
  if (decl && ts.isVariableDeclaration(decl) && decl.initializer && decl.parent.flags & ts.NodeFlags.Const)
@@ -249,6 +271,10 @@ function initLeaves(raw, layout, s, at, out = {}) {
249
271
  if (raw !== EMPTY && !(typeof raw === 'object' && raw !== null && !Object.keys(raw).length) && !(raw instanceof Map && !raw.size))
250
272
  refuse(at, `${layout.name} starts with entries (a map starts empty in the subset)`);
251
273
  return out;
274
+ case 'list':
275
+ if (raw !== EMPTY_LIST && !(Array.isArray(raw) && !raw.length))
276
+ refuse(at, `${layout.name} starts with items (a list starts empty in the subset)`);
277
+ return out;
252
278
  case 'const': return out;
253
279
  }
254
280
  }
@@ -378,8 +404,8 @@ function argOf(ex, param, prefix, body) {
378
404
  heap.push([id, { k: 'rec', fields, origin: 'input' }]);
379
405
  return { t: 'ref', id };
380
406
  }
381
- if (sh.k === 'map')
382
- return refuse(param, `${pname}.${path.join('.')}: a map in a request`);
407
+ if (sh.k === 'map' || sh.k === 'list')
408
+ return refuse(param, `${pname}.${path.join('.')}: a ${sh.k === 'map' ? 'map' : 'list'} in a request`);
383
409
  const key = path.join('_');
384
410
  let sort = sh;
385
411
  // A string field compared with literals (an action's `type: string`): a choice among them, and any other.
@@ -442,8 +468,13 @@ function readFunctionsOnce(code, file, opts) {
442
468
  for (const d of stmt.declarationList.declarations)
443
469
  if (ts.isIdentifier(d.name) && d.name.text === 'initialState' && d.initializer)
444
470
  initExpr = d.initializer;
445
- if (!initExpr)
471
+ if (!initExpr) {
472
+ // A function whose result is not of its first argument's type takes no state to step: name what it is.
473
+ const sig = s.checker.getSignatureFromDeclaration(first), rt = sig && s.checker.getReturnTypeOfSignature(sig), st0 = s.checker.getTypeAtLocation(sp);
474
+ if (rt && !(st0.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) && !s.checker.isTypeAssignableTo(rt, st0))
475
+ refuse(first, `${names[0]} is not a step over a state (a step takes the state first and returns the next): it takes ${s.checker.typeToString(st0).slice(0, 60)} and returns ${s.checker.typeToString(rt).slice(0, 60)}`);
446
476
  refuse(sp, 'no initial state: a default parameter, useReducer(reducer, initial), a const initialState, or init');
477
+ }
447
478
  raw = constValue(initExpr, s);
448
479
  initSource = initExpr.getText();
449
480
  }
@@ -537,8 +568,12 @@ function finish(s, m) {
537
568
  for (const [n, w] of m.final.maps)
538
569
  if (w)
539
570
  mapWrites[n] = { key: w.key, has: w.has, vals: Object.fromEntries([...w.vals].map(([f, v]) => [f, termOf(v)])) };
571
+ const listWrites = {};
572
+ for (const [n, ops] of m.final.lists ?? [])
573
+ if (ops.length)
574
+ listWrites[n] = ops.map(o => (o.op === 'pop' ? o : { ...o, x: termOf(o.x) }));
540
575
  return { name: m.name, shape: m.shape, file: m.file, entry: m.entry, params: vars.filter(v => v.role === 'param'), inputs: vars.filter(v => v.role === 'input'), state: vars.filter(v => v.role === 'state'),
541
- maps: [...s.maps.values()], init: m.init, writes, mapWrites, outputs: m.outputs, refuse: m.refuse, pre: m.pre, layout: m.layout, events: m.events, notes: [...s.notes], hints: s.hints,
576
+ maps: [...s.maps.values()], ...(s.lists?.size ? { lists: [...s.lists.values()], listWrites } : {}), init: m.init, writes, mapWrites, outputs: m.outputs, refuse: m.refuse, pre: m.pre, layout: m.layout, events: m.events, notes: [...s.notes], hints: s.hints,
542
577
  ...(m.event ? { event: m.event } : {}), ...(m.ctorArgs ? { ctorArgs: m.ctorArgs } : {}), ...(s.lazy.size ? { lazy: s.lazy } : {}), ...(m.initSource ? { initSource: m.initSource } : {}), ...(s.spans ? { spans: s.spans } : {}) };
543
578
  }
544
579
  // --- classes --------------------------------------------------------------------------------------------------------
@@ -554,6 +589,7 @@ function findClass(sf, name) {
554
589
  return refuse(at0(sf), `no class ${name} in the file`);
555
590
  }
556
591
  const has = (n, k) => !!(ts.canHaveModifiers(n) && ts.getModifiers(n)?.some(m => m.kind === k));
592
+ const isEmptyArray = (e) => !!e && ((ts.isArrayLiteralExpression(e) && !e.elements.length) || ((ts.isAsExpression(e) || ts.isParenthesizedExpression(e)) && isEmptyArray(e.expression)));
557
593
  const isMapInit = (e) => !!e && ((ts.isNewExpression(e) && ts.isIdentifier(e.expression) && e.expression.text === 'Map' && !e.arguments?.length) || (ts.isObjectLiteralExpression(e) && !e.properties.length) || ((ts.isAsExpression(e) || ts.isParenthesizedExpression(e)) && isMapInit(e.expression)));
558
594
  export function readClass(code, file, opts) {
559
595
  // Read twice: first with every field a state variable, to see which the methods write; then with the others as the
@@ -561,36 +597,77 @@ export function readClass(code, file, opts) {
561
597
  const written = attempt(code, file, opts, new Set()).written;
562
598
  return attempt(code, file, opts, written).model;
563
599
  }
600
+ // The classes a class extends, the most derived first: each one the files read declare (a class made by a call, a
601
+ // mixin, or one from another module is refused where it is named).
602
+ function chainOf(s, cls) {
603
+ const chain = [cls];
604
+ for (let c = cls;;) {
605
+ const h = c.heritageClauses?.find(x => x.token === ts.SyntaxKind.ExtendsKeyword);
606
+ if (!h)
607
+ return chain;
608
+ const e = h.types[0].expression;
609
+ if (!ts.isIdentifier(e) && !ts.isPropertyAccessExpression(e))
610
+ return refuse(h, `extends ${e.getText().slice(0, 60)}: a class a call makes (a mixin), not one the files read declare`);
611
+ let sym = s.checker.getSymbolAtLocation(ts.isPropertyAccessExpression(e) ? e.name : e);
612
+ if (sym && sym.flags & ts.SymbolFlags.Alias)
613
+ sym = s.checker.getAliasedSymbol(sym);
614
+ const decl = sym?.declarations?.find(ts.isClassLike);
615
+ if (!decl)
616
+ return refuse(h, `extends ${e.getText()}: no class of the files read (another module's, or not a class)`);
617
+ if (!s.ours(decl.getSourceFile()))
618
+ return refuse(h, `extends ${e.getText()}, a class from another module (not among the files read)`);
619
+ if (chain.includes(decl))
620
+ return refuse(h, 'a class that extends itself');
621
+ chain.push(decl);
622
+ c = decl;
623
+ }
624
+ }
564
625
  function attempt(code, file, opts, written) {
565
626
  const s = setupOf(code, file, {}, opts.files), cls = findClass(s.sf, opts.entry), first = written.size === 0;
566
627
  s.cls = cls;
567
- // `implements` is a type's only (nothing at run time); `extends` brings another class's fields and methods.
568
- if (cls.heritageClauses?.some(h => h.token === ts.SyntaxKind.ExtendsKeyword))
569
- refuse(cls, 'a class that extends another');
570
- const ctor = cls.members.find(ts.isConstructorDeclaration);
571
- if (ctor)
572
- (s.spans ??= []).push([ctor.getStart(), ctor.end]);
628
+ // `implements` is a type's only (nothing at run time); `extends` brings another class's fields and methods: each
629
+ // member resolved statically, from the entry class up (this.m() the entry's own or the nearest inherited; super.m()
630
+ // the nearest above the class it is written in).
631
+ const chain = chainOf(s, cls);
632
+ s.chain = chain;
633
+ if (chain.length > 1)
634
+ s.notes.add(`${opts.entry} extends ${chain.slice(1).map(c => c.name?.text ?? '(a class)').join(', which extends ')}: its fields and methods are read with them, each method the nearest the object has`);
635
+ const ownCtor = (c) => c.members.find((m) => ts.isConstructorDeclaration(m) && !!m.body);
636
+ // The constructor the object is made with: the entry's, or the nearest it inherits.
637
+ const ctorAt = chain.findIndex(ownCtor), ctor = ctorAt >= 0 ? ownCtor(chain[ctorAt]) : undefined;
638
+ for (const c of chain) {
639
+ const k = ownCtor(c);
640
+ if (k && k.getSourceFile() === s.sf)
641
+ (s.spans ??= []).push([k.getStart(), k.end]);
642
+ }
573
643
  const fields = [];
574
- for (const m of cls.members) {
575
- if (ts.isPropertyDeclaration(m)) {
576
- if (ts.isPrivateIdentifier(m.name))
577
- refuse(m, `${m.name.text}: a #private field (the check reads the object's fields; \`private\` is in the subset)`);
578
- if (has(m, ts.SyntaxKind.StaticKeyword))
579
- refuse(m, 'a static field (state shared by every object)');
580
- fields.push({ name: memberName(m.name), shape: shapeOf(s.checker.getTypeAtLocation(m), s.checker, m), node: m, ...(m.initializer ? { init: m.initializer } : {}) });
581
- }
582
- else if (ts.isSetAccessorDeclaration(m))
583
- refuse(m, 'a setter');
584
- else if (ts.isMethodDeclaration(m) && ts.isPrivateIdentifier(m.name))
585
- refuse(m, 'a #private method');
586
- else if (ts.isIndexSignatureDeclaration(m) || ts.isClassStaticBlockDeclaration(m))
587
- refuse(m, 'a static block or index signature');
588
- }
589
- for (const p of ctor?.parameters ?? [])
590
- if (ts.isParameterPropertyDeclaration(p, ctor))
591
- fields.push({ name: p.name.text, shape: shapeOf(s.checker.getTypeAtLocation(p), s.checker, p), node: p });
644
+ const addField = (f) => { if (fields.some(x => x.name === f.name))
645
+ refuse(f.node, `${f.name}: a field declared again in a class that extends one with it`); fields.push(f); };
646
+ for (const c of [...chain].reverse()) {
647
+ for (const m of c.members) {
648
+ if (ts.isPropertyDeclaration(m)) {
649
+ if (ts.isPrivateIdentifier(m.name))
650
+ refuse(m, `${m.name.text}: a #private field (the check reads the object's fields; \`private\` is in the subset)`);
651
+ if (has(m, ts.SyntaxKind.StaticKeyword))
652
+ refuse(m, 'a static field (state shared by every object)');
653
+ if (has(m, ts.SyntaxKind.AbstractKeyword) || has(m, ts.SyntaxKind.DeclareKeyword))
654
+ continue;
655
+ addField({ name: memberName(m.name), shape: shapeOf(s.checker.getTypeAtLocation(m), s.checker, m), node: m, ...(m.initializer ? { init: m.initializer } : {}), of: c });
656
+ }
657
+ else if (ts.isSetAccessorDeclaration(m))
658
+ refuse(m, 'a setter');
659
+ else if (ts.isMethodDeclaration(m) && ts.isPrivateIdentifier(m.name))
660
+ refuse(m, 'a #private method');
661
+ else if (ts.isIndexSignatureDeclaration(m) || ts.isClassStaticBlockDeclaration(m))
662
+ refuse(m, 'a static block or index signature');
663
+ }
664
+ const k = ownCtor(c);
665
+ for (const p of k?.parameters ?? [])
666
+ if (ts.isParameterPropertyDeclaration(p, k))
667
+ addField({ name: p.name.text, shape: shapeOf(s.checker.getTypeAtLocation(p), s.checker, p), node: p, of: c });
668
+ }
592
669
  const ex0 = new Exec(s);
593
- const constant = (f) => !first && !written.has(f.name) && f.shape.k !== 'map';
670
+ const constant = (f) => !first && !written.has(f.name) && f.shape.k !== 'map' && f.shape.k !== 'list';
594
671
  // The state's variables first (so they keep the fields' names), then the params.
595
672
  const stateHeap = new Map(), thisFields = new Map(), layout = [], stateLayout = [];
596
673
  for (const f of fields)
@@ -600,66 +677,163 @@ function attempt(code, file, opts, written) {
600
677
  layout.push([f.name, r.layout]);
601
678
  stateLayout.push([f.name, r.layout]);
602
679
  }
603
- // The constructor, run over its arguments (the params): what each field starts at, and what it refuses (the pre).
680
+ // The constructor, run over its arguments (the params): what each field starts at, and what it refuses (the pre). A
681
+ // class that extends another runs the other's at super(...) (or, with no constructor of its own, first, with the
682
+ // same arguments), then its own field initializers, then the rest of its constructor.
604
683
  s.nowRole = 'param';
605
684
  const ctorArgs = [], ctorHeap = new Map(), ctorFields = new Map(fields.map(f => [f.name, { t: 'undef' }]));
606
685
  ctorHeap.set('this', { k: 'rec', fields: ctorFields, origin: 'fresh' });
607
686
  let cp = { pc: [], locals: new Map(), heap: ctorHeap, wrote: [], nows: 0 };
608
687
  const exC = new Exec(s);
609
688
  s.ctor = true;
689
+ const empty = new Set(), mapArgs = new Map();
690
+ const setThis = (q, f, v) => { const o = q.heap.get('this'); return { ...q, heap: new Map(q.heap).set('this', { ...o, fields: new Map(o.fields).set(f, v) }) }; };
691
+ const argValues = [];
610
692
  for (const p of ctor?.parameters ?? []) {
611
693
  if (!ts.isIdentifier(p.name))
612
694
  refuse(p, 'a destructured constructor argument');
613
695
  const sh = shapeOf(s.checker.getTypeAtLocation(p), s.checker, p);
696
+ // A Map given to the constructor: the field it becomes starts as that Map, taken here as empty (as callers make it).
697
+ if (sh.k === 'map') {
698
+ ctorArgs.push(`$map:${sh.js}`);
699
+ argValues.push({ t: 'undef' });
700
+ mapArgs.set(p.name.text, `$map:${sh.js}`);
701
+ continue;
702
+ }
614
703
  if (sh.k !== 'num' && sh.k !== 'bool' && sh.k !== 'choice')
615
- refuse(p, `${p.name.getText()}: a constructor argument that isn't a number, a boolean or a union of literals`);
704
+ refuse(p, `${p.name.getText()}: a constructor argument that isn't a number, a boolean, a union of literals or a Map`);
705
+ if (sh.k === 'num' && sh.date)
706
+ refuse(p, `${p.name.getText()}: a Date given to the constructor (the object would share it with its caller)`);
616
707
  const x = exC.newVar(p.name.getText(), sh, 'param', 'a constructor argument');
617
708
  ctorArgs.push(x.name);
618
- cp = exC.bind(p.name, Exec.valueOf(x), cp);
619
- if (ts.isParameterPropertyDeclaration(p, ctor)) {
620
- const o = cp.heap.get('this');
621
- cp = { ...cp, heap: new Map(cp.heap).set('this', { ...o, fields: new Map(o.fields).set(p.name.text, Exec.valueOf(x)) }) };
622
- }
709
+ argValues.push(Exec.valueOf(x));
623
710
  }
624
- const empty = new Set();
625
- for (const f of fields)
626
- if (f.init) {
627
- if (f.shape.k === 'map') {
628
- if (!isMapInit(f.init))
629
- refuse(f.init, `${f.name} starts with entries (a map starts empty in the subset)`);
630
- empty.add(f.name);
631
- continue;
632
- }
633
- const [v, q] = exC.ev(f.init, cp);
634
- cp = q;
635
- const o = cp.heap.get('this');
636
- cp = { ...cp, heap: new Map(cp.heap).set('this', { ...o, fields: new Map(o.fields).set(f.name, v) }) };
637
- }
638
- const body = (ctor?.body?.statements ?? []).filter(st => {
711
+ // The statements of one constructor that set a map field (to an empty map, or to the Map given): a map that starts
712
+ // empty, not a write.
713
+ const mapInits = (k, locals) => (k.body?.statements ?? []).filter(st => {
639
714
  if (!ts.isExpressionStatement(st) || !ts.isBinaryExpression(st.expression) || st.expression.operatorToken.kind !== ts.SyntaxKind.EqualsToken)
640
715
  return true;
641
716
  const l = st.expression.left;
642
717
  if (!ts.isPropertyAccessExpression(l) || l.expression.kind !== ts.SyntaxKind.ThisKeyword)
643
718
  return true;
644
719
  const f = fields.find(x => x.name === memberName(l.name));
720
+ if (f?.shape.k === 'list') {
721
+ if (!isEmptyArray(st.expression.right))
722
+ refuse(st, `${f.name} starts with items (a list starts empty in the subset)`);
723
+ empty.add(f.name);
724
+ return false;
725
+ }
645
726
  if (f?.shape.k !== 'map')
646
727
  return true;
647
- if (!isMapInit(st.expression.right))
728
+ const r = st.expression.right, rn = ts.isIdentifier(r) ? r.text : undefined, given = rn && locals.get(rn)?.t === 'undef' && k === ctor ? mapArgs.get(rn) : undefined;
729
+ if (given) {
730
+ if ([...empty].some(x => x === f.name))
731
+ refuse(st, `${f.name} set twice`);
732
+ if (s.notes.has(`maparg:${rn}`))
733
+ refuse(st, `the Map ${rn} given to two fields (one Map in two places)`);
734
+ s.notes.add(`maparg:${rn}`);
735
+ s.notes.add(`${f.name} is the Map given to the constructor (${rn}): it starts empty here, as the code's callers make it (\`new ${opts.entry}(new Map())\`); a Map given with entries, or changed by its caller after, is outside this rule`);
736
+ }
737
+ else if (!isMapInit(r))
648
738
  refuse(st, `${f.name} starts with entries (a map starts empty in the subset)`);
649
739
  empty.add(f.name);
650
740
  return false;
651
741
  });
652
- const cflow = exC.block(body, cp);
653
- if (cflow.rets.some(([, v]) => v.t !== 'undef'))
654
- refuse(ctor, 'a constructor that returns a value');
655
- const ends = [...cflow.rets.map(([p]) => p), ...(cflow.live ? [cflow.live] : [])];
742
+ const fieldInits = (c, q) => {
743
+ for (const f of fields)
744
+ if (f.of === c && f.init) {
745
+ if (f.shape.k === 'list') {
746
+ if (!isEmptyArray(f.init))
747
+ refuse(f.init, `${f.name} starts with items (a list starts empty in the subset)`);
748
+ empty.add(f.name);
749
+ continue;
750
+ }
751
+ if (f.shape.k === 'map') {
752
+ if (!isMapInit(f.init))
753
+ refuse(f.init, `${f.name} starts with entries (a map starts empty in the subset)`);
754
+ empty.add(f.name);
755
+ continue;
756
+ }
757
+ const [v, q2] = exC.ev(f.init, q);
758
+ q = setThis(q2, f.name, v);
759
+ }
760
+ return q;
761
+ };
762
+ const ends = [];
763
+ const construct = (k, args, q, at) => {
764
+ const c = chain[k], own = ownCtor(c);
765
+ if (!own) {
766
+ // No constructor of its own: the one above with the same arguments, then its field initializers.
767
+ const q2 = k + 1 < chain.length ? construct(k + 1, args, q, at) : q;
768
+ return q2 && fieldInits(c, q2);
769
+ }
770
+ const outer = q.locals;
771
+ let r = { ...q, locals: new Map() };
772
+ own.parameters.forEach((p, i) => {
773
+ if (!ts.isIdentifier(p.name))
774
+ refuse(p, 'a destructured constructor argument');
775
+ let v = args[i];
776
+ if (v === undefined) {
777
+ if (!p.initializer)
778
+ refuse(at, 'super(...) with fewer arguments than the constructor takes');
779
+ const [dv, r2] = exC.ev(p.initializer, r);
780
+ v = dv;
781
+ r = r2;
782
+ }
783
+ r = exC.bind(p.name, v, r);
784
+ });
785
+ const props = (x) => own.parameters.reduce((y, p) => (ts.isParameterPropertyDeclaration(p, own) ? setThis(y, p.name.text, y.locals.get(p.name.text)) : y), x);
786
+ const body = mapInits(own, r.locals);
787
+ const sup = body.findIndex(st => ts.isExpressionStatement(st) && ts.isCallExpression(st.expression) && st.expression.expression.kind === ts.SyntaxKind.SuperKeyword);
788
+ if (k + 1 < chain.length && sup < 0)
789
+ refuse(own, 'a constructor of a class that extends another with no super(...) at its top level');
790
+ const run = (stmts, x) => {
791
+ const f = exC.block(stmts, x);
792
+ if (f.rets.some(([, v]) => v.t !== 'undef'))
793
+ refuse(own, 'a constructor that returns a value');
794
+ ends.push(...f.rets.map(([p]) => ({ ...p, locals: outer })));
795
+ return f.live;
796
+ };
797
+ let live;
798
+ if (k + 1 < chain.length) {
799
+ const before = run(body.slice(0, sup), r);
800
+ if (!before)
801
+ return undefined;
802
+ const call = body[sup].expression;
803
+ let at2 = before;
804
+ const sargs = [];
805
+ for (const a of call.arguments) {
806
+ if (ts.isSpreadElement(a))
807
+ refuse(a, 'a spread argument');
808
+ const [v, q2] = exC.ev(a, at2);
809
+ sargs.push(v);
810
+ at2 = q2;
811
+ }
812
+ const above = construct(k + 1, sargs, at2, call);
813
+ if (!above)
814
+ return undefined;
815
+ live = run(body.slice(sup + 1), fieldInits(c, props({ ...above, locals: at2.locals })));
816
+ }
817
+ else
818
+ live = run(body, fieldInits(c, props(r)));
819
+ return live && { ...live, locals: outer };
820
+ };
821
+ const made0 = construct(0, argValues, cp, ctor ?? cls);
822
+ if (made0)
823
+ ends.push(made0);
656
824
  const cend = ends.reduceRight((acc, x) => exC.merge(x, acc, ctor ?? cls), undefined) ?? refuse(ctor ?? cls, 'a constructor that always throws');
657
825
  s.ctor = false;
826
+ for (const n of [...s.notes])
827
+ if (n.startsWith('maparg:'))
828
+ s.notes.delete(n);
658
829
  const pre = I.not(refusalOf(exC));
659
830
  const made = cend.heap.get('this').fields;
660
831
  for (const f of fields)
661
832
  if (f.shape.k === 'map' && !empty.has(f.name))
662
- refuse(f.node, `${f.name}: a map field must start as new Map() or {}`);
833
+ refuse(f.node, `${f.name}: a map field must start as new Map() or {} (or the Map the constructor is given)`);
834
+ for (const f of fields)
835
+ if (f.shape.k === 'list' && !empty.has(f.name))
836
+ refuse(f.node, `${f.name}: an array field must start as []`);
663
837
  // Each field's start, over the params: a state variable's init, or a constant field's value in every method.
664
838
  const init = {};
665
839
  const startOf = (v, lay, at) => {
@@ -668,7 +842,7 @@ function attempt(code, file, opts, written) {
668
842
  init[n] = termOf(x);
669
843
  };
670
844
  for (const [fname, lay] of layout)
671
- if (lay.k !== 'map')
845
+ if (lay.k !== 'map' && lay.k !== 'list')
672
846
  startOf(made.get(fname), lay, fields.find(f => f.name === fname).node);
673
847
  for (const f of fields)
674
848
  if (constant(f)) {
@@ -693,34 +867,83 @@ function attempt(code, file, opts, written) {
693
867
  s.now = undefined;
694
868
  s.nowRole = 'input';
695
869
  stateHeap.set('this', { k: 'rec', fields: thisFields, origin: 'this' });
696
- // The methods: each public one an event, run from the state as variables.
697
- const methods = cls.members.filter((m) => ts.isMethodDeclaration(m) && !has(m, ts.SyntaxKind.StaticKeyword) && !has(m, ts.SyntaxKind.PrivateKeyword) && !has(m, ts.SyntaxKind.ProtectedKeyword))
698
- .filter(m => !opts.methods || opts.methods.includes(memberName(m.name)));
870
+ // The methods: each public one an event (the nearest of each name, through the classes it extends), run from the
871
+ // state as variables.
872
+ const seenNames = new Set(), methods = [];
873
+ for (const c of chain)
874
+ for (const m of c.members) {
875
+ if (!ts.isMethodDeclaration(m) || seenNames.has(memberName(m.name)))
876
+ continue;
877
+ if (!m.body && has(m, ts.SyntaxKind.AbstractKeyword))
878
+ continue;
879
+ seenNames.add(memberName(m.name));
880
+ if (has(m, ts.SyntaxKind.StaticKeyword) || has(m, ts.SyntaxKind.PrivateKeyword) || has(m, ts.SyntaxKind.ProtectedKeyword))
881
+ continue;
882
+ if (!opts.methods || opts.methods.includes(memberName(m.name)))
883
+ methods.push(m);
884
+ }
699
885
  if (opts.methods)
700
886
  for (const n of opts.methods)
701
- if (!methods.some(m => memberName(m.name) === n))
702
- refuse(cls, `no public method ${n}`);
887
+ if (!methods.some(m => memberName(m.name) === n)) {
888
+ const st = chain.flatMap(c => c.members).find(m => ts.isMethodDeclaration(m) && memberName(m.name) === n && has(m, ts.SyntaxKind.StaticKeyword));
889
+ refuse(st ?? cls, st ? `${n} is static (a function of the class, not a step of an object): the subset reads an object's methods` : `no public method ${n}`);
890
+ }
703
891
  if (!methods.length)
704
892
  refuse(cls, 'a class with no public methods (no events)');
705
893
  const mnames = methods.map(m => memberName(m.name)), ev = ex0.newVar('method', { k: 'choice', values: mnames }, 'input'), evL = { op: 'var', name: ev.name, values: mnames };
706
894
  const outputs = [], perMethod = [], events = [];
707
- const outVars = new Map();
895
+ const results = {}, outVars = new Map();
896
+ const outVar = (name, sort, what) => { const x = ex0.newVar(name, sort, 'state', what); outputs.push(x.name); return x; };
708
897
  for (const m of methods) {
709
898
  const name = memberName(m.name), sig = s.checker.getSignatureFromDeclaration(m), rt = s.checker.getReturnTypeOfSignature(sig);
710
899
  if (has(m, ts.SyntaxKind.AsyncKeyword) || m.asteriskToken)
711
900
  refuse(m, `${name}: an async or generator method (its steps interleave with others)`);
712
- if (!(rt.flags & (ts.TypeFlags.Void | ts.TypeFlags.Undefined))) {
713
- const sh = shapeOf(rt, s.checker, m);
901
+ if (rt.flags & (ts.TypeFlags.Void | ts.TypeFlags.Undefined))
902
+ continue;
903
+ const what = `what ${name} returned, at the step that called it (its default at others)`;
904
+ // A value that may be missing (T | null, T | undefined): the value, and whether it is missing.
905
+ const parts = rt.isUnion() ? rt.types : [rt], missing = parts.filter(x => x.flags & (ts.TypeFlags.Null | ts.TypeFlags.Undefined)), rest = parts.filter(x => !(x.flags & (ts.TypeFlags.Null | ts.TypeFlags.Undefined)));
906
+ if (missing.length && rest.length) {
907
+ if (missing.length > 1)
908
+ refuse(m, `${name} returns null or undefined (two ways missing)`);
909
+ const rt1 = rest.length === 1 ? rest[0] : rest.every(x => x.flags & ts.TypeFlags.BooleanLiteral) ? s.checker.getBooleanType() : undefined;
910
+ const sh = rt1 ? shapeOf(rt1, s.checker, m) : rest.every(x => x.flags & ts.TypeFlags.StringLiteral) ? { k: 'choice', values: rest.map(x => x.value) } : refuse(m, `${name} returns ${s.checker.typeToString(rt)}`);
714
911
  if (sh.k !== 'num' && sh.k !== 'bool' && sh.k !== 'choice')
715
- refuse(m, `${name} returns ${sh.k === 'str' ? 'a string' : 'a compound value'} (a result kept is a number, a boolean or a union of literals)`);
716
- const x = ex0.newVar(`${name}_result`, sh, 'state', `what ${name} returned, at the step that called it (its default at others)`);
717
- outVars.set(name, x);
718
- outputs.push(x.name);
912
+ refuse(m, `${name} returns ${s.checker.typeToString(rt)} (a result kept is a number, a boolean or a union of literals, or a record of them)`);
913
+ if (sh.date)
914
+ refuse(m, `${name} returns a Date (the caller would share it with the object)`);
915
+ const x = outVar(`${name}_result`, sh, what), y = outVar(`${name}_result_missing`, { k: 'bool' }, `whether ${name} returned ${missing[0].flags & ts.TypeFlags.Null ? 'null' : 'undefined'}`);
916
+ results[name] = { k: 'maybe', name: x.name, missing: y.name, null: !!(missing[0].flags & ts.TypeFlags.Null) };
917
+ outVars.set(name, [x, y]);
719
918
  layout.push([`${name}()`, { k: 'scalar', name: x.name }]);
919
+ continue;
720
920
  }
921
+ const sh = shapeOf(rt, s.checker, m);
922
+ if (sh.k === 'rec') {
923
+ const vs = sh.fields.map(([f, fs]) => {
924
+ if (fs.k !== 'num' && fs.k !== 'bool' && fs.k !== 'choice')
925
+ return refuse(m, `${name} returns a record whose ${f} is ${fs.k === 'str' ? 'a string' : 'compound'}`);
926
+ if (fs.date)
927
+ return refuse(m, `${name} returns a record holding a Date (the caller would share it with the object)`);
928
+ return [f, outVar(`${name}_result_${f}`, fs, `${what}: its ${f}`)];
929
+ });
930
+ results[name] = { k: 'rec', fields: vs.map(([f, x]) => [f, x.name]) };
931
+ outVars.set(name, vs.map(([, x]) => x));
932
+ layout.push([`${name}()`, { k: 'rec', fields: vs.map(([f, x]) => [f, { k: 'scalar', name: x.name }]) }]);
933
+ continue;
934
+ }
935
+ if (sh.k !== 'num' && sh.k !== 'bool' && sh.k !== 'choice')
936
+ refuse(m, `${name} returns ${sh.k === 'str' ? 'a string' : 'a compound value'} (a result kept is a number, a boolean or a union of literals, or a record of them)`);
937
+ if (sh.date)
938
+ refuse(m, `${name} returns a Date (the caller would share it with the object)`);
939
+ const x = outVar(`${name}_result`, sh, what);
940
+ results[name] = { k: 'scalar', name: x.name };
941
+ outVars.set(name, [x]);
942
+ layout.push([`${name}()`, { k: 'scalar', name: x.name }]);
721
943
  }
722
944
  for (const m of methods)
723
- (s.spans ??= []).push([m.getStart(), m.end]);
945
+ if (m.getSourceFile() === s.sf)
946
+ (s.spans ??= []).push([m.getStart(), m.end]);
724
947
  for (const m of methods) {
725
948
  const name = memberName(m.name), ex = new Exec(s), sel = I.is(evL, name);
726
949
  let p = { pc: [sel], locals: new Map(), heap: new Map(stateHeap), wrote: [], nows: 0 };
@@ -743,8 +966,33 @@ function attempt(code, file, opts, written) {
743
966
  const self = rp.heap.get('this'), sv = { leaves: new Map(), maps: new Map() };
744
967
  for (const [f, lay] of stateLayout)
745
968
  materialize(ex, self.fields.get(f), lay, rp, m, sv);
746
- for (const [mn, x] of outVars)
747
- sv.leaves.set(x.name, mn === name ? (rv.t === 'undef' ? refuse(m, `${name} returns nothing on some path`) : outValue(ex, rv, x, rp, m)) : Exec.defaultOf(x.sort));
969
+ for (const [mn, xs] of outVars) {
970
+ if (mn !== name) {
971
+ for (const x of xs)
972
+ sv.leaves.set(x.name, Exec.defaultOf(x.sort));
973
+ continue;
974
+ }
975
+ const r = results[mn];
976
+ if (r.k === 'scalar') {
977
+ sv.leaves.set(r.name, rv.t === 'undef' ? refuse(m, `${name} returns nothing on some path`) : outValue(ex, rv, xs[0], rp, m));
978
+ continue;
979
+ }
980
+ if (r.k === 'maybe') {
981
+ const missingKind = (x) => (x.t === 'undef' ? x.null === r.null : x.t === 'opt' ? !!x.null === r.null || (x.has.op === 'const' && x.has.v) : true);
982
+ if (!missingKind(rv))
983
+ refuse(m, `${name} returns ${r.null ? 'undefined' : 'null'} where its type says ${r.null ? 'null' : 'undefined'}`);
984
+ const has = rv.t === 'undef' ? I.F : rv.t === 'opt' ? rv.has : I.T, inner = rv.t === 'undef' ? undefined : rv.t === 'opt' ? rv.v : rv;
985
+ const there = inner ? outValue(ex, inner, xs[0], { ...rp, pc: [...rp.pc, has] }, m) : Exec.defaultOf(xs[0].sort);
986
+ sv.leaves.set(r.name, ex.mergeScalar(has, there, Exec.defaultOf(xs[0].sort), m));
987
+ sv.leaves.set(r.missing, { t: 'bool', e: I.not(has) });
988
+ continue;
989
+ }
990
+ // A record returned: a fresh one (a field of the state's own objects would be shared with the caller).
991
+ const d = rv.t === 'ref' ? rp.heap.get(rv.id) : undefined;
992
+ if (rv.t !== 'ref' || d?.k !== 'rec' || d.origin !== 'fresh')
993
+ refuse(m, `${name} returns ${rv.t === 'ref' ? "an object of the state's own (the caller would share it)" : 'other than a record'}`);
994
+ r.fields.forEach(([f, n], i) => sv.leaves.set(n, outValue(ex, d.fields.get(f) ?? refuse(m, `${name} returns a record without ${f}`), xs[i], rp, m)));
995
+ }
748
996
  return [rp, sv];
749
997
  });
750
998
  perMethod.push({ sel, sv: joinAll(ex, outs, m), refuse: refusalOf(ex) });
@@ -754,6 +1002,280 @@ function attempt(code, file, opts, written) {
754
1002
  let final = perMethod.at(-1).sv;
755
1003
  for (let i = perMethod.length - 2; i >= 0; i--)
756
1004
  final = mergeVals(ex0, perMethod[i].sel, perMethod[i].sv, final, cls);
1005
+ for (const xs of outVars.values())
1006
+ for (const x of xs)
1007
+ init[x.name] = termOf(Exec.defaultOf(x.sort));
1008
+ const wrote = new Set();
1009
+ for (const [f, lay] of layout) {
1010
+ const leaves = [];
1011
+ const walk = (l) => { if (l.k === 'scalar')
1012
+ leaves.push(l.name);
1013
+ else if (l.k === 'rec')
1014
+ l.fields.forEach(([, x]) => walk(x));
1015
+ else if (l.k === 'map')
1016
+ leaves.push(`map:${l.name}`);
1017
+ else if (l.k === 'list')
1018
+ leaves.push(`list:${l.name}`); };
1019
+ walk(lay);
1020
+ if (leaves.some(n => (n.startsWith('map:') ? final.maps.get(n.slice(4)) !== undefined : n.startsWith('list:') ? !!final.lists?.get(n.slice(5))?.length : !sameTerm(final.leaves.get(n), Exec.valueOf(s.vars.get(n))))))
1021
+ wrote.add(f);
1022
+ }
1023
+ const model = finish(s, { name: opts.entry, shape: 'class', file, entry: opts.entry, layout: { k: 'rec', fields: layout }, init, final, refuse: I.or(...perMethod.map(x => I.and(x.sel, x.refuse))), pre, events, outputs, event: ev.name, ctorArgs });
1024
+ model.results = results;
1025
+ return { model, written: wrote };
1026
+ }
1027
+ // --- objects a factory makes ----------------------------------------------------------------------------------------
1028
+ // A function that returns an object of functions (`function counter(limit) { let n = 0; return {inc() {...}, get: () =>
1029
+ // n} }`): the object's state is what its functions close over (the factory's variables, and its arguments), each a
1030
+ // field; the factory's arguments the params; each function returned an event. Read as a class whose fields are those
1031
+ // variables, `this` refused in the object's functions. The check reads and sets the closed-over state through two
1032
+ // functions it adds to the returned object (it reads the code that way only: nothing else is changed).
1033
+ export const isFactory = (code, file, entry) => {
1034
+ const sf = ts.createSourceFile(file, code, ts.ScriptTarget.ES2022, true);
1035
+ let fn;
1036
+ for (const st of sf.statements) {
1037
+ if (ts.isFunctionDeclaration(st) && st.name?.text === entry)
1038
+ fn = st;
1039
+ if (ts.isVariableStatement(st))
1040
+ for (const d of st.declarationList.declarations)
1041
+ if (ts.isIdentifier(d.name) && d.name.text === entry && d.initializer && (ts.isArrowFunction(d.initializer) || ts.isFunctionExpression(d.initializer)))
1042
+ fn = d.initializer;
1043
+ }
1044
+ return !!fn && !!returnedObject(fn);
1045
+ };
1046
+ function returnedObject(fn) {
1047
+ const strip0 = (e) => (ts.isParenthesizedExpression(e) || ts.isAsExpression(e) || ts.isSatisfiesExpression(e) ? strip0(e.expression) : e);
1048
+ const body = fn.body;
1049
+ if (!body)
1050
+ return undefined;
1051
+ const ret = ts.isBlock(body) ? body.statements.at(-1) : undefined, e = ts.isBlock(body) ? (ret && ts.isReturnStatement(ret) && ret.expression ? strip0(ret.expression) : undefined) : strip0(body);
1052
+ if (!e || !ts.isObjectLiteralExpression(e))
1053
+ return undefined;
1054
+ // A shorthand entry is a function where the factory declares one by that name.
1055
+ const local = new Set((ts.isBlock(body) ? body.statements : []).flatMap(st => (ts.isFunctionDeclaration(st) && st.name ? [st.name.text] : ts.isVariableStatement(st) ? st.declarationList.declarations.filter(d => d.initializer && (ts.isArrowFunction(strip0(d.initializer)) || ts.isFunctionExpression(strip0(d.initializer)))).map(d => d.name.getText()) : [])));
1056
+ const fnOf = (p) => ts.isMethodDeclaration(p) || (ts.isPropertyAssignment(p) && (ts.isArrowFunction(strip0(p.initializer)) || ts.isFunctionExpression(strip0(p.initializer)))) || (ts.isShorthandPropertyAssignment(p) && local.has(p.name.text));
1057
+ return e.properties.length && e.properties.some(fnOf) ? e : undefined;
1058
+ }
1059
+ export function readFactory(code, file, opts) {
1060
+ const written = factoryAttempt(code, file, opts, new Set()).written;
1061
+ return factoryAttempt(code, file, opts, written).model;
1062
+ }
1063
+ function factoryAttempt(code, file, opts, written) {
1064
+ const s = setupOf(code, file, {}, opts.files), fn = findFunction(s.sf, opts.entry), first = written.size === 0;
1065
+ if (fn.modifiers?.some(m => m.kind === ts.SyntaxKind.AsyncKeyword) || fn.asteriskToken)
1066
+ refuse(fn, 'an async or generator factory');
1067
+ const obj = returnedObject(fn) ?? refuse(fn, `${opts.entry} returns no object of functions`);
1068
+ const stmts = fn.body && ts.isBlock(fn.body) ? fn.body.statements.slice(0, -1) : [];
1069
+ const fields = [], closure = new Set(), helpers = new Set();
1070
+ for (const p of fn.parameters) {
1071
+ if (!ts.isIdentifier(p.name) || p.dotDotDotToken)
1072
+ refuse(p, 'a destructured or rest argument to the factory');
1073
+ fields.push({ name: p.name.text, shape: shapeOf(s.checker.getTypeAtLocation(p), s.checker, p), node: p, param: true });
1074
+ closure.add(p);
1075
+ }
1076
+ for (const st of stmts) {
1077
+ if (ts.isFunctionDeclaration(st)) {
1078
+ helpers.add(st);
1079
+ continue;
1080
+ }
1081
+ if (ts.isIfStatement(st) || ts.isExpressionStatement(st) || ts.isThrowStatement(st))
1082
+ continue;
1083
+ if (!ts.isVariableStatement(st))
1084
+ return refuse(st, `${ts.SyntaxKind[st.kind]} in the factory (a factory read here declares its state, checks its arguments, then returns its object)`);
1085
+ if (!(st.declarationList.flags & (ts.NodeFlags.Let | ts.NodeFlags.Const)))
1086
+ refuse(st, 'var (let or const are in the subset)');
1087
+ for (const d of st.declarationList.declarations) {
1088
+ if (!ts.isIdentifier(d.name))
1089
+ refuse(d, 'a destructuring in the factory');
1090
+ const init = d.initializer && (ts.isParenthesizedExpression(d.initializer) ? d.initializer.expression : d.initializer);
1091
+ if (init && (ts.isArrowFunction(init) || ts.isFunctionExpression(init))) {
1092
+ helpers.add(d);
1093
+ continue;
1094
+ }
1095
+ if (!init)
1096
+ refuse(d, `${d.name.text} starts undefined`);
1097
+ fields.push({ name: d.name.text, shape: shapeOf(s.checker.getTypeAtLocation(d), s.checker, d), node: d, init: d.initializer, isConst: !!(st.declarationList.flags & ts.NodeFlags.Const) });
1098
+ closure.add(d);
1099
+ }
1100
+ }
1101
+ s.closure = closure;
1102
+ s.notes.add(`${opts.entry} makes an object of functions: its state is what they close over (${fields.map(f => f.name).join(', ') || 'nothing'}), its arguments the params`);
1103
+ const ex0 = new Exec(s);
1104
+ const constant = (f) => !first && !written.has(f.name) && f.shape.k !== 'map' && f.shape.k !== 'list';
1105
+ const stateHeap = new Map(), thisFields = new Map(), layout = [], stateLayout = [];
1106
+ for (const f of fields)
1107
+ if (!constant(f)) {
1108
+ const r = build(ex0, f.shape, [f.name], stateHeap, 'this', f.node);
1109
+ thisFields.set(f.name, r.v);
1110
+ layout.push([f.name, r.layout]);
1111
+ stateLayout.push([f.name, r.layout]);
1112
+ }
1113
+ // The factory run over its arguments (the params): each variable's start, and its refusals (the precondition).
1114
+ s.nowRole = 'param';
1115
+ const ctorArgs = [], exC = new Exec(s), empty = new Set();
1116
+ const ctorFields = new Map();
1117
+ for (const f of fields.filter(x => x.param)) {
1118
+ if (f.shape.k === 'map') {
1119
+ ctorArgs.push(`$map:${f.shape.js}`);
1120
+ empty.add(f.name);
1121
+ s.notes.add(`${f.name} is the Map given to the factory: it starts empty here, as callers make it; a Map given with entries, or changed by its caller after, is outside this rule`);
1122
+ continue;
1123
+ }
1124
+ if (f.shape.k !== 'num' && f.shape.k !== 'bool' && f.shape.k !== 'choice')
1125
+ refuse(f.node, `${f.name}: a factory argument that isn't a number, a boolean, a union of literals or a Map`);
1126
+ if (f.shape.date)
1127
+ refuse(f.node, `${f.name}: a Date given to the factory (shared with its caller)`);
1128
+ const x = exC.newVar(f.name, f.shape, 'param', 'an argument of the factory');
1129
+ ctorArgs.push(x.name);
1130
+ ctorFields.set(f.name, Exec.valueOf(x));
1131
+ }
1132
+ for (const f of fields)
1133
+ if (!ctorFields.has(f.name))
1134
+ ctorFields.set(f.name, { t: 'undef' });
1135
+ const ctorHeap = new Map([['this', { k: 'rec', fields: ctorFields, origin: 'fresh' }]]);
1136
+ let cp = { pc: [], locals: new Map(), heap: ctorHeap, wrote: [], nows: 0 };
1137
+ s.ctor = true;
1138
+ // In order: each variable's initializer, and the checks and writes between them (a throw is the precondition).
1139
+ for (const st of stmts) {
1140
+ if (ts.isFunctionDeclaration(st))
1141
+ continue;
1142
+ if (ts.isVariableStatement(st)) {
1143
+ for (const d of st.declarationList.declarations) {
1144
+ const f = fields.find(x => x.node === d);
1145
+ if (!f?.init)
1146
+ continue;
1147
+ if (f.shape.k === 'map') {
1148
+ if (!isMapInit(f.init))
1149
+ refuse(f.init, `${f.name} starts with entries (a map starts empty in the subset)`);
1150
+ empty.add(f.name);
1151
+ continue;
1152
+ }
1153
+ if (f.shape.k === 'list') {
1154
+ if (!isEmptyArray(f.init))
1155
+ refuse(f.init, `${f.name} starts with items (a list starts empty in the subset)`);
1156
+ empty.add(f.name);
1157
+ continue;
1158
+ }
1159
+ const [v, q] = exC.ev(f.init, cp);
1160
+ const o = q.heap.get('this');
1161
+ cp = { ...q, heap: new Map(q.heap).set('this', { ...o, fields: new Map(o.fields).set(f.name, v) }) };
1162
+ }
1163
+ continue;
1164
+ }
1165
+ const flow = exC.stmt(st, cp);
1166
+ if (flow.rets.length || flow.breaks.length)
1167
+ refuse(st, 'a return or break in the factory before its object');
1168
+ cp = flow.live ?? refuse(st, 'a factory that always throws');
1169
+ }
1170
+ s.ctor = false;
1171
+ const pre = I.not(refusalOf(exC)), made = cp.heap.get('this').fields;
1172
+ const init = {};
1173
+ for (const [fname, lay] of layout)
1174
+ if (lay.k !== 'map' && lay.k !== 'list') {
1175
+ const sv = materialize(exC, made.get(fname), lay, cp, fields.find(f => f.name === fname).node);
1176
+ for (const [n, x] of sv.leaves)
1177
+ init[n] = termOf(x);
1178
+ }
1179
+ for (const f of fields)
1180
+ if (constant(f)) {
1181
+ const v = made.get(f.name);
1182
+ if (v.t === 'undef' || v.t === 'opt')
1183
+ refuse(f.node, `${f.name} starts undefined`);
1184
+ if (v.t === 'ref') {
1185
+ const copy = (id) => { const o = cp.heap.get(id); if (o?.k === 'rec') {
1186
+ stateHeap.set(id, { ...o, origin: 'this' });
1187
+ for (const x of o.fields.values())
1188
+ if (x.t === 'ref')
1189
+ copy(x.id);
1190
+ }
1191
+ else
1192
+ refuse(f.node, `${f.name}: a constant map`); };
1193
+ copy(v.id);
1194
+ }
1195
+ thisFields.set(f.name, v);
1196
+ layout.push([f.name, constLayout(v, cp, f.node)]);
1197
+ }
1198
+ for (const f of fields)
1199
+ if (written.has(f.name) && f.isConst && f.shape.k !== 'map' && f.shape.k !== 'rec')
1200
+ refuse(f.node, `${f.name} is a const written by the object`);
1201
+ s.now = undefined;
1202
+ s.nowRole = 'input';
1203
+ stateHeap.set('this', { k: 'rec', fields: thisFields, origin: 'this' });
1204
+ const strip0 = (e) => (ts.isParenthesizedExpression(e) || ts.isAsExpression(e) ? strip0(e.expression) : e);
1205
+ const fns = obj.properties.map(p => {
1206
+ if (ts.isMethodDeclaration(p))
1207
+ return { name: memberName(p.name), decl: p };
1208
+ if (ts.isPropertyAssignment(p)) {
1209
+ const x = strip0(p.initializer);
1210
+ if (ts.isArrowFunction(x) || ts.isFunctionExpression(x))
1211
+ return { name: memberName(p.name), decl: x };
1212
+ }
1213
+ if (ts.isShorthandPropertyAssignment(p)) {
1214
+ const d = s.checker.getShorthandAssignmentValueSymbol(p)?.valueDeclaration;
1215
+ const f = d && ts.isFunctionDeclaration(d) ? d : d && ts.isVariableDeclaration(d) && d.initializer && (ts.isArrowFunction(strip0(d.initializer)) || ts.isFunctionExpression(strip0(d.initializer))) ? strip0(d.initializer) : undefined;
1216
+ if (f && (helpers.has(d) || helpers.has(f)))
1217
+ return { name: p.name.text, decl: f };
1218
+ }
1219
+ return refuse(p, `${p.name?.getText() ?? 'an entry'}: a value the object returns beside its functions (its state is what they close over)`);
1220
+ }).filter(f => !opts.methods || opts.methods.includes(f.name));
1221
+ if (!fns.length)
1222
+ refuse(obj, 'an object with no functions (no events)');
1223
+ const mnames = fns.map(f => f.name), ev = ex0.newVar('method', { k: 'choice', values: mnames }, 'input'), evL = { op: 'var', name: ev.name, values: mnames };
1224
+ const outputs = [], perMethod = [], events = [], results = {}, outVars = new Map();
1225
+ for (const f of fns) {
1226
+ if (f.decl.modifiers?.some(m => m.kind === ts.SyntaxKind.AsyncKeyword) || f.decl.asteriskToken)
1227
+ refuse(f.decl, `${f.name}: an async or generator function (its steps interleave with others)`);
1228
+ const sig = s.checker.getSignatureFromDeclaration(f.decl), rt = s.checker.getReturnTypeOfSignature(sig);
1229
+ if (rt.flags & (ts.TypeFlags.Void | ts.TypeFlags.Undefined))
1230
+ continue;
1231
+ const sh = shapeOf(rt, s.checker, f.decl);
1232
+ if (sh.k !== 'num' && sh.k !== 'bool' && sh.k !== 'choice')
1233
+ refuse(f.decl, `${f.name} returns ${sh.k === 'str' ? 'a string' : 'a compound value'} (a result kept is a number, a boolean or a union of literals)`);
1234
+ if (sh.date)
1235
+ refuse(f.decl, `${f.name} returns a Date (shared with the caller)`);
1236
+ const x = ex0.newVar(`${f.name}_result`, sh, 'state', `what ${f.name} returned, at the step that called it (its default at others)`);
1237
+ outVars.set(f.name, x);
1238
+ outputs.push(x.name);
1239
+ results[f.name] = { k: 'scalar', name: x.name };
1240
+ layout.push([`${f.name}()`, { k: 'scalar', name: x.name }]);
1241
+ }
1242
+ for (const f of fns)
1243
+ if (f.decl.getSourceFile() === s.sf)
1244
+ (s.spans ??= []).push([f.decl.getStart(), f.decl.end]);
1245
+ for (const st of stmts)
1246
+ if (st.getSourceFile() === s.sf)
1247
+ (s.spans ??= []).push([st.getStart(), st.end]);
1248
+ for (const f of fns) {
1249
+ const ex = new Exec(s), sel = I.is(evL, f.name);
1250
+ let p = { pc: [sel], locals: new Map(), heap: new Map(stateHeap), wrote: [], nows: 0 };
1251
+ const args = [];
1252
+ for (const param of f.decl.parameters) {
1253
+ if (param.dotDotDotToken || !ts.isIdentifier(param.name))
1254
+ refuse(param, 'a rest or destructured argument');
1255
+ const a = argOf(ex, param, `${f.name}_`, f.decl.body ?? f.decl);
1256
+ if (a.events.length !== 1)
1257
+ refuse(param, 'an argument that is a union of records');
1258
+ for (const [id, o] of a.heap)
1259
+ p.heap.set(id, o);
1260
+ p = ex.bind(param.name, a.v, p);
1261
+ args.push(a.events[0].arg);
1262
+ }
1263
+ const body = f.decl.body ?? refuse(f.decl, `${f.name} has no body`);
1264
+ const ends = ts.isBlock(body) ? (() => { const flow = ex.block(body.statements, p); return [...flow.rets, ...(flow.live ? [[flow.live, { t: 'undef' }]] : [])]; })() : [(([v, q]) => [q, v])(ex.ev(body, p))];
1265
+ const outs = ends.map(([rp, rv]) => {
1266
+ const self = rp.heap.get('this'), sv = { leaves: new Map(), maps: new Map() };
1267
+ for (const [fl, lay] of stateLayout)
1268
+ materialize(ex, self.fields.get(fl), lay, rp, f.decl, sv);
1269
+ for (const [mn, x] of outVars)
1270
+ sv.leaves.set(x.name, mn === f.name ? (rv.t === 'undef' ? refuse(f.decl, `${f.name} returns nothing on some path`) : outValue(ex, rv, x, rp, f.decl)) : Exec.defaultOf(x.sort));
1271
+ return [rp, sv];
1272
+ });
1273
+ perMethod.push({ sel, sv: joinAll(ex, outs, f.decl), refuse: refusalOf(ex) });
1274
+ events.push({ select: { [ev.name]: f.name }, call: f.name, args });
1275
+ }
1276
+ let final = perMethod.at(-1).sv;
1277
+ for (let i = perMethod.length - 2; i >= 0; i--)
1278
+ final = mergeVals(ex0, perMethod[i].sel, perMethod[i].sv, final, fn);
757
1279
  for (const x of outVars.values())
758
1280
  init[x.name] = termOf(Exec.defaultOf(x.sort));
759
1281
  const wrote = new Set();
@@ -764,12 +1286,20 @@ function attempt(code, file, opts, written) {
764
1286
  else if (l.k === 'rec')
765
1287
  l.fields.forEach(([, x]) => walk(x));
766
1288
  else if (l.k === 'map')
767
- leaves.push(`map:${l.name}`); };
1289
+ leaves.push(`map:${l.name}`);
1290
+ else if (l.k === 'list')
1291
+ leaves.push(`list:${l.name}`); };
768
1292
  walk(lay);
769
- if (leaves.some(n => (n.startsWith('map:') ? final.maps.get(n.slice(4)) !== undefined : !sameTerm(final.leaves.get(n), Exec.valueOf(s.vars.get(n))))))
1293
+ if (leaves.some(n => (n.startsWith('map:') ? final.maps.get(n.slice(4)) !== undefined : n.startsWith('list:') ? !!final.lists?.get(n.slice(5))?.length : !sameTerm(final.leaves.get(n), Exec.valueOf(s.vars.get(n))))))
770
1294
  wrote.add(f);
771
1295
  }
772
1296
  const model = finish(s, { name: opts.entry, shape: 'class', file, entry: opts.entry, layout: { k: 'rec', fields: layout }, init, final, refuse: I.or(...perMethod.map(x => I.and(x.sel, x.refuse))), pre, events, outputs, event: ev.name, ctorArgs });
1297
+ model.results = results;
1298
+ // How the check reads and sets the state: two functions added to the object returned (at its end).
1299
+ const state = stateLayout.map(([n]) => n);
1300
+ const set = state.map(n => (fields.find(f => f.name === n).shape.k === 'list' ? `${n}.length = 0; ${n}.push(...__s.${n});` : fields.find(f => f.name === n).shape.k === 'map' ? `${n}.clear(); for (const [k, v] of (__s.${n} instanceof Map ? __s.${n} : Object.entries(__s.${n}))) ${n} instanceof Map ? ${n}.set(k, v) : (${n}[k] = v);` : `${n} = __s.${n};`)).join(' ');
1301
+ const shown = layout.map(([n]) => n).filter(n => !n.endsWith('()'));
1302
+ model.factory = { at: obj.properties.hasTrailingComma ? obj.end - 1 : obj.properties.at(-1).end, text: `${obj.properties.hasTrailingComma ? '' : ','} __gdpGet: () => ({${shown.join(', ')}}), __gdpSet: (__s) => { ${set} }` };
773
1303
  return { model, written: wrote };
774
1304
  }
775
1305
  function constLayout(v, p, at) {