tla-ts 0.0.3-dev.bffbba3 → 0.0.3-dev.c2b256f

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 (81) hide show
  1. package/dist/cli.cjs +1 -1
  2. package/dist/cli.js +1 -1
  3. package/dist/index.cjs +1 -1
  4. package/dist/index.d.cts +150 -8
  5. package/dist/index.d.ts +150 -8
  6. package/dist/index.js +1 -1
  7. package/dist/parallel-worker.cjs +1 -1
  8. package/dist/parallel-worker.js +2 -2
  9. package/dist/parallel.cjs +1 -1
  10. package/dist/parallel.js +2 -2
  11. package/dist/run-cli.cjs +1351 -20
  12. package/dist/run-cli.js +1351 -20
  13. package/dist/transfer.cjs +86 -28
  14. package/dist/transfer.js +86 -28
  15. package/package.json +5 -1
  16. package/src/ast.ts +57 -6
  17. package/src/bags.ts +4 -7
  18. package/src/builtins.ts +29 -11
  19. package/src/bundled-modules.ts +3 -3
  20. package/src/canonical.ts +4 -3
  21. package/src/check.ts +1358 -219
  22. package/src/cli.ts +8 -1
  23. package/src/codegen.ts +68 -18
  24. package/src/config.ts +252 -179
  25. package/src/environment.ts +457 -132
  26. package/src/errors.ts +217 -3
  27. package/src/evaluate.ts +724 -117
  28. package/src/exit-codes.ts +5 -4
  29. package/src/index.ts +1 -0
  30. package/src/instances.ts +4 -2
  31. package/src/java-overrides.ts +104 -25
  32. package/src/levels.ts +183 -37
  33. package/src/lexer.ts +112 -29
  34. package/src/live-check.ts +220 -84
  35. package/src/liveness.ts +192 -65
  36. package/src/obligation-expression.ts +2 -2
  37. package/src/obligation-source.ts +2 -0
  38. package/src/parallel-worker.ts +8 -3
  39. package/src/parallel.ts +56 -5
  40. package/src/parser.ts +445 -147
  41. package/src/pcal-ast.ts +770 -0
  42. package/src/pcal-parse.ts +1523 -0
  43. package/src/pcal-tokenize.ts +516 -0
  44. package/src/pcal-translate.ts +1230 -0
  45. package/src/pcal-validate.ts +454 -0
  46. package/src/randomization.ts +24 -7
  47. package/src/resolve.ts +1439 -411
  48. package/src/run-cli.ts +1167 -155
  49. package/src/runtime.ts +16 -0
  50. package/src/sany-builtins.ts +147 -0
  51. package/src/sany-generator.ts +3112 -0
  52. package/src/sany-levels.ts +1208 -0
  53. package/src/sany-lexer.ts +545 -0
  54. package/src/sany-linter.ts +122 -0
  55. package/src/sany-modules.ts +1398 -0
  56. package/src/sany-nodes.ts +463 -0
  57. package/src/sany-parse-error.ts +2161 -0
  58. package/src/sany-report.ts +354 -0
  59. package/src/sany-selectors.ts +738 -0
  60. package/src/sany-source.ts +248 -0
  61. package/src/sany-xml.ts +1017 -0
  62. package/src/spec-description.ts +26 -7
  63. package/src/standard-modules.ts +203 -146
  64. package/src/standard-ranges.ts +116 -0
  65. package/src/state-graph.ts +29 -6
  66. package/src/subexpressions.ts +221 -161
  67. package/src/substitution-levels.ts +38 -17
  68. package/src/successors.ts +162 -114
  69. package/src/symmetry.ts +180 -52
  70. package/src/tableau.ts +4 -2
  71. package/src/tlc-ext.ts +13 -17
  72. package/src/tlc-messages.ts +329 -0
  73. package/src/tlc-module.ts +46 -18
  74. package/src/tlc-order.ts +56 -6
  75. package/src/tlc-random.ts +37 -9
  76. package/src/tlc-replay.ts +655 -0
  77. package/src/tlc-summary.ts +20 -5
  78. package/src/tlc-version.ts +18 -0
  79. package/src/transfer.ts +15 -3
  80. package/src/value-sources.ts +29 -0
  81. package/src/values.ts +684 -204
