tla-ts 0.0.3-dev.852fbc8 → 0.0.3-dev.872f125

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 (80) hide show
  1. package/dist/cli.cjs +1 -1
  2. package/dist/cli.js +1 -1
  3. package/dist/index.cjs +1 -1
  4. package/dist/index.d.cts +165 -46
  5. package/dist/index.d.ts +165 -46
  6. package/dist/index.js +1 -1
  7. package/dist/parallel-worker.cjs +1 -1
  8. package/dist/parallel-worker.js +2 -2
  9. package/dist/parallel.cjs +1 -1
  10. package/dist/parallel.js +2 -2
  11. package/dist/run-cli.cjs +1351 -22
  12. package/dist/run-cli.js +1351 -22
  13. package/dist/transfer.cjs +83 -34
  14. package/dist/transfer.js +83 -34
  15. package/package.json +5 -1
  16. package/src/ast.ts +55 -7
  17. package/src/bags.ts +4 -7
  18. package/src/builtins.ts +29 -11
  19. package/src/bundled-modules.ts +3 -3
  20. package/src/canonical.ts +4 -3
  21. package/src/check.ts +1317 -425
  22. package/src/cli.ts +8 -1
  23. package/src/codegen.ts +68 -21
  24. package/src/config.ts +225 -206
  25. package/src/environment.ts +423 -127
  26. package/src/errors.ts +155 -18
  27. package/src/evaluate.ts +716 -262
  28. package/src/exit-codes.ts +6 -24
  29. package/src/index.ts +1 -0
  30. package/src/instances.ts +3 -1
  31. package/src/java-overrides.ts +104 -25
  32. package/src/levels.ts +149 -31
  33. package/src/lexer.ts +112 -29
  34. package/src/live-check.ts +204 -148
  35. package/src/liveness.ts +191 -122
  36. package/src/obligation-expression.ts +2 -2
  37. package/src/obligation-source.ts +2 -0
  38. package/src/parallel-worker.ts +6 -1
  39. package/src/parallel.ts +57 -6
  40. package/src/parser.ts +428 -141
  41. package/src/pcal-ast.ts +770 -0
  42. package/src/pcal-parse.ts +1523 -0
  43. package/src/pcal-tokenize.ts +516 -0
  44. package/src/pcal-translate.ts +1230 -0
  45. package/src/pcal-validate.ts +454 -0
  46. package/src/randomization.ts +24 -7
  47. package/src/resolve.ts +1420 -459
  48. package/src/run-cli.ts +1161 -196
  49. package/src/runtime.ts +16 -0
  50. package/src/sany-builtins.ts +147 -0
  51. package/src/sany-generator.ts +3128 -0
  52. package/src/sany-levels.ts +1208 -0
  53. package/src/sany-lexer.ts +545 -0
  54. package/src/sany-linter.ts +122 -0
  55. package/src/sany-modules.ts +1398 -0
  56. package/src/sany-nodes.ts +463 -0
  57. package/src/sany-parse-error.ts +2161 -0
  58. package/src/sany-report.ts +354 -0
  59. package/src/sany-selectors.ts +738 -0
  60. package/src/sany-source.ts +248 -0
  61. package/src/sany-xml.ts +1017 -0
  62. package/src/spec-description.ts +25 -5
  63. package/src/standard-modules.ts +202 -151
  64. package/src/standard-ranges.ts +116 -0
  65. package/src/state-graph.ts +29 -6
  66. package/src/subexpressions.ts +221 -161
  67. package/src/substitution-levels.ts +38 -17
  68. package/src/successors.ts +141 -173
  69. package/src/symmetry.ts +168 -50
  70. package/src/tableau.ts +3 -1
  71. package/src/tlc-ext.ts +13 -17
  72. package/src/tlc-messages.ts +329 -0
  73. package/src/tlc-module.ts +49 -21
  74. package/src/tlc-modules.ts +0 -4
  75. package/src/tlc-order.ts +55 -9
  76. package/src/tlc-random.ts +28 -3
  77. package/src/tlc-replay.ts +655 -0
  78. package/src/tlc-version.ts +18 -0
  79. package/src/transfer.ts +15 -3
  80. package/src/values.ts +705 -296
@@ -24,6 +24,7 @@ import {
24
24
  import { TEMPORAL_LEVEL } from "./levels";
25
25
  import { getLevel } from "./liveness";
26
26
  import { createRecord, createSet, createTuple, formatValue, type Value } from "./values";
27
+ import type { TlcVersion } from "./tlc-version";
27
28
 
28
29
  export interface SpecAction {
29
30
  name: string;
@@ -62,7 +63,8 @@ const toLocationValue = (location: SourceLocation) => {
62
63
  ]);
63
64
  };
64
65
 
