tla-ts 0.0.3 → 0.0.4-dev.0be9567

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 +162 -8
  6. package/dist/index.d.ts +162 -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 +98 -39
  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 +994 -279
  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 +203 -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 +220 -108
  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 +743 -189
@@ -1,16 +1,20 @@
1
- import type { Definition, Expression, SourceLocation, SourceRange } from "./ast";
1
+ import {
2
+ isLocallyResolved,
3
+ type Definition,
4
+ type Expression,
5
+ type SourceLocation,
6
+ type SourceRange,
7
+ } from "./ast";
2
8
  import type { ModelConfig } from "./config";
3
9
  import type { InstanceAction } from "./environment";
4
- import { TlaError } from "./errors";
10
+ import { formatRange, TlaError } from "./errors";
5
11
  import {
6
12
  bindDefinitions,
7
13
  bindOperatorArguments,
8
14
  evaluate,
9
15
  forEachBinding,
10
- formatRange,
11
16
  getDefinition,
12
17
  isConstantLevel,
13
- isLocallyResolved,
14
18
  lookupScope,
15
19
  resolveGlobalOperator,
16
20
  type Closure,
@@ -20,6 +24,7 @@ import {
20
24
  import { TEMPORAL_LEVEL } from "./levels";
21
25
  import { getLevel } from "./liveness";
22
26
  import { createRecord, createSet, createTuple, formatValue, type Value } from "./values";
27
+ import type { TlcVersion } from "./tlc-version";
23
28
 
24
29
  export interface SpecAction {
25
30
  name: string;
@@ -58,7 +63,8 @@ const toLocationValue = (location: SourceLocation) => {
58
63
  ]);
59
64
  };
60
65
 
61
- 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) => {
62
68
  const fields: [string, Value][] = [
63
69
  ["name", action.name],
64
70
  ["location", toLocationValue(action.location)],
@@ -245,8 +251,12 @@ const getActions = (
245
251
  return getInstanceActions(instanceAction, expression, scope, called, environment);
246
252
  if (!called) return [createSplitAction()];
247
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);
248
258
  const callAction = (): SpecAction[] => [
249
- { name: called.name, location: expression.location, parameters: [], expression, scope },
259
+ { name: calledName, location: expression.location, parameters: [], expression, scope },
250
260
  ];
251
261
  if (isConstantDefinition(called, environment)) return callAction();
252
262
  if (args.some((arg) => getLevel(arg, scope, environment) !== 0)) return callAction();
@@ -262,7 +272,13 @@ const getActions = (
262
272
  }),
263
273
  called.scope,
264
274
  );
265
- 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
+ );
266
282
  }, callAction);
267
283
  };
268
284
 
@@ -457,6 +473,13 @@ const describe = (
457
473
  return description;
458
474
  };
459
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
+
460
483
  // TLC's split of the next-state relation into the actions it names in a behavior.
