gdp-wired 0.56.1 → 0.57.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/cli.d.ts +15 -0
- package/dist/core/cli.js +310 -13
- package/dist/core/effect.d.ts +2 -2
- package/dist/core/effect.js +630 -210
- package/dist/core/extract-check.js +14 -5
- package/dist/core/extract-read.d.ts +34 -0
- package/dist/core/extract-read.js +78 -4
- package/dist/core/extract-shapes.d.ts +11 -1
- package/dist/core/extract-shapes.js +14 -5
- package/dist/core/extract-standalone.js +1 -1
- package/dist/core/extract-xstate.d.ts +2 -1
- package/dist/core/extract-xstate.js +9 -4
- package/dist/core/extract.d.ts +2 -1
- package/dist/core/extract.js +6 -3
- package/dist/core/native-domain.js +38 -9
- package/package.json +1 -1
|
@@ -20,7 +20,7 @@ const vmOf = () => { const m = proc?.getBuiltinModule?.('node:vm'); if (!m)
|
|
|
20
20
|
import { Int, Term, bool, int, intern, interned, nat, no, oneOf, str, proveSteps } from "./dsl.js";
|
|
21
21
|
import { seeded, walk } from "./machine.js";
|
|
22
22
|
import { allowed } from "./watch.js";
|
|
23
|
-
import { normalize, resolveIn, sameLazyRoot, scriptKind } from "./extract-read.js";
|
|
23
|
+
import { assertNoReservedHarness, normalize, resolveIn, sameLazyRoot, scriptKind } from "./extract-read.js";
|
|
24
24
|
import * as I from "./extract-ir.js";
|
|
25
25
|
import { nativeSnapshot, rememberNative } from "./source-check.js";
|
|
26
26
|
import { nativeCaptureEdits, nativeInputs } from "./native-domain.js";
|
|
@@ -154,13 +154,22 @@ function instrumentTicks(js, file) {
|
|
|
154
154
|
return out;
|
|
155
155
|
}
|
|
156
156
|
export function sandbox(code, file, expose, modules = {}, init, files = {}, extra = [], nativeMethods = []) {
|
|
157
|
+
assertNoReservedHarness(code, file, files);
|
|
157
158
|
const vm = vmOf();
|
|
158
159
|
// A final arrow can end exactly where a factory appends fields. Its capture
|
|
159
160
|
// must close first; instrument preserves the order of equal-position edits.
|
|
160
161
|
const { js, arms } = instrument(code, file, init ? `\n;(globalThis as any).__gdpInit = () => (${init});\n` : '', [...nativeCaptureEdits(code, file, nativeMethods), ...extra]);
|
|
161
162
|
const captured = new Map(), captureErrors = new Map();
|
|
162
163
|
const counts = arms.map(() => 0);
|
|
163
|
-
let now = 0, invocation = 0, observedClock, observing = false;
|
|
164
|
+
let now = 0, invocation = 0, observedClock, observationError, observing = false;
|
|
165
|
+
const recordClock = (t) => {
|
|
166
|
+
if (!observing)
|
|
167
|
+
return;
|
|
168
|
+
if (observedClock !== undefined && observedClock !== t)
|
|
169
|
+
observationError ??= 'conflicting actual clock reads';
|
|
170
|
+
else
|
|
171
|
+
observedClock = t;
|
|
172
|
+
};
|
|
164
173
|
let ticks = 0, deadline = Infinity, limitMs = 0, timedOut = false;
|
|
165
174
|
const startBudget = (ms) => { ticks = 0; limitMs = ms; timedOut = false; deadline = performance.now() + ms; };
|
|
166
175
|
const stopBudget = () => { deadline = Infinity; timedOut = false; };
|
|
@@ -181,8 +190,7 @@ export function sandbox(code, file, expose, modules = {}, init, files = {}, extr
|
|
|
181
190
|
});
|
|
182
191
|
const module = { exports: {} };
|
|
183
192
|
const ctx = vm.createContext({
|
|
184
|
-
__cov: (i) => { counts[i]++; }, __now: () => {
|
|
185
|
-
observedClock = now; return now; }, module, exports: module.exports,
|
|
193
|
+
__cov: (i) => { counts[i]++; }, __now: () => { recordClock(now); return now; }, __gdp_clock: () => now, __gdp_observe_clock: (t) => { recordClock(t); }, module, exports: module.exports,
|
|
186
194
|
__gdp_native_capture: (name, value) => {
|
|
187
195
|
if (captured.has(name) || captureErrors.has(name))
|
|
188
196
|
return;
|
|
@@ -259,6 +267,7 @@ export function sandbox(code, file, expose, modules = {}, init, files = {}, extr
|
|
|
259
267
|
captureErrors.clear();
|
|
260
268
|
invocation++;
|
|
261
269
|
observedClock = undefined;
|
|
270
|
+
observationError = undefined;
|
|
262
271
|
}
|
|
263
272
|
observing = request;
|
|
264
273
|
Object.assign(ctx, { __f: f, __self: self, __args: args });
|
|
@@ -294,7 +303,7 @@ export function sandbox(code, file, expose, modules = {}, init, files = {}, extr
|
|
|
294
303
|
}
|
|
295
304
|
return ctx.__r;
|
|
296
305
|
};
|
|
297
|
-
return { ctx, counts, arms, call, observations: () => validateNativeObservations({ invocation, calls: {}, ...(observedClock === undefined ? {} : { clock: observedClock }) }, new Set()), setNow: n => { now = n; }, get: name => vm.runInContext(`__gdp[${JSON.stringify(name)}]`, ctx),
|
|
306
|
+
return { ctx, counts, arms, call, observations: () => validateNativeObservations({ invocation, calls: {}, ...(observedClock === undefined ? {} : { clock: observedClock }), ...(observationError === undefined ? {} : { error: observationError }) }, new Set()), setNow: n => { now = n; }, get: name => vm.runInContext(`__gdp[${JSON.stringify(name)}]`, ctx),
|
|
298
307
|
bindings: method => { if (captureErrors.has(method))
|
|
299
308
|
throw new Error(captureErrors.get(method)); return captured.get(method); } };
|
|
300
309
|
}
|
|
@@ -167,11 +167,42 @@ export type ListWrite = ({
|
|
|
167
167
|
x: Term;
|
|
168
168
|
when: B;
|
|
169
169
|
})[];
|
|
170
|
+
export type DeclSpan = {
|
|
171
|
+
file: string;
|
|
172
|
+
start: number;
|
|
173
|
+
end: number;
|
|
174
|
+
};
|
|
175
|
+
export declare function declNodeOf(sf: ts.SourceFile, n: ts.Node): ts.Node;
|
|
176
|
+
export declare function declSpanOf(sf: ts.SourceFile, n: ts.Node): DeclSpan;
|
|
177
|
+
export declare function assertNoReservedHarness(code: string, file: string, files?: Record<string, string>): void;
|
|
178
|
+
export type EffectAtom = {
|
|
179
|
+
txDepth: number;
|
|
180
|
+
locks: ts.Node[];
|
|
181
|
+
syncDepth: number;
|
|
182
|
+
yieldEpoch: number;
|
|
183
|
+
syncId: number;
|
|
184
|
+
units: number;
|
|
185
|
+
rawStateOps: number;
|
|
186
|
+
unlockedStateOps: number;
|
|
187
|
+
sawClock: boolean;
|
|
188
|
+
sleptAfterClock: boolean;
|
|
189
|
+
stateAfterSleptClock: boolean;
|
|
190
|
+
locksUsed: ts.Node[];
|
|
191
|
+
multiOpLocks: ts.Node[];
|
|
192
|
+
touchedState: string[];
|
|
193
|
+
closureStateTouched: string[];
|
|
194
|
+
lastClosureEpoch?: string;
|
|
195
|
+
closureMultiStep: boolean;
|
|
196
|
+
scopeOps: number[];
|
|
197
|
+
};
|
|
198
|
+
export declare const initEffectAtom: () => EffectAtom;
|
|
199
|
+
export declare const mergeEffectAtom: (a?: EffectAtom, b?: EffectAtom) => EffectAtom | undefined;
|
|
170
200
|
export type Model = {
|
|
171
201
|
name: string;
|
|
172
202
|
shape: 'reducer' | 'functions' | 'class';
|
|
173
203
|
file: string;
|
|
174
204
|
entry: string;
|
|
205
|
+
declSpans?: DeclSpan[];
|
|
175
206
|
standalone?: true;
|
|
176
207
|
standaloneDomains?: Record<string, number[]>;
|
|
177
208
|
standaloneBindings?: string[];
|
|
@@ -335,6 +366,7 @@ type Path = {
|
|
|
335
366
|
wrote: string[];
|
|
336
367
|
nows: number;
|
|
337
368
|
outs?: string[];
|
|
369
|
+
atom?: EffectAtom;
|
|
338
370
|
};
|
|
339
371
|
type Flow = {
|
|
340
372
|
live?: Path;
|
|
@@ -415,7 +447,9 @@ export type Setup = {
|
|
|
415
447
|
names: Set<string>;
|
|
416
448
|
mods?: Set<string>;
|
|
417
449
|
};
|
|
450
|
+
declSpans?: DeclSpan[];
|
|
418
451
|
effect?: (ex: Exec, e: ts.Expression, p: Path) => [V, Path] | undefined;
|
|
452
|
+
onStateAccess?: (name: string, kind: 'read' | 'write', p: Path, at: ts.Node) => Path;
|
|
419
453
|
};
|
|
420
454
|
export declare class Exec {
|
|
421
455
|
readonly s: Setup;
|
|
@@ -33,6 +33,76 @@ export const sameLazyRoot = (a, b) => {
|
|
|
33
33
|
const x = a.root ?? [a.prefix, 0], y = b.root ?? [b.prefix, 0];
|
|
34
34
|
return x[0] === y[0] && x[1] === y[1];
|
|
35
35
|
};
|
|
36
|
+
// Canonical enclosing declaration node: for `const a = ..., b = ...` the specific VariableDeclaration,
|
|
37
|
+
// otherwise the top-level statement (ClassDeclaration, FunctionDeclaration, ExportAssignment, etc.).
|
|
38
|
+
export function declNodeOf(sf, n) {
|
|
39
|
+
let cur = n, varDecl;
|
|
40
|
+
while (cur.parent && cur.parent !== sf) {
|
|
41
|
+
if (ts.isVariableDeclaration(cur) && cur.parent.parent?.parent === sf)
|
|
42
|
+
varDecl = cur;
|
|
43
|
+
cur = cur.parent;
|
|
44
|
+
}
|
|
45
|
+
return ts.isVariableStatement(cur) ? varDecl ?? cur : cur;
|
|
46
|
+
}
|
|
47
|
+
export function declSpanOf(sf, n) {
|
|
48
|
+
const d = declNodeOf(sf, n);
|
|
49
|
+
return { file: sf.fileName, start: d.getStart(sf), end: d.end };
|
|
50
|
+
}
|
|
51
|
+
const RESERVED_HARNESS_RE = /\b(__gdp_tick|__cov|__now)\b/;
|
|
52
|
+
export function assertNoReservedHarness(code, file, files) {
|
|
53
|
+
const checkOne = (src, at) => {
|
|
54
|
+
const m = RESERVED_HARNESS_RE.exec(src);
|
|
55
|
+
if (!m)
|
|
56
|
+
return;
|
|
57
|
+
const before = src.slice(0, m.index).split('\n');
|
|
58
|
+
const line = before.length, col = before.at(-1).length + 1;
|
|
59
|
+
throw new Refusal(`${at}:${line}:${col}`, `${m[1]}: reserved harness name (the check's sandbox uses __gdp_tick, __cov and __now)`);
|
|
60
|
+
};
|
|
61
|
+
checkOne(code, file);
|
|
62
|
+
if (files)
|
|
63
|
+
for (const [p, src] of Object.entries(files))
|
|
64
|
+
checkOne(src, p);
|
|
65
|
+
}
|
|
66
|
+
export const initEffectAtom = () => ({
|
|
67
|
+
txDepth: 0, locks: [], syncDepth: 0, yieldEpoch: 0, syncId: 0,
|
|
68
|
+
units: 0, rawStateOps: 0, unlockedStateOps: 0,
|
|
69
|
+
sawClock: false, sleptAfterClock: false, stateAfterSleptClock: false,
|
|
70
|
+
locksUsed: [], multiOpLocks: [], touchedState: [], closureStateTouched: [],
|
|
71
|
+
closureMultiStep: false, scopeOps: [],
|
|
72
|
+
});
|
|
73
|
+
export const mergeEffectAtom = (a, b) => {
|
|
74
|
+
if (!a)
|
|
75
|
+
return b;
|
|
76
|
+
if (!b)
|
|
77
|
+
return a;
|
|
78
|
+
const maxScope = Math.max(a.scopeOps.length, b.scopeOps.length);
|
|
79
|
+
const scopeOps = [];
|
|
80
|
+
for (let i = 0; i < maxScope; i++)
|
|
81
|
+
scopeOps.push(Math.max(a.scopeOps[i] ?? 0, b.scopeOps[i] ?? 0));
|
|
82
|
+
const lastClosureEpoch = a.lastClosureEpoch && b.lastClosureEpoch
|
|
83
|
+
? (a.lastClosureEpoch === b.lastClosureEpoch ? a.lastClosureEpoch : 'mixed')
|
|
84
|
+
: (a.lastClosureEpoch ?? b.lastClosureEpoch);
|
|
85
|
+
return {
|
|
86
|
+
txDepth: Math.max(a.txDepth, b.txDepth),
|
|
87
|
+
locks: a.locks.length >= b.locks.length ? a.locks : b.locks,
|
|
88
|
+
syncDepth: Math.max(a.syncDepth, b.syncDepth),
|
|
89
|
+
yieldEpoch: Math.max(a.yieldEpoch, b.yieldEpoch),
|
|
90
|
+
syncId: Math.max(a.syncId, b.syncId),
|
|
91
|
+
units: Math.max(a.units, b.units),
|
|
92
|
+
rawStateOps: Math.max(a.rawStateOps, b.rawStateOps),
|
|
93
|
+
unlockedStateOps: Math.max(a.unlockedStateOps, b.unlockedStateOps),
|
|
94
|
+
sawClock: a.sawClock || b.sawClock,
|
|
95
|
+
sleptAfterClock: a.sleptAfterClock || b.sleptAfterClock,
|
|
96
|
+
stateAfterSleptClock: a.stateAfterSleptClock || b.stateAfterSleptClock,
|
|
97
|
+
locksUsed: [...new Set([...a.locksUsed, ...b.locksUsed])],
|
|
98
|
+
multiOpLocks: [...new Set([...a.multiOpLocks, ...b.multiOpLocks])],
|
|
99
|
+
touchedState: [...new Set([...a.touchedState, ...b.touchedState])],
|
|
100
|
+
closureStateTouched: [...new Set([...a.closureStateTouched, ...b.closureStateTouched])],
|
|
101
|
+
...(lastClosureEpoch !== undefined ? { lastClosureEpoch } : {}),
|
|
102
|
+
closureMultiStep: a.closureMultiStep || b.closureMultiStep,
|
|
103
|
+
scopeOps,
|
|
104
|
+
};
|
|
105
|
+
};
|
|
36
106
|
export const unparen = (x) => (ts.isParenthesizedExpression(x) ? unparen(x.expression) : x);
|
|
37
107
|
// An expression without its parentheses, casts and `!` (what it is, as the front ends read it).
|
|
38
108
|
export const bare = (x) => (ts.isParenthesizedExpression(x) || ts.isAsExpression(x) || ts.isSatisfiesExpression(x) || ts.isNonNullExpression(x) ? bare(x.expression) : x);
|
|
@@ -302,7 +372,8 @@ export class Exec {
|
|
|
302
372
|
heap.set(id, !oa ? ob : !ob ? oa : this.mergeObj(c, oa, ob, a, b, heap, pairs, at));
|
|
303
373
|
}
|
|
304
374
|
const outs = [...new Set([...(a.outs ?? []), ...(b.outs ?? [])])];
|
|
305
|
-
|
|
375
|
+
const atom = mergeEffectAtom(a.atom, b.atom);
|
|
376
|
+
return { pc, locals, heap, wrote: [...new Set([...a.wrote, ...b.wrote])], nows: Math.max(a.nows, b.nows), ...(outs.length ? { outs } : {}), ...(atom ? { atom } : {}) };
|
|
306
377
|
}
|
|
307
378
|
deref(p, v) {
|
|
308
379
|
while (v.t === 'ref') {
|
|
@@ -751,8 +822,10 @@ export class Exec {
|
|
|
751
822
|
const sym = this.resolved(e);
|
|
752
823
|
const decl = sym?.valueDeclaration ?? sym?.declarations?.[0];
|
|
753
824
|
// A factory's own variable (or argument), closed over by the object it returns: a field of that object's state.
|
|
754
|
-
if (decl && this.s.closure?.has(decl))
|
|
755
|
-
|
|
825
|
+
if (decl && this.s.closure?.has(decl)) {
|
|
826
|
+
const q = !this.s.ctor && this.s.onStateAccess ? this.s.onStateAccess(e.text, 'read', p, e) : p;
|
|
827
|
+
return this.field({ t: 'ref', id: 'this' }, e.text, e, q);
|
|
828
|
+
}
|
|
756
829
|
if (decl && ts.isVariableDeclaration(decl) && decl.initializer && this.s.ours(decl.getSourceFile()) && ts.isVariableStatement(decl.parent.parent) && ts.isSourceFile(decl.parent.parent.parent)) {
|
|
757
830
|
if (!(decl.parent.flags & ts.NodeFlags.Const))
|
|
758
831
|
return refuse(e, `${e.text}: a module-level let (state outside the step)`);
|
|
@@ -1272,7 +1345,8 @@ export class Exec {
|
|
|
1272
1345
|
if (cd && this.s.closure?.has(cd)) {
|
|
1273
1346
|
if (ts.isVariableDeclaration(cd) && cd.parent.flags & ts.NodeFlags.Const)
|
|
1274
1347
|
return refuse(target, `${target.text} is a const`);
|
|
1275
|
-
|
|
1348
|
+
const q = !this.s.ctor && this.s.onStateAccess ? this.s.onStateAccess(target.text, 'write', p, target) : p;
|
|
1349
|
+
return this.writeField({ t: 'ref', id: 'this' }, target.text, v, q, target);
|
|
1276
1350
|
}
|
|
1277
1351
|
if (!p.locals.has(target.text))
|
|
1278
1352
|
return refuse(target, `${target.text}: an assignment to a name outside the step`);
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import ts from 'typescript';
|
|
2
|
-
import { Exec, type Heap, type Model, type Path, type Setup, type Shape, type Sort, type V } from './extract-read.js';
|
|
2
|
+
import { type DeclSpan, type EffectAtom, Exec, type Heap, type Model, type Path, type Setup, type Shape, type Sort, type V } from './extract-read.js';
|
|
3
3
|
export type ReadOptions = {
|
|
4
4
|
entry: string;
|
|
5
5
|
strict?: boolean;
|
|
@@ -42,6 +42,16 @@ export type FactoryOf = {
|
|
|
42
42
|
calls: string;
|
|
43
43
|
extra?: [number, string][];
|
|
44
44
|
start?: [string, Heap extends Map<string, infer O> ? O : never][];
|
|
45
|
+
declSpans?: DeclSpan[];
|
|
46
|
+
initAtom?: () => EffectAtom;
|
|
47
|
+
onFields?: (fields: {
|
|
48
|
+
name: string;
|
|
49
|
+
param?: boolean;
|
|
50
|
+
isConst?: boolean;
|
|
51
|
+
node: ts.Node;
|
|
52
|
+
}[], written: Set<string>, first: boolean) => void;
|
|
53
|
+
beginMethod?: (name: string) => void;
|
|
54
|
+
endMethod?: (name: string, atoms: (EffectAtom | undefined)[]) => void;
|
|
45
55
|
};
|
|
46
56
|
export declare function readFactory(code: string, file: string, opts: ReadOptions, fx?: (s: Setup) => FactoryOf): Model;
|
|
47
57
|
export declare const isSlice: (code: string, entry: string) => boolean;
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
import ts from 'typescript';
|
|
7
7
|
import { standaloneClosure } from "./extract-standalone.js";
|
|
8
8
|
import * as I from "./extract-ir.js";
|
|
9
|
-
import { Exec, Retype, lazyKey, memberName, mergeOps, normalize, program, refuse, shapeOf, unparen } from "./extract-read.js";
|
|
9
|
+
import { Exec, Retype, declSpanOf, lazyKey, memberName, mergeOps, normalize, program, refuse, shapeOf, unparen } from "./extract-read.js";
|
|
10
10
|
const at0 = (sf) => sf.statements[0] ?? sf;
|
|
11
11
|
export function setupOf(code, file, typed = {}, files = {}) {
|
|
12
12
|
const root = file.slice(0, file.length - (file.split('/').pop().length)), extra = Object.fromEntries(Object.entries(files).map(([p, c]) => [normalize(`${root}${p}`), c]));
|
|
@@ -446,7 +446,8 @@ const sortOf = (sh, lits) => (sh.k === 'str' && lits.length ? { k: 'choice', val
|
|
|
446
446
|
// Experimental opt-in: a pure, standalone scalar function. No third-party call or state is synthesized.
|
|
447
447
|
export function readStandalone(code, file, opts) {
|
|
448
448
|
const s = setupOf(code, file, opts.typed, opts.files), fn = findFunction(s.sf, opts.entry);
|
|
449
|
-
|
|
449
|
+
s.declSpans = [declSpanOf(s.sf, fn)];
|
|
450
|
+
if (opts.entry === 'undefined' || opts.entry === '__cov' || opts.entry === '__now' || opts.entry === '__gdp_tick')
|
|
450
451
|
refuse(fn, 'standalone: reserved entry name');
|
|
451
452
|
const bindings = standaloneClosure(s, fn);
|
|
452
453
|
s.spans = [[fn.getStart(), fn.end]];
|
|
@@ -607,6 +608,7 @@ export function readFunctions(code, file, opts) {
|
|
|
607
608
|
}
|
|
608
609
|
function readFunctionsOnce(code, file, opts) {
|
|
609
610
|
const s = setupOf(code, file, opts.typed, opts.files), names = opts.functions ?? [opts.entry], fns = names.map(n => findFunction(s.sf, n));
|
|
611
|
+
s.declSpans = fns.map(f => declSpanOf(s.sf, f));
|
|
610
612
|
const first = fns[0], sp = first.parameters[0] ?? refuse(first, 'a step function takes the state first');
|
|
611
613
|
// The initial state: given, a default parameter, useReducer's second argument, or `initialState`.
|
|
612
614
|
let raw = opts.init, initSource, initExpr;
|
|
@@ -735,7 +737,7 @@ function finish(s, m) {
|
|
|
735
737
|
listWrites[n] = ops.map(o => (o.op === 'pop' ? o : { ...o, x: termOf(o.x) }));
|
|
736
738
|
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'),
|
|
737
739
|
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,
|
|
738
|
-
...(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 } : {}),
|
|
740
|
+
...(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 } : {}), ...(s.declSpans?.length ? { declSpans: s.declSpans } : {}),
|
|
739
741
|
...(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\./, '')])) } : {}), ...(s.fnFields?.mods?.size ? { imports: [...s.fnFields.mods] } : {}) };
|
|
740
742
|
}
|
|
741
743
|
// --- classes --------------------------------------------------------------------------------------------------------
|
|
@@ -834,6 +836,7 @@ function mixinOf(s, call, at) {
|
|
|
834
836
|
function attempt(code, file, opts, written) {
|
|
835
837
|
const s = setupOf(code, file, {}, opts.files), cls = findClass(s.sf, opts.entry), first = written.size === 0;
|
|
836
838
|
s.cls = cls;
|
|
839
|
+
s.declSpans = [declSpanOf(s.sf, cls)];
|
|
837
840
|
// `implements` is a type's only (nothing at run time); `extends` brings another class's fields and methods: each
|
|
838
841
|
// member resolved statically, from the entry class up (this.m() the entry's own or the nearest inherited; super.m()
|
|
839
842
|
// the nearest above the class it is written in).
|
|
@@ -1318,6 +1321,7 @@ export function readFactory(code, file, opts, fx) {
|
|
|
1318
1321
|
}
|
|
1319
1322
|
function factoryAttempt(code, file, opts, written, fxOf) {
|
|
1320
1323
|
const s = setupOf(code, file, {}, opts.files), fx = fxOf?.(s), fn = fx?.fn ?? findFunction(s.sf, opts.entry), first = written.size === 0;
|
|
1324
|
+
s.declSpans = fx?.declSpans ?? [declSpanOf(s.sf, fn)];
|
|
1321
1325
|
if (!fx && (fn.modifiers?.some(m => m.kind === ts.SyntaxKind.AsyncKeyword) || fn.asteriskToken))
|
|
1322
1326
|
refuse(fn, 'an async or generator factory');
|
|
1323
1327
|
const obj = fx?.obj ?? returnedObject(fn) ?? refuse(fn, `${opts.entry} returns no object of functions`);
|
|
@@ -1365,6 +1369,7 @@ function factoryAttempt(code, file, opts, written, fxOf) {
|
|
|
1365
1369
|
}
|
|
1366
1370
|
}
|
|
1367
1371
|
s.closure = closure;
|
|
1372
|
+
fx?.onFields?.(fields, written, first);
|
|
1368
1373
|
s.notes.add(`${opts.entry} makes an object of functions: its state is what they close over (${fields.map(f => f.name).join(', ') || 'nothing'}), its arguments the params`);
|
|
1369
1374
|
const ex0 = new Exec(s);
|
|
1370
1375
|
const constant = (f) => !first && !written.has(f.name) && f.shape.k !== 'map' && f.shape.k !== 'list';
|
|
@@ -1524,8 +1529,9 @@ function factoryAttempt(code, file, opts, written, fxOf) {
|
|
|
1524
1529
|
if (st.getSourceFile() === s.sf)
|
|
1525
1530
|
(s.spans ??= []).push([st.getStart(), st.end]);
|
|
1526
1531
|
for (const f of fns) {
|
|
1532
|
+
fx?.beginMethod?.(f.name);
|
|
1527
1533
|
const ex = new Exec(s), sel = I.is(evL, f.name);
|
|
1528
|
-
let p = { pc: [sel], locals: new Map(), heap: new Map(stateHeap), wrote: [], nows: 0 };
|
|
1534
|
+
let p = { pc: [sel], locals: new Map(), heap: new Map(stateHeap), wrote: [], nows: 0, ...(fx?.initAtom ? { atom: fx.initAtom() } : {}) };
|
|
1529
1535
|
const args = [];
|
|
1530
1536
|
for (const [ordinal, param] of f.decl.parameters.entries()) {
|
|
1531
1537
|
if (param.dotDotDotToken || !ts.isIdentifier(param.name))
|
|
@@ -1543,7 +1549,9 @@ function factoryAttempt(code, file, opts, written, fxOf) {
|
|
|
1543
1549
|
// A method that returns an effect: the effect run (a generator's body is run as it is read).
|
|
1544
1550
|
if (fx && !f.decl.asteriskToken)
|
|
1545
1551
|
ends = ends.map(([q, v]) => { const [v2, q2] = fx.run(ex, v, f.decl, q); return [q2, v2]; });
|
|
1546
|
-
const
|
|
1552
|
+
const liveEnds = ends.filter(([q]) => ex.feasible(q));
|
|
1553
|
+
fx?.endMethod?.(f.name, liveEnds.map(([q]) => q.atom));
|
|
1554
|
+
const outs = liveEnds.map(([rp, rv]) => {
|
|
1547
1555
|
const self = rp.heap.get('this'), sv = { leaves: new Map(), maps: new Map() };
|
|
1548
1556
|
for (const [fl, lay] of stateLayout)
|
|
1549
1557
|
materialize(ex, self.fields.get(fl), lay, rp, f.decl, sv);
|
|
@@ -1643,6 +1651,7 @@ export function readSlice(code, file, opts) {
|
|
|
1643
1651
|
}
|
|
1644
1652
|
function readSliceOnce(code, file, opts) {
|
|
1645
1653
|
const s = setupOf(code, file, opts.typed, opts.files), cfg = sliceOf(s.sf, opts.entry) ?? refuse(at0(s.sf), `no createSlice ${opts.entry} in the file`);
|
|
1654
|
+
s.declSpans = [declSpanOf(s.sf, cfg)];
|
|
1646
1655
|
const prop = (k) => cfg.properties.find((p) => (ts.isPropertyAssignment(p) || ts.isShorthandPropertyAssignment(p)) && p.name.getText() === k);
|
|
1647
1656
|
// A shorthand entry's value: the variable it names (its initializer, for a const).
|
|
1648
1657
|
const valueOf = (p) => {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// The opt-in scalar reader's closed binding boundary. No module code is run here.
|
|
2
2
|
import ts from 'typescript';
|
|
3
3
|
import { refuse, unparen } from "./extract-read.js";
|
|
4
|
-
const reserved = (name) => ['undefined', '__cov', '$join', 'this'].includes(name) || name.startsWith('__gdp');
|
|
4
|
+
const reserved = (name) => ['undefined', '__cov', '__now', '$join', 'this'].includes(name) || name.startsWith('__gdp');
|
|
5
5
|
export function standaloneClosure(s, entry) {
|
|
6
6
|
const bindings = new Map(), active = new Set(), done = new Set(), reached = new Set();
|
|
7
7
|
const symbol = (id) => s.checker.getSymbolAtLocation(id) ?? refuse(id, 'standalone: unresolved binding');
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type Source } from './extract-read.js';
|
|
1
|
+
import { type DeclSpan, type Source } from './extract-read.js';
|
|
2
2
|
import type { Law } from './machine.js';
|
|
3
3
|
import type { Name } from './extract.js';
|
|
4
4
|
import type { Rule } from './dsl.js';
|
|
@@ -41,5 +41,6 @@ export type XStateExtraction = {
|
|
|
41
41
|
ms: number;
|
|
42
42
|
mismatch?: string;
|
|
43
43
|
};
|
|
44
|
+
declSpans?: DeclSpan[];
|
|
44
45
|
};
|
|
45
46
|
export declare function extractXState(at: Source, opts?: XStateOptions): XStateExtraction;
|
|
@@ -27,7 +27,7 @@ import ts from 'typescript';
|
|
|
27
27
|
import * as dsl from "./dsl.js";
|
|
28
28
|
import { compileFunction, seeded } from "./machine.js";
|
|
29
29
|
import * as I from "./extract-ir.js";
|
|
30
|
-
import { Exec, Refusal, beside, memberName, normalize, placed, program, refuse, scriptKind, shapeOf, sourceOf, where } from "./extract-read.js";
|
|
30
|
+
import { Exec, Refusal, assertNoReservedHarness, beside, declSpanOf, memberName, normalize, placed, program, refuse, scriptKind, shapeOf, sourceOf, where } from "./extract-read.js";
|
|
31
31
|
import { kindOf, pb, pterm, sortsOf } from "./extract-print.js";
|
|
32
32
|
import { sandbox } from "./extract-check.js";
|
|
33
33
|
import { conforms, eventsOf, fromXState } from "./xstate.js";
|
|
@@ -73,11 +73,12 @@ function machineOf(code, file) {
|
|
|
73
73
|
function readXState(code, opts) {
|
|
74
74
|
const file = opts.file, t0 = performance.now(), notes = [];
|
|
75
75
|
try {
|
|
76
|
+
assertNoReservedHarness(code, file, opts.files);
|
|
76
77
|
const at = placed(file), root = at.slice(0, at.length - file.split('/').pop().length);
|
|
77
78
|
const extra = Object.fromEntries(Object.entries(opts.files ?? {}).map(([p, c]) => [normalize(`${root}${p}`), c]));
|
|
78
79
|
const { sf, checker } = program(code, at, extra);
|
|
79
80
|
// The entry: a machine (setup(...).createMachine(...), createMachine(...)) or a function that returns one.
|
|
80
|
-
let init, factory;
|
|
81
|
+
let init, factory, declNode;
|
|
81
82
|
for (const st of sf.statements) {
|
|
82
83
|
if (ts.isVariableStatement(st))
|
|
83
84
|
for (const d of st.declarationList.declarations)
|
|
@@ -87,10 +88,14 @@ function readXState(code, opts) {
|
|
|
87
88
|
factory = x;
|
|
88
89
|
else
|
|
89
90
|
init = d.initializer;
|
|
91
|
+
declNode = d;
|
|
90
92
|
}
|
|
91
|
-
if (ts.isFunctionDeclaration(st) && st.name?.text === opts.entry)
|
|
93
|
+
if (ts.isFunctionDeclaration(st) && st.name?.text === opts.entry) {
|
|
92
94
|
factory = st;
|
|
95
|
+
declNode = st;
|
|
96
|
+
}
|
|
93
97
|
}
|
|
98
|
+
const declSpans = declNode ? [declSpanOf(sf, declNode)] : [];
|
|
94
99
|
if (factory) {
|
|
95
100
|
const body = factory.body ?? refuse(factory, `${opts.entry} has no body`);
|
|
96
101
|
if (!ts.isBlock(body))
|
|
@@ -879,7 +884,7 @@ function readXState(code, opts) {
|
|
|
879
884
|
const names0 = [...Object.keys(chart.rule.machine.state).filter(k => !k.includes('.last') && !keptKeys.some(c => k === c || k.startsWith(`${c}$`) || k.startsWith(`${c}.`))).map(k => ({ code: k === 'state' ? 'value' : `value.${k}`, rule: k, role: 'state' })),
|
|
880
885
|
...fields.filter(f => !f.dropped && f.var).map(f => ({ code: f.k, rule: f.k, role: 'state' })), ...params.map(x => ({ code: x.name, rule: x.name, role: 'param' })),
|
|
881
886
|
...inputs.map(x => (outside.has(x.name) ? { code: outside.get(x.name).path, rule: x.name, role: 'answer' } : { code: `event.${field(x.name)}`, rule: x.name, role: 'input' })), { code: 'event', rule: 'event', role: 'method' }];
|
|
882
|
-
return { ok: true, source, chart, rule: chart.rule, invariants: chart.chartLaws(), names: names0, evidence, notes, refusals: [] };
|
|
887
|
+
return { ok: true, source, chart, rule: chart.rule, invariants: chart.chartLaws(), names: names0, evidence, notes, refusals: [], ...(declSpans.length ? { declSpans } : {}) };
|
|
883
888
|
}
|
|
884
889
|
catch (e) {
|
|
885
890
|
if (e instanceof Refusal)
|
package/dist/core/extract.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { Rule } from './dsl.js';
|
|
2
2
|
import type { Law } from './machine.js';
|
|
3
|
-
import { type Model, Refusal, type Source, type Term } from './extract-read.js';
|
|
3
|
+
import { type DeclSpan, type Model, Refusal, type Source, type Term } from './extract-read.js';
|
|
4
4
|
import { type ReadOptions } from './extract-shapes.js';
|
|
5
5
|
import { type Sorts } from './extract-print.js';
|
|
6
6
|
import { type CheckOptions, type Evidence } from './extract-check.js';
|
|
@@ -53,6 +53,7 @@ export type Extraction = {
|
|
|
53
53
|
base: number;
|
|
54
54
|
}[];
|
|
55
55
|
consts?: Record<string, number | string | boolean>;
|
|
56
|
+
declSpans?: DeclSpan[];
|
|
56
57
|
};
|
|
57
58
|
export type Name = {
|
|
58
59
|
code: string;
|
package/dist/core/extract.js
CHANGED
|
@@ -42,7 +42,7 @@ import { attachSource } from "./source-check.js";
|
|
|
42
42
|
import { compileFunction, walk } from "./machine.js";
|
|
43
43
|
import * as I from "./extract-ir.js";
|
|
44
44
|
import { PASS } from "./extract-ir.js";
|
|
45
|
-
import { Refusal, placed, sourceOf, syntaxError, tooDeep } from "./extract-read.js";
|
|
45
|
+
import { Refusal, assertNoReservedHarness, placed, sourceOf, syntaxError, tooDeep } from "./extract-read.js";
|
|
46
46
|
import { isFactory, isSlice, readClass, readFactory, readFunctions, readSlice, readStandalone } from "./extract-shapes.js";
|
|
47
47
|
import { kindOf, mapEmpty, mapKind, natOK, nonneg, pb, pidx, pk, pnum, pterm, sortsOf } from "./extract-print.js";
|
|
48
48
|
import { check } from "./extract-check.js";
|
|
@@ -123,9 +123,12 @@ export function extract(at, opts = {}) {
|
|
|
123
123
|
if (!o.entry || Array.isArray(opts.entry) || opts.functions || opts.shape || opts.orm)
|
|
124
124
|
throw new Refusal(file, 'standalone mode needs exactly one named function and no other shape');
|
|
125
125
|
model = readStandalone(code, placed(file), o);
|
|
126
|
+
assertNoReservedHarness(code, file, opts.files);
|
|
126
127
|
}
|
|
127
|
-
else
|
|
128
|
+
else {
|
|
129
|
+
assertNoReservedHarness(code, file, opts.files);
|
|
128
130
|
model = o.entry ? readModel(code, file, o, opts.shape) : inferred(code, file, o, opts.shape);
|
|
131
|
+
}
|
|
129
132
|
model.file = file;
|
|
130
133
|
}
|
|
131
134
|
catch (e) {
|
|
@@ -200,7 +203,7 @@ export function fromModel(model, file, domains, notes, run) {
|
|
|
200
203
|
if (evidence.mismatch)
|
|
201
204
|
return { ok: false, source, model, sorts, evidence, refusals: [{ where: file, what: `the rule and the code differ: ${evidence.mismatch}` }], notes };
|
|
202
205
|
attachSource(rule, evidence, invariants);
|
|
203
|
-
return { ok: true, rule, ...(invariants.length ? { invariants } : {}), source, model, sorts, evidence, refusals: [], notes };
|
|
206
|
+
return { ok: true, rule, ...(invariants.length ? { invariants } : {}), source, model, sorts, evidence, refusals: [], notes, ...(model.declSpans ? { declSpans: model.declSpans } : {}) };
|
|
204
207
|
}
|
|
205
208
|
// Internal builder for the C safety first-fault monitor machine: evaluates the
|
|
206
209
|
// monitored model and its invariants without marking the monitor rule as an
|
|
@@ -6,13 +6,39 @@ import { normalize, program, scriptKind } from "./extract-read.js";
|
|
|
6
6
|
const LIMIT = 65536;
|
|
7
7
|
class TooLarge extends Error {
|
|
8
8
|
}
|
|
9
|
-
|
|
9
|
+
const unwrap = (n) => {
|
|
10
|
+
while (ts.isParenthesizedExpression(n) || ts.isAsExpression(n) || ts.isSatisfiesExpression(n))
|
|
11
|
+
n = n.expression;
|
|
12
|
+
return n;
|
|
13
|
+
};
|
|
14
|
+
const climb = (n) => {
|
|
15
|
+
let p = n.parent;
|
|
16
|
+
while (p && (ts.isParenthesizedExpression(p) || ts.isAsExpression(p) || ts.isSatisfiesExpression(p)))
|
|
17
|
+
p = p.parent;
|
|
18
|
+
return p;
|
|
19
|
+
};
|
|
20
|
+
// An Effect.fn / Effect.fnUntraced call wrapping a generator method body (with or without a span name).
|
|
21
|
+
function effectFnCall(p, n) {
|
|
22
|
+
if (!n.asteriskToken || !p || !ts.isCallExpression(p) || p.arguments.length !== 1 || unwrap(p.arguments[0]) !== n)
|
|
23
|
+
return undefined;
|
|
24
|
+
const callee = unwrap(p.expression);
|
|
25
|
+
const head = ts.isCallExpression(callee) ? unwrap(callee.expression) : callee;
|
|
26
|
+
if (!ts.isPropertyAccessExpression(head))
|
|
27
|
+
return undefined;
|
|
28
|
+
return (ts.isCallExpression(callee) ? head.name.text === 'fn' : head.name.text === 'fn' || head.name.text === 'fnUntraced') ? p : undefined;
|
|
29
|
+
}
|
|
30
|
+
function named(n, allowEffectFn = false) {
|
|
10
31
|
if (ts.isFunctionDeclaration(n) || ts.isMethodDeclaration(n))
|
|
11
32
|
return n.name && (ts.isIdentifier(n.name) || ts.isStringLiteral(n.name)) ? n.name.text : undefined;
|
|
12
33
|
if (ts.isArrowFunction(n) || ts.isFunctionExpression(n)) {
|
|
13
|
-
const p = n
|
|
14
|
-
if ((ts.isVariableDeclaration(p) || ts.isPropertyAssignment(p)) && (ts.isIdentifier(p.name) || ts.isStringLiteral(p.name)))
|
|
34
|
+
const p = climb(n);
|
|
35
|
+
if (p && (ts.isVariableDeclaration(p) || ts.isPropertyAssignment(p)) && (ts.isIdentifier(p.name) || ts.isStringLiteral(p.name)))
|
|
15
36
|
return p.name.text;
|
|
37
|
+
if (allowEffectFn && ts.isFunctionExpression(n)) {
|
|
38
|
+
const call = effectFnCall(p, n), holder = call && climb(call);
|
|
39
|
+
if (holder && (ts.isVariableDeclaration(holder) || ts.isPropertyAssignment(holder)) && (ts.isIdentifier(holder.name) || ts.isStringLiteral(holder.name)))
|
|
40
|
+
return holder.name.text;
|
|
41
|
+
}
|
|
16
42
|
}
|
|
17
43
|
return undefined;
|
|
18
44
|
}
|
|
@@ -25,12 +51,15 @@ export function nativeCaptureEdits(code, file, methods) {
|
|
|
25
51
|
return [];
|
|
26
52
|
const sf = ts.createSourceFile(file, code, ts.ScriptTarget.ES2022, true, scriptKind(file)), edits = [];
|
|
27
53
|
const visit = (n) => {
|
|
28
|
-
if (callable(n) && n.body
|
|
29
|
-
const
|
|
30
|
-
if (
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
54
|
+
if (callable(n) && n.body) {
|
|
55
|
+
const method = named(n, true);
|
|
56
|
+
if (method && methods.includes(method)) {
|
|
57
|
+
const names = n.parameters.flatMap(p => bindingNames(p.name)), capture = `__gdp_native_capture(${JSON.stringify(method)}, {${names.join(',')}})`;
|
|
58
|
+
if (ts.isBlock(n.body))
|
|
59
|
+
edits.push([n.body.getStart(sf) + 1, `${capture};`]);
|
|
60
|
+
else
|
|
61
|
+
edits.push([n.body.getStart(sf), `(${capture}, (`], [n.body.end, '))']);
|
|
62
|
+
}
|
|
34
63
|
}
|
|
35
64
|
ts.forEachChild(n, visit);
|
|
36
65
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "gdp-wired",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.57.0",
|
|
4
4
|
"description": "An automatic prover for stateful rules (budgets, caps, windows, workflows, policies): laws proven with no proof to write, checked again in Lean, counterexamples found on the GPU, the rule shipped as code",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"verification",
|