65
- const toActionValue = (action: SpecAction) => {
66
+ // TLC's RecordValue(Action): the action's name and location, with the values of its parameters.
67
+ export const toActionValue = (action: SpecAction) => {
66
68
  const fields: [string, Value][] = [
67
69
  ["name", action.name],
68
70
  ["location", toLocationValue(action.location)],
@@ -249,8 +251,12 @@ const getActions = (
249
251
  return getInstanceActions(instanceAction, expression, scope, called, environment);
250
252
  if (!called) return [createSplitAction()];
251
253
  const args = getArguments(expression);
254
+ // TLC names an action after the operator it applies, as SANY names it in the spec.
255
+ const calledName = isLocallyResolved(expression)
256
+ ? called.name
257
+ : (environment.instanceNames.get(getOperatorName(expression) ?? "") ?? called.name);
252
258
  const callAction = (): SpecAction[] => [
253
- { name: called.name, location: expression.location, parameters: [], expression, scope },
259
+ { name: calledName, location: expression.location, parameters: [], expression, scope },
254
260
  ];
255
261
  if (isConstantDefinition(called, environment)) return callAction();
256
262
  if (args.some((arg) => getLevel(arg, scope, environment) !== 0)) return callAction();
@@ -266,7 +272,13 @@ const getActions = (
266
272
  }),
267
273
  called.scope,
268
274
  );
269
- return getActions(called.body, boundScope, called, environment, instanceActions);
275
+ return getActions(
276
+ called.body,
277
+ boundScope,
278
+ { ...called, name: calledName },
279
+ environment,
280
+ instanceActions,
281
+ );
270
282
  }, callAction);
271
283
  };
272
284
 
@@ -461,6 +473,13 @@ const describe = (
461
473
  return description;
462
474
  };
463
475
 
476
+ // TLC's initial predicates, which it conjoins to compute the initial states.
477
+ export const getInitActions = (
478
+ config: ModelConfig,
479
+ environment: Environment,
480
+ instanceActions: Map<string, InstanceAction>,
481
+ ) => describe(config, environment, instanceActions).inits;
482
+
464
483
  // TLC's split of the next-state relation into the actions it names in a behavior.
