tla-ts 0.0.3-dev.51ddd47 → 0.0.3-dev.596cd91

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 (83) hide show
  1. package/README.md +12 -12
  2. package/dist/cli.cjs +1 -1
  3. package/dist/cli.js +1 -1
  4. package/dist/index.cjs +1 -1
  5. package/dist/index.d.cts +150 -8
  6. package/dist/index.d.ts +150 -8
  7. package/dist/index.js +1 -1
  8. package/dist/parallel-worker.cjs +1 -1
  9. package/dist/parallel-worker.js +2 -2
  10. package/dist/parallel.cjs +1 -1
  11. package/dist/parallel.js +2 -2
  12. package/dist/run-cli.cjs +45 -19
  13. package/dist/run-cli.js +45 -19
  14. package/dist/transfer.cjs +1391 -28
  15. package/dist/transfer.js +1391 -28
  16. package/package.json +5 -1
  17. package/src/ast.ts +57 -6
  18. package/src/bags.ts +4 -7
  19. package/src/builtins.ts +29 -11
  20. package/src/bundled-modules.ts +3 -3
  21. package/src/canonical.ts +4 -3
  22. package/src/check.ts +1393 -226
  23. package/src/cli.ts +8 -1
  24. package/src/codegen.ts +68 -18
  25. package/src/config.ts +254 -181
  26. package/src/environment.ts +473 -132
  27. package/src/errors.ts +217 -3
  28. package/src/evaluate.ts +722 -112
  29. package/src/exit-codes.ts +5 -4
  30. package/src/index.ts +1 -0
  31. package/src/instances.ts +4 -2
  32. package/src/java-overrides.ts +104 -25
  33. package/src/levels.ts +183 -37
  34. package/src/lexer.ts +122 -29
  35. package/src/live-check.ts +220 -102
  36. package/src/liveness.ts +216 -52
  37. package/src/obligation-expression.ts +2 -2
  38. package/src/obligation-source.ts +2 -0
  39. package/src/parallel-worker.ts +8 -3
  40. package/src/parallel.ts +56 -5
  41. package/src/parser.ts +445 -147
  42. package/src/pcal-ast.ts +770 -0
  43. package/src/pcal-parse.ts +1523 -0
  44. package/src/pcal-tokenize.ts +516 -0
  45. package/src/pcal-translate.ts +1230 -0
  46. package/src/pcal-validate.ts +454 -0
  47. package/src/randomization.ts +24 -7
  48. package/src/resolve.ts +1465 -411
  49. package/src/run-cli.ts +1179 -155
  50. package/src/runtime.ts +16 -0
  51. package/src/sany-builtins.ts +147 -0
  52. package/src/sany-generator.ts +3128 -0
  53. package/src/sany-levels.ts +1208 -0
  54. package/src/sany-lexer.ts +545 -0
  55. package/src/sany-linter.ts +122 -0
  56. package/src/sany-modules.ts +1398 -0
  57. package/src/sany-nodes.ts +463 -0
  58. package/src/sany-parse-error.ts +2161 -0
  59. package/src/sany-report.ts +356 -0
  60. package/src/sany-selectors.ts +738 -0
  61. package/src/sany-source.ts +248 -0
  62. package/src/sany-xml.ts +1017 -0
  63. package/src/spec-description.ts +26 -7
  64. package/src/standard-modules.ts +200 -148
  65. package/src/standard-ranges.ts +116 -0
  66. package/src/state-graph.ts +29 -6
  67. package/src/subexpressions.ts +221 -161
  68. package/src/substitution-levels.ts +38 -17
  69. package/src/successors.ts +207 -103
  70. package/src/symmetry.ts +180 -52
  71. package/src/tableau.ts +54 -25
  72. package/src/tlc-ext.ts +13 -17
  73. package/src/tlc-messages.ts +329 -0
  74. package/src/tlc-module.ts +46 -18
  75. package/src/tlc-modules.ts +4 -0
  76. package/src/tlc-order.ts +61 -7
  77. package/src/tlc-random.ts +37 -9
  78. package/src/tlc-replay.ts +655 -0
  79. package/src/tlc-summary.ts +20 -5
  80. package/src/tlc-version.ts +18 -0
  81. package/src/transfer.ts +15 -3
  82. package/src/value-sources.ts +29 -0
  83. package/src/values.ts +713 -180
