gdp-wired 0.30.1 → 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) => {
@@ -95,7 +98,7 @@ export function shapeOf(t, checker, at, inner) {
95
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`);
96
99
  if (t.flags & ts.TypeFlags.Object) {
97
100
  const sym = t.getSymbol() ?? t.aliasSymbol, name = sym?.getName();
98
- if (name === 'Map') {
101
+ if (name === 'Map' || name === 'ReadonlyMap') {
99
102
  const [kt, vt] = checker.getTypeArguments(t);
100
103
  if (!kt || !vt)
101
104
  return refuse(at, 'a Map without its key and value types');
@@ -113,7 +116,12 @@ export function shapeOf(t, checker, at, inner) {
113
116
  }
114
117
  if (name === 'Date')
115
118
  return { k: 'num', date: true };
116
- 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')
117
125
  return refuse(at, `a ${name}`);
118
126
  const sidx = checker.getIndexInfoOfType(t, ts.IndexKind.String), nidx = checker.getIndexInfoOfType(t, ts.IndexKind.Number);
119
127
  if (sidx || nidx) {
@@ -267,6 +275,8 @@ export class Exec {
267
275
  }
268
276
  if (va.t === 'ref' && vb.t === 'ref' && va.id === vb.id)
269
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);
270
280
  // Two objects by the path taken: a reference to each by the condition.
271
281
  const refs = ['ref', 'cell', 'phi'];
272
282
  if (refs.includes(va.t) && refs.includes(vb.t))
@@ -332,7 +342,7 @@ export class Exec {
332
342
  let live = p;
333
343
  const rets = [], breaks = [];
334
344
  for (const st of stmts) {
335
- if (!live)
345
+ if (!live || !this.feasible(live))
336
346
  break;
337
347
  if (ts.isVariableStatement(st))
338
348
  for (const d of st.declarationList.declarations)
@@ -515,6 +525,8 @@ export class Exec {
515
525
  case 'opt': return I.and(v.has, this.truthy(v.v, at));
516
526
  case 'undef': return I.F;
517
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`);
518
530
  }
519
531
  }
520
532
  num(v, at, p) {
@@ -558,6 +570,9 @@ export class Exec {
558
570
  ev(e, p) {
559
571
  if (ts.isParenthesizedExpression(e) || ts.isAsExpression(e) || ts.isSatisfiesExpression(e) || ts.isTypeAssertionExpression(e))
560
572
  return this.ev(e.expression, p);
573
+ const fe = this.s.effect?.(this, e, p);
574
+ if (fe)
575
+ return fe;
561
576
  if (ts.isNonNullExpression(e)) {
562
577
  const [v, q] = this.ev(e.expression, p);
563
578
  if (v.t !== 'opt')
@@ -830,8 +845,18 @@ export class Exec {
830
845
  const st = this.s.checker.getTypeAtLocation(prop.expression);
831
846
  if (this.s.checker.getPropertiesOfType(st).some(x => isDate(this.s.checker.getTypeOfSymbolAtLocation(x, prop))))
832
847
  refuse(prop, 'a spread of an object holding a Date (the copy and the original share it)');
833
- const [v, q2] = this.ev(prop.expression, q);
848
+ const [v0, q2] = this.ev(prop.expression, q);
834
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
+ }
835
860
  const src = v.t === 'ref' ? this.obj(q, v.id) : undefined;
836
861
  if (src?.k !== 'rec')
837
862
  return refuse(prop, 'a spread of other than an object');
@@ -911,6 +936,11 @@ export class Exec {
911
936
  }
912
937
  if (x.t === 'ref' && y.t === 'ref' && x.id === y.id)
913
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)) };
914
944
  const refs = ['ref', 'cell', 'phi'];
915
945
  if (refs.includes(x.t) && refs.includes(y.t))
916
946
  return { t: 'phi', c, a: x, b: y };
@@ -1001,9 +1031,17 @@ export class Exec {
1001
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)])) };
1002
1032
  }
