tla-ts 0.0.1 → 0.0.3-dev.037ac3b

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 (74) hide show
  1. package/README.md +98 -39
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +225 -30
  4. package/dist/index.d.ts +225 -30
  5. package/dist/index.js +1 -1
  6. package/dist/parallel-worker.cjs +2 -2
  7. package/dist/parallel-worker.js +2 -2
  8. package/dist/parallel.cjs +1 -1
  9. package/dist/parallel.js +2 -2
  10. package/dist/run-cli.cjs +21 -1
  11. package/dist/run-cli.js +21 -1
  12. package/dist/transfer.cjs +400 -39
  13. package/dist/transfer.js +400 -39
  14. package/package.json +6 -2
  15. package/src/ast.ts +213 -6
  16. package/src/bags.ts +161 -71
  17. package/src/builtins.ts +203 -23
  18. package/src/bundled-modules.ts +63 -32
  19. package/src/check.ts +1132 -258
  20. package/src/cli-options.ts +64 -0
  21. package/src/codegen.ts +58 -34
  22. package/src/config.ts +39 -11
  23. package/src/dependencies.ts +2 -2
  24. package/src/environment.ts +557 -153
  25. package/src/errors.ts +66 -1
  26. package/src/evaluate.ts +553 -258
  27. package/src/exit-codes.ts +53 -0
  28. package/src/fingerprints.ts +48 -13
  29. package/src/index.ts +9 -4
  30. package/src/instances.ts +235 -79
  31. package/src/java-overrides.ts +241 -0
  32. package/src/json.ts +153 -72
  33. package/src/levels.ts +850 -0
  34. package/src/lexer.ts +108 -29
  35. package/src/live-check.ts +692 -0
  36. package/src/liveness.ts +71 -596
  37. package/src/obligation-action.ts +384 -0
  38. package/src/obligation-anon.ts +575 -0
  39. package/src/obligation-deref.ts +637 -0
  40. package/src/obligation-expression.ts +1060 -0
  41. package/src/obligation-format.ts +406 -0
  42. package/src/obligation-generate.ts +1074 -0
  43. package/src/obligation-levels.ts +329 -0
  44. package/src/obligation-module.ts +1042 -0
  45. package/src/obligation-printer.ts +889 -0
  46. package/src/obligation-proof.ts +76 -0
  47. package/src/obligation-source.ts +1084 -0
  48. package/src/obligation-tuples.ts +184 -0
  49. package/src/obligations.ts +316 -0
  50. package/src/parallel-worker.ts +186 -201
  51. package/src/parallel.ts +179 -84
  52. package/src/parser.ts +970 -206
  53. package/src/pretty-print.ts +259 -0
  54. package/src/randomization.ts +24 -113
  55. package/src/resolve.ts +483 -51
  56. package/src/run-cli.ts +473 -62
  57. package/src/runtime.ts +65 -28
  58. package/src/spec-description.ts +521 -0
  59. package/src/standard-levels.ts +105 -0
  60. package/src/standard-modules.ts +218 -92
  61. package/src/state-graph.ts +157 -0
  62. package/src/subexpressions.ts +31 -45
  63. package/src/substitution-levels.ts +184 -0
  64. package/src/successors.ts +336 -57
  65. package/src/symmetry.ts +79 -23
  66. package/src/tableau.ts +93 -60
  67. package/src/tlc-ext.ts +148 -44
  68. package/src/tlc-module.ts +71 -66
  69. package/src/tlc-modules.ts +1022 -0
  70. package/src/tlc-order.ts +511 -0
  71. package/src/tlc-random.ts +414 -0
  72. package/src/tlc-summary.ts +124 -0
  73. package/src/transfer.ts +26 -5
  74. package/src/values.ts +1285 -179
