tla-ts 0.0.8 → 0.0.9-dev.0dd11f695

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 (119) hide show
  1. package/README.md +30 -0
  2. package/dist/compile.cjs +23 -0
  3. package/dist/compile.js +23 -0
  4. package/dist/deciders.cjs +15 -15
  5. package/dist/deciders.js +40 -40
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +98 -19
  8. package/dist/index.d.ts +98 -19
  9. package/dist/index.js +1 -1
  10. package/dist/parallel-worker.cjs +1 -1
  11. package/dist/parallel-worker.js +1 -1
  12. package/dist/prove-worker.cjs +1 -1
  13. package/dist/prove-worker.js +1 -1
  14. package/dist/prove.cjs +116 -36
  15. package/dist/prove.js +116 -36
  16. package/dist/run.cjs +143 -31
  17. package/dist/run.js +143 -31
  18. package/dist/tlapm.cjs +2 -2
  19. package/dist/tlapm.js +1 -1
  20. package/dist/transfer.cjs +128 -106
  21. package/dist/transfer.js +128 -106
  22. package/dist/worker.cjs +7 -7
  23. package/dist/worker.js +7 -7
  24. package/package.json +3 -1
  25. package/src/ast.ts +7 -21
  26. package/src/bags.ts +99 -99
  27. package/src/builtins.ts +44 -75
  28. package/src/bundled-modules.ts +1 -8
  29. package/src/check.ts +605 -311
  30. package/src/cli/options.ts +12 -3
  31. package/src/cli/run.ts +2 -2
  32. package/src/cli/runtime-invariants.ts +135 -0
  33. package/src/cli/shared.ts +20 -9
  34. package/src/cli/tlc-arguments.ts +646 -0
  35. package/src/cli/tlc-usage.ts +362 -0
  36. package/src/cli/tlc.ts +571 -185
  37. package/src/cli/typescript.ts +26 -0
  38. package/src/cli/xml-exporter.ts +4 -10
  39. package/src/codegen.ts +190 -51
  40. package/src/config.ts +101 -68
  41. package/src/coverage.ts +855 -0
  42. package/src/dependencies.ts +340 -24
  43. package/src/dfid.ts +636 -0
  44. package/src/environment.ts +289 -109
  45. package/src/errors.ts +142 -45
  46. package/src/evaluate.ts +734 -980
  47. package/src/exit-codes.ts +37 -1
  48. package/src/index.ts +3 -0
  49. package/src/instances.ts +85 -9
  50. package/src/java-overrides.ts +2 -12
  51. package/src/json-reader.ts +456 -0
  52. package/src/json.ts +262 -139
  53. package/src/levels.ts +2 -3
  54. package/src/lexer.ts +150 -70
  55. package/src/liveness-checker.ts +10 -18
  56. package/src/liveness.ts +122 -64
  57. package/src/parallel-worker.ts +14 -10
  58. package/src/parallel.ts +41 -17
  59. package/src/parser.ts +436 -90
  60. package/src/pcal/ast.ts +7 -28
  61. package/src/pcal/parse.ts +11 -39
  62. package/src/pcal/tokenize.ts +4 -20
  63. package/src/pcal/translate.ts +10 -42
  64. package/src/pcal/validate.ts +3 -21
  65. package/src/pretty-print.ts +1 -2
  66. package/src/prover/smt/solver/solver.ts +31 -27
  67. package/src/randomization.ts +84 -35
  68. package/src/resolve.ts +18 -60
  69. package/src/runtime.ts +11 -4
  70. package/src/sany/builtins.ts +3 -4
  71. package/src/sany/generator.ts +128 -176
  72. package/src/sany/levels.ts +6 -30
  73. package/src/sany/lexer.ts +7 -23
  74. package/src/sany/linter.ts +31 -29
  75. package/src/sany/modules.ts +1 -5
  76. package/src/sany/nodes.ts +4 -28
  77. package/src/sany/parse-error.ts +44 -100
  78. package/src/sany/report.ts +25 -40
  79. package/src/sany/selectors.ts +8 -22
  80. package/src/sany/source.ts +8 -15
  81. package/src/sany/xml.ts +11 -42
  82. package/src/search.ts +550 -150
  83. package/src/simulate.ts +694 -0
  84. package/src/spec-description.ts +167 -49
  85. package/src/standard-definitions.ts +2 -3
  86. package/src/standard-modules.ts +264 -68
  87. package/src/state-graph.ts +51 -18
  88. package/src/subexpressions.ts +31 -5
  89. package/src/successors.ts +269 -85
  90. package/src/symmetry.ts +59 -147
  91. package/src/tableau.ts +1 -2
  92. package/src/tlc/fingerprint.ts +226 -151
  93. package/src/tlc/jar-data.ts +113 -6
  94. package/src/tlc/messages.ts +122 -37
  95. package/src/tlc/order.ts +56 -82
  96. package/src/tlc/random.ts +16 -16
  97. package/src/tlc/replay.ts +564 -212
  98. package/src/tlc/summary.ts +2 -4
  99. package/src/tlc/tlc-operators.ts +81 -36
  100. package/src/tlc/tlcext-operators.ts +138 -117
  101. package/src/tlc/trace-spec.ts +273 -0
  102. package/src/tlc/value-stream.ts +143 -0
  103. package/src/tlc/version.ts +2 -4
  104. package/src/typescript/actions.ts +494 -0
  105. package/src/typescript/collections.ts +615 -0
  106. package/src/typescript/compile.ts +70 -0
  107. package/src/typescript/context.ts +106 -0
  108. package/src/typescript/emit.ts +122 -0
  109. package/src/typescript/expressions.ts +508 -0
  110. package/src/typescript/formula.ts +160 -0
  111. package/src/typescript/functions.ts +295 -0
  112. package/src/typescript/model.ts +164 -0
  113. package/src/typescript/names.ts +116 -0
  114. package/src/typescript/program.ts +51 -0
  115. package/src/typescript/properties.ts +148 -0
  116. package/src/typescript/scope.ts +117 -0
  117. package/src/typescript/steps.ts +175 -0
  118. package/src/typescript/types.ts +178 -0
  119. package/src/values.ts +910 -318
