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.
Files changed (72) hide show
  1. package/README.md +82 -6
  2. package/dist/core/c/reader.d.ts +86 -0
  3. package/dist/core/c/reader.js +860 -0
  4. package/dist/core/cli.d.ts +66 -0
  5. package/dist/core/cli.js +582 -0
  6. package/dist/core/dsl.d.ts +4 -2
  7. package/dist/core/dsl.js +22 -12
  8. package/dist/core/effect.d.ts +6 -4
  9. package/dist/core/effect.js +48 -10
  10. package/dist/core/ex/harness.exs +177 -0
  11. package/dist/core/ex/json.exs +46 -0
  12. package/dist/core/ex/reader.exs +462 -0
  13. package/dist/core/exists.d.ts +3 -0
  14. package/dist/core/exists.js +3 -1
  15. package/dist/core/extract-c.d.ts +35 -0
  16. package/dist/core/extract-c.js +424 -0
  17. package/dist/core/extract-check.js +27 -6
  18. package/dist/core/extract-ex.d.ts +16 -0
  19. package/dist/core/extract-ex.js +33 -0
  20. package/dist/core/extract-go-check.d.ts +28 -0
  21. package/dist/core/extract-go-check.js +639 -0
  22. package/dist/core/extract-go.d.ts +231 -0
  23. package/dist/core/extract-go.js +1166 -0
  24. package/dist/core/extract-jvm.d.ts +23 -0
  25. package/dist/core/extract-jvm.js +220 -0
  26. package/dist/core/extract-print.js +17 -7
  27. package/dist/core/extract-py.d.ts +15 -0
  28. package/dist/core/extract-py.js +31 -0
  29. package/dist/core/extract-rb.d.ts +17 -0
  30. package/dist/core/extract-rb.js +31 -0
  31. package/dist/core/extract-read.d.ts +20 -0
  32. package/dist/core/extract-read.js +46 -6
  33. package/dist/core/extract-rs.d.ts +12 -0
  34. package/dist/core/extract-rs.js +306 -0
  35. package/dist/core/extract-shapes.d.ts +2 -0
  36. package/dist/core/extract-shapes.js +6 -5
  37. package/dist/core/extract-step.d.ts +806 -0
  38. package/dist/core/extract-step.js +4141 -0
  39. package/dist/core/extract-swift.d.ts +27 -0
  40. package/dist/core/extract-swift.js +484 -0
  41. package/dist/core/extract-xstate.d.ts +10 -3
  42. package/dist/core/extract-xstate.js +50 -4
  43. package/dist/core/extract.d.ts +22 -3
  44. package/dist/core/extract.js +107 -18
  45. package/dist/core/go/go.mod +3 -0
  46. package/dist/core/go/reader.go +901 -0
  47. package/dist/core/infer.js +1770 -52
  48. package/dist/core/jvm/Harness.java +361 -0
  49. package/dist/core/jvm/JavaReader.java +825 -0
  50. package/dist/core/jvm/Jvm.java +332 -0
  51. package/dist/core/jvm/KtReader.java +960 -0
  52. package/dist/core/jvm/Rt.java +10 -0
  53. package/dist/core/laws.d.ts +66 -0
  54. package/dist/core/laws.js +522 -0
  55. package/dist/core/py/harness.py +328 -0
  56. package/dist/core/py/reader.py +447 -0
  57. package/dist/core/rb/harness.rb +233 -0
  58. package/dist/core/rb/reader.rb +375 -0
  59. package/dist/core/rs/Cargo.lock +108 -0
  60. package/dist/core/rs/Cargo.toml +14 -0
  61. package/dist/core/rs/src/main.rs +681 -0
  62. package/dist/core/swift/Harness.swift +124 -0
  63. package/dist/core/swift/Main.swift +34 -0
  64. package/dist/core/swift/Package.swift +13 -0
  65. package/dist/core/swift/Sources/gdp-swiftreader/main.swift +1341 -0
  66. package/dist/kernel/epr.d.ts +35 -0
  67. package/dist/kernel/epr.js +1676 -0
  68. package/dist/kernel/prove.d.ts +44 -0
  69. package/dist/kernel/prove.js +657 -50
  70. package/dist/lean-kernel/emit.d.ts +1 -0
  71. package/dist/lean-kernel/emit.js +21 -4
  72. package/package.json +53 -2