@@ -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"));
@@ -550,6 +550,10 @@ export const SANY_NODE_NAMES = [
550
550
  "N_AssertStep",
551
551
  ];
552
552
 
553
+ // The standard modules that a spec may ship its own file of, such as CommunityModules' Json.tla,
554
+ // which SANY reads in place of its own.
555
+ export const USER_STANDARD_MODULES = new Set(["Bags", "Json", "Randomization", "TLCExt"]);
556
+
553
557
  export const TLC_MODULE_SOURCES = new Map([
554
558
  [
555
559
  "Naturals",
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";
@@ -12,6 +13,7 @@ import {
12
13
  TLC_MODULE_SOURCES,
13
14
  TLC_RUNTIME_STRINGS,
14
15
  TLC_STARTUP_STRINGS,
16
+ USER_STANDARD_MODULES,
15
17
  } from "./tlc-modules";
16
18
 
17
19
  type SymbolKind = "builtin" | "constant" | "variable" | "definition" | "theorem" | "module";
@@ -166,6 +168,9 @@ const getModuleReferences = (
166
168
  innerModules.set(name, inner.references);
167
169
  references.inner.push(inner.references);
168
170
  index = inner.end;
171
+ } else if (tokens[index - 1]?.text === ".") {
172
+ // A record field named EXTENDS or INSTANCE, as in r.EXTENDS or [r EXCEPT !.INSTANCE = 0].
173
+ continue;
169
174
  } else if (token.text === "EXTENDS") {
170
175
  const names = getDeclarations(tokens, index + 1);
171
176
  references.extends.push(...names);
@@ -221,6 +226,9 @@ const getParsedTexts = (tokens: Token[]) => {
221
226
  return texts;
222
227
  };
223
228
 
229
+ // A module starts with ---- MODULE Name, so its third token is its name.
230
+ const getModuleName = (tokens: Token[]) => tokens[2]?.text;
231
+
224
232
  const getRanges = (tokens: Token[]) => {
225
233
  const ranges = new Map<string, { start: number; end: number }>();
226
234
  const open: { name: string; start: number }[] = [];
@@ -252,10 +260,13 @@ const createModuleSet = (source: string, loadModule: ModuleLoader) => {
252
260
  const text =
253
261
  name === undefined
254
262
  ? source
255
- : (TLC_MODULE_SOURCES.get(name) ?? loadModule?.(name) ?? extractModule(source, name));
263
+ : ((USER_STANDARD_MODULES.has(name) ? loadModule?.(name) : undefined) ??
264
+ TLC_MODULE_SOURCES.get(name) ??
265
+ loadModule?.(name) ??
266
+ extractModule(source, name));
256
267
  const tokens = text === undefined ? [] : tokenize(text);
257
268
  const ranges = getRanges(tokens);
258
- const range = ranges.get(tokens[2]?.text ?? "") ?? { start: 0, end: 0 };
269
+ const range = ranges.get(getModuleName(tokens) ?? "") ?? { start: 0, end: 0 };
259
270
  const parsed = { module: undefined as Module | undefined };
260
271
  const file = {
261
272
  tokens,
@@ -278,9 +289,8 @@ const createModuleSet = (source: string, loadModule: ModuleLoader) => {
278
289
  (name === undefined ? undefined : nestedModules.get(name)) ?? getFile(name);
279
290
  };
280
291
 
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[] => {
292
+ // SANY's Context of each module, which the root module has under undefined.
293
+ const createContexts = (source: string, loadModule: ModuleLoader) => {
284
294
  const getParsed = createModuleSet(source, loadModule);
285
295
  const getUnits = (unit: ParsedModule) => {
286
296
  const tokens = unit.tokens;
@@ -381,6 +391,8 @@ export const getTlcVariableOrder = (source: string, loadModule: ModuleLoader): s
381
391
  };
382
392
 
383
393
  const contexts = new Map<string, SymbolTable>();
394
+ // Where the entries a module adds itself start, after those of the modules it extends.
395
+ const ownStarts = new Map<SymbolTable, number>();
384
396
  const getContext = (name: string | undefined): SymbolTable => {
385
397
  const cached = contexts.get(name ?? "");
386
398
  if (cached) return cached;
@@ -395,16 +407,53 @@ export const getTlcVariableOrder = (source: string, loadModule: ModuleLoader): s
395
407
  if (!entry.isLocal) table.put(entry);
396
408
  }),
397
409
  );
410
+ ownStarts.set(table, table.inserted.length);
398
411
  getUnits(unit).forEach((item) => item.apply(table));
399
412
  return table;
400
413
  };
401
- return getContext(undefined)
414
+ return {
415
+ getContext,
416
+ getOwnEntries: (name: string | undefined) => {
417
+ const table = getContext(name);
418
+ return table.inserted.slice(ownStarts.get(table));
419
+ },
420
+ };
421
+ };
422
+
423
+ // The variables or constants of the root module in the reverse of its context enumeration, as
424
+ // ModuleNode.getVariableDecls and getConstantDecls return them. TLC compares variables in this
425
+ // order, and checks that the configuration assigns each constant in it.
426
+ export const getTlcDeclarationOrder = (
427
+ source: string,
428
+ loadModule: ModuleLoader,
429
+ kind: "variable" | "constant",
430
+ ): string[] =>
431
+ createContexts(source, loadModule)
432
+ .getContext(undefined)
402
433
  .enumerate()
403
- .filter((entry) => entry.kind === "variable")
434
+ .filter((entry) => entry.kind === kind)
404
435
  .map((entry) => entry.name)
405
436
  .reverse();
437
+
438
+ // The names of the definitions each module adds to its context, in the order of
439
+ // ModuleNode.getOpDefs, in which TLC computes the constant definitions as it starts. An INSTANCE
440
+ // adds the definitions of the module it instantiates in the order that module's Hashtable
441
+ // enumerates them.
442
+ export const createTlcDefinitionOrder = (source: string, loadModule: ModuleLoader) => {
443
+ const contexts = createContexts(source, loadModule);
444
+ // The root module's context reads every file of the spec, and so finds the modules nested in
445
+ // the files it extends or instantiates.
446
+ contexts.getContext(undefined);
447
+ return (name: string | undefined) =>
448
+ contexts
449
+ .getOwnEntries(name)
450
+ .filter((entry) => entry.kind === "definition")
451
+ .map((entry) => entry.name);
406
452
  };
407
453
 
454
+ export const getTlcVariableOrder = (source: string, loadModule: ModuleLoader) =>
455
+ getTlcDeclarationOrder(source, loadModule, "variable");
456
+
408
457
  // Every string TLC interns before model checking starts, in order: values in the config, TLC's
409
458
  // startup strings, each module's tokens in the order SpecObj.loadSpec parses the modules, string
410
459
  // literals in semantic analysis order, and the names TLC interns for TLCGet.
@@ -488,6 +537,11 @@ export const getTlcStringOrder = (
488
537
  dependencies.set(module.unit, [...(dependencies.get(module.unit) ?? []), name]);
489
538
  if (parsedUnits.has(name)) continue;
490
539
  parsedUnits.add(name);
540
+ // SANY stops at the first module it can't find, in the order it reads them.
541
+ if (getParsed(name).tokens.length === 0) {
542
+ const importer = module.unit ?? getModuleName(getParsed(undefined).tokens);
543
+ throw createMissingModuleError(name, importer);
544
+ }
491
545
  getParsedTexts(getUnitTokens(name)).forEach(intern);
492
546
  }
493
547
  SEMANTIC_PRELUDE.forEach(intern);