package/src/tlc/order.ts CHANGED
@@ -1,11 +1,11 @@
1
- // TLC orders strings and model values by when it first interned their text, and compares a
2
- // state's variables in the order of SANY's symbol table. This reproduces both orders.
1
+ // Reproduces TLC's string order, by first interning, and its variable order, from SANY's context.
3
2
  import type { Module, SourceLocation } from "../ast";
4
3
  import type { ConfigValue, ModelConfig } from "../config";
5
4
  import { createMissingModuleError } from "../errors";
6
5
  import { tokenize, type Token } from "../lexer";
7
6
  import { extractModule, parseModule, parseModuleTokens } from "../parser";
8
7
  import { isBefore } from "../resolve";
8
+ import { SANY_STANDARD_MODULES } from "../sany/modules";
9
9
  import {
10
10
  SANY_BUILTINS,
11
11
  SANY_NODE_NAMES,
@@ -13,7 +13,6 @@ import {
13
13
  TLC_MODULE_SOURCES,
14
14
  TLC_RUNTIME_STRINGS,
15
15
  TLC_STARTUP_STRINGS,
16
- USER_STANDARD_MODULES,
17
16
  } from "./jar-data";
18
17
 
19
18
  type SymbolKind = "builtin" | "constant" | "variable" | "definition" | "theorem" | "module";
@@ -38,7 +37,6 @@ interface ParsedModule {
38
37
  tokens: Token[];
39
38
  start: number;
40
39
  end: number;
41
- isTlcSource: boolean;
42
40
  getModule: () => Module;
43
41
  }
44
42
 
@@ -67,9 +65,8 @@ const getJavaHash = (text: string) => {
67
65
  return hash;
68
66
  };
69
67
 
70
- // java.util.Hashtable as SANY's Context uses it: default capacity 11, load factor 0.75, new
71
- // entries at the head of their bucket, and enumeration from the last bucket to the first. Each
72
- // bucket lists its entries from tail to head, so a new entry goes at the end.
68
+ // java.util.Hashtable as SANY's Context uses it: capacity 11, load factor 0.75, new entries at
69
+ // the head of their bucket, and enumeration from the last bucket, each from tail to head.
73
70
  const createSymbolTable = (): SymbolTable => {
74
71
  let buckets: SymbolEntry[][] = Array.from({ length: 11 }, () => []);
75
72
  let threshold = 8;
@@ -126,7 +123,8 @@ const getDeclaredName = (tokens: Token[], start: number) => {
126
123
  return { name: first.text === "-" ? "-." : getCanonicalName(first.text), end: start + 2 };
127
124
  }
128
125
  if (second?.text !== "(") return { name: first.text, end: start + 1 };
129
- const close = tokens.findIndex((token, index) => index > start && token.text === ")");
126
+ let close = start + 2;
127
+ while (close < tokens.length && tokens[close].text !== ")") close++;
130
128
  return { name: first.text, end: close + 1 };
131
129
  };
132
130
 
@@ -156,8 +154,7 @@ type ModuleSearch = (
156
154
  visited: Set<string>,
157
155
  ) => [ModuleReferences, string] | undefined;
158
156
 
159
- // The modules a module extends and instantiates, with its inner modules, as SANY's SpecObj
160
- // walks them to decide which module to parse next.
157
+ // In the order SANY's SpecObj walks them to decide which module to parse next.
161
158
  const getModuleReferences = (
162
159
  tokens: Token[],
163
160
  unit: string | undefined,
@@ -212,9 +209,8 @@ const STRING_ESCAPES: Record<string, string> = {
212
209
  "\f": "\\f",
213
210
  };
214
211
 
215
- // The texts SANY interns while parsing, in order. SANY reads a proof step label such as <1>2 and
216
- // a module header such as ---- MODULE as one token. It interns a string literal as written, quotes
217
- // included, and interns the literal's contents only during semantic analysis.
212
+ // SANY reads <1>2 and ---- MODULE as one token each, and interns a string literal with its
213
+ // quotes, its contents only during semantic analysis.
218
214
  const getParsedTexts = (tokens: Token[]) => {
219
215
  const texts: string[] = [];
220
216
  for (let index = 0; index < tokens.length; index++) {
@@ -268,6 +264,7 @@ interface ModuleText {
268
264
  getModule: () => Module;
269
265
  }
270
266
 
267
+ // Read and parsed once, for every order and for the environment that evaluates it.
271
268
  const readModuleText = (text: string | undefined): ModuleText => {
272
269
  const tokens = text === undefined ? [] : tokenize(text);
273
270
  const parsed = { module: undefined as Module | undefined };
@@ -279,79 +276,54 @@ const readModuleText = (text: string | undefined): ModuleText => {
279
276
  };
280
277
  };
281
278
 
282
- // TLC's own module sources never change, so every check shares their tokens and parse.
283
- const tlcModuleTexts = new Map<string, ModuleText>();
284
-
285
- const getTlcModuleText = (name: string, text: string): ModuleText => {
286
- const known = tlcModuleTexts.get(name);
287
- if (known) return known;
288
- const read = readModuleText(text);
289
- tlcModuleTexts.set(name, read);
290
- return read;
291
- };
292
-
293
- // The modules TLC reads for a spec: the root module, TLC's standard modules, the files the loader
294
- // returns, the modules that follow the root module, and the modules nested in any of these. A
295
- // module without a source has no tokens.
279
+ // A module without a source has no tokens.
296
280
  const createModuleSet = (source: string, loadModule: ModuleLoader) => {
297
281
  const files = new Map<string, ParsedModule>();
298
282
  const nestedModules = new Map<string, ParsedModule>();
283
+ const texts = new Map<string, ModuleText>();
284
+ const readText = (text: string | undefined) => {
285
+ const known = text === undefined ? undefined : texts.get(text);
286
+ if (known) return known;
287
+ const read = readModuleText(text);
288
+ if (text !== undefined) texts.set(text, read);
289
+ return read;
290
+ };
299
291
  const getFile = (name: string | undefined) => {
300
292
  const cached = files.get(name ?? "");
301
293
  if (cached) return cached;
302
294
  const text =
303
295
  name === undefined
304
296
  ? source
305
- : ((USER_STANDARD_MODULES.has(name) ? loadModule?.(name) : undefined) ??
297
+ : (loadModule?.(name) ??
306
298
  TLC_MODULE_SOURCES.get(name) ??
307
- loadModule?.(name) ??
299
+ SANY_STANDARD_MODULES.get(name) ??
308
300
  extractModule(source, name));
309
- const isTlcSource =
310
- name !== undefined && text !== undefined && text === TLC_MODULE_SOURCES.get(name);
311
- const { tokens, ranges, getModule } = isTlcSource
312
- ? getTlcModuleText(name, text)
313
- : readModuleText(text);
301
+ const { tokens, ranges, getModule } = readText(text);
314
302
  const range = ranges.get(getModuleName(tokens) ?? "") ?? { start: 0, end: 0 };
315
- const file = { tokens, ...range, isTlcSource, getModule };
303
+ const file = { tokens, ...range, getModule };
316
304
  files.set(name ?? "", file);
317
305
  ranges.forEach((nestedRange, nestedName) => {
318
306
  if (nestedRange.start === range.start || nestedModules.has(nestedName)) return;
319
307
  nestedModules.set(nestedName, {
320
308
  tokens,
321
309
  ...nestedRange,
322
- isTlcSource: false,
323
310
  getModule: () => findModule(file.getModule().modules, nestedName) ?? file.getModule(),
324
311
  });
325
312
  });
326
313
  return file;
327
314
  };
328
315
  getFile(undefined);
329
- return (name: string | undefined): ParsedModule =>
330
- (name === undefined ? undefined : nestedModules.get(name)) ?? getFile(name);
316
+ return {
317
+ getParsed: (name: string | undefined): ParsedModule =>
318
+ (name === undefined ? undefined : nestedModules.get(name)) ?? getFile(name),
319
+ parseText: (text: string) => readText(text).getModule(),
320
+ };
331
321
  };
332
322
 
333
- // SANY's Context of each module, which the root module has under undefined.
334
- type ModuleSet = ReturnType<typeof createModuleSet>;
335
-
336
- // The Context of one of TLC's own modules is the same in every check when every module it extends
337
- // or instantiates is also TLC's own.
338
- const tlcContexts = new Map<string, SymbolTable>();
323
+ // The root module's context is under undefined.
324
+ type ModuleSet = ReturnType<typeof createModuleSet>["getParsed"];
339
325
 
340
326
  const createContexts = (getParsed: ModuleSet) => {
341
- const sharedModules = new Map<string, boolean>();
342
- const isShared = (name: string): boolean => {
343
- const known = sharedModules.get(name);
344
- if (known !== undefined) return known;
345
- sharedModules.set(name, false);
346
- const unit = getParsed(name);
347
- const module = unit.isTlcSource ? unit.getModule() : undefined;
348
- const shared =
349
- module !== undefined &&
350
- module.extends.every((extended) => isShared(extended)) &&
351
- module.instances.every((instance) => isShared(instance.module));
352
- sharedModules.set(name, shared);
353
- return shared;
354
- };
355
327
  const getUnits = (unit: ParsedModule) => {
356
328
  const tokens = unit.tokens;
357
329
  const module = unit.getModule();
@@ -367,6 +339,13 @@ const createContexts = (getParsed: ModuleSet) => {
367
339
  const recursiveNames = new Set(
368
340
  module.definitions.filter((definition) => definition.isRecursive).map((item) => item.name),
369
341
  );
342
+ const declarationKeywords = new Set(
343
+ module.units.flatMap((moduleUnit) =>
344
+ moduleUnit.kind === "Constants" || moduleUnit.kind === "Variables"
345
+ ? [`${moduleUnit.location.line}:${moduleUnit.location.column}`]
346
+ : [],
347
+ ),
348
+ );
370
349
  const depth = { value: 0 };
371
350
  tokens.slice(unit.start, unit.end).forEach((_, offset) => {
372
351
  const index = unit.start + offset;
@@ -384,8 +363,13 @@ const createContexts = (getParsed: ModuleSet) => {
384
363
  }
385
364
  if (token.kind === "ModuleEnd") depth.value--;
386
365
  if (depth.value !== 1 || token.kind !== "Keyword") return;
387
- if (token.text === "CONSTANT" || token.text === "CONSTANTS") declare(index, "constant");
388
- if (token.text === "VARIABLE" || token.text === "VARIABLES") declare(index, "variable");
366
+ const isDeclaration = declarationKeywords.has(`${token.line}:${token.column}`);
367
+ if (isDeclaration && (token.text === "CONSTANT" || token.text === "CONSTANTS")) {
368
+ declare(index, "constant");
369
+ }
370
+ if (isDeclaration && (token.text === "VARIABLE" || token.text === "VARIABLES")) {
371
+ declare(index, "variable");
372
+ }
389
373
  if (token.text === "RECURSIVE") {
390
374
  const names = getDeclarations(tokens, index + 1);
391
375
  if (names.every((name) => recursiveNames.has(name))) declare(index, "definition");
@@ -452,8 +436,7 @@ const createContexts = (getParsed: ModuleSet) => {
452
436
 
453
437
  const contexts = new Map<string, SymbolTable>();
454
438
  const getContext = (name: string | undefined): SymbolTable => {
455
- const isTlcContext = name !== undefined && isShared(name);
456
- const cached = contexts.get(name ?? "") ?? (isTlcContext ? tlcContexts.get(name) : undefined);
439
+ const cached = contexts.get(name ?? "");
457
440
  if (cached) return cached;
458
441
  const table = createSymbolTable();
459
442
  contexts.set(name ?? "", table);
@@ -468,7 +451,6 @@ const createContexts = (getParsed: ModuleSet) => {
468
451
  );
469
452
  table.ownStart = table.inserted.length;
470
453
  getUnits(unit).forEach((item) => item.apply(table));
471
- if (isTlcContext) tlcContexts.set(name, table);
472
454
  return table;
473
455
  };
474
456
  return {
@@ -480,9 +462,8 @@ const createContexts = (getParsed: ModuleSet) => {
480
462
  };
481
463
  };
482
464
 
483
- // Every string TLC interns before model checking starts, in order: values in the config, TLC's
484
- // startup strings, each module's tokens in the order SpecObj.loadSpec parses the modules, string
485
- // literals in semantic analysis order, and the names TLC interns for TLCGet.
465
+ // In order: config values, TLC's startup strings, each module's tokens as SpecObj.loadSpec
466
+ // parses them, string literals in semantic analysis order, and TLCGet's names.
486
467
  const getStringOrder = (getParsed: ModuleSet, config: ModelConfig): string[] => {
487
468
  const order = new Set<string>();
488
469
  const intern = (text: string) => {
@@ -586,29 +567,22 @@ const getStringOrder = (getParsed: ModuleSet, config: ModelConfig): string[] =>
586
567
  };
587
568
 
588
569
  export interface TlcOrder {
589
- // The root module, parsed once for the order and the environment.
590
- getRootModule: () => Module;
591
- // Every string TLC interns before model checking starts.
592
570
  getStringOrder: (config: ModelConfig) => string[];
593
- // The variables or constants of the root module in the reverse of its context enumeration, as
594
- // ModuleNode.getVariableDecls and getConstantDecls return them. TLC compares variables in this
595
- // order, and checks that the configuration assigns each constant in it.
571
+ // The reverse of the root module's context enumeration, in which TLC compares variables and
572
+ // checks that the configuration assigns each constant.
596
573
  getDeclarationOrder: (kind: "variable" | "constant") => string[];
597
- // The names of the definitions each module adds to its context, in the order of
598
- // ModuleNode.getOpDefs, in which TLC computes the constant definitions as it starts. An INSTANCE
599
- // adds the definitions of the module it instantiates in the order that module's Hashtable
600
- // enumerates them.
574
+ // In the order TLC computes constant definitions at startup. An INSTANCE adds those of the
575
+ // module it instantiates in the order that module's Hashtable enumerates them.
601
576
  createDefinitionOrder: () => (name: string | undefined) => string[];
577
+ parseModule: (source: string) => Module;
602
578
  }
603
579
 
604
- // One check reads the spec's modules once, and every order shares their tokens, parses and
605
- // contexts.
606
580
  export const createTlcOrder = (source: string, loadModule: ModuleLoader): TlcOrder => {
607
- const getParsed = createModuleSet(source, loadModule);
581
+ const modules = createModuleSet(source, loadModule);
582
+ const getParsed = modules.getParsed;
608
583
  let contexts: ReturnType<typeof createContexts> | undefined;
609
584
  const getContexts = () => (contexts ??= createContexts(getParsed));
610
585
  return {
611
- getRootModule: () => getParsed(undefined).getModule(),
612
586
  getStringOrder: (config) => getStringOrder(getParsed, config),
613
587
  getDeclarationOrder: (kind) =>
614
588
  getContexts()
@@ -617,10 +591,10 @@ export const createTlcOrder = (source: string, loadModule: ModuleLoader): TlcOrd
617
591
  .filter((entry) => entry.kind === kind)
618
592
  .map((entry) => entry.name)
619
593
  .reverse(),
594
+ parseModule: modules.parseText,
620
595
  createDefinitionOrder: () => {
621
596
  const { getContext, getOwnEntries } = getContexts();
622
- // The root module's context reads every file of the spec, and so finds the modules nested
623
- // in the files it extends or instantiates.
597
+ // The root module's context finds the modules nested in the files it extends or instantiates.
624
598
  getContext(undefined);
625
599
  return (name) =>
626
600
  getOwnEntries(name)
package/src/tlc/random.ts CHANGED
@@ -1,9 +1,11 @@
1
+ import { toEnumeratedSet } from "../builtins";
1
2
  import { TlaEvaluationError } from "../errors";
2
3
  import type { TlcVersion } from "./version";
3
4
  import {
4
5
  createRecord,
5
6
  createSortedFunction,
6
7
  createTuple,
8
+ formatValue,
7
9
  getFunctionDomain,
8
10
  isEmptySet,
9
11
  toFiniteSet,
@@ -21,7 +23,6 @@ const MULTIPLIER = 0x5deece66dn;
21
23
  const SEED_MASK = (1n << 48n) - 1n;
22
24
  const MAXIMUM_INT = 2147483647;
23
25
 
24
- // java.util.Random, which TLC's RandomEnumerableValues extends.
25
26
  export const createJavaRandom = (seed: bigint): JavaRandom => {
26
27
  const state = { value: (BigInt.asUintN(64, seed) ^ MULTIPLIER) & SEED_MASK };
27
28
  const next = (bits: number) => {
@@ -63,7 +64,7 @@ const getPrimes = () => {
63
64
  return PRIMES;
64
65
  };
65
66
 
66
- const nextPrime = (random: JavaRandom) => {
67
+ export const nextPrime = (random: JavaRandom) => {
67
68
  const primes = getPrimes();
68
69
  const choice = { index: primes.length };
69
70
  while (choice.index === primes.length) {
@@ -101,8 +102,6 @@ const getModulusAndMultiplier = (size: number) => {
101
102
  }
102
103
  };
103
104
 
104
- // EnumerableValue.SubsetEnumerator: count indices below size from a full-period linear
105
- // congruential generator that starts at random.nextInt(size).
106
105
  const getSubsetIndicesMaster = (count: number, size: number, random: JavaRandom) => {
107
106
  if (size <= 0) return [];
108
107
  const generator = getModulusAndMultiplier(size);
@@ -130,8 +129,7 @@ const getSubsetIndices174 = (count: number, size: number, random: JavaRandom) =>
130
129
 
131
130
  const LARGE_STRIDE = (1n << 63n) - 1n - 24n;
132
131
 
133
- // SetOfFcnsOrRcdsValue.BigIntegerSubsetEnumerator, for products with more than 2^31 - 1
134
- // elements.
132
+ // For products with more than 2^31 - 1 elements.
135
133
  const getLargeSubsetIndices = (count: number, size: bigint, random: JavaRandom) => {
136
134
  const signed = random.nextLong();
137
135
  const offset = BigInt.asIntN(64, signed < 0n ? -signed : signed);
@@ -187,7 +185,6 @@ export const getEnumeratedFactors = (set: Value, version: TlcVersion) =>
187
185
  ? set.factors
188
186
  : undefined;
189
187
 
190
- // Enumerable#getRandomSubset, which Randomization's RandomSubset calls.
191
188
  export const getRandomSubset = (
192
189
  count: number,
193
190
  set: Value,
@@ -214,18 +211,12 @@ export const getRandomSubset = (
214
211
  return getSubsetIndices(count, elements.length, random).map((index) => elements[Number(index)]);
215
212
  };
216
213
 
217
- const pickElement = (elements: Value[], random: JavaRandom) => {
218
- const element = elements[Math.floor(random.nextDouble() * elements.length)];
219
- if (element === undefined) throw new TlaEvaluationError("RandomElement of the empty set");
220
- return element;
221
- };
222
-
223
214
  // TLC!RandomElement chooses each component of a set of functions, records, or tuples
224
215
  // separately, and otherwise indexes the enumerated set with nextDouble.
225
216
  export const getRandomElement = (set: Value, random: JavaRandom): Value => {
226
217
  if (typeof set === "object" && set.kind === "FunctionSet") {
227
218
  // TLC builds the chosen function without the interval its domain came from.
228
- const domain = [...getFunctionDomain(set.domain)];
219
+ const domain = [...toEnumeratedSet(set.domain, "RandomElement", set).elements];
229
220
  return createSortedFunction(
230
221
  domain,
231
222
  domain.map(() => getRandomElement(set.range, random)),
@@ -245,8 +236,17 @@ export const getRandomElement = (set: Value, random: JavaRandom): Value => {
245
236
  if (typeof set === "object" && set.kind === "Interval") {
246
237
  const size = Math.max(0, set.high - set.low + 1);
247
238
  const offset = Math.floor(random.nextDouble() * size);
248
- if (offset >= size) throw new TlaEvaluationError("RandomElement of the empty set");
239
+ if (offset >= size) {
240
+ throw new TlaEvaluationError(
241
+ `Attempted to retrieve out-of-bounds element from the interval value ${formatValue(set)}.`,
242
+ );
243
+ }
249
244
  return set.low + offset;
250
245
  }
251
- return pickElement(toFiniteSet(set).elements, random);
246
+ const elements = toEnumeratedSet(set, "RandomElement").elements;
247
+ const index = Math.floor(random.nextDouble() * elements.length);
248
+ if (index >= elements.length) {
249
+ throw new TlaEvaluationError(`Index ${index} out of bounds for length ${elements.length}`);
250
+ }
251
+ return elements[index];
252
252
  };