gdp-wired 0.27.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.
@@ -160,7 +160,8 @@ function snapOf(v, layout, m, consts, out = { leaves: {}, maps: {} }, path = 'st
160
160
  case 'rec': {
161
161
  if (typeof v !== 'object' || v === null)
162
162
  throw new Error(`${path} is ${JSON.stringify(v)}, not an object`);
163
- const own = Object.keys(v), want = layout.fields.map(([f]) => f).filter(f => !f.endsWith('()'));
163
+ // (a class's fields holding a function are no state: the object's own, left out where they hold one)
164
+ const own = Object.keys(v).filter(k => !(path === 'state' && m.fnFields?.includes(k) && typeof v[k] === 'function')), want = layout.fields.map(([f]) => f).filter(f => !f.endsWith('()'));
164
165
  for (const k of own)
165
166
  if (!want.includes(k))
166
167
  throw new Error(`${path} has a field ${k} the rule doesn't`);
@@ -376,18 +377,28 @@ export function check(code, file, m, r, sorts, opts = {}) {
376
377
  vmOf().runInContext(`__gdp.$method = function (name, args) { return this[name](...args) }; __gdp.$new = function (...args) { return new __gdp[${E}](...args) }; __gdp.$at = function (fields) { return Object.assign(Object.create(__gdp[${E}].prototype), fields) }`, box.ctx);
377
378
  if (m.factory)
378
379
  vmOf().runInContext(`__gdp.$method = function (name, args) { return this[name](...args) }; __gdp.$new = function (...args) { return __gdp[${E}](...args) }; __gdp.$get = function () { return this.__gdpGet() }; __gdp.$at = function (fields, args) { const o = __gdp[${E}](...args); o.__gdpSet(fields); return o }`, box.ctx);
379
- const ctorValues = (params) => (m.ctorArgs ?? []).filter(n => !m.params.find(v => v.name === n)?.note?.startsWith('Date.now()')).map(n => (n.startsWith('$map:') ? vmOf().runInContext(n === '$map:Map' ? 'new Map()' : '({})', box.ctx) : params[n]));
380
+ // A class's fields holding a function: each answers the request's input (set on the object before each call; a
381
+ // function given to the constructor is one such too).
382
+ let answers = {};
383
+ const answering = (f) => () => { const n = Object.keys(m.answers ?? {}).find(k => m.answers[k] === f); return n === undefined ? undefined : answers[n]; };
384
+ const fnArg = () => () => { throw new Error('a function given to the constructor called while the object is made'); };
385
+ const ctorValue = (n, params) => (n === '$fn' ? fnArg() : n.startsWith('$map:') ? vmOf().runInContext(n === '$map:Map' ? 'new Map()' : '({})', box.ctx) : params[n]);
386
+ const ctorValues = (params) => (m.ctorArgs ?? []).filter(n => !m.params.find(v => v.name === n)?.note?.startsWith('Date.now()')).map(n => ctorValue(n, params));
380
387
  const side = {
381
388
  make: params => {
382
389
  const now0 = m.params.find(v => v.note?.startsWith('Date.now()'));
383
390
  if (now0)
384
391
  box.setNow(params[now0.name]);
385
392
  // A Map the constructor is given: an empty one, made in the code's realm.
386
- return box.call('$new', undefined, (m.ctorArgs ?? []).filter(n => n !== now0?.name).map(n => (n.startsWith('$map:') ? vmOf().runInContext(n === '$map:Map' ? 'new Map()' : '({})', box.ctx) : params[n])));
393
+ return box.call('$new', undefined, (m.ctorArgs ?? []).filter(n => n !== now0?.name).map(n => ctorValue(n, params)));
387
394
  },
388
395
  at: (snap, params) => (box.call('$at', undefined, [valueOf(snap, m.layout, m, evalAt(params), box.ctx), ctorValues(params)]).ok ? box.ctx.__r.value : (() => { throw new Error(`could not make the object: ${box.ctx.__r.error}`); })()),
389
396
  snapOf: (self, params) => snapOf(stateOf(self), m.layout, m, evalAt(params)),
390
- call: (self, e, args) => box.call('$method', self, [e.call, args]),
397
+ call: (self, e, args) => {
398
+ for (const f of new Set(Object.values(m.answers ?? {})))
399
+ self[f] = answering(f);
400
+ return box.call('$method', self, [e.call, args]);
401
+ },
391
402
  reduce: (snap, e, args, params) => {
392
403
  const input = valueOf(snap, m.layout, m, evalAt(params), box.ctx), before = JSON.stringify(input, mapReplacer);
393
404
  const res = box.call(e.call, undefined, [input, ...args.slice(1)]);
@@ -396,6 +407,7 @@ export function check(code, file, m, r, sorts, opts = {}) {
396
407
  return res.ok ? { snap: snapOf(res.value, m.layout, m, evalAt(params)) } : { refused: res.error };
397
408
  },
398
409
  args: (inputs, e) => {
410
+ answers = inputs;
399
411
  const dateIn = (n) => { const x = m.inputs.find(v => v.name === n); return x?.sort.k === 'num' && x.sort.date ? vmOf().runInContext(`new Date(${Number(inputs[n])})`, box.ctx) : inputs[n]; };
400
412
  const build = (a) => (a.k === 'input' ? dateIn(a.name) : a.k === 'lit' ? a.value : a.k === 'rec' ? Object.fromEntries(a.fields.map(([f, x]) => [f, build(x)])) : a.k === 'lazy'
401
413
  ? Object.fromEntries([...m.inputs].filter(v => m.lazy?.get(v.name)?.prefix === a.prefix).map(v => [m.lazy.get(v.name).field, inputs[v.name]]))
@@ -473,7 +485,7 @@ export function drive(m, r, sorts, code, opts = {}) {
473
485
  used.add(v.name); };
474
486
  e.args.forEach(walk);
475
487
  for (const v of m.inputs)
476
- if (v.note?.startsWith('Date.now()'))
488
+ if (v.note?.startsWith('Date.now()') || m.answers?.[v.name])
477
489
  used.add(v.name);
478
490
  // An input the event doesn't bring: its kind's first value (the rule reads it only under another event).
479
491
  return Object.fromEntries(m.inputs.map(v => [v.name, v.name in e.select ? e.select[v.name] : used.has(v.name) ? inputs[v.name] : v.sort.k === 'num' ? 0 : v.sort.k === 'bool' ? false : v.sort.k === 'choice' ? v.sort.values[0] : '']));
@@ -173,6 +173,8 @@ export type Model = {
173
173
  null: boolean;
174
174
  }>;
175
175
  laws?: string[];
176
+ answers?: Record<string, string>;
177
+ fnFields?: string[];
176
178
  };
177
179
  type V = {
178
180
  t: 'num';
@@ -253,12 +255,14 @@ type Path = {
253
255
  heap: Heap;
254
256
  wrote: string[];
255
257
  nows: number;
258
+ outs?: string[];
256
259
  };
257
260
  type Flow = {
258
261
  live?: Path;
259
262
  rets: [Path, V][];
260
263
  breaks: Path[];
261
264
  };
265
+ export declare const unparen: (x: ts.Expression) => ts.Expression;
262
266
  export declare const normalize: (path: string) => string;
263
267
  export declare const resolveIn: (files: Record<string, string>, from: string, spec: string) => string | undefined;
264
268
  export declare function program(code: string, file: string, extra?: Record<string, string>): {
@@ -299,6 +303,13 @@ export type Setup = {
299
303
  sort: Sort;
300
304
  }>;
301
305
  };
306
+ fnFields?: {
307
+ outside: Map<string, {
308
+ path: string;
309
+ sort: Sort;
310
+ }>;
311
+ names: Set<string>;
312
+ };
302
313
  };
303
314
  export declare class Exec {
304
315
  readonly s: Setup;
@@ -364,6 +375,7 @@ export declare class Exec {
364
375
  resolved(e: ts.Node): ts.Symbol | undefined;
365
376
  private args;
366
377
  private call;
378
+ fnField(x: ts.Expression): boolean;
367
379
  private outside;
368
380
  private listLen;
369
381
  private listOp;
@@ -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') {
@@ -496,10 +498,13 @@ export class Exec {
496
498
  case 'choice': return v.values.includes('') ? I.not(I.is(v.e, '')) : I.T;
497
499
  // A string is truthy where it isn't empty.
498
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;
499
505
  case 'ref':
500
506
  case 'cell':
501
- case 'phi':
502
- case 'outside': return I.T;
507
+ case 'phi': return I.T;
503
508
  case 'opt': return I.and(v.has, this.truthy(v.v, at));
504
509
  case 'undef': return I.F;
505
510
  case 'opaque': return refuse(at, `${text(at)} read as a condition: ${v.what}`);
@@ -689,6 +694,15 @@ export class Exec {
689
694
  }
690
695
  binary(e, p) {
691
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
+ }
692
706
  if (op === S.EqualsToken) {
693
707
  const [v, q] = this.ev(e.right, p);
694
708
  return [v, this.assign(e.left, v, q)];
@@ -1234,6 +1248,11 @@ export class Exec {
1234
1248
  // A function the factory is given: its answer is an input of the step (any value of its type), read once.
1235
1249
  if (ts.isIdentifier(obj) && p.locals.get(obj.text)?.t === 'outside')
1236
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
+ }
1237
1256
  if (obj.kind === ts.SyntaxKind.ThisKeyword && this.s.cls) {
1238
1257
  const member = this.member(m);
1239
1258
  if (member && ts.isMethodDeclaration(member)) {
@@ -1321,8 +1340,14 @@ export class Exec {
1321
1340
  }
1322
1341
  return refuse(e, 'a call the subset doesn\'t read');
1323
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
+ }
1324
1348
  outside(e, path, p) {
1325
- 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`);
1326
1351
  if (e.arguments.some(impure))
1327
1352
  refuse(e, `${path}(...) with arguments that have effects`);
1328
1353
  const [, q] = this.args(e.arguments, p);
@@ -1336,6 +1361,20 @@ export class Exec {
1336
1361
  const sh = shapeOf(t, this.s.checker, e);
1337
1362
  if (sh.k !== 'num' && sh.k !== 'bool' && sh.k !== 'choice' && sh.k !== 'str')
1338
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
+ }
1339
1378
  if ([...x.outside.values()].some(o => o.path === path))
1340
1379
  return refuse(e, `${path}() read in two places (each call may answer differently)`);
1341
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)`);
@@ -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, mergeOps, 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;
@@ -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
  }
@@ -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";
@@ -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
+ }
@@ -74,6 +74,8 @@ const joinPrime = env.GDP_JOIN_PRIME !== '0';
74
74
  // GDP_JOIN_DOWN=0: a blocked cube kept as its refutation's core cuts it (no literal dropped); joinDownQueries, the
75
75
  // queries a cube's generalization may ask.
76
76
  const joinDown = env.GDP_JOIN_DOWN !== '0', joinDownQueries = 24;
77
+ // GDP_INFER_HALVES=0: a cell form chosen without its equality's other half (below).
78
+ const inferHalves = env.GDP_INFER_HALVES !== '0';
77
79
  const isRule = (t) => typeof t.kindsOfState === 'function';
78
80
  // The constants a machine's expressions hold, and the factors it multiplies by.
79
81
  function constantsOf(m, laws) {
@@ -1664,6 +1666,8 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1664
1666
  forget();
1665
1667
  return whole;
1666
1668
  };
1669
+ // A cell form's mirror, −Σ ≤ −d beside Σ ≤ d under the same guard (its text).
1670
+ const mirrorText = (f) => (!f.cells || f.mod || f.cong || f.never || f.nevers || f.cube || f.unreachable || f.also || !f.coef.length ? undefined : textOf({ ...f, coef: f.coef.map(([i, c]) => [i, -c]), d: -f.d }));
1667
1671
  for (let iter = 0; iter < 300 && now() < until && !stop(); iter++) {
1668
1672
  const began = now(), wall = performance.now();
1669
1673
  // (each law proven alone, then the set as a whole: the same goals, grown once)
@@ -1699,8 +1703,14 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
1699
1703
  next = best(p);
1700
1704
  opts.progress?.('cti', { forms: made.length, ms: Math.round(performance.now() - t) });
1701
1705
  }
1706
+ // (a cell form chosen with its mirror where that is alive: the equality both halves state at every key, neither
1707
+ // inductive without the other, as the real-world corpus's Timelock and blnk need; on CHC's scalar forms, measured,
1708
+ // it cost s_split tasks, so cell forms only)
1702
1709
  if (next) {
1703
1710
  chosen.push(next);
1711
+ const mt = inferHalves ? mirrorText(next) : undefined, mirror = mt && pool.find(g => !chosen.includes(g) && textOf(g) === mt);
1712
+ if (mirror)
1713
+ chosen.push(mirror);
1704
1714
  continue;
1705
1715
  }
1706
1716
  // Stuck with no counterexample on a goal not a candidate's: the last candidate made it harder, so it goes.
@@ -0,0 +1,15 @@
1
+ import { type Law, type Machine, type Rand, type Request } from './machine.js';
2
+ import { type Liveness } from '../kernel/kernel.js';
3
+ import { type LeadsVerdict } from './cycles.js';
4
+ import { inferLaws } from './infer.js';
5
+ type Env = Record<string, number>;
6
+ export type Draws = {
7
+ params: (rand: Rand, bound: number) => Env;
8
+ input: (rand: Rand, bound: number, ps: Env) => Request;
9
+ state?: (rand: Rand, bound: number) => Env;
10
+ rule?: Parameters<typeof inferLaws>[0];
11
+ };
12
+ export declare function leadsByTerms(m: Machine, laws: Law[], l: Liveness, draws: Draws, opts?: {
13
+ ms?: number;
14
+ }): LeadsVerdict;
15
+ export {};