tslaws 1.1.0 → 1.2.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.
@@ -0,0 +1,406 @@
1
+ // Local HTTP ESM server for browser laws: gives every browser law a real `http://127.0.0.1:<port>` origin
2
+ // (localStorage, History API, Cookies, WebCrypto, relative fetch, native ESM), caches esbuild bundles once per
3
+ // `.browser.laws.ts` file instead of once per law, and bundles a browser fast-check runner for zero-IPC in-browser
4
+ // property testing. No external dev-server dependency (no Vite).
5
+ import { existsSync, statSync } from 'node:fs';
6
+ import { createServer } from 'node:http';
7
+ import { extname, join, relative as pathRelative, resolve, sep } from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { build as bundleWith } from 'esbuild';
10
+ import { explainBundleError, loadBundlerPlugins } from "./bundlerPlugins.js";
11
+ import { lawEnv, readConfig } from "./coverage.js";
12
+ import { compiledDirOf } from "./lawRuntime.js";
13
+ import { importMetaEnvGlobal } from "./runtimeEnv.js";
14
+ const assetExtensions = [
15
+ '.png',
16
+ '.jpg',
17
+ '.jpeg',
18
+ '.gif',
19
+ '.webp',
20
+ '.avif',
21
+ '.svg',
22
+ '.ico',
23
+ '.woff',
24
+ '.woff2',
25
+ '.ttf',
26
+ '.otf',
27
+ '.eot',
28
+ ];
29
+ function projectModulesPlugin(cwd) {
30
+ return {
31
+ name: 'tslaws-project-modules',
32
+ setup(build) {
33
+ build.onResolve({ filter: /^[^./]/ }, async (args) => {
34
+ if (args.pluginData === 'tslaws' || args.kind === 'entry-point' || /^[a-zA-Z]:/.test(args.path))
35
+ return undefined;
36
+ const found = await build.resolve(args.path, { kind: args.kind, resolveDir: cwd, pluginData: 'tslaws' });
37
+ if (found.errors.length === 0)
38
+ return { path: found.path, external: found.external, sideEffects: found.sideEffects };
39
+ return args.path === 'axe-core' ? { path: 'axe-core', external: true } : undefined;
40
+ });
41
+ },
42
+ };
43
+ }
44
+ function sourceFilesPlugin(cwd) {
45
+ const out = join(cwd, '.tslaws', 'out');
46
+ const project = compiledDirOf(cwd);
47
+ return {
48
+ name: 'tslaws-source-files',
49
+ setup(build) {
50
+ build.onResolve({ filter: /^\.\.?\// }, (args) => {
51
+ if (args.resolveDir !== out && !args.resolveDir.startsWith(out + sep))
52
+ return undefined;
53
+ const inOut = resolve(args.resolveDir, args.path);
54
+ if (existsSync(inOut))
55
+ return undefined;
56
+ const source = join(cwd, pathRelative(project, inOut));
57
+ return existsSync(source) && !source.endsWith('.js') ? { path: source } : undefined;
58
+ });
59
+ },
60
+ };
61
+ }
62
+ function bundlerTsconfig(cwd) {
63
+ const setting = readConfig(cwd).tsconfig;
64
+ if (setting === false)
65
+ return { tsconfigRaw: '{}' };
66
+ return setting === undefined ? {} : { tsconfig: resolve(cwd, setting) };
67
+ }
68
+ // Per-file bundle cache: keyed by `(cwd, jsFile, mtimeMs, size, plugins)` so a file with 20 laws bundles once.
69
+ const bundleCache = new Map();
70
+ const bundlesById = new Map();
71
+ let nextBundleId = 1;
72
+ function fileStamp(cwd, jsFile) {
73
+ const config = readConfig(cwd);
74
+ const plugins = (config.bundlerPlugins ?? []).join(',');
75
+ try {
76
+ const st = statSync(jsFile);
77
+ return `${st.size}:${st.mtimeMs}:${plugins}:${String(config.tsconfig ?? '')}`;
78
+ }
79
+ catch {
80
+ return `${Date.now()}:${plugins}`;
81
+ }
82
+ }
83
+ /** Bundles `jsFile` once per file version and registers it with the local HTTP server. */
84
+ export async function bundleLawFile(jsFile, cwd) {
85
+ const key = `${resolve(cwd)}\0${resolve(jsFile)}`;
86
+ const stamp = fileStamp(cwd, jsFile);
87
+ const cached = bundleCache.get(key);
88
+ if (cached !== undefined && cached.stamp === stamp)
89
+ return cached.bundle;
90
+ const id = `b${nextBundleId++}`;
91
+ const promise = (async () => {
92
+ const projectPlugins = await loadBundlerPlugins(cwd, readConfig(cwd).bundlerPlugins);
93
+ try {
94
+ const result = await bundleWith({
95
+ plugins: [...projectPlugins, sourceFilesPlugin(cwd), projectModulesPlugin(cwd)],
96
+ entryPoints: [jsFile],
97
+ bundle: true,
98
+ write: false,
99
+ outdir: join(cwd, '.tslaws', 'bundle'),
100
+ loader: Object.fromEntries(assetExtensions.map((extension) => [extension, 'dataurl'])),
101
+ format: 'iife',
102
+ globalName: '__lawModule',
103
+ platform: 'browser',
104
+ target: 'es2022',
105
+ absWorkingDir: cwd,
106
+ ...bundlerTsconfig(cwd),
107
+ logLevel: 'silent',
108
+ define: {
109
+ 'process.env.NODE_ENV': '"development"',
110
+ global: 'globalThis',
111
+ 'import.meta.env': `globalThis.${importMetaEnvGlobal}`,
112
+ },
113
+ });
114
+ const emitted = (extension) => result.outputFiles
115
+ .filter((file) => file.path.endsWith(extension))
116
+ .map((file) => file.text)
117
+ .join('\n');
118
+ const bundled = { id, js: emitted('.js'), css: emitted('.css'), cwd };
119
+ bundlesById.set(id, bundled);
120
+ return bundled;
121
+ }
122
+ catch (error) {
123
+ bundleCache.delete(key);
124
+ throw explainBundleError(error);
125
+ }
126
+ })();
127
+ bundleCache.set(key, { stamp, bundle: promise });
128
+ return promise;
129
+ }
130
+ // Browser-bundled fast-check + plan + regression runner, built once per process and served at `/__tslaws/fc-runner.js`.
131
+ let fcRunnerPromise;
132
+ function buildFcRunner() {
133
+ if (fcRunnerPromise !== undefined)
134
+ return fcRunnerPromise;
135
+ const dir = fileURLToPath(new URL('.', import.meta.url));
136
+ const ext = import.meta.url.endsWith('.ts') ? '.ts' : '.js';
137
+ const planPath = join(dir, `plan${ext}`);
138
+ const regressionsPath = join(dir, `regressions${ext}`);
139
+ const entry = `
140
+ import * as fc from 'fast-check';
141
+ import { arbitraryOf } from ${JSON.stringify(planPath)};
142
+ import { decodeExample, encodeExample } from ${JSON.stringify(regressionsPath)};
143
+
144
+ window.__runPropertyInBrowser = async (spec) => {
145
+ const generators = spec.plans.map(arbitraryOf);
146
+ const none = generators.length === 0;
147
+ const property = fc.asyncProperty(
148
+ ...(none ? [fc.constant(undefined)] : generators),
149
+ async (...args) => {
150
+ const res = await window.__runLaw(spec.symbol, none ? [] : args, false, 0, true);
151
+ if (res.discarded) {
152
+ fc.pre(false);
153
+ return true;
154
+ }
155
+ if (res.error) {
156
+ const err = new Error(res.error.message);
157
+ err.name = res.error.name || 'Error';
158
+ if (res.error.stack) err.stack = res.error.stack;
159
+ throw err;
160
+ }
161
+ return res.ok !== false;
162
+ },
163
+ );
164
+ const examples = !none && Array.isArray(spec.regressionExamples) && spec.regressionExamples.length > 0
165
+ ? spec.regressionExamples.map(decodeExample)
166
+ : undefined;
167
+ const details = await fc.check(property, {
168
+ numRuns: none ? 1 : spec.runs,
169
+ seed: spec.seed,
170
+ maxSkipsPerRun: 100,
171
+ ...(examples ? { examples } : {}),
172
+ });
173
+ let encoded;
174
+ if (details.failed && details.counterexample !== null) {
175
+ try { encoded = encodeExample(details.counterexample); } catch {}
176
+ }
177
+ const message = details.errorInstance instanceof Error ? details.errorInstance.message : undefined;
178
+ const stack = details.errorInstance instanceof Error ? details.errorInstance.stack : undefined;
179
+ return {
180
+ failed: details.failed,
181
+ numRuns: details.numRuns,
182
+ seed: details.seed,
183
+ counterexample: details.counterexample === null ? undefined : fc.stringify(details.counterexample),
184
+ rawCounterexample: details.failed && details.counterexample !== null ? details.counterexample : undefined,
185
+ encoded,
186
+ regression: encoded !== undefined && Array.isArray(spec.regressionExamples) && spec.regressionExamples.includes(encoded),
187
+ message,
188
+ stack,
189
+ };
190
+ };
191
+ `;
192
+ fcRunnerPromise = bundleWith({
193
+ stdin: { contents: entry, resolveDir: dir, loader: 'ts' },
194
+ bundle: true,
195
+ write: false,
196
+ format: 'iife',
197
+ platform: 'browser',
198
+ target: 'es2022',
199
+ logLevel: 'silent',
200
+ // Stub out node:crypto / node:fs / node:path imported transitively by regressions.ts (only encodeExample/decodeExample are used).
201
+ plugins: [
202
+ {
203
+ name: 'tslaws-node-stubs',
204
+ setup(build) {
205
+ build.onResolve({ filter: /^node:/ }, (args) => ({ path: args.path, namespace: 'node-stub' }));
206
+ build.onLoad({ filter: /.*/, namespace: 'node-stub' }, () => ({
207
+ contents: [
208
+ 'export const createHash = () => ({ update() { return this; }, digest() { return ""; } });',
209
+ 'export const existsSync = () => false;',
210
+ 'export const mkdirSync = () => undefined;',
211
+ 'export const readdirSync = () => [];',
212
+ 'export const readFileSync = () => "";',
213
+ 'export const rmSync = () => undefined;',
214
+ 'export const writeFileSync = () => undefined;',
215
+ 'export const join = (...p) => p.join("/");',
216
+ 'export const posix = { join: (...p) => p.join("/"), normalize: (p) => p };',
217
+ 'export const win32 = { join: (...p) => p.join("\\\\"), normalize: (p) => p };',
218
+ 'export const performance = globalThis.performance;',
219
+ 'export default {};',
220
+ ].join('\n'),
221
+ }));
222
+ },
223
+ },
224
+ ],
225
+ }).then((res) => res.outputFiles[0].text);
226
+ fcRunnerPromise.catch(() => {
227
+ fcRunnerPromise = undefined;
228
+ });
229
+ return fcRunnerPromise;
230
+ }
231
+ // Runs inside the page: clean DOM + storage + mocks before and after each input, revive generated functions.
232
+ export const pageHarnessScript = `
233
+ window.__runLaw = async (name, args, keep, pause, raw) => {
234
+ const clean = async () => {
235
+ for (const undo of (window.__tslawsCleanup || []).splice(0)) {
236
+ try { await undo(); } catch (e) {}
237
+ }
238
+ try { localStorage.clear(); } catch (e) {}
239
+ try { sessionStorage.clear(); } catch (e) {}
240
+ document.body.innerHTML = '';
241
+ if (typeof window.__tslawsBridge === 'function') {
242
+ try { await window.__tslawsBridge({ action: 'resetMocks' }); } catch (e) {}
243
+ }
244
+ };
245
+ const revive = (v) => {
246
+ if (Array.isArray(v)) return v.map(revive);
247
+ if (v && typeof v === 'object') {
248
+ if (Array.isArray(v.$tslawsFn)) {
249
+ const samples = v.$tslawsFn;
250
+ return (...a) => {
251
+ let key = '';
252
+ try { key = JSON.stringify(a) || ''; } catch (e) {}
253
+ let h = 5381;
254
+ for (let i = 0; i < key.length; i++) h = (Math.imul(h, 33) + key.charCodeAt(i)) | 0;
255
+ return samples[(h >>> 0) % samples.length];
256
+ };
257
+ }
258
+ return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, revive(x)]));
259
+ }
260
+ return v;
261
+ };
262
+ await clean();
263
+ try {
264
+ const input = raw ? args : revive(args);
265
+ const result = await window.__lawModule[name](...input);
266
+ return { ok: result !== false };
267
+ } catch (error) {
268
+ if (error && error.name === 'LawDiscard') return { discarded: true };
269
+ return {
270
+ error: {
271
+ name: error && error.name,
272
+ message: error && error.message ? error.message : String(error),
273
+ stack: error && error.stack ? String(error.stack) : undefined,
274
+ },
275
+ };
276
+ } finally {
277
+ if (pause > 0) {
278
+ window.__shown = true;
279
+ await new Promise((done) => setTimeout(done, pause));
280
+ window.__shown = false;
281
+ }
282
+ if (!keep) await clean();
283
+ }
284
+ };
285
+ `;
286
+ const iframeHostHtml = `<!doctype html>
287
+ <html>
288
+ <head><meta charset="utf-8"><title>tslaws runner</title>
289
+ <style>html,body{margin:0;padding:0;width:100%;height:100%;overflow:hidden;}iframe{border:0;width:100%;height:100%;display:block;}</style>
290
+ </head>
291
+ <body>
292
+ <script>
293
+ window.__tslawsMountFrame = (src) => new Promise((resolve, reject) => {
294
+ document.body.innerHTML = '';
295
+ const frame = document.createElement('iframe');
296
+ frame.name = 'tslaws-law-frame';
297
+ frame.onload = () => resolve(true);
298
+ frame.onerror = (e) => reject(e);
299
+ frame.src = src;
300
+ document.body.appendChild(frame);
301
+ });
302
+ </script>
303
+ </body>
304
+ </html>`;
305
+ let server;
306
+ let serverUrl;
307
+ /** Ensures the local HTTP server for browser laws is listening and returns its base URL (`http://127.0.0.1:<port>`). */
308
+ export async function ensureBrowserServer() {
309
+ if (serverUrl !== undefined)
310
+ return serverUrl;
311
+ serverUrl = new Promise((resolveUrl, rejectUrl) => {
312
+ const http = createServer((req, res) => {
313
+ void handleRequest(req, res);
314
+ });
315
+ http.once('error', rejectUrl);
316
+ http.listen(0, '127.0.0.1', () => {
317
+ http.off('error', rejectUrl);
318
+ http.unref();
319
+ server = http;
320
+ const addr = http.address();
321
+ resolveUrl(`http://127.0.0.1:${addr.port}`);
322
+ });
323
+ });
324
+ return serverUrl;
325
+ }
326
+ async function handleRequest(req, res) {
327
+ const url = new URL(req.url ?? '/', 'http://127.0.0.1');
328
+ if (url.pathname === '/__tslaws/host') {
329
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' }).end(iframeHostHtml);
330
+ return;
331
+ }
332
+ if (url.pathname === '/__tslaws/harness.js') {
333
+ res
334
+ .writeHead(200, { 'content-type': 'application/javascript; charset=utf-8', 'cache-control': 'no-store' })
335
+ .end(pageHarnessScript);
336
+ return;
337
+ }
338
+ if (url.pathname === '/__tslaws/fc-runner.js') {
339
+ try {
340
+ const code = await buildFcRunner();
341
+ res
342
+ .writeHead(200, {
343
+ 'content-type': 'application/javascript; charset=utf-8',
344
+ 'cache-control': 'public, max-age=3600',
345
+ })
346
+ .end(code);
347
+ }
348
+ catch (error) {
349
+ res.writeHead(500).end(String(error));
350
+ }
351
+ return;
352
+ }
353
+ if (url.pathname === '/__tslaws/page') {
354
+ const id = url.searchParams.get('id') ?? '';
355
+ const bundle = bundlesById.get(id);
356
+ if (bundle === undefined) {
357
+ res.writeHead(404).end('unknown bundle');
358
+ return;
359
+ }
360
+ const env = JSON.stringify(lawEnv(bundle.cwd, 'browser'));
361
+ const style = bundle.css === '' ? '' : `<link rel="stylesheet" href="/__tslaws/style/${id}.css">`;
362
+ const withFc = url.searchParams.get('fc') === '1' ? '<script src="/__tslaws/fc-runner.js"></script>' : '';
363
+ const html = `<!doctype html><html><head><meta charset="utf-8">${style}<script>globalThis.${importMetaEnvGlobal} = ${env};</script></head><body><script src="/__tslaws/bundle/${id}.js"></script><script src="/__tslaws/harness.js"></script>${withFc}</body></html>`;
364
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' }).end(html);
365
+ return;
366
+ }
367
+ const styleMatch = /^\/__tslaws\/style\/([^/]+)\.css$/.exec(url.pathname);
368
+ if (styleMatch !== null) {
369
+ const bundle = bundlesById.get(styleMatch[1]);
370
+ if (bundle === undefined) {
371
+ res.writeHead(404).end('');
372
+ return;
373
+ }
374
+ res.writeHead(200, { 'content-type': 'text/css; charset=utf-8', 'cache-control': 'no-store' }).end(bundle.css);
375
+ return;
376
+ }
377
+ const bundleMatch = /^\/__tslaws\/bundle\/([^/]+)\.js$/.exec(url.pathname);
378
+ if (bundleMatch !== null) {
379
+ const bundle = bundlesById.get(bundleMatch[1]);
380
+ if (bundle === undefined) {
381
+ res.writeHead(404).end('');
382
+ return;
383
+ }
384
+ res
385
+ .writeHead(200, { 'content-type': 'application/javascript; charset=utf-8', 'cache-control': 'no-store' })
386
+ .end(bundle.js);
387
+ return;
388
+ }
389
+ // Ignore favicon requests silently so the console stays clean.
390
+ if (extname(url.pathname) === '.ico') {
391
+ res.writeHead(204).end();
392
+ return;
393
+ }
394
+ res.writeHead(404).end('not found');
395
+ }
396
+ /** Stops the local browser HTTP server. */
397
+ export async function closeBrowserServer() {
398
+ const http = server;
399
+ server = undefined;
400
+ serverUrl = undefined;
401
+ bundlesById.clear();
402
+ bundleCache.clear();
403
+ if (http !== undefined) {
404
+ await new Promise((done) => http.close(() => done()));
405
+ }
406
+ }
@@ -7,7 +7,7 @@
7
7
  // keeps the status it had. `"certify": "require"` turns anything short of `certified` into an error.
