tla-ts 0.0.3 → 0.0.4-dev.2be6058

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 (86) hide show
  1. package/README.md +32 -12
  2. package/dist/cli.cjs +1 -1
  3. package/dist/cli.js +1 -1
  4. package/dist/index.cjs +1 -1
  5. package/dist/index.d.cts +160 -8
  6. package/dist/index.d.ts +160 -8
  7. package/dist/index.js +1 -1
  8. package/dist/parallel-worker.cjs +2 -2
  9. package/dist/parallel-worker.js +2 -2
  10. package/dist/parallel.cjs +1 -1
  11. package/dist/parallel.js +2 -2
  12. package/dist/run-cli.cjs +45 -18
  13. package/dist/run-cli.js +45 -18
  14. package/dist/transfer.cjs +1393 -18
  15. package/dist/transfer.js +1393 -18
  16. package/package.json +5 -1
  17. package/src/ast.ts +147 -6
  18. package/src/bags.ts +4 -7
  19. package/src/builtins.ts +29 -11
  20. package/src/bundled-modules.ts +3 -3
  21. package/src/canonical.ts +4 -3
  22. package/src/check.ts +1539 -235
  23. package/src/cli-options.ts +11 -5
  24. package/src/cli.ts +8 -1
  25. package/src/codegen.ts +77 -37
  26. package/src/config.ts +254 -181
  27. package/src/dependencies.ts +2 -2
  28. package/src/environment.ts +540 -140
  29. package/src/errors.ts +224 -3
  30. package/src/evaluate.ts +797 -246
  31. package/src/exit-codes.ts +22 -43
  32. package/src/fingerprints.ts +46 -11
  33. package/src/index.ts +1 -0
  34. package/src/instances.ts +19 -16
  35. package/src/java-overrides.ts +104 -25
  36. package/src/levels.ts +191 -45
  37. package/src/lexer.ts +127 -30
  38. package/src/live-check.ts +867 -0
  39. package/src/liveness.ts +218 -572
  40. package/src/obligation-expression.ts +2 -2
  41. package/src/obligation-source.ts +2 -0
  42. package/src/parallel-worker.ts +174 -213
  43. package/src/parallel.ts +131 -39
  44. package/src/parser.ts +456 -147
  45. package/src/pcal-ast.ts +770 -0
  46. package/src/pcal-parse.ts +1523 -0
  47. package/src/pcal-tokenize.ts +516 -0
  48. package/src/pcal-translate.ts +1230 -0
  49. package/src/pcal-validate.ts +454 -0
  50. package/src/randomization.ts +24 -7
  51. package/src/resolve.ts +1481 -426
  52. package/src/run-cli.ts +1212 -143
  53. package/src/runtime.ts +19 -1
  54. package/src/sany-builtins.ts +147 -0
  55. package/src/sany-generator.ts +3128 -0
  56. package/src/sany-levels.ts +1208 -0
  57. package/src/sany-lexer.ts +545 -0
  58. package/src/sany-linter.ts +122 -0
  59. package/src/sany-modules.ts +1398 -0
  60. package/src/sany-nodes.ts +463 -0
  61. package/src/sany-parse-error.ts +2161 -0
  62. package/src/sany-report.ts +356 -0
  63. package/src/sany-selectors.ts +738 -0
  64. package/src/sany-source.ts +248 -0
  65. package/src/sany-xml.ts +1017 -0
  66. package/src/spec-description.ts +42 -11
  67. package/src/standard-modules.ts +200 -148
  68. package/src/standard-ranges.ts +116 -0
  69. package/src/state-graph.ts +180 -0
  70. package/src/subexpressions.ts +231 -171
  71. package/src/substitution-levels.ts +38 -17
  72. package/src/successors.ts +219 -107
  73. package/src/symmetry.ts +194 -54
  74. package/src/tableau.ts +54 -25
  75. package/src/tlc-ext.ts +42 -29
  76. package/src/tlc-messages.ts +329 -0
  77. package/src/tlc-module.ts +52 -43
  78. package/src/tlc-modules.ts +4 -0
  79. package/src/tlc-order.ts +78 -10
  80. package/src/tlc-random.ts +37 -9
  81. package/src/tlc-replay.ts +655 -0
  82. package/src/tlc-summary.ts +20 -5
  83. package/src/tlc-version.ts +18 -0
  84. package/src/transfer.ts +15 -3
  85. package/src/value-sources.ts +29 -0
  86. package/src/values.ts +731 -184
package/src/evaluate.ts CHANGED
@@ -1,54 +1,74 @@
1
- import type {
2
- Bound,
3
- BoundPattern,
4
- DecimalExpression,
5
- Definition,
6
- Expression,
7
- FunctionDefinition,
8
- NumberExpression,
9
- OperatorParam,
10
- RecordField,
11
- SourceRange,
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,
12
14
  } from "./ast";
13
15
  import { getKindString } from "./builtins";
14
- import { TlaEvaluationError } from "./errors";
16
+ import { isStackOverflow, TlaEvaluationError, TlaUnassignedError } from "./errors";
15
17
  import { EXIT_STATUS, setExitCode } from "./exit-codes";
16
18
  import { generateEvaluator } from "./codegen";
19
+ import { MESSAGE_CODE } from "./tlc-messages";
17
20
  import type { CheckerRuntime } from "./runtime";
18
21
  import { getReadVariables } from "./dependencies";
19
22
  import { contextualApplications, mapChildren, substitutedExpressions } from "./instances";
23
+ import { prettyPrint } from "./pretty-print";
20
24
  import { isEnabled } from "./successors";
21
25
  import {
22
26
  applyFunction,
27
+ describeMissingArgument,
23
28
  combineHash,
24
29
  compareValues,
25
30
  createFunction,
31
+ createNonIntegerKeyError,
32
+ createRecord,
26
33
  createEnumeratedSet,
27
34
  createSortedFunction,
35
+ createSortedRecord,
28
36
  createSortedSet,
29
37
  createWrittenRecord,
30
38
  createTuple,
31
39
  formatValue,
40
+ getCardinality,
32
41
  getDomain,
33
42
  getFunctionDomain,
34
43
  getIntervalElements,
44
+ getLazySubsets,
45
+ getStreamedElements,
46
+ getFunctionClass,
35
47
  getSequenceElements,
36
48
  getValueHash,
49
+ isElementOf,
37
50
  isEnumerable,
38
51
  isFunctionValue,
39
52
  isOverriddenSet,
40
53
  isSameValue,
41
54
  markLambdaFunction,
55
+ isReducibleSet,
42
56
  isSetValue,
43
57
  MAXIMUM_INTEGER,
44
58
  MINIMUM_INTEGER,
59
+ toFiniteFunction,
45
60
  toFiniteSet,
46
61
  updateFunction,
47
62
  valuesEqual,
63
+ type FilteredSetValue,
48
64
  type LazyFunctionSource,
49
65
  type LazyFunctionValue,
66
+ type ObjectValue,
50
67
  type Value,
68
+ markNormalized,
69
+ setTrace,
51
70
  } from "./values";
71
+ import type { TlcVersion } from "./tlc-version";
52
72
 
53
73
  export type State = (Value | undefined)[];
54
74
 
@@ -71,6 +91,8 @@ export interface Builtin {
71
91
  evaluateUnary: ((value: Value) => Value) | undefined;
72
92
  evaluateBinary: ((left: Value, right: Value) => Value) | undefined;
73
93
  isStateLevel?: boolean;
94
+ // Whether TLC takes an application for a constant one although its value depends on the state.
95
+ isLevelConstant?: boolean;
74
96
  isLazy?: boolean;
75
97
  }
76
98
 
@@ -107,18 +129,89 @@ export interface Environment {
107
129
  builtins: Map<string, Builtin>;
108
130
  constants: Map<string, Value>;
109
131
  substitutions: Map<string, string>;
132
+ // The name SANY gives each definition that a named instance such as `M == INSTANCE Module`
133
+ // copies, such as M!Op, by the key of the copy.
134
+ instanceNames: Map<string, string>;
110
135
  variables: string[];
111
136
  variableIndex: Map<string, number>;
112
137
  definitionValues: Map<Definition, Value>;
113
138
  constantLevels: Map<Definition, boolean>;
139
+ // The definitions an INSTANCE copies from a module that declares constants or variables. SANY
140
+ // wraps the body of each in its substitutions.
141
+ substitutedDefinitions: Set<Definition>;
114
142
  evaluators: WeakMap<Expression, Evaluator>;
143
+ // The expressions being evaluated, outermost first, when the environment replays an error to
144
+ // find where it occurred, as TLC's CallStackTool does.
145
+ callStack?: CallStack;
146
+ }
147
+
148
+ export interface CallStack {
149
+ expressions: Expression[];
150
+ // TLC stops popping the stack once an evaluation fails, so it keeps where the failure occurred.
151
+ isFrozen: boolean;
152
+ // The expression that built each value of the replay that TLC's CallStackTool gives a source.
153
+ sources: WeakMap<ObjectValue, Expression>;
154
+ // The value each expression of the replay last evaluated to.
155
+ values: WeakMap<Expression, Value>;
156
+ // The expression each failure last left, which tells a failure of an operand from one of the
157
+ // method that computes the operator.
158
+ failures: WeakMap<Error, Expression>;
159
+ // The failure of a value with a source, which TLC raises as a FingerprintException.
160
+ fingerprint?: FingerprintFailure;
161
+ }
162
+
163
+ export interface FingerprintFailure {
164
+ // The sources of the values whose methods failed, outermost first.
165
+ sources: Expression[];
166
+ // The message of the error the innermost one raised.
167
+ reason: string;
115
168
  }
