tla-ts 0.0.8 → 0.0.9-dev.4ce0657

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.
Files changed (63) hide show
  1. package/README.md +23 -0
  2. package/dist/compile.cjs +23 -0
  3. package/dist/compile.js +23 -0
  4. package/dist/deciders.cjs +15 -15
  5. package/dist/deciders.js +48 -48
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +27 -9
  8. package/dist/index.d.ts +27 -9
  9. package/dist/index.js +1 -1
  10. package/dist/parallel-worker.cjs +1 -1
  11. package/dist/parallel-worker.js +1 -1
  12. package/dist/prove.cjs +17 -17
  13. package/dist/prove.js +32 -32
  14. package/dist/run.cjs +28 -28
  15. package/dist/run.js +31 -31
  16. package/dist/tlapm.cjs +2 -2
  17. package/dist/tlapm.js +1 -1
  18. package/dist/transfer.cjs +30 -33
  19. package/dist/transfer.js +30 -33
  20. package/dist/worker.cjs +4 -4
  21. package/dist/worker.js +4 -4
  22. package/package.json +3 -1
  23. package/src/check.ts +77 -46
  24. package/src/cli/options.ts +2 -1
  25. package/src/cli/tlc.ts +26 -8
  26. package/src/cli/typescript.ts +26 -0
  27. package/src/codegen.ts +0 -5
  28. package/src/dependencies.ts +348 -24
  29. package/src/environment.ts +27 -11
  30. package/src/errors.ts +15 -0
  31. package/src/evaluate.ts +188 -712
  32. package/src/instances.ts +67 -6
  33. package/src/lexer.ts +140 -51
  34. package/src/liveness-checker.ts +6 -3
  35. package/src/liveness.ts +8 -18
  36. package/src/parallel-worker.ts +6 -3
  37. package/src/parallel.ts +15 -7
  38. package/src/prover/smt/solver/solver.ts +31 -27
  39. package/src/sany/generator.ts +9 -7
  40. package/src/sany/linter.ts +30 -21
  41. package/src/search.ts +48 -32
  42. package/src/spec-description.ts +1 -1
  43. package/src/successors.ts +6 -12
  44. package/src/symmetry.ts +32 -143
  45. package/src/tlc/fingerprint.ts +69 -116
  46. package/src/tlc/order.ts +27 -48
  47. package/src/tlc/replay.ts +1 -1
  48. package/src/typescript/actions.ts +494 -0
  49. package/src/typescript/collections.ts +615 -0
  50. package/src/typescript/compile.ts +70 -0
  51. package/src/typescript/context.ts +106 -0
  52. package/src/typescript/emit.ts +122 -0
  53. package/src/typescript/expressions.ts +508 -0
  54. package/src/typescript/formula.ts +160 -0
  55. package/src/typescript/functions.ts +295 -0
  56. package/src/typescript/model.ts +164 -0
  57. package/src/typescript/names.ts +116 -0
  58. package/src/typescript/program.ts +51 -0
  59. package/src/typescript/properties.ts +141 -0
  60. package/src/typescript/scope.ts +117 -0
  61. package/src/typescript/steps.ts +175 -0
  62. package/src/typescript/types.ts +178 -0
  63. package/src/values.ts +126 -82
