tla-ts 0.0.7-dev.bd12468 → 0.0.8-dev.4114a01

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 {
@@ -5,22 +5,24 @@ import {
5
5
  isSharedFingerprintsFull,
6
6
  writeStateFingerprint,
7
7
  } from "./fingerprints";
8
- import type { CoordinatorMessage, LevelMessage, StartMessage, WorkerMessage } from "./parallel";
8
+ import type { CoordinatorMessage, 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 {
15
15
  createCanonicalizer,
16
+ getRankedString,
16
17
  getRankedStringCount,
17
18
  setStringOrder,
18
19
  setValueVersion,
19
20
  type Value,
20
21
  } from "./values";
21
- import { getParentPort, type Port } from "./worker";
22
+ import { createBreak, getParentPort, type Port } from "./worker";
22
23
 
23
24
  const LOCKED = -1;
25
+ const BREAK_INTERVAL = 100;
24
26
 
25
27
  interface Expansion {
26
28
  states: Value[][];
@@ -33,18 +35,21 @@ interface Expansion {
33
35
  outDegrees: number[];
34
36
  next: Value[][];
35
37
  fingerprintStates: Value[][];
38
+ breakAt: number;
36
39
  }
37
40
 
38
41
  const runWorker = (start: StartMessage, parent: Port) => {
39
42
  const modules = new Map(start.modules);
40
43
  const loadModule = (name: string) => modules.get(name);
41
44
  const classes = new Map(start.classes);
42
- setStringOrder(getTlcStringOrder(start.source, start.config, loadModule));
45
+ const order = createTlcOrder(start.source, loadModule);
46
+ setStringOrder(order.getStringOrder(start.config));
43
47
  setValueVersion(start.version);
44
48
  const startupStrings = getRankedStringCount();
45
49
  const specification = createEnvironment(start.config, {
46
50
  source: start.source,
47
51
  loadModule,
52
+ order,
48
53
  loadClass: (name) => classes.get(name),
49
54
  print: () => {},
50
55
  files: { readFile: undefined, writeFile: undefined },
@@ -55,7 +60,7 @@ const runWorker = (start: StartMessage, parent: Port) => {
55
60
  });
56
61
  const environment = specification.environment;
57
62
  const search = createSearch(start.config, environment, () =>
58
- getTlcVariableOrder(start.source, loadModule),
63
+ order.getDeclarationOrder("variable"),
59
64
  );
60
65
  const nextAction = search?.spec.next;
61
66
  if (!search || nextAction === undefined)
@@ -76,6 +81,7 @@ const runWorker = (start: StartMessage, parent: Port) => {
76
81
  port?.start?.();
77
82
  });
78
83
  const frontier = { states: decode(start.seed).map(canonicalize) };
84
+ const takeBreak = createBreak();
79
85
 
80
86
  // A worker that runs out of states asks a peer for some by writing its index + 1 to the peer's
81
87
  // request word. The peer sends half of the states it hasn't started, keeps expanding, and wakes
@@ -111,6 +117,7 @@ const runWorker = (start: StartMessage, parent: Port) => {
111
117
  for (; expansion.origin < expansion.end; expansion.origin++) {
112
118
  const state = expansion.states[expansion.origin];
113
119
  if (!expansion.successors) {
120
+ if (performance.now() >= expansion.breakAt) return "break";
114
121
  if (Atomics.load(requests, workerIndex) > 0) answerRequest(expansion, 0);
115
122
  Atomics.store(remaining, workerIndex, expansion.end - expansion.origin - 1);
116
123
  expansion.successors = getSuccessors(nextAction, state, environment, search.spec.scope);
@@ -182,7 +189,7 @@ const runWorker = (start: StartMessage, parent: Port) => {
182
189
  const report = (message: WorkerMessage) =>
183
190
  parent.postMessage(message, message.type === "level" ? [message.fingerprints.buffer] : []);
184
191
 
185
- const runLevel = async (): Promise<LevelMessage | undefined> => {
192
+ const runLevel = async (): Promise<WorkerMessage | undefined> => {
186
193
  const expansion: Expansion = {
187
194
  states: frontier.states,
188
195
  origin: 0,
@@ -194,10 +201,18 @@ const runWorker = (start: StartMessage, parent: Port) => {
194
201
  outDegrees: Array.from({ length: OUT_DEGREE_BUCKETS }, () => 0),
195
202
  next: [],
196
203
  fingerprintStates: [],
204
+ breakAt: performance.now() + BREAK_INTERVAL,
197
205
  };
198
206
  for (;;) {
199
207
  const status = expand(expansion);
200
208
  if (status === undefined) return undefined;
209
+ // HACK: Bun runs its garbage collection timers on the event loop, so a worker that expands a
210
+ // long level without returning to the loop holds on to memory it no longer uses.
211
+ if (status === "break") {
212
+ await takeBreak();
213
+ expansion.breakAt = performance.now() + BREAK_INTERVAL;
214
+ continue;
215
+ }
201
216
  lockRequests(expansion);
202
217
  if (status === "paused") {
203
218
  const resumed = new Promise<void>((resolve) => (waiters.resume = resolve));
@@ -208,7 +223,9 @@ const runWorker = (start: StartMessage, parent: Port) => {
208
223
  }
209
224
  if (!(await steal(expansion))) break;
210
225
  }
211
- if (getRankedStringCount() !== startupStrings) return undefined;
226
+ if (getRankedStringCount() !== startupStrings) {
227
+ return { type: "abort", string: getRankedString(startupStrings) };
228
+ }
212
229
  frontier.states = expansion.next;
213
230
  Atomics.store(remaining, workerIndex, frontier.states.length);
214
231
  return {
package/src/parallel.ts CHANGED
@@ -25,12 +25,13 @@ 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";
32
32
  import {
33
33
  createCanonicalizer,
34
+ getRankedString,
34
35
  getRankedStringCount,
35
36
  setStringOrder,
36
37
  setValueVersion,
@@ -56,7 +57,7 @@ export interface StartMessage {
56
57
  remaining: Int32Array;
57
58
  }
58
59
 
59
- export interface LevelMessage {
60
+ interface LevelMessage {
60
61
  type: "level";
61
62
  generated: number;
62
63
  added: number;
@@ -66,7 +67,7 @@ export interface LevelMessage {
66
67
 
67
68
  export type WorkerMessage =
68
69
  | { type: "ready" }
69
- | { type: "abort" }
70
+ | { type: "abort"; string?: string }
70
71
  | { type: "paused" }
71
72
  | LevelMessage;
72
73
 
@@ -96,7 +97,10 @@ export const check = async (options: CheckOptions): Promise<CheckResult> => {
96
97
  };
97
98
  // The search on the calling thread prints and reports what this one did while it started, so it
98
99
  // skips that.
99
- const fallBack = () => {
100
+ const fallBack = (createdString?: string) => {
101
+ if (createdString !== undefined) {
102
+ options.onProgress?.({ kind: "sequential-fallback", string: createdString });
103
+ }
100
104
  const skipped = { count: printed.count };
101
105
  return checkSequentially({
102
106
  ...options,
@@ -108,12 +112,13 @@ export const check = async (options: CheckOptions): Promise<CheckResult> => {
108
112
  });
109
113
  };
110
114
  const workerCount = options.workers ?? 1;
111
- // TLC's workers write the -dump state graph in whichever order they find it, so one worker
112
- // writes the graph a single TLC worker does.
115
+ // TLC's workers write the -dump state graph, and print the violations -continue goes on past, in
116
+ // whichever order they find them, so one worker does what a single TLC worker does.
113
117
  const isSequential =
114
118
  workerCount < 2 ||
115
119
  typeof SharedArrayBuffer !== "function" ||
116
120
  options.dump !== undefined ||
121
+ options.isContinued === true ||
117
122
  config.view !== undefined ||
118
123
  config.postconditions.length > 0 ||
119
124
  config.possible.length > 0;
@@ -130,12 +135,14 @@ export const check = async (options: CheckOptions): Promise<CheckResult> => {
130
135
  classes.set(name, bytes);
131
136
  return bytes;
132
137
  };
133
- setStringOrder(getTlcStringOrder(options.source, config, loadModule));
138
+ const order = createTlcOrder(options.source, loadModule);
139
+ setStringOrder(order.getStringOrder(config));
134
140
  setValueVersion(options.version);
135
141
  const startupStrings = getRankedStringCount();
136
142
  const specification = createEnvironment(config, {
137
143
  source: options.source,
138
144
  loadModule,
145
+ order,
139
146
  loadClass,
140
147
  print: (text) => {
141
148
  printed.count++;
@@ -153,7 +160,7 @@ export const check = async (options: CheckOptions): Promise<CheckResult> => {
153
160
  const search = createSearch(
154
161
  config,
155
162
  environment,
156
- () => getTlcVariableOrder(options.source, loadModule),
163
+ () => order.getDeclarationOrder("variable"),
157
164
  report,
158
165
  );
159
166
  if (findAssumptionViolation(specification.assumptions, environment)) return fallBack();
@@ -230,7 +237,7 @@ export const check = async (options: CheckOptions): Promise<CheckResult> => {
230
237
  if (!(error instanceof TlaEvaluationError)) throw error;
231
238
  return fallBack();
232
239
  }
233
- if (getRankedStringCount() !== startupStrings) return fallBack();
240
+ if (getRankedStringCount() !== startupStrings) return fallBack(getRankedString(startupStrings));
234
241
  statistics.depth = statistics.generatedStates === 0 ? 0 : 1;
235
242
  statistics.initialStates = {
236
243
  generated: statistics.generatedStates,
@@ -322,7 +329,10 @@ export const check = async (options: CheckOptions): Promise<CheckResult> => {
322
329
  const messages = await collectLevels(await reported);
323
330
  if (isAborted(messages)) {
324
331
  terminate();
325
- return fallBack();
332
+ const aborted = messages.find(
333
+ (message) => message.type === "abort" && message.string !== undefined,
334
+ );
335
+ return fallBack(aborted?.type === "abort" ? aborted.string : undefined);
326
336
  }
327
337
  const levels = messages.flatMap((message) => (message.type === "level" ? [message] : []));
328
338
  const added = levels.reduce((sum, message) => sum + message.added, 0);
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");
@@ -1783,11 +1783,15 @@ export const generateSanySpecification = (
1783
1783
  (params.length === 0 || params[params.length - 1].arity === 0);
1784
1784
  if (existing.letInLevel !== state.curLevel) {
1785
1785
  addError(location, `Recursive operator ${name} defined at wrong LET/IN level.`);
1786
- } else if (!isMatching) {
1787
- addError(
1788
- location,
1789
- `Definition of ${existing.name} has different arity than its RECURSIVE declaration.`,
1790
- );
1786
+ } else {
1787
+ if (!isMatching) {
1788
+ addError(
1789
+ location,
1790
+ `Definition of ${existing.name} has different arity than its RECURSIVE declaration.`,
1791
+ );
1792
+ }
1793
+ // SANY sets the parameters before it analyzes the body.
1794
+ existing.params = params;
1791
1795
  }
1792
1796
  } else if (existing !== undefined) {
1793
1797
  addError(location, `Operator ${name} already defined or declared.`);
@@ -1805,8 +1809,6 @@ export const generateSanySpecification = (
1805
1809
  !existing.isDefined &&
1806
1810
  existing.letInLevel === state.curLevel
1807
1811
  ) {
1808
- // OpDefNode.setParams keeps the arity of the RECURSIVE declaration.
1809
- existing.params = params;
1810
1812
  existing.weights = params.map(() => 0);
1811
1813
  existing.maxLevels = params.map(() => TEMPORAL_LEVEL);
1812
1814
  existing.isLeibnizArg = params.map(() => true);