tla-ts 0.0.10-dev.28c823e4b → 0.0.10-dev.b4a856304

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 (68) hide show
  1. package/dist/index.cjs +1 -1
  2. package/dist/index.d.cts +0 -34
  3. package/dist/index.d.ts +0 -34
  4. package/dist/index.js +1 -1
  5. package/dist/parallel-worker.cjs +1 -1
  6. package/dist/parallel-worker.js +1 -1
  7. package/dist/prove.cjs +43 -43
  8. package/dist/prove.js +47 -47
  9. package/dist/run.cjs +30 -30
  10. package/dist/run.js +33 -33
  11. package/dist/transfer.cjs +38 -38
  12. package/dist/transfer.js +39 -39
  13. package/package.json +1 -1
  14. package/src/ast.ts +5 -0
  15. package/src/bags.ts +5 -2
  16. package/src/builtins.ts +8 -1
  17. package/src/check.ts +193 -128
  18. package/src/cli/run.ts +2 -0
  19. package/src/cli/runtime-invariants.ts +7 -8
  20. package/src/cli/shared.ts +4 -0
  21. package/src/cli/tlc-arguments.ts +30 -24
  22. package/src/cli/tlc-usage.ts +3 -2
  23. package/src/evaluate.ts +102 -26
  24. package/src/java-overrides.ts +9 -4
  25. package/src/json-reader.ts +2 -1
  26. package/src/json.ts +11 -4
  27. package/src/levels.ts +15 -7
  28. package/src/lexer.ts +83 -72
  29. package/src/liveness-checker.ts +106 -77
  30. package/src/liveness.ts +34 -10
  31. package/src/parallel.ts +33 -26
  32. package/src/parser.ts +226 -163
  33. package/src/pcal/ast.ts +65 -53
  34. package/src/pcal/parse.ts +191 -144
  35. package/src/pcal/tokenize.ts +115 -91
  36. package/src/pcal/translate.ts +98 -83
  37. package/src/pcal/validate.ts +50 -48
  38. package/src/pretty-print.ts +6 -6
  39. package/src/randomization.ts +4 -1
  40. package/src/resolve.ts +70 -12
  41. package/src/runtime.ts +18 -11
  42. package/src/sany/builtins.ts +3 -1
  43. package/src/sany/generator.ts +127 -74
  44. package/src/sany/levels.ts +9 -5
  45. package/src/sany/lexer.ts +44 -40
  46. package/src/sany/linter.ts +1 -0
  47. package/src/search.ts +1 -1
  48. package/src/simulate.ts +59 -50
  49. package/src/spec-description.ts +34 -23
  50. package/src/standard-definitions.ts +3 -0
  51. package/src/standard-modules.ts +12 -1
  52. package/src/state-graph.ts +8 -1
  53. package/src/subexpressions.ts +47 -38
  54. package/src/successors.ts +35 -14
  55. package/src/symmetry.ts +19 -4
  56. package/src/tlc/fingerprint.ts +21 -15
  57. package/src/tlc/jar-data.ts +1 -0
  58. package/src/tlc/messages.ts +21 -2
  59. package/src/tlc/order.ts +38 -20
  60. package/src/tlc/random.ts +30 -18
  61. package/src/tlc/replay.ts +33 -13
  62. package/src/tlc/summary.ts +45 -36
  63. package/src/tlc/tlc-operators.ts +14 -4
  64. package/src/tlc/tlcext-operators.ts +15 -11
  65. package/src/tlc/trace-spec.ts +4 -0
  66. package/src/tlc/value-stream.ts +13 -9
  67. package/src/tlc/version.ts +1 -0
  68. package/src/values.ts +181 -74