package/src/instances.ts CHANGED
@@ -14,8 +14,6 @@ import {
14
14
  import { TlaSyntaxError } from "./errors";
15
15
  import { getArity, getBoundNames, getPatternNames, isBefore, LOCAL_RESOLUTION } from "./resolve";
16
16
 
17
- export const substitutedExpressions = new WeakSet<Expression>();
18
-
19
17
  // Applications inside an instance with substitutions or parameters, which TLC evaluates in a
20
18
  // context that binds them.
21
19
  export const contextualApplications = new WeakSet<Expression>();
@@ -224,6 +222,8 @@ interface Instantiation {
224
222
  substitutions: Map<string, Expression>;
225
223
  variables: Set<string>;
226
224
  getDefinition: (key: string) => Definition | undefined;
225
+ // A definition of the instantiating module that a substitution names.
226
+ getOuterDefinition: (name: string) => Definition | undefined;
227
227
  isParameterized: (key: string) => boolean;
228
228
  addDefinition: (source: string, name: string, create: (key: string) => Definition) => string;
229
229
  createName: (name: string) => string;
@@ -240,8 +240,40 @@ interface Rewrite {
240
240
  copies: Map<string, string>;
241
241
  mode: RewriteMode;
242
242
  modes: Map<RewriteMode, Rewrite>;
243
+ // The substitutions an operator's copy reads, which it binds once, as TLC binds each to a lazy
244
+ // value when it evaluates the operator's body.
245
+ bindings?: Map<string, Expression>;
243
246
  }
244
247
 
248
+ const getSubstitutionName = (name: string) => `${name}@SUBSTITUTION`;
249
+
250
+ const isVariableAlias = (expression: Expression): boolean =>
251
+ expression.kind === "Identifier" ||
252
+ (expression.kind === "Tuple" && expression.elements.every(isVariableAlias));
253
+
254
+ // A name, or a tuple of names, stays in place, so a step can assign it or leave it unchanged as
255
+ // TLC does through its lazy value. An operator or a literal costs nothing to evaluate again. A name
256
+ // of a definition that isn't such an alias is bound once.
257
+ const isBoundOnce = (replacement: Expression, instantiation: Instantiation) => {
258
+ if (replacement.kind !== "Identifier") {
259
+ return (
260
+ !isVariableAlias(replacement) &&
261
+ replacement.kind !== "OperatorReference" &&
262
+ replacement.kind !== "Lambda" &&
263
+ replacement.kind !== "Number" &&
264
+ replacement.kind !== "String"
265
+ );
266
+ }
267
+ const definition = isLocallyResolved(replacement)
268
+ ? undefined
269
+ : instantiation.getOuterDefinition(replacement.name);
270
+ return (
271
+ definition?.kind === "Operator" &&
272
+ definition.params.length === 0 &&
273
+ !isVariableAlias(definition.body)
274
+ );
275
+ };
276
+
245
277
  const getFreeNames = (expression: Expression, bound = new Set<string>()): string[] => {
246
278
  const name =
247
279
  expression.kind === "Identifier"
@@ -515,10 +547,15 @@ const substitute = (
515
547
  if (enabled) return enabled;
516
548
  if (expression.kind === "Identifier" && isFree(expression.name)) {
517
549
  const replacement = instantiation.substitutions.get(expression.name);
518
- if (replacement) {
519
- substitutedExpressions.add(replacement);
550
+ const bindings = rewrite.bindings;
551
+ if (replacement && (bindings === undefined || !isBoundOnce(replacement, instantiation))) {
520
552
  return replacement;
521
553
  }
554
+ if (replacement && bindings) {
555
+ const name = getSubstitutionName(expression.name);
556
+ bindings.set(name, replacement);
557
+ return createLocalIdentifier(name, expression.location);
558
+ }
522
559
  const copy = getCopy(rewrite, expression.name);
523
560
  if (copy === undefined) return expression;
524
561
  if (params.length === 0) return { ...expression, name: copy };
@@ -649,13 +686,37 @@ const copyDefinition = (rewrite: Rewrite, key: string): string => {
649
686
  return instantiation.addDefinition(key, definition.name, (copyKey) => {
650
687
  rewrite.copies.set(key, copyKey);
651
688
  const rename = createRenamer(rewrite);
689
+ const bindings = new Map<string, Expression>();
690
+ const bodyRewrite =
691
+ definition.kind === "Operator" && rewrite.mode === "Normal"
692
+ ? { ...rewrite, bindings }
693
+ : rewrite;
652
694
  const mapped = renameParams(
653
695
  mapDefinition(definition, (child, bound) =>
654
- substitute(child, rewrite, bindNames(new Map(), bound, rename)),
696
+ substitute(child, bodyRewrite, bindNames(new Map(), bound, rename)),
655
697
  ),
656
698
  rename,
657
699
  );
658
- return withInstanceParams(mapped, instantiation.params, definition.location);
700
+ if (mapped.kind !== "Operator" || bindings.size === 0) {
701
+ return withInstanceParams(mapped, instantiation.params, definition.location);
702
+ }
703
+ const definitions = [...bindings].map(([name, replacement]): Definition => ({
704
+ kind: "Operator",
705
+ name,
706
+ params: [],
707
+ body: replacement,
708
+ isLocal: true,
709
+ isRecursive: false,
710
+ location: replacement.location,
711
+ }));
712
+ return withInstanceParams(
713
+ {
714
+ ...mapped,
715
+ body: { kind: "Let", definitions, body: mapped.body, location: mapped.body.location },
716
+ },
717
+ instantiation.params,
718
+ definition.location,
719
+ );
659
720
  });
660
721
  };
661
722
 
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) {
@@ -268,11 +268,14 @@ export const createLivenessChecker = (
268
268
  return cache;
269
269
  };
270
270
  // TLCGet("level") reads the level of the state whose successors the checks run on.
271
+ // A check that fails leaves no source, so the failure's trace reads the levels of the search.
271
272
  const evaluateFrom = <Result>(source: number | undefined, evaluate: () => Result) => {
272
273
  environment.runtime.setLivenessSource(source);
273
- const result = evaluate();
274
- environment.runtime.setLivenessSource(undefined);
275
- return result;
274
+ try {
275
+ return evaluate();
276
+ } finally {
277
+ environment.runtime.setLivenessSource(undefined);
278
+ }
276
279
  };
277
280
  const evaluateState = (predicate: LiveExpression, state: Value[]) =>
278
281
  evaluateLive(
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 => ({
@@ -93,7 +92,11 @@ export const getLevel = (
93
92
  const binding = lookupScope(scope, name);
94
93
  if (!binding) return undefined;
95
94
  if (binding.kind === "Value") return CONSTANT_LEVEL;
96
- if (binding.kind === "Thunk") return getLevel(binding.expression, binding.scope, environment);
95
+ if (binding.kind === "Thunk") {
96
+ return binding.isReleased
97
+ ? CONSTANT_LEVEL
98
+ : getLevel(binding.expression, binding.scope, environment);
99
+ }
97
100
  const operator = binding.operator;
98
101
  return operator.kind === "Closure"
99
102
  ? getLevel(operator.body, operator.scope, environment)
@@ -159,19 +162,6 @@ export const getLevel = (
159
162
  }
160
163
  };
161
164
 
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
165
  // TLC leaves a formula whose sets it fails to enumerate, and doesn't expect an EvalException.
176
166
  const getUnrolledElements = (bounds: Bound[], context: Context) => {
177
167
  try {
@@ -224,7 +214,7 @@ export const expandTemporal = (
224
214
  }
225
215
  if (expression.kind === "Identifier") {
226
216
  const binding = isLocallyResolved(expression) ? lookupScope(scope, expression.name) : undefined;
227
- if (binding?.kind === "Thunk") {
217
+ if (binding?.kind === "Thunk" && !binding.isReleased) {
228
218
  return expand(binding.expression, binding.scope);
229
219
  }
230
220
  const definition = environment.constants.has(expression.name)
@@ -359,7 +349,7 @@ export const toLiveExpression = (
359
349
  isLocallyResolved(expression) || getDefinition(name, environment) === undefined
360
350
  ? lookupScope(scope, name)
361
351
  : undefined;
362
- if (binding?.kind === "Thunk" && definitionThunks.has(binding)) {
352
+ if (binding?.kind === "Thunk" && !binding.isReleased && definitionThunks.has(binding)) {
363
353
  return expandCall(expression, () =>
364
354
  expand(binding.expression, binding.scope, expression, scope),
365
355
  );
@@ -5,7 +5,7 @@ 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
11
  import { createTlcOrder } from "./tlc/order";
@@ -13,6 +13,7 @@ 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,
@@ -188,7 +189,7 @@ const runWorker = (start: StartMessage, parent: Port) => {
188
189
  const report = (message: WorkerMessage) =>
189
190
  parent.postMessage(message, message.type === "level" ? [message.fingerprints.buffer] : []);
190
191
 
191
- const runLevel = async (): Promise<LevelMessage | undefined> => {
192
+ const runLevel = async (): Promise<WorkerMessage | undefined> => {
192
193
  const expansion: Expansion = {
193
194
  states: frontier.states,
194
195
  origin: 0,
@@ -222,7 +223,9 @@ const runWorker = (start: StartMessage, parent: Port) => {
222
223
  }
223
224
  if (!(await steal(expansion))) break;
224
225
  }
225
- if (getRankedStringCount() !== startupStrings) return undefined;
226
+ if (getRankedStringCount() !== startupStrings) {
227
+ return { type: "abort", string: getRankedString(startupStrings) };
228
+ }
226
229
  frontier.states = expansion.next;
227
230
  Atomics.store(remaining, workerIndex, frontier.states.length);
228
231
  return {
package/src/parallel.ts CHANGED
@@ -31,6 +31,7 @@ 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;
@@ -232,7 +237,7 @@ export const check = async (options: CheckOptions): Promise<CheckResult> => {
232
237
  if (!(error instanceof TlaEvaluationError)) throw error;
233
238
  return fallBack();
234
239
  }
235
- if (getRankedStringCount() !== startupStrings) return fallBack();
240
+ if (getRankedStringCount() !== startupStrings) return fallBack(getRankedString(startupStrings));
236
241
  statistics.depth = statistics.generatedStates === 0 ? 0 : 1;
237
242
  statistics.initialStates = {
238
243
  generated: statistics.generatedStates,
@@ -324,7 +329,10 @@ export const check = async (options: CheckOptions): Promise<CheckResult> => {
324
329
  const messages = await collectLevels(await reported);
325
330
  if (isAborted(messages)) {
326
331
  terminate();
327
- 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);
328
336
  }
329
337
  const levels = messages.flatMap((message) => (message.type === "level" ? [message] : []));
330
338
  const added = levels.reduce((sum, message) => sum + message.added, 0);