package/src/evaluate.ts CHANGED
@@ -1,35 +1,53 @@
1
- import type {
2
- Bound,
3
- BoundPattern,
4
- Definition,
5
- Expression,
6
- FunctionDefinition,
7
- OperatorParam,
8
- RecordField,
1
+ import {
2
+ getChildren,
3
+ isLocallyResolved,
4
+ type Bound,
5
+ type BoundPattern,
6
+ type DecimalExpression,
7
+ type Definition,
8
+ type Expression,
9
+ type FunctionDefinition,
10
+ type NumberExpression,
11
+ type OperatorParam,
12
+ type RecordField,
13
+ type SourceRange,
9
14
  } from "./ast";
15
+ import { getKindString } from "./builtins";
10
16
  import { TlaEvaluationError } from "./errors";
17
+ import { EXIT_STATUS, setExitCode } from "./exit-codes";
11
18
  import { generateEvaluator } from "./codegen";
12
19
  import type { CheckerRuntime } from "./runtime";
13
20
  import { getReadVariables } from "./dependencies";
14
- import { mapChildren, substitutedExpressions } from "./instances";
21
+ import { contextualApplications, mapChildren, substitutedExpressions } from "./instances";
15
22
  import { isEnabled } from "./successors";
16
23
  import {
17
24
  applyFunction,
18
- checkInteger,
25
+ combineHash,
26
+ compareValues,
19
27
  createFunction,
20
- createSet,
28
+ createEnumeratedSet,
21
29
  createSortedFunction,
22
30
  createSortedSet,
31
+ createWrittenRecord,
23
32
  createTuple,
24
33
  formatValue,
34
+ getDomain,
35
+ getFunctionDomain,
36
+ getIntervalElements,
25
37
  getSequenceElements,
26
38
  getValueHash,
27
- isEnumerable,
39
+ isFunctionValue,
40
+ isOverriddenSet,
28
41
  isSameValue,
42
+ markLambdaFunction,
43
+ isReducible,
29
44
  isSetValue,
45
+ MAXIMUM_INTEGER,
46
+ MINIMUM_INTEGER,
30
47
  toFiniteSet,
31
48
  updateFunction,
32
49
  valuesEqual,
50
+ type LazyFunctionSource,
33
51
  type LazyFunctionValue,
34
52
  type Value,
35
53
  } from "./values";
@@ -42,6 +60,7 @@ export interface OperatorValue {
42
60
  arity: number;
43
61
  call: (args: Value[]) => Value;
44
62
  expression?: Expression;
63
+ literalBody?: Value;
45
64
  }
46
65
 
47
66
  export type BuiltinArgument = Value | OperatorValue;
@@ -65,7 +84,7 @@ export interface Closure {
65
84
  scope: Scope | undefined;
66
85
  }
67
86
 
68
- export type Operator = Closure | Builtin | OperatorValue;
87
+ type Operator = Closure | Builtin | OperatorValue;
69
88
 
70
89
  export interface Thunk {
71
90
  kind: "Thunk";
@@ -76,10 +95,7 @@ export interface Thunk {
76
95
  cache: Value | undefined;
77
96
  }
78
97
 
79
- export type Binding =
80
- | { kind: "Value"; value: Value }
81
- | Thunk
82
- | { kind: "Operator"; operator: Operator };
98
+ type Binding = { kind: "Value"; value: Value } | Thunk | { kind: "Operator"; operator: Operator };
83
99
 
84
100
  export interface Scope {
85
101
  name: string;
@@ -111,6 +127,12 @@ export type Evaluator = (context: Context) => Value;
111
127
 
112
128
  type ArgumentBinder = (context: Context) => Binding;
113
129
 
130
+ interface CompiledStep {
131
+ kind: "Field" | "Index";
132
+ name: string;
133
+ args: Evaluator[];
134
+ }
135
+
114
136
  type GlobalName =
115
137
  | { kind: "Variable"; index: number }
116
138
  | { kind: "Value"; value: Value }
@@ -118,9 +140,87 @@ type GlobalName =
118
140
 
119
141
  const EXCEPT_AT = "@";
120
142
 
121
- const describeLocation = (expression: Expression) =>
143
+ export const describeLocation = (expression: Expression) =>
122
144
  `line ${expression.location.line}, column ${expression.location.column}`;
123
145
 
146
+ export const formatRange = (range: SourceRange) =>
147
+ `line ${range.start.line}, col ${range.start.column} to line ${range.end.line}, col ${range.end.column} of module ${range.module}`;
148
+
149
+ export const describeRange = (expression: Expression) => {
150
+ const range = expression.location.range;
151
+ return range ? formatRange(range) : describeLocation(expression);
152
+ };
153
+
154
+ export const getConditionError = (expression: Expression, value: Value) =>
155
+ new TlaEvaluationError(
156
+ `A non-boolean expression (${getKindString(value)}) was used as the condition of an IF.\n${describeRange(expression)}`,
157
+ );
158
+
159
+ // TLC parses an infix chain of /\ as nested binary conjunctions and a bulleted list as one
160
+ // conjunction list, and it words the error differently for each.
161
+ export const getConjunctError = (
162
+ expression: Expression & { kind: "And" | "Or" },
163
+ index: number,
164
+ value: Value,
165
+ ) => {
166
+ const range = expression.location.range;
167
+ const isBulleted =
168
+ range?.start.line === expression.location.line &&
169
+ range.start.column === expression.location.column;
170
+ if (isBulleted || !range) {
171
+ const operand = expression.operands[index];
172
+ // SANY prints a numeral as its value instead of its location.
173
+ const description = operand.kind === "Number" ? String(operand.value) : describeRange(operand);
174
+ return new TlaEvaluationError(
175
+ `A non-boolean expression (${getKindString(value)}) was used as a formula in a conjunction.\n${description}`,
176
+ );
177
+ }
178
+ const end = expression.operands[Math.max(index, 1)].location.range?.end ?? range.end;
179
+ return new TlaEvaluationError(
180
+ `Attempted to evaluate an expression of form P /\\ Q when ${index === 0 ? "P" : "Q"} was\n${getKindString(value)}.\n${describeRange({ ...expression, location: { ...expression.location, range: { ...range, end } } })}`,
181
+ );
182
+ };
183
+
184
+ export const getFieldError =
185
+ (expression: Expression & { kind: "FieldAccess" }) => (record: Value) =>
186
+ `Attempted to select nonexistent field "${expression.field}" from the record\n${formatValue(record)}\n${describeRange(expression)}`;
187
+
188
+ export const getDomainOperator = (expression: Expression) => (value: Value) => {
189
+ if (!isFunctionValue(value)) {
190
+ throw new TlaEvaluationError(
191
+ `Attempted to apply the operator DOMAIN to a non-function\n(${getKindString(value)})\n${describeRange(expression)}`,
192
+ );
193
+ }
194
+ return getDomain(value);
195
+ };
196
+
197
+ export const getSubsetOperator =
198
+ (expression: Expression, builtin: Builtin) => (left: Value, right: Value) => {
199
+ if (!isSetValue(left) || isOverriddenSet(left)) {
200
+ throw new TlaEvaluationError(
201
+ `Attempted to evaluate an expression of form S \\subseteq T, but S was not enumerable.\n${describeRange(expression)}`,
202
+ );
203
+ }
204
+ return builtin.evaluate([left, right]);
205
+ };
206
+
207
+ // TLC rejects a decimal, or an integer literal too big for it, while it processes the spec.
208
+ export const createRealNumberError = (expression: DecimalExpression) =>
209
+ setExitCode(
210
+ new TlaEvaluationError(
211
+ `TLC can't handle real numbers: ${expression.text} at ${describeLocation(expression)}`,
212
+ ),
213
+ EXIT_STATUS.configParseError,
214
+ );
215
+
216
+ export const createBigNumberError = (expression: NumberExpression) =>
217
+ setExitCode(
218
+ new TlaEvaluationError(
219
+ `TLC can't handle a number this big: ${expression.text ?? expression.value} at ${describeLocation(expression)}`,
220
+ ),
221
+ EXIT_STATUS.error,
222
+ );
223
+
124
224
  export const lookupScope = (scope: Scope | undefined, name: string): Binding | undefined => {
125
225
  for (let current = scope; current; current = current.parent) {
126
226
  if (current.name === name) return current.binding;
@@ -134,11 +234,7 @@ export const bindValue = (scope: Scope | undefined, name: string, value: Value):
134
234
  parent: scope,
135
235
  });
136
236
 
137
- export const bindPattern = (
138
- scope: Scope | undefined,
139
- pattern: BoundPattern,
140
- value: Value,
141
- ): Scope => {
237
+ const bindPattern = (scope: Scope | undefined, pattern: BoundPattern, value: Value) => {
142
238
  if (pattern.kind === "Name") return bindValue(scope, pattern.name, value);
143
239
  const elements = getSequenceElements(value);
144
240
  if (!elements || elements.length !== pattern.names.length) {
@@ -149,7 +245,7 @@ export const bindPattern = (
149
245
  return pattern.names.reduce<Scope | undefined>(
150
246
  (current, name, index) => bindValue(current, name, elements[index]),
151
247
  scope,
152
- ) as Scope;
248
+ );
153
249
  };
154
250
 
155
251
  const withScope = (context: Context, scope: Scope | undefined): Context => ({
@@ -168,95 +264,6 @@ export const expectBoolean = (value: Value, description: string) => {
168
264
  return value;
169
265
  };
170
266
 
171
- export const getChildren = (expression: Expression): Expression[] => {
172
- switch (expression.kind) {
173
- case "Number":
174
- case "String":
175
- case "Identifier":
176
- case "OperatorReference":
177
- case "ExceptAt":
178
- return [];
179
- case "Apply":
180
- return expression.args;
181
- case "Lambda":
182
- return [expression.body];
183
- case "And":
184
- case "Or":
185
- return expression.operands;
186
- case "Prime":
187
- case "Unchanged":
188
- case "Enabled":
189
- case "Always":
190
- case "Eventually":
191
- return [expression.expression];
192
- case "If":
193
- return [expression.condition, expression.consequent, expression.alternative];
194
- case "Case":
195
- return [
196
- ...expression.arms.flatMap((arm) => [arm.condition, arm.body]),
197
- ...(expression.other ? [expression.other] : []),
198
- ];
199
- case "Let":
200
- return [
201
- ...expression.definitions.flatMap((definition) =>
202
- definition.kind === "Function"
203
- ? [...definition.bounds.map((bound) => bound.set), definition.body]
204
- : [definition.body],
205
- ),
206
- expression.body,
207
- ];
208
- case "Forall":
209
- case "Exists":
210
- return [...expression.bounds.map((bound) => bound.set), expression.body];
211
- case "UnboundedQuantifier":
212
- return [expression.body];
213
- case "Choose":
214
- return [...(expression.set ? [expression.set] : []), expression.body];
215
- case "SetEnumeration":
216
- case "Tuple":
217
- return expression.elements;
218
- case "SetFilter":
219
- return [expression.bound.set, expression.predicate];
220
- case "SetMap":
221
- return [expression.expression, ...expression.bounds.map((bound) => bound.set)];
222
- case "FunctionConstruction":
223
- return [...expression.bounds.map((bound) => bound.set), expression.body];
224
- case "FunctionSet":
225
- return [expression.domain, expression.range];
226
- case "Record":
227
- case "RecordSet":
228
- return expression.fields.map((field) => field.value);
229
- case "Except":
230
- return [
231
- expression.function,
232
- ...expression.updates.flatMap((update) => [
233
- ...update.path.flatMap((step) => (step.kind === "Index" ? step.args : [])),
234
- update.value,
235
- ]),
236
- ];
237
- case "FunctionApplication":
238
- return [expression.function, ...expression.args];
239
- case "FieldAccess":
240
- return [expression.record];
241
- case "Product":
242
- return expression.factors;
243
- case "BoxAction":
244
- case "AngleAction":
245
- return [expression.action, expression.subscript];
246
- case "WeakFairness":
247
- case "StrongFairness":
248
- return [expression.subscript, expression.action];
249
- case "Label":
250
- return [expression.body];
251
- case "Subexpression":
252
- return expression.selectors.flatMap((selector) => ("args" in selector ? selector.args : []));
253
- }
254
- };
255
-
256
- export const isLocallyResolved = (expression: Expression) =>
257
- (expression.kind === "Identifier" || expression.kind === "Apply") &&
258
- expression.resolution?.kind === "Local";
259
-
260
267
  export const getDefinition = (name: string, environment: Environment) =>
261
268
  environment.definitions.get(environment.substitutions.get(name) ?? name);
262
269
 
@@ -296,13 +303,37 @@ export const isConstantLevel = (definition: Definition, environment: Environment
296
303
  return isConstant;
297
304
  };
298
305
 
306
+ const getBoundExplanation = (set: Value, text: string) => {
307
+ const quantified = `universally (\\A) or existentially (\\E) quantify over ${text}, because this would require checking an\ninfinite number of cases.`;
308
+ if (typeof set === "object" && set.kind === "SequenceSet") {
309
+ return `In TLA+, Seq(S) represents the set of all finite sequences whose elements come from the set S. Even when S\nis a finite set, the number of possible sequences in Seq(S) is unbounded because sequences can have any\nfinite length (e.g., length 0, 1, 2, and so on). As a result, TLC cannot evaluate expressions that\n${quantified} Note that for a finite set of sequences s, TLC handles s \\subseteq Seq(S).\nSee https://explain.tlapl.us/seq-unenumerable for additional details.`;
310
+ }
311
+ if (
312
+ typeof set === "object" &&
313
+ set.kind === "InfiniteSet" &&
314
+ set.name !== "STRING" &&
315
+ set.name !== "Any"
316
+ ) {
317
+ return `The set ${set.name} contains infinitely many elements. As a result, TLC cannot evaluate expressions that\n${quantified} Note that TLC handles set membership like T \\subseteq ${set.name} for any finite set T.`;
318
+ }
319
+ return undefined;
320
+ };
321
+
322
+ // TLC enumerates every set except the ones it implements in Java, so any other set fails as its own
323
+ // class does.
299
324
  export const getEnumeratedElements = (set: Value, expression: Expression) => {
300
- if (!isEnumerable(set)) {
325
+ if (!isSetValue(set) || isOverriddenSet(set)) {
326
+ const text = formatValue(set);
327
+ const explanation = getBoundExplanation(set, text);
301
328
  throw new TlaEvaluationError(
302
- `TLC encountered a non-enumerable quantifier bound ${formatValue(set)} at ${describeLocation(expression)}`,
329
+ explanation === undefined
330
+ ? `TLC encountered a non-enumerable quantifier bound\n${text}.\n${describeRange(expression)}`
331
+ : `TLC encountered the non-enumerable quantifier bound\n${text}\n${describeRange(expression)}\n${explanation}`,
303
332
  );
304
333
  }
305
- return toFiniteSet(set).elements;
334
+ return typeof set === "object" && set.kind === "Interval"
335
+ ? getIntervalElements(set)
336
+ : toFiniteSet(set).elements;
306
337
  };
307
338
 
308
339
  export const forEachBinding = (
@@ -336,14 +367,66 @@ export const bindArgument = (bounds: Bound[], scope: Scope | undefined, argument
336
367
  );
337
368
  };
338
369
 
370
+ // TLC prints a function it can't enumerate as its parameters and the location of its body. It
371
+ // prints only the first name of a group such as `m, n \in S`.
372
+ interface LazyFunctionTemplate {
373
+ parameters: { index: number; name: string }[];
374
+ body: string;
375
+ }
376
+
377
+ const lazyFunctionTemplates = new WeakMap<Expression, LazyFunctionTemplate>();
378
+
379
+ const getLazyFunctionTemplate = (bounds: Bound[], body: Expression) => {
380
+ const cached = lazyFunctionTemplates.get(body);
381
+ if (cached) return cached;
382
+ const range = body.location.range;
383
+ if (!range) return undefined;
384
+ const template = {
385
+ parameters: bounds.flatMap((bound, index) =>
386
+ index > 0 && bounds[index - 1].set === bound.set
387
+ ? []
388
+ : [
389
+ {
390
+ index,
391
+ name:
392
+ bound.pattern.kind === "Name"
393
+ ? bound.pattern.name
394
+ : `<<${bound.pattern.names.join(", ")}>>`,
395
+ },
396
+ ],
397
+ ),
398
+ body: formatRange(range),
399
+ };
400
+ lazyFunctionTemplates.set(body, template);
401
+ return template;
402
+ };
403
+
404
+ const getLazyFunctionSource = (bounds: Bound[], body: Expression, domain: Value) => {
405
+ const template = getLazyFunctionTemplate(bounds, body);
406
+ if (!template) return undefined;
407
+ const domains =
408
+ bounds.length > 1 && typeof domain === "object" && domain.kind === "ProductSet"
409
+ ? domain.factors
410
+ : [domain];
411
+ return {
412
+ parameters: template.parameters.map((parameter) => ({
413
+ name: parameter.name,
414
+ domain: domains[parameter.index],
415
+ })),
416
+ body: template.body,
417
+ };
418
+ };
419
+
339
420
  const createLazyFunction = (
340
421
  domain: Value,
341
422
  compute: (argument: Value, self: LazyFunctionValue) => Value,
342
- ): LazyFunctionValue => {
423
+ source: LazyFunctionSource | undefined,
424
+ ) => {
343
425
  const memo = new Map<number, Value[]>();
344
426
  const self: LazyFunctionValue = {
345
427
  kind: "LazyFunction",
346
428
  domain,
429
+ source,
347
430
  apply: (argument) => {
348
431
  const hash = getValueHash(argument);
349
432
  const bucket = memo.get(hash);
@@ -362,18 +445,29 @@ const createLazyFunction = (
362
445
  return self;
363
446
  };
364
447
 
365
- const createRecursiveFunction = (definition: FunctionDefinition, context: Context) =>
366
- createLazyFunction(getBoundsDomain(definition.bounds, context), (argument, self) =>
367
- evaluate(
368
- definition.body,
369
- withScope(
370
- context,
371
- bindArgument(definition.bounds, bindValue(undefined, definition.name, self), argument),
448
+ const createRecursiveFunction = (definition: FunctionDefinition, context: Context) => {
449
+ const domain = getBoundsDomain(definition.bounds, context);
450
+ const functionValue = createLazyFunction(
451
+ domain,
452
+ (argument, self) =>
453
+ evaluate(
454
+ definition.body,
455
+ withScope(
456
+ context,
457
+ bindArgument(definition.bounds, bindValue(undefined, definition.name, self), argument),
458
+ ),
372
459
  ),
373
- ),
460
+ getLazyFunctionSource(definition.bounds, definition.body, domain),
374
461
  );
462
+ return definition.bounds.length === 1 ? markLambdaFunction(functionValue) : functionValue;
463
+ };
464
+
465
+ const evaluateDefinitionBody = (definition: Definition, context: Context) =>
466
+ definition.kind === "Function"
467
+ ? createRecursiveFunction(definition, context)
468
+ : evaluate(definition.body, context);
375
469
 
376
- const evaluateDefinitionValue = (definition: Definition, context: Context): Value => {
470
+ const evaluateDefinitionValue = (definition: Definition, context: Context) => {
377
471
  const isConstant = isConstantLevel(definition, context.environment);
378
472
  const cached = isConstant ? context.environment.definitionValues.get(definition) : undefined;
379
473
  if (cached !== undefined) return cached;
@@ -383,11 +477,11 @@ const evaluateDefinitionValue = (definition: Definition, context: Context): Valu
383
477
  );
384
478
  }
385
479
  const topLevel = withScope(context, undefined);
386
- const value =
387
- definition.kind === "Function"
388
- ? createRecursiveFunction(definition, topLevel)
389
- : evaluate(definition.body, topLevel);
390
- if (isConstant) context.environment.definitionValues.set(definition, value);
480
+ if (!isConstant) return evaluateDefinitionBody(definition, topLevel);
481
+ const value = context.environment.runtime.evaluateAtStartup(() =>
482
+ evaluateDefinitionBody(definition, topLevel),
483
+ );
484
+ context.environment.definitionValues.set(definition, value);
391
485
  return value;
392
486
  };
393
487
 
@@ -477,11 +571,7 @@ const evaluateOperatorArgument = (expression: Expression, context: Context): Ope
477
571
  return operator;
478
572
  };
479
573
 
480
- export const callOperatorWithValues = (
481
- operator: Operator,
482
- args: Value[],
483
- context: Context,
484
- ): Value => {
574
+ const callOperatorWithValues = (operator: Operator, args: Value[], context: Context): Value => {
485
575
  if (operator.kind === "Builtin") return operator.evaluate(args, context);
486
576
  if (operator.kind === "Operator") return operator.call(args);
487
577
  const scope = operator.params.reduce<Scope | undefined>(
@@ -499,6 +589,11 @@ const toOperatorValue = (operator: Operator, context: Context): OperatorValue =>
499
589
  name: operator.name,
500
590
  arity: getArity(operator),
501
591
  call: (args) => callOperatorWithValues(operator, args, context),
592
+ literalBody:
593
+ operator.kind === "Closure" &&
594
+ (operator.body.kind === "Number" || operator.body.kind === "String")
595
+ ? operator.body.value
596
+ : undefined,
502
597
  };
503
598
 
504
599
  const isOperatorArgument = (expression: Expression, context: Context) => {
@@ -551,7 +646,9 @@ const compileArgumentBinder = (argument: Expression, environment: Environment):
551
646
  if (global === undefined) {
552
647
  return (context) => {
553
648
  const binding = lookupScope(context.scope, argument.name);
554
- return binding?.kind === "Value" ? binding : createThunk(argument, context);
649
+ return binding?.kind === "Value" || binding?.kind === "Thunk"
650
+ ? binding
651
+ : createThunk(argument, context);
555
652
  };
556
653
  }
557
654
  }
@@ -590,7 +687,7 @@ export const bindOperatorArguments = (
590
687
  return scope;
591
688
  };
592
689
 
593
- const callOperator = (operator: Operator, args: Expression[], context: Context): Value => {
690
+ const callOperator = (operator: Operator, args: Expression[], context: Context) => {
594
691
  if (operator.kind === "Closure") {
595
692
  return evaluate(
596
693
  operator.body,
@@ -609,7 +706,11 @@ const callOperator = (operator: Operator, args: Expression[], context: Context):
609
706
  );
610
707
  };
611
708
 
612
- export const bindDefinitions = (definitions: Definition[], context: Context): Scope | undefined =>
709
+ export const bindDefinitions = (
710
+ definitions: Definition[],
711
+ context: Context,
712
+ reevaluated?: ReadonlySet<Definition>,
713
+ ): Scope | undefined =>
613
714
  definitions.reduce<Scope | undefined>((scope, definition) => {
614
715
  const node: Scope = {
615
716
  name: definition.name,
@@ -633,7 +734,7 @@ export const bindDefinitions = (definitions: Definition[], context: Context): Sc
633
734
  };
634
735
  return node;
635
736
  }
636
- if (definition.params.length > 0) {
737
+ if (definition.params.length > 0 || reevaluated?.has(definition)) {
637
738
  node.binding = {
638
739
  kind: "Operator",
639
740
  operator: {
@@ -670,11 +771,7 @@ const evaluateLocalIdentifier = (name: string, expression: Expression, context:
670
771
  const global = findGlobalName(name, context.environment);
671
772
  if (global?.kind === "Variable") {
672
773
  const value = context.state?.[global.index];
673
- if (value === undefined) {
674
- throw new TlaEvaluationError(
675
- `The variable ${name} is not assigned at ${describeLocation(expression)}`,
676
- );
677
- }
774
+ if (value === undefined) throw createUnassignedError(name, expression);
678
775
  return value;
679
776
  }
680
777
  if (global?.kind === "Value") return global.value;
@@ -684,10 +781,10 @@ const evaluateLocalIdentifier = (name: string, expression: Expression, context:
684
781
  throw new TlaEvaluationError(`Unknown identifier ${name} at ${describeLocation(expression)}`);
685
782
  };
686
783
 
687
- const isTlcInteger = (value: number) =>
688
- Number.isInteger(value) && value <= 2147483647 && value >= -2147483648;
784
+ export const isTlcInteger = (value: number) =>
785
+ Number.isInteger(value) && value <= MAXIMUM_INTEGER && value >= MINIMUM_INTEGER;
689
786
 
690
- export const IMPURE_BUILTINS = new Set([
787
+ const IMPURE_BUILTINS = new Set([
691
788
  "Print",
692
789
  "PrintT",
693
790
  "Assert",
@@ -700,6 +797,85 @@ export const IMPURE_BUILTINS = new Set([
700
797
  export const isImpureBuiltin = (name: string, environment: Environment) =>
701
798
  IMPURE_BUILTINS.has(name) || environment.builtins.get(name)?.isStateLevel === true;
702
799
 
800
+ interface Impurity {
801
+ builtins: Set<string>;
802
+ definitions: WeakMap<Definition, boolean>;
803
+ }
804
+
805
+ const ANY_EFFECT: Impurity = { builtins: IMPURE_BUILTINS, definitions: new WeakMap() };
806
+
807
+ // An Assert that held holds again, so evaluating it twice looks the same as evaluating it once.
808
+ const REPEATED_EFFECT: Impurity = {
809
+ builtins: new Set([...IMPURE_BUILTINS].filter((name) => name !== "Assert")),
810
+ definitions: new WeakMap(),
811
+ };
812
+
813
+ const isEvaluatedOnce = (definition: Definition, environment: Environment) =>
814
+ definition.kind === "Operator" &&
815
+ definition.params.length === 0 &&
816
+ isConstantLevel(definition, environment);
817
+
818
+ const callsImpureBuiltin = (
819
+ expression: Expression,
820
+ environment: Environment,
821
+ impurity: Impurity,
822
+ ): boolean => {
823
+ const name =
824
+ expression.kind === "Identifier"
825
+ ? expression.name
826
+ : expression.kind === "Apply" || expression.kind === "OperatorReference"
827
+ ? expression.operator
828
+ : undefined;
829
+ if (name !== undefined && !isLocallyResolved(expression)) {
830
+ const definition = getDefinition(name, environment);
831
+ const isImpureCall =
832
+ impurity.builtins.has(name) || environment.builtins.get(name)?.isStateLevel === true;
833
+ if (!definition && isImpureCall) return true;
834
+ if (
835
+ definition &&
836
+ !isEvaluatedOnce(definition, environment) &&
837
+ isImpureDefinition(definition, environment, impurity)
838
+ ) {
839
+ return true;
840
+ }
841
+ }
842
+ return getChildren(expression).some((child) => callsImpureBuiltin(child, environment, impurity));
843
+ };
844
+
845
+ // TLC evaluates a constant definition without parameters once, so only other definitions pass
846
+ // on the side effects and random choices of the builtins they call.
847
+ const isImpureDefinition = (
848
+ definition: Definition,
849
+ environment: Environment,
850
+ impurity = ANY_EFFECT,
851
+ ): boolean => {
852
+ const cached = impurity.definitions.get(definition);
853
+ if (cached !== undefined) return cached;
854
+ impurity.definitions.set(definition, false);
855
+ const isImpure =
856
+ callsImpureBuiltin(definition.body, environment, impurity) ||
857
+ (definition.kind === "Function" &&
858
+ definition.bounds.some((bound) => callsImpureBuiltin(bound.set, environment, impurity)));
859
+ impurity.definitions.set(definition, isImpure);
860
+ return isImpure;
861
+ };
862
+
863
+ // TLC's next-state generator does not bind LET definitions to values, so each reference to one
864
+ // that calls an impure builtin evaluates it again.
865
+ export const getReevaluatedDefinitions = (definitions: Definition[], environment: Environment) =>
866
+ new Set(definitions.filter((definition) => isImpureDefinition(definition, environment)));
867
+
868
+ export const isImpure = (environment: Environment) =>
869
+ [...environment.definitions.values()].some((definition) =>
870
+ isImpureDefinition(definition, environment),
871
+ );
872
+
873
+ // Whether evaluating a definition again can show, such as by printing twice.
874
+ export const hasRepeatedEffects = (environment: Environment) =>
875
+ [...environment.definitions.values()].some((definition) =>
876
+ isImpureDefinition(definition, environment, REPEATED_EFFECT),
877
+ );
878
+
703
879
  const closedConstants = new WeakMap<Expression, boolean>();
704
880
 
705
881
  export const isClosedConstant = (expression: Expression, environment: Environment): boolean => {
@@ -742,7 +918,7 @@ const isClosedIn = (
742
918
  expression: Expression,
743
919
  environment: Environment,
744
920
  bound: ReadonlySet<string>,
745
- ): boolean =>
921
+ ) =>
746
922
  bound.size === 0
747
923
  ? isClosedConstant(expression, environment)
748
924
  : computeIsClosedConstant(expression, environment, bound);
@@ -760,28 +936,24 @@ const computeIsClosedConstant = (
760
936
  if (expression.kind === "Identifier") {
761
937
  const global = findGlobalName(expression.name, environment);
762
938
  if (global?.kind === "Value") return true;
763
- return (
764
- global?.kind === "Definition" &&
765
- global.definition.kind === "Operator" &&
766
- global.definition.params.length === 0 &&
767
- isConstantLevel(global.definition, environment)
768
- );
939
+ return global?.kind === "Definition" && isEvaluatedOnce(global.definition, environment);
769
940
  }
770
941
  if (expression.kind === "Apply") {
771
942
  if (isImpureBuiltin(expression.operator, environment) || expression.operator === "~>") {
772
943
  return false;
773
944
  }
774
945
  const operator = resolveGlobalOperator(expression.operator, environment);
775
- const isPure =
776
- operator?.kind === "Builtin" ||
777
- (operator?.kind === "Closure" &&
778
- (() => {
779
- const definition = environment.definitions.get(
780
- environment.substitutions.get(expression.operator) ?? expression.operator,
781
- );
782
- return definition !== undefined && isConstantLevel(definition, environment);
783
- })());
784
- if (!isPure || operator === undefined) return false;
946
+ if (operator?.kind !== "Builtin" && operator?.kind !== "Closure") return false;
947
+ if (operator.kind === "Closure") {
948
+ const definition = getDefinition(expression.operator, environment);
949
+ if (
950
+ !definition ||
951
+ !isConstantLevel(definition, environment) ||
952
+ isImpureDefinition(definition, environment)
953
+ ) {
954
+ return false;
955
+ }
956
+ }
785
957
  const params = operator.kind === "Closure" ? operator.params : [];
786
958
  const hasOperatorArgument = params.some((param) => param.arity > 0);
787
959
  if (hasOperatorArgument) return false;
@@ -855,7 +1027,7 @@ export const getEvaluator = (expression: Expression, environment: Environment):
855
1027
 
856
1028
  const entryEvaluators = new WeakMap<Expression, Evaluator>();
857
1029
 
858
- const getEntryEvaluator = (expression: Expression, environment: Environment): Evaluator => {
1030
+ export const getEntryEvaluator = (expression: Expression, environment: Environment) => {
859
1031
  const cached = entryEvaluators.get(expression);
860
1032
  if (cached) return cached;
861
1033
  const evaluator =
@@ -879,11 +1051,7 @@ const compileIdentifier = (
879
1051
  const index = global.index;
880
1052
  return (context) => {
881
1053
  const value = context.state?.[index];
882
- if (value === undefined) {
883
- throw new TlaEvaluationError(
884
- `The variable ${name} is not assigned at ${describeLocation(expression)}`,
885
- );
886
- }
1054
+ if (value === undefined) throw createUnassignedError(name, expression);
887
1055
  return value;
888
1056
  };
889
1057
  }
@@ -1031,18 +1199,79 @@ export const compileArgumentScope = (
1031
1199
  };
1032
1200
  };
1033
1201
 
1202
+ interface MemoizedCall {
1203
+ args: Value[];
1204
+ value: Value;
1205
+ }
1206
+
1207
+ const MEMOIZED_CALL_LIMIT = 1 << 16;
1208
+
1209
+ const callMemos = new WeakMap<Closure, { calls: Map<number, MemoizedCall[]>; size: number }>();
1210
+
1211
+ const getCallMemo = (closure: Closure) => {
1212
+ const cached = callMemos.get(closure);
1213
+ if (cached) return cached;
1214
+ const memo = { calls: new Map<number, MemoizedCall[]>(), size: 0 };
1215
+ callMemos.set(closure, memo);
1216
+ return memo;
1217
+ };
1218
+
1219
+ const getArgumentValues = (scope: Scope | undefined, arity: number) => {
1220
+ const values: Value[] = [];
1221
+ for (let current = scope; values.length < arity; current = current?.parent) {
1222
+ if (current?.binding.kind !== "Value") return undefined;
1223
+ values.push(current.binding.value);
1224
+ }
1225
+ return values;
1226
+ };
1227
+
1228
+ const isSameArguments = (left: Value[], right: Value[]) =>
1229
+ left.every((value, index) => isSameValue(value, right[index]));
1230
+
1231
+ // A constant-level operator without side effects yields the same value for the same arguments,
1232
+ // so its calls with evaluated arguments share one result.
1233
+ const isMemoizable = (expression: Expression & { kind: "Apply" }, environment: Environment) => {
1234
+ const definition = getDefinition(expression.operator, environment);
1235
+ return (
1236
+ definition?.kind === "Operator" &&
1237
+ definition.params.length > 0 &&
1238
+ definition.params.every((param) => param.arity === 0) &&
1239
+ isConstantLevel(definition, environment) &&
1240
+ !isImpureDefinition(definition, environment)
1241
+ );
1242
+ };
1243
+
1034
1244
  const compileClosureCall = (
1035
1245
  closure: Closure,
1036
1246
  args: Expression[],
1037
1247
  environment: Environment,
1248
+ isMemoized: boolean,
1038
1249
  ): Evaluator => {
1039
1250
  const bindArguments = compileArgumentScope(closure, args, environment);
1040
1251
  const compiled = { body: undefined as Evaluator | undefined };
1041
- return (context) => {
1042
- const scope = bindArguments(context);
1252
+ const evaluateBody = (scope: Scope | undefined, context: Context) => {
1043
1253
  compiled.body ??= getEntryEvaluator(closure.body, environment);
1044
1254
  return compiled.body({ environment, scope, state: context.state, next: context.next });
1045
1255
  };
1256
+ if (!isMemoized) return (context) => evaluateBody(bindArguments(context), context);
1257
+ const memo = getCallMemo(closure);
1258
+ return (context) => {
1259
+ const scope = bindArguments(context);
1260
+ const values = getArgumentValues(scope, args.length);
1261
+ if (!values) return evaluateBody(scope, context);
1262
+ let hash = values.length;
1263
+ for (const value of values) hash = combineHash(hash, getValueHash(value));
1264
+ const bucket = memo.calls.get(hash);
1265
+ const known = bucket?.find((call) => isSameArguments(call.args, values));
1266
+ if (known) return known.value;
1267
+ const value = evaluateBody(scope, context);
1268
+ if (memo.size < MEMOIZED_CALL_LIMIT) {
1269
+ memo.size++;
1270
+ if (bucket) bucket.push({ args: values, value });
1271
+ else memo.calls.set(hash, [{ args: values, value }]);
1272
+ }
1273
+ return value;
1274
+ };
1046
1275
  };
1047
1276
 
1048
1277
  const compileApply = (
@@ -1065,7 +1294,29 @@ const compileApply = (
1065
1294
  const global = isLocallyResolved(expression)
1066
1295
  ? undefined
1067
1296
  : resolveGlobalOperator(expression.operator, environment);
1068
- if (global?.kind === "Closure") return compileClosureCall(global, args, environment);
1297
+ if (global?.kind === "Closure") {
1298
+ return compileClosureCall(global, args, environment, isMemoizable(expression, environment));
1299
+ }
1300
+ if (global?.kind === "Builtin" && global.name === "DOMAIN") {
1301
+ const operand = getEvaluator(args[0], environment);
1302
+ const domain = getDomainOperator(expression);
1303
+ return (context) => domain(operand(context));
1304
+ }
1305
+ // TLC sorts the value of a constant TLCEval argument only where no context binds a name.
1306
+ if (global?.kind === "Builtin" && global.name === "TLCEval" && args.length === 1) {
1307
+ const operand = getEvaluator(args[0], environment);
1308
+ if (contextualApplications.has(expression) || isStateDependent(args[0], environment)) {
1309
+ return operand;
1310
+ }
1311
+ return (context) =>
1312
+ context.scope === undefined ? global.evaluate([operand(context)]) : operand(context);
1313
+ }
1314
+ if (global?.kind === "Builtin" && global.name === "\\subseteq" && args.length === 2) {
1315
+ const left = getEvaluator(args[0], environment);
1316
+ const right = getEvaluator(args[1], environment);
1317
+ const subset = getSubsetOperator(expression, global);
1318
+ return (context) => subset(left(context), right(context));
1319
+ }
1069
1320
  if (global?.kind === "Builtin") return compileBuiltinCall(global, args, environment);
1070
1321
  return (context) => {
1071
1322
  const operator = resolveOperator(expression.operator, context);
@@ -1134,7 +1385,7 @@ const compileQuantifier = (
1134
1385
  };
1135
1386
  };
1136
1387
 
1137
- const lookupKey = (pattern: BoundPattern, scope: Scope | undefined): Value | undefined => {
1388
+ const lookupKey = (pattern: BoundPattern, scope: Scope | undefined) => {
1138
1389
  if (pattern.kind === "Tuple") {
1139
1390
  return createTuple(
1140
1391
  pattern.names.map((name) => {
@@ -1147,10 +1398,21 @@ const lookupKey = (pattern: BoundPattern, scope: Scope | undefined): Value | und
1147
1398
  return binding?.kind === "Value" ? binding.value : undefined;
1148
1399
  };
1149
1400
 
1401
+ // TLC keeps a function constructor lazy when it is the function of an application, or the base of
1402
+ // an EXCEPT that is, so it evaluates the body only at the arguments it is applied to.
1403
+ const keptLazyExpressions = new WeakSet<Expression>();
1404
+
1405
+ export const keepLazy = (expression: Expression) => {
1406
+ if (expression.kind === "FunctionConstruction" || expression.kind === "Except") {
1407
+ keptLazyExpressions.add(expression);
1408
+ }
1409
+ };
1410
+
1150
1411
  const compileFunctionConstruction = (
1151
1412
  expression: Expression & { kind: "FunctionConstruction" },
1152
1413
  environment: Environment,
1153
1414
  ): Evaluator => {
1415
+ const isKeptLazy = keptLazyExpressions.has(expression);
1154
1416
  const body = getEvaluator(expression.body, environment);
1155
1417
  const bounds = expression.bounds;
1156
1418
  const bound = bounds[0];
@@ -1158,17 +1420,28 @@ const compileFunctionConstruction = (
1158
1420
  const set = getEvaluator(bound.set, environment);
1159
1421
  return (context) => {
1160
1422
  const domain = isSingleName ? set(context) : getBoundsDomain(bounds, context);
1161
- if (expression.isRecursive || !isEnumerable(domain)) {
1162
- return createLazyFunction(domain, (argument) =>
1163
- body(withScope(context, bindArgument(bounds, context.scope, argument))),
1423
+ // TLC builds the function only when it reduces every domain, and evaluates the body lazily
1424
+ // otherwise.
1425
+ const domains =
1426
+ typeof domain === "object" && domain.kind === "ProductSet" && bounds.length > 1
1427
+ ? domain.factors
1428
+ : [domain];
1429
+ if (expression.isRecursive || isKeptLazy || !domains.every(isReducible)) {
1430
+ const functionValue = createLazyFunction(
1431
+ domain,
1432
+ (argument) => body(withScope(context, bindArgument(bounds, context.scope, argument))),
1433
+ getLazyFunctionSource(bounds, expression.body, domain),
1164
1434
  );
1435
+ return bounds.length === 1 ? markLambdaFunction(functionValue) : functionValue;
1165
1436
  }
1166
1437
  if (isSingleName && bound.pattern.kind === "Name") {
1167
1438
  const name = bound.pattern.name;
1168
- const keys = toFiniteSet(domain).elements;
1169
- return createSortedFunction(
1170
- keys,
1171
- keys.map((key) => body(withScope(context, bindValue(context.scope, name, key)))),
1439
+ const keys = getFunctionDomain(domain);
1440
+ return markLambdaFunction(
1441
+ createSortedFunction(
1442
+ keys,
1443
+ keys.map((key) => body(withScope(context, bindValue(context.scope, name, key)))),
1444
+ ),
1172
1445
  );
1173
1446
  }
1174
1447
  const pairs: [Value, Value][] = [];
@@ -1188,21 +1461,22 @@ const compileExcept = (
1188
1461
  expression: Expression & { kind: "Except" },
1189
1462
  environment: Environment,
1190
1463
  ): Evaluator => {
1191
- const fn = getEvaluator(expression.function, environment);
1464
+ const isKeptLazy = keptLazyExpressions.has(expression);
1465
+ if (isKeptLazy) keepLazy(expression.function);
1466
+ const evaluateFunction = getEvaluator(expression.function, environment);
1192
1467
  const updates = expression.updates.map((update) => ({
1193
- path: update.path.map((step) =>
1468
+ path: update.path.map((step): CompiledStep =>
1194
1469
  step.kind === "Field"
1195
- ? { kind: "Field" as const, name: step.name, args: [] as Evaluator[] }
1470
+ ? { kind: "Field", name: step.name, args: [] }
1196
1471
  : {
1197
- kind: "Index" as const,
1472
+ kind: "Index",
1198
1473
  name: "",
1199
1474
  args: step.args.map((arg) => getEvaluator(arg, environment)),
1200
1475
  },
1201
1476
  ),
1202
1477
  value: getEvaluator(update.value, environment),
1203
1478
  }));
1204
- type CompiledStep = (typeof updates)[number]["path"][number];
1205
- const getKey = (step: CompiledStep, context: Context): Value => {
1479
+ const getKey = (step: CompiledStep, context: Context) => {
1206
1480
  if (step.kind === "Field") return step.name;
1207
1481
  if (step.args.length === 1) return step.args[0](context);
1208
1482
  return createTuple(step.args.map((arg) => arg(context)));
@@ -1217,12 +1491,15 @@ const compileExcept = (
1217
1491
  if (depth === path.length) {
1218
1492
  return value(withScope(context, bindValue(context.scope, EXCEPT_AT, current)));
1219
1493
  }
1220
- return updateFunction(current, getKey(path[depth], context), (previous) =>
1221
- update(previous, path, depth + 1, context, value),
1494
+ return updateFunction(
1495
+ current,
1496
+ getKey(path[depth], context),
1497
+ (previous) => update(previous, path, depth + 1, context, value),
1498
+ isKeptLazy && depth === 0,
1222
1499
  );
1223
1500
  };
1224
1501
  return (context) => {
1225
- let current = fn(context);
1502
+ let current = evaluateFunction(context);
1226
1503
  for (const item of updates) current = update(current, item.path, 0, context, item.value);
1227
1504
  return current;
1228
1505
  };
@@ -1243,9 +1520,7 @@ const compileSetComprehension = (
1243
1520
  predicate(withScope(context, bindPattern(context.scope, pattern, element))),
1244
1521
  "a set filter predicate",
1245
1522
  );
1246
- const isReducible =
1247
- typeof base === "object" && (base.kind === "Set" || base.kind === "Interval");
1248
- if (!isReducible) {
1523
+ if (!isReducible(base)) {
1249
1524
  if (isSetValue(base)) return { kind: "FilteredSet", base, test };
1250
1525
  throw new TlaEvaluationError(
1251
1526
  `TLC encountered a non-enumerable quantifier bound ${formatValue(base)} at ${describeLocation(expression.bound.set)}`,
@@ -1262,7 +1537,7 @@ const compileSetComprehension = (
1262
1537
  elements.push(mapped(withScope(context, scope)));
1263
1538
  return false;
1264
1539
  });
1265
- return createSet(elements);
1540
+ return createEnumeratedSet(elements);
1266
1541
  };
1267
1542
  }
1268
1543
  const set = expression.set;
@@ -1284,18 +1559,31 @@ const compileSetComprehension = (
1284
1559
  });
1285
1560
  if (chosen.value === undefined) {
1286
1561
  throw new TlaEvaluationError(
1287
- `Attempted to compute CHOOSE x \\in S : P, but no element of S satisfies P at ${describeLocation(expression)}`,
1562
+ `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)}`,
1288
1563
  );
1289
1564
  }
1290
1565
  return chosen.value;
1291
1566
  };
1292
1567
  };
1293
1568
 
1294
- const compileRecord = (recordFields: RecordField[], environment: Environment): Evaluator => {
1295
- const fields = [...recordFields].sort((left, right) => (left.name < right.name ? -1 : 1));
1296
- const hasDuplicates = fields.some(
1297
- (field, index) => index > 0 && fields[index - 1].name === field.name,
1569
+ // TLC orders a record's fields by name.
1570
+ export const getSortedFields = (fields: RecordField[]) =>
1571
+ [...fields].sort((left, right) => compareValues(left.name, right.name));
1572
+
1573
+ export const hasDuplicateFields = (sortedFields: RecordField[]) =>
1574
+ sortedFields.some((field, index) => index > 0 && sortedFields[index - 1].name === field.name);
1575
+
1576
+ export const createUnassignedError = (name: string, expression: Expression) =>
1577
+ new TlaEvaluationError(`The variable ${name} is not assigned at ${describeLocation(expression)}`);
1578
+
1579
+ export const createPrimeOutsideActionError = (expression: Expression) =>
1580
+ new TlaEvaluationError(
1581
+ `A primed expression appears outside an action at ${describeLocation(expression)}`,
1298
1582
  );
1583
+
1584
+ const compileRecord = (recordFields: RecordField[], environment: Environment): Evaluator => {
1585
+ const fields = getSortedFields(recordFields);
1586
+ const hasDuplicates = hasDuplicateFields(fields);
1299
1587
  const values = fields.map((field) => getEvaluator(field.value, environment));
1300
1588
  if (hasDuplicates) {
1301
1589
  return (context) =>
@@ -1303,7 +1591,16 @@ const compileRecord = (recordFields: RecordField[], environment: Environment): E
1303
1591
  fields.map((field, index): [Value, Value] => [field.name, values[index](context)]),
1304
1592
  );
1305
1593
  }
1306
- const names: Value[] = fields.map((field) => field.name);
1594
+ const names = fields.map((field) => field.name);
1595
+ const writtenNames = recordFields.map((field) => field.name);
1596
+ if (writtenNames.some((name, index) => name !== names[index])) {
1597
+ return (context) =>
1598
+ createWrittenRecord(
1599
+ names,
1600
+ values.map((value) => value(context)),
1601
+ writtenNames,
1602
+ );
1603
+ }
1307
1604
  return (context) =>
1308
1605
  createSortedFunction(
1309
1606
  names,
@@ -1311,25 +1608,21 @@ const compileRecord = (recordFields: RecordField[], environment: Environment): E
1311
1608
  );
1312
1609
  };
1313
1610
 
1314
- const createUnchanged = (expression: Expression, location: Expression["location"]): Expression => ({
1315
- kind: "Unchanged",
1316
- expression,
1317
- location,
1318
- });
1319
-
1320
- const throwing =
1321
- (createError: () => Error): Evaluator =>
1322
- () => {
1323
- throw createError();
1324
- };
1325
-
1326
1611
  const compile = (expression: Expression, environment: Environment): Evaluator => {
1327
1612
  const child = (node: Expression) => getEvaluator(node, environment);
1328
1613
  switch (expression.kind) {
1329
1614
  case "Number": {
1330
1615
  const value = expression.value;
1331
- return isTlcInteger(value) ? () => value : () => checkInteger(value);
1616
+ return isTlcInteger(value)
1617
+ ? () => value
1618
+ : () => {
1619
+ throw createBigNumberError(expression);
1620
+ };
1332
1621
  }
1622
+ case "Decimal":
1623
+ return () => {
1624
+ throw createRealNumberError(expression);
1625
+ };
1333
1626
  case "String": {
1334
1627
  const value = expression.value;
1335
1628
  return () => value;
@@ -1340,17 +1633,18 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1340
1633
  return compileApply(expression, environment);
1341
1634
  case "OperatorReference":
1342
1635
  case "Lambda":
1343
- return throwing(
1344
- () =>
1345
- new TlaEvaluationError(
1346
- `An operator cannot be used as a value at ${describeLocation(expression)}`,
1347
- ),
1348
- );
1636
+ return () => {
1637
+ throw new TlaEvaluationError(
1638
+ `An operator cannot be used as a value at ${describeLocation(expression)}`,
1639
+ );
1640
+ };
1349
1641
  case "And": {
1350
1642
  const operands = expression.operands.map(child);
1351
1643
  return (context) => {
1352
1644
  for (let index = 0; index < operands.length; index++) {
1353
- if (!expectBoolean(operands[index](context), "a conjunct")) return false;
1645
+ const value = operands[index](context);
1646
+ if (typeof value !== "boolean") throw getConjunctError(expression, index, value);
1647
+ if (!value) return false;
1354
1648
  }
1355
1649
  return true;
1356
1650
  };
@@ -1367,11 +1661,7 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1367
1661
  case "Prime": {
1368
1662
  const inner = child(expression.expression);
1369
1663
  return (context) => {
1370
- if (!context.next) {
1371
- throw new TlaEvaluationError(
1372
- `A primed expression appears outside an action at ${describeLocation(expression)}`,
1373
- );
1374
- }
1664
+ if (!context.next) throw createPrimeOutsideActionError(expression);
1375
1665
  return inner({
1376
1666
  environment: context.environment,
1377
1667
  scope: context.scope,
@@ -1393,10 +1683,11 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1393
1683
  const condition = child(expression.condition);
1394
1684
  const consequent = child(expression.consequent);
1395
1685
  const alternative = child(expression.alternative);
1396
- return (context) =>
1397
- expectBoolean(condition(context), "an IF condition")
1398
- ? consequent(context)
1399
- : alternative(context);
1686
+ return (context) => {
1687
+ const value = condition(context);
1688
+ if (typeof value !== "boolean") throw getConditionError(expression, value);
1689
+ return value ? consequent(context) : alternative(context);
1690
+ };
1400
1691
  }
1401
1692
  case "Case": {
1402
1693
  const arms = expression.arms.map((arm) => ({
@@ -1409,7 +1700,9 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1409
1700
  if (expectBoolean(arm.condition(context), "a CASE guard")) return arm.body(context);
1410
1701
  }
1411
1702
  if (other) return other(context);
1412
- throw new TlaEvaluationError(`No CASE guard is true at ${describeLocation(expression)}`);
1703
+ throw new TlaEvaluationError(
1704
+ `Attempted to evaluate a CASE with no conditions true.\n${describeRange(expression)}`,
1705
+ );
1413
1706
  };
1414
1707
  }
1415
1708
  case "Let": {
@@ -1421,19 +1714,18 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1421
1714
  case "Exists":
1422
1715
  return compileQuantifier(expression, environment);
1423
1716
  case "UnboundedQuantifier":
1424
- return throwing(
1425
- () =>
1426
- new TlaEvaluationError(
1427
- `TLC cannot evaluate an unbounded quantifier at ${describeLocation(expression)}`,
1428
- ),
1429
- );
1717
+ return () => {
1718
+ throw new TlaEvaluationError(
1719
+ `TLC cannot evaluate an unbounded quantifier at ${describeLocation(expression)}`,
1720
+ );
1721
+ };
1430
1722
  case "Choose":
1431
1723
  case "SetFilter":
1432
1724
  case "SetMap":
1433
1725
  return compileSetComprehension(expression, environment);
1434
1726
  case "SetEnumeration": {
1435
1727
  const elements = expression.elements.map(child);
1436
- return (context) => createSet(elements.map((element) => element(context)));
1728
+ return (context) => createEnumeratedSet(elements.map((element) => element(context)));
1437
1729
  }
1438
1730
  case "Tuple": {
1439
1731
  const elements = expression.elements.map(child);
@@ -1449,9 +1741,7 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1449
1741
  case "Record":
1450
1742
  return compileRecord(expression.fields, environment);
1451
1743
  case "RecordSet": {
1452
- const fields = [...expression.fields].sort((left, right) =>
1453
- left.name < right.name ? -1 : 1,
1454
- );
1744
+ const fields = getSortedFields(expression.fields);
1455
1745
  const names = fields.map((field) => field.name);
1456
1746
  const sets = fields.map((field) => child(field.value));
1457
1747
  return (context) => ({ kind: "RecordSet", names, sets: sets.map((set) => set(context)) });
@@ -1469,18 +1759,21 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1469
1759
  return binding.value;
1470
1760
  };
1471
1761
  case "FunctionApplication": {
1472
- const fn = child(expression.function);
1762
+ keepLazy(expression.function);
1763
+ const evaluateFunction = child(expression.function);
1473
1764
  const args = expression.args.map(child);
1474
1765
  if (args.length === 1) {
1475
1766
  const argument = args[0];
1476
- return (context) => applyFunction(fn(context), argument(context));
1767
+ return (context) => applyFunction(evaluateFunction(context), argument(context));
1477
1768
  }
1478
- return (context) => applyFunction(fn(context), createTuple(args.map((arg) => arg(context))));
1769
+ return (context) =>
1770
+ applyFunction(evaluateFunction(context), createTuple(args.map((arg) => arg(context))));
1479
1771
  }
1480
1772
  case "FieldAccess": {
1481
1773
  const record = child(expression.record);
1482
1774
  const field = expression.field;
1483
- return (context) => applyFunction(record(context), field);
1775
+ const describeMissing = getFieldError(expression);
1776
+ return (context) => applyFunction(record(context), field, describeMissing);
1484
1777
  }
1485
1778
  case "Product": {
1486
1779
  const factors = expression.factors.map(child);
@@ -1492,7 +1785,11 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1492
1785
  case "BoxAction":
1493
1786
  case "AngleAction": {
1494
1787
  const action = child(expression.action);
1495
- const unchanged = child(createUnchanged(expression.subscript, expression.location));
1788
+ const unchanged = child({
1789
+ kind: "Unchanged",
1790
+ expression: expression.subscript,
1791
+ location: expression.location,
1792
+ });
1496
1793
  const isBox = expression.kind === "BoxAction";
1497
1794
  return (context) =>
1498
1795
  isBox
@@ -1506,21 +1803,19 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1506
1803
  case "Label":
1507
1804
  return child(expression.body);
1508
1805
  case "Subexpression":
1509
- return throwing(
1510
- () =>
1511
- new TlaEvaluationError(
1512
- `The subexpression reference at ${describeLocation(expression)} does not name a subexpression`,
1513
- ),
1514
- );
1806
+ return () => {
1807
+ throw new TlaEvaluationError(
1808
+ `The subexpression reference at ${describeLocation(expression)} does not name a subexpression`,
1809
+ );
1810
+ };
1515
1811
  case "Always":
1516
1812
  case "Eventually":
1517
1813
  case "WeakFairness":
1518
1814
  case "StrongFairness":
1519
- return throwing(
1520
- () =>
1521
- new TlaEvaluationError(
1522
- `TLC cannot evaluate a temporal formula in a state at ${describeLocation(expression)}`,
1523
- ),
1524
- );
1815
+ return () => {
1816
+ throw new TlaEvaluationError(
1817
+ `TLC cannot evaluate a temporal formula in a state at ${describeLocation(expression)}`,
1818
+ );
1819
+ };
1525
1820
  }
1526
1821
  };