gdp-wired 0.25.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 (50) hide show
  1. package/README.md +14 -9
  2. package/dist/core/accel.d.ts +1 -1
  3. package/dist/core/accel.js +336 -101
  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 +35 -131
  8. package/dist/core/cyclic.d.ts +4 -1
  9. package/dist/core/cyclic.js +86 -64
  10. package/dist/core/data.d.ts +1 -1
  11. package/dist/core/data.js +89 -118
  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.js +72 -18
  28. package/dist/core/machine.d.ts +6 -0
  29. package/dist/core/machine.js +35 -3
  30. package/dist/core/nonterm.d.ts +5 -1
  31. package/dist/core/nonterm.js +109 -41
  32. package/dist/core/q.d.ts +1 -0
  33. package/dist/core/q.js +2 -2
  34. package/dist/core/relation.d.ts +1 -0
  35. package/dist/core/relation.js +20 -36
  36. package/dist/core/solver.d.ts +12 -0
  37. package/dist/core/solver.js +76 -30
  38. package/dist/core/transfer.js +22 -13
  39. package/dist/core/translate.d.ts +1 -1
  40. package/dist/core/translate.js +22 -49
  41. package/dist/core/xstate.d.ts +6 -1
  42. package/dist/core/xstate.js +336 -55
  43. package/dist/kernel/cdcl.js +1 -2
  44. package/dist/kernel/prove.d.ts +6 -1
  45. package/dist/kernel/prove.js +96 -82
  46. package/dist/kernel/reader.d.ts +1 -0
  47. package/dist/kernel/reader.js +4 -3
  48. package/dist/kernel/simplex.d.ts +1 -1
  49. package/dist/kernel/simplex.js +13 -1
  50. package/package.json +3 -2
@@ -93,9 +93,19 @@ export function shapeOf(t, checker, at) {
93
93
  return refuse(at, 'a Map without its key and value types');
94
94
  return { k: 'map', key: keySort(shapeOf(kt, checker, at), at), val: shapeOf(vt, checker, at), js: 'Map' };
95
95
  }
96
- if (checker.isArrayType(t) || checker.isTupleType(t))
97
- return refuse(at, `${checker.typeToString(t)}: an array (lists are not in the subset yet)`);
98
- if (name === 'Set' || name === 'Date' || name === 'Promise')
96
+ if (checker.isTupleType(t))
97
+ return refuse(at, `${checker.typeToString(t)}: a tuple`);
98
+ if (checker.isArrayType(t)) {
99
+ const el = shapeOf(checker.getTypeArguments(t)[0], checker, at);
100
+ if (el.k !== 'num' && el.k !== 'bool' && el.k !== 'choice')
101
+ return refuse(at, `${checker.typeToString(t)}: an array of ${el.k === 'str' ? 'strings' : el.k === 'rec' ? 'records' : 'compound values'} (arrays of numbers, booleans and string unions are lists in the subset)`);
102
+ if (el.date)
103
+ return refuse(at, `${checker.typeToString(t)}: an array of Dates`);
104
+ return { k: 'list', of: el };
105
+ }
106
+ if (name === 'Date')
107
+ return { k: 'num', date: true };
108
+ if (name === 'Set' || name === 'Promise')
99
109
  return refuse(at, `a ${name}`);
100
110
  const sidx = checker.getIndexInfoOfType(t, ts.IndexKind.String), nidx = checker.getIndexInfoOfType(t, ts.IndexKind.Number);