465
484
  export const getNextActions = (
466
485
  config: ModelConfig,
@@ -473,8 +492,9 @@ const formatParameters = (action: SpecAction) =>
473
492
  ? ""
474
493
  : `(${action.parameters.map((parameter) => formatValue(parameter[1])).join(",")})`;
475
494
 
476
- export const getActionLabel = (action: SpecAction) =>
477
- `${action.name === UNNAMED_ACTION ? "Action" : action.name}${formatParameters(action)} ${formatRange(action.location.range ?? BUILTIN_RANGE)}`;
495
+ // TLC's Action.getLocation, which TLC 1.7.4 names the action in without its parameters.
496
+ export const getActionLabel = (action: SpecAction, version?: TlcVersion) =>
497
+ `${action.name === UNNAMED_ACTION ? "Action" : action.name}${version === "1.7.4" ? "" : formatParameters(action)} ${formatRange(action.location.range ?? BUILTIN_RANGE)}`;
478
498
 
479
499
  // TLC's Action.getInvocationSignature, which names the action and the values of its parameters.
480
500
  export const getActionSignature = (action: SpecAction) =>
@@ -11,7 +11,7 @@ import {
11
11
  getNumber,
12
12
  getOperator,
13
13
  getSet,
14
- getIntegersSignature,
14
+ getJavaSignature,
15
15
  getJavaInteger,
16
16
  getValue,
17
17
  isOutOfRange,
@@ -19,7 +19,7 @@ import {
19
19
  } from "./builtins";
20
20
  import type { Builtin, BuiltinArgument } from "./evaluate";
21
21
  import type { CheckerRuntime } from "./runtime";
22
- import { BAGS_OPERATORS } from "./bags";
22
+ import { createBagsOperators } from "./bags";
23
23
  import { createJsonOperators, type FileSystem } from "./json";
24
24
  import { createRandomizationOperators } from "./randomization";
25
25
  import { createPossibleOperators, createTlcExtOperators } from "./tlc-ext";
@@ -40,7 +40,9 @@ import {
40
40
  isEnumerable,
41
41
  isFiniteSet,
42
42
  isFunctionValue,
43
- isReducible,
43
+ computeLikeTlcOnFailure,
44
+ isReducibleSet,
45
+ markStreamedSet,
44
46
  isSetValue,
45
47
  toFiniteSet,
46
48
  unionSorted,
@@ -48,13 +50,14 @@ import {
48
50
  createEnumeratedSet,
49
51
  EMPTY_SET,
50
52
  isEnumeratedSet,
51
- type ReducibleSet,
53
+ type IntervalValue,
52
54
  type MixedSetValue,
53
55
  type SetOperationValue,
54
56
  type SetValue,
55
57
  type Value,
56
58
  rankString,
57
59
  } from "./values";
60
+ import type { TlcVersion } from "./tlc-version";
58
61
 
59
62
  interface StandardModule {
60
63
  extends: string[];
@@ -76,6 +79,8 @@ const unionInTree = (sets: SetValue[], start: number, end: number): SetValue =>
76
79
 
77
80
  const SET_OPERATORS: SetOperationValue["operator"][] = ["\\cup", "\\cap", "\\"];
78
81
 
82
+ type ReducibleSet = SetValue | MixedSetValue | IntervalValue;
83
+
79
84
  const isMixedSet = (value: Value) => typeof value === "object" && value.kind === "MixedSet";
80
85
 
81
86
  const getReducibleElements = (set: ReducibleSet) =>
@@ -96,7 +101,9 @@ const combineReducible = (
96
101
  );
97
102
  }
98
103
  if (elements.length === 0) return other;
99
- if (!isReducible(other)) return { kind: "SetOperation", operator, left: set, right: other };
104
+ if (!isReducibleSet(other)) {
105
+ return markStreamedSet({ kind: "SetOperation", operator, left: set, right: other });
106
+ }
100
107
  const added = toFiniteSet(other).elements.filter((element) => !isElementOf(element, set));
101
108
  return createEnumeratedSet([...elements, ...added]);
102
109
  };
@@ -123,6 +130,7 @@ export const CORE_OPERATORS: Builtin[] = [
123
130
  ),
124
131
  defineOperator("\\subseteq", 2, (args) => {
125
132
  const left = getSet(args, 0, "\\subseteq");
133
+ // TLC tests each element of the left set for membership in the right value.
126
134
  const right = getValue(args, 1, "\\subseteq");
127
135
  const isPowerSets =
128
136
  typeof left === "object" &&
@@ -133,11 +141,18 @@ export const CORE_OPERATORS: Builtin[] = [
133
141
  if (isPowerSets) return isSubsetOf(toFiniteSet(left.base).elements, right.base);
134
142
  return isSubsetOf(toFiniteSet(left).elements, right);
135
143
  }),
144
+ // TLC defers the set operations of values that aren't sets to the enumeration or the membership
145
+ // tests of the result.
136
146
  ...SET_OPERATORS.map((operator) =>
137
147
  defineOperator(operator, 2, (args) => {
138
- const left = getSet(args, 0, operator);
139
- const right = getSet(args, 1, operator);
140
- if (isReducible(left) && isReducible(right) && !isMixedSet(left) && !isMixedSet(right)) {
148
+ const left = getValue(args, 0, operator);
149
+ const right = getValue(args, 1, operator);
150
+ if (
151
+ isReducibleSet(left) &&
152
+ isReducibleSet(right) &&
153
+ !isMixedSet(left) &&
154
+ !isMixedSet(right)
155
+ ) {
141
156
  if (operator === "\\cup" && isEmptySet(left)) return right;
142
157
  const merge =
143
158
  operator === "\\cup"
@@ -145,25 +160,24 @@ export const CORE_OPERATORS: Builtin[] = [
145
160
  : operator === "\\cap"
146
161
  ? intersectSorted
147
162
  : differenceSorted;
148
- // Merging compares elements across the sets. Where that fails, TLC's element-by-element
149
- // membership test fails or succeeds on its own.
150
- try {
151
- return merge(toFiniteSet(left), toFiniteSet(right));
152
- } catch (error) {
153
- if (!(error instanceof TlaEvaluationError)) throw error;
154
- }
163
+ // The merge compares the elements, which TLC tests for membership one by one instead.
164
+ return computeLikeTlcOnFailure(
165
+ () => merge(toFiniteSet(left), toFiniteSet(right)),
166
+ () => combineReducible(operator, left, right),
167
+ );
155
168
  }
156
- if (isReducible(left)) return combineReducible(operator, left, right);
157
- if (operator !== "\\" && isReducible(right)) return combineReducible(operator, right, left);
158
- return { kind: "SetOperation", operator, left, right };
169
+ if (isReducibleSet(left)) return combineReducible(operator, left, right);
170
+ if (operator !== "\\" && isReducibleSet(right))
171
+ return combineReducible(operator, right, left);
172
+ return markStreamedSet({ kind: "SetOperation", operator, left, right });
159
173
  }),
160
174
  ),
161
- defineOperator("SUBSET", 1, (args) => ({ kind: "Subset", base: getSet(args, 0, "SUBSET") })),
175
+ defineOperator("SUBSET", 1, (args) => ({ kind: "Subset", base: getValue(args, 0, "SUBSET") })),
162
176
  defineOperator("UNION", 1, (args) => {
163
177
  const outer = getSet(args, 0, "UNION");
164
178
  const sets = isEnumeratedSet(outer) ? outer.elements.filter(isEnumeratedSet) : [];
165
179
  if (!isEnumeratedSet(outer) || sets.length !== outer.elements.length) {
166
- return { kind: "Union", base: outer };
180
+ return markStreamedSet({ kind: "Union", base: outer });
167
181
  }
168
182
  if (isMixedSet(outer) || sets.some(isMixedSet)) {
169
183
  const union: MixedSetValue = { kind: "MixedSet", elements: [] };
@@ -185,51 +199,79 @@ export const CORE_OPERATORS: Builtin[] = [
185
199
  }),
186
200
  ];
187
201
 
188
- const DOT_DOT_SIGNATURE = getIntegersSignature("DotDot", "IntervalValue", 2);
202
+ const NEG_SIGNATURE = getJavaSignature("Integers", "Neg", "IntValue", 1);
189
203
 
190
- const NEG_SIGNATURE = getIntegersSignature("Neg", "IntValue", 1);
204
+ // TLC overrides the arithmetic of Naturals with the Java methods of tlc2.module.Naturals, or with
205
+ // those of tlc2.module.Integers when the spec loads Integers, and names the method in an error.
206
+ const createArithmeticOperators = (module: string) => {
207
+ const dotDotSignature = getJavaSignature(module, "DotDot", "IntervalValue", 2);
208
+ return [
209
+ defineArithmetic(module, "+", "Plus", (left, right) => left + right),
210
+ defineArithmetic(module, "-", "Minus", (left, right) => left - right),
211
+ defineArithmetic(module, "*", "Times", (left, right) => left * right),
212
+ defineArithmetic(module, "^", "Expt", (base, exponent) => {
213
+ if (exponent < 0) {
214
+ throw new TlaModuleError(
215
+ `The second argument of ^ should be a natural number, but instead it is:\n${exponent}`,
216
+ );
217
+ }
218
+ if (base === 0 && exponent === 0) throw new TlaModuleError("0^0 is undefined.");
219
+ return base ** exponent;
220
+ }),
221
+ defineArithmetic(module, "\\div", "Divide", (left, right) => {
222
+ if (right === 0) throw new TlaModuleError("The second argument of \\div is 0.");
223
+ // tlc2.module.Naturals#Divide floors only a quotient Java truncates below 0, and lets
224
+ // -2147483648 \div -1 overflow.
225
+ if (module === "Naturals") {
226
+ const truncated = Math.trunc(left / right) | 0;
227
+ return truncated < 0 && Math.imul(truncated, right) !== left ? truncated - 1 : truncated;
228
+ }
229
+ const quotient = Math.floor(left / right);
230
+ if (isOutOfRange(quotient)) throw createOverflowError(`${left} \\div ${right}`);
231
+ return quotient;
232
+ }),
233
+ defineArithmetic(module, "%", "Mod", (left, right) => {
234
+ if (right <= 0) {
235
+ throw new TlaModuleError(
236
+ `The second argument of % should be a positive number, but instead it is:\n${right}`,
237
+ );
238
+ }
239
+ return ((left % right) + right) % right;
240
+ }),
241
+ defineOperator("..", 2, (args) => ({
242
+ kind: "Interval",
243
+ low: getJavaInteger(getValue(args, 0, ".."), dotDotSignature),
244
+ high: getJavaInteger(getValue(args, 1, ".."), dotDotSignature),
245
+ })),
246
+ ];
247
+ };
248
+
249
+ const NATURALS_ARITHMETIC = createArithmeticOperators("Naturals");
250
+
251
+ const INTEGERS_ARITHMETIC = createArithmeticOperators("Integers");
252
+
253
+ // The operators of Naturals that TLC overrides with the methods of tlc2.module.Integers when it
254
+ // loads Integers for its trace exploration spec, by the operator each replaces.
255
+ export const getTraceSpecArithmetic = (builtin: Builtin) => {
256
+ const index = NATURALS_ARITHMETIC.indexOf(builtin);
257
+ return index === -1 ? undefined : INTEGERS_ARITHMETIC[index];
258
+ };
191
259
 
192
260
  const NATURALS_OPERATORS = [
193
261
  defineConstant("Nat", { kind: "InfiniteSet", name: "Nat" }),
194
- defineArithmetic("+", "Plus", (left, right) => left + right),
195
- defineArithmetic("-", "Minus", (left, right) => left - right),
196
- defineArithmetic("*", "Times", (left, right) => left * right),
197
- defineArithmetic("^", "Expt", (base, exponent) => {
198
- if (exponent < 0) {
199
- throw new TlaModuleError(
200
- `The second argument of ^ should be a natural number, but instead it is:\n${exponent}`,
201
- );
202
- }
203
- if (base === 0 && exponent === 0) throw new TlaModuleError("0^0 is undefined.");
204
- return base ** exponent;
205
- }),
206
- defineArithmetic("\\div", "Divide", (left, right) => {
207
- if (right === 0) throw new TlaModuleError("The second argument of \\div is 0.");
208
- const quotient = Math.floor(left / right);
209
- if (isOutOfRange(quotient)) throw createOverflowError(`${left} \\div ${right}`);
210
- return quotient;
211
- }),
212
- defineArithmetic("%", "Mod", (left, right) => {
213
- if (right <= 0) {
214
- throw new TlaModuleError(
215
- `The second argument of % should be a positive number, but instead it is:\n${right}`,
216
- );
217
- }
218
- return ((left % right) + right) % right;
219
- }),
262
+ ...NATURALS_ARITHMETIC,
220
263
  defineComparison("<", (left, right) => left < right),
221
264
  defineComparison(">", (left, right) => left > right),
222
265
  defineComparison("<=", (left, right) => left <= right),
223
- defineComparison(">=", (left, right) => left >= right),
224
- defineOperator("..", 2, (args) => ({
225
- kind: "Interval",
226
- low: getJavaInteger(getValue(args, 0, ".."), DOT_DOT_SIGNATURE),
227
- high: getJavaInteger(getValue(args, 1, ".."), DOT_DOT_SIGNATURE),
228
- })),
266
+ // tlc2.module.Naturals#GEQ names itself > in its errors. Only a spec that extends Integers gets
267
+ // the GEQ of tlc2.module.Integers, not one that loads Integers for its trace exploration spec.
268
+ defineComparison(">=", (left, right) => left >= right, ">"),
229
269
  ];
230
270
 
231
271
  const INTEGERS_OPERATORS = [
232
272
  defineConstant("Int", { kind: "InfiniteSet", name: "Int" }),
273
+ ...INTEGERS_ARITHMETIC,
274
+ defineComparison(">=", (left, right) => left >= right),
233
275
  defineOperator("-.", 1, (args) => {
234
276
  const value = getJavaInteger(getValue(args, 0, "-"), NEG_SIGNATURE);
235
277
  if (isOutOfRange(-value)) throw createOverflowError(`-${value}`);
@@ -269,103 +311,111 @@ const withJavaMethods = (module: string, operators: Builtin[]) => {
269
311
  });
270
312
  };
271
313
 
272
- const SEQUENCES_OPERATORS = withJavaMethods("Sequences", [
273
- defineOperator("Seq", 1, (args) => ({ kind: "SequenceSet", base: getValue(args, 0, "Seq") })),
274
- defineOperator(
275
- "Len",
276
- 1,
277
- (args) => getSequenceOrString(args, 0, getSequenceMessage("", "Len")).length,
278
- ),
279
- defineOperator("\\o", 2, (args) => {
280
- const left = getSequenceOrString(args, 0, getEvaluatingMessage("s \\o t", "sequence"));
281
- if (typeof left !== "string") {
282
- const right = getSequenceArgument(args, 1, getEvaluatingMessage("t \\o s", "sequence"));
283
- return createTuple([...left, ...right]);
284
- }
285
- const right = getValue(args, 1, "\\o");
286
- if (typeof right !== "string") {
287
- throw new TlaModuleError(
288
- `${getEvaluatingMessage("t \\o s", "string")}\n${formatValue(right)}`,
289
- );
290
- }
291
- return rankString(left + right);
292
- }),
293
- defineOperator("Append", 2, (args) =>
294
- createTuple([
295
- ...getSequenceArgument(args, 0, getEvaluatingMessage("Append(s, v)", "sequence")),
296
- getValue(args, 1, "Append"),
297
- ]),
298
- ),
299
- defineOperator("Head", 1, (args) => {
300
- const elements = getSequenceArgument(args, 0, getSequenceMessage("", "Head"));
301
- if (elements.length === 0)
302
- throw new TlaModuleError("Attempted to apply Head to the empty sequence.");
303
- return elements[0];
304
- }),
305
- defineOperator("Tail", 1, (args) => {
306
- const sequence = getSequenceOrString(args, 0, getSequenceMessage("", "Tail"));
307
- if (sequence.length === 0)
308
- throw new TlaModuleError("Attempted to apply Tail to the empty sequence.");
309
- return sliceSequence(sequence, 1);
310
- }),
311
- defineOperator("SubSeq", 3, (args) => {
312
- const sequence = getSequenceOrString(args, 0, getSequenceMessage("first ", "SubSeq"));
313
- const start = getNumber(args, 1, "SubSeq");
314
- const end = getNumber(args, 2, "SubSeq");
315
- if (start > end) return sliceSequence(sequence, 0, 0);
316
- const outOfDomain =
317
- start < 1
318
- ? { position: "second", value: start }
319
- : end > sequence.length
320
- ? { position: "third", value: end }
321
- : undefined;
322
- if (outOfDomain) {
323
- throw new TlaModuleError(
324
- `The ${outOfDomain.position} argument of SubSeq must be in the domain of its first argument:\n${formatValue(getValue(args, 0, "SubSeq"))}\n, but instead it is\n${outOfDomain.value}`,
314
+ const createSequencesOperators = (version: TlcVersion) =>
315
+ withJavaMethods("Sequences", [
316
+ defineOperator("Seq", 1, (args) => ({ kind: "SequenceSet", base: getValue(args, 0, "Seq") })),
317
+ defineOperator(
318
+ "Len",
319
+ 1,
320
+ (args) => getSequenceOrString(args, 0, getSequenceMessage("", "Len")).length,
321
+ ),
322
+ defineOperator("\\o", 2, (args) => {
323
+ const left = getSequenceOrString(args, 0, getEvaluatingMessage("s \\o t", "sequence"));
324
+ if (typeof left !== "string") {
325
+ const right = getSequenceArgument(args, 1, getEvaluatingMessage("t \\o s", "sequence"));
326
+ return createTuple([...left, ...right]);
327
+ }
328
+ const right = getValue(args, 1, "\\o");
329
+ if (typeof right !== "string") {
330
+ throw new TlaModuleError(
331
+ `${getEvaluatingMessage("t \\o s", "string")}\n${formatValue(right)}`,
332
+ );
333
+ }
334
+ return rankString(left + right);
335
+ }),
336
+ defineOperator("Append", 2, (args) =>
337
+ createTuple([
338
+ ...getSequenceArgument(
339
+ args,
340
+ 0,
341
+ getEvaluatingMessage(version === "1.7.4" ? "Append(v, s)" : "Append(s, v)", "sequence"),
342
+ ),
343
+ getValue(args, 1, "Append"),
344
+ ]),
345
+ ),
346
+ defineOperator("Head", 1, (args) => {
347
+ const elements = getSequenceArgument(args, 0, getSequenceMessage("", "Head"));
348
+ if (elements.length === 0)
349
+ throw new TlaModuleError("Attempted to apply Head to the empty sequence.");
350
+ return elements[0];
351
+ }),
352
+ defineOperator("Tail", 1, (args) => {
353
+ const sequence = getSequenceOrString(args, 0, getSequenceMessage("", "Tail"));
354
+ if (sequence.length === 0)
355
+ throw new TlaModuleError("Attempted to apply Tail to the empty sequence.");
356
+ return sliceSequence(sequence, 1);
357
+ }),
358
+ defineOperator("SubSeq", 3, (args) => {
359
+ const sequence = getSequenceOrString(args, 0, getSequenceMessage("first ", "SubSeq"));
360
+ const start = getNumber(args, 1, "SubSeq");
361
+ const end = getNumber(args, 2, "SubSeq");
362
+ if (start > end) return sliceSequence(sequence, 0, 0);
363
+ const outOfDomain =
364
+ start < 1 || start > sequence.length
365
+ ? { position: "second", value: start }
366
+ : end > sequence.length
367
+ ? { position: "third", value: end }
368
+ : undefined;
369
+ if (outOfDomain) {
370
+ throw new TlaModuleError(
371
+ `The ${outOfDomain.position} argument of SubSeq must be in the domain of its first argument:\n${formatValue(getValue(args, 0, "SubSeq"))}\n, but instead it is\n${outOfDomain.value}`,
372
+ );
373
+ }
374
+ return sliceSequence(sequence, start - 1, end);
375
+ }),
376
+ defineHigherOrderOperator("SelectSeq", 2, (args) => {
377
+ const test = getOperator(args, 1, "SelectSeq");
378
+ return createTuple(
379
+ getSequenceArgument(args, 0, getSequenceMessage("first ", "SelectSeq")).filter(
380
+ (element) => {
381
+ const result = test.call([element]);
382
+ if (typeof result !== "boolean") {
383
+ throw new TlaModuleError(
384
+ `The second argument of SelectSeq should be a operator, but instead it is:\n${formatValue(result)}`,
385
+ );
386
+ }
387
+ return result;
388
+ },
389
+ ),
325
390
  );
326
- }
327
- return sliceSequence(sequence, start - 1, end);
328
- }),
329
- defineHigherOrderOperator("SelectSeq", 2, (args) => {
330
- const test = getOperator(args, 1, "SelectSeq");
331
- return createTuple(
332
- getSequenceArgument(args, 0, getSequenceMessage("first ", "SelectSeq")).filter((element) => {
333
- const result = test.call([element]);
334
- if (typeof result !== "boolean") {
335
- throw new TlaModuleError(
336
- `The second argument of SelectSeq should be a operator, but instead it is:\n${formatValue(result)}`,
337
- );
338
- }
339
- return result;
340
- }),
341
- );
342
- }),
343
- ]);
391
+ }),
392
+ ]);
344
393
 
345
- const FINITE_SETS_OPERATORS = withJavaMethods("FiniteSets", [
346
- defineOperator("IsFiniteSet", 1, (args) => {
347
- const value = getValue(args, 0, "IsFiniteSet");
348
- if (isSetValue(value)) return isFiniteSet(value);
349
- if (typeof value === "object" && value.kind === "Function") return true;
350
- throw new TlaEvaluationError(
351
- typeof value === "object" && value.kind === "LazyFunction"
352
- ? `Attempted to check if the function:\n${formatValue(value)}\nis a finite set.`
353
- : `Attempted to check if the ${describeKind(value)} ${formatValue(value)} is a finite set.`,
354
- );
355
- }),
356
- defineOperator("Cardinality", 1, (args) => {
357
- const set = getValue(args, 0, "Cardinality");
358
- if (
359
- !isSetValue(set) ||
360
- (typeof set === "object" && (set.kind === "InfiniteSet" || set.kind === "SequenceSet"))
361
- ) {
362
- throw new TlaModuleError(
363
- `Attempted to compute cardinality of the value\n${formatValue(set)}`,
394
+ const createFiniteSetsOperators = (version: TlcVersion) =>
395
+ withJavaMethods("FiniteSets", [
396
+ defineOperator("IsFiniteSet", 1, (args) => {
397
+ const value = getValue(args, 0, "IsFiniteSet");
398
+ if (isSetValue(value)) return isFiniteSet(value);
399
+ if (typeof value === "object" && value.kind === "Function") return true;
400
+ throw new TlaEvaluationError(
401
+ typeof value === "object" && value.kind === "LazyFunction"
402
+ ? `Attempted to check if the function:\n${formatValue(value)}\nis a finite set.`
403
+ : `Attempted to check if the ${describeKind(value)} ${formatValue(value)} is a finite set.`,
364
404
  );
365
- }
366
- return getCardinality(set);
367
- }),
368
- ]);
405
+ }),
406
+ defineOperator("Cardinality", 1, (args) => {
407
+ const set = getValue(args, 0, "Cardinality");
408
+ if (
409
+ !isSetValue(set) ||
410
+ (typeof set === "object" && (set.kind === "InfiniteSet" || set.kind === "SequenceSet"))
411
+ ) {
412
+ throw new TlaModuleError(
413
+ `Attempted to compute cardinality of the value\n${formatValue(set)}`,
414
+ );
415
+ }
416
+ return getCardinality(set, version);
417
+ }),
418
+ ]);
369
419
 
370
420
  // The modules that each standard module loads through EXTENDS and LOCAL INSTANCE in TLC.
371
421
  export const STANDARD_DEPENDENCIES = new Map([
@@ -385,6 +435,7 @@ export const getStandardModule = (
385
435
  print: (text: string) => void,
386
436
  runtime: CheckerRuntime,
387
437
  files: FileSystem,
438
+ builtins: ReadonlyMap<string, Builtin>,
388
439
  ): StandardModule | undefined => {
389
440
  switch (name) {
390
441
  case "Naturals":
@@ -392,9 +443,9 @@ export const getStandardModule = (
392
443
  case "Integers":
393
444
  return { extends: ["Naturals"], operators: INTEGERS_OPERATORS };
394
445
  case "Sequences":
395
- return { extends: [], operators: SEQUENCES_OPERATORS };
446
+ return { extends: [], operators: createSequencesOperators(runtime.version) };
396
447
  case "FiniteSets":
397
- return { extends: [], operators: FINITE_SETS_OPERATORS };
448
+ return { extends: [], operators: createFiniteSetsOperators(runtime.version) };
398
449
  case "TLC":
399
450
  return { extends: [], operators: withJavaMethods("TLC", createTlcOperators(print, runtime)) };
400
451
  case "Randomization":
@@ -404,7 +455,7 @@ export const getStandardModule = (
404
455
  case "Json":
405
456
  return { extends: [], operators: createJsonOperators(files) };
406
457
  case "Bags":
407
- return { extends: [], operators: BAGS_OPERATORS };
458
+ return { extends: [], operators: createBagsOperators(builtins) };
408
459
  case "TLCExt":
409
460
  return { extends: [], operators: createTlcExtOperators(print, runtime) };
410
461
  default:
@@ -0,0 +1,116 @@
1
+ import type { SourceRange } from "./ast";
2
+
3
+ // Where the modules in TLC's tla2sany/StandardModules define the operators that tla-ts implements
4
+ // natively, which SANY reports when a spec defines one of them again.
5
+ const RANGES: Record<string, Record<string, [number, number, number, number]>> = {
6
+ Naturals: {
7
+ Nat: [14, 1, 14, 16],
8
+ "+": [15, 1, 15, 19],
9
+ "-": [17, 1, 17, 33],
10
+ "*": [18, 1, 18, 17],
11
+ "^": [19, 1, 19, 19],
12
+ "<": [20, 1, 20, 19],
13
+ ">": [21, 1, 21, 19],
14
+ "<=": [22, 1, 22, 19],
15
+ ">=": [23, 1, 23, 19],
16
+ "%": [33, 1, 33, 20],
17
+ "\\div": [34, 1, 34, 20],
18
+ "..": [35, 1, 35, 20],
19
+ },
20
+ Integers: {
21
+ Int: [18, 1, 18, 12],
22
+ "-.": [22, 1, 22, 13],
23
+ },
24
+ Sequences: {
25
+ Seq: [20, 1, 20, 41],
26
+ Len: [25, 1, 25, 44],
27
+ "\\o": [30, 1, 31, 76],
28
+ Append: [36, 1, 36, 26],
29
+ Head: [41, 1, 41, 15],
30
+ Tail: [42, 1, 42, 61],
31
+ SubSeq: [48, 1, 48, 50],
32
+ SelectSeq: [53, 1, 65, 14],
33
+ },
34
+ FiniteSets: {
35
+ IsFiniteSet: [14, 1, 19, 68],
36
+ Cardinality: [21, 1, 27, 11],
37
+ },
38
+ Bags: {
39
+ IsABag: [20, 1, 24, 41],
40
+ BagToSet: [26, 1, 26, 23],
41
+ SetToBag: [31, 1, 31, 30],
42
+ BagIn: [36, 1, 36, 31],
43
+ EmptyBag: [41, 1, 41, 24],
44
+ "\\oplus": [43, 1, 49, 46],
45
+ "\\ominus": [51, 1, 60, 50],
46
+ BagUnion: [74, 1, 79, 58],
47
+ "\\sqsubseteq": [81, 1, 87, 42],
48
+ SubBag: [89, 1, 110, 11],
49
+ BagOfAll: [122, 1, 130, 66],
50
+ BagCardinality: [132, 1, 138, 8],
51
+ CopiesIn: [140, 1, 145, 33],
52
+ },
53
+ TLC: {
54
+ Print: [17, 1, 17, 22],
55
+ PrintT: [18, 1, 18, 19],
56
+ Assert: [24, 1, 25, 54],
57
+ JavaTime: [26, 1, 26, 32],
58
+ TLCGet: [75, 1, 75, 28],
59
+ TLCSet: [76, 1, 76, 20],
60
+ ":>": [78, 1, 78, 27],
61
+ "@@": [79, 1, 80, 50],
62
+ Permutations: [81, 1, 82, 54],
63
+ SortSeq: [88, 1, 92, 40],
64
+ RandomElement: [110, 1, 110, 41],
65
+ Any: [119, 1, 119, 22],
66
+ ToString: [121, 1, 121, 58],
67
+ TLCEval: [145, 1, 145, 15],
68
+ },
69
+ TLCExt: {
70
+ AssertEq: [14, 1, 20, 14],
71
+ AssertError: [23, 1, 26, 72],
72
+ TLCGetOrDefault: [30, 1, 31, 17],
73
+ TLCGetAndSet: [33, 1, 35, 57],
74
+ Trace: [41, 1, 57, 6],
75
+ CounterExample: [61, 1, 75, 8],
76
+ ToTrace: [77, 1, 87, 12],
77
+ TLCModelValue: [91, 1, 120, 29],
78
+ TLCDefer: [122, 1, 134, 6],
79
+ TLCNoOp: [138, 1, 145, 5],
80
+ PickSuccessor: [148, 1, 162, 37],
81
+ TLCCache: [166, 1, 173, 12],
82
+ TLCFP: [175, 1, 181, 24],
83
+ TLCEvalDefinition: [185, 1, 190, 6],
84
+ },
85
+ Randomization: {
86
+ RandomSubset: [30, 1, 30, 64],
87
+ RandomSetOfSubsets: [48, 1, 49, 67],
88
+ TestRandomSetOfSubsets: [61, 1, 62, 71],
89
+ },
90
+ Json: {
91
+ ToJson: [46, 1, 55, 37],
92
+ ToJsonArray: [57, 1, 64, 42],
93
+ ToJsonObject: [66, 1, 73, 43],
94
+ JsonSerialize: [75, 1, 80, 6],
95
+ JsonDeserialize: [82, 1, 87, 19],
96
+ ndJsonSerialize: [89, 1, 95, 6],
97
+ ndJsonDeserialize: [97, 1, 103, 19],
98
+ },
99
+ _Possible: {
100
+ _Track: [10, 1, 17, 38],
101
+ _Counts: [24, 1, 30, 14],
102
+ _CheckName: [32, 1, 35, 35],
103
+ _PrintCounts: [37, 1, 37, 31],
104
+ },
105
+ };
106
+
107
+ export const getStandardRange = (module: string, name: string): SourceRange | undefined => {
108
+ const range = RANGES[module]?.[name];
109
+ return (
110
+ range && {
111
+ module,
112
+ start: { line: range[0], column: range[1] },
113
+ end: { line: range[2], column: range[3] },
114
+ }
115
+ );
116
+ };