gdp-wired 0.26.0 → 0.28.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 (44) hide show
  1. package/dist/core/accel.d.ts +24 -0
  2. package/dist/core/accel.js +557 -207
  3. package/dist/core/bmc.d.ts +4 -1
  4. package/dist/core/bmc.js +18 -15
  5. package/dist/core/cycles.d.ts +2 -0
  6. package/dist/core/cycles.js +1 -1
  7. package/dist/core/cyclic.js +17 -10
  8. package/dist/core/data.d.ts +1 -0
  9. package/dist/core/data.js +73 -18
  10. package/dist/core/discover.js +64 -25
  11. package/dist/core/dsl.js +108 -18
  12. package/dist/core/extract-check.d.ts +52 -2
  13. package/dist/core/extract-check.js +155 -104
  14. package/dist/core/extract-read.d.ts +25 -0
  15. package/dist/core/extract-read.js +55 -14
  16. package/dist/core/extract-shapes.js +94 -18
  17. package/dist/core/extract-xstate.js +16 -3
  18. package/dist/core/extract.d.ts +1 -0
  19. package/dist/core/extract.js +16 -8
  20. package/dist/core/fresh.d.ts +9 -0
  21. package/dist/core/fresh.js +91 -0
  22. package/dist/core/infer.d.ts +1 -0
  23. package/dist/core/infer.js +64 -46
  24. package/dist/core/live.d.ts +15 -0
  25. package/dist/core/live.js +317 -0
  26. package/dist/core/machine.js +0 -1
  27. package/dist/core/nonterm.d.ts +3 -1
  28. package/dist/core/nonterm.js +103 -25
  29. package/dist/core/solver.d.ts +21 -0
  30. package/dist/core/solver.js +8 -0
  31. package/dist/core/translate.js +69 -19
  32. package/dist/kernel/cdcl.js +212 -78
  33. package/dist/kernel/kernel.d.ts +17 -1
  34. package/dist/kernel/kernel.js +158 -2
  35. package/dist/kernel/prove.d.ts +30 -4
  36. package/dist/kernel/prove.js +119 -25
  37. package/dist/kernel/reader.d.ts +74 -5
  38. package/dist/kernel/reader.js +531 -75
  39. package/dist/kernel/simplex.d.ts +26 -1
  40. package/dist/kernel/simplex.js +148 -14
  41. package/dist/lean-kernel/emit.d.ts +15 -3
  42. package/dist/lean-kernel/emit.js +144 -12
  43. package/dist/lean-kernel/library.js +1 -1
  44. package/package.json +2 -2
@@ -26,6 +26,7 @@ export class Retype extends Error {
26
26
  this.sort = sort;
27
27
  }
28
28
  }
29
+ export const unparen = (x) => (ts.isParenthesizedExpression(x) ? unparen(x.expression) : x);
29
30
  const where = (n) => {
30
31
  const sf = n.getSourceFile(), { line, character } = sf.getLineAndCharacterOfPosition(n.getStart());
31
32
  return `${sf.fileName.split('/').pop()}:${line + 1}:${character + 1}`;
@@ -213,7 +214,8 @@ export class Exec {
213
214
  const oa = a.heap.get(id), ob = b.heap.get(id);
214
215
  heap.set(id, !oa ? ob : !ob ? oa : this.mergeObj(c, oa, ob, a, b, heap, pairs, at));
215
216
  }
216
- return { pc, locals, heap, wrote: [...new Set([...a.wrote, ...b.wrote])], nows: Math.max(a.nows, b.nows) };
217
+ const outs = [...new Set([...(a.outs ?? []), ...(b.outs ?? [])])];
218
+ return { pc, locals, heap, wrote: [...new Set([...a.wrote, ...b.wrote])], nows: Math.max(a.nows, b.nows), ...(outs.length ? { outs } : {}) };
217
219
  }
218
220
  deref(p, v) {
219
221
  while (v.t === 'ref') {
@@ -280,7 +282,7 @@ export class Exec {
280
282
  if (oa.base !== ob.base)
281
283
  return refuse(at, 'one of two lists by the path taken');
282
284
  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) }))] };
285
+ return { ...oa, origin, ops: mergeOps(c, oa.ops, ob.ops) };
284
286
  }
