tla-ts 0.0.3-dev.a85c0bd → 0.0.3-dev.ab9c809

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/src/errors.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { SourceRange } from "./ast";
1
2
  import { EXIT_STATUS, getExitCode } from "./exit-codes";
2
3
  import type { Value } from "./values";
3
4
 
@@ -27,16 +28,55 @@ export interface SyntaxFailure {
27
28
  isEnd: boolean;
28
29
  }
29
30
 
31
+ // An error SANY reports at a location, such as "In module M" or a range in a module.
32
+ export interface SanyError {
33
+ location: string;
34
+ message: string;
35
+ }
36
+
37
+ // The errors SANY reports for a spec. A fatal error stops it before semantic analysis. SANY's
38
+ // parser prints its message for a module it rejects before the report.
39
+ export interface SanyReport {
40
+ errors: SanyError[];
41
+ isFatal: boolean;
42
+ parseError?: string;
43
+ }
44
+
30
45
  export class TlaSyntaxError extends TlaError {
31
46
  failure: SyntaxFailure | undefined;
47
+ sany: SanyReport | undefined;
32
48
 
33
- constructor(message: string, cause?: unknown, failure?: SyntaxFailure) {
49
+ constructor(message: string, cause?: unknown, failure?: SyntaxFailure, sany?: SanyReport) {
34
50
  super(message, cause);
35
51
  this.name = "TlaSyntaxError";
36
52
  this.failure = failure;
53
+ this.sany = sany;
54
+ }
55
+ }
56
+
57
+ export const createSanyError = (errors: SanyError[], isFatal = false, parseError?: string) =>
58
+ new TlaSyntaxError(
59
+ errors.map((error) => `${error.location}\n\n${error.message}`).join("\n\n"),
60
+ undefined,
61
+ undefined,
62
+ { errors, isFatal, parseError },
63
+ );
64
+
65
+ // SANY's message for a module its parser rejects, such as a "***Parse Error***" with the
66
+ // productions it was in.
67
+ export class TlaParseError extends TlaError {
68
+ constructor(message: string) {
69
+ super(message);
70
+ this.name = "TlaParseError";
37
71
  }
38
72
  }
39
73
 
74
+ export const formatRange = (range: SourceRange) =>
75
+ `line ${range.start.line}, col ${range.start.column} to line ${range.end.line}, col ${range.end.column} of module ${range.module}`;
76
+
77
+ export const createSemanticError = (message: string, range: SourceRange) =>
78
+ createSanyError([{ location: formatRange(range), message }]);
79
+
40
80
  export class TlaConfigError extends TlaError {
41
81
  constructor(message: string, cause?: unknown) {
42
82
  super(message, cause);
@@ -63,6 +103,17 @@ export class TlaModuleError extends TlaEvaluationError {
63
103
  }
64
104
  }
65
105
 
106
+ // A variable that a partial state leaves without a value.
107
+ export class TlaUnassignedError extends TlaEvaluationError {
108
+ variable: string;
109
+
110
+ constructor(message: string, variable: string) {
111
+ super(message);
112
+ this.name = "TlaEvaluationError";
113
+ this.variable = variable;
114
+ }
115
+ }
116
+
66
117
  // TLC reports a successor state that the next-state relation leaves incomplete as an error of its
67
118
  // own, not as an exception. It keeps the name TlaEvaluationError, and index.ts doesn't export it.
68
119
  export class TlaIncompleteStateError extends TlaEvaluationError {
@@ -81,6 +132,17 @@ export class TlaIncompleteStateError extends TlaEvaluationError {
81
132
  }
82
133
  }
83
134
 
135
+ // TLC reports an initial state that the initial predicate leaves incomplete as an illegal state.
136
+ export class TlaIllegalStateError extends TlaEvaluationError {
137
+ state: (Value | undefined)[];
138
+
139
+ constructor(state: (Value | undefined)[]) {
140
+ super("current state is not a legal state");
141
+ this.name = "TlaEvaluationError";
142
+ this.state = state;
143
+ }
144
+ }
145
+
84
146
  export interface TlapmReport {
85
147
  failure?: string;
86
148
  exception?: string;
package/src/evaluate.ts CHANGED
@@ -10,16 +10,16 @@ import {
10
10
  type NumberExpression,
11
11
  type OperatorParam,
12
12
  type RecordField,
13
- type SourceRange,
14
13
  } from "./ast";
15
14
  import { getKindString } from "./builtins";
16
- import { TlaEvaluationError } from "./errors";
15
+ import { formatRange, TlaEvaluationError, TlaUnassignedError } from "./errors";
17
16
  import { EXIT_STATUS, setExitCode, setOwnExitCode } from "./exit-codes";
18
17
  import { generateEvaluator } from "./codegen";
19
18
  import type { CheckerRuntime } from "./runtime";
20
19
  import { getReadVariables } from "./dependencies";
21
20
  import { contextualApplications, mapChildren, substitutedExpressions } from "./instances";
22
21
  import { isEnabled } from "./successors";
22
+ import { getFingerprintTrace, valueSources, withSource } from "./value-sources";
23
23
  import {
24
24
  applyFunction,
25
25
  combineHash,
@@ -35,6 +35,7 @@ import {
35
35
  getDomain,
36
36
  getFunctionDomain,
37
37
  getIntervalElements,
38
+ getLazySubsets,
38
39
  getSequenceElements,
39
40
  getValueHash,
40
41
  isFunctionValue,
@@ -49,6 +50,7 @@ import {
49
50
  toFiniteSet,
50
51
  updateFunction,
51
52
  valuesEqual,
53
+ type FilteredSetValue,
52
54
  type FunctionValue,
53
55
  type LazyFunctionSource,
54
56
  type LazyFunctionValue,
@@ -117,6 +119,7 @@ export interface Environment {
117
119
  definitionValues: Map<Definition, Value>;
118
120
  constantLevels: Map<Definition, boolean>;
119
121
  evaluators: WeakMap<Expression, Evaluator>;
122
+ trace?: Expression[];
120
123
  }
121
124
 
122
125
  export interface Context {
@@ -146,9 +149,6 @@ const EXCEPT_AT = "@";
146
149
  export const describeLocation = (expression: Expression) =>
147
150
  `line ${expression.location.line}, column ${expression.location.column}`;
148
151
 
149
- export const formatRange = (range: SourceRange) =>
150
- `line ${range.start.line}, col ${range.start.column} to line ${range.end.line}, col ${range.end.column} of module ${range.module}`;
151
-
152
152
  export const describeRange = (expression: Expression) => {
153
153
  const range = expression.location.range;
154
154
  return range ? formatRange(range) : describeLocation(expression);
@@ -343,9 +343,8 @@ export const getEnumeratedElements = (set: Value, expression: Expression) => {
343
343
  : `TLC encountered the non-enumerable quantifier bound\n${text}\n${describeRange(expression)}\n${explanation}`,
344
344
  );
345
345
  }
346
- return typeof set === "object" && set.kind === "Interval"
347
- ? getIntervalElements(set)
348
- : toFiniteSet(set).elements;
346
+ if (typeof set === "object" && set.kind === "Interval") return getIntervalElements(set);
347
+ return getLazySubsets(set) ?? toFiniteSet(set).elements;
349
348
  };
350
349
 
351
350
  export const forEachBinding = (
@@ -1023,16 +1022,80 @@ const isStateCached = (expression: Expression, environment: Environment) =>
1023
1022
  getReadVariables(expression, environment) !== undefined &&
1024
1023
  !hasFreeLocals(expression, NO_BOUND_NAMES);
1025
1024
 
1025
+ // CallStackTool also evaluates the predicate of a lazy set filter it returns, even one that TLC
1026
+ // made before the replay.
1027
+ const filteredSetRetracers = new WeakMap<
1028
+ FilteredSetValue,
1029
+ (environment: Environment) => FilteredSetValue
1030
+ >();
1031
+
1032
+ const SOURCED_KINDS = new Set<Expression["kind"]>([
1033
+ "SetEnumeration",
1034
+ "SetMap",
1035
+ "SetFilter",
1036
+ "Tuple",
1037
+ "Record",
1038
+ "RecordSet",
1039
+ "FunctionSet",
1040
+ "Product",
1041
+ ]);
1042
+
1043
+ const SOURCED_OPERATORS = new Set(["SUBSET", "UNION", "DOMAIN", "\\cup", "\\cap", "\\"]);
1044
+
1045
+ // CallStackTool gives a set, tuple or record it builds the expression as its source, but not a lazy
1046
+ // set filter, which it returns as a copy.
1047
+ const isSourced = (expression: Expression, environment: Environment) =>
1048
+ SOURCED_KINDS.has(expression.kind) ||
1049
+ (expression.kind === "Apply" &&
1050
+ SOURCED_OPERATORS.has(expression.operator) &&
1051
+ !isLocallyResolved(expression) &&
1052
+ resolveGlobalOperator(expression.operator, environment)?.kind === "Builtin");
1053
+
1054
+ // When an evaluation fails, CallStackTool freezes the stack at the innermost expression and pushes
1055
+ // the source of each value whose method failed.
1056
+ const evaluateTraced = (
1057
+ evaluator: Evaluator,
1058
+ context: Context,
1059
+ trace: Expression[],
1060
+ depth: number,
1061
+ ) => {
1062
+ try {
1063
+ return evaluator(context);
1064
+ } catch (error) {
1065
+ if (trace.length === depth + 1) trace.push(...(getFingerprintTrace(error) ?? []));
1066
+ throw error;
1067
+ }
1068
+ };
1069
+
1026
1070
  export const getEvaluator = (expression: Expression, environment: Environment): Evaluator => {
1027
1071
  const cached = environment.evaluators.get(expression);
1028
1072
  if (cached) return cached;
1029
1073
  const compiled = compile(expression, environment);
1030
- const evaluator =
1074
+ const cachedEvaluator =
1031
1075
  isWorthCaching(expression) && isClosedConstant(expression, environment)
1032
1076
  ? cacheFirstValue(compiled)
1033
1077
  : isStateCached(expression, environment)
1034
1078
  ? cacheStateValue(compiled)
1035
1079
  : compiled;
1080
+ const trace = environment.trace;
1081
+ const isSourcedExpression = trace !== undefined && isSourced(expression, environment);
1082
+ // TLC's CallStackTool pushes each expression it evaluates and keeps the stack when one fails.
1083
+ const evaluator: Evaluator = trace
1084
+ ? (context) => {
1085
+ const depth = trace.length;
1086
+ trace.push(expression);
1087
+ const value = evaluateTraced(cachedEvaluator, context, trace, depth);
1088
+ trace.length = depth;
1089
+ if (isSourcedExpression && typeof value === "object" && value.kind !== "FilteredSet") {
1090
+ valueSources.current?.set(value, expression);
1091
+ }
1092
+ const retrace =
1093
+ typeof value === "object" && value.kind === "FilteredSet"
1094
+ ? filteredSetRetracers.get(value)
1095
+ : undefined;
1096
+ return retrace ? retrace(environment) : value;
1097
+ }
1098
+ : cachedEvaluator;
1036
1099
  environment.evaluators.set(expression, evaluator);
1037
1100
  return evaluator;
1038
1101
  };
@@ -1040,6 +1103,7 @@ export const getEvaluator = (expression: Expression, environment: Environment):
1040
1103
  const entryEvaluators = new WeakMap<Expression, Evaluator>();
1041
1104
 
1042
1105
  export const getEntryEvaluator = (expression: Expression, environment: Environment) => {
1106
+ if (environment.trace) return getEvaluator(expression, environment);
1043
1107
  const cached = entryEvaluators.get(expression);
1044
1108
  if (cached) return cached;
1045
1109
  const evaluator =
@@ -1148,11 +1212,32 @@ const getLazyArguments = (args: Expression[], context: Context): OperatorValue[]
1148
1212
  expression: arg,
1149
1213
  }));
1150
1214
 
1215
+ const RECEIVING_OPERATORS = new Set(["=", "#", "\\in", "\\notin", "\\cup", "\\cap", "\\"]);
1216
+
1217
+ // The argument whose method TLC calls to apply a built-in operator.
1218
+ const getReceiver = (name: string, left: Value, right: Value) =>
1219
+ name === "\\in" ||
1220
+ name === "\\notin" ||
1221
+ ((name === "\\cup" || name === "\\cap") && !isReducible(left))
1222
+ ? right
1223
+ : left;
1224
+
1151
1225
  const compileBuiltinCall = (
1152
1226
  builtin: Builtin,
1153
1227
  args: Expression[],
1154
1228
  environment: Environment,
1155
1229
  ): Evaluator => {
1230
+ if (environment.trace && RECEIVING_OPERATORS.has(builtin.name) && args.length === 2) {
1231
+ const evaluateLeft = getEvaluator(args[0], environment);
1232
+ const evaluateRight = getEvaluator(args[1], environment);
1233
+ return (context) => {
1234
+ const left = evaluateLeft(context);
1235
+ const right = evaluateRight(context);
1236
+ return withSource(getReceiver(builtin.name, left, right), () =>
1237
+ builtin.evaluate([left, right], context),
1238
+ );
1239
+ };
1240
+ }
1156
1241
  if (builtin.isLazy) {
1157
1242
  return (context) => builtin.evaluate(getLazyArguments(args, context), context);
1158
1243
  }
@@ -1312,6 +1397,13 @@ const compileApply = (
1312
1397
  if (global?.kind === "Builtin" && global.name === "DOMAIN") {
1313
1398
  const operand = getEvaluator(args[0], environment);
1314
1399
  const domain = getDomainOperator(expression);
1400
+ // TLC builds a new interval for the domain of a tuple, so the source it gives one stays its own.
1401
+ if (environment.trace) {
1402
+ return (context) => {
1403
+ const value = domain(operand(context));
1404
+ return typeof value === "object" && value.kind === "Interval" ? { ...value } : value;
1405
+ };
1406
+ }
1315
1407
  return (context) => domain(operand(context));
1316
1408
  }
1317
1409
  // TLC sorts the value of a constant TLCEval argument only where no context binds a name.
@@ -1327,6 +1419,13 @@ const compileApply = (
1327
1419
  const left = getEvaluator(args[0], environment);
1328
1420
  const right = getEvaluator(args[1], environment);
1329
1421
  const subset = getSubsetOperator(expression, global);
1422
+ if (environment.trace) {
1423
+ return (context) => {
1424
+ const subsetValue = left(context);
1425
+ const superset = right(context);
1426
+ return withSource(subsetValue, () => subset(subsetValue, superset));
1427
+ };
1428
+ }
1330
1429
  return (context) => subset(left(context), right(context));
1331
1430
  }
1332
1431
  if (global?.kind === "Builtin") return compileBuiltinCall(global, args, environment);
@@ -1532,13 +1631,21 @@ const compileSetComprehension = (
1532
1631
  const pattern = expression.bound.pattern;
1533
1632
  return (context) => {
1534
1633
  const base = set(context);
1535
- const test = (element: Value) =>
1634
+ const getTest = (evaluatePredicate: Evaluator) => (element: Value) =>
1536
1635
  expectBoolean(
1537
- predicate(withScope(context, bindPattern(context.scope, pattern, element))),
1636
+ evaluatePredicate(withScope(context, bindPattern(context.scope, pattern, element))),
1538
1637
  "a set filter predicate",
1539
1638
  );
1639
+ const test = getTest(predicate);
1540
1640
  if (!isReducible(base)) {
1541
- if (isSetValue(base)) return { kind: "FilteredSet", base, test };
1641
+ if (isSetValue(base)) {
1642
+ const filtered: FilteredSetValue = { kind: "FilteredSet", base, test };
1643
+ filteredSetRetracers.set(filtered, (traced) => ({
1644
+ ...filtered,
1645
+ test: getTest(getEvaluator(expression.predicate, traced)),
1646
+ }));
1647
+ return filtered;
1648
+ }
1542
1649
  throw new TlaEvaluationError(
1543
1650
  `TLC encountered a non-enumerable quantifier bound ${formatValue(base)} at ${describeLocation(expression.bound.set)}`,
1544
1651
  );
@@ -1592,8 +1699,9 @@ export const hasDuplicateFields = (sortedFields: RecordField[]) =>
1592
1699
 
1593
1700
  export const createUnassignedError = (name: string, expression: Expression) =>
1594
1701
  setOwnExitCode(
1595
- new TlaEvaluationError(
1702
+ new TlaUnassignedError(
1596
1703
  `In evaluation, the identifier ${name} is either undefined or not an operator.\n${describeRange(expression)}`,
1704
+ name,
1597
1705
  ),
1598
1706
  EXIT_STATUS.configParseError,
1599
1707
  );
@@ -1785,6 +1893,16 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1785
1893
  const evaluateFunction = child(expression.function);
1786
1894
  const args = expression.args.map(child);
1787
1895
  const describeNonFunction = getNonFunctionError(expression);
1896
+ if (args.length === 1 && environment.trace) {
1897
+ const argument = args[0];
1898
+ return (context) => {
1899
+ const functionValue = evaluateFunction(context);
1900
+ const argumentValue = argument(context);
1901
+ const apply = () =>
1902
+ applyFunction(functionValue, argumentValue, undefined, describeNonFunction);
1903
+ return isFunctionValue(functionValue) ? withSource(functionValue, apply) : apply();
1904
+ };
1905
+ }
1788
1906
  if (args.length === 1) {
1789
1907
  const argument = args[0];
1790
1908
  return (context) =>
@@ -1,4 +1,4 @@
1
- import { getValueFingerprint, getValueHash, type Value } from "./values";
1
+ import { assertFingerprintable, getValueFingerprint, getValueHash, type Value } from "./values";
2
2
 
3
3
  const EMPTY = 0;
4
4
  const INITIAL_CAPACITY = 1 << 12;
@@ -20,6 +20,7 @@ export const writeStateFingerprint = (state: Value[], fingerprint: Int32Array) =
20
20
  first = Math.imul(first ^ getValueHash(state[index]), 0x01000193);
21
21
  second = Math.imul(second ^ getValueFingerprint(state[index]), 0x5bd1e995);
22
22
  }
23
+ assertFingerprintable(state);
23
24
  fingerprint[0] = mix(first) || 1;
24
25
  fingerprint[1] = mix(second);
25
26
  };
package/src/instances.ts CHANGED
@@ -164,7 +164,7 @@ export const mapChildren = (
164
164
  case "RecordSet":
165
165
  return {
166
166
  ...expression,
167
- fields: expression.fields.map((field) => ({ name: field.name, value: plain(field.value) })),
167
+ fields: expression.fields.map((field) => ({ ...field, value: plain(field.value) })),
168
168
  };
169
169
  case "Except":
170
170
  return {