116
169
 
170
+ // The operators of Tool#evalAppl whose value TLC's CallStackTool gives a source.
171
+ const SOURCED_OPERATORS = new Set(["SUBSET", "UNION", "DOMAIN", "\\cup", "\\cap", "\\"]);
172
+
173
+ // CallStackTool copies the SetPredValue, FcnLambdaValue and OpLambdaValue that an evaluation
174
+ // returns without their source, and a function TLC builds from a FcnLambdaValue has none.
175
+ const SOURCED_KINDS = new Set<Expression["kind"]>([
176
+ "SetEnumeration",
177
+ "SetFilter",
178
+ "SetMap",
179
+ "Tuple",
180
+ "FunctionSet",
181
+ "Record",
182
+ "RecordSet",
183
+ "Product",
184
+ ]);
185
+
186
+ const isSourced = (expression: Expression) =>
187
+ SOURCED_KINDS.has(expression.kind) ||
188
+ (expression.kind === "Apply" && SOURCED_OPERATORS.has(expression.operator));
189
+
190
+ // The argument whose method Tool#evalAppl calls to compute an operator, as with S.member(e) for
191
+ // 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.
192
+ const getReceiver = (expression: Expression, values: CallStack["values"]) => {
193
+ if (expression.kind === "FunctionApplication" || expression.kind === "Except") {
194
+ return expression.function;
195
+ }
196
+ if (expression.kind !== "Apply" || expression.args.length !== 2) return undefined;
197
+ if (["\\subseteq", "=", "#", "\\"].includes(expression.operator)) return expression.args[0];
198
+ if (expression.operator === "\\cap" || expression.operator === "\\cup") {
199
+ const left = values.get(expression.args[0]);
200
+ return left !== undefined && isReducibleSet(left) ? expression.args[0] : expression.args[1];
201
+ }
202
+ return expression.operator === "\\in" || expression.operator === "\\notin"
203
+ ? expression.args[1]
204
+ : undefined;
205
+ };
206
+
117
207
  export interface Context {
118
208
  environment: Environment;
119
209
  scope: Scope | undefined;
120
210
  state: State | undefined;
121
211
  next: State | undefined;
212
+ // EvalControl.KeepLazy, which Tool#evalAppl sets to evaluate the function it applies and which
213
+ // the evaluation passes on, so that a function constructor within builds a FcnLambdaValue.
214
+ isKeepLazy?: boolean;
122
215
  }
123
216
 
124
217
  export type Evaluator = (context: Context) => Value;
@@ -149,14 +242,20 @@ export const describeRange = (expression: Expression) => {
149
242
  return range ? formatRange(range) : describeLocation(expression);
150
243
  };
151
244
 
245
+ // SANY prints a numeral as written and any other expression by its location.
246
+ export const describeNode = (expression: Expression) =>
247
+ expression.kind === "Number"
248
+ ? (expression.text ?? String(expression.value))
249
+ : describeRange(expression);
250
+
152
251
  export const getConditionError = (expression: Expression, value: Value) =>
153
252
  new TlaEvaluationError(
154
253
  `A non-boolean expression (${getKindString(value)}) was used as the condition of an IF.\n${describeRange(expression)}`,
155
254
  );
156
255
 
