tla-ts 0.0.10-dev.b4a856304 → 0.0.10-dev.f16792fed

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