tla-ts 0.0.2 → 0.0.3-dev.14337b3

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 (65) hide show
  1. package/README.md +78 -12
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +85 -15
  4. package/dist/index.d.ts +85 -15
  5. package/dist/index.js +1 -1
  6. package/dist/parallel-worker.cjs +2 -2
  7. package/dist/parallel-worker.js +2 -2
  8. package/dist/parallel.cjs +1 -1
  9. package/dist/parallel.js +2 -2
  10. package/dist/run-cli.cjs +22 -2
  11. package/dist/run-cli.js +22 -2
  12. package/dist/transfer.cjs +37 -16
  13. package/dist/transfer.js +37 -16
  14. package/package.json +3 -1
  15. package/src/ast.ts +137 -4
  16. package/src/check.ts +378 -100
  17. package/src/cli-options.ts +64 -0
  18. package/src/codegen.ts +15 -22
  19. package/src/config.ts +224 -170
  20. package/src/dependencies.ts +2 -2
  21. package/src/environment.ts +116 -28
  22. package/src/errors.ts +101 -3
  23. package/src/evaluate.ts +129 -153
  24. package/src/exit-codes.ts +39 -42
  25. package/src/fingerprints.ts +46 -11
  26. package/src/instances.ts +16 -15
  27. package/src/levels.ts +62 -34
  28. package/src/lexer.ts +11 -2
  29. package/src/live-check.ts +772 -0
  30. package/src/liveness.ts +116 -543
  31. package/src/obligation-action.ts +384 -0
  32. package/src/obligation-anon.ts +575 -0
  33. package/src/obligation-deref.ts +637 -0
  34. package/src/obligation-expression.ts +1060 -0
  35. package/src/obligation-format.ts +406 -0
  36. package/src/obligation-generate.ts +1074 -0
  37. package/src/obligation-levels.ts +329 -0
  38. package/src/obligation-module.ts +1042 -0
  39. package/src/obligation-printer.ts +889 -0
  40. package/src/obligation-proof.ts +76 -0
  41. package/src/obligation-source.ts +1084 -0
  42. package/src/obligation-tuples.ts +184 -0
  43. package/src/obligations.ts +316 -0
  44. package/src/parallel-worker.ts +168 -212
  45. package/src/parallel.ts +78 -37
  46. package/src/parser.ts +315 -60
  47. package/src/resolve.ts +122 -44
  48. package/src/run-cli.ts +376 -44
  49. package/src/runtime.ts +3 -1
  50. package/src/spec-description.ts +19 -8
  51. package/src/standard-levels.ts +3 -3
  52. package/src/standard-modules.ts +2 -7
  53. package/src/state-graph.ts +157 -0
  54. package/src/subexpressions.ts +10 -10
  55. package/src/successors.ts +99 -25
  56. package/src/symmetry.ts +30 -8
  57. package/src/tableau.ts +51 -24
  58. package/src/tlc-ext.ts +29 -12
  59. package/src/tlc-module.ts +14 -33
  60. package/src/tlc-modules.ts +4 -0
  61. package/src/tlc-order.ts +25 -7
  62. package/src/tlc-random.ts +9 -6
  63. package/src/tlc-summary.ts +20 -5
  64. package/src/transfer.ts +22 -1
  65. package/src/values.ts +179 -42
