tla-ts 0.0.7-dev.bd12468 → 0.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/worker.cjs CHANGED
@@ -18,4 +18,7 @@ to an element in its putative domain.`;var S=class extends b{constructor(){super
18
18
  G))).Worker(e);return r.on(`message`,t),r.on(`error`,n),{postMessage:(e,t)=>r.postMessage(e,t),terminate:()=>void r.terminate()}},J=async()=>typeof globalThis.postMessage==`function`?globalThis:(await import(
19
19
  /* @vite-ignore */
20
20
  /* webpackIgnore: true */
21
- G)).parentPort;Object.defineProperty(exports,"A",{enumerable:!0,get:function(){return j}}),Object.defineProperty(exports,"B",{enumerable:!0,get:function(){return V}}),Object.defineProperty(exports,"C",{enumerable:!0,get:function(){return O}}),Object.defineProperty(exports,"D",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"E",{enumerable:!0,get:function(){return S}}),Object.defineProperty(exports,"F",{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,"G",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"H",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"I",{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,"K",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"L",{enumerable:!0,get:function(){return C}}),Object.defineProperty(exports,"M",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"N",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"O",{enumerable:!0,get:function(){return T}}),Object.defineProperty(exports,"P",{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,"R",{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,"S",{enumerable:!0,get:function(){return E}}),Object.defineProperty(exports,"T",{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,"U",{enumerable:!0,get:function(){return e}}),Object.defineProperty(exports,"V",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"W",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return D}}),Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return W}}),Object.defineProperty(exports,"b",{enumerable:!0,get:function(){return B}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return R}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return I}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return z}}),Object.defineProperty(exports,"g",{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,"h",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return L}}),Object.defineProperty(exports,"j",{enumerable:!0,get:function(){return k}}),Object.defineProperty(exports,"k",{enumerable:!0,get:function(){return N}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return x}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return y}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return K}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return H}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return P}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return q}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return U}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return J}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return F}}),Object.defineProperty(exports,"v",{enumerable:!0,get:function(){return w}}),Object.defineProperty(exports,"w",{enumerable:!0,get:function(){return A}}),Object.defineProperty(exports,"x",{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,"y",{enumerable:!0,get:function(){return M}}),Object.defineProperty(exports,"z",{enumerable:!0,get:function(){return g}});
21
+ G)).parentPort,Y=()=>{let e=`Bun`in globalThis?import(
22
+ /* @vite-ignore */
23
+ /* webpackIgnore: true */
24
+ `bun:jsc`):void 0;return async()=>{(await e)?.edenGC(),await new Promise(e=>typeof setImmediate==`function`?setImmediate(e):setTimeout(e,0))}};Object.defineProperty(exports,"A",{enumerable:!0,get:function(){return N}}),Object.defineProperty(exports,"B",{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,"C",{enumerable:!0,get:function(){return E}}),Object.defineProperty(exports,"D",{enumerable:!0,get:function(){return S}}),Object.defineProperty(exports,"E",{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,"F",{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,"G",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"H",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"I",{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,"K",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"L",{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,"M",{enumerable:!0,get:function(){return k}}),Object.defineProperty(exports,"N",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"O",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"P",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"R",{enumerable:!0,get:function(){return C}}),Object.defineProperty(exports,"S",{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,"T",{enumerable:!0,get:function(){return A}}),Object.defineProperty(exports,"U",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"V",{enumerable:!0,get:function(){return V}}),Object.defineProperty(exports,"W",{enumerable:!0,get:function(){return e}}),Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return L}}),Object.defineProperty(exports,"b",{enumerable:!0,get:function(){return M}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return U}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return F}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return I}}),Object.defineProperty(exports,"g",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"h",{enumerable:!0,get:function(){return y}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return q}}),Object.defineProperty(exports,"j",{enumerable:!0,get:function(){return j}}),Object.defineProperty(exports,"k",{enumerable:!0,get:function(){return T}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return R}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return P}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return J}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return W}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return z}}),Object.defineProperty(exports,"q",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return K}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return H}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return Y}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return x}}),Object.defineProperty(exports,"v",{enumerable:!0,get:function(){return D}}),Object.defineProperty(exports,"w",{enumerable:!0,get:function(){return O}}),Object.defineProperty(exports,"x",{enumerable:!0,get:function(){return B}}),Object.defineProperty(exports,"y",{enumerable:!0,get:function(){return w}}),Object.defineProperty(exports,"z",{enumerable:!0,get:function(){return _}});
package/dist/worker.js CHANGED
@@ -18,4 +18,7 @@ to an element in its putative domain.`;var S=class extends b{constructor(){super
18
18
  G))).Worker(e);return r.on(`message`,t),r.on(`error`,n),{postMessage:(e,t)=>r.postMessage(e,t),terminate:()=>void r.terminate()}},J=async()=>typeof globalThis.postMessage==`function`?globalThis:(await import(
19
19
  /* @vite-ignore */
20
20
  /* webpackIgnore: true */
21
- G)).parentPort;export{j as A,V as B,O as C,d as D,S as E,m as F,n as G,l as H,v as I,a as K,C as L,c as M,s as N,T as O,h as P,_ as R,E as S,f as T,e as U,o as V,r as W,D as _,W as a,B as b,R as c,I as d,z as f,b as g,u as h,L as i,k as j,N as k,x as l,y as m,K as n,H as o,P as p,q as r,U as s,J as t,F as u,w as v,A as w,p as x,M as y,g as z};
21
+ G)).parentPort,Y=()=>{let e=`Bun`in globalThis?import(
22
+ /* @vite-ignore */
23
+ /* webpackIgnore: true */
24
+ `bun:jsc`):void 0;return async()=>{(await e)?.edenGC(),await new Promise(e=>typeof setImmediate==`function`?setImmediate(e):setTimeout(e,0))}};export{N as A,g as B,E as C,S as D,f as E,h as F,r as G,o as H,m as I,n as K,v as L,k as M,c as N,d as O,s as P,C as R,p as S,A as T,l as U,V,e as W,b as _,L as a,M as b,U as c,F as d,I as f,u as g,y as h,q as i,j,T as k,R as l,P as m,J as n,W as o,z as p,a as q,K as r,H as s,Y as t,x as u,D as v,O as w,B as x,w as y,_ as z};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tla-ts",
3
- "version": "0.0.7-dev.bd12468",
3
+ "version": "0.0.8",
4
4
  "description": "A TLA+ interpreter and model checker in TypeScript, 2× faster than TLC",
