tla-ts 0.0.7-dev.bd12468 → 0.0.8-dev.aa7b562

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/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
+ };