gdp-wired 0.31.1 → 0.32.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/README.md +82 -6
- package/dist/core/c/reader.d.ts +86 -0
- package/dist/core/c/reader.js +860 -0
- package/dist/core/cli.d.ts +66 -0
- package/dist/core/cli.js +582 -0
- package/dist/core/dsl.d.ts +4 -2
- package/dist/core/dsl.js +22 -12
- package/dist/core/effect.d.ts +6 -4
- package/dist/core/effect.js +48 -10
- package/dist/core/ex/harness.exs +177 -0
- package/dist/core/ex/json.exs +46 -0
- package/dist/core/ex/reader.exs +462 -0
- package/dist/core/exists.d.ts +3 -0
- package/dist/core/exists.js +3 -1
- package/dist/core/extract-c.d.ts +35 -0
- package/dist/core/extract-c.js +424 -0
- package/dist/core/extract-check.js +27 -6
- package/dist/core/extract-ex.d.ts +16 -0
- package/dist/core/extract-ex.js +33 -0
- package/dist/core/extract-go-check.d.ts +28 -0
- package/dist/core/extract-go-check.js +639 -0
- package/dist/core/extract-go.d.ts +231 -0
- package/dist/core/extract-go.js +1166 -0
- package/dist/core/extract-jvm.d.ts +23 -0
- package/dist/core/extract-jvm.js +220 -0
- package/dist/core/extract-print.js +17 -7
- package/dist/core/extract-py.d.ts +15 -0
- package/dist/core/extract-py.js +31 -0
- package/dist/core/extract-rb.d.ts +17 -0
- package/dist/core/extract-rb.js +31 -0
- package/dist/core/extract-read.d.ts +20 -0
- package/dist/core/extract-read.js +46 -6
- package/dist/core/extract-rs.d.ts +12 -0
- package/dist/core/extract-rs.js +306 -0
- package/dist/core/extract-shapes.d.ts +2 -0
- package/dist/core/extract-shapes.js +6 -5
- package/dist/core/extract-step.d.ts +806 -0
- package/dist/core/extract-step.js +4141 -0
- package/dist/core/extract-swift.d.ts +27 -0
- package/dist/core/extract-swift.js +484 -0
- package/dist/core/extract-xstate.d.ts +10 -3
- package/dist/core/extract-xstate.js +50 -4
- package/dist/core/extract.d.ts +22 -3
- package/dist/core/extract.js +107 -18
- package/dist/core/go/go.mod +3 -0
- package/dist/core/go/reader.go +901 -0
- package/dist/core/infer.js +1770 -52
- package/dist/core/jvm/Harness.java +361 -0
- package/dist/core/jvm/JavaReader.java +825 -0
- package/dist/core/jvm/Jvm.java +332 -0
- package/dist/core/jvm/KtReader.java +960 -0
- package/dist/core/jvm/Rt.java +10 -0
- package/dist/core/laws.d.ts +66 -0
- package/dist/core/laws.js +522 -0
- package/dist/core/py/harness.py +328 -0
- package/dist/core/py/reader.py +447 -0
- package/dist/core/rb/harness.rb +233 -0
- package/dist/core/rb/reader.rb +375 -0
- package/dist/core/rs/Cargo.lock +108 -0
- package/dist/core/rs/Cargo.toml +14 -0
- package/dist/core/rs/src/main.rs +681 -0
- package/dist/core/swift/Harness.swift +124 -0
- package/dist/core/swift/Main.swift +34 -0
- package/dist/core/swift/Package.swift +13 -0
- package/dist/core/swift/Sources/gdp-swiftreader/main.swift +1341 -0
- package/dist/kernel/epr.d.ts +35 -0
- package/dist/kernel/epr.js +1676 -0
- package/dist/kernel/prove.d.ts +44 -0
- package/dist/kernel/prove.js +657 -50
- package/dist/lean-kernel/emit.d.ts +1 -0
- package/dist/lean-kernel/emit.js +21 -4
- package/package.json +53 -2
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { type Extraction } from './extract.js';
|
|
2
|
+
import { type FileURL } from './extract-read.js';
|
|
3
|
+
import { type PArg, type SModule, type StepOptions, type StepRead } from './extract-step.js';
|
|
4
|
+
export { proveRule, proveSteps } from './dsl.js';
|
|
5
|
+
export type SwiftOptions = StepOptions & {
|
|
6
|
+
swift?: string;
|
|
7
|
+
ctor?: number | string;
|
|
8
|
+
target?: string;
|
|
9
|
+
};
|
|
10
|
+
export declare function swiftReader(o?: SwiftOptions): string;
|
|
11
|
+
type Pkg = {
|
|
12
|
+
root: string;
|
|
13
|
+
file?: string;
|
|
14
|
+
target: string;
|
|
15
|
+
dir: string;
|
|
16
|
+
files: string[];
|
|
17
|
+
single: boolean;
|
|
18
|
+
};
|
|
19
|
+
export declare function swiftPackage(at: string, o?: SwiftOptions): Pkg;
|
|
20
|
+
export declare function readSwift(at: string, names: string[], o?: SwiftOptions): {
|
|
21
|
+
mod: SModule;
|
|
22
|
+
pkg: Pkg;
|
|
23
|
+
};
|
|
24
|
+
export declare function extractSwift(where: string | FileURL, opts?: SwiftOptions): Extraction & {
|
|
25
|
+
read?: StepRead;
|
|
26
|
+
};
|
|
27
|
+
export type { PArg };
|
|
@@ -0,0 +1,484 @@
|
|
|
1
|
+
import { Refusal, pathOf } from "./extract-read.js";
|
|
2
|
+
import { entryNames, extractStep, node, stubbed } from "./extract-step.js";
|
|
3
|
+
export { proveRule, proveSteps } from "./dsl.js";
|
|
4
|
+
const env = () => globalThis.process?.env ?? {};
|
|
5
|
+
const errText = (e) => { const ls = `${e.stdout ?? ''}\n${e.stderr ?? ''}`.split('\n'); return (ls.filter(l => /\berror:/.test(l)).length ? ls.filter(l => /\berror:/.test(l)) : ls.filter(l => /error|fatal/i.test(l))).slice(0, 4).join(' | ').slice(0, 900) || String(e.message).slice(0, 300); };
|
|
6
|
+
const hash = (s) => node('node:crypto').createHash('sha256').update(s).digest('hex').slice(0, 16);
|
|
7
|
+
const swiftOf = (o) => o.swift ?? env().GDP_SWIFT ?? 'swift';
|
|
8
|
+
// --- the reader: compiled once per version of its source and of the toolchain ----------------------------------------
|
|
9
|
+
// Against the toolchain's own SwiftSyntax (lib/swift/host, which ships it for macros) where there is one: seconds.
|
|
10
|
+
// Else the reader's package, swift-syntax pinned, built by SwiftPM: minutes, once.
|
|
11
|
+
export function swiftReader(o = {}) {
|
|
12
|
+
const fs = node('node:fs'), cp = node('node:child_process'), os = node('node:os'), path = node('node:path');
|
|
13
|
+
const dir = new URL('./swift/', import.meta.url).pathname, main = `${dir}Sources/gdp-swiftreader/main.swift`;
|
|
14
|
+
let version;
|
|
15
|
+
try {
|
|
16
|
+
version = cp.execFileSync(swiftOf(o), ['--version'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
throw new Refusal('swift', 'a Swift toolchain (5.9 or later: swift on the PATH, or swift: / $GDP_SWIFT) is needed to extract Swift');
|
|
20
|
+
}
|
|
21
|
+
const out = `${os.tmpdir()}/gdp-swiftreader-${hash(fs.readFileSync(main, 'utf8') + fs.readFileSync(`${dir}Package.swift`, 'utf8') + version)}`, bin = `${out}/gdp-swiftreader`;
|
|
22
|
+
if (fs.existsSync(bin))
|
|
23
|
+
return bin;
|
|
24
|
+
fs.mkdirSync(out, { recursive: true });
|
|
25
|
+
const tmpBin = `${bin}.${Date.now()}${Math.random().toString(36).slice(2, 8)}`;
|
|
26
|
+
// (the toolchain's swiftc and its host modules)
|
|
27
|
+
let swiftc = '';
|
|
28
|
+
try {
|
|
29
|
+
swiftc = cp.execFileSync('sh', ['-c', `command -v xcrun >/dev/null && xcrun --find swiftc || command -v swiftc`], { encoding: 'utf8' }).trim();
|
|
30
|
+
}
|
|
31
|
+
catch { /* none */ }
|
|
32
|
+
const host = swiftc && path.resolve(fs.realpathSync(swiftc), '../../lib/swift/host');
|
|
33
|
+
let err = '';
|
|
34
|
+
if (host && fs.existsSync(`${host}/SwiftSyntax.swiftmodule`)) {
|
|
35
|
+
try {
|
|
36
|
+
cp.execFileSync(swiftc, ['-O', '-I', host, '-L', host, '-lSwiftSyntax', '-lSwiftParser', '-lSwiftOperators', '-Xlinker', '-rpath', '-Xlinker', host, main, '-o', tmpBin], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 1 << 26 });
|
|
37
|
+
fs.renameSync(tmpBin, bin);
|
|
38
|
+
return bin;
|
|
39
|
+
}
|
|
40
|
+
catch (e) {
|
|
41
|
+
err = errText(e);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
try {
|
|
45
|
+
cp.execFileSync(swiftOf(o), ['build', '-c', 'release', '--package-path', dir, '--scratch-path', `${out}/build`], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 1 << 28 });
|
|
46
|
+
const built = cp.execFileSync(swiftOf(o), ['build', '-c', 'release', '--package-path', dir, '--scratch-path', `${out}/build`, '--show-bin-path'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
|
|
47
|
+
fs.writeFileSync(tmpBin, '');
|
|
48
|
+
cp.execFileSync('cp', [`${built}/gdp-swiftreader`, tmpBin], {});
|
|
49
|
+
fs.renameSync(tmpBin, bin);
|
|
50
|
+
return bin;
|
|
51
|
+
}
|
|
52
|
+
catch (e) {
|
|
53
|
+
throw new Refusal('swift', `the Swift reader didn't build (${errText(e) || err}): a Swift 5.9 or later toolchain is needed to extract Swift`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
function swiftFiles(d) {
|
|
57
|
+
const fs = node('node:fs'), path = node('node:path');
|
|
58
|
+
if (!fs.existsSync(d))
|
|
59
|
+
return [];
|
|
60
|
+
return fs.readdirSync(d, { withFileTypes: true }).flatMap(e => (e.isDirectory() ? (e.name.startsWith('.') ? [] : swiftFiles(path.join(d, e.name))) : e.name.endsWith('.swift') ? [path.join(d, e.name)] : [])).sort();
|
|
61
|
+
}
|
|
62
|
+
export function swiftPackage(at, o = {}) {
|
|
63
|
+
const fs = node('node:fs'), path = node('node:path'), cp = node('node:child_process');
|
|
64
|
+
const abs = path.resolve(at);
|
|
65
|
+
if (!fs.existsSync(abs))
|
|
66
|
+
throw new Refusal(at, 'no such file or directory');
|
|
67
|
+
const isDir = fs.statSync(abs).isDirectory();
|
|
68
|
+
let root = isDir ? abs : undefined;
|
|
69
|
+
for (let d = isDir ? abs : path.dirname(abs); !root; d = path.dirname(d)) {
|
|
70
|
+
if (fs.existsSync(path.join(d, 'Package.swift')))
|
|
71
|
+
root = d;
|
|
72
|
+
if (path.dirname(d) === d)
|
|
73
|
+
break;
|
|
74
|
+
}
|
|
75
|
+
// (one file outside any package: its own package, made for the check)
|
|
76
|
+
if (!root || !fs.existsSync(path.join(root, 'Package.swift'))) {
|
|
77
|
+
if (isDir)
|
|
78
|
+
throw new Refusal(at, 'no Package.swift: give a .swift file or a package\'s directory');
|
|
79
|
+
return { root: path.dirname(abs), file: abs, target: 'GdpCode', dir: path.dirname(abs), files: [abs], single: true };
|
|
80
|
+
}
|
|
81
|
+
let targets = [];
|
|
82
|
+
try {
|
|
83
|
+
targets = JSON.parse(cp.execFileSync(swiftOf(o), ['package', 'dump-package', '--package-path', root], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 1 << 26 })).targets;
|
|
84
|
+
}
|
|
85
|
+
catch (e) {
|
|
86
|
+
throw new Refusal(root, `the package's manifest didn't load (${errText(e)})`);
|
|
87
|
+
}
|
|
88
|
+
const dirOf = (t) => path.join(root, t.path ?? (t.type === 'test' ? `Tests/${t.name}` : `Sources/${t.name}`));
|
|
89
|
+
const lib = targets.filter(t => t.type === 'regular');
|
|
90
|
+
const t = !isDir ? lib.find(x => abs.startsWith(`${dirOf(x)}/`)) : o.target ? lib.find(x => x.name === o.target) : lib.length === 1 ? lib[0] : undefined;
|
|
91
|
+
if (!t)
|
|
92
|
+
throw new Refusal(at, isDir ? `the package has ${lib.length} library targets (${lib.map(x => x.name).join(', ')}): give the file, or name one (target)` : 'not a file of one of the package\'s library targets');
|
|
93
|
+
return { root, ...(isDir ? {} : { file: abs }), target: t.name, dir: dirOf(t), files: swiftFiles(dirOf(t)), single: false };
|
|
94
|
+
}
|
|
95
|
+
export function readSwift(at, names, o = {}) {
|
|
96
|
+
const cp = node('node:child_process');
|
|
97
|
+
const pkg = swiftPackage(at, o);
|
|
98
|
+
let out;
|
|
99
|
+
try {
|
|
100
|
+
out = cp.execFileSync(swiftReader(o), [pkg.root, pkg.file ?? '-', names.length ? names.join(',') : '-', o.ctor === undefined ? '-' : String(o.ctor), ...pkg.files], { encoding: 'utf8', maxBuffer: 1 << 29, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
101
|
+
}
|
|
102
|
+
catch (e) {
|
|
103
|
+
throw new Refusal(at, `the Swift reader didn't run (${errText(e)})`);
|
|
104
|
+
}
|
|
105
|
+
const mod = JSON.parse(out);
|
|
106
|
+
mod.module = pkg.target;
|
|
107
|
+
return { mod, pkg };
|
|
108
|
+
}
|
|
109
|
+
export function extractSwift(where, opts = {}) {
|
|
110
|
+
const at = pathOf(where);
|
|
111
|
+
let r;
|
|
112
|
+
try {
|
|
113
|
+
if (opts.stores && Object.keys(opts.stores).length)
|
|
114
|
+
throw new Refusal(at, 'stores: not in the Swift front end yet (an injected protocol\'s are inferred)');
|
|
115
|
+
r = readSwift(at, entryNames(opts), opts);
|
|
116
|
+
}
|
|
117
|
+
catch (e) {
|
|
118
|
+
if (e instanceof Refusal)
|
|
119
|
+
return { ok: false, refusals: [{ where: e.where, what: e.what }], notes: [] };
|
|
120
|
+
throw e;
|
|
121
|
+
}
|
|
122
|
+
const x = extractStep(r.mod, read => harnessFor(r.pkg, r.mod, read, opts), opts);
|
|
123
|
+
// (what the check assumed of the code's runtime, in the notes)
|
|
124
|
+
const cls = x.read?.cls ? r.mod.recs[x.read.cls].swift : undefined;
|
|
125
|
+
if (cls?.kind === 'actor')
|
|
126
|
+
x.notes.push(`${x.read.model.name}: an actor, its methods each one step (Swift runs an actor's method without interleaving up to a suspension point, and these have none): checked as a class whose calls don't overlap`);
|
|
127
|
+
if (x.evidence)
|
|
128
|
+
x.notes.push('Swift: checked in a debug build (overflow traps, assert and precondition on), each request run first in a forked child (a crash is the step\'s failure); branch arms not counted (no instrumentation yet)');
|
|
129
|
+
return x;
|
|
130
|
+
}
|
|
131
|
+
// --- the harness: Swift beside the code, generated per reading ----------------------------------------------------------
|
|
132
|
+
// (its fixed parts, Swift files shipped beside the reader)
|
|
133
|
+
const resource = (f) => node('node:fs').readFileSync(new URL(`./swift/${f}`, import.meta.url).pathname, 'utf8');
|
|
134
|
+
// The Swift name of an integer type, and of an answer's type.
|
|
135
|
+
const intName = (t) => { const x = t; return x.sw ?? (x.bits === 64 || !x.bits ? (x.signed === false ? 'UInt' : 'Int') : `${x.signed === false ? 'UInt' : 'Int'}${x.bits}`); };
|
|
136
|
+
function answerType(a, read) {
|
|
137
|
+
const ty = read.ints[a.inputs.name], base = a.sort.replace(/\s*\|\s*None$/, '').trim();
|
|
138
|
+
const inner = base === 'int' || /^[ui](8|16|32|64|size)$/.test(base) ? (ty ? intName({ k: 'int', bits: ty.bits, signed: ty.signed }) : 'Int') : base === 'bool' ? 'Bool' : base === 'str' ? 'String' : base === 'float' ? 'Double' : 'Int';
|
|
139
|
+
return a.inputs.none ? `${inner}?` : inner;
|
|
140
|
+
}
|
|
141
|
+
// The expression making a value of type t from the JSON value `j` (a __GdpJ?), throwing __GdpBad where it can't.
|
|
142
|
+
function conv(t, j, mod, depth = 0) {
|
|
143
|
+
if (t.k === 'int')
|
|
144
|
+
return `try __gdpInt(${j}, ${intName(t)}.self)`;
|
|
145
|
+
if (t.k === 'bool')
|
|
146
|
+
return `try __gdpBool(${j})`;
|
|
147
|
+
if (t.k === 'str')
|
|
148
|
+
return `try __gdpStr(${j})`;
|
|
149
|
+
if (t.k === 'choice')
|
|
150
|
+
return `try { () throws -> ${t.enum} in switch try __gdpStr(${j}) { ${t.values.map(v => `case ${JSON.stringify(v)}: return .${v}`).join('; ')}; default: throw __GdpBad(why: "no case") } }()`;
|
|
151
|
+
if (t.k === 'opt')
|
|
152
|
+
return `(__gdpIsNone(${j}) ? nil : ${conv(t.of, j, mod, depth + 1)})`;
|
|
153
|
+
if (t.k === 'rec') {
|
|
154
|
+
const r = mod.recs[t.name], ps = r?.swift?.props?.filter(p => !p.init);
|
|
155
|
+
if (!r || r.swift?.kind !== 'struct' || depth > 4 || r.methods.__init__ === undefined || !ps)
|
|
156
|
+
return `try { throw __GdpBad(why: "a value of ${t.name}") }()`;
|
|
157
|
+
return `${t.name}(${ps.map(p => `${p.name}: ${conv(r.fields.find(f => f.name === p.name).t, `${j}?["f"]?[${JSON.stringify(p.name)}]`, mod, depth + 1)}`).join(', ')})`;
|
|
158
|
+
}
|
|
159
|
+
return `try { throw __GdpBad(why: "a value of ${t.k}") }()`;
|
|
160
|
+
}
|
|
161
|
+
// A value as a leaf of the state holds it (numbers as strings, choices by their case's name).
|
|
162
|
+
const caseName = (t, x) => `{ () -> String in switch ${x} { ${t.values.map(v => `case .${v}: return ${JSON.stringify(v)}`).join('; ')} } }()`;
|
|
163
|
+
function enc(t, x) {
|
|
164
|
+
return t.k === 'int' ? `__GdpJ.s(String(${x}))` : t.k === 'bool' ? `__GdpJ.b(${x})` : t.k === 'str' ? `__GdpJ.s(${x})` : t.k === 'choice' ? `__GdpJ.s(${caseName(t, x)})` : '__GdpJ.null';
|
|
165
|
+
}
|
|
166
|
+
// A method's result as the protocol tags it.
|
|
167
|
+
function out(t, x) {
|
|
168
|
+
return t.k === 'int' ? `__GdpJ.o(["n": .s(String(${x}))])` : t.k === 'bool' ? `__GdpJ.b(${x})` : t.k === 'str' ? `__GdpJ.o(["s": .s(${x})])` : t.k === 'choice' ? `__GdpJ.o(["s": ${enc(t, x)}])`
|
|
169
|
+
: t.k === 'opt' ? `(${x}.map { (__v) -> __GdpJ in ${out(t.of, '__v')} } ?? __GdpJ.null)` : t.k === 'none' ? '__GdpJ.null' : `__GdpJ.o(["o": .s("value")])`;
|
|
170
|
+
}
|
|
171
|
+
// The accessor of a field of a record type (in the type's own file, so its private members are in reach).
|
|
172
|
+
function accessor(g, mod, rec, f) {
|
|
173
|
+
const r = mod.recs[rec], p = r.swift?.props?.find(x => x.name === f);
|
|
174
|
+
if (!r.swift?.file || !p || /^no declared type|unknown/.test(p.t))
|
|
175
|
+
throw new Refusal(r.p, `${r.short}.${f}: a property of no type the check's harness can name`);
|
|
176
|
+
const s = g.access.get(rec) ?? g.access.set(rec, new Set()).get(rec);
|
|
177
|
+
if (!s.has(f)) {
|
|
178
|
+
s.add(f);
|
|
179
|
+
(g.edits.get(r.swift.file) ?? g.edits.set(r.swift.file, []).get(r.swift.file)).push(`extension ${r.swift.qual} { var __gdp_${f}: ${p.t} { get { self.${f} } set { self.${f} = newValue } } }`);
|
|
180
|
+
}
|
|
181
|
+
return `__gdp_${f}`;
|
|
182
|
+
}
|
|
183
|
+
function harnessCode(g, mod, read, cls) {
|
|
184
|
+
const sw = cls.swift, E = sw.qual, isClass = sw.kind !== 'struct', mut = isClass ? '' : 'mutating ';
|
|
185
|
+
if (read.inject?.length)
|
|
186
|
+
throw new Refusal(cls.p, 'a field injected after the init: the Swift harness gives dependencies only through the init');
|
|
187
|
+
// (each leaf's place: the object's field, through its records' accessors)
|
|
188
|
+
const place = (path) => { let cur = cls.name, out = 'o'; for (const seg of path) {
|
|
189
|
+
const fd = mod.recs[cur].fields.find(f => f.name === seg);
|
|
190
|
+
out += `.${accessor(g, mod, cur, seg)}`;
|
|
191
|
+
if (fd?.t.k === 'rec')
|
|
192
|
+
cur = fd.t.name;
|
|
193
|
+
} return out; };
|
|
194
|
+
const typeAt = (path) => { let cur = cls.name, t; for (const seg of path) {
|
|
195
|
+
t = mod.recs[cur]?.fields.find(f => f.name === seg)?.t;
|
|
196
|
+
if (t?.k === 'rec')
|
|
197
|
+
cur = t.name;
|
|
198
|
+
} return t; };
|
|
199
|
+
const get = [], set = [];
|
|
200
|
+
const byPath = new Map();
|
|
201
|
+
for (const l of read.leaves)
|
|
202
|
+
if (l.kind !== 'frame' && !l.store) {
|
|
203
|
+
const k = l.path.join('.');
|
|
204
|
+
byPath.set(k, [...(byPath.get(k) ?? []), l]);
|
|
205
|
+
}
|
|
206
|
+
for (const [, ls] of byPath) {
|
|
207
|
+
const val = ls.find(l => l.kind !== 'none'), none = ls.find(l => l.kind === 'none'), path = ls[0].path, pl = place(path), t0 = typeAt(path);
|
|
208
|
+
if (!t0)
|
|
209
|
+
throw new Refusal(cls.p, `${path.join('.')}: a leaf of no type the harness reads`);
|
|
210
|
+
if (val?.kind === 'map') {
|
|
211
|
+
if (t0.k !== 'map')
|
|
212
|
+
throw new Refusal(cls.p, `${path.join('.')}: a map of no declared type`);
|
|
213
|
+
const kt = t0.key, vt = t0.val, vr = vt.k === 'rec' ? vt.name : undefined;
|
|
214
|
+
const tyName = (t) => (t.k === 'int' ? intName(t) : t.k === 'bool' ? 'Bool' : t.k === 'str' ? 'String' : t.k === 'choice' ? t.enum : t.k === 'rec' ? mod.recs[t.name].swift?.qual ?? t.name : 'Never');
|
|
215
|
+
const vfields = vr ? (val.fields ?? []).map(f => ({ name: f.name, t: mod.recs[vr].fields.find(y => y.name === f.name).t })) : [];
|
|
216
|
+
const cell = (x) => (vr ? `__GdpJ.o([${vfields.map(f => `${JSON.stringify(f.name)}: ${enc(f.t, `${x}.${accessor(g, mod, vr, f.name)}`)}`).join(', ')}])` : `__GdpJ.o(["value": ${enc(vt, x)}])`);
|
|
217
|
+
const keyText = kt.k === 'choice' ? caseName(kt, '$0.key') : 'String(describing: $0.key)';
|
|
218
|
+
get.push(`s[${JSON.stringify(val.name)}] = .o(Dictionary(uniqueKeysWithValues: ${pl}.map { (${keyText}, ${cell('$0.value')}) }))`);
|
|
219
|
+
// (a record value made by its memberwise init: the fields the rule reads from the cell, the others their zero)
|
|
220
|
+
const vrec = vr ? mod.recs[vr] : undefined;
|
|
221
|
+
if (vrec && (vrec.swift?.kind !== 'struct' || !vrec.swift.props))
|
|
222
|
+
throw new Refusal(cls.p, `${path.join('.')}: a map of ${vrec.short}, which the harness can't make (a struct by its memberwise init)`);
|
|
223
|
+
const mk = vrec ? `${tyName(vt)}(${vrec.swift.props.filter(p => !p.init).map(p => { const f = vfields.find(x => x.name === p.name), ft = vrec.fields.find(x => x.name === p.name).t; return `${p.name}: ${f ? conv(ft, `__c[${JSON.stringify(p.name)}]`, mod) : '__gdpZero()'}`; }).join(', ')})` : conv(vt, '__c["value"]', mod);
|
|
224
|
+
set.push(`do { var __m: [${tyName(kt)}: ${tyName(vt)}] = [:]; if case .o(let __cs)? = st[${JSON.stringify(val.name)}] { for (__k, __c) in __cs { __m[${conv(kt, '__GdpJ.s(__k)', mod)}] = ${mk} } }; ${pl} = __m }`);
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
if (!val)
|
|
228
|
+
continue;
|
|
229
|
+
const t = t0.k === 'opt' ? t0.of : t0;
|
|
230
|
+
if (none) {
|
|
231
|
+
get.push(`if let __x = ${pl} { s[${JSON.stringify(val.name)}] = ${enc(t, '__x')}; s[${JSON.stringify(none.name)}] = .b(false) } else { s[${JSON.stringify(val.name)}] = ${t.k === 'int' ? '.s("0")' : t.k === 'bool' ? '.b(false)' : t.k === 'choice' ? `.s(${JSON.stringify(t.values[0])})` : '.s("")'}; s[${JSON.stringify(none.name)}] = .b(true) }`);
|
|
232
|
+
set.push(`${pl} = __gdpIsTrue(st[${JSON.stringify(none.name)}]) ? nil : ${conv(t, `st[${JSON.stringify(val.name)}]`, mod)}`);
|
|
233
|
+
}
|
|
234
|
+
else {
|
|
235
|
+
get.push(`s[${JSON.stringify(val.name)}] = ${enc(t, pl)}`);
|
|
236
|
+
set.push(`${pl} = ${conv(t, `st[${JSON.stringify(val.name)}]`, mod)}`);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
// The stores (an injected dependency's keys, by template): each object's, its cells by the template's hole.
|
|
240
|
+
const storeLeaves = read.leaves.filter(l => l.store);
|
|
241
|
+
for (const l of storeLeaves) {
|
|
242
|
+
get.push(`do { var __cs: [String: __GdpJ] = [:]; for (__k, __v) in (__gdpS.cur[${JSON.stringify(l.store)}]?.data ?? [:]) { if let __h = __gdpTpl(${JSON.stringify(l.tpl ?? '{}')}, __k) { __cs[__h] = .o(["value": __gdpLeaf(__v)]) } }; s[${JSON.stringify(l.name)}] = .o(__cs) }`);
|
|
243
|
+
set.push(`if let __st = __gdpS.cur[${JSON.stringify(l.store)}] { for __k in __st.data.keys where __gdpTpl(${JSON.stringify(l.tpl ?? '{}')}, __k) != nil { __st.data[__k] = nil }; if case .o(let __cs)? = st[${JSON.stringify(l.name)}] { for (__h, __c) in __cs { __st.data[__gdpFill(${JSON.stringify(l.tpl ?? '{}')}, __h)] = __c["value"] } } }`);
|
|
244
|
+
}
|
|
245
|
+
const tpls = {};
|
|
246
|
+
for (const l of storeLeaves)
|
|
247
|
+
(tpls[l.store] ??= []).push(l.tpl ?? '{}');
|
|
248
|
+
// The frames (fields the rule leaves out): each as it was, after a call.
|
|
249
|
+
const frames = read.leaves.filter(l => l.kind === 'frame' && !l.cls).map(l => l.path).filter(p => { try {
|
|
250
|
+
place(p);
|
|
251
|
+
return true;
|
|
252
|
+
}
|
|
253
|
+
catch {
|
|
254
|
+
return false;
|
|
255
|
+
} });
|
|
256
|
+
// The fakes: an injected protocol's conforming class (get, set and delete over what it keeps; answered methods from
|
|
257
|
+
// the request; those left out doing nothing; any other one a crash, which the check reports).
|
|
258
|
+
const fakes = [], fakeOf = new Map();
|
|
259
|
+
const init = mod.funcs[cls.methods.__init__ ?? ''], ctorParams = init?.params.filter(p => !p.self) ?? [];
|
|
260
|
+
for (const [name, a] of read.ctor) {
|
|
261
|
+
if (a.k !== 'store')
|
|
262
|
+
continue;
|
|
263
|
+
const pa = ctorParams.find(p => p.name === name), pt = pa?.t.k === 'opt' ? pa.t.of : pa?.t, pr = pt?.k === 'rec' ? mod.recs[pt.name] : undefined;
|
|
264
|
+
if (!pr?.swift?.reqs)
|
|
265
|
+
throw new Refusal(cls.p, `${cls.short}(${name}): an injected dependency of a protocol outside the files read (the check can't make one)`);
|
|
266
|
+
if (pr.swift.assoc)
|
|
267
|
+
throw new Refusal(cls.p, `${cls.short}(${name}): a protocol with associated types (the check can't make one)`);
|
|
268
|
+
// (the executor's names where the reading states none: get, set and delete)
|
|
269
|
+
const d0 = read.stores[name] ?? {}, d = { ...d0, get: d0.get ?? ['get', 'async_get_cache', 'get_cache'], set: d0.set ?? ['set', 'async_set_cache', 'set_cache'], delete: d0.delete ?? ['delete', 'delete_cache', 'async_delete_cache'] }, cname = `__GdpFake_${name}`;
|
|
270
|
+
fakeOf.set(name, cname);
|
|
271
|
+
const body = (q) => {
|
|
272
|
+
const ps = q.params ?? [], key = ps[0] ? `"\\(${ps[0].name === '_' ? '__a0' : ps[0].name})"` : '""';
|
|
273
|
+
const ans = read.answers.find(x => x.patch.store === name && x.patch.path?.at(-1) === q.name);
|
|
274
|
+
if (ans)
|
|
275
|
+
return `return __gdpAnswer(${JSON.stringify(ans.key)})`;
|
|
276
|
+
if (d.get.includes(q.name))
|
|
277
|
+
return `return __gdpStoreGet(__store, ${key})`;
|
|
278
|
+
if (d.set.includes(q.name) && ps[1])
|
|
279
|
+
return `__store.data[${key}] = __gdpEnc(${ps[1].name === '_' ? '__a1' : ps[1].name})${q.ret === 'Void' || q.ret === '()' ? '' : '; return __gdpZero()'}`;
|
|
280
|
+
if (d.delete.includes(q.name))
|
|
281
|
+
return `__store.data[${key}] = nil${q.ret === 'Void' || q.ret === '()' ? '' : '; return __gdpZero()'}`;
|
|
282
|
+
if (d.skip?.includes(q.name))
|
|
283
|
+
return q.ret === 'Void' || q.ret === '()' ? '' : 'return __gdpZero()';
|
|
284
|
+
return `fatalError(${JSON.stringify(`${name}.${q.name}: a method of the injected dependency the rule doesn't read`)})`;
|
|
285
|
+
};
|
|
286
|
+
const members = pr.swift.reqs.map(q => {
|
|
287
|
+
if (q.kind === 'var')
|
|
288
|
+
return `var ${q.name}: ${q.ret} { get { ${body({ ...q, params: [] })} }${q.set ? ' set { }' : ''} }`;
|
|
289
|
+
// (the requirement's own declaration, its unnamed parameters named, `mutating` dropped: a class conforms)
|
|
290
|
+
let i = 0;
|
|
291
|
+
const decl = (q.decl ?? '').replace(/\bmutating\s+/, '').replace(/(\(|,\s*)_\s*:/g, (_m, pre) => `${pre}_ __a${i++}:`);
|
|
292
|
+
return `${decl} { ${body(q)} }`;
|
|
293
|
+
});
|
|
294
|
+
fakes.push(`final class ${cname}: ${pr.swift.qual}, @unchecked Sendable { let __store: __GdpStore; init(_ s: __GdpStore) { __store = s }\n ${members.join('\n ')}\n}`);
|
|
295
|
+
}
|
|
296
|
+
// The object made (the init's arguments, a store for each injected dependency).
|
|
297
|
+
const ctor = sw.ctor ?? { labels: [], throws: false, types: [] };
|
|
298
|
+
const made = ctorParams.map((pa, i) => {
|
|
299
|
+
const a = read.ctor.find(([n]) => n === pa.name)?.[1], lab = ctor.labels[i] ?? '_', arg = (x) => (lab === '_' ? x : `${lab}: ${x}`);
|
|
300
|
+
if (a?.k === 'store')
|
|
301
|
+
return arg(`${fakeOf.get(pa.name)}({ let __s = __GdpStore(); __gdpS.cur[${JSON.stringify(pa.name)}] = __s; return __s }())`);
|
|
302
|
+
return arg(conv(pa.t, `a?[${i}]?[1]`, mod));
|
|
303
|
+
});
|
|
304
|
+
if (sw.refused)
|
|
305
|
+
throw new Refusal(cls.p, sw.refused);
|
|
306
|
+
// The requests: each method by its labels, its result as the protocol tags it.
|
|
307
|
+
const calls = Object.keys(read.args).map(m => {
|
|
308
|
+
const fid = cls.methods[m], fn = fid ? mod.funcs[fid] : undefined, sig = sw.sigs?.[m];
|
|
309
|
+
if (!fn || !sig)
|
|
310
|
+
throw new Refusal(cls.p, `${m}: a request the harness can't call`);
|
|
311
|
+
if (sig.async)
|
|
312
|
+
throw new Refusal(fn.p, `${m}: an async method (the check's harness calls synchronously; an actor's methods are read as its class's)`);
|
|
313
|
+
const ps = fn.params.filter(p => !p.self);
|
|
314
|
+
const lets = ps.map((p, i) => `let __a${i} = ${conv(p.t, `a?[${i}]?[1]`, mod)}`);
|
|
315
|
+
const callArgs = ps.map((_, i) => (sig.labels[i] === '_' ? `__a${i}` : `${sig.labels[i]}: __a${i}`)).join(', ');
|
|
316
|
+
const ret = fn.ret.k === 'none' || sig.ret === 'Void' ? 'none' : 'some';
|
|
317
|
+
return `case ${JSON.stringify(m)}:\n ${lets.join('; ')}${lets.length ? '\n ' : ''}do { ${ret === 'none' ? `try self.${sig.name}(${callArgs}); return .null` : `let __r = try self.${sig.name}(${callArgs}); return ${out(fn.ret, '__r')}`} } catch { throw __GdpErr(why: "\\(error)") }`;
|
|
318
|
+
});
|
|
319
|
+
const entry = `
|
|
320
|
+
// --- gdp-wired's check harness (generated in the check's copy; the code itself is never changed) ---
|
|
321
|
+
extension ${E} {
|
|
322
|
+
static func __gdpNew(_ a: __GdpJ?) throws -> ${E} {
|
|
323
|
+
do { return try ${E}(${made.join(', ')}) } catch let b as __GdpBad { throw b } catch { throw __GdpErr(why: "\\(error)") }
|
|
324
|
+
}
|
|
325
|
+
${mut}func __gdpCall(_ m: String, _ a: __GdpJ?) throws -> __GdpJ {
|
|
326
|
+
switch m {
|
|
327
|
+
${calls.join('\n ')}
|
|
328
|
+
default: throw __GdpBad(why: "no method \\(m)")
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
${fakes.join('\n')}
|
|
333
|
+
func __gdpGet(_ o: ${E}) -> [String: __GdpJ] { var s: [String: __GdpJ] = [:]; ${get.join('\n ')}
|
|
334
|
+
return s }
|
|
335
|
+
func __gdpSet(_ o: inout ${E}, _ st: [String: __GdpJ]) throws { ${set.join('\n ')} }
|
|
336
|
+
func __gdpFrames(_ o: ${E}) -> [String: String] { [${frames.map(p => `${JSON.stringify(p.join('.'))}: String(describing: ${place(p)})`).join(', ') || ':'}] }
|
|
337
|
+
let __gdpTpls: [String: [String]] = [${Object.entries(tpls).map(([k, v]) => `${JSON.stringify(k)}: ${JSON.stringify(v)}`).join(', ') || ':'}]
|
|
338
|
+
final class __GdpState: @unchecked Sendable { var objs: [${E}] = []; var stores: [[String: __GdpStore]] = []; var cur: [String: __GdpStore] = [:]; var answers: [String: __GdpJ] = [:]; var discard = false }
|
|
339
|
+
let __gdpS = __GdpState()
|
|
340
|
+
typealias __GdpEntry = ${E}
|
|
341
|
+
${resource('Harness.swift')}`;
|
|
342
|
+
const main = resource('Main.swift').replace('__GDP_MODULE__', mod.module);
|
|
343
|
+
return { entry, main };
|
|
344
|
+
}
|
|
345
|
+
// The package copied (stable per package, so `swift build` rebuilds only what changed), the harness generated beside the
|
|
346
|
+
// type, the answered calls rewritten to the request's answers, an actor read as a class (its methods don't interleave),
|
|
347
|
+
// its `let` properties `var` (the check sets them; the code can't), an executable target that drives it, built in debug.
|
|
348
|
+
function harnessFor(pkg, mod, read, opts) {
|
|
349
|
+
const fs = node('node:fs'), cp = node('node:child_process'), os = node('node:os'), path = node('node:path');
|
|
350
|
+
read.arms.length = 0;
|
|
351
|
+
const cls = read.cls ? mod.recs[read.cls] : undefined;
|
|
352
|
+
if (!cls?.swift)
|
|
353
|
+
return { cmd: 'false', args: [], hello: {}, error: 'the Swift harness reads a type\'s methods (not free functions yet)' };
|
|
354
|
+
const work = `${os.tmpdir()}/gdp-swiftcheck-${hash(pkg.root + (pkg.single ? pkg.file : ''))}`, lock = `${work}.lock`;
|
|
355
|
+
const rel = (f) => (pkg.single ? `Sources/GdpCode/${path.basename(f)}` : f);
|
|
356
|
+
// (one check at a time per package: its copy is shared)
|
|
357
|
+
for (let i = 0;; i++) {
|
|
358
|
+
try {
|
|
359
|
+
fs.mkdirSync(lock);
|
|
360
|
+
break;
|
|
361
|
+
}
|
|
362
|
+
catch {
|
|
363
|
+
if (i > 1200) {
|
|
364
|
+
try {
|
|
365
|
+
fs.rmdirSync(lock);
|
|
366
|
+
}
|
|
367
|
+
catch { /* gone */ }
|
|
368
|
+
}
|
|
369
|
+
else
|
|
370
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 500);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
try {
|
|
374
|
+
const g = { edits: new Map(), access: new Map() };
|
|
375
|
+
let code;
|
|
376
|
+
try {
|
|
377
|
+
code = harnessCode(g, mod, read, cls);
|
|
378
|
+
}
|
|
379
|
+
catch (e) {
|
|
380
|
+
if (e instanceof Refusal)
|
|
381
|
+
return { cmd: 'false', args: [], hello: {}, error: e.what };
|
|
382
|
+
throw e;
|
|
383
|
+
}
|
|
384
|
+
// The copy: every file of the package written where it differs (so its mtime moves only then).
|
|
385
|
+
const want = new Map(), links = new Map();
|
|
386
|
+
if (pkg.single) {
|
|
387
|
+
want.set('Package.swift', `// swift-tools-version:5.9\nimport PackageDescription\nlet package = Package(name: "GdpCode", targets: [.target(name: "GdpCode", path: "Sources/GdpCode")])\n`);
|
|
388
|
+
want.set(rel(pkg.file), fs.readFileSync(pkg.file, 'utf8'));
|
|
389
|
+
}
|
|
390
|
+
else {
|
|
391
|
+
// (a link to a directory linked again in the copy, to where it points)
|
|
392
|
+
const walk = (d) => fs.readdirSync(d, { withFileTypes: true }).flatMap(e => { const p = path.join(d, e.name); if (['.build', '.git', '.swiftpm', 'GdpHarness'].includes(e.name))
|
|
393
|
+
return []; if (e.isDirectory())
|
|
394
|
+
return walk(p); if (fs.statSync(p).isDirectory()) {
|
|
395
|
+
links.set(path.relative(pkg.root, p), fs.realpathSync(p));
|
|
396
|
+
return [];
|
|
397
|
+
} return [p]; });
|
|
398
|
+
for (const f of walk(pkg.root))
|
|
399
|
+
want.set(path.relative(pkg.root, f), fs.readFileSync(f, 'binary'));
|
|
400
|
+
}
|
|
401
|
+
// (the check's own changes: let as var where the harness sets a property, the answered calls, the actor, the harness)
|
|
402
|
+
const lets = new Map();
|
|
403
|
+
for (const rn of [cls.name, ...g.access.keys()])
|
|
404
|
+
for (const p of mod.recs[rn].swift?.props ?? [])
|
|
405
|
+
if (p.let) {
|
|
406
|
+
const m = /^(.*):(\d+):(\d+)$/.exec(p.kw);
|
|
407
|
+
if (m)
|
|
408
|
+
(lets.get(m[1]) ?? lets.set(m[1], new Set()).get(m[1])).add(`${m[2]}:${m[3]}`);
|
|
409
|
+
}
|
|
410
|
+
const text = (f) => {
|
|
411
|
+
const t = want.get(rel(f)) ?? want.get(f);
|
|
412
|
+
if (t === undefined || !lets.has(f))
|
|
413
|
+
return t;
|
|
414
|
+
return t.split('\n').map((l, i) => { let s = l; for (const lc of lets.get(f)) {
|
|
415
|
+
const [ln, col] = lc.split(':').map(Number);
|
|
416
|
+
if (ln === i + 1 && s.slice(col - 1, col + 2) === 'let')
|
|
417
|
+
s = `${s.slice(0, col - 1)}var${s.slice(col + 2)}`;
|
|
418
|
+
} return s; }).join('\n');
|
|
419
|
+
};
|
|
420
|
+
const changed = new Map();
|
|
421
|
+
for (const f of new Set([...lets.keys()]))
|
|
422
|
+
changed.set(f, text(f));
|
|
423
|
+
let stubs;
|
|
424
|
+
try {
|
|
425
|
+
stubs = stubbed({ ...read, answers: read.answers.filter(a => !a.patch.store) }, f => changed.get(f) ?? text(f), a => `(__gdpAnswer(${JSON.stringify(a.key)}) as ${answerType(a, read)})`);
|
|
426
|
+
}
|
|
427
|
+
catch (e) {
|
|
428
|
+
if (e instanceof Refusal)
|
|
429
|
+
return { cmd: 'false', args: [], hello: {}, error: e.what };
|
|
430
|
+
throw e;
|
|
431
|
+
}
|
|
432
|
+
for (const [f, t] of stubs)
|
|
433
|
+
changed.set(f, t);
|
|
434
|
+
const ef = cls.swift.file;
|
|
435
|
+
let et = changed.get(ef) ?? text(ef);
|
|
436
|
+
if (cls.swift.kind === 'actor')
|
|
437
|
+
et = et.replace(new RegExp(`\\bactor(\\s+${cls.short}\\b)`), 'final class$1').replace(/\bnonisolated(\(unsafe\))?\s+/g, '');
|
|
438
|
+
changed.set(ef, `${et}\n${code.entry}`);
|
|
439
|
+
for (const [f, exts] of g.edits)
|
|
440
|
+
changed.set(f, `${changed.get(f) ?? text(f)}\n${exts.join('\n')}\n`);
|
|
441
|
+
for (const [f, t] of changed)
|
|
442
|
+
want.set(rel(f), t);
|
|
443
|
+
for (const m of [...want.keys()].filter(k => /^Package(@swift-[\d.]+)?\.swift$/.test(k)))
|
|
444
|
+
want.set(m, `${want.get(m)}\npackage.targets.append(.executableTarget(name: "GdpHarness", dependencies: [.target(name: ${JSON.stringify(pkg.target)})], path: "GdpHarness"))\n`);
|
|
445
|
+
want.set('GdpHarness/main.swift', code.main);
|
|
446
|
+
fs.mkdirSync(work, { recursive: true });
|
|
447
|
+
for (const [f, t] of want) {
|
|
448
|
+
const to = path.join(work, f);
|
|
449
|
+
let same = false;
|
|
450
|
+
try {
|
|
451
|
+
same = fs.readFileSync(to, 'binary') === t;
|
|
452
|
+
}
|
|
453
|
+
catch { /* new */ }
|
|
454
|
+
if (!same) {
|
|
455
|
+
fs.mkdirSync(path.dirname(to), { recursive: true });
|
|
456
|
+
fs.writeFileSync(to, t);
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
// (files of an earlier copy the package no longer has)
|
|
460
|
+
const walkW = (d) => fs.readdirSync(d, { withFileTypes: true }).flatMap(e => (['.build', '.swiftpm'].includes(e.name) || links.has(path.relative(work, path.join(d, e.name))) ? [] : e.isDirectory() ? walkW(path.join(d, e.name)) : [path.join(d, e.name)]));
|
|
461
|
+
for (const f of walkW(work))
|
|
462
|
+
if (!want.has(path.relative(work, f)) && !links.has(path.relative(work, f)))
|
|
463
|
+
fs.rmSync(f);
|
|
464
|
+
for (const [l, to] of links)
|
|
465
|
+
if (!fs.existsSync(path.join(work, l))) {
|
|
466
|
+
fs.mkdirSync(path.dirname(path.join(work, l)), { recursive: true });
|
|
467
|
+
node('node:fs').symlinkSync(to, path.join(work, l));
|
|
468
|
+
}
|
|
469
|
+
try {
|
|
470
|
+
cp.execFileSync(swiftOf(opts), ['build', '--product', 'GdpHarness', '--package-path', work], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 1 << 28 });
|
|
471
|
+
}
|
|
472
|
+
catch (e) {
|
|
473
|
+
return { cmd: 'false', args: [], hello: {}, error: `the package doesn't build with the check's harness: ${errText(e)}` };
|
|
474
|
+
}
|
|
475
|
+
const bin = cp.execFileSync(swiftOf(opts), ['build', '--package-path', work, '--show-bin-path'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
|
|
476
|
+
return { cmd: `${bin}/GdpHarness`, args: [], hello: {} };
|
|
477
|
+
}
|
|
478
|
+
finally {
|
|
479
|
+
try {
|
|
480
|
+
fs.rmdirSync(lock);
|
|
481
|
+
}
|
|
482
|
+
catch { /* gone */ }
|
|
483
|
+
}
|
|
484
|
+
}
|
|
@@ -1,9 +1,13 @@
|
|
|
1
|
+
import { type Source } from './extract-read.js';
|
|
2
|
+
import type { Law } from './machine.js';
|
|
3
|
+
import type { Name } from './extract.js';
|
|
4
|
+
import type { Rule } from './dsl.js';
|
|
1
5
|
import { type Coverage } from './extract-check.js';
|
|
2
6
|
import { fromXState } from './xstate.js';
|
|
3
7
|
export type XStateOptions = {
|
|
4
8
|
file?: string;
|
|
5
|
-
entry
|
|
6
|
-
xstate
|
|
9
|
+
entry?: string;
|
|
10
|
+
xstate?: {
|
|
7
11
|
createActor?: (m: never) => {
|
|
8
12
|
start: () => unknown;
|
|
9
13
|
};
|
|
@@ -27,6 +31,9 @@ export type XStateExtraction = {
|
|
|
27
31
|
what: string;
|
|
28
32
|
}[];
|
|
29
33
|
notes: string[];
|
|
34
|
+
rule?: Rule;
|
|
35
|
+
invariants?: Law[];
|
|
36
|
+
names?: Name[];
|
|
30
37
|
evidence?: {
|
|
31
38
|
runs: number;
|
|
32
39
|
events: number;
|
|
@@ -35,4 +42,4 @@ export type XStateExtraction = {
|
|
|
35
42
|
mismatch?: string;
|
|
36
43
|
};
|
|
37
44
|
};
|
|
38
|
-
export declare function extractXState(
|
|
45
|
+
export declare function extractXState(at: Source, opts?: XStateOptions): XStateExtraction;
|
|
@@ -5,6 +5,9 @@
|
|
|
5
5
|
// the context it writes. The chart is then run beside XState's own actor (`conforms`) on random events with payloads,
|
|
6
6
|
// every state and kept context field compared, the code's branches counted; any difference refuses it.
|
|
7
7
|
//
|
|
8
|
+
// const x = extractXState('./order.ts') // a path or a URL; the machine inferred; xstate from the file's project
|
|
9
|
+
// proveRule(x.rule!, [...x.invariants!, x.rule!.law('retries within 2', ({retries}) => retries.atMost(2))])
|
|
10
|
+
//
|
|
8
11
|
// - A machine made by a function (a factory): read with its arguments as the world gives them. An argument that is an
|
|
9
12
|
// object of functions (the effects a machine is given, its services) is outside: each answer a guard or an action
|
|
10
13
|
// reads of it is an input of the step (any value of its type, read once), a call that answers nothing an effect
|
|
@@ -24,14 +27,51 @@ import ts from 'typescript';
|
|
|
24
27
|
import * as dsl from "./dsl.js";
|
|
25
28
|
import { compileFunction, seeded } from "./machine.js";
|
|
26
29
|
import * as I from "./extract-ir.js";
|
|
27
|
-
import { Exec, Refusal, memberName, normalize, placed, program, refuse, shapeOf, where } from "./extract-read.js";
|
|
30
|
+
import { Exec, Refusal, beside, memberName, normalize, placed, program, refuse, scriptKind, shapeOf, sourceOf, where } from "./extract-read.js";
|
|
28
31
|
import { kindOf, pb, pterm, sortsOf } from "./extract-print.js";
|
|
29
32
|
import { sandbox } from "./extract-check.js";
|
|
30
33
|
import { conforms, eventsOf, fromXState } from "./xstate.js";
|
|
31
34
|
const strip = (e) => (ts.isParenthesizedExpression(e) || ts.isAsExpression(e) || ts.isSatisfiesExpression(e) ? strip(e.expression) : e);
|
|
32
35
|
const isFn = (e) => ts.isArrowFunction(e) || ts.isFunctionExpression(e);
|
|
33
|
-
export function extractXState(
|
|
34
|
-
|
|
36
|
+
export function extractXState(at, opts = {}) {
|
|
37
|
+
let code, file, entry, xstate;
|
|
38
|
+
try {
|
|
39
|
+
;
|
|
40
|
+
({ code, file } = sourceOf(at, opts.file, 'machine.ts'));
|
|
41
|
+
xstate = opts.xstate ?? beside(file, 'xstate') ?? none(file, 'no xstate package resolves from the file (install it in its project, or give it: {xstate: await import(\'xstate\')})');
|
|
42
|
+
entry = opts.entry ?? machineOf(code, file);
|
|
43
|
+
}
|
|
44
|
+
catch (e) {
|
|
45
|
+
if (e instanceof Refusal)
|
|
46
|
+
return { ok: false, refusals: [{ where: e.where, what: e.what }], notes: [] };
|
|
47
|
+
throw e;
|
|
48
|
+
}
|
|
49
|
+
const x = readXState(code, { ...opts, file, entry, xstate });
|
|
50
|
+
if (!opts.entry)
|
|
51
|
+
x.notes.unshift(`the entry inferred: ${entry}, the file's one machine`);
|
|
52
|
+
return x;
|
|
53
|
+
}
|
|
54
|
+
const none = (where, what) => { throw new Refusal(where, what); };
|
|
55
|
+
// The machine a file makes: a createMachine (setup(...)'s too) or a function returning one, the only one.
|
|
56
|
+
function machineOf(code, file) {
|
|
57
|
+
const sf = ts.createSourceFile(file, code, ts.ScriptTarget.ES2022, true, scriptKind(file));
|
|
58
|
+
const makes = (e) => {
|
|
59
|
+
if (!e)
|
|
60
|
+
return false;
|
|
61
|
+
if (isFn(e) || ts.isFunctionDeclaration(e)) {
|
|
62
|
+
const b = e.body, st = b && ts.isBlock(b) ? b.statements.at(-1) : undefined;
|
|
63
|
+
return b && ts.isBlock(b) ? !!st && ts.isReturnStatement(st) && makes(st.expression) : makes(b);
|
|
64
|
+
}
|
|
65
|
+
const c = strip(e);
|
|
66
|
+
if (isFn(c))
|
|
67
|
+
return makes(c);
|
|
68
|
+
return ts.isCallExpression(c) && (ts.isIdentifier(c.expression) ? c.expression.text : ts.isPropertyAccessExpression(c.expression) ? c.expression.name.text : '') === 'createMachine';
|
|
69
|
+
};
|
|
70
|
+
const found = sf.statements.flatMap(st => (ts.isVariableStatement(st) ? st.declarationList.declarations.filter(d => ts.isIdentifier(d.name) && makes(d.initializer)).map(d => d.name.text) : ts.isFunctionDeclaration(st) && st.name && makes(st) ? [st.name.text] : []));
|
|
71
|
+
return found.length === 1 ? found[0] : none(file, found.length ? `several machines in the file (${found.join(', ')}): name one (entry)` : 'no machine in the file (createMachine, setup(...).createMachine, or a function returning one): name the entry');
|
|
72
|
+
}
|
|
73
|
+
function readXState(code, opts) {
|
|
74
|
+
const file = opts.file, t0 = performance.now(), notes = [];
|
|
35
75
|
try {
|
|
36
76
|
const at = placed(file), root = at.slice(0, at.length - file.split('/').pop().length);
|
|
37
77
|
const extra = Object.fromEntries(Object.entries(opts.files ?? {}).map(([p, c]) => [normalize(`${root}${p}`), c]));
|
|
@@ -833,7 +873,13 @@ export function extractXState(code, opts) {
|
|
|
833
873
|
notes.push(...s.notes);
|
|
834
874
|
if (result.failure)
|
|
835
875
|
return { ok: false, source, evidence, notes, refusals: [{ where: file, what: `the chart and XState differ: ${result.failure}` }] };
|
|
836
|
-
|
|
876
|
+
// (the names: the state as XState's snapshot.value, each region's as value.<region>, the context's fields, the
|
|
877
|
+
// factory's context as <field>0, the event and its payload's fields, the answers of the functions it is given)
|
|
878
|
+
const field = (n) => [...s.lazy].find(([k, l]) => k === n && l.prefix === '')?.[1].field ?? n;
|
|
879
|
+
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
|
+
...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
|
+
...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: [] };
|
|
837
883
|
}
|
|
838
884
|
catch (e) {
|
|
839
885
|
if (e instanceof Refusal)
|