tla-ts 0.0.10-dev.b4a856304 → 0.0.10-dev.f16792fed

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 (72) hide show
  1. package/dist/index.cjs +1 -1
  2. package/dist/index.d.cts +34 -0
  3. package/dist/index.d.ts +34 -0
  4. package/dist/index.js +1 -1
  5. package/dist/parallel-worker.cjs +1 -1
  6. package/dist/parallel-worker.js +1 -1
  7. package/dist/prove.cjs +48 -48
  8. package/dist/prove.js +29 -29
  9. package/dist/run.cjs +40 -40
  10. package/dist/run.js +31 -31
  11. package/dist/transfer.cjs +36 -36
  12. package/dist/transfer.js +40 -40
  13. package/package.json +1 -1
  14. package/src/ast.ts +0 -5
  15. package/src/bags.ts +2 -5
  16. package/src/builtins.ts +1 -8
  17. package/src/check.ts +128 -193
  18. package/src/cli/options.ts +1 -1
  19. package/src/cli/run.ts +0 -2
  20. package/src/cli/runtime-invariants.ts +8 -7
  21. package/src/cli/shared.ts +0 -4
  22. package/src/cli/tlc-arguments.ts +24 -30
  23. package/src/cli/tlc-usage.ts +2 -3
  24. package/src/coverage.ts +3 -8
  25. package/src/evaluate.ts +26 -102
  26. package/src/java-hash.ts +7 -0
  27. package/src/java-overrides.ts +4 -9
  28. package/src/json-reader.ts +1 -2
  29. package/src/json.ts +4 -11
  30. package/src/levels.ts +7 -15
  31. package/src/lexer.ts +72 -83
  32. package/src/liveness-checker.ts +77 -106
  33. package/src/liveness.ts +10 -34
  34. package/src/parallel.ts +26 -33
  35. package/src/parser.ts +163 -226
  36. package/src/pcal/ast.ts +53 -65
  37. package/src/pcal/parse.ts +144 -191
  38. package/src/pcal/tokenize.ts +91 -115
  39. package/src/pcal/translate.ts +83 -98
  40. package/src/pcal/validate.ts +48 -50
  41. package/src/pretty-print.ts +6 -6
  42. package/src/randomization.ts +1 -4
  43. package/src/resolve.ts +12 -70
  44. package/src/runtime.ts +11 -18
  45. package/src/sany/builtins.ts +1 -3
  46. package/src/sany/generator.ts +74 -127
  47. package/src/sany/levels.ts +5 -9
  48. package/src/sany/lexer.ts +40 -44
  49. package/src/sany/linter.ts +0 -1
  50. package/src/sany/nodes.ts +4 -10
  51. package/src/search.ts +1 -1
  52. package/src/simulate.ts +50 -59
  53. package/src/spec-description.ts +23 -34
  54. package/src/standard-definitions.ts +0 -3
  55. package/src/standard-modules.ts +1 -12
  56. package/src/state-graph.ts +3 -15
  57. package/src/subexpressions.ts +38 -47
  58. package/src/successors.ts +14 -35
  59. package/src/symmetry.ts +4 -19
  60. package/src/tlc/fingerprint.ts +15 -21
  61. package/src/tlc/jar-data.ts +0 -1
  62. package/src/tlc/messages.ts +2 -21
  63. package/src/tlc/order.ts +22 -47
  64. package/src/tlc/random.ts +18 -30
  65. package/src/tlc/replay.ts +13 -33
  66. package/src/tlc/summary.ts +36 -45
  67. package/src/tlc/tlc-operators.ts +4 -14
  68. package/src/tlc/tlcext-operators.ts +11 -15
  69. package/src/tlc/trace-spec.ts +4 -9
  70. package/src/tlc/value-stream.ts +9 -13
  71. package/src/tlc/version.ts +0 -1
  72. package/src/values.ts +74 -186
package/src/evaluate.ts CHANGED
@@ -10,7 +10,6 @@ import {
10
10
  type NumberExpression,
11
11
  type OperatorParam,
12
12
  type RecordField,
13
- type SourceRange,
14
13
  } from "./ast";
15
14
  import { getKindString } from "./builtins";
