gdp-wired 0.30.0 → 0.31.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.
@@ -27,12 +27,15 @@ export class Retype extends Error {
27
27
  }
28
28
  }
29
29
  export const unparen = (x) => (ts.isParenthesizedExpression(x) ? unparen(x.expression) : x);
30
- const where = (n) => {
30
+ // An expression without its parentheses, casts and `!` (what it is, as the front ends read it).
31
+ export const bare = (x) => (ts.isParenthesizedExpression(x) || ts.isAsExpression(x) || ts.isSatisfiesExpression(x) || ts.isNonNullExpression(x) ? bare(x.expression) : x);
32
+ // Where a node is, and a refusal there (every TypeScript front end's).
33
+ export const where = (n) => {
31
34
  const sf = n.getSourceFile(), { line, character } = sf.getLineAndCharacterOfPosition(n.getStart());
32
35
  return `${sf.fileName.split('/').pop()}:${line + 1}:${character + 1}`;
33
36
  };
34
- const refuse = (n, what) => { throw new Refusal(where(n), what); };
35
- const text = (n) => n.getText().replace(/\s+/g, ' ').slice(0, 60);
37
+ export const refuse = (n, what) => { throw new Refusal(where(n), what); };
38
+ export const text = (n) => n.getText().replace(/\s+/g, ' ').slice(0, 60);
36
39
  // --- the program ----------------------------------------------------------------------------------------------------
37
40
  // A path, normalized (posix: the files are a repository's).
38
41
  export const normalize = (path) => {
@@ -56,11 +59,17 @@ export function program(code, file, extra = {}) {
56
59
  host.getSourceFile = (name, lang, ...rest) => (name === file ? ts.createSourceFile(name, code, lang, true, scriptKind(file)) : name in extra ? ts.createSourceFile(name, extra[name], lang, true, scriptKind(name)) : getSourceFile(name, lang, ...rest));
57
60
  host.readFile = name => (name === file ? code : name in extra ? extra[name] : readFile(name));
58
61
  host.fileExists = name => name === file || name in extra || fileExists(name);
59
- const dirExists = host.directoryExists?.bind(host), dirs = new Set(Object.keys(extra).flatMap(f => f.split('/').slice(1, -1).map((_, i, a) => `/${a.slice(0, i + 1).join('/')}`)));
62
+ const dirExists = host.directoryExists?.bind(host), dirs = new Set(Object.keys(extra).flatMap(f => { const p = f.split('/'); return p.slice(1, -1).map((_, i) => p.slice(0, i + 2).join('/')); }));
60
63
  host.directoryExists = d => dirs.has(d.replace(/\/$/, '')) || (dirExists ? dirExists(d) : true);
61
64
  const p = ts.createProgram([file], options, host);
62
65
  return { sf: p.getSourceFile(file), checker: p.getTypeChecker() };
63
66
  }
67
+ // Where the file sits: an absolute path as given (backslashes as slashes), a relative one in the working directory, so its
68
+ // imports (xstate, say) resolve as the project's do.
69
+ export function placed(file) {
70
+ const cwd = globalThis.process?.cwd?.() ?? '.';
71
+ return (/^([A-Za-z]:)?[\\/]/.test(file) ? file : `${cwd}/${file}`).replace(/\\/g, '/');
72
+ }
64
73
  export const scriptKind = (file) => (/\.jsx$/.test(file) ? ts.ScriptKind.JSX : /\.tsx$/.test(file) ? ts.ScriptKind.TSX : /\.[cm]?js$/.test(file) ? ts.ScriptKind.JS : ts.ScriptKind.TS);
65
74
  // The shape a type has in the subset.
66
75
  // (`inner`: the field path inside the value at `at` that t is the type of, for where a refusal says it is)
@@ -89,7 +98,7 @@ export function shapeOf(t, checker, at, inner) {
89
98
  return refuse(at, inner ? `${(ts.isPropertyDeclaration(at) || ts.isParameter(at) || ts.isPropertySignature(at)) && ts.isIdentifier(at.name) ? at.name.text : text(at)}.${inner} has no type the subset reads (any or unknown${t.flags & ts.TypeFlags.Any ? ': a type not among the files read, say' : ''})` : `${text(at)} has no type the subset reads (any or unknown): annotate it`);
90
99
  if (t.flags & ts.TypeFlags.Object) {
91
100
  const sym = t.getSymbol() ?? t.aliasSymbol, name = sym?.getName();
92
- if (name === 'Map') {
101
+ if (name === 'Map' || name === 'ReadonlyMap') {
93
102
  const [kt, vt] = checker.getTypeArguments(t);
94
103
  if (!kt || !vt)
95
104
  return refuse(at, 'a Map without its key and value types');
@@ -107,7 +116,12 @@ export function shapeOf(t, checker, at, inner) {
107
116
  }
108
117
  if (name === 'Date')
109
118
  return { k: 'num', date: true };
110
- if (name === 'Set' || name === 'Promise')
119
+ // A Set: a map of the keys it holds (each cell its `has` alone).
120
+ if (name === 'Set' || name === 'ReadonlySet') {
121
+ const [kt] = checker.getTypeArguments(t);
122
+ return kt ? { k: 'map', key: keySort(shapeOf(kt, checker, at), at), val: { k: 'rec', fields: [] }, js: 'Set' } : refuse(at, 'a Set without its type');
123
+ }
124
+ if (name === 'Promise')
111
125
  return refuse(at, `a ${name}`);
112
126
  const sidx = checker.getIndexInfoOfType(t, ts.IndexKind.String), nidx = checker.getIndexInfoOfType(t, ts.IndexKind.Number);
113
127
  if (sidx || nidx) {
@@ -261,6 +275,8 @@ export class Exec {
261
275
  }
262
276
  if (va.t === 'ref' && vb.t === 'ref' && va.id === vb.id)
263
277
  return va;
278
+ if ((va.t === 'eff' && vb.t === 'eff') || (va.t === 'tuple' && vb.t === 'tuple'))
279
+ return this.phiV(c, va, vb, at);
264
280
  // Two objects by the path taken: a reference to each by the condition.
265
281
  const refs = ['ref', 'cell', 'phi'];
266
282
  if (refs.includes(va.t) && refs.includes(vb.t))
@@ -326,7 +342,7 @@ export class Exec {
326
342
  let live = p;
327
343
  const rets = [], breaks = [];
328
344
  for (const st of stmts) {
329
- if (!live)
345
+ if (!live || !this.feasible(live))
330
346
  break;
331
347
  if (ts.isVariableStatement(st))
332
348
  for (const d of st.declarationList.declarations)
@@ -509,6 +525,8 @@ export class Exec {
509
525
  case 'opt': return I.and(v.has, this.truthy(v.v, at));
510
526
  case 'undef': return I.F;
511
527
  case 'opaque': return refuse(at, `${text(at)} read as a condition: ${v.what}`);
528
+ case 'eff':
529
+ case 'tuple': return refuse(at, `${text(at)}: an ${v.t === 'eff' ? 'effect' : 'array'} read as a condition`);
512
530
  }
513
531
  }
514
532
  num(v, at, p) {
@@ -552,6 +570,9 @@ export class Exec {
552
570
  ev(e, p) {
553
571
  if (ts.isParenthesizedExpression(e) || ts.isAsExpression(e) || ts.isSatisfiesExpression(e) || ts.isTypeAssertionExpression(e))
554
572
  return this.ev(e.expression, p);
573
+ const fe = this.s.effect?.(this, e, p);
574
+ if (fe)
575
+ return fe;
555
576
  if (ts.isNonNullExpression(e)) {
556
577
  const [v, q] = this.ev(e.expression, p);
557
578
  if (v.t !== 'opt')
@@ -824,8 +845,18 @@ export class Exec {
824
845
  const st = this.s.checker.getTypeAtLocation(prop.expression);
825
846
  if (this.s.checker.getPropertiesOfType(st).some(x => isDate(this.s.checker.getTypeOfSymbolAtLocation(x, prop))))
826
847
  refuse(prop, 'a spread of an object holding a Date (the copy and the original share it)');
827
- const [v, q2] = this.ev(prop.expression, q);
848
+ const [v0, q2] = this.ev(prop.expression, q);
828
849
  q = q2;
850
+ // A value known to be there (narrowed on the path), and a map's cell: its values copied.
851
+ const v = this.deref(q, v0.t === 'opt' && this.known(q, v0.has) ? v0.v : v0);
852
+ if (v.t === 'cell') {
853
+ const mo = q.heap.get(v.map);
854
+ if (mo.gen !== v.gen)
855
+ return refuse(prop, 'a spread of a reference into a map read before the map was set');
856
+ for (const [f, fv] of this.readCell(mo, v.key).vals)
857
+ fields.set(f, fv);
858
+ continue;
859
+ }
829
860
  const src = v.t === 'ref' ? this.obj(q, v.id) : undefined;
830
861
  if (src?.k !== 'rec')
831
862
  return refuse(prop, 'a spread of other than an object');
@@ -905,6 +936,11 @@ export class Exec {
905
936
  }
906
937
  if (x.t === 'ref' && y.t === 'ref' && x.id === y.id)
907
938
  return x;
939
+ // An effect by a condition: each run where it is the one; a tuple, item by item.
940
+ if (x.t === 'eff' && y.t === 'eff')
941
+ return { t: 'eff', run: q => { const [va, qa] = x.run(this.withCond(q, c)), [vb, qb] = y.run(this.withCond(q, I.not(c))); return this.joinValues(c, qa, va, qb, vb, at); } };
942
+ if (x.t === 'tuple' && y.t === 'tuple' && x.xs.length === y.xs.length)
943
+ return { t: 'tuple', xs: x.xs.map((v, i) => this.phiV(c, v, y.xs[i], at)) };
908
944
  const refs = ['ref', 'cell', 'phi'];
909
945
  if (refs.includes(x.t) && refs.includes(y.t))
910
946
  return { t: 'phi', c, a: x, b: y };
@@ -995,9 +1031,17 @@ export class Exec {
995
1031
  return { has: I.bite(c, m.w.has, base.has), vals: new Map([...base.vals].map(([f, v]) => [f, this.mergeScalar(c, m.w.vals.get(f), v, undefined)])) };
996
1032
  }
997
1033
  access(e, p) {
998
- if (e.questionDotToken)
1034
+ if (e.questionDotToken && !ts.isPropertyAccessExpression(e))
999
1035
  return refuse(e, 'optional chaining');
1000
1036
  const [base, q] = this.ev(e.expression, p);
1037
+ // x?.f: missing where x is, else x.f (read where x is there).
1038
+ const ob = e.questionDotToken ? this.deref(q, base) : undefined;
1039
+ if (ob?.t === 'undef')
1040
+ return [ob, q];
1041
+ if (ob?.t === 'opt' && ts.isPropertyAccessExpression(e)) {
1042
+ const [f, q2] = this.field(ob.v, memberName(e.name), e, q);
1043
+ return [f.t === 'opt' ? { ...f, has: I.and(ob.has, f.has) } : f.t === 'undef' ? f : { t: 'opt', has: ob.has, v: f, ...(ob.null ? { null: true } : {}) }, q2];
1044
+ }
1001
1045
  if (ts.isPropertyAccessExpression(e)) {
1002
1046
  const f = memberName(e.name);
1003
1047
  if (base.t === 'ref') {
@@ -1066,6 +1110,8 @@ export class Exec {
1066
1110
  vals = new Map(m.decl.fields.map(f => [f.name, Exec.defaultOf(f.sort)]));
1067
1111
  has = I.F;
1068
1112
  }
1113
+ else if (m.decl.js === 'Set')
1114
+ vals = new Map();
1069
1115
  else if (m.decl.scalar)
1070
1116
  vals = new Map([['value', this.cellValue(v, m.decl.fields[0], at, p)]]);
1071
1117
  else {
@@ -1193,8 +1239,11 @@ export class Exec {
1193
1239
  return refuse(target, `${f} set to other than an object`);
1194
1240
  if (old.t === 'ref' && v.t === 'ref') {
1195
1241
  const om = this.obj(q, old.id);
1196
- if (om?.k === 'map')
1197
- return refuse(target, `${f}: a map replaced in a step (clearing every key is not in the subset yet)`);
1242
+ if (om?.k === 'map') {
1243
+ const nm = this.obj(q, v.id);
1244
+ if (nm?.k !== 'map' || nm.base !== om.base)
1245
+ return refuse(target, `${f}: a map replaced in a step (clearing every key is not in the subset yet)`);
1246
+ }
1198
1247
  const nl = this.obj(q, v.id);
1199
1248
  if (om?.k === 'list' && (nl?.k !== 'list' || nl.base !== om.base || nl.origin === 'this'))
1200
1249
  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'}`);
@@ -1202,6 +1251,27 @@ export class Exec {
1202
1251
  const heap = new Map(q.heap).set(id, { ...o, fields: new Map(o.fields).set(f, v) });
1203
1252
  return { ...q, heap, wrote: o.origin === 'this' ? [...new Set([...q.wrote, f])] : q.wrote };
1204
1253
  }
1254
+ // A value replaced whole (a Ref's: never written in place by another holder): two objects by a condition made one,
1255
+ // a map by cases, a record field by field.
1256
+ whole(v, q, at) {
1257
+ if (v.t !== 'phi')
1258
+ return [v, q];
1259
+ const [a, qa] = this.whole(v.a, q, at), [b, qb] = this.whole(v.b, qa, at), oa = a.t === 'ref' ? this.obj(qb, a.id) : undefined, ob = b.t === 'ref' ? this.obj(qb, b.id) : undefined, id = this.id(oa?.k ?? 'obj');
1260
+ if (oa?.k === 'map' && ob?.k === 'map' && oa.base === ob.base) {
1261
+ const w = this.mergeWrites(v.c, oa.decl, oa.w, ob.w, at);
1262
+ return [{ t: 'ref', id }, { ...qb, heap: new Map(qb.heap).set(id, { k: 'map', base: oa.base, decl: oa.decl, ...(w ? { w } : {}), origin: 'fresh', gen: Math.max(oa.gen, ob.gen) + 1 }) }];
1263
+ }
1264
+ if (oa?.k !== 'rec' || ob?.k !== 'rec' || oa.lazy || ob.lazy || [...oa.fields.keys()].sort().join() !== [...ob.fields.keys()].sort().join())
1265
+ return [{ t: 'phi', c: v.c, a, b }, qb];
1266
+ let r = qb;
1267
+ const fields = new Map();
1268
+ for (const [f, x] of oa.fields) {
1269
+ const [y, r2] = this.whole(this.phiV(v.c, x, ob.fields.get(f), at), r, at);
1270
+ fields.set(f, y);
1271
+ r = r2;
1272
+ }
1273
+ return [{ t: 'ref', id }, { ...r, heap: new Map(r.heap).set(id, { k: 'rec', fields, origin: 'fresh' }) }];
1274
+ }
1205
1275
  // A name's symbol, through an import to what it names.
1206
1276
  resolved(e) {
1207
1277
  const sym = this.s.checker.getSymbolAtLocation(e);
@@ -1308,7 +1378,11 @@ export class Exec {
1308
1378
  if (o?.k === 'map' && b.t === 'ref') {
1309
1379
  const [args, q2] = this.args(e.arguments, q);
1310
1380
  const k = () => this.key(args[0] ?? refuse(e, `${m} with no key`), e.arguments[0], o.decl);
1381
+ const isSet = o.decl.js === 'Set';
1382
+ if (isSet ? !['has', 'add', 'delete'].includes(m) : m === 'add')
1383
+ return refuse(e, isSet ? `the Set method ${m} (has, add and delete are in the subset)` : `the map method ${m} (get, set, has and delete are in the subset)`);
1311
1384
  switch (m) {
1385
+ case 'add': return [b, this.mapSet(b.id, k(), { t: 'bool', e: I.T }, e, q2)];
1312
1386
  case 'get': return [this.mapGet(b.id, k(), q2), q2];
1313
1387
  case 'has': return [{ t: 'bool', e: this.readCell(o, k()).has }, q2];
1314
1388
  case 'set': return [b, this.mapSet(b.id, k(), args[1] ?? refuse(e, 'set with no value'), e, q2)];
@@ -1404,6 +1478,10 @@ export class Exec {
1404
1478
  }
1405
1479
  // [...xs] (a copy), [...xs, x] (a copy with x pushed); [] only as a state's start.
1406
1480
  array(e, p) {
1481
+ if (this.s.effect && e.elements.length && !e.elements.some(ts.isSpreadElement)) {
1482
+ const [xs, q] = this.args(e.elements, p);
1483
+ return [{ t: 'tuple', xs }, q];
1484
+ }
1407
1485
  const [first, ...rest] = e.elements;
1408
1486
  if (!first || !ts.isSpreadElement(first) || rest.length > 1 || rest.some(ts.isSpreadElement))
1409
1487
  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)');
@@ -1473,13 +1551,13 @@ export class Exec {
1473
1551
  }
1474
1552
  newExpr(e, p) {
1475
1553
  const c = e.expression;
1476
- if (ts.isIdentifier(c) && c.text === 'Map') {
1554
+ if (ts.isIdentifier(c) && (c.text === 'Map' || c.text === 'Set')) {
1477
1555
  const a = e.arguments ?? [];
1478
1556
  if (a.length !== 1)
1479
- return refuse(e, 'a new Map in a step (clearing every key is not in the subset yet)');
1557
+ return refuse(e, `a new ${c.text} in a step (clearing every key is not in the subset yet)`);
1480
1558
  const [v, q] = this.ev(a[0], p), src = v.t === 'ref' ? this.obj(q, v.id) : undefined;
1481
- if (src?.k !== 'map')
1482
- return refuse(e, 'a new Map of other than a map');
1559
+ if (src?.k !== 'map' || (src.decl.js === 'Set') !== (c.text === 'Set'))
1560
+ return refuse(e, `a new ${c.text} of other than a ${c.text === 'Set' ? 'Set' : 'map'}`);
1483
1561
  const id = this.id('map');
1484
1562
  return [{ t: 'ref', id }, { ...q, heap: new Map(q.heap).set(id, { ...src, origin: 'fresh' }) }];
1485
1563
  }
@@ -1498,7 +1576,7 @@ export class Exec {
1498
1576
  return refuse(e, `new ${text(c)}`);
1499
1577
  }
1500
1578
  // A function of the same module, or a method or getter of the class, run where it is called.
1501
- inline(f, args, at, p) {
1579
+ inline(f, args, at, p, locals = new Map()) {
1502
1580
  if (++this.depth > 24)
1503
1581
  return refuse(at, 'calls nested too deep (recursion is not in the subset)');
1504
1582
  if (f.decl.getSourceFile() === this.s.sf)
@@ -1510,7 +1588,7 @@ export class Exec {
1510
1588
  return refuse(at, 'an async or generator function');
1511
1589
  if (!d.body)
1512
1590
  return refuse(at, 'a function without a body');
1513
- let q = { ...p, locals: new Map() };
1591
+ let q = { ...p, locals: new Map(locals) };
1514
1592
  d.parameters.forEach((param, i) => {
1515
1593
  if (param.dotDotDotToken)
1516
1594
  refuse(param, 'a rest parameter');
@@ -1,4 +1,5 @@
1
- import { type Model, type Sort } from './extract-read.js';
1
+ import ts from 'typescript';
2
+ import { Exec, type Heap, type Model, type Path, type Setup, type Shape, type Sort, type V } from './extract-read.js';
2
3
  export type ReadOptions = {
3
4
  entry: string;
4
5
  files?: Record<string, string>;
@@ -22,6 +23,23 @@ export type Result = {
22
23
  null: boolean;
23
24
  };
24
25
  export declare const isFactory: (code: string, file: string, entry: string) => boolean;
25
- export declare function readFactory(code: string, file: string, opts: ReadOptions): Model;
26
+ export type FactoryOf = {
27
+ fn: ts.FunctionLikeDeclaration;
28
+ params: readonly ts.ParameterDeclaration[];
29
+ obj: ts.ObjectLiteralExpression;
30
+ decl: (d: ts.VariableDeclaration) => {
31
+ shape: Shape;
32
+ init: ts.Expression;
33
+ } | 'helper' | undefined;
34
+ fnOf: (e: ts.Expression) => ts.FunctionLikeDeclaration | undefined;
35
+ result: (f: ts.FunctionLikeDeclaration) => ts.Type;
36
+ run: (ex: Exec, v: V, at: ts.Node, p: Path) => [V, Path];
37
+ get: (field: string) => string | undefined;
38
+ set: (field: string) => string | undefined;
39
+ calls: string;
40
+ extra?: [number, string][];
41
+ start?: [string, Heap extends Map<string, infer O> ? O : never][];
42
+ };
43
+ export declare function readFactory(code: string, file: string, opts: ReadOptions, fx?: (s: Setup) => FactoryOf): Model;
26
44
  export declare const isSlice: (code: string, entry: string) => boolean;
27
45
  export declare function readSlice(code: string, file: string, opts: ReadOptions): Model;
@@ -5,10 +5,8 @@
5
5
  // the step's writes, what the code refuses (its throws) and how a request is made of the code.
6
6
  import ts from 'typescript';
7
7
  import * as I from "./extract-ir.js";
8
- import { Exec, Refusal, Retype, memberName, mergeOps, normalize, program, shapeOf, unparen } from "./extract-read.js";
8
+ import { Exec, Retype, memberName, mergeOps, normalize, program, refuse, shapeOf, unparen } from "./extract-read.js";
9
9
  const at0 = (sf) => sf.statements[0] ?? sf;
10
- const where = (n) => { const sf = n.getSourceFile(), { line, character } = sf.getLineAndCharacterOfPosition(n.getStart()); return `${sf.fileName.split('/').pop()}:${line + 1}:${character + 1}`; };
11
- const refuse = (n, what) => { throw new Refusal(where(n), what); };
12
10
  function setupOf(code, file, typed = {}, files = {}) {
13
11
  const root = file.slice(0, file.length - (file.split('/').pop().length)), extra = Object.fromEntries(Object.entries(files).map(([p, c]) => [normalize(`${root}${p}`), c]));
14
12
  const { sf, checker } = program(code, file, extra);
@@ -591,7 +589,7 @@ function findClass(sf, name) {
591
589
  }
592
590
  const has = (n, k) => !!(ts.canHaveModifiers(n) && ts.getModifiers(n)?.some(m => m.kind === k));
593
591
  const isEmptyArray = (e) => !!e && ((ts.isArrayLiteralExpression(e) && !e.elements.length) || ((ts.isAsExpression(e) || ts.isParenthesizedExpression(e)) && isEmptyArray(e.expression)));
594
- 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)));
592
+ const isMapInit = (e) => !!e && ((ts.isNewExpression(e) && ts.isIdentifier(e.expression) && (e.expression.text === 'Map' || e.expression.text === 'Set') && !e.arguments?.length) || (ts.isObjectLiteralExpression(e) && !e.properties.length) || ((ts.isAsExpression(e) || ts.isParenthesizedExpression(e)) && isMapInit(e.expression)));
595
593
  export function readClass(code, file, opts) {
596
594
  // Read twice: first with every field a state variable, to see which the methods write; then with the others as the
597
595
  // constants the constructor makes them.
@@ -1137,18 +1135,18 @@ function returnedObject(fn) {
1137
1135
  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));
1138
1136
  return e.properties.length && e.properties.some(fnOf) ? e : undefined;
1139
1137
  }
1140
- export function readFactory(code, file, opts) {
1141
- const written = factoryAttempt(code, file, opts, new Set()).written;
1142
- return factoryAttempt(code, file, opts, written).model;
1138
+ export function readFactory(code, file, opts, fx) {
1139
+ const written = factoryAttempt(code, file, opts, new Set(), fx).written;
1140
+ return factoryAttempt(code, file, opts, written, fx).model;
1143
1141
  }
1144
- function factoryAttempt(code, file, opts, written) {
1145
- const s = setupOf(code, file, {}, opts.files), fn = findFunction(s.sf, opts.entry), first = written.size === 0;
1146
- if (fn.modifiers?.some(m => m.kind === ts.SyntaxKind.AsyncKeyword) || fn.asteriskToken)
1142
+ function factoryAttempt(code, file, opts, written, fxOf) {
1143
+ const s = setupOf(code, file, {}, opts.files), fx = fxOf?.(s), fn = fx?.fn ?? findFunction(s.sf, opts.entry), first = written.size === 0;
1144
+ if (!fx && (fn.modifiers?.some(m => m.kind === ts.SyntaxKind.AsyncKeyword) || fn.asteriskToken))
1147
1145
  refuse(fn, 'an async or generator factory');
1148
- const obj = returnedObject(fn) ?? refuse(fn, `${opts.entry} returns no object of functions`);
1146
+ const obj = fx?.obj ?? returnedObject(fn) ?? refuse(fn, `${opts.entry} returns no object of functions`);
1149
1147
  const stmts = fn.body && ts.isBlock(fn.body) ? fn.body.statements.slice(0, -1) : [];
1150
1148
  const fields = [], closure = new Set(), helpers = new Set();
1151
- for (const p of fn.parameters) {
1149
+ for (const p of fx?.params ?? fn.parameters) {
1152
1150
  if (!ts.isIdentifier(p.name) || p.dotDotDotToken)
1153
1151
  refuse(p, 'a destructured or rest argument to the factory');
1154
1152
  fields.push({ name: p.name.text, shape: shapeOf(s.checker.getTypeAtLocation(p), s.checker, p), node: p, param: true });
@@ -1168,6 +1166,16 @@ function factoryAttempt(code, file, opts, written) {
1168
1166
  for (const d of st.declarationList.declarations) {
1169
1167
  if (!ts.isIdentifier(d.name))
1170
1168
  refuse(d, 'a destructuring in the factory');
1169
+ const own = fx?.decl(d);
1170
+ if (own === 'helper') {
1171
+ helpers.add(d);
1172
+ continue;
1173
+ }
1174
+ if (own) {
1175
+ fields.push({ name: d.name.text, shape: own.shape, node: d, init: own.init });
1176
+ closure.add(d);
1177
+ continue;
1178
+ }
1171
1179
  const init = d.initializer && (ts.isParenthesizedExpression(d.initializer) ? d.initializer.expression : d.initializer);
1172
1180
  if (init && (ts.isArrowFunction(init) || ts.isFunctionExpression(init))) {
1173
1181
  helpers.add(d);
@@ -1244,7 +1252,7 @@ function factoryAttempt(code, file, opts, written) {
1244
1252
  continue;
1245
1253
  }
1246
1254
  const flow = exC.stmt(st, cp);
1247
- if (flow.rets.length || flow.breaks.length)
1255
+ if (flow.rets.some(([q]) => exC.feasible(q)) || flow.breaks.length)
1248
1256
  refuse(st, 'a return or break in the factory before its object');
1249
1257
  cp = flow.live ?? refuse(st, 'a factory that always throws');
1250
1258
  }
@@ -1282,18 +1290,21 @@ function factoryAttempt(code, file, opts, written) {
1282
1290
  s.now = undefined;
1283
1291
  s.nowRole = 'input';
1284
1292
  stateHeap.set('this', { k: 'rec', fields: thisFields, origin: 'this' });
1293
+ for (const [id, o] of fx?.start ?? [])
1294
+ stateHeap.set(id, o);
1285
1295
  const strip0 = (e) => (ts.isParenthesizedExpression(e) || ts.isAsExpression(e) ? strip0(e.expression) : e);
1286
1296
  const fns = obj.properties.map(p => {
1287
1297
  if (ts.isMethodDeclaration(p))
1288
1298
  return { name: memberName(p.name), decl: p };
1299
+ const fnOf = (x) => fx?.fnOf(x) ?? (ts.isArrowFunction(x) || ts.isFunctionExpression(x) ? x : undefined);
1289
1300
  if (ts.isPropertyAssignment(p)) {
1290
- const x = strip0(p.initializer);
1291
- if (ts.isArrowFunction(x) || ts.isFunctionExpression(x))
1301
+ const x = fnOf(strip0(p.initializer));
1302
+ if (x)
1292
1303
  return { name: memberName(p.name), decl: x };
1293
1304
  }
1294
1305
  if (ts.isShorthandPropertyAssignment(p)) {
1295
1306
  const d = s.checker.getShorthandAssignmentValueSymbol(p)?.valueDeclaration;
1296
- 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;
1307
+ const f = d && ts.isFunctionDeclaration(d) ? d : d && ts.isVariableDeclaration(d) && d.initializer ? fnOf(strip0(d.initializer)) : undefined;
1297
1308
  if (f && (helpers.has(d) || helpers.has(f)))
1298
1309
  return { name: p.name.text, decl: f };
1299
1310
  }
@@ -1304,10 +1315,10 @@ function factoryAttempt(code, file, opts, written) {
1304
1315
  const mnames = fns.map(f => f.name), ev = ex0.newVar('method', { k: 'choice', values: mnames }, 'input'), evL = { op: 'var', name: ev.name, values: mnames };
1305
1316
  const outputs = [], perMethod = [], events = [], results = {}, outVars = new Map();
1306
1317
  for (const f of fns) {
1307
- if (f.decl.modifiers?.some(m => m.kind === ts.SyntaxKind.AsyncKeyword) || f.decl.asteriskToken)
1318
+ if (f.decl.modifiers?.some(m => m.kind === ts.SyntaxKind.AsyncKeyword) || (f.decl.asteriskToken && !fx))
1308
1319
  refuse(f.decl, `${f.name}: an async or generator function (its steps interleave with others)`);
1309
- const sig = s.checker.getSignatureFromDeclaration(f.decl), rt = s.checker.getReturnTypeOfSignature(sig);
1310
- if (rt.flags & (ts.TypeFlags.Void | ts.TypeFlags.Undefined))
1320
+ const rt = fx ? fx.result(f.decl) : s.checker.getReturnTypeOfSignature(s.checker.getSignatureFromDeclaration(f.decl));
1321
+ if (rt.flags & (ts.TypeFlags.Void | ts.TypeFlags.Undefined | ts.TypeFlags.Never))
1311
1322
  continue;
1312
1323
  const sh = shapeOf(rt, s.checker, f.decl);
1313
1324
  if (sh.k !== 'num' && sh.k !== 'bool' && sh.k !== 'choice')
@@ -1342,8 +1353,11 @@ function factoryAttempt(code, file, opts, written) {
1342
1353
  args.push(a.events[0].arg);
1343
1354
  }
1344
1355
  const body = f.decl.body ?? refuse(f.decl, `${f.name} has no body`);
1345
- 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))];
1346
- const outs = ends.map(([rp, rv]) => {
1356
+ let 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))];
1357
+ // A method that returns an effect: the effect run (a generator's body is run as it is read).
1358
+ if (fx && !f.decl.asteriskToken)
1359
+ ends = ends.map(([q, v]) => { const [v2, q2] = fx.run(ex, v, f.decl, q); return [q2, v2]; });
1360
+ const outs = ends.filter(([q]) => ex.feasible(q)).map(([rp, rv]) => {
1347
1361
  const self = rp.heap.get('this'), sv = { leaves: new Map(), maps: new Map() };
1348
1362
  for (const [fl, lay] of stateLayout)
1349
1363
  materialize(ex, self.fields.get(fl), lay, rp, f.decl, sv);
@@ -1378,9 +1392,9 @@ function factoryAttempt(code, file, opts, written) {
1378
1392
  model.results = results;
1379
1393
  // How the check reads and sets the state: two functions added to the object returned (at its end).
1380
1394
  const state = stateLayout.map(([n]) => n);
1381
- 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(' ');
1395
+ const set = state.map(n => fx?.set(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} : __s.${n} instanceof Set ? [...__s.${n}].map(k => [k, true]) : Object.entries(__s.${n}))) ${n} instanceof Map ? ${n}.set(k, v) : ${n} instanceof Set ? ${n}.add(k) : (${n}[k] = v);` : `${n} = __s.${n};`)).join(' ');
1382
1396
  const shown = layout.map(([n]) => n).filter(n => !n.endsWith('()'));
1383
- model.factory = { at: obj.properties.hasTrailingComma ? obj.end - 1 : obj.properties.at(-1).end, text: `${obj.properties.hasTrailingComma ? '' : ','} __gdpGet: () => ({${shown.join(', ')}}), __gdpSet: (__s) => { ${set} }` };
1397
+ model.factory = { at: obj.properties.hasTrailingComma ? obj.end - 1 : obj.properties.at(-1).end, text: `${obj.properties.hasTrailingComma ? '' : ','} __gdpGet: () => ({${shown.map(n => fx?.get(n) ?? n).join(', ')}}), __gdpSet: (__s) => { ${set} }`, ...(fx ? { calls: fx.calls, ...(fx.extra ? { extra: fx.extra } : {}) } : {}) };
1384
1398
  return { model, written: wrote };
1385
1399
  }
1386
1400
  function constLayout(v, p, at) {
@@ -24,19 +24,16 @@ import ts from 'typescript';
24
24
  import * as dsl from "./dsl.js";
25
25
  import { compileFunction, seeded } from "./machine.js";
26
26
  import * as I from "./extract-ir.js";
27
- import { Exec, Refusal, memberName, normalize, program, shapeOf } from "./extract-read.js";
27
+ import { Exec, Refusal, memberName, normalize, placed, program, refuse, shapeOf, where } from "./extract-read.js";
28
28
  import { kindOf, pb, pterm, sortsOf } from "./extract-print.js";
29
29
  import { sandbox } from "./extract-check.js";
30
30
  import { conforms, eventsOf, fromXState } from "./xstate.js";
31
- const where = (n) => { const sf = n.getSourceFile(), { line, character } = sf.getLineAndCharacterOfPosition(n.getStart()); return `${sf.fileName.split('/').pop()}:${line + 1}:${character + 1}`; };
32
- const refuse = (n, what) => { throw new Refusal(where(n), what); };
33
31
  const strip = (e) => (ts.isParenthesizedExpression(e) || ts.isAsExpression(e) || ts.isSatisfiesExpression(e) ? strip(e.expression) : e);
34
32
  const isFn = (e) => ts.isArrowFunction(e) || ts.isFunctionExpression(e);
35
33
  export function extractXState(code, opts) {
36
34
  const file = opts.file ?? 'machine.ts', t0 = performance.now(), notes = [];
37
35
  try {
38
- const cwd = globalThis.process?.cwd?.() ?? '.';
39
- const at = `${cwd}/${file}`, root = at.slice(0, at.length - file.split('/').pop().length);
36
+ const at = placed(file), root = at.slice(0, at.length - file.split('/').pop().length);
40
37
  const extra = Object.fromEntries(Object.entries(opts.files ?? {}).map(([p, c]) => [normalize(`${root}${p}`), c]));
41
38
  const { sf, checker } = program(code, at, extra);
42
39
  // The entry: a machine (setup(...).createMachine(...), createMachine(...)) or a function that returns one.
@@ -39,7 +39,7 @@
39
39
  import * as dsl from "./dsl.js";
40
40
  import { compileFunction, walk } from "./machine.js";
41
41
  import * as I from "./extract-ir.js";
42
- import { Refusal } from "./extract-read.js";
42
+ import { Refusal, placed } from "./extract-read.js";
43
43
  import { isFactory, isSlice, readClass, readFactory, readFunctions, readSlice } from "./extract-shapes.js";
44
44
  import { kindOf, mapEmpty, mapKind, natOK, pb, pidx, pk, pterm, sortsOf } from "./extract-print.js";
45
45
  import { check } from "./extract-check.js";
@@ -48,8 +48,7 @@ export function extract(code, opts) {
48
48
  let model;
49
49
  try {
50
50
  const isClass = opts.shape ? opts.shape === 'class' : new RegExp(`\\bclass\\s+${opts.entry}\\b|\\b${opts.entry}\\s*=\\s*class\\b`).test(code);
51
- // The file sits in the working directory, so its imports (xstate, say) resolve as the project's do.
52
- const cwd = globalThis.process?.cwd?.() ?? '.', at = `${cwd}/${file}`;
51
+ const at = placed(file);
53
52
  model = isClass ? readClass(code, at, opts) : isSlice(code, opts.entry) ? readSlice(code, at, opts) : isFactory(code, file, opts.entry) ? readFactory(code, at, opts) : readFunctions(code, at, opts);
54
53
  model.file = file;
55
54
  }
@@ -134,7 +133,7 @@ function evaluate(body) {
134
133
  function invariantsOf(m, sorts) {
135
134
  const empty = (d, f) => (f.sort.k === 'num' ? `.eq(0)` : f.sort.k === 'bool' ? `.not()` : f.sort.k === 'choice' ? `.is(${JSON.stringify(f.sort.values[0])})` : `.eq('')`);
136
135
  void sorts;
137
- return [...(m.laws ?? []), ...m.maps.map(d => `r.law(${JSON.stringify(`${d.name}: a key it doesn't hold holds the defaults`)}, ({${d.name}}) => forall(k => any(${d.name}.at(k).has, all(${d.fields.map(f => `${d.name}.at(k).${f.name}${empty(d, f)}`).join(', ')}))))`),
136
+ return [...(m.laws ?? []), ...m.maps.filter(d => d.fields.length).map(d => `r.law(${JSON.stringify(`${d.name}: a key it doesn't hold holds the defaults`)}, ({${d.name}}) => forall(k => any(${d.name}.at(k).has, all(${d.fields.map(f => `${d.name}.at(k).${f.name}${empty(d, f)}`).join(', ')}))))`),
138
137
  ...(m.lists ?? []).map(d => `r.law(${JSON.stringify(`${d.name}: nothing past its end`)}, ({${d.name}}) => ${d.name}.within())`)];
139
138
  }
140
139
  function evaluateLaws(r, xs) {
@@ -148,7 +147,7 @@ function moduleOf(m, body, file) {
148
147
  const used = NAMES.filter(n => new RegExp(`(^|[^.\\w$])${n}\\(|(^|[^.\\w$])${n}\\b(?!\\s*:)`).test(body.replace(/'[^']*'/g, "''")) || (n === 'rule'));
149
148
  const ident = identOf(m);
150
149
  return [
151
- `// Extracted by gdp-wired/extract from ${file} (${m.entry}, ${m.factory ? 'a factory of an object of functions' : m.shape === 'class' ? (/\.go$/.test(file) ? 'a struct and its methods' : 'a class') : m.shape === 'reducer' ? 'a step function' : 'functions over one record'}).`,
150
+ `// Extracted by gdp-wired/extract from ${file} (${m.entry}, ${m.factory?.calls ? 'an Effect service' : m.factory ? 'a factory of an object of functions' : m.shape === 'class' ? (/\.go$/.test(file) ? 'a struct and its methods' : 'a class') : m.shape === 'reducer' ? 'a step function' : 'functions over one record'}).`,
152
151
  `// Checked against the code it was read from; read again with extract() after the code changes.`,
153
152
  `import {${[...new Set([...used, ...(m.maps.length ? ['all', 'any', 'forall'] : []), ...['all', 'any', 'forall'].filter(n => (m.laws ?? []).some(l => l.includes(`${n}(`)))])].sort((a, b) => a.localeCompare(b)).join(', ')}} from 'gdp-wired'`,
154
153
  '',
@@ -219,7 +218,7 @@ function builderOf(m, sorts) {
219
218
  for (const [n, w] of mw) {
220
219
  const d = m.maps.find(x => x.name === n);
221
220
  const vals = d.fields.map(f => `${f.name}: ${pterm(w.vals[f.name], P, { m, sorts, atoms: [w.has] }, `${n}.${f.name}`)}`);
222
- outs.push([n, `${n}.set(${pk(w.key, P, ctx())}, {has: ${pb(w.has, P, ctx())}, ${vals.join(', ')}})`]);
221
+ outs.push([n, `${n}.set(${pk(w.key, P, ctx())}, {${[`has: ${pb(w.has, P, ctx())}`, ...vals].join(', ')}})`]);
223
222
  }
224
223
  // A list's write: its apply over the operations by cases (each under its condition).
225
224
  const lw = Object.entries(m.listWrites ?? {});