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
package/src/dfid.ts ADDED
@@ -0,0 +1,636 @@
1
+ import type { Expression } from "./ast";
2
+ import type { CheckOptions } from "./check";
3
+ import {
4
+ getErrorExitCode,
5
+ getUnexpectedException,
6
+ isStackOverflow,
7
+ TlaEvaluationError,
8
+ TlaIncompleteSuccessorError,
9
+ TlaStackOverflowError,
10
+ TlaTooManyStatesError,
11
+ TlaUnsupportedError,
12
+ } from "./errors";
13
+ import { createTracingEnvironment } from "./evaluate";
14
+ import { EXIT_STATUS, getMessageExitStatus, withLivenessExitCode } from "./exit-codes";
15
+ import { createLivenessChecker } from "./liveness-checker";
16
+ import { getIncompleteSuccessorMessage, prepareSearch, reportAssumptionViolation } from "./search";
17
+ import { getNextActions, type SpecAction } from "./spec-description";
18
+ import { forEachInitialState, forEachSuccessor } from "./successors";
19
+ import {
20
+ formatNestedMessage,
21
+ formatTlcDate,
22
+ getFailureMessage,
23
+ isEvalException,
24
+ isHeadedError,
25
+ MESSAGE_CODE,
26
+ withUnexpectedException,
27
+ } from "./tlc/messages";
28
+ import { getTlcFingerprint } from "./tlc/fingerprint";
29
+ import { replaySuccessors } from "./tlc/replay";
30
+ import { getOptimisticProbability, getActualProbability } from "./tlc/summary";
31
+ import { createModelValue, formatState, getSetBound, type Value } from "./values";
32
+
33
+ export interface DepthFirstOptions extends CheckOptions {
34
+ maxDepth: number;
35
+ onOutput: (output: DepthFirstOutput) => void;
36
+ }
37
+
38
+ export type DepthFirstOutput =
39
+ | { kind: "message"; code: number; isError: boolean; message: string; toolMessage: string }
40
+ | { kind: "behavior"; states: Record<string, Value>[]; isInvariant: boolean }
41
+ | { kind: "nested-expressions"; callStack: Expression[] }
42
+ | { kind: "success"; optimistic: number; actual: number };
43
+
44
+ interface StateEntry {
45
+ state: Value[];
46
+ fingerprint: bigint;
47
+ }
48
+
49
+ interface CheckerState {
50
+ isDone: boolean;
51
+ errorCode: number;
52
+ continuedCode: number;
53
+ isKeepingCallStack: boolean;
54
+ errorEntry: StateEntry | undefined;
55
+ stopCode: number;
56
+ isMoreLevel: boolean;
57
+ }
58
+
59
+ interface StateHolder {
60
+ state: Value[] | undefined;
61
+ }
62
+
63
+ interface Processing {
64
+ successor: (Value | undefined)[] | undefined;
65
+ }
66
+
67
+ interface LevelLoop {
68
+ isTerminated: boolean;
69
+ code: number;
70
+ }
71
+
72
+ const DONE = 1;
73
+ const LEVELED = 2;
74
+
75
+ const NO_ERROR = 0;
76
+
77
+ const LONG_MAX = (1n << 63n) - 1n;
78
+
79
+ const INITIAL_BUCKETS = 1n << 16n;
80
+ const MAX_LOAD = 20n;
81
+
82
+ // MemFPIntSet.checkFPs reads a fingerprint back with the sign of its low word extended over its
83
+ // high word, and compares two fingerprints in one bucket by Math.abs of their difference but two
84
+ // in different buckets only when the difference doesn't overflow.
85
+ const getFingerprintDistance = (fingerprints: bigint[], buckets: bigint) => {
86
+ const values = fingerprints.map((fingerprint) => {
87
+ const low = BigInt.asIntN(32, fingerprint);
88
+ return low < 0n ? low : BigInt.asIntN(64, fingerprint);
89
+ });
90
+ const sorted = values.toSorted((left, right) => (left < right ? -1 : left > right ? 1 : 0));
91
+ const gaps = sorted
92
+ .slice(1)
93
+ .map((value, index) => value - sorted[index])
94
+ .filter((gap) => gap <= LONG_MAX);
95
+ const ranges = new Map<bigint, { min: bigint; max: bigint }>();
96
+ fingerprints.forEach((fingerprint, index) => {
97
+ const bucket = fingerprint & (buckets - 1n);
98
+ const range = ranges.get(bucket);
99
+ const value = values[index];
100
+ if (!range) {
101
+ ranges.set(bucket, { min: value, max: value });
102
+ return;
103
+ }
104
+ range.min = value < range.min ? value : range.min;
105
+ range.max = value > range.max ? value : range.max;
106
+ });
107
+ const wraps = [...ranges.values()]
108
+ .map((range) => range.max - range.min)
109
+ .filter((difference) => difference > LONG_MAX)
110
+ .map((difference) => (difference === LONG_MAX + 1n ? -difference : (1n << 64n) - difference));
111
+ return [...gaps, ...wraps].reduce((min, gap) => (gap < min ? gap : min), LONG_MAX);
112
+ };
113
+
114
+ const getUnexpectedMessage = (cause: string, error: TlaEvaluationError) => {
115
+ const exception = isEvalException(error)
116
+ ? "tlc2.tool.EvalException"
117
+ : "java.lang.RuntimeException";
118
+ return cause === ""
119
+ ? getUnexpectedException(exception)
120
+ : `TLC threw an unexpected exception.\nThis was probably caused by an error in the spec or model.\nThe error occurred when TLC was ${cause}.\nThe exception was a ${exception}\n: `;
121
+ };
122
+
123
+ // DFIDWorker picks the next initial state and successor with an unseeded generator, so tla-ts picks
124
+ // the first one.
125
+ export const checkDepthFirst = (options: DepthFirstOptions): number => {
126
+ const output = options.onOutput;
127
+ const isTool = options.isTool ?? false;
128
+ const isContinued = options.isContinued ?? false;
129
+ const prepared = prepareSearch(options);
130
+ const config = prepared.config;
131
+ const environment = prepared.environment;
132
+ const runtime = environment.runtime;
133
+ const search = prepared.search;
134
+ if (!search) {
135
+ throw new TlaUnsupportedError("tla-ts can't search a specification without variables");
136
+ }
137
+ const message = (code: number, text: string, toolText = text, isError = true) =>
138
+ output({ kind: "message", code, isError, message: text, toolMessage: toolText });
139
+ const temporalProperties = search.properties.liveness;
140
+ if (temporalProperties.length > 0) {
141
+ options.onProgress?.({
142
+ kind: "liveness-initializing",
143
+ isSymmetric: search.isSymmetric,
144
+ isConstrained: search.isConstrained,
145
+ });
146
+ const branches = withLivenessExitCode(() =>
147
+ withUnexpectedException(() =>
148
+ createLivenessChecker(temporalProperties, search.spec.temporals, environment, {
149
+ getFingerprint: () => 0,
150
+ getSuccessors: () => [],
151
+ }),
152
+ ),
153
+ )?.branches;
154
+ if (branches) options.onProgress?.({ kind: "liveness-prepared", branches });
155
+ }
156
+ if ((options.workers ?? 1) !== 1) {
157
+ message(
158
+ MESSAGE_CODE.general,
159
+ "Depth-First Iterative Deepening mode does not support multiple workers (https://github.com/tlaplus/tlaplus/issues/548). Please run TLC with a single worker.",
160
+ );
161
+ return EXIT_STATUS.error;
162
+ }
163
+ if (temporalProperties.length > 0) {
164
+ message(
165
+ MESSAGE_CODE.general,
166
+ "Depth-First Iterative Deepening mode does not support checking liveness properties (https://github.com/tlaplus/tlaplus/issues/548). Please check liveness properties in Breadth-First-Search mode.",
167
+ );
168
+ return EXIT_STATUS.error;
169
+ }
170
+ runtime.generatedStates = -1;
171
+ runtime.distinctStates = -1;
172
+ runtime.initialStates = -1;
173
+ runtime.queueSize = -1;
174
+ runtime.diameter = -1;
175
+ runtime.isStarted = true;
176
+ const assumptionStatus = reportAssumptionViolation(
177
+ prepared.specification.assumptions,
178
+ environment,
179
+ message,
180
+ );
181
+ if (assumptionStatus !== undefined) return assumptionStatus;
182
+
183
+ const nextActions = getNextActions(config, environment, prepared.specification.instanceActions);
184
+ const statuses = new Map<bigint, number>();
185
+ const fingerprintSet = { level: 1, leveled: 0, buckets: INITIAL_BUCKETS };
186
+ const setStatus = (fingerprint: bigint, status: number) => {
187
+ const old = statuses.get(fingerprint);
188
+ if (old !== undefined) {
189
+ statuses.set(fingerprint, old | status);
190
+ return old;
191
+ }
192
+ if (BigInt(statuses.size) >= fingerprintSet.buckets * MAX_LOAD) fingerprintSet.buckets *= 2n;
193
+ statuses.set(fingerprint, (fingerprintSet.level << 2) | fingerprintSet.leveled | status);
194
+ return 0;
195
+ };
196
+ const getStatus = (fingerprint: bigint) => statuses.get(fingerprint) ?? 0;
197
+ const isCompleted = (status: number) =>
198
+ (status & LEVELED) === fingerprintSet.leveled || (status & DONE) === DONE;
199
+ const isLeafStatus = (status: number) => status === 0 || status >>> 2 === fingerprintSet.level;
200
+
201
+ const statistics = { generated: 0 };
202
+ const checker: CheckerState = {
203
+ isDone: false,
204
+ errorCode: NO_ERROR,
205
+ continuedCode: NO_ERROR,
206
+ isKeepingCallStack: false,
207
+ errorEntry: undefined,
208
+ stopCode: 0,
209
+ isMoreLevel: false,
210
+ };
211
+ const setErrorState = (entry: StateEntry, isKeepingCallStack: boolean, code: number) => {
212
+ if (!isContinued && checker.isDone) return false;
213
+ checker.errorEntry = entry;
214
+ checker.errorCode = code;
215
+ checker.isDone = true;
216
+ checker.isKeepingCallStack = isKeepingCallStack;
217
+ checker.stopCode = 2;
218
+ return true;
219
+ };
220
+ const toRecord = (state: (Value | undefined)[]) =>
221
+ search.toRecord(state.map((value) => value ?? createModelValue("null")));
222
+ const printSummary = () => {
223
+ const counts = `${statistics.generated} states generated, ${statuses.size} distinct states found`;
224
+ if (isTool) {
225
+ message(
226
+ MESSAGE_CODE.depthFirstProgress,
227
+ `Progress: ${counts}.`,
228
+ `Progress(-1) at ${formatTlcDate(new Date())}: ${counts}, -1 states left on queue.`,
229
+ false,
230
+ );
231
+ }
232
+ message(MESSAGE_CODE.depthFirstStats, `${counts}.`, undefined, false);
233
+ };
234
+ const reportSuccess = () =>
235
+ output({
236
+ kind: "success",
237
+ optimistic: getOptimisticProbability(statuses.size, statistics.generated),
238
+ actual:
239
+ statuses.size === 0 && statistics.generated === 0
240
+ ? 0
241
+ : getActualProbability(
242
+ getFingerprintDistance([...statuses.keys()], fingerprintSet.buckets),
243
+ ),
244
+ });
245
+ const levels = new WeakMap<(Value | undefined)[], number>();
246
+ const current: StateHolder = { state: undefined };
247
+ runtime.getLevel = (state) => levels.get(state) ?? 0;
248
+ runtime.getCurrentState = () => current.state;
249
+
250
+ const initialEntries: StateEntry[] = [];
251
+ const errorState: StateHolder = { state: undefined };
252
+ const computeInitialStates = (): number => {
253
+ const generated: (Value | undefined)[][] = [];
254
+ const addGenerated = (state: (Value | undefined)[]) => {
255
+ generated.push(state);
256
+ return false;
257
+ };
258
+ const init = search.spec.init;
259
+ if (init) forEachInitialState(init, environment, addGenerated, search.spec.scope, addGenerated);
260
+ statistics.generated = generated.length;
261
+ for (const state of generated) {
262
+ if (!state.every((value) => value !== undefined)) {
263
+ message(
264
+ MESSAGE_CODE.initialStateIncomplete,
265
+ `State is not completely specified by the initial predicate:\n${formatState(toRecord(state))}`,
266
+ );
267
+ return MESSAGE_CODE.initialStateIncomplete;
268
+ }
269
+ errorState.state = state;
270
+ levels.set(state, 1);
271
+ const isInModel = search.satisfiesConstraints(state);
272
+ const fingerprint = isInModel ? runtime.getFingerprint(state) : 0n;
273
+ const status = isInModel ? setStatus(fingerprint, 0) : 0;
274
+ if (isInModel && status === 0) initialEntries.push({ state, fingerprint });
275
+ if (status !== 0) continue;
276
+ const alias = () =>
277
+ config.alias === undefined
278
+ ? search.toRecord(state)
279
+ : search.evaluateAlias(config.alias, state, state, isTool);
280
+ const violated = isContinued
281
+ ? search.getViolatedInvariants(state)
282
+ : [search.findViolatedInvariant(state)].filter((invariant) => invariant !== undefined);
283
+ for (const invariant of violated) {
284
+ message(
285
+ MESSAGE_CODE.invariantViolatedInitial,
286
+ `Invariant ${invariant.name} is violated by the initial state:\n${formatState(alias())}`,
287
+ );
288
+ if (!isContinued) return MESSAGE_CODE.invariantViolatedInitial;
289
+ checker.continuedCode = MESSAGE_CODE.invariantViolatedInitial;
290
+ }
291
+ const predicate = search.findFailedInitialPredicate(state);
292
+ if (predicate) {
293
+ message(
294
+ MESSAGE_CODE.propertyViolatedInitial,
295
+ `Property ${predicate.name} is violated by the initial state:\n${formatState(alias())}`,
296
+ );
297
+ return MESSAGE_CODE.propertyViolatedInitial;
298
+ }
299
+ }
300
+ return NO_ERROR;
301
+ };
302
+
303
+ const getActionSuccessors = (action: SpecAction, state: Value[]) => {
304
+ const successors: Value[][] = [];
305
+ try {
306
+ forEachSuccessor(
307
+ action.expression,
308
+ state,
309
+ environment,
310
+ (successor) => {
311
+ if (successors.length === getSetBound()) throw new TlaTooManyStatesError();
312
+ successors.push(successor.state);
313
+ return false;
314
+ },
315
+ action.scope,
316
+ );
317
+ return { successors, incomplete: undefined };
318
+ } catch (error) {
319
+ if (!(error instanceof TlaIncompleteSuccessorError)) throw error;
320
+ return { successors, incomplete: error };
321
+ }
322
+ };
323
+
324
+ const findCheckFailure = (state: Value[], successor: Value[], isNew: boolean) => {
325
+ try {
326
+ const invariant = isNew ? search.findViolatedInvariant(successor, state) : undefined;
327
+ if (invariant) {
328
+ return {
329
+ code: MESSAGE_CODE.invariantViolatedBehavior,
330
+ text: `Invariant ${invariant.name} is violated.`,
331
+ isViolated: true,
332
+ };
333
+ }
334
+ const property = search.findViolatedActionProperty(state, successor);
335
+ return (
336
+ property && {
337
+ code: MESSAGE_CODE.actionPropertyViolatedBehavior,
338
+ text: `Action property ${property.name} is violated.`,
339
+ isViolated: true,
340
+ }
341
+ );
342
+ } catch (error) {
343
+ if (!(error instanceof TlaEvaluationError) || !isHeadedError(error)) throw error;
344
+ return {
345
+ code: getFailureMessage(error, true).code,
346
+ text: error.message.slice(0, error.message.indexOf("\n")),
347
+ isViolated: false,
348
+ };
349
+ }
350
+ };
351
+ const stack: StateEntry[] = [];
352
+ const successorStack: StateEntry[][] = [];
353
+ const printTrace = (
354
+ code: number,
355
+ text: string,
356
+ toolText: string,
357
+ depth: number,
358
+ successor: (Value | undefined)[] | undefined,
359
+ ) => {
360
+ message(code, text, toolText);
361
+ message(MESSAGE_CODE.behaviorUpToThisPoint, "The behavior up to this point is:");
362
+ const states = [
363
+ ...stack.slice(0, depth + 1).map((entry) => entry.state),
364
+ ...(successor ? [successor] : []),
365
+ ];
366
+ output({
367
+ kind: "behavior",
368
+ states: states.map(toRecord),
369
+ isInvariant: code === MESSAGE_CODE.invariantViolatedBehavior,
370
+ });
371
+ };
372
+ const expandState = (depth: number, isLeaf: boolean, successors: StateEntry[]) => {
373
+ const entry = stack[depth];
374
+ const state = entry.state;
375
+ const result = { isDeadlocked: true, isAllDone: true, isNoLeaf: true };
376
+ const processing: Processing = { successor: undefined };
377
+ const report = (code: number, text: string, isKeepingCallStack: boolean) => {
378
+ if (setErrorState(entry, isKeepingCallStack, code)) {
379
+ printTrace(code, text, text, depth, processing.successor);
380
+ }
381
+ return result.isNoLeaf;
382
+ };
383
+ current.state = state;
384
+ try {
385
+ for (const action of nextActions) {
386
+ const next = getActionSuccessors(action, state);
387
+ const incomplete = next.incomplete;
388
+ const count = next.successors.length + (incomplete ? 1 : 0);
389
+ statistics.generated += count;
390
+ result.isDeadlocked &&= count === 0;
391
+ for (const successor of next.successors) {
392
+ processing.successor = successor;
393
+ levels.set(successor, depth + 2);
394
+ const isInModel =
395
+ search.satisfiesConstraints(successor, state) &&
396
+ search.satisfiesActionConstraints(state, successor);
397
+ const fingerprint = isInModel ? runtime.getFingerprint(successor) : 0n;
398
+ const status = isInModel ? setStatus(fingerprint, 0) : 0;
399
+ if (isInModel) {
400
+ result.isAllDone &&= (status & DONE) === DONE;
401
+ result.isNoLeaf &&= !isLeafStatus(status);
402
+ if (!isCompleted(status)) {
403
+ if (successors.length === getSetBound()) throw new TlaTooManyStatesError();
404
+ successors.push({ state: successor, fingerprint });
405
+ }
406
+ }
407
+ const failure = findCheckFailure(state, successor, status === 0);
408
+ if (failure?.isViolated && isContinued) {
409
+ printTrace(failure.code, failure.text, failure.text, depth, successor);
410
+ checker.continuedCode = failure.code;
411
+ continue;
412
+ }
413
+ if (failure) return report(failure.code, failure.text, !failure.isViolated);
414
+ }
415
+ if (incomplete) {
416
+ processing.successor = incomplete.state;
417
+ return report(
418
+ MESSAGE_CODE.incompleteSuccessor,
419
+ getIncompleteSuccessorMessage(
420
+ incomplete.variables,
421
+ action.name,
422
+ nextActions.length,
423
+ options.version,
424
+ ),
425
+ false,
426
+ );
427
+ }
428
+ processing.successor = undefined;
429
+ }
430
+ if (result.isDeadlocked && config.checkDeadlock) {
431
+ return report(MESSAGE_CODE.deadlockReached, "Deadlock reached.", false);
432
+ }
433
+ if (result.isAllDone || (isLeaf && result.isNoLeaf)) setStatus(entry.fingerprint, DONE);
434
+ return result.isNoLeaf;
435
+ } catch (error) {
436
+ const failure = isStackOverflow(error) ? new TlaStackOverflowError() : error;
437
+ if (!(failure instanceof TlaEvaluationError)) throw error;
438
+ const isOverflow = failure instanceof TlaStackOverflowError;
439
+ if (
440
+ setErrorState(
441
+ entry,
442
+ !isOverflow,
443
+ isOverflow ? MESSAGE_CODE.stackOverflow : MESSAGE_CODE.general,
444
+ )
445
+ ) {
446
+ const unexpected = getUnexpectedMessage("computing the set of next states", failure);
447
+ printTrace(
448
+ isOverflow ? MESSAGE_CODE.stackOverflow : MESSAGE_CODE.general,
449
+ isOverflow ? failure.message : `${unexpected}${failure.message}`,
450
+ isOverflow
451
+ ? failure.message
452
+ : `${unexpected}${formatNestedMessage(failure.message, true)}`,
453
+ depth,
454
+ processing.successor,
455
+ );
456
+ }
457
+ throw failure;
458
+ }
459
+ };
460
+ const getNextIndex = (successors: StateEntry[], level: number) => {
461
+ while (successors.length > 0) {
462
+ const status = getStatus(successors[0].fingerprint);
463
+ if (!isCompleted(status) && level < status >>> 2) return 0;
464
+ successors[0] = successors[successors.length - 1];
465
+ successors.pop();
466
+ }
467
+ return -1;
468
+ };
469
+ const searchLevel = (toLevel: number) => {
470
+ const initials = [...initialEntries];
471
+ checker.stopCode = 0;
472
+ checker.isMoreLevel = false;
473
+ const position = { level: 0 };
474
+ try {
475
+ while (checker.stopCode === 0) {
476
+ while (initials.length > 0 && isCompleted(getStatus(initials[0].fingerprint))) {
477
+ initials[0] = initials[initials.length - 1];
478
+ initials.pop();
479
+ }
480
+ if (initials.length === 0) {
481
+ checker.stopCode = 1;
482
+ return;
483
+ }
484
+ stack[0] = initials[0];
485
+ successorStack[0] = [];
486
+ position.level = 0;
487
+ const isInitialLeaf = toLevel < 2;
488
+ const isInitialNoLeaf = expandState(0, isInitialLeaf, successorStack[0]);
489
+ checker.isMoreLevel ||= !isInitialNoLeaf;
490
+ position.level = 1;
491
+ while (!isInitialLeaf) {
492
+ const index = getNextIndex(successorStack[position.level - 1], position.level);
493
+ if (index === -1) {
494
+ const entry = stack[position.level - 1];
495
+ statuses.set(
496
+ entry.fingerprint,
497
+ (getStatus(entry.fingerprint) & ~LEVELED) | fingerprintSet.leveled,
498
+ );
499
+ if (position.level === 1) break;
500
+ position.level--;
501
+ continue;
502
+ }
503
+ stack[position.level] = successorStack[position.level - 1][index];
504
+ successorStack[position.level] = [];
505
+ const isLeaf = position.level >= toLevel - 1;
506
+ const isNoLeaf = expandState(position.level, isLeaf, successorStack[position.level]);
507
+ checker.isMoreLevel ||= !isNoLeaf;
508
+ position.level++;
509
+ if (isLeaf) break;
510
+ }
511
+ }
512
+ } catch (error) {
513
+ if (!(error instanceof TlaEvaluationError)) throw error;
514
+ checker.stopCode = 2;
515
+ if (setErrorState(stack[position.level], true, MESSAGE_CODE.general)) {
516
+ const unexpected = getUnexpectedMessage("", error);
517
+ message(
518
+ MESSAGE_CODE.general,
519
+ `${unexpected}${error.message}`,
520
+ `${unexpected}${formatNestedMessage(error.message, true)}`,
521
+ );
522
+ }
523
+ }
524
+ };
525
+ const replayExpansion = (entry: StateEntry) => {
526
+ const tracing = createTracingEnvironment(environment);
527
+ try {
528
+ const isPassed = nextActions.every((action) => {
529
+ const successors: Value[][] = [];
530
+ replaySuccessors([action], entry.state, tracing, (successor) => successors.push(successor));
531
+ statistics.generated += successors.length;
532
+ return successors.every(
533
+ (successor) =>
534
+ successor.every((value) => value !== undefined) &&
535
+ search.checkReplayedSuccessor(
536
+ entry.state,
537
+ successor,
538
+ tracing,
539
+ () => setStatus(runtime.getFingerprint(successor), 0) === 0,
540
+ ),
541
+ );
542
+ });
543
+ if (isPassed) return;
544
+ } catch (error) {
545
+ if (!(error instanceof TlaEvaluationError) && !isStackOverflow(error)) throw error;
546
+ }
547
+ output({ kind: "nested-expressions", callStack: tracing.callStack?.expressions ?? [] });
548
+ };
549
+
550
+ const finish = (code: number) => {
551
+ printSummary();
552
+ const status = [code, checker.errorCode, checker.continuedCode].find(
553
+ (candidate) => candidate !== NO_ERROR,
554
+ );
555
+ return status === undefined ? EXIT_STATUS.success : getMessageExitStatus(status);
556
+ };
557
+ const tryInitialStates = () => {
558
+ try {
559
+ return { code: computeInitialStates(), error: undefined };
560
+ } catch (error) {
561
+ const failure = isStackOverflow(error) ? new TlaStackOverflowError() : error;
562
+ if (!(failure instanceof TlaEvaluationError)) throw error;
563
+ return { code: NO_ERROR, error: failure };
564
+ }
565
+ };
566
+ const initialFailure = tryInitialStates();
567
+ if (initialFailure.error) {
568
+ const failure = initialFailure.error;
569
+ const inner =
570
+ isHeadedError(failure) && failure.cause instanceof TlaEvaluationError
571
+ ? failure.cause
572
+ : failure;
573
+ const initialState = errorState.state;
574
+ const prefix = initialState ? "" : getUnexpectedMessage("computing initial states", inner);
575
+ const suffix = initialState
576
+ ? `\nWhile working on the initial state:\n${formatState(toRecord(initialState))}`
577
+ : "";
578
+ message(
579
+ initialState ? MESSAGE_CODE.initialState : MESSAGE_CODE.general,
580
+ `${prefix}${inner.message}${suffix}`,
581
+ `${prefix}${formatNestedMessage(inner.message, true)}${suffix}`,
582
+ );
583
+ // TLC prints its Tool in place of the call stack, named by an identity hash.
584
+ statistics.generated = 0;
585
+ initialEntries.length = 0;
586
+ const isReplayFailed = tryInitialStates().error !== undefined;
587
+ if (isReplayFailed) {
588
+ message(
589
+ MESSAGE_CODE.nestedExpression,
590
+ `The error occurred when TLC was evaluating the nested\nexpressions at the following positions:\ntlc2.tool.impl.FastTool@${(Number(BigInt.asUintN(28, getTlcFingerprint([options.source]))) | 0x1000_0000).toString(16)}`,
591
+ );
592
+ }
593
+ printSummary();
594
+ return isReplayFailed ? EXIT_STATUS.specEvaluationFailure : getErrorExitCode(inner);
595
+ }
596
+ if (initialFailure.code !== NO_ERROR) return getMessageExitStatus(initialFailure.code);
597
+ message(
598
+ MESSAGE_CODE.depthFirstInitGenerated,
599
+ `Finished computing initial states: ${statistics.generated} states generated, with ${initialEntries.length} of them distinct.`,
600
+ undefined,
601
+ false,
602
+ );
603
+ if (nextActions.length === 0) {
604
+ reportSuccess();
605
+ return finish(NO_ERROR);
606
+ }
607
+ const loop: LevelLoop = {
608
+ isTerminated: false,
609
+ code: MESSAGE_CODE.general,
610
+ };
611
+ for (let level = 2; level <= options.maxDepth; level++) {
612
+ if (loop.isTerminated) {
613
+ const errorEntry = checker.errorEntry;
614
+ if (!errorEntry && checker.continuedCode === NO_ERROR) {
615
+ loop.code = NO_ERROR;
616
+ reportSuccess();
617
+ }
618
+ if (errorEntry && checker.isKeepingCallStack) replayExpansion(errorEntry);
619
+ break;
620
+ }
621
+ message(
622
+ MESSAGE_CODE.depthFirstLevel,
623
+ `Starting level ${level}: ${statistics.generated} states generated, ${statuses.size} distinct states found.`,
624
+ undefined,
625
+ false,
626
+ );
627
+ fingerprintSet.level++;
628
+ fingerprintSet.leveled = LEVELED - fingerprintSet.leveled;
629
+ searchLevel(level);
630
+ checker.isDone = false;
631
+ loop.code = checker.isKeepingCallStack ? NO_ERROR : checker.errorCode;
632
+ if (loop.code !== NO_ERROR) return finish(loop.code);
633
+ loop.isTerminated = checker.stopCode === 2 || !checker.isMoreLevel;
634
+ }
635
+ return finish(loop.code);
636
+ };