461
484
  export const getNextActions = (
462
485
  config: ModelConfig,
@@ -464,10 +487,18 @@ export const getNextActions = (
464
487
  instanceActions: Map<string, InstanceAction>,
465
488
  ) => describe(config, environment, instanceActions).actions;
466
489
 
467
- export const getActionLabel = (action: SpecAction) => {
468
- const parameters = action.parameters.map((parameter) => formatValue(parameter[1]));
469
- return `${action.name === UNNAMED_ACTION ? "Action" : action.name}${parameters.length === 0 ? "" : `(${parameters.join(",")})`} ${formatRange(action.location.range ?? BUILTIN_RANGE)}`;
470
- };
490
+ const formatParameters = (action: SpecAction) =>
491
+ action.parameters.length === 0
492
+ ? ""
493
+ : `(${action.parameters.map((parameter) => formatValue(parameter[1])).join(",")})`;
494
+
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)}`;
498
+
499
+ // TLC's Action.getInvocationSignature, which names the action and the values of its parameters.
500
+ export const getActionSignature = (action: SpecAction) =>
501
+ `${action.name}${formatParameters(action)}`;
471
502
 
472
503
  export const getSpecificationValue = (
473
504
  config: ModelConfig,
@@ -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,6 +40,9 @@ import {
40
40
  isEnumerable,
41
41
  isFiniteSet,
42
42
  isFunctionValue,
43
+ computeLikeTlcOnFailure,
44
+ isReducibleSet,
45
+ markStreamedSet,
43
46
  isSetValue,
44
47
  toFiniteSet,
45
48
  unionSorted,
@@ -54,6 +57,7 @@ import {
54
57
  type Value,
55
58
  rankString,
56
59
  } from "./values";
60
+ import type { TlcVersion } from "./tlc-version";
57
61
 
58
62
  interface StandardModule {
59
63
  extends: string[];
@@ -77,10 +81,6 @@ const SET_OPERATORS: SetOperationValue["operator"][] = ["\\cup", "\\cap", "\\"];
77
81
 
78
82
  type ReducibleSet = SetValue | MixedSetValue | IntervalValue;
79
83
 
80
- const isReducible = (value: Value): value is ReducibleSet =>
81
- typeof value === "object" &&
82
- (value.kind === "Set" || value.kind === "MixedSet" || value.kind === "Interval");
83
-
84
84
  const isMixedSet = (value: Value) => typeof value === "object" && value.kind === "MixedSet";
85
85
 
86
86
  const getReducibleElements = (set: ReducibleSet) =>
@@ -101,7 +101,9 @@ const combineReducible = (
101
101
  );
102
102
  }
103
103
  if (elements.length === 0) return other;
104
- 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
+ }
105
107
  const added = toFiniteSet(other).elements.filter((element) => !isElementOf(element, set));
106
108
  return createEnumeratedSet([...elements, ...added]);
107
109
  };
@@ -128,7 +130,8 @@ export const CORE_OPERATORS: Builtin[] = [
128
130
  ),
129
131
  defineOperator("\\subseteq", 2, (args) => {
130
132
  const left = getSet(args, 0, "\\subseteq");
131
- const right = getSet(args, 1, "\\subseteq");
133
+ // TLC tests each element of the left set for membership in the right value.
134
+ const right = getValue(args, 1, "\\subseteq");
132
135
  const isPowerSets =
133
136
  typeof left === "object" &&
134
137
  left.kind === "Subset" &&
@@ -138,11 +141,18 @@ export const CORE_OPERATORS: Builtin[] = [
138
141
  if (isPowerSets) return isSubsetOf(toFiniteSet(left.base).elements, right.base);
139
142
  return isSubsetOf(toFiniteSet(left).elements, right);
140
143
  }),
144
+ // TLC defers the set operations of values that aren't sets to the enumeration or the membership
145
+ // tests of the result.
141
146
  ...SET_OPERATORS.map((operator) =>
142
147
  defineOperator(operator, 2, (args) => {
143
- const left = getSet(args, 0, operator);
144
- const right = getSet(args, 1, operator);
145
- 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
+ ) {
146
156
  if (operator === "\\cup" && isEmptySet(left)) return right;
147
157
  const merge =
148
158
  operator === "\\cup"
@@ -150,19 +160,27 @@ export const CORE_OPERATORS: Builtin[] = [
150
160
  : operator === "\\cap"
151
161
  ? intersectSorted
152
162
  : differenceSorted;
153
- return merge(toFiniteSet(left), toFiniteSet(right));
163
+ // The merge compares the elements, which TLC tests for membership one by one instead.
164
+ return computeLikeTlcOnFailure(
165
+ (finiteLeft, finiteRight) => merge(toFiniteSet(finiteLeft), toFiniteSet(finiteRight)),
166
+ (reducibleLeft, reducibleRight) =>
167
+ combineReducible(operator, reducibleLeft, reducibleRight),
168
+ left,
169
+ right,
170
+ );
154
171
  }
155
- if (isReducible(left)) return combineReducible(operator, left, right);
156
- if (operator !== "\\" && isReducible(right)) return combineReducible(operator, right, left);
157
- return { kind: "SetOperation", operator, left, right };
172
+ if (isReducibleSet(left)) return combineReducible(operator, left, right);
173
+ if (operator !== "\\" && isReducibleSet(right))
174
+ return combineReducible(operator, right, left);
175
+ return markStreamedSet({ kind: "SetOperation", operator, left, right });
158
176
  }),
159
177
  ),
160
- defineOperator("SUBSET", 1, (args) => ({ kind: "Subset", base: getSet(args, 0, "SUBSET") })),
178
+ defineOperator("SUBSET", 1, (args) => ({ kind: "Subset", base: getValue(args, 0, "SUBSET") })),
161
179
  defineOperator("UNION", 1, (args) => {
162
180
  const outer = getSet(args, 0, "UNION");
163
181
  const sets = isEnumeratedSet(outer) ? outer.elements.filter(isEnumeratedSet) : [];
164
182
  if (!isEnumeratedSet(outer) || sets.length !== outer.elements.length) {
165
- return { kind: "Union", base: outer };
183
+ return markStreamedSet({ kind: "Union", base: outer });
166
184
  }
167
185
  if (isMixedSet(outer) || sets.some(isMixedSet)) {
168
186
  const union: MixedSetValue = { kind: "MixedSet", elements: [] };
@@ -184,51 +202,79 @@ export const CORE_OPERATORS: Builtin[] = [
184
202
  }),
185
203
  ];
186
204
 
187
- const DOT_DOT_SIGNATURE = getIntegersSignature("DotDot", "IntervalValue", 2);
205
+ const NEG_SIGNATURE = getJavaSignature("Integers", "Neg", "IntValue", 1);
188
206
 
189
- const NEG_SIGNATURE = getIntegersSignature("Neg", "IntValue", 1);
207
+ // TLC overrides the arithmetic of Naturals with the Java methods of tlc2.module.Naturals, or with
208
+ // those of tlc2.module.Integers when the spec loads Integers, and names the method in an error.
209
+ const createArithmeticOperators = (module: string) => {
210
+ const dotDotSignature = getJavaSignature(module, "DotDot", "IntervalValue", 2);
211
+ return [
212
+ defineArithmetic(module, "+", "Plus", (left, right) => left + right),
213
+ defineArithmetic(module, "-", "Minus", (left, right) => left - right),
214
+ defineArithmetic(module, "*", "Times", (left, right) => left * right),
215
+ defineArithmetic(module, "^", "Expt", (base, exponent) => {
216
+ if (exponent < 0) {
217
+ throw new TlaModuleError(
218
+ `The second argument of ^ should be a natural number, but instead it is:\n${exponent}`,
219
+ );
220
+ }
221
+ if (base === 0 && exponent === 0) throw new TlaModuleError("0^0 is undefined.");
222
+ return base ** exponent;
223
+ }),
224
+ defineArithmetic(module, "\\div", "Divide", (left, right) => {
225
+ if (right === 0) throw new TlaModuleError("The second argument of \\div is 0.");
226
+ // tlc2.module.Naturals#Divide floors only a quotient Java truncates below 0, and lets
227
+ // -2147483648 \div -1 overflow.
228
+ if (module === "Naturals") {
229
+ const truncated = Math.trunc(left / right) | 0;
230
+ return truncated < 0 && Math.imul(truncated, right) !== left ? truncated - 1 : truncated;
231
+ }
232
+ const quotient = Math.floor(left / right);
233
+ if (isOutOfRange(quotient)) throw createOverflowError(`${left} \\div ${right}`);
234
+ return quotient;
235
+ }),
236
+ defineArithmetic(module, "%", "Mod", (left, right) => {
237
+ if (right <= 0) {
238
+ throw new TlaModuleError(
239
+ `The second argument of % should be a positive number, but instead it is:\n${right}`,
240
+ );
241
+ }
242
+ return ((left % right) + right) % right;
243
+ }),
244
+ defineOperator("..", 2, (args) => ({
245
+ kind: "Interval",
246
+ low: getJavaInteger(getValue(args, 0, ".."), dotDotSignature),
247
+ high: getJavaInteger(getValue(args, 1, ".."), dotDotSignature),
248
+ })),
249
+ ];
250
+ };
251
+
252
+ const NATURALS_ARITHMETIC = createArithmeticOperators("Naturals");
253
+
254
+ const INTEGERS_ARITHMETIC = createArithmeticOperators("Integers");
255
+
256
+ // The operators of Naturals that TLC overrides with the methods of tlc2.module.Integers when it
257
+ // loads Integers for its trace exploration spec, by the operator each replaces.
258
+ export const getTraceSpecArithmetic = (builtin: Builtin) => {
259
+ const index = NATURALS_ARITHMETIC.indexOf(builtin);
260
+ return index === -1 ? undefined : INTEGERS_ARITHMETIC[index];
261
+ };
190
262
 
191
263
  const NATURALS_OPERATORS = [
192
264
  defineConstant("Nat", { kind: "InfiniteSet", name: "Nat" }),
193
- defineArithmetic("+", "Plus", (left, right) => left + right),
194
- defineArithmetic("-", "Minus", (left, right) => left - right),
195
- defineArithmetic("*", "Times", (left, right) => left * right),
196
- defineArithmetic("^", "Expt", (base, exponent) => {
197
- if (exponent < 0) {
198
- throw new TlaModuleError(
199
- `The second argument of ^ should be a natural number, but instead it is:\n${exponent}`,
200
- );
201
- }
202
- if (base === 0 && exponent === 0) throw new TlaModuleError("0^0 is undefined.");
203
- return base ** exponent;
204
- }),
205
- defineArithmetic("\\div", "Divide", (left, right) => {
206
- if (right === 0) throw new TlaModuleError("The second argument of \\div is 0.");
207
- const quotient = Math.floor(left / right);
208
- if (isOutOfRange(quotient)) throw createOverflowError(`${left} \\div ${right}`);
209
- return quotient;
210
- }),
211
- defineArithmetic("%", "Mod", (left, right) => {
212
- if (right <= 0) {
213
- throw new TlaModuleError(
214
- `The second argument of % should be a positive number, but instead it is:\n${right}`,
215
- );
216
- }
217
- return ((left % right) + right) % right;
218
- }),
265
+ ...NATURALS_ARITHMETIC,
219
266
  defineComparison("<", (left, right) => left < right),
220
267
  defineComparison(">", (left, right) => left > right),
221
268
  defineComparison("<=", (left, right) => left <= right),
222
- defineComparison(">=", (left, right) => left >= right),
223
- defineOperator("..", 2, (args) => ({
224
- kind: "Interval",
225
- low: getJavaInteger(getValue(args, 0, ".."), DOT_DOT_SIGNATURE),
226
- high: getJavaInteger(getValue(args, 1, ".."), DOT_DOT_SIGNATURE),
227
- })),
269
+ // tlc2.module.Naturals#GEQ names itself > in its errors. Only a spec that extends Integers gets
270
+ // the GEQ of tlc2.module.Integers, not one that loads Integers for its trace exploration spec.
271
+ defineComparison(">=", (left, right) => left >= right, ">"),
228
272
  ];
229
273
 
230
274
  const INTEGERS_OPERATORS = [
231
275
  defineConstant("Int", { kind: "InfiniteSet", name: "Int" }),
276
+ ...INTEGERS_ARITHMETIC,
277
+ defineComparison(">=", (left, right) => left >= right),
232
278
  defineOperator("-.", 1, (args) => {
233
279
  const value = getJavaInteger(getValue(args, 0, "-"), NEG_SIGNATURE);
234
280
  if (isOutOfRange(-value)) throw createOverflowError(`-${value}`);
@@ -268,103 +314,111 @@ const withJavaMethods = (module: string, operators: Builtin[]) => {
268
314
  });
269
315
  };
270
316
 
271
- const SEQUENCES_OPERATORS = withJavaMethods("Sequences", [
272
- defineOperator("Seq", 1, (args) => ({ kind: "SequenceSet", base: getValue(args, 0, "Seq") })),
273
- defineOperator(
274
- "Len",
275
- 1,
276
- (args) => getSequenceOrString(args, 0, getSequenceMessage("", "Len")).length,
277
- ),
278
- defineOperator("\\o", 2, (args) => {
279
- const left = getSequenceOrString(args, 0, getEvaluatingMessage("s \\o t", "sequence"));
280
- if (typeof left !== "string") {
281
- const right = getSequenceArgument(args, 1, getEvaluatingMessage("t \\o s", "sequence"));
282
- return createTuple([...left, ...right]);
283
- }
284
- const right = getValue(args, 1, "\\o");
285
- if (typeof right !== "string") {
286
- throw new TlaModuleError(
287
- `${getEvaluatingMessage("t \\o s", "string")}\n${formatValue(right)}`,
288
- );
289
- }
290
- return rankString(left + right);
291
- }),
292
- defineOperator("Append", 2, (args) =>
293
- createTuple([
294
- ...getSequenceArgument(args, 0, getEvaluatingMessage("Append(s, v)", "sequence")),
295
- getValue(args, 1, "Append"),
296
- ]),
297
- ),
298
- defineOperator("Head", 1, (args) => {
299
- const elements = getSequenceArgument(args, 0, getSequenceMessage("", "Head"));
300
- if (elements.length === 0)
301
- throw new TlaModuleError("Attempted to apply Head to the empty sequence.");
302
- return elements[0];
303
- }),
304
- defineOperator("Tail", 1, (args) => {
305
- const sequence = getSequenceOrString(args, 0, getSequenceMessage("", "Tail"));
306
- if (sequence.length === 0)
307
- throw new TlaModuleError("Attempted to apply Tail to the empty sequence.");
308
- return sliceSequence(sequence, 1);
309
- }),
310
- defineOperator("SubSeq", 3, (args) => {
311
- const sequence = getSequenceOrString(args, 0, getSequenceMessage("first ", "SubSeq"));
312
- const start = getNumber(args, 1, "SubSeq");
313
- const end = getNumber(args, 2, "SubSeq");
314
- if (start > end) return sliceSequence(sequence, 0, 0);
315
- const outOfDomain =
316
- start < 1
317
- ? { position: "second", value: start }
318
- : end > sequence.length
319
- ? { position: "third", value: end }
320
- : undefined;
321
- if (outOfDomain) {
322
- throw new TlaModuleError(
323
- `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}`,
317
+ const createSequencesOperators = (version: TlcVersion) =>
318
+ withJavaMethods("Sequences", [
319
+ defineOperator("Seq", 1, (args) => ({ kind: "SequenceSet", base: getValue(args, 0, "Seq") })),
320
+ defineOperator(
321
+ "Len",
322
+ 1,
323
+ (args) => getSequenceOrString(args, 0, getSequenceMessage("", "Len")).length,
324
+ ),
325
+ defineOperator("\\o", 2, (args) => {
326
+ const left = getSequenceOrString(args, 0, getEvaluatingMessage("s \\o t", "sequence"));
327
+ if (typeof left !== "string") {
328
+ const right = getSequenceArgument(args, 1, getEvaluatingMessage("t \\o s", "sequence"));
329
+ return createTuple([...left, ...right]);
330
+ }
331
+ const right = getValue(args, 1, "\\o");
332
+ if (typeof right !== "string") {
333
+ throw new TlaModuleError(
334
+ `${getEvaluatingMessage("t \\o s", "string")}\n${formatValue(right)}`,
335
+ );
336
+ }
337
+ return rankString(left + right);
338
+ }),
339
+ defineOperator("Append", 2, (args) =>
340
+ createTuple([
341
+ ...getSequenceArgument(
342
+ args,
343
+ 0,
344
+ getEvaluatingMessage(version === "1.7.4" ? "Append(v, s)" : "Append(s, v)", "sequence"),
345
+ ),
346
+ getValue(args, 1, "Append"),
347
+ ]),
348
+ ),
349
+ defineOperator("Head", 1, (args) => {
350
+ const elements = getSequenceArgument(args, 0, getSequenceMessage("", "Head"));
351
+ if (elements.length === 0)
352
+ throw new TlaModuleError("Attempted to apply Head to the empty sequence.");
353
+ return elements[0];
354
+ }),
355
+ defineOperator("Tail", 1, (args) => {
356
+ const sequence = getSequenceOrString(args, 0, getSequenceMessage("", "Tail"));
357
+ if (sequence.length === 0)
358
+ throw new TlaModuleError("Attempted to apply Tail to the empty sequence.");
359
+ return sliceSequence(sequence, 1);
360
+ }),
361
+ defineOperator("SubSeq", 3, (args) => {
362
+ const sequence = getSequenceOrString(args, 0, getSequenceMessage("first ", "SubSeq"));
363
+ const start = getNumber(args, 1, "SubSeq");
364
+ const end = getNumber(args, 2, "SubSeq");
365
+ if (start > end) return sliceSequence(sequence, 0, 0);
366
+ const outOfDomain =
367
+ start < 1 || start > sequence.length
368
+ ? { position: "second", value: start }
369
+ : end > sequence.length
370
+ ? { position: "third", value: end }
371
+ : undefined;
372
+ if (outOfDomain) {
373
+ throw new TlaModuleError(
374
+ `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}`,
375
+ );
376
+ }
377
+ return sliceSequence(sequence, start - 1, end);
378
+ }),
379
+ defineHigherOrderOperator("SelectSeq", 2, (args) => {
380
+ const test = getOperator(args, 1, "SelectSeq");
381
+ return createTuple(
382
+ getSequenceArgument(args, 0, getSequenceMessage("first ", "SelectSeq")).filter(
383
+ (element) => {
384
+ const result = test.call([element]);
385
+ if (typeof result !== "boolean") {
386
+ throw new TlaModuleError(
387
+ `The second argument of SelectSeq should be a operator, but instead it is:\n${formatValue(result)}`,
388
+ );
389
+ }
390
+ return result;
391
+ },
392
+ ),
324
393
  );
325
- }
326
- return sliceSequence(sequence, start - 1, end);
327
- }),
328
- defineHigherOrderOperator("SelectSeq", 2, (args) => {
329
- const test = getOperator(args, 1, "SelectSeq");
330
- return createTuple(
331
- getSequenceArgument(args, 0, getSequenceMessage("first ", "SelectSeq")).filter((element) => {
332
- const result = test.call([element]);
333
- if (typeof result !== "boolean") {
334
- throw new TlaModuleError(
335
- `The second argument of SelectSeq should be a operator, but instead it is:\n${formatValue(result)}`,
336
- );
337
- }
338
- return result;
339
- }),
340
- );
341
- }),
342
- ]);
394
+ }),
395
+ ]);
343
396
 
344
- const FINITE_SETS_OPERATORS = withJavaMethods("FiniteSets", [
345
- defineOperator("IsFiniteSet", 1, (args) => {
346
- const value = getValue(args, 0, "IsFiniteSet");
347
- if (isSetValue(value)) return isFiniteSet(value);
348
- if (typeof value === "object" && value.kind === "Function") return true;
349
- throw new TlaEvaluationError(
350
- typeof value === "object" && value.kind === "LazyFunction"
351
- ? `Attempted to check if the function:\n${formatValue(value)}\nis a finite set.`
352
- : `Attempted to check if the ${describeKind(value)} ${formatValue(value)} is a finite set.`,
353
- );
354
- }),
355
- defineOperator("Cardinality", 1, (args) => {
356
- const set = getValue(args, 0, "Cardinality");
357
- if (
358
- !isSetValue(set) ||
359
- (typeof set === "object" && (set.kind === "InfiniteSet" || set.kind === "SequenceSet"))
360
- ) {
361
- throw new TlaModuleError(
362
- `Attempted to compute cardinality of the value\n${formatValue(set)}`,
397
+ const createFiniteSetsOperators = (version: TlcVersion) =>
398
+ withJavaMethods("FiniteSets", [
399
+ defineOperator("IsFiniteSet", 1, (args) => {
400
+ const value = getValue(args, 0, "IsFiniteSet");
401
+ if (isSetValue(value)) return isFiniteSet(value);
402
+ if (typeof value === "object" && value.kind === "Function") return true;
403
+ throw new TlaEvaluationError(
404
+ typeof value === "object" && value.kind === "LazyFunction"
405
+ ? `Attempted to check if the function:\n${formatValue(value)}\nis a finite set.`
406
+ : `Attempted to check if the ${describeKind(value)} ${formatValue(value)} is a finite set.`,
363
407
  );
364
- }
365
- return getCardinality(set);
366
- }),
367
- ]);
408
+ }),
409
+ defineOperator("Cardinality", 1, (args) => {
410
+ const set = getValue(args, 0, "Cardinality");
411
+ if (
412
+ !isSetValue(set) ||
413
+ (typeof set === "object" && (set.kind === "InfiniteSet" || set.kind === "SequenceSet"))
414
+ ) {
415
+ throw new TlaModuleError(
416
+ `Attempted to compute cardinality of the value\n${formatValue(set)}`,
417
+ );
418
+ }
419
+ return getCardinality(set, version);
420
+ }),
421
+ ]);
368
422
 
369
423
  // The modules that each standard module loads through EXTENDS and LOCAL INSTANCE in TLC.
370
424
  export const STANDARD_DEPENDENCIES = new Map([
@@ -384,6 +438,7 @@ export const getStandardModule = (
384
438
  print: (text: string) => void,
385
439
  runtime: CheckerRuntime,
386
440
  files: FileSystem,
441
+ builtins: ReadonlyMap<string, Builtin>,
387
442
  ): StandardModule | undefined => {
388
443
  switch (name) {
389
444
  case "Naturals":
@@ -391,9 +446,9 @@ export const getStandardModule = (
391
446
  case "Integers":
392
447
  return { extends: ["Naturals"], operators: INTEGERS_OPERATORS };
393
448
  case "Sequences":
394
- return { extends: [], operators: SEQUENCES_OPERATORS };
449
+ return { extends: [], operators: createSequencesOperators(runtime.version) };
395
450
  case "FiniteSets":
396
- return { extends: [], operators: FINITE_SETS_OPERATORS };
451
+ return { extends: [], operators: createFiniteSetsOperators(runtime.version) };
397
452
  case "TLC":
398
453
  return { extends: [], operators: withJavaMethods("TLC", createTlcOperators(print, runtime)) };
399
454
  case "Randomization":
@@ -403,7 +458,7 @@ export const getStandardModule = (
403
458
  case "Json":
404
459
  return { extends: [], operators: createJsonOperators(files) };
405
460
  case "Bags":
406
- return { extends: [], operators: BAGS_OPERATORS };
461
+ return { extends: [], operators: createBagsOperators(builtins) };
407
462
  case "TLCExt":
408
463
  return { extends: [], operators: createTlcExtOperators(print, runtime) };
409
464
  default: