tla-ts 0.0.3-dev.b74f28c → 0.0.3-dev.bffbba3

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/successors.ts CHANGED
@@ -1,28 +1,36 @@
1
- import type { Bound, Definition, Expression } from "./ast";
1
+ import {
2
+ getChildren,
3
+ isLocallyResolved,
4
+ type Bound,
5
+ type Definition,
6
+ type Expression,
7
+ type QuantifierExpression,
8
+ } from "./ast";
2
9
  import { getReadVariables } from "./dependencies";
3
- import { TlaEvaluationError } from "./errors";
10
+ import { TlaEvaluationError, UNEXPECTED_EXCEPTION } from "./errors";
4
11
  import { EXIT_STATUS, setExitCode } from "./exit-codes";
5
12
  import {
6
13
  describeLocation,
14
+ describeRange,
7
15
  bindArgument,
8
16
  bindDefinitions,
9
17
  bindOperatorArguments,
10
18
  bindValue,
11
19
  compileArgumentScope,
12
20
  evaluate,
21
+ getEntryEvaluator,
13
22
  expectBoolean,
14
23
  forEachBinding,
15
24
  getBoundsDomain,
16
- getChildren,
17
25
  getDefinition,
18
26
  getEnumeratedElements,
19
27
  getReevaluatedDefinitions,
20
28
  lookupScope,
21
29
  resolveApplyOperator,
22
30
  resolveGlobalOperator,
23
- isLocallyResolved,
24
31
  type Context,
25
32
  type Environment,
33
+ type Evaluator,
26
34
  type Scope,
27
35
  type State,
28
36
  } from "./evaluate";
@@ -81,8 +89,7 @@ const assign = (partial: State, index: number, value: Value) => {
81
89
  return copy;
82
90
  };
83
91
 