@@ -0,0 +1,329 @@
1
+ import { STACK_OVERFLOW_MESSAGE, TlaModuleError, type TlaEvaluationError } from "./errors";
2
+ import type { TlcVersion } from "./tlc-version";
3
+
4
+ // TLC's codes for the messages it prints, from tlc2.output.EC.
5
+ export const MESSAGE_CODE = {
6
+ general: 1000,
7
+ commandLineError: 1102,
8
+ initialState: 2102,
9
+ nestedExpression: 2103,
10
+ assumptionFalse: 2104,
11
+ assumptionEvaluationError: 2105,
12
+ exceptAppliedToUnknownField: 2144,
13
+ fingerprintFailed: 2147,
14
+ invariantViolatedInitial: 2107,
15
+ incompleteSuccessor: 2109,
16
+ propertyViolatedInitial: 2108,
17
+ invariantViolatedBehavior: 2110,
18
+ invariantEvaluationFailed: 2111,
19
+ actionPropertyViolatedBehavior: 2112,
20
+ actionPropertyEvaluationFailed: 2113,
21
+ deadlockReached: 2114,
22
+ temporalPropertyViolated: 2116,
23
+ behaviorUpToThisPoint: 2121,
24
+ backToState: 2122,
25
+ constantLevelInvariant: 2149,
26
+ javaOverrideLoaded: 2168,
27
+ starting: 2185,
28
+ modelChecking: 2187,
29
+ finished: 2186,
30
+ computingInit: 2189,
31
+ initGenerated1: 2190,
32
+ initGenerated2: 2191,
33
+ checkingTemporal: 2192,
34
+ success: 2193,
35
+ searchDepth: 2194,
36
+ stats: 2199,
37
+ progress: 2200,
38
+ temporalBranches: 2212,
39
+ statePrint2: 2217,
40
+ statePrint3: 2218,
41
+ sanyFinished: 2219,
42
+ startingSany: 2220,
43
+ stateLevelProperty: 2255,
44
+ version: 2262,
45
+ noSpecificationButProperty: 2257,
46
+ noFairnessButProperty: 2259,
47
+ counterExample: 2264,
48
+ checkingTemporalEnd: 2267,
49
+ stateGraphOutdegree: 2268,
50
+ computingInitProgress: 2269,
51
+ livenessSymmetry: 2279,
52
+ livenessConstraints: 2284,
53
+ symmetrySetTooSmall: 2300,
54
+ javaOverrideMismatch: 2400,
55
+ postconditionFalse: 2404,
56
+ postconditionFailed: 2405,
57
+ possibleUnwitnessed: 2780,
58
+ parsingFailed: 3002,
59
+ configFileError: 5001,
60
+ } as const;
61
+
62
+ // TLC's message levels, from tlc2.output.MP.
63
+ export const MESSAGE_LEVEL = { none: 0, error: 1, warning: 3, state: 4 } as const;
64
+
65
+ type MessageLevel = (typeof MESSAGE_LEVEL)[keyof typeof MESSAGE_LEVEL];
66
+
67
+ // Without -tool, TLC starts a message with the prefix of its level.
68
+ const LEVEL_PREFIXES: Record<MessageLevel, string> = {
69
+ 0: "",
70
+ 1: "Error: ",
71
+ 3: "Warning: ",
72
+ 4: "State ",
73
+ };
74
+
75
+ export interface MessagePrinter {
76
+ isTool: boolean;
77
+ version: TlcVersion;
78
+ print: (code: number, level: MessageLevel, text: string) => void;
79
+ }
80
+
81
+ // With -tool, TLC wraps each message in markers that name its code and level, so that a program
82
+ // can read the output. Lines outside the markers, such as the output of Print, stay as they are.
83
+ // MP.printWarning prints a warning once, which -nowarning drops, and without -tool, TLC follows the
84
+ // first warning with how to drop them.
85
+ export const createMessagePrinter = (
86
+ isTool: boolean,
87
+ isWarningEnabled = true,
88
+ version: TlcVersion = "master",
89
+ ): MessagePrinter => {
90
+ const warnings = new Set<string>();
91
+ return {
92
+ isTool,
93
+ version,
94
+ print: (code, level, text) => {
95
+ const isWarning = level === MESSAGE_LEVEL.warning;
96
+ if (isWarning && !isWarningEnabled) return;
97
+ const hint =
98
+ isWarning && !isTool && warnings.size === 0
99
+ ? "\n(Use the -nowarning option to disable this warning.)"
100
+ : "";
101
+ const message = isTool
102
+ ? `@!@!@STARTMSG ${code}:${level} @!@!@\n${text}\n@!@!@ENDMSG ${code} @!@!@`
103
+ : `${LEVEL_PREFIXES[level]}${text}${hint}`;
104
+ if (isWarning && warnings.has(message)) return;
105
+ if (isWarning) warnings.add(message);
106
+ console.log(message);
107
+ },
108
+ };
109
+ };
110
+
111
+ // TLC 1.7.4's message for a missing initial predicate, which blames a parameterized INSTANCE as
112
+ // well.
113
+ export const MISSING_INIT_174 =
114
+ "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.";
115
+
116
+ // The messages that TLC builds from a message code, from tlc2.output.MP, by their code and
117
+ // template, with whether TLC throws them as an EvalException rather than a TLCRuntimeException.
118
+ // TLC's -tool output wraps such a message in its own markers even inside another message.
119
+ const CODED_MESSAGES: [code: number, template: string, isEvalException: boolean][] = [
120
+ [1005, STACK_OVERFLOW_MESSAGE, false],
121
+ [2117, "Failed to recover the next state from its fingerprint.", true],
122
+ [2123, "Failed to recover the initial state from its fingerprint.", true],
123
+ [2132, "The first argument of Assert evaluated to FALSE; the second argument was:\n%1%", true],
124
+ [2145, "TLCGet(%1%) was undefined.", true],
125
+ [
126
+ 2154,
127
+ "Attempted to apply the operator overridden by the Java method\n%1%,\nbut it produced the following error:\n%2%",
128
+ false,
129
+ ],
130
+ [
131
+ 2148,
132
+ "The action formula A appearing in a WF_v(A) or SF_v(A) operator does not specify the primed value of the variable %1% occurring in the state formula v.\n",
133
+ false,
134
+ ],
135
+ [2155, "Attempted to compare %1% with the value\n%2%", true],
136
+ [2158, "Attempted to check if the value:\n%1%\nis an element of %2%.", true],
137
+ [
138
+ 2157,
139
+ "Attempted to apply TransitiveClosure to a set containing\nthe following value:\n%1%",
140
+ true,
141
+ ],
142
+ [2165, "Choose can only deal with numbers up to %1%", false],
143
+ [2169, "The %1% argument of %2% should be a %3%, but instead it is:\n%4%", true],
144
+ [2176, "Applying %1% to the following value,\nwhich is not %2%:\n%3%", true],
145
+ [
146
+ 2177,
147
+ "Attempted to apply BagUnion to the following set, whose\nelement is not a bag:\n%1%",
148
+ true,
149
+ ],
150
+ [2178, "Overflow when computing %1%", false],
151
+ [2179, "The second argument of \\div is 0.", true],
152
+ [2180, "0^0 is undefined.", true],
153
+ [2181, "Attempted to compute cardinality of the value\n%1%", true],
154
+ [2182, "Evaluating an expression of the form %1% when s is not a %2%:\n%3%", true],
155
+ [
156
+ 2183,
157
+ "The %1% argument of %2% must be in the domain of its %3% argument:\n%4%\n, but instead it is\n%5%",
158
+ true,
159
+ ],
160
+ [2184, "Attempted to apply %1% to the empty sequence.", true],
161
+ [2115, "No next state actions defined to generate successor states from.", false],
162
+ [
163
+ 2146,
164
+ "The invariant %1% is not a state predicate (one with no primes or temporal operators).%2%",
165
+ false,
166
+ ],
167
+ [2213, "TLC cannot handle the temporal formula %1%", false],
168
+ [2214, "Temporal formulas containing actions must be of forms <>[]A or []<>A.", false],
169
+ [2215, "TLC expected a %1% value, but did not find one. %2%", false],
170
+ [2222, "The constant parameter %1% is not assigned a value by the configuration file.", false],
171
+ [
172
+ 2223,
173
+ "In the configuration file, the identifier %1% appears\non the right-hand side of a <- after already appearing on the\nleft-hand side of one.",
174
+ false,
175
+ ],
176
+ [2224, "The configuration file substitutes for %1% with the undefined identifier %2%.", false],
177
+ [
178
+ 2225,
179
+ "The configuration file substitutes for %1% with %2% of different number of arguments.",
180
+ false,
181
+ ],
182
+ [
183
+ 2226,
184
+ "In the configuration file, the identifier %1% does not appear in the specification.",
185
+ false,
186
+ ],
187
+ [2227, "The configuration file cannot specify both INIT/NEXT and SPECIFICATION fields.", false],
188
+ [2228, "TLC requires %1% not to take any argument.", false],
189
+ [2228, "TLC requires %1% not to take any argument, but one was given: %2%", false],
190
+ [
191
+ 2229,
192
+ "The %1% %2% specified in the configuration file\nis not defined in the specification.",
193
+ false,
194
+ ],
195
+ [2230, "The %1% of %2% is equal to %3%", false],
196
+ [2231, "The configuration file did not specify the initial state predicate.", false],
197
+ [2231, MISSING_INIT_174, false],
198
+ [2232, "The configuration file did not specify the next state predicate.", false],
199
+ [2233, "The %1% %2% cannot be a constant.", false],
200
+ [2234, "The operator %1% cannot take any argument.", false],
201
+ [2235, "The operator %1% is not defined in the spec.", false],
202
+ [2237, "The spec is trivially false because %1% is false.", false],
203
+ [2238, "TLC cannot handle subscript %1%", false],
204
+ [2239, "TLC cannot handle this conjunct of the spec:\n%1%", false],
205
+ [2241, "The property %1% is not correctly defined.", false],
206
+ [2242, "The arity of the operator %1% is inconsistent in the configuration file.", false],
207
+ [2244, "TLC can't handle real numbers.\n%1%", false],
208
+ [2247, "In computing %1%, TLC expected a %2% expression,\nbut instead found %3%.\n%4%", false],
209
+ [2248, "In computing %1%, TLC expected a %2% expression,\nbut didn't find one.\n%3%", false],
210
+ [2260, "In computing ENABLED, TLC encountered a temporal formula (%1%).\n%2%", false],
211
+ [
212
+ 2261,
213
+ "TLC encountered a temporal formula (%1%) when evaluating a predicate or action.\n%2%",
214
+ false,
215
+ ],
216
+ [2265, "TLC can't handle a number this big.\n%1%", false],
217
+ [2266, "The %1% argument of %2% should be an %3%, but instead it is:\n%4%", true],
218
+ [2280, "In evaluation, the identifier %1% is either undefined or not an operator.\n%2%", false],
219
+ [2281, "The configuration file substitutes constant %1% with non-constant %2%%3%", false],
220
+ [2283, "The argument of %1% should be a %2%, but instead it is:\n%3%", true],
221
+ [
222
+ 5003,
223
+ "TLC found an error in the configuration file at line %1%\nThe keyword %2% was not followed by an identifier.",
224
+ false,
225
+ ],
226
+ [
227
+ 5004,
228
+ "TLC found an error in the configuration file at line %1%\nThe keyword %2% appeared twice.",
229
+ false,
230
+ ],
231
+ [
232
+ 5005,
233
+ "TLC found an error in the configuration file at line %1%\nExpected an identifier after %2%.",
234
+ false,
235
+ ],
236
+ [
237
+ 5006,
238
+ "TLC found an error in the configuration file at line %1%\nIt was expecting %2%, but did not find it.",
239
+ false,
240
+ ],
241
+ [5007, "TLC found an error in the configuration file:\n%1%", false],
242
+ // The general message is a prefix of the others above.
243
+ [5002, "TLC found an error in the configuration file at line %1%\n", false],
244
+ [2253, "Temporal formula is a tautology (its negation is unsatisfiable).", false],
245
+ [
246
+ 2301,
247
+ "TLC does not support temporal existential, nor universal, quantification over state variables.",
248
+ false,
249
+ ],
250
+ ];
251
+
252
+ interface CodedMessage {
253
+ code: number;
254
+ isEvalException: boolean;
255
+ }
256
+
257
+ const codedMessagePatterns = {
258
+ value: undefined as { pattern: RegExp; message: CodedMessage }[] | undefined,
259
+ };
260
+
261
+ const getCodedMessagePatterns = () =>
262
+ (codedMessagePatterns.value ??= CODED_MESSAGES.map(([code, template, isEvalException]) => ({
263
+ pattern: new RegExp(
264
+ `^${template
265
+ .split(/%\d+%/)
266
+ .map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))
267
+ .join("[\\s\\S]*")}$`,
268
+ ),
269
+ message: { code, isEvalException },
270
+ })));
271
+
272
+ // The overflows of SetOfFcnsValue and SetOfTuplesValue, which TLC raises with a plain message that
273
+ // reads like the coded overflow of SetOfRcdsValue and SubsetValue.
274
+ const UNCODED_MESSAGE_PATTERN =
275
+ /^Overflow when computing the number of elements in( |:\n\[(?![A-Za-z0-9_]+ : ))/;
276
+
277
+ export const getCodedMessage = (text: string): CodedMessage | undefined =>
278
+ UNCODED_MESSAGE_PATTERN.test(text)
279
+ ? undefined
280
+ : getCodedMessagePatterns().find((item) => item.pattern.test(text))?.message;
281
+
282
+ // Whether TLC raises an error as an EvalException, which only a standard module's Java code throws,
283
+ // rather than as the TLCRuntimeException of every Assert.fail.
284
+ export const isEvalException = (error: TlaEvaluationError) =>
285
+ error instanceof TlaModuleError || getCodedMessage(error.message)?.isEvalException === true;
286
+
287
+ // The messages that end with the message of the error they report, after this text.
288
+ const INNER_MESSAGE_PREFIXES = new Map([
289
+ // "The exception was a <class>\n: "
290
+ [1000, "\n: "],
291
+ [2105, "failed.\n"],
292
+ [2154, "but it produced the following error:\n"],
293
+ [2213, ":\n"],
294
+ [2281, " - specifically: "],
295
+ ]);
296
+
297
+ // The text of a coded message with the message of the error it reports marked in -tool output, as
298
+ // TLC's message holds that error's text as TLC printed it.
299
+ export const formatInnerMessage = (code: number, text: string, isTool: boolean) => {
300
+ const prefix = isTool ? INNER_MESSAGE_PREFIXES.get(code) : undefined;
301
+ const index = prefix === undefined ? -1 : text.indexOf(prefix);
302
+ if (prefix === undefined || index === -1) return text;
303
+ const end = index + prefix.length;
304
+ return `${text.slice(0, end)}${formatNestedMessage(text.slice(end), isTool)}`;
305
+ };
306
+
307
+ // The text of an error's message as TLC prints it inside another message.
308
+ export const formatNestedMessage = (text: string, isTool: boolean): string => {
309
+ const code = isTool ? getCodedMessage(text)?.code : undefined;
310
+ return code === undefined
311
+ ? text
312
+ : `@!@!@STARTMSG ${code}:${MESSAGE_LEVEL.none} @!@!@\n${formatInnerMessage(code, text, isTool)}\n@!@!@ENDMSG ${code} @!@!@`;
313
+ };
314
+
315
+ const pad = (value: number) => String(value).padStart(2, "0");
316
+
317
+ // TLC's convertRuntimeToHumanReadable: a duration in its two largest units.
318
+ export const formatTlcDuration = (milliseconds: number) => {
319
+ const seconds = Math.floor(milliseconds / 1000) % 60;
320
+ const minutes = Math.floor(milliseconds / 60_000) % 60;
321
+ const hours = Math.floor(milliseconds / 3_600_000);
322
+ if (milliseconds > 86_400_000) return `${Math.floor(hours / 24)}d ${pad(hours % 24)}h`;
323
+ if (milliseconds > 3_600_000) return `${pad(hours % 24)}h ${pad(minutes)}min`;
324
+ return milliseconds > 60_000 ? `${pad(minutes)}min ${pad(seconds)}s` : `${pad(seconds)}s`;
325
+ };
326
+
327
+ // TLC's SimpleDateFormat("yyyy-MM-dd HH:mm:ss") in the local time zone.
328
+ export const formatTlcDate = (date: Date) =>
329
+ `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
package/src/tlc-module.ts CHANGED
@@ -1,10 +1,11 @@
1
1
  import { TlaModuleError } from "./errors";
2
2
  import { EXIT_STATUS } from "./exit-codes";
3
- import type { Builtin } from "./evaluate";
3
+ import type { Builtin, Context } from "./evaluate";
4
4
  import { prettyPrint } from "./pretty-print";
5
5
  import {
6
6
  defineConstant,
7
7
  defineHigherOrderOperator,
8
+ defineLazyOperator,
8
9
  defineOperator,
9
10
  defineStateOperator,
10
11
  getElements,
@@ -12,7 +13,9 @@ import {
12
13
  getFunction,
13
14
  getOperator,
14
15
  getSequence,
16
+ getThunk,
15
17
  getValue,
18
+ overrideWithJava,
16
19
  } from "./builtins";
17
20
  import { getNamedRegisters, NAMED_REGISTER_PREFIX, type CheckerRuntime } from "./runtime";
18
21
  import { createActionRecord, setTlcValue } from "./tlc-ext";
@@ -41,15 +44,20 @@ const getRegisterFunction = <Key extends Value>(registers: Map<Key, Value>) =>
41
44
 
42
45
  // TLC creates its model checker after it processes the spec, so these are undefined before then.
43
46
  const CHECKER_KEYS = new Set(["diameter", "generated", "distinct", "queue", "stats", "config"]);
47
+ // The keys of TLC 1.7.4's TLCGet, and those it can't read before it creates its model checker.
48
+ const TLC_174_KEYS = new Set(["diameter", "distinct", "queue", "duration", "level"]);
49
+ const CHECKER_KEYS_174 = new Set(["diameter", "distinct", "queue", "level"]);
44
50
 
45
51
  const getRuntimeValue = (
46
52
  runtime: CheckerRuntime,
47
53
  key: string,
48
54
  state: (Value | undefined)[] | undefined,
49
55
  ) => {
50
- if (!runtime.isStarted && CHECKER_KEYS.has(key)) {
51
- throw new TlaModuleError(`TLCGet(${key}) was undefined.`);
52
- }
56
+ const isUndefined =
57
+ runtime.version === "1.7.4"
58
+ ? !TLC_174_KEYS.has(key) || (!runtime.isStarted && CHECKER_KEYS_174.has(key))
59
+ : !runtime.isStarted && CHECKER_KEYS.has(key);
60
+ if (isUndefined) throw new TlaModuleError(`TLCGet(${key}) was undefined.`);
53
61
  const duration = Math.floor((Date.now() - runtime.startedAt) / 1000);
54
62
  switch (key) {
55
63
  case "level":
@@ -111,6 +119,20 @@ const getRuntimeValue = (
111
119
  throw new TlaModuleError(`TLCGet(${key}) was undefined.`);
112
120
  };
113
121
 
122
+ const getTlcValue = (runtime: CheckerRuntime, key: Value, context: Context | undefined) => {
123
+ if (typeof key === "number" && key >= 0) {
124
+ const value = runtime.registers.get(key);
125
+ if (value === undefined) throw new TlaModuleError(`TLCGet(${key}) was undefined.`);
126
+ return value;
127
+ }
128
+ if (typeof key !== "string") {
129
+ throw new TlaModuleError(
130
+ `The argument of TLCGet should be a nonnegative integer, but instead it is:\n${formatValue(key)}`,
131
+ );
132
+ }
133
+ return getRuntimeValue(runtime, key, context?.state);
134
+ };
135
+
114
136
  const getPermutations = (elements: Value[]): Value[][] =>
115
137
  elements.length === 0
116
138
  ? [[]]
@@ -193,20 +215,26 @@ export const createTlcOperators = (
193
215
  }, []),
194
216
  );
195
217
  }),
196
- defineStateOperator("TLCGet", 1, (args, context) => {
197
- const key = getValue(args, 0, "TLCGet");
198
- if (typeof key === "number" && key >= 0) {
199
- const value = runtime.registers.get(key);
200
- if (value === undefined) throw new TlaModuleError(`TLCGet(${key}) was undefined.`);
201
- return value;
202
- }
203
- if (typeof key !== "string") {
204
- throw new TlaModuleError(
205
- `The argument of TLCGet should be a nonnegative integer, but instead it is:\n${formatValue(key)}`,
206
- );
207
- }
208
- return getRuntimeValue(runtime, key, context?.state);
209
- }),
218
+ // TLC evaluates TLCGet with its argument in TLCGetSet.TLCGetEval, so it reports any failure,
219
+ // the argument's too, as a failure of that method. TLC 1.7.4 calls TLC.TLCGet with the value of
220
+ // its argument.
221
+ runtime.version === "1.7.4"
222
+ ? overrideWithJava(
223
+ {
224
+ ...defineStateOperator("TLCGet", 1, (args, context) =>
225
+ getTlcValue(runtime, getValue(args, 0, "TLCGet"), context),
226
+ ),
227
+ // Unlike TLCGetSet.TLCGetEval, TLC.TLCGet declares no minimum level.
228
+ isLevelConstant: true,
229
+ },
230
+ "public static tlc2.value.impl.Value tlc2.module.TLC.TLCGet(tlc2.value.impl.Value)",
231
+ )
232
+ : overrideWithJava(
233
+ defineLazyOperator("TLCGet", 1, (args, context) =>
234
+ getTlcValue(runtime, getThunk(args, 0, "TLCGet")(), context),
235
+ ),
236
+ "public static tlc2.value.impl.Value tlc2.module.TLCGetSet.TLCGetEval(tlc2.tool.impl.Tool,tla2sany.semantic.ExprOrOpArgNode[],tlc2.util.Context,tlc2.tool.TLCState,tlc2.tool.TLCState,int,tlc2.tool.coverage.CostModel)",
237
+ ),
210
238
  defineStateOperator("TLCSet", 2, (args) => {
211
239
  const key = getValue(args, 0, "TLCSet");
212
240
  setTlcValue(runtime, print, key, getValue(args, 1, "TLCSet"));
package/src/tlc-order.ts CHANGED
@@ -2,6 +2,7 @@
2
2
  // state's variables in the order of SANY's symbol table. This reproduces both orders.
3
3
  import type { Module, SourceLocation } from "./ast";
4
4
  import type { ConfigValue, ModelConfig } from "./config";
5
+ import { createMissingModuleError } from "./errors";
5
6
  import { tokenize, type Token } from "./lexer";
6
7
  import { extractModule, parseModule } from "./parser";
7
8
  import { isBefore } from "./resolve";
@@ -166,6 +167,9 @@ const getModuleReferences = (
166
167
  innerModules.set(name, inner.references);
167
168
  references.inner.push(inner.references);
168
169
  index = inner.end;
170
+ } else if (tokens[index - 1]?.text === ".") {
171
+ // A record field named EXTENDS or INSTANCE, as in r.EXTENDS or [r EXCEPT !.INSTANCE = 0].
172
+ continue;
169
173
  } else if (token.text === "EXTENDS") {
170
174
  const names = getDeclarations(tokens, index + 1);
171
175
  references.extends.push(...names);
@@ -221,6 +225,9 @@ const getParsedTexts = (tokens: Token[]) => {
221
225
  return texts;
222
226
  };
223
227
 
228
+ // A module starts with ---- MODULE Name, so its third token is its name.
229
+ const getModuleName = (tokens: Token[]) => tokens[2]?.text;
230
+
224
231
  const getRanges = (tokens: Token[]) => {
225
232
  const ranges = new Map<string, { start: number; end: number }>();
226
233
  const open: { name: string; start: number }[] = [];
@@ -255,7 +262,7 @@ const createModuleSet = (source: string, loadModule: ModuleLoader) => {
255
262
  : (TLC_MODULE_SOURCES.get(name) ?? loadModule?.(name) ?? extractModule(source, name));
256
263
  const tokens = text === undefined ? [] : tokenize(text);
257
264
  const ranges = getRanges(tokens);
258
- const range = ranges.get(tokens[2]?.text ?? "") ?? { start: 0, end: 0 };
265
+ const range = ranges.get(getModuleName(tokens) ?? "") ?? { start: 0, end: 0 };
259
266
  const parsed = { module: undefined as Module | undefined };
260
267
  const file = {
261
268
  tokens,
@@ -278,9 +285,8 @@ const createModuleSet = (source: string, loadModule: ModuleLoader) => {
278
285
  (name === undefined ? undefined : nestedModules.get(name)) ?? getFile(name);
279
286
  };
280
287
 
281
- // The variables in the order TLC compares them: the reverse of the root module's context
282
- // enumeration, as ModuleNode.getVariableDecls returns them.
283
- export const getTlcVariableOrder = (source: string, loadModule: ModuleLoader): string[] => {
288
+ // SANY's Context of each module, which the root module has under undefined.
289
+ const createContexts = (source: string, loadModule: ModuleLoader) => {
284
290
  const getParsed = createModuleSet(source, loadModule);
285
291
  const getUnits = (unit: ParsedModule) => {
286
292
  const tokens = unit.tokens;
@@ -381,6 +387,8 @@ export const getTlcVariableOrder = (source: string, loadModule: ModuleLoader): s
381
387
  };
382
388
 
383
389
  const contexts = new Map<string, SymbolTable>();
390
+ // Where the entries a module adds itself start, after those of the modules it extends.
391
+ const ownStarts = new Map<SymbolTable, number>();
384
392
  const getContext = (name: string | undefined): SymbolTable => {
385
393
  const cached = contexts.get(name ?? "");
386
394
  if (cached) return cached;
@@ -395,16 +403,53 @@ export const getTlcVariableOrder = (source: string, loadModule: ModuleLoader): s
395
403
  if (!entry.isLocal) table.put(entry);
396
404
  }),
397
405
  );
406
+ ownStarts.set(table, table.inserted.length);
398
407
  getUnits(unit).forEach((item) => item.apply(table));
399
408
  return table;
400
409
  };
401
- return getContext(undefined)
410
+ return {
411
+ getContext,
412
+ getOwnEntries: (name: string | undefined) => {
413
+ const table = getContext(name);
414
+ return table.inserted.slice(ownStarts.get(table));
415
+ },
416
+ };
417
+ };
418
+
419
+ // The variables or constants of the root module in the reverse of its context enumeration, as
420
+ // ModuleNode.getVariableDecls and getConstantDecls return them. TLC compares variables in this
421
+ // order, and checks that the configuration assigns each constant in it.
422
+ export const getTlcDeclarationOrder = (
423
+ source: string,
424
+ loadModule: ModuleLoader,
425
+ kind: "variable" | "constant",
426
+ ): string[] =>
427
+ createContexts(source, loadModule)
428
+ .getContext(undefined)
402
429
  .enumerate()
403
- .filter((entry) => entry.kind === "variable")
430
+ .filter((entry) => entry.kind === kind)
404
431
  .map((entry) => entry.name)
405
432
  .reverse();
433
+
434
+ // The names of the definitions each module adds to its context, in the order of
435
+ // ModuleNode.getOpDefs, in which TLC computes the constant definitions as it starts. An INSTANCE
436
+ // adds the definitions of the module it instantiates in the order that module's Hashtable
437
+ // enumerates them.
438
+ export const createTlcDefinitionOrder = (source: string, loadModule: ModuleLoader) => {
439
+ const contexts = createContexts(source, loadModule);
440
+ // The root module's context reads every file of the spec, and so finds the modules nested in
441
+ // the files it extends or instantiates.
442
+ contexts.getContext(undefined);
443
+ return (name: string | undefined) =>
444
+ contexts
445
+ .getOwnEntries(name)
446
+ .filter((entry) => entry.kind === "definition")
447
+ .map((entry) => entry.name);
406
448
  };
407
449
 
450
+ export const getTlcVariableOrder = (source: string, loadModule: ModuleLoader) =>
451
+ getTlcDeclarationOrder(source, loadModule, "variable");
452
+
408
453
  // Every string TLC interns before model checking starts, in order: values in the config, TLC's
409
454
  // startup strings, each module's tokens in the order SpecObj.loadSpec parses the modules, string
410
455
  // literals in semantic analysis order, and the names TLC interns for TLCGet.
@@ -488,6 +533,11 @@ export const getTlcStringOrder = (
488
533
  dependencies.set(module.unit, [...(dependencies.get(module.unit) ?? []), name]);
489
534
  if (parsedUnits.has(name)) continue;
490
535
  parsedUnits.add(name);
536
+ // SANY stops at the first module it can't find, in the order it reads them.
537
+ if (getParsed(name).tokens.length === 0) {
538
+ const importer = module.unit ?? getModuleName(getParsed(undefined).tokens);
539
+ throw createMissingModuleError(name, importer);
540
+ }
491
541
  getParsedTexts(getUnitTokens(name)).forEach(intern);
492
542
  }
493
543
  SEMANTIC_PRELUDE.forEach(intern);
package/src/tlc-random.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { TlaEvaluationError } from "./errors";
2
+ import type { TlcVersion } from "./tlc-version";
2
3
  import {
3
4
  createRecord,
4
5
  createSortedFunction,
@@ -181,8 +182,10 @@ const createShiftTable = (length: number) => {
181
182
 
182
183
  // Extending a fingerprint by a byte is linear over GF(2), so extending it by a value's bytes
183
184
  // XORs the value's own fingerprint from zero into the fingerprint shifted by their length.
184
- // The fingerprinter caches each distinct variable value for one pass over the stored states.
185
- export const createTlcFingerprinter = () => {
185
+ // The fingerprinter caches each distinct variable value for one pass over the stored states. It
186
+ // reads a state's variables in `order` and writes each fingerprint's low and high words into
187
+ // `words`, an Int32Array over a little-endian BigInt64Array.
188
+ export const createTlcFingerprinter = (order: number[], words: Int32Array) => {
186
189
  const shiftTables = new Map<number, Int32Array>();
187
190
  const indices = new Map<Value, number>();
188
191
  const contributions: number[] = [];
@@ -204,11 +207,11 @@ export const createTlcFingerprinter = () => {
204
207
  shiftTables.set(length, table);
205
208
  return table;
206
209
  };
207
- return (state: Value[]) => {
210
+ return (state: Value[], position: number) => {
208
211
  const outer = { high, low };
209
212
  const fingerprint = { high: INITIAL_HIGH, low: INITIAL_LOW };
210
- for (const value of state) {
211
- const contribution = getContribution(value);
213
+ for (const index of order) {
214
+ const contribution = getContribution(state[index]);
212
215
  const table = getShiftTable(contributions[contribution]);
213
216
  const extended = {
214
217
  high: contributions[contribution + 1],
@@ -225,7 +228,8 @@ export const createTlcFingerprinter = () => {
225
228
  }
226
229
  high = outer.high;
227
230
  low = outer.low;
228
- return (BigInt(fingerprint.high >>> 0) << 32n) | BigInt(fingerprint.low >>> 0);
231
+ words[2 * position] = fingerprint.low;
232
+ words[2 * position + 1] = fingerprint.high;
229
233
  };
230
234
  };
231
235
 
@@ -286,7 +290,7 @@ const getModulusAndMultiplier = (size: number) => {
286
290
 
287
291
  // EnumerableValue.SubsetEnumerator: count indices below size from a full-period linear
288
292
  // congruential generator that starts at random.nextInt(size).
289
- const getSubsetIndices = (count: number, size: number, random: JavaRandom) => {
293
+ const getSubsetIndicesMaster = (count: number, size: number, random: JavaRandom) => {
290
294
  if (size <= 0) return [];
291
295
  const generator = getModulusAndMultiplier(size);
292
296
  const state = { index: BigInt(random.nextInt(size)) };
@@ -299,6 +303,18 @@ const getSubsetIndices = (count: number, size: number, random: JavaRandom) => {
299
303
  });
300
304
  };
301
305
 
306
+ // TLC 1.7.4's EnumerableValue.SubsetEnumerator: the i-th index is (x * i + a) mod size, for a
307
+ // prime x above size and a = random.nextInt(size), so the first size indices are distinct.
308
+ const getSubsetIndices174 = (count: number, size: number, random: JavaRandom) => {
309
+ if (size <= 0) return [];
310
+ const stride = BigInt(size < 191 ? 191 : MAXIMUM_INT);
311
+ const offset = BigInt(random.nextInt(size));
312
+ return Array.from(
313
+ { length: Math.min(count, size) },
314
+ (_, index) => (stride * BigInt(index) + offset) % BigInt(size),
315
+ );
316
+ };
317
+
302
318
  const LARGE_STRIDE = (1n << 63n) - 1n - 24n;
303
319
 
304
320
  // SetOfFcnsOrRcdsValue.BigIntegerSubsetEnumerator, for products with more than 2^31 - 1
@@ -352,15 +368,27 @@ const getProduct = (set: Value): Product | undefined => {
352
368
  return undefined;
353
369
  };
354
370
 
371
+ // TLC 1.7.4 enumerates a set of tuples to draw from it.
372
+ export const getEnumeratedFactors = (set: Value, version: TlcVersion) =>
373
+ version === "1.7.4" && typeof set === "object" && set.kind === "ProductSet"
374
+ ? set.factors
375
+ : undefined;
376
+
355
377
  // Enumerable#getRandomSubset, which Randomization's RandomSubset calls.
356
- export const getRandomSubset = (count: number, set: Value, random: JavaRandom): Value[] => {
378
+ export const getRandomSubset = (
379
+ count: number,
380
+ set: Value,
381
+ random: JavaRandom,
382
+ version: TlcVersion,
383
+ ): Value[] => {
357
384
  if (isEmptySet(set)) return [];
385
+ const getSubsetIndices = version === "1.7.4" ? getSubsetIndices174 : getSubsetIndicesMaster;
358
386
  if (typeof set === "object" && set.kind === "Interval") {
359
387
  return getSubsetIndices(count, Math.max(0, set.high - set.low + 1), random).map(
360
388
  (index) => set.low + Number(index),
361
389
  );
362
390
  }
363
- const product = getProduct(set);
391
+ const product = getEnumeratedFactors(set, version) ? undefined : getProduct(set);
364
392
  if (product) {
365
393
  const size = product.lists.reduce((total, list) => total * BigInt(list.length), 1n);
366
394
  const indices =