157
- // TLC parses an infix chain of /\ as nested binary conjunctions and a bulleted list as one
158
- // conjunction list, and it words the error differently for each.
159
- export const getConjunctError = (
256
+ // TLC parses an infix chain of /\ or \/ as nested binary junctions and a bulleted list as one
257
+ // junction list, and it words the error differently for each.
258
+ export const getJunctionError = (
160
259
  expression: Expression & { kind: "And" | "Or" },
161
260
  index: number,
162
261
  value: Value,
@@ -166,22 +265,48 @@ export const getConjunctError = (
166
265
  range?.start.line === expression.location.line &&
167
266
  range.start.column === expression.location.column;
168
267
  if (isBulleted || !range) {
169
- const operand = expression.operands[index];
170
- // SANY prints a numeral as its value instead of its location.
171
- const description = operand.kind === "Number" ? String(operand.value) : describeRange(operand);
172
268
  return new TlaEvaluationError(
173
- `A non-boolean expression (${getKindString(value)}) was used as a formula in a conjunction.\n${description}`,
269
+ `A non-boolean expression (${getKindString(value)}) was used as a formula in a ${expression.kind === "And" ? "conjunction" : "disjunction"}.\n${describeNode(expression.operands[index])}`,
174
270
  );
175
271
  }
176
- const end = expression.operands[Math.max(index, 1)].location.range?.end ?? range.end;
272
+ const end = expression.prefixEnds?.[Math.max(index, 1) - 1] ?? range.end;
177
273
  return new TlaEvaluationError(
178
- `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 } } })}`,
274
+ `Attempted to evaluate an expression of form P ${expression.kind === "And" ? "/\\" : "\\/"} Q when ${index === 0 ? "P" : "Q"} was\n${getKindString(value)}.\n${describeRange({ ...expression, location: { ...expression.location, range: { ...range, end } } })}`,
179
275
  );
180
276
  };
181
277
 
182
- export const getFieldError =
183
- (expression: Expression & { kind: "FieldAccess" }) => (record: Value) =>
184
- `Attempted to select nonexistent field "${expression.field}" from the record\n${formatValue(record)}\n${describeRange(expression)}`;
278
+ // TLC selects a field of a record, and of another function from the function it converts it to,
279
+ // which for a tuple keeps its domain as an interval.
280
+ export const getFieldSelector = (expression: Expression & { kind: "FieldAccess" }) => {
281
+ const field = expression.field;
282
+ const describeMissing = (record: Value) =>
283
+ `Attempted to select nonexistent field "${field}" from the record\n${formatValue(record)}\n${describeRange(expression)}`;
284
+ const describeNotInDomain = (functionValue: Value) =>
285
+ `Attempted to apply function:\n${prettyPrint(formatValue(functionValue))}\nto argument "${field}", which is not in the domain of the function.`;
286
+ return (value: Value) => {
287
+ if (!isFunctionValue(value)) {
288
+ throw new TlaEvaluationError(
289
+ `Attempted to select field "${field}" from a non-record value ${prettyPrint(formatValue(value))}\n${describeRange(expression)}`,
290
+ );
291
+ }
292
+ const functionClass = getFunctionClass(value);
293
+ if (functionClass === "tuple") throw createNonIntegerKeyError(field);
294
+ // Only TLC's RecordValue names the field it lacks. Any other function, such as a FcnRcdValue
295
+ // whose keys are strings, reports an argument outside its domain.
296
+ return applyFunction(
297
+ value,
298
+ field,
299
+ functionClass === "record" ? describeMissing : describeNotInDomain,
300
+ );
301
+ };
302
+ };
303
+
304
+ // TLC 1.7.4 words what a tuple or a record lacks differently.
305
+ export const getMissingArgumentDescriber = (version: TlcVersion | undefined) =>
306
+ version === "1.7.4"
307
+ ? (functionValue: Value, argument: Value) =>
308
+ describeMissingArgument(functionValue, argument, version)
309
+ : undefined;
185
310
 
186
311
  export const getDomainOperator = (expression: Expression) => (value: Value) => {
187
312
  if (!isFunctionValue(value)) {
@@ -246,11 +371,23 @@ const bindPattern = (scope: Scope | undefined, pattern: BoundPattern, value: Val
246
371
  );
247
372
  };
248
373
 
374
+ // Tool#evalAppl checks that it applies a function before it evaluates the argument.
375
+ export const expectFunction = (value: Value, application: Expression) => {
376
+ if (isFunctionValue(value)) return value;
377
+ throw new TlaEvaluationError(
378
+ `A non-function (${getKindString(value)}) was applied as a function.\n${describeRange(application)}`,
379
+ );
380
+ };
381
+
382
+ export const toKeepLazyContext = (context: Context): Context =>
383
+ context.isKeepLazy ? context : { ...context, isKeepLazy: true };
384
+
249
385
  const withScope = (context: Context, scope: Scope | undefined): Context => ({
250
386
  environment: context.environment,
251
387
  scope,
252
388
  state: context.state,
253
389
  next: context.next,
390
+ isKeepLazy: context.isKeepLazy,
254
391
  });
255
392
 
256
393
  export const expectBoolean = (value: Value, description: string) => {
@@ -262,104 +399,29 @@ export const expectBoolean = (value: Value, description: string) => {
262
399
  return value;
263
400
  };
264
401
 
265
- export const getChildren = (expression: Expression): Expression[] => {
266
- switch (expression.kind) {
267
- case "Number":
268
- case "Decimal":
269
- case "String":
270
- case "Identifier":
271
- case "OperatorReference":
272
- case "ExceptAt":
273
- return [];
274
- case "Apply":
275
- return expression.args;
276
- case "Lambda":
277
- return [expression.body];
278
- case "And":
279
- case "Or":
280
- return expression.operands;
281
- case "Prime":
282
- case "Unchanged":
283
- case "Enabled":
284
- case "Always":
285
- case "Eventually":
286
- return [expression.expression];
287
- case "If":
288
- return [expression.condition, expression.consequent, expression.alternative];
289
- case "Case":
290
- return [
291
- ...expression.arms.flatMap((arm) => [arm.condition, arm.body]),
292
- ...(expression.other ? [expression.other] : []),
293
- ];
294
- case "Let":
295
- return [
296
- ...expression.definitions.flatMap((definition) =>
297
- definition.kind === "Function"
298
- ? [...definition.bounds.map((bound) => bound.set), definition.body]
299
- : [definition.body],
300
- ),
301
- expression.body,
302
- ];
303
- case "Forall":
304
- case "Exists":
305
- return [...expression.bounds.map((bound) => bound.set), expression.body];
306
- case "UnboundedQuantifier":
307
- return [expression.body];
308
- case "Choose":
309
- return [...(expression.set ? [expression.set] : []), expression.body];
310
- case "SetEnumeration":
311
- case "Tuple":
312
- return expression.elements;
313
- case "SetFilter":
314
- return [expression.bound.set, expression.predicate];
315
- case "SetMap":
316
- return [expression.expression, ...expression.bounds.map((bound) => bound.set)];
317
- case "FunctionConstruction":
318
- return [...expression.bounds.map((bound) => bound.set), expression.body];
319
- case "FunctionSet":
320
- return [expression.domain, expression.range];
321
- case "Record":
322
- case "RecordSet":
323
- return expression.fields.map((field) => field.value);
324
- case "Except":
325
- return [
326
- expression.function,
327
- ...expression.updates.flatMap((update) => [
328
- ...update.path.flatMap((step) => (step.kind === "Index" ? step.args : [])),
329
- update.value,
330
- ]),
331
- ];
332
- case "FunctionApplication":
333
- return [expression.function, ...expression.args];
334
- case "FieldAccess":
335
- return [expression.record];
336
- case "Product":
337
- return expression.factors;
338
- case "BoxAction":
339
- case "AngleAction":
340
- return [expression.action, expression.subscript];
341
- case "WeakFairness":
342
- case "StrongFairness":
343
- return [expression.subscript, expression.action];
344
- case "Label":
345
- return [expression.body];
346
- case "Subexpression":
347
- return expression.selectors.flatMap((selector) => ("args" in selector ? selector.args : []));
348
- }
349
- };
350
-
351
- export const isLocallyResolved = (expression: Expression) =>
352
- (expression.kind === "Identifier" || expression.kind === "Apply") &&
353
- expression.resolution?.kind === "Local";
354
-
355
402
  export const getDefinition = (name: string, environment: Environment) =>
356
403
  environment.definitions.get(environment.substitutions.get(name) ?? name);
357
404
 
358
- const isStateDependent = (expression: Expression, environment: Environment): boolean => {
405
+ // TLC bounds the level of every action and temporal operator above constant, whatever its operands.
406
+ const NONCONSTANT_KINDS = new Set<Expression["kind"]>([
407
+ "Prime",
408
+ "Unchanged",
409
+ "Enabled",
410
+ "BoxAction",
411
+ "AngleAction",
412
+ "Always",
413
+ "Eventually",
414
+ "WeakFairness",
415
+ "StrongFairness",
416
+ ]);
417
+
418
+ const NONCONSTANT_OPERATORS = new Set(["~>", "-+->", "\\cdot"]);
419
+
420
+ const isNonconstant = (expression: Expression, environment: Environment): boolean => {
359
421
  if (
360
- expression.kind === "Prime" ||
361
- expression.kind === "Unchanged" ||
362
- expression.kind === "Enabled"
422
+ NONCONSTANT_KINDS.has(expression.kind) ||
423
+ (expression.kind === "UnboundedQuantifier" && expression.isTemporal === true) ||
424
+ (expression.kind === "Apply" && NONCONSTANT_OPERATORS.has(expression.operator))
363
425
  ) {
364
426
  return true;
365
427
  }
@@ -376,7 +438,7 @@ const isStateDependent = (expression: Expression, environment: Environment): boo
376
438
  if (definition && !environment.constants.has(name) && !isConstantLevel(definition, environment))
377
439
  return true;
378
440
  }
379
- return getChildren(expression).some((child) => isStateDependent(child, environment));
441
+ return getChildren(expression).some((child) => isNonconstant(child, environment));
380
442
  };
381
443
 
382
444
  export const isConstantLevel = (definition: Definition, environment: Environment): boolean => {
@@ -384,9 +446,9 @@ export const isConstantLevel = (definition: Definition, environment: Environment
384
446
  if (cached !== undefined) return cached;
385
447
  environment.constantLevels.set(definition, true);
386
448
  const isConstant =
387
- !isStateDependent(definition.body, environment) &&
449
+ !isNonconstant(definition.body, environment) &&
388
450
  (definition.kind === "Operator" ||
389
- !definition.bounds.some((bound) => isStateDependent(bound.set, environment)));
451
+ !definition.bounds.some((bound) => isNonconstant(bound.set, environment)));
390
452
  environment.constantLevels.set(definition, isConstant);
391
453
  return isConstant;
392
454
  };
@@ -409,38 +471,90 @@ const getBoundExplanation = (set: Value, text: string) => {
409
471
 
410
472
  // TLC enumerates every set except the ones it implements in Java, so any other set fails as its own
411
473
  // class does.
412
- export const getEnumeratedElements = (set: Value, expression: Expression) => {
474
+ const checkEnumerable = (set: Value, expression: Expression, version: TlcVersion) => {
413
475
  if (!isSetValue(set) || isOverriddenSet(set)) {
414
476
  const text = formatValue(set);
415
- const explanation = getBoundExplanation(set, text);
477
+ // TLC 1.7.4 doesn't explain why it can't enumerate a set.
478
+ const explanation = version === "1.7.4" ? undefined : getBoundExplanation(set, text);
416
479
  throw new TlaEvaluationError(
417
480
  explanation === undefined
418
- ? `TLC encountered a non-enumerable quantifier bound\n${text}.\n${describeRange(expression)}`
419
- : `TLC encountered the non-enumerable quantifier bound\n${text}\n${describeRange(expression)}\n${explanation}`,
481
+ ? `TLC encountered a non-enumerable quantifier bound\n${text}.\n${describeNode(expression)}`
482
+ : `TLC encountered the non-enumerable quantifier bound\n${text}\n${describeNode(expression)}\n${explanation}`,
420
483
  );
421
484
  }
422
- return typeof set === "object" && set.kind === "Interval"
423
- ? getIntervalElements(set)
424
- : toFiniteSet(set).elements;
425
485
  };
426
486
 
427
- export const forEachBinding = (
487
+ const getEnumeratedElements = (set: Value, expression: Expression, version: TlcVersion) => {
488
+ checkEnumerable(set, expression, version);
489
+ if (typeof set === "object" && set.kind === "Interval") return getIntervalElements(set);
490
+ return getLazySubsets(set) ?? toFiniteSet(set).elements;
491
+ };
492
+
493
+ // The elements Tool.contexts binds to the bound of a quantifier or a set map. TLC 1.7.4 streams a
494
+ // lazy set's elements, where later versions normalize the set first.
495
+ export const getContextElements = (set: Value, expression: Expression, version: TlcVersion) => {
496
+ if (version !== "1.7.4") return getEnumeratedElements(set, expression, version);
497
+ checkEnumerable(set, expression, version);
498
+ return getLazySubsets(set) ?? getStreamedElements(set);
499
+ };
500
+
501
+ // Like TLC, a quantifier keeps an interval as an interval, so that it can stop at the first witness
502
+ // in a large interval such as 1..2000000000 without listing it.
503
+ const getKeptInterval = (set: Value) => {
504
+ if (typeof set !== "object" || set.kind !== "Interval") return undefined;
505
+ getCardinality(set);
506
+ return set;
507
+ };
508
+
509
+ export const getQuantifierElements = (set: Value, expression: Expression, version: TlcVersion) =>
510
+ getKeptInterval(set) ?? getContextElements(set, expression, version);
511
+
512
+ // CHOOSE and a function constructor visit the elements of the normalized set.
513
+ const getNormalizedElements = (set: Value, expression: Expression, version: TlcVersion) =>
514
+ getKeptInterval(set) ?? getEnumeratedElements(set, expression, version);
515
+
516
+ const someElement = (
517
+ elements: ReturnType<typeof getQuantifierElements>,
518
+ visit: (element: Value) => boolean,
519
+ ) => {
520
+ if (Array.isArray(elements)) return elements.some(visit);
521
+ for (let element = elements.low; element <= elements.high; element++) {
522
+ if (visit(element)) return true;
523
+ }
524
+ return false;
525
+ };
526
+
527
+ export const getBoundElements = (bounds: Bound[], context: Context) =>
528
+ bounds.map((bound) =>
529
+ getQuantifierElements(
530
+ evaluate(bound.set, context),
531
+ bound.set,
532
+ context.environment.runtime.version,
533
+ ),
534
+ );
535
+
536
+ // Visits each binding of the bounds to the elements of their sets, until visit returns true.
537
+ export const forEachBoundElement = (
428
538
  bounds: Bound[],
429
- context: Context,
539
+ sets: ReturnType<typeof getBoundElements>,
540
+ scope: Scope | undefined,
430
541
  visit: (scope: Scope | undefined) => boolean,
431
542
  ): boolean => {
432
- const sets = bounds.map((bound) =>
433
- getEnumeratedElements(evaluate(bound.set, context), bound.set),
434
- );
435
- const visitBound = (index: number, scope: Scope | undefined): boolean => {
436
- if (index < 0) return visit(scope);
437
- return sets[index].some((element) =>
438
- visitBound(index - 1, bindPattern(scope, bounds[index].pattern, element)),
543
+ const visitBound = (index: number, bound: Scope | undefined): boolean => {
544
+ if (index < 0) return visit(bound);
545
+ return someElement(sets[index], (element) =>
546
+ visitBound(index - 1, bindPattern(bound, bounds[index].pattern, element)),
439
547
  );
440
548
  };
441
- return visitBound(bounds.length - 1, context.scope);
549
+ return visitBound(bounds.length - 1, scope);
442
550
  };
443
551
 
552
+ export const forEachBinding = (
553
+ bounds: Bound[],
554
+ context: Context,
555
+ visit: (scope: Scope | undefined) => boolean,
556
+ ) => forEachBoundElement(bounds, getBoundElements(bounds, context), context.scope, visit);
557
+
444
558
  export const getBoundsDomain = (bounds: Bound[], context: Context): Value => {
445
559
  const sets = bounds.map((bound) => evaluate(bound.set, context));
446
560
  return sets.length === 1 ? sets[0] : { kind: "ProductSet", factors: sets };
@@ -455,6 +569,84 @@ export const bindArgument = (bounds: Bound[], scope: Scope | undefined, argument
455
569
  );
456
570
  };
457
571
 
572
+ // The parameters, body and scope of each function a constructor or a definition keeps lazy, whose
573
+ // body TLC's getInitStates and getNextStates walk for an argument, as they do a FcnLambdaValue's.
574
+ interface LazyFunction {
575
+ value: LazyFunctionValue;
576
+ bounds: Bound[];
577
+ body: Expression;
578
+ scope: Scope | undefined;
579
+ }
580
+
581
+ // The function keeps its parameters, body and scope itself, since a WeakMap entry for each
582
+ // short-lived function makes every garbage collection slower.
583
+ interface KeptLazyFunctionValue extends LazyFunctionValue {
584
+ lambda: LazyFunction;
585
+ }
586
+
587
+ const isKeptLazyFunction = (value: Value): value is KeptLazyFunctionValue =>
588
+ typeof value === "object" && value.kind === "LazyFunction" && "lambda" in value;
589
+
590
+ const keepLambda = (lambda: LazyFunction) => Object.assign(lambda.value, { lambda });
591
+
592
+ export const getLazyFunction = (value: Value) =>
593
+ isKeptLazyFunction(value) ? value.lambda : undefined;
594
+
595
+ // Tool.getFcnContext: the scope of a lazy function's body for the arguments of an application. It
596
+ // ignores arguments beyond the parameters.
597
+ export const bindLazyArguments = (
598
+ lambda: LazyFunction,
599
+ expression: Expression & { kind: "FunctionApplication" },
600
+ context: Context,
601
+ ) => {
602
+ const value = lambda.value;
603
+ const args = expression.args.map((arg) => evaluate(arg, context));
604
+ const argument = args.length === 1 ? args[0] : createTuple(args);
605
+ const describeArgument = (ordinal: string, element: Value, problem: string) =>
606
+ `In applying the function\n${prettyPrint(formatValue(value))},\nthe ${ordinal} is:\n${prettyPrint(formatValue(element))}${problem}.\n${describeRange(expression.function)}`;
607
+ const bounds = lambda.bounds;
608
+ if (bounds.length === 1) {
609
+ if (!isElementOf(argument, value.domain)) {
610
+ throw new TlaEvaluationError(
611
+ describeArgument("first argument", argument, "which is not in its domain"),
612
+ );
613
+ }
614
+ return bindArgument(bounds, lambda.scope, argument);
615
+ }
616
+ const elements = getSequenceElements(argument);
617
+ const domains =
618
+ typeof value.domain === "object" && value.domain.kind === "ProductSet"
619
+ ? value.domain.factors
620
+ : [];
621
+ if (elements === undefined || elements.length < bounds.length) {
622
+ throw new TlaEvaluationError(
623
+ `Attempted to apply a function to an argument not in its domain.\n${describeRange(expression.function)}`,
624
+ );
625
+ }
626
+ bounds.forEach((bound, index) => {
627
+ const element = elements[index];
628
+ const ordinal = `argument number ${index + 1}`;
629
+ if (!isElementOf(element, domains[index])) {
630
+ throw new TlaEvaluationError(
631
+ describeArgument(
632
+ ordinal,
633
+ element,
634
+ `${bound.pattern.kind === "Name" ? "" : "\n"}which is not in its domain`,
635
+ ),
636
+ );
637
+ }
638
+ if (
639
+ bound.pattern.kind === "Tuple" &&
640
+ getSequenceElements(element)?.length !== bound.pattern.names.length
641
+ ) {
642
+ throw new TlaEvaluationError(
643
+ describeArgument(ordinal, element, "which does not match its formal parameter"),
644
+ );
645
+ }
646
+ });
647
+ return bindArgument(bounds, lambda.scope, createTuple(elements.slice(0, bounds.length)));
648
+ };
649
+
458
650
  // TLC prints a function it can't enumerate as its parameters and the location of its body. It
459
651
  // prints only the first name of a group such as `m, n \in S`.
460
652
  interface LazyFunctionTemplate {
@@ -533,6 +725,22 @@ const createLazyFunction = (
533
725
  return self;
534
726
  };
535
727
 
728
+ const definitionSources = new WeakMap<FunctionDefinition, Expression>();
729
+
730
+ // The function constructor of a definition, which SANY locates at the whole definition.
731
+ const getDefinitionSource = (definition: FunctionDefinition) => {
732
+ const cached = definitionSources.get(definition);
733
+ if (cached) return cached;
734
+ const source: Expression = {
735
+ kind: "FunctionConstruction",
736
+ bounds: definition.bounds,
737
+ body: definition.body,
738
+ location: definition.location,
739
+ };
740
+ definitionSources.set(definition, source);
741
+ return source;
742
+ };
743
+
536
744
  const createRecursiveFunction = (definition: FunctionDefinition, context: Context) => {
537
745
  const domain = getBoundsDomain(definition.bounds, context);
538
746
  const functionValue = createLazyFunction(
@@ -547,13 +755,44 @@ const createRecursiveFunction = (definition: FunctionDefinition, context: Contex
547
755
  ),
548
756
  getLazyFunctionSource(definition.bounds, definition.body, domain),
549
757
  );
758
+ keepLambda({
759
+ value: functionValue,
760
+ bounds: definition.bounds,
761
+ body: definition.body,
762
+ scope: bindValue(undefined, definition.name, functionValue),
763
+ });
550
764
  return definition.bounds.length === 1 ? markLambdaFunction(functionValue) : functionValue;
551
765
  };
552
766
 
553
- const evaluateDefinitionBody = (definition: Definition, context: Context) =>
554
- definition.kind === "Function"
767
+ // TLC computes a constant definition when it starts, without keeping a function it constructs
768
+ // lazy, so a function over an interval or an enumerated set is a FcnRcdValue.
769
+ const toStartupValue = (definition: Definition, value: Value): Value => {
770
+ if (typeof value !== "object" || getFunctionClass(value) !== "lambda") return value;
771
+ if (
772
+ definition.kind === "Operator" ||
773
+ definition.isSelfReferential ||
774
+ value.kind !== "LazyFunction" ||
775
+ !isReducibleSet(value.domain)
776
+ ) {
777
+ return value;
778
+ }
779
+ try {
780
+ const finite = toFiniteFunction(value);
781
+ return createSortedFunction(finite.domain, finite.range);
782
+ } catch (error) {
783
+ // TLC leaves a definition it fails to compute to evaluate where the spec uses it.
784
+ if (error instanceof TlaEvaluationError) return value;
785
+ throw error;
786
+ }
787
+ };
788
+
789
+ // TLC evaluates a function definition that isn't recursive as it does a function constructor.
790
+ const evaluateDefinitionBody = (definition: Definition, context: Context) => {
791
+ if (definition.kind !== "Function") return evaluate(definition.body, context);
792
+ return definition.isSelfReferential
555
793
  ? createRecursiveFunction(definition, context)
556
- : evaluate(definition.body, context);
794
+ : evaluate(getDefinitionSource(definition), context);
795
+ };
557
796
 
558
797
  const evaluateDefinitionValue = (definition: Definition, context: Context) => {
559
798
  const isConstant = isConstantLevel(definition, context.environment);
@@ -567,12 +806,35 @@ const evaluateDefinitionValue = (definition: Definition, context: Context) => {
567
806
  const topLevel = withScope(context, undefined);
568
807
  if (!isConstant) return evaluateDefinitionBody(definition, topLevel);
569
808
  const value = context.environment.runtime.evaluateAtStartup(() =>
570
- evaluateDefinitionBody(definition, topLevel),
809
+ toStartupValue(definition, evaluateDefinitionBody(definition, topLevel)),
571
810
  );
572
811
  context.environment.definitionValues.set(definition, value);
573
812
  return value;
574
813
  };
575
814
 
815
+ // TLC computes each constant definition the configuration doesn't replace when it starts, and
816
+ // leaves one it fails to compute to evaluate where the spec uses it.
817
+ export const evaluateStartupDefinitions = (definitions: Definition[], environment: Environment) =>
818
+ definitions.forEach((definition) => {
819
+ if (definition.kind === "Operator" && definition.params.length > 0) return;
820
+ const name = definition.name;
821
+ if (environment.constants.has(name) || environment.substitutions.has(name)) return;
822
+ if (!isConstantLevel(definition, environment)) return;
823
+ try {
824
+ markNormalized(
825
+ evaluateDefinitionValue(definition, {
826
+ environment,
827
+ scope: undefined,
828
+ state: undefined,
829
+ next: undefined,
830
+ }),
831
+ );
832
+ } catch (error) {
833
+ // TLC swallows whatever the definition throws, a stack overflow included.
834
+ if (!(error instanceof TlaEvaluationError) && !isStackOverflow(error)) throw error;
835
+ }
836
+ });
837
+
576
838
  const forceThunk = (thunk: Thunk, context: Context) => {
577
839
  const isSameState = thunk.state === context.state && thunk.next === context.next;
578
840
  if (isSameState && thunk.cache !== undefined) return thunk.cache;
@@ -859,11 +1121,7 @@ const evaluateLocalIdentifier = (name: string, expression: Expression, context:
859
1121
  const global = findGlobalName(name, context.environment);
860
1122
  if (global?.kind === "Variable") {
861
1123
  const value = context.state?.[global.index];
862
- if (value === undefined) {
863
- throw new TlaEvaluationError(
864
- `The variable ${name} is not assigned at ${describeLocation(expression)}`,
865
- );
866
- }
1124
+ if (value === undefined) throw createUnassignedError(name, expression);
867
1125
  return value;
868
1126
  }
869
1127
  if (global?.kind === "Value") return global.value;
@@ -889,14 +1147,29 @@ const IMPURE_BUILTINS = new Set([
889
1147
  export const isImpureBuiltin = (name: string, environment: Environment) =>
890
1148
  IMPURE_BUILTINS.has(name) || environment.builtins.get(name)?.isStateLevel === true;
891
1149
 
892
- const impureDefinitions = new WeakMap<Definition, boolean>();
1150
+ interface Impurity {
1151
+ builtins: Set<string>;
1152
+ definitions: WeakMap<Definition, boolean>;
1153
+ }
1154
+
1155
+ const ANY_EFFECT: Impurity = { builtins: IMPURE_BUILTINS, definitions: new WeakMap() };
1156
+
1157
+ // An Assert that held holds again, so evaluating it twice looks the same as evaluating it once.
1158
+ const REPEATED_EFFECT: Impurity = {
1159
+ builtins: new Set([...IMPURE_BUILTINS].filter((name) => name !== "Assert")),
1160
+ definitions: new WeakMap(),
1161
+ };
893
1162
 
894
1163
  const isEvaluatedOnce = (definition: Definition, environment: Environment) =>
895
1164
  definition.kind === "Operator" &&
896
1165
  definition.params.length === 0 &&
897
1166
  isConstantLevel(definition, environment);
898
1167
 
899
- const callsImpureBuiltin = (expression: Expression, environment: Environment): boolean => {
1168
+ const callsImpureBuiltin = (
1169
+ expression: Expression,
1170
+ environment: Environment,
1171
+ impurity: Impurity,
1172
+ ): boolean => {
900
1173
  const name =
901
1174
  expression.kind === "Identifier"
902
1175
  ? expression.name
@@ -905,42 +1178,68 @@ const callsImpureBuiltin = (expression: Expression, environment: Environment): b
905
1178
  : undefined;
906
1179
  if (name !== undefined && !isLocallyResolved(expression)) {
907
1180
  const definition = getDefinition(name, environment);
908
- if (!definition && isImpureBuiltin(name, environment)) return true;
1181
+ const isImpureCall =
1182
+ impurity.builtins.has(name) || environment.builtins.get(name)?.isStateLevel === true;
1183
+ if (!definition && isImpureCall) return true;
909
1184
  if (
910
1185
  definition &&
911
1186
  !isEvaluatedOnce(definition, environment) &&
912
- isImpureDefinition(definition, environment)
1187
+ isImpureDefinition(definition, environment, impurity)
913
1188
  ) {
914
1189
  return true;
915
1190
  }
916
1191
  }
917
- return getChildren(expression).some((child) => callsImpureBuiltin(child, environment));
1192
+ return getChildren(expression).some((child) => callsImpureBuiltin(child, environment, impurity));
918
1193
  };
919
1194
 
920
1195
  // TLC evaluates a constant definition without parameters once, so only other definitions pass
921
1196
  // on the side effects and random choices of the builtins they call.
922
- const isImpureDefinition = (definition: Definition, environment: Environment): boolean => {
923
- const cached = impureDefinitions.get(definition);
1197
+ const isImpureDefinition = (
1198
+ definition: Definition,
1199
+ environment: Environment,
1200
+ impurity = ANY_EFFECT,
1201
+ ): boolean => {
1202
+ const cached = impurity.definitions.get(definition);
924
1203
  if (cached !== undefined) return cached;
925
- impureDefinitions.set(definition, false);
1204
+ impurity.definitions.set(definition, false);
926
1205
  const isImpure =
927
- callsImpureBuiltin(definition.body, environment) ||
1206
+ callsImpureBuiltin(definition.body, environment, impurity) ||
928
1207
  (definition.kind === "Function" &&
929
- definition.bounds.some((bound) => callsImpureBuiltin(bound.set, environment)));
930
- impureDefinitions.set(definition, isImpure);
1208
+ definition.bounds.some((bound) => callsImpureBuiltin(bound.set, environment, impurity)));
1209
+ impurity.definitions.set(definition, isImpure);
931
1210
  return isImpure;
932
1211
  };
933
1212
 
1213
+ // UNION and \cup build sets that stream the sets they combine until TLC caches them, and TLC
1214
+ // builds a new one at each evaluation.
1215
+ const STREAMED_SET: Impurity = {
1216
+ builtins: new Set(["UNION", "\\cup"]),
1217
+ definitions: new WeakMap(),
1218
+ };
1219
+
934
1220
  // TLC's next-state generator does not bind LET definitions to values, so each reference to one
935
- // that calls an impure builtin evaluates it again.
1221
+ // evaluates it again: one that calls an impure builtin repeats its effects, and a set one builds
1222
+ // with UNION or \cup starts out uncached.
936
1223
  export const getReevaluatedDefinitions = (definitions: Definition[], environment: Environment) =>
937
- new Set(definitions.filter((definition) => isImpureDefinition(definition, environment)));
1224
+ new Set(
1225
+ definitions.filter(
1226
+ (definition) =>
1227
+ isImpureDefinition(definition, environment) ||
1228
+ isImpureDefinition(definition, environment, STREAMED_SET),
1229
+ ),
1230
+ );
938
1231
 
939
1232
  export const isImpure = (environment: Environment) =>
940
1233
  [...environment.definitions.values()].some((definition) =>
941
1234
  isImpureDefinition(definition, environment),
942
1235
  );
943
1236
 
1237
+ // Whether evaluating a definition again can show, such as by printing twice.
1238
+ export const hasRepeatedEffects = (environment: Environment) =>
1239
+ [...environment.definitions.values()].some((definition) =>
1240
+ isImpureDefinition(definition, environment, REPEATED_EFFECT),
1241
+ );
1242
+
944
1243
  const closedConstants = new WeakMap<Expression, boolean>();
945
1244
 
946
1245
  export const isClosedConstant = (expression: Expression, environment: Environment): boolean => {
@@ -1004,7 +1303,11 @@ const computeIsClosedConstant = (
1004
1303
  return global?.kind === "Definition" && isEvaluatedOnce(global.definition, environment);
1005
1304
  }
1006
1305
  if (expression.kind === "Apply") {
1007
- if (isImpureBuiltin(expression.operator, environment) || expression.operator === "~>") {
1306
+ if (
1307
+ isImpureBuiltin(expression.operator, environment) ||
1308
+ STREAMED_SET.builtins.has(expression.operator) ||
1309
+ expression.operator === "~>"
1310
+ ) {
1008
1311
  return false;
1009
1312
  }
1010
1313
  const operator = resolveGlobalOperator(expression.operator, environment);
@@ -1076,12 +1379,128 @@ const isStateCached = (expression: Expression, environment: Environment) =>
1076
1379
  getReadVariables(expression, environment) !== undefined &&
1077
1380
  !hasFreeLocals(expression, NO_BOUND_NAMES);
1078
1381
 
1382
+ // A set filter TLC evaluates lazily, with how to rebuild it so that its predicate runs in another
1383
+ // environment.
1384
+ interface RebindableFilteredSet extends FilteredSetValue {
1385
+ rebind: (environment: Environment) => Value;
1386
+ }
1387
+
1388
+ const isRebindableFilteredSet = (value: Value): value is RebindableFilteredSet =>
1389
+ typeof value === "object" && value.kind === "FilteredSet" && "rebind" in value;
1390
+
1391
+ // TLC's CallStackTool rebinds the lazy values its evaluations return, so their later evaluation
1392
+ // records its call stack too.
1393
+ const traceEvaluator =
1394
+ (
1395
+ expression: Expression,
1396
+ evaluator: Evaluator,
1397
+ environment: Environment,
1398
+ callStack: CallStack,
1399
+ ): Evaluator =>
1400
+ (context) => {
1401
+ callStack.expressions.push(expression);
1402
+ const outerSets = setTrace.sets;
1403
+ const outerCallStack = setTrace.callStack;
1404
+ const sets = outerSets ?? [];
1405
+ const depth = sets.length;
1406
+ setTrace.sets = sets;
1407
+ setTrace.callStack = callStack;
1408
+ try {
1409
+ const computed = evaluator(context);
1410
+ const value = isRebindableFilteredSet(computed) ? computed.rebind(environment) : computed;
1411
+ callStack.values.set(expression, value);
1412
+ if (typeof value === "object" && value.kind !== "FilteredSet" && isSourced(expression)) {
1413
+ callStack.sources.set(value, expression);
1414
+ }
1415
+ return value;
1416
+ } catch (error) {
1417
+ const failed = error instanceof Error ? callStack.failures.get(error) : undefined;
1418
+ if (error instanceof Error) callStack.failures.set(error, expression);
1419
+ const receiver = getReceiver(expression, callStack.values);
1420
+ const received =
1421
+ receiver && !getChildren(expression).some((child) => child === failed)
1422
+ ? callStack.values.get(receiver)
1423
+ : undefined;
1424
+ const value =
1425
+ expression.kind === "FunctionApplication" &&
1426
+ received !== undefined &&
1427
+ !isFunctionValue(received)
1428
+ ? undefined
1429
+ : received;
1430
+ freezeCallStack(
1431
+ callStack,
1432
+ [value, ...sets.slice(depth).filter((set) => set !== value)],
1433
+ error,
1434
+ );
1435
+ throw error;
1436
+ } finally {
1437
+ if (!callStack.isFrozen) callStack.expressions.pop();
1438
+ sets.length = depth;
1439
+ setTrace.sets = outerSets;
1440
+ setTrace.callStack = outerCallStack;
1441
+ }
1442
+ };
1443
+
1444
+ // A method of a value with a source raises a FingerprintException, which each value with a source
1445
+ // whose method called it heads in turn. CallStack#freeze adds their sources to the stack, outermost
1446
+ // first. The values are those whose methods failed, outermost first.
1447
+ export const freezeCallStack = (
1448
+ callStack: CallStack,
1449
+ values: (Value | undefined)[],
1450
+ error: unknown,
1451
+ ) => {
1452
+ // A set that streams its elements enumerates itself too, so it can appear twice.
1453
+ const sources = [...new Set(values)].flatMap((item) => {
1454
+ const source = typeof item === "object" ? callStack.sources.get(item) : undefined;
1455
+ return source ? [source] : [];
1456
+ });
1457
+ // A value with a source raises a FingerprintException even when the stack is frozen already.
1458
+ if (sources.length > 0 && error instanceof TlaEvaluationError) {
1459
+ if (!callStack.isFrozen) callStack.expressions.push(...sources);
1460
+ const inner = callStack.fingerprint;
1461
+ callStack.fingerprint = {
1462
+ sources: [...sources, ...(inner?.sources ?? [])],
1463
+ reason: inner?.reason ?? error.message,
1464
+ };
1465
+ }
1466
+ callStack.isFrozen = true;
1467
+ };
1468
+
1469
+ // A FingerprintException that a method of a value with a source raises, or that passes through one,
1470
+ // takes the value's source as its new head.
1471
+ const headFingerprint = (callStack: CallStack, source: Expression, error: unknown) => {
1472
+ if (!(error instanceof TlaEvaluationError)) return;
1473
+ if (!callStack.isFrozen) callStack.expressions.push(source);
1474
+ callStack.isFrozen = true;
1475
+ const inner = callStack.fingerprint;
1476
+ callStack.fingerprint = {
1477
+ sources: [source, ...(inner?.sources ?? [])],
1478
+ reason: inner?.reason ?? error.message,
1479
+ };
1480
+ };
1481
+
1482
+ // A copy of the environment that records the call stack of each evaluation, with evaluators of its
1483
+ // own since the environment's evaluators record nothing.
1484
+ export const createTracingEnvironment = (environment: Environment): Environment => ({
1485
+ ...environment,
1486
+ evaluators: new WeakMap(),
1487
+ callStack: {
1488
+ expressions: [],
1489
+ isFrozen: false,
1490
+ sources: new WeakMap(),
1491
+ values: new WeakMap(),
1492
+ failures: new WeakMap(),
1493
+ },
1494
+ });
1495
+
1079
1496
  export const getEvaluator = (expression: Expression, environment: Environment): Evaluator => {
1080
1497
  const cached = environment.evaluators.get(expression);
1081
1498
  if (cached) return cached;
1082
1499
  const compiled = compile(expression, environment);
1083
- const evaluator =
1084
- isWorthCaching(expression) && isClosedConstant(expression, environment)
1500
+ const callStack = environment.callStack;
1501
+ const evaluator = callStack
1502
+ ? traceEvaluator(expression, compiled, environment, callStack)
1503
+ : isWorthCaching(expression) && isClosedConstant(expression, environment)
1085
1504
  ? cacheFirstValue(compiled)
1086
1505
  : isStateCached(expression, environment)
1087
1506
  ? cacheStateValue(compiled)
@@ -1093,6 +1512,7 @@ export const getEvaluator = (expression: Expression, environment: Environment):
1093
1512
  const entryEvaluators = new WeakMap<Expression, Evaluator>();
1094
1513
 
1095
1514
  const getEntryEvaluator = (expression: Expression, environment: Environment) => {
1515
+ if (environment.callStack) return getEvaluator(expression, environment);
1096
1516
  const cached = entryEvaluators.get(expression);
1097
1517
  if (cached) return cached;
1098
1518
  const evaluator =
@@ -1116,11 +1536,7 @@ const compileIdentifier = (
1116
1536
  const index = global.index;
1117
1537
  return (context) => {
1118
1538
  const value = context.state?.[index];
1119
- if (value === undefined) {
1120
- throw new TlaEvaluationError(
1121
- `The variable ${name} is not assigned at ${describeLocation(expression)}`,
1122
- );
1123
- }
1539
+ if (value === undefined) throw createUnassignedError(name, expression);
1124
1540
  return value;
1125
1541
  };
1126
1542
  }
@@ -1320,14 +1736,21 @@ const compileClosureCall = (
1320
1736
  const compiled = { body: undefined as Evaluator | undefined };
1321
1737
  const evaluateBody = (scope: Scope | undefined, context: Context) => {
1322
1738
  compiled.body ??= getEntryEvaluator(closure.body, environment);
1323
- return compiled.body({ environment, scope, state: context.state, next: context.next });
1739
+ return compiled.body({
1740
+ environment,
1741
+ scope,
1742
+ state: context.state,
1743
+ next: context.next,
1744
+ isKeepLazy: context.isKeepLazy,
1745
+ });
1324
1746
  };
1325
1747
  if (!isMemoized) return (context) => evaluateBody(bindArguments(context), context);
1326
1748
  const memo = getCallMemo(closure);
1327
1749
  return (context) => {
1328
1750
  const scope = bindArguments(context);
1329
1751
  const values = getArgumentValues(scope, args.length);
1330
- if (!values) return evaluateBody(scope, context);
1752
+ // A call TLC evaluates with EvalControl.KeepLazy builds what a memoized one wouldn't.
1753
+ if (!values || context.isKeepLazy) return evaluateBody(scope, context);
1331
1754
  let hash = values.length;
1332
1755
  for (const value of values) hash = combineHash(hash, getValueHash(value));
1333
1756
  const bucket = memo.calls.get(hash);
@@ -1364,7 +1787,9 @@ const compileApply = (
1364
1787
  ? undefined
1365
1788
  : resolveGlobalOperator(expression.operator, environment);
1366
1789
  if (global?.kind === "Closure") {
1367
- return compileClosureCall(global, args, environment, isMemoizable(expression, environment));
1790
+ // The replay records the evaluation of each call, which TLC repeats.
1791
+ const isMemoized = !environment.callStack && isMemoizable(expression, environment);
1792
+ return compileClosureCall(global, args, environment, isMemoized);
1368
1793
  }
1369
1794
  if (global?.kind === "Builtin" && global.name === "DOMAIN") {
1370
1795
  const operand = getEvaluator(args[0], environment);
@@ -1374,7 +1799,7 @@ const compileApply = (
1374
1799
  // TLC sorts the value of a constant TLCEval argument only where no context binds a name.
1375
1800
  if (global?.kind === "Builtin" && global.name === "TLCEval" && args.length === 1) {
1376
1801
  const operand = getEvaluator(args[0], environment);
1377
- if (contextualApplications.has(expression) || isStateDependent(args[0], environment)) {
1802
+ if (contextualApplications.has(expression) || isNonconstant(args[0], environment)) {
1378
1803
  return operand;
1379
1804
  }
1380
1805
  return (context) =>
@@ -1387,6 +1812,16 @@ const compileApply = (
1387
1812
  return (context) => subset(left(context), right(context));
1388
1813
  }
1389
1814
  if (global?.kind === "Builtin") return compileBuiltinCall(global, args, environment);
1815
+ // TLC refuses action composition unless a Java property enables its incomplete implementation.
1816
+ if (expression.operator === "\\cdot" && args.length === 2) {
1817
+ return () => {
1818
+ throw new TlaEvaluationError(
1819
+ environment.runtime.version === "1.7.4"
1820
+ ? "The current version of TLC does not support action composition."
1821
+ : "The current version of TLC does not support action composition. An incomplete implementation can be enabled via the tlc2.tool.impl.Tool.cdot=true java property.",
1822
+ );
1823
+ };
1824
+ }
1390
1825
  return (context) => {
1391
1826
  const operator = resolveOperator(expression.operator, context);
1392
1827
  if (operator) return callOperator(operator, args, context);
@@ -1412,15 +1847,15 @@ const compileQuantifier = (
1412
1847
  const name = bound.pattern.name;
1413
1848
  const set = getEvaluator(bound.set, environment);
1414
1849
  return (context) => {
1415
- const elements = getEnumeratedElements(set(context), bound.set);
1416
- for (let index = 0; index < elements.length; index++) {
1417
- const result = expectBoolean(
1418
- body(withScope(context, bindValue(context.scope, name, elements[index]))),
1419
- description,
1420
- );
1421
- if (result !== isForall) return result;
1422
- }
1423
- return isForall;
1850
+ const isFound = someElement(
1851
+ getQuantifierElements(set(context), bound.set, environment.runtime.version),
1852
+ (element) =>
1853
+ expectBoolean(
1854
+ body(withScope(context, bindValue(context.scope, name, element))),
1855
+ description,
1856
+ ) !== isForall,
1857
+ );
1858
+ return isFound ? !isForall : isForall;
1424
1859
  };
1425
1860
  }
1426
1861
  const bounds = expression.bounds;
@@ -1429,17 +1864,15 @@ const compileQuantifier = (
1429
1864
  const sets = bounds.map((item) => getEvaluator(item.set, environment));
1430
1865
  return (context) => {
1431
1866
  const lists = sets.map((set, index) =>
1432
- getEnumeratedElements(set(context), bounds[index].set),
1867
+ getQuantifierElements(set(context), bounds[index].set, environment.runtime.version),
1433
1868
  );
1434
1869
  const visit = (index: number, scope: Scope | undefined): boolean => {
1435
1870
  if (index < 0) {
1436
1871
  return expectBoolean(body(withScope(context, scope)), description) !== isForall;
1437
1872
  }
1438
- const list = lists[index];
1439
- for (let position = 0; position < list.length; position++) {
1440
- if (visit(index - 1, bindValue(scope, names[index], list[position]))) return true;
1441
- }
1442
- return false;
1873
+ return someElement(lists[index], (element) =>
1874
+ visit(index - 1, bindValue(scope, names[index], element)),
1875
+ );
1443
1876
  };
1444
1877
  return visit(bounds.length - 1, context.scope) ? !isForall : isForall;
1445
1878
  };
@@ -1487,28 +1920,26 @@ const compileFunctionConstruction = (
1487
1920
  const bound = bounds[0];
1488
1921
  const isSingleName = bounds.length === 1 && bound.pattern.kind === "Name";
1489
1922
  const set = getEvaluator(bound.set, environment);
1490
- return (context) => {
1491
- const domain = isSingleName ? set(context) : getBoundsDomain(bounds, context);
1492
- if (expression.isRecursive || isKeptLazy || !isEnumerable(domain)) {
1493
- const functionValue = createLazyFunction(
1494
- domain,
1495
- (argument) => body(withScope(context, bindArgument(bounds, context.scope, argument))),
1496
- getLazyFunctionSource(bounds, expression.body, domain),
1497
- );
1498
- return bounds.length === 1 ? markLambdaFunction(functionValue) : functionValue;
1499
- }
1923
+ const construct = (domain: Value, context: Context) => {
1500
1924
  if (isSingleName && bound.pattern.kind === "Name") {
1501
1925
  const name = bound.pattern.name;
1502
1926
  const keys = getFunctionDomain(domain);
1503
- return markLambdaFunction(
1504
- createSortedFunction(
1505
- keys,
1506
- keys.map((key) => body(withScope(context, bindValue(context.scope, name, key)))),
1507
- ),
1927
+ const functionValue = createSortedFunction(
1928
+ keys,
1929
+ keys.map((key) => body(withScope(context, bindValue(context.scope, name, key)))),
1508
1930
  );
1931
+ // FcnLambdaValue#toFcnRcd builds a FcnRcdValue over an interval or an enumerated set.
1932
+ return isReducibleSet(domain) ? functionValue : markLambdaFunction(functionValue);
1509
1933
  }
1510
1934
  const pairs: [Value, Value][] = [];
1511
- forEachBinding(bounds, context, (scope) => {
1935
+ const sets = bounds.map((item) =>
1936
+ getNormalizedElements(
1937
+ evaluate(item.set, context),
1938
+ item.set,
1939
+ context.environment.runtime.version,
1940
+ ),
1941
+ );
1942
+ forEachBoundElement(bounds, sets, context.scope, (scope) => {
1512
1943
  const key =
1513
1944
  bounds.length === 1
1514
1945
  ? (lookupKey(bound.pattern, scope) ?? false)
@@ -1518,6 +1949,46 @@ const compileFunctionConstruction = (
1518
1949
  });
1519
1950
  return createFunction(pairs);
1520
1951
  };
1952
+ const createLazy = (domain: Value, context: Context) => {
1953
+ const functionValue = keepLambda({
1954
+ value: createLazyFunction(
1955
+ domain,
1956
+ (argument) => body(withScope(context, bindArgument(bounds, context.scope, argument))),
1957
+ getLazyFunctionSource(bounds, expression.body, domain),
1958
+ ),
1959
+ bounds,
1960
+ body: expression.body,
1961
+ scope: context.scope,
1962
+ });
1963
+ return bounds.length === 1 ? markLambdaFunction(functionValue) : functionValue;
1964
+ };
1965
+ const callStack = environment.callStack;
1966
+ return (context) => {
1967
+ const domain = isSingleName ? set(context) : getBoundsDomain(bounds, context);
1968
+ if (expression.isRecursive || isKeptLazy || context.isKeepLazy || !isEnumerable(domain)) {
1969
+ return createLazy(domain, context);
1970
+ }
1971
+ // TLC builds a function over a domain other than a set enumeration or an interval lazily, so
1972
+ // its body fails only where TLC forces it, as the replay does. Building it at once is faster
1973
+ // otherwise.
1974
+ if (!isReducibleSet(domain)) {
1975
+ if (callStack) return createLazy(domain, context);
1976
+ try {
1977
+ return construct(domain, context);
1978
+ } catch (error) {
1979
+ if (!(error instanceof TlaEvaluationError)) throw error;
1980
+ return createLazy(domain, context);
1981
+ }
1982
+ }
1983
+ if (!callStack) return construct(domain, context);
1984
+ // TLC builds the function in a method of the FcnLambdaValue that CallStackTool gives a source.
1985
+ try {
1986
+ return construct(domain, context);
1987
+ } catch (error) {
1988
+ headFingerprint(callStack, expression, error);
1989
+ throw error;
1990
+ }
1991
+ };
1521
1992
  };
1522
1993
 
1523
1994
  const compileExcept = (
@@ -1563,7 +2034,20 @@ const compileExcept = (
1563
2034
  };
1564
2035
  return (context) => {
1565
2036
  let current = evaluateFunction(context);
1566
- for (const item of updates) current = update(current, item.path, 0, context, item.value);
2037
+ for (const item of updates) {
2038
+ // TLC leaves the value as it is when an update's path is not in it, and warns.
2039
+ const found = { value: false };
2040
+ current = update(current, item.path, 0, context, (inner) => {
2041
+ found.value = true;
2042
+ return item.value(inner);
2043
+ });
2044
+ if (!found.value) {
2045
+ context.environment.runtime.warn(
2046
+ MESSAGE_CODE.exceptAppliedToUnknownField,
2047
+ `The EXCEPT was applied to non-existing fields of the value at\n${describeRange(expression.function)}`,
2048
+ );
2049
+ }
2050
+ }
1567
2051
  return current;
1568
2052
  };
1569
2053
  };
@@ -1576,23 +2060,37 @@ const compileSetComprehension = (
1576
2060
  const predicate = getEvaluator(expression.predicate, environment);
1577
2061
  const set = getEvaluator(expression.bound.set, environment);
1578
2062
  const pattern = expression.bound.pattern;
2063
+ const range = expression.predicate.location.range;
2064
+ const source = range && {
2065
+ names: pattern.kind === "Name" ? pattern.name : pattern.names.join(", "),
2066
+ predicate: formatRange(range),
2067
+ };
2068
+ const createTest = (evaluator: Evaluator, context: Context) => (element: Value) =>
2069
+ expectBoolean(
2070
+ evaluator(withScope(context, bindPattern(context.scope, pattern, element))),
2071
+ "a set filter predicate",
2072
+ );
2073
+ const createFiltered = (
2074
+ base: Value,
2075
+ context: Context,
2076
+ evaluator: Evaluator,
2077
+ ): RebindableFilteredSet => ({
2078
+ kind: "FilteredSet",
2079
+ base,
2080
+ test: createTest(evaluator, context),
2081
+ source,
2082
+ rebind: (tracing) =>
2083
+ createFiltered(
2084
+ base,
2085
+ { ...context, environment: tracing },
2086
+ getEvaluator(expression.predicate, tracing),
2087
+ ),
2088
+ });
1579
2089
  return (context) => {
1580
2090
  const base = set(context);
1581
- const test = (element: Value) =>
1582
- expectBoolean(
1583
- predicate(withScope(context, bindPattern(context.scope, pattern, element))),
1584
- "a set filter predicate",
1585
- );
1586
- const isReducible =
1587
- typeof base === "object" &&
1588
- (base.kind === "Set" || base.kind === "MixedSet" || base.kind === "Interval");
1589
- if (!isReducible) {
1590
- if (isSetValue(base)) return { kind: "FilteredSet", base, test };
1591
- throw new TlaEvaluationError(
1592
- `TLC encountered a non-enumerable quantifier bound ${formatValue(base)} at ${describeLocation(expression.bound.set)}`,
1593
- );
1594
- }
1595
- return createSortedSet(toFiniteSet(base).elements.filter(test));
2091
+ // TLC filters any value it can't enumerate lazily, and fails only when it uses the result.
2092
+ if (!isReducibleSet(base)) return createFiltered(base, context, predicate);
2093
+ return createSortedSet(toFiniteSet(base).elements.filter(createTest(predicate, context)));
1596
2094
  };
1597
2095
  }
1598
2096
  if (expression.kind === "SetMap") {
@@ -1615,10 +2113,18 @@ const compileSetComprehension = (
1615
2113
  };
1616
2114
  }
1617
2115
  const body = getEvaluator(expression.body, environment);
1618
- const bound = { pattern: expression.pattern, set };
2116
+ const evaluateSet = getEvaluator(set, environment);
1619
2117
  return (context) => {
2118
+ const base = evaluateSet(context);
2119
+ if (!isSetValue(base) || isOverriddenSet(base)) {
2120
+ throw new TlaEvaluationError(
2121
+ `Attempted to compute the value of an expression of\nform CHOOSE x \\in S: P, but S was not enumerable.\n${describeRange(expression)}`,
2122
+ );
2123
+ }
1620
2124
  const chosen = { value: undefined as Value | undefined };
1621
- forEachBinding([bound], context, (scope) => {
2125
+ const elements = getNormalizedElements(base, set, context.environment.runtime.version);
2126
+ someElement(elements, (element) => {
2127
+ const scope = bindPattern(context.scope, expression.pattern, element);
1622
2128
  if (!expectBoolean(body(withScope(context, scope)), "the body of CHOOSE")) return false;
1623
2129
  chosen.value = lookupKey(expression.pattern, scope);
1624
2130
  return true;
@@ -1632,16 +2138,42 @@ const compileSetComprehension = (
1632
2138
  };
1633
2139
  };
1634
2140
 
1635
- const compileRecord = (recordFields: RecordField[], environment: Environment): Evaluator => {
1636
- const fields = [...recordFields].sort((left, right) => compareValues(left.name, right.name));
1637
- const hasDuplicates = fields.some(
1638
- (field, index) => index > 0 && fields[index - 1].name === field.name,
2141
+ // TLC orders a record's fields by name.
2142
+ export const getSortedFields = (fields: RecordField[]) =>
2143
+ [...fields].sort((left, right) => compareValues(left.name, right.name));
2144
+
2145
+ export const hasDuplicateFields = (sortedFields: RecordField[]) =>
2146
+ sortedFields.some((field, index) => index > 0 && sortedFields[index - 1].name === field.name);
2147
+
2148
+ // TLC's Tool#evalAppl fails to look up a variable the state doesn't assign.
2149
+ export const createUnassignedError = (name: string, expression: Expression) =>
2150
+ new TlaUnassignedError(
2151
+ `In evaluation, the identifier ${name} is either undefined or not an operator.\n${describeRange(expression)}`,
2152
+ name,
2153
+ );
2154
+
2155
+ // TLC's Tool#enabled reads the subscript of <<A>>_v in the successor as a state of its own, and
2156
+ // names the fairness condition when A leaves a variable of v unassigned, unlike TLC 1.7.4's.
2157
+ export const toUnspecifiedSubscriptError = (error: unknown, version: TlcVersion | undefined) =>
2158
+ error instanceof TlaUnassignedError && version !== "1.7.4"
2159
+ ? new TlaEvaluationError(
2160
+ `The action formula A appearing in a WF_v(A) or SF_v(A) operator does not specify the primed value of the variable ${error.variable} occurring in the state formula v.\n`,
2161
+ )
2162
+ : error;
2163
+
2164
+ export const createPrimeOutsideActionError = (expression: Expression) =>
2165
+ new TlaEvaluationError(
2166
+ `A primed expression appears outside an action at ${describeLocation(expression)}`,
1639
2167
  );
2168
+
2169
+ const compileRecord = (recordFields: RecordField[], environment: Environment): Evaluator => {
2170
+ const fields = getSortedFields(recordFields);
2171
+ const hasDuplicates = hasDuplicateFields(fields);
1640
2172
  const values = fields.map((field) => getEvaluator(field.value, environment));
1641
2173
  if (hasDuplicates) {
1642
2174
  return (context) =>
1643
- createFunction(
1644
- fields.map((field, index): [Value, Value] => [field.name, values[index](context)]),
2175
+ createRecord(
2176
+ fields.map((field, index): [string, Value] => [field.name, values[index](context)]),
1645
2177
  );
1646
2178
  }
1647
2179
  const names = fields.map((field) => field.name);
@@ -1655,7 +2187,7 @@ const compileRecord = (recordFields: RecordField[], environment: Environment): E
1655
2187
  );
1656
2188
  }
1657
2189
  return (context) =>
1658
- createSortedFunction(
2190
+ createSortedRecord(
1659
2191
  names,
1660
2192
  values.map((value) => value(context)),
1661
2193
  );
@@ -1684,6 +2216,12 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1684
2216
  return compileIdentifier(expression, environment);
1685
2217
  case "Apply":
1686
2218
  return compileApply(expression, environment);
2219
+ case "Bracket":
2220
+ return () => {
2221
+ throw new TlaEvaluationError(
2222
+ `A bracket without a function or subscript is not an expression at ${describeLocation(expression)}`,
2223
+ );
2224
+ };
1687
2225
  case "OperatorReference":
1688
2226
  case "Lambda":
1689
2227
  return () => {
@@ -1696,7 +2234,7 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1696
2234
  return (context) => {
1697
2235
  for (let index = 0; index < operands.length; index++) {
1698
2236
  const value = operands[index](context);
1699
- if (typeof value !== "boolean") throw getConjunctError(expression, index, value);
2237
+ if (typeof value !== "boolean") throw getJunctionError(expression, index, value);
1700
2238
  if (!value) return false;
1701
2239
  }
1702
2240
  return true;
@@ -1706,7 +2244,9 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1706
2244
  const operands = expression.operands.map(child);
1707
2245
  return (context) => {
1708
2246
  for (let index = 0; index < operands.length; index++) {
1709
- if (expectBoolean(operands[index](context), "a disjunct")) return true;
2247
+ const value = operands[index](context);
2248
+ if (typeof value !== "boolean") throw getJunctionError(expression, index, value);
2249
+ if (value) return true;
1710
2250
  }
1711
2251
  return false;
1712
2252
  };
@@ -1714,16 +2254,13 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1714
2254
  case "Prime": {
1715
2255
  const inner = child(expression.expression);
1716
2256
  return (context) => {
1717
- if (!context.next) {
1718
- throw new TlaEvaluationError(
1719
- `A primed expression appears outside an action at ${describeLocation(expression)}`,
1720
- );
1721
- }
2257
+ if (!context.next) throw createPrimeOutsideActionError(expression);
1722
2258
  return inner({
1723
2259
  environment: context.environment,
1724
2260
  scope: context.scope,
1725
2261
  state: context.next,
1726
2262
  next: undefined,
2263
+ isKeepLazy: context.isKeepLazy,
1727
2264
  });
1728
2265
  };
1729
2266
  }
@@ -1748,16 +2285,25 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1748
2285
  }
1749
2286
  case "Case": {
1750
2287
  const arms = expression.arms.map((arm) => ({
2288
+ source: arm.condition,
1751
2289
  condition: child(arm.condition),
1752
2290
  body: child(arm.body),
1753
2291
  }));
1754
2292
  const other = expression.other ? child(expression.other) : undefined;
1755
2293
  return (context) => {
1756
2294
  for (const arm of arms) {
1757
- if (expectBoolean(arm.condition(context), "a CASE guard")) return arm.body(context);
2295
+ const value = arm.condition(context);
2296
+ if (typeof value !== "boolean") {
2297
+ throw new TlaEvaluationError(
2298
+ `A non-boolean expression (${getKindString(value)}) was used as a condition of a CASE. ${describeNode(arm.source)}`,
2299
+ );
2300
+ }
2301
+ if (value) return arm.body(context);
1758
2302
  }
1759
2303
  if (other) return other(context);
1760
- throw new TlaEvaluationError(`No CASE guard is true at ${describeLocation(expression)}`);
2304
+ throw new TlaEvaluationError(
2305
+ `Attempted to evaluate a CASE with no conditions true.\n${describeRange(expression)}`,
2306
+ );
1761
2307
  };
1762
2308
  }
1763
2309
  case "Let": {
@@ -1796,9 +2342,7 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1796
2342
  case "Record":
1797
2343
  return compileRecord(expression.fields, environment);
1798
2344
  case "RecordSet": {
1799
- const fields = [...expression.fields].sort((left, right) =>
1800
- compareValues(left.name, right.name),
1801
- );
2345
+ const fields = getSortedFields(expression.fields);
1802
2346
  const names = fields.map((field) => field.name);
1803
2347
  const sets = fields.map((field) => child(field.value));
1804
2348
  return (context) => ({ kind: "RecordSet", names, sets: sets.map((set) => set(context)) });
@@ -1817,20 +2361,27 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1817
2361
  };
1818
2362
  case "FunctionApplication": {
1819
2363
  keepLazy(expression.function);
1820
- const evaluateFunction = child(expression.function);
2364
+ const evaluated = child(expression.function);
2365
+ const evaluateFunction = (context: Context) =>
2366
+ expectFunction(evaluated(toKeepLazyContext(context)), expression);
1821
2367
  const args = expression.args.map(child);
2368
+ const describeMissing = getMissingArgumentDescriber(environment.runtime.version);
1822
2369
  if (args.length === 1) {
1823
2370
  const argument = args[0];
1824
- return (context) => applyFunction(evaluateFunction(context), argument(context));
2371
+ return (context) =>
2372
+ applyFunction(evaluateFunction(context), argument(context), describeMissing);
1825
2373
  }
1826
2374
  return (context) =>
1827
- applyFunction(evaluateFunction(context), createTuple(args.map((arg) => arg(context))));
2375
+ applyFunction(
2376
+ evaluateFunction(context),
2377
+ createTuple(args.map((arg) => arg(context))),
2378
+ describeMissing,
2379
+ );
1828
2380
  }
1829
2381
  case "FieldAccess": {
1830
2382
  const record = child(expression.record);
1831
- const field = expression.field;
1832
- const describeMissing = getFieldError(expression);
1833
- return (context) => applyFunction(record(context), field, describeMissing);
2383
+ const select = getFieldSelector(expression);
2384
+ return (context) => select(record(context));
1834
2385
  }
1835
2386
  case "Product": {
1836
2387
  const factors = expression.factors.map(child);