tla-ts 0.0.3 → 0.0.4-dev.2be6058

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 +160 -8
  6. package/dist/index.d.ts +160 -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 +77 -37
  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 +797 -246
  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 +200 -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 +219 -107
  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 +731 -184
@@ -0,0 +1,454 @@
1
+ import { PcalError, PcalRuntimeError } from "./errors";
2
+ import {
3
+ formatPcalNode,
4
+ getPcalLocation,
5
+ getPcalVersionNumber,
6
+ PCAL_VERSION_WEIGHT,
7
+ type PcalAlgorithm,
8
+ } from "./pcal-ast";
9
+ import { parsePcalAlgorithm, type PcalSession } from "./pcal-parse";
10
+ import { createPcalCharReader } from "./pcal-tokenize";
11
+ import { translatePcalAlgorithm } from "./pcal-translate";
12
+ import type { TlcVersion } from "./tlc-version";
13
+
14
+ // Validator.ValidationResult.
15
+ type PcalValidationResult =
16
+ | "NO_PLUSCAL_EXISTS"
17
+ | "NO_TRANSLATION_EXISTS"
18
+ | "NO_PCAL_CHECKSUMS_EXIST"
19
+ | "TLA_DIVERGENCE_EXISTS"
20
+ | "PCAL_DIVERGENCE_EXISTS"
21
+ | "ERROR_ENCOUNTERED"
22
+ | "NO_DIVERGENCE";
23
+
24
+ // Java's \s, which unlike JavaScript's matches no Unicode spaces.
25
+ const SPACE = "[ \\t\\n\\x0B\\f\\r]";
26
+
27
+ // Validator.CHECKSUM_PATTERN, whose (?i) groups become character classes.
28
+ const CHECKSUM_PATTERN = new RegExp(
29
+ `\\\\\\* BEGIN TRANSLATION${SPACE}+\\(${SPACE}*([cC][hH]([eE][cC])?[kK][sS][uU][mM]\\([pP]([lL][uU][sS])?[cC][aA][lL]\\))${SPACE}*(=${SPACE}*"(?<pcal>[0-9A-Fa-f]*)"|\\\\in${SPACE}*STRING)${SPACE}*\\/\\\\${SPACE}*([cC][hH]([eE][cC])?[kK][sS][uU][mM]\\([tT][lL][aA]\\+?\\))${SPACE}*(=${SPACE}*"(?<tla>[0-9A-Fa-f]*)"|\\\\in${SPACE}*STRING)${SPACE}*\\)`,
30
+ );
31
+
32
+ // Validator.checksum: CRC32 of the string's bytes, in Long.toHexString's unpadded lowercase hex.
33
+ // Only a spec with PlusCal needs node:zlib, so it loads then rather than at startup.
34
+ const getChecksum = (text: string) =>
35
+ process.getBuiltinModule("node:zlib").crc32(Buffer.from(text, "utf8")).toString(16);
36
+
37
+ const reportUnrecoverableError = (session: PcalSession, message: string) =>
38
+ session.log(`\nUnrecoverable error:\n -- ${message}.\n`);
39
+
40
+ // PcalDebug.reportError: an UnrecoverablePositionedException names its statement's position.
41
+ const reportPcalError = (session: PcalSession, error: PcalError) =>
42
+ reportUnrecoverableError(
43
+ session,
44
+ error.node === undefined || error.node.line === 0
45
+ ? error.message
46
+ : `${error.message}\n at ${getPcalLocation(error.node)}`,
47
+ );
48
+
49
+ // trans.removeTabs: tabs reach the next multiple of 8, and every line gets a trailing space.
50
+ const removeTabs = (lines: string[]) =>
51
+ lines.map(
52
+ (line) =>
53
+ `${Array.from(line).reduce(
54
+ (result, char) =>
55
+ char === "\t" ? result + " ".repeat(8 - (result.length % 8)) : result + char,
56
+ "",
57
+ )} `,
58
+ );
59
+
60
+ // trans.findTokenPair: the first line from start with first followed by second after spaces.
61
+ const findTokenPair = (lines: string[], start: number, first: string, second: string) => {
62
+ for (let index = Math.max(start, 0); index < lines.length; index++) {
63
+ const line = lines[index];
64
+ const column = line.indexOf(first);
65
+ if (column === -1) continue;
66
+ const afterFirst = column + first.length;
67
+ const spaces = line.slice(afterFirst).search(/[^ ]/);
68
+ if (spaces !== -1 && afterFirst + spaces === line.indexOf(second)) return index;
69
+ }
70
+ return -1;
71
+ };
72
+
73
+ interface PcalSearchLocation {
74
+ line: number;
75
+ column: number;
76
+ }
77
+
78
+ // ParseAlgorithm.GotoNextNonSpace: moves the location to the next character that isn't a space,
79
+ // returning its line, or "" past the last line.
80
+ const gotoNextNonSpace = (lines: string[], location: PcalSearchLocation) => {
81
+ while (location.line < lines.length) {
82
+ const line = lines[location.line];
83
+ while (location.column < line.length && line[location.column] === " ") location.column += 1;
84
+ if (location.column < line.length) return line;
85
+ location.line += 1;
86
+ location.column = 0;
87
+ }
88
+ return "";
89
+ };
90
+
91
+ // ParseAlgorithm.NextSpaceCol and NextDelimiterCol: the first delimiter from column on, or the
92
+ // end of the line.
93
+ const getNextDelimiter = (line: string, column: number, delimiters: string) => {
94
+ const index = Array.from(line.slice(column)).findIndex((char) => delimiters.includes(char));
95
+ return index === -1 ? line.length : column + line.slice(column, column + index).length;
96
+ };
97
+
98
+ const isIdChar = (char: string) => /^[\p{L}\p{Nd}_]$/u.test(char);
99
+
100
+ // ParseAlgorithm.FindToken: moves the location past the next occurrence of token that starts a
101
+ // word and isn't followed by a letter or "_".
102
+ const findToken = (lines: string[], location: PcalSearchLocation, token: string) => {
103
+ while (location.line < lines.length) {
104
+ const line = gotoNextNonSpace(lines, location);
105
+ if (line.slice(location.column).startsWith(token)) {
106
+ const end = location.column + token.length;
107
+ if (end >= line.length || !/^[\p{L}_]$/u.test(line[end])) {
108
+ location.column = getNextDelimiter(line, end, " ");
109
+ return true;
110
+ }
111
+ }
112
+ location.column = getNextDelimiter(line, location.column, " ");
113
+ }
114
+ return false;
115
+ };
116
+
117
+ // trans.CommandLineError.
118
+ const reportCommandLineError = (session: PcalSession, message: string) =>
119
+ reportUnrecoverableError(session, `Command-line error: ${message}`);
120
+
121
+ // trans.parseAndProcessArguments for the options of a "PlusCal options" statement, which set the
122
+ // translator's options for the rest of SANY's run.
123
+ const processOptionArguments = (session: PcalSession, args: string[]) => {
124
+ const params = session.params;
125
+ const fairness = { isFirst: true, isExplicitNof: false };
126
+ const setFairness = (option: string) => {
127
+ if (fairness.isFirst) {
128
+ params.fairnessOption = "";
129
+ fairness.isFirst = false;
130
+ }
131
+ if (params.fairnessOption !== "") {
132
+ reportCommandLineError(session, "Can only have one of -wf, -sf, -wfNext, and -nof options");
133
+ return false;
134
+ }
135
+ params.fairnessOption = option;
136
+ return true;
137
+ };
138
+ for (let index = 0; index < args.length; index++) {
139
+ const option = args[index];
140
+ const argument = args[index + 1];
141
+ switch (option) {
142
+ case "-spec":
143
+ case "spec":
144
+ case "-myspec":
145
+ case "myspec": {
146
+ const isMyspec = option.endsWith("myspec");
147
+ params[isMyspec ? "myspecOption" : "specOption"] = true;
148
+ if (params.specOption && params.myspecOption) {
149
+ reportCommandLineError(
150
+ session,
151
+ "\nCan have at most one of the options -spec, -myspec, -spec2, -myspec2, writeAST",
152
+ );
153
+ return;
154
+ }
155
+ if (argument === undefined) {
156
+ reportCommandLineError(
157
+ session,
158
+ `Specification name must follow \`-${isMyspec ? "myspec" : "spec"}' option`,
159
+ );
160
+ return;
161
+ }
162
+ params.specFile = argument;
163
+ index += 1;
164
+ continue;
165
+ }
166
+ case "-termination":
167
+ case "termination":
168
+ params.checkTermination = true;
169
+ continue;
170
+ case "-noold":
171
+ params.noOld = true;
172
+ continue;
173
+ case "-nocfg":
174
+ params.nocfg = true;
175
+ continue;
176
+ case "-noDoneDisjunct":
177
+ case "noDoneDisjunct":
178
+ params.noDoneDisjunct = true;
179
+ continue;
180
+ case "-wf":
181
+ case "wf":
182
+ case "-sf":
183
+ case "sf":
184
+ case "-wfNext":
185
+ case "wfNext":
186
+ case "-nof":
187
+ case "nof":
188
+ if (!setFairness(option.replace(/^-/, ""))) return;
189
+ if (option.endsWith("nof")) fairness.isExplicitNof = true;
190
+ continue;
191
+ case "-label":
192
+ case "label":
193
+ params.labelFlag = true;
194
+ continue;
195
+ case "-labelRoot":
196
+ case "labelRoot":
197
+ if (argument === undefined) {
198
+ reportCommandLineError(session, "Label root must follow `-labelRoot' option");
199
+ return;
200
+ }
201
+ if (!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(argument)) {
202
+ reportCommandLineError(
203
+ session,
204
+ "Label root must be a valid PlusCal identifier (must start with a letter and contain only letters, numbers, and underscores)",
205
+ );
206
+ return;
207
+ }
208
+ params.labelRoot = argument;
209
+ index += 1;
210
+ continue;
211
+ case "-version":
212
+ case "version": {
213
+ if (argument === undefined) {
214
+ reportCommandLineError(session, "Version number must follow `-version' option");
215
+ return;
216
+ }
217
+ // PcalParams.ProcessVersion.
218
+ const version = getPcalVersionNumber(argument);
219
+ if (version < 0 || version > PCAL_VERSION_WEIGHT) {
220
+ reportUnrecoverableError(
221
+ session,
222
+ version < 0
223
+ ? `Illegal version ${argument} specified.`
224
+ : `Specified version ${argument} later than current version 1.12`,
225
+ );
226
+ reportCommandLineError(session, "Bad version number");
227
+ return;
228
+ }
229
+ params.inputVersionNumber = version;
230
+ index += 1;
231
+ continue;
232
+ }
233
+ case "-lineWidth":
234
+ // PcalTLAGen's line width only shapes the translation's text.
235
+ if (!/^[+-]?\d+$/.test(argument ?? "") || Number(argument) < 60) {
236
+ reportCommandLineError(
237
+ session,
238
+ "Integer value at least 60 must follow `-lineWidth' option",
239
+ );
240
+ return;
241
+ }
242
+ index += 1;
243
+ continue;
244
+ default:
245
+ reportCommandLineError(
246
+ session,
247
+ `Unknown or illegal option in options statement: ${option}`,
248
+ );
249
+ return;
250
+ }
251
+ }
252
+ if (params.checkTermination && params.fairnessOption === "" && !fairness.isExplicitNof) {
253
+ params.fairnessOption = "wf";
254
+ }
255
+ };
256
+
257
+ // ParseAlgorithm.ProcessOptions: the location is just past "PlusCal".
258
+ const processOptions = (session: PcalSession, lines: string[], location: PcalSearchLocation) => {
259
+ gotoNextNonSpace(lines, location);
260
+ location.column += "options".length;
261
+ const afterOptions = gotoNextNonSpace(lines, location);
262
+ if (!afterOptions.slice(location.column).startsWith("(")) {
263
+ reportUnrecoverableError(session, "`PlusCal options' not followed by '('");
264
+ return;
265
+ }
266
+ location.column += 1;
267
+ const args: string[] = [];
268
+ for (;;) {
269
+ const line = gotoNextNonSpace(lines, location);
270
+ if (location.line >= lines.length || line[location.column] === ")") break;
271
+ if (line[location.column] === ",") {
272
+ location.column += 1;
273
+ continue;
274
+ }
275
+ const end = getNextDelimiter(line, location.column, " ,)");
276
+ args.push(line.slice(location.column, end));
277
+ location.column = end;
278
+ }
279
+ if (location.line >= lines.length) {
280
+ reportUnrecoverableError(session, "No closing ')' found in options statement");
281
+ return;
282
+ }
283
+ processOptionArguments(session, args);
284
+ };
285
+
286
+ // ParseAlgorithm.uncomment: blanks out the comment delimiters and nested comments from the
287
+ // algorithm's start to the "*)" that ends the comment it is in, dropping the rest of that line,
288
+ // and returns the error it throws for a line that ends in a string.
289
+ const uncomment = (lines: string[], startLine: number, startColumn: number) => {
290
+ const scan = { depth: 0, isDone: false, isInString: false };
291
+ for (let index = startLine; !scan.isDone && index < lines.length; index++) {
292
+ const line = lines[index];
293
+ const start = index === startLine ? startColumn : 0;
294
+ const output = [line.slice(0, start)];
295
+ scan.isInString = false;
296
+ for (let column = start; !scan.isDone && column < line.length; column++) {
297
+ const char = line[column];
298
+ const pair = line.slice(column, column + 2);
299
+ if (pair === "(*" && !scan.isInString) {
300
+ scan.depth += 1;
301
+ output.push(" ");
302
+ column += 1;
303
+ continue;
304
+ }
305
+ if (pair === "*)" && !scan.isInString && scan.depth === 0) {
306
+ output.push(pair);
307
+ scan.isDone = true;
308
+ continue;
309
+ }
310
+ if (pair === "*)" && !scan.isInString) {
311
+ scan.depth -= 1;
312
+ output.push(" ");
313
+ column += 1;
314
+ continue;
315
+ }
316
+ if (scan.depth > 0) {
317
+ output.push(" ");
318
+ continue;
319
+ }
320
+ if (scan.isInString && char === "\\" && pair.length === 2) {
321
+ output.push(pair);
322
+ column += 1;
323
+ continue;
324
+ }
325
+ if (!scan.isInString && pair === "\\*") {
326
+ output.push(" ");
327
+ break;
328
+ }
329
+ if (char === '"') scan.isInString = !scan.isInString;
330
+ output.push(char);
331
+ }
332
+ if (scan.isInString) return new PcalError(`Unterminated string in line ${index + 1}`);
333
+ lines[index] = output.join("");
334
+ }
335
+ return undefined;
336
+ };
337
+
338
+ // Vector.get on an index out of its range, whose message names the vector's capacity: the 10 it
339
+ // starts with, doubled as it grows.
340
+ const throwIndexOutOfBounds = (index: number, size: number): never => {
341
+ const capacity = 10 * 2 ** Math.max(0, Math.ceil(Math.log2(size / 10)));
342
+ throw new PcalRuntimeError(
343
+ `java.lang.ArrayIndexOutOfBoundsException: Index ${index} out of bounds for length ${capacity}`,
344
+ );
345
+ };
346
+
347
+ // Validator.validate: checks the PlusCal algorithm of the module whose lines are given, from its
348
+ // first to its last, against the checksums its translation records.
349
+ export const validatePcalModule = (
350
+ session: PcalSession,
351
+ specificationText: string[],
352
+ version?: TlcVersion,
353
+ ): Set<PcalValidationResult> => {
354
+ if (!specificationText.some((line) => line.indexOf("algorithm") > 0)) {
355
+ return new Set(["NO_PLUSCAL_EXISTS"]);
356
+ }
357
+ const lines = removeTabs(specificationText);
358
+ const searchLocation = { line: 0, column: 0 };
359
+ while (findToken(lines, searchLocation, "PlusCal")) {
360
+ const line = gotoNextNonSpace(lines, searchLocation);
361
+ const rest = line.slice(searchLocation.column);
362
+ const idEnd = Array.from(rest).findIndex((char) => !isIdChar(char));
363
+ if (rest.startsWith("options") && (idEnd === -1 ? rest.length : idEnd) === 7) {
364
+ session.params.optionsInFile = true;
365
+ processOptions(session, lines, searchLocation);
366
+ break;
367
+ }
368
+ }
369
+ const begin = { line: 0, column: -1, isFound: false, isFair: false };
370
+ for (; begin.line < lines.length; begin.line++) {
371
+ const line = lines[begin.line];
372
+ // TLAConstants.MODULE_CLOSING_REGEX, which the trailing space removeTabs adds keeps from
373
+ // matching.
374
+ if (/^=+$/.test(line)) break;
375
+ const algorithmColumn = line.indexOf("--algorithm");
376
+ const fairColumn = line.indexOf("--fair");
377
+ if (algorithmColumn !== -1) {
378
+ begin.column = algorithmColumn + "--algorithm".length;
379
+ begin.isFound = true;
380
+ break;
381
+ }
382
+ if (fairColumn !== -1) {
383
+ begin.column = fairColumn + "--fair".length;
384
+ begin.isFound = true;
385
+ begin.isFair = true;
386
+ break;
387
+ }
388
+ }
389
+ const results = new Set<PcalValidationResult>();
390
+ const translationLine = findTokenPair(lines, 0, "BEGIN", "TRANSLATION");
391
+ if (translationLine === -1) results.add("NO_TRANSLATION_EXISTS");
392
+ const endTranslationLine = findTokenPair(lines, translationLine + 1, "END", "TRANSLATION");
393
+ if (endTranslationLine === -1) results.add("NO_TRANSLATION_EXISTS");
394
+ if (translationLine === -1 && endTranslationLine === -1) return results;
395
+ if (!begin.isFound) {
396
+ results.add("NO_PLUSCAL_EXISTS");
397
+ return results;
398
+ }
399
+ const uncommentError = uncomment(lines, begin.line, begin.column);
400
+ if (uncommentError !== undefined) {
401
+ reportPcalError(session, uncommentError);
402
+ return new Set(["ERROR_ENCOUNTERED"]);
403
+ }
404
+ const parsed: { ast: PcalAlgorithm | undefined } = { ast: undefined };
405
+ // HACK: Validator reports the exceptions of ParseAlgorithm.getAlgorithm and PCalTLAGenerator
406
+ // and goes on to compare the checksums.
407
+ try {
408
+ const reader = createPcalCharReader(
409
+ lines,
410
+ begin.line,
411
+ begin.column,
412
+ specificationText.length,
413
+ 0,
414
+ );
415
+ const result = parsePcalAlgorithm(session, reader, begin.isFair);
416
+ parsed.ast = result.ast;
417
+ translatePcalAlgorithm(result.ast, result.omitPC, result.hasDefaultInitialization, session.log);
418
+ } catch (error) {
419
+ if (!(error instanceof PcalError)) throw error;
420
+ reportPcalError(session, error);
421
+ }
422
+ if (translationLine === -1) throwIndexOutOfBounds(-1, lines.length);
423
+ const match = CHECKSUM_PATTERN.exec(lines[translationLine]);
424
+ if (match === null) {
425
+ results.add("NO_PCAL_CHECKSUMS_EXIST");
426
+ return results;
427
+ }
428
+ const pcalChecksum = match.groups?.pcal;
429
+ // The Java checksums the string "fair" for a --fair algorithm, unlike TLC 1.7.4's, and a failed
430
+ // parse leaves an AST whose text, Object.toString's class name and hash code, matches no checksum.
431
+ const algorithmText =
432
+ begin.isFair && version !== "1.7.4"
433
+ ? "fair"
434
+ : parsed.ast === undefined
435
+ ? undefined
436
+ : formatPcalNode(parsed.ast, session.params.inputVersionNumber, version);
437
+ if (
438
+ pcalChecksum !== undefined &&
439
+ (algorithmText === undefined || pcalChecksum !== getChecksum(algorithmText))
440
+ ) {
441
+ results.add("PCAL_DIVERGENCE_EXISTS");
442
+ }
443
+ const tlaChecksum = match.groups?.tla;
444
+ if (tlaChecksum !== undefined) {
445
+ if (endTranslationLine === -1) {
446
+ throw new PcalRuntimeError(
447
+ `java.lang.IllegalArgumentException: fromIndex(${translationLine + 1}) > toIndex(-1)`,
448
+ );
449
+ }
450
+ const translation = specificationText.slice(translationLine + 1, endTranslationLine).join("");
451
+ if (tlaChecksum !== getChecksum(translation)) results.add("TLA_DIVERGENCE_EXISTS");
452
+ }
453
+ return results.size === 0 ? new Set(["NO_DIVERGENCE"]) : results;
454
+ };
@@ -1,8 +1,8 @@
1
- import { defineStateOperator, getValue } from "./builtins";
2
- import { TlaEvaluationError, TlaModuleError } from "./errors";
1
+ import { createJavaOverrideError, defineStateOperator, getValue } from "./builtins";
2
+ import { TlaModuleError } from "./errors";
3
3
  import type { Builtin, BuiltinArgument } from "./evaluate";
