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/successors.ts CHANGED
@@ -7,7 +7,12 @@ import {
7
7
  } from "./ast";
8
8
  import { getKindString } from "./builtins";
9
9
  import { getReadVariables } from "./dependencies";
10
- import { TlaEvaluationError, TlaIllegalStateError, TlaIncompleteSuccessorError } from "./errors";
10
+ import {
11
+ TlaEvaluationError,
12
+ TlaIllegalStateError,
13
+ TlaIncompleteSuccessorError,
14
+ TlaUncodedError,
15
+ } from "./errors";
11
16
  import { EXIT_STATUS, setExitCode } from "./exit-codes";
12
17
  import {
13
18
  describeLocation,
@@ -16,10 +21,10 @@ import {
16
21
  bindLazyArguments,
17
22
  bindDefinitions,
18
23
  bindOperatorArguments,
24
+ bindPattern,
19
25
  bindValue,
20
26
  compileArgumentScope,
21
27
  evaluate,
22
- expectBoolean,
23
28
  forEachBinding,
24
29
  getLazyFunction,
25
30
  toKeepLazyContext,
@@ -27,7 +32,9 @@ import {
27
32
  getContextElements,
28
33
  getEntryEvaluator,
29
34
  getReevaluatedDefinitions,
35
+ getStartupValue,
30
36
  lookupScope,
37
+ mapBoundSets,
31
38
  resolveApplyOperator,
32
39
  resolveGlobalOperator,
33
40
  toUnspecifiedSubscriptError,
@@ -38,13 +45,21 @@ import {
38
45
  type State,
39
46
  } from "./evaluate";
40
47
  import { mapChildren } from "./instances";
41
- import { isAssignedShortcut, LITERAL_KINDS, replayEnabled } from "./tlc/replay";
48
+ import { CORE_OPERATORS } from "./standard-modules";
49
+ import { getRandomSubset, nextPrime, type JavaRandom } from "./tlc/random";
50
+ import {
51
+ getEnabledFailure,
52
+ isAssignedShortcut,
53
+ LITERAL_KINDS,
54
+ replayEnabled,
55
+ warnChangedUnchanged,
56
+ } from "./tlc/replay";
42
57
  import {
43
58
  formatValue,
44
59
  getStreamedElements,
60
+ isEqualLikeTlc,
45
61
  isFunctionValue,
46
62
  isTlcEnumerable,
47
- valuesEqual,
48
63
  type Value,
49
64
  } from "./values";
50
65
 
@@ -56,10 +71,12 @@ export interface Successor {
56
71
  interface Run {
57
72
  environment: Environment;
58
73
  isInit: boolean;
59
- // Whether the run computes ENABLED rather than the successors of the state.
60
74
  isEnabled: boolean;
61
75
  current: Value[] | undefined;
62
76
  isStopped: boolean;
77
+ generator: JavaRandom | undefined;
78
+ successors: number;
79
+ onUnsatisfied?: (state: Value[], conjunct: Expression) => void;
63
80
  }
64
81
 
65
82
  type Continuation = (partial: State, action: string | undefined) => void;
@@ -76,7 +93,7 @@ type Runner = (
76
93
  type Conjunct = { expression: Expression } & (
77
94
  | { kind: "Guard" }
78
95
  | { kind: "Assign"; index: number; value: Expression }
79
- | { kind: "Unchanged"; indices: number[] }
96
+ | { kind: "Unchanged"; variables: UnchangedVariable[] }
80
97
  | { kind: "Branch"; runner: Runner }
81
98
  );
82
99
 
@@ -94,7 +111,6 @@ const assign = (partial: State, index: number, value: Value) => {
94
111
  return copy;
95
112
  };
96
113
 
97
- // What TLC says it was computing when it fails.
98
114
  const getComputation = (run: Run) =>
99
115
  run.isInit ? "initial states" : run.isEnabled ? "ENABLED" : "next states";
100
116
 
@@ -104,8 +120,7 @@ const createRunError = (run: Run, message: string) => {
104
120
  return run.isInit ? error : setExitCode(error, EXIT_STATUS.error);
105
121
  };
106
122
 
107
- // TLC's message for a conjunct that isn't a boolean, which differs for a literal it walks to rather
108
- // than evaluates.
123
+ // TLC words this differently for a literal it walks to rather than evaluates.
109
124
  const getNonBooleanMessage = (
110
125
  run: Run,
111
126
  value: Value,
@@ -134,9 +149,20 @@ const getIfConditionMessage = (run: Run, value: Value, expression: Expression) =
134
149
  const holds = (run: Run, expression: Expression, context: Context) =>
135
150
  holdsValue(run, expression, evaluate(expression, context));
136
151
 
152
+ const CORE_OPERATOR_NAMES = new Set(CORE_OPERATORS.map((operator) => operator.name));
153
+
154
+ // TLC's initial states evaluate a built-in operator for its value, and report it in a plain message.
155
+ const isBuiltInOperation = (expression: Expression) =>
156
+ expression.kind === "Apply"
157
+ ? CORE_OPERATOR_NAMES.has(expression.operator)
158
+ : expression.kind !== "Identifier" && !LITERAL_KINDS.has(expression.kind);
159
+
137
160
  const holdsValue = (run: Run, expression: Expression, value: Value, isWalked = true) => {
138
161
  if (typeof value === "boolean") return value;
139
- throw createRunError(run, getNonBooleanMessage(run, value, expression, isWalked));
162
+ const message = getNonBooleanMessage(run, value, expression, isWalked);
163
+ throw run.isInit && isWalked && isBuiltInOperation(expression)
164
+ ? new TlaUncodedError(message)
165
+ : createRunError(run, message);
140
166
  };
141
167
 
142
168
  const evaluateCached = (
@@ -156,7 +182,12 @@ const getRunner = (expression: Expression, environment: Environment, isInit: boo
156
182
  const runners = isInit ? initRunners : nextRunners;
157
183
  const cached = runners.get(expression);
158
184
  if (cached) return cached;
159
- const runner = compileAction(expression, environment, isInit);
185
+ const deterministic = compileAction(expression, environment, isInit);
186
+ const random = isInit ? undefined : compileRandomAction(expression, environment);
187
+ const runner: Runner = random
188
+ ? (run, scope, partial, action, isFixed, onComplete) =>
189
+ (run.generator ? random : deterministic)(run, scope, partial, action, isFixed, onComplete)
190
+ : deterministic;
160
191
  runners.set(expression, runner);
161
192
  return runner;
162
193
  };
@@ -204,7 +235,7 @@ const getRuntimeVariableIndex = (
204
235
  }
205
236
  if (expression.kind !== "Identifier") return undefined;
206
237
  const binding = lookupScope(scope, expression.name);
207
- if (binding?.kind === "Thunk") {
238
+ if (binding?.kind === "Thunk" && !binding.isReleased) {
208
239
  return getRuntimeVariableIndex(binding.expression, binding.scope, partial, run, isPrimed);
209
240
  }
210
241
  if (binding) return undefined;
@@ -220,24 +251,29 @@ const isPossiblyAssignable = (target: Expression, isInit: boolean) =>
220
251
  (target.kind === "Identifier" && (isInit || isLocallyResolved(target))) ||
221
252
  (!isInit && target.kind === "Prime");
222
253
 
223
- const getUnchangedIndices = (
254
+ interface UnchangedVariable {
255
+ index: number;
256
+ expression: Expression;
257
+ }
258
+
259
+ const getUnchangedVariables = (
224
260
  expression: Expression,
225
261
  environment: Environment,
226
262
  visited = new Set<string>(),
227
- ): number[] | undefined => {
263
+ ): UnchangedVariable[] | undefined => {
228
264
  if (expression.kind === "Tuple") {
229
- const indices = expression.elements.map((element) =>
230
- getUnchangedIndices(element, environment, visited),
265
+ const variables = expression.elements.map((element) =>
266
+ getUnchangedVariables(element, environment, visited),
231
267
  );
232
- return indices.every((item) => item !== undefined) ? indices.flat() : undefined;
268
+ return variables.every((item) => item !== undefined) ? variables.flat() : undefined;
233
269
  }
234
270
  if (expression.kind !== "Identifier" || visited.has(expression.name)) return undefined;
235
271
  const index = environment.variableIndex.get(expression.name);
236
- if (index !== undefined) return [index];
272
+ if (index !== undefined) return [{ index, expression }];
237
273
  const definition = getZeroArityBody(expression.name, environment);
238
274
  if (!definition) return undefined;
239
275
  visited.add(expression.name);
240
- return getUnchangedIndices(definition.body, environment, visited);
276
+ return getUnchangedVariables(definition.body, environment, visited);
241
277
  };
242
278
 
243
279
  const ACTION_KINDS = new Set([
@@ -277,8 +313,7 @@ const isGuard = (expression: Expression, environment: Environment, isInit: boole
277
313
 
278
314
  const NO_NAMES: ReadonlySet<string> = new Set();
279
315
 
280
- // The local names an expression reads from enclosing scopes, or undefined when it applies a local
281
- // operator, whose body may assign variables.
316
+ // Undefined when the expression applies a local operator, whose body may assign variables.
282
317
  export const getReadLocals = (
283
318
  expression: Expression,
284
319
  bound: ReadonlySet<string>,
@@ -300,8 +335,7 @@ export const getReadLocals = (
300
335
  return result.isReadOnly ? names : undefined;
301
336
  };
302
337
 
303
- // TLC generates a successor for every disjunct and witness that holds, so an expression only
304
- // checks like a guard when it has neither.
338
+ // TLC generates a successor per disjunct and witness, so only an expression without any is a guard.
305
339
  const hasBranches = (
306
340
  expression: Expression,
307
341
  environment: Environment,
@@ -337,15 +371,14 @@ const toConjunct = (
337
371
  }
338
372
  }
339
373
  if (!isInit && expression.kind === "Unchanged") {
340
- const indices = getUnchangedIndices(expression.expression, environment);
341
- if (indices) return { kind: "Unchanged", expression, indices };
374
+ const variables = getUnchangedVariables(expression.expression, environment);
375
+ if (variables) return { kind: "Unchanged", expression, variables };
342
376
  }
343
377
  if (isGuard(expression, environment, isInit)) return { kind: "Guard", expression };
344
378
  return { kind: "Branch", expression, runner: getRunner(expression, environment, isInit) };
345
379
  };
346
380
 
347
- // The leading guards of `\E x \in S, y \in T : P /\ Q` that read no inner bound hold for every inner
348
- // binding alike, so they can run once for each element of the outermost bound.
381
+ // Leading guards that read no inner bound hold for every inner binding, so they run once.
349
382
  const getHoistedGuards = (expression: QuantifierExpression, environment: Environment) => {
350
383
  if (expression.bounds.length < 2 || expression.body.kind !== "And") return undefined;
351
384
  const names = expression.bounds.flatMap((bound) =>
@@ -388,9 +421,27 @@ const compileConjunction = (
388
421
  if (index > 0 && isShortcut && isComplete(current)) {
389
422
  context ??= getContext(run, scope, current);
390
423
  for (let rest = index; rest < conjuncts.length; rest++) {
391
- const expression = conjuncts[rest].expression;
424
+ const conjunct = conjuncts[rest];
425
+ // Tool#getNextStates0 takes this shortcut with warnings on, though its comment says the
426
+ // shortcut skips the warning for a changed UNCHANGED variable. tla-ts still warns.
427
+ const state = run.current;
428
+ const changed =
429
+ state && conjunct.kind === "Unchanged"
430
+ ? conjunct.variables.find((variable) => {
431
+ const assigned = current[variable.index];
432
+ return assigned !== undefined && !isEqualLikeTlc(assigned, state[variable.index]);
433
+ })
434
+ : undefined;
435
+ if (changed) {
436
+ warnChangedUnchanged(run.environment, changed.index, changed.expression);
437
+ return;
438
+ }
439
+ const expression = conjunct.expression;
392
440
  const value = evaluateCached(restEvaluators, rest, expression, context);
393
- if (!holdsValue(run, expression, value, false)) return;
441
+ if (!holdsValue(run, expression, value, false)) {
442
+ run.onUnsatisfied?.(current, expression);
443
+ return;
444
+ }
394
445
  }
395
446
  onComplete(current, action);
396
447
  return;
@@ -409,7 +460,7 @@ const compileConjunction = (
409
460
  if (assigned === undefined) {
410
461
  current = assign(current, conjunct.index, value);
411
462
  context = undefined;
412
- } else if (!valuesEqual(assigned, value)) {
463
+ } else if (!isEqualLikeTlc(assigned, value)) {
413
464
  return;
414
465
  }
415
466
  continue;
@@ -418,12 +469,13 @@ const compileConjunction = (
418
469
  const state = run.current;
419
470
  if (!state) return;
420
471
  let unchanged: State | undefined;
421
- for (const variable of conjunct.indices) {
422
- const assigned = (unchanged ?? current)[variable];
472
+ for (const variable of conjunct.variables) {
473
+ const assigned = (unchanged ?? current)[variable.index];
423
474
  if (assigned === undefined) {
424
475
  unchanged ??= current.slice();
425
- unchanged[variable] = state[variable];
426
- } else if (!valuesEqual(assigned, state[variable])) {
476
+ unchanged[variable.index] = state[variable.index];
477
+ } else if (!isEqualLikeTlc(assigned, state[variable.index])) {
478
+ warnChangedUnchanged(run.environment, variable.index, variable.expression);
427
479
  return;
428
480
  }
429
481
  }
@@ -445,11 +497,13 @@ const compileConjunction = (
445
497
  runFrom(0, run, scope, partial, action, onComplete);
446
498
  };
447
499
 
448
- const compileGuard =
449
- (expression: Expression): Runner =>
450
- (run, scope, partial, action, _isFixed, onComplete) => {
500
+ const compileGuard = (expression: Expression): Runner => {
501
+ const enabledFailure = getEnabledFailure(expression);
502
+ return (run, scope, partial, action, _isFixed, onComplete) => {
503
+ if (run.isEnabled && enabledFailure !== undefined) throw createRunError(run, enabledFailure);
451
504
  if (holds(run, expression, getContext(run, scope, partial))) onComplete(partial, action);
452
505
  };
506
+ };
453
507
 
454
508
  const compileMembership = (
455
509
  expression: Expression & { kind: "Apply" },
@@ -473,6 +527,17 @@ const compileMembership = (
473
527
  throw createRunError(run, `${message}\n${describeRange(expression)}`);
474
528
  }
475
529
  const elements = getStreamedElements(value);
530
+ if (run.generator) {
531
+ for (const element of getRandomSubset(
532
+ elements.length,
533
+ value,
534
+ run.environment.runtime.getRandom(),
535
+ run.environment.runtime.version,
536
+ )) {
537
+ onComplete(assign(partial, index, element), action);
538
+ if (run.successors > 0 || run.isStopped) return;
539
+ }
540
+ }
476
541
  for (let position = 0; position < elements.length && !run.isStopped; position++) {
477
542
  onComplete(assign(partial, index, elements[position]), action);
478
543
  }
@@ -520,8 +585,8 @@ const compileDynamicAssignment = (
520
585
  };
521
586
  };
522
587
 
523
- // Tool.getInitStates and Tool.getNextStates walk the body of a function they apply that is still
524
- // lazy, which they evaluate as TLC computes the initial states eagerly, and otherwise apply it.
588
+ // TLC walks the body of an applied function that is still lazy, which it evaluates as it
589
+ // computes the initial states eagerly, and otherwise applies it.
525
590
  const compileFunctionAction = (
526
591
  expression: Expression & { kind: "FunctionApplication" },
527
592
  environment: Environment,
@@ -561,15 +626,15 @@ const compileFunctionAction = (
561
626
  };
562
627
 
563
628
  const compileUnchanged = (expression: Expression, environment: Environment): Runner => {
564
- const indices = getUnchangedIndices(expression, environment);
565
- if (indices) return compileConjunction([getUnchangedWrapper(expression)], environment, false);
629
+ if (getUnchangedVariables(expression, environment))
630
+ return compileConjunction([getUnchangedWrapper(expression)], environment, false);
566
631
  if (expression.kind === "Tuple")
567
632
  return getRunner(getUnchangedWrapper(expression), environment, false);
568
633
  const unchanged = getUnchangedWrapper(expression);
569
634
  return (run, scope, partial, action, isFixed, onComplete) => {
570
635
  const binding =
571
636
  expression.kind === "Identifier" ? lookupScope(scope, expression.name) : undefined;
572
- if (binding?.kind === "Thunk") {
637
+ if (binding?.kind === "Thunk" && !binding.isReleased) {
573
638
  getRunner(getUnchangedWrapper(binding.expression), environment, false)(
574
639
  run,
575
640
  binding.scope,
@@ -580,7 +645,23 @@ const compileUnchanged = (expression: Expression, environment: Environment): Run
580
645
  );
581
646
  return;
582
647
  }
583
- if (holds(run, unchanged, getContext(run, scope, partial))) onComplete(partial, action);
648
+ const context = getContext(run, scope, partial);
649
+ // Tool#enabledUnchanged fails on an operator application, as its comment says.
650
+ if (run.isEnabled && expression.kind === "Apply") {
651
+ const operator = resolveApplyOperator(expression, context);
652
+ if (operator?.kind === "Closure" && operator.params.length === expression.args.length) {
653
+ getRunner(getUnchangedWrapper(operator.body), environment, false)(
654
+ run,
655
+ bindOperatorArguments(operator, expression.args, context),
656
+ partial,
657
+ action,
658
+ isFixed,
659
+ onComplete,
660
+ );
661
+ return;
662
+ }
663
+ }
664
+ if (holds(run, unchanged, context)) onComplete(partial, action);
584
665
  };
585
666
  };
586
667
 
@@ -640,7 +721,7 @@ const compileIdentifier = (
640
721
  const compiled = { body: undefined as Runner | undefined };
641
722
  return (run, scope, partial, action, isFixed, onComplete) => {
642
723
  const binding = lookupScope(scope, expression.name);
643
- if (binding?.kind === "Thunk") {
724
+ if (binding?.kind === "Thunk" && !binding.isReleased) {
644
725
  getRunner(binding.expression, environment, isInit)(
645
726
  run,
646
727
  binding.scope,
@@ -651,7 +732,13 @@ const compileIdentifier = (
651
732
  );
652
733
  return;
653
734
  }
654
- if (binding || !definition) {
735
+ // TLC computed a constant definition at startup, so it looks up its value. It walks the body
736
+ // of the configured INIT or NEXT, which isn't a reference in the source and has no range.
737
+ if (
738
+ binding ||
739
+ !definition ||
740
+ (expression.location.range && getStartupValue(definition, environment) !== undefined)
741
+ ) {
655
742
  guard(run, scope, partial, action, isFixed, onComplete);
656
743
  return;
657
744
  }
@@ -660,11 +747,9 @@ const compileIdentifier = (
660
747
  };
661
748
  };
662
749
 
663
- // A PlusCal action starts with a guard such as pc[self] = "L1", and a process is a disjunction of
664
- // its actions. The labels an expression requires of one variable at one bound name let a
665
- // disjunction skip the operands whose guard is false without evaluating them. A hand-written
666
- // action often puts other guards first, such as running = self /\ pc[self] = "L1". TLC evaluates
667
- // those before the label's guard, so a skipped operand still runs them, for their errors.
750
+ // A disjunction of PlusCal actions skips the operands whose label guard, such as
751
+ // pc[self] = "L1", is false. TLC evaluates guards before the label's guard, so a skipped
752
+ // operand still runs them, for their errors.
668
753
  interface LabelGuard {
669
754
  variable: number;
670
755
  argument: string;
@@ -689,16 +774,13 @@ const toLabelGuard = (expression: Expression, environment: Environment) => {
689
774
  const getConjuncts = (expression: Expression): Expression[] =>
690
775
  expression.kind === "And" ? expression.operands.flatMap(getConjuncts) : [expression];
691
776
 
692
- // What may come before the label's guard: a comparison or a name that a conjunction checks as a
693
- // guard. An operand with another conjunct first, such as an assignment or a name defined as an
694
- // action that may branch, runs in full.
777
+ // An operand with another conjunct first, such as an assignment, runs in full.
695
778
  const isLeadingGuard = (expression: Expression, environment: Environment) =>
696
779
  (expression.kind === "Identifier" ||
697
780
  (expression.kind === "Apply" &&
698
781
  (expression.operator === "=" || expression.operator === "#"))) &&
699
782
  isGuard(expression, environment, false);
700
783
 
701
- // Checks the guards before a label's guard as a conjunction does, for TLC's errors.
702
784
  const compileLeadingGuards = (guards: Expression[]) => {
703
785
  const evaluators: (Evaluator | undefined)[] = [];
704
786
  return (run: Run, scope: Scope | undefined, partial: State) => {
@@ -813,6 +895,66 @@ const compileDisjunction = (
813
895
  };
814
896
  };
815
897
 
898
+ const compileRandomChoice =
899
+ (choices: Runner[]): Runner =>
900
+ (run, scope, partial, action, isFixed, onComplete) => {
901
+ const generator = run.generator;
902
+ if (!generator) throw new Error("A random choice needs the run's generator");
903
+ const start = Math.floor(generator.nextDouble() * choices.length);
904
+ const prime = nextPrime(generator);
905
+ for (let attempt = 0; attempt < choices.length; attempt++) {
906
+ choices[(start + attempt * prime) % choices.length](
907
+ run,
908
+ scope,
909
+ partial,
910
+ action,
911
+ isFixed,
912
+ onComplete,
913
+ );
914
+ if (run.successors > 0 || run.isStopped) return;
915
+ }
916
+ };
917
+
918
+ const compileRandomExists = (
919
+ expression: QuantifierExpression,
920
+ environment: Environment,
921
+ ): Runner => {
922
+ const body = getRunner(expression.body, environment, false);
923
+ return (run, scope, partial, action, isFixed, onComplete) => {
924
+ const context = getContext(run, scope, partial);
925
+ const version = environment.runtime.version;
926
+ const orders = mapBoundSets(expression.bounds, (set) => evaluate(set, context)).map(
927
+ (set, index) =>
928
+ getRandomSubset(
929
+ getContextElements(set, expression.bounds[index].set, version).length,
930
+ set,
931
+ environment.runtime.getRandom(),
932
+ version,
933
+ ),
934
+ );
935
+ const visit = (position: number, boundScope: Scope | undefined): boolean => {
936
+ if (position < 0) {
937
+ body(run, boundScope, partial, action, isFixed, onComplete);
938
+ return run.successors > 0 || run.isStopped;
939
+ }
940
+ const pattern = expression.bounds[position].pattern;
941
+ return orders[position].some((element) =>
942
+ visit(position - 1, bindPattern(boundScope, pattern, element)),
943
+ );
944
+ };
945
+ visit(orders.length - 1, scope);
946
+ };
947
+ };
948
+
949
+ const compileRandomAction = (expression: Expression, environment: Environment) => {
950
+ if (expression.kind === "Exists") return compileRandomExists(expression, environment);
951
+ if (expression.kind !== "Or") return undefined;
952
+ const runners = expression.operands.map((operand) => getRunner(operand, environment, false));
953
+ return expression.isBulleted
954
+ ? compileRandomChoice(runners)
955
+ : runners.reduce((left, right) => compileRandomChoice([left, right]));
956
+ };
957
+
816
958
  const compileAction = (
817
959
  expression: Expression,
818
960
  environment: Environment,
@@ -852,12 +994,8 @@ const compileAction = (
852
994
  const rest = compileConjunction(hoisted.rest, environment, isInit);
853
995
  return (run, scope, partial, action, isFixed, onComplete) => {
854
996
  const context = getContext(run, scope, partial);
855
- const sets = expression.bounds.map((innerBound) =>
856
- getContextElements(
857
- evaluate(innerBound.set, context),
858
- innerBound.set,
859
- environment.runtime.version,
860
- ),
997
+ const sets = mapBoundSets(expression.bounds, (set) =>
998
+ getContextElements(evaluate(set, context), set, environment.runtime.version),
861
999
  );
862
1000
  if (sets.some((elements) => elements.length === 0)) return;
863
1001
  const visit = (index: number, boundScope: Scope | undefined): void => {
@@ -995,7 +1133,12 @@ const compileAction = (
995
1133
  return compileUnchanged(expression.expression, environment);
996
1134
  case "AngleAction": {
997
1135
  const body = getChildRunner(expression.action);
998
- const unchanged = getUnchangedWrapper(expression.subscript);
1136
+ // TLC compares the whole subscript of <<A>>_v, unlike UNCHANGED's, which it splits.
1137
+ const unchanged: Expression = {
1138
+ kind: "Unchanged",
1139
+ expression: expression.subscript,
1140
+ location: expression.subscript.location,
1141
+ };
999
1142
  const isUnchanged = (run: Run, scope: Scope | undefined, nextPartial: State) => {
1000
1143
  try {
1001
1144
  return holds(run, unchanged, getContext(run, scope, nextPartial));
@@ -1011,11 +1154,11 @@ const compileAction = (
1011
1154
  });
1012
1155
  }
1013
1156
  case "BoxAction":
1014
- return getChildRunner({
1015
- kind: "Or",
1016
- operands: [expression.action, getUnchangedWrapper(expression.subscript)],
1017
- location: expression.location,
1018
- });
1157
+ return compileDisjunction(
1158
+ [expression.action, getUnchangedWrapper(expression.subscript)],
1159
+ environment,
1160
+ isInit,
1161
+ );
1019
1162
  case "Label":
1020
1163
  return getChildRunner(expression.body);
1021
1164
  case "Identifier":
@@ -1038,11 +1181,19 @@ const compileAction = (
1038
1181
  const right = getChildRunner(args[1]);
1039
1182
  return (run, scope, partial, action, isFixed, onComplete) => {
1040
1183
  const condition = evaluate(args[0], getContext(run, scope, partial));
1041
- const isTrue =
1042
- typeof condition === "boolean"
1043
- ? condition
1044
- : expectBoolean(condition, `the left side of => at ${describeLocation(args[0])}`);
1045
- if (!isTrue) {
1184
+ if (typeof condition !== "boolean") {
1185
+ const kind = getKindString(condition);
1186
+ const range = describeRange(expression);
1187
+ throw createRunError(
1188
+ run,
1189
+ run.isInit
1190
+ ? `In computing initial states of a predicate of form P => Q, P was ${kind}\n.${range}`
1191
+ : run.isEnabled
1192
+ ? `While computing ENABLED of an expression of the form P => Q, P was ${kind}.\n${range}`
1193
+ : `In computing next states of a predicate of the form P => Q, P was\n${kind}.\n${range}`,
1194
+ );
1195
+ }
1196
+ if (!condition) {
1046
1197
  onComplete(partial, action);
1047
1198
  return;
1048
1199
  }
@@ -1056,7 +1207,6 @@ const compileAction = (
1056
1207
  }
1057
1208
  };
1058
1209
 
1059
- // A partial state that assigns no variable, which a run fills in as it assigns them.
1060
1210
  const getEmptyState = (environment: Environment): State =>
1061
1211
  environment.variables.map((): Value | undefined => undefined);
1062
1212
 
@@ -1083,6 +1233,8 @@ export const isEnabled = (expression: Expression, context: Context): boolean =>
1083
1233
  isEnabled: true,
1084
1234
  current: state,
1085
1235
  isStopped: false,
1236
+ generator: undefined,
1237
+ successors: 0,
1086
1238
  };
1087
1239
  // TLC stops computing ENABLED at the first successor, so it skips the rest of the action.
1088
1240
  getRunner(expression, environment, false)(
@@ -1103,6 +1255,7 @@ export const forEachInitialState = (
1103
1255
  environment: Environment,
1104
1256
  onState: (state: Value[]) => boolean,
1105
1257
  scope?: Scope,
1258
+ onIncomplete?: (state: State) => boolean,
1106
1259
  ) => {
1107
1260
  const run: Run = {
1108
1261
  environment,
@@ -1110,6 +1263,8 @@ export const forEachInitialState = (
1110
1263
  isEnabled: false,
1111
1264
  current: undefined,
1112
1265
  isStopped: false,
1266
+ generator: undefined,
1267
+ successors: 0,
1113
1268
  };
1114
1269
  getRunner(expression, environment, true)(
1115
1270
  run,
@@ -1120,8 +1275,11 @@ export const forEachInitialState = (
1120
1275
  (partial) => {
1121
1276
  if (run.isStopped) return;
1122
1277
  if (!isComplete(partial)) {
1123
- // TLC reports an initial state that isn't completely specified as an illegal state, not as
1124
- // an evaluation failure.
1278
+ if (onIncomplete) {
1279
+ run.isStopped = onIncomplete([...partial]);
1280
+ return;
1281
+ }
1282
+ // TLC reports an initial state that isn't completely specified as an illegal state.
1125
1283
  throw setExitCode(new TlaIllegalStateError([...partial]), EXIT_STATUS.error);
1126
1284
  }
1127
1285
  run.isStopped = onState(partial);
@@ -1153,6 +1311,8 @@ export const forEachSuccessor = (
1153
1311
  environment: Environment,
1154
1312
  onSuccessor: (successor: Successor) => boolean,
1155
1313
  scope?: Scope,
1314
+ generator?: JavaRandom,
1315
+ onUnsatisfied?: Run["onUnsatisfied"],
1156
1316
  ) => {
1157
1317
  const run: Run = {
1158
1318
  environment,
@@ -1160,8 +1320,10 @@ export const forEachSuccessor = (
1160
1320
  isEnabled: false,
1161
1321
  current: state,
1162
1322
  isStopped: false,
1323
+ generator,
1324
+ successors: 0,
1325
+ onUnsatisfied,
1163
1326
  };
1164
- const counter = { successors: 0 };
1165
1327
  getRunner(expression, environment, false)(
1166
1328
  run,
1167
1329
  scope,
@@ -1179,11 +1341,39 @@ export const forEachSuccessor = (
1179
1341
  missing,
1180
1342
  );
1181
1343
  }
1182
- counter.successors++;
1344
+ run.successors++;
1183
1345
  run.isStopped = onSuccessor({ state: partial, action });
1184
1346
  },
1185
1347
  );
1186
- return counter.successors;
1348
+ return run.successors;
1349
+ };
1350
+
1351
+ export const hasIncompleteSuccessor = (
1352
+ expression: Expression,
1353
+ state: Value[],
1354
+ environment: Environment,
1355
+ scope?: Scope,
1356
+ ) => {
1357
+ const run: Run = {
1358
+ environment,
1359
+ isInit: false,
1360
+ isEnabled: false,
1361
+ current: state,
1362
+ isStopped: false,
1363
+ generator: undefined,
1364
+ successors: 0,
1365
+ };
1366
+ getRunner(expression, environment, false)(
1367
+ run,
1368
+ scope,
1369
+ getEmptyState(environment),
1370
+ undefined,
1371
+ false,
1372
+ (partial) => {
1373
+ if (!isComplete(partial)) run.isStopped = true;
1374
+ },
1375
+ );
1376
+ return run.isStopped;
1187
1377
  };
1188
1378
 
1189
1379
  export const getSuccessors = (