101
111
  if (sidx || nidx) {
@@ -217,6 +227,10 @@ export class Exec {
217
227
  mergeV(c, va, vb, a, b, heap, pairs, at) {
218
228
  va = this.deref(a, va);
219
229
  vb = this.deref(b, vb);
230
+ if (va.t === 'outside' && vb.t === 'outside' && va.path === vb.path)
231
+ return va;
232
+ if (va.t === 'opaque' && vb.t === 'opaque')
233
+ return va;
220
234
  if (va.t === 'num' && vb.t === 'num')
221
235
  return { t: 'num', e: I.nite(c, va.e, vb.e) };
222
236
  if (va.t === 'bool' && vb.t === 'bool')
@@ -228,12 +242,12 @@ export class Exec {
228
242
  return { t: 'choice', e: I.lite(c, this.asChoice(va, values, at), this.asChoice(vb, values, at)), values };
229
243
  }
230
244
  if (va.t === 'undef' && vb.t === 'undef')
231
- return va;
245
+ return va.null === vb.null ? va : refuse(at, 'null on one path and undefined on another');
232
246
  if (va.t === 'opt' || vb.t === 'opt' || va.t === 'undef' || vb.t === 'undef') {
233
247
  const [ha, xa] = va.t === 'opt' ? [va.has, va.v] : va.t === 'undef' ? [I.F, undefined] : [I.T, va];
234
248
  const [hb, xb] = vb.t === 'opt' ? [vb.has, vb.v] : vb.t === 'undef' ? [I.F, undefined] : [I.T, vb];
235
- const v = !xa ? xb : !xb ? xa : this.mergeV(c, xa, xb, a, b, heap, pairs, at);
236
- return { t: 'opt', has: I.bite(c, ha, hb), v };
249
+ const v = !xa && !xb ? refuse(at, 'a value missing on both paths') : !xa ? xb : !xb ? xa : this.mergeV(c, xa, xb, a, b, heap, pairs, at);
250
+ return { t: 'opt', has: I.bite(c, ha, hb), v, ...nullOf(at, va, vb) };
237
251
  }
238
252
  if (va.t === 'cell' && vb.t === 'cell' && va.map === vb.map) {
239
253
  // Current on both paths (the map not set since it was read on either): current in the map merged.
@@ -254,11 +268,19 @@ export class Exec {
254
268
  if (oa.k === 'alias' && ob.k === 'alias')
255
269
  return { k: 'alias', to: this.mergeV(c, oa.to, ob.to, a, b, heap, pairs, at) };
256
270
  if (oa.k === 'rec' && ob.k === 'rec') {
257
- const fa = [...oa.fields.keys()].sort().join(), fb = [...ob.fields.keys()].sort().join();
271
+ // An untyped record grows a field as it is read (an input): read on one path, it is there on the other too.
272
+ const fA = oa.lazy && ob.lazy ? new Map([...ob.fields, ...oa.fields]) : oa.fields, fB = oa.lazy && ob.lazy ? new Map([...oa.fields, ...ob.fields]) : ob.fields;
273
+ const fa = [...fA.keys()].sort().join(), fb = [...fB.keys()].sort().join();
258
274
  if (fa !== fb)
259
275
  return refuse(at, 'an object with other fields by the path taken');
260
276
  const origin = oa.origin === 'input' || ob.origin === 'input' ? 'input' : oa.origin === 'shared' || ob.origin === 'shared' ? 'shared' : oa.origin;
261
- return { k: 'rec', origin, fields: new Map([...oa.fields].map(([f, v]) => [f, this.mergeV(c, v, ob.fields.get(f), a, b, heap, pairs, at)])), ...(oa.lazy ? { lazy: oa.lazy } : {}) };
277
+ return { k: 'rec', origin, fields: new Map([...fA].map(([f, v]) => [f, this.mergeV(c, v, fB.get(f), a, b, heap, pairs, at)])), ...(oa.lazy ? { lazy: oa.lazy } : {}) };
278
+ }
279
+ if (oa.k === 'list' && ob.k === 'list') {
280
+ if (oa.base !== ob.base)
281
+ return refuse(at, 'one of two lists by the path taken');
282
+ const origin = oa.origin === 'input' || ob.origin === 'input' ? 'input' : oa.origin;
283
+ return { ...oa, origin, ops: [...oa.ops.map(o => ({ ...o, when: I.and(c, o.when) })), ...ob.ops.map(o => ({ ...o, when: I.and(I.not(c), o.when) }))] };
262
284
  }
263
285
  if (oa.k === 'map' && ob.k === 'map') {
264
286
  if (oa.base !== ob.base)
@@ -347,6 +369,8 @@ export class Exec {
347
369
  refuse(st, 'var (let or const are in the subset)');
348
370
  let q = p;
349
371
  for (const d of st.declarationList.declarations) {
372
+ if (isDate(this.s.checker.getTypeAtLocation(d.name)) && !freshDate(d.initializer))
373
+ refuse(d, `${d.name.getText()}: a second name for a Date (its time is read where it is held: getTime())`);
350
374
  let v = { t: 'undef' };
351
375
  if (d.initializer)
352
376
  [v, q] = this.ev(d.initializer, q);
@@ -478,12 +502,15 @@ export class Exec {
478
502
  case 'bool': return v.e;
479
503
  case 'num': return I.not(I.cmp('=', v.e, I.num(0)));
480
504
  case 'choice': return v.values.includes('') ? I.not(I.is(v.e, '')) : I.T;
481
- case 'str': return v.e.op === 'slit' ? (v.e.value ? I.T : I.F) : refuse(at, 'a string as a condition');
505
+ // A string is truthy where it isn't empty.
506
+ case 'str': return v.e.op === 'slit' ? (v.e.value ? I.T : I.F) : I.not(I.keq(v.e, { op: 'slit', value: '' }));
482
507
  case 'ref':
483
508
  case 'cell':
484
- case 'phi': return I.T;
509
+ case 'phi':
510
+ case 'outside': return I.T;
485
511
  case 'opt': return I.and(v.has, this.truthy(v.v, at));
486
512
  case 'undef': return I.F;
513
+ case 'opaque': return refuse(at, `${text(at)} read as a condition: ${v.what}`);
487
514
  }
488
515
  }
489
516
  num(v, at, p) {
@@ -493,10 +520,22 @@ export class Exec {
493
520
  return this.num(v.v, at, p);
494
521
  if (v.t === 'opt')
495
522
  return refuse(at, `${text(at)} may be missing (undefined): give a default (?? 0) or check for it first`);
496
- return refuse(at, `${text(at)} is a ${v.t === 'bool' ? 'boolean' : v.t === 'choice' || v.t === 'str' ? 'string' : v.t === 'undef' ? 'undefined' : 'object'} where a number is read`);
523
+ if (v.t === 'opaque')
524
+ return refuse(at, `${text(at)} read as a number: ${v.what}`);
525
+ return refuse(at, `${text(at)} is a ${v.t === 'bool' ? 'boolean' : v.t === 'choice' || v.t === 'str' ? 'string' : v.t === 'undef' ? (v.null ? 'null' : 'undefined') : 'object'} where a number is read`);
497
526
  }
498
527
  bool(v, at) { return v.t === 'bool' ? v.e : refuse(at, `${text(at)} where a boolean is read`); }
499
- equal(a, b, at) {
528
+ equal(a, b, at, loose = false) {
529
+ if (a.t === 'opaque' || b.t === 'opaque')
530
+ return refuse(at, `${text(at)} compares ${(a.t === 'opaque' ? a : b).what}`);
531
+ // Missing values: null and undefined are == to each other, === each to itself; one that may be missing is equal to a
532
+ // missing one where it is missing, to a value where it is there and equal.
533
+ if (a.t === 'opt' || b.t === 'opt' || (a.t === 'undef' && b.t === 'undef')) {
534
+ const parts = (x) => (x.t === 'opt' ? [x.has, x.v, !!x.null] : x.t === 'undef' ? [I.F, undefined, !!x.null] : [I.T, x, false]);
535
+ const [ha, va, na] = parts(a), [hb, vb, nb] = parts(b);
536
+ const bothMissing = loose || na === nb ? I.and(I.not(ha), I.not(hb)) : I.F;
537
+ return I.or(bothMissing, va && vb ? I.and(ha, hb, this.equal(va, vb, at, loose)) : I.F);
538
+ }
500
539
  if (a.t === 'num' && b.t === 'num')
501
540
  return I.cmp('=', a.e, b.e);
502
541
  if (a.t === 'bool' && b.t === 'bool')
@@ -507,10 +546,9 @@ export class Exec {
507
546
  return this.equal(b, a, at);
508
547
  if (a.t === 'str' && b.t === 'str')
509
548
  return I.keq(a.e, b.e);
510
- if (a.t === 'undef' || b.t === 'undef') {
511
- const o = a.t === 'undef' ? b : a;
512
- return o.t === 'undef' ? I.T : o.t === 'opt' ? I.not(o.has) : I.F;
513
- }
549
+ // A missing value and one that is there: never equal.
550
+ if (a.t === 'undef' || b.t === 'undef')
551
+ return I.F;
514
552
  return refuse(at, `a comparison of a ${a.t} with a ${b.t}`);
515
553
  }
516
554
  ev(e, p) {
@@ -537,10 +575,10 @@ export class Exec {
537
575
  if (e.kind === ts.SyntaxKind.FalseKeyword)
538
576
  return [{ t: 'bool', e: I.F }, p];
539
577
  if (e.kind === ts.SyntaxKind.NullKeyword)
540
- return refuse(e, 'null');
578
+ return [{ t: 'undef', null: true }, p];
541
579
  if (e.kind === ts.SyntaxKind.ThisKeyword) {
542
- if (!p.heap.has('this'))
543
- refuse(e, 'this outside a class');
580
+ if (!p.heap.has('this') || this.s.closure)
581
+ refuse(e, this.s.closure ? 'this in an object a factory makes (its functions close over the factory\'s variables: this is the object, called as it is called)' : 'this outside a class');
544
582
  return [{ t: 'ref', id: 'this' }, p];
545
583
  }
546
584
  if (ts.isIdentifier(e))
@@ -573,7 +611,7 @@ export class Exec {
573
611
  if (ts.isNewExpression(e))
574
612
  return this.newExpr(e, p);
575
613
  if (ts.isArrayLiteralExpression(e))
576
- return refuse(e, 'an array (lists are not in the subset yet)');
614
+ return this.array(e, p);
577
615
  if (ts.isTemplateExpression(e))
578
616
  return refuse(e, 'a template string');
579
617
  if (ts.isArrowFunction(e) || ts.isFunctionExpression(e))
@@ -603,6 +641,9 @@ export class Exec {
603
641
  return refuse(e, `${e.text} (the subset's numbers are integers)`);
604
642
  const sym = this.resolved(e);
605
643
  const decl = sym?.valueDeclaration ?? sym?.declarations?.[0];
644
+ // A factory's own variable (or argument), closed over by the object it returns: a field of that object's state.
645
+ if (decl && this.s.closure?.has(decl))
646
+ return this.field({ t: 'ref', id: 'this' }, e.text, e, p);
606
647
  if (decl && ts.isVariableDeclaration(decl) && decl.initializer && this.s.ours(decl.getSourceFile()) && ts.isVariableStatement(decl.parent.parent) && ts.isSourceFile(decl.parent.parent.parent)) {
607
648
  if (!(decl.parent.flags & ts.NodeFlags.Const))
608
649
  return refuse(e, `${e.text}: a module-level let (state outside the step)`);
@@ -692,14 +733,18 @@ export class Exec {
692
733
  return [{ t: 'bool', e: I.cmp('<', n(r, e.right), n(l, e.left)) }, q2];
693
734
  if (op === S.GreaterThanEqualsToken)
694
735
  return [{ t: 'bool', e: I.cmp('<=', n(r, e.right), n(l, e.left)) }, q2];
736
+ if ((op === S.EqualsEqualsEqualsToken || op === S.EqualsEqualsToken || op === S.ExclamationEqualsEqualsToken || op === S.ExclamationEqualsToken) && (isDate(this.s.checker.getTypeAtLocation(e.left)) || isDate(this.s.checker.getTypeAtLocation(e.right))))
737
+ return refuse(e, 'two Dates compared by === (that is whether they are one object; their times are compared by getTime())');
695
738
  if (op === S.EqualsEqualsEqualsToken || op === S.EqualsEqualsToken)
696
- return [{ t: 'bool', e: this.equal(l, r, e) }, q2];
739
+ return [{ t: 'bool', e: this.equal(l, r, e, op === S.EqualsEqualsToken) }, q2];
697
740
  if (op === S.ExclamationEqualsEqualsToken || op === S.ExclamationEqualsToken)
698
- return [{ t: 'bool', e: I.not(this.equal(l, r, e)) }, q2];
741
+ return [{ t: 'bool', e: I.not(this.equal(l, r, e, op === S.ExclamationEqualsToken)) }, q2];
699
742
  if (op === S.PlusToken || op === S.MinusToken || op === S.AsteriskToken || op === S.PercentToken)
700
743
  return [this.arith(op, l, r, e, q2), q2];
744
+ // A fraction is a binary float in the code: each operation on it rounds (0.1 + 0.2 is not 0.3), so a rule over ℚ
745
+ // (gdp-wired/rationals) is the code only where nothing rounds, which no check shows; refused, with what is read.
701
746
  if (op === S.SlashToken)
702
- return refuse(e, 'a division (its result may be a fraction): Math.floor(x / k) for a constant k is in the subset');
747
+ return refuse(e, 'a division whose result may be a fraction (a binary float in the code: each operation on it rounds, where a rule over the rationals would not; Math.floor or Math.ceil of x / k for a constant k is in the subset)');
703
748
  if (op === S.AsteriskAsteriskToken)
704
749
  return refuse(e, 'a power');
705
750
  if (op === S.CommaToken)
@@ -769,6 +814,9 @@ export class Exec {
769
814
  const fields = new Map();
770
815
  for (const prop of e.properties) {
771
816
  if (ts.isSpreadAssignment(prop)) {
817
+ const st = this.s.checker.getTypeAtLocation(prop.expression);
818
+ if (this.s.checker.getPropertiesOfType(st).some(x => isDate(this.s.checker.getTypeOfSymbolAtLocation(x, prop))))
819
+ refuse(prop, 'a spread of an object holding a Date (the copy and the original share it)');
772
820
  const [v, q2] = this.ev(prop.expression, q);
773
821
  q = q2;
774
822
  const src = v.t === 'ref' ? this.obj(q, v.id) : undefined;
@@ -781,6 +829,8 @@ export class Exec {
781
829
  }
782
830
  else if (ts.isPropertyAssignment(prop)) {
783
831
  const name = ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name) ? prop.name.text : refuse(prop, 'a computed field name on an object');
832
+ if (isDate(this.s.checker.getTypeAtLocation(prop.initializer)) && !freshDate(prop.initializer))
833
+ refuse(prop, `${name}: a Date held elsewhere (one object in two places)`);
784
834
  const [v, q2] = this.ev(prop.initializer, q);
785
835
  q = q2;
786
836
  fields.set(name, v);
@@ -823,6 +873,10 @@ export class Exec {
823
873
  }
824
874
  // Two values within one path, by a condition.
825
875
  phiV(c, x, y, at) {
876
+ if (x.t === 'outside' && y.t === 'outside' && x.path === y.path)
877
+ return x;
878
+ if (x.t === 'opaque' && y.t === 'opaque')
879
+ return x;
826
880
  if (x.t === 'num' && y.t === 'num')
827
881
  return { t: 'num', e: I.nite(c, x.e, y.e) };
828
882
  if (x.t === 'bool' && y.t === 'bool')
@@ -836,11 +890,11 @@ export class Exec {
836
890
  return { t: 'choice', e: I.lite(c, this.asChoice(x, values, at), this.asChoice(y, values, at)), values };
837
891
  }
838
892
  if (x.t === 'undef' && y.t === 'undef')
839
- return x;
893
+ return x.null === y.null ? x : refuse(at, 'null or undefined by a condition');
840
894
  if (x.t === 'opt' || y.t === 'opt' || x.t === 'undef' || y.t === 'undef') {
841
895
  const [hx, vx] = x.t === 'opt' ? [x.has, x.v] : x.t === 'undef' ? [I.F, undefined] : [I.T, x];
842
896
  const [hy, vy] = y.t === 'opt' ? [y.has, y.v] : y.t === 'undef' ? [I.F, undefined] : [I.T, y];
843
- return { t: 'opt', has: I.bite(c, hx, hy), v: !vx ? vy : !vy ? vx : this.phiV(c, vx, vy, at) };
897
+ return { t: 'opt', has: I.bite(c, hx, hy), v: !vx ? vy : !vy ? vx : this.phiV(c, vx, vy, at), ...nullOf(at, x, y) };
844
898
  }
845
899
  if (x.t === 'ref' && y.t === 'ref' && x.id === y.id)
846
900
  return x;
@@ -869,6 +923,8 @@ export class Exec {
869
923
  const x = cell.vals.get(f);
870
924
  return x ? [x, p] : refuse(at, `no field ${f}`);
871
925
  }
926
+ if (v.t === 'outside')
927
+ return refuse(at, `${text(at)}: a function from outside used as a value`);
872
928
  if (v.t !== 'ref')
873
929
  return refuse(at, `${text(at)}: a field of a ${v.t}`);
874
930
  const o = this.obj(p, v.id);
@@ -880,8 +936,33 @@ export class Exec {
880
936
  if (o.lazy) {
881
937
  // Its sort: compared with literals, a choice among them; else its type where it has one (an XState event's
882
938
  // payload, typed by setup's types); else a number.
883
- const typed = (() => { const t = this.s.checker.getTypeAtLocation(at); if (t.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown))
884
- return undefined; const sh = shapeOf(t, this.s.checker, at); return sh.k === 'num' || sh.k === 'bool' || sh.k === 'choice' || sh.k === 'str' ? sh : undefined; })();
939
+ // In XState's guards and actions, a payload field of a type outside the subset (an object, a value that may be
940
+ // missing) is opaque: refused where it is read, kept where it is only passed on.
941
+ let opaque;
942
+ const typed = (() => {
943
+ const t = this.s.checker.getTypeAtLocation(at);
944
+ if (t.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) {
945
+ if (this.s.xstate && t.flags & ts.TypeFlags.Unknown)
946
+ opaque = `${text(at)} is of type unknown`;
947
+ return undefined;
948
+ }
949
+ let sh;
950
+ try {
951
+ sh = shapeOf(t, this.s.checker, at);
952
+ }
953
+ catch (x) {
954
+ if (this.s.xstate && x instanceof Refusal) {
955
+ opaque = x.what;
956
+ return undefined;
957
+ }
958
+ throw x;
959
+ }
960
+ if (this.s.xstate && sh.k !== 'num' && sh.k !== 'bool' && sh.k !== 'choice' && sh.k !== 'str')
961
+ opaque = `${text(at)} is a ${sh.k === 'rec' ? 'record' : 'map'} (not a value the subset reads)`;
962
+ return sh.k === 'num' || sh.k === 'bool' || sh.k === 'choice' || sh.k === 'str' ? sh : undefined;
963
+ })();
964
+ if (opaque)
965
+ return [{ t: 'opaque', what: opaque }, p];
885
966
  const path = `${o.lazy.prefix}${f}`, sort = this.s.lazySorts.get(path) ?? typed ?? { k: 'num' };
886
967
  // The same field read again (in another guard or action, say) is the same input.
887
968
  const seen = [...this.s.lazy].find(([, l]) => l.prefix === o.lazy.prefix && l.field === f)?.[0];
@@ -891,7 +972,7 @@ export class Exec {
891
972
  return [nv, { ...p, heap: new Map(p.heap).set(v.id, { ...o, fields }) }];
892
973
  }
893
974
  if (v.id === 'this' && this.s.cls) {
894
- const member = this.s.cls.members.find(m => m.name && memberName(m.name) === f);
975
+ const member = this.member(f);
895
976
  if (member && ts.isGetAccessorDeclaration(member))
896
977
  return this.inline({ decl: member, self: 'this' }, [], at, p);
897
978
  if (member && ts.isMethodDeclaration(member))
@@ -917,14 +998,27 @@ export class Exec {
917
998
  if (o?.k === 'map')
918
999
  return refuse(e, `${f} of a map (get, set, has and delete are in the subset)`);
919
1000
  }
1001
+ if (base.t === 'ref') {
1002
+ const o = this.obj(q, base.id);
1003
+ if (o?.k === 'list') {
1004
+ if (f !== 'length')
1005
+ return refuse(e, `${f} of an array (length, [i], push, pop and [i] = x are in the subset)`);
1006
+ return [{ t: 'num', e: this.listLen(o, e) }, q];
1007
+ }
1008
+ }
920
1009
  if (f === 'length')
921
- return refuse(e, 'length (lists and strings are not in the subset yet)');
1010
+ return refuse(e, 'length of a string (strings are compared and set in the subset)');
922
1011
  return this.field(base, f, e, q);
923
1012
  }
924
1013
  const arg = e.argumentExpression;
925
1014
  const b = this.deref(q, base);
926
1015
  if (b.t === 'ref') {
927
1016
  const o = this.obj(q, b.id);
1017
+ if (o?.k === 'list') {
1018
+ // xs[i]: the item there, or undefined past either end.
1019
+ const [k, q2] = this.ev(arg, q), i = this.num(k, arg, q2), len = this.listLen(o, e);
1020
+ return [{ t: 'opt', has: I.and(I.cmp('<=', I.num(0), i), I.cmp('<', i, len)), v: Exec.cellOf(o.decl, { op: 'num', e: i }, o.decl.fields[0]) }, q2];
1021
+ }
928
1022
  if (o?.k === 'map') {
929
1023
  if (o.decl.js !== 'record')
930
1024
  return refuse(e, 'a Map read with [ ] (get is how a Map is read)');
@@ -1002,10 +1096,24 @@ export class Exec {
1002
1096
  }
1003
1097
  }
1004
1098
  // Assignment: to a local, a field (of this, or of an object the step made), a map's key, or through a cell.
1005
- assign(target, v, p) {
1099
+ assign(target, v, p, setTime = false) {
1006
1100
  if (ts.isParenthesizedExpression(target))
1007
- return this.assign(target.expression, v, p);
1101
+ return this.assign(target.expression, v, p, setTime);
1102
+ // A Date is an object: one written where it is held is a new one (new Date(...)), or its time set (setTime); one taken
1103
+ // from another place would be shared by both (a setTime through one moves the other).
1104
+ if (!setTime && isDate(this.s.checker.getTypeAtLocation(target))) {
1105
+ const rhs = ts.isBinaryExpression(target.parent) && target.parent.left === target ? target.parent.right : undefined;
1106
+ const fresh = (x) => !!x && (ts.isParenthesizedExpression(x) ? fresh(x.expression) : ts.isNewExpression(x) && ts.isIdentifier(x.expression) && x.expression.text === 'Date');
1107
+ if (!fresh(rhs))
1108
+ return refuse(target, `${text(target)} set to a Date held elsewhere (one object in two places: a setTime through one moves the other)`);
1109
+ }
1008
1110
  if (ts.isIdentifier(target)) {
1111
+ const cd = !p.locals.has(target.text) ? this.s.checker.getSymbolAtLocation(target)?.valueDeclaration : undefined;
1112
+ if (cd && this.s.closure?.has(cd)) {
1113
+ if (ts.isVariableDeclaration(cd) && cd.parent.flags & ts.NodeFlags.Const)
1114
+ return refuse(target, `${target.text} is a const`);
1115
+ return this.writeField({ t: 'ref', id: 'this' }, target.text, v, p, target);
1116
+ }
1009
1117
  if (!p.locals.has(target.text))
1010
1118
  return refuse(target, `${target.text}: an assignment to a name outside the step`);
1011
1119
  const sym = this.s.checker.getSymbolAtLocation(target), decl = sym?.valueDeclaration;
@@ -1019,6 +1127,13 @@ export class Exec {
1019
1127
  const b = this.deref(q, base);
1020
1128
  if (ts.isElementAccessExpression(target) && b.t === 'ref') {
1021
1129
  const o = this.obj(q, b.id);
1130
+ if (o?.k === 'list') {
1131
+ // xs[i] = x: within the list only (past its end the array grows, with holes where nothing was set).
1132
+ const [k, q2] = this.ev(target.argumentExpression, q), i = this.num(k, target.argumentExpression, q2), len = this.listLen(o, target);
1133
+ if (!this.known(q2, I.cmp('<=', I.num(0), i)) || !this.known(q2, I.cmp('<', i, len)))
1134
+ return refuse(target, `${text(target)} = ...: an index the code doesn't keep within the array (past its end the array grows, with holes)`);
1135
+ return this.listOp(b.id, { op: 'set', i, x: v, when: I.T }, target, q2);
1136
+ }
1022
1137
  if (o?.k === 'map') {
1023
1138
  const [k, q2] = this.ev(target.argumentExpression, q);
1024
1139
  return this.mapSet(b.id, this.key(k, target.argumentExpression, o.decl), v, target, q2);
@@ -1073,6 +1188,9 @@ export class Exec {
1073
1188
  const om = this.obj(q, old.id);
1074
1189
  if (om?.k === 'map')
1075
1190
  return refuse(target, `${f}: a map replaced in a step (clearing every key is not in the subset yet)`);
1191
+ const nl = this.obj(q, v.id);
1192
+ if (om?.k === 'list' && (nl?.k !== 'list' || nl.base !== om.base || nl.origin === 'this'))
1193
+ return refuse(target, `${f} set to ${nl?.k === 'list' && nl.base !== om.base ? 'another array (one array in two places, or another list)' : nl?.k === 'list' ? 'itself' : 'other than a copy of itself'}`);
1076
1194
  }
1077
1195
  const heap = new Map(q.heap).set(id, { ...o, fields: new Map(o.fields).set(f, v) });
1078
1196
  return { ...q, heap, wrote: o.origin === 'this' ? [...new Set([...q.wrote, f])] : q.wrote };
@@ -1121,15 +1239,60 @@ export class Exec {
1121
1239
  }
1122
1240
  if (ts.isIdentifier(obj) && ['Number', 'Object', 'JSON', 'Array', 'String', 'Promise', 'performance'].includes(obj.text))
1123
1241
  return refuse(e, `${obj.text}.${m}`);
1242
+ // A function the factory is given: its answer is an input of the step (any value of its type), read once.
1243
+ if (ts.isIdentifier(obj) && p.locals.get(obj.text)?.t === 'outside')
1244
+ return this.outside(e, `${p.locals.get(obj.text).path}.${m}`, p);
1124
1245
  if (obj.kind === ts.SyntaxKind.ThisKeyword && this.s.cls) {
1125
- const member = this.s.cls.members.find(x => x.name && memberName(x.name) === m);
1246
+ const member = this.member(m);
1126
1247
  if (member && ts.isMethodDeclaration(member)) {
1127
1248
  const [args, q] = this.args(e.arguments, p);
1128
1249
  return this.inline({ decl: member, self: 'this' }, args, e, q);
1129
1250
  }
1130
1251
  }
1252
+ // super.m(): the nearest m above the class the call is written in (resolved where it is written, not by the object).
1253
+ if (obj.kind === ts.SyntaxKind.SuperKeyword && this.s.chain) {
1254
+ let c = e;
1255
+ while (c && !ts.isClassLike(c))
1256
+ c = c.parent;
1257
+ const k = this.s.chain.indexOf(c), member = k >= 0 ? this.member(m, k + 1) : undefined;
1258
+ if (!member || !ts.isMethodDeclaration(member))
1259
+ return refuse(e, `super.${m}: no method ${m} above ${c?.name?.text ?? 'this class'}`);
1260
+ const [args, q] = this.args(e.arguments, p);
1261
+ return this.inline({ decl: member, self: 'this' }, args, e, q);
1262
+ }
1263
+ // A Date's time: getTime() (or valueOf()) reads it; setTime(t) sets it where the Date is (a field, not a second
1264
+ // name for it).
1265
+ if (isDate(this.s.checker.getTypeAtLocation(obj)) && (m === 'getTime' || m === 'valueOf') && !e.arguments.length) {
1266
+ const [v, q] = this.ev(obj, p);
1267
+ return [{ t: 'num', e: this.num(v, obj, q) }, q];
1268
+ }
1269
+ if (isDate(this.s.checker.getTypeAtLocation(obj)) && m === 'setTime' && e.arguments.length === 1) {
1270
+ const target = ts.isParenthesizedExpression(obj) ? obj.expression : obj;
1271
+ if (!ts.isPropertyAccessExpression(target) && !ts.isElementAccessExpression(target))
1272
+ return refuse(e, `setTime on ${text(target)}, a second name for a Date (its time is set where it is held)`);
1273
+ const [v, q] = this.ev(e.arguments[0], p), t = { t: 'num', e: this.num(v, e.arguments[0], q) };
1274
+ return [t, this.assign(target, t, q, true)];
1275
+ }
1276
+ if (isDate(this.s.checker.getTypeAtLocation(obj)))
1277
+ return refuse(e, `Date.prototype.${m} (a Date's time is read by getTime and set by setTime)`);
1131
1278
  const [base, q] = this.ev(obj, p), b = this.deref(q, base);
1132
1279
  const o = b.t === 'ref' ? this.obj(q, b.id) : undefined;
1280
+ if (o?.k === 'list' && b.t === 'ref') {
1281
+ const [args, q2] = this.args(e.arguments, q);
1282
+ if (m === 'push') {
1283
+ if (args.length !== 1)
1284
+ return refuse(e, 'push of other than one item');
1285
+ const len = this.listLen(o, e);
1286
+ return [{ t: 'num', e: I.add(len, I.num(1)) }, this.listOp(b.id, { op: 'push', x: args[0], when: I.T }, e, q2)];
1287
+ }
1288
+ if (m === 'pop') {
1289
+ if (args.length)
1290
+ return refuse(e, 'pop() takes no argument');
1291
+ const len = this.listLen(o, e), last = { t: 'opt', has: I.cmp('<', I.num(0), len), v: Exec.cellOf(o.decl, { op: 'num', e: I.sub(len, I.num(1)) }, o.decl.fields[0]) };
1292
+ return [last, this.listOp(b.id, { op: 'pop', when: I.T }, e, q2)];
1293
+ }
1294
+ return refuse(e, `the array method ${m} (length, [i], push, pop and [i] = x are in the subset)`);
1295
+ }
1133
1296
  if (o?.k === 'map' && b.t === 'ref') {
1134
1297
  const [args, q2] = this.args(e.arguments, q);
1135
1298
  const k = () => this.key(args[0] ?? refuse(e, `${m} with no key`), e.arguments[0], o.decl);
@@ -1147,6 +1310,13 @@ export class Exec {
1147
1310
  return refuse(e, `${text(callee)}: a method the subset doesn't read`);
1148
1311
  }
1149
1312
  if (ts.isIdentifier(callee)) {
1313
+ // Boolean(x): whether x is truthy.
1314
+ if (callee.text === 'Boolean' && !p.locals.has('Boolean') && e.arguments.length === 1) {
1315
+ const [v, q] = this.ev(e.arguments[0], p);
1316
+ return [{ t: 'bool', e: this.truthy(v, e.arguments[0]) }, q];
1317
+ }
1318
+ if (p.locals.get(callee.text)?.t === 'outside')
1319
+ return this.outside(e, p.locals.get(callee.text).path, p);
1150
1320
  const sym = this.resolved(callee), decl = sym?.valueDeclaration;
1151
1321
  const fn = decl && ts.isFunctionDeclaration(decl) ? decl : decl && ts.isVariableDeclaration(decl) && decl.initializer && (ts.isArrowFunction(decl.initializer) || ts.isFunctionExpression(decl.initializer)) ? decl.initializer : undefined;
1152
1322
  if (fn && this.s.ours(fn.getSourceFile())) {
@@ -1159,6 +1329,74 @@ export class Exec {
1159
1329
  }
1160
1330
  return refuse(e, 'a call the subset doesn\'t read');
1161
1331
  }
1332
+ outside(e, path, p) {
1333
+ const x = this.s.xstate ?? refuse(e, `${path}: a function from outside`);
1334
+ if (e.arguments.some(impure))
1335
+ refuse(e, `${path}(...) with arguments that have effects`);
1336
+ const [, q] = this.args(e.arguments, p);
1337
+ const t = this.s.checker.getTypeAtLocation(e);
1338
+ if (t.flags & (ts.TypeFlags.Void | ts.TypeFlags.Undefined)) {
1339
+ this.s.notes.add(`${path}() is an effect outside the machine (it returns nothing; left out)`);
1340
+ return [{ t: 'undef' }, q];
1341
+ }
1342
+ if (t.getSymbol()?.getName() === 'Promise')
1343
+ return refuse(e, `${path}() returns a promise (an answer that comes later is an actor's, invoked)`);
1344
+ const sh = shapeOf(t, this.s.checker, e);
1345
+ if (sh.k !== 'num' && sh.k !== 'bool' && sh.k !== 'choice' && sh.k !== 'str')
1346
+ return refuse(e, `${path}() returns a compound value`);
1347
+ if ([...x.outside.values()].some(o => o.path === path))
1348
+ return refuse(e, `${path}() read in two places (each call may answer differently)`);
1349
+ const v = this.newVar(path.split('.').pop(), sh, 'input', `${path}(): the answer of a function the machine is given (any value of its type)`);
1350
+ x.outside.set(v.name, { path, sort: sh });
1351
+ return [Exec.valueOf(v), q];
1352
+ }
1353
+ // --- arrays, as lists -------------------------------------------------------------------------------------------
1354
+ // Its length, read before it is written in the step (a read after would need the write's place: refused).
1355
+ listLen(o, at) {
1356
+ if (o.ops.length)
1357
+ return refuse(at, `${o.decl.name} read after it is written in one step`);
1358
+ return I.nvar(`${o.decl.name}_len`);
1359
+ }
1360
+ // A list's write: one a step (the list's apply takes the first of its operations whose condition holds).
1361
+ listOp(id, op, at, p) {
1362
+ id = this.mapId(p, id);
1363
+ const o = p.heap.get(id);
1364
+ if (o.origin === 'input')
1365
+ return refuse(at, `writes to ${o.decl.name} in the state it was given (React and Redux keep the old state; copy it first)`);
1366
+ if (o.origin === 'shared')
1367
+ return refuse(at, 'writes to a module-level array (every call shares it)');
1368
+ if (o.ops.length)
1369
+ return refuse(at, `a second write to ${o.decl.name} in one step (a rule's list takes one write a step)`);
1370
+ const x = op.op === 'pop' ? op : { ...op, x: this.cellValue(op.x, o.decl.fields[0], at, p) };
1371
+ return { ...p, heap: new Map(p.heap).set(id, { ...o, ops: [x] }), wrote: o.origin === 'this' ? [...new Set([...p.wrote, o.decl.name])] : p.wrote };
1372
+ }
1373
+ // [...xs] (a copy), [...xs, x] (a copy with x pushed); [] only as a state's start.
1374
+ array(e, p) {
1375
+ const [first, ...rest] = e.elements;
1376
+ if (!first || !ts.isSpreadElement(first) || rest.length > 1 || rest.some(ts.isSpreadElement))
1377
+ return refuse(e, e.elements.length ? 'an array made other than as [...xs] or [...xs, x]' : 'an empty array in a step (a list emptied whole is not in the subset)');
1378
+ const [v, q] = this.ev(first.expression, p), src = v.t === 'ref' ? this.obj(q, v.id) : undefined;
1379
+ if (src?.k !== 'list')
1380
+ return refuse(first, 'a spread of other than an array');
1381
+ if (src.ops.length)
1382
+ return refuse(first, `${src.decl.name} copied after it is written in one step`);
1383
+ const id = this.id('list');
1384
+ let r = { ...q, heap: new Map(q.heap).set(id, { ...src, origin: 'fresh', ops: [] }) };
1385
+ if (rest[0]) {
1386
+ const [x, r2] = this.ev(rest[0], r);
1387
+ r = this.listOp(id, { op: 'push', x, when: I.T }, rest[0], r2);
1388
+ }
1389
+ return [{ t: 'ref', id }, r];
1390
+ }
1391
+ // A member of the class by name, from the most derived (or from the k-th class up).
1392
+ member(name, from = 0) {
1393
+ for (const c of (this.s.chain ?? (this.s.cls ? [this.s.cls] : [])).slice(from)) {
1394
+ const m = c.members.find(x => x.name && memberName(x.name) === name && !(ts.isMethodDeclaration(x) && !x.body));
1395
+ if (m)
1396
+ return m;
1397
+ }
1398
+ return undefined;
1399
+ }
1162
1400
  math(m, e, p) {
1163
1401
  if (m === 'floor' || m === 'ceil') {
1164
1402
  const a = e.arguments[0];
@@ -1213,8 +1451,18 @@ export class Exec {
1213
1451
  const id = this.id('map');
1214
1452
  return [{ t: 'ref', id }, { ...q, heap: new Map(q.heap).set(id, { ...src, origin: 'fresh' }) }];
1215
1453
  }
1216
- if (ts.isIdentifier(c) && c.text === 'Date')
1217
- return refuse(e, 'new Date() (Date.now() is how the subset reads the time)');
1454
+ // new Date(): the time now (a read of Date.now()); new Date(t): the time t.
1455
+ if (ts.isIdentifier(c) && c.text === 'Date' && !p.locals.has('Date')) {
1456
+ const a = e.arguments ?? [];
1457
+ if (!a.length)
1458
+ return this.now(e, p);
1459
+ if (a.length !== 1)
1460
+ return refuse(e, 'new Date(y, m, ...) (a calendar date)');
1461
+ const [v, q] = this.ev(a[0], p);
1462
+ if (v.t !== 'num')
1463
+ return refuse(e, 'new Date of other than a number of milliseconds');
1464
+ return [v, q];
1465
+ }
1218
1466
  return refuse(e, `new ${text(c)}`);
1219
1467
  }
1220
1468
  // A function of the same module, or a method or getter of the class, run where it is called.
@@ -1234,6 +1482,8 @@ export class Exec {
1234
1482
  d.parameters.forEach((param, i) => {
1235
1483
  if (param.dotDotDotToken)
1236
1484
  refuse(param, 'a rest parameter');
1485
+ if (isDate(this.s.checker.getTypeAtLocation(param)))
1486
+ refuse(param, `${param.name.getText()}: a Date passed as an argument (a second name for it)`);
1237
1487
  let v = args[i];
1238
1488
  if (v === undefined) {
1239
1489
  if (!param.initializer)
@@ -1264,6 +1514,17 @@ export class Exec {
1264
1514
  }
1265
1515
  }
1266
1516
  // A map set on one path and not the other: a generation of its own, so a reference read before either is stale.
1517
+ // Missing as null or as undefined, the same on both sides (a value that is null on one and undefined on the other has
1518
+ // three cases a rule's maybe doesn't hold).
1519
+ const freshDate = (x) => !!x && (ts.isParenthesizedExpression(x) ? freshDate(x.expression) : ts.isNewExpression(x) && ts.isIdentifier(x.expression) && x.expression.text === 'Date');
1520
+ export const isDate = (t) => t.getSymbol()?.getName() === 'Date' || t.aliasSymbol?.getName() === 'Date';
1521
+ const nullOf = (at, a, b) => {
1522
+ const kind = (x) => (x.t === 'opt' || x.t === 'undef' ? (x.null ? 'null' : 'undefined') : undefined);
1523
+ const ka = kind(a), kb = kind(b);
1524
+ if (ka && kb && ka !== kb)
1525
+ refuse(at, 'a value that may be null on one side and undefined on the other');
1526
+ return ka === 'null' || kb === 'null' ? { null: true } : {};
1527
+ };
1267
1528
  const mergedGen = (a, b) => (a.gen === b.gen ? a.gen : Math.max(a.gen, b.gen) + 1);
1268
1529
  // The module an import names, for a refusal.
1269
1530
  const moduleOf = (d) => { let n = d; while (n && !ts.isImportDeclaration(n))
@@ -9,5 +9,19 @@ export type ReadOptions = {
9
9
  };
10
10
  export declare function readFunctions(code: string, file: string, opts: ReadOptions): Model;
11
11
  export declare function readClass(code: string, file: string, opts: ReadOptions): Model;
12
+ export type Result = {
13
+ k: 'scalar';
14
+ name: string;
15
+ } | {
16
+ k: 'rec';
17
+ fields: [string, string][];
18
+ } | {
19
+ k: 'maybe';
20
+ name: string;
21
+ missing: string;
22
+ null: boolean;
23
+ };
24
+ export declare const isFactory: (code: string, file: string, entry: string) => boolean;
25
+ export declare function readFactory(code: string, file: string, opts: ReadOptions): Model;
12
26
  export declare const isSlice: (code: string, entry: string) => boolean;
13
27
  export declare function readSlice(code: string, file: string, opts: ReadOptions): Model;