@@ -0,0 +1,23 @@
1
+ import { type Extraction } from './extract.js';
2
+ import { type FileURL } from './extract-read.js';
3
+ import { type SModule, type StepOptions, type StepRead } from './extract-step.js';
4
+ export { proveRule, proveSteps } from './dsl.js';
5
+ export type JvmOptions = StepOptions & {
6
+ root?: string;
7
+ classpath?: string[];
8
+ prebuilt?: boolean;
9
+ sources?: string[];
10
+ ctor?: number;
11
+ javaHome?: string;
12
+ kotlinHome?: string;
13
+ };
14
+ export declare function readJvm(lang: 'java' | 'kotlin', file: string, names: string[], o?: JvmOptions): SModule;
15
+ export declare function extractJvm(lang: 'java' | 'kotlin', at: string | FileURL, opts?: JvmOptions): Extraction & {
16
+ read?: StepRead;
17
+ };
18
+ export declare const extractJava: (at: string | FileURL, opts?: JvmOptions) => Extraction & {
19
+ read?: StepRead;
20
+ };
21
+ export declare const extractKotlin: (at: string | FileURL, opts?: JvmOptions) => Extraction & {
22
+ read?: StepRead;
23
+ };
@@ -0,0 +1,220 @@
1
+ import { Refusal, pathOf } from "./extract-read.js";
2
+ import { entryNames, extractStep, node } from "./extract-step.js";
3
+ export { proveRule, proveSteps } from "./dsl.js";
4
+ const here = (f) => new URL(`./jvm/${f}`, import.meta.url).pathname;
5
+ const TOOLS = ['Jvm.java', 'JavaReader.java', 'Harness.java', 'Rt.java'];
6
+ // (a JVM's stack trace: its exception's line first)
7
+ const errText = (e) => { const ls = String(e.stderr || e.stdout || e.message).split('\n').filter(l => l.trim() && !/^\s+at /.test(l)); return ls.slice(-3).join(' | ').slice(0, 600); };
8
+ // (javac's: its error lines, not the notes and the count after them)
9
+ const javacErr = (e) => { const ls = String(e.stderr || e.stdout || '').split('\n').filter(l => /\berror:/.test(l)); return ls.length ? ls.slice(0, 3).join(' | ').slice(0, 900) : errText(e); };
10
+ // The Kotlin compiler the Kotlin reader is built against (its PSI and its environment's API); research/langs/jvm/jvm-setup.sh.
11
+ const KOTLIN = '2.4.21';
12
+ function jdk(o) {
13
+ const env = globalThis.process?.env ?? {};
14
+ const home = o.javaHome ?? env.JAVA_HOME;
15
+ return home ? { java: `${home}/bin/java`, javac: `${home}/bin/javac` } : { java: 'java', javac: 'javac' };
16
+ }
17
+ function kotlinLib(o) {
18
+ const fs = node('node:fs'), cp = node('node:child_process'), path = node('node:path');
19
+ const env = globalThis.process?.env ?? {};
20
+ let home = o.kotlinHome ?? env.KOTLIN_HOME;
21
+ if (!home) {
22
+ try {
23
+ home = path.resolve(path.dirname(fs.realpathSync(cp.execFileSync('sh', ['-c', 'command -v kotlinc'], { encoding: 'utf8' }).trim())), '..');
24
+ }
25
+ catch { /* none */ }
26
+ }
27
+ const lib = home && [`${home}/lib`, `${home}/libexec/lib`].find(d => fs.existsSync(`${d}/kotlin-compiler.jar`));
28
+ if (!lib)
29
+ throw new Refusal('kotlinc', 'kotlinc (the Kotlin compiler: its lib/kotlin-compiler.jar and kotlin-stdlib.jar) is needed to extract Kotlin; set kotlinHome or $KOTLIN_HOME');
30
+ return lib;
31
+ }
32
+ // The tools (the readers and the harness), compiled once per version of their sources and of the compiler.
33
+ // (Java 17, the oldest JDK they support, by `--release 17` whichever JDK compiles them, so a later javac refuses what
34
+ // 17's would)
35
+ const FLAGS = ['-nowarn', '-Xlint:none', '--release', '17'];
36
+ // What was found, for a refusal: the JDK's version and kotlinc's (its build.txt, beside lib/).
37
+ function found(o, kt) {
38
+ const fs = node('node:fs'), cp = node('node:child_process');
39
+ let j = 'no javac';
40
+ try {
41
+ j = cp.execFileSync('sh', ['-c', '"$0" -version 2>&1', jdk(o).javac], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim().split('\n')[0] || 'javac';
42
+ }
43
+ catch { /* none */ }
44
+ let k = '';
45
+ if (kt) {
46
+ try {
47
+ k = `, kotlinc ${fs.readFileSync(`${kt}/../build.txt`, 'utf8').trim()}`;
48
+ }
49
+ catch {
50
+ k = ', kotlinc of unknown version';
51
+ }
52
+ }
53
+ return `${j}${k}`;
54
+ }
55
+ function tools(o, kt) {
56
+ const fs = node('node:fs'), cp = node('node:child_process'), os = node('node:os'), crypto = node('node:crypto');
57
+ const files = kt ? ['KtReader.java'] : TOOLS;
58
+ const h = crypto.createHash('sha256').update(files.map(f => fs.readFileSync(here(f), 'utf8')).join('\0') + (kt ?? '') + jdk(o).javac + FLAGS.join(' ')).digest('hex').slice(0, 16);
59
+ const dir = `${os.tmpdir()}/gdp-jvm${kt ? 'kt' : ''}-${h}`;
60
+ if (fs.existsSync(`${dir}/ok`))
61
+ return dir;
62
+ const base = kt ? tools(o) : undefined, tmp = fs.mkdtempSync(`${dir}-`);
63
+ try {
64
+ cp.execFileSync(jdk(o).javac, [...FLAGS, '-d', tmp, ...(kt ? ['-cp', `${base}:${kt}/kotlin-compiler.jar:${kt}/kotlin-stdlib.jar`] : []), ...files.map(here)], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
65
+ }
66
+ catch (e) {
67
+ fs.rmSync(tmp, { recursive: true, force: true });
68
+ throw new Refusal('javac', `the JVM tools didn't compile (${javacErr(e)}; found ${found(o, kt)}): a JDK 17 or later${kt ? ` and kotlinc ${KOTLIN} (the compiler the Kotlin reader is built against)` : ''} is needed to extract ${kt ? 'Kotlin' : 'Java'}`);
69
+ }
70
+ fs.writeFileSync(`${tmp}/ok`, '');
71
+ try {
72
+ fs.renameSync(tmp, dir);
73
+ }
74
+ catch {
75
+ fs.rmSync(tmp, { recursive: true, force: true });
76
+ }
77
+ return dir;
78
+ }
79
+ const jvmOf = (mod) => mod.jvm;
80
+ // The class read's own (an entry inferred among the file's classes): its binary name, constructor and methods.
81
+ const classOf = (mod, read) => {
82
+ const j = jvmOf(mod), r = read.cls ? mod.recs[read.cls]?.jvm : undefined;
83
+ return r?.cls ? { cls: r.cls, ctor: r.ctor?.params ?? [], methods: r.sigs ?? {}, reducers: r.reducers ?? j.reducers ?? [] } : { cls: j.cls, ctor: j.ctor ?? [], methods: j.methods, reducers: j.reducers ?? [] };
84
+ };
85
+ // The package root of a file: its directory less the package's.
86
+ function packageRoot(file, kotlin) {
87
+ const fs = node('node:fs'), path = node('node:path');
88
+ let text = '';
89
+ try {
90
+ text = fs.readFileSync(file, 'utf8');
91
+ }
92
+ catch { /* read by the reader, which says so */ }
93
+ const m = /^\s*package\s+([\w.]+)/m.exec(text);
94
+ let d = path.dirname(path.resolve(file));
95
+ if (m && !kotlin)
96
+ for (const _ of m[1].split('.'))
97
+ d = path.dirname(d);
98
+ return d;
99
+ }
100
+ export function readJvm(lang, file, names, o = {}) {
101
+ const cp = node('node:child_process'), path = node('node:path');
102
+ const abs = path.resolve(file), root = path.resolve(o.root ?? packageRoot(abs, lang === 'kotlin'));
103
+ const kt = lang === 'kotlin' ? kotlinLib(o) : undefined;
104
+ const t = tools(o), cpath = kt ? [t, tools(o, kt), `${kt}/kotlin-compiler.jar`, `${kt}/kotlin-stdlib.jar`, ...(o.classpath ?? [])].join(':') : t;
105
+ let out;
106
+ try {
107
+ out = cp.execFileSync(jdk(o).java, ['-cp', cpath, `gdp.jvm.${kt ? 'KtReader' : 'JavaReader'}`, JSON.stringify({ root, file: abs, names, classpath: (o.classpath ?? []).join(':'), sources: o.sources ?? [], ctor: o.ctor ?? null })], { encoding: 'utf8', maxBuffer: 1 << 29, stdio: ['ignore', 'pipe', 'pipe'] });
108
+ }
109
+ catch (e) {
110
+ throw new Refusal(file, `the ${kt ? 'Kotlin' : 'Java'} reader didn't run (${errText(e)}${kt ? `; found ${found(o, kt)}` : ''}): a JDK 17 or later${kt ? ` and kotlinc ${KOTLIN} (the compiler the Kotlin reader is built against)` : ''} is needed to extract ${kt ? 'Kotlin' : 'Java'}`);
111
+ }
112
+ return JSON.parse(out);
113
+ }
114
+ // An answered call's sites: the calls of other code whose names the answer's key matches (the executor's own rule):
115
+ // a static one's (`ext`) and a method's of an object of other code (an injected dependency's are the harness's own).
116
+ function answerSites(mod, keys) {
117
+ const out = [];
118
+ const hit = (names) => keys.find(e => names.some(n => n === e || n.startsWith(`${e}.`) || n.endsWith(`.${e}`) || n.endsWith(`.${e.replace(/^self\./, '')}`)));
119
+ const walk = (x) => {
120
+ if (Array.isArray(x)) {
121
+ x.forEach(walk);
122
+ return;
123
+ }
124
+ if (!x || typeof x !== 'object')
125
+ return;
126
+ const n = x;
127
+ const f = n.f;
128
+ if (n.e === 'call' && f && (f.e === 'ext' || f.e === 'get') && n.span) {
129
+ const k = hit([String(f.text), ...(f.e === 'ext' ? [String(f.q)] : [String(f.f)])]);
130
+ if (k)
131
+ out.push({ span: n.span, key: k, jt: n.jt ?? 'java.lang.Object' });
132
+ }
133
+ for (const v of Object.values(n))
134
+ walk(v);
135
+ };
136
+ walk(mod.funcs);
137
+ return out;
138
+ }
139
+ const BOXES = { int: 'java.lang.Integer', long: 'java.lang.Long', short: 'java.lang.Short', byte: 'java.lang.Byte', char: 'java.lang.Character', boolean: 'java.lang.Boolean', float: 'java.lang.Float', double: 'java.lang.Double' };
140
+ const KT = { int: 'Int', long: 'Long', short: 'Short', byte: 'Byte', char: 'Char', boolean: 'Boolean', float: 'Float', double: 'Double', 'java.lang.String': 'String' };
141
+ // The code compiled for the check: a copy of the file with the clock's and the answered calls' sites rewritten.
142
+ function compiled(lang, mod, read, o, made) {
143
+ const fs = node('node:fs'), cp = node('node:child_process'), os = node('node:os'), path = node('node:path');
144
+ const j = jvmOf(mod), kotlin = lang === 'kotlin';
145
+ const sites = [...j.rewrites.map(r => ({ span: r.span, text: 'gdp.Rt.now()' })), ...answerSites(mod, read.answers.filter(a => !a.patch.store).map(a => a.key)).map(s => {
146
+ const t = s.jt.replace(/\?$/, '').replace(/<.*$/, ''), box = BOXES[t] ?? t;
147
+ return { span: s.span, text: kotlin ? `(gdp.Rt.answer(${JSON.stringify(s.key)}, ${box}::class.java) as ${KT[t] ?? t.split('.').pop()}${s.jt.endsWith('?') ? '?' : ''})` : `((${box}) gdp.Rt.answer(${JSON.stringify(s.key)}, ${box}.class))` };
148
+ })];
149
+ if (o.prebuilt)
150
+ return sites.length ? { dirs: [], error: 'prebuilt: the rule reads the clock or an answered call, which the shipped classes can\'t be given (compile the file instead)' } : { dirs: [] };
151
+ const work = fs.mkdtempSync(`${os.tmpdir()}/gdp-jvmcheck-`);
152
+ made.push(work);
153
+ const src = fs.readFileSync(mod.path, 'utf8');
154
+ let text = src;
155
+ for (const s of [...sites].sort((a, b) => b.span[0] - a.span[0]))
156
+ text = text.slice(0, s.span[0]) + s.text + text.slice(s.span[1]);
157
+ const rel = mod.path.startsWith(`${mod.root}/`) ? mod.path.slice(mod.root.length + 1) : mod.file;
158
+ const copy = `${work}/src/${rel}`;
159
+ fs.mkdirSync(path.dirname(copy), { recursive: true });
160
+ fs.writeFileSync(copy, text);
161
+ const out = `${work}/classes`, t = tools(o), extra = (o.classpath ?? []).join(':');
162
+ try {
163
+ if (kotlin) {
164
+ const kt = kotlinLib(o);
165
+ cp.execFileSync(jdk(o).java, ['-Xss8m', '-cp', `${kt}/kotlin-compiler.jar`, 'org.jetbrains.kotlin.cli.jvm.K2JVMCompiler', '-kotlin-home', path.dirname(kt), '-nowarn', '-no-reflect', '-d', out, '-cp', [t, extra].filter(Boolean).join(':'), copy, ...(o.sources ?? []).map(f => path.resolve(f))], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 1 << 26 });
166
+ return { dirs: [out, `${kt}/kotlin-stdlib.jar`] };
167
+ }
168
+ cp.execFileSync(jdk(o).javac, ['-nowarn', '-Xlint:none', '-proc:none', '-implicit:class', '-d', out, '-sourcepath', `${work}/src:${mod.root}`, '-cp', [t, extra].filter(Boolean).join(':'), copy], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 1 << 26 });
169
+ return { dirs: [out] };
170
+ }
171
+ catch (e) {
172
+ return { dirs: [], error: `the code doesn't compile for the check (${errText(e)})` };
173
+ }
174
+ }
175
+ export function extractJvm(lang, at, opts = {}) {
176
+ const file = pathOf(at);
177
+ let mod;
178
+ try {
179
+ if (opts.stores && Object.keys(opts.stores).length)
180
+ throw new Refusal(file, `stores: not in the ${lang === 'java' ? 'Java' : 'Kotlin'} front end yet`);
181
+ mod = readJvm(lang, file, entryNames(opts), opts);
182
+ // (the shipped classes can't be rewritten: an answer, other than an injected dependency's, can't be stubbed)
183
+ if (opts.prebuilt)
184
+ mod.stubs = false;
185
+ }
186
+ catch (e) {
187
+ if (e instanceof Refusal)
188
+ return { ok: false, refusals: [{ where: e.where, what: e.what }], notes: [] };
189
+ throw e;
190
+ }
191
+ // (the check's copies of the code, removed once it ran)
192
+ const made = [];
193
+ const harness = (read) => {
194
+ read.arms.length = 0;
195
+ read.model.notes.push(`${lang === 'java' ? 'Java' : 'Kotlin'}: the code is checked as ${opts.prebuilt ? 'its classes ship' : 'compiled from the file'}; its branch arms are not counted (no instrumentation yet)`);
196
+ const j = classOf(mod, read);
197
+ let c;
198
+ try {
199
+ c = compiled(lang, mod, read, opts, made);
200
+ }
201
+ catch (e) {
202
+ if (e instanceof Refusal)
203
+ return { cmd: 'false', args: [], hello: {}, error: e.what };
204
+ throw e;
205
+ }
206
+ if (c.error)
207
+ return { cmd: 'false', args: [], hello: {}, error: c.error };
208
+ const t = tools(opts);
209
+ return { cmd: jdk(opts).java, args: ['-cp', t, 'gdp.jvm.Harness'], hello: { jcls: j.cls, cp: [...c.dirs, ...(opts.classpath ?? [])], jctor: { params: j.ctor }, methods: j.methods, reducers: j.reducers } };
210
+ };
211
+ try {
212
+ return extractStep(mod, harness, opts);
213
+ }
214
+ finally {
215
+ for (const d of made)
216
+ node('node:fs').rmSync(d, { recursive: true, force: true });
217
+ }
218
+ }
219
+ export const extractJava = (at, opts = {}) => extractJvm('java', at, opts);
220
+ export const extractKotlin = (at, opts = {}) => extractJvm('kotlin', at, opts);
@@ -158,15 +158,25 @@ function atomicFacts(ctx, side) {
158
158
  out.push(...atomicCond(ctx.m.pre, ctx, side));
159
159
  return out;
160
160
  }