8
8
  import { spawn } from 'node:child_process';
9
9
  import { createHash } from 'node:crypto';
10
- import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
10
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
11
11
  import { tmpdir } from 'node:os';
12
12
  import { dirname, join } from 'node:path';
13
13
  import { certificationProblem } from "./chc.js";
@@ -142,41 +142,63 @@ const aletheRareRules = {
142
142
  ')',
143
143
  ].join('\n'),
144
144
  };
145
+ /** Cached RARE rule database per cvc5 binary (path + args + stat), so `-o rare-db` runs once per binary instead of once per law. */
146
+ const rareDbCache = new Map();
147
+ function rareCacheKey(cvc5) {
148
+ const target = cvc5.args[0] ?? cvc5.file;
149
+ try {
150
+ const st = statSync(target);
151
+ return `${cvc5.file}\0${cvc5.args.join('\0')}\0${st.size}:${st.mtimeMs}`;
152
+ }
153
+ catch {
154
+ return `${cvc5.file}\0${cvc5.args.join('\0')}`;
155
+ }
156
+ }
145
157
  /**
146
158
  * The RARE rule declarations for `names`, in the form Carcara reads. cvc5 itself prints its database of rewrite rules, so
147
159
  * the rules a proof may lean on come from the same binary that wrote the proof and never from a file beside the proof;
148
160
  * the few rules in `aletheRareRules` are the exception, because the binary's own text for them cannot be checked.
149
161
  */