4
4
  import type { CheckerRuntime } from "./runtime";
5
- import { getRandomSubset, type JavaRandom } from "./tlc-random";
5
+ import { getEnumeratedFactors, getRandomSubset, type JavaRandom } from "./tlc-random";
6
6
  import {
7
7
  createSet,
8
8
  createTuple,
@@ -14,6 +14,12 @@ import {
14
14
  type Value,
15
15
  } from "./values";
16
16
 
17
+ const RANDOM_SUBSET_SIGNATURE =
18
+ "public static tlc2.value.impl.Value tlc2.module.Randomization.RandomSubset(tlc2.value.impl.Value,tlc2.value.impl.Value)";
19
+
20
+ // TLCGlobals.setBound: TLC 1.7.4's ValueVec holds at most this many elements of a set.
21
+ const SET_BOUND_174 = 1000000;
22
+
17
23
  const createArgumentError = (position: string, name: string, expected: string, value: string) =>
18
24
  new TlaModuleError(
19
25
  `The ${position} argument of ${name} should be a ${expected}, but instead it is:\n${value}`,
@@ -77,15 +83,26 @@ export const createRandomizationOperators = (runtime: CheckerRuntime): Builtin[]
77
83
  throw createArgumentError("first", "RandomSubset", "nonnegative integer", formatValue(count));
78
84
  }
79
85
  if (count < 0) {
80
- throw new TlaEvaluationError(
81
- `Attempted to apply the operator overridden by the Java method\npublic static tlc2.value.impl.Value tlc2.module.Randomization.RandomSubset(tlc2.value.impl.Value,tlc2.value.impl.Value),\nbut it produced the following error:\n${count}`,
82
- );
86
+ throw createJavaOverrideError(RANDOM_SUBSET_SIGNATURE, String(count));
83
87
  }
84
88
  const set = getValue(args, 1, "RandomSubset");
85
89
  if (!isSetValue(set) || (!isEmptySet(set) && !isEnumerable(set))) {
86
90
  throw createArgumentError("second", "RandomSubset", "a finite set", formatValue(set));
87
91
  }
88
- return createSet(getRandomSubset(count, set, runtime.getRandom()));
92
+ const factors = getEnumeratedFactors(set, runtime.version);
93
+ if (factors) {
94
+ const size = factors.reduce<number>(
95
+ (total, factor) => total * toFiniteSet(factor).elements.length,
96
+ 1,
97
+ );
98
+ if (size > SET_BOUND_174) {
99
+ throw createJavaOverrideError(
100
+ RANDOM_SUBSET_SIGNATURE,
101
+ `Attempted to construct a set with too many elements (>${SET_BOUND_174}).`,
102
+ );
103
+ }
104
+ }
105
+ return createSet(getRandomSubset(count, set, runtime.getRandom(), runtime.version));
89
106
  }),
90
107
  defineStateOperator("RandomSetOfSubsets", 3, (args) => getRandomSetOfSubsets(args, runtime)),
91
108
  defineStateOperator("TestRandomSetOfSubsets", 3, (args) =>