tla-ts 0.0.7 → 0.0.8-dev.d9bffda

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/lexer.ts CHANGED
@@ -314,8 +314,6 @@ const UNICODE_OPERATORS = new Map([
314
314
  ["≀", "\\wr"],
315
315
  ]);
316
316
 
317
- const BASED_NUMBER = /^\\([bB][01]+|[oO][0-7]+|[hH][0-9a-fA-F]+)/;
318
-
319
317
  const NUMBER_BASES = new Map([
320
318
  ["b", 2],
321
319
  ["o", 8],
@@ -330,17 +328,91 @@ export const getNumeralValue = (text: string) =>
330
328
 
331
329
  const MODULE_HEADER = /-{4,}[ \t]*MODULE\b/;
332
330
 
333
- const isIdentifierCharacter = (character: string) => /[A-Za-z0-9_]/.test(character);
331
+ const CODE_TAB = 9;
332
+ const CODE_NEWLINE = 10;
333
+ const CODE_RETURN = 13;
334
+ const CODE_SPACE = 32;
335
+ const CODE_QUOTE = 34;
336
+ const CODE_OPEN_PAREN = 40;
337
+ const CODE_STAR = 42;
338
+ const CODE_DASH = 45;
339
+ const CODE_DOT = 46;
340
+ const CODE_LESS_THAN = 60;
341
+ const CODE_EQUALS = 61;
342
+ const CODE_BACKSLASH = 92;
343
+ const CODE_UNDERSCORE = 95;
344
+
345
+ const DIGIT = 1;
346
+ const LETTER = 2;
347
+ const UNDERSCORE = 4;
348
+ const BINARY_DIGIT = 8;
349
+ const OCTAL_DIGIT = 16;
350
+ const HEX_DIGIT = 32;
351
+ const IDENTIFIER = DIGIT | LETTER | UNDERSCORE;
352
+
353
+ const LOWERCASE = "abcdefghijklmnopqrstuvwxyz";
354
+
355
+ // The classes each ASCII character belongs to, as a bit each.
356
+ const CHARACTER_CLASSES = new Uint8Array(128);
357
+ new Map([
358
+ ["0123456789", DIGIT | HEX_DIGIT],
359
+ [LOWERCASE + LOWERCASE.toUpperCase(), LETTER],
360
+ ["_", UNDERSCORE],
361
+ ["01", BINARY_DIGIT],
362
+ ["01234567", OCTAL_DIGIT],
363
+ ["abcdefABCDEF", HEX_DIGIT],
364
+ ]).forEach((characterClass, characters) => {
365
+ for (const character of characters) {
366
+ CHARACTER_CLASSES[character.charCodeAt(0)] |= characterClass;
367
+ }
368
+ });
369
+
370
+ // charCodeAt past the end of a source gives NaN, which is in no class.
371
+ const isInClass = (code: number, characterClass: number) =>
372
+ code < 128 && (CHARACTER_CLASSES[code] & characterClass) !== 0;
373
+
374
+ const skipClass = (source: string, index: number, characterClass: number) => {
375
+ let end = index;
376
+ while (isInClass(source.charCodeAt(end), characterClass)) end++;
377
+ return end;
378
+ };
334
379
 
335
380
  interface OperatorMatch {
336
381
  text: string;
337
382
  length: number;
338
383
  }
339
384
 
385
+ // The symbol operators that start with each character, in the order of SYMBOL_OPERATORS, which
386
+ // lists a longer operator before the operators it starts with.
387
+ const SYMBOL_OPERATORS_BY_START = new Map<number, string[]>();
388
+ SYMBOL_OPERATORS.forEach((symbol) => {
389
+ const start = symbol.charCodeAt(0);
390
+ const candidates = SYMBOL_OPERATORS_BY_START.get(start) ?? [];
391
+ candidates.push(symbol);
392
+ SYMBOL_OPERATORS_BY_START.set(start, candidates);
393
+ });
394
+
395
+ const matchSymbolOperator = (source: string, index: number) => {
396
+ const candidates = SYMBOL_OPERATORS_BY_START.get(source.charCodeAt(index));
397
+ if (candidates === undefined) return undefined;
398
+ for (let position = 0; position < candidates.length; position++) {
399
+ if (source.startsWith(candidates[position], index)) return candidates[position];
400
+ }
401
+ return undefined;
402
+ };
403
+
404
+ const matchUnicodeOperator = (source: string, index: number) => {
405
+ if (source.charCodeAt(index) < 128) return undefined;
406
+ const pair = source.slice(index, index + 2);
407
+ if (UNICODE_OPERATORS.has(pair)) return pair;
408
+ const single = source[index];
409
+ return UNICODE_OPERATORS.has(single) ? single : undefined;
410
+ };
411
+
340
412
  export const matchOperator = (source: string, index: number): OperatorMatch | undefined => {
341
- const character = source[index];
342
- if (character === "\\" && /[A-Za-z]/.test(source[index + 1] ?? "")) {
343
- const word = /^[A-Za-z]+/.exec(source.slice(index + 1))?.[0] ?? "";
413
+ const code = source.charCodeAt(index);
414
+ if (code === CODE_BACKSLASH && isInClass(source.charCodeAt(index + 1), LETTER)) {
415
+ const word = source.slice(index + 1, skipClass(source, index + 1, LETTER));
344
416
  // Like SANY, read the longest operator that the word starts with, so S\used is S \ used.
345
417
  const length = { value: word.length };
346
418
  while (length.value > 0 && !BACKSLASH_OPERATORS.has(word.slice(0, length.value))) {
@@ -349,15 +421,13 @@ export const matchOperator = (source: string, index: number): OperatorMatch | un
349
421
  const operator = BACKSLASH_OPERATORS.get(word.slice(0, length.value));
350
422
  return { text: operator ?? "\\", length: operator === undefined ? 1 : length.value + 1 };
351
423
  }
352
- const unicodeSymbol = [source.slice(index, index + 2), character].find((candidate) =>
353
- UNICODE_OPERATORS.has(candidate),
354
- );
424
+ const unicodeSymbol = matchUnicodeOperator(source, index);
355
425
  if (unicodeSymbol !== undefined) {
356
426
  return { text: UNICODE_OPERATORS.get(unicodeSymbol) ?? "", length: unicodeSymbol.length };
357
427
  }
358
- const symbol = SYMBOL_OPERATORS.find((candidate) => source.startsWith(candidate, index));
428
+ const symbol = matchSymbolOperator(source, index);
359
429
  if (symbol) return { text: SYMBOL_ALIASES.get(symbol) ?? symbol, length: symbol.length };
360
- return character === "\\" ? { text: "\\", length: 1 } : undefined;
430
+ return code === CODE_BACKSLASH ? { text: "\\", length: 1 } : undefined;
361
431
  };
362
432
 
363
433
  // TLC's configuration parser reads its tokens with SANY's lexer, so it reads a Unicode operator, or
@@ -370,9 +440,6 @@ export const matchUnicodeToken = (source: string, index: number): OperatorMatch
370
440
  return token === undefined ? undefined : { text: token, length: token.length };
371
441
  };
372
442
 
373
- const isDigit = (character: string | undefined) =>
374
- character !== undefined && character >= "0" && character <= "9";
375
-
376
443
  export const skipWhile = (
377
444
  source: string,
378
445
  index: number,
@@ -386,11 +453,10 @@ export const skipWhile = (
386
453
  // The length of a step number such as <1>a., <+>, or <2>*., which SANY reads as one token wherever
387
454
  // it appears.
388
455
  const matchStep = (source: string, index: number) => {
389
- if (source[index] !== "<") return 0;
390
456
  const isImplicit = source[index + 1] === "+" || source[index + 1] === "*";
391
- const levelEnd = isImplicit ? index + 2 : skipWhile(source, index + 1, isDigit);
457
+ const levelEnd = isImplicit ? index + 2 : skipClass(source, index + 1, DIGIT);
392
458
  if (levelEnd === index + 1 || source[levelEnd] !== ">") return 0;
393
- const nameEnd = skipWhile(source, levelEnd + 1, isIdentifierCharacter);
459
+ const nameEnd = skipClass(source, levelEnd + 1, IDENTIFIER);
394
460
  const isDash = nameEnd === levelEnd + 1 && (source[nameEnd] === "*" || source[nameEnd] === "-");
395
461
  return (
396
462
  skipWhile(source, isDash ? nameEnd + 1 : nameEnd, (character) => character === ".") - index
@@ -403,8 +469,25 @@ export const readAtAsIdentifier = (token: Token): Token =>
403
469
 
404
470
  const TAB_SIZE = 8;
405
471
 
406
- const getWidthAfter = (width: number, character: string | undefined) =>
407
- character === "\t" ? width + TAB_SIZE - (width % TAB_SIZE) : width + 1;
472
+ const STRING_ESCAPES: Record<string, string> = { n: "\n", t: "\t", r: "\r", f: "\f" };
473
+
474
+ const getWidthAfter = (width: number, code: number) =>
475
+ code === CODE_TAB ? width + TAB_SIZE - (width % TAB_SIZE) : width + 1;
476
+
477
+ const BASED_NUMBER_DIGITS = new Map([
478
+ ["b", BINARY_DIGIT],
479
+ ["o", OCTAL_DIGIT],
480
+ ["h", HEX_DIGIT],
481
+ ]);
482
+
483
+ // The length of a based numeral such as \b01 or \hFF at index, or 0.
484
+ const matchBasedNumber = (source: string, index: number) => {
485
+ if (source.charCodeAt(index) !== CODE_BACKSLASH) return 0;
486
+ const digits = BASED_NUMBER_DIGITS.get(source.charAt(index + 1).toLowerCase());
487
+ if (digits === undefined) return 0;
488
+ const end = skipClass(source, index + 2, digits);
489
+ return end === index + 2 ? 0 : end - index;
490
+ };
408
491
 
409
492
  export const tokenize = (source: string): Token[] => {
410
493
  const headerMatch = MODULE_HEADER.exec(source);
@@ -429,9 +512,9 @@ export const tokenize = (source: string): Token[] => {
429
512
  scan.width = 0;
430
513
  }
431
514
  for (; scan.position < cursor.index; scan.position++) {
432
- scan.width = getWidthAfter(scan.width, source[scan.position]);
515
+ scan.width = getWidthAfter(scan.width, source.charCodeAt(scan.position));
433
516
  }
434
- return getWidthAfter(scan.width, source[cursor.index]);
517
+ return getWidthAfter(scan.width, source.charCodeAt(cursor.index));
435
518
  };
436
519
  const pushToken = (kind: TokenKind, text: string, length: number, spelling?: string) => {
437
520
  const column = getColumn();
@@ -447,7 +530,7 @@ export const tokenize = (source: string): Token[] => {
447
530
  };
448
531
  const advanceOver = (length: number) => {
449
532
  for (let offset = 0; offset < length; offset++) {
450
- if (source[cursor.index] === "\n") {
533
+ if (source.charCodeAt(cursor.index) === CODE_NEWLINE) {
451
534
  cursor.line++;
452
535
  cursor.lineStart = cursor.index + 1;
453
536
  }
@@ -463,18 +546,18 @@ export const tokenize = (source: string): Token[] => {
463
546
  });
464
547
 
465
548
  while (cursor.index < source.length) {
466
- const character = source[cursor.index];
549
+ const code = source.charCodeAt(cursor.index);
467
550
 
468
- if (character === "\n" || character === " " || character === "\t" || character === "\r") {
551
+ if (code === CODE_NEWLINE || code === CODE_SPACE || code === CODE_TAB || code === CODE_RETURN) {
469
552
  advanceOver(1);
470
553
  continue;
471
554
  }
472
- if (source.startsWith("\\*", cursor.index)) {
555
+ if (code === CODE_BACKSLASH && source.charCodeAt(cursor.index + 1) === CODE_STAR) {
473
556
  const lineEnd = source.indexOf("\n", cursor.index);
474
557
  advanceOver((lineEnd === -1 ? source.length : lineEnd) - cursor.index);
475
558
  continue;
476
559
  }
477
- if (source.startsWith("(*", cursor.index)) {
560
+ if (code === CODE_OPEN_PAREN && source.charCodeAt(cursor.index + 1) === CODE_STAR) {
478
561
  const depth = { value: 0 };
479
562
  do {
480
563
  if (cursor.index >= source.length) throw createError("Unterminated comment");
@@ -490,7 +573,7 @@ export const tokenize = (source: string): Token[] => {
490
573
  } while (depth.value > 0);
491
574
  continue;
492
575
  }
493
- if (source.startsWith("----", cursor.index)) {
576
+ if (code === CODE_DASH && source.startsWith("----", cursor.index)) {
494
577
  const length = skipWhile(source, cursor.index, (next) => next === "-") - cursor.index;
495
578
  if (
496
579
  source
@@ -502,28 +585,29 @@ export const tokenize = (source: string): Token[] => {
502
585
  pushToken("Separator", "----", length);
503
586
  continue;
504
587
  }
505
- if (source.startsWith("====", cursor.index)) {
588
+ if (code === CODE_EQUALS && source.startsWith("====", cursor.index)) {
506
589
  const length = skipWhile(source, cursor.index, (next) => next === "=") - cursor.index;
507
590
  pushToken("ModuleEnd", "====", length);
508
591
  cursor.moduleDepth--;
509
592
  if (cursor.moduleDepth <= 0) break;
510
593
  continue;
511
594
  }
512
- if (character === '"') {
595
+ if (code === CODE_QUOTE) {
513
596
  const line = cursor.line;
514
597
  const column = getColumn();
515
598
  const characters: string[] = [];
516
599
  advanceOver(1);
517
- while (source[cursor.index] !== '"') {
518
- if (cursor.index >= source.length || "\n\r".includes(source[cursor.index])) {
600
+ while (source.charCodeAt(cursor.index) !== CODE_QUOTE) {
601
+ const next = source.charCodeAt(cursor.index);
602
+ if (cursor.index >= source.length || next === CODE_NEWLINE || next === CODE_RETURN) {
519
603
  throw createError("Unterminated string");
520
604
  }
521
- if (source[cursor.index] === "\\") {
605
+ if (next === CODE_BACKSLASH) {
522
606
  const escaped = source[cursor.index + 1];
523
607
  if (escaped === undefined || !'ntrf\\"'.includes(escaped)) {
524
608
  throw createError("Invalid escape in string");
525
609
  }
526
- characters.push({ n: "\n", t: "\t", r: "\r", f: "\f" }[escaped] ?? escaped);
610
+ characters.push(STRING_ESCAPES[escaped] ?? escaped);
527
611
  advanceOver(2);
528
612
  continue;
529
613
  }
@@ -540,24 +624,26 @@ export const tokenize = (source: string): Token[] => {
540
624
  });
541
625
  continue;
542
626
  }
543
- const basedNumber = BASED_NUMBER.exec(source.slice(cursor.index, cursor.index + 64));
544
- if (basedNumber) {
545
- pushToken("Number", basedNumber[0], basedNumber[0].length);
627
+ const basedLength = matchBasedNumber(source, cursor.index);
628
+ if (basedLength > 0) {
629
+ pushToken("Number", source.slice(cursor.index, cursor.index + basedLength), basedLength);
546
630
  continue;
547
631
  }
548
- if (isIdentifierCharacter(character)) {
549
- const word = source.slice(
550
- cursor.index,
551
- skipWhile(source, cursor.index, isIdentifierCharacter),
552
- );
553
- if (/^\d+$/.test(word)) {
554
- const number = /^\d+(\.\d+)?/.exec(source.slice(cursor.index))?.[0] ?? word;
555
- pushToken(number.includes(".") ? "Decimal" : "Number", number, number.length);
632
+ if (isInClass(code, IDENTIFIER)) {
633
+ const wordEnd = skipClass(source, cursor.index, IDENTIFIER);
634
+ const word = source.slice(cursor.index, wordEnd);
635
+ const digitsEnd = skipClass(source, cursor.index, DIGIT);
636
+ if (digitsEnd === wordEnd) {
637
+ const fractionEnd =
638
+ source.charCodeAt(wordEnd) === CODE_DOT ? skipClass(source, wordEnd + 1, DIGIT) : wordEnd;
639
+ const isDecimal = fractionEnd > wordEnd + 1;
640
+ const number = isDecimal ? source.slice(cursor.index, fractionEnd) : word;
641
+ pushToken(isDecimal ? "Decimal" : "Number", number, number.length);
556
642
  continue;
557
643
  }
558
644
  // A word needs a letter to be a name, so SANY reads one without as underscores and numbers.
559
- const part = /^(_|\d+)/.exec(word)?.[0];
560
- if (part !== undefined && !/[A-Za-z]/.test(word)) {
645
+ if (!/[A-Za-z]/.test(word)) {
646
+ const part = code === CODE_UNDERSCORE ? "_" : source.slice(cursor.index, digitsEnd);
561
647
  pushToken(part === "_" ? "Operator" : "Number", part, part.length);
562
648
  continue;
563
649
  }
@@ -570,15 +656,18 @@ export const tokenize = (source: string): Token[] => {
570
656
  pushToken(KEYWORDS.has(word) ? "Keyword" : "Identifier", name, word.length);
571
657
  continue;
572
658
  }
573
- if ("ℕℤℝ".includes(character)) {
659
+ const character = source[cursor.index];
660
+ if (code >= 128 && UNICODE_NAMES.has(character)) {
574
661
  pushToken("Identifier", names.get(character) ?? character, 1);
575
662
  names.set(character, character);
576
663
  continue;
577
664
  }
578
- const stepLength = matchStep(source, cursor.index);
579
- if (stepLength > 0) {
580
- pushToken("Step", source.slice(cursor.index, cursor.index + stepLength), stepLength);
581
- continue;
665
+ if (code === CODE_LESS_THAN) {
666
+ const stepLength = matchStep(source, cursor.index);
667
+ if (stepLength > 0) {
668
+ pushToken("Step", source.slice(cursor.index, cursor.index + stepLength), stepLength);
669
+ continue;
670
+ }
582
671
  }
583
672
  const operator = matchOperator(source, cursor.index);
584
673
  if (operator) {
package/src/liveness.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { isLocallyResolved, type Bound, type Definition, type Expression } from "./ast";
2
+ import { getDefinitionLevel } from "./dependencies";
2
3
  import {
3
4
  createStackOverflowError,
4
5
  TlaEvaluationError,
@@ -66,8 +67,6 @@ export const createTautologyError = () =>
66
67
 
67
68
  const TEMPORAL_OPERATORS = new Set(["~>", "-+->"]);
68
69
 
69
- const definitionLevels = new WeakMap<Definition, number>();
70
-
71
70
  const definitionThunks = new WeakSet<Thunk>();
72
71
 
73
72
  const getConstantContext = (environment: Environment, scope: Scope | undefined): Context => ({
@@ -159,19 +158,6 @@ export const getLevel = (
159
158
  }
160
159
  };
161
160
 
162
- const getDefinitionLevel = (definition: Definition, environment: Environment) => {
163
- const cached = definitionLevels.get(definition);
164
- if (cached !== undefined) return cached;
165
- definitionLevels.set(definition, 0);
166
- const bounds = definition.kind === "Function" ? definition.bounds : [];
167
- const level = Math.max(
168
- getLevel(definition.body, undefined, environment),
169
- ...bounds.map((bound) => getLevel(bound.set, undefined, environment)),
170
- );
171
- definitionLevels.set(definition, level);
172
- return level;
173
- };
174
-
175
161
  // TLC leaves a formula whose sets it fails to enumerate, and doesn't expect an EvalException.
176
162
  const getUnrolledElements = (bounds: Bound[], context: Context) => {
177
163
  try {
@@ -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/search.ts CHANGED
@@ -14,7 +14,7 @@ import type {
14
14
  Violation,
15
15
  } from "./check";
16
16
  import type { ConfigValue, ModelConfig } from "./config";
17
- import { getReadVariables } from "./dependencies";
17
+ import { getReadVariables, isConstantLevel } from "./dependencies";
18
18
  import {
19
19
  isStackOverflow,
20
20
  TlaConfigError,
@@ -27,10 +27,10 @@ import {
27
27
  describeRange,
28
28
  evaluate,
29
29
  evaluateStartupDefinitions,
30
+ getStartupValue,
30
31
  expectBoolean,
31
32
  formatRange,
32
33
  getDefinition,
33
- isConstantLevel,
34
34
  type Context,
35
35
  type Environment,
36
36
  type Scope,
@@ -49,7 +49,7 @@ import { prettyPrint } from "./pretty-print";
49
49
  import { getPossibleCounts, type CheckerRuntime } from "./runtime";
50
50
  import { getRepresentative, getSymmetryGroup } from "./symmetry";
51
51
  import { MESSAGE_CODE, MISSING_INIT_174, withHeadline } from "./tlc/messages";
52
- import { createTlcFingerprinter, getTlcFingerprint } from "./tlc/fingerprint";
52
+ import { getTlcFingerprint, getTlcFingerprints } from "./tlc/fingerprint";
53
53
  import { formatValue, isUpdatedElementOf, type Value } from "./values";
54
54
 
55
55
  interface NamedExpression {
@@ -761,8 +761,6 @@ export const createSearch = (
761
761
  );
762
762
  };
763
763
  const isFingerprintedLikeTlc = hasWideString(config, environment);
764
- // One fingerprinter for every level keeps the values it cached for the states of earlier levels.
765
- let storedFingerprinter: ReturnType<typeof createTlcFingerprinter> | undefined;
766
764
  runtime.getFingerprint = getTlcStateFingerprint;
767
765
  const findUnwitnessedPossible = () => {
768
766
  const unwitnessed = possible.find((item) => !runtime.possibleCounts.get(item.name));
@@ -786,8 +784,7 @@ export const createSearch = (
786
784
  if (view !== undefined || isFingerprintedLikeTlc) {
787
785
  return BigInt64Array.from(states, getTlcStateFingerprint);
788
786
  }
789
- storedFingerprinter ??= createTlcFingerprinter(getTlcOrder());
790
- return storedFingerprinter(fingerprintStates);
787
+ return getTlcFingerprints(fingerprintStates, getTlcOrder());
791
788
  },
792
789
  getFingerprintState: (state) => {
793
790
  if (isFingerprintedLikeTlc) return [String(getTlcStateFingerprint(state))];
@@ -925,7 +922,7 @@ export const createSearch = (
925
922
  // a postcondition before it checks any of them.
926
923
  const constant = config.postconditions.find((name) => {
927
924
  const definition = getDefinition(name, environment);
928
- return definition !== undefined && environment.definitionValues.has(definition);
925
+ return definition !== undefined && getStartupValue(definition, environment) !== undefined;
929
926
  });
930
927
  if (constant !== undefined) {
931
928
  if (isAfterViolation) return undefined;
@@ -1,3 +1,4 @@
1
+ import { isConstantLevel } from "./dependencies";
1
2
  import {
2
3
  isLocallyResolved,
3
4
  type Definition,
@@ -14,7 +15,6 @@ import {
14
15
  evaluate,
15
16
  forEachBinding,
16
17
  getDefinition,
17
- isConstantLevel,
18
18
  lookupScope,
19
19
  resolveGlobalOperator,
20
20
  type Closure,
package/src/successors.ts CHANGED
@@ -1056,15 +1056,9 @@ const compileAction = (
1056
1056
  }
1057
1057
  };
1058
1058
 
1059
- const emptyStates = new WeakMap<Environment, State>();
1060
-
1061
- const getEmptyState = (environment: Environment) => {
1062
- const cached = emptyStates.get(environment);
1063
- if (cached) return cached;
1064
- const state = environment.variables.map((): Value | undefined => undefined);
1065
- emptyStates.set(environment, state);
1066
- return state;
1067
- };
1059
+ // A partial state that assigns no variable, which a run fills in as it assigns them.
1060
+ const getEmptyState = (environment: Environment): State =>
1061
+ environment.variables.map((): Value | undefined => undefined);
1068
1062
 
1069
1063
  const isComplete = (partial: State): partial is Value[] => {
1070
1064
  for (let index = 0; index < partial.length; index++) {