84
- const holds = (expression: Expression, context: Context) => {
85
- const value = evaluate(expression, context);
92
+ const holds = (expression: Expression, context: Context, value = evaluate(expression, context)) => {
86
93
  if (typeof value === "boolean") return value;
87
94
  try {
88
95
  return expectBoolean(value, `the action at ${describeLocation(expression)}`);
@@ -287,12 +294,34 @@ const toConjunct = (
287
294
  return { kind: "Branch", expression, runner: getRunner(expression, environment, isInit) };
288
295
  };
289
296
 
297
+ // The leading guards of `\E x \in S, y \in T : P /\ Q` that read no inner bound hold for every inner
298
+ // binding alike, so they can run once for each element of the outermost bound.
299
+ const getHoistedGuards = (expression: QuantifierExpression, environment: Environment) => {
300
+ if (expression.bounds.length < 2 || expression.body.kind !== "And") return undefined;
301
+ const names = expression.bounds.flatMap((bound) =>
302
+ bound.pattern.kind === "Name" ? [bound.pattern.name] : [],
303
+ );
304
+ if (names.length !== expression.bounds.length) return undefined;
305
+ const innerNames = new Set(names.slice(0, -1));
306
+ const operands = expression.body.operands;
307
+ const index = operands.findIndex((operand) => {
308
+ if (getReadVariables(operand, environment) === undefined) return true;
309
+ if (hasBranches(operand, environment, new Set())) return true;
310
+ const readLocals = getReadLocals(operand, NO_NAMES);
311
+ return !readLocals || readLocals.some((name) => innerNames.has(name));
312
+ });
313
+ const count = index === -1 ? operands.length : index;
314
+ if (count === 0) return undefined;
315
+ return { names, guards: operands.slice(0, count), rest: operands.slice(count) };
316
+ };
317
+
290
318
  const compileConjunction = (
291
319
  operands: Expression[],
292
320
  environment: Environment,
293
321
  isInit: boolean,
294
322
  ): Runner => {
295
323
  const conjuncts = operands.map((operand) => toConjunct(operand, environment, isInit));
324
+ const evaluators: (Evaluator | undefined)[] = conjuncts.map(() => undefined);
296
325
  const runFrom = (
297
326
  start: number,
298
327
  run: Run,
@@ -315,12 +344,17 @@ const compileConjunction = (
315
344
  const conjunct = conjuncts[index];
316
345
  if (conjunct.kind === "Guard") {
317
346
  context ??= getContext(run, scope, current);
318
- if (!holds(conjunct.expression, context)) return;
347
+ const evaluator = (evaluators[index] ??= getEntryEvaluator(
348
+ conjunct.expression,
349
+ environment,
350
+ ));
351
+ if (!holds(conjunct.expression, context, evaluator(context))) return;
319
352
  continue;
320
353
  }
321
354
  if (conjunct.kind === "Assign") {
322
355
  context ??= getContext(run, scope, current);
323
- const value = evaluate(conjunct.value, context);
356
+ const evaluator = (evaluators[index] ??= getEntryEvaluator(conjunct.value, environment));
357
+ const value = evaluator(context);
324
358
  const assigned = current[conjunct.index];
325
359
  if (assigned === undefined) {
326
360
  current = assign(current, conjunct.index, value);
@@ -729,6 +763,33 @@ const compileAction = (
729
763
  }
730
764
  };
731
765
  }
766
+ const hoisted = isInit ? undefined : getHoistedGuards(expression, environment);
767
+ if (hoisted) {
768
+ const rest = compileConjunction(hoisted.rest, environment, isInit);
769
+ return (run, scope, partial, action, isFixed, onComplete) => {
770
+ const context = getContext(run, scope, partial);
771
+ const sets = expression.bounds.map((innerBound) =>
772
+ getEnumeratedElements(evaluate(innerBound.set, context), innerBound.set),
773
+ );
774
+ if (sets.some((elements) => elements.length === 0)) return;
775
+ const visit = (index: number, boundScope: Scope | undefined): void => {
776
+ if (index < 0) {
777
+ rest(run, boundScope, partial, action, isFixed, onComplete);
778
+ return;
779
+ }
780
+ for (const element of sets[index]) {
781
+ if (run.isStopped) return;
782
+ const elementScope = bindValue(boundScope, hoisted.names[index], element);
783
+ if (index === sets.length - 1) {
784
+ const guardContext = getContext(run, elementScope, partial);
785
+ if (!hoisted.guards.every((guard) => holds(guard, guardContext))) continue;
786
+ }
787
+ visit(index - 1, elementScope);
788
+ }
789
+ };
790
+ visit(sets.length - 1, scope);
791
+ };
792
+ }
732
793
  return (run, scope, partial, action, isFixed, onComplete) => {
733
794
  forEachBinding(expression.bounds, getContext(run, scope, partial), (boundScope) => {
734
795
  body(run, boundScope, partial, action, isFixed, onComplete);
@@ -804,7 +865,9 @@ const compileAction = (
804
865
  );
805
866
  const body = arm?.body ?? other;
806
867
  if (!body)
807
- throw new TlaEvaluationError(`No CASE guard is true at ${describeLocation(expression)}`);
868
+ throw new TlaEvaluationError(
869
+ `${UNEXPECTED_EXCEPTION}In computing next states, TLC encountered a CASE with no conditions true.\n${describeRange(expression)}`,
870
+ );
808
871
  body(run, scope, partial, action, isFixed, onComplete);
809
872
  };
810
873
  }
@@ -913,18 +976,19 @@ export const isEnabled = (expression: Expression, context: Context): boolean =>
913
976
  );
914
977
  }
915
978
  const environment = context.environment;
916
- const found = { value: false };
979
+ const run: Run = { environment, isInit: false, current: state, isStopped: false };
980
+ // TLC stops computing ENABLED at the first successor, so it skips the rest of the action.
917
981
  getRunner(expression, environment, false)(
918
- { environment, isInit: false, current: state, isStopped: false },
982
+ run,
919
983
  context.scope,
920
984
  getEmptyState(environment),
921
985
  undefined,
922
986
  false,
923
987
  () => {
924
- found.value = true;
988
+ run.isStopped = true;
925
989
  },
926
990
  );
927
- return found.value;
991
+ return run.isStopped;
928
992
  };
929
993
 
930
994
  export const forEachInitialState = (
package/src/tableau.ts CHANGED
@@ -162,22 +162,39 @@ const containsAction = (expression: LiveExpression): boolean => {
162
162
  }
163
163
  };
164
164
 
165
- const isEqual = (left: LiveExpression, right: LiveExpression): boolean => {
166
- if (left.kind !== right.kind) return false;
167
- if (left.kind === "Boolean" && right.kind === "Boolean") return left.value === right.value;
168
- if (isAtom(left)) return left === right;
169
- if ("body" in left && "body" in right) return isEqual(left.body, right.body);
170
- if ("operands" in left && "operands" in right) {
171
- return (
172
- left.operands.length === right.operands.length &&
173
- left.operands.every((operand, index) => isEqual(operand, right.operands[index]))
174
- );
175
- }
176
- return false;
165
+ const termKeys = new WeakMap<LiveExpression, string>();
166
+ const atoms = { count: 0 };
167
+
168
+ // A term's structure as a string in which each atom stands for itself, so equal terms share a key.
169
+ export const getTermKey = (expression: LiveExpression): string => {
170
+ const cached = termKeys.get(expression);
171
+ if (cached !== undefined) return cached;
172
+ const key = (() => {
173
+ switch (expression.kind) {
174
+ case "Boolean":
175
+ return String(expression.value);
176
+ case "State":
177
+ case "Enabled":
178
+ case "Action":
179
+ return `#${atoms.count++}`;
180
+ case "And":
181
+ case "Or":
182
+ return `${expression.kind}(${expression.operands.map(getTermKey).join(",")})`;
183
+ default:
184
+ return `${expression.kind}(${getTermKey(expression.body)})`;
185
+ }
186
+ })();
187
+ termKeys.set(expression, key);
188
+ return key;
177
189
  };
178
190
 
179
- const isMember = (items: LiveExpression[], expression: LiveExpression) =>
180
- items.some((item) => isEqual(item, expression));
191
+ const isEqual = (left: LiveExpression, right: LiveExpression) =>
192
+ left === right || getTermKey(left) === getTermKey(right);
193
+
194
+ const isMember = (items: LiveExpression[], expression: LiveExpression) => {
195
+ const key = getTermKey(expression);
196
+ return items.some((item) => item === expression || getTermKey(item) === key);
197
+ };
181
198
 
182
199
  const getDual = (kind: LiveJunction["kind"]) => (kind === "And" ? "Or" : "And");
183
200
 
@@ -446,13 +463,14 @@ const getTriples = (
446
463
  return parts ? [{ whole: term, first: parts.first, second: parts.second }] : [];
447
464
  });
448
465
 
449
- const isSameParticle = (left: LiveExpression[], right: LiveExpression[]) =>
450
- left.every((term) => isMember(right, term)) && right.every((term) => isMember(left, term));
466
+ // A particle is a set of terms, so its key ignores order and repeats.
467
+ const getParticleKey = (particle: LiveExpression[]) =>
468
+ [...new Set(particle.map(getTermKey))].sort().join("|");
451
469
 
452
- const unionParticles = (left: LiveExpression[][], right: LiveExpression[][]) => [
453
- ...left.filter((particle) => !right.some((other) => isSameParticle(particle, other))),
454
- ...right,
455
- ];
470
+ const unionParticles = (left: LiveExpression[][], right: LiveExpression[][]) => {
471
+ const rightKeys = new Set(right.map(getParticleKey));
472
+ return [...left.filter((particle) => !rightKeys.has(getParticleKey(particle))), ...right];
473
+ };
456
474
 
457
475
  const getParticleClosure = (terms: LiveExpression[]) => {
458
476
  const closure = getPositiveClosure(terms);
@@ -516,14 +534,23 @@ const createTableauNode = (particle: LiveExpression[]): TableauNode => ({
516
534
  const createTableau = (formula: LiveExpression) => {
517
535
  const nodes = getParticleClosure([formula]).map(createTableauNode);
518
536
  const initialCount = nodes.length;
537
+ const indices = new Map<string, number>();
538
+ nodes.forEach((node, index) => {
539
+ const key = getParticleKey(node.particle);
540
+ if (!indices.has(key)) indices.set(key, index);
541
+ });
519
542
  for (let index = 0; index < nodes.length; index++) {
520
543
  const implied = nodes[index].particle.flatMap((term) =>
521
544
  term.kind === "Next" ? [term.body] : [],
522
545
  );
523
546
  for (const particle of getParticleClosure(implied)) {
524
- const existing = nodes.findIndex((node) => isSameParticle(node.particle, particle));
525
- if (existing === -1) nodes.push(createTableauNode(particle));
526
- nodes[index].successors.push(existing === -1 ? nodes.length - 1 : existing);
547
+ const key = getParticleKey(particle);
548
+ const existing = indices.get(key);
549
+ if (existing === undefined) {
550
+ indices.set(key, nodes.length);
551
+ nodes.push(createTableauNode(particle));
552
+ }
553
+ nodes[index].successors.push(existing ?? nodes.length - 1);
527
554
  }
528
555
  }
529
556
  return { nodes, initialCount };
package/src/tlc-ext.ts CHANGED
@@ -10,16 +10,8 @@ import {
10
10
  } from "./builtins";
11
11
  import { TlaEvaluationError, TlaModuleError, TlaUnsupportedError } from "./errors";
12
12
  import { getTlcFingerprint } from "./tlc-random";
13
- import {
14
- evaluate,
15
- expectBoolean,
16
- getChildren,
17
- getDefinition,
18
- isLocallyResolved,
19
- type Builtin,
20
- type Environment,
21
- } from "./evaluate";
22
- import type { Definition, Expression } from "./ast";
13
+ import { evaluate, expectBoolean, getDefinition, type Builtin, type Environment } from "./evaluate";
14
+ import { getChildren, isLocallyResolved, type Definition, type Expression } from "./ast";
23
15
  import type { TraceStep } from "./check";
24
16
  import {
25
17
  getNamedRegisters,
@@ -111,15 +103,35 @@ const getRegister = (runtime: CheckerRuntime, key: Value) => {
111
103
  return undefined;
112
104
  };
113
105
 
114
- const setRegister = (runtime: CheckerRuntime, key: Value, value: Value) => {
106
+ // TLC's TLCSet. TLCExt's TLCGetAndSet is a TLA+ definition that calls it.
107
+ export const setTlcValue = (
108
+ runtime: CheckerRuntime,
109
+ print: (text: string) => void,
110
+ key: Value,
111
+ value: Value,
112
+ ) => {
115
113
  if (typeof key === "number" && key >= 0) {
116
114
  runtime.registers.set(key, value);
117
115
  return;
118
116
  }
117
+ if (key === "exit") {
118
+ if (value === true) runtime.isStopped = true;
119
+ return;
120
+ }
121
+ if (key === "pause") {
122
+ if (value !== true) return;
123
+ print("Press enter to resume model checking.");
124
+ runtime.pause();
125
+ return;
126
+ }
119
127
  if (typeof key === "string" && key.startsWith(NAMED_REGISTER_PREFIX)) {
120
128
  runtime.namedRegisters.set(key, value);
121
129
  return;
122
130
  }
131
+ if (typeof key === "string" && key.startsWith("-D")) {
132
+ runtime.properties.set(key.slice(2), formatValue(value));
133
+ return;
134
+ }
123
135
  throw new TlaModuleError(
124
136
  `The first argument of TLCSet should be a nonnegative integer, but instead it is:\n${formatValue(key)}`,
125
137
  );
@@ -203,7 +215,12 @@ export const createTlcExtOperators = (
203
215
  const key = getValue(args, 0, "TLCGetAndSet");
204
216
  const previous = getRegister(runtime, key) ?? getValue(args, 3, "TLCGetAndSet");
205
217
  const update = getOperator(args, 1, "TLCGetAndSet");
206
- setRegister(runtime, key, update.call([previous, getValue(args, 2, "TLCGetAndSet")]));
218
+ setTlcValue(
219
+ runtime,
220
+ print,
221
+ key,
222
+ update.call([previous, getValue(args, 2, "TLCGetAndSet")]),
223
+ );
207
224
  return previous;
208
225
  }),
209
226
  isStateLevel: true,
package/src/tlc-module.ts CHANGED
@@ -15,7 +15,7 @@ import {
15
15
  getValue,
16
16
  } from "./builtins";
17
17
  import { getNamedRegisters, NAMED_REGISTER_PREFIX, type CheckerRuntime } from "./runtime";
18
- import { createActionRecord } from "./tlc-ext";
18
+ import { createActionRecord, setTlcValue } from "./tlc-ext";
19
19
  import { getRandomElement } from "./tlc-random";
20
20
  import {
21
21
  ANY_SET,
@@ -39,11 +39,17 @@ const formatCalendarVersion = (date: Date) =>
39
39
  const getRegisterFunction = <Key extends Value>(registers: Map<Key, Value>) =>
40
40
  createFunction([...registers].map(([key, value]): [Value, Value] => [key, createTuple([value])]));
41
41
 
42
+ // TLC creates its model checker after it processes the spec, so these are undefined before then.
43
+ const CHECKER_KEYS = new Set(["diameter", "generated", "distinct", "queue", "stats", "config"]);
44
+
42
45
  const getRuntimeValue = (
43
46
  runtime: CheckerRuntime,
44
47
  key: string,
45
48
  state: (Value | undefined)[] | undefined,
46
49
  ) => {
50
+ if (!runtime.isStarted && CHECKER_KEYS.has(key)) {
51
+ throw new TlaModuleError(`TLCGet(${key}) was undefined.`);
52
+ }
47
53
  const duration = Math.floor((Date.now() - runtime.startedAt) / 1000);
48
54
  switch (key) {
49
55
  case "level":
@@ -203,33 +209,8 @@ export const createTlcOperators = (
203
209
  }),
204
210
  defineStateOperator("TLCSet", 2, (args) => {
205
211
  const key = getValue(args, 0, "TLCSet");
206
- const value = getValue(args, 1, "TLCSet");
207
- if (typeof key === "number" && key >= 0) {
208
- runtime.registers.set(key, value);
209
- return true;
210
- }
211
- if (key === "exit") {
212
- if (value === true) runtime.isStopped = true;
213
- return true;
214
- }
215
- if (key === "pause") {
216
- if (value === true) {
217
- print("Press enter to resume model checking.");
218
- runtime.pause();
219
- }
220
- return true;
221
- }
222
- if (typeof key === "string" && key.startsWith(NAMED_REGISTER_PREFIX)) {
223
- runtime.namedRegisters.set(key, value);
224
- return true;
225
- }
226
- if (typeof key === "string" && key.startsWith("-D")) {
227
- runtime.properties.set(key.slice(2), formatValue(value));
228
- return true;
229
- }
230
- throw new TlaModuleError(
231
- `The first argument of TLCSet should be a nonnegative integer, but instead it is:\n${formatValue(key)}`,
232
- );
212
+ setTlcValue(runtime, print, key, getValue(args, 1, "TLCSet"));
213
+ return true;
233
214
  }),
234
215
  defineConstant("Any", ANY_SET),
235
216
  defineOperator("RandomElement", 1, (args) =>
package/src/tlc-order.ts CHANGED
@@ -184,9 +184,18 @@ const isAdjacent = (left: Token, right: Token | undefined) =>
184
184
  right.line === left.line &&
185
185
  right.column === left.column + left.text.length;
186
186
 
187
+ const STRING_ESCAPES: Record<string, string> = {
188
+ "\\": "\\\\",
189
+ '"': '\\"',
190
+ "\n": "\\n",
191
+ "\t": "\\t",
192
+ "\r": "\\r",
193
+ "\f": "\\f",
194
+ };
195
+
187
196
  // The texts SANY interns while parsing, in order. SANY reads a proof step label such as <1>2 and
188
- // a module header such as ---- MODULE as one token, and interns a string literal's contents only
189
- // during semantic analysis.
197
+ // a module header such as ---- MODULE as one token. It interns a string literal as written, quotes
198
+ // included, and interns the literal's contents only during semantic analysis.
190
199
  const getParsedTexts = (tokens: Token[]) => {
191
200
  const texts: string[] = [];
192
201
  for (let index = 0; index < tokens.length; index++) {
@@ -202,7 +211,12 @@ const getParsedTexts = (tokens: Token[]) => {
202
211
  continue;
203
212
  }
204
213
  const isHeader = token.text === "MODULE" && tokens[index - 1]?.kind === "Separator";
205
- if (token.kind !== "String" && !isHeader) texts.push(token.text);
214
+ if (isHeader) continue;
215
+ texts.push(
216
+ token.kind === "String"
217
+ ? `"${token.text.replace(/[\\"\n\t\r\f]/g, (character) => STRING_ESCAPES[character])}"`
218
+ : token.text,
219
+ );
206
220
  }
207
221
  return texts;
208
222
  };
package/src/values.ts CHANGED
@@ -137,6 +137,13 @@ export const isSetValue = (value: Value) =>
137
137
  value.kind !== "Function" &&
138
138
  value.kind !== "LazyFunction";
139
139
 
140
+ export type ReducibleSet = SetValue | MixedSetValue | IntervalValue;
141
+
142
+ // TLC reduces a set enumeration or an interval eagerly, and keeps every other set lazy.
143
+ export const isReducible = (value: Value): value is ReducibleSet =>
144
+ typeof value === "object" &&
145
+ (value.kind === "Set" || value.kind === "MixedSet" || value.kind === "Interval");
146
+
140
147
  export const isFunctionValue = (value: Value): value is FunctionValue | LazyFunctionValue =>
141
148
  typeof value === "object" && (value.kind === "Function" || value.kind === "LazyFunction");
142
149
 
@@ -371,7 +378,7 @@ export const compareValues = (left: Value, right: Value): number => {
371
378
  `Attempted to compare ${describeKind(left)} ${formatValue(left)} with ${describeKind(right)} ${formatValue(right)}`,
372
379
  );
373
380
  }
374
- if (isLeftSet) return compareSets(toFiniteSet(left), toFiniteSet(right));
381
+ if (isLeftSet) return compareSets(toFiniteSet(left), toComparedSet(right));
375
382
  return compareFunctions(toFiniteFunction(left), toFiniteFunction(right));
376
383
  }
377
384
  if (typeof left === "number" && typeof right === "number") return left - right;
@@ -864,9 +871,11 @@ export const isEqualLikeTlc = (left: Value, right: Value) => {
864
871
  }
865
872
  };
866
873
 
874
+ // TLC sorts a set by comparing each element with the ones before it, so the later element converts
875
+ // a lazy set it compares and caches it.
867
876
  const isStrictlySorted = (elements: Value[]) => {
868
877
  for (let index = 1; index < elements.length; index++) {
869
- if (compareValues(elements[index - 1], elements[index]) >= 0) return false;
878
+ if (compareValues(elements[index], elements[index - 1]) <= 0) return false;
870
879
  }
871
880
  return true;
872
881
  };
@@ -1069,13 +1078,16 @@ const isTlcEnumerable = (value: Value) => isSetValue(value) && !isOverriddenSet(
1069
1078
  const formatUnion = (value: UnionValue, isStrict = false) =>
1070
1079
  `UNION(${formatValue(value.base, isStrict)})`;
1071
1080
 
1072
- const getUnionSets = (value: UnionValue) => {
1081
+ const getUnionSets = (
1082
+ value: UnionValue,
1083
+ getElements = (set: Value) => toFiniteSet(set).elements,
1084
+ ) => {
1073
1085
  if (!isTlcEnumerable(value.base)) {
1074
1086
  throw new TlaEvaluationError(
1075
1087
  `Attempted to enumerate the nonenumerable set:\n${formatUnion(value)}`,
1076
1088
  );
1077
1089
  }
1078
- return toFiniteSet(value.base).elements;
1090
+ return getElements(value.base);
1079
1091
  };
1080
1092
 
1081
1093
  const getUnionSet = (set: Value, index: number, union: UnionValue) => {
@@ -1111,7 +1123,7 @@ export const isEnumerable = (value: Value): boolean => {
1111
1123
  case "ProductSet":
1112
1124
  return value.factors.every(isEnumerable) || getEmptiness(value) === true;
1113
1125
  case "Union":
1114
- return isEnumerable(value.base) && toFiniteSet(value.base).elements.every(isEnumerable);
1126
+ return isEnumerable(value.base) && getStreamedElements(value.base).every(isEnumerable);
1115
1127
  case "SetOperation":
1116
1128
  if (value.operator === "\\cup") return isEnumerable(value.left) && isEnumerable(value.right);
1117
1129
  if (value.operator === "\\cap") return isEnumerable(value.left) || isEnumerable(value.right);
@@ -1318,6 +1330,7 @@ const enumerateSet = (value: Value): Value[] => {
1318
1330
  };
1319
1331
 
1320
1332
  const finiteSets = new WeakMap<ObjectValue, SetValue>();
1333
+ const comparedSets = new WeakMap<ObjectValue, SetValue>();
1321
1334
 
1322
1335
  export const toFiniteSet = (value: Value): SetValue => {
1323
1336
  if (typeof value === "object" && value.kind === "Set") return value;
@@ -1326,6 +1339,13 @@ export const toFiniteSet = (value: Value): SetValue => {
1326
1339
  }
1327
1340
  const cached = typeof value === "object" ? finiteSets.get(value) : undefined;
1328
1341
  if (cached) return cached;
1342
+ const set =
1343
+ (typeof value === "object" ? comparedSets.get(value) : undefined) ?? enumerateFiniteSet(value);
1344
+ if (typeof value === "object") finiteSets.set(value, set);
1345
+ return set;
1346
+ };
1347
+
1348
+ const enumerateFiniteSet = (value: Value) => {
1329
1349
  const elements = enumerateSet(value);
1330
1350
  const isSorted =
1331
1351
  typeof value === "object" &&
@@ -1336,8 +1356,20 @@ export const toFiniteSet = (value: Value): SetValue => {
1336
1356
  value.kind === "ProductSet" ||
1337
1357
  value.kind === "FunctionSet" ||
1338
1358
  value.kind === "Subset");
1339
- const set = isSorted ? createSortedSet(elements) : createSet(elements);
1340
- if (typeof value === "object") finiteSets.set(value, set);
1359
+ return isSorted ? createSortedSet(elements) : createSet(elements);
1360
+ };
1361
+
1362
+ // TLC converts the set a comparison receives as its argument without caching it, so a lazy set
1363
+ // compared that way still streams the sets it combines.
1364
+ const toComparedSet = (value: Value) => {
1365
+ const isStreamed =
1366
+ typeof value === "object" &&
1367
+ (value.kind === "Union" || value.kind === "SetOperation" || value.kind === "FilteredSet");
1368
+ if (!isStreamed || finiteSets.has(value)) return toFiniteSet(value);
1369
+ const compared = comparedSets.get(value);
1370
+ if (compared) return compared;
1371
+ const set = enumerateFiniteSet(value);
1372
+ comparedSets.set(value, set);
1341
1373
  return set;
1342
1374
  };
1343
1375
 
@@ -1345,8 +1377,10 @@ export const toFiniteSet = (value: Value): SetValue => {
1345
1377
  // so an element that two of them share comes up once for each.
1346
1378
  export const getStreamedElements = (value: Value): Value[] => {
1347
1379
  if (typeof value !== "object" || finiteSets.has(value)) return toFiniteSet(value).elements;
1380
+ // TLC streams the sets of a UNION it hasn't enumerated, so a set that appears twice there yields
1381
+ // its elements twice.
1348
1382
  if (value.kind === "Union") {
1349
- return getUnionSets(value).flatMap((set, index) =>
1383
+ return getUnionSets(value, getStreamedElements).flatMap((set, index) =>
1350
1384
  getStreamedElements(getUnionSet(set, index, value)),
1351
1385
  );
1352
1386
  }
@@ -2101,8 +2135,11 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
2101
2135
  return `[${parameters} |-> <expression ${source.body}>]`;
2102
2136
  }
2103
2137
  const functionValue = toFiniteFunction(value);
2138
+ // TLC normalizes a lambda's domain to print it, but evaluates its body afterward.
2139
+ const formatRange = (inner: Value) =>
2140
+ formatValue(inner, isStrict, isNormalized && value.kind === "Function");
2104
2141
  if (functionValue.domain.every((key, index) => key === index + 1)) {
2105
- return `<<${functionValue.range.map(format).join(", ")}>>`;
2142
+ return `<<${functionValue.range.map(formatRange).join(", ")}>>`;
2106
2143
  }
2107
2144
  if (functionValue.domain.every((key) => typeof key === "string" && isFieldName(key))) {
2108
2145
  const isSorted =
@@ -2110,9 +2147,20 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
2110
2147
  const pairs = isSorted
2111
2148
  ? functionValue.domain.map((key, index) => [key, functionValue.range[index]])
2112
2149
  : getWrittenPairs(functionValue);
2113
- return `[${pairs.map((pair) => `${String(pair[0])} |-> ${format(pair[1])}`).join(", ")}]`;
2150
+ return `[${pairs.map((pair) => `${String(pair[0])} |-> ${formatRange(pair[1])}`).join(", ")}]`;
2114
2151
  }
2115
- return `(${functionValue.domain.map((key, index) => `${format(key)} :> ${format(functionValue.range[index])}`).join(" @@ ")})`;
2152
+ return `(${functionValue.domain.map((key, index) => `${format(key)} :> ${formatRange(functionValue.range[index])}`).join(" @@ ")})`;
2116
2153
  }
2117
2154
  }
2118
2155
  };
2156
+
2157
+ // TLC's TLCState.toString: a line per variable, as a conjunction when there are several.
2158
+ export const formatState = (state: Record<string, Value>) => {
2159
+ const entries = Object.entries(state);
2160
+ return entries
2161
+ .map(
2162
+ ([name, value]) =>
2163
+ `${entries.length === 1 ? "" : "/\\ "}${name} = ${prettyPrint(formatValue(value))}\n`,
2164
+ )
2165
+ .join("");
2166
+ };