1003
1033
  access(e, p) {
1004
- if (e.questionDotToken)
1034
+ if (e.questionDotToken && !ts.isPropertyAccessExpression(e))
1005
1035
  return refuse(e, 'optional chaining');
1006
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
+ }
1007
1045
  if (ts.isPropertyAccessExpression(e)) {
1008
1046
  const f = memberName(e.name);
1009
1047
  if (base.t === 'ref') {
@@ -1072,6 +1110,8 @@ export class Exec {
1072
1110
  vals = new Map(m.decl.fields.map(f => [f.name, Exec.defaultOf(f.sort)]));
1073
1111
  has = I.F;
1074
1112
  }
1113
+ else if (m.decl.js === 'Set')
1114
+ vals = new Map();
1075
1115
  else if (m.decl.scalar)
1076
1116
  vals = new Map([['value', this.cellValue(v, m.decl.fields[0], at, p)]]);
1077
1117
  else {
@@ -1199,8 +1239,11 @@ export class Exec {
1199
1239
  return refuse(target, `${f} set to other than an object`);
1200
1240
  if (old.t === 'ref' && v.t === 'ref') {
1201
1241
  const om = this.obj(q, old.id);
1202
- if (om?.k === 'map')
1203
- 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
+ }
1204
1247
  const nl = this.obj(q, v.id);
1205
1248
  if (om?.k === 'list' && (nl?.k !== 'list' || nl.base !== om.base || nl.origin === 'this'))
1206
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'}`);
@@ -1208,6 +1251,27 @@ export class Exec {
1208
1251
  const heap = new Map(q.heap).set(id, { ...o, fields: new Map(o.fields).set(f, v) });
1209
1252
  return { ...q, heap, wrote: o.origin === 'this' ? [...new Set([...q.wrote, f])] : q.wrote };
1210
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
+ }
1211
1275
  // A name's symbol, through an import to what it names.
1212
1276
  resolved(e) {
1213
1277
  const sym = this.s.checker.getSymbolAtLocation(e);
@@ -1314,7 +1378,11 @@ export class Exec {
1314
1378
  if (o?.k === 'map' && b.t === 'ref') {
1315
1379
  const [args, q2] = this.args(e.arguments, q);
1316
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)`);
1317
1384
  switch (m) {
1385
+ case 'add': return [b, this.mapSet(b.id, k(), { t: 'bool', e: I.T }, e, q2)];
1318
1386
  case 'get': return [this.mapGet(b.id, k(), q2), q2];
1319
1387
  case 'has': return [{ t: 'bool', e: this.readCell(o, k()).has }, q2];
1320
1388
  case 'set': return [b, this.mapSet(b.id, k(), args[1] ?? refuse(e, 'set with no value'), e, q2)];
@@ -1410,6 +1478,10 @@ export class Exec {
1410
1478
  }
1411
1479
  // [...xs] (a copy), [...xs, x] (a copy with x pushed); [] only as a state's start.
1412
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
+ }
1413
1485
  const [first, ...rest] = e.elements;
1414
1486
  if (!first || !ts.isSpreadElement(first) || rest.length > 1 || rest.some(ts.isSpreadElement))
1415
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)');
@@ -1479,13 +1551,13 @@ export class Exec {
1479
1551
  }
1480
1552
  newExpr(e, p) {
1481
1553
  const c = e.expression;
1482
- if (ts.isIdentifier(c) && c.text === 'Map') {
1554
+ if (ts.isIdentifier(c) && (c.text === 'Map' || c.text === 'Set')) {
1483
1555
  const a = e.arguments ?? [];
1484
1556
  if (a.length !== 1)
1485
- 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)`);
1486
1558
  const [v, q] = this.ev(a[0], p), src = v.t === 'ref' ? this.obj(q, v.id) : undefined;
1487
- if (src?.k !== 'map')
1488
- 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'}`);
1489
1561
  const id = this.id('map');
1490
1562
  return [{ t: 'ref', id }, { ...q, heap: new Map(q.heap).set(id, { ...src, origin: 'fresh' }) }];
1491
1563
  }
@@ -1504,7 +1576,7 @@ export class Exec {
1504
1576
  return refuse(e, `new ${text(c)}`);
1505
1577
  }
1506
1578
  // A function of the same module, or a method or getter of the class, run where it is called.
1507
- inline(f, args, at, p) {
1579
+ inline(f, args, at, p, locals = new Map()) {
1508
1580
  if (++this.depth > 24)
1509
1581
  return refuse(at, 'calls nested too deep (recursion is not in the subset)');
1510
1582
  if (f.decl.getSourceFile() === this.s.sf)
@@ -1516,7 +1588,7 @@ export class Exec {
1516
1588
  return refuse(at, 'an async or generator function');
1517
1589
  if (!d.body)
1518
1590
  return refuse(at, 'a function without a body');
1519
- let q = { ...p, locals: new Map() };
1591
+ let q = { ...p, locals: new Map(locals) };
1520
1592
  d.parameters.forEach((param, i) => {
1521
1593
  if (param.dotDotDotToken)
1522
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,12 +24,10 @@ 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, placed, 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) {
@@ -133,7 +133,7 @@ function evaluate(body) {
133
133
  function invariantsOf(m, sorts) {
134
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('')`);
135
135
  void sorts;
136
- 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(', ')}))))`),
137
137
  ...(m.lists ?? []).map(d => `r.law(${JSON.stringify(`${d.name}: nothing past its end`)}, ({${d.name}}) => ${d.name}.within())`)];
138
138
  }
139
139
  function evaluateLaws(r, xs) {
@@ -147,7 +147,7 @@ function moduleOf(m, body, file) {
147
147
  const used = NAMES.filter(n => new RegExp(`(^|[^.\\w$])${n}\\(|(^|[^.\\w$])${n}\\b(?!\\s*:)`).test(body.replace(/'[^']*'/g, "''")) || (n === 'rule'));
148
148
  const ident = identOf(m);
149
149
  return [
150
- `// 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'}).`,
151
151
  `// Checked against the code it was read from; read again with extract() after the code changes.`,
152
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'`,
153
153
  '',
@@ -218,7 +218,7 @@ function builderOf(m, sorts) {
218
218
  for (const [n, w] of mw) {
219
219
  const d = m.maps.find(x => x.name === n);
220
220
  const vals = d.fields.map(f => `${f.name}: ${pterm(w.vals[f.name], P, { m, sorts, atoms: [w.has] }, `${n}.${f.name}`)}`);
221
- 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(', ')}})`]);
222
222
  }
223
223
  // A list's write: its apply over the operations by cases (each under its condition).
224
224
  const lw = Object.entries(m.listWrites ?? {});