161
+ // (an atom's own facts read the refusals, whose atoms ask again: past a few levels a term isn't taken as a natural)
162
+ let depth = 0;
161
163
  export function nonneg(e, ctx) {
162
- const side = [], lin = atomic(e, ctx, side), afacts = atomicFacts(ctx, side);
163
- if (refutes([...side, ...afacts, ...lt(lin, lk(0))]))
164
- return true;
165
- const cs = cases(e, ctx);
166
- if (!cs)
164
+ if (depth > 3)
167
165
  return false;
168
- const facts = factsAt(ctx);
169
- return cs.every(c => refutes([...facts, ...c.cons, ...lt(c.lin, lk(0))]));
166
+ depth++;
167
+ try {
168
+ const side = [], lin = atomic(e, ctx, side), afacts = atomicFacts(ctx, side);
169
+ if (refutes([...side, ...afacts, ...lt(lin, lk(0))]))
170
+ return true;
171
+ const cs = cases(e, ctx);
172
+ if (!cs)
173
+ return false;
174
+ const facts = factsAt(ctx);
175
+ return cs.every(c => refutes([...facts, ...c.cons, ...lt(c.lin, lk(0))]));
176
+ }
177
+ finally {
178
+ depth--;
179
+ }
170
180
  }
171
181
  const withAtom = (ctx, c) => ({ ...ctx, atoms: [...ctx.atoms, c] });