285
287
  if (oa.k === 'map' && ob.k === 'map') {
286
288
  if (oa.base !== ob.base)
@@ -292,15 +294,7 @@ export class Exec {
292
294
  return refuse(at, 'an object that is of another kind by the path taken');
293
295
  }
294
296
  mergeW(c, oa, ob, at) { return this.mergeWrites(c, oa.decl, oa.w, ob.w, at); }
295
- mergeWrites(c, decl, wa, wb, at) {
296
- if (!wa && !wb)
297
- return undefined;
298
- const base = (key) => this.baseCell(decl, key);
299
- const fill = (w, key) => w ?? { key, ...base(key) };
300
- const xa = fill(wa, (wa ?? wb).key), xb = fill(wb, (wb ?? wa).key);
301
- const vals = new Map([...xa.vals].map(([f, v]) => [f, this.mergeScalar(c, v, xb.vals.get(f), at)]));
302
- return { key: I.kite(c, xa.key, xb.key), has: I.bite(c, xa.has, xb.has), vals };
303
- }
297
+ mergeWrites(c, decl, wa, wb, at) { return mergeWrites(c, wa, wb, key => this.baseCell(decl, key), (c2, x, y) => this.mergeScalar(c2, x, y, at)); }
304
298
  mergeScalar(c, a, b, at) {
305
299
  if (a.t === 'num' && b.t === 'num')
306
300
  return { t: 'num', e: I.nite(c, a.e, b.e) };
@@ -504,10 +498,13 @@ export class Exec {
504
498
  case 'choice': return v.values.includes('') ? I.not(I.is(v.e, '')) : I.T;
505
499
  // A string is truthy where it isn't empty.
506
500
  case 'str': return v.e.op === 'slit' ? (v.e.value ? I.T : I.F) : I.not(I.keq(v.e, { op: 'slit', value: '' }));
501
+ case 'outside':
502
+ if (v.path.startsWith('new? '))
503
+ return refuse(at, `${text(at)}: whether a function was given to the constructor, read (the check gives one: the claim would be only for calls that do)`);
504
+ return I.T;
507
505
  case 'ref':
508
506
  case 'cell':
509
- case 'phi':
510
- case 'outside': return I.T;
507
+ case 'phi': return I.T;
511
508
  case 'opt': return I.and(v.has, this.truthy(v.v, at));
512
509
  case 'undef': return I.F;
513
510
  case 'opaque': return refuse(at, `${text(at)} read as a condition: ${v.what}`);
@@ -697,6 +694,15 @@ export class Exec {
697
694
  }
698
695
  binary(e, p) {
699
696
  const op = e.operatorToken.kind, S = ts.SyntaxKind;
697
+ if (op === S.EqualsToken && this.fnField(e.left)) {
698
+ // A function field set while the object is made, to the function given or one written there: nothing the rule keeps.
699
+ const r = unparen(e.right), given = ts.isIdentifier(r) && p.locals.get(r.text)?.t === 'outside';
700
+ if (!this.s.ctor)
701
+ return refuse(e, `${text(e.left)}: a field holding a function, set by a method (its calls would answer by another function from then on)`);
702
+ if (!given && !ts.isArrowFunction(r) && !ts.isFunctionExpression(r))
703
+ return refuse(e, `${text(e.left)} set to ${text(r)} (a field holding a function is set to the function given or one written there)`);
704
+ return [{ t: 'undef' }, p];
705
+ }
700
706
  if (op === S.EqualsToken) {
701
707
  const [v, q] = this.ev(e.right, p);
702
708
  return [v, this.assign(e.left, v, q)];
@@ -1242,6 +1248,11 @@ export class Exec {
1242
1248
  // A function the factory is given: its answer is an input of the step (any value of its type), read once.
1243
1249
  if (ts.isIdentifier(obj) && p.locals.get(obj.text)?.t === 'outside')
1244
1250
  return this.outside(e, `${p.locals.get(obj.text).path}.${m}`, p);
1251
+ if (this.fnField(callee)) {
1252
+ if (this.s.ctor)
1253
+ return refuse(e, `${text(callee)}() called while the object is made`);
1254
+ return this.outside(e, `this.${m}`, p);
1255
+ }
1245
1256
  if (obj.kind === ts.SyntaxKind.ThisKeyword && this.s.cls) {
1246
1257
  const member = this.member(m);
1247
1258
  if (member && ts.isMethodDeclaration(member)) {
@@ -1329,8 +1340,14 @@ export class Exec {
1329
1340
  }
1330
1341
  return refuse(e, 'a call the subset doesn\'t read');
1331
1342
  }
1343
+ // this.f, where f is a field holding a function.
1344
+ fnField(x) {
1345
+ const t = unparen(x);
1346
+ return !!this.s.fnFields && ts.isPropertyAccessExpression(t) && t.expression.kind === ts.SyntaxKind.ThisKeyword && this.s.fnFields.names.has(memberName(t.name));
1347
+ }
1332
1348
  outside(e, path, p) {
1333
- const x = this.s.xstate ?? refuse(e, `${path}: a function from outside`);
1349
+ const own = this.s.fnFields;
1350
+ const x = this.s.xstate ?? own ?? refuse(e, `${path}: a function from outside`);
1334
1351
  if (e.arguments.some(impure))
1335
1352
  refuse(e, `${path}(...) with arguments that have effects`);
1336
1353
  const [, q] = this.args(e.arguments, p);
@@ -1344,6 +1361,20 @@ export class Exec {
1344
1361
  const sh = shapeOf(t, this.s.checker, e);
1345
1362
  if (sh.k !== 'num' && sh.k !== 'bool' && sh.k !== 'choice' && sh.k !== 'str')
1346
1363
  return refuse(e, `${path}() returns a compound value`);
1364
+ if (own) {
1365
+ // A class's: one answer a step (a second call may answer differently), the same input in each method.
1366
+ if (q.outs?.includes(path))
1367
+ return refuse(e, `${path}() called twice in one step (each call may answer differently: call it once into a local)`);
1368
+ const had = [...own.outside].find(([, o]) => o.path === path);
1369
+ if (had && had[1].sort.k !== sh.k)
1370
+ return refuse(e, `${path}() read as two sorts`);
1371
+ const v = had ? this.s.vars.get(had[0]) : this.newVar(path.split('.').pop(), sh, 'input', `${path}(): the answer of the function the field holds (any value of its type: the claim is for every such function that leaves the object alone)`);
1372
+ if (!had) {
1373
+ own.outside.set(v.name, { path, sort: sh });
1374
+ this.s.notes.add(`${path}(): the answer of the function the field holds, an input (any value of its type: the claim is for every such function that leaves the object alone)`);
1375
+ }
1376
+ return [Exec.valueOf(v), { ...q, outs: [...(q.outs ?? []), path] }];
1377
+ }
1347
1378
  if ([...x.outside.values()].some(o => o.path === path))
1348
1379
  return refuse(e, `${path}() read in two places (each call may answer differently)`);
1349
1380
  const v = this.newVar(path.split('.').pop(), sh, 'input', `${path}(): the answer of a function the machine is given (any value of its type)`);
@@ -1525,6 +1556,16 @@ const nullOf = (at, a, b) => {
1525
1556
  refuse(at, 'a value that may be null on one side and undefined on the other');
1526
1557
  return ka === 'null' || kb === 'null' ? { null: true } : {};
1527
1558
  };
1559
+ // A map's write and a list's operations by a condition (the Go reader's too).
1560
+ export function mergeWrites(c, wa, wb, base, scalar) {
1561
+ if (!wa && !wb)
1562
+ return undefined;
1563
+ const fill = (w, key) => w ?? { key, ...base(key) };
1564
+ const xa = fill(wa, (wa ?? wb).key), xb = fill(wb, (wb ?? wa).key);
1565
+ const vals = new Map([...xa.vals].map(([f, v]) => [f, scalar(c, v, xb.vals.get(f))]));
1566
+ return { key: I.kite(c, xa.key, xb.key), has: I.bite(c, xa.has, xb.has), vals };
1567
+ }
1568
+ export const mergeOps = (c, a, b) => [...a.map(o => ({ ...o, when: I.and(c, o.when) })), ...b.map(o => ({ ...o, when: I.and(I.not(c), o.when) }))];
1528
1569
  const mergedGen = (a, b) => (a.gen === b.gen ? a.gen : Math.max(a.gen, b.gen) + 1);
1529
1570
  // The module an import names, for a refusal.
1530
1571
  const moduleOf = (d) => { let n = d; while (n && !ts.isImportDeclaration(n))
@@ -5,7 +5,7 @@
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, normalize, program, shapeOf } from "./extract-read.js";
8
+ import { Exec, Refusal, Retype, memberName, mergeOps, normalize, program, shapeOf, unparen } from "./extract-read.js";
9
9
  const at0 = (sf) => sf.statements[0] ?? sf;
10
10
  const where = (n) => { const sf = n.getSourceFile(), { line, character } = sf.getLineAndCharacterOfPosition(n.getStart()); return `${sf.fileName.split('/').pop()}:${line + 1}:${character + 1}`; };
11
11
  const refuse = (n, what) => { throw new Refusal(where(n), what); };
@@ -138,7 +138,7 @@ function materialize(ex, v, layout, p, at, out = { leaves: new Map(), maps: new
138
138
  case 'const': return out;
139
139
  }
140
140
  }
141
- const strip = (p) => ({ pc: p.pc, locals: new Map(), heap: new Map(), wrote: [], nows: p.nows });
141
+ const strip = (p) => ({ pc: p.pc, locals: new Map(), heap: new Map(), wrote: [], nows: p.nows, ...(p.outs ? { outs: p.outs } : {}) });
142
142
  // The condition that tells two paths apart (as Exec.merge reads it).
143
143
  function split(a, b) {
144
144
  let i = 0;
@@ -153,7 +153,7 @@ function mergeVals(ex, c, a, b, at) {
153
153
  // A list's write by cases: each side's under its condition.
154
154
  const lists = new Map();
155
155
  for (const n of new Set([...(a.lists?.keys() ?? []), ...(b.lists?.keys() ?? [])]))
156
- lists.set(n, [...(a.lists?.get(n) ?? []).map(o => ({ ...o, when: I.and(c, o.when) })), ...(b.lists?.get(n) ?? []).map(o => ({ ...o, when: I.and(I.not(c), o.when) }))]);
156
+ lists.set(n, mergeOps(c, a.lists?.get(n) ?? [], b.lists?.get(n) ?? []));
157
157
  return { leaves, maps, ...(lists.size ? { lists } : {}) };
158
158
  }
159
159
  // Every way a step ends (each a path and its state), as one state by cases.
@@ -574,7 +574,8 @@ function finish(s, m) {
574
574
  listWrites[n] = ops.map(o => (o.op === 'pop' ? o : { ...o, x: termOf(o.x) }));
575
575
  return { name: m.name, shape: m.shape, file: m.file, entry: m.entry, params: vars.filter(v => v.role === 'param'), inputs: vars.filter(v => v.role === 'input'), state: vars.filter(v => v.role === 'state'),
576
576
  maps: [...s.maps.values()], ...(s.lists?.size ? { lists: [...s.lists.values()], listWrites } : {}), init: m.init, writes, mapWrites, outputs: m.outputs, refuse: m.refuse, pre: m.pre, layout: m.layout, events: m.events, notes: [...s.notes], hints: s.hints,
577
- ...(m.event ? { event: m.event } : {}), ...(m.ctorArgs ? { ctorArgs: m.ctorArgs } : {}), ...(s.lazy.size ? { lazy: s.lazy } : {}), ...(m.initSource ? { initSource: m.initSource } : {}), ...(s.spans ? { spans: s.spans } : {}) };
577
+ ...(m.event ? { event: m.event } : {}), ...(m.ctorArgs ? { ctorArgs: m.ctorArgs } : {}), ...(s.lazy.size ? { lazy: s.lazy } : {}), ...(m.initSource ? { initSource: m.initSource } : {}), ...(s.spans ? { spans: s.spans } : {}),
578
+ ...(s.fnFields?.names.size ? { fnFields: [...s.fnFields.names] } : {}), ...(s.fnFields?.outside.size ? { answers: Object.fromEntries([...s.fnFields.outside].map(([n, o]) => [n, o.path.replace(/^this\./, '')])) } : {}) };
578
579
  }
579
580
  // --- classes --------------------------------------------------------------------------------------------------------
580
581
  function findClass(sf, name) {
@@ -601,27 +602,72 @@ export function readClass(code, file, opts) {
601
602
  // mixin, or one from another module is refused where it is named).
602
603
  function chainOf(s, cls) {
603
604
  const chain = [cls];
604
- for (let c = cls;;) {
605
- const h = c.heritageClauses?.find(x => x.token === ts.SyntaxKind.ExtendsKeyword);
606
- if (!h)
607
- return chain;
608
- const e = h.types[0].expression;
605
+ const add = (decl, at) => { if (chain.includes(decl))
606
+ refuse(at, ts.isClassExpression(decl) ? 'a mixin applied twice (one class written once, twice in the chain)' : 'a class that extends itself'); chain.push(decl); };
607
+ // What `extends e` names: a class of the files read, or (a mixin) the class a function of the files read makes from
608
+ // the class it is given, `(B) => class extends B {...}`, which extends what the call is given.
609
+ const base = (e, at) => {
610
+ e = unparen(e);
611
+ if (ts.isClassExpression(e)) {
612
+ add(e, at);
613
+ return e;
614
+ }
615
+ if (ts.isCallExpression(e)) {
616
+ // (the mixin's class, then what it is given: the class that one extends)
617
+ add(mixinOf(s, e, at), at);
618
+ return base(e.arguments[0], e);
619
+ }
609
620
  if (!ts.isIdentifier(e) && !ts.isPropertyAccessExpression(e))
610
- return refuse(h, `extends ${e.getText().slice(0, 60)}: a class a call makes (a mixin), not one the files read declare`);
621
+ return refuse(at, `extends ${e.getText().slice(0, 60)}: neither a class nor a mixin of the files read`);
611
622
  let sym = s.checker.getSymbolAtLocation(ts.isPropertyAccessExpression(e) ? e.name : e);
612
623
  if (sym && sym.flags & ts.SymbolFlags.Alias)
613
624
  sym = s.checker.getAliasedSymbol(sym);
614
625
  const decl = sym?.declarations?.find(ts.isClassLike);
615
626
  if (!decl)
616
- return refuse(h, `extends ${e.getText()}: no class of the files read (another module's, or not a class)`);
627
+ return refuse(at, `extends ${e.getText()}: no class of the files read (another module's, or not a class)`);
617
628
  if (!s.ours(decl.getSourceFile()))
618
- return refuse(h, `extends ${e.getText()}, a class from another module (not among the files read)`);
619
- if (chain.includes(decl))
620
- return refuse(h, 'a class that extends itself');
621
- chain.push(decl);
622
- c = decl;
629
+ return refuse(at, `extends ${e.getText()}, a class from another module (not among the files read)`);
630
+ add(decl, at);
631
+ return decl;
632
+ };
633
+ for (let c = cls;;) {
634
+ const h = c.heritageClauses?.find(x => x.token === ts.SyntaxKind.ExtendsKeyword);
635
+ if (!h)
636
+ return chain;
637
+ c = base(h.types[0].expression, h);
623
638
  }
624
639
  }
640
+ // A mixin of the files read: a function of one parameter whose body is a class expression (or returns one) extending
641
+ // that parameter, called with one argument. Its class is resolved where it is written, so one mixin applied twice is
642
+ // one class here: refused (its members would be the same declarations twice in the chain).
643
+ function mixinOf(s, call, at) {
644
+ const what = `extends ${call.getText().slice(0, 60)}`;
645
+ if (!ts.isIdentifier(call.expression))
646
+ return refuse(at, `${what}: a class a call makes (a mixin) that isn't a function of the files read`);
647
+ let sym = s.checker.getSymbolAtLocation(call.expression);
648
+ if (sym && sym.flags & ts.SymbolFlags.Alias)
649
+ sym = s.checker.getAliasedSymbol(sym);
650
+ const d = sym?.valueDeclaration;
651
+ const fn = d && ts.isFunctionDeclaration(d) ? d : d && ts.isVariableDeclaration(d) && d.initializer && (ts.isArrowFunction(unparen(d.initializer)) || ts.isFunctionExpression(unparen(d.initializer))) ? unparen(d.initializer) : undefined;
652
+ if (!fn || !s.ours(fn.getSourceFile()))
653
+ return refuse(at, `${what}: a class a call makes (a mixin), not one the files read declare`);
654
+ if (d && ts.isVariableDeclaration(d) && !(d.parent.flags & ts.NodeFlags.Const))
655
+ return refuse(at, `${what}: a mixin held in a let`);
656
+ const p = fn.parameters[0];
657
+ if (fn.parameters.length !== 1 || !p || !ts.isIdentifier(p.name) || p.initializer)
658
+ return refuse(fn, `${what}: a mixin of other than one parameter (the class it extends)`);
659
+ if (call.arguments.length !== 1 || ts.isSpreadElement(call.arguments[0]))
660
+ return refuse(call, `${what}: a mixin called with other than the class it extends`);
661
+ const body = fn.body && ts.isBlock(fn.body) ? (fn.body.statements.length === 1 && ts.isReturnStatement(fn.body.statements[0]) ? fn.body.statements[0].expression : undefined) : fn.body;
662
+ const ce = body && unparen(body);
663
+ if (!ce || !ts.isClassExpression(ce))
664
+ return refuse(fn, `${what}: a mixin whose body is more than a class (a function read as a mixin returns one class expression)`);
665
+ const h = ce.heritageClauses?.find(x => x.token === ts.SyntaxKind.ExtendsKeyword);
666
+ const he = h && unparen(h.types[0].expression);
667
+ if (!he || !ts.isIdentifier(he) || he.text !== p.name.text)
668
+ return refuse(ce, `${what}: a mixin's class that extends other than its parameter`);
669
+ return ce;
670
+ }
625
671
  function attempt(code, file, opts, written) {
626
672
  const s = setupOf(code, file, {}, opts.files), cls = findClass(s.sf, opts.entry), first = written.size === 0;
627
673
  s.cls = cls;
@@ -632,7 +678,15 @@ function attempt(code, file, opts, written) {
632
678
  s.chain = chain;
633
679
  if (chain.length > 1)
634
680
  s.notes.add(`${opts.entry} extends ${chain.slice(1).map(c => c.name?.text ?? '(a class)').join(', which extends ')}: its fields and methods are read with them, each method the nearest the object has`);
635
- const ownCtor = (c) => c.members.find((m) => ts.isConstructorDeclaration(m) && !!m.body);
681
+ // (`constructor(...args) { super(...args) }`, a mixin's usual one, is the constructor a class without one has)
682
+ const forwards = (k) => {
683
+ const [p] = k.parameters, st = k.body?.statements;
684
+ if (k.parameters.length !== 1 || !p?.dotDotDotToken || !ts.isIdentifier(p.name) || st?.length !== 1 || !ts.isExpressionStatement(st[0]))
685
+ return false;
686
+ const call = st[0].expression;
687
+ return ts.isCallExpression(call) && call.expression.kind === ts.SyntaxKind.SuperKeyword && call.arguments.length === 1 && ts.isSpreadElement(call.arguments[0]) && ts.isIdentifier(call.arguments[0].expression) && call.arguments[0].expression.text === p.name.text;
688
+ };
689
+ const ownCtor = (c) => c.members.find((m) => ts.isConstructorDeclaration(m) && !!m.body && !forwards(m));
636
690
  // The constructor the object is made with: the entry's, or the nearest it inherits.
637
691
  const ctorAt = chain.findIndex(ownCtor), ctor = ctorAt >= 0 ? ownCtor(chain[ctorAt]) : undefined;
638
692
  for (const c of chain) {
@@ -643,6 +697,12 @@ function attempt(code, file, opts, written) {
643
697
  const fields = [];
644
698
  const addField = (f) => { if (fields.some(x => x.name === f.name))
645
699
  refuse(f.node, `${f.name}: a field declared again in a class that extends one with it`); fields.push(f); };
700
+ // A field whose type is a function (an injected clock, random or id source): no state; each call an input
701
+ // (core/extract-read.ts's fnFields). Its start is a function written there or the one the constructor is given.
702
+ const fnType = (t) => !(t.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) && s.checker.getSignaturesOfType(s.checker.getNonNullableType(t), ts.SignatureKind.Call).length > 0 && !s.checker.getPropertiesOfType(s.checker.getNonNullableType(t)).length;
703
+ s.fnFields = { outside: new Map(), names: new Set() };
704
+ const fnField = (name, at) => { if (s.fnFields.names.has(name))
705
+ refuse(at, `${name}: a field declared again in a class that extends one with it`); s.fnFields.names.add(name); };
646
706
  for (const c of [...chain].reverse()) {
647
707
  for (const m of c.members) {
648
708
  if (ts.isPropertyDeclaration(m)) {
@@ -652,6 +712,13 @@ function attempt(code, file, opts, written) {
652
712
  refuse(m, 'a static field (state shared by every object)');
653
713
  if (has(m, ts.SyntaxKind.AbstractKeyword) || has(m, ts.SyntaxKind.DeclareKeyword))
654
714
  continue;
715
+ if (fnType(s.checker.getTypeAtLocation(m))) {
716
+ const i = m.initializer && unparen(m.initializer);
717
+ if (i && !ts.isArrowFunction(i) && !ts.isFunctionExpression(i))
718
+ refuse(m, `${memberName(m.name)} starts as ${i.getText().slice(0, 40)} (a field holding a function starts as one written there, or the one the constructor is given)`);
719
+ fnField(memberName(m.name), m);
720
+ continue;
721
+ }
655
722
  addField({ name: memberName(m.name), shape: shapeOf(s.checker.getTypeAtLocation(m), s.checker, m), node: m, ...(m.initializer ? { init: m.initializer } : {}), of: c });
656
723
  }
657
724
  else if (ts.isSetAccessorDeclaration(m))
@@ -663,7 +730,9 @@ function attempt(code, file, opts, written) {
663
730
  }
664
731
  const k = ownCtor(c);
665
732
  for (const p of k?.parameters ?? [])
666
- if (ts.isParameterPropertyDeclaration(p, k))
733
+ if (ts.isParameterPropertyDeclaration(p, k) && fnType(s.checker.getTypeAtLocation(p)))
734
+ fnField(p.name.text, p);
735
+ else if (ts.isParameterPropertyDeclaration(p, k))
667
736
  addField({ name: p.name.text, shape: shapeOf(s.checker.getTypeAtLocation(p), s.checker, p), node: p, of: c });
668
737
  }
669
738
  const ex0 = new Exec(s);
@@ -692,6 +761,13 @@ function attempt(code, file, opts, written) {
692
761
  for (const p of ctor?.parameters ?? []) {
693
762
  if (!ts.isIdentifier(p.name))
694
763
  refuse(p, 'a destructured constructor argument');
764
+ // A function given to the constructor: the check gives one that answers each request's input.
765
+ if (fnType(s.checker.getTypeAtLocation(p))) {
766
+ const optional = !!p.questionToken || !!p.initializer || !!(s.checker.getTypeAtLocation(p).flags & ts.TypeFlags.Union && s.checker.getTypeAtLocation(p).types.some(x => x.flags & (ts.TypeFlags.Undefined | ts.TypeFlags.Null)));
767
+ ctorArgs.push('$fn');
768
+ argValues.push({ t: 'outside', path: `new${optional ? '?' : ''} ${opts.entry}(${p.name.text})` });
769
+ continue;
770
+ }
695
771
  const sh = shapeOf(s.checker.getTypeAtLocation(p), s.checker, p);
696
772
  // A Map given to the constructor: the field it becomes starts as that Map, taken here as empty (as callers make it).
697
773
  if (sh.k === 'map') {
@@ -105,9 +105,16 @@ export function extractXState(code, opts) {
105
105
  if (ctxExpr && ts.isIdentifier(ctxExpr) && ctxExpr.text === name)
106
106
  return { name, kind: 'context', node, type: t };
107
107
  const nn = checker.getNonNullableType(t), props = checker.getPropertiesOfType(nn);
108
- const fnTyped = (p) => checker.getSignaturesOfType(checker.getNonNullableType(checker.getTypeOfSymbolAtLocation(p, node)), ts.SignatureKind.Call).length > 0;
109
- if (props.length && props.every(fnTyped))
108
+ // A function's member, or one of type any (untyped code's): the machine's own guards and actions reading it are
109
+ // refused where they call it (its answer has no type the subset reads); an actor's body calling it is outside.
110
+ const untyped = (p) => (checker.getTypeOfSymbolAtLocation(p, node).flags & ts.TypeFlags.Any) !== 0;
111
+ const fnTyped = (p) => untyped(p) || checker.getSignaturesOfType(checker.getNonNullableType(checker.getTypeOfSymbolAtLocation(p, node)), ts.SignatureKind.Call).length > 0;
112
+ if (props.length && props.every(fnTyped)) {
113
+ const anys = props.filter(untyped).map(p => p.getName());
114
+ if (anys.length)
115
+ notes.push(`${name}: ${anys.join(', ')} of type any, called only where an actor runs (outside the machine): a guard or an action that calls one is refused`);
110
116
  return { name, kind: 'outside', node, type: nn, fields: props.map(p => [p.getName(), checker.getNonNullableType(checker.getTypeOfSymbolAtLocation(p, node))]) };
117
+ }
111
118
  const bad = props.find(p => !fnTyped(p));
112
119
  return refuse(node, `${name}: a factory argument that is neither the machine's context nor an object of functions (${props.length ? `${bad.getName()} is of type ${checker.typeToString(checker.getTypeOfSymbolAtLocation(bad, node))}` : `of type ${checker.typeToString(t)}`})`);
113
120
  };
@@ -131,7 +138,13 @@ export function extractXState(code, opts) {
131
138
  const stubOf = (a) => {
132
139
  const out = {};
133
140
  for (const [f, t] of a.fields ?? []) {
134
- const sig = checker.getSignaturesOfType(t, ts.SignatureKind.Call)[0], rt = checker.getReturnTypeOfSignature(sig);
141
+ const sig = checker.getSignaturesOfType(t, ts.SignatureKind.Call)[0];
142
+ // An untyped one: called while the machine is made, it throws (and the factory is refused).
143
+ if (!sig) {
144
+ out[f] = () => { throw new Error(`${a.name}.${f}, of type any, called`); };
145
+ continue;
146
+ }
147
+ const rt = checker.getReturnTypeOfSignature(sig);
135
148
  const promise = rt.getSymbol()?.getName() === 'Promise', path = `${a.name}.${f}`;
136
149
  out[f] = promise ? () => new Promise(() => { }) : () => answers[path];
137
150
  }
@@ -25,6 +25,7 @@ export type Extraction = {
25
25
  notes: string[];
26
26
  };
27
27
  export declare function extract(code: string, opts: ExtractOptions): Extraction;
28
+ export declare function fromModel(model: Model, file: string, domains: Record<string, 'nat' | 'int'> | undefined, notes: string[], run: (rule: Rule, sorts: Sorts) => Evidence): Extraction;
28
29
  export declare const toSource: (x: Extraction) => string;
29
30
  export type { Evidence, Model, Term };
30
31
  export { Refusal };
@@ -28,11 +28,14 @@
28
28
  // Boolean(x), Date.now() (an input; once a step), throws (the rule's refusals: its assumption, or its precondition
29
29
  // for a constructor), helper functions and methods of the same files (inlined), getters, single inheritance (each
30
30
  // member resolved statically: this.m() the nearest the object has, super.m() the nearest above the class it is in),
31
- // results kept (a value, a record of values, a value that may be missing). Refused: loops, strings beyond keys and
31
+ // mixins of the same files (`(B) => class extends B {...}`, its class between the entry and the class it is given),
32
+ // a field holding a function (an injected clock, random or id source: each call's answer an input, one a step, for
33
+ // every such function that leaves the object alone), results kept (a value, a record of values, a value that may be
34
+ // missing). Refused: loops, strings beyond keys and
32
35
  // literals, floats, async, try/catch, writes to the state a reducer is given, a throw after a method wrote a field, two
33
36
  // keys of one map or two writes of one list in one step, a map or a list replaced whole, a reference into a map held
34
- // across a set, one object (an array, a Map, a Date) in two places, aliasing that depends on the path, mixins, other
35
- // modules' code.
37
+ // across a set, one object (an array, a Map, a Date) in two places, aliasing that depends on the path, mixins of other
38
+ // modules, other modules' code.
36
39
  import * as dsl from "./dsl.js";
37
40
  import { compileFunction, walk } from "./machine.js";
38
41
  import * as I from "./extract-ir.js";
@@ -55,9 +58,14 @@ export function extract(code, opts) {
55
58
  return { ok: false, refusals: [{ where: e.where, what: e.what }], notes };
56
59
  throw e;
57
60
  }
61
+ return fromModel(model, file, opts.domains, notes, (rule, sorts) => check(code, file, model, rule, sorts, { ...opts.check, ...(opts.files ? { files: opts.files } : {}), ...(opts.domains ? { given: opts.domains } : {}) }));
62
+ }
63
+ // A model read by a front end (this file's TypeScript, or core/extract-go.ts's Go) printed as the rule, built, and
64
+ // checked against the code by the front end's own check: what both front ends share.
65
+ export function fromModel(model, file, domains, notes, run) {
58
66
  let source, body, sorts;
59
67
  try {
60
- const s = sortsOf(model, opts.domains);
68
+ const s = sortsOf(model, domains);
61
69
  sorts = s.sorts;
62
70
  datesInRange(model, sorts);
63
71
  notes.push(...model.notes, ...s.notes);
@@ -79,7 +87,7 @@ export function extract(code, opts) {
79
87
  }
80
88
  if (invariants.length)
81
89
  source = `${source}\n// What every state of the code is: a law about every state is about the code's with these beside it.\nexport const ${identOf(model)}Invariants = [${invariantsOf(model, sorts).map(x => x.replace(/^r\./, `${identOf(model)}Rule.`)).join(', ')}]\n`;
82
- const evidence = check(code, file, model, rule, sorts, { ...opts.check, ...(opts.files ? { files: opts.files } : {}), ...(opts.domains ? { given: opts.domains } : {}) });
90
+ const evidence = run(rule, sorts);
83
91
  if (evidence.mismatch)
84
92
  return { ok: false, source, model, sorts, evidence, refusals: [{ where: file, what: `the rule and the code differ: ${evidence.mismatch}` }], notes };
85
93
  return { ok: true, rule, ...(invariants.length ? { invariants } : {}), source, model, sorts, evidence, refusals: [], notes };
@@ -126,7 +134,7 @@ function evaluate(body) {
126
134
  function invariantsOf(m, sorts) {
127
135
  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('')`);
128
136
  void sorts;
129
- return [...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(', ')}))))`),
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(', ')}))))`),
130
138
  ...(m.lists ?? []).map(d => `r.law(${JSON.stringify(`${d.name}: nothing past its end`)}, ({${d.name}}) => ${d.name}.within())`)];
131
139
  }
132
140
  function evaluateLaws(r, xs) {
@@ -140,9 +148,9 @@ function moduleOf(m, body, file) {
140
148
  const used = NAMES.filter(n => new RegExp(`(^|[^.\\w$])${n}\\(|(^|[^.\\w$])${n}\\b(?!\\s*:)`).test(body.replace(/'[^']*'/g, "''")) || (n === 'rule'));
141
149
  const ident = identOf(m);
142
150
  return [
143
- `// Extracted by gdp-wired/extract from ${file} (${m.entry}, ${m.factory ? 'a factory of an object of functions' : m.shape === 'class' ? 'a class' : m.shape === 'reducer' ? 'a step function' : 'functions over one record'}).`,
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'}).`,
144
152
  `// Checked against the code it was read from; read again with extract() after the code changes.`,
145
- `import {${[...new Set([...used, ...(m.maps.length ? ['all', 'any', 'forall'] : [])])].sort((a, b) => a.localeCompare(b)).join(', ')}} from 'gdp-wired'`,
153
+ `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'`,
146
154
  '',
147
155
  `export const ${ident}Rule = ${body}`,
148
156
  '',
@@ -0,0 +1,9 @@
1
+ import { type Law, type Machine } from './machine.js';
2
+ import type { Draws } from './live.js';
3
+ export type FreshLaw = {
4
+ law: Law;
5
+ text: string;
6
+ };
7
+ export declare function freshLaws(m: Machine, kinds: Law[], draws: Draws, opts?: {
8
+ ms?: number;
9
+ }): FreshLaw[];
@@ -0,0 +1,91 @@
1
+ // Laws about ids handed out by a counter: a state variable that only goes up (the next id), and maps written at the
2
+ // ids it has handed out. Code that numbers its sessions, tokens, grants or rows so (the n-th created gets id n) keeps
3
+ // ∀k. c <= k → M[k] is M's initial value (no row exists yet at an id not handed out)
4
+ // ∀k. G[k] is G's initial value ∨ M[k] < c (a row that exists holds an id handed out, of a counter c)
5
+ // and laws about one id often need them: a deleted session never comes back, a rotated token's old value is rejected.
6
+ // The candidates are each counter (never lower after a step of the runs, and some map's cell at its value written as it
7
+ // goes on: an id handed out) with each map, and each map with each map of the
8
+ // same record (`Tok.st`, `Tok.grant`) or itself; those the runs' states keep, then those proven inductive together
9
+ // (Houdini: a candidate whose goal fails is dropped, the rest proven again). Nothing new is trusted: what is kept is
10
+ // laws the kernel proves.
11
+ import { evalC, interpret, seeded } from "./machine.js";
12
+ import { clock, proveLaws } from "../kernel/prove.js";
13
+ import { allowed, watch } from "./watch.js";
14
+ const v = (name) => ({ op: 'var', name }), get = (map, key) => ({ op: 'get', map, key });
15
+ export function freshLaws(m, kinds, draws, opts = {}) {
16
+ const maps = Object.entries(m.maps ?? {}).filter(([n]) => !(m.inputMaps ?? []).includes(n));
17
+ if (!maps.length || m.history)
18
+ return [];
19
+ const until = clock() + (opts.ms ?? 5000), run = interpret(m), rand = seeded(53), bound = 4;
20
+ // the runs: their states, and the variables some step lowers
21
+ const states = [], lowered = new Set(), handed = new Set();
22
+ for (let trial = 0; trial < 60 && clock() < until; trial++) {
23
+ let ps, st;
24
+ try {
25
+ ps = draws.params(rand, bound);
26
+ if (m.pre && !evalC(m.pre, ps, { scalars: {}, maps: {} }, m))
27
+ continue;
28
+ st = run.init(ps);
29
+ }
30
+ catch {
31
+ continue;
32
+ }
33
+ for (let d = 0, tries = 0; d < 20 && tries < 60; tries++) {
34
+ try {
35
+ const input = draws.input(rand, bound, ps);
36
+ if (!allowed(m, run, ps, st, input))
37
+ continue;
38
+ const next = run.step(ps, st, input);
39
+ for (const x of Object.keys(m.state)) {
40
+ const was = st.scalars[x], now = next.scalars[x];
41
+ if (now < was)
42
+ lowered.add(x);
43
+ // an id handed out: the counter goes on, and some map's cell at its old value is written
44
+ else if (now > was && maps.some(([n, init]) => (st.maps[n]?.get(was) ?? init) !== (next.maps[n]?.get(was) ?? init)))
45
+ handed.add(x);
46
+ }
47
+ st = next;
48
+ d++;
49
+ states.push({ ps, st });
50
+ }
51
+ catch { /* refused: another */ }
52
+ }
53
+ }
54
+ const counters = [...handed].filter(c => !lowered.has(c));
55
+ if (!counters.length)
56
+ return [];
57
+ const key = 'k$fresh', record = (n) => n.slice(0, Math.max(0, n.indexOf('.')));
58
+ const cands = [];
59
+ for (const c of counters)
60
+ for (const [map, init] of maps) {
61
+ const at = get(map, v(key)), initial = { op: '=', a: at, b: { op: 'const', value: init } };
62
+ cands.push({ law: { name: `ids from ${c}: ${map} unset past them`, holds: { op: 'or', xs: [{ op: '<', a: v(key), b: v(c) }, initial] }, forall: key }, text: `∀k. ${c} <= k → ${map}[k] = ${init}` });
63
+ for (const [g, gi] of maps) {
64
+ if (g !== map && (!record(g) || record(g) !== record(map)))
65
+ continue;
66
+ cands.push({ law: { name: `ids from ${c}: ${map} below them where ${g} is set`, holds: { op: 'or', xs: [{ op: '=', a: get(g, v(key)), b: { op: 'const', value: gi } }, { op: '<', a: at, b: v(c) }] }, forall: key }, text: `∀k. ${g}[k] ≠ ${gi} → ${map}[k] < ${c}` });
67
+ }
68
+ }
69
+ let alive = cands.filter(f => states.every(({ ps, st }) => { try {
70
+ return watch(m, run, f.law, ps, bound).start(st);
71
+ }
72
+ catch {
73
+ return false;
74
+ } }));
75
+ while (alive.length && clock() < until) {
76
+ let out;
77
+ try {
78
+ out = proveLaws(m, [...kinds, ...alive.map(f => f.law)]);
79
+ }
80
+ catch {
81
+ return [];
82
+ }
83
+ if (out.proven && out.checked)
84
+ return alive;
85
+ const failed = out.failed?.goal ?? '', drop = alive.findIndex(f => failed.startsWith(`${f.law.name} @`) || failed.startsWith(`${f.law.name}:`));
86
+ if (drop < 0)
87
+ return [];
88
+ alive = alive.filter((_, i) => i !== drop);
89
+ }
90
+ return [];
91
+ }
@@ -14,6 +14,7 @@ export type InferOptions = {
14
14
  existentials?: boolean;
15
15
  minimize?: boolean;
16
16
  remainders?: boolean;
17
+ join?: number;
17
18
  };
18
19
  export type Found = {
19
20
  law: Law;