16
15
  import {
@@ -18,6 +17,7 @@ import {
18
17
  TlaEvaluationError,
19
18
  TlaSetBoundError,
20
19
  TlaUnassignedError,
20
+ formatRange,
21
21
  } from "./errors";
22
22
  import { EXIT_STATUS, setExitCode } from "./exit-codes";
23
23
  import { generateEvaluator } from "./codegen";
@@ -103,9 +103,7 @@ export interface Builtin {
103
103
  evaluateUnary: ((value: Value) => Value) | undefined;
104
104
  evaluateBinary: ((left: Value, right: Value) => Value) | undefined;
105
105
  isStateLevel?: boolean;
106
- // Whether TLC takes an application for a constant one although its value depends on the state.
107
106
  isLevelConstant?: boolean;
108
- // TLC's minLevel of ActionLevel for a Java override.
109
107
  isActionLevel?: boolean;
110
108
  isLazy?: boolean;
111
109
  }
@@ -127,14 +125,11 @@ export interface Thunk {
127
125
  state: State | undefined;
128
126
  next: State | undefined;
129
127
  cache: Value | undefined;
130
- // Whether the value may stream until TLC caches it, so the thunk caches only a settled value.
131
128
  isStreamed: boolean;
132
- // Whether the thunk dropped its scope after caching a value that holds in every state.
133
129
  isReleased?: boolean;
134
130
  }
135
131
 
136
132
  type Binding =
137
- // A literal argument keeps its expression, which TLC binds lazily like any other.
138
133
  | { kind: "Value"; value: Value; argument?: Expression }
139
134
  | Thunk
140
135
  | { kind: "Operator"; operator: Operator };
@@ -155,9 +150,7 @@ export interface Environment {
155
150
  variables: string[];
156
151
  variableIndex: Map<string, number>;
157
152
  facts: DefinitionFacts;
158
- // TLC evaluates a constant definition it failed to compute at startup where the spec uses it.
159
153
  startupValues: (Value | undefined)[];
160
- // SANY wraps the body of each of these INSTANCE copies in its substitutions.
161
154
  substitutedDefinitions: Set<Definition>;
162
155
  instanceParams: Set<OperatorParam>;
163
156
  evaluators: WeakMap<Expression, Evaluator>;
@@ -169,26 +162,20 @@ export interface Environment {
169
162
 
170
163
  export interface CallStack {
171
164
  expressions: Expression[];
172
- // TLC stops popping the stack once an evaluation fails, so it keeps where the failure occurred.
173
165
  isFrozen: boolean;
174
166
  sources: WeakMap<ObjectValue, Expression>;
175
167
  values: WeakMap<Expression, Value>;
176
- // Tells a failure of an operand from one of the method that computes the operator.
177
168
  failures: WeakMap<Error, Expression>;
178
169
  fingerprint?: FingerprintFailure;
179
170
  }
180
171
 
181
172
  export interface FingerprintFailure {
182
- // The sources of the values whose methods failed, outermost first.
183
173
  sources: Expression[];
184
174
  reason: string;
185
175
  }
186
176
 
187
- // The operators whose value TLC's CallStackTool gives a source.
188
177
  const SOURCED_OPERATORS = new Set(["SUBSET", "UNION", "DOMAIN", "\\cup", "\\cap", "\\"]);
189
178
 
190
- // CallStackTool returns these lazy values without their source, and a function TLC builds
191
- // from a FcnLambdaValue has none.
192
179
  const SOURCED_KINDS = new Set<Expression["kind"]>([
193
180
  "SetEnumeration",
194
181
  "SetFilter",
@@ -204,7 +191,6 @@ const isSourced = (expression: Expression) =>
204
191
  SOURCED_KINDS.has(expression.kind) ||
205
192
  (expression.kind === "Apply" && SOURCED_OPERATORS.has(expression.operator));
206
193
 
207
- // The operand whose Java method computes the operator, such as S in e \in S or f in f[e].
208
194
  const getReceiver = (expression: Expression, values: CallStack["values"]) => {
209
195
  if (expression.kind === "FunctionApplication" || expression.kind === "Except") {
210
196
  return expression.function;
@@ -225,7 +211,6 @@ export interface Context {
225
211
  scope: Scope | undefined;
226
212
  state: State | undefined;
227
213
  next: State | undefined;
228
- // TLC's EvalControl.KeepLazy, so a function constructor within an applied function stays lazy.
229
214
  isKeepLazy?: boolean;
230
215
  }
231
216
 
@@ -249,9 +234,6 @@ const EXCEPT_AT = "@";
249
234
  export const describeLocation = (expression: Expression) =>
250
235
  `line ${expression.location.line}, column ${expression.location.column}`;
251
236
 
252
- export const formatRange = (range: SourceRange) =>
253
- `line ${range.start.line}, col ${range.start.column} to line ${range.end.line}, col ${range.end.column} of module ${range.module}`;
254
-
255
237
  export const describeRange = (expression: Expression) => {
256
238
  const range = expression.location.range;
257
239
  return range ? formatRange(range) : describeLocation(expression);
@@ -269,7 +251,6 @@ const createTemporalFormulaError = (form: string, expression: Expression) =>
269
251
  `TLC encountered a temporal formula (${form}) when evaluating a predicate or action.\n${describeRange(expression)}`,
270
252
  );
271
253
 
272
- // SANY prints a numeral as written and any other expression by its location.
273
254
  export const describeNode = (expression: Expression) =>
274
255
  expression.kind === "Number"
275
256
  ? (expression.text ?? String(expression.value))
@@ -280,7 +261,6 @@ export const createConditionError = (expression: Expression, value: Value) =>
280
261
  `A non-boolean expression (${getKindString(value)}) was used as the condition of an IF.\n${describeRange(expression)}`,
281
262
  );
282
263
 
283
- // TLC words the error differently for an infix chain of /\ or \/ and for a bulleted list.
284
264
  export const createJunctionError = (
285
265
  expression: Expression & { kind: "And" | "Or" },
286
266
  index: number,
@@ -301,7 +281,6 @@ export const createJunctionError = (
301
281
  );
302
282
  };
303
283
 
304
- // TLC selects a field from the function it converts a non-record to, which keeps a tuple's domain.
305
284
  export const getFieldSelector = (expression: Expression & { kind: "FieldAccess" }) => {
306
285
  const field = expression.field;
307
286
  const describeMissing = (record: Value) =>
@@ -316,7 +295,6 @@ export const getFieldSelector = (expression: Expression & { kind: "FieldAccess"
316
295
  }
317
296
  const functionClass = getFunctionClass(value);
318
297
  if (functionClass === "tuple") throw createNonIntegerKeyError(field);
319
- // Only TLC's RecordValue names the field it lacks, and TLC enumerates a FcnLambdaValue first.
320
298
  return applyFunction(
321
299
  value.kind === "LazyFunction" ? toFiniteFunction(value) : value,
322
300
  field,
@@ -325,7 +303,6 @@ export const getFieldSelector = (expression: Expression & { kind: "FieldAccess"
325
303
  };
326
304
  };
327
305
 
328
- // TLC 1.7.4 words what a tuple or a record lacks differently.
329
306
  export const getMissingArgumentDescriber = (version: TlcVersion | undefined) =>
330
307
  version === "1.7.4"
331
308
  ? (functionValue: Value, argument: Value) =>
@@ -353,7 +330,6 @@ export const getSubsetOperator =
353
330
  : builtin.evaluate([left, right]);
354
331
  };
355
332
 
356
- // TLC rejects a decimal, or an integer literal too big for it, while it processes the spec.
357
333
  export const createRealNumberError = (expression: DecimalExpression) =>
358
334
  setExitCode(
359
335
  new TlaEvaluationError(`TLC can't handle real numbers.\n${expression.text}`),
@@ -374,8 +350,6 @@ export const createUnassignedError = (name: string, expression: Expression) =>
374
350
  name,
375
351
  );
376
352
 
377
- // TLC reads the subscript of <<A>>_v in the successor as a state of its own, and after 1.7.4
378
- // names the fairness condition when A leaves a variable of v unassigned.
379
353
  export const toUnspecifiedSubscriptError = (error: unknown, version: TlcVersion | undefined) =>
380
354
  error instanceof TlaUnassignedError && version !== "1.7.4"
381
355
  ? new TlaEvaluationError(
@@ -411,7 +385,6 @@ export const bindPattern = (scope: Scope | undefined, pattern: BoundPattern, val
411
385
  );
412
386
  };
413
387
 
414
- // Tool#evalAppl checks that it applies a function before it evaluates the argument.
415
388
  export const expectFunction = (value: Value, application: Expression) => {
416
389
  if (isFunctionValue(value)) return value;
417
390
  throw new TlaEvaluationError(
@@ -502,11 +475,9 @@ const getBoundExplanation = (set: Value, text: string) => {
502
475
  return undefined;
503
476
  };
504
477
 
505
- // TLC enumerates every set but its Java ones, so any other set fails as its own class does.
506
478
  const checkEnumerable = (set: Value, expression: Expression, version: TlcVersion) => {
507
479
  if (!isSetValue(set) || isOverriddenSet(set)) {
508
480
  const text = formatValue(set);
509
- // TLC 1.7.4 doesn't explain why it can't enumerate a set.
510
481
  const explanation = version === "1.7.4" ? undefined : getBoundExplanation(set, text);
511
482
  throw new TlaEvaluationError(
512
483
  explanation === undefined
@@ -522,14 +493,12 @@ const getEnumeratedElements = (set: Value, expression: Expression, version: TlcV
522
493
  return getLazySubsets(set) ?? getNormalizedSetElements(set);
523
494
  };
524
495
 
525
- // TLC 1.7.4 streams a lazy set's elements, where later versions normalize the set first.
526
496
  export const getContextElements = (set: Value, expression: Expression, version: TlcVersion) => {
527
497
  if (version !== "1.7.4") return getEnumeratedElements(set, expression, version);
528
498
  checkEnumerable(set, expression, version);
529
499
  return getLazySubsets(set) ?? getStreamedElements(set);
530
500
  };
531
501
 
532
- // Like TLC, keep an interval so a quantifier can stop at a witness in 1..2000000000 early.
533
502
  const getKeptInterval = (set: Value) => {
534
503
  if (typeof set !== "object" || set.kind !== "Interval") return undefined;
535
504
  getCardinality(set);
@@ -553,7 +522,6 @@ const someElement = (
553
522
  return false;
554
523
  };
555
524
 
556
- // The names of one bound, as in \A x, y \in S, share its set, which TLC evaluates once.
557
525
  export const mapBoundSets = <Result>(bounds: Bound[], map: (set: Expression) => Result) =>
558
526
  bounds.reduce<Result[]>((results, bound, index) => {
559
527
  results.push(
@@ -646,8 +614,7 @@ export const bindLazyArguments = (
646
614
  typeof value.domain === "object" && value.domain.kind === "ProductSet"
647
615
  ? value.domain.factors
648
616
  : [];
649
- // FcnLambdaValue#apply indexes past an argument tuple shorter than the bounds and ignores one
650
- // longer, where this rejects the list.
617
+ // Deviation from TLC: FcnLambdaValue#apply indexes past an argument tuple shorter than the bounds and ignores a longer one.
651
618
  const createListError = () =>
652
619
  new TlaEvaluationError(
653
620
  `In applying the function\n${prettyPrint(formatValue(value))},\nthe argument list is:\n${prettyPrint(formatValue(argument))}\nwhich does not match its formal parameter.\n`,
@@ -679,7 +646,6 @@ export const bindLazyArguments = (
679
646
  return bindArgument(bounds, lambda.scope, argument);
680
647
  };
681
648
 
682
- // TLC prints a function it can't enumerate with only the first name of a group such as m, n.
683
649
  interface LazyFunctionTemplate {
684
650
  parameters: { index: number; name: string }[];
685
651
  body: string;
@@ -748,7 +714,6 @@ const getBoundTupleLengths = (bounds: Bound[]) =>
748
714
  bound.pattern.kind === "Tuple" ? bound.pattern.names.length : undefined,
749
715
  );
750
716
 
751
- // The function constructor of a definition, which SANY locates at the whole definition.
752
717
  const getDefinitionSource = (definition: FunctionDefinition): Expression => ({
753
718
  kind: "FunctionConstruction",
754
719
  bounds: definition.bounds,
@@ -794,7 +759,6 @@ const createRecursiveFunction = (
794
759
  return definition.bounds.length === 1 ? markLambdaFunction(rebindable) : rebindable;
795
760
  };
796
761
 
797
- // TLC computes a constant definition eagerly, so a function over a reducible set is a FcnRcdValue.
798
762
  const toStartupValue = (definition: Definition, value: Value): Value => {
799
763
  if (typeof value !== "object" || getFunctionClass(value) !== "lambda") return value;
800
764
  if (
@@ -809,13 +773,11 @@ const toStartupValue = (definition: Definition, value: Value): Value => {
809
773
  const finite = toFiniteFunction(value);
810
774
  return createSortedFunction(finite.domain, finite.range);
811
775
  } catch (error) {
812
- // TLC leaves a definition it fails to compute to evaluate where the spec uses it.
813
776
  if (error instanceof TlaEvaluationError) return value;
814
777
  throw error;
815
778
  }
816
779
  };
817
780
 
818
- // TLC evaluates a function definition that isn't recursive as it does a function constructor.
819
781
  const compileDefinitionBody = (definition: Definition, environment: Environment): Evaluator => {
820
782
  if (definition.kind === "Operator" && definition.params.length > 0) {
821
783
  return () => {
@@ -834,19 +796,19 @@ const getDefinitionEvaluator = (definition: Definition, environment: Environment
834
796
  const compiled = environment.definitionEvaluators.get(definition);
835
797
  if (compiled) return compiled;
836
798
  const body = compileDefinitionBody(definition, environment);
837
- const id = environment.facts.ids.get(definition);
799
+ const definitionId = environment.facts.ids.get(definition);
838
800
  const startupValues = environment.startupValues;
839
801
  const evaluator: Evaluator =
840
- id === undefined
802
+ definitionId === undefined
841
803
  ? (context) => body(withScope(context, undefined))
842
- : (context) => startupValues[id] ?? body(withScope(context, undefined));
804
+ : (context) => startupValues[definitionId] ?? body(withScope(context, undefined));
843
805
  environment.definitionEvaluators.set(definition, evaluator);
844
806
  return evaluator;
845
807
  };
846
808
 
847
809
  export const getStartupValue = (definition: Definition, environment: Environment) => {
848
- const id = environment.facts.ids.get(definition);
849
- return id === undefined ? undefined : environment.startupValues[id];
810
+ const definitionId = environment.facts.ids.get(definition);
811
+ return definitionId === undefined ? undefined : environment.startupValues[definitionId];
850
812
  };
851
813
 
852
814
  export const evaluateStartupDefinitions = (definitions: Definition[], environment: Environment) =>
@@ -855,22 +817,21 @@ export const evaluateStartupDefinitions = (definitions: Definition[], environmen
855
817
  const name = definition.name;
856
818
  if (environment.constants.has(name) || environment.substitutions.has(name)) return;
857
819
  if (!isConstantLevel(definition, environment)) return;
858
- const id = environment.facts.ids.get(definition);
859
- if (id === undefined || environment.startupValues[id] !== undefined) return;
820
+ const definitionId = environment.facts.ids.get(definition);
821
+ if (definitionId === undefined || environment.startupValues[definitionId] !== undefined) return;
860
822
  const context = { environment, scope: undefined, state: undefined, next: undefined };
861
823
  try {
862
824
  const value = environment.runtime.evaluateAtStartup(() =>
863
825
  toStartupValue(definition, compileDefinitionBody(definition, environment)(context)),
864
826
  );
865
827
  markNormalized(value);
866
- environment.startupValues[id] = value;
828
+ environment.startupValues[definitionId] = value;
867
829
  } catch (error) {
868
830
  // TLC swallows whatever the definition throws, a stack overflow included.
869
831
  if (!(error instanceof TlaEvaluationError) && !isStackOverflow(error)) throw error;
870
832
  }
871
833
  });
872
834
 
873
- // TLC reuses a cached value while each variable the cached state assigns keeps its value.
874
835
  const isStateWithin = (state: State | undefined, cached: State | undefined) => {
875
836
  if (cached === undefined || state === cached) return true;
876
837
  try {
@@ -904,8 +865,6 @@ const forceThunk = (thunk: Thunk, context: Context) => {
904
865
  thunk.state = context.state;
905
866
  thunk.next = context.next;
906
867
  }
907
- // A value a thunk cached with no state read no variable, so it holds in every state. Releasing
908
- // its scope frees the evaluations the scope's bindings cached, which a long script keeps alive.
909
868
  if (thunk.cache !== undefined && thunk.state === undefined && thunk.next === undefined) {
910
869
  thunk.scope = undefined;
911
870
  thunk.isReleased = true;
@@ -1054,7 +1013,6 @@ const compileArgumentBinder = (argument: Expression, environment: Environment):
1054
1013
  const binding: Binding = { kind: "Value", value: argument.value, argument };
1055
1014
  return () => binding;
1056
1015
  }
1057
- // TLC counts an argument where the operator's body evaluates it, under the call.
1058
1016
  const coverage = environment.coverage;
1059
1017
  if (coverage) {
1060
1018
  return (context) => {
@@ -1124,8 +1082,6 @@ interface ReevaluatedDefinitions {
1124
1082
  streamed: ReadonlySet<Definition>;
1125
1083
  }
1126
1084
 
1127
- // A LET's function definition has one function constructor, as in SANY, so its code compiles once
1128
- // however often the LET is evaluated.
1129
1085
  const letFunctionConstructions = new WeakMap<FunctionDefinition, Expression>();
1130
1086
 
1131
1087
  const getLetFunctionConstruction = (definition: FunctionDefinition): Expression => {
@@ -1189,7 +1145,6 @@ export const bindDefinitions = (
1189
1145
  isStreamed: reevaluated?.streamed.has(definition) ?? false,
1190
1146
  };
1191
1147
  });
1192
- // TLC counts a LET definition under the node that encloses the LET.
1193
1148
  const coverage = context.environment.coverage;
1194
1149
  if (coverage && coverage.current !== -1) {
1195
1150
  nodes.forEach((node) => {
@@ -1224,8 +1179,6 @@ const evaluateLocalIdentifier = (name: string, expression: Expression, context:
1224
1179
  throw new TlaEvaluationError(`Unknown identifier ${name} at ${describeLocation(expression)}`);
1225
1180
  };
1226
1181
 
1227
- // TLC's next-state generator evaluates a LET definition again at each reference, so one that
1228
- // calls an impure builtin repeats its effects, and a UNION or \cup set starts out uncached.
1229
1182
  export const getReevaluatedDefinitions = (
1230
1183
  definitions: Definition[],
1231
1184
  environment: Environment,
@@ -1267,7 +1220,6 @@ const toNextContext = (context: Context): Context => ({
1267
1220
  isKeepLazy: context.isKeepLazy,
1268
1221
  });
1269
1222
 
1270
- // TLC evaluates the expression in the current state first.
1271
1223
  const compileUnchanged =
1272
1224
  (evaluator: Evaluator): Evaluator =>
1273
1225
  (context) => {
@@ -1275,7 +1227,6 @@ const compileUnchanged =
1275
1227
  return valuesEqual(current, evaluator(toNextContext(context)));
1276
1228
  };
1277
1229
 
1278
- // TLC's CallStackTool rebinds the lazy values it returns, so their later evaluation records too.
1279
1230
  const traceEvaluator =
1280
1231
  (
1281
1232
  expression: Expression,
@@ -1331,19 +1282,15 @@ const traceEvaluator =
1331
1282
  }
1332
1283
  };
1333
1284
 
1334
- // A FingerprintException from a method of a value with a source is headed by each such value
1335
- // whose method called it in turn, outermost first.
1336
1285
  export const freezeCallStack = (
1337
1286
  callStack: CallStack,
1338
1287
  values: (Value | undefined)[],
1339
1288
  error: unknown,
1340
1289
  ) => {
1341
- // A set that streams its elements enumerates itself too, so it can appear twice.
1342
1290
  const sources = [...new Set(values)].flatMap((item) => {
1343
1291
  const source = typeof item === "object" ? callStack.sources.get(item) : undefined;
1344
1292
  return source ? [source] : [];
1345
1293
  });
1346
- // A value with a source raises a FingerprintException even when the stack is frozen already.
1347
1294
  if (sources.length > 0 && error instanceof TlaEvaluationError) {
1348
1295
  if (!callStack.isFrozen) callStack.expressions.push(...sources);
1349
1296
  const inner = callStack.fingerprint;
@@ -1366,7 +1313,6 @@ const headFingerprint = (callStack: CallStack, source: Expression, error: unknow
1366
1313
  };
1367
1314
  };
1368
1315
 
1369
- // With evaluators of its own, since the environment's evaluators record nothing.
1370
1316
  export const createTracingEnvironment = (environment: Environment): Environment => ({
1371
1317
  ...environment,
1372
1318
  coverage: undefined,
@@ -1382,7 +1328,6 @@ export const createTracingEnvironment = (environment: Environment): Environment
1382
1328
  },
1383
1329
  });
1384
1330
 
1385
- // A replay that walks into the expression has recorded its frames already.
1386
1331
  const traceFrames =
1387
1332
  (
1388
1333
  expression: Expression,
@@ -1400,8 +1345,6 @@ const traceFrames =
1400
1345
  }
1401
1346
  };
1402
1347
 
1403
- // TLC counts an evaluation under the node of the expression in the tree of the check it counts,
1404
- // or, when the tree has none there, under the node it evaluates in.
1405
1348
  const countEvaluator =
1406
1349
  (expression: Expression, evaluator: Evaluator, coverage: Coverage): Evaluator =>
1407
1350
  (context) => {
@@ -1469,11 +1412,9 @@ const compileIdentifier = (
1469
1412
  return () => value;
1470
1413
  }
1471
1414
  if (global?.kind === "Definition") {
1472
- // The body compiles when first evaluated, as a recursive definition's body refers back to it.
1473
1415
  const definition = global.definition;
1474
- const compiled = { reference: undefined as Evaluator | undefined };
1475
- return (context) =>
1476
- (compiled.reference ??= getDefinitionEvaluator(definition, environment))(context);
1416
+ let compiled: Evaluator | undefined;
1417
+ return (context) => (compiled ??= getDefinitionEvaluator(definition, environment))(context);
1477
1418
  }
1478
1419
  return (context) => evaluateLocalIdentifier(name, expression, context);
1479
1420
  };
@@ -1553,11 +1494,10 @@ const compileClosureCall = (
1553
1494
  environment: Environment,
1554
1495
  ): Evaluator => {
1555
1496
  const bindArguments = compileArgumentScope(closure, args, environment);
1556
- // The body compiles when the call is first evaluated, as a recursive operator's body calls it.
1557
- const compiled = { body: undefined as Evaluator | undefined };
1497
+ let body: Evaluator | undefined;
1558
1498
  return (context) => {
1559
- compiled.body ??= getEntryEvaluator(closure.body, environment);
1560
- return compiled.body({
1499
+ body ??= getEntryEvaluator(closure.body, environment);
1500
+ return body({
1561
1501
  environment,
1562
1502
  scope: bindArguments(context),
1563
1503
  state: context.state,
@@ -1605,7 +1545,6 @@ const compileApply = (
1605
1545
  const domain = getDomainOperator(expression);
1606
1546
  return (context) => domain(operand(context));
1607
1547
  }
1608
- // TLC caches the value of a constant TLCEval argument only where no context binds a name.
1609
1548
  if (global?.kind === "Builtin" && global.name === "TLCEval" && args.length === 1) {
1610
1549
  const isCached =
1611
1550
  !contextualApplications.has(expression) && !isNonconstant(args[0], environment);
@@ -1622,7 +1561,6 @@ const compileApply = (
1622
1561
  return (context) => subset(left(context), right(context));
1623
1562
  }
1624
1563
  if (global?.kind === "Builtin") return compileBuiltinCall(global, args, environment);
1625
- // TLC refuses action composition unless a Java property enables its incomplete implementation.
1626
1564
  if (expression.operator === "\\cdot" && args.length === 2) {
1627
1565
  return () => {
1628
1566
  throw new TlaEvaluationError(
@@ -1713,7 +1651,6 @@ const getBoundValue = (pattern: BoundPattern, scope: Scope | undefined) => {
1713
1651
  return binding?.kind === "Value" ? binding.value : undefined;
1714
1652
  };
1715
1653
 
1716
- // TLC keeps a function constructor lazy when it is applied, or is the base of an applied EXCEPT.
1717
1654
  const keptLazyExpressions = new WeakSet<Expression>();
1718
1655
 
1719
1656
  export const keepLazy = (expression: Expression) => {
@@ -1722,8 +1659,6 @@ export const keepLazy = (expression: Expression) => {
1722
1659
  }
1723
1660
  };
1724
1661
 
1725
- // The names an expression may look up in its scope, or undefined when a subexpression selector may
1726
- // look up others.
1727
1662
  const scopeNames = new WeakMap<Expression, string[] | undefined>();
1728
1663
 
1729
1664
  const getScopeNames = (expression: Expression) => {
@@ -1741,9 +1676,6 @@ const getScopeNames = (expression: Expression) => {
1741
1676
  return result;
1742
1677
  };
1743
1678
 
1744
- // The bindings of a scope that names look up, so that a lazy function keeps only those alive and
1745
- // not the values its other bindings cached. An unnamed node ends the chain, since a TLCEval in the
1746
- // body sorts its value only where no context binds a name.
1747
1679
  const trimScope = (scope: Scope | undefined, names: string[] | undefined) =>
1748
1680
  names === undefined || scope === undefined
1749
1681
  ? scope
@@ -1757,7 +1689,6 @@ const trimScope = (scope: Scope | undefined, names: string[] | undefined) =>
1757
1689
 
1758
1690
  export const isKeptLazy = (expression: Expression) => keptLazyExpressions.has(expression);
1759
1691
 
1760
- // Builds the function of a constructor from its evaluated domain.
1761
1692
  export const getFunctionBuilder = (
1762
1693
  expression: Expression & { kind: "FunctionConstruction" },
1763
1694
  environment: Environment,
@@ -1772,8 +1703,7 @@ export const getFunctionBuilder = (
1772
1703
  const name = bound.pattern.name;
1773
1704
  const evaluateAt = (key: Value) =>
1774
1705
  body(withScope(context, bindValue(context.scope, name, key)));
1775
- // TLC sizes the domain, then evaluates the body at each element. A domain too large to hold
1776
- // the values stays lazy.
1706
+ // TLC sizes the domain and evaluates the body at each element of a domain too large to hold.
1777
1707
  if (isBeyondSetBound(domain)) {
1778
1708
  getCardinality(domain);
1779
1709
  forEachElement(domain, evaluateAt);
@@ -1828,7 +1758,6 @@ export const getFunctionBuilder = (
1828
1758
  ) {
1829
1759
  return createLazy(domain, context);
1830
1760
  }
1831
- // TLC builds a function lazily unless each bound is reducible, so its body fails where forced.
1832
1761
  const isReducibleDomain =
1833
1762
  bounds.length === 1
1834
1763
  ? isReducibleSet(domain)
@@ -1845,7 +1774,6 @@ export const getFunctionBuilder = (
1845
1774
  }
1846
1775
  }
1847
1776
  if (!callStack) return construct(domain, context);
1848
- // TLC builds the function in a method of the FcnLambdaValue that CallStackTool gives a source.
1849
1777
  try {
1850
1778
  return construct(domain, context);
1851
1779
  } catch (error) {
@@ -1873,8 +1801,8 @@ const compileExcept = (
1873
1801
  expression: Expression & { kind: "Except" },
1874
1802
  environment: Environment,
1875
1803
  ): Evaluator => {
1876
- const isKeptLazy = keptLazyExpressions.has(expression);
1877
- if (isKeptLazy) keepLazy(expression.function);
1804
+ const isKeptLazyExpression = keptLazyExpressions.has(expression);
1805
+ if (isKeptLazyExpression) keepLazy(expression.function);
1878
1806
  const evaluateFunction = getEvaluator(expression.function, environment);
1879
1807
  const updates = expression.updates.map((update) => ({
1880
1808
  path: update.path.map((step): CompiledStep =>
@@ -1907,19 +1835,18 @@ const compileExcept = (
1907
1835
  current,
1908
1836
  getKey(path[depth], context),
1909
1837
  (previous) => update(previous, path, depth + 1, context, value),
1910
- isKeptLazy && depth === 0,
1838
+ isKeptLazyExpression && depth === 0,
1911
1839
  );
1912
1840
  };
1913
1841
  return (context) => {
1914
1842
  let current = evaluateFunction(context);
1915
1843
  for (const item of updates) {
1916
- // TLC leaves the value as it is when an update's path is not in it, and warns.
1917
- const found = { value: false };
1844
+ let isFound = false;
1918
1845
  current = update(current, item.path, 0, context, (inner) => {
1919
- found.value = true;
1846
+ isFound = true;
1920
1847
  return item.value(inner);
1921
1848
  });
1922
- if (!found.value) {
1849
+ if (!isFound) {
1923
1850
  context.environment.runtime.warn(
1924
1851
  MESSAGE_CODE.exceptAppliedToUnknownField,
1925
1852
  `The EXCEPT was applied to non-existing fields of the value at\n${describeRange(expression.function)}`,
@@ -1930,7 +1857,6 @@ const compileExcept = (
1930
1857
  };
1931
1858
  };
1932
1859
 
1933
- // TLC filters any value it can't enumerate lazily, and fails only when it uses the result.
1934
1860
  export const getLazyFilter = (
1935
1861
  expression: Expression & { kind: "SetFilter" },
1936
1862
  environment: Environment,
@@ -1944,8 +1870,6 @@ export const getLazyFilter = (
1944
1870
  };
1945
1871
  const predicateNode = describeNode(expression.predicate);
1946
1872
  const coverage = environment.coverage;
1947
- // TLC evaluates a lazy set's predicate under the set's node only as it enumerates the set,
1948
- // and costs each element it tests and each it keeps.
1949
1873
  const testCovered = (node: number, isMember: boolean, test: () => Value) => {
1950
1874
  if (!coverage || node === -1) return test();
1951
1875
  if (!isMember) coverage.secondary[node]++;
@@ -2081,7 +2005,7 @@ const compileSetComprehension = (
2081
2005
  set,
2082
2006
  context.environment.runtime.version,
2083
2007
  );
2084
- const chosen = { value: undefined as Value | undefined };
2008
+ let chosen: Value | undefined;
2085
2009
  const pattern = expression.pattern;
2086
2010
  someElement(elements, (element) => {
2087
2011
  if (
@@ -2094,11 +2018,11 @@ const compileSetComprehension = (
2094
2018
  }
2095
2019
  const scope = bindPattern(context.scope, pattern, element);
2096
2020
  if (!expectBooleanBody(body(withScope(context, scope)), expression)) return false;
2097
- chosen.value = getBoundValue(pattern, scope);
2021
+ chosen = getBoundValue(pattern, scope);
2098
2022
  return true;
2099
2023
  });
2100
- if (chosen.value === undefined) throw createNoChoiceError(expression);
2101
- return chosen.value;
2024
+ if (chosen === undefined) throw createNoChoiceError(expression);
2025
+ return chosen;
2102
2026
  };
2103
2027
  };
2104
2028
 
@@ -0,0 +1,7 @@
1
+ export const getJavaHashCode = (text: string): number => {
2
+ let hash = 0;
3
+ for (let index = 0; index < text.length; index++) {
4
+ hash = (Math.imul(hash, 31) + text.charCodeAt(index)) | 0;
5
+ }
6
+ return hash;
7
+ };
@@ -35,7 +35,6 @@ const ACCESS_PUBLIC = 0x0001;
35
35
  const ACCESS_STATIC = 0x0008;
36
36
  const VALUE_PACKAGE = "tlc2/value/impl/";
37
37
 
38
- // The constant pool tags of the JVM specification, section 4.4.
39
38
  const POOL_TAG = {
40
39
  utf8: 1,
41
40
  integer: 3,
@@ -68,10 +67,10 @@ const OPCODE = {
68
67
 
69
68
  const createReader = (bytes: Uint8Array) => {
70
69
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
71
- const cursor = { offset: 0 };
70
+ let offset = 0;
72
71
  const advance = (length: number) => {
73
- const start = cursor.offset;
74
- cursor.offset += length;
72
+ const start = offset;
73
+ offset += length;
75
74
  return start;
76
75
  };
77
76
  return {
@@ -79,7 +78,7 @@ const createReader = (bytes: Uint8Array) => {
79
78
  readUint16: () => view.getUint16(advance(2)),
80
79
  readUint32: () => view.getUint32(advance(4)),
81
80
  readInt32: () => view.getInt32(advance(4)),
82
- readBytes: (length: number) => bytes.subarray(advance(length), cursor.offset),
81
+ readBytes: (length: number) => bytes.subarray(advance(length), offset),
83
82
  };
84
83
  };
85
84
 
@@ -95,7 +94,6 @@ const PRIMITIVE_TYPES = new Map([
95
94
  ["V", "void"],
96
95
  ]);
97
96
 
98
- // The modifiers Method#toString prints, in the order of Modifier#toString.
99
97
  const METHOD_MODIFIERS: [number, string][] = [
100
98
  [0x0001, "public"],
101
99
  [0x0004, "protected"],
@@ -119,8 +117,6 @@ const getClassName = (pool: PoolEntry[], index: number) => pool[pool[index].firs
119
117
  const getJavaClassName = (pool: PoolEntry[], index: number) =>
120
118
  getClassName(pool, index).replaceAll("/", ".");
121
119
 
122
- // In the order of the class file. Class#getDeclaredMethods orders them by where HotSpot allocated
123
- // the symbols of their names.
124
120
  const readClassFile = (bytes: Uint8Array) => {
125
121
  const reader = createReader(bytes);
126
122
  if (reader.readUint32() !== CLASS_MAGIC)
@@ -181,7 +177,6 @@ const readClassFile = (bytes: Uint8Array) => {
181
177
  const isOverride = (access & ACCESS_PUBLIC) !== 0 && (access & ACCESS_STATIC) !== 0;
182
178
  if (!isOverride) continue;
183
179
  const code = attributes.find((attribute) => attribute.name === "Code")?.reader;
184
- // A Code attribute holds max_stack and max_locals before the length of the bytecode.
185
180
  code?.readBytes(4);
186
181
  const thrown = attributes.find((attribute) => attribute.name === "Exceptions")?.reader;
187
182
  const exceptions = thrown
@@ -78,8 +78,7 @@ const NON_EXECUTE_PREFIX = ")]}'\n";
78
78
  const MALFORMED_JSON_GUIDE =
79
79
  "\nSee https://github.com/google/gson/blob/main/Troubleshooting.md#malformed-json";
80
80
 
81
- // Gson's JsonParser.parseReader: a lenient JsonReader reads one element, and the reader, strict
82
- // again, then rejects anything but whitespace after it. An empty document reads as JSON null.
81
+ // Gson's JsonParser.parseReader: a lenient JsonReader reads one element, then, strict again, rejects anything but whitespace after it.
83
82
  export const readJson = (text: string): JsonElement => {
84
83
  const byteOrderMarkLength = text.startsWith("") ? 1 : 0;
85
84
  let pos = byteOrderMarkLength;