172
182
  // A condition the place is already under (or under its negation): the branch it takes.
@@ -0,0 +1,15 @@
1
+ import { type Extraction } from './extract.js';
2
+ import { type FileURL } from './extract-read.js';
3
+ import { type SModule, type StepOptions, type StepRead } from './extract-step.js';
4
+ export { proveRule, proveSteps } from './dsl.js';
5
+ export type PyOptions = StepOptions & {
6
+ root?: string;
7
+ python?: string;
8
+ };
9
+ export declare function readPython(file: string, names: string[], opts?: {
10
+ root?: string;
11
+ python?: string;
12
+ }): SModule;
13
+ export declare function extractPython(at: string | FileURL, opts?: PyOptions): Extraction & {
14
+ read?: StepRead;
15
+ };
@@ -0,0 +1,31 @@
1
+ import { Refusal, pathOf } from "./extract-read.js";
2
+ import { entryNames, extractStep, node } from "./extract-step.js";
3
+ export { proveRule, proveSteps } from "./dsl.js";
4
+ const here = (f) => new URL(`./py/${f}`, import.meta.url).pathname;
5
+ // The module as the reader lowers it (the names given and the module's functions).
6
+ export function readPython(file, names, opts = {}) {
7
+ const cp = node('node:child_process'), path = node('node:path');
8
+ const abs = path.resolve(file), root = path.resolve(opts.root ?? path.dirname(abs));
9
+ let out;
10
+ try {
11
+ out = cp.execFileSync(opts.python ?? 'python3', ['-I', here('reader.py'), JSON.stringify({ root, file: abs, names })], { encoding: 'utf8', maxBuffer: 1 << 29, stdio: ['ignore', 'pipe', 'pipe'] });
12
+ }
13
+ catch (e) {
14
+ throw new Refusal(file, `the Python reader didn't run (${String(e.stderr ?? e.message).split('\n').filter(Boolean).slice(-2).join(' | ')}): python3 is needed to extract Python`);
15
+ }
16
+ return JSON.parse(out);
17
+ }
18
+ export function extractPython(at, opts = {}) {
19
+ const file = pathOf(at);
20
+ let mod;
21
+ try {
22
+ mod = readPython(file, entryNames(opts), opts);
23
+ }
24
+ catch (e) {
25
+ if (e instanceof Refusal)
26
+ return { ok: false, refusals: [{ where: e.where, what: e.what }], notes: [] };
27
+ throw e;
28
+ }
29
+ const harness = () => ({ cmd: opts.python ?? 'python3', args: [here('harness.py')], env: { PYTHONDONTWRITEBYTECODE: '1' }, hello: { root: mod.root, path: mod.path, module: mod.module } });
30
+ return extractStep(mod, harness, opts);
31
+ }
@@ -0,0 +1,17 @@
1
+ import { type Extraction } from './extract.js';
2
+ import { type FileURL } from './extract-read.js';
3
+ import { type SModule, type StepOptions, type StepRead } from './extract-step.js';
4
+ export { proveRule, proveSteps } from './dsl.js';
5
+ export type RbOptions = StepOptions & {
6
+ root?: string;
7
+ ruby?: string;
8
+ clocks?: string[];
9
+ };
10
+ export declare function readRuby(file: string, names: string[], opts?: {
11
+ root?: string;
12
+ ruby?: string;
13
+ clocks?: string[];
14
+ }): SModule;
15
+ export declare function extractRuby(at: string | FileURL, opts?: RbOptions): Extraction & {
16
+ read?: StepRead;
17
+ };
@@ -0,0 +1,31 @@
1
+ import { Refusal, pathOf } from "./extract-read.js";
2
+ import { entryNames, extractStep, node } from "./extract-step.js";
3
+ export { proveRule, proveSteps } from "./dsl.js";
4
+ const here = (f) => new URL(`./rb/${f}`, import.meta.url).pathname;
5
+ // The file as the reader lowers it (the class named).
6
+ export function readRuby(file, names, opts = {}) {
7
+ const cp = node('node:child_process'), path = node('node:path');
8
+ const abs = path.resolve(file), root = path.resolve(opts.root ?? path.dirname(abs));
9
+ let out;
10
+ try {
11
+ out = cp.execFileSync(opts.ruby ?? 'ruby', [here('reader.rb'), JSON.stringify({ root, file: abs, names, clocks: opts.clocks ?? [] })], { encoding: 'utf8', maxBuffer: 1 << 29, stdio: ['ignore', 'pipe', 'pipe'] });
12
+ }
13
+ catch (e) {
14
+ throw new Refusal(file, `the Ruby reader didn't run (${String(e.stderr ?? e.message).split('\n').filter(Boolean).slice(-2).join(' | ')}): ruby 3.3 or later (with Prism) is needed to extract Ruby`);
15
+ }
16
+ return JSON.parse(out);
17
+ }
18
+ export function extractRuby(at, opts = {}) {
19
+ const file = pathOf(at);
20
+ let mod;
21
+ try {
22
+ mod = readRuby(file, entryNames(opts), opts);
23
+ }
24
+ catch (e) {
25
+ if (e instanceof Refusal)
26
+ return { ok: false, refusals: [{ where: e.where, what: e.what }], notes: [] };
27
+ throw e;
28
+ }
29
+ const harness = () => ({ cmd: opts.ruby ?? 'ruby', args: [here('harness.rb')], hello: { root: mod.root, path: mod.path, clocks: opts.clocks ?? [], loads: mod.loads ?? [] } });
30
+ return extractStep(mod, harness, opts);
31
+ }
@@ -46,6 +46,7 @@ export type MapDecl = {
46
46
  scalar: boolean;
47
47
  js: 'Map' | 'record' | 'Set';
48
48
  untyped?: boolean;
49
+ len?: number;
49
50
  };