package/src/evaluate.ts CHANGED
@@ -1,18 +1,19 @@
1
- import type {
2
- Bound,
3
- BoundPattern,
4
- DecimalExpression,
5
- Definition,
6
- Expression,
7
- FunctionDefinition,
8
- NumberExpression,
9
- OperatorParam,
10
- RecordField,
11
- SourceRange,
1
+ import {
2
+ getChildren,
3
+ isLocallyResolved,
4
+ type Bound,
5
+ type BoundPattern,
6
+ type DecimalExpression,
7
+ type Definition,
8
+ type Expression,
9
+ type FunctionDefinition,
10
+ type NumberExpression,
11
+ type OperatorParam,
12
+ type RecordField,
12
13
  } from "./ast";
13
14
  import { getKindString } from "./builtins";
14
- import { TlaEvaluationError } from "./errors";
15
- import { EXIT_STATUS, setExitCode } from "./exit-codes";
15
+ import { formatRange, TlaEvaluationError } from "./errors";
16
+ import { EXIT_STATUS, setExitCode, setOwnExitCode } from "./exit-codes";
16
17
  import { generateEvaluator } from "./codegen";
17
18
  import type { CheckerRuntime } from "./runtime";
18
19
  import { getReadVariables } from "./dependencies";
@@ -28,23 +29,26 @@ import {
28
29
  createSortedSet,
29
30
  createWrittenRecord,
30
31
  createTuple,
32
+ describeMissingField,
31
33
  formatValue,
32
34
  getDomain,
33
35
  getFunctionDomain,
34
36
  getIntervalElements,
35
37
  getSequenceElements,
36
38
  getValueHash,
37
- isEnumerable,
38
39
  isFunctionValue,
39
40
  isOverriddenSet,
41
+ isRecordValue,
40
42
  isSameValue,
41
43
  markLambdaFunction,
44
+ isReducible,
42
45
  isSetValue,
43
46
  MAXIMUM_INTEGER,
44
47
  MINIMUM_INTEGER,
45
48
  toFiniteSet,
46
49
  updateFunction,
47
50
  valuesEqual,
51
+ type FunctionValue,
48
52
  type LazyFunctionSource,
49
53
  type LazyFunctionValue,
50
54
  type Value,
@@ -141,9 +145,6 @@ const EXCEPT_AT = "@";
141
145
  export const describeLocation = (expression: Expression) =>
142
146
  `line ${expression.location.line}, column ${expression.location.column}`;
143
147
 
144
- export const formatRange = (range: SourceRange) =>
145
- `line ${range.start.line}, col ${range.start.column} to line ${range.end.line}, col ${range.end.column} of module ${range.module}`;
146
-
147
148
  export const describeRange = (expression: Expression) => {
148
149
  const range = expression.location.range;
149
150
  return range ? formatRange(range) : describeLocation(expression);
@@ -180,8 +181,17 @@ export const getConjunctError = (
180
181
  };
181
182
 
182
183
  export const getFieldError =
183
- (expression: Expression & { kind: "FieldAccess" }) => (record: Value) =>
184
- `Attempted to select nonexistent field "${expression.field}" from the record\n${formatValue(record)}\n${describeRange(expression)}`;
184
+ (expression: Expression & { kind: "FieldAccess" }) => (record: FunctionValue) =>
185
+ isRecordValue(record)
186
+ ? `Attempted to select nonexistent field "${expression.field}" from the record\n${formatValue(record)}\n${describeRange(expression)}`
187
+ : describeMissingField(record, expression.field);
188
+
189
+ export const getNonFunctionError = (expression: Expression) => (value: Value) =>
190
+ `A non-function (${getKindString(value)}) was applied as a function.\n${describeRange(expression)}`;
191
+
192
+ export const getNonRecordError =
193
+ (expression: Expression & { kind: "FieldAccess" }) => (value: Value) =>
194
+ `Attempted to select field "${expression.field}" from a non-record value ${formatValue(value)}\n${describeRange(expression)}`;
185
195
 
186
196
  export const getDomainOperator = (expression: Expression) => (value: Value) => {
187
197
  if (!isFunctionValue(value)) {
@@ -262,96 +272,6 @@ export const expectBoolean = (value: Value, description: string) => {
262
272
  return value;
263
273
  };
264
274
 
265
- export const getChildren = (expression: Expression): Expression[] => {
266
- switch (expression.kind) {
267
- case "Number":
268
- case "Decimal":
269
- case "String":
270
- case "Identifier":
271
- case "OperatorReference":
272
- case "ExceptAt":
273
- return [];
274
- case "Apply":
275
- return expression.args;
276
- case "Lambda":
277
- return [expression.body];
278
- case "And":
279
- case "Or":
280
- return expression.operands;
281
- case "Prime":
282
- case "Unchanged":
283
- case "Enabled":
284
- case "Always":
285
- case "Eventually":
286
- return [expression.expression];
287
- case "If":
288
- return [expression.condition, expression.consequent, expression.alternative];
289
- case "Case":
290
- return [
291
- ...expression.arms.flatMap((arm) => [arm.condition, arm.body]),
292
- ...(expression.other ? [expression.other] : []),
293
- ];
294
- case "Let":
295
- return [
296
- ...expression.definitions.flatMap((definition) =>
297
- definition.kind === "Function"
298
- ? [...definition.bounds.map((bound) => bound.set), definition.body]
299
- : [definition.body],
300
- ),
301
- expression.body,
302
- ];
303
- case "Forall":
304
- case "Exists":
305
- return [...expression.bounds.map((bound) => bound.set), expression.body];
306
- case "UnboundedQuantifier":
307
- return [expression.body];
308
- case "Choose":
309
- return [...(expression.set ? [expression.set] : []), expression.body];
310
- case "SetEnumeration":
311
- case "Tuple":
312
- return expression.elements;
313
- case "SetFilter":
314
- return [expression.bound.set, expression.predicate];
315
- case "SetMap":
316
- return [expression.expression, ...expression.bounds.map((bound) => bound.set)];
317
- case "FunctionConstruction":
318
- return [...expression.bounds.map((bound) => bound.set), expression.body];
319
- case "FunctionSet":
320
- return [expression.domain, expression.range];
321
- case "Record":
322
- case "RecordSet":
323
- return expression.fields.map((field) => field.value);
324
- case "Except":
325
- return [
326
- expression.function,
327
- ...expression.updates.flatMap((update) => [
328
- ...update.path.flatMap((step) => (step.kind === "Index" ? step.args : [])),
329
- update.value,
330
- ]),
331
- ];
332
- case "FunctionApplication":
333
- return [expression.function, ...expression.args];
334
- case "FieldAccess":
335
- return [expression.record];
336
- case "Product":
337
- return expression.factors;
338
- case "BoxAction":
339
- case "AngleAction":
340
- return [expression.action, expression.subscript];
341
- case "WeakFairness":
342
- case "StrongFairness":
343
- return [expression.subscript, expression.action];
344
- case "Label":
345
- return [expression.body];
346
- case "Subexpression":
347
- return expression.selectors.flatMap((selector) => ("args" in selector ? selector.args : []));
348
- }
349
- };
350
-
351
- export const isLocallyResolved = (expression: Expression) =>
352
- (expression.kind === "Identifier" || expression.kind === "Apply") &&
353
- expression.resolution?.kind === "Local";
354
-
355
275
  export const getDefinition = (name: string, environment: Environment) =>
356
276
  environment.definitions.get(environment.substitutions.get(name) ?? name);
357
277
 
@@ -734,7 +654,9 @@ const compileArgumentBinder = (argument: Expression, environment: Environment):
734
654
  if (global === undefined) {
735
655
  return (context) => {
736
656
  const binding = lookupScope(context.scope, argument.name);
737
- return binding?.kind === "Value" ? binding : createThunk(argument, context);
657
+ return binding?.kind === "Value" || binding?.kind === "Thunk"
658
+ ? binding
659
+ : createThunk(argument, context);
738
660
  };
739
661
  }
740
662
  }
@@ -857,11 +779,7 @@ const evaluateLocalIdentifier = (name: string, expression: Expression, context:
857
779
  const global = findGlobalName(name, context.environment);
858
780
  if (global?.kind === "Variable") {
859
781
  const value = context.state?.[global.index];
860
- if (value === undefined) {
861
- throw new TlaEvaluationError(
862
- `The variable ${name} is not assigned at ${describeLocation(expression)}`,
863
- );
864
- }
782
+ if (value === undefined) throw createUnassignedError(name, expression);
865
783
  return value;
866
784
  }
867
785
  if (global?.kind === "Value") return global.value;
@@ -887,14 +805,29 @@ const IMPURE_BUILTINS = new Set([
887
805
  export const isImpureBuiltin = (name: string, environment: Environment) =>
888
806
  IMPURE_BUILTINS.has(name) || environment.builtins.get(name)?.isStateLevel === true;
889
807
 
890
- const impureDefinitions = new WeakMap<Definition, boolean>();
808
+ interface Impurity {
809
+ builtins: Set<string>;
810
+ definitions: WeakMap<Definition, boolean>;
811
+ }
812
+
813
+ const ANY_EFFECT: Impurity = { builtins: IMPURE_BUILTINS, definitions: new WeakMap() };
814
+
815
+ // An Assert that held holds again, so evaluating it twice looks the same as evaluating it once.
816
+ const REPEATED_EFFECT: Impurity = {
817
+ builtins: new Set([...IMPURE_BUILTINS].filter((name) => name !== "Assert")),
818
+ definitions: new WeakMap(),
819
+ };
891
820
 
892
821
  const isEvaluatedOnce = (definition: Definition, environment: Environment) =>
893
822
  definition.kind === "Operator" &&
894
823
  definition.params.length === 0 &&
895
824
  isConstantLevel(definition, environment);
896
825
 
897
- const callsImpureBuiltin = (expression: Expression, environment: Environment): boolean => {
826
+ const callsImpureBuiltin = (
827
+ expression: Expression,
828
+ environment: Environment,
829
+ impurity: Impurity,
830
+ ): boolean => {
898
831
  const name =
899
832
  expression.kind === "Identifier"
900
833
  ? expression.name
@@ -903,29 +836,35 @@ const callsImpureBuiltin = (expression: Expression, environment: Environment): b
903
836
  : undefined;
904
837
  if (name !== undefined && !isLocallyResolved(expression)) {
905
838
  const definition = getDefinition(name, environment);
906
- if (!definition && isImpureBuiltin(name, environment)) return true;
839
+ const isImpureCall =
840
+ impurity.builtins.has(name) || environment.builtins.get(name)?.isStateLevel === true;
841
+ if (!definition && isImpureCall) return true;
907
842
  if (
908
843
  definition &&
909
844
  !isEvaluatedOnce(definition, environment) &&
910
- isImpureDefinition(definition, environment)
845
+ isImpureDefinition(definition, environment, impurity)
911
846
  ) {
912
847
  return true;
913
848
  }
914
849
  }
915
- return getChildren(expression).some((child) => callsImpureBuiltin(child, environment));
850
+ return getChildren(expression).some((child) => callsImpureBuiltin(child, environment, impurity));
916
851
  };
917
852
 
918
853
  // TLC evaluates a constant definition without parameters once, so only other definitions pass
919
854
  // on the side effects and random choices of the builtins they call.
920
- const isImpureDefinition = (definition: Definition, environment: Environment): boolean => {
921
- const cached = impureDefinitions.get(definition);
855
+ const isImpureDefinition = (
856
+ definition: Definition,
857
+ environment: Environment,
858
+ impurity = ANY_EFFECT,
859
+ ): boolean => {
860
+ const cached = impurity.definitions.get(definition);
922
861
  if (cached !== undefined) return cached;
923
- impureDefinitions.set(definition, false);
862
+ impurity.definitions.set(definition, false);
924
863
  const isImpure =
925
- callsImpureBuiltin(definition.body, environment) ||
864
+ callsImpureBuiltin(definition.body, environment, impurity) ||
926
865
  (definition.kind === "Function" &&
927
- definition.bounds.some((bound) => callsImpureBuiltin(bound.set, environment)));
928
- impureDefinitions.set(definition, isImpure);
866
+ definition.bounds.some((bound) => callsImpureBuiltin(bound.set, environment, impurity)));
867
+ impurity.definitions.set(definition, isImpure);
929
868
  return isImpure;
930
869
  };
931
870
 
@@ -939,6 +878,12 @@ export const isImpure = (environment: Environment) =>
939
878
  isImpureDefinition(definition, environment),
940
879
  );
941
880
 
881
+ // Whether evaluating a definition again can show, such as by printing twice.
882
+ export const hasRepeatedEffects = (environment: Environment) =>
883
+ [...environment.definitions.values()].some((definition) =>
884
+ isImpureDefinition(definition, environment, REPEATED_EFFECT),
885
+ );
886
+
942
887
  const closedConstants = new WeakMap<Expression, boolean>();
943
888
 
944
889
  export const isClosedConstant = (expression: Expression, environment: Environment): boolean => {
@@ -1090,7 +1035,7 @@ export const getEvaluator = (expression: Expression, environment: Environment):
1090
1035
 
1091
1036
  const entryEvaluators = new WeakMap<Expression, Evaluator>();
1092
1037
 
1093
- const getEntryEvaluator = (expression: Expression, environment: Environment) => {
1038
+ export const getEntryEvaluator = (expression: Expression, environment: Environment) => {
1094
1039
  const cached = entryEvaluators.get(expression);
1095
1040
  if (cached) return cached;
1096
1041
  const evaluator =
@@ -1114,11 +1059,7 @@ const compileIdentifier = (
1114
1059
  const index = global.index;
1115
1060
  return (context) => {
1116
1061
  const value = context.state?.[index];
1117
- if (value === undefined) {
1118
- throw new TlaEvaluationError(
1119
- `The variable ${name} is not assigned at ${describeLocation(expression)}`,
1120
- );
1121
- }
1062
+ if (value === undefined) throw createUnassignedError(name, expression);
1122
1063
  return value;
1123
1064
  };
1124
1065
  }
@@ -1392,6 +1333,11 @@ const compileApply = (
1392
1333
  if (definition?.kind === "Function") {
1393
1334
  throw new TlaEvaluationError(`${expression.operator} is a function; apply it with brackets`);
1394
1335
  }
1336
+ if (expression.operator === "\\cdot") {
1337
+ throw new TlaEvaluationError(
1338
+ "The current version of TLC does not support action composition. An incomplete implementation can be enabled via the tlc2.tool.impl.Tool.cdot=true java property.",
1339
+ );
1340
+ }
1395
1341
  throw new TlaEvaluationError(
1396
1342
  `Unknown operator ${expression.operator} at ${describeLocation(expression)}`,
1397
1343
  );
@@ -1487,7 +1433,13 @@ const compileFunctionConstruction = (
1487
1433
  const set = getEvaluator(bound.set, environment);
1488
1434
  return (context) => {
1489
1435
  const domain = isSingleName ? set(context) : getBoundsDomain(bounds, context);
1490
- if (expression.isRecursive || isKeptLazy || !isEnumerable(domain)) {
1436
+ // TLC builds the function only when it reduces every domain, and evaluates the body lazily
1437
+ // otherwise.
1438
+ const domains =
1439
+ typeof domain === "object" && domain.kind === "ProductSet" && bounds.length > 1
1440
+ ? domain.factors
1441
+ : [domain];
1442
+ if (expression.isRecursive || isKeptLazy || !domains.every(isReducible)) {
1491
1443
  const functionValue = createLazyFunction(
1492
1444
  domain,
1493
1445
  (argument) => body(withScope(context, bindArgument(bounds, context.scope, argument))),
@@ -1581,10 +1533,7 @@ const compileSetComprehension = (
1581
1533
  predicate(withScope(context, bindPattern(context.scope, pattern, element))),
1582
1534
  "a set filter predicate",
1583
1535
  );
1584
- const isReducible =
1585
- typeof base === "object" &&
1586
- (base.kind === "Set" || base.kind === "MixedSet" || base.kind === "Interval");
1587
- if (!isReducible) {
1536
+ if (!isReducible(base)) {
1588
1537
  if (isSetValue(base)) return { kind: "FilteredSet", base, test };
1589
1538
  throw new TlaEvaluationError(
1590
1539
  `TLC encountered a non-enumerable quantifier bound ${formatValue(base)} at ${describeLocation(expression.bound.set)}`,
@@ -1630,11 +1579,29 @@ const compileSetComprehension = (
1630
1579
  };
1631
1580
  };
1632
1581
 
1633
- const compileRecord = (recordFields: RecordField[], environment: Environment): Evaluator => {
1634
- const fields = [...recordFields].sort((left, right) => compareValues(left.name, right.name));
1635
- const hasDuplicates = fields.some(
1636
- (field, index) => index > 0 && fields[index - 1].name === field.name,
1582
+ // TLC orders a record's fields by name.
1583
+ export const getSortedFields = (fields: RecordField[]) =>
1584
+ [...fields].sort((left, right) => compareValues(left.name, right.name));
1585
+
1586
+ export const hasDuplicateFields = (sortedFields: RecordField[]) =>
1587
+ sortedFields.some((field, index) => index > 0 && sortedFields[index - 1].name === field.name);
1588
+
1589
+ export const createUnassignedError = (name: string, expression: Expression) =>
1590
+ setOwnExitCode(
1591
+ new TlaEvaluationError(
1592
+ `In evaluation, the identifier ${name} is either undefined or not an operator.\n${describeRange(expression)}`,
1593
+ ),
1594
+ EXIT_STATUS.configParseError,
1637
1595
  );
1596
+
1597
+ export const createPrimeOutsideActionError = (expression: Expression) =>
1598
+ new TlaEvaluationError(
1599
+ `A primed expression appears outside an action at ${describeLocation(expression)}`,
1600
+ );
1601
+
1602
+ const compileRecord = (recordFields: RecordField[], environment: Environment): Evaluator => {
1603
+ const fields = getSortedFields(recordFields);
1604
+ const hasDuplicates = hasDuplicateFields(fields);
1638
1605
  const values = fields.map((field) => getEvaluator(field.value, environment));
1639
1606
  if (hasDuplicates) {
1640
1607
  return (context) =>
@@ -1712,11 +1679,7 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1712
1679
  case "Prime": {
1713
1680
  const inner = child(expression.expression);
1714
1681
  return (context) => {
1715
- if (!context.next) {
1716
- throw new TlaEvaluationError(
1717
- `A primed expression appears outside an action at ${describeLocation(expression)}`,
1718
- );
1719
- }
1682
+ if (!context.next) throw createPrimeOutsideActionError(expression);
1720
1683
  return inner({
1721
1684
  environment: context.environment,
1722
1685
  scope: context.scope,
@@ -1755,7 +1718,9 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1755
1718
  if (expectBoolean(arm.condition(context), "a CASE guard")) return arm.body(context);
1756
1719
  }
1757
1720
  if (other) return other(context);
1758
- throw new TlaEvaluationError(`No CASE guard is true at ${describeLocation(expression)}`);
1721
+ throw new TlaEvaluationError(
1722
+ `Attempted to evaluate a CASE with no conditions true.\n${describeRange(expression)}`,
1723
+ );
1759
1724
  };
1760
1725
  }
1761
1726
  case "Let": {
@@ -1794,9 +1759,7 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1794
1759
  case "Record":
1795
1760
  return compileRecord(expression.fields, environment);
1796
1761
  case "RecordSet": {
1797
- const fields = [...expression.fields].sort((left, right) =>
1798
- compareValues(left.name, right.name),
1799
- );
1762
+ const fields = getSortedFields(expression.fields);
1800
1763
  const names = fields.map((field) => field.name);
1801
1764
  const sets = fields.map((field) => child(field.value));
1802
1765
  return (context) => ({ kind: "RecordSet", names, sets: sets.map((set) => set(context)) });
@@ -1817,18 +1780,31 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1817
1780
  keepLazy(expression.function);
1818
1781
  const evaluateFunction = child(expression.function);
1819
1782
  const args = expression.args.map(child);
1783
+ const describeNonFunction = getNonFunctionError(expression);
1820
1784
  if (args.length === 1) {
1821
1785
  const argument = args[0];
1822
- return (context) => applyFunction(evaluateFunction(context), argument(context));
1786
+ return (context) =>
1787
+ applyFunction(
1788
+ evaluateFunction(context),
1789
+ argument(context),
1790
+ undefined,
1791
+ describeNonFunction,
1792
+ );
1823
1793
  }
1824
1794
  return (context) =>
1825
- applyFunction(evaluateFunction(context), createTuple(args.map((arg) => arg(context))));
1795
+ applyFunction(
1796
+ evaluateFunction(context),
1797
+ createTuple(args.map((arg) => arg(context))),
1798
+ undefined,
1799
+ describeNonFunction,
1800
+ );
1826
1801
  }
1827
1802
  case "FieldAccess": {
1828
1803
  const record = child(expression.record);
1829
1804
  const field = expression.field;
1830
1805
  const describeMissing = getFieldError(expression);
1831
- return (context) => applyFunction(record(context), field, describeMissing);
1806
+ const describeNonRecord = getNonRecordError(expression);
1807
+ return (context) => applyFunction(record(context), field, describeMissing, describeNonRecord);
1832
1808
  }
1833
1809
  case "Product": {
1834
1810
  const factors = expression.factors.map(child);
package/src/exit-codes.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { LivenessChecker } from "./liveness";
1
+ import type { LivenessChecker } from "./live-check";
2
2
 
3
3
  // TLC's exit statuses, from EC.ExitStatus.
4
4
  export const EXIT_STATUS = {
@@ -17,12 +17,6 @@ export const EXIT_STATUS = {
17
17
  } as const;
18
18
 
19
19
  const exitCodes = new WeakMap<Error, number>();
20
- const moduleExitCodes = new WeakMap<Error, number>();
21
- const phase = { isNextState: false };
22
-
23
- export const setNextStatePhase = (isNextState: boolean) => {
24
- phase.isNextState = isNextState;
25
- };
26
20
 
27
21
  // The innermost site that knows TLC's exit status for an error sets it first and wins.
28
22
  export const setExitCode = <Thrown>(error: Thrown, code: number) => {
@@ -30,46 +24,49 @@ export const setExitCode = <Thrown>(error: Thrown, code: number) => {
30
24
  return error;
31
25
  };
32
26
 
33
- // TLC exits with the code of an exception from a standard module's Java code only when the exception
34
- // escapes the computation of next states. In every other phase, the phase decides the code.
35
- export const setModuleExitCode = (error: Error, code: number) => {
36
- if (phase.isNextState) moduleExitCodes.set(error, code);
27
+ export const getExitCode = (error: Error) => exitCodes.get(error);
28
+
29
+ const ownExitCodes = new WeakMap<Error, number>();
30
+
31
+ // The exit status of the error code TLC gives an EvalException, which TLC uses only where it
32
+ // doesn't report the error again as a nested expression.
33
+ export const setOwnExitCode = <Thrown extends Error>(error: Thrown, code: number) => {
34
+ ownExitCodes.set(error, code);
35
+ return error;
37
36
  };
38
37
 
39
- export const getExitCode = (error: Error) => exitCodes.get(error) ?? moduleExitCodes.get(error);
38
+ export const getOwnExitCode = (error: unknown) =>
39
+ error instanceof Error ? ownExitCodes.get(error) : undefined;
40
40
 
41
- // TLC exits with 255 when it fails to process or evaluate a liveness property, in any phase.
42
- export const withLivenessExitCode = (
43
- create: () => LivenessChecker | undefined,
44
- ): LivenessChecker | undefined => {
41
+ // TLC exits with 255 when it fails to process or evaluate a liveness property.
42
+ const withErrorExitCode = <Result>(run: () => Result) => {
45
43
  try {
46
- const checker = create();
47
- return (
48
- checker && {
49
- addInitialState: (index, state) => {
50
- try {
51
- checker.addInitialState(index, state);
52
- } catch (error) {
53
- throw setExitCode(error, EXIT_STATUS.error);
54
- }
55
- },
56
- addState: (index, state, successors) => {
57
- try {
58
- return checker.addState(index, state, successors);
59
- } catch (error) {
60
- throw setExitCode(error, EXIT_STATUS.error);
61
- }
62
- },
63
- findViolation: () => {
64
- try {
65
- return checker.findViolation();
66
- } catch (error) {
67
- throw setExitCode(error, EXIT_STATUS.error);
68
- }
69
- },
70
- }
71
- );
44
+ return run();
72
45
  } catch (error) {
73
46
  throw setExitCode(error, EXIT_STATUS.error);
74
47
  }
75
48
  };
49
+
50
+ export const withLivenessExitCode = (
51
+ create: () => LivenessChecker | undefined,
52
+ ): LivenessChecker | undefined => {
53
+ const checker = withErrorExitCode(create);
54
+ return (
55
+ checker && {
56
+ // TLC replays the initial states to report an error, but skips the liveness check of a
57
+ // state it has already seen, so it exits with the status of the error's own code.
58
+ addInitialState: (index, state) => {
59
+ try {
60
+ checker.addInitialState(index, state);
61
+ } catch (error) {
62
+ throw setExitCode(error, getOwnExitCode(error) ?? EXIT_STATUS.error);
63
+ }
64
+ },
65
+ addState: (index, state, successors) =>
66
+ withErrorExitCode(() => checker.addState(index, state, successors)),
67
+ findViolation: () => withErrorExitCode(() => checker.findViolation()),
68
+ getViolatedProperties: (path, cycleStart) =>
69
+ withErrorExitCode(() => checker.getViolatedProperties(path, cycleStart)),
70
+ }
71
+ );
72
+ };
@@ -1,12 +1,10 @@
1
1
  import { getValueFingerprint, getValueHash, type Value } from "./values";
2
2
 
3
3
  const EMPTY = 0;
4
- const TOMBSTONE = 1;
5
4
  const INITIAL_CAPACITY = 1 << 12;
6
5
 
7
6
  interface FingerprintTable {
8
7
  insert: (first: number, second: number) => boolean;
9
- remove: (first: number, second: number) => void;
10
8
  }
11
9
 
12
10
  const mix = (hash: number) => {
@@ -26,15 +24,13 @@ export const writeStateFingerprint = (state: Value[], fingerprint: Int32Array) =
26
24
  fingerprint[1] = mix(second);
27
25
  };
28
26
 
29
- export const getFingerprintOwner = (second: number, count: number) => (second >>> 0) % count;
30
-
31
27
  export const createFingerprintTable = (): FingerprintTable => {
32
28
  const table = { slots: new Int32Array(INITIAL_CAPACITY * 2), used: 0 };
33
29
  const findSlot = (slots: Int32Array, first: number, second: number) => {
34
30
  const mask = slots.length / 2 - 1;
35
31
  for (let index = first & mask; ; index = (index + 1) & mask) {
36
32
  const stored = slots[index * 2];
37
- if (stored === EMPTY && slots[index * 2 + 1] === EMPTY) return index;
33
+ if (stored === EMPTY) return index;
38
34
  if (stored === first && slots[index * 2 + 1] === second) return index;
39
35
  }
40
36
  };
@@ -59,11 +55,50 @@ export const createFingerprintTable = (): FingerprintTable => {
59
55
  table.used++;
60
56
  return true;
61
57
  },
62
- remove: (first, second) => {
63
- const slot = findSlot(table.slots, first, second);
64
- if (table.slots[slot * 2] !== first) return;
65
- table.slots[slot * 2] = EMPTY;
66
- table.slots[slot * 2 + 1] = TOMBSTONE;
67
- },
68
58
  };
69
59
  };
60
+
61
+ // Workers share one table of 64-bit fingerprints. The first word is never 0, so 0 marks an empty slot.
62
+ export interface SharedFingerprints {
63
+ slots: BigInt64Array;
64
+ used: Int32Array;
65
+ }
66
+
67
+ const INITIAL_SHARED_CAPACITY = 1 << 10;
68
+
69
+ const insertSharedKey = (slots: BigInt64Array, key: bigint) => {
70
+ const mask = slots.length - 1;
71
+ for (let index = Number(key >> 32n) & mask; ; index = (index + 1) & mask) {
72
+ const stored = Atomics.load(slots, index);
73
+ if (stored === key) return false;
74
+ if (stored !== 0n) continue;
75
+ const previous = Atomics.compareExchange(slots, index, 0n, key);
76
+ if (previous === 0n) return true;
77
+ if (previous === key) return false;
78
+ }
79
+ };
80
+
81
+ export const createSharedFingerprints = (): SharedFingerprints => ({
82
+ slots: new BigInt64Array(new SharedArrayBuffer(INITIAL_SHARED_CAPACITY * 8)),
83
+ used: new Int32Array(new SharedArrayBuffer(4)),
84
+ });
85
+
86
+ export const insertSharedFingerprint = (
87
+ table: SharedFingerprints,
88
+ first: number,
89
+ second: number,
90
+ ) => {
91
+ const key = BigInt.asIntN(64, (BigInt(first) << 32n) | BigInt(second >>> 0));
92
+ if (!insertSharedKey(table.slots, key)) return false;
93
+ Atomics.add(table.used, 0, 1);
94
+ return true;
95
+ };
96
+
97
+ export const isSharedFingerprintsFull = (table: SharedFingerprints) =>
98
+ Atomics.load(table.used, 0) * 2 >= table.slots.length;
99
+
100
+ export const growSharedFingerprints = (table: SharedFingerprints): SharedFingerprints => {
101
+ const slots = new BigInt64Array(new SharedArrayBuffer(table.slots.byteLength * 2));
102
+ for (const key of table.slots) if (key !== 0n) insertSharedKey(slots, key);
103
+ return { slots, used: table.used };
104
+ };