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/evaluate.ts CHANGED
@@ -13,9 +13,15 @@ import {
13
13
  type SourceRange,
14
14
  } from "./ast";
15
15
  import { getKindString } from "./builtins";
16
- import { isStackOverflow, TlaEvaluationError, TlaUnassignedError } from "./errors";
16
+ import {
17
+ isStackOverflow,
18
+ TlaEvaluationError,
19
+ TlaSetBoundError,
20
+ TlaUnassignedError,
21
+ } from "./errors";
17
22
  import { EXIT_STATUS, setExitCode } from "./exit-codes";
18
23
  import { generateEvaluator } from "./codegen";
24
+ import { countCoverage, getCoverageNode, runAtCoverageNode, type Coverage } from "./coverage";
19
25
  import { MESSAGE_CODE } from "./tlc/messages";
20
26
  import type { CheckerRuntime } from "./runtime";
21
27
  import {
@@ -24,7 +30,7 @@ import {
24
30
  isNonconstant,
25
31
  type DefinitionFacts,
26
32
  } from "./dependencies";
27
- import { contextualApplications } from "./instances";
33
+ import { contextualApplications, substitutionFrames } from "./instances";
28
34
  import { prettyPrint } from "./pretty-print";
29
35
  import { isEnabled } from "./successors";
30
36
  import {
@@ -32,12 +38,15 @@ import {
32
38
  describeMissingArgument,
33
39
  compareValues,
34
40
  createFunction,
41
+ addBoundedElement,
35
42
  createNonIntegerKeyError,
43
+ forEachElement,
44
+ isBeyondSetBound,
36
45
  createRecord,
37
46
  createEnumeratedSet,
38
47
  createSortedFunction,
39
48
  createSortedRecord,
40
- createSortedSet,
49
+ createNormalizedSet,
41
50
  createWrittenRecord,
42
51
  createTuple,
43
52
  formatValue,
@@ -47,7 +56,9 @@ import {
47
56
  getIntervalElements,
48
57
  getLazySubsets,
49
58
  getStreamedElements,
59
+ normalizeShallowly,
50
60
  getFunctionClass,
61
+ getNormalizedSetElements,
51
62
  getSequenceElements,
52
63
  isElementOf,
53
64
  isEnumerable,
@@ -80,7 +91,6 @@ export interface OperatorValue {
80
91
  arity: number;
81
92
  call: (args: Value[]) => Value;
82
93
  expression?: Expression;
83
- literalBody?: Value;
84
94
  }
85
95
 
86
96
  export type BuiltinArgument = Value | OperatorValue;
@@ -95,6 +105,8 @@ export interface Builtin {
95
105
  isStateLevel?: boolean;
96
106
  // Whether TLC takes an application for a constant one although its value depends on the state.
97
107
  isLevelConstant?: boolean;
108
+ // TLC's minLevel of ActionLevel for a Java override.
109
+ isActionLevel?: boolean;
98
110
  isLazy?: boolean;
99
111
  }
100
112
 
@@ -115,12 +127,17 @@ export interface Thunk {
115
127
  state: State | undefined;
116
128
  next: State | undefined;
117
129
  cache: Value | undefined;
118
- // Whether the expression may build a set that streams until TLC caches it, so that the thunk
119
- // caches only a settled value.
130
+ // Whether the value may stream until TLC caches it, so the thunk caches only a settled value.
120
131
  isStreamed: boolean;
132
+ // Whether the thunk dropped its scope after caching a value that holds in every state.
133
+ isReleased?: boolean;
121
134
  }
122
135
 
123
- type Binding = { kind: "Value"; value: Value } | Thunk | { kind: "Operator"; operator: Operator };
136
+ type Binding =
137
+ // A literal argument keeps its expression, which TLC binds lazily like any other.
138
+ | { kind: "Value"; value: Value; argument?: Expression }
139
+ | Thunk
140
+ | { kind: "Operator"; operator: Operator };
124
141
 
125
142
  export interface Scope {
126
143
  name: string;
@@ -134,55 +151,44 @@ export interface Environment {
134
151
  builtins: Map<string, Builtin>;
135
152
  constants: Map<string, Value>;
136
153
  substitutions: Map<string, string>;
137
- // The name SANY gives each definition that a named instance such as `M == INSTANCE Module`
138
- // copies, such as M!Op, by the key of the copy.
139
154
  instanceNames: Map<string, string>;
140
155
  variables: string[];
141
156
  variableIndex: Map<string, number>;
142
157
  facts: DefinitionFacts;
143
- // The value of each constant definition TLC computed when it started, by the definition's id in
144
- // facts. TLC evaluates a definition it failed to compute where the spec uses it.
158
+ // TLC evaluates a constant definition it failed to compute at startup where the spec uses it.
145
159
  startupValues: (Value | undefined)[];
146
- // The definitions an INSTANCE copies from a module that declares constants or variables. SANY
147
- // wraps the body of each in its substitutions.
160
+ // SANY wraps the body of each of these INSTANCE copies in its substitutions.
148
161
  substitutedDefinitions: Set<Definition>;
149
- // The compiled code of each expression, of each expression evaluated as a whole, which generated
150
- // code can serve, and of each reference to a definition.
162
+ instanceParams: Set<OperatorParam>;
151
163
  evaluators: WeakMap<Expression, Evaluator>;
152
164
  entryEvaluators: WeakMap<Expression, Evaluator>;
153
165
  definitionEvaluators: WeakMap<Definition, Evaluator>;
154
- // The expressions being evaluated, outermost first, when the environment replays an error to
155
- // find where it occurred, as TLC's CallStackTool does.
156
166
  callStack?: CallStack;
167
+ coverage?: Coverage;
157
168
  }
158
169
 
159
170
  export interface CallStack {
160
171
  expressions: Expression[];
161
172
  // TLC stops popping the stack once an evaluation fails, so it keeps where the failure occurred.
162
173
  isFrozen: boolean;
163
- // The expression that built each value of the replay that TLC's CallStackTool gives a source.
164
174
  sources: WeakMap<ObjectValue, Expression>;
165
- // The value each expression of the replay last evaluated to.
166
175
  values: WeakMap<Expression, Value>;
167
- // The expression each failure last left, which tells a failure of an operand from one of the
168
- // method that computes the operator.
176
+ // Tells a failure of an operand from one of the method that computes the operator.
169
177
  failures: WeakMap<Error, Expression>;
170
- // The failure of a value with a source, which TLC raises as a FingerprintException.
171
178
  fingerprint?: FingerprintFailure;
172
179
  }
173
180
 
174
181
  export interface FingerprintFailure {
175
182
  // The sources of the values whose methods failed, outermost first.
176
183
  sources: Expression[];
177
- // The message of the error the innermost one raised.
178
184
  reason: string;
179
185
  }
180
186
 
181
- // The operators of Tool#evalAppl whose value TLC's CallStackTool gives a source.
187
+ // The operators whose value TLC's CallStackTool gives a source.
182
188
  const SOURCED_OPERATORS = new Set(["SUBSET", "UNION", "DOMAIN", "\\cup", "\\cap", "\\"]);
183
189
 
184
- // CallStackTool copies the SetPredValue, FcnLambdaValue and OpLambdaValue that an evaluation
185
- // returns without their source, and a function TLC builds from a FcnLambdaValue has none.
190
+ // CallStackTool returns these lazy values without their source, and a function TLC builds
191
+ // from a FcnLambdaValue has none.
186
192
  const SOURCED_KINDS = new Set<Expression["kind"]>([
187
193
  "SetEnumeration",
188
194
  "SetFilter",
@@ -198,8 +204,7 @@ const isSourced = (expression: Expression) =>
198
204
  SOURCED_KINDS.has(expression.kind) ||
199
205
  (expression.kind === "Apply" && SOURCED_OPERATORS.has(expression.operator));
200
206
 
201
- // The argument whose method Tool#evalAppl calls to compute an operator, as with S.member(e) for
202
- // e \in S, f.apply(e) for f[e] when f is a function, or S.diff(T) for S \ T when S is Reducible.
207
+ // The operand whose Java method computes the operator, such as S in e \in S or f in f[e].
203
208
  const getReceiver = (expression: Expression, values: CallStack["values"]) => {
204
209
  if (expression.kind === "FunctionApplication" || expression.kind === "Except") {
205
210
  return expression.function;
@@ -220,8 +225,7 @@ export interface Context {
220
225
  scope: Scope | undefined;
221
226
  state: State | undefined;
222
227
  next: State | undefined;
223
- // EvalControl.KeepLazy, which Tool#evalAppl sets to evaluate the function it applies and which
224
- // the evaluation passes on, so that a function constructor within builds a FcnLambdaValue.
228
+ // TLC's EvalControl.KeepLazy, so a function constructor within an applied function stays lazy.
225
229
  isKeepLazy?: boolean;
226
230
  }
227
231
 
@@ -253,6 +257,18 @@ export const describeRange = (expression: Expression) => {
253
257
  return range ? formatRange(range) : describeLocation(expression);
254
258
  };
255
259
 
260
+ const TEMPORAL_FORMS = {
261
+ Always: "[]A",
262
+ Eventually: "<>A",
263
+ WeakFairness: "WF",
264
+ StrongFairness: "SF",
265
+ };
266
+
267
+ const createTemporalFormulaError = (form: string, expression: Expression) =>
268
+ new TlaEvaluationError(
269
+ `TLC encountered a temporal formula (${form}) when evaluating a predicate or action.\n${describeRange(expression)}`,
270
+ );
271
+
256
272
  // SANY prints a numeral as written and any other expression by its location.
257
273
  export const describeNode = (expression: Expression) =>
258
274
  expression.kind === "Number"
@@ -264,8 +280,7 @@ export const createConditionError = (expression: Expression, value: Value) =>
264
280
  `A non-boolean expression (${getKindString(value)}) was used as the condition of an IF.\n${describeRange(expression)}`,
265
281
  );
266
282
 
267
- // TLC parses an infix chain of /\ or \/ as nested binary junctions and a bulleted list as one
268
- // junction list, and it words the error differently for each.
283
+ // TLC words the error differently for an infix chain of /\ or \/ and for a bulleted list.
269
284
  export const createJunctionError = (
270
285
  expression: Expression & { kind: "And" | "Or" },
271
286
  index: number,
@@ -286,12 +301,11 @@ export const createJunctionError = (
286
301
  );
287
302
  };
288
303
 
289
- // TLC selects a field of a record, and of another function from the function it converts it to,
290
- // which for a tuple keeps its domain as an interval.
304
+ // TLC selects a field from the function it converts a non-record to, which keeps a tuple's domain.
291
305
  export const getFieldSelector = (expression: Expression & { kind: "FieldAccess" }) => {
292
306
  const field = expression.field;
293
307
  const describeMissing = (record: Value) =>
294
- `Attempted to select nonexistent field "${field}" from the record\n${formatValue(record)}\n${describeRange(expression)}`;
308
+ `Attempted to select nonexistent field "${field}" from the record\n${prettyPrint(formatValue(record))}\n${describeRange(expression)}`;
295
309
  const describeNotInDomain = (functionValue: Value) =>
296
310
  `Attempted to apply function:\n${prettyPrint(formatValue(functionValue))}\nto argument "${field}", which is not in the domain of the function.`;
297
311
  return (value: Value) => {
@@ -302,10 +316,9 @@ export const getFieldSelector = (expression: Expression & { kind: "FieldAccess"
302
316
  }
303
317
  const functionClass = getFunctionClass(value);
304
318
  if (functionClass === "tuple") throw createNonIntegerKeyError(field);
305
- // Only TLC's RecordValue names the field it lacks. Any other function, such as a FcnRcdValue
306
- // whose keys are strings, reports an argument outside its domain.
319
+ // Only TLC's RecordValue names the field it lacks, and TLC enumerates a FcnLambdaValue first.
307
320
  return applyFunction(
308
- value,
321
+ value.kind === "LazyFunction" ? toFiniteFunction(value) : value,
309
322
  field,
310
323
  functionClass === "record" ? describeMissing : describeNotInDomain,
311
324
  );
@@ -335,35 +348,34 @@ export const getSubsetOperator =
335
348
  `Attempted to evaluate an expression of form S \\subseteq T, but S was not enumerable.\n${describeRange(expression)}`,
336
349
  );
337
350
  }
338
- return builtin.evaluate([left, right]);
351
+ return builtin.evaluateBinary
352
+ ? builtin.evaluateBinary(left, right)
353
+ : builtin.evaluate([left, right]);
339
354
  };
340
355
 
341
356
  // TLC rejects a decimal, or an integer literal too big for it, while it processes the spec.
342
357
  export const createRealNumberError = (expression: DecimalExpression) =>
343
358
  setExitCode(
344
- new TlaEvaluationError(
345
- `TLC can't handle real numbers: ${expression.text} at ${describeLocation(expression)}`,
346
- ),
359
+ new TlaEvaluationError(`TLC can't handle real numbers.\n${expression.text}`),
347
360
  EXIT_STATUS.configParseError,
348
361
  );
349
362
 
350
363
  export const createBigNumberError = (expression: NumberExpression) =>
351
364
  setExitCode(
352
365
  new TlaEvaluationError(
353
- `TLC can't handle a number this big: ${expression.text ?? expression.value} at ${describeLocation(expression)}`,
366
+ `TLC can't handle a number this big.\n${expression.text ?? expression.value}`,
354
367
  ),
355
368
  EXIT_STATUS.error,
356
369
  );
357
370
 
358
- // TLC's Tool#evalAppl fails to look up a variable the state doesn't assign.
359
371
  export const createUnassignedError = (name: string, expression: Expression) =>
360
372
  new TlaUnassignedError(
361
373
  `In evaluation, the identifier ${name} is either undefined or not an operator.\n${describeRange(expression)}`,
362
374
  name,
363
375
  );
364
376
 
365
- // TLC's Tool#enabled reads the subscript of <<A>>_v in the successor as a state of its own, and
366
- // names the fairness condition when A leaves a variable of v unassigned, unlike TLC 1.7.4's.
377
+ // TLC reads the subscript of <<A>>_v in the successor as a state of its own, and after 1.7.4
378
+ // names the fairness condition when A leaves a variable of v unassigned.
367
379
  export const toUnspecifiedSubscriptError = (error: unknown, version: TlcVersion | undefined) =>
368
380
  error instanceof TlaUnassignedError && version !== "1.7.4"
369
381
  ? new TlaEvaluationError(
@@ -371,11 +383,6 @@ export const toUnspecifiedSubscriptError = (error: unknown, version: TlcVersion
371
383
  )
372
384
  : error;
373
385
 
374
- export const createPrimeOutsideActionError = (expression: Expression) =>
375
- new TlaEvaluationError(
376
- `A primed expression appears outside an action at ${describeLocation(expression)}`,
377
- );
378
-
379
386
  export const lookupScope = (scope: Scope | undefined, name: string): Binding | undefined => {
380
387
  for (let current = scope; current; current = current.parent) {
381
388
  if (current.name === name) return current.binding;
@@ -389,12 +396,13 @@ export const bindValue = (scope: Scope | undefined, name: string, value: Value):
389
396
  parent: scope,
390
397
  });
391
398
 
392
- const bindPattern = (scope: Scope | undefined, pattern: BoundPattern, value: Value) => {
399
+ export const bindPattern = (scope: Scope | undefined, pattern: BoundPattern, value: Value) => {
393
400
  if (pattern.kind === "Name") return bindValue(scope, pattern.name, value);
394
401
  const elements = getSequenceElements(value);
395
402
  if (!elements || elements.length !== pattern.names.length) {
403
+ const range = pattern.ranges?.[0];
396
404
  throw new TlaEvaluationError(
397
- `Cannot bind <<${pattern.names.join(", ")}>> to ${formatValue(value)}, which is not a tuple of that length`,
405
+ `Argument mismatch in operator application.${range ? formatRange(range) : ""}`,
398
406
  );
399
407
  }
400
408
  return pattern.names.reduce<Scope | undefined>(
@@ -439,6 +447,42 @@ export const expectBoolean = (value: Value, description: string) => {
439
447
  return value;
440
448
  };
441
449
 
450
+ export const expectImplication = (value: Value, expression: Expression, side: "P" | "Q") => {
451
+ if (typeof value !== "boolean") {
452
+ throw new TlaEvaluationError(
453
+ `Attempted to evaluate an expression of form P => Q when ${side} was\n${getKindString(value)}.\n${describeRange(expression)}`,
454
+ );
455
+ }
456
+ return value;
457
+ };
458
+
459
+ export const negate = (value: Value, expression: Expression) => {
460
+ if (typeof value !== "boolean") {
461
+ throw new TlaEvaluationError(
462
+ `Attempted to apply the operator ~ to a non-boolean\n(${getKindString(value)})\n${describeRange(expression)}`,
463
+ );
464
+ }
465
+ return !value;
466
+ };
467
+
468
+ export const isEquivalent = (left: Value, right: Value, expression: Expression) => {
469
+ if (typeof left !== "boolean" || typeof right !== "boolean") {
470
+ throw new TlaEvaluationError(
471
+ `Attempted to evaluate an expression of form P <=> Q when P or Q was not a boolean.\n${describeRange(expression)}`,
472
+ );
473
+ }
474
+ return left === right;
475
+ };
476
+
477
+ export const expectBooleanBody = (value: Value, expression: Expression) => {
478
+ if (typeof value !== "boolean") {
479
+ throw new TlaEvaluationError(
480
+ `TLC expected a boolean value, but did not find one. ${describeNode(expression)}`,
481
+ );
482
+ }
483
+ return value;
484
+ };
485
+
442
486
  export const getDefinition = (name: string, environment: Environment) =>
443
487
  environment.definitions.get(environment.substitutions.get(name) ?? name);
444
488
 
@@ -458,8 +502,7 @@ const getBoundExplanation = (set: Value, text: string) => {
458
502
  return undefined;
459
503
  };
460
504
 
461
- // TLC enumerates every set except the ones it implements in Java, so any other set fails as its own
462
- // class does.
505
+ // TLC enumerates every set but its Java ones, so any other set fails as its own class does.
463
506
  const checkEnumerable = (set: Value, expression: Expression, version: TlcVersion) => {
464
507
  if (!isSetValue(set) || isOverriddenSet(set)) {
465
508
  const text = formatValue(set);
@@ -476,19 +519,17 @@ const checkEnumerable = (set: Value, expression: Expression, version: TlcVersion
476
519
  const getEnumeratedElements = (set: Value, expression: Expression, version: TlcVersion) => {
477
520
  checkEnumerable(set, expression, version);
478
521
  if (typeof set === "object" && set.kind === "Interval") return getIntervalElements(set);
479
- return getLazySubsets(set) ?? toFiniteSet(set).elements;
522
+ return getLazySubsets(set) ?? getNormalizedSetElements(set);
480
523
  };
481
524
 
482
- // The elements Tool.contexts binds to the bound of a quantifier or a set map. TLC 1.7.4 streams a
483
- // lazy set's elements, where later versions normalize the set first.
525
+ // TLC 1.7.4 streams a lazy set's elements, where later versions normalize the set first.
484
526
  export const getContextElements = (set: Value, expression: Expression, version: TlcVersion) => {
485
527
  if (version !== "1.7.4") return getEnumeratedElements(set, expression, version);
486
528
  checkEnumerable(set, expression, version);
487
529
  return getLazySubsets(set) ?? getStreamedElements(set);
488
530
  };
489
531
 
490
- // Like TLC, a quantifier keeps an interval as an interval, so that it can stop at the first witness
491
- // in a large interval such as 1..2000000000 without listing it.
532
+ // Like TLC, keep an interval so a quantifier can stop at a witness in 1..2000000000 early.
492
533
  const getKeptInterval = (set: Value) => {
493
534
  if (typeof set !== "object" || set.kind !== "Interval") return undefined;
494
535
  getCardinality(set);
@@ -498,7 +539,6 @@ const getKeptInterval = (set: Value) => {
498
539
  export const getQuantifierElements = (set: Value, expression: Expression, version: TlcVersion) =>
499
540
  getKeptInterval(set) ?? getContextElements(set, expression, version);
500
541
 
501
- // CHOOSE and a function constructor visit the elements of the normalized set.
502
542
  const getNormalizedElements = (set: Value, expression: Expression, version: TlcVersion) =>
503
543
  getKeptInterval(set) ?? getEnumeratedElements(set, expression, version);
504
544
 
@@ -513,16 +553,20 @@ const someElement = (
513
553
  return false;
514
554
  };
515
555
 
556
+ // The names of one bound, as in \A x, y \in S, share its set, which TLC evaluates once.
557
+ export const mapBoundSets = <Result>(bounds: Bound[], map: (set: Expression) => Result) =>
558
+ bounds.reduce<Result[]>((results, bound, index) => {
559
+ results.push(
560
+ index > 0 && bounds[index - 1].set === bound.set ? results[index - 1] : map(bound.set),
561
+ );
562
+ return results;
563
+ }, []);
564
+
516
565
  export const getBoundElements = (bounds: Bound[], context: Context) =>
517
- bounds.map((bound) =>
518
- getQuantifierElements(
519
- evaluate(bound.set, context),
520
- bound.set,
521
- context.environment.runtime.version,
522
- ),
566
+ mapBoundSets(bounds, (set) =>
567
+ getQuantifierElements(evaluate(set, context), set, context.environment.runtime.version),
523
568
  );
524
569
 
525
- // Visits each binding of the bounds to the elements of their sets, until visit returns true.
526
570
  export const forEachBoundElement = (
527
571
  bounds: Bound[],
528
572
  sets: ReturnType<typeof getBoundElements>,
@@ -545,7 +589,7 @@ export const forEachBinding = (
545
589
  ) => forEachBoundElement(bounds, getBoundElements(bounds, context), context.scope, visit);
546
590
 
547
591
  const getBoundsDomain = (bounds: Bound[], context: Context): Value => {
548
- const sets = bounds.map((bound) => evaluate(bound.set, context));
592
+ const sets = mapBoundSets(bounds, (set) => evaluate(set, context));
549
593
  return sets.length === 1 ? sets[0] : { kind: "ProductSet", factors: sets };
550
594
  };
551
595
 
@@ -558,8 +602,6 @@ const bindArgument = (bounds: Bound[], scope: Scope | undefined, argument: Value
558
602
  );
559
603
  };
560
604
 
561
- // The parameters, body and scope of each function a constructor or a definition keeps lazy, whose
562
- // body TLC's getInitStates and getNextStates walk for an argument, as they do a FcnLambdaValue's.
563
605
  interface LazyFunction {
564
606
  value: LazyFunctionValue;
565
607
  bounds: Bound[];
@@ -567,8 +609,7 @@ interface LazyFunction {
567
609
  scope: Scope | undefined;
568
610
  }
569
611
 
570
- // The function keeps its parameters, body and scope itself, since a WeakMap entry for each
571
- // short-lived function makes every garbage collection slower.
612
+ // Kept on the value itself, since a WeakMap entry per short-lived function slows every GC.
572
613
  interface KeptLazyFunctionValue extends LazyFunctionValue {
573
614
  lambda: LazyFunction;
574
615
  }
@@ -581,8 +622,6 @@ const keepLambda = (lambda: LazyFunction) => Object.assign(lambda.value, { lambd
581
622
  export const getLazyFunction = (value: Value) =>
582
623
  isKeptLazyFunction(value) ? value.lambda : undefined;
583
624
 
584
- // Tool.getFcnContext: the scope of a lazy function's body for the arguments of an application. It
585
- // ignores arguments beyond the parameters.
586
625
  export const bindLazyArguments = (
587
626
  lambda: LazyFunction,
588
627
  expression: Expression & { kind: "FunctionApplication" },
@@ -607,12 +646,15 @@ export const bindLazyArguments = (
607
646
  typeof value.domain === "object" && value.domain.kind === "ProductSet"
608
647
  ? value.domain.factors
609
648
  : [];
610
- if (elements === undefined || elements.length < bounds.length) {
611
- throw new TlaEvaluationError(
612
- `Attempted to apply a function to an argument not in its domain.\n${describeRange(expression.function)}`,
649
+ // FcnLambdaValue#apply indexes past an argument tuple shorter than the bounds and ignores one
650
+ // longer, where this rejects the list.
651
+ const createListError = () =>
652
+ new TlaEvaluationError(
653
+ `In applying the function\n${prettyPrint(formatValue(value))},\nthe argument list is:\n${prettyPrint(formatValue(argument))}\nwhich does not match its formal parameter.\n`,
613
654
  );
614
- }
655
+ if (elements === undefined) throw createListError();
615
656
  bounds.forEach((bound, index) => {
657
+ if (index >= elements.length) throw createListError();
616
658
  const element = elements[index];
617
659
  const ordinal = `argument number ${index + 1}`;
618
660
  if (!isElementOf(element, domains[index])) {
@@ -633,11 +675,11 @@ export const bindLazyArguments = (
633
675
  );
634
676
  }
635
677
  });
636
- return bindArgument(bounds, lambda.scope, createTuple(elements.slice(0, bounds.length)));
678
+ if (elements.length > bounds.length) throw createListError();
679
+ return bindArgument(bounds, lambda.scope, argument);
637
680
  };
638
681
 
639
- // TLC prints a function it can't enumerate as its parameters and the location of its body. It
640
- // prints only the first name of a group such as `m, n \in S`.
682
+ // TLC prints a function it can't enumerate with only the first name of a group such as m, n.
641
683
  interface LazyFunctionTemplate {
642
684
  parameters: { index: number; name: string }[];
643
685
  body: string;
@@ -683,21 +725,29 @@ const getLazyFunctionSource = (
683
725
  };
684
726
  };
685
727
 
686
- // TLC's FcnLambdaValue evaluates its body at each application.
687
728
  const createLazyFunction = (
688
729
  domain: Value,
689
730
  compute: (argument: Value, self: LazyFunctionValue) => Value,
690
731
  source: LazyFunctionSource | undefined,
732
+ boundTupleLengths: (number | undefined)[] | undefined,
691
733
  ) => {
692
734
  const self: LazyFunctionValue = {
693
735
  kind: "LazyFunction",
694
736
  domain,
695
737
  source,
738
+ boundTupleLengths,
696
739
  apply: (argument) => compute(argument, self),
697
740
  };
698
741
  return self;
699
742
  };
700
743
 
744
+ const getBoundTupleLengths = (bounds: Bound[]) =>
745
+ bounds.length === 1
746
+ ? undefined
747
+ : bounds.map((bound) =>
748
+ bound.pattern.kind === "Tuple" ? bound.pattern.names.length : undefined,
749
+ );
750
+
701
751
  // The function constructor of a definition, which SANY locates at the whole definition.
702
752
  const getDefinitionSource = (definition: FunctionDefinition): Expression => ({
703
753
  kind: "FunctionConstruction",
@@ -706,7 +756,10 @@ const getDefinitionSource = (definition: FunctionDefinition): Expression => ({
706
756
  location: definition.location,
707
757
  });
708
758
 
709
- const createRecursiveFunction = (definition: FunctionDefinition, context: Context) => {
759
+ const createRecursiveFunction = (
760
+ definition: FunctionDefinition,
761
+ context: Context,
762
+ ): RebindableLazyFunction => {
710
763
  const domain = getBoundsDomain(definition.bounds, context);
711
764
  const functionValue = createLazyFunction(
712
765
  domain,
@@ -723,6 +776,7 @@ const createRecursiveFunction = (definition: FunctionDefinition, context: Contex
723
776
  definition.bounds,
724
777
  domain,
725
778
  ),
779
+ getBoundTupleLengths(definition.bounds),
726
780
  );
727
781
  keepLambda({
728
782
  value: functionValue,
@@ -730,11 +784,17 @@ const createRecursiveFunction = (definition: FunctionDefinition, context: Contex
730
784
  body: definition.body,
731
785
  scope: bindValue(undefined, definition.name, functionValue),
732
786
  });
733
- return definition.bounds.length === 1 ? markLambdaFunction(functionValue) : functionValue;
787
+ const rebindable: RebindableLazyFunction = Object.assign(functionValue, {
788
+ rebind: (tracing: Environment) => {
789
+ const rebound = createRecursiveFunction(definition, { ...context, environment: tracing });
790
+ rebound.enumerated = functionValue.enumerated;
791
+ return rebound;
792
+ },
793
+ });
794
+ return definition.bounds.length === 1 ? markLambdaFunction(rebindable) : rebindable;
734
795
  };
735
796
 
736
- // TLC computes a constant definition when it starts, without keeping a function it constructs
737
- // lazy, so a function over an interval or an enumerated set is a FcnRcdValue.
797
+ // TLC computes a constant definition eagerly, so a function over a reducible set is a FcnRcdValue.
738
798
  const toStartupValue = (definition: Definition, value: Value): Value => {
739
799
  if (typeof value !== "object" || getFunctionClass(value) !== "lambda") return value;
740
800
  if (
@@ -755,8 +815,7 @@ const toStartupValue = (definition: Definition, value: Value): Value => {
755
815
  }
756
816
  };
757
817
 
758
- // The code of a definition's body, evaluated as a whole. TLC evaluates a function definition that
759
- // isn't recursive as it does a function constructor.
818
+ // TLC evaluates a function definition that isn't recursive as it does a function constructor.
760
819
  const compileDefinitionBody = (definition: Definition, environment: Environment): Evaluator => {
761
820
  if (definition.kind === "Operator" && definition.params.length > 0) {
762
821
  return () => {
@@ -771,8 +830,6 @@ const compileDefinitionBody = (definition: Definition, environment: Environment)
771
830
  return getEntryEvaluator(getDefinitionSource(definition), environment);
772
831
  };
773
832
 
774
- // The code that evaluates a reference to a definition: the value TLC computed at startup when it
775
- // has one, and the body at the top level otherwise.
776
833
  const getDefinitionEvaluator = (definition: Definition, environment: Environment): Evaluator => {
777
834
  const compiled = environment.definitionEvaluators.get(definition);
778
835
  if (compiled) return compiled;
@@ -792,8 +849,6 @@ export const getStartupValue = (definition: Definition, environment: Environment
792
849
  return id === undefined ? undefined : environment.startupValues[id];
793
850
  };
794
851
 
795
- // TLC computes each constant definition the configuration doesn't replace when it starts, and
796
- // leaves one it fails to compute to evaluate where the spec uses it.
797
852
  export const evaluateStartupDefinitions = (definitions: Definition[], environment: Environment) =>
798
853
  definitions.forEach((definition) => {
799
854
  if (definition.kind === "Operator" && definition.params.length > 0) return;
@@ -815,11 +870,46 @@ export const evaluateStartupDefinitions = (definitions: Definition[], environmen
815
870
  }
816
871
  });
817
872
 
873
+ // TLC reuses a cached value while each variable the cached state assigns keeps its value.
874
+ const isStateWithin = (state: State | undefined, cached: State | undefined) => {
875
+ if (cached === undefined || state === cached) return true;
876
+ try {
877
+ return cached.every(
878
+ (value, index) =>
879
+ value === undefined || (state?.[index] !== undefined && valuesEqual(state[index], value)),
880
+ );
881
+ } catch (error) {
882
+ if (error instanceof TlaEvaluationError) return false;
883
+ throw error;
884
+ }
885
+ };
886
+
818
887
  const forceThunk = (thunk: Thunk, context: Context) => {
819
- const isSameState = thunk.state === context.state && thunk.next === context.next;
820
- if (isSameState && thunk.cache !== undefined) return thunk.cache;
821
- const value = evaluate(thunk.expression, withScope(context, thunk.scope));
822
- if (isSameState && (!thunk.isStreamed || isSettledValue(value))) thunk.cache = value;
888
+ const cache = thunk.cache;
889
+ const isCached =
890
+ cache !== undefined &&
891
+ isStateWithin(context.state, thunk.state) &&
892
+ isStateWithin(context.next, thunk.next);
893
+ if (isCached) return cache;
894
+ const coverage = context.environment.coverage;
895
+ const node = coverage?.current === -1 ? undefined : coverage?.values.get(thunk);
896
+ const value =
897
+ coverage && node !== undefined
898
+ ? runAtCoverageNode(coverage, node, () =>
899
+ evaluate(thunk.expression, withScope(context, thunk.scope)),
900
+ )
901
+ : evaluate(thunk.expression, withScope(context, thunk.scope));
902
+ if (!thunk.isStreamed || isSettledValue(value)) {
903
+ thunk.cache = value;
904
+ thunk.state = context.state;
905
+ thunk.next = context.next;
906
+ }
907
+ // A value a thunk cached with no state read no variable, so it holds in every state. Releasing
908
+ // its scope frees the evaluations the scope's bindings cached, which a long script keeps alive.
909
+ if (thunk.cache !== undefined && thunk.state === undefined && thunk.next === undefined) {
910
+ thunk.scope = undefined;
911
+ thunk.isReleased = true;
912
+ }
823
913
  return value;
824
914
  };
825
915
 
@@ -887,6 +977,12 @@ const evaluateOperatorArgument = (expression: Expression, context: Context): Ope
887
977
  };
888
978
 
889
979
  const callOperatorWithValues = (operator: Operator, args: Value[], context: Context): Value => {
980
+ if (operator.kind === "Builtin" && operator.isLazy) {
981
+ return operator.evaluate(
982
+ args.map((value) => ({ kind: "Operator", name: "argument", arity: 0, call: () => value })),
983
+ context,
984
+ );
985
+ }
890
986
  if (operator.kind === "Builtin") return operator.evaluate(args, context);
891
987
  if (operator.kind === "Operator") return operator.call(args);
892
988
  const scope = operator.params.reduce<Scope | undefined>(
@@ -904,11 +1000,6 @@ const toOperatorValue = (operator: Operator, context: Context): OperatorValue =>
904
1000
  name: operator.name,
905
1001
  arity: getArity(operator),
906
1002
  call: (args) => callOperatorWithValues(operator, args, context),
907
- literalBody:
908
- operator.kind === "Closure" &&
909
- (operator.body.kind === "Number" || operator.body.kind === "String")
910
- ? operator.body.value
911
- : undefined,
912
1003
  };
913
1004
 
914
1005
  const isOperatorArgument = (expression: Expression, context: Context) => {
@@ -960,9 +1051,18 @@ const compileArgumentBinder = (argument: Expression, environment: Environment):
960
1051
  const isLiteral =
961
1052
  argument.kind === "String" || (argument.kind === "Number" && isTlcInteger(argument.value));
962
1053
  if (isLiteral) {
963
- const binding: Binding = { kind: "Value", value: argument.value };
1054
+ const binding: Binding = { kind: "Value", value: argument.value, argument };
964
1055
  return () => binding;
965
1056
  }
1057
+ // TLC counts an argument where the operator's body evaluates it, under the call.
1058
+ const coverage = environment.coverage;
1059
+ if (coverage) {
1060
+ return (context) => {
1061
+ const thunk = createThunk(argument, context);
1062
+ if (coverage.current !== -1) coverage.values.set(thunk, coverage.current);
1063
+ return thunk;
1064
+ };
1065
+ }
966
1066
  if (argument.kind === "Identifier") {
967
1067
  const global = isLocallyResolved(argument)
968
1068
  ? undefined
@@ -971,7 +1071,7 @@ const compileArgumentBinder = (argument: Expression, environment: Environment):
971
1071
  const binding: Binding = { kind: "Value", value: global.value };
972
1072
  return () => binding;
973
1073
  }
974
- if (global === undefined) {
1074
+ if (global === undefined && !environment.callStack) {
975
1075
  return (context) => {
976
1076
  const binding = lookupScope(context.scope, argument.name);
977
1077
  return binding?.kind === "Value" || binding?.kind === "Thunk"
@@ -1019,65 +1119,85 @@ const callOperator = (
1019
1119
  return operator.evaluate(evaluateBuiltinArguments(args, context), context);
1020
1120
  };
1021
1121
 
1022
- // The LET definitions that a reference evaluates again, and those that cache only a settled value.
1023
1122
  interface ReevaluatedDefinitions {
1024
1123
  impure: ReadonlySet<Definition>;
1025
1124
  streamed: ReadonlySet<Definition>;
1026
1125
  }
1027
1126
 
1127
+ // A LET's function definition has one function constructor, as in SANY, so its code compiles once
1128
+ // however often the LET is evaluated.
1129
+ const letFunctionConstructions = new WeakMap<FunctionDefinition, Expression>();
1130
+
1131
+ const getLetFunctionConstruction = (definition: FunctionDefinition): Expression => {
1132
+ const known = letFunctionConstructions.get(definition);
1133
+ if (known) return known;
1134
+ const construction: Expression = {
1135
+ kind: "FunctionConstruction",
1136
+ bounds: definition.bounds,
1137
+ body: definition.body,
1138
+ location: definition.location,
1139
+ isRecursive: true,
1140
+ };
1141
+ letFunctionConstructions.set(definition, construction);
1142
+ return construction;
1143
+ };
1144
+
1028
1145
  export const bindDefinitions = (
1029
1146
  definitions: Definition[],
1030
1147
  context: Context,
1031
1148
  reevaluated?: ReevaluatedDefinitions,
1032
- ): Scope | undefined =>
1033
- definitions.reduce<Scope | undefined>((scope, definition) => {
1034
- const node: Scope = {
1035
- name: definition.name,
1036
- binding: { kind: "Value", value: false },
1037
- parent: scope,
1038
- };
1039
- if (definition.kind === "Function") {
1040
- node.binding = {
1041
- kind: "Thunk",
1042
- expression: {
1043
- kind: "FunctionConstruction",
1044
- bounds: definition.bounds,
1045
- body: definition.body,
1046
- location: definition.location,
1047
- isRecursive: true,
1048
- },
1049
- scope: node,
1050
- state: context.state,
1051
- next: context.next,
1052
- cache: undefined,
1053
- isStreamed: false,
1054
- };
1055
- return node;
1056
- }
1057
- if (definition.params.length > 0 || reevaluated?.impure.has(definition)) {
1058
- node.binding = {
1059
- kind: "Operator",
1060
- operator: {
1061
- kind: "Closure",
1062
- name: definition.name,
1063
- params: definition.params,
1064
- body: definition.body,
1065
- scope: node,
1066
- },
1067
- };
1068
- return node;
1069
- }
1070
- node.binding = {
1071
- kind: "Thunk",
1072
- expression: definition.body,
1073
- scope: node,
1074
- state: context.state,
1075
- next: context.next,
1076
- cache: undefined,
1077
- isStreamed: reevaluated?.streamed.has(definition) ?? false,
1078
- };
1149
+ ): Scope | undefined => {
1150
+ const nodes = definitions.map((definition): Scope => ({
1151
+ name: definition.name,
1152
+ binding: { kind: "Value", value: false },
1153
+ parent: undefined,
1154
+ }));
1155
+ const scope = nodes.reduce<Scope | undefined>((parent, node) => {
1156
+ node.parent = parent;
1079
1157
  return node;
1080
1158
  }, context.scope);
1159
+ definitions.forEach((definition, index) => {
1160
+ nodes[index].binding =
1161
+ definition.kind === "Function"
1162
+ ? {
1163
+ kind: "Thunk",
1164
+ expression: getLetFunctionConstruction(definition),
1165
+ scope,
1166
+ state: context.state,
1167
+ next: context.next,
1168
+ cache: undefined,
1169
+ isStreamed: false,
1170
+ }
1171
+ : definition.params.length > 0 || reevaluated?.impure.has(definition)
1172
+ ? {
1173
+ kind: "Operator",
1174
+ operator: {
1175
+ kind: "Closure",
1176
+ name: definition.name,
1177
+ params: definition.params,
1178
+ body: definition.body,
1179
+ scope,
1180
+ },
1181
+ }
1182
+ : {
1183
+ kind: "Thunk",
1184
+ expression: definition.body,
1185
+ scope,
1186
+ state: context.state,
1187
+ next: context.next,
1188
+ cache: undefined,
1189
+ isStreamed: reevaluated?.streamed.has(definition) ?? false,
1190
+ };
1191
+ });
1192
+ // TLC counts a LET definition under the node that encloses the LET.
1193
+ const coverage = context.environment.coverage;
1194
+ if (coverage && coverage.current !== -1) {
1195
+ nodes.forEach((node) => {
1196
+ if (node.binding.kind === "Thunk") coverage.values.set(node.binding, coverage.current);
1197
+ });
1198
+ }
1199
+ return scope;
1200
+ };
1081
1201
 
1082
1202
  const evaluateLocalIdentifier = (name: string, expression: Expression, context: Context): Value => {
1083
1203
  const binding = lookupScope(context.scope, name);
@@ -1104,9 +1224,8 @@ const evaluateLocalIdentifier = (name: string, expression: Expression, context:
1104
1224
  throw new TlaEvaluationError(`Unknown identifier ${name} at ${describeLocation(expression)}`);
1105
1225
  };
1106
1226
 
1107
- // TLC's next-state generator does not bind LET definitions to values, so each reference to one
1108
- // evaluates it again: one that calls an impure builtin repeats its effects, and a set one builds
1109
- // with UNION or \cup starts out uncached.
1227
+ // TLC's next-state generator evaluates a LET definition again at each reference, so one that
1228
+ // calls an impure builtin repeats its effects, and a UNION or \cup set starts out uncached.
1110
1229
  export const getReevaluatedDefinitions = (
1111
1230
  definitions: Definition[],
1112
1231
  environment: Environment,
@@ -1122,23 +1241,41 @@ export const isImpure = (environment: Environment) =>
1122
1241
  isImpureDefinition(definition, environment),
1123
1242
  );
1124
1243
 
1125
- // Whether evaluating a definition again can show, such as by printing twice.
1126
1244
  export const hasRepeatedEffects = (environment: Environment) =>
1127
1245
  [...environment.facts.ids.keys()].some((definition) =>
1128
1246
  isImpureDefinition(definition, environment, "repeated"),
1129
1247
  );
1130
1248
 
1131
- // A set filter TLC evaluates lazily, with how to rebuild it so that its predicate runs in another
1132
- // environment.
1133
1249
  interface RebindableFilteredSet extends FilteredSetValue {
1134
1250
  rebind: (environment: Environment) => Value;
1135
1251
  }
1136
1252
 
1137
- const isRebindableFilteredSet = (value: Value): value is RebindableFilteredSet =>
1138
- typeof value === "object" && value.kind === "FilteredSet" && "rebind" in value;
1253
+ interface RebindableLazyFunction extends LazyFunctionValue {
1254
+ rebind: (environment: Environment) => Value;
1255
+ }
1256
+
1257
+ const isRebindable = (value: Value): value is RebindableFilteredSet | RebindableLazyFunction =>
1258
+ typeof value === "object" &&
1259
+ (value.kind === "FilteredSet" || value.kind === "LazyFunction") &&
1260
+ "rebind" in value;
1261
+
1262
+ const toNextContext = (context: Context): Context => ({
1263
+ environment: context.environment,
1264
+ scope: context.scope,
1265
+ state: context.next,
1266
+ next: undefined,
1267
+ isKeepLazy: context.isKeepLazy,
1268
+ });
1269
+
1270
+ // TLC evaluates the expression in the current state first.
1271
+ const compileUnchanged =
1272
+ (evaluator: Evaluator): Evaluator =>
1273
+ (context) => {
1274
+ const current = evaluator(context);
1275
+ return valuesEqual(current, evaluator(toNextContext(context)));
1276
+ };
1139
1277
 
1140
- // TLC's CallStackTool rebinds the lazy values its evaluations return, so their later evaluation
1141
- // records its call stack too.
1278
+ // TLC's CallStackTool rebinds the lazy values it returns, so their later evaluation records too.
1142
1279
  const traceEvaluator =
1143
1280
  (
1144
1281
  expression: Expression,
@@ -1156,13 +1293,17 @@ const traceEvaluator =
1156
1293
  setTrace.callStack = callStack;
1157
1294
  try {
1158
1295
  const computed = evaluator(context);
1159
- const value = isRebindableFilteredSet(computed) ? computed.rebind(environment) : computed;
1296
+ const value = isRebindable(computed) ? computed.rebind(environment) : computed;
1160
1297
  callStack.values.set(expression, value);
1161
1298
  if (typeof value === "object" && value.kind !== "FilteredSet" && isSourced(expression)) {
1162
1299
  callStack.sources.set(value, expression);
1163
1300
  }
1164
1301
  return value;
1165
1302
  } catch (error) {
1303
+ if (error instanceof TlaSetBoundError && !callStack.isFrozen) {
1304
+ callStack.expressions.length = 0;
1305
+ callStack.isFrozen = true;
1306
+ }
1166
1307
  const failed = error instanceof Error ? callStack.failures.get(error) : undefined;
1167
1308
  if (error instanceof Error) callStack.failures.set(error, expression);
1168
1309
  const receiver = getReceiver(expression, callStack.values);
@@ -1190,9 +1331,8 @@ const traceEvaluator =
1190
1331
  }
1191
1332
  };
1192
1333
 
1193
- // A method of a value with a source raises a FingerprintException, which each value with a source
1194
- // whose method called it heads in turn. CallStack#freeze adds their sources to the stack, outermost
1195
- // first. The values are those whose methods failed, outermost first.
1334
+ // A FingerprintException from a method of a value with a source is headed by each such value
1335
+ // whose method called it in turn, outermost first.
1196
1336
  export const freezeCallStack = (
1197
1337
  callStack: CallStack,
1198
1338
  values: (Value | undefined)[],
@@ -1215,8 +1355,6 @@ export const freezeCallStack = (
1215
1355
  callStack.isFrozen = true;
1216
1356
  };
1217
1357
 
1218
- // A FingerprintException that a method of a value with a source raises, or that passes through one,
1219
- // takes the value's source as its new head.
1220
1358
  const headFingerprint = (callStack: CallStack, source: Expression, error: unknown) => {
1221
1359
  if (!(error instanceof TlaEvaluationError)) return;
1222
1360
  if (!callStack.isFrozen) callStack.expressions.push(source);
@@ -1228,10 +1366,10 @@ const headFingerprint = (callStack: CallStack, source: Expression, error: unknow
1228
1366
  };
1229
1367
  };
1230
1368
 
1231
- // A copy of the environment that records the call stack of each evaluation, with evaluators of its
1232
- // own since the environment's evaluators record nothing.
1369
+ // With evaluators of its own, since the environment's evaluators record nothing.
1233
1370
  export const createTracingEnvironment = (environment: Environment): Environment => ({
1234
1371
  ...environment,
1372
+ coverage: undefined,
1235
1373
  evaluators: new WeakMap(),
1236
1374
  entryEvaluators: new WeakMap(),
1237
1375
  definitionEvaluators: new WeakMap(),
@@ -1244,20 +1382,63 @@ export const createTracingEnvironment = (environment: Environment): Environment
1244
1382
  },
1245
1383
  });
1246
1384
 
1385
+ // A replay that walks into the expression has recorded its frames already.
1386
+ const traceFrames =
1387
+ (
1388
+ expression: Expression,
1389
+ frames: Expression[],
1390
+ evaluator: Evaluator,
1391
+ callStack: CallStack,
1392
+ ): Evaluator =>
1393
+ (context) => {
1394
+ if (callStack.expressions.at(-1) === expression) return evaluator(context);
1395
+ callStack.expressions.push(...frames);
1396
+ try {
1397
+ return evaluator(context);
1398
+ } finally {
1399
+ if (!callStack.isFrozen) callStack.expressions.length -= frames.length;
1400
+ }
1401
+ };
1402
+
1403
+ // TLC counts an evaluation under the node of the expression in the tree of the check it counts,
1404
+ // or, when the tree has none there, under the node it evaluates in.
1405
+ const countEvaluator =
1406
+ (expression: Expression, evaluator: Evaluator, coverage: Coverage): Evaluator =>
1407
+ (context) => {
1408
+ const outer = coverage.current;
1409
+ if (outer === -1 || !coverage.covered.has(expression)) return evaluator(context);
1410
+ const node = getCoverageNode(coverage, outer, expression);
1411
+ countCoverage(coverage, node);
1412
+ coverage.current = node;
1413
+ try {
1414
+ const value = evaluator(context);
1415
+ if (typeof value === "object" && expression.kind === "SetEnumeration") {
1416
+ coverage.values.set(value, node);
1417
+ }
1418
+ return value;
1419
+ } finally {
1420
+ coverage.current = outer;
1421
+ }
1422
+ };
1423
+
1247
1424
  export const getEvaluator = (expression: Expression, environment: Environment): Evaluator => {
1248
1425
  const cached = environment.evaluators.get(expression);
1249
1426
  if (cached) return cached;
1250
1427
  const compiled = compile(expression, environment);
1251
1428
  const callStack = environment.callStack;
1252
- const evaluator = callStack
1429
+ const frames = callStack && substitutionFrames.get(expression);
1430
+ const traced = callStack
1253
1431
  ? traceEvaluator(expression, compiled, environment, callStack)
1254
1432
  : compiled;
1433
+ const framed = callStack && frames ? traceFrames(expression, frames, traced, callStack) : traced;
1434
+ const coverage = environment.coverage;
1435
+ const evaluator = coverage ? countEvaluator(expression, framed, coverage) : framed;
1255
1436
  environment.evaluators.set(expression, evaluator);
1256
1437
  return evaluator;
1257
1438
  };
1258
1439
 
1259
1440
  export const getEntryEvaluator = (expression: Expression, environment: Environment) => {
1260
- if (environment.callStack) return getEvaluator(expression, environment);
1441
+ if (environment.callStack || environment.coverage) return getEvaluator(expression, environment);
1261
1442
  const compiled = environment.entryEvaluators.get(expression);
1262
1443
  if (compiled) return compiled;
1263
1444
  const evaluator =
@@ -1288,8 +1469,7 @@ const compileIdentifier = (
1288
1469
  return () => value;
1289
1470
  }
1290
1471
  if (global?.kind === "Definition") {
1291
- // The body compiles when the reference is first evaluated, as a recursive definition's body
1292
- // refers back to it.
1472
+ // The body compiles when first evaluated, as a recursive definition's body refers back to it.
1293
1473
  const definition = global.definition;
1294
1474
  const compiled = { reference: undefined as Evaluator | undefined };
1295
1475
  return (context) =>
@@ -1396,12 +1576,24 @@ const compileApply = (
1396
1576
  const left = getEvaluator(args[0], environment);
1397
1577
  const right = getEvaluator(args[1], environment);
1398
1578
  return (context) =>
1399
- !expectBoolean(left(context), "the left side of =>") ||
1400
- expectBoolean(right(context), "the right side of =>");
1579
+ !expectImplication(left(context), expression, "P") ||
1580
+ expectImplication(right(context), expression, "Q");
1581
+ }
1582
+ if (expression.operator === "~" && args.length === 1) {
1583
+ const operand = getEvaluator(args[0], environment);
1584
+ return (context) => negate(operand(context), expression);
1401
1585
  }
1402
- if (expression.operator === "~>") {
1586
+ if (expression.operator === "<=>") {
1587
+ const left = getEvaluator(args[0], environment);
1588
+ const right = getEvaluator(args[1], environment);
1589
+ return (context) => isEquivalent(left(context), right(context), expression);
1590
+ }
1591
+ if (expression.operator === "~>" || expression.operator === "-+->") {
1403
1592
  return () => {
1404
- throw new TlaEvaluationError("TLC cannot evaluate a temporal formula such as ~> in a state");
1593
+ throw createTemporalFormulaError(
1594
+ expression.operator === "~>" ? "a ~> b" : "a -+-> formula",
1595
+ expression,
1596
+ );
1405
1597
  };
1406
1598
  }
1407
1599
  const global = isLocallyResolved(expression)
@@ -1413,14 +1605,15 @@ const compileApply = (
1413
1605
  const domain = getDomainOperator(expression);
1414
1606
  return (context) => domain(operand(context));
1415
1607
  }
1416
- // TLC sorts the value of a constant TLCEval argument only where no context binds a name.
1608
+ // TLC caches the value of a constant TLCEval argument only where no context binds a name.
1417
1609
  if (global?.kind === "Builtin" && global.name === "TLCEval" && args.length === 1) {
1418
- const operand = getEvaluator(args[0], environment);
1419
- if (contextualApplications.has(expression) || isNonconstant(args[0], environment)) {
1420
- return operand;
1421
- }
1610
+ const isCached =
1611
+ !contextualApplications.has(expression) && !isNonconstant(args[0], environment);
1422
1612
  return (context) =>
1423
- context.scope === undefined ? global.evaluate([operand(context)]) : operand(context);
1613
+ global.evaluate(
1614
+ getLazyArguments(args, context),
1615
+ isCached && context.scope === undefined ? undefined : context,
1616
+ );
1424
1617
  }
1425
1618
  if (global?.kind === "Builtin" && global.name === "\\subseteq" && args.length === 2) {
1426
1619
  const left = getEvaluator(args[0], environment);
@@ -1458,7 +1651,6 @@ const compileQuantifier = (
1458
1651
  environment: Environment,
1459
1652
  ): Evaluator => {
1460
1653
  const isForall = expression.kind === "Forall";
1461
- const description = isForall ? "the body of \\A" : "the body of \\E";
1462
1654
  const body = getEvaluator(expression.body, environment);
1463
1655
  const bound = expression.bounds[0];
1464
1656
  if (expression.bounds.length === 1 && bound.pattern.kind === "Name") {
@@ -1468,9 +1660,9 @@ const compileQuantifier = (
1468
1660
  const isFound = someElement(
1469
1661
  getQuantifierElements(set(context), bound.set, environment.runtime.version),
1470
1662
  (element) =>
1471
- expectBoolean(
1663
+ expectBooleanBody(
1472
1664
  body(withScope(context, bindValue(context.scope, name, element))),
1473
- description,
1665
+ expression,
1474
1666
  ) !== isForall,
1475
1667
  );
1476
1668
  return isFound ? !isForall : isForall;
@@ -1479,14 +1671,17 @@ const compileQuantifier = (
1479
1671
  const bounds = expression.bounds;
1480
1672
  if (bounds.every((item) => item.pattern.kind === "Name")) {
1481
1673
  const names = bounds.map((item) => (item.pattern.kind === "Name" ? item.pattern.name : ""));
1482
- const sets = bounds.map((item) => getEvaluator(item.set, environment));
1483
1674
  return (context) => {
1484
- const lists = sets.map((set, index) =>
1485
- getQuantifierElements(set(context), bounds[index].set, environment.runtime.version),
1675
+ const lists = mapBoundSets(bounds, (set) =>
1676
+ getQuantifierElements(
1677
+ getEvaluator(set, environment)(context),
1678
+ set,
1679
+ environment.runtime.version,
1680
+ ),
1486
1681
  );
1487
1682
  const visit = (index: number, scope: Scope | undefined): boolean => {
1488
1683
  if (index < 0) {
1489
- return expectBoolean(body(withScope(context, scope)), description) !== isForall;
1684
+ return expectBooleanBody(body(withScope(context, scope)), expression) !== isForall;
1490
1685
  }
1491
1686
  return someElement(lists[index], (element) =>
1492
1687
  visit(index - 1, bindValue(scope, names[index], element)),
@@ -1499,7 +1694,7 @@ const compileQuantifier = (
1499
1694
  const isFound = forEachBinding(
1500
1695
  bounds,
1501
1696
  context,
1502
- (scope) => expectBoolean(body(withScope(context, scope)), description) !== isForall,
1697
+ (scope) => expectBooleanBody(body(withScope(context, scope)), expression) !== isForall,
1503
1698
  );
1504
1699
  return isFound ? !isForall : isForall;
1505
1700
  };
@@ -1518,8 +1713,7 @@ const getBoundValue = (pattern: BoundPattern, scope: Scope | undefined) => {
1518
1713
  return binding?.kind === "Value" ? binding.value : undefined;
1519
1714
  };
1520
1715
 
1521
- // TLC keeps a function constructor lazy when it is the function of an application, or the base of
1522
- // an EXCEPT that is, so it evaluates the body only at the arguments it is applied to.
1716
+ // TLC keeps a function constructor lazy when it is applied, or is the base of an applied EXCEPT.
1523
1717
  const keptLazyExpressions = new WeakSet<Expression>();
1524
1718
 
1525
1719
  export const keepLazy = (expression: Expression) => {
@@ -1528,34 +1722,72 @@ export const keepLazy = (expression: Expression) => {
1528
1722
  }
1529
1723
  };
1530
1724
 
1531
- const compileFunctionConstruction = (
1725
+ // The names an expression may look up in its scope, or undefined when a subexpression selector may
1726
+ // look up others.
1727
+ const scopeNames = new WeakMap<Expression, string[] | undefined>();
1728
+
1729
+ const getScopeNames = (expression: Expression) => {
1730
+ if (scopeNames.has(expression)) return scopeNames.get(expression);
1731
+ const names = new Set<string>();
1732
+ const visit = (node: Expression): boolean => {
1733
+ if (node.kind === "Subexpression") return false;
1734
+ if (node.kind === "Identifier") names.add(node.name);
1735
+ if (node.kind === "Apply" || node.kind === "OperatorReference") names.add(node.operator);
1736
+ if (node.kind === "ExceptAt") names.add(EXCEPT_AT);
1737
+ return getChildren(node).every(visit);
1738
+ };
1739
+ const result = visit(expression) ? [...names] : undefined;
1740
+ scopeNames.set(expression, result);
1741
+ return result;
1742
+ };
1743
+
1744
+ // The bindings of a scope that names look up, so that a lazy function keeps only those alive and
1745
+ // not the values its other bindings cached. An unnamed node ends the chain, since a TLCEval in the
1746
+ // body sorts its value only where no context binds a name.
1747
+ const trimScope = (scope: Scope | undefined, names: string[] | undefined) =>
1748
+ names === undefined || scope === undefined
1749
+ ? scope
1750
+ : names.reduce<Scope>(
1751
+ (trimmed, name) => {
1752
+ const binding = lookupScope(scope, name);
1753
+ return binding ? { name, binding, parent: trimmed } : trimmed;
1754
+ },
1755
+ { name: "", binding: { kind: "Value", value: false }, parent: undefined },
1756
+ );
1757
+
1758
+ export const isKeptLazy = (expression: Expression) => keptLazyExpressions.has(expression);
1759
+
1760
+ // Builds the function of a constructor from its evaluated domain.
1761
+ export const getFunctionBuilder = (
1532
1762
  expression: Expression & { kind: "FunctionConstruction" },
1533
1763
  environment: Environment,
1534
- ): Evaluator => {
1535
- const isKeptLazy = keptLazyExpressions.has(expression);
1764
+ ) => {
1765
+ const isKeptLazyExpression = isKeptLazy(expression);
1536
1766
  const body = getEvaluator(expression.body, environment);
1537
1767
  const bounds = expression.bounds;
1538
1768
  const bound = bounds[0];
1539
1769
  const isSingleName = bounds.length === 1 && bound.pattern.kind === "Name";
1540
- const set = getEvaluator(bound.set, environment);
1541
1770
  const construct = (domain: Value, context: Context) => {
1542
1771
  if (isSingleName && bound.pattern.kind === "Name") {
1543
1772
  const name = bound.pattern.name;
1773
+ const evaluateAt = (key: Value) =>
1774
+ body(withScope(context, bindValue(context.scope, name, key)));
1775
+ // TLC sizes the domain, then evaluates the body at each element. A domain too large to hold
1776
+ // the values stays lazy.
1777
+ if (isBeyondSetBound(domain)) {
1778
+ getCardinality(domain);
1779
+ forEachElement(domain, evaluateAt);
1780
+ return createLazy(domain, context);
1781
+ }
1544
1782
  const keys = getFunctionDomain(domain);
1545
- const functionValue = createSortedFunction(
1546
- keys,
1547
- keys.map((key) => body(withScope(context, bindValue(context.scope, name, key)))),
1548
- );
1549
- // FcnLambdaValue#toFcnRcd builds a FcnRcdValue over an interval or an enumerated set.
1550
- return isReducibleSet(domain) ? functionValue : markLambdaFunction(functionValue);
1783
+ const functionValue = createSortedFunction(keys, keys.map(evaluateAt));
1784
+ if (isReducibleSet(domain)) return functionValue;
1785
+ functionValue.lambdaDomain = domain;
1786
+ return markLambdaFunction(functionValue);
1551
1787
  }
1552
1788
  const pairs: [Value, Value][] = [];
1553
- const sets = bounds.map((item) =>
1554
- getNormalizedElements(
1555
- evaluate(item.set, context),
1556
- item.set,
1557
- context.environment.runtime.version,
1558
- ),
1789
+ const sets = mapBoundSets(bounds, (set) =>
1790
+ getNormalizedElements(evaluate(set, context), set, context.environment.runtime.version),
1559
1791
  );
1560
1792
  forEachBoundElement(bounds, sets, context.scope, (scope) => {
1561
1793
  const key =
@@ -1568,13 +1800,17 @@ const compileFunctionConstruction = (
1568
1800
  return createFunction(pairs);
1569
1801
  };
1570
1802
  const template = getLazyFunctionTemplate(bounds, expression.body);
1803
+ const boundTupleLengths = getBoundTupleLengths(bounds);
1804
+ const bodyNames = getScopeNames(expression.body);
1571
1805
  const createLazy = (domain: Value, context: Context) => {
1572
- const scope = context.scope;
1806
+ const scope = trimScope(context.scope, bodyNames);
1807
+ const lambdaContext = withScope(context, scope);
1573
1808
  const functionValue = keepLambda({
1574
1809
  value: createLazyFunction(
1575
1810
  domain,
1576
- (argument) => body(withScope(context, bindArgument(bounds, scope, argument))),
1811
+ (argument) => body(withScope(lambdaContext, bindArgument(bounds, scope, argument))),
1577
1812
  getLazyFunctionSource(template, bounds, domain),
1813
+ boundTupleLengths,
1578
1814
  ),
1579
1815
  bounds,
1580
1816
  body: expression.body,
@@ -1583,15 +1819,23 @@ const compileFunctionConstruction = (
1583
1819
  return bounds.length === 1 ? markLambdaFunction(functionValue) : functionValue;
1584
1820
  };
1585
1821
  const callStack = environment.callStack;
1586
- return (context) => {
1587
- const domain = isSingleName ? set(context) : getBoundsDomain(bounds, context);
1588
- if (expression.isRecursive || isKeptLazy || context.isKeepLazy || !isEnumerable(domain)) {
1822
+ const build = (domain: Value, context: Context) => {
1823
+ if (
1824
+ expression.isRecursive ||
1825
+ isKeptLazyExpression ||
1826
+ context.isKeepLazy ||
1827
+ !isEnumerable(domain)
1828
+ ) {
1589
1829
  return createLazy(domain, context);
1590
1830
  }
1591
- // TLC builds a function over a domain other than a set enumeration or an interval lazily, so
1592
- // its body fails only where TLC forces it, as the replay does. Building it at once is faster
1593
- // otherwise.
1594
- if (!isReducibleSet(domain)) {
1831
+ // TLC builds a function lazily unless each bound is reducible, so its body fails where forced.
1832
+ const isReducibleDomain =
1833
+ bounds.length === 1
1834
+ ? isReducibleSet(domain)
1835
+ : typeof domain === "object" &&
1836
+ domain.kind === "ProductSet" &&
1837
+ domain.factors.every(isReducibleSet);
1838
+ if (!isReducibleDomain) {
1595
1839
  if (callStack) return createLazy(domain, context);
1596
1840
  try {
1597
1841
  return construct(domain, context);
@@ -1609,6 +1853,20 @@ const compileFunctionConstruction = (
1609
1853
  throw error;
1610
1854
  }
1611
1855
  };
1856
+ return { build, createLazy };
1857
+ };
1858
+
1859
+ const compileFunctionConstruction = (
1860
+ expression: Expression & { kind: "FunctionConstruction" },
1861
+ environment: Environment,
1862
+ ): Evaluator => {
1863
+ const build = getFunctionBuilder(expression, environment).build;
1864
+ const bounds = expression.bounds;
1865
+ if (bounds.length === 1 && bounds[0].pattern.kind === "Name") {
1866
+ const set = getEvaluator(bounds[0].set, environment);
1867
+ return (context) => build(set(context), context);
1868
+ }
1869
+ return (context) => build(getBoundsDomain(bounds, context), context);
1612
1870
  };
1613
1871
 
1614
1872
  const compileExcept = (
@@ -1672,6 +1930,101 @@ const compileExcept = (
1672
1930
  };
1673
1931
  };
1674
1932
 
1933
+ // TLC filters any value it can't enumerate lazily, and fails only when it uses the result.
1934
+ export const getLazyFilter = (
1935
+ expression: Expression & { kind: "SetFilter" },
1936
+ environment: Environment,
1937
+ ) => {
1938
+ const predicate = getEvaluator(expression.predicate, environment);
1939
+ const pattern = expression.bound.pattern;
1940
+ const range = expression.predicate.location.range;
1941
+ const source = range && {
1942
+ names: pattern.kind === "Name" ? pattern.name : pattern.names.join(", "),
1943
+ predicate: formatRange(range),
1944
+ };
1945
+ const predicateNode = describeNode(expression.predicate);
1946
+ const coverage = environment.coverage;
1947
+ // TLC evaluates a lazy set's predicate under the set's node only as it enumerates the set,
1948
+ // and costs each element it tests and each it keeps.
1949
+ const testCovered = (node: number, isMember: boolean, test: () => Value) => {
1950
+ if (!coverage || node === -1) return test();
1951
+ if (!isMember) coverage.secondary[node]++;
1952
+ const value = runAtCoverageNode(coverage, isMember ? -1 : node, test);
1953
+ if (!isMember && value === true) coverage.secondary[node]++;
1954
+ return value;
1955
+ };
1956
+ const createFiltered = (
1957
+ base: Value,
1958
+ context: Context,
1959
+ evaluator: Evaluator,
1960
+ node: number,
1961
+ ): RebindableFilteredSet => ({
1962
+ kind: "FilteredSet",
1963
+ base,
1964
+ test: (element, isMember) => {
1965
+ if (
1966
+ pattern.kind === "Tuple" &&
1967
+ getSequenceElements(element)?.length !== pattern.names.length
1968
+ ) {
1969
+ throw new TlaEvaluationError(
1970
+ `Attempted to check if the value:\n${prettyPrint(formatValue(element))}\nis an element of a set of ${pattern.names.length}-tuples.`,
1971
+ );
1972
+ }
1973
+ const value = testCovered(node, isMember, () =>
1974
+ evaluator(withScope(context, bindPattern(context.scope, pattern, element))),
1975
+ );
1976
+ if (typeof value !== "boolean") {
1977
+ throw new TlaEvaluationError(
1978
+ `${isMember ? "The evaluation of predicate" : "Evaluating predicate"} ${predicateNode} yielded non-Boolean value.`,
1979
+ );
1980
+ }
1981
+ return value;
1982
+ },
1983
+ source,
1984
+ rebind: (tracing) =>
1985
+ createFiltered(
1986
+ base,
1987
+ { ...context, environment: tracing },
1988
+ getEvaluator(expression.predicate, tracing),
1989
+ -1,
1990
+ ),
1991
+ });
1992
+ return (base: Value, context: Context, node = -1) =>
1993
+ createFiltered(base, context, predicate, node);
1994
+ };
1995
+
1996
+ export const expectFilterPredicate = (
1997
+ value: Value,
1998
+ expression: Expression & { kind: "SetFilter" },
1999
+ ) => {
2000
+ if (typeof value !== "boolean") {
2001
+ throw new TlaEvaluationError(
2002
+ `Attempted to evaluate an expression of form {x \\in S : P(x)} when P was ${getKindString(value)}.\n${describeNode(expression.predicate)}`,
2003
+ );
2004
+ }
2005
+ return value;
2006
+ };
2007
+
2008
+ export const getChoiceElements = (
2009
+ base: Value,
2010
+ expression: Expression & { kind: "Choose" },
2011
+ set: Expression,
2012
+ version: TlcVersion,
2013
+ ) => {
2014
+ if (!isSetValue(base) || isOverriddenSet(base)) {
2015
+ throw new TlaEvaluationError(
2016
+ `Attempted to compute the value of an expression of\nform CHOOSE x \\in S: P, but S was not enumerable.\n${describeRange(expression)}`,
2017
+ );
2018
+ }
2019
+ normalizeShallowly(base);
2020
+ return getNormalizedElements(base, set, version);
2021
+ };
2022
+
2023
+ export const createNoChoiceError = (expression: Expression & { kind: "Choose" }) =>
2024
+ new TlaEvaluationError(
2025
+ `Attempted to compute the value of an expression of form\nCHOOSE x \\in S: P, but no element of S satisfied P.\n${describeRange(expression)}`,
2026
+ );
2027
+
1675
2028
  const compileSetComprehension = (
1676
2029
  expression: Expression & { kind: "SetFilter" | "SetMap" | "Choose" },
1677
2030
  environment: Environment,
@@ -1679,38 +2032,25 @@ const compileSetComprehension = (
1679
2032
  if (expression.kind === "SetFilter") {
1680
2033
  const predicate = getEvaluator(expression.predicate, environment);
1681
2034
  const set = getEvaluator(expression.bound.set, environment);
2035
+ const filterLazily = getLazyFilter(expression, environment);
1682
2036
  const pattern = expression.bound.pattern;
1683
- const range = expression.predicate.location.range;
1684
- const source = range && {
1685
- names: pattern.kind === "Name" ? pattern.name : pattern.names.join(", "),
1686
- predicate: formatRange(range),
1687
- };
1688
- const createTest = (evaluator: Evaluator, context: Context) => (element: Value) =>
1689
- expectBoolean(
1690
- evaluator(withScope(context, bindPattern(context.scope, pattern, element))),
1691
- "a set filter predicate",
1692
- );
1693
- const createFiltered = (
1694
- base: Value,
1695
- context: Context,
1696
- evaluator: Evaluator,
1697
- ): RebindableFilteredSet => ({
1698
- kind: "FilteredSet",
1699
- base,
1700
- test: createTest(evaluator, context),
1701
- source,
1702
- rebind: (tracing) =>
1703
- createFiltered(
1704
- base,
1705
- { ...context, environment: tracing },
1706
- getEvaluator(expression.predicate, tracing),
1707
- ),
1708
- });
2037
+ const coverage = environment.coverage;
1709
2038
  return (context) => {
1710
2039
  const base = set(context);
1711
- // TLC filters any value it can't enumerate lazily, and fails only when it uses the result.
1712
- if (!isReducibleSet(base)) return createFiltered(base, context, predicate);
1713
- return createSortedSet(toFiniteSet(base).elements.filter(createTest(predicate, context)));
2040
+ if (!isReducibleSet(base)) return filterLazily(base, context, coverage?.current);
2041
+ const kept: Value[] = [];
2042
+ const visit = (element: Value) => {
2043
+ const value = predicate(withScope(context, bindPattern(context.scope, pattern, element)));
2044
+ if (expectFilterPredicate(value, expression)) addBoundedElement(kept, element);
2045
+ };
2046
+ const elements = base.kind === "Interval" ? base : toFiniteSet(base).elements;
2047
+ forEachElement(elements, visit);
2048
+ if (coverage && coverage.current !== -1) {
2049
+ coverage.secondary[coverage.current] +=
2050
+ (Array.isArray(elements) ? elements.length : elements.high - elements.low + 1) +
2051
+ kept.length;
2052
+ }
2053
+ return createNormalizedSet(kept);
1714
2054
  };
1715
2055
  }
1716
2056
  if (expression.kind === "SetMap") {
@@ -1718,7 +2058,7 @@ const compileSetComprehension = (
1718
2058
  return (context) => {
1719
2059
  const elements: Value[] = [];
1720
2060
  forEachBinding(expression.bounds, context, (scope) => {
1721
- elements.push(mapped(withScope(context, scope)));
2061
+ addBoundedElement(elements, mapped(withScope(context, scope)));
1722
2062
  return false;
1723
2063
  });
1724
2064
  return createEnumeratedSet(elements);
@@ -1728,37 +2068,40 @@ const compileSetComprehension = (
1728
2068
  if (!set) {
1729
2069
  return () => {
1730
2070
  throw new TlaEvaluationError(
1731
- `TLC cannot evaluate an unbounded CHOOSE at ${describeLocation(expression)}`,
2071
+ `TLC attempted to evaluate an unbounded CHOOSE.\nMake sure that the expression is of form CHOOSE x \\in S: P(x).\n${describeRange(expression)}`,
1732
2072
  );
1733
2073
  };
1734
2074
  }
1735
2075
  const body = getEvaluator(expression.body, environment);
1736
2076
  const evaluateSet = getEvaluator(set, environment);
1737
2077
  return (context) => {
1738
- const base = evaluateSet(context);
1739
- if (!isSetValue(base) || isOverriddenSet(base)) {
1740
- throw new TlaEvaluationError(
1741
- `Attempted to compute the value of an expression of\nform CHOOSE x \\in S: P, but S was not enumerable.\n${describeRange(expression)}`,
1742
- );
1743
- }
2078
+ const elements = getChoiceElements(
2079
+ evaluateSet(context),
2080
+ expression,
2081
+ set,
2082
+ context.environment.runtime.version,
2083
+ );
1744
2084
  const chosen = { value: undefined as Value | undefined };
1745
- const elements = getNormalizedElements(base, set, context.environment.runtime.version);
2085
+ const pattern = expression.pattern;
1746
2086
  someElement(elements, (element) => {
1747
- const scope = bindPattern(context.scope, expression.pattern, element);
1748
- if (!expectBoolean(body(withScope(context, scope)), "the body of CHOOSE")) return false;
1749
- chosen.value = getBoundValue(expression.pattern, scope);
2087
+ if (
2088
+ pattern.kind === "Tuple" &&
2089
+ getSequenceElements(element)?.length !== pattern.names.length
2090
+ ) {
2091
+ throw new TlaEvaluationError(
2092
+ `Attempted to compute the value of an expression of form\nCHOOSE <<x1, ... , xN>> \\in S: P, but S was not a set\nof N-tuples.\n${describeRange(expression)}`,
2093
+ );
2094
+ }
2095
+ const scope = bindPattern(context.scope, pattern, element);
2096
+ if (!expectBooleanBody(body(withScope(context, scope)), expression)) return false;
2097
+ chosen.value = getBoundValue(pattern, scope);
1750
2098
  return true;
1751
2099
  });
1752
- if (chosen.value === undefined) {
1753
- throw new TlaEvaluationError(
1754
- `Attempted to compute the value of an expression of form\nCHOOSE x \\in S: P, but no element of S satisfied P.\n${describeRange(expression)}`,
1755
- );
1756
- }
2100
+ if (chosen.value === undefined) throw createNoChoiceError(expression);
1757
2101
  return chosen.value;
1758
2102
  };
1759
2103
  };
1760
2104
 
1761
- // TLC orders a record's fields by name.
1762
2105
  export const getSortedFields = (fields: RecordField[]) =>
1763
2106
  [...fields].sort((left, right) => compareValues(left.name, right.name));
1764
2107
 
@@ -1852,26 +2195,10 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1852
2195
  }
1853
2196
  case "Prime": {
1854
2197
  const inner = getChildEvaluator(expression.expression);
1855
- return (context) => {
1856
- if (!context.next) throw createPrimeOutsideActionError(expression);
1857
- return inner({
1858
- environment: context.environment,
1859
- scope: context.scope,
1860
- state: context.next,
1861
- next: undefined,
1862
- isKeepLazy: context.isKeepLazy,
1863
- });
1864
- };
1865
- }
1866
- case "Unchanged": {
1867
- const primed = getChildEvaluator({
1868
- kind: "Prime",
1869
- expression: expression.expression,
1870
- location: expression.location,
1871
- });
1872
- const current = getChildEvaluator(expression.expression);
1873
- return (context) => valuesEqual(primed(context), current(context));
2198
+ return (context) => inner(toNextContext(context));
1874
2199
  }
2200
+ case "Unchanged":
2201
+ return compileUnchanged(getChildEvaluator(expression.expression));
1875
2202
  case "If": {
1876
2203
  const condition = getChildEvaluator(expression.condition);
1877
2204
  const consequent = getChildEvaluator(expression.consequent);
@@ -1915,8 +2242,15 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1915
2242
  return compileQuantifier(expression, environment);
1916
2243
  case "UnboundedQuantifier":
1917
2244
  return () => {
2245
+ const operator = expression.quantifier === "Forall" ? "\\A" : "\\E";
2246
+ if (expression.isTemporal) {
2247
+ throw createTemporalFormulaError(
2248
+ expression.quantifier === "Forall" ? "\\AA" : "\\EE",
2249
+ expression,
2250
+ );
2251
+ }
1918
2252
  throw new TlaEvaluationError(
1919
- `TLC cannot evaluate an unbounded quantifier at ${describeLocation(expression)}`,
2253
+ `TLC attempted to evaluate an unbounded ${operator}.\nMake sure that the expression is of form ${operator} x \\in S: P(x).\n${describeRange(expression)}`,
1920
2254
  );
1921
2255
  };
1922
2256
  case "Choose":
@@ -1992,16 +2326,18 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1992
2326
  case "BoxAction":
1993
2327
  case "AngleAction": {
1994
2328
  const action = getChildEvaluator(expression.action);
1995
- const unchanged = getChildEvaluator({
1996
- kind: "Unchanged",
1997
- expression: expression.subscript,
1998
- location: expression.location,
1999
- });
2329
+ const unchanged = compileUnchanged(getChildEvaluator(expression.subscript));
2000
2330
  const isBox = expression.kind === "BoxAction";
2001
- return (context) =>
2002
- isBox
2003
- ? expectBoolean(action(context), "an action") || unchanged(context)
2004
- : expectBoolean(action(context), "an action") && !unchanged(context);
2331
+ const form = isBox ? "[A]_e" : "<A>_e";
2332
+ return (context) => {
2333
+ const value = action(context);
2334
+ if (typeof value !== "boolean") {
2335
+ throw new TlaEvaluationError(
2336
+ `Attempted to evaluate an expression of form ${form}, but A was not a boolean.\n${describeRange(expression)}`,
2337
+ );
2338
+ }
2339
+ return isBox ? value || unchanged(context) : value && !unchanged(context);
2340
+ };
2005
2341
  }
2006
2342
  case "Enabled": {
2007
2343
  const action = expression.expression;
@@ -2020,9 +2356,7 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
2020
2356
  case "WeakFairness":
2021
2357
  case "StrongFairness":
2022
2358
  return () => {
2023
- throw new TlaEvaluationError(
2024
- `TLC cannot evaluate a temporal formula in a state at ${describeLocation(expression)}`,
2025
- );
2359
+ throw createTemporalFormulaError(TEMPORAL_FORMS[expression.kind], expression);
2026
2360
  };
2027
2361
  }
2028
2362
  };