tla-ts 0.0.8-dev.d9bffda → 0.0.9-dev.0dd11f695

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 (119) hide show
  1. package/README.md +30 -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 +40 -40
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +80 -10
  8. package/dist/index.d.ts +80 -10
  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-worker.cjs +1 -1
  13. package/dist/prove-worker.js +1 -1
  14. package/dist/prove.cjs +116 -36
  15. package/dist/prove.js +116 -36
  16. package/dist/run.cjs +143 -31
  17. package/dist/run.js +143 -31
  18. package/dist/tlapm.cjs +2 -2
  19. package/dist/tlapm.js +1 -1
  20. package/dist/transfer.cjs +128 -103
  21. package/dist/transfer.js +128 -103
  22. package/dist/worker.cjs +7 -7
  23. package/dist/worker.js +7 -7
  24. package/package.json +3 -1
  25. package/src/ast.ts +7 -21
  26. package/src/bags.ts +99 -99
  27. package/src/builtins.ts +44 -75
  28. package/src/bundled-modules.ts +1 -8
  29. package/src/check.ts +605 -311
  30. package/src/cli/options.ts +12 -3
  31. package/src/cli/run.ts +2 -2
  32. package/src/cli/runtime-invariants.ts +135 -0
  33. package/src/cli/shared.ts +20 -9
  34. package/src/cli/tlc-arguments.ts +646 -0
  35. package/src/cli/tlc-usage.ts +362 -0
  36. package/src/cli/tlc.ts +571 -185
  37. package/src/cli/typescript.ts +26 -0
  38. package/src/cli/xml-exporter.ts +4 -10
  39. package/src/codegen.ts +190 -46
  40. package/src/config.ts +101 -68
  41. package/src/coverage.ts +855 -0
  42. package/src/dependencies.ts +20 -28
  43. package/src/dfid.ts +636 -0
  44. package/src/environment.ts +266 -98
  45. package/src/errors.ts +142 -45
  46. package/src/evaluate.ts +632 -298
  47. package/src/exit-codes.ts +37 -1
  48. package/src/index.ts +3 -0
  49. package/src/instances.ts +85 -9
  50. package/src/java-overrides.ts +2 -12
  51. package/src/json-reader.ts +456 -0
  52. package/src/json.ts +262 -139
  53. package/src/levels.ts +2 -3
  54. package/src/lexer.ts +17 -26
  55. package/src/liveness-checker.ts +10 -18
  56. package/src/liveness.ts +121 -49
  57. package/src/parallel-worker.ts +14 -10
  58. package/src/parallel.ts +41 -17
  59. package/src/parser.ts +436 -90
  60. package/src/pcal/ast.ts +7 -28
  61. package/src/pcal/parse.ts +11 -39
  62. package/src/pcal/tokenize.ts +4 -20
  63. package/src/pcal/translate.ts +10 -42
  64. package/src/pcal/validate.ts +3 -21
  65. package/src/pretty-print.ts +1 -2
  66. package/src/prover/smt/solver/solver.ts +31 -27
  67. package/src/randomization.ts +84 -35
  68. package/src/resolve.ts +18 -60
  69. package/src/runtime.ts +11 -4
  70. package/src/sany/builtins.ts +3 -4
  71. package/src/sany/generator.ts +128 -176
  72. package/src/sany/levels.ts +6 -30
  73. package/src/sany/lexer.ts +7 -23
  74. package/src/sany/linter.ts +31 -29
  75. package/src/sany/modules.ts +1 -5
  76. package/src/sany/nodes.ts +4 -28
  77. package/src/sany/parse-error.ts +44 -100
  78. package/src/sany/report.ts +25 -40
  79. package/src/sany/selectors.ts +8 -22
  80. package/src/sany/source.ts +8 -15
  81. package/src/sany/xml.ts +11 -42
  82. package/src/search.ts +547 -144
  83. package/src/simulate.ts +694 -0
  84. package/src/spec-description.ts +166 -48
  85. package/src/standard-definitions.ts +2 -3
  86. package/src/standard-modules.ts +264 -68
  87. package/src/state-graph.ts +51 -18
  88. package/src/subexpressions.ts +31 -5
  89. package/src/successors.ts +267 -77
  90. package/src/symmetry.ts +31 -8
  91. package/src/tableau.ts +1 -2
  92. package/src/tlc/fingerprint.ts +183 -61
  93. package/src/tlc/jar-data.ts +113 -6
  94. package/src/tlc/messages.ts +122 -37
  95. package/src/tlc/order.ts +33 -38
  96. package/src/tlc/random.ts +16 -16
  97. package/src/tlc/replay.ts +563 -211
  98. package/src/tlc/summary.ts +2 -4
  99. package/src/tlc/tlc-operators.ts +81 -36
  100. package/src/tlc/tlcext-operators.ts +138 -117
  101. package/src/tlc/trace-spec.ts +273 -0
  102. package/src/tlc/value-stream.ts +143 -0
  103. package/src/tlc/version.ts +2 -4
  104. package/src/typescript/actions.ts +494 -0
  105. package/src/typescript/collections.ts +615 -0
  106. package/src/typescript/compile.ts +70 -0
  107. package/src/typescript/context.ts +106 -0
  108. package/src/typescript/emit.ts +122 -0
  109. package/src/typescript/expressions.ts +508 -0
  110. package/src/typescript/formula.ts +160 -0
  111. package/src/typescript/functions.ts +295 -0
  112. package/src/typescript/model.ts +164 -0
  113. package/src/typescript/names.ts +116 -0
  114. package/src/typescript/program.ts +51 -0
  115. package/src/typescript/properties.ts +148 -0
  116. package/src/typescript/scope.ts +117 -0
  117. package/src/typescript/steps.ts +175 -0
  118. package/src/typescript/types.ts +178 -0
  119. package/src/values.ts +832 -255
