tla-ts 0.0.7-dev.bd12468 → 0.0.8-dev.8067c48

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.
package/src/tlc/order.ts CHANGED
@@ -4,7 +4,7 @@ import type { Module, SourceLocation } from "../ast";
4
4
  import type { ConfigValue, ModelConfig } from "../config";
5
5
  import { createMissingModuleError } from "../errors";
6
6
  import { tokenize, type Token } from "../lexer";
7
- import { extractModule, parseModule } from "../parser";
7
+ import { extractModule, parseModule, parseModuleTokens } from "../parser";
8
8
  import { isBefore } from "../resolve";
9
9
  import {
10
10
  SANY_BUILTINS,
@@ -21,6 +21,7 @@ type SymbolKind = "builtin" | "constant" | "variable" | "definition" | "theorem"
21
21
  interface SymbolEntry {
22
22
  key: string;
23
23
  name: string;
24
+ hash: number;
24
25
  kind: SymbolKind;
25
26
  isLocal: boolean;
26
27
  }
@@ -28,6 +29,8 @@ interface SymbolEntry {
28
29
  interface SymbolTable {
29
30
  put: (entry: SymbolEntry) => void;
30
31
  inserted: SymbolEntry[];
32
+ // Where the entries the module adds itself start, after those of the modules it extends.
33
+ ownStart: number;
31
34
  enumerate: () => SymbolEntry[];
32
35
  }
33
36
 
@@ -64,38 +67,48 @@ const getJavaHash = (text: string) => {
64
67
  };
65
68
 
66
69
  // java.util.Hashtable as SANY's Context uses it: default capacity 11, load factor 0.75, new
67
- // entries at the head of their bucket, and enumeration from the last bucket to the first.
70
+ // entries at the head of their bucket, and enumeration from the last bucket to the first. Each
71
+ // bucket lists its entries from tail to head, so a new entry goes at the end.
68
72
  const createSymbolTable = (): SymbolTable => {
69
- const table = { buckets: Array.from({ length: 11 }, (): SymbolEntry[] => []), threshold: 8 };
73
+ let buckets: SymbolEntry[][] = Array.from({ length: 11 }, () => []);
74
+ let threshold = 8;
70
75
  const keys = new Set<string>();
71
76
  const inserted: SymbolEntry[] = [];
72
- const getBucket = (entry: SymbolEntry, capacity: number) =>
73
- (getJavaHash(entry.name) & 0x7fffffff) % capacity;
74
- const rehash = () => {
75
- const capacity = table.buckets.length * 2 + 1;
76
- const buckets = Array.from({ length: capacity }, (): SymbolEntry[] => []);
77
- for (let index = table.buckets.length - 1; index >= 0; index--) {
78
- for (const entry of table.buckets[index]) buckets[getBucket(entry, capacity)].unshift(entry);
77
+ const forEachEntry = (visit: (entry: SymbolEntry) => void) => {
78
+ for (let index = buckets.length - 1; index >= 0; index--) {
79
+ const bucket = buckets[index];
80
+ for (let position = bucket.length - 1; position >= 0; position--) visit(bucket[position]);
79
81
  }
80
- table.buckets = buckets;
81
- table.threshold = Math.floor(capacity * 0.75);
82
+ };
83
+ const rehash = () => {
84
+ const capacity = buckets.length * 2 + 1;
85
+ const rehashed: SymbolEntry[][] = Array.from({ length: capacity }, () => []);
86
+ forEachEntry((entry) => rehashed[entry.hash % capacity].push(entry));
87
+ buckets = rehashed;
88
+ threshold = Math.floor(capacity * 0.75);
82
89
  };
83
90
  return {
84
91
  put: (entry) => {
85
92
  if (keys.has(entry.key)) return;
86
- if (inserted.length >= table.threshold) rehash();
87
- table.buckets[getBucket(entry, table.buckets.length)].unshift(entry);
93
+ if (inserted.length >= threshold) rehash();
94
+ buckets[entry.hash % buckets.length].push(entry);
88
95
  keys.add(entry.key);
89
96
  inserted.push(entry);
90
97
  },
91
98
  inserted,
92
- enumerate: () => table.buckets.toReversed().flat(),
99
+ ownStart: 0,
100
+ enumerate: () => {
101
+ const entries: SymbolEntry[] = [];
102
+ forEachEntry((entry) => entries.push(entry));
103
+ return entries;
104
+ },
93
105
  };
94
106
  };
95
107
 
96
- const createEntry = (name: string, kind: SymbolKind, isLocal: boolean) => ({
108
+ const createEntry = (name: string, kind: SymbolKind, isLocal: boolean): SymbolEntry => ({
97
109
  key: kind === "module" ? `module ${name}` : name,
98
110
  name,
111
+ hash: getJavaHash(name) & 0x7fffffff,
99
112
  kind,
100
113
  isLocal,
101
114
  });
@@ -112,7 +125,8 @@ const getDeclaredName = (tokens: Token[], start: number) => {
112
125
  return { name: first.text === "-" ? "-." : getCanonicalName(first.text), end: start + 2 };
113
126
  }
114
127
  if (second?.text !== "(") return { name: first.text, end: start + 1 };
115
- const close = tokens.findIndex((token, index) => index > start && token.text === ")");
128
+ let close = start + 2;
129
+ while (close < tokens.length && tokens[close].text !== ")") close++;
116
130
  return { name: first.text, end: close + 1 };
117
131
  };
118
132
 
@@ -248,12 +262,40 @@ const findModule = (modules: Module[], name: string): Module | undefined =>
248
262
  modules.find((module) => module.name === name) ??
249
263
  modules.map((module) => findModule(module.modules, name)).find(Boolean);
250
264
 
265
+ interface ModuleText {
266
+ tokens: Token[];
267
+ ranges: Map<string, { start: number; end: number }>;
268
+ getModule: () => Module;
269
+ }
270
+
271
+ // A module's source is read into tokens once, and parsed from them once, for every order and for
272
+ // the environment that evaluates it.
273
+ const readModuleText = (text: string | undefined): ModuleText => {
274
+ const tokens = text === undefined ? [] : tokenize(text);
275
+ const parsed = { module: undefined as Module | undefined };
276
+ return {
277
+ tokens,
278
+ ranges: getRanges(tokens),
279
+ getModule: () =>
280
+ (parsed.module ??= text === undefined ? parseModule("") : parseModuleTokens(text, tokens)),
281
+ };
282
+ };
283
+
251
284
  // The modules TLC reads for a spec: the root module, TLC's standard modules, the files the loader
252
285
  // returns, the modules that follow the root module, and the modules nested in any of these. A
253
286
  // module without a source has no tokens.
254
287
  const createModuleSet = (source: string, loadModule: ModuleLoader) => {
255
288
  const files = new Map<string, ParsedModule>();
256
289
  const nestedModules = new Map<string, ParsedModule>();
290
+ // The read of each module text, so that the environment parses a text the order read only once.
291
+ const texts = new Map<string, ModuleText>();
292
+ const readText = (text: string | undefined) => {
293
+ const known = text === undefined ? undefined : texts.get(text);
294
+ if (known) return known;
295
+ const read = readModuleText(text);
296
+ if (text !== undefined) texts.set(text, read);
297
+ return read;
298
+ };
257
299
  const getFile = (name: string | undefined) => {
258
300
  const cached = files.get(name ?? "");
259
301
  if (cached) return cached;
@@ -264,15 +306,9 @@ const createModuleSet = (source: string, loadModule: ModuleLoader) => {
264
306
  TLC_MODULE_SOURCES.get(name) ??
265
307
  loadModule?.(name) ??
266
308
  extractModule(source, name));
267
- const tokens = text === undefined ? [] : tokenize(text);
268
- const ranges = getRanges(tokens);
309
+ const { tokens, ranges, getModule } = readText(text);
269
310
  const range = ranges.get(getModuleName(tokens) ?? "") ?? { start: 0, end: 0 };
270
- const parsed = { module: undefined as Module | undefined };
271
- const file = {
272
- tokens,
273
- ...range,
274
- getModule: () => (parsed.module ??= parseModule(text ?? "")),
275
- };
311
+ const file = { tokens, ...range, getModule };
276
312
  files.set(name ?? "", file);
277
313
  ranges.forEach((nestedRange, nestedName) => {
278
314
  if (nestedRange.start === range.start || nestedModules.has(nestedName)) return;
@@ -285,13 +321,17 @@ const createModuleSet = (source: string, loadModule: ModuleLoader) => {
285
321
  return file;
286
322
  };
287
323
  getFile(undefined);
288
- return (name: string | undefined): ParsedModule =>
289
- (name === undefined ? undefined : nestedModules.get(name)) ?? getFile(name);
324
+ return {
325
+ getParsed: (name: string | undefined): ParsedModule =>
326
+ (name === undefined ? undefined : nestedModules.get(name)) ?? getFile(name),
327
+ parseText: (text: string) => readText(text).getModule(),
328
+ };
290
329
  };
291
330
 
292
331
  // SANY's Context of each module, which the root module has under undefined.
293
- const createContexts = (source: string, loadModule: ModuleLoader) => {
294
- const getParsed = createModuleSet(source, loadModule);
332
+ type ModuleSet = ReturnType<typeof createModuleSet>["getParsed"];
333
+
334
+ const createContexts = (getParsed: ModuleSet) => {
295
335
  const getUnits = (unit: ParsedModule) => {
296
336
  const tokens = unit.tokens;
297
337
  const module = unit.getModule();
@@ -391,8 +431,6 @@ const createContexts = (source: string, loadModule: ModuleLoader) => {
391
431
  };
392
432
 
393
433
  const contexts = new Map<string, SymbolTable>();
394
- // Where the entries a module adds itself start, after those of the modules it extends.
395
- const ownStarts = new Map<SymbolTable, number>();
396
434
  const getContext = (name: string | undefined): SymbolTable => {
397
435
  const cached = contexts.get(name ?? "");
398
436
  if (cached) return cached;
@@ -407,7 +445,7 @@ const createContexts = (source: string, loadModule: ModuleLoader) => {
407
445
  if (!entry.isLocal) table.put(entry);
408
446
  }),
409
447
  );
410
- ownStarts.set(table, table.inserted.length);
448
+ table.ownStart = table.inserted.length;
411
449
  getUnits(unit).forEach((item) => item.apply(table));
412
450
  return table;
413
451
  };
@@ -415,54 +453,15 @@ const createContexts = (source: string, loadModule: ModuleLoader) => {
415
453
  getContext,
416
454
  getOwnEntries: (name: string | undefined) => {
417
455
  const table = getContext(name);
418
- return table.inserted.slice(ownStarts.get(table));
456
+ return table.inserted.slice(table.ownStart);
419
457
  },
420
458
  };
421
459
  };
422
460
 
423
- // The variables or constants of the root module in the reverse of its context enumeration, as
424
- // ModuleNode.getVariableDecls and getConstantDecls return them. TLC compares variables in this
425
- // order, and checks that the configuration assigns each constant in it.
426
- export const getTlcDeclarationOrder = (
427
- source: string,
428
- loadModule: ModuleLoader,
429
- kind: "variable" | "constant",
430
- ): string[] =>
431
- createContexts(source, loadModule)
432
- .getContext(undefined)
433
- .enumerate()
434
- .filter((entry) => entry.kind === kind)
435
- .map((entry) => entry.name)
436
- .reverse();
437
-
438
- // The names of the definitions each module adds to its context, in the order of
439
- // ModuleNode.getOpDefs, in which TLC computes the constant definitions as it starts. An INSTANCE
440
- // adds the definitions of the module it instantiates in the order that module's Hashtable
441
- // enumerates them.
442
- export const createTlcDefinitionOrder = (source: string, loadModule: ModuleLoader) => {
443
- const contexts = createContexts(source, loadModule);
444
- // The root module's context reads every file of the spec, and so finds the modules nested in
445
- // the files it extends or instantiates.
446
- contexts.getContext(undefined);
447
- return (name: string | undefined) =>
448
- contexts
449
- .getOwnEntries(name)
450
- .filter((entry) => entry.kind === "definition")
451
- .map((entry) => entry.name);
452
- };
453
-
454
- export const getTlcVariableOrder = (source: string, loadModule: ModuleLoader) =>
455
- getTlcDeclarationOrder(source, loadModule, "variable");
456
-
457
461
  // Every string TLC interns before model checking starts, in order: values in the config, TLC's
458
462
  // startup strings, each module's tokens in the order SpecObj.loadSpec parses the modules, string
459
463
  // literals in semantic analysis order, and the names TLC interns for TLCGet.
460
- export const getTlcStringOrder = (
461
- source: string,
462
- config: ModelConfig,
463
- loadModule: ModuleLoader,
464
- ): string[] => {
465
- const getParsed = createModuleSet(source, loadModule);
464
+ const getStringOrder = (getParsed: ModuleSet, config: ModelConfig): string[] => {
466
465
  const order = new Set<string>();
467
466
  const intern = (text: string) => {
468
467
  order.add(text);
@@ -563,3 +562,49 @@ export const getTlcStringOrder = (
563
562
  TLC_RUNTIME_STRINGS.forEach(intern);
564
563
  return [...order];
565
564
  };
565
+
566
+ export interface TlcOrder {
567
+ // Every string TLC interns before model checking starts.
568
+ getStringOrder: (config: ModelConfig) => string[];
569
+ // The variables or constants of the root module in the reverse of its context enumeration, as
570
+ // ModuleNode.getVariableDecls and getConstantDecls return them. TLC compares variables in this
571
+ // order, and checks that the configuration assigns each constant in it.
572
+ getDeclarationOrder: (kind: "variable" | "constant") => string[];
573
+ // The names of the definitions each module adds to its context, in the order of
574
+ // ModuleNode.getOpDefs, in which TLC computes the constant definitions as it starts. An INSTANCE
575
+ // adds the definitions of the module it instantiates in the order that module's Hashtable
576
+ // enumerates them.
577
+ createDefinitionOrder: () => (name: string | undefined) => string[];
578
+ // Parses a module's source, once for the order and the environment.
579
+ parseModule: (source: string) => Module;
580
+ }
581
+
582
+ // One check reads the spec's modules once, and every order shares their tokens, parses and
583
+ // contexts.
584
+ export const createTlcOrder = (source: string, loadModule: ModuleLoader): TlcOrder => {
585
+ const modules = createModuleSet(source, loadModule);
586
+ const getParsed = modules.getParsed;
587
+ let contexts: ReturnType<typeof createContexts> | undefined;
588
+ const getContexts = () => (contexts ??= createContexts(getParsed));
589
+ return {
590
+ getStringOrder: (config) => getStringOrder(getParsed, config),
591
+ getDeclarationOrder: (kind) =>
592
+ getContexts()
593
+ .getContext(undefined)
594
+ .enumerate()
595
+ .filter((entry) => entry.kind === kind)
596
+ .map((entry) => entry.name)
597
+ .reverse(),
598
+ parseModule: modules.parseText,
599
+ createDefinitionOrder: () => {
600
+ const { getContext, getOwnEntries } = getContexts();
601
+ // The root module's context reads every file of the spec, and so finds the modules nested
602
+ // in the files it extends or instantiates.
603
+ getContext(undefined);
604
+ return (name) =>
605
+ getOwnEntries(name)
606
+ .filter((entry) => entry.kind === "definition")
607
+ .map((entry) => entry.name);
608
+ },
609
+ };
610
+ };
package/src/tlc/replay.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { Expression, SourceLocation } from "../ast";
2
2
  import { TlaEvaluationError } from "../errors";
3
+ import { isConstantLevel } from "../dependencies";
3
4
  import {
4
5
  bindDefinitions,
5
6
  bindLazyArguments,
@@ -9,7 +10,6 @@ import {
9
10
  freezeCallStack,
10
11
  getLazyFunction,
11
12
  toKeepLazyContext,
12
- isConstantLevel,
13
13
  lookupScope,
14
14
  resolveApplyOperator,
15
15
  resolveGlobalOperator,
package/src/values.ts CHANGED
@@ -7,6 +7,16 @@ export interface ModelValue {
7
7
  name: string;
8
8
  type: string | undefined;
9
9
  rank: number;
10
+ hash: number;
11
+ fingerprint: number;
12
+ }
13
+
14
+ // What TLC keeps on a set it builds lazily: the enumeration it converted to and cached, as
15
+ // SetPredValue#convertAndCache does, whether it has cached it, and whether it has fingerprinted it.
16
+ interface LazySet {
17
+ enumerated?: SetValue;
18
+ isCached?: boolean;
19
+ isFingerprinted?: boolean;
10
20
  }
11
21
 
12
22
  export interface SetValue {
@@ -19,7 +29,7 @@ export interface SetValue {
19
29
 
20
30
  // A set enumeration whose elements TLC can't sort, such as {1, "a"}. TLC sorts a set enumeration
21
31
  // only when it has to, so it still checks membership in one element by element.
22
- export interface MixedSetValue {
32
+ export interface MixedSetValue extends LazySet {
23
33
  kind: "MixedSet";
24
34
  elements: Value[];
25
35
  }
@@ -46,34 +56,34 @@ export interface InfiniteSetValue {
46
56
  name: "Nat" | "Int" | "STRING" | "Any";
47
57
  }
48
58
 
49
- export interface SubsetValue {
59
+ export interface SubsetValue extends LazySet {
50
60
  kind: "Subset";
51
61
  base: Value;
52
62
  }
53
63
 
54
- export interface FunctionSetValue {
64
+ export interface FunctionSetValue extends LazySet {
55
65
  kind: "FunctionSet";
56
66
  domain: Value;
57
67
  range: Value;
58
68
  }
59
69
 
60
- export interface RecordSetValue {
70
+ export interface RecordSetValue extends LazySet {
61
71
  kind: "RecordSet";
62
72
  names: string[];
63
73
  sets: Value[];
64
74
  }
65
75
 
66
- export interface ProductSetValue {
76
+ export interface ProductSetValue extends LazySet {
67
77
  kind: "ProductSet";
68
78
  factors: Value[];
69
79
  }
70
80
 
71
- export interface SequenceSetValue {
81
+ export interface SequenceSetValue extends LazySet {
72
82
  kind: "SequenceSet";
73
83
  base: Value;
74
84
  }
75
85
 
76
- export interface SetOperationValue {
86
+ export interface SetOperationValue extends LazySet {
77
87
  kind: "SetOperation";
78
88
  operator: "\\cup" | "\\cap" | "\\";
79
89
  left: Value;
@@ -86,7 +96,7 @@ interface FilteredSetSource {
86
96
  predicate: string;
87
97
  }
88
98
 
89
- export interface FilteredSetValue {
99
+ export interface FilteredSetValue extends LazySet {
90
100
  kind: "FilteredSet";
91
101
  base: Value;
92
102
  test: (element: Value) => boolean;
@@ -94,7 +104,7 @@ export interface FilteredSetValue {
94
104
  }
95
105
 
96
106
  // UNION S when some element of S isn't a set enumeration. TLC enumerates it only when it has to.
97
- export interface UnionValue {
107
+ export interface UnionValue extends LazySet {
98
108
  kind: "Union";
99
109
  base: Value;
100
110
  }
@@ -109,12 +119,16 @@ export interface LazyFunctionSource {
109
119
  body: string;
110
120
  }
111
121
 
122
+ // enumerated is the FcnRcdValue TLC converts the function to and keeps, as FcnLambdaValue#toFcnRcd
123
+ // does, from the first time it compares or fingerprints the function.
112
124
  export interface LazyFunctionValue {
113
125
  kind: "LazyFunction";
114
126
  domain: Value;
115
127
  apply: (argument: Value) => Value;
116
128
  source?: LazyFunctionSource;
117
129
  functionClass?: FunctionClass;
130
+ enumerated?: FunctionValue;
131
+ isFingerprinted?: boolean;
118
132
  }
119
133
 
120
134
  export type Value =
@@ -139,6 +153,26 @@ export type Value =
139
153
 
140
154
  export type ObjectValue = Exclude<Value, boolean | number | string>;
141
155
 
156
+ // The sets TLC builds lazily, which it converts and caches as it uses them.
157
+ type ConvertibleSetValue =
158
+ | MixedSetValue
159
+ | SubsetValue
160
+ | FunctionSetValue
161
+ | RecordSetValue
162
+ | ProductSetValue
163
+ | SequenceSetValue
164
+ | SetOperationValue
165
+ | FilteredSetValue
166
+ | UnionValue;
167
+
168
+ const isLazySet = (value: ObjectValue): value is ConvertibleSetValue =>
169
+ value.kind !== "ModelValue" &&
170
+ value.kind !== "Set" &&
171
+ value.kind !== "Function" &&
172
+ value.kind !== "Interval" &&
173
+ value.kind !== "InfiniteSet" &&
174
+ value.kind !== "LazyFunction";
175
+
142
176
  export const MAXIMUM_INTEGER = 2147483647;
143
177
  export const MINIMUM_INTEGER = -2147483648;
144
178
  const MAXIMUM_ENUMERATED_SUBSET_BASE = 30;
@@ -430,6 +464,8 @@ export const createModelValue = (name: string): ModelValue => {
430
464
  name,
431
465
  type: name.length > 2 && name[1] === "_" ? name[0] : undefined,
432
466
  rank: getStringRank(name),
467
+ hash: finalizeHash(combineHash(hashString(name), 0x6d)),
468
+ fingerprint: finalizeFingerprint(fingerprintString(name) ^ 0x3c),
433
469
  };
434
470
  modelValues.set(name, value);
435
471
  return value;
@@ -480,12 +516,9 @@ export const markLambdaFunction = <FunctionLike extends FunctionValue | LazyFunc
480
516
  functionValue: FunctionLike,
481
517
  ) => setFunctionClass(functionValue, "lambda");
482
518
 
483
- const fingerprintedValues = new WeakSet<ObjectValue>();
484
-
485
- // The lazy sets TLC has cached the elements of. TLC caches a set as the receiver of compareTo,
486
- // equals, size, and fingerPrint, not as their argument, and enumerates the sets an uncached one
487
- // combines, duplicates and all.
488
- const cachedSets = new WeakSet<ObjectValue>();
519
+ // TLC caches a lazy set as the receiver of compareTo, equals, size, and fingerPrint, not as their
520
+ // argument, and enumerates the sets an uncached one combines, duplicates and all.
521
+ const isCachedSet = (value: ObjectValue) => isLazySet(value) && value.isCached === true;
489
522
 
490
523
  // Whether the spec has built a UNION or \cup set, the sets that stream duplicates, so that a spec
491
524
  // without one skips tracking what TLC caches.
@@ -512,9 +545,10 @@ const cacheSet = (value: Value) => {
512
545
  if (
513
546
  streamedSetPresence.isPresent &&
514
547
  typeof value === "object" &&
548
+ isLazySet(value) &&
515
549
  STREAMING_KINDS.has(value.kind)
516
550
  ) {
517
- cachedSets.add(value);
551
+ value.isCached = true;
518
552
  }
519
553
  };
520
554
 
@@ -524,13 +558,11 @@ export const markFingerprinted = (value: Value): void => {
524
558
  if ((!lambdaPresence.isPresent && !streamedSetPresence.isPresent) || typeof value !== "object") {
525
559
  return;
526
560
  }
527
- if (value.kind === "Function" || value.kind === "Set") {
528
- if (value.isFingerprinted) return;
529
- value.isFingerprinted = true;
530
- } else {
531
- if (fingerprintedValues.has(value)) return;
532
- fingerprintedValues.add(value);
561
+ if (value.kind === "ModelValue" || value.kind === "Interval" || value.kind === "InfiniteSet") {
562
+ return;
533
563
  }
564
+ if (value.isFingerprinted) return;
565
+ value.isFingerprinted = true;
534
566
  if (value.kind === "Function") {
535
567
  if (value.functionClass === "lambda") value.functionClass = undefined;
536
568
  value.domain.forEach(markFingerprinted);
@@ -1565,15 +1597,13 @@ const enumerateSet = (
1565
1597
  }
1566
1598
  };
1567
1599
 
1568
- const finiteSets = new WeakMap<ObjectValue, SetValue>();
1569
-
1570
1600
  export const toFiniteSet = (value: Value): SetValue => {
1571
1601
  if (typeof value === "object" && value.kind === "Set") return value;
1572
1602
  if (typeof value === "object" && value.kind === "Interval") {
1573
1603
  return createSortedSet(enumerateSet(value));
1574
1604
  }
1575
- const cached = typeof value === "object" ? finiteSets.get(value) : undefined;
1576
- if (cached) return cached;
1605
+ const lazy = typeof value === "object" && isLazySet(value) ? value : undefined;
1606
+ if (lazy?.enumerated) return lazy.enumerated;
1577
1607
  const sets = setTrace.sets;
1578
1608
  sets?.push(value);
1579
1609
  const elements = enumerateSet(value);
@@ -1588,14 +1618,14 @@ export const toFiniteSet = (value: Value): SetValue => {
1588
1618
  value.kind === "FunctionSet" ||
1589
1619
  value.kind === "Subset");
1590
1620
  const set = isSorted ? createSortedSet(elements) : createSet(elements);
1591
- if (typeof value === "object") finiteSets.set(value, set);
1621
+ if (lazy) lazy.enumerated = set;
1592
1622
  return set;
1593
1623
  };
1594
1624
 
1595
1625
  // TLC's Enumerator for a lazy set streams the sets it combines until the set caches its elements,
1596
1626
  // so an element that two of them share comes up once for each.
1597
1627
  export const getStreamedElements = (value: Value): Value[] => {
1598
- if (typeof value !== "object" || cachedSets.has(value)) return toFiniteSet(value).elements;
1628
+ if (typeof value !== "object" || isCachedSet(value)) return toFiniteSet(value).elements;
1599
1629
  const sets = setTrace.sets;
1600
1630
  sets?.push(value);
1601
1631
  const elements = streamElements(value);
@@ -1647,7 +1677,7 @@ export const isSettledValue = (value: Value): boolean => {
1647
1677
  // Whether a set streams its elements in another order than the normalized set, so that a set of
1648
1678
  // tuples, records, or functions it is a component of has to stream too.
1649
1679
  const isStreamedApart = (value: Value): boolean => {
1650
- if (typeof value !== "object" || cachedSets.has(value)) return false;
1680
+ if (typeof value !== "object" || isCachedSet(value)) return false;
1651
1681
  if (value.kind === "Union") return true;
1652
1682
  if (value.kind === "FilteredSet") return isStreamedApart(value.base);
1653
1683
  if (value.kind === "SetOperation") {
@@ -2102,15 +2132,17 @@ export const isUpdatedElementOf = (element: Value, member: Value, set: Value): b
2102
2132
  export const toFiniteFunction = (value: Value): FunctionValue => {
2103
2133
  if (typeof value === "object" && value.kind === "Function") return value;
2104
2134
  if (typeof value === "object" && value.kind === "LazyFunction") {
2135
+ if (value.enumerated) return value.enumerated;
2105
2136
  if (!isEnumerable(value.domain)) getCardinality(value.domain);
2106
2137
  const domain = getFunctionDomain(value.domain);
2107
- return setFunctionClass(
2138
+ value.enumerated = setFunctionClass(
2108
2139
  createSortedFunction(
2109
2140
  domain,
2110
2141
  domain.map((key) => value.apply(key)),
2111
2142
  ),
2112
2143
  getFunctionClass(value),
2113
2144
  );
2145
+ return value.enumerated;
2114
2146
  }
2115
2147
  throw new TlaEvaluationError(`Expected a function but found ${formatValue(value)}`);
2116
2148
  };
@@ -2315,8 +2347,6 @@ export const updateFunction = (
2315
2347
  return updated;
2316
2348
  };
2317
2349
 
2318
- const valueHashes = new WeakMap<ObjectValue, number>();
2319
-
2320
2350
  const HASH_SEED = 0x811c9dc5;
2321
2351
 
2322
2352
  const finalizeHash = (hash: number) => {
@@ -2348,11 +2378,9 @@ const getEntryContribution = (keyHash: number, valueHash: number) =>
2348
2378
  // when TLC fingerprints it.
2349
2379
  const UNFINGERPRINTABLE_HASH = 0x2f6b1c4d;
2350
2380
 
2351
- const computeValueHash = (value: ObjectValue) => {
2352
- if (value.kind === "ModelValue") return finalizeHash(combineHash(hashString(value.name), 0x6d));
2353
- if (isSetValue(value)) {
2354
- if (!isEnumerable(value)) return UNFINGERPRINTABLE_HASH;
2355
- const elements = toFiniteSet(value).elements;
2381
+ const computeValueHash = (value: SetValue | FunctionValue) => {
2382
+ if (value.kind === "Set") {
2383
+ const elements = value.elements;
2356
2384
  let hash = SET_HASH_SEED;
2357
2385
  for (let index = 0; index < elements.length; index++) {
2358
2386
  const elementHash = getValueHash(elements[index]);
@@ -2361,12 +2389,10 @@ const computeValueHash = (value: ObjectValue) => {
2361
2389
  }
2362
2390
  return hash;
2363
2391
  }
2364
- if (value.kind === "LazyFunction" && !isEnumerable(value.domain)) return UNFINGERPRINTABLE_HASH;
2365
- const functionValue = toFiniteFunction(value);
2366
2392
  let hash = FUNCTION_HASH_SEED;
2367
- for (let index = 0; index < functionValue.domain.length; index++) {
2368
- const keyHash = getValueHash(functionValue.domain[index]);
2369
- const itemHash = getValueHash(functionValue.range[index]);
2393
+ for (let index = 0; index < value.domain.length; index++) {
2394
+ const keyHash = getValueHash(value.domain[index]);
2395
+ const itemHash = getValueHash(value.range[index]);
2370
2396
  if (keyHash === UNFINGERPRINTABLE_HASH || itemHash === UNFINGERPRINTABLE_HASH) {
2371
2397
  return UNFINGERPRINTABLE_HASH;
2372
2398
  }
@@ -2442,15 +2468,15 @@ export const getValueHash = (value: Value): number => {
2442
2468
  if (value.hash === 0) value.hash = computeValueHash(value);
2443
2469
  return value.hash;
2444
2470
  }
2445
- const cached = valueHashes.get(value);
2446
- if (cached !== undefined) return cached;
2447
- const hash = computeValueHash(value);
2448
- valueHashes.set(value, hash);
2449
- return hash;
2471
+ if (value.kind === "ModelValue") return value.hash;
2472
+ if (value.kind === "LazyFunction") {
2473
+ return isEnumerable(value.domain)
2474
+ ? getValueHash(toFiniteFunction(value))
2475
+ : UNFINGERPRINTABLE_HASH;
2476
+ }
2477
+ return isEnumerable(value) ? getValueHash(toFiniteSet(value)) : UNFINGERPRINTABLE_HASH;
2450
2478
  };
2451
2479
 
2452
- const valueFingerprints = new WeakMap<ObjectValue, number>();
2453
-
2454
2480
  const finalizeFingerprint = (hash: number) => {
2455
2481
  const first = Math.imul(hash ^ (hash >>> 15), 0x2c1b3c6d);
2456
2482
  const second = Math.imul(first ^ (first >>> 12), 0x297a2d39);
@@ -2472,23 +2498,18 @@ const getEntryFingerprint = (key: Value, value: Value) =>
2472
2498
  (Math.imul(getValueFingerprint(key), 0x165667b1) + getValueFingerprint(value)) | 0,
2473
2499
  );
2474
2500
 
2475
- const computeValueFingerprint = (value: ObjectValue) => {
2476
- if (value.kind === "ModelValue") return finalizeFingerprint(fingerprintString(value.name) ^ 0x3c);
2477
- if (isSetValue(value)) {
2478
- if (!isEnumerable(value)) return fingerprintString(getValueKey(value));
2479
- const elements = toFiniteSet(value).elements;
2501
+ const computeValueFingerprint = (value: SetValue | FunctionValue) => {
2502
+ if (value.kind === "Set") {
2503
+ const elements = value.elements;
2480
2504
  let fingerprint = 0x1b873593;
2481
2505
  for (let index = 0; index < elements.length; index++) {
2482
2506
  fingerprint = (fingerprint + getElementFingerprint(elements[index])) | 0;
2483
2507
  }
2484
2508
  return fingerprint;
2485
2509
  }
2486
- const functionValue = toFiniteFunction(value);
2487
2510
  let fingerprint = 0x4cf5ad43;
2488
- for (let index = 0; index < functionValue.domain.length; index++) {
2489
- fingerprint =
2490
- (fingerprint + getEntryFingerprint(functionValue.domain[index], functionValue.range[index])) |
2491
- 0;
2511
+ for (let index = 0; index < value.domain.length; index++) {
2512
+ fingerprint = (fingerprint + getEntryFingerprint(value.domain[index], value.range[index])) | 0;
2492
2513
  }
2493
2514
  return fingerprint;
2494
2515
  };
@@ -2501,24 +2522,18 @@ export const getValueFingerprint = (value: Value): number => {
2501
2522
  if (value.fingerprint === 0) value.fingerprint = computeValueFingerprint(value);
2502
2523
  return value.fingerprint;
2503
2524
  }
2504
- const cached = valueFingerprints.get(value);
2505
- if (cached !== undefined) return cached;
2506
- const fingerprint = computeValueFingerprint(value);
2507
- valueFingerprints.set(value, fingerprint);
2508
- return fingerprint;
2525
+ if (value.kind === "ModelValue") return value.fingerprint;
2526
+ if (value.kind === "LazyFunction") return getValueFingerprint(toFiniteFunction(value));
2527
+ return isEnumerable(value)
2528
+ ? getValueFingerprint(toFiniteSet(value))
2529
+ : fingerprintString(getValueKey(value));
2509
2530
  };
2510
2531
 
2511
- const valueKeys = new WeakMap<ObjectValue, string>();
2512
-
2513
2532
  export const getValueKey = (value: Value): string => {
2514
2533
  if (typeof value === "boolean") return value ? "T" : "F";
2515
2534
  if (typeof value === "number") return String(value);
2516
2535
  if (typeof value === "string") return JSON.stringify(value);
2517
- const cached = valueKeys.get(value);
2518
- if (cached !== undefined) return cached;
2519
- const key = computeValueKey(value);
2520
- valueKeys.set(value, key);
2521
- return key;
2536
+ return computeValueKey(value);
2522
2537
  };
2523
2538
 
2524
2539
  const computeValueKey = (value: ObjectValue) => {