tla-ts 0.0.3-dev.7ca58b6 → 0.0.3-dev.868dd4c

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tla-ts",
3
- "version": "0.0.3-dev.7ca58b6",
3
+ "version": "0.0.3-dev.868dd4c",
4
4
  "description": "A TLA+ interpreter and model checker in TypeScript, 2× faster than TLC",
5
5
  "keywords": [
6
6
  "formal verification",
package/src/check.ts CHANGED
@@ -13,6 +13,7 @@ import {
13
13
  getErrorExitCode,
14
14
  TlaConfigError,
15
15
  TlaEvaluationError,
16
+ TlaIncompleteStateError,
16
17
  TlaModuleError,
17
18
  UNEXPECTED_EXCEPTION,
18
19
  } from "./errors";
@@ -59,7 +60,7 @@ import {
59
60
  type StateWriter,
60
61
  } from "./state-graph";
61
62
  import { getRepresentative, getSymmetryGroup } from "./symmetry";
62
- import { getTlcStringOrder, getTlcVariableOrder } from "./tlc-order";
63
+ import { getTlcStringOrder, getTlcDeclarationOrder } from "./tlc-order";
63
64
  import { createTlcFingerprinter, getTlcFingerprint } from "./tlc-random";
64
65
  import { createCanonicalizer } from "./canonical";
65
66
  import { getPossibleCounts, type CheckerRuntime } from "./runtime";
@@ -276,8 +277,11 @@ const getInvariants = (names: string[], environment: Environment) => {
276
277
  levels.params.size === 0
277
278
  ? ""
278
279
  : "\nNote that a bug can cause TLC to incorrectly report this error.\nIf you believe your TLA+ or PlusCal specification to be correct,\nplease check if this bug described in LevelNode.java starting at line 590ff affects you.";
279
- throw new TlaConfigError(
280
- `The invariant ${name} is not a state predicate (one with no primes or temporal operators).${note}`,
280
+ throw setExitCode(
281
+ new TlaConfigError(
282
+ `The invariant ${name} is not a state predicate (one with no primes or temporal operators).${note}`,
283
+ ),
284
+ EXIT_STATUS.safetyEvaluationFailure,
281
285
  );
282
286
  }
283
287
  return [{ name, expression: createIdentifier(name), scope: undefined }];
@@ -899,6 +903,18 @@ export const createSearch = (
899
903
  const withNextStateExitCode = (error: unknown) =>
900
904
  error instanceof TlaModuleError ? setExitCode(error, error.exitCode) : error;
901
905
 
906
+ // TLC reports a failure of the next-state relation as an unexpected exception, unless a standard
907
+ // module raised it as an EvalException.
908
+ const toNextStateError = (error: unknown) =>
909
+ error instanceof TlaEvaluationError &&
910
+ !(error instanceof TlaModuleError) &&
911
+ !(error instanceof TlaIncompleteStateError)
912
+ ? setExitCode(
913
+ new TlaEvaluationError(`${UNEXPECTED_EXCEPTION}${error.message}`, error),
914
+ getErrorExitCode(error),
915
+ )
916
+ : withNextStateExitCode(error);
917
+
902
918
  const withHeadline = (error: unknown, headline: string) =>
903
919
  error instanceof TlaEvaluationError
904
920
  ? setExitCode(
@@ -985,7 +1001,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
985
1001
  });
986
1002
 
987
1003
  const search = createSearch(config, environment, () =>
988
- getTlcVariableOrder(options.source, options.loadModule),
1004
+ getTlcDeclarationOrder(options.source, options.loadModule, "variable"),
989
1005
  );
990
1006
  const assumptionViolation = findAssumptionViolation(specification.assumptions, environment);
991
1007
  if (assumptionViolation) return createResult("assumption-violation", assumptionViolation);
@@ -1554,7 +1570,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1554
1570
  try {
1555
1571
  outcome.result = expandState(index);
1556
1572
  } catch (error) {
1557
- outcome.result = toFailure(withNextStateExitCode(error), getStateTrace(index));
1573
+ outcome.result = toFailure(toNextStateError(error), getStateTrace(index));
1558
1574
  }
1559
1575
  if (outcome.result) return outcome.result;
1560
1576
  outDegrees[getOutDegreeBucket()]++;
package/src/codegen.ts CHANGED
@@ -10,6 +10,8 @@ import {
10
10
  getSubsetOperator,
11
11
  getEvaluator,
12
12
  getFieldError,
13
+ getNonFunctionError,
14
+ getNonRecordError,
13
15
  isClosedConstant,
14
16
  isTlcInteger,
15
17
  isValueArgument,
@@ -250,12 +252,13 @@ const generateExpression = (generator: Generator, expression: Expression, frame:
250
252
  case "FunctionApplication": {
251
253
  keepLazy(expression.function);
252
254
  const functionCode = generate(expression.function);
255
+ const describeNonFunction = addReference(generator, getNonFunctionError(expression));
253
256
  if (expression.args.length === 1)
254
- return `apply(${functionCode}, ${generate(expression.args[0])})`;
255
- return `apply(${functionCode}, tuple([${expression.args.map((arg) => generate(arg)).join(", ")}]))`;
257
+ return `apply(${functionCode}, ${generate(expression.args[0])}, undefined, ${describeNonFunction})`;
258
+ return `apply(${functionCode}, tuple([${expression.args.map((arg) => generate(arg)).join(", ")}]), undefined, ${describeNonFunction})`;
256
259
  }
257
260
  case "FieldAccess":
258
- return `apply(${generate(expression.record)}, ${JSON.stringify(expression.field)}, ${addReference(generator, getFieldError(expression))})`;
261
+ return `apply(${generate(expression.record)}, ${JSON.stringify(expression.field)}, ${addReference(generator, getFieldError(expression))}, ${addReference(generator, getNonRecordError(expression))})`;
259
262
  case "Record": {
260
263
  const fields = getSortedFields(expression.fields);
261
264
  if (hasDuplicateFields(fields)) return generateDelegate(generator, expression, frame);
@@ -47,6 +47,7 @@ import { CORE_OPERATORS, getStandardModule, STANDARD_DEPENDENCIES } from "./stan
47
47
  import { resolveInstanceSubexpressions, resolveModuleSubexpressions } from "./subexpressions";
48
48
  import { checkModuleLevels, createLevelAnalyzer } from "./levels";
49
49
  import { checkInstances, type InstanceCheck } from "./substitution-levels";
50
+ import { getTlcDeclarationOrder } from "./tlc-order";
50
51
  import {
51
52
  checkInteger,
52
53
  createModelValue,
@@ -908,11 +909,19 @@ export const createEnvironment = (
908
909
  if (symbol.key === key && name !== key) definitions.set(name, alias);
909
910
  });
910
911
  });
911
- declaredConstants.forEach((name) => {
912
- if (!constants.has(name) && !substitutions.has(name) && !operatorKeys.has(name)) {
913
- throw new TlaConfigError(`The constant ${name} is not assigned a value by the configuration`);
914
- }
915
- });
912
+ const unassigned = declaredConstants.filter(
913
+ (name) => !constants.has(name) && !substitutions.has(name) && !operatorKeys.has(name),
914
+ );
915
+ if (unassigned.length > 0) {
916
+ // TLC reports the first constant it finds unassigned in SANY's order of declarations.
917
+ const name =
918
+ getTlcDeclarationOrder(options.source, options.loadModule, "constant").find((constant) =>
919
+ unassigned.includes(constant),
920
+ ) ?? unassigned[0];
921
+ throw new TlaConfigError(
922
+ `The constant parameter ${name} is not assigned a value by the configuration file.`,
923
+ );
924
+ }
916
925
 
917
926
  const environment: Environment = {
918
927
  runtime,
package/src/errors.ts CHANGED
@@ -55,6 +55,15 @@ export class TlaModuleError extends TlaEvaluationError {
55
55
  }
56
56
  }
57
57
 
58
+ // TLC reports a successor state that the next-state relation leaves incomplete as an error of its
59
+ // own, not as an exception. It keeps the name TlaEvaluationError, and index.ts doesn't export it.
60
+ export class TlaIncompleteStateError extends TlaEvaluationError {
61
+ constructor(message: string) {
62
+ super(message);
63
+ this.name = "TlaEvaluationError";
64
+ }
65
+ }
66
+
58
67
  export interface TlapmReport {
59
68
  failure?: string;
60
69
  exception?: string;
package/src/evaluate.ts CHANGED
@@ -30,6 +30,7 @@ import {
30
30
  createSortedSet,
31
31
  createWrittenRecord,
32
32
  createTuple,
33
+ describeMissingField,
33
34
  formatValue,
34
35
  getDomain,
35
36
  getFunctionDomain,
@@ -38,6 +39,7 @@ import {
38
39
  getValueHash,
39
40
  isFunctionValue,
40
41
  isOverriddenSet,
42
+ isRecordValue,
41
43
  isSameValue,
42
44
  markLambdaFunction,
43
45
  isReducible,
@@ -47,6 +49,7 @@ import {
47
49
  toFiniteSet,
48
50
  updateFunction,
49
51
  valuesEqual,
52
+ type FunctionValue,
50
53
  type LazyFunctionSource,
51
54
  type LazyFunctionValue,
52
55
  type Value,
@@ -182,8 +185,17 @@ export const getConjunctError = (
182
185
  };
183
186
 
184
187
  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)}`;
188
+ (expression: Expression & { kind: "FieldAccess" }) => (record: FunctionValue) =>
189
+ isRecordValue(record)
190
+ ? `Attempted to select nonexistent field "${expression.field}" from the record\n${formatValue(record)}\n${describeRange(expression)}`
191
+ : describeMissingField(record, expression.field);
192
+
193
+ export const getNonFunctionError = (expression: Expression) => (value: Value) =>
194
+ `A non-function (${getKindString(value)}) was applied as a function.\n${describeRange(expression)}`;
195
+
196
+ export const getNonRecordError =
197
+ (expression: Expression & { kind: "FieldAccess" }) => (value: Value) =>
198
+ `Attempted to select field "${expression.field}" from a non-record value ${formatValue(value)}\n${describeRange(expression)}`;
187
199
 
188
200
  export const getDomainOperator = (expression: Expression) => (value: Value) => {
189
201
  if (!isFunctionValue(value)) {
@@ -1574,7 +1586,9 @@ export const hasDuplicateFields = (sortedFields: RecordField[]) =>
1574
1586
  sortedFields.some((field, index) => index > 0 && sortedFields[index - 1].name === field.name);
1575
1587
 
1576
1588
  export const createUnassignedError = (name: string, expression: Expression) =>
1577
- new TlaEvaluationError(`The variable ${name} is not assigned at ${describeLocation(expression)}`);
1589
+ new TlaEvaluationError(
1590
+ `In evaluation, the identifier ${name} is either undefined or not an operator.\n${describeRange(expression)}`,
1591
+ );
1578
1592
 
1579
1593
  export const createPrimeOutsideActionError = (expression: Expression) =>
1580
1594
  new TlaEvaluationError(
@@ -1762,18 +1776,31 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1762
1776
  keepLazy(expression.function);
1763
1777
  const evaluateFunction = child(expression.function);
1764
1778
  const args = expression.args.map(child);
1779
+ const describeNonFunction = getNonFunctionError(expression);
1765
1780
  if (args.length === 1) {
1766
1781
  const argument = args[0];
1767
- return (context) => applyFunction(evaluateFunction(context), argument(context));
1782
+ return (context) =>
1783
+ applyFunction(
1784
+ evaluateFunction(context),
1785
+ argument(context),
1786
+ undefined,
1787
+ describeNonFunction,
1788
+ );
1768
1789
  }
1769
1790
  return (context) =>
1770
- applyFunction(evaluateFunction(context), createTuple(args.map((arg) => arg(context))));
1791
+ applyFunction(
1792
+ evaluateFunction(context),
1793
+ createTuple(args.map((arg) => arg(context))),
1794
+ undefined,
1795
+ describeNonFunction,
1796
+ );
1771
1797
  }
1772
1798
  case "FieldAccess": {
1773
1799
  const record = child(expression.record);
1774
1800
  const field = expression.field;
1775
1801
  const describeMissing = getFieldError(expression);
1776
- return (context) => applyFunction(record(context), field, describeMissing);
1802
+ const describeNonRecord = getNonRecordError(expression);
1803
+ return (context) => applyFunction(record(context), field, describeMissing, describeNonRecord);
1777
1804
  }
1778
1805
  case "Product": {
1779
1806
  const factors = expression.factors.map(child);
package/src/live-check.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { TlaEvaluationError } from "./errors";
2
+ import { EXIT_STATUS, setExitCode } from "./exit-codes";
2
3
  import { hasRepeatedEffects, type Environment } from "./evaluate";
3
4
  import {
4
5
  evaluateLive,
@@ -137,7 +138,10 @@ export const createLivenessChecker = (
137
138
  fairness.length === 0 ? violation : createJunction("And", [...fairness, violation]);
138
139
  const solutions = getSolutions(formula);
139
140
  if (solutions.length === 0) {
140
- throw new TlaEvaluationError(TAUTOLOGY_MESSAGE);
141
+ throw setExitCode(
142
+ new TlaEvaluationError(TAUTOLOGY_MESSAGE),
143
+ EXIT_STATUS.livenessEvaluationFailure,
144
+ );
141
145
  }
142
146
  const actionIds = new Map<string, number>();
143
147
  const checks = solutions.map((solution): Check => ({
@@ -15,7 +15,7 @@ import type {
15
15
  WorkerMessage,
16
16
  } from "./parallel";
17
17
  import { getSuccessors, type Successor } from "./successors";
18
- import { getTlcStringOrder, getTlcVariableOrder } from "./tlc-order";
18
+ import { getTlcStringOrder, getTlcDeclarationOrder } from "./tlc-order";
19
19
  import { OUT_DEGREE_BUCKETS } from "./tlc-summary";
20
20
  import { createStateDecoder, createStateEncoder, type EncodedStates } from "./transfer";
21
21
  import { getRankedStringCount, setStringOrder, type Value } from "./values";
@@ -61,7 +61,7 @@ const run = (start: StartMessage, parent: Port) => {
61
61
  });
62
62
  const environment = specification.environment;
63
63
  const search = createSearch(start.config, environment, () =>
64
- getTlcVariableOrder(start.source, loadModule),
64
+ getTlcDeclarationOrder(start.source, loadModule, "variable"),
65
65
  );
66
66
  const nextAction = search?.spec.next;
67
67
  if (!search || nextAction === undefined)
package/src/parallel.ts CHANGED
@@ -20,7 +20,7 @@ import {
20
20
  type SharedFingerprints,
21
21
  } from "./fingerprints";
22
22
  import { getInitialStates } from "./successors";
23
- import { getTlcStringOrder, getTlcVariableOrder } from "./tlc-order";
23
+ import { getTlcStringOrder, getTlcDeclarationOrder } from "./tlc-order";
24
24
  import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc-summary";
25
25
  import { createStateEncoder, type EncodedStates } from "./transfer";
26
26
  import { getRankedStringCount, setStringOrder, type Value } from "./values";
@@ -150,7 +150,7 @@ export const check = async (options: CheckOptions): Promise<CheckResult> => {
150
150
  });
151
151
  const environment = specification.environment;
152
152
  const search = createSearch(config, environment, () =>
153
- getTlcVariableOrder(options.source, loadModule),
153
+ getTlcDeclarationOrder(options.source, loadModule, "variable"),
154
154
  );
155
155
  if (findAssumptionViolation(specification.assumptions, environment)) return fallBack();
156
156
  if (
package/src/successors.ts CHANGED
@@ -7,7 +7,7 @@ import {
7
7
  type QuantifierExpression,
8
8
  } from "./ast";
9
9
  import { getReadVariables } from "./dependencies";
10
- import { TlaEvaluationError, UNEXPECTED_EXCEPTION } from "./errors";
10
+ import { TlaEvaluationError, TlaIncompleteStateError } from "./errors";
11
11
  import { EXIT_STATUS, setExitCode } from "./exit-codes";
12
12
  import {
13
13
  describeLocation,
@@ -866,7 +866,7 @@ const compileAction = (
866
866
  const body = arm?.body ?? other;
867
867
  if (!body)
868
868
  throw new TlaEvaluationError(
869
- `${UNEXPECTED_EXCEPTION}In computing next states, TLC encountered a CASE with no conditions true.\n${describeRange(expression)}`,
869
+ `In computing ${run.isInit ? "initial" : "next"} states, TLC encountered a CASE with no conditions true.\n${describeRange(expression)}`,
870
870
  );
871
871
  body(run, scope, partial, action, isFixed, onComplete);
872
872
  };
@@ -1057,7 +1057,7 @@ export const forEachSuccessor = (
1057
1057
  (partial, action) => {
1058
1058
  if (run.isStopped) return;
1059
1059
  if (!isComplete(partial)) {
1060
- throw new TlaEvaluationError(
1060
+ throw new TlaIncompleteStateError(
1061
1061
  `Successor state is not completely specified by action ${action ?? "Next"}. The following variables are not assigned: ${getMissingVariables(partial, environment).join(", ")}`,
1062
1062
  );
1063
1063
  }
package/src/symmetry.ts CHANGED
@@ -1,5 +1,6 @@
1
- import { TlaConfigError } from "./errors";
1
+ import { TlaConfigError, TlaEvaluationError, UNEXPECTED_EXCEPTION } from "./errors";
2
2
  import { evaluate, type Environment } from "./evaluate";
3
+ import { EXIT_STATUS, setExitCode } from "./exit-codes";
3
4
  import {
4
5
  compareValues,
5
6
  createFunction,
@@ -47,9 +48,13 @@ const composePermutations = (first: Images, second: Images) => {
47
48
  return composed;
48
49
  };
49
50
 
50
- const toImages = (value: Value, name: string) => {
51
+ // TLC checks the symmetry set outside any phase that reports an error itself.
52
+ const createSymmetryError = (message: string) =>
53
+ setExitCode(new TlaEvaluationError(`${UNEXPECTED_EXCEPTION}${message}`), EXIT_STATUS.error);
54
+
55
+ const toImages = (value: Value) => {
51
56
  if (!isFunctionValue(value)) {
52
- throw new TlaConfigError(`The symmetry values of ${name} must be functions`);
57
+ throw createSymmetryError("The symmetry values must be function records.");
53
58
  }
54
59
  const functionValue = toFiniteFunction(value);
55
60
  const permutation: Images = new Map();
@@ -65,8 +70,13 @@ const toImages = (value: Value, name: string) => {
65
70
 
66
71
  export const getSymmetryGroup = (name: string, environment: Environment): Permutation[] => {
67
72
  const definition = environment.definitions.get(name);
73
+ if (definition === undefined && !environment.constants.has(name)) {
74
+ throw new TlaConfigError(
75
+ `The symmetry function ${name} specified in the configuration file\nis not defined in the specification.`,
76
+ );
77
+ }
68
78
  if (definition?.kind !== "Operator" || definition.params.length > 0) {
69
- throw new TlaConfigError(`The symmetry function ${name} must specify a set of permutations`);
79
+ throw createSymmetryError(`The symmetry function ${name} must specify a set of permutations.`);
70
80
  }
71
81
  const value = evaluate(definition.body, {
72
82
  environment,
@@ -75,9 +85,9 @@ export const getSymmetryGroup = (name: string, environment: Environment): Permut
75
85
  next: undefined,
76
86
  });
77
87
  if (!isSetValue(value) || !isEnumerable(value)) {
78
- throw new TlaConfigError("The symmetry operator must specify a set of functions");
88
+ throw createSymmetryError("The symmetry operator must specify a set of functions.");
79
89
  }
80
- const permutations = toFiniteSet(value).elements.map((element) => toImages(element, name));
90
+ const permutations = toFiniteSet(value).elements.map(toImages);
81
91
  const isDisabled =
82
92
  definition.body.kind === "Apply" && definition.body.args.length >= permutations.length;
83
93
  if (isDisabled) return [];
package/src/tableau.ts CHANGED
@@ -289,7 +289,7 @@ const toDisjunctiveNormalForm = (expression: LiveExpression): LiveExpression =>
289
289
  total.value *= normal.operands.length;
290
290
  if (total.value > MAXIMUM_DISJUNCTS) {
291
291
  throw new TlaEvaluationError(
292
- "TLC cannot handle the temporal formula because it exceeds the maximum supported size in disjunctive normal form",
292
+ "TLC cannot handle the temporal formula because it exceeds the maximum supported size in disjunctive normal form.",
293
293
  );
294
294
  }
295
295
  }
package/src/tlc-order.ts CHANGED
@@ -278,9 +278,13 @@ const createModuleSet = (source: string, loadModule: ModuleLoader) => {
278
278
  (name === undefined ? undefined : nestedModules.get(name)) ?? getFile(name);
279
279
  };
280
280
 
281
- // The variables in the order TLC compares them: the reverse of the root module's context
282
- // enumeration, as ModuleNode.getVariableDecls returns them.
283
- export const getTlcVariableOrder = (source: string, loadModule: ModuleLoader): string[] => {
281
+ // The constants or variables in the order of ModuleNode.getConstantDecls or getVariableDecls: the
282
+ // reverse of the root module's context enumeration. TLC compares a state's variables in this order.
283
+ export const getTlcDeclarationOrder = (
284
+ source: string,
285
+ loadModule: ModuleLoader,
286
+ kind: "constant" | "variable",
287
+ ): string[] => {
284
288
  const getParsed = createModuleSet(source, loadModule);
285
289
  const getUnits = (unit: ParsedModule) => {
286
290
  const tokens = unit.tokens;
@@ -400,7 +404,7 @@ export const getTlcVariableOrder = (source: string, loadModule: ModuleLoader): s
400
404
  };
401
405
  return getContext(undefined)
402
406
  .enumerate()
403
- .filter((entry) => entry.kind === "variable")
407
+ .filter((entry) => entry.kind === kind)
404
408
  .map((entry) => entry.name)
405
409
  .reverse();
406
410
  };
package/src/values.ts CHANGED
@@ -1224,9 +1224,7 @@ const enumerateSet = (value: Value): Value[] => {
1224
1224
  if (isOverriddenSet(value.base)) getCardinality(value.base);
1225
1225
  const base = toFiniteSet(value.base).elements;
1226
1226
  if (base.length > MAXIMUM_ENUMERATED_SUBSET_BASE) {
1227
- throw new TlaEvaluationError(
1228
- `SUBSET of a set with ${base.length} elements is too large to enumerate`,
1229
- );
1227
+ throw new TlaEvaluationError(describeOverflow(value));
1230
1228
  }
1231
1229
  return getSortedSubsets(base);
1232
1230
  }
@@ -1752,10 +1750,61 @@ export const markLambdaFunction = <FunctionLike extends FunctionValue | LazyFunc
1752
1750
  return functionValue;
1753
1751
  };
1754
1752
 
1755
- const describeMissingArgument = (functionValue: Value, argument: Value) =>
1756
- typeof functionValue === "object" && lambdaFunctions.has(functionValue)
1757
- ? `In applying the function\n${prettyPrint(formatValue(functionValue))},\nthe first argument is:\n${prettyPrint(formatValue(argument))}\nwhich is not in its domain.\n`
1758
- : `Attempted to apply function ${formatValue(functionValue)} to ${formatValue(argument)}, which is not in its domain`;
1753
+ // TLC applies a tuple, a record and a function over an interval with their own classes, and each
1754
+ // reports a missing argument in its own words.
1755
+ const getFunctionClass = (functionValue: FunctionValue) => {
1756
+ const domain = functionValue.domain;
1757
+ if (domain.length === 0) return lambdaFunctions.has(functionValue) ? "FcnRcdValue" : "TupleValue";
1758
+ if (domain === intervalDomains[domain.length]) return "TupleValue";
1759
+ if (intervalArrays.has(domain)) return "IntervalFcnRcdValue";
1760
+ return domain.every((key) => typeof key === "string") ? "RecordValue" : "FcnRcdValue";
1761
+ };
1762
+
1763
+ const describeNotInDomain = (functionValue: FunctionValue, argument: Value) =>
1764
+ `Attempted to apply function:\n${prettyPrint(formatValue(functionValue))}\nto argument ${prettyPrint(formatValue(argument))}, which is not in the domain of the function.`;
1765
+
1766
+ const describeNonIntegerArgument = (argument: Value) =>
1767
+ `Attempted to apply function with integer domain to the non-integer argument ${prettyPrint(formatValue(argument))}`;
1768
+
1769
+ const describeMissingArgument = (
1770
+ functionValue: FunctionValue | LazyFunctionValue,
1771
+ argument: Value,
1772
+ ) => {
1773
+ if (lambdaFunctions.has(functionValue) || functionValue.kind === "LazyFunction")
1774
+ return `In applying the function\n${prettyPrint(formatValue(functionValue))},\nthe first argument is:\n${prettyPrint(formatValue(argument))}\nwhich is not in its domain.\n`;
1775
+ const functionClass = getFunctionClass(functionValue);
1776
+ if (functionClass === "TupleValue")
1777
+ return typeof argument === "number"
1778
+ ? `Attempted to access index ${argument} of tuple\n${prettyPrint(formatValue(functionValue))}\nwhich is out of bounds.`
1779
+ : `Attempted to access tuple at a non integral index: ${prettyPrint(formatValue(argument))}`;
1780
+ if (functionClass === "RecordValue")
1781
+ return typeof argument === "string"
1782
+ ? `Attempted to access nonexistent field '${argument}' of record\n${prettyPrint(formatValue(functionValue))}`
1783
+ : `Attempted to access record by a non-string argument: ${prettyPrint(formatValue(argument))}`;
1784
+ return functionClass === "IntervalFcnRcdValue" && typeof argument !== "number"
1785
+ ? describeNonIntegerArgument(argument)
1786
+ : describeNotInDomain(functionValue, argument);
1787
+ };
1788
+
1789
+ // TLC selects a field of a value that isn't a record from the function the value converts to,
1790
+ // which keeps a tuple's domain as an interval.
1791
+ export const describeMissingField = (functionValue: FunctionValue, field: string) =>
1792
+ getFunctionClass(functionValue) === "FcnRcdValue"
1793
+ ? describeNotInDomain(functionValue, field)
1794
+ : describeNonIntegerArgument(field);
1795
+
1796
+ export const isRecordValue = (functionValue: FunctionValue) =>
1797
+ getFunctionClass(functionValue) === "RecordValue";
1798
+
1799
+ // TLC checks the type of an argument to a tuple or a record before it looks the argument up, so
1800
+ // it never compares the argument with a key of another type.
1801
+ const isForeignKey = (domain: Value[], argument: Value) => {
1802
+ const first = domain[0];
1803
+ return typeof first === "number"
1804
+ ? typeof argument !== "number" &&
1805
+ (domain === intervalDomains[domain.length] || intervalArrays.has(domain))
1806
+ : typeof first === "string" && typeof argument !== "string";
1807
+ };
1759
1808
 
1760
1809
  const findKeyIndex = (domain: Value[], argument: Value) => {
1761
1810
  const first = domain[0];
@@ -1774,6 +1823,7 @@ export const applyFunction = (
1774
1823
  functionValue: Value,
1775
1824
  argument: Value,
1776
1825
  describeMissing?: (functionValue: FunctionValue) => string,
1826
+ describeNonFunction?: (value: Value) => string,
1777
1827
  ): Value => {
1778
1828
  if (typeof functionValue === "object" && functionValue.kind === "LazyFunction") {
1779
1829
  if (!isElementOf(argument, functionValue.domain)) {
@@ -1787,10 +1837,13 @@ export const applyFunction = (
1787
1837
  }
1788
1838
  if (typeof functionValue !== "object" || functionValue.kind !== "Function") {
1789
1839
  throw new TlaEvaluationError(
1790
- `Attempted to apply ${formatValue(functionValue)}, which is not a function`,
1840
+ describeNonFunction?.(functionValue) ??
1841
+ `Attempted to apply ${formatValue(functionValue)}, which is not a function`,
1791
1842
  );
1792
1843
  }
1793
- const position = findKeyIndex(functionValue.domain, argument);
1844
+ const position = isForeignKey(functionValue.domain, argument)
1845
+ ? -1
1846
+ : findKeyIndex(functionValue.domain, argument);
1794
1847
  if (position === -1) {
1795
1848
  throw new TlaEvaluationError(
1796
1849
  describeMissing?.(functionValue) ?? describeMissingArgument(functionValue, argument),