gdp-wired 0.27.0 → 0.29.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.
- package/dist/core/accel.d.ts +5 -0
- package/dist/core/accel.js +24 -16
- package/dist/core/cycles.d.ts +2 -0
- package/dist/core/cycles.js +31 -4
- package/dist/core/data.d.ts +5 -0
- package/dist/core/data.js +259 -40
- package/dist/core/dsl.d.ts +11 -1
- package/dist/core/dsl.js +205 -21
- package/dist/core/extract-check.js +17 -5
- package/dist/core/extract-read.d.ts +13 -1
- package/dist/core/extract-read.js +47 -7
- package/dist/core/extract-shapes.js +100 -19
- package/dist/core/extract-xstate.js +105 -13
- package/dist/core/extract.js +6 -3
- package/dist/core/fresh.d.ts +9 -0
- package/dist/core/fresh.js +106 -0
- package/dist/core/infer.js +829 -188
- package/dist/core/live.d.ts +15 -0
- package/dist/core/live.js +317 -0
- package/dist/core/machine.d.ts +5 -0
- package/dist/core/machine.js +3 -3
- package/dist/core/nonterm.d.ts +3 -1
- package/dist/core/nonterm.js +76 -18
- package/dist/kernel/cdcl.d.ts +18 -1
- package/dist/kernel/cdcl.js +13 -8
- package/dist/kernel/kernel.d.ts +34 -2
- package/dist/kernel/kernel.js +345 -13
- package/dist/kernel/prove.d.ts +5 -1
- package/dist/kernel/prove.js +200 -63
- package/dist/kernel/reader.d.ts +2 -0
- package/dist/kernel/reader.js +7 -4
- package/dist/lean-kernel/emit.d.ts +27 -3
- package/dist/lean-kernel/emit.js +251 -25
- package/dist/lean-kernel/library.js +3 -2
- package/package.json +3 -2
|
@@ -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
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
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(
|
|
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(
|
|
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(
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
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
|
-
|
|
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,16 @@ 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
|
+
// A field's type as the entry's object has it: a class it extends with type arguments (`extends Base<Ctx>`) has its
|
|
705
|
+
// fields of a type parameter at the types given (TypeScript's own instantiation of the chain).
|
|
706
|
+
const ct = s.checker.getTypeAtLocation(cls), inst = ts.isClassDeclaration(cls) ? ct : ct.getConstructSignatures()[0]?.getReturnType();
|
|
707
|
+
const typeOf = (name, node) => { const sym = inst && s.checker.getPropertyOfType(inst, name); return sym ? s.checker.getTypeOfSymbolAtLocation(sym, cls) : s.checker.getTypeAtLocation(node); };
|
|
708
|
+
const fnField = (name, at) => { if (s.fnFields.names.has(name))
|
|
709
|
+
refuse(at, `${name}: a field declared again in a class that extends one with it`); s.fnFields.names.add(name); };
|
|
646
710
|
for (const c of [...chain].reverse()) {
|
|
647
711
|
for (const m of c.members) {
|
|
648
712
|
if (ts.isPropertyDeclaration(m)) {
|
|
@@ -652,7 +716,15 @@ function attempt(code, file, opts, written) {
|
|
|
652
716
|
refuse(m, 'a static field (state shared by every object)');
|
|
653
717
|
if (has(m, ts.SyntaxKind.AbstractKeyword) || has(m, ts.SyntaxKind.DeclareKeyword))
|
|
654
718
|
continue;
|
|
655
|
-
|
|
719
|
+
const mt = typeOf(memberName(m.name), m);
|
|
720
|
+
if (fnType(mt)) {
|
|
721
|
+
const i = m.initializer && unparen(m.initializer);
|
|
722
|
+
if (i && !ts.isArrowFunction(i) && !ts.isFunctionExpression(i))
|
|
723
|
+
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)`);
|
|
724
|
+
fnField(memberName(m.name), m);
|
|
725
|
+
continue;
|
|
726
|
+
}
|
|
727
|
+
addField({ name: memberName(m.name), shape: shapeOf(mt, s.checker, m), node: m, ...(m.initializer ? { init: m.initializer } : {}), of: c });
|
|
656
728
|
}
|
|
657
729
|
else if (ts.isSetAccessorDeclaration(m))
|
|
658
730
|
refuse(m, 'a setter');
|
|
@@ -663,8 +735,10 @@ function attempt(code, file, opts, written) {
|
|
|
663
735
|
}
|
|
664
736
|
const k = ownCtor(c);
|
|
665
737
|
for (const p of k?.parameters ?? [])
|
|
666
|
-
if (ts.isParameterPropertyDeclaration(p, k))
|
|
667
|
-
|
|
738
|
+
if (ts.isParameterPropertyDeclaration(p, k) && fnType(typeOf(p.name.text, p)))
|
|
739
|
+
fnField(p.name.text, p);
|
|
740
|
+
else if (ts.isParameterPropertyDeclaration(p, k))
|
|
741
|
+
addField({ name: p.name.text, shape: shapeOf(typeOf(p.name.text, p), s.checker, p), node: p, of: c });
|
|
668
742
|
}
|
|
669
743
|
const ex0 = new Exec(s);
|
|
670
744
|
const constant = (f) => !first && !written.has(f.name) && f.shape.k !== 'map' && f.shape.k !== 'list';
|
|
@@ -692,6 +766,13 @@ function attempt(code, file, opts, written) {
|
|
|
692
766
|
for (const p of ctor?.parameters ?? []) {
|
|
693
767
|
if (!ts.isIdentifier(p.name))
|
|
694
768
|
refuse(p, 'a destructured constructor argument');
|
|
769
|
+
// A function given to the constructor: the check gives one that answers each request's input.
|
|
770
|
+
if (fnType(s.checker.getTypeAtLocation(p))) {
|
|
771
|
+
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)));
|
|
772
|
+
ctorArgs.push('$fn');
|
|
773
|
+
argValues.push({ t: 'outside', path: `new${optional ? '?' : ''} ${opts.entry}(${p.name.text})` });
|
|
774
|
+
continue;
|
|
775
|
+
}
|
|
695
776
|
const sh = shapeOf(s.checker.getTypeAtLocation(p), s.checker, p);
|
|
696
777
|
// A Map given to the constructor: the field it becomes starts as that Map, taken here as empty (as callers make it).
|
|
697
778
|
if (sh.k === 'map') {
|
|
@@ -89,11 +89,28 @@ export function extractXState(code, opts) {
|
|
|
89
89
|
return p && (ts.isPropertyAssignment(p) ? p.initializer : ts.isShorthandPropertyAssignment(p) ? p.name : undefined);
|
|
90
90
|
};
|
|
91
91
|
const prop = (o, name) => { const x = propRaw(o, name); return x && strip(x); };
|
|
92
|
+
// What a name stands for, through the program: a const's value or a function declared, in the files read (an import,
|
|
93
|
+
// `export default X`, a const of a const), as TypeScript resolves the name; anything else as it is.
|
|
94
|
+
const valueOf = (e, depth = 0) => {
|
|
95
|
+
e = strip(e);
|
|
96
|
+
if (!ts.isIdentifier(e) || depth > 8)
|
|
97
|
+
return e;
|
|
98
|
+
let sym = ts.isShorthandPropertyAssignment(e.parent) && e.parent.name === e ? checker.getShorthandAssignmentValueSymbol(e.parent) : checker.getSymbolAtLocation(e);
|
|
99
|
+
if (sym && sym.flags & ts.SymbolFlags.Alias)
|
|
100
|
+
sym = checker.getAliasedSymbol(sym);
|
|
101
|
+
const d = sym?.valueDeclaration;
|
|
102
|
+
if (d && ts.isFunctionDeclaration(d) && d.body)
|
|
103
|
+
return d;
|
|
104
|
+
if (d && ts.isVariableDeclaration(d) && d.initializer && d.parent.flags & ts.NodeFlags.Const && !d.getSourceFile().isDeclarationFile)
|
|
105
|
+
return valueOf(d.initializer, depth + 1);
|
|
106
|
+
return e;
|
|
107
|
+
};
|
|
92
108
|
const objOf = (o, name) => {
|
|
93
|
-
const
|
|
94
|
-
if (
|
|
109
|
+
const v0 = prop(o, name);
|
|
110
|
+
if (v0 === undefined)
|
|
95
111
|
return undefined;
|
|
96
|
-
|
|
112
|
+
const v = valueOf(v0);
|
|
113
|
+
return ts.isObjectLiteralExpression(v) ? v : refuse(v0, `the ${name} given as other than an object of them`);
|
|
97
114
|
};
|
|
98
115
|
const args = [];
|
|
99
116
|
const ctxExpr = prop(config, 'context');
|
|
@@ -105,9 +122,16 @@ export function extractXState(code, opts) {
|
|
|
105
122
|
if (ctxExpr && ts.isIdentifier(ctxExpr) && ctxExpr.text === name)
|
|
106
123
|
return { name, kind: 'context', node, type: t };
|
|
107
124
|
const nn = checker.getNonNullableType(t), props = checker.getPropertiesOfType(nn);
|
|
108
|
-
|
|
109
|
-
|
|
125
|
+
// A function's member, or one of type any (untyped code's): the machine's own guards and actions reading it are
|
|
126
|
+
// refused where they call it (its answer has no type the subset reads); an actor's body calling it is outside.
|
|
127
|
+
const untyped = (p) => (checker.getTypeOfSymbolAtLocation(p, node).flags & ts.TypeFlags.Any) !== 0;
|
|
128
|
+
const fnTyped = (p) => untyped(p) || checker.getSignaturesOfType(checker.getNonNullableType(checker.getTypeOfSymbolAtLocation(p, node)), ts.SignatureKind.Call).length > 0;
|
|
129
|
+
if (props.length && props.every(fnTyped)) {
|
|
130
|
+
const anys = props.filter(untyped).map(p => p.getName());
|
|
131
|
+
if (anys.length)
|
|
132
|
+
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
133
|
return { name, kind: 'outside', node, type: nn, fields: props.map(p => [p.getName(), checker.getNonNullableType(checker.getTypeOfSymbolAtLocation(p, node))]) };
|
|
134
|
+
}
|
|
111
135
|
const bad = props.find(p => !fnTyped(p));
|
|
112
136
|
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
137
|
};
|
|
@@ -131,7 +155,13 @@ export function extractXState(code, opts) {
|
|
|
131
155
|
const stubOf = (a) => {
|
|
132
156
|
const out = {};
|
|
133
157
|
for (const [f, t] of a.fields ?? []) {
|
|
134
|
-
const sig = checker.getSignaturesOfType(t, ts.SignatureKind.Call)[0]
|
|
158
|
+
const sig = checker.getSignaturesOfType(t, ts.SignatureKind.Call)[0];
|
|
159
|
+
// An untyped one: called while the machine is made, it throws (and the factory is refused).
|
|
160
|
+
if (!sig) {
|
|
161
|
+
out[f] = () => { throw new Error(`${a.name}.${f}, of type any, called`); };
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
const rt = checker.getReturnTypeOfSignature(sig);
|
|
135
165
|
const promise = rt.getSymbol()?.getName() === 'Promise', path = `${a.name}.${f}`;
|
|
136
166
|
out[f] = promise ? () => new Promise(() => { }) : () => answers[path];
|
|
137
167
|
}
|
|
@@ -280,8 +310,8 @@ export function extractXState(code, opts) {
|
|
|
280
310
|
// One function of ({context, event}) (v4: (context, event)) at a time, with the context as variables and the event's
|
|
281
311
|
// fields as inputs.
|
|
282
312
|
const run = (f, what) => {
|
|
283
|
-
const fn =
|
|
284
|
-
if (!isFn(fn))
|
|
313
|
+
const fn = valueOf(f);
|
|
314
|
+
if (!isFn(fn) && !ts.isFunctionDeclaration(fn))
|
|
285
315
|
return refuse(f, `${what}: a reference to a function defined elsewhere`);
|
|
286
316
|
if (fn.parameters.length > (v === 4 ? 2 : 1))
|
|
287
317
|
refuse(fn, `${what} reads its params (guards and actions with params are not in the subset)`);
|
|
@@ -305,7 +335,14 @@ export function extractXState(code, opts) {
|
|
|
305
335
|
};
|
|
306
336
|
// A guard: a condition of ({context, event}), or stateIn.
|
|
307
337
|
const guardOf = (g, name) => {
|
|
308
|
-
|
|
338
|
+
const gv = valueOf(g);
|
|
339
|
+
if (ts.isFunctionDeclaration(gv)) {
|
|
340
|
+
const { v: out } = run(g, `the guard ${name}`);
|
|
341
|
+
if (out.t !== 'bool')
|
|
342
|
+
refuse(g, `the guard ${name} returns other than a boolean`);
|
|
343
|
+
return out.e;
|
|
344
|
+
}
|
|
345
|
+
g = gv;
|
|
309
346
|
if (ts.isCallExpression(g) && ts.isIdentifier(g.expression) && g.expression.text === 'stateIn') {
|
|
310
347
|
const a = g.arguments[0] && strip(g.arguments[0]);
|
|
311
348
|
const path = (o) => (ts.isStringLiteral(o) ? o.text : ts.isObjectLiteralExpression(o) && o.properties.length === 1 && ts.isPropertyAssignment(o.properties[0]) ? `${o.properties[0].name.getText()}.${path(strip(o.properties[0].initializer))}` : refuse(o, 'a stateIn of other than one state'));
|
|
@@ -325,7 +362,12 @@ export function extractXState(code, opts) {
|
|
|
325
362
|
throw e;
|
|
326
363
|
} };
|
|
327
364
|
const actionOf = (a, name) => {
|
|
328
|
-
|
|
365
|
+
const av = valueOf(a);
|
|
366
|
+
if (ts.isFunctionDeclaration(av)) {
|
|
367
|
+
notes.push(`the action ${name} writes no context (its effects outside the machine are left out)`);
|
|
368
|
+
return null;
|
|
369
|
+
}
|
|
370
|
+
a = av;
|
|
329
371
|
const fname = ts.isCallExpression(a) && ts.isIdentifier(a.expression) ? a.expression.text : undefined;
|
|
330
372
|
if (fname === 'assign' && ts.isCallExpression(a)) {
|
|
331
373
|
const arg = a.arguments[0] ? strip(a.arguments[0]) : refuse(a, 'assign()');
|
|
@@ -381,12 +423,62 @@ export function extractXState(code, opts) {
|
|
|
381
423
|
}
|
|
382
424
|
return refuse(a, `the action ${name}: an action the subset doesn't read`);
|
|
383
425
|
};
|
|
384
|
-
|
|
426
|
+
// An object's entries by name: `name: value`, `name` (the value its name stands for), `...other` (another
|
|
427
|
+
// object's entries, the later ones winning, as JavaScript spreads them).
|
|
428
|
+
const named = (o, out = new Map(), depth = 0) => {
|
|
429
|
+
for (const x of o?.properties ?? []) {
|
|
430
|
+
if (ts.isPropertyAssignment(x))
|
|
431
|
+
out.set(memberName(x.name), x.initializer);
|
|
432
|
+
else if (ts.isShorthandPropertyAssignment(x))
|
|
433
|
+
out.set(x.name.text, x.name);
|
|
434
|
+
else if (ts.isSpreadAssignment(x)) {
|
|
435
|
+
const w = valueOf(x.expression);
|
|
436
|
+
if (!ts.isObjectLiteralExpression(w) || depth > 4)
|
|
437
|
+
refuse(x, 'an entry spread from other than an object of them');
|
|
438
|
+
named(w, out, depth + 1);
|
|
439
|
+
}
|
|
440
|
+
else
|
|
441
|
+
refuse(x, 'an entry written other than name: value');
|
|
442
|
+
}
|
|
443
|
+
return out;
|
|
444
|
+
};
|
|
445
|
+
// Only the guards and actions the config names are read: XState runs no other (an object shared by several machines
|
|
446
|
+
// holds others').
|
|
447
|
+
const names = new Set();
|
|
448
|
+
const namesIn = (e, role) => {
|
|
449
|
+
e = strip(e);
|
|
450
|
+
if (role && ts.isStringLiteral(e)) {
|
|
451
|
+
names.add(e.text);
|
|
452
|
+
return;
|
|
453
|
+
}
|
|
454
|
+
if (ts.isArrayLiteralExpression(e)) {
|
|
455
|
+
e.elements.forEach(el => namesIn(el, role));
|
|
456
|
+
return;
|
|
457
|
+
}
|
|
458
|
+
if (ts.isCallExpression(e)) {
|
|
459
|
+
e.arguments.forEach(el => namesIn(el, role));
|
|
460
|
+
return;
|
|
461
|
+
}
|
|
462
|
+
if (!ts.isObjectLiteralExpression(e))
|
|
463
|
+
return;
|
|
464
|
+
for (const p of e.properties)
|
|
465
|
+
if (ts.isPropertyAssignment(p)) {
|
|
466
|
+
const k = ts.isIdentifier(p.name) || ts.isStringLiteral(p.name) ? p.name.text : '';
|
|
467
|
+
namesIn(p.initializer, ['guard', 'cond', 'actions', 'entry', 'exit'].includes(k) || (role === true && k === 'type'));
|
|
468
|
+
}
|
|
469
|
+
};
|
|
470
|
+
namesIn(config);
|
|
471
|
+
const implementations = (o, what) => {
|
|
472
|
+
const all = [...named(o)], used = all.filter(([n]) => names.has(n));
|
|
473
|
+
if (used.length < all.length)
|
|
474
|
+
notes.push(`${all.length - used.length} ${what} of the object the config never names, not read (XState runs only those it names)`);
|
|
475
|
+
return used;
|
|
476
|
+
};
|
|
385
477
|
const guards = [], actions = [];
|
|
386
478
|
const where0 = v === 5 ? setupArg : options;
|
|
387
|
-
for (const [n, g] of
|
|
479
|
+
for (const [n, g] of implementations(objOf(where0, 'guards'), 'guards'))
|
|
388
480
|
guards.push([n, guardOf(g, n)]);
|
|
389
|
-
for (const [n, a] of
|
|
481
|
+
for (const [n, a] of implementations(objOf(where0, 'actions'), 'actions'))
|
|
390
482
|
actions.push([n, actionOf(a, n)]);
|
|
391
483
|
if (v === 4 && setupArg)
|
|
392
484
|
refuse(setupArg, 'setup() with XState v4');
|
package/dist/core/extract.js
CHANGED
|
@@ -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
|
-
//
|
|
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
|
|
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,106 @@
|
|
|
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
|
+
// a high-water mark: a variable every key a step writes some map at is at most, after the step (top = max(top, b),
|
|
23
|
+
// a cell written at b): each map no step wrote past it, and each it was seen bounding
|
|
24
|
+
const past = new Set(), bounds = new Set();
|
|
25
|
+
for (let trial = 0; trial < 60 && clock() < until; trial++) {
|
|
26
|
+
let ps, st;
|
|
27
|
+
try {
|
|
28
|
+
ps = draws.params(rand, bound);
|
|
29
|
+
if (m.pre && !evalC(m.pre, ps, { scalars: {}, maps: {} }, m))
|
|
30
|
+
continue;
|
|
31
|
+
st = run.init(ps);
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
for (let d = 0, tries = 0; d < 20 && tries < 60; tries++) {
|
|
37
|
+
try {
|
|
38
|
+
const input = draws.input(rand, bound, ps);
|
|
39
|
+
if (!allowed(m, run, ps, st, input))
|
|
40
|
+
continue;
|
|
41
|
+
const next = run.step(ps, st, input);
|
|
42
|
+
for (const x of Object.keys(m.state)) {
|
|
43
|
+
const was = st.scalars[x], now = next.scalars[x];
|
|
44
|
+
if (now < was)
|
|
45
|
+
lowered.add(x);
|
|
46
|
+
// an id handed out: the counter goes on, and some map's cell at its old value is written
|
|
47
|
+
else if (now > was && maps.some(([n, init]) => (st.maps[n]?.get(was) ?? init) !== (next.maps[n]?.get(was) ?? init)))
|
|
48
|
+
handed.add(x);
|
|
49
|
+
}
|
|
50
|
+
for (const [n, init] of maps)
|
|
51
|
+
for (const key of new Set([...(st.maps[n]?.keys() ?? []), ...(next.maps[n]?.keys() ?? [])])) {
|
|
52
|
+
if ((st.maps[n]?.get(key) ?? init) === (next.maps[n]?.get(key) ?? init))
|
|
53
|
+
continue;
|
|
54
|
+
for (const x of Object.keys(m.state))
|
|
55
|
+
(key <= next.scalars[x] ? bounds : past).add(`${x}\u0000${n}`);
|
|
56
|
+
}
|
|
57
|
+
st = next;
|
|
58
|
+
d++;
|
|
59
|
+
states.push({ ps, st });
|
|
60
|
+
}
|
|
61
|
+
catch { /* refused: another */ }
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
const counters = [...handed].filter(c => !lowered.has(c));
|
|
65
|
+
const highs = [...bounds].filter(p => !past.has(p) && !lowered.has(p.split('\u0000')[0]) && !counters.includes(p.split('\u0000')[0])).map(p => p.split('\u0000'));
|
|
66
|
+
if (!counters.length && !highs.length)
|
|
67
|
+
return [];
|
|
68
|
+
const key = 'k$fresh', record = (n) => n.slice(0, Math.max(0, n.indexOf('.')));
|
|
69
|
+
const cands = [];
|
|
70
|
+
for (const c of counters)
|
|
71
|
+
for (const [map, init] of maps) {
|
|
72
|
+
const at = get(map, v(key)), initial = { op: '=', a: at, b: { op: 'const', value: init } };
|
|
73
|
+
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}` });
|
|
74
|
+
for (const [g, gi] of maps) {
|
|
75
|
+
if (g !== map && (!record(g) || record(g) !== record(map)))
|
|
76
|
+
continue;
|
|
77
|
+
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}` });
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
for (const [c, map] of highs) {
|
|
81
|
+
const init = m.maps[map];
|
|
82
|
+
cands.push({ law: { name: `keys up to ${c}: ${map} unset past it`, holds: { op: 'or', xs: [{ op: '<=', a: v(key), b: v(c) }, { op: '=', a: get(map, v(key)), b: { op: 'const', value: init } }] }, forall: key }, text: `∀k. ${c} < k → ${map}[k] = ${init}` });
|
|
83
|
+
}
|
|
84
|
+
let alive = cands.filter(f => states.every(({ ps, st }) => { try {
|
|
85
|
+
return watch(m, run, f.law, ps, bound).start(st);
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
return false;
|
|
89
|
+
} }));
|
|
90
|
+
while (alive.length && clock() < until) {
|
|
91
|
+
let out;
|
|
92
|
+
try {
|
|
93
|
+
out = proveLaws(m, [...kinds, ...alive.map(f => f.law)]);
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
return [];
|
|
97
|
+
}
|
|
98
|
+
if (out.proven && out.checked)
|
|
99
|
+
return alive;
|
|
100
|
+
const failed = out.failed?.goal ?? '', drop = alive.findIndex(f => failed.startsWith(`${f.law.name} @`) || failed.startsWith(`${f.law.name}:`));
|
|
101
|
+
if (drop < 0)
|
|
102
|
+
return [];
|
|
103
|
+
alive = alive.filter((_, i) => i !== drop);
|
|
104
|
+
}
|
|
105
|
+
return [];
|
|
106
|
+
}
|