@@ -1,24 +1,32 @@
1
1
  import {
2
2
  getErrorExitCode,
3
+ getUnexpectedException,
3
4
  STACK_OVERFLOW_MESSAGE,
4
5
  TlaEvaluationError,
5
6
  TlaModuleError,
7
+ TlaSetBoundError,
8
+ TlaStackOverflowError,
9
+ TlaUncodedError,
10
+ TlaWarningAsError,
11
+ TOO_MANY_STATES_MESSAGE,
6
12
  UNEXPECTED_EVAL_EXCEPTION,
7
13
  UNEXPECTED_EXCEPTION,
8
14
  } from "../errors";
9
15
  import { setExitCode } from "../exit-codes";
10
16
  import type { TlcVersion } from "./version";
11
17
 
12
- // TLC's codes for the messages it prints, from tlc2.output.EC.
13
18
  export const MESSAGE_CODE = {
14
19
  general: 1000,
20
+ stackOverflow: 1005,
15
21
  commandLineError: 1102,
16
22
  initialState: 2102,
17
23
  nestedExpression: 2103,
18
24
  assumptionFalse: 2104,
19
25
  assumptionEvaluationError: 2105,
26
+ unchangedVariableChanged: 2143,
20
27
  exceptAppliedToUnknownField: 2144,
21
28
  fingerprintFailed: 2147,
29
+ initialStateIncomplete: 2106,
22
30
  invariantViolatedInitial: 2107,
23
31
  incompleteSuccessor: 2109,
24
32
  propertyViolatedInitial: 2108,
@@ -28,13 +36,20 @@ export const MESSAGE_CODE = {
28
36
  actionPropertyEvaluationFailed: 2113,
29
37
  deadlockReached: 2114,
30
38
  temporalPropertyViolated: 2116,
39
+ noInitialStates: 2118,
40
+ errorState: 2120,
31
41
  behaviorUpToThisPoint: 2121,
32
42
  backToState: 2122,
43
+ subscriptUndetermined: 2139,
44
+ subscriptMissingVariable: 2140,
33
45
  constantLevelInvariant: 2149,
34
46
  javaOverrideLoaded: 2168,
35
47
  starting: 2185,
36
48
  modelChecking: 2187,
49
+ simulating: 2188,
37
50
  finished: 2186,
51
+ traceSpecWritten: 2501,
52
+ traceSpecFailed: 2502,
38
53
  computingInit: 2189,
39
54
  initGenerated1: 2190,
40
55
  initGenerated2: 2191,
@@ -43,14 +58,27 @@ export const MESSAGE_CODE = {
43
58
  searchDepth: 2194,
44
59
  stats: 2199,
45
60
  progress: 2200,
61
+ coverageStart: 2201,
62
+ coverageEnd: 2202,
63
+ coverageValue: 2221,
64
+ depthFirstStats: 2204,
65
+ depthFirstLevel: 2205,
66
+ depthFirstProgress: 2206,
67
+ depthFirstInitGenerated: 2208,
68
+ simulationProgress: 2209,
69
+ simulationStats: 2210,
46
70
  temporalBranches: 2212,
71
+ statePrint1: 2216,
47
72
  statePrint2: 2217,
48
73
  statePrint3: 2218,
49
74
  sanyFinished: 2219,
50
75
  startingSany: 2220,
51
76
  stateLevelProperty: 2255,
77
+ noInitialStatesInModel: 2256,
52
78
  version: 2262,
79
+ depthFirstModelChecking: 2271,
53
80
  noSpecificationButProperty: 2257,
81
+ fairnessTautology: 2258,
54
82
  noFairnessButProperty: 2259,
55
83
  counterExample: 2264,
56
84
  checkingTemporalEnd: 2267,
@@ -62,17 +90,23 @@ export const MESSAGE_CODE = {
62
90
  javaOverrideMismatch: 2400,
63
91
  postconditionFalse: 2404,
64
92
  postconditionFailed: 2405,
93
+ coverageNext: 2772,
94
+ coverageInit: 2773,
95
+ coverageProperty: 2774,
96
+ coverageValueCost: 2775,
97
+ coverageEndOverhead: 2777,
98
+ coverageConstraint: 2778,
99
+ coverageVariable: 2779,
65
100
  possibleUnwitnessed: 2780,
66
101
  parsingFailed: 3002,
67
102
  configFileError: 5001,
103
+ moduleOverrideStdout: 20000,
68
104
  } as const;
69
105
 
70
- // TLC's message levels, from tlc2.output.MP.
71
106
  export const MESSAGE_LEVEL = { none: 0, error: 1, warning: 3, state: 4 } as const;
72
107
 
73
108
  type MessageLevel = (typeof MESSAGE_LEVEL)[keyof typeof MESSAGE_LEVEL];
74
109
 
75
- // Without -tool, TLC starts a message with the prefix of its level.
76
110
  const LEVEL_PREFIXES: Record<MessageLevel, string> = {
77
111
  0: "",
78
112
  1: "Error: ",
@@ -86,14 +120,20 @@ export interface MessagePrinter {
86
120
  print: (code: number, level: MessageLevel, text: string) => void;
87
121
  }
88
122
 
89
- // With -tool, TLC wraps each message in markers that name its code and level, so that a program
90
- // can read the output. Lines outside the markers, such as the output of Print, stay as they are.
91
- // MP.printWarning prints a warning once, which -nowarning drops, and without -tool, TLC follows the
92
- // first warning with how to drop them.
123
+ export const formatMessage = (isTool: boolean, code: number, level: MessageLevel, text: string) =>
124
+ isTool
125
+ ? `@!@!@STARTMSG ${code}:${level} @!@!@\n${text}\n@!@!@ENDMSG ${code} @!@!@`
126
+ : `${LEVEL_PREFIXES[level]}${text}`;
127
+
128
+ // With -tool, TLC wraps each message in markers of its code and level, and leaves lines such as
129
+ // Print's bare. A warning prints once, -nowarning drops it, and without -tool the first one
130
+ // says how to drop them.
93
131
  export const createMessagePrinter = (
94
132
  isTool: boolean,
95
133
  isWarningEnabled = true,
96
134
  version: TlcVersion = "master",
135
+ suppressedCodes: number[] = [],
136
+ errorCodes: number[] = [],
97
137
  ): MessagePrinter => {
98
138
  const warnings = new Set<string>();
99
139
  return {
@@ -101,14 +141,16 @@ export const createMessagePrinter = (
101
141
  version,
102
142
  print: (code, level, text) => {
103
143
  const isWarning = level === MESSAGE_LEVEL.warning;
144
+ if (isWarning && errorCodes.includes(code)) {
145
+ throw new TlaWarningAsError(code, text);
146
+ }
104
147
  if (isWarning && !isWarningEnabled) return;
148
+ if (level !== MESSAGE_LEVEL.error && suppressedCodes.includes(code)) return;
105
149
  const hint =
106
150
  isWarning && !isTool && warnings.size === 0
107
151
  ? "\n(Use the -nowarning option to disable this warning.)"
108
152
  : "";
109
- const message = isTool
110
- ? `@!@!@STARTMSG ${code}:${level} @!@!@\n${text}\n@!@!@ENDMSG ${code} @!@!@`
111
- : `${LEVEL_PREFIXES[level]}${text}${hint}`;
153
+ const message = formatMessage(isTool, code, level, `${text}${hint}`);
112
154
  if (isWarning && warnings.has(message)) return;
113
155
  if (isWarning) warnings.add(message);
114
156
  console.log(message);
@@ -116,19 +158,25 @@ export const createMessagePrinter = (
116
158
  };
117
159
  };
118
160
 
119
- // TLC 1.7.4's message for a missing initial predicate, which blames a parameterized INSTANCE as
120
- // well.
161
+ // TLC 1.7.4's message for a missing initial predicate also blames a parameterized INSTANCE.
121
162
  export const MISSING_INIT_174 =
122
163
  "The configuration file did not specify the initial state predicate.\nCan also be caused by trying to run TLC on a specification from\na module imported with a parameterized INSTANCE statement.";
123
164
 
124
- // The messages that TLC builds from a message code, from tlc2.output.MP, by their code and
125
- // template, with whether TLC throws them as an EvalException rather than a TLCRuntimeException.
165
+ // isEvalException: whether TLC throws the message as an EvalException, not a TLCRuntimeException.
126
166
  // TLC's -tool output wraps such a message in its own markers even inside another message.
127
167
  const CODED_MESSAGES: [code: number, template: string, isEvalException: boolean][] = [
128
168
  [1005, STACK_OVERFLOW_MESSAGE, false],
169
+ [
170
+ 1000,
171
+ "In evaluating TLCExt!Trace, the state is not completely specified yet (variable%1% %2% undefined).",
172
+ false,
173
+ ],
174
+ [1000, "Could not find operator: %1% in module: %2%", false],
129
175
  [2117, "Failed to recover the next state from its fingerprint.", true],
130
176
  [2123, "Failed to recover the initial state from its fingerprint.", true],
131
177
  [2132, "The first argument of Assert evaluated to FALSE; the second argument was:\n%1%", true],
178
+ [2143, "The variable %1% was changed while it is specified as UNCHANGED at\n%2%", false],
179
+ [2144, "The EXCEPT was applied to non-existing fields of the value at\n%1%", false],
132
180
  [2145, "TLCGet(%1%) was undefined.", true],
133
181
  [
134
182
  2154,
@@ -147,8 +195,13 @@ const CODED_MESSAGES: [code: number, template: string, isEvalException: boolean]
147
195
  "Attempted to apply TransitiveClosure to a set containing\nthe following value:\n%1%",
148
196
  true,
149
197
  ],
198
+ [2156, "TLC supports at most %1% model values, but model value %2% exceeds this limit.", false],
199
+ [2156, "tla-ts can't recover a model check from the checkpoint in %1%.", false],
150
200
  [2165, "Choose can only deal with numbers up to %1%", false],
151
201
  [2169, "The %1% argument of %2% should be a %3%, but instead it is:\n%4%", true],
202
+ [2170, "Argument mismatch in operator application.%1%", false],
203
+ [2171, "Parsing or semantic analysis failed.%1%", false],
204
+ [2172, TOO_MANY_STATES_MESSAGE, false],
152
205
  [2176, "Applying %1% to the following value,\nwhich is not %2%:\n%3%", true],
153
206
  [
154
207
  2177,
@@ -207,12 +260,23 @@ const CODED_MESSAGES: [code: number, template: string, isEvalException: boolean]
207
260
  [2233, "The %1% %2% cannot be a constant.", false],
208
261
  [2234, "The operator %1% cannot take any argument.", false],
209
262
  [2235, "The operator %1% is not defined in the spec.", false],
263
+ [2236, "The operator %1%, which equals %2%,\ncannot be used as a %3%", false],
210
264
  [2237, "The spec is trivially false because %1% is false.", false],
211
265
  [2238, "TLC cannot handle subscript %1%", false],
212
266
  [2239, "TLC cannot handle this conjunct of the spec:\n%1%", false],
267
+ [
268
+ 2240,
269
+ "The specification contains more than one conjunct of the form [][Next]_v,\nbut TLC can handle only specifications with one next-state relation.",
270
+ false,
271
+ ],
213
272
  [2241, "The property %1% is not correctly defined.", false],
214
273
  [2242, "The arity of the operator %1% is inconsistent in the configuration file.", false],
215
274
  [2244, "TLC can't handle real numbers.\n%1%", false],
275
+ [
276
+ 2245,
277
+ "In the configuration file, the module name %1% is not a module in the specification.",
278
+ false,
279
+ ],
216
280
  [2247, "In computing %1%, TLC expected a %2% expression,\nbut instead found %3%.\n%4%", false],
217
281
  [2248, "In computing %1%, TLC expected a %2% expression,\nbut didn't find one.\n%3%", false],
218
282
  [2260, "In computing ENABLED, TLC encountered a temporal formula (%1%).\n%2%", false],
@@ -223,6 +287,21 @@ const CODED_MESSAGES: [code: number, template: string, isEvalException: boolean]
223
287
  ],
224
288
  [2265, "TLC can't handle a number this big.\n%1%", false],
225
289
  [2266, "The %1% argument of %2% should be an %3%, but instead it is:\n%4%", true],
290
+ [
291
+ 2272,
292
+ "The formula %1% at %2% is an action-level formula (i.e., it contains no temporal operators). Only temporal-level (or state-level) formulas are allowed under PROPERTY or PROPERTIES. To check that action %1% holds in *every* step of the behavior, define a temporal property: Let A be the formula at %2%; rewrite A as [][A]_v, where v is a state function (typically the tuple of variables) (compare page 90 of Specifying Systems at https://lamport.azurewebsites.net/tla/book.html).",
293
+ false,
294
+ ],
295
+ [
296
+ 2273,
297
+ 'The formula %1% at %2% is an action-level formula (i.e., it contains no temporal operators). Only temporal-level (or state-level) formulas are allowed under PROPERTY or PROPERTIES. To check that action %1% holds in *every* step of the behavior, define a temporal property by applying the "always" temporal operator ([]) to the formula at %2% (compare page 90 of Specifying Systems at https://lamport.azurewebsites.net/tla/book.html).',
298
+ false,
299
+ ],
300
+ [
301
+ 2274,
302
+ 'The formula %1% at %2% is an action-level formula (i.e., it contains no temporal operators). Only temporal-level (or state-level) formulas are allowed under PROPERTY or PROPERTIES. To check that infinitely many %1% steps occur, define a temporal property by applying the "always eventually" temporal operator combination ([]<>) to the formula at %2% (compare page 91 of Specifying Systems at https://lamport.azurewebsites.net/tla/book.html).',
303
+ false,
304
+ ],
226
305
  [2280, "In evaluation, the identifier %1% is either undefined or not an operator.\n%2%", false],
227
306
  [2281, "The configuration file substitutes constant %1% with non-constant %2%%3%", false],
228
307
  [2283, "The argument of %1% should be a %2%, but instead it is:\n%3%", true],
@@ -249,6 +328,8 @@ const CODED_MESSAGES: [code: number, template: string, isEvalException: boolean]
249
328
  [5007, "TLC found an error in the configuration file:\n%1%", false],
250
329
  // The general message is a prefix of the others above.
251
330
  [5002, "TLC found an error in the configuration file at line %1%\n", false],
331
+ [2250, "A state predicate was evaluated to a non-boolean value.", false],
332
+ [2252, "Encountered an action predicate that's not a boolean.", false],
252
333
  [2253, "Temporal formula is a tautology (its negation is unsatisfiable).", false],
253
334
  [
254
335
  2301,
@@ -277,18 +358,17 @@ const getCodedMessagePatterns = () =>
277
358
  message: { code, isEvalException },
278
359
  })));
279
360
 
280
- // The overflows of SetOfFcnsValue and SetOfTuplesValue, which TLC raises with a plain message that
281
- // reads like the coded overflow of SetOfRcdsValue and SubsetValue.
361
+ // Plain messages that read like coded ones: the overflows of SetOfFcnsValue and SetOfTuplesValue,
362
+ // SetPredValue's tuple membership, and Tool#enabled's for ~> and -+->.
282
363
  const UNCODED_MESSAGE_PATTERN =
283
- /^Overflow when computing the number of elements in( |:\n\[(?![A-Za-z0-9_]+ : ))/;
364
+ /^Overflow when computing the number of elements in( |:\n\[(?![A-Za-z0-9_]+: ))|\nis an element of a set of \d+-tuples\.$|^In computing ENABLED, TLC encountered a temporal formula \(a (~> b|-\+-> formula)\)\./;
284
365
 
285
366
  export const getCodedMessage = (text: string): CodedMessage | undefined =>
286
367
  UNCODED_MESSAGE_PATTERN.test(text)
287
368
  ? undefined
288
369
  : getCodedMessagePatterns().find((item) => item.pattern.test(text))?.message;
289
370
 
290
- // Whether TLC raises an error as an EvalException, which only a standard module's Java code throws,
291
- // rather than as the TLCRuntimeException of every Assert.fail.
371
+ // Only a standard module's Java code throws an EvalException; Assert.fail throws the other kind.
292
372
  export const isEvalException = (error: TlaEvaluationError) =>
293
373
  error instanceof TlaModuleError || getCodedMessage(error.message)?.isEvalException === true;
294
374
 
@@ -298,12 +378,13 @@ const INNER_MESSAGE_PREFIXES = new Map([
298
378
  [1000, "\n: "],
299
379
  [2105, "failed.\n"],
300
380
  [2154, "but it produced the following error:\n"],
381
+ [2171, "Parsing or semantic analysis failed."],
301
382
  [2213, ":\n"],
302
383
  [2281, " - specifically: "],
384
+ [2405, "failed.\n"],
303
385
  ]);
304
386
 
305
- // The text of a coded message with the message of the error it reports marked in -tool output, as
306
- // TLC's message holds that error's text as TLC printed it.
387
+ // TLC's message holds the inner error's text as TLC printed it, markers included.
307
388
  export const formatInnerMessage = (code: number, text: string, isTool: boolean) => {
308
389
  const prefix = isTool ? INNER_MESSAGE_PREFIXES.get(code) : undefined;
309
390
  const index = prefix === undefined ? -1 : text.indexOf(prefix);
@@ -312,7 +393,6 @@ export const formatInnerMessage = (code: number, text: string, isTool: boolean)
312
393
  return `${text.slice(0, end)}${formatNestedMessage(text.slice(end), isTool)}`;
313
394
  };
314
395
 
315
- // The text of an error's message as TLC prints it inside another message.
316
396
  export const formatNestedMessage = (text: string, isTool: boolean): string => {
317
397
  const code = isTool ? getCodedMessage(text)?.code : undefined;
318
398
  return code === undefined
@@ -322,7 +402,6 @@ export const formatNestedMessage = (text: string, isTool: boolean): string => {
322
402
 
323
403
  const zeroPad = (value: number) => String(value).padStart(2, "0");
324
404
 
325
- // TLC's convertRuntimeToHumanReadable: a duration in its two largest units.
326
405
  export const formatTlcDuration = (milliseconds: number) => {
327
406
  const seconds = Math.floor(milliseconds / 1000) % 60;
328
407
  const minutes = Math.floor(milliseconds / 60_000) % 60;
@@ -334,12 +413,9 @@ export const formatTlcDuration = (milliseconds: number) => {
334
413
  : `${zeroPad(seconds)}s`;
335
414
  };
336
415
 
337
- // TLC's SimpleDateFormat("yyyy-MM-dd HH:mm:ss") in the local time zone.
338
416
  export const formatTlcDate = (date: Date) =>
339
417
  `${date.getFullYear()}-${zeroPad(date.getMonth() + 1)}-${zeroPad(date.getDate())} ${zeroPad(date.getHours())}:${zeroPad(date.getMinutes())}:${zeroPad(date.getSeconds())}`;
340
418
 
341
- // An error that TLC reports with a message of its own, by that message's code and first line, and
342
- // the error whose message follows.
343
419
  interface HeadedError {
344
420
  code: number;
345
421
  headline: string;
@@ -360,18 +436,18 @@ export const withHeadline = (error: unknown, code: number, headline: string) =>
360
436
 
361
437
  export const isHeadedError = (error: Error) => headedErrors.has(error);
362
438
 
439
+ const WRONG_INVOCATION_EXCEPTION = getUnexpectedException("util.WrongInvocationException");
440
+
363
441
  const UNEXPECTED_HEADLINE = UNEXPECTED_EXCEPTION.slice(0, UNEXPECTED_EXCEPTION.indexOf("\n"));
364
442
 
365
- // TLC 1.7.4's Worker wraps an error in adding a successor in a RuntimeException, whose message
366
- // names the class of the error.
443
+ // TLC 1.7.4 wraps an error in adding a successor in a RuntimeException naming its class.
367
444
  const WRAPPED_EVAL_EXCEPTION = `${UNEXPECTED_EXCEPTION}tlc2.tool.EvalException: `;
368
445
  const WRAPPED_RUNTIME_EXCEPTION = `${UNEXPECTED_EXCEPTION}util.Assert$TLCRuntimeException: `;
369
446
 
370
447
  export const getWrappedException = (error: TlaEvaluationError) =>
371
448
  isEvalException(error) ? WRAPPED_EVAL_EXCEPTION : WRAPPED_RUNTIME_EXCEPTION;
372
449
 
373
- // TLC reports an EvalException, or a TLCRuntimeException without a message of its own, as an
374
- // exception it didn't expect.
450
+ // TLC reports an EvalException, or a TLCRuntimeException without its own message, as unexpected.
375
451
  export const withUnexpectedException = <Result>(compute: () => Result) => {
376
452
  try {
377
453
  return compute();
@@ -392,19 +468,17 @@ const UNEXPECTED_EXCEPTION_PREFIXES = [
392
468
  UNEXPECTED_EVAL_EXCEPTION,
393
469
  ];
394
470
 
395
- // The text of an error's message, with the message of a coded error inside it marked in -tool
396
- // output as TLC marks it.
397
471
  const formatErrorMessage = (error: TlaEvaluationError, isTool: boolean): string => {
398
472
  const headed = headedErrors.get(error);
399
473
  if (headed) return `${headed.headline}\n${formatErrorMessage(headed.inner, isTool)}`;
400
474
  const message = error.message;
475
+ if (error instanceof TlaUncodedError) return message;
401
476
  const prefix = UNEXPECTED_EXCEPTION_PREFIXES.find((start) => message.startsWith(start)) ?? "";
402
477
  return `${prefix}${formatNestedMessage(message.slice(prefix.length), isTool)}`;
403
478
  };
404
479
 
405
- // How TLC reports an error: with the code of its own message for an error that it reports with a
406
- // headline; and, when the error escapes the computation of next states, with the code of an
407
- // EvalException, or as an unexpected exception for any other error.
480
+ // TLC reports an error with a headline by its message's code, and one that escapes the next
481
+ // states with an EvalException's code, or as an unexpected exception.
408
482
  export interface FailureMessage {
409
483
  code: number;
410
484
  message: string;
@@ -424,6 +498,14 @@ export const getFailureMessage = (
424
498
  toolMessage: formatErrorMessage(error, true),
425
499
  };
426
500
  }
501
+ // TLC prints a StackOverflowError by its code in the next states, as plain text in the initial.
502
+ if (error instanceof TlaStackOverflowError) {
503
+ return {
504
+ code: isNextState ? MESSAGE_CODE.stackOverflow : MESSAGE_CODE.general,
505
+ message,
506
+ toolMessage: message,
507
+ };
508
+ }
427
509
  if (isNextState && isEvalException(error)) {
428
510
  return {
429
511
  code: getCodedMessage(message)?.code ?? MESSAGE_CODE.general,
@@ -431,8 +513,11 @@ export const getFailureMessage = (
431
513
  toolMessage: message,
432
514
  };
433
515
  }
434
- const isUnexpected = isNextState && !message.startsWith(UNEXPECTED_HEADLINE);
435
- const prefix = isUnexpected ? UNEXPECTED_EXCEPTION : "";
516
+ const isUnexpected =
517
+ isNextState && !message.startsWith(UNEXPECTED_HEADLINE) && !(error instanceof TlaUncodedError);
518
+ const exception =
519
+ error instanceof TlaSetBoundError ? WRONG_INVOCATION_EXCEPTION : UNEXPECTED_EXCEPTION;
520
+ const prefix = isUnexpected ? exception : "";
436
521
  return {
437
522
  code: MESSAGE_CODE.general,
438
523
  message: `${prefix}${message}`,
package/src/tlc/order.ts CHANGED
@@ -1,11 +1,11 @@
1
- // TLC orders strings and model values by when it first interned their text, and compares a
2
- // state's variables in the order of SANY's symbol table. This reproduces both orders.
1
+ // Reproduces TLC's string order, by first interning, and its variable order, from SANY's context.
3
2
  import type { Module, SourceLocation } from "../ast";
4
3
  import type { ConfigValue, ModelConfig } from "../config";
5
4
  import { createMissingModuleError } from "../errors";
6
5
  import { tokenize, type Token } from "../lexer";
7
6
  import { extractModule, parseModule, parseModuleTokens } from "../parser";
8
7
  import { isBefore } from "../resolve";
8
+ import { SANY_STANDARD_MODULES } from "../sany/modules";
9
9
  import {
10
10
  SANY_BUILTINS,
11
11
  SANY_NODE_NAMES,
@@ -13,7 +13,6 @@ import {
13
13
  TLC_MODULE_SOURCES,
14
14
  TLC_RUNTIME_STRINGS,
15
15
  TLC_STARTUP_STRINGS,
16
- USER_STANDARD_MODULES,
17
16
  } from "./jar-data";
18
17
 
19
18
  type SymbolKind = "builtin" | "constant" | "variable" | "definition" | "theorem" | "module";
@@ -66,9 +65,8 @@ const getJavaHash = (text: string) => {
66
65
  return hash;
67
66
  };
68
67
 
69
- // java.util.Hashtable as SANY's Context uses it: default capacity 11, load factor 0.75, new
70
- // entries at the head of their bucket, and enumeration from the last bucket to the first. Each
71
- // bucket lists its entries from tail to head, so a new entry goes at the end.
68
+ // java.util.Hashtable as SANY's Context uses it: capacity 11, load factor 0.75, new entries at
69
+ // the head of their bucket, and enumeration from the last bucket, each from tail to head.
72
70
  const createSymbolTable = (): SymbolTable => {
73
71
  let buckets: SymbolEntry[][] = Array.from({ length: 11 }, () => []);
74
72
  let threshold = 8;
@@ -156,8 +154,7 @@ type ModuleSearch = (
156
154
  visited: Set<string>,
157
155
  ) => [ModuleReferences, string] | undefined;
158
156
 
159
- // The modules a module extends and instantiates, with its inner modules, as SANY's SpecObj
160
- // walks them to decide which module to parse next.
157
+ // In the order SANY's SpecObj walks them to decide which module to parse next.
161
158
  const getModuleReferences = (
162
159
  tokens: Token[],
163
160
  unit: string | undefined,
@@ -212,9 +209,8 @@ const STRING_ESCAPES: Record<string, string> = {
212
209
  "\f": "\\f",
213
210
  };
214
211
 
215
- // The texts SANY interns while parsing, in order. SANY reads a proof step label such as <1>2 and
216
- // a module header such as ---- MODULE as one token. It interns a string literal as written, quotes
217
- // included, and interns the literal's contents only during semantic analysis.
212
+ // SANY reads <1>2 and ---- MODULE as one token each, and interns a string literal with its
213
+ // quotes, its contents only during semantic analysis.
218
214
  const getParsedTexts = (tokens: Token[]) => {
219
215
  const texts: string[] = [];
220
216
  for (let index = 0; index < tokens.length; index++) {
@@ -268,8 +264,7 @@ interface ModuleText {
268
264
  getModule: () => Module;
269
265
  }
270
266
 
271
- // A module's source is read into tokens once, and parsed from them once, for every order and for
272
- // the environment that evaluates it.
267
+ // Read and parsed once, for every order and for the environment that evaluates it.
273
268
  const readModuleText = (text: string | undefined): ModuleText => {
274
269
  const tokens = text === undefined ? [] : tokenize(text);
275
270
  const parsed = { module: undefined as Module | undefined };
@@ -281,13 +276,10 @@ const readModuleText = (text: string | undefined): ModuleText => {
281
276
  };
282
277
  };
283
278
 
284
- // The modules TLC reads for a spec: the root module, TLC's standard modules, the files the loader
285
- // returns, the modules that follow the root module, and the modules nested in any of these. A
286
- // module without a source has no tokens.
279
+ // A module without a source has no tokens.
287
280
  const createModuleSet = (source: string, loadModule: ModuleLoader) => {
288
281
  const files = new Map<string, ParsedModule>();
289
282
  const nestedModules = new Map<string, ParsedModule>();
290
- // The read of each module text, so that the environment parses a text the order read only once.
291
283
  const texts = new Map<string, ModuleText>();
292
284
  const readText = (text: string | undefined) => {
293
285
  const known = text === undefined ? undefined : texts.get(text);
@@ -302,9 +294,9 @@ const createModuleSet = (source: string, loadModule: ModuleLoader) => {
302
294
  const text =
303
295
  name === undefined
304
296
  ? source
305
- : ((USER_STANDARD_MODULES.has(name) ? loadModule?.(name) : undefined) ??
297
+ : (loadModule?.(name) ??
306
298
  TLC_MODULE_SOURCES.get(name) ??
307
- loadModule?.(name) ??
299
+ SANY_STANDARD_MODULES.get(name) ??
308
300
  extractModule(source, name));
309
301
  const { tokens, ranges, getModule } = readText(text);
310
302
  const range = ranges.get(getModuleName(tokens) ?? "") ?? { start: 0, end: 0 };
@@ -328,7 +320,7 @@ const createModuleSet = (source: string, loadModule: ModuleLoader) => {
328
320
  };
329
321
  };
330
322
 
331
- // SANY's Context of each module, which the root module has under undefined.
323
+ // The root module's context is under undefined.
332
324
  type ModuleSet = ReturnType<typeof createModuleSet>["getParsed"];
333
325
 
334
326
  const createContexts = (getParsed: ModuleSet) => {
@@ -347,6 +339,13 @@ const createContexts = (getParsed: ModuleSet) => {
347
339
  const recursiveNames = new Set(
348
340
  module.definitions.filter((definition) => definition.isRecursive).map((item) => item.name),
349
341
  );
342
+ const declarationKeywords = new Set(
343
+ module.units.flatMap((moduleUnit) =>
344
+ moduleUnit.kind === "Constants" || moduleUnit.kind === "Variables"
345
+ ? [`${moduleUnit.location.line}:${moduleUnit.location.column}`]
346
+ : [],
347
+ ),
348
+ );
350
349
  const depth = { value: 0 };
351
350
  tokens.slice(unit.start, unit.end).forEach((_, offset) => {
352
351
  const index = unit.start + offset;
@@ -364,8 +363,13 @@ const createContexts = (getParsed: ModuleSet) => {
364
363
  }
365
364
  if (token.kind === "ModuleEnd") depth.value--;
366
365
  if (depth.value !== 1 || token.kind !== "Keyword") return;
367
- if (token.text === "CONSTANT" || token.text === "CONSTANTS") declare(index, "constant");
368
- if (token.text === "VARIABLE" || token.text === "VARIABLES") declare(index, "variable");
366
+ const isDeclaration = declarationKeywords.has(`${token.line}:${token.column}`);
367
+ if (isDeclaration && (token.text === "CONSTANT" || token.text === "CONSTANTS")) {
368
+ declare(index, "constant");
369
+ }
370
+ if (isDeclaration && (token.text === "VARIABLE" || token.text === "VARIABLES")) {
371
+ declare(index, "variable");
372
+ }
369
373
  if (token.text === "RECURSIVE") {
370
374
  const names = getDeclarations(tokens, index + 1);
371
375
  if (names.every((name) => recursiveNames.has(name))) declare(index, "definition");
@@ -458,9 +462,8 @@ const createContexts = (getParsed: ModuleSet) => {
458
462
  };
459
463
  };
460
464
 
461
- // Every string TLC interns before model checking starts, in order: values in the config, TLC's
462
- // startup strings, each module's tokens in the order SpecObj.loadSpec parses the modules, string
463
- // literals in semantic analysis order, and the names TLC interns for TLCGet.
465
+ // In order: config values, TLC's startup strings, each module's tokens as SpecObj.loadSpec
466
+ // parses them, string literals in semantic analysis order, and TLCGet's names.
464
467
  const getStringOrder = (getParsed: ModuleSet, config: ModelConfig): string[] => {
465
468
  const order = new Set<string>();
466
469
  const intern = (text: string) => {
@@ -564,23 +567,16 @@ const getStringOrder = (getParsed: ModuleSet, config: ModelConfig): string[] =>
564
567
  };
565
568
 
566
569
  export interface TlcOrder {
567
- // Every string TLC interns before model checking starts.
568
570
  getStringOrder: (config: ModelConfig) => string[];
569
- // The variables or constants of the root module in the reverse of its context enumeration, as
570
- // ModuleNode.getVariableDecls and getConstantDecls return them. TLC compares variables in this
571
- // order, and checks that the configuration assigns each constant in it.
571
+ // The reverse of the root module's context enumeration, in which TLC compares variables and
572
+ // checks that the configuration assigns each constant.
572
573
  getDeclarationOrder: (kind: "variable" | "constant") => string[];
573
- // The names of the definitions each module adds to its context, in the order of
574
- // ModuleNode.getOpDefs, in which TLC computes the constant definitions as it starts. An INSTANCE
575
- // adds the definitions of the module it instantiates in the order that module's Hashtable
576
- // enumerates them.
574
+ // In the order TLC computes constant definitions at startup. An INSTANCE adds those of the
575
+ // module it instantiates in the order that module's Hashtable enumerates them.
577
576
  createDefinitionOrder: () => (name: string | undefined) => string[];
578
- // Parses a module's source, once for the order and the environment.
579
577
  parseModule: (source: string) => Module;
580
578
  }
581
579
 
582
- // One check reads the spec's modules once, and every order shares their tokens, parses and
583
- // contexts.
584
580
  export const createTlcOrder = (source: string, loadModule: ModuleLoader): TlcOrder => {
585
581
  const modules = createModuleSet(source, loadModule);
586
582
  const getParsed = modules.getParsed;
@@ -598,8 +594,7 @@ export const createTlcOrder = (source: string, loadModule: ModuleLoader): TlcOrd
598
594
  parseModule: modules.parseText,
599
595
  createDefinitionOrder: () => {
600
596
  const { getContext, getOwnEntries } = getContexts();
601
- // The root module's context reads every file of the spec, and so finds the modules nested
602
- // in the files it extends or instantiates.
597
+ // The root module's context finds the modules nested in the files it extends or instantiates.
603
598
  getContext(undefined);
604
599
  return (name) =>
605
600
  getOwnEntries(name)