150
162
  export async function rareDeclarations(names, work, budget) {
163
+ // If every requested rule is already covered by the built-in sound overrides, no cvc5 dump is needed.
164
+ if (names.every((name) => aletheRareRules[name] !== undefined)) {
165
+ return { text: `${names.map((name) => aletheRareRules[name]).join('\n')}\n` };
166
+ }
151
167
  const cvc5 = toolCommand('TSLAWS_CVC5', 'cvc5');
152
- const input = join(work, 'rare.smt2');
153
- writeFileSync(input, '(check-sat)\n');
154
- const printed = await run(cvc5.file, [
155
- ...cvc5.args,
156
- '-o',
157
- 'rare-db',
158
- '--force-logic=ALL',
159
- '--produce-proofs',
160
- '--proof-granularity=dsl-rewrite',
161
- '--proof-format-mode=alethe',
162
- input,
163
- ], budget);
164
- if (printed === undefined)
165
- return { status: 'unavailable', reason: cvc5Missing };
166
- if (printed === 'timeout')
167
- return { status: 'uncertified', reason: `cvc5 did not print its rewrite rules within ${budget} ms` };
168
- const blocks = new Map();
169
- let current;
170
- for (const line of printed.stdout.split(/\r?\n/)) {
171
- const start = /^\(declare-rule\s+(\S+)/.exec(line);
172
- if (start !== null)
173
- current = { name: start[1], lines: [] };
174
- if (current !== undefined)
175
- current.lines.push(line);
176
- if (current !== undefined && line === ')') {
177
- blocks.set(current.name, current.lines.join('\n').replace('(declare-rule ', '(declare-rare-rule '));
178
- current = undefined;
168
+ const cacheKey = rareCacheKey(cvc5);
169
+ let blocks = rareDbCache.get(cacheKey);
170
+ if (blocks === undefined) {
171
+ const input = join(work, 'rare.smt2');
172
+ writeFileSync(input, '(check-sat)\n');
173
+ const printed = await run(cvc5.file, [
174
+ ...cvc5.args,
175
+ '-o',
176
+ 'rare-db',
177
+ '--force-logic=ALL',
178
+ '--produce-proofs',
179
+ '--proof-granularity=dsl-rewrite',
180
+ '--proof-format-mode=alethe',
181
+ input,
182
+ ], budget);
183
+ if (printed === undefined)
184
+ return { status: 'unavailable', reason: cvc5Missing };
185
+ if (printed === 'timeout')
186
+ return { status: 'uncertified', reason: `cvc5 did not print its rewrite rules within ${budget} ms` };
187
+ blocks = new Map();
188
+ let current;
189
+ for (const line of printed.stdout.split(/\r?\n/)) {
190
+ const start = /^\(declare-rule\s+(\S+)/.exec(line);
191
+ if (start !== null)
192
+ current = { name: start[1], lines: [] };
193
+ if (current !== undefined)
194
+ current.lines.push(line);
195
+ if (current !== undefined && line === ')') {
196
+ blocks.set(current.name, current.lines.join('\n').replace('(declare-rule ', '(declare-rare-rule '));
197
+ current = undefined;
198
+ }
179
199
  }
200
+ if (blocks.size > 0)
201
+ rareDbCache.set(cacheKey, blocks);
180
202
  }
181
203
  const missing = names.filter((name) => !blocks.has(name) && aletheRareRules[name] === undefined);
182
204
  if (missing.length > 0)
package/dist/chc.js CHANGED
@@ -23,15 +23,38 @@ export class SolverCrash extends Error {
23
23
  const unknown = (reason) => ({ kind: 'unknown', reason });
24
24
  /** Floating point and strings are outside what the CHC engines decide: the unrolled proof handles those. */
25
25
  const unmodelled = /FloatingPoint|\bfp\.|to_fp|\bstr\.|\bString\b|\bre\./;
26
- function expand(text, shared) {
27
- let out = text;
28
- // A shared term may name an earlier one, so expand until nothing is left.
29
- for (let round = 0; round <= shared.size && /\b_s\d+\b/.test(out); round += 1)
30
- out = out.replace(/\b_s\d+\b/g, (name) => shared.get(name) ?? name);
31
- return out;
26
+ /** Wraps `text` in nested SMT-LIB `let` bindings for any `_sN` shared terms it transitively references (DAG-preserving, no exponential blowup). */
27
+ function bindShared(text, shared) {
28
+ if (shared.size === 0 || !/\b_s\d+\b/.test(text))
29
+ return text;
30
+ const needed = new Set();
31
+ const queue = [...text.matchAll(/\b_s\d+\b/g)].map((m) => m[0]);
32
+ while (queue.length > 0) {
33
+ const name = queue.pop();
34
+ if (needed.has(name))
35
+ continue;
36
+ const def = shared.get(name);
37
+ if (def === undefined)
38
+ continue;
39
+ needed.add(name);
40
+ for (const match of def.matchAll(/\b_s\d+\b/g)) {
41
+ if (!needed.has(match[0]))
42
+ queue.push(match[0]);
43
+ }
44
+ }
45
+ if (needed.size === 0)
46
+ return text;
47
+ // Shared terms are created sequentially (`_s0`, `_s1`, ...), so numeric order is guaranteed topological.
48
+ const ordered = [...needed].sort((a, b) => Number(a.slice(2)) - Number(b.slice(2)));
49
+ let wrapped = text;
50
+ for (let i = ordered.length - 1; i >= 0; i -= 1) {
51
+ const name = ordered[i];
52
+ wrapped = `(let ((${name} ${shared.get(name)})) ${wrapped})`;
53
+ }
54
+ return wrapped;
32
55
  }
33
56
  const closed = (system, text) => {
34
- const body = expand(text, system.shared);
57
+ const body = bindShared(text, system.shared);
35
58
  if (system.constants.length === 0)
36
59
  return body;
37
60
  return `(forall (${system.constants.map((c) => `(${c.name} ${c.sort})`).join(' ')}) ${body})`;