5
5
  "keywords": [
6
6
  "formal verification",
package/src/check.ts CHANGED
@@ -75,7 +75,7 @@ import {
75
75
  withUnexpectedException,
76
76
  type FailureMessage,
77
77
  } from "./tlc/messages";
78
- import { getTlcStringOrder, getTlcVariableOrder } from "./tlc/order";
78
+ import { createTlcOrder } from "./tlc/order";
79
79
  import { replayInitialStates, replaySuccessors } from "./tlc/replay";
80
80
  import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc/summary";
81
81
  import { createActionRecord, createCounterExample } from "./tlc/tlcext-operators";
@@ -406,11 +406,13 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
406
406
  capturedOutput.lines = outer;
407
407
  }
408
408
  };
409
- setStringOrder(getTlcStringOrder(options.source, config, options.loadModule));
409
+ const order = createTlcOrder(options.source, options.loadModule);
410
+ setStringOrder(order.getStringOrder(config));
410
411
  setValueVersion(options.version);
411
412
  const specification = createEnvironment(config, {
412
413
  source: options.source,
413
414
  loadModule: options.loadModule,
415
+ order,
414
416
  loadClass: options.loadClass,
415
417
  print,
416
418
  files: { readFile: options.readFile, writeFile: options.writeFile },
@@ -482,7 +484,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
482
484
  const search = createSearch(
483
485
  config,
484
486
  environment,
485
- () => getTlcVariableOrder(options.source, options.loadModule),
487
+ () => order.getDeclarationOrder("variable"),
486
488
  options.onProgress,
487
489
  );
488
490
  const findViolatedAssumption = () =>
package/src/codegen.ts CHANGED
@@ -116,6 +116,18 @@ const generatedHelpers = {
116
116
  value: undefined as ReturnType<typeof createGeneratedHelpers> | undefined,
117
117
  };
118
118
 
119
+ const codeGeneration = { isAllowed: undefined as boolean | undefined };
120
+
121
+ // Hosts such as Cloudflare Workers, or a page whose CSP lacks 'unsafe-eval', throw an EvalError.
122
+ const getIsCodeGenerationAllowed = () => {
123
+ try {
124
+ return Boolean(new Function(""));
125
+ } catch (error) {
126
+ if (error instanceof EvalError) return false;
127
+ throw error;
128
+ }
129
+ };
130
+
119
131
  const addReference = (generator: Generator, value: unknown) => {
120
132
  generator.references.push(value);
121
133
  return `reference${generator.references.length - 1}`;
@@ -381,6 +393,8 @@ export const generateEvaluator = (
381
393
  environment: Environment,
382
394
  ): Evaluator | undefined => {
383
395
  if (!GENERATED_KINDS.has(expression.kind)) return undefined;
396
+ codeGeneration.isAllowed ??= getIsCodeGenerationAllowed();
397
+ if (!codeGeneration.isAllowed) return undefined;
384
398
  const generator: Generator = { environment, references: [], helpers: [], counter: 0 };
385
399
  const frame: Frame = {
386
400
  context: "context",
@@ -73,7 +73,7 @@ import { resolveInstanceSubexpressions, resolveModuleSubexpressions } from "./su
73
73
  import { checkModuleLevels, createLevelAnalyzer } from "./levels";
74
74
  import { createInstanceChecker, type InstanceCheck } from "./substitution-levels";
75
75
  import { isEvalException } from "./tlc/messages";
76
- import { createTlcDefinitionOrder, getTlcDeclarationOrder } from "./tlc/order";
76
+ import { createTlcOrder, type TlcOrder } from "./tlc/order";
77
77
  import {
78
78
  isTlcInteger,
79
79
  createModelValue,
@@ -88,6 +88,8 @@ import type { TlcVersion } from "./tlc/version";
88
88
  interface EnvironmentOptions {
89
89
  source: string;
90
90
  loadModule: ((name: string) => string | undefined) | undefined;
91
+ // The TLC orders of the same spec, when the caller already reads them.
92
+ order?: TlcOrder;
91
93
  loadClass?: (name: string) => Uint8Array | undefined;
92
94
  print: (text: string) => void;
93
95
  files: FileSystem;
@@ -299,7 +301,8 @@ export const createEnvironment = (
299
301
  config: ModelConfig,
300
302
  options: EnvironmentOptions,
301
303
  ): Specification => {
302
- const root = parseModule(options.source);
304
+ const order = options.order ?? createTlcOrder(options.source, options.loadModule);
305
+ const root = order.getRootModule();
303
306
  const definitions = new Map<string, Definition>();
304
307
  const parameterized = new Map<string, boolean>();
305
308
  // The definition each instance copy came from, and the instance parameters the copy adds.
@@ -1222,9 +1225,8 @@ export const createEnvironment = (
1222
1225
  if (unassigned.length > 0 && !options.isUnconfigured) {
1223
1226
  // TLC reports the first constant it finds unassigned in SANY's order of declarations.
1224
1227
  const name =
1225
- getTlcDeclarationOrder(options.source, options.loadModule, "constant").find((constant) =>
1226
- unassigned.includes(constant),
1227
- ) ?? unassigned[0];
1228
+ order.getDeclarationOrder("constant").find((constant) => unassigned.includes(constant)) ??
1229
+ unassigned[0];
1228
1230
  throw new TlaConfigError(
1229
1231
  `The constant parameter ${name} is not assigned a value by the configuration file.`,
1230
1232
  );
@@ -1298,7 +1300,7 @@ export const createEnvironment = (
1298
1300
  const instantiated = new Set(
1299
1301
  linkOrder.flatMap((linked) => linked.module.instances.map((instance) => instance.module)),
1300
1302
  );
1301
- const getDefinitionOrder = createTlcDefinitionOrder(options.source, options.loadModule);
1303
+ const getDefinitionOrder = order.createDefinitionOrder();
1302
1304
  return {
1303
1305
  environment,
1304
1306
  assumptions,
@@ -8,7 +8,7 @@ import {
8
8
  import type { CoordinatorMessage, LevelMessage, StartMessage, WorkerMessage } from "./parallel";
9
9
  import { createSearch } from "./search";
10
10
  import { getSuccessors, type Successor } from "./successors";
11
- import { getTlcStringOrder, getTlcVariableOrder } from "./tlc/order";
11
+ import { createTlcOrder } from "./tlc/order";
12
12
  import { OUT_DEGREE_BUCKETS } from "./tlc/summary";
13
13
  import { createStateDecoder, createStateEncoder, type EncodedStates } from "./transfer";
14
14
  import {
@@ -18,9 +18,10 @@ import {
18
18
  setValueVersion,
19
19
  type Value,
20
20
  } from "./values";
21
- import { getParentPort, type Port } from "./worker";
21
+ import { createBreak, getParentPort, type Port } from "./worker";
22
22
 
23
23
  const LOCKED = -1;
24
+ const BREAK_INTERVAL = 100;
24
25
 
25
26
  interface Expansion {
26
27
  states: Value[][];
@@ -33,18 +34,21 @@ interface Expansion {
33
34
  outDegrees: number[];
34
35
  next: Value[][];
35
36
  fingerprintStates: Value[][];
37
+ breakAt: number;
36
38
  }
37
39
 
38
40
  const runWorker = (start: StartMessage, parent: Port) => {
39
41
  const modules = new Map(start.modules);
40
42
  const loadModule = (name: string) => modules.get(name);
41
43
  const classes = new Map(start.classes);
42
- setStringOrder(getTlcStringOrder(start.source, start.config, loadModule));
44
+ const order = createTlcOrder(start.source, loadModule);
45
+ setStringOrder(order.getStringOrder(start.config));
43
46
  setValueVersion(start.version);
44
47
  const startupStrings = getRankedStringCount();
45
48
  const specification = createEnvironment(start.config, {
46
49
  source: start.source,
47
50
  loadModule,
51
+ order,
48
52
  loadClass: (name) => classes.get(name),
49
53
  print: () => {},
50
54
  files: { readFile: undefined, writeFile: undefined },
@@ -55,7 +59,7 @@ const runWorker = (start: StartMessage, parent: Port) => {
55
59
  });
56
60
  const environment = specification.environment;
57
61
  const search = createSearch(start.config, environment, () =>
58
- getTlcVariableOrder(start.source, loadModule),
62
+ order.getDeclarationOrder("variable"),
59
63
  );
60
64
  const nextAction = search?.spec.next;
61
65
  if (!search || nextAction === undefined)
@@ -76,6 +80,7 @@ const runWorker = (start: StartMessage, parent: Port) => {
76
80
  port?.start?.();
77
81
  });
78
82
  const frontier = { states: decode(start.seed).map(canonicalize) };
83
+ const takeBreak = createBreak();
79
84
 
80
85
  // A worker that runs out of states asks a peer for some by writing its index + 1 to the peer's
81
86
  // request word. The peer sends half of the states it hasn't started, keeps expanding, and wakes
@@ -111,6 +116,7 @@ const runWorker = (start: StartMessage, parent: Port) => {
111
116
  for (; expansion.origin < expansion.end; expansion.origin++) {
112
117
  const state = expansion.states[expansion.origin];
113
118
  if (!expansion.successors) {
119
+ if (performance.now() >= expansion.breakAt) return "break";
114
120
  if (Atomics.load(requests, workerIndex) > 0) answerRequest(expansion, 0);
115
121
  Atomics.store(remaining, workerIndex, expansion.end - expansion.origin - 1);
116
122
  expansion.successors = getSuccessors(nextAction, state, environment, search.spec.scope);
@@ -194,10 +200,18 @@ const runWorker = (start: StartMessage, parent: Port) => {
194
200
  outDegrees: Array.from({ length: OUT_DEGREE_BUCKETS }, () => 0),
195
201
  next: [],
196
202
  fingerprintStates: [],
203
+ breakAt: performance.now() + BREAK_INTERVAL,
197
204
  };
198
205
  for (;;) {
199
206
  const status = expand(expansion);
200
207
  if (status === undefined) return undefined;
208
+ // HACK: Bun runs its garbage collection timers on the event loop, so a worker that expands a
209
+ // long level without returning to the loop holds on to memory it no longer uses.
210
+ if (status === "break") {
211
+ await takeBreak();
212
+ expansion.breakAt = performance.now() + BREAK_INTERVAL;
213
+ continue;
214
+ }
201
215
  lockRequests(expansion);
202
216
  if (status === "paused") {
203
217
  const resumed = new Promise<void>((resolve) => (waiters.resume = resolve));
package/src/parallel.ts CHANGED
@@ -25,7 +25,7 @@ import {
25
25
  reportStartup,
26
26
  } from "./search";
27
27
  import { getInitialStates } from "./successors";
28
- import { getTlcStringOrder, getTlcVariableOrder } from "./tlc/order";
28
+ import { createTlcOrder } from "./tlc/order";
29
29
  import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc/summary";
30
30
  import { createStateEncoder, type EncodedStates } from "./transfer";
31
31
  import type { TlcVersion } from "./tlc/version";
@@ -130,12 +130,14 @@ export const check = async (options: CheckOptions): Promise<CheckResult> => {
130
130
  classes.set(name, bytes);
131
131
  return bytes;
132
132
  };
133
- setStringOrder(getTlcStringOrder(options.source, config, loadModule));
133
+ const order = createTlcOrder(options.source, loadModule);
134
+ setStringOrder(order.getStringOrder(config));
134
135
  setValueVersion(options.version);
135
136
  const startupStrings = getRankedStringCount();
136
137
  const specification = createEnvironment(config, {
137
138
  source: options.source,
138
139
  loadModule,
140
+ order,
139
141
  loadClass,
140
142
  print: (text) => {
141
143
  printed.count++;
@@ -153,7 +155,7 @@ export const check = async (options: CheckOptions): Promise<CheckResult> => {
153
155
  const search = createSearch(
154
156
  config,
155
157
  environment,
156
- () => getTlcVariableOrder(options.source, loadModule),
158
+ () => order.getDeclarationOrder("variable"),
157
159
  report,
158
160
  );
159
161
  if (findAssumptionViolation(specification.assumptions, environment)) return fallBack();
package/src/parser.ts CHANGED
@@ -347,9 +347,9 @@ export const extractModule = (source: string, name: string) => {
347
347
  // generator.
348
348
  type ParseMode = "tlc" | "tlapm" | "sany";
349
349
 
350
- const parse = (source: string, mode: ParseMode): Module => {
350
+ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source)): Module => {
351
351
  const isTlapm = mode === "tlapm";
352
- const tokens = isTlapm ? tokenize(source) : tokenize(source).map(readAtAsIdentifier);
352
+ const tokens = isTlapm ? sourceTokens : sourceTokens.map(readAtAsIdentifier);
353
353
  const cursor = { index: 0, offsideColumns: [] as number[] };
354
354
  const operators: OperatorContext = {};
355
355
  // A RECURSIVE declaration covers the definitions of its own LET or module.
@@ -2102,6 +2102,9 @@ const parse = (source: string, mode: ParseMode): Module => {
2102
2102
 
2103
2103
  export const parseModule = (source: string) => parse(source, "tlc");
2104
2104
 
2105
+ // Parses a module the caller has tokenized already.
2106
+ export const parseModuleTokens = (source: string, tokens: Token[]) => parse(source, "tlc", tokens);
2107
+
2105
2108
  export const parseTlapmModule = (source: string) => parse(source, "tlapm");
2106
2109
 
2107
2110
  export const parseSanyModule = (source: string) => parse(source, "sany");
package/src/tlc/order.ts CHANGED
@@ -4,7 +4,7 @@ import type { Module, SourceLocation } from "../ast";
4
4
  import type { ConfigValue, ModelConfig } from "../config";
5
5
  import { createMissingModuleError } from "../errors";
6
6
  import { tokenize, type Token } from "../lexer";
7
- import { extractModule, parseModule } from "../parser";
7
+ import { extractModule, parseModule, parseModuleTokens } from "../parser";
8
8
  import { isBefore } from "../resolve";
9
9
  import {
10
10
  SANY_BUILTINS,
@@ -21,6 +21,7 @@ type SymbolKind = "builtin" | "constant" | "variable" | "definition" | "theorem"
21
21
  interface SymbolEntry {
22
22
  key: string;
23
23
  name: string;
24
+ hash: number;
24
25
  kind: SymbolKind;
25
26
  isLocal: boolean;
26
27
  }
@@ -28,6 +29,8 @@ interface SymbolEntry {
28
29
  interface SymbolTable {
29
30
  put: (entry: SymbolEntry) => void;
30
31
  inserted: SymbolEntry[];
32
+ // Where the entries the module adds itself start, after those of the modules it extends.
33
+ ownStart: number;
31
34
  enumerate: () => SymbolEntry[];
32
35
  }
33
36
 
@@ -35,6 +38,7 @@ interface ParsedModule {
35
38
  tokens: Token[];
36
39
  start: number;
37
40
  end: number;
41
+ isTlcSource: boolean;
38
42
  getModule: () => Module;
39
43
  }
40
44
 
@@ -64,38 +68,48 @@ const getJavaHash = (text: string) => {
64
68
  };
65
69
 
66
70
  // java.util.Hashtable as SANY's Context uses it: default capacity 11, load factor 0.75, new
67
- // entries at the head of their bucket, and enumeration from the last bucket to the first.
71
+ // entries at the head of their bucket, and enumeration from the last bucket to the first. Each
72
+ // bucket lists its entries from tail to head, so a new entry goes at the end.
68
73
  const createSymbolTable = (): SymbolTable => {
69
- const table = { buckets: Array.from({ length: 11 }, (): SymbolEntry[] => []), threshold: 8 };
74
+ let buckets: SymbolEntry[][] = Array.from({ length: 11 }, () => []);
75
+ let threshold = 8;
70
76
  const keys = new Set<string>();
71
77
  const inserted: SymbolEntry[] = [];
72
- const getBucket = (entry: SymbolEntry, capacity: number) =>
73
- (getJavaHash(entry.name) & 0x7fffffff) % capacity;
74
- const rehash = () => {
75
- const capacity = table.buckets.length * 2 + 1;
76
- const buckets = Array.from({ length: capacity }, (): SymbolEntry[] => []);
77
- for (let index = table.buckets.length - 1; index >= 0; index--) {
78
- for (const entry of table.buckets[index]) buckets[getBucket(entry, capacity)].unshift(entry);
78
+ const forEachEntry = (visit: (entry: SymbolEntry) => void) => {
79
+ for (let index = buckets.length - 1; index >= 0; index--) {
80
+ const bucket = buckets[index];
81
+ for (let position = bucket.length - 1; position >= 0; position--) visit(bucket[position]);
79
82
  }
80
- table.buckets = buckets;
81
- table.threshold = Math.floor(capacity * 0.75);
83
+ };
84
+ const rehash = () => {
85
+ const capacity = buckets.length * 2 + 1;
86
+ const rehashed: SymbolEntry[][] = Array.from({ length: capacity }, () => []);
87
+ forEachEntry((entry) => rehashed[entry.hash % capacity].push(entry));
88
+ buckets = rehashed;
89
+ threshold = Math.floor(capacity * 0.75);
82
90
  };
83
91
  return {
84
92
  put: (entry) => {
85
93
  if (keys.has(entry.key)) return;
86
- if (inserted.length >= table.threshold) rehash();
87
- table.buckets[getBucket(entry, table.buckets.length)].unshift(entry);
94
+ if (inserted.length >= threshold) rehash();
95
+ buckets[entry.hash % buckets.length].push(entry);
88
96
  keys.add(entry.key);
89
97
  inserted.push(entry);
90
98
  },
91
99
  inserted,
92
- enumerate: () => table.buckets.toReversed().flat(),
100
+ ownStart: 0,
101
+ enumerate: () => {
102
+ const entries: SymbolEntry[] = [];
103
+ forEachEntry((entry) => entries.push(entry));
104
+ return entries;
105
+ },
93
106
  };
94
107
  };
95
108
 
96
- const createEntry = (name: string, kind: SymbolKind, isLocal: boolean) => ({
109
+ const createEntry = (name: string, kind: SymbolKind, isLocal: boolean): SymbolEntry => ({
97
110
  key: kind === "module" ? `module ${name}` : name,
98
111
  name,
112
+ hash: getJavaHash(name) & 0x7fffffff,
99
113
  kind,
100
114
  isLocal,
101
115
  });
@@ -248,6 +262,34 @@ const findModule = (modules: Module[], name: string): Module | undefined =>
248
262
  modules.find((module) => module.name === name) ??
249
263
  modules.map((module) => findModule(module.modules, name)).find(Boolean);
250
264
 
265
+ interface ModuleText {
266
+ tokens: Token[];
267
+ ranges: Map<string, { start: number; end: number }>;
268
+ getModule: () => Module;
269
+ }
270
+
271
+ const readModuleText = (text: string | undefined): ModuleText => {
272
+ const tokens = text === undefined ? [] : tokenize(text);
273
+ const parsed = { module: undefined as Module | undefined };
274
+ return {
275
+ tokens,
276
+ ranges: getRanges(tokens),
277
+ getModule: () =>
278
+ (parsed.module ??= text === undefined ? parseModule("") : parseModuleTokens(text, tokens)),
279
+ };
280
+ };
281
+
282
+ // TLC's own module sources never change, so every check shares their tokens and parse.
283
+ const tlcModuleTexts = new Map<string, ModuleText>();
284
+
285
+ const getTlcModuleText = (name: string, text: string): ModuleText => {
286
+ const known = tlcModuleTexts.get(name);
287
+ if (known) return known;
288
+ const read = readModuleText(text);
289
+ tlcModuleTexts.set(name, read);
290
+ return read;
291
+ };
292
+
251
293
  // The modules TLC reads for a spec: the root module, TLC's standard modules, the files the loader
252
294
  // returns, the modules that follow the root module, and the modules nested in any of these. A
253
295
  // module without a source has no tokens.
@@ -264,21 +306,20 @@ const createModuleSet = (source: string, loadModule: ModuleLoader) => {
264
306
  TLC_MODULE_SOURCES.get(name) ??
265
307
  loadModule?.(name) ??
266
308
  extractModule(source, name));
267
- const tokens = text === undefined ? [] : tokenize(text);
268
- const ranges = getRanges(tokens);
309
+ const isTlcSource =
310
+ name !== undefined && text !== undefined && text === TLC_MODULE_SOURCES.get(name);
311
+ const { tokens, ranges, getModule } = isTlcSource
312
+ ? getTlcModuleText(name, text)
313
+ : readModuleText(text);
269
314
  const range = ranges.get(getModuleName(tokens) ?? "") ?? { start: 0, end: 0 };
270
- const parsed = { module: undefined as Module | undefined };
271
- const file = {
272
- tokens,
273
- ...range,
274
- getModule: () => (parsed.module ??= parseModule(text ?? "")),
275
- };
315
+ const file = { tokens, ...range, isTlcSource, getModule };
276
316
  files.set(name ?? "", file);
277
317
  ranges.forEach((nestedRange, nestedName) => {
278
318
  if (nestedRange.start === range.start || nestedModules.has(nestedName)) return;
279
319
  nestedModules.set(nestedName, {
280
320
  tokens,
281
321
  ...nestedRange,
322
+ isTlcSource: false,
282
323
  getModule: () => findModule(file.getModule().modules, nestedName) ?? file.getModule(),
283
324
  });
284
325
  });
@@ -290,8 +331,27 @@ const createModuleSet = (source: string, loadModule: ModuleLoader) => {
290
331
  };
291
332
 
292
333
  // SANY's Context of each module, which the root module has under undefined.
293
- const createContexts = (source: string, loadModule: ModuleLoader) => {
294
- const getParsed = createModuleSet(source, loadModule);
334
+ type ModuleSet = ReturnType<typeof createModuleSet>;
335
+
336
+ // The Context of one of TLC's own modules is the same in every check when every module it extends
337
+ // or instantiates is also TLC's own.
338
+ const tlcContexts = new Map<string, SymbolTable>();
339
+
340
+ const createContexts = (getParsed: ModuleSet) => {
341
+ const sharedModules = new Map<string, boolean>();
342
+ const isShared = (name: string): boolean => {
343
+ const known = sharedModules.get(name);
344
+ if (known !== undefined) return known;
345
+ sharedModules.set(name, false);
346
+ const unit = getParsed(name);
347
+ const module = unit.isTlcSource ? unit.getModule() : undefined;
348
+ const shared =
349
+ module !== undefined &&
350
+ module.extends.every((extended) => isShared(extended)) &&
351
+ module.instances.every((instance) => isShared(instance.module));
352
+ sharedModules.set(name, shared);
353
+ return shared;
354
+ };
295
355
  const getUnits = (unit: ParsedModule) => {
296
356
  const tokens = unit.tokens;
297
357
  const module = unit.getModule();
@@ -391,10 +451,9 @@ const createContexts = (source: string, loadModule: ModuleLoader) => {
391
451
  };
392
452
 
393
453
  const contexts = new Map<string, SymbolTable>();
394
- // Where the entries a module adds itself start, after those of the modules it extends.
395
- const ownStarts = new Map<SymbolTable, number>();
396
454
  const getContext = (name: string | undefined): SymbolTable => {
397
- const cached = contexts.get(name ?? "");
455
+ const isTlcContext = name !== undefined && isShared(name);
456
+ const cached = contexts.get(name ?? "") ?? (isTlcContext ? tlcContexts.get(name) : undefined);
398
457
  if (cached) return cached;
399
458
  const table = createSymbolTable();
400
459
  contexts.set(name ?? "", table);
@@ -407,62 +466,24 @@ const createContexts = (source: string, loadModule: ModuleLoader) => {
407
466
  if (!entry.isLocal) table.put(entry);
408
467
  }),
409
468
  );
410
- ownStarts.set(table, table.inserted.length);
469
+ table.ownStart = table.inserted.length;
411
470
  getUnits(unit).forEach((item) => item.apply(table));
471
+ if (isTlcContext) tlcContexts.set(name, table);
412
472
  return table;
413
473
  };
414
474
  return {
415
475
  getContext,
416
476
  getOwnEntries: (name: string | undefined) => {
417
477
  const table = getContext(name);
418
- return table.inserted.slice(ownStarts.get(table));
478
+ return table.inserted.slice(table.ownStart);
419
479
  },
420
480
  };
421
481
  };
422
482
 
423
- // The variables or constants of the root module in the reverse of its context enumeration, as
424
- // ModuleNode.getVariableDecls and getConstantDecls return them. TLC compares variables in this
425
- // order, and checks that the configuration assigns each constant in it.
426
- export const getTlcDeclarationOrder = (
427
- source: string,
428
- loadModule: ModuleLoader,
429
- kind: "variable" | "constant",
430
- ): string[] =>
431
- createContexts(source, loadModule)
432
- .getContext(undefined)
433
- .enumerate()
434
- .filter((entry) => entry.kind === kind)
435
- .map((entry) => entry.name)
436
- .reverse();
437
-
438
- // The names of the definitions each module adds to its context, in the order of
439
- // ModuleNode.getOpDefs, in which TLC computes the constant definitions as it starts. An INSTANCE
440
- // adds the definitions of the module it instantiates in the order that module's Hashtable
441
- // enumerates them.
442
- export const createTlcDefinitionOrder = (source: string, loadModule: ModuleLoader) => {
443
- const contexts = createContexts(source, loadModule);
444
- // The root module's context reads every file of the spec, and so finds the modules nested in
445
- // the files it extends or instantiates.
446
- contexts.getContext(undefined);
447
- return (name: string | undefined) =>
448
- contexts
449
- .getOwnEntries(name)
450
- .filter((entry) => entry.kind === "definition")
451
- .map((entry) => entry.name);
452
- };
453
-
454
- export const getTlcVariableOrder = (source: string, loadModule: ModuleLoader) =>
455
- getTlcDeclarationOrder(source, loadModule, "variable");
456
-
457
483
  // Every string TLC interns before model checking starts, in order: values in the config, TLC's
458
484
  // startup strings, each module's tokens in the order SpecObj.loadSpec parses the modules, string
459
485
  // literals in semantic analysis order, and the names TLC interns for TLCGet.
460
- export const getTlcStringOrder = (
461
- source: string,
462
- config: ModelConfig,
463
- loadModule: ModuleLoader,
464
- ): string[] => {
465
- const getParsed = createModuleSet(source, loadModule);
486
+ const getStringOrder = (getParsed: ModuleSet, config: ModelConfig): string[] => {
466
487
  const order = new Set<string>();
467
488
  const intern = (text: string) => {
468
489
  order.add(text);
@@ -563,3 +584,48 @@ export const getTlcStringOrder = (
563
584
  TLC_RUNTIME_STRINGS.forEach(intern);
564
585
  return [...order];
565
586
  };
587
+
588
+ export interface TlcOrder {
589
+ // The root module, parsed once for the order and the environment.
590
+ getRootModule: () => Module;
591
+ // Every string TLC interns before model checking starts.
592
+ getStringOrder: (config: ModelConfig) => string[];
593
+ // The variables or constants of the root module in the reverse of its context enumeration, as
594
+ // ModuleNode.getVariableDecls and getConstantDecls return them. TLC compares variables in this
595
+ // order, and checks that the configuration assigns each constant in it.
596
+ getDeclarationOrder: (kind: "variable" | "constant") => string[];
597
+ // The names of the definitions each module adds to its context, in the order of
598
+ // ModuleNode.getOpDefs, in which TLC computes the constant definitions as it starts. An INSTANCE
599
+ // adds the definitions of the module it instantiates in the order that module's Hashtable
600
+ // enumerates them.
601
+ createDefinitionOrder: () => (name: string | undefined) => string[];
602
+ }
603
+
604
+ // One check reads the spec's modules once, and every order shares their tokens, parses and
605
+ // contexts.
606
+ export const createTlcOrder = (source: string, loadModule: ModuleLoader): TlcOrder => {
607
+ const getParsed = createModuleSet(source, loadModule);
608
+ let contexts: ReturnType<typeof createContexts> | undefined;
609
+ const getContexts = () => (contexts ??= createContexts(getParsed));
610
+ return {
611
+ getRootModule: () => getParsed(undefined).getModule(),
612
+ getStringOrder: (config) => getStringOrder(getParsed, config),
613
+ getDeclarationOrder: (kind) =>
614
+ getContexts()
615
+ .getContext(undefined)
616
+ .enumerate()
617
+ .filter((entry) => entry.kind === kind)
618
+ .map((entry) => entry.name)
619
+ .reverse(),
620
+ createDefinitionOrder: () => {
621
+ const { getContext, getOwnEntries } = getContexts();
622
+ // The root module's context reads every file of the spec, and so finds the modules nested
623
+ // in the files it extends or instantiates.
624
+ getContext(undefined);
625
+ return (name) =>
626
+ getOwnEntries(name)
627
+ .filter((entry) => entry.kind === "definition")
628
+ .map((entry) => entry.name);
629
+ },
630
+ };
631
+ };
package/src/worker.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  // Worker threads as Web Workers, or as Node's worker_threads where there are none.
2
2
 
3
3
  const WORKER_THREADS_MODULE = "node:worker_threads";
4
+ const BUN_JSC_MODULE = "bun:jsc";
4
5
 
5
6
  export interface Port {
6
7
  postMessage: (message: unknown, transfer?: unknown[]) => void;
@@ -60,3 +61,18 @@ export const getParentPort = async () => {
60
61
  );
61
62
  return threads.parentPort as unknown as Port;
62
63
  };
64
+
65
+ // A break runs an eden collection on Bun, then lets the event loop turn, where JavaScriptCore's
66
+ // timers give back the memory the collection freed.
67
+ export const createBreak = () => {
68
+ const jsc: Promise<{ edenGC: () => void }> | undefined =
69
+ "Bun" in globalThis
70
+ ? import(/* @vite-ignore */ /* webpackIgnore: true */ BUN_JSC_MODULE)
71
+ : undefined;
72
+ return async () => {
73
+ (await jsc)?.edenGC();
74
+ await new Promise((resolve) =>
75
+ typeof setImmediate === "function" ? setImmediate(resolve) : setTimeout(resolve, 0),
76
+ );
77
+ };
78
+ };