@@ -272,14 +272,14 @@ const checkDefinitionBody = (node: AnyDefNode, params: FormalParamNode[], body:
272
272
  node.minMaxLevel = params.map((param) =>
273
273
  Array.from(
274
274
  { length: param.arity },
275
- (_value, position) =>
275
+ (_, position) =>
276
276
  body.argLevelConstraints.get(getArgLevelConstraintKey(param, position))?.level ??
277
277
  CONSTANT_LEVEL,
278
278
  ),
279
279
  );
280
280
  node.opLevelCond = params.map((param) =>
281
281
  params.map((other) =>
282
- Array.from({ length: param.arity }, (_value, index) =>
282
+ Array.from({ length: param.arity }, (_, index) =>
283
283
  body.argLevelParams.has(getArgLevelKey(param, index, other)),
284
284
  ),
285
285
  ),
@@ -391,7 +391,7 @@ const constrainArguments = (
391
391
  ) => {
392
392
  const params = operator.params ?? [];
393
393
  const getArgument = (symbol: SymbolNode) =>
394
- node.operands.find((_operand, index) => params[index] === symbol);
394
+ node.operands.find((_, index) => params[index] === symbol);
395
395
  putLevelConstraints(node.levelConstraints, operator.levelConstraints);
396
396
  node.operands.forEach((operand) => {
397
397
  if (operand === undefined) return;
@@ -527,6 +527,7 @@ const LOGICAL_OPERATOR_NAMES = new Map([
527
527
  ["$DisjList", "Disjunction list"],
528
528
  ]);
529
529
 
530
+ // TLC 1.7.4's SANY reports these errors but leaves the node level-correct.
530
531
  const checkTemporalApplication = (node: OpApplNode, check: LevelCheck) => {
531
532
  const addTemporalError = (location: SanyLocation, text: string) => {
532
533
  addError(check, location, text);
@@ -679,7 +680,7 @@ const checkTheoremDefinition = (node: ThmOrAssumpDefNode, iteration: number, che
679
680
  node.levelChecked = iteration;
680
681
  node.maxLevels = node.params.map(() => TEMPORAL_LEVEL);
681
682
  // SANY allocates isLeibnizArg anew for each parameter, so only the last one starts out Leibniz.
682
- node.isLeibnizArg = node.params.map((_param, index) => index === node.params.length - 1);
683
+ node.isLeibnizArg = node.params.map((_, index) => index === node.params.length - 1);
683
684
  if (node.params.length > 0) node.isLeibniz = true;
684
685
  node.levelCorrect = checkLevel(node.body, iteration, check);
685
686
  node.level = node.body.level;
@@ -691,6 +692,8 @@ const checkTheoremDefinition = (node: ThmOrAssumpDefNode, iteration: number, che
691
692
  return node.levelCorrect;
692
693
  };
693
694
 
695
+ // SANY checks the definitions of each recursive section twice, the second time with the highest
696
+ // level and the parameters of the section's recursive operators.
694
697
  export const checkModuleLevels = (module: ModuleNode, check: LevelCheck) => {
695
698
  if (module.isLevelChecked) return module.levelCorrect;
696
699
  module.isLevelChecked = true;
@@ -1108,7 +1111,8 @@ const checkLevel = (node: SemanticNode, iteration: number, check: LevelCheck): b
1108
1111
  return isBodyCorrect && isDefinitionCorrect;
1109
1112
  }
1110
1113
  case "Theorem": {
1111
- // SANY's TheoremNode declares its own levelChecked, so levelCheckSubnodes still runs on it.
1114
+ // TheoremNode declares its own levelChecked, so levelCheckSubnodes still runs on its definition,
1115
+ // or its statement when it has none, and its proof.
1112
1116
  if (node.levelChecked >= iteration) return true;
1113
1117
  const isCorrect = checkSubnodes(
1114
1118
  node,
package/src/sany/lexer.ts CHANGED
@@ -10,6 +10,7 @@ export interface SanyToken {
10
10
  next: SanyToken | undefined;
11
11
  }
12
12
 
13
+ // In TLAplusParserConstants order, by which JavaCC breaks a tie between matches of one length.
13
14
  const KINDS: [string, ...string[]][] = [
14
15
  ["EOF"],
15
16
  ["BEGIN_PRAGMA", "--->"],
@@ -225,6 +226,7 @@ const KIND_INDEXES = new Map(
225
226
  KIND_NAMES.map((name, kind): [string, number] => [name, kind]).reverse(),
226
227
  );
227
228
 
229
+ // The anonymous infix operators share the name "infix", which no caller looks up.
228
230
  export const getKind = (name: string) => {
229
231
  const kind = KIND_INDEXES.get(name);
230
232
  if (kind === undefined) throw new TlaError(`Unknown SANY token kind ${name}`);
@@ -237,7 +239,7 @@ const LITERALS = new Map(
237
239
  const LONGEST_LITERAL = Math.max(...[...LITERALS.keys()].map((image) => image.length));
238
240
  const LITERAL_LENGTHS = Array.from(
239
241
  { length: LONGEST_LITERAL },
240
- (_value, index) => LONGEST_LITERAL - index,
242
+ (_, index) => LONGEST_LITERAL - index,
241
243
  );
242
244
 
243
245
  const BEGIN_MODULE = /----+ *MODULE/y;
@@ -325,30 +327,27 @@ export const getTabStop = (column: number) => column + 8 - (column % 8);
325
327
  const getPositions = (source: string) => {
326
328
  const lines: number[] = [];
327
329
  const columns: number[] = [];
328
- let line = 1;
329
- let column = 0;
330
- let isAfterCr = false;
331
- let isAfterLf = false;
330
+ const state = { line: 1, column: 0, isAfterCr: false, isAfterLf: false };
332
331
  for (const character of source) {
333
332
  for (let unit = 0; unit < character.length; unit++) {
334
- column++;
335
- if (isAfterLf) {
336
- isAfterLf = false;
337
- line++;
338
- column = 1;
339
- } else if (isAfterCr) {
340
- isAfterCr = false;
341
- if (character === "\n") isAfterLf = true;
333
+ state.column++;
334
+ if (state.isAfterLf) {
335
+ state.isAfterLf = false;
336
+ state.line++;
337
+ state.column = 1;
338
+ } else if (state.isAfterCr) {
339
+ state.isAfterCr = false;
340
+ if (character === "\n") state.isAfterLf = true;
342
341
  else {
343
- line++;
344
- column = 1;
342
+ state.line++;
343
+ state.column = 1;
345
344
  }
346
345
  }
347
- if (character === "\r") isAfterCr = true;
348
- else if (character === "\n") isAfterLf = true;
349
- else if (character === "\t") column = getTabStop(column - 1);
350
- lines.push(line);
351
- columns.push(column);
346
+ if (character === "\r") state.isAfterCr = true;
347
+ else if (character === "\n") state.isAfterLf = true;
348
+ else if (character === "\t") state.column = getTabStop(state.column - 1);
349
+ lines.push(state.line);
350
+ columns.push(state.column);
352
351
  }
353
352
  }
354
353
  return { lines, columns };
@@ -357,7 +356,7 @@ const getPositions = (source: string) => {
357
356
  const STRING_PREFIX = /"(?:[^"\n\r\\]|\\[ntrf\\"])*\\?/y;
358
357
  const LITERAL_PREFIXES = new Set(
359
358
  [...LITERALS.keys()].flatMap((image) =>
360
- Array.from({ length: image.length - 1 }, (_value, index) => image.slice(0, index + 1)),
359
+ Array.from({ length: image.length - 1 }, (_, index) => image.slice(0, index + 1)),
361
360
  ),
362
361
  );
363
362
 
@@ -372,8 +371,7 @@ const getTokenPrefix = (source: string, offset: number) => {
372
371
 
373
372
  export const createSanyLexer = (source: string) => {
374
373
  const positions = getPositions(source);
375
- let nextOffset = 0;
376
- let mode = "DEFAULT";
374
+ const state = { offset: 0, mode: "DEFAULT" };
377
375
  const createToken = (kind: number, start: number, length: number): SanyToken => ({
378
376
  kind,
379
377
  image: source.slice(start, start + length),
@@ -383,6 +381,8 @@ export const createSanyLexer = (source: string) => {
383
381
  });
384
382
  // JavaCC places the end of the file at the file's last character.
385
383
  const getEndOfFile = () => createToken(getKind("EOF"), source.length - 1, 0);
384
+ // TLAplusParser.parse reports the end of the file in a token that starts on an earlier line as an
385
+ // open comment.
386
386
  const getLexicalError = (start: number, end: number, after: string) => {
387
387
  const index = end - 1;
388
388
  const line = positions.lines[index];
@@ -395,12 +395,13 @@ export const createSanyLexer = (source: string) => {
395
395
  ? formatLexicalError(line + 1, 0, undefined, after)
396
396
  : formatLexicalError(line, column + 1, undefined, after);
397
397
  };
398
+ // The end of the file right after a nested comment bracket ends the token stream.
398
399
  const skipComment = () => {
399
- const start = nextOffset;
400
+ const start = state.offset;
400
401
  if (source.startsWith("\\*", start)) {
401
402
  const end = source.slice(start).search(/[\n\r]/);
402
403
  if (end === -1) return getLexicalError(start, source.length, "");
403
- nextOffset += end + 1;
404
+ state.offset += end + 1;
404
405
  return undefined;
405
406
  }
406
407
  let depth = 0;
@@ -416,40 +417,41 @@ export const createSanyLexer = (source: string) => {
416
417
  offset += 2;
417
418
  chainStart = offset;
418
419
  if (depth === 0) {
419
- nextOffset = offset;
420
+ state.offset = offset;
420
421
  return undefined;
421
422
  }
422
423
  } else offset++;
423
424
  }
424
- nextOffset = offset;
425
+ state.offset = offset;
425
426
  return chainStart === source.length ? undefined : getLexicalError(chainStart, offset, "");
426
427
  };
427
428
  const getSkippingToken = (patterns: [string, RegExp[]][]): SanyToken => {
428
- while (nextOffset < source.length) {
429
- const match = matchPatterns(patterns, source, nextOffset);
429
+ while (state.offset < source.length) {
430
+ const match = matchPatterns(patterns, source, state.offset);
430
431
  if (match.length > 0) {
431
- const token = createToken(match.kind, nextOffset, match.length);
432
- nextOffset += match.length;
433
- if (KIND_NAMES[match.kind].startsWith("_BM")) mode = "SPEC";
434
- if (KIND_NAMES[match.kind] === "BEGIN_PRAGMA") mode = "PRAGMA";
432
+ const token = createToken(match.kind, state.offset, match.length);
433
+ state.offset += match.length;
434
+ if (KIND_NAMES[match.kind].startsWith("_BM")) state.mode = "SPEC";
435
+ if (KIND_NAMES[match.kind] === "BEGIN_PRAGMA") state.mode = "PRAGMA";
435
436
  return token;
436
437
  }
437
- nextOffset++;
438
+ state.offset++;
438
439
  }
439
440
  return getEndOfFile();
440
441
  };
441
442
  const getNextToken = (): SanyToken | string => {
442
- if (mode === "DEFAULT") return getSkippingToken(DEFAULT_PATTERNS);
443
- if (mode === "PRAGMA") return getSkippingToken(PRAGMA_PATTERNS);
444
- while (nextOffset < source.length) {
445
- const offset = nextOffset;
446
- if (" \t\n\r".includes(source[offset])) nextOffset++;
443
+ if (state.mode === "DEFAULT") return getSkippingToken(DEFAULT_PATTERNS);
444
+ if (state.mode === "PRAGMA") return getSkippingToken(PRAGMA_PATTERNS);
445
+ while (state.offset < source.length) {
446
+ const offset = state.offset;
447
+ if (" \t\n\r".includes(source[offset])) state.offset++;
447
448
  else if (source.startsWith("(*", offset) || source.startsWith("\\*", offset)) {
448
449
  const error = skipComment();
449
450
  if (error !== undefined) return error;
450
451
  } else {
451
452
  const match = matchSpecToken(source, offset);
452
453
  if (match.length === 0) {
454
+ // JavaCC reads on while a token could continue, and one more character.
453
455
  const prefix = getTokenPrefix(source, offset);
454
456
  const end = Math.min(offset + prefix.length + 1, source.length);
455
457
  const read = source.slice(offset, end);
@@ -457,7 +459,7 @@ export const createSanyLexer = (source: string) => {
457
459
  return getLexicalError(offset, end, after);
458
460
  }
459
461
  const token = createToken(match.kind, offset, match.length);
460
- nextOffset += match.length;
462
+ state.offset += match.length;
461
463
  return token;
462
464
  }
463
465
  }
@@ -494,6 +496,8 @@ export const formatLexicalError = (
494
496
  ) =>
495
497
  `Lexical error at line ${line}, column ${column}. Encountered: ${character === undefined ? "<EOF> " : `"${escapeLexeme(character)}" (${character.charCodeAt(0)}), `}after : "${escapeLexeme(after)}"`;
496
498
 
499
+ // TLC 1.7.4's lexer, generated without UNICODE_INPUT, reads a character past U+00FF outside a
500
+ // comment by its low byte, and stops at one whose low byte is below 0x80.
497
501
  export const getSany174LexicalError = (source: string) => {
498
502
  const readToken = createSanyLexer(source);
499
503
  for (
@@ -69,6 +69,7 @@ const getFieldName = (pair: OpApplNode) => {
69
69
  return name?.kind === "String" ? name : undefined;
70
70
  };
71
71
 
72
+ // Records.sameDomain, given that SANY rejects a record with two fields of the same name.
72
73
  const getDomain = (record: OpApplNode) =>
73
74
  JSON.stringify([
74
75
  record.operands.length,
package/src/search.ts CHANGED
@@ -30,7 +30,6 @@ import {
30
30
  TlaEvaluationError,
31
31
  TlaModuleError,
32
32
  UNEXPECTED_EXCEPTION,
33
- formatRange,
34
33
  } from "./errors";
35
34
  import {
36
35
  describeNode,
@@ -40,6 +39,7 @@ import {
40
39
  getStartupValue,
41
40
  expectBoolean,
42
41
  expectBooleanBody,
42
+ formatRange,
43
43
  getDefinition,
44
44
  type Context,
45
45
  type Environment,
package/src/simulate.ts CHANGED
@@ -111,6 +111,8 @@ export const simulate = (options: SimulationOptions): number => {
111
111
  const search = prepared.search;
112
112
  const seed = options.seed ?? 0n;
113
113
  const traceDepth = options.traceDepth === -1 ? INFINITE_DEPTH : options.traceDepth;
114
+ // TLC.process seeds its RandomGenerator and draws -aril doubles, and each worker's generator is
115
+ // seeded with the next long of it.
114
116
  const random = createJavaRandom(seed);
115
117
  for (let index = 0n; index < options.aril; index++) random.nextDouble();
116
118
  const workerRandom = createJavaRandom(random.nextLong());
@@ -122,14 +124,13 @@ export const simulate = (options: SimulationOptions): number => {
122
124
  seed,
123
125
  aril: options.aril,
124
126
  };
125
- const reportMessage = (code: number, text: string, toolText = text, isError = true) =>
127
+ const message = (code: number, text: string, toolText = text, isError = true) =>
126
128
  output({ kind: "message", code, isError, message: text, toolMessage: toolText });
127
129
  const printSummary = () => output({ kind: "summary", statistics: { ...statistics } });
128
130
  const nodes = new WeakMap<(Value | undefined)[], TraceNode>();
129
131
  const initActions = getInitActions(config, environment, specification.instanceActions);
130
132
  const nextActions = getNextActions(config, environment, specification.instanceActions);
131
- let traceCount = 0;
132
- let currentTrace = 0;
133
+ const worker = { traceCount: 0, currentTrace: 0 };
133
134
  runtime.getLevel = (state) => nodes.get(state)?.level ?? 0;
134
135
  runtime.getBehavior = (state) => {
135
136
  const node = nodes.get(state);
@@ -139,7 +140,7 @@ export const simulate = (options: SimulationOptions): number => {
139
140
  const node = state && nodes.get(state);
140
141
  switch (key) {
141
142
  case "diameter":
142
- return currentTrace === 0 ? 0 : traceCount + 1;
143
+ return worker.currentTrace === 0 ? 0 : worker.traceCount + 1;
143
144
  case "generated":
144
145
  case "distinct":
145
146
  case "queue":
@@ -171,7 +172,7 @@ export const simulate = (options: SimulationOptions): number => {
171
172
  "behavior",
172
173
  createRecord([
173
174
  ["actions", createRecord([...actions])],
174
- ["id", currentTrace],
175
+ ["id", worker.currentTrace],
175
176
  ]),
176
177
  ],
177
178
  ["worker", 0],
@@ -194,7 +195,7 @@ export const simulate = (options: SimulationOptions): number => {
194
195
  const postcondition = search.findPostconditionViolation(isAfterViolation);
195
196
  if (!postcondition) return undefined;
196
197
  if (postcondition.counts !== undefined) (options.onPrint ?? console.log)(postcondition.counts);
197
- reportMessage(
198
+ message(
198
199
  postcondition.code,
199
200
  postcondition.message,
200
201
  formatInnerMessage(postcondition.code, postcondition.message, true),
@@ -218,7 +219,7 @@ export const simulate = (options: SimulationOptions): number => {
218
219
  const assumptionStatus = reportAssumptionViolation(
219
220
  specification.assumptions,
220
221
  environment,
221
- reportMessage,
222
+ message,
222
223
  );
223
224
  if (assumptionStatus !== undefined) return assumptionStatus;
224
225
  const initAction = initActions[initActions.length - 1];
@@ -242,6 +243,8 @@ export const simulate = (options: SimulationOptions): number => {
242
243
  };
243
244
  const toRecord = (state: (Value | undefined)[]) =>
244
245
  search.toRecord(state.map((value) => value ?? createModelValue("null")));
246
+ // Simulator.printBehavior evaluates the alias of each state with its successor, the last state
247
+ // with itself.
245
248
  const toTraceSteps = (trace: TraceNode[]): TraceStep[] =>
246
249
  trace.map((node, index) => ({
247
250
  action: node.action.name,
@@ -270,7 +273,7 @@ export const simulate = (options: SimulationOptions): number => {
270
273
  const reportInitialException = (error: unknown, state: Value[] | undefined) => {
271
274
  const failure = toEvaluationError(error);
272
275
  if (!state) {
273
- reportMessage(
276
+ message(
274
277
  MESSAGE_CODE.general,
275
278
  `${getUnexpectedPrefix(failure)}${failure.message}`,
276
279
  `${getUnexpectedPrefix(failure)}${formatNestedMessage(failure.message, true)}`,
@@ -280,7 +283,7 @@ export const simulate = (options: SimulationOptions): number => {
280
283
  }
281
284
  const text = getFailureMessage(failure, false);
282
285
  const initial = `While working on the initial state:\n${formatState(toRecord(state))}`;
283
- reportMessage(
286
+ message(
284
287
  MESSAGE_CODE.initialState,
285
288
  `${text.message}\n${initial}`,
286
289
  `${text.toolMessage}\n${initial}`,
@@ -300,7 +303,7 @@ export const simulate = (options: SimulationOptions): number => {
300
303
  return reportInitialException(error, undefined);
301
304
  }
302
305
  statistics.generatedStates = generated.length;
303
- reportMessage(
306
+ message(
304
307
  MESSAGE_CODE.computingInitProgress,
305
308
  `Computed ${generated.length} initial states...`,
306
309
  undefined,
@@ -308,7 +311,7 @@ export const simulate = (options: SimulationOptions): number => {
308
311
  );
309
312
  for (const state of generated) {
310
313
  if (!isComplete(state)) {
311
- reportMessage(
314
+ message(
312
315
  MESSAGE_CODE.initialStateIncomplete,
313
316
  `State is not completely specified by the initial predicate:\n${formatState(toRecord(state))}`,
314
317
  );
@@ -319,7 +322,7 @@ export const simulate = (options: SimulationOptions): number => {
319
322
  const violated = search.findViolatedInvariant(state);
320
323
  if (violated) {
321
324
  const alias = toTraceSteps([node])[0].state;
322
- reportMessage(
325
+ message(
323
326
  MESSAGE_CODE.invariantViolatedInitial,
324
327
  `Invariant ${violated.name} is violated by the initial state:\n${formatState(alias)}`,
325
328
  );
@@ -327,11 +330,12 @@ export const simulate = (options: SimulationOptions): number => {
327
330
  reportPostcondition(true);
328
331
  return EXIT_STATUS.safetyViolation;
329
332
  }
330
- // Deviation from TLC: its simulator checks no implied init, tla-ts checks them after invariants.
333
+ // Simulator#simulate checks no implied init, where tla-ts checks them as the model checker
334
+ // does, after the invariants.
331
335
  const predicate = search.findFailedInitialPredicate(state);
332
336
  if (predicate) {
333
337
  const alias = toTraceSteps([node])[0].state;
334
- reportMessage(
338
+ message(
335
339
  MESSAGE_CODE.propertyViolatedInitial,
336
340
  `Property ${predicate.name} is violated by the initial state:\n${formatState(alias)}`,
337
341
  );
@@ -348,20 +352,20 @@ export const simulate = (options: SimulationOptions): number => {
348
352
  }
349
353
  }
350
354
  if (generated.length === 0) {
351
- reportMessage(
355
+ message(
352
356
  MESSAGE_CODE.noInitialStates,
353
357
  "There is no state satisfying the initial state predicate.",
354
358
  );
355
359
  return EXIT_STATUS.error;
356
360
  }
357
361
  if (initialStates.length === 0) {
358
- reportMessage(
362
+ message(
359
363
  MESSAGE_CODE.noInitialStatesInModel,
360
364
  "There is no state satisfying the initial state predicate and the state-constraint(s).",
361
365
  );
362
366
  return EXIT_STATUS.error;
363
367
  }
364
- reportMessage(
368
+ message(
365
369
  MESSAGE_CODE.initGenerated1,
366
370
  `Finished computing initial states: ${initialStates.length} distinct state generated at ${formatTlcDate(new Date())}.`,
367
371
  undefined,
@@ -400,6 +404,8 @@ export const simulate = (options: SimulationOptions): number => {
400
404
  );
401
405
  const lasso = checker.findViolation();
402
406
  if (!lasso) return undefined;
407
+ // StateTraceResolver recovers the states of the counterexample by their position in the
408
+ // behavior, so TLC prints as many states of the behavior as the counterexample has.
403
409
  const getLength = (path: number[]) =>
404
410
  path.filter((index, position) => position === 0 || index !== path[position - 1]).length;
405
411
  const path = [...lasso.prefix, ...lasso.cycle];
@@ -432,7 +438,7 @@ export const simulate = (options: SimulationOptions): number => {
432
438
  });
433
439
  const getSuccessors = (current: TraceNode, action: SpecAction) => {
434
440
  const successors: TraceNode[] = [];
435
- let failure: WorkerError | undefined;
441
+ const failure: { error: WorkerError | undefined } = { error: undefined };
436
442
  runtime.deferred = undefined;
437
443
  try {
438
444
  forEachSuccessor(
@@ -447,7 +453,7 @@ export const simulate = (options: SimulationOptions): number => {
447
453
  try {
448
454
  const violated = search.findViolatedInvariant(node.state, current.state);
449
455
  if (violated) {
450
- failure = toWorkerError(
456
+ failure.error = toWorkerError(
451
457
  MESSAGE_CODE.invariantViolatedBehavior,
452
458
  `Invariant ${violated.name} is violated.`,
453
459
  node,
@@ -456,7 +462,7 @@ export const simulate = (options: SimulationOptions): number => {
456
462
  }
457
463
  const property = search.findViolatedActionProperty(current.state, node.state);
458
464
  if (property) {
459
- failure = toWorkerError(
465
+ failure.error = toWorkerError(
460
466
  MESSAGE_CODE.actionPropertyViolatedBehavior,
461
467
  `Action property ${property.name} is violated.`,
462
468
  node,
@@ -466,7 +472,7 @@ export const simulate = (options: SimulationOptions): number => {
466
472
  } catch (error) {
467
473
  if (!(error instanceof TlaEvaluationError) || !isHeadedError(error)) throw error;
468
474
  const text = getFailureMessage(error, true);
469
- failure = {
475
+ failure.error = {
470
476
  ...toWorkerError(text.code, text.message, node),
471
477
  toolMessage: text.toolMessage,
472
478
  };
@@ -498,9 +504,9 @@ export const simulate = (options: SimulationOptions): number => {
498
504
  );
499
505
  return { successors, error: toWorkerError(MESSAGE_CODE.incompleteSuccessor, text, node) };
500
506
  }
501
- return { successors, error: failure };
507
+ return { successors, error: failure.error };
502
508
  };
503
- let currentNode = initialStates[0];
509
+ const current = { node: initialStates[0] };
504
510
  const qualities = nextActions.map(() => new Map<bigint | SpecAction, number>());
505
511
  const getQualityKey = (node: TraceNode) =>
506
512
  options.scheduler === "rlaction" ? node.action : runtime.getFingerprint(node.state);
@@ -519,11 +525,11 @@ export const simulate = (options: SimulationOptions): number => {
519
525
  const ranked = weights
520
526
  .map((weight, index) => ({ index, weight: weight / total }))
521
527
  .sort((left, right) => right.weight - left.weight);
522
- const threshold = workerRandom.nextDouble();
523
- let cumulativeWeight = 0;
528
+ const random = workerRandom.nextDouble();
529
+ const cumulative = { weight: 0 };
524
530
  const chosen = ranked.find((item, position) => {
525
- cumulativeWeight = position === 0 ? item.weight : cumulativeWeight + item.weight;
526
- return cumulativeWeight >= threshold;
531
+ cumulative.weight = position === 0 ? item.weight : cumulative.weight + item.weight;
532
+ return cumulative.weight >= random;
527
533
  });
528
534
  return (chosen ?? ranked[ranked.length - 1]).index;
529
535
  };
@@ -550,43 +556,44 @@ export const simulate = (options: SimulationOptions): number => {
550
556
  }
551
557
  };
552
558
  const simulateTrace = (): WorkerError | "stopped" | undefined => {
553
- currentNode = initialStates[Math.floor(workerRandom.nextDouble() * initialStates.length)];
559
+ current.node = initialStates[Math.floor(workerRandom.nextDouble() * initialStates.length)];
554
560
  for (let depth = 0; depth < traceDepth; depth++) {
555
561
  if (runtime.isStopped) return "stopped";
556
- let actionIndex = getNextActionIndex(currentNode);
562
+ const choice = { index: getNextActionIndex(current.node) };
557
563
  const prime = nextPrime(workerRandom);
558
- let successors: TraceNode[] = [];
564
+ const found: { successors: TraceNode[] } = { successors: [] };
559
565
  for (let attempt = 0; attempt < nextActions.length; attempt++) {
560
- const result = getSuccessors(currentNode, nextActions[actionIndex]);
566
+ const result = getSuccessors(current.node, nextActions[choice.index]);
561
567
  if (result.error) return result.error;
562
- successors = result.successors;
563
- if (successors.length > 0) break;
564
- markDisabled(actionIndex, currentNode);
565
- actionIndex = (actionIndex + prime) % nextActions.length;
568
+ found.successors = result.successors;
569
+ if (found.successors.length > 0) break;
570
+ markDisabled(choice.index, current.node);
571
+ choice.index = (choice.index + prime) % nextActions.length;
566
572
  }
567
- if (successors.length === 0) {
573
+ if (found.successors.length === 0) {
568
574
  if (config.checkDeadlock) {
569
- return toWorkerError(MESSAGE_CODE.deadlockReached, "Deadlock reached.", currentNode);
575
+ return toWorkerError(MESSAGE_CODE.deadlockReached, "Deadlock reached.", current.node);
570
576
  }
571
577
  break;
572
578
  }
573
- currentNode = successors[Math.floor(workerRandom.nextDouble() * successors.length)];
574
- currentNode.deferred?.(currentNode.state);
579
+ current.node =
580
+ found.successors[Math.floor(workerRandom.nextDouble() * found.successors.length)];
581
+ current.node.deferred?.(current.node.state);
575
582
  }
576
583
  if (runtime.isStopped) return "stopped";
577
- const violation = findTemporalViolation(currentNode);
584
+ const violation = findTemporalViolation(current.node);
578
585
  if (violation) {
579
586
  return {
580
- ...toWorkerError(MESSAGE_CODE.temporalPropertyViolated, "", currentNode),
587
+ ...toWorkerError(MESSAGE_CODE.temporalPropertyViolated, "", current.node),
581
588
  isException: true,
582
589
  violation,
583
590
  };
584
591
  }
585
- const length = Math.min(traceDepth, currentNode.level);
592
+ const length = Math.min(traceDepth, current.node.level);
586
593
  const delta = length - statistics.levelMean;
587
594
  statistics.levelMean += Math.trunc(delta / Math.max(statistics.traces, 1));
588
595
  statistics.levelM2 += delta * (length - statistics.levelMean);
589
- if (options.scheduler === "rl") learnTrace(currentNode);
596
+ if (options.scheduler === "rl") learnTrace(current.node);
590
597
  return undefined;
591
598
  };
592
599
  const toException = (error: unknown, node: TraceNode): WorkerError => {
@@ -620,20 +627,21 @@ export const simulate = (options: SimulationOptions): number => {
620
627
  const traceLimit = options.traceCount ?? (1n << 63n) - 1n;
621
628
  while (true) {
622
629
  statistics.traces++;
623
- currentTrace = statistics.traces;
630
+ worker.currentTrace = statistics.traces;
624
631
  const outcome = (() => {
625
632
  try {
626
633
  return simulateTrace();
627
634
  } catch (error) {
628
- return toException(error, currentNode);
635
+ return toException(error, current.node);
629
636
  }
630
637
  })();
631
638
  if (outcome === "stopped") break;
632
- traceCount++;
639
+ worker.traceCount++;
633
640
  if (outcome) errors.push(outcome);
634
641
  if (outcome?.isException) break;
635
- if (BigInt(traceCount) >= traceLimit) break;
636
- // TLC's worker starts one more behavior before the Simulator stops it, unless traces are bounded.
642
+ if (BigInt(worker.traceCount) >= traceLimit) break;
643
+ // The worker runs on through its behaviors while the Simulator prints an error that stops it.
644
+ // Without a bound on them, it starts the next before the Simulator stops it.
637
645
  const isStopping = outcome !== undefined && (!isContinued || FATAL_CODES.has(outcome.code));
638
646
  if (isStopping && options.traceCount === undefined) {
639
647
  statistics.traces++;
@@ -654,10 +662,11 @@ export const simulate = (options: SimulationOptions): number => {
654
662
  printSummary();
655
663
  return;
656
664
  }
657
- reportMessage(error.code, error.message, error.toolMessage);
665
+ message(error.code, error.message, error.toolMessage);
666
+ const nodes = getTrace(error.node);
658
667
  output({
659
668
  kind: "behavior",
660
- trace: toTraceSteps(getTrace(error.node)),
669
+ trace: toTraceSteps(nodes),
661
670
  isLastStateOnly: traceDepth === INFINITE_DEPTH,
662
671
  });
663
672
  if (error.isSummarized) printSummary();