tla-ts 0.0.1 → 0.0.3-dev.037ac3b

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 (74) hide show
  1. package/README.md +98 -39
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +225 -30
  4. package/dist/index.d.ts +225 -30
  5. package/dist/index.js +1 -1
  6. package/dist/parallel-worker.cjs +2 -2
  7. package/dist/parallel-worker.js +2 -2
  8. package/dist/parallel.cjs +1 -1
  9. package/dist/parallel.js +2 -2
  10. package/dist/run-cli.cjs +21 -1
  11. package/dist/run-cli.js +21 -1
  12. package/dist/transfer.cjs +400 -39
  13. package/dist/transfer.js +400 -39
  14. package/package.json +6 -2
  15. package/src/ast.ts +213 -6
  16. package/src/bags.ts +161 -71
  17. package/src/builtins.ts +203 -23
  18. package/src/bundled-modules.ts +63 -32
  19. package/src/check.ts +1132 -258
  20. package/src/cli-options.ts +64 -0
  21. package/src/codegen.ts +58 -34
  22. package/src/config.ts +39 -11
  23. package/src/dependencies.ts +2 -2
  24. package/src/environment.ts +557 -153
  25. package/src/errors.ts +66 -1
  26. package/src/evaluate.ts +553 -258
  27. package/src/exit-codes.ts +53 -0
  28. package/src/fingerprints.ts +48 -13
  29. package/src/index.ts +9 -4
  30. package/src/instances.ts +235 -79
  31. package/src/java-overrides.ts +241 -0
  32. package/src/json.ts +153 -72
  33. package/src/levels.ts +850 -0
  34. package/src/lexer.ts +108 -29
  35. package/src/live-check.ts +692 -0
  36. package/src/liveness.ts +71 -596
  37. package/src/obligation-action.ts +384 -0
  38. package/src/obligation-anon.ts +575 -0
  39. package/src/obligation-deref.ts +637 -0
  40. package/src/obligation-expression.ts +1060 -0
  41. package/src/obligation-format.ts +406 -0
  42. package/src/obligation-generate.ts +1074 -0
  43. package/src/obligation-levels.ts +329 -0
  44. package/src/obligation-module.ts +1042 -0
  45. package/src/obligation-printer.ts +889 -0
  46. package/src/obligation-proof.ts +76 -0
  47. package/src/obligation-source.ts +1084 -0
  48. package/src/obligation-tuples.ts +184 -0
  49. package/src/obligations.ts +316 -0
  50. package/src/parallel-worker.ts +186 -201
  51. package/src/parallel.ts +179 -84
  52. package/src/parser.ts +970 -206
  53. package/src/pretty-print.ts +259 -0
  54. package/src/randomization.ts +24 -113
  55. package/src/resolve.ts +483 -51
  56. package/src/run-cli.ts +473 -62
  57. package/src/runtime.ts +65 -28
  58. package/src/spec-description.ts +521 -0
  59. package/src/standard-levels.ts +105 -0
  60. package/src/standard-modules.ts +218 -92
  61. package/src/state-graph.ts +157 -0
  62. package/src/subexpressions.ts +31 -45
  63. package/src/substitution-levels.ts +184 -0
  64. package/src/successors.ts +336 -57
  65. package/src/symmetry.ts +79 -23
  66. package/src/tableau.ts +93 -60
  67. package/src/tlc-ext.ts +148 -44
  68. package/src/tlc-module.ts +71 -66
  69. package/src/tlc-modules.ts +1022 -0
  70. package/src/tlc-order.ts +511 -0
  71. package/src/tlc-random.ts +414 -0
  72. package/src/tlc-summary.ts +124 -0
  73. package/src/transfer.ts +26 -5
  74. package/src/values.ts +1285 -179