50
51
  export type Layout = {
51
52
  k: 'scalar';
@@ -95,6 +96,7 @@ export type Event = {
95
96
  select: Record<string, string>;
96
97
  call: string;
97
98
  args: Arg[];
99
+ names?: string[];
98
100
  };
99
101
  export type MapWrite = {
100
102
  key: K;
@@ -177,6 +179,8 @@ export type Model = {
177
179
  laws?: string[];
178
180
  answers?: Record<string, string>;
179
181
  fnFields?: string[];
182
+ imports?: string[];
183
+ kind?: string;
180
184
  };
181
185
  type V = {
182
186
  t: 'num';
@@ -282,6 +286,20 @@ export declare function program(code: string, file: string, extra?: Record<strin
282
286
  checker: ts.TypeChecker;
283
287
  };
284
288
  export declare function placed(file: string): string;
289
+ export type FileURL = {
290
+ readonly href: string;
291
+ readonly protocol: string;
292
+ };
293
+ export type Source = string | FileURL | {
294
+ code: string;
295
+ file?: string;
296
+ };
297
+ export declare const pathOf: (at: string | FileURL) => string;
298
+ export declare function sourceOf(at: Source, file: string | undefined, dflt: string): {
299
+ code: string;
300
+ file: string;
301
+ };
302
+ export declare function beside<T>(file: string, spec: string): T | undefined;
285
303
  export declare const scriptKind: (file: string) => ts.ScriptKind;
286
304
  export declare function shapeOf(t: ts.Type, checker: ts.TypeChecker, at: ts.Node, inner?: string): Shape;
287
305
  type Callable = {
@@ -316,12 +334,14 @@ export type Setup = {
316
334
  sort: Sort;
317
335
  }>;
318
336
  };
337
+ strict?: boolean;
319
338
  fnFields?: {
320
339
  outside: Map<string, {
321
340
  path: string;
322
341
  sort: Sort;
323
342
  }>;
324
343
  names: Set<string>;
344
+ mods?: Set<string>;
325
345
  };
326
346
  effect?: (ex: Exec, e: ts.Expression, p: Path) => [V, Path] | undefined;
327
347
  };
@@ -70,6 +70,33 @@ export function placed(file) {
70
70
  const cwd = globalThis.process?.cwd?.() ?? '.';
71
71
  return (/^([A-Za-z]:)?[\\/]/.test(file) ? file : `${cwd}/${file}`).replace(/\\/g, '/');
72
72
  }
73
+ const builtin = (id) => globalThis.process?.getBuiltinModule?.(id);
74
+ export const pathOf = (at) => (typeof at === 'string' ? at : builtin('node:url').fileURLToPath(at.href));
75
+ // A TypeScript front end's source. A string is the code where it can't be a path (a line break, or no script's
76
+ // extension): the code-first call, as it was.
77
+ export function sourceOf(at, file, dflt) {
78
+ if (typeof at === 'object' && 'code' in at)
79
+ return { code: at.code, file: at.file ?? file ?? dflt };
80
+ if (typeof at === 'string' && (at.includes('\n') || !/\.[cm]?[jt]sx?$/.test(at)))
81
+ return { code: at, file: file ?? dflt };
82
+ const p = pathOf(at).replace(/^(\.\/)+/, '');
83
+ try {
84
+ return { code: builtin('node:fs').readFileSync(p, 'utf8'), file: p };
85
+ }
86
+ catch {
87
+ throw new Refusal(p, 'no such file');
88
+ }
89
+ }
90
+ // A package as the code at `file` imports it (from its own project's node_modules), so the check runs on the version
91
+ // the code is written for; undefined where none resolves.
92
+ export function beside(file, spec) {
93
+ try {
94
+ return builtin('node:module').createRequire(placed(file))(spec);
95
+ }
96
+ catch {
97
+ return undefined;
98
+ }
99
+ }
73
100
  export const scriptKind = (file) => (/\.jsx$/.test(file) ? ts.ScriptKind.JSX : /\.tsx$/.test(file) ? ts.ScriptKind.TSX : /\.[cm]?js$/.test(file) ? ts.ScriptKind.JS : ts.ScriptKind.TS);
74
101
  // The shape a type has in the subset.
75
102
  // (`inner`: the field path inside the value at `at` that t is the type of, for where a refusal says it is)
@@ -1405,12 +1432,21 @@ export class Exec {
1405
1432
  return this.outside(e, p.locals.get(callee.text).path, p);
1406
1433
  const sym = this.resolved(callee), decl = sym?.valueDeclaration;
1407
1434
  const fn = decl && ts.isFunctionDeclaration(decl) ? decl : decl && ts.isVariableDeclaration(decl) && decl.initializer && (ts.isArrowFunction(decl.initializer) || ts.isFunctionExpression(decl.initializer)) ? decl.initializer : undefined;
1408
- if (fn && this.s.ours(fn.getSourceFile())) {
1435
+ const bodyless = !!decl && ts.isFunctionDeclaration(decl) && !decl.body;
1436
+ if (fn && !bodyless && this.s.ours(fn.getSourceFile())) {
1409
1437
  const [args, q] = this.args(e.arguments, p);
1410
1438
  return this.inline({ decl: fn }, args, e, q);
1411
1439
  }
1412
- if (!decl || !this.s.ours(decl.getSourceFile()))
1440
+ if (!decl || bodyless || !this.s.ours(decl.getSourceFile())) {
1441
+ // (another module's function, called by a class: at the boundary, as a function the class is given is, unless
1442
+ // strict: its answer an input over its declared type, a call that returns nothing left out; stubbed by name)
1443
+ const imp = this.s.checker.getSymbolAtLocation(callee)?.declarations?.find(d => ts.isImportSpecifier(d)), mod = imp && moduleOf(imp).replace(/^ \('|'\)$/g, '');
1444
+ if (imp && mod && this.s.fnFields && !this.s.strict) {
1445
+ (this.s.fnFields.mods ??= new Set()).add(mod);
1446
+ return this.outside(e, `import:${mod}:${(imp.propertyName ?? imp.name).text}`, p);
1447
+ }
1413
1448
  return refuse(e, `${callee.text}: a function from another module (not among the files read)`);
1449
+ }
1414
1450
  return refuse(e, `${callee.text}: a call the subset doesn't read`);
1415
1451
  }
1416
1452
  return refuse(e, 'a call the subset doesn\'t read');
@@ -1425,10 +1461,14 @@ export class Exec {
1425
1461
  const x = this.s.xstate ?? own ?? refuse(e, `${path}: a function from outside`);
1426
1462
  if (e.arguments.some(impure))
1427
1463
  refuse(e, `${path}(...) with arguments that have effects`);
1428
- const [, q] = this.args(e.arguments, p);
1464
+ const [args, q] = this.args(e.arguments, p);
1465
+ // (a function from outside given the object's state, or a part of it, may change it: refused)
1466
+ const state = (v) => v.t === 'ref' ? (o => !!o && (o.k === 'alias' ? state(o.to) : o.origin === 'this' || o.origin === 'shared'))(q.heap.get(v.id)) : v.t === 'phi' ? state(v.a) || state(v.b) : v.t === 'opt' ? state(v.v) : v.t === 'tuple' && v.xs.some(state);
1467
+ if (args.some(state))
1468
+ refuse(e, `${path}(...) is given the object's state, which the function may change`);
1429
1469
  const t = this.s.checker.getTypeAtLocation(e);
1430
1470
  if (t.flags & (ts.TypeFlags.Void | ts.TypeFlags.Undefined)) {
1431
- this.s.notes.add(`${path}() is an effect outside the machine (it returns nothing; left out)`);
1471
+ this.s.notes.add(path.startsWith('import:') ? `${path.slice(7).replace(':', '.')}() (${where(e)}): left out (inferred: it returns nothing), the check giving a function that does nothing` : `${path}() is an effect outside the machine (it returns nothing; left out)`);
1432
1472
  return [{ t: 'undef' }, q];
1433
1473
  }
1434
1474
  if (t.getSymbol()?.getName() === 'Promise')
@@ -1443,10 +1483,10 @@ export class Exec {
1443
1483
  const had = [...own.outside].find(([, o]) => o.path === path);
1444
1484
  if (had && had[1].sort.k !== sh.k)
1445
1485
  return refuse(e, `${path}() read as two sorts`);
1446
- const v = had ? this.s.vars.get(had[0]) : this.newVar(path.split('.').pop(), sh, 'input', `${path}(): the answer of the function the field holds (any value of its type: the claim is for every such function that leaves the object alone)`);
1486
+ const v = had ? this.s.vars.get(had[0]) : this.newVar(path.split(/[.:]/).pop(), sh, 'input', `${path}(): the answer of the function the field holds (any value of its type: the claim is for every such function that leaves the object alone)`);
1447
1487
  if (!had) {
1448
1488
  own.outside.set(v.name, { path, sort: sh });
1449
- this.s.notes.add(`${path}(): the answer of the function the field holds, an input (any value of its type: the claim is for every such function that leaves the object alone)`);
1489
+ this.s.notes.add(path.startsWith('import:') ? `${path.slice(7).replace(':', '.')}() (${where(e)}): answered by the request (inferred: its value is read; assumes it may return any value of its declared type)` : `${path}(): the answer of the function the field holds, an input (any value of its type: the claim is for every such function that leaves the object alone)`);
1450
1490
  }
1451
1491
  return [Exec.valueOf(v), { ...q, outs: [...(q.outs ?? []), path] }];
1452
1492
  }
@@ -0,0 +1,12 @@
1
+ import { type Extraction } from './extract.js';
2
+ import { type FileURL } from './extract-read.js';
3
+ import { type SModule, type StepOptions, type StepRead } from './extract-step.js';
4
+ export { proveRule, proveSteps } from './dsl.js';
5
+ export type RsOptions = StepOptions & {
6
+ cargo?: string;
7
+ };
8
+ export declare function rsReader(cargo?: string): string;
9
+ export declare function readRust(dir: string, names: string[], cargo?: string): SModule;
10
+ export declare function extractRust(at: string | FileURL, opts?: RsOptions): Extraction & {
11
+ read?: StepRead;
12
+ };