@@ -0,0 +1,105 @@
1
+ import type { OperatorLevels } from "./levels";
2
+
3
+ type Signature =
4
+ | [string, number, number[], number[], number[]]
5
+ | [string, number, number[], number[], number[], number[][], string[]];
6
+
7
+ // The levels SANY computes for the dummy definitions in tla2sany/StandardModules of the operators
8
+ // that tla-ts implements natively.
9
+ const SIGNATURES: Signature[] = [
10
+ ["Nat", 0, [], [], []],
11
+ ["+", 0, [0, 0], [2, 2], [1, 1]],
12
+ ["-", 0, [0, 0], [2, 2], [1, 1]],
13
+ ["*", 0, [0, 0], [3, 3], [0, 0]],
14
+ ["^", 0, [0, 0], [2, 2], [1, 1]],
15
+ ["<", 0, [0, 0], [2, 2], [1, 1]],
16
+ [">", 0, [0, 0], [2, 2], [1, 1]],
17
+ ["<=", 0, [0, 0], [2, 2], [1, 1]],
18
+ [">=", 0, [0, 0], [2, 2], [1, 1]],
19
+ ["%", 0, [0, 0], [2, 2], [1, 1]],
20
+ ["\\div", 0, [0, 0], [2, 2], [1, 1]],
21
+ ["..", 0, [0, 0], [2, 2], [1, 1]],
22
+ ["Int", 0, [], [], []],
23
+ ["-.", 0, [0], [2], [1]],
24
+ ["Seq", 0, [0], [2], [1]],
25
+ ["Len", 0, [0], [2], [1]],
26
+ ["\\o", 0, [0, 0], [2, 2], [1, 1]],
27
+ ["Append", 0, [0, 0], [2, 2], [1, 1]],
28
+ ["Head", 0, [0], [2], [1]],
29
+ ["Tail", 0, [0], [2], [1]],
30
+ ["SubSeq", 0, [0, 0, 0], [2, 2, 2], [1, 1, 1]],
31
+ ["SelectSeq", 0, [0, 1], [2, 2], [1, 1], [], ["1,0,0"]],
32
+ ["IsFiniteSet", 0, [0], [2], [1]],
33
+ ["Cardinality", 0, [0], [2], [1]],
34
+ ["IsABag", 0, [0], [2], [1]],
35
+ ["BagToSet", 0, [0], [2], [1]],
36
+ ["SetToBag", 0, [0], [3], [1]],
37
+ ["BagIn", 0, [0, 0], [2, 2], [1, 1]],
38
+ ["EmptyBag", 0, [], [], []],
39
+ ["\\oplus", 0, [0, 0], [2, 2], [1, 1]],
40
+ ["\\ominus", 0, [0, 0], [2, 2], [1, 1]],
41
+ ["BagUnion", 0, [0], [2], [1]],
42
+ ["\\sqsubseteq", 0, [0, 0], [2, 2], [1, 1]],
43
+ ["SubBag", 0, [0], [2], [1]],
44
+ ["BagOfAll", 0, [1, 0], [2, 2], [1, 1]],
45
+ ["BagCardinality", 0, [0], [2], [1]],
46
+ ["CopiesIn", 0, [0, 0], [2, 2], [1, 1]],
47
+ ["Print", 0, [0, 0], [3, 3], [0, 1]],
48
+ ["PrintT", 0, [0], [3], [0]],
49
+ ["Assert", 0, [0, 0], [2, 3], [1, 0]],
50
+ ["JavaTime", 0, [], [], []],
51
+ ["TLCGet", 0, [0], [3], [0]],
52
+ ["TLCSet", 0, [0, 0], [3, 3], [0, 0]],
53
+ [":>", 0, [0, 0], [2, 3], [1, 1]],
54
+ ["@@", 0, [0, 0], [2, 2], [1, 1]],
55
+ ["Permutations", 0, [0], [2], [1]],
56
+ ["SortSeq", 0, [0, 2], [2, 2], [1, 1], [], ["1,0,0", "1,0,1"]],
57
+ ["RandomElement", 0, [0], [3], [1]],
58
+ ["Any", 0, [], [], []],
59
+ ["ToString", 0, [0], [2], [1]],
60
+ ["TLCEval", 0, [0], [3], [1]],
61
+ ["AssertEq", 0, [0, 0], [2, 2], [1, 1]],
62
+ ["AssertError", 0, [0, 0], [2, 3], [1, 0]],
63
+ ["TLCGetOrDefault", 0, [0, 0], [3, 3], [0, 0]],
64
+ ["TLCGetAndSet", 0, [0, 2, 0, 0], [3, 3, 3, 3], [0, 0, 0, 0], [], ["1,2,1"]],
65
+ ["Trace", 0, [], [], []],
66
+ ["CounterExample", 0, [], [], []],
67
+ ["ToTrace", 0, [0], [3], [0]],
68
+ ["TLCModelValue", 0, [0], [2], [1]],
69
+ ["TLCDefer", 0, [0], [3], [0]],
70
+ ["TLCNoOp", 0, [0], [3], [1]],
71
+ ["PickSuccessor", 0, [0], [3], [1]],
72
+ ["TLCCache", 0, [0, 0], [3, 3], [1, 0]],
73
+ ["TLCFP", 0, [0], [3], [0]],
74
+ ["TLCEvalDefinition", 0, [0], [3], [0]],
75
+ ["ToJson", 0, [0], [2], [1]],
76
+ ["ToJsonArray", 0, [0], [2], [1]],
77
+ ["ToJsonObject", 0, [0], [2], [1]],
78
+ ["JsonSerialize", 0, [0, 0], [3, 3], [0, 0]],
79
+ ["JsonDeserialize", 0, [0], [3], [0]],
80
+ ["ndJsonSerialize", 0, [0, 0], [3, 3], [0, 0]],
81
+ ["ndJsonDeserialize", 0, [0], [3], [0]],
82
+ ["RandomSubset", 0, [0, 0], [2, 2], [1, 1]],
83
+ ["RandomSetOfSubsets", 0, [0, 0, 0], [2, 3, 2], [1, 0, 1]],
84
+ ["TestRandomSetOfSubsets", 0, [0, 0, 0], [2, 3, 2], [1, 0, 1]],
85
+ ];
86
+
87
+ export const STANDARD_LEVELS = new Map(
88
+ SIGNATURES.map((signature): [string, OperatorLevels] => [
89
+ signature[0],
90
+ {
91
+ name: signature[0],
92
+ level: signature[1],
93
+ params: new Set(),
94
+ constraints: new Map(),
95
+ argConstraints: new Map(),
96
+ argParams: new Set(),
97
+ formals: signature[2].map((arity, index) => ({ name: `$${index}`, arity })),
98
+ maxLevels: signature[3],
99
+ weights: signature[4],
100
+ minMaxLevels: signature[5] ?? [],
101
+ conditions: new Set(signature[6]),
102
+ nonLeibniz: new Set(),
103
+ },
104
+ ]),
105
+ );
@@ -1,5 +1,6 @@
1
- import { TlaEvaluationError } from "./errors";
1
+ import { TlaEvaluationError, TlaModuleError } from "./errors";
2
2
  import {
3
+ createOverflowError,
3
4
  defineArithmetic,
4
5
  defineBinary,
5
6
  defineComparison,
@@ -7,12 +8,14 @@ import {
7
8
  defineHigherOrderOperator,
8
9
  defineOperator,
9
10
  getBoolean,
10
- getElements,
11
11
  getNumber,
12
12
  getOperator,
13
- getSequence,
14
13
  getSet,
14
+ getIntegersSignature,
15
+ getJavaInteger,
15
16
  getValue,
17
+ isOutOfRange,
18
+ overrideWithJava,
16
19
  } from "./builtins";
17
20
  import type { Builtin, BuiltinArgument } from "./evaluate";
18
21
  import type { CheckerRuntime } from "./runtime";
@@ -21,10 +24,10 @@ import { createJsonOperators, type FileSystem } from "./json";
21
24
  import { createRandomizationOperators } from "./randomization";
22
25
  import { createPossibleOperators, createTlcExtOperators } from "./tlc-ext";
23
26
  import { createTlcOperators } from "./tlc-module";
27
+ import { TLC_JAVA_METHODS } from "./tlc-modules";
24
28
  import {
25
- checkInteger,
26
29
  createSet,
27
- createSortedSet,
30
+ describeKind,
28
31
  createTuple,
29
32
  differenceSorted,
30
33
  formatValue,
@@ -32,16 +35,25 @@ import {
32
35
  getDomain,
33
36
  intersectSorted,
34
37
  isElementOf,
38
+ getSequenceElements,
35
39
  isEmptySet,
36
40
  isEnumerable,
41
+ isFiniteSet,
37
42
  isFunctionValue,
43
+ isReducible,
38
44
  isSetValue,
39
45
  toFiniteSet,
40
46
  unionSorted,
41
- valuesEqual,
47
+ isEqualLikeTlc,
48
+ createEnumeratedSet,
49
+ EMPTY_SET,
50
+ isEnumeratedSet,
51
+ type ReducibleSet,
52
+ type MixedSetValue,
42
53
  type SetOperationValue,
43
54
  type SetValue,
44
55
  type Value,
56
+ rankString,
45
57
  } from "./values";
46
58
 
47
59
  interface StandardModule {
@@ -53,30 +65,61 @@ const isSubsetOf = (left: Value[], right: Value) =>
53
65
  left.every((element) => isElementOf(element, right));
54
66
 
55
67
  const BOOLEAN_SET = createSet([false, true]);
56
- const EMPTY_SET = createSortedSet([]);
57
- const MERGED_UNION_LIMIT = 8;
68
+
69
+ // Merging the sets pairwise in a balanced tree compares each element about log2 of their count
70
+ // times.
71
+ const unionInTree = (sets: SetValue[], start: number, end: number): SetValue => {
72
+ if (end - start === 1) return sets[start];
73
+ const middle = (start + end) >> 1;
74
+ return unionSorted(unionInTree(sets, start, middle), unionInTree(sets, middle, end));
75
+ };
58
76
 
59
77
  const SET_OPERATORS: SetOperationValue["operator"][] = ["\\cup", "\\cap", "\\"];
60
78
 
79
+ const isMixedSet = (value: Value) => typeof value === "object" && value.kind === "MixedSet";
80
+
81
+ const getReducibleElements = (set: ReducibleSet) =>
82
+ set.kind === "Interval" ? toFiniteSet(set).elements : set.elements;
83
+
84
+ // TLC combines a set enumeration or an interval with another set element by element, testing each
85
+ // element for membership in the other set.
86
+ const combineReducible = (
87
+ operator: SetOperationValue["operator"],
88
+ set: ReducibleSet,
89
+ other: Value,
90
+ ): Value => {
91
+ const elements = getReducibleElements(set);
92
+ if (operator !== "\\cup") {
93
+ const isKept = operator === "\\cap";
94
+ return createEnumeratedSet(
95
+ elements.filter((element) => isElementOf(element, other) === isKept),
96
+ );
97
+ }
98
+ if (elements.length === 0) return other;
99
+ if (!isReducible(other)) return { kind: "SetOperation", operator, left: set, right: other };
100
+ const added = toFiniteSet(other).elements.filter((element) => !isElementOf(element, set));
101
+ return createEnumeratedSet([...elements, ...added]);
102
+ };
103
+
61
104
  export const CORE_OPERATORS: Builtin[] = [
62
105
  defineConstant("TRUE", true),
63
106
  defineConstant("FALSE", false),
64
107
  defineConstant("BOOLEAN", BOOLEAN_SET),
65
108
  defineConstant("STRING", { kind: "InfiniteSet", name: "STRING" }),
66
- defineBinary("=", valuesEqual),
67
- defineBinary("#", (left, right) => !valuesEqual(left, right)),
109
+ defineBinary("=", isEqualLikeTlc),
110
+ defineBinary("#", (left, right) => !isEqualLikeTlc(left, right)),
68
111
  defineOperator("~", 1, (args) => !getBoolean(args, 0, "~")),
69
112
  defineOperator("<=>", 2, (args) => getBoolean(args, 0, "<=>") === getBoolean(args, 1, "<=>")),
70
113
  defineOperator("/\\", 2, (args) => getBoolean(args, 0, "/\\") && getBoolean(args, 1, "/\\")),
71
114
  defineOperator("\\/", 2, (args) => getBoolean(args, 0, "\\/") || getBoolean(args, 1, "\\/")),
72
115
  defineOperator("=>", 2, (args) => !getBoolean(args, 0, "=>") || getBoolean(args, 1, "=>")),
73
116
  defineOperator("\\in", 2, (args) =>
74
- isElementOf(getValue(args, 0, "\\in"), getSet(args, 1, "\\in")),
117
+ isElementOf(getValue(args, 0, "\\in"), getValue(args, 1, "\\in")),
75
118
  ),
76
119
  defineOperator(
77
120
  "\\notin",
78
121
  2,
79
- (args) => !isElementOf(getValue(args, 0, "\\notin"), getSet(args, 1, "\\notin")),
122
+ (args) => !isElementOf(getValue(args, 0, "\\notin"), getValue(args, 1, "\\notin")),
80
123
  ),
81
124
  defineOperator("\\subseteq", 2, (args) => {
82
125
  const left = getSet(args, 0, "\\subseteq");
@@ -88,13 +131,14 @@ export const CORE_OPERATORS: Builtin[] = [
88
131
  right.kind === "Subset" &&
89
132
  isEnumerable(left.base);
90
133
  if (isPowerSets) return isSubsetOf(toFiniteSet(left.base).elements, right.base);
91
- return isSubsetOf(getElements(args, 0, "\\subseteq"), right);
134
+ return isSubsetOf(toFiniteSet(left).elements, right);
92
135
  }),
93
136
  ...SET_OPERATORS.map((operator) =>
94
137
  defineOperator(operator, 2, (args) => {
95
138
  const left = getSet(args, 0, operator);
96
139
  const right = getSet(args, 1, operator);
97
- if (isEnumerable(left) && isEnumerable(right)) {
140
+ if (isReducible(left) && isReducible(right) && !isMixedSet(left) && !isMixedSet(right)) {
141
+ if (operator === "\\cup" && isEmptySet(left)) return right;
98
142
  const merge =
99
143
  operator === "\\cup"
100
144
  ? unionSorted
@@ -103,35 +147,28 @@ export const CORE_OPERATORS: Builtin[] = [
103
147
  : differenceSorted;
104
148
  return merge(toFiniteSet(left), toFiniteSet(right));
105
149
  }
106
- const isReducible = (value: Value) =>
107
- typeof value === "object" && (value.kind === "Set" || value.kind === "Interval");
108
- const isSwapped = operator === "\\cup" && !isReducible(left) && isReducible(right);
109
- const set: Value = isSwapped
110
- ? { kind: "SetOperation", operator, left: right, right: left }
111
- : { kind: "SetOperation", operator, left, right };
112
- return isEnumerable(set) ? toFiniteSet(set) : set;
150
+ if (isReducible(left)) return combineReducible(operator, left, right);
151
+ if (operator !== "\\" && isReducible(right)) return combineReducible(operator, right, left);
152
+ return { kind: "SetOperation", operator, left, right };
113
153
  }),
114
154
  ),
115
155
  defineOperator("SUBSET", 1, (args) => ({ kind: "Subset", base: getSet(args, 0, "SUBSET") })),
116
156
  defineOperator("UNION", 1, (args) => {
117
- const sets = getElements(args, 0, "UNION");
118
- sets.forEach((element) => {
119
- if (!isSetValue(element)) {
120
- throw new TlaEvaluationError(
121
- `UNION expects a set of sets but found ${formatValue(element)}`,
122
- );
123
- }
124
- });
125
- if (sets.every((element) => typeof element === "object" && element.kind === "Set")) {
126
- if (sets.length > MERGED_UNION_LIMIT) {
127
- return createSet(sets.flatMap((element) => toFiniteSet(element).elements));
128
- }
129
- return sets.reduce<SetValue>(
130
- (union, element) => unionSorted(union, toFiniteSet(element)),
131
- EMPTY_SET,
157
+ const outer = getSet(args, 0, "UNION");
158
+ const sets = isEnumeratedSet(outer) ? outer.elements.filter(isEnumeratedSet) : [];
159
+ if (!isEnumeratedSet(outer) || sets.length !== outer.elements.length) {
160
+ return { kind: "Union", base: outer };
161
+ }
162
+ if (isMixedSet(outer) || sets.some(isMixedSet)) {
163
+ const union: MixedSetValue = { kind: "MixedSet", elements: [] };
164
+ sets.forEach((set) =>
165
+ set.elements.forEach((member) => {
166
+ if (!isElementOf(member, union)) union.elements.push(member);
167
+ }),
132
168
  );
169
+ return createEnumeratedSet(union.elements);
133
170
  }
134
- return sets.reduce((left, right) => ({ kind: "SetOperation", operator: "\\cup", left, right }));
171
+ return sets.length === 0 ? EMPTY_SET : unionInTree(sets.map(toFiniteSet), 0, sets.length);
135
172
  }),
136
173
  defineOperator("DOMAIN", 1, (args) => {
137
174
  const value = getValue(args, 0, "DOMAIN");
@@ -142,24 +179,36 @@ export const CORE_OPERATORS: Builtin[] = [
142
179
  }),
143
180
  ];
144
181
 
145
- const NATURALS_OPERATORS: Builtin[] = [
182
+ const DOT_DOT_SIGNATURE = getIntegersSignature("DotDot", "IntervalValue", 2);
183
+
184
+ const NEG_SIGNATURE = getIntegersSignature("Neg", "IntValue", 1);
185
+
186
+ const NATURALS_OPERATORS = [
146
187
  defineConstant("Nat", { kind: "InfiniteSet", name: "Nat" }),
147
- defineArithmetic("+", (left, right) => left + right),
148
- defineArithmetic("-", (left, right) => left - right),
149
- defineArithmetic("*", (left, right) => left * right),
150
- defineArithmetic("^", (base, exponent) => {
151
- if (exponent < 0 || (base === 0 && exponent === 0)) {
152
- throw new TlaEvaluationError(`${base}^${exponent} is undefined`);
188
+ defineArithmetic("+", "Plus", (left, right) => left + right),
189
+ defineArithmetic("-", "Minus", (left, right) => left - right),
190
+ defineArithmetic("*", "Times", (left, right) => left * right),
191
+ defineArithmetic("^", "Expt", (base, exponent) => {
192
+ if (exponent < 0) {
193
+ throw new TlaModuleError(
194
+ `The second argument of ^ should be a natural number, but instead it is:\n${exponent}`,
195
+ );
153
196
  }
197
+ if (base === 0 && exponent === 0) throw new TlaModuleError("0^0 is undefined.");
154
198
  return base ** exponent;
155
199
  }),
156
- defineArithmetic("\\div", (left, right) => {
157
- if (right === 0) throw new TlaEvaluationError(`Division by zero in ${left} \\div 0`);
158
- return Math.floor(left / right);
200
+ defineArithmetic("\\div", "Divide", (left, right) => {
201
+ if (right === 0) throw new TlaModuleError("The second argument of \\div is 0.");
202
+ const quotient = Math.floor(left / right);
203
+ if (isOutOfRange(quotient)) throw createOverflowError(`${left} \\div ${right}`);
204
+ return quotient;
159
205
  }),
160
- defineArithmetic("%", (left, right) => {
161
- if (right <= 0)
162
- throw new TlaEvaluationError(`The second argument of % must be positive, but was ${right}`);
206
+ defineArithmetic("%", "Mod", (left, right) => {
207
+ if (right <= 0) {
208
+ throw new TlaModuleError(
209
+ `The second argument of % should be a positive number, but instead it is:\n${right}`,
210
+ );
211
+ }
163
212
  return ((left % right) + right) % right;
164
213
  }),
165
214
  defineComparison("<", (left, right) => left < right),
@@ -168,85 +217,162 @@ const NATURALS_OPERATORS: Builtin[] = [
168
217
  defineComparison(">=", (left, right) => left >= right),
169
218
  defineOperator("..", 2, (args) => ({
170
219
  kind: "Interval",
171
- low: getNumber(args, 0, ".."),
172
- high: getNumber(args, 1, ".."),
220
+ low: getJavaInteger(getValue(args, 0, ".."), DOT_DOT_SIGNATURE),
221
+ high: getJavaInteger(getValue(args, 1, ".."), DOT_DOT_SIGNATURE),
173
222
  })),
174
223
  ];
175
224
 
176
- const INTEGERS_OPERATORS: Builtin[] = [
225
+ const INTEGERS_OPERATORS = [
177
226
  defineConstant("Int", { kind: "InfiniteSet", name: "Int" }),
178
- defineOperator("-.", 1, (args) => checkInteger(-getNumber(args, 0, "-"))),
227
+ defineOperator("-.", 1, (args) => {
228
+ const value = getJavaInteger(getValue(args, 0, "-"), NEG_SIGNATURE);
229
+ if (isOutOfRange(-value)) throw createOverflowError(`-${value}`);
230
+ return -value;
231
+ }),
179
232
  ];
180
233
 
181
- const getSequenceOrString = (args: BuiltinArgument[], index: number, name: string) => {
182
- const value = getValue(args, index, name);
183
- return typeof value === "string" ? value : getSequence(args, index, name);
234
+ const getSequenceArgument = (args: BuiltinArgument[], index: number, message: string) => {
235
+ const value = getValue(args, index, message);
236
+ const elements = getSequenceElements(value);
237
+ if (!elements) throw new TlaModuleError(`${message}\n${formatValue(value)}`);
238
+ return elements;
184
239
  };
185
240
 
186
- const SEQUENCES_OPERATORS: Builtin[] = [
187
- defineOperator("Seq", 1, (args) => ({ kind: "SequenceSet", base: getSet(args, 0, "Seq") })),
188
- defineOperator("Len", 1, (args) => getSequenceOrString(args, 0, "Len").length),
241
+ const getSequenceOrString = (args: BuiltinArgument[], index: number, message: string) => {
242
+ const value = getValue(args, index, message);
243
+ return typeof value === "string" ? value : getSequenceArgument(args, index, message);
244
+ };
245
+
246
+ const sliceSequence = (sequence: string | Value[], start: number, end?: number) =>
247
+ typeof sequence === "string"
248
+ ? rankString(sequence.slice(start, end))
249
+ : createTuple(sequence.slice(start, end));
250
+
251
+ const getSequenceMessage = (position: string, name: string) =>
252
+ `The ${position}argument of ${name} should be a sequence, but instead it is:`;
253
+
254
+ const getEvaluatingMessage = (form: string, kind: string) =>
255
+ `Evaluating an expression of the form ${form} when s is not a ${kind}:`;
256
+
257
+ const withJavaMethods = (module: string, operators: Builtin[]) => {
258
+ const methods = TLC_JAVA_METHODS.get(module);
259
+ if (!methods) return operators;
260
+ return operators.map((operator) => {
261
+ const signature = methods.get(operator.name);
262
+ return signature ? overrideWithJava(operator, signature) : operator;
263
+ });
264
+ };
265
+
266
+ const SEQUENCES_OPERATORS = withJavaMethods("Sequences", [
267
+ defineOperator("Seq", 1, (args) => ({ kind: "SequenceSet", base: getValue(args, 0, "Seq") })),
268
+ defineOperator(
269
+ "Len",
270
+ 1,
271
+ (args) => getSequenceOrString(args, 0, getSequenceMessage("", "Len")).length,
272
+ ),
189
273
  defineOperator("\\o", 2, (args) => {
190
- const left = getSequenceOrString(args, 0, "\\o");
191
- const right = getSequenceOrString(args, 1, "\\o");
192
- if (typeof left === "string" && typeof right === "string") return left + right;
193
- if (typeof left === "string" || typeof right === "string") {
194
- throw new TlaEvaluationError("\\o cannot concatenate a string with a sequence");
274
+ const left = getSequenceOrString(args, 0, getEvaluatingMessage("s \\o t", "sequence"));
275
+ if (typeof left !== "string") {
276
+ const right = getSequenceArgument(args, 1, getEvaluatingMessage("t \\o s", "sequence"));
277
+ return createTuple([...left, ...right]);
195
278
  }
196
- return createTuple([...left, ...right]);
279
+ const right = getValue(args, 1, "\\o");
280
+ if (typeof right !== "string") {
281
+ throw new TlaModuleError(
282
+ `${getEvaluatingMessage("t \\o s", "string")}\n${formatValue(right)}`,
283
+ );
284
+ }
285
+ return rankString(left + right);
197
286
  }),
198
287
  defineOperator("Append", 2, (args) =>
199
- createTuple([...getSequence(args, 0, "Append"), getValue(args, 1, "Append")]),
288
+ createTuple([
289
+ ...getSequenceArgument(args, 0, getEvaluatingMessage("Append(s, v)", "sequence")),
290
+ getValue(args, 1, "Append"),
291
+ ]),
200
292
  ),
201
293
  defineOperator("Head", 1, (args) => {
202
- const elements = getSequence(args, 0, "Head");
294
+ const elements = getSequenceArgument(args, 0, getSequenceMessage("", "Head"));
203
295
  if (elements.length === 0)
204
- throw new TlaEvaluationError("Attempted to apply Head to the empty sequence");
296
+ throw new TlaModuleError("Attempted to apply Head to the empty sequence.");
205
297
  return elements[0];
206
298
  }),
207
299
  defineOperator("Tail", 1, (args) => {
208
- const sequence = getSequenceOrString(args, 0, "Tail");
300
+ const sequence = getSequenceOrString(args, 0, getSequenceMessage("", "Tail"));
209
301
  if (sequence.length === 0)
210
- throw new TlaEvaluationError("Attempted to apply Tail to the empty sequence");
211
- return typeof sequence === "string" ? sequence.slice(1) : createTuple(sequence.slice(1));
302
+ throw new TlaModuleError("Attempted to apply Tail to the empty sequence.");
303
+ return sliceSequence(sequence, 1);
212
304
  }),
213
305
  defineOperator("SubSeq", 3, (args) => {
214
- const sequence = getSequenceOrString(args, 0, "SubSeq");
306
+ const sequence = getSequenceOrString(args, 0, getSequenceMessage("first ", "SubSeq"));
215
307
  const start = getNumber(args, 1, "SubSeq");
216
308
  const end = getNumber(args, 2, "SubSeq");
217
- if (start > end) return typeof sequence === "string" ? "" : createTuple([]);
218
- if (start < 1 || end > sequence.length) {
219
- throw new TlaEvaluationError(
220
- `SubSeq bounds ${start}..${end} are outside 1..${sequence.length}`,
309
+ if (start > end) return sliceSequence(sequence, 0, 0);
310
+ const outOfDomain =
311
+ start < 1
312
+ ? { position: "second", value: start }
313
+ : end > sequence.length
314
+ ? { position: "third", value: end }
315
+ : undefined;
316
+ if (outOfDomain) {
317
+ throw new TlaModuleError(
318
+ `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}`,
221
319
  );
222
320
  }
223
- return typeof sequence === "string"
224
- ? sequence.slice(start - 1, end)
225
- : createTuple(sequence.slice(start - 1, end));
321
+ return sliceSequence(sequence, start - 1, end);
226
322
  }),
227
323
  defineHigherOrderOperator("SelectSeq", 2, (args) => {
228
324
  const test = getOperator(args, 1, "SelectSeq");
229
325
  return createTuple(
230
- getSequence(args, 0, "SelectSeq").filter((element) => {
326
+ getSequenceArgument(args, 0, getSequenceMessage("first ", "SelectSeq")).filter((element) => {
231
327
  const result = test.call([element]);
232
- if (typeof result !== "boolean")
233
- throw new TlaEvaluationError("The test of SelectSeq must return a boolean");
328
+ if (typeof result !== "boolean") {
329
+ throw new TlaModuleError(
330
+ `The second argument of SelectSeq should be a operator, but instead it is:\n${formatValue(result)}`,
331
+ );
332
+ }
234
333
  return result;
235
334
  }),
236
335
  );
237
336
  }),
238
- ];
337
+ ]);
239
338
 
240
- const FINITE_SETS_OPERATORS: Builtin[] = [
241
- defineOperator("IsFiniteSet", 1, (args) => isEnumerable(getSet(args, 0, "IsFiniteSet"))),
339
+ const FINITE_SETS_OPERATORS = withJavaMethods("FiniteSets", [
340
+ defineOperator("IsFiniteSet", 1, (args) => {
341
+ const value = getValue(args, 0, "IsFiniteSet");
342
+ if (isSetValue(value)) return isFiniteSet(value);
343
+ if (typeof value === "object" && value.kind === "Function") return true;
344
+ throw new TlaEvaluationError(
345
+ typeof value === "object" && value.kind === "LazyFunction"
346
+ ? `Attempted to check if the function:\n${formatValue(value)}\nis a finite set.`
347
+ : `Attempted to check if the ${describeKind(value)} ${formatValue(value)} is a finite set.`,
348
+ );
349
+ }),
242
350
  defineOperator("Cardinality", 1, (args) => {
243
- const set = getSet(args, 0, "Cardinality");
244
- if (isEmptySet(set)) return 0;
245
- if (!isEnumerable(set))
246
- throw new TlaEvaluationError(`Cardinality of the infinite set ${formatValue(set)}`);
351
+ const set = getValue(args, 0, "Cardinality");
352
+ if (
353
+ !isSetValue(set) ||
354
+ (typeof set === "object" && (set.kind === "InfiniteSet" || set.kind === "SequenceSet"))
355
+ ) {
356
+ throw new TlaModuleError(
357
+ `Attempted to compute cardinality of the value\n${formatValue(set)}`,
358
+ );
359
+ }
247
360
  return getCardinality(set);
248
361
  }),
249
- ];
362
+ ]);
363
+
364
+ // The modules that each standard module loads through EXTENDS and LOCAL INSTANCE in TLC.
365
+ export const STANDARD_DEPENDENCIES = new Map([
366
+ ["Integers", ["Naturals"]],
367
+ ["Sequences", ["Naturals"]],
368
+ ["FiniteSets", ["Naturals", "Sequences"]],
369
+ ["TLC", ["Naturals", "Sequences", "FiniteSets"]],
370
+ ["Randomization", ["Naturals", "FiniteSets", "Sequences"]],
371
+ ["_Possible", ["TLC", "TLCExt", "Naturals", "Sequences", "FiniteSets", "Integers"]],
372
+ ["Json", ["Sequences", "FiniteSets", "TLC", "Naturals"]],
373
+ ["Bags", ["Naturals"]],
374
+ ["TLCExt", ["TLC", "Integers", "Naturals", "Sequences", "FiniteSets"]],
375
+ ]);
250
376
 
251
377
  export const getStandardModule = (
252
378
  name: string,
@@ -264,7 +390,7 @@ export const getStandardModule = (
264
390
  case "FiniteSets":
265
391
  return { extends: [], operators: FINITE_SETS_OPERATORS };
266
392
  case "TLC":
267
- return { extends: [], operators: createTlcOperators(print, runtime) };
393
+ return { extends: [], operators: withJavaMethods("TLC", createTlcOperators(print, runtime)) };
268
394
  case "Randomization":
269
395
  return { extends: [], operators: createRandomizationOperators(